diff --git a/.gitattributes b/.gitattributes index c1edd5934fccaae2000af6e092f0a08b40aa9f77..5ce50252724afe0cf88fe8743a19eb3647888707 100644 --- a/.gitattributes +++ b/.gitattributes @@ -307,3 +307,41 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text .venv/lib/python3.12/site-packages/polars/lazyframe/__pycache__/frame.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text .venv/lib/python3.12/site-packages/polars/series/__pycache__/series.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text .venv/lib/python3.12/site-packages/psutil/_psutil_linux.abi3.so filter=lfs diff=lfs merge=lfs -text +.venv/lib/python3.12/site-packages/pyparsing/__pycache__/core.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text +.venv/lib/python3.12/site-packages/pywt/_extensions/_cwt.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text +.venv/lib/python3.12/site-packages/pywt/_extensions/_dwt.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text +.venv/lib/python3.12/site-packages/pywt/_extensions/_pywt.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text +.venv/lib/python3.12/site-packages/pywt/_extensions/_swt.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text +.venv/lib/python3.12/site-packages/regex/__pycache__/_regex_core.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text +.venv/lib/python3.12/site-packages/regex/_regex.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text +.venv/lib/python3.12/site-packages/regex/tests/__pycache__/test_regex.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text +.venv/lib/python3.12/site-packages/scipy/_cyutility.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text +.venv/lib/python3.12/site-packages/scipy/_lib/_uarray/_uarray.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text +.venv/lib/python3.12/site-packages/scipy/cluster/hierarchy/_hierarchy.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text +.venv/lib/python3.12/site-packages/scipy/cluster/hierarchy/_optimal_leaf_ordering.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text +.venv/lib/python3.12/site-packages/scipy/cluster/vq/_vq.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text +.venv/lib/python3.12/site-packages/scipy/fft/_duccfft/pyduccfft.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text +.venv/lib/python3.12/site-packages/scipy/fftpack/convolve.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text +.venv/lib/python3.12/site-packages/scipy/integrate/_quadpack.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text +.venv/lib/python3.12/site-packages/scipy/integrate/_vode.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text +.venv/lib/python3.12/site-packages/scipy/interpolate/_dierckx.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text +.venv/lib/python3.12/site-packages/scipy/interpolate/_fitpack.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text +.venv/lib/python3.12/site-packages/scipy/interpolate/_interpnd.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text +.venv/lib/python3.12/site-packages/scipy/interpolate/_ppoly.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text +.venv/lib/python3.12/site-packages/scipy/interpolate/_rbfinterp_pythran.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text +.venv/lib/python3.12/site-packages/scipy/interpolate/_rgi_cython.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text +.venv/lib/python3.12/site-packages/scipy/io/_fast_matrix_market/_fmm_core.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text +.venv/lib/python3.12/site-packages/scipy/io/matlab/_mio5_utils.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text +.venv/lib/python3.12/site-packages/scipy/io/matlab/_streams.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text +.venv/lib/python3.12/site-packages/scipy/linalg/_batched_linalg.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text +.venv/lib/python3.12/site-packages/scipy/linalg/_cythonized_array_utils.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text +.venv/lib/python3.12/site-packages/scipy/linalg/_decomp_interpolative.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text +.venv/lib/python3.12/site-packages/scipy/linalg/_decomp_update.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text +.venv/lib/python3.12/site-packages/scipy/linalg/_fblas.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text +.venv/lib/python3.12/site-packages/scipy/linalg/_flapack.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text +.venv/lib/python3.12/site-packages/scipy/linalg/_internal_matfuncs.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text +.venv/lib/python3.12/site-packages/scipy/linalg/_linalg_pythran.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text +.venv/lib/python3.12/site-packages/scipy/linalg/_matfuncs_sqrtm_triu.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text +.venv/lib/python3.12/site-packages/scipy/linalg/_solve_toeplitz.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text +.venv/lib/python3.12/site-packages/scipy/linalg/cython_blas.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text +.venv/lib/python3.12/site-packages/scipy/linalg/cython_lapack.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text diff --git a/.venv/lib/python3.12/site-packages/pygments-2.21.0.dist-info/INSTALLER b/.venv/lib/python3.12/site-packages/pygments-2.21.0.dist-info/INSTALLER new file mode 100644 index 0000000000000000000000000000000000000000..a1b589e38a32041e49332e5e81c2d363dc418d68 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/pygments-2.21.0.dist-info/INSTALLER @@ -0,0 +1 @@ +pip diff --git a/.venv/lib/python3.12/site-packages/pygments-2.21.0.dist-info/METADATA b/.venv/lib/python3.12/site-packages/pygments-2.21.0.dist-info/METADATA new file mode 100644 index 0000000000000000000000000000000000000000..cc4e5734b999d8563bf83b1911a47270c4976913 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/pygments-2.21.0.dist-info/METADATA @@ -0,0 +1,58 @@ +Metadata-Version: 2.5 +Name: Pygments +Version: 2.21.0 +Summary: Pygments is a syntax highlighting package written in Python. +Project-URL: Homepage, https://pygments.org +Project-URL: Documentation, https://pygments.org/docs +Project-URL: Source, https://github.com/pygments/pygments +Project-URL: Bug Tracker, https://github.com/pygments/pygments/issues +Project-URL: Changelog, https://github.com/pygments/pygments/blob/master/CHANGES +Author-email: Georg Brandl +Maintainer: Matthäus G. Chajdas +Maintainer-email: Georg Brandl , Jean Abou Samra +License-Expression: BSD-2-Clause +License-File: AUTHORS +License-File: LICENSE +Keywords: syntax highlighting +Classifier: Development Status :: 6 - Mature +Classifier: Intended Audience :: Developers +Classifier: Intended Audience :: End Users/Desktop +Classifier: Intended Audience :: System Administrators +Classifier: Operating System :: OS Independent +Classifier: Programming Language :: Python +Classifier: Programming Language :: Python :: 3 +Classifier: Programming Language :: Python :: 3.9 +Classifier: Programming Language :: Python :: 3.10 +Classifier: Programming Language :: Python :: 3.11 +Classifier: Programming Language :: Python :: 3.12 +Classifier: Programming Language :: Python :: 3.13 +Classifier: Programming Language :: Python :: 3.14 +Classifier: Programming Language :: Python :: 3.15 +Classifier: Programming Language :: Python :: Implementation :: CPython +Classifier: Programming Language :: Python :: Implementation :: PyPy +Classifier: Topic :: Text Processing :: Filters +Classifier: Topic :: Utilities +Requires-Python: >=3.9 +Provides-Extra: plugins +Provides-Extra: windows-terminal +Requires-Dist: colorama>=0.4.6; extra == 'windows-terminal' +Description-Content-Type: text/x-rst + +Pygments +~~~~~~~~ + +Pygments is a syntax highlighting package written in Python. + +It is a generic syntax highlighter suitable for use in code hosting, forums, +wikis or other applications that need to prettify source code. Highlights +are: + +* a wide range of over 500 languages and other text formats is supported +* special attention is paid to details, increasing quality by a fair amount +* support for new languages and formats are added easily +* a number of output formats, presently HTML, LaTeX, RTF, SVG, all image + formats that PIL supports and ANSI sequences +* it is usable as a command-line tool and as a library + +Copyright 2006-present by the Pygments team, see ``AUTHORS``. +Licensed under the BSD, see ``LICENSE`` for details. diff --git a/.venv/lib/python3.12/site-packages/pygments-2.21.0.dist-info/RECORD b/.venv/lib/python3.12/site-packages/pygments-2.21.0.dist-info/RECORD new file mode 100644 index 0000000000000000000000000000000000000000..b211e2f56281bd2a2053efe14319080094afd37e --- /dev/null +++ b/.venv/lib/python3.12/site-packages/pygments-2.21.0.dist-info/RECORD @@ -0,0 +1,694 @@ +../../../bin/pygmentize,sha256=vB_TaKZbBTCCReGD8G81J1dt93XkvY2-SkvqWOGbo0I,247 +pygments-2.21.0.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4 +pygments-2.21.0.dist-info/METADATA,sha256=Hd4HVXATZ3THBr8ACRg6eT_g7iYuSlWQzG7_hFPu3UM,2527 +pygments-2.21.0.dist-info/RECORD,, +pygments-2.21.0.dist-info/WHEEL,sha256=zOwg4jB6zX2kU910N-cMawjivD6tO8NEWvE12je1bVk,87 +pygments-2.21.0.dist-info/entry_points.txt,sha256=uUXw-XhMKBEX4pWcCtpuTTnPhL3h7OEE2jWi51VQsa8,53 +pygments-2.21.0.dist-info/licenses/AUTHORS,sha256=cag4cq2C9Xvmks-CfgSOLNUdRRac-h6j8ocG2XqHLA8,11048 +pygments-2.21.0.dist-info/licenses/LICENSE,sha256=qdZvHVJt8C4p3Oc0NtNOVuhjL0bCdbvf_HBWnogvnxc,1331 +pygments/__init__.py,sha256=g_6ZaI4G7YDX1E0yX3kCfeg6Q0xg8km87_1n_aPn0rE,2962 +pygments/__main__.py,sha256=QZWj0T6TTRsqr-w-0YvVILo1DyAvzzydGCRONwdEzqo,351 +pygments/__pycache__/__init__.cpython-312.pyc,, +pygments/__pycache__/__main__.cpython-312.pyc,, +pygments/__pycache__/cmdline.cpython-312.pyc,, +pygments/__pycache__/console.cpython-312.pyc,, +pygments/__pycache__/filter.cpython-312.pyc,, +pygments/__pycache__/formatter.cpython-312.pyc,, +pygments/__pycache__/lexer.cpython-312.pyc,, +pygments/__pycache__/modeline.cpython-312.pyc,, +pygments/__pycache__/plugin.cpython-312.pyc,, +pygments/__pycache__/regexopt.cpython-312.pyc,, +pygments/__pycache__/scanner.cpython-312.pyc,, +pygments/__pycache__/sphinxext.cpython-312.pyc,, +pygments/__pycache__/style.cpython-312.pyc,, +pygments/__pycache__/token.cpython-312.pyc,, +pygments/__pycache__/unistring.cpython-312.pyc,, +pygments/__pycache__/util.cpython-312.pyc,, +pygments/cmdline.py,sha256=k_r5QTPmEQFHanJqxex-k_1yrUysww2GI3VlyfisEIo,23542 +pygments/console.py,sha256=C189JAwhC1Qh0AKgshzb1wVDzFqBnv1VZ45kTEDIO30,1721 +pygments/filter.py,sha256=1dnbkq2AdC3AkHt3DaXwnOkTBLChl1kR6naSLwnr_tc,1913 +pygments/filters/__init__.py,sha256=03ZYdIYmxnWCh7gNXD7lEQ869Df4kzHnOGM44iJxan8,40349 +pygments/filters/__pycache__/__init__.cpython-312.pyc,, +pygments/formatter.py,sha256=PTBnTW0EHke2vzlAKuvHJkj3-_CMj8duIx-3yVUie-o,4369 +pygments/formatters/__init__.py,sha256=qPG4q5cuaZRGBglmEJVLP4SDv43QI3tAUskj30M-mOY,5352 +pygments/formatters/__pycache__/__init__.cpython-312.pyc,, +pygments/formatters/__pycache__/_mapping.cpython-312.pyc,, +pygments/formatters/__pycache__/bbcode.cpython-312.pyc,, +pygments/formatters/__pycache__/groff.cpython-312.pyc,, +pygments/formatters/__pycache__/html.cpython-312.pyc,, +pygments/formatters/__pycache__/img.cpython-312.pyc,, +pygments/formatters/__pycache__/irc.cpython-312.pyc,, +pygments/formatters/__pycache__/latex.cpython-312.pyc,, +pygments/formatters/__pycache__/other.cpython-312.pyc,, +pygments/formatters/__pycache__/pangomarkup.cpython-312.pyc,, +pygments/formatters/__pycache__/rtf.cpython-312.pyc,, +pygments/formatters/__pycache__/svg.cpython-312.pyc,, +pygments/formatters/__pycache__/terminal.cpython-312.pyc,, +pygments/formatters/__pycache__/terminal256.cpython-312.pyc,, +pygments/formatters/_mapping.py,sha256=1Cw37FuQlNacnxRKmtlPX4nyLoX9_ttko5ZwscNUZZ4,4176 +pygments/formatters/bbcode.py,sha256=lvG1REZJv0pM6VMe-QwLSuo0Yl1Ra_X51wh93fW8A2k,3299 +pygments/formatters/groff.py,sha256=FB87OIEw5S4Z0jyVVXL2csegglHazdyqP28ay3rDiYg,5089 +pygments/formatters/html.py,sha256=3N1fl214jgyqkCX6Lz3gS8l2EQS7v4Wj7xieYNllNig,36351 +pygments/formatters/img.py,sha256=41uSY0pKg9VmKJYrHuavCVgg0z-mg81p28QEMktwf1o,23304 +pygments/formatters/irc.py,sha256=hdOqAvF02bI8CY8_tutnUptBZpWEBLzVAqS4_YA0tew,4907 +pygments/formatters/latex.py,sha256=KynzALIwJh3w4d96fGmuUqjGed-kGzB3eLvzuWE16-I,19814 +pygments/formatters/other.py,sha256=lI66b25wazeSYlHE30yJVhj3RNvWKZqFS7tUgMMrExk,5007 +pygments/formatters/pangomarkup.py,sha256=L4jU6oO18UqEMqXeN5FkPtkisXrXuXq9wcecgy_6dzo,2209 +pygments/formatters/rtf.py,sha256=YQYW8NTrB4XfOjLbQzutyD4j35TimFNZ0T39dET9DOo,11924 +pygments/formatters/svg.py,sha256=mQoph1amKkD8s-HuO7jWwHzdpSEYpQAXmCU7lOhgGBA,6852 +pygments/formatters/terminal.py,sha256=q7jLLanle33eCZkDr4CoHAN-dHBFf1DBhi4FcBQ8_1E,4629 +pygments/formatters/terminal256.py,sha256=lQEMwHwLRBFpWiZMPnJHbumwoKHBSoCl8HIvuF_rGBE,11718 +pygments/lexer.py,sha256=IDdjLlw7vxjGwSoU3DiBXgWEsWsugee3ZcBK8bPhtzg,35155 +pygments/lexers/__init__.py,sha256=G4dtqE5QMEAqoaaD1rwSZZeuqKhMyS4utlMz1szkrTg,12070 +pygments/lexers/__pycache__/__init__.cpython-312.pyc,, +pygments/lexers/__pycache__/_ada_builtins.cpython-312.pyc,, +pygments/lexers/__pycache__/_asy_builtins.cpython-312.pyc,, +pygments/lexers/__pycache__/_cl_builtins.cpython-312.pyc,, +pygments/lexers/__pycache__/_cocoa_builtins.cpython-312.pyc,, +pygments/lexers/__pycache__/_csound_builtins.cpython-312.pyc,, +pygments/lexers/__pycache__/_css_builtins.cpython-312.pyc,, +pygments/lexers/__pycache__/_googlesql_builtins.cpython-312.pyc,, +pygments/lexers/__pycache__/_julia_builtins.cpython-312.pyc,, +pygments/lexers/__pycache__/_lasso_builtins.cpython-312.pyc,, +pygments/lexers/__pycache__/_lilypond_builtins.cpython-312.pyc,, +pygments/lexers/__pycache__/_lua_builtins.cpython-312.pyc,, +pygments/lexers/__pycache__/_luau_builtins.cpython-312.pyc,, +pygments/lexers/__pycache__/_mapping.cpython-312.pyc,, +pygments/lexers/__pycache__/_mql_builtins.cpython-312.pyc,, +pygments/lexers/__pycache__/_mysql_builtins.cpython-312.pyc,, +pygments/lexers/__pycache__/_openedge_builtins.cpython-312.pyc,, +pygments/lexers/__pycache__/_php_builtins.cpython-312.pyc,, +pygments/lexers/__pycache__/_postgres_builtins.cpython-312.pyc,, +pygments/lexers/__pycache__/_qlik_builtins.cpython-312.pyc,, +pygments/lexers/__pycache__/_scheme_builtins.cpython-312.pyc,, +pygments/lexers/__pycache__/_scilab_builtins.cpython-312.pyc,, +pygments/lexers/__pycache__/_sourcemod_builtins.cpython-312.pyc,, +pygments/lexers/__pycache__/_sql_builtins.cpython-312.pyc,, +pygments/lexers/__pycache__/_stan_builtins.cpython-312.pyc,, +pygments/lexers/__pycache__/_stata_builtins.cpython-312.pyc,, +pygments/lexers/__pycache__/_tsql_builtins.cpython-312.pyc,, +pygments/lexers/__pycache__/_usd_builtins.cpython-312.pyc,, +pygments/lexers/__pycache__/_vbscript_builtins.cpython-312.pyc,, +pygments/lexers/__pycache__/_vim_builtins.cpython-312.pyc,, +pygments/lexers/__pycache__/actionscript.cpython-312.pyc,, +pygments/lexers/__pycache__/ada.cpython-312.pyc,, +pygments/lexers/__pycache__/agile.cpython-312.pyc,, +pygments/lexers/__pycache__/algebra.cpython-312.pyc,, +pygments/lexers/__pycache__/ambient.cpython-312.pyc,, +pygments/lexers/__pycache__/amdgpu.cpython-312.pyc,, +pygments/lexers/__pycache__/ampl.cpython-312.pyc,, +pygments/lexers/__pycache__/apdlexer.cpython-312.pyc,, +pygments/lexers/__pycache__/apl.cpython-312.pyc,, +pygments/lexers/__pycache__/archetype.cpython-312.pyc,, +pygments/lexers/__pycache__/arrow.cpython-312.pyc,, +pygments/lexers/__pycache__/arturo.cpython-312.pyc,, +pygments/lexers/__pycache__/asc.cpython-312.pyc,, +pygments/lexers/__pycache__/asm.cpython-312.pyc,, +pygments/lexers/__pycache__/asn1.cpython-312.pyc,, +pygments/lexers/__pycache__/automation.cpython-312.pyc,, +pygments/lexers/__pycache__/bare.cpython-312.pyc,, +pygments/lexers/__pycache__/basic.cpython-312.pyc,, +pygments/lexers/__pycache__/bdd.cpython-312.pyc,, +pygments/lexers/__pycache__/berry.cpython-312.pyc,, +pygments/lexers/__pycache__/bibtex.cpython-312.pyc,, +pygments/lexers/__pycache__/bitbake.cpython-312.pyc,, +pygments/lexers/__pycache__/blueprint.cpython-312.pyc,, +pygments/lexers/__pycache__/boa.cpython-312.pyc,, +pygments/lexers/__pycache__/bqn.cpython-312.pyc,, +pygments/lexers/__pycache__/business.cpython-312.pyc,, +pygments/lexers/__pycache__/c_cpp.cpython-312.pyc,, +pygments/lexers/__pycache__/c_like.cpython-312.pyc,, +pygments/lexers/__pycache__/capnproto.cpython-312.pyc,, +pygments/lexers/__pycache__/carbon.cpython-312.pyc,, +pygments/lexers/__pycache__/cddl.cpython-312.pyc,, +pygments/lexers/__pycache__/cel.cpython-312.pyc,, +pygments/lexers/__pycache__/chapel.cpython-312.pyc,, +pygments/lexers/__pycache__/clean.cpython-312.pyc,, +pygments/lexers/__pycache__/codeql.cpython-312.pyc,, +pygments/lexers/__pycache__/comal.cpython-312.pyc,, +pygments/lexers/__pycache__/compiled.cpython-312.pyc,, +pygments/lexers/__pycache__/configs.cpython-312.pyc,, +pygments/lexers/__pycache__/console.cpython-312.pyc,, +pygments/lexers/__pycache__/cplint.cpython-312.pyc,, +pygments/lexers/__pycache__/crystal.cpython-312.pyc,, +pygments/lexers/__pycache__/csound.cpython-312.pyc,, +pygments/lexers/__pycache__/css.cpython-312.pyc,, +pygments/lexers/__pycache__/d.cpython-312.pyc,, +pygments/lexers/__pycache__/dalvik.cpython-312.pyc,, +pygments/lexers/__pycache__/data.cpython-312.pyc,, +pygments/lexers/__pycache__/dax.cpython-312.pyc,, +pygments/lexers/__pycache__/devicetree.cpython-312.pyc,, +pygments/lexers/__pycache__/diff.cpython-312.pyc,, +pygments/lexers/__pycache__/dns.cpython-312.pyc,, +pygments/lexers/__pycache__/dotnet.cpython-312.pyc,, +pygments/lexers/__pycache__/dsls.cpython-312.pyc,, +pygments/lexers/__pycache__/dylan.cpython-312.pyc,, +pygments/lexers/__pycache__/ecl.cpython-312.pyc,, +pygments/lexers/__pycache__/eiffel.cpython-312.pyc,, +pygments/lexers/__pycache__/elm.cpython-312.pyc,, +pygments/lexers/__pycache__/elpi.cpython-312.pyc,, +pygments/lexers/__pycache__/email.cpython-312.pyc,, +pygments/lexers/__pycache__/erlang.cpython-312.pyc,, +pygments/lexers/__pycache__/esoteric.cpython-312.pyc,, +pygments/lexers/__pycache__/ezhil.cpython-312.pyc,, +pygments/lexers/__pycache__/factor.cpython-312.pyc,, +pygments/lexers/__pycache__/fantom.cpython-312.pyc,, +pygments/lexers/__pycache__/felix.cpython-312.pyc,, +pygments/lexers/__pycache__/fift.cpython-312.pyc,, +pygments/lexers/__pycache__/floscript.cpython-312.pyc,, +pygments/lexers/__pycache__/forth.cpython-312.pyc,, +pygments/lexers/__pycache__/fortran.cpython-312.pyc,, +pygments/lexers/__pycache__/foxpro.cpython-312.pyc,, +pygments/lexers/__pycache__/freefem.cpython-312.pyc,, +pygments/lexers/__pycache__/func.cpython-312.pyc,, +pygments/lexers/__pycache__/functional.cpython-312.pyc,, +pygments/lexers/__pycache__/futhark.cpython-312.pyc,, +pygments/lexers/__pycache__/gcodelexer.cpython-312.pyc,, +pygments/lexers/__pycache__/gdscript.cpython-312.pyc,, +pygments/lexers/__pycache__/gleam.cpython-312.pyc,, +pygments/lexers/__pycache__/go.cpython-312.pyc,, +pygments/lexers/__pycache__/grammar_notation.cpython-312.pyc,, +pygments/lexers/__pycache__/graph.cpython-312.pyc,, +pygments/lexers/__pycache__/graphics.cpython-312.pyc,, +pygments/lexers/__pycache__/graphql.cpython-312.pyc,, +pygments/lexers/__pycache__/graphviz.cpython-312.pyc,, +pygments/lexers/__pycache__/gsql.cpython-312.pyc,, +pygments/lexers/__pycache__/hare.cpython-312.pyc,, +pygments/lexers/__pycache__/haskell.cpython-312.pyc,, +pygments/lexers/__pycache__/haxe.cpython-312.pyc,, +pygments/lexers/__pycache__/hdl.cpython-312.pyc,, +pygments/lexers/__pycache__/hexdump.cpython-312.pyc,, +pygments/lexers/__pycache__/html.cpython-312.pyc,, +pygments/lexers/__pycache__/idl.cpython-312.pyc,, +pygments/lexers/__pycache__/igor.cpython-312.pyc,, +pygments/lexers/__pycache__/inferno.cpython-312.pyc,, +pygments/lexers/__pycache__/installers.cpython-312.pyc,, +pygments/lexers/__pycache__/int_fiction.cpython-312.pyc,, +pygments/lexers/__pycache__/iolang.cpython-312.pyc,, +pygments/lexers/__pycache__/j.cpython-312.pyc,, +pygments/lexers/__pycache__/javascript.cpython-312.pyc,, +pygments/lexers/__pycache__/jmespath.cpython-312.pyc,, +pygments/lexers/__pycache__/jslt.cpython-312.pyc,, +pygments/lexers/__pycache__/json5.cpython-312.pyc,, +pygments/lexers/__pycache__/jsonnet.cpython-312.pyc,, +pygments/lexers/__pycache__/jsx.cpython-312.pyc,, +pygments/lexers/__pycache__/julia.cpython-312.pyc,, +pygments/lexers/__pycache__/jvm.cpython-312.pyc,, +pygments/lexers/__pycache__/kuin.cpython-312.pyc,, +pygments/lexers/__pycache__/kusto.cpython-312.pyc,, +pygments/lexers/__pycache__/ldap.cpython-312.pyc,, +pygments/lexers/__pycache__/lean.cpython-312.pyc,, +pygments/lexers/__pycache__/lilypond.cpython-312.pyc,, +pygments/lexers/__pycache__/lisp.cpython-312.pyc,, +pygments/lexers/__pycache__/macaulay2.cpython-312.pyc,, +pygments/lexers/__pycache__/make.cpython-312.pyc,, +pygments/lexers/__pycache__/maple.cpython-312.pyc,, +pygments/lexers/__pycache__/markup.cpython-312.pyc,, +pygments/lexers/__pycache__/math.cpython-312.pyc,, +pygments/lexers/__pycache__/matlab.cpython-312.pyc,, +pygments/lexers/__pycache__/maxima.cpython-312.pyc,, +pygments/lexers/__pycache__/meson.cpython-312.pyc,, +pygments/lexers/__pycache__/mime.cpython-312.pyc,, +pygments/lexers/__pycache__/minecraft.cpython-312.pyc,, +pygments/lexers/__pycache__/mips.cpython-312.pyc,, +pygments/lexers/__pycache__/ml.cpython-312.pyc,, +pygments/lexers/__pycache__/modeling.cpython-312.pyc,, +pygments/lexers/__pycache__/modula2.cpython-312.pyc,, +pygments/lexers/__pycache__/mojo.cpython-312.pyc,, +pygments/lexers/__pycache__/monte.cpython-312.pyc,, +pygments/lexers/__pycache__/mosel.cpython-312.pyc,, +pygments/lexers/__pycache__/ncl.cpython-312.pyc,, +pygments/lexers/__pycache__/nimrod.cpython-312.pyc,, +pygments/lexers/__pycache__/nit.cpython-312.pyc,, +pygments/lexers/__pycache__/nix.cpython-312.pyc,, +pygments/lexers/__pycache__/numbair.cpython-312.pyc,, +pygments/lexers/__pycache__/oberon.cpython-312.pyc,, +pygments/lexers/__pycache__/objective.cpython-312.pyc,, +pygments/lexers/__pycache__/ooc.cpython-312.pyc,, +pygments/lexers/__pycache__/openscad.cpython-312.pyc,, +pygments/lexers/__pycache__/other.cpython-312.pyc,, +pygments/lexers/__pycache__/parasail.cpython-312.pyc,, +pygments/lexers/__pycache__/parsers.cpython-312.pyc,, +pygments/lexers/__pycache__/pascal.cpython-312.pyc,, +pygments/lexers/__pycache__/pawn.cpython-312.pyc,, +pygments/lexers/__pycache__/pddl.cpython-312.pyc,, +pygments/lexers/__pycache__/perl.cpython-312.pyc,, +pygments/lexers/__pycache__/phix.cpython-312.pyc,, +pygments/lexers/__pycache__/php.cpython-312.pyc,, +pygments/lexers/__pycache__/pointless.cpython-312.pyc,, +pygments/lexers/__pycache__/pony.cpython-312.pyc,, +pygments/lexers/__pycache__/praat.cpython-312.pyc,, +pygments/lexers/__pycache__/procfile.cpython-312.pyc,, +pygments/lexers/__pycache__/prolog.cpython-312.pyc,, +pygments/lexers/__pycache__/promql.cpython-312.pyc,, +pygments/lexers/__pycache__/prql.cpython-312.pyc,, +pygments/lexers/__pycache__/ptx.cpython-312.pyc,, +pygments/lexers/__pycache__/purescript.cpython-312.pyc,, +pygments/lexers/__pycache__/python.cpython-312.pyc,, +pygments/lexers/__pycache__/q.cpython-312.pyc,, +pygments/lexers/__pycache__/qlik.cpython-312.pyc,, +pygments/lexers/__pycache__/qvt.cpython-312.pyc,, +pygments/lexers/__pycache__/r.cpython-312.pyc,, +pygments/lexers/__pycache__/rdf.cpython-312.pyc,, +pygments/lexers/__pycache__/rebol.cpython-312.pyc,, +pygments/lexers/__pycache__/rego.cpython-312.pyc,, +pygments/lexers/__pycache__/rell.cpython-312.pyc,, +pygments/lexers/__pycache__/resource.cpython-312.pyc,, +pygments/lexers/__pycache__/ride.cpython-312.pyc,, +pygments/lexers/__pycache__/rita.cpython-312.pyc,, +pygments/lexers/__pycache__/rnc.cpython-312.pyc,, +pygments/lexers/__pycache__/roboconf.cpython-312.pyc,, +pygments/lexers/__pycache__/robotframework.cpython-312.pyc,, +pygments/lexers/__pycache__/ruby.cpython-312.pyc,, +pygments/lexers/__pycache__/rust.cpython-312.pyc,, +pygments/lexers/__pycache__/sas.cpython-312.pyc,, +pygments/lexers/__pycache__/savi.cpython-312.pyc,, +pygments/lexers/__pycache__/scdoc.cpython-312.pyc,, +pygments/lexers/__pycache__/scripting.cpython-312.pyc,, +pygments/lexers/__pycache__/sgf.cpython-312.pyc,, +pygments/lexers/__pycache__/shell.cpython-312.pyc,, +pygments/lexers/__pycache__/sieve.cpython-312.pyc,, +pygments/lexers/__pycache__/slash.cpython-312.pyc,, +pygments/lexers/__pycache__/smalltalk.cpython-312.pyc,, +pygments/lexers/__pycache__/smithy.cpython-312.pyc,, +pygments/lexers/__pycache__/smv.cpython-312.pyc,, +pygments/lexers/__pycache__/snobol.cpython-312.pyc,, +pygments/lexers/__pycache__/solidity.cpython-312.pyc,, +pygments/lexers/__pycache__/soong.cpython-312.pyc,, +pygments/lexers/__pycache__/sophia.cpython-312.pyc,, +pygments/lexers/__pycache__/special.cpython-312.pyc,, +pygments/lexers/__pycache__/spice.cpython-312.pyc,, +pygments/lexers/__pycache__/sql.cpython-312.pyc,, +pygments/lexers/__pycache__/srcinfo.cpython-312.pyc,, +pygments/lexers/__pycache__/stata.cpython-312.pyc,, +pygments/lexers/__pycache__/supercollider.cpython-312.pyc,, +pygments/lexers/__pycache__/tablegen.cpython-312.pyc,, +pygments/lexers/__pycache__/tact.cpython-312.pyc,, +pygments/lexers/__pycache__/tal.cpython-312.pyc,, +pygments/lexers/__pycache__/tcl.cpython-312.pyc,, +pygments/lexers/__pycache__/teal.cpython-312.pyc,, +pygments/lexers/__pycache__/templates.cpython-312.pyc,, +pygments/lexers/__pycache__/teraterm.cpython-312.pyc,, +pygments/lexers/__pycache__/testing.cpython-312.pyc,, +pygments/lexers/__pycache__/text.cpython-312.pyc,, +pygments/lexers/__pycache__/textedit.cpython-312.pyc,, +pygments/lexers/__pycache__/textfmts.cpython-312.pyc,, +pygments/lexers/__pycache__/theorem.cpython-312.pyc,, +pygments/lexers/__pycache__/thingsdb.cpython-312.pyc,, +pygments/lexers/__pycache__/tlb.cpython-312.pyc,, +pygments/lexers/__pycache__/tls.cpython-312.pyc,, +pygments/lexers/__pycache__/tnt.cpython-312.pyc,, +pygments/lexers/__pycache__/trafficscript.cpython-312.pyc,, +pygments/lexers/__pycache__/typoscript.cpython-312.pyc,, +pygments/lexers/__pycache__/typst.cpython-312.pyc,, +pygments/lexers/__pycache__/ul4.cpython-312.pyc,, +pygments/lexers/__pycache__/unicon.cpython-312.pyc,, +pygments/lexers/__pycache__/urbi.cpython-312.pyc,, +pygments/lexers/__pycache__/usd.cpython-312.pyc,, +pygments/lexers/__pycache__/varnish.cpython-312.pyc,, +pygments/lexers/__pycache__/verification.cpython-312.pyc,, +pygments/lexers/__pycache__/verifpal.cpython-312.pyc,, +pygments/lexers/__pycache__/vip.cpython-312.pyc,, +pygments/lexers/__pycache__/vyper.cpython-312.pyc,, +pygments/lexers/__pycache__/web.cpython-312.pyc,, +pygments/lexers/__pycache__/webassembly.cpython-312.pyc,, +pygments/lexers/__pycache__/webidl.cpython-312.pyc,, +pygments/lexers/__pycache__/webmisc.cpython-312.pyc,, +pygments/lexers/__pycache__/wgsl.cpython-312.pyc,, +pygments/lexers/__pycache__/whiley.cpython-312.pyc,, +pygments/lexers/__pycache__/wowtoc.cpython-312.pyc,, +pygments/lexers/__pycache__/wren.cpython-312.pyc,, +pygments/lexers/__pycache__/x10.cpython-312.pyc,, +pygments/lexers/__pycache__/xorg.cpython-312.pyc,, +pygments/lexers/__pycache__/yang.cpython-312.pyc,, +pygments/lexers/__pycache__/yara.cpython-312.pyc,, +pygments/lexers/__pycache__/zig.cpython-312.pyc,, +pygments/lexers/_ada_builtins.py,sha256=dZb-lodsSM6L5emLlgLg-rClm2HumvnHK72CetnSRdA,1546 +pygments/lexers/_asy_builtins.py,sha256=zg54fGhgzWXQUk6-qZ6OW5GTL9d4OrnB8SJQkjrD0xs,27290 +pygments/lexers/_cl_builtins.py,sha256=oBF00ZkJyD14LkYuR603EDFIMyitkze12aT7UzDYLYs,13997 +pygments/lexers/_cocoa_builtins.py,sha256=ab6sq-iy5LapE1cNYyl8PJXLg6EINXx-lMRbwERdKYs,105176 +pygments/lexers/_csound_builtins.py,sha256=wuWiQjmEMhaVvsV8b_efsebgU0YKIoMC0ECpOavTCIM,18417 +pygments/lexers/_css_builtins.py,sha256=qhmC4tRGG53zvzMQE1qn794LvbVODRtVacxWCP3kIkA,12449 +pygments/lexers/_googlesql_builtins.py,sha256=mGfOGuKKjZoHHAAZq6Hpc68x0qKycx-SX_wGDScSOYI,16135 +pygments/lexers/_julia_builtins.py,sha256=u6v0yAzZjqUENjiIQ5qMfcso1r_6ERqGbj3aHwFnyqA,11886 +pygments/lexers/_lasso_builtins.py,sha256=YO_c_f05ZoxspHxCR3oWQCpZhbAJUzBJBhVuuwTjr5c,134513 +pygments/lexers/_lilypond_builtins.py,sha256=-_4i4gpgDgcFHvaZMJL2s1rI9dSNY2ZC6vO6ul7Hml0,115114 +pygments/lexers/_lua_builtins.py,sha256=-OWsR1hO60uWEe-HyWFtPNoIbPOpsWzjXNfKwGcyXkQ,8110 +pygments/lexers/_luau_builtins.py,sha256=YLUj2bcZ0Cb0SBkIlNXWHFGDUFkpddOJx-ukrZx1cMc,958 +pygments/lexers/_mapping.py,sha256=_X4awUqJXkdZHHqRFGDrvipHyu2BFZ6ikndsCKEitPo,71218 +pygments/lexers/_mql_builtins.py,sha256=CkcvMyHYh4U5rGgV6AgShxRnTOv0tmqEbOiVdpaFLqs,24716 +pygments/lexers/_mysql_builtins.py,sha256=SqiVYVVirtnN4lSgtfeRPxtVpcumjUvvUq9n8JObuQ4,26876 +pygments/lexers/_openedge_builtins.py,sha256=AzF1o6eAkMc6vnvmeVqNnUZUVijzbNYkjzrUdtCQe3M,49401 +pygments/lexers/_php_builtins.py,sha256=9g-WLT3qbSGolQJB_4PS6FW_r7HVXBWvI5OWxKtbwok,108054 +pygments/lexers/_postgres_builtins.py,sha256=QGg2mBTThgv4LdXjFm5wrKaKnCU9DubmJi6lXB7y2Mg,13346 +pygments/lexers/_qlik_builtins.py,sha256=3ZkCSDjtxSxXDI9erigWTLSUct_ap_W0LqfZjFeKQYI,12598 +pygments/lexers/_scheme_builtins.py,sha256=O3BRtt5suTESbZ_bSReQ6D0r0G_Sq_i4wCcUkdUrdS0,32567 +pygments/lexers/_scilab_builtins.py,sha256=E33R0mknNc-5eZ9Ugu7u7Av_vUxAaQoMTtdx3MceyxU,52414 +pygments/lexers/_sourcemod_builtins.py,sha256=8qspLxCLsfN9J7N0SWZRNs0A-qJOIGRBAJaNMeWaOBQ,26780 +pygments/lexers/_sql_builtins.py,sha256=fLphonB6wv6Oit8zanJiExgRoLvZoFW4l9lNH-PTYvw,6770 +pygments/lexers/_stan_builtins.py,sha256=sIoONg4TjLkGN7Ab0tZB1HM7tQ071_Z2c41n9lXZl04,16623 +pygments/lexers/_stata_builtins.py,sha256=ymh8GxEca6eSCgHnqsLqsi9OrfRqYnt5O8yBeinJ7DE,27230 +pygments/lexers/_tsql_builtins.py,sha256=Mw6UnMByju0U-OBgT8af3A4utfrS00Tn5lDnaxBtj9c,15463 +pygments/lexers/_usd_builtins.py,sha256=SGp_ePf2VuktrFV59q6df4mTyxZV7AZYs0TJFSWoBAI,1661 +pygments/lexers/_vbscript_builtins.py,sha256=TFtyc11yvpD_OlNrrFbcCOJoUYkWMq3EeHHCpw_zJNc,4228 +pygments/lexers/_vim_builtins.py,sha256=-_wGWnH2Hu4NNtGasyzbxV6cG4_LO3-y0Lrn7seiC7E,120501 +pygments/lexers/actionscript.py,sha256=LrMgu7597B5-C0gy0WlVLkHn22sRBbk6_gUXDhINwcA,11738 +pygments/lexers/ada.py,sha256=BWoQ2CpWBI5TbwN-VGCd0lPsLuImYXKVtCU1tDZrAzY,5323 +pygments/lexers/agile.py,sha256=Du-vjnGZEPHuE40XxTMO-XLt56pYcIaKIAxIwcYHFH0,899 +pygments/lexers/algebra.py,sha256=DpVQCnuiceTGyfXRNvWdl-4s64n60S28-qo-fIMopjs,10161 +pygments/lexers/ambient.py,sha256=8Nk8WX4qrId9zj_zgjJBuFT40yQXG2OXxFhhF3R00g8,2608 +pygments/lexers/amdgpu.py,sha256=GkVjwo54ADtgpyWO9ELnw4YAoU7UZ9ssR3UchnQ9gqU,1725 +pygments/lexers/ampl.py,sha256=TkqkaVyIfbNQpQBDzdTbq0gObv0gGJYZHu5IUvxC4eU,4179 +pygments/lexers/apdlexer.py,sha256=puSpLBWevciSc8G0wg2Y_yQIoGgqPes0UBkpFImqvO4,30803 +pygments/lexers/apl.py,sha256=-jhPYsBVT4ckL7CZmukIZNi6tfaJJbBk2vutld372rs,3407 +pygments/lexers/archetype.py,sha256=buhH2WHtxBowy_KD5SPm5vgHpmLoKMdV9tgMs_bE4xU,11577 +pygments/lexers/arrow.py,sha256=e6mb3Ix4jL7TMGNUpk8iRbJy_VF7VY2J0VUknlo1EvA,3567 +pygments/lexers/arturo.py,sha256=GkklOaiEJTOz8E0zdxd_hd1zXwv7lYgp8IJl7uh13hg,11417 +pygments/lexers/asc.py,sha256=CvFSi7FYDW6eu-5oiKGc0MN3aF1XVZDoFI5-3mHpBDk,1696 +pygments/lexers/asm.py,sha256=cS3eEMyP6affGJ_u6TkbdFMIk8qbVHwIj0AkINziQF8,42201 +pygments/lexers/asn1.py,sha256=MLakOeBFkdhKKr42eHFzonpGITEJxR_God8vqjWPva4,4267 +pygments/lexers/automation.py,sha256=pHnV3yUQhW0E-icbexMyDUKI8vaK8y7RHEW1ghIU1Dw,19834 +pygments/lexers/bare.py,sha256=AdqL9Z20nd0bhNGWielLhAHej6V8_8m1OWUkCOrSBx8,3023 +pygments/lexers/basic.py,sha256=UoNDxIFWAOtHUb_b-bc8fKRXy--935mvO3nkbkCrYA4,27949 +pygments/lexers/bdd.py,sha256=KeuOzXBLJRxxM2gV7aMuYsdV_aJFHyBuF8ptBpWxD5M,1644 +pygments/lexers/berry.py,sha256=THBzW216WxxZ__5r7a36Lv7UuGIedlNGhsN9oZ70ZUU,3212 +pygments/lexers/bibtex.py,sha256=sgfFqXyNyCxROHIe8C0gre69rzbADALnpDtTaqHfSas,4814 +pygments/lexers/bitbake.py,sha256=zwqK9cthJnio8jxqlUJUPt5O5d_I4Byd9dwk950lfdc,6132 +pygments/lexers/blueprint.py,sha256=dW-L5bFIiWxRPDashee2EOYmXIRHdwuCZ1y3iN-a6_0,6191 +pygments/lexers/boa.py,sha256=VqYF1Yg_XdDA5tK_Eiuo1rr7ediBsKUTpB6xza_B5d4,3924 +pygments/lexers/bqn.py,sha256=se4W2XPsNiT36z0Am9X5F4yNLrQvMI5X8miY6R9SEM8,3674 +pygments/lexers/business.py,sha256=YqMwDV7SwF66W7ug0O6sjatfUk7GBjRLF9mWMArozD8,28348 +pygments/lexers/c_cpp.py,sha256=HwYJqLkCAhedyMKnrM8xNEVZYTNa7yB-l3jbt9qpBQ0,21069 +pygments/lexers/c_like.py,sha256=uI1J_xS7sy7bjGp_R5V7ZgLJIlW7Nm8zSJ4GpYhNhks,32374 +pygments/lexers/capnproto.py,sha256=kc3rT95GkeQmrW1LeP5HMVb7Nk8sqXkW6OJkkWIHYbA,2177 +pygments/lexers/carbon.py,sha256=_M-0YbofjZMrJIaiXKoT6wpkd3_6fFq-OdSZ7V961I4,3214 +pygments/lexers/cddl.py,sha256=7Wri2q2yKexWo0CD7s2c7AoCAMbrwyEE6f_gz5B6x1Y,5079 +pygments/lexers/cel.py,sha256=ibsHrMk7abui4WpMEIb2ApwlSugfj0AcNcoUNfra4lM,5063 +pygments/lexers/chapel.py,sha256=hX62O91PcXe6b9d3Oi7lUWYCmiJNd0BgQoQC2pivfIA,5159 +pygments/lexers/clean.py,sha256=_oV3Tbmrpl3S1phPMS6gyMWyGZGj6Wy0q8adpf5vunY,6421 +pygments/lexers/codeql.py,sha256=hAX51uWeG5Zk9JhXSnOxPMaznFOpaX4ZnZHZ2krrPGk,2579 +pygments/lexers/comal.py,sha256=0fcTyV5h36zPlxoQPWWGet2yaYi5ESXiFpx6EbsqP00,3182 +pygments/lexers/compiled.py,sha256=PRimy7eb2weP7X6bEukz1JaSLuQAETO34K7maHLGbxA,1429 +pygments/lexers/configs.py,sha256=9ev0yIzHwM9rVmyHPcqI5aAi5EkllP-80vSBOQT3r2Q,53776 +pygments/lexers/console.py,sha256=UWhJ21BpDWj3913l2Ne5Ni7M_NweUrLTS8gyB9aOnbs,4752 +pygments/lexers/cplint.py,sha256=mJI_of7ACPi_sA0K1DGzsAH2N54MW9hFregCP9ru27M,1391 +pygments/lexers/crystal.py,sha256=k8Xy8TpfGKTPvsP1WikxILScILD8iXZ5qceLZopsLYE,15757 +pygments/lexers/csound.py,sha256=7FVCxtcGXH8nQIoI7E5skcTo9hqEgXLeSEnL5sQZ_5Q,17006 +pygments/lexers/css.py,sha256=6AjX9yYAx9kZ_BK6qL4ox7bqgqqiHp1gC34zR7h0eD4,26457 +pygments/lexers/d.py,sha256=Yh8_dPSlJwFf1eFb82y-kkP1LzqYSoa8X2AFzln0x60,9917 +pygments/lexers/dalvik.py,sha256=0f5mB5y8g0l1ID2liJ_5qM2NjyR_SBs7ckuIDeNbbj8,4609 +pygments/lexers/data.py,sha256=cKO2LwqOeJxjD3_FaMd0jxyzjzf_tE9IKDAlEdUan3I,27068 +pygments/lexers/dax.py,sha256=N-5fxukBfFtFCT2LJoyg1VJsfldWHxXKLY3ZPLnPrig,8101 +pygments/lexers/devicetree.py,sha256=Tig-tTSrpmGzbGxN2ka4MMTiC344roav9A4hoc9o_kw,4826 +pygments/lexers/diff.py,sha256=-627lmuYpJ2uUVUM_orVGgXJGXIBGSVHbmlqflCEeaM,5385 +pygments/lexers/dns.py,sha256=ElzSN3IEoRs1g6iWMnzVIV8H0x9WSEF1wBjm2a0ByxE,3894 +pygments/lexers/dotnet.py,sha256=b4g5nMhHtOU-5if6f-JQlttJLx36XWo-2AIN16c4y2A,40222 +pygments/lexers/dsls.py,sha256=uI1VJaYf95U1swmpx6seFXbulDGtIaantJ5yI883iIg,36750 +pygments/lexers/dylan.py,sha256=fi8mSyni4dnGP5x1crE6BKNqLWJs4dDWdmkur-TbbNc,10412 +pygments/lexers/ecl.py,sha256=kT_kUz6RmeQmkMAaqayS4Qoa7yV3_e3nz_xEoa-iUKk,6374 +pygments/lexers/eiffel.py,sha256=bZo9OWM8rIl7lJh60beL9Rvzqxo9kXIKKaJ8eWOcbfw,2656 +pygments/lexers/elm.py,sha256=Xj3HlbUTEkEUFwhem4NCujx55tQ2TS61_Kcf6BCPHAI,3155 +pygments/lexers/elpi.py,sha256=RZqAVzdxfA_BqBmtMHj8ATw5f9e24SKL-QeO14QuKk4,7904 +pygments/lexers/email.py,sha256=RxPstHy9RVpCYhVX7tZmTMyXiG493WNoEZHM55h-sNI,4690 +pygments/lexers/erlang.py,sha256=2aUlVBVFtQdR2QISsDeKTOPjGrV7r1ckyXL17KJot9c,19150 +pygments/lexers/esoteric.py,sha256=uTYR77pBotb4Q9egWk3IOQ35-gZ7s-ioK6nV0frefJE,10502 +pygments/lexers/ezhil.py,sha256=tbGYtGnqZAB8ffnyPdeMMJHtKYJ7OAciUFRrR_8QpXM,3275 +pygments/lexers/factor.py,sha256=lKs1uQzTtMPEx87rMU7Bw79QRKrzxBWnBqTpJasZNu0,19403 +pygments/lexers/fantom.py,sha256=pP_H_fxfu3Qsil87HNHtp55NeiU6Mp_N4MmSVyqu4UE,10200 +pygments/lexers/felix.py,sha256=DvPOs_Em6fFtUBQCaZWWHWgnvAFeBrDe97Cy9XyQ8ps,9658 +pygments/lexers/fift.py,sha256=Q9OLJivp4ngqFso7APCvX85h-ghdbp9ZqpP8GKHws1M,1647 +pygments/lexers/floscript.py,sha256=aOBKAo64-3cnvoM6Q4XvLng2iuz4609fIReab4tMEy4,3028 +pygments/lexers/forth.py,sha256=4e0OCfJGcElkQrHInmQMucvsI9dljuPx4FYg38dyjno,7196 +pygments/lexers/fortran.py,sha256=ouvOHdMbj56j40Nrj21WCRf4rNKpuwphxmtlUVsnzhc,10385 +pygments/lexers/foxpro.py,sha256=nV8yyES39QoFmTNlM8xl3MteOsvmt6yV1l6x6xnXqIU,26298 +pygments/lexers/freefem.py,sha256=ZmZLIYLXtCK2kWqGzBmrkp7ychOy7vgfaorafUkUl1I,26916 +pygments/lexers/func.py,sha256=ZjOerj3njJcaGnHWc_npWjxb4D5O-udxBRK7RLHEibU,3703 +pygments/lexers/functional.py,sha256=4m9JlAnfpXxSkQQIrNOob2VTwin6hPLAqWuhv9aVkAg,697 +pygments/lexers/futhark.py,sha256=_MAz8PIdhlK0pBSaT39OqLhsOfg36ET0booAdi70lJY,3709 +pygments/lexers/gcodelexer.py,sha256=t8JMWaaDjWZwdGiRGwrpsYtfjKTmibwlRyOLCiJZ8qw,877 +pygments/lexers/gdscript.py,sha256=1aIezdxqgC6zWhq6oA8G1bxntrP4YlwT7Y_5lFQWqwM,7565 +pygments/lexers/gleam.py,sha256=Jx6LnUpWV9pmjdSYLUMt16c3UamZ-v5X6CcuEhWxf-8,2395 +pygments/lexers/go.py,sha256=Rn7fUpj6FLjUkFYjW6qAgDFSQhk1ZrKqAAEdrrkT3Ak,3416 +pygments/lexers/grammar_notation.py,sha256=ZGYcwhSvOolw1J7cA9Pc7hVpcIselaCgxwsvAf5yRgc,8046 +pygments/lexers/graph.py,sha256=X_IsdjxXZn5p9Dq4cLXyqwo4C8emcYA8NP6VZ9ZTBaU,4111 +pygments/lexers/graphics.py,sha256=KfCvhVdl6i3N7elbzehd9Gx6WrU4iYyC94jsTwVdL6A,39137 +pygments/lexers/graphql.py,sha256=RWE_kfVUDEAnv_-SYyOi9IJUks61NvOakmUfWOlorzo,5604 +pygments/lexers/graphviz.py,sha256=yhzFd2537OKnPlRiGF9YiEjfBzaRnMdaGF25Ib4vqLk,1937 +pygments/lexers/gsql.py,sha256=_FJmuKNZsx5fFQUyPFp8-3cQTpnraA7fwcInPINh8b0,3993 +pygments/lexers/hare.py,sha256=eCrRPwcswXL-ZHTWNlhE1A05G9rxzS20_IqSddv2M9Y,2652 +pygments/lexers/haskell.py,sha256=sr5gq3U7xt0D2Bi41xdTsBaponX6otP1qPyRMCuxM7E,33323 +pygments/lexers/haxe.py,sha256=_MzQJTWx18kD9bP_sniBshKbtOZDRm4OZnifaOgw_aY,31169 +pygments/lexers/hdl.py,sha256=JCQKW6HFdoTdFFibL90F1m7cYJhM3IP2AWmxIYEDgdk,22742 +pygments/lexers/hexdump.py,sha256=SAGr_YEkdL8omo1uQb_PtUCAESyE8hPlVK7FGGkOr3Q,3656 +pygments/lexers/html.py,sha256=ROfHF8WggPj4adE6-S9sKvCh5UY0K0I868UxO5y-3fI,22007 +pygments/lexers/idl.py,sha256=STF000ZDy03EDjWYYQzysCpXjScmNg09nzLgEnhgyWo,15451 +pygments/lexers/igor.py,sha256=Sv5EGBJeKy0UOyl6-GF3lBeeoWArVcMDJtQtl2RXRYo,31636 +pygments/lexers/inferno.py,sha256=J6zFrYvkPLd_PGqcH7R2nRsajW8RfRuX1xZlRzC49YA,3138 +pygments/lexers/installers.py,sha256=ioK2JUPSJk9vcsoe3NASvMt-paXd1_Nn3e8WmaqJ7CE,14494 +pygments/lexers/int_fiction.py,sha256=BUjvXilUiuMF-euXEQDzQZs45jn_aLs17eTKcfEptrI,56547 +pygments/lexers/iolang.py,sha256=0YyjBAWP4xl3zd8PcsOtZMIbSh10KXnJCLc6xqclkZo,1908 +pygments/lexers/j.py,sha256=56qUbs1C7wKdZ6-WpNnxHntNqsxWroqiO7keI2yoR1o,4856 +pygments/lexers/javascript.py,sha256=ZuzIW7rxRSfgehj1Ek321cTG3SUkrmDiwv9BmpNfU5M,63365 +pygments/lexers/jmespath.py,sha256=OXI1qW6ylypsmbQLRgmTr8GykaIZ3zfPHyXwqesfDZA,2087 +pygments/lexers/jslt.py,sha256=UOVw1J3uK-hVRWomoFK2jMS_yeuo5iqga-LhXUJI660,3703 +pygments/lexers/json5.py,sha256=GyeZ58AxKkJJiiH7JuPmakDZXropa6bDkFRguJHifqU,2505 +pygments/lexers/jsonnet.py,sha256=rPso9d_PVMnNVJlWMqtkGSxLJb9Exb0OcAjMOtMgGME,5543 +pygments/lexers/jsx.py,sha256=-00tc-VTkFaHkkFV5bvznuvKUeCD5xfWmS4Rqi1nq8E,2748 +pygments/lexers/julia.py,sha256=2JR78TfsGoGI8Ky3Z-1yQSrCIgeicEvEwdCTxOhh4Bk,11688 +pygments/lexers/jvm.py,sha256=PRMUxmztoVBtwvyNi2aN47P5qAADADlylqvzc6ifQ9Q,73264 +pygments/lexers/kuin.py,sha256=R_WrbyuoUK2pvYlzmSjs0lXHgyN94s2NJ250WCCK1-M,11401 +pygments/lexers/kusto.py,sha256=aP9GeFag3cin5oACFw2MXTXEdc8btMVJQm03Jkv810A,3486 +pygments/lexers/ldap.py,sha256=_ya4_InnSIRj-RYjGagWFZJDy1NdgQUocQzVWjiRp68,6554 +pygments/lexers/lean.py,sha256=qP_iwUQ7MJZ1C5s3KYBW8Wu6-uuVj4PAG3a2Ghjp99U,8588 +pygments/lexers/lilypond.py,sha256=o264ovGZFrcx8ZwpKRX-gjUECK1w5T8T0n6LoTjP92U,9755 +pygments/lexers/lisp.py,sha256=CC-VZaGEuWLWtuS66q-1xT-kIPVTuL8yqZ5YxR3HVgM,157900 +pygments/lexers/macaulay2.py,sha256=P43kgbuo6W2jeiSggcC8IJUGkRwqhba2tJRo226alAw,35392 +pygments/lexers/make.py,sha256=wAV0KRRXTAFMliLfAKXDihQIE2VAVUvWjFZ-yuM7a08,7834 +pygments/lexers/maple.py,sha256=aZ4lMzm9hEtgHm0-tkBhBn3SpwR6srI1eW55tyP_3ms,7965 +pygments/lexers/markup.py,sha256=kFcWyal07K7-jlib26R7U9yHoDfn_ubKeZjVc9MVGGU,66526 +pygments/lexers/math.py,sha256=Nspl6IZtCyh9egiYUahboWSmy4cJCVZUBxyVnCuF1ag,698 +pygments/lexers/matlab.py,sha256=21aZat9CTpxJLEyOdzFBePOFEpXB4hF6Hcq6zaOIg9c,132992 +pygments/lexers/maxima.py,sha256=ha-f-JzGkjggAr5kxmVq7_uJTCcpHstQWnsLHYIhNwU,2718 +pygments/lexers/meson.py,sha256=WXA6cdMx8OAVN_rawbAoopYsO2z9_453s3OAOutkgCA,4347 +pygments/lexers/mime.py,sha256=l5BsFkad3agJ6KDg_IHI6nU0Ao0Y9EcwjYoYP8vQD-g,7585 +pygments/lexers/minecraft.py,sha256=bBbMbqvsVgTfO7CBxf03oGP_qOAgrw06PSzH1QF7txs,13701 +pygments/lexers/mips.py,sha256=QpgBoMPzsk1t90cIF0W_EV-QZ8LwgTapS-fSISxZcFc,4659 +pygments/lexers/ml.py,sha256=jqA8SxYk8E6DlrmPID1M4ntBFqiPYa9TwsNZcnbF4Jc,35398 +pygments/lexers/modeling.py,sha256=PplErE4xasvfL8QjY036Aiu75igMbFmyIqOd5C38KAo,14664 +pygments/lexers/modula2.py,sha256=dXW0KNFu3ETgABsPMsIhdJI0DKF-KWtT831FKsz2VXw,53075 +pygments/lexers/mojo.py,sha256=QrVci9-WIOgvSLczXoWhm8AD3PGAYs6VrN5FcGj4Ofo,24232 +pygments/lexers/monte.py,sha256=JTx-jSrFKlWRwA1qzhPd647ETGSElwhP4YMlVrfXyX8,6292 +pygments/lexers/mosel.py,sha256=qgH6LxmoSoBDb_LrL3eXswt_esaPIX96vkAy68wFH_w,9300 +pygments/lexers/ncl.py,sha256=RZXkxOK-iHspLX_sFVT0wc5H6v-pa4kKghP79fJGQPQ,64002 +pygments/lexers/nimrod.py,sha256=L8Ww5CUaP-ojywoQZXnjC08m5Be64fBynSf5aWGIaPw,6416 +pygments/lexers/nit.py,sha256=ffrBJiZ4coH6THmsSBlcCEpD58lRxwkLkpAobT_v5-4,2727 +pygments/lexers/nix.py,sha256=M2E-k--F7pneuMAOae9ag4srJsKhWJ1f1fRueO6PtKM,4424 +pygments/lexers/numbair.py,sha256=tATiI26K4OfAyj3Sy3_8gyMMXFA4FgzIa_QuK4nV6us,1756 +pygments/lexers/oberon.py,sha256=uH1FkPeXCfdd0IQ_--S8SHUNaf2dnjiQZjtIT-jxu4A,4216 +pygments/lexers/objective.py,sha256=RD5nhW15pg3FUuy1IfGvb_h4be_3h5-HkFWpLVRI8eU,23663 +pygments/lexers/ooc.py,sha256=HEjWHdQDVk7tRb_TuEb1_C5qi-peJwwyYBVAhf49MS0,3005 +pygments/lexers/openscad.py,sha256=te2iL8VkfXul_PYXlz8UK3_QtMjdmNgt0YHCYEvdEtM,3703 +pygments/lexers/other.py,sha256=OAlXzsrVDUx4Ma25fyG98U5LaBEHyt-LJZ2IHvMJJWY,1766 +pygments/lexers/parasail.py,sha256=Kv6_y28WTDDusIbynUsUUj_oazx4huRbO0Dh9Hfd6jA,2987 +pygments/lexers/parsers.py,sha256=mKalKvYx1RrCz2VpEUZaUP_asGH4bP4F_TvdKxQ8Dsc,26598 +pygments/lexers/pascal.py,sha256=4dewXkwc12f_iiMfdNDqbxb_oqAEX2dCzb5VIZ62V54,30992 +pygments/lexers/pawn.py,sha256=n64BStqTxTzqcqCgNECyH7gv-XYEYfl_3SFoNXmwPvo,8256 +pygments/lexers/pddl.py,sha256=a8A2keCF9qNQvVZQirgBV5fH4u3cjrta8-eZJ8tsxmY,2992 +pygments/lexers/perl.py,sha256=ozzAeXY4O2mTIXNOuWomFViqW6I6IPQisGD1-Hl_VoY,39195 +pygments/lexers/phix.py,sha256=nEWWt5-OoIDapw4IJ_cNL19Th8Ztt6OIQgeuogVed10,23252 +pygments/lexers/php.py,sha256=U6wmxPM-pS-SY1N3qdv0ebUDBxLH6-EFIFcatUvg74w,13171 +pygments/lexers/pointless.py,sha256=gNcuhhOY9cEpIPyGFjMh2DItNB1UD8CmjceXkDRModE,1977 +pygments/lexers/pony.py,sha256=rqrhNoTPoAGLmaYChyTM4ALgaTsnLakvmAEi1jsVUwM,3280 +pygments/lexers/praat.py,sha256=sfVAd7zfRsI-TcCouuYMWlcU8EBxAwJ4wkh0ZuNsZ34,12679 +pygments/lexers/procfile.py,sha256=fhRTtscyMMPcPbvzjxVtXix1mYlpO-4JuWUL7Db4ENI,1158 +pygments/lexers/prolog.py,sha256=C5pMapUlzrV6KaPEdyD8aRdAigIlnUzjFVnFu0TvHWA,12866 +pygments/lexers/promql.py,sha256=04fS_R6HBWhpKNe3WPp_QXgIdFvJr5p6KxStZYw7yHU,4741 +pygments/lexers/prql.py,sha256=XJhd8dpEWPBIKmQXx_09-z1NyotLXIskpuzX36HykHo,8750 +pygments/lexers/ptx.py,sha256=mqqaC17DGpmdc2v55u-4e_1htBxmXvuKK07Vcsbzabo,4498 +pygments/lexers/purescript.py,sha256=cbDAly-NUN4O_SUk6v5zJSUQzoZZJbOTMHWeZRPx6lo,6086 +pygments/lexers/python.py,sha256=56Mm_WBnPjPatEOXyZq-PxCCJNYZo05bIK9e1i62A6U,54574 +pygments/lexers/q.py,sha256=2CbJYgRu8uz8wOSp5FMr086KCC7IjSRmIODVY0uKrCA,6939 +pygments/lexers/qlik.py,sha256=9b6Q-6jXeeraIRcWtsKsYWCOlBhfmjNzIN49pUvMR-I,3696 +pygments/lexers/qvt.py,sha256=Xl_lizvhmMwO-l11MUFzZuBKHb-cPNDN7F_PXhk0nBg,6106 +pygments/lexers/r.py,sha256=-4ZaP45fsq5EiEacsZkI2PQdi1-cHV-woef-wLL355Q,6476 +pygments/lexers/rdf.py,sha256=FM154fB1lxfOpSpeW6bWOVld5kJBgEuYyT9udt-EcK0,16063 +pygments/lexers/rebol.py,sha256=CQ3pMaAz64UMqiQVrYoREnOgjU5QPeF_H3aaHNdVRC8,18262 +pygments/lexers/rego.py,sha256=Yi0G4secTWOL7CUhLLCzJ9gA6SJzDJpPJNij3hXixC0,1751 +pygments/lexers/rell.py,sha256=-oa-JHAAyRP8--ZmFrPtaifzQNuqzqydmN1jF3XclOk,2484 +pygments/lexers/resource.py,sha256=RDEY7iSv2hgQ3V-I1DeOKVOumNKgFqbV2Me_9Y21o10,2930 +pygments/lexers/ride.py,sha256=1zg7kGYPKRIekyuZY3f6OVqRlXyrX-sR-tHEX1M9nz4,5038 +pygments/lexers/rita.py,sha256=fCNElPik6dDIZzGd96kKgdlY4Qqp_zVI87waTBHMBfg,1130 +pygments/lexers/rnc.py,sha256=PNfnnTlnZjNvvG33BNMCqPzdA9LZEYvDsGoaDd_2mn8,1975 +pygments/lexers/roboconf.py,sha256=l6BeJIS-ZAUb3zc5GEuVIb0edrRpPFmKdffEBx74Zxg,2077 +pygments/lexers/robotframework.py,sha256=8s1U7GldhzRPGR7d8_rMSG0ZJz9ZOm-LGqBTGILwt2U,18451 +pygments/lexers/ruby.py,sha256=5STDLcvmmBwGdRp1FNhzW25I9A4cvBv44dwLNuXy_V4,22987 +pygments/lexers/rust.py,sha256=7qD3KGVir-tUWf_bPBt4EX8l9aIWe8TblMCFI75oorc,8263 +pygments/lexers/sas.py,sha256=BF-HLqzjnBW64nkw3E5OplkXnIkf-OS3SX3HmWJKzyU,9457 +pygments/lexers/savi.py,sha256=HCllgBe3rzP_7-2b1hSUEbE2dYz08Iysxc6Dcxj3f2c,4881 +pygments/lexers/scdoc.py,sha256=9n64S-bO1dI4x-2Kzh2jrDM6gEmB5YI7ch6ndPB4-cw,2527 +pygments/lexers/scripting.py,sha256=vsw_KNTMFb5yzWHlDwd7w5C8bKCer2ZeL_BVtUhpy0Q,83232 +pygments/lexers/sgf.py,sha256=ya_sG4TOvDWwzEM6cIi40XSbhkTuHCqvo-uHnNYfi5Q,1988 +pygments/lexers/shell.py,sha256=rJ1yhM-pScZ10C6SZCFZweHBbid7RRC9qmlTUG265xg,36425 +pygments/lexers/sieve.py,sha256=CXR9S1nGeVTln2u5R600hxgkAmJFVVTTTBh_k3aw-pk,2517 +pygments/lexers/slash.py,sha256=Vlwv2EX5_s0V-TGnlXW7VjfQIeaFpj0pE_IUamdApnQ,8491 +pygments/lexers/smalltalk.py,sha256=q52NHegl3pjn1jMkJWA9J0nOA_A5VzUULZAPgb-6uNU,7207 +pygments/lexers/smithy.py,sha256=PBzMxxqZslii_U3AWTMUfjY6cOFTwBPvNjdL7-iRs7Y,3233 +pygments/lexers/smv.py,sha256=D51In9Qr2nWFicYAOX_bJpeFgmJ3BUkEXnvXPmA04D4,2808 +pygments/lexers/snobol.py,sha256=BX_1VPUZi-ckKCYlF2sttQprF2bLUHOi8blhInFHv9s,2781 +pygments/lexers/solidity.py,sha256=pz0DZ0xiHwufhbQ9hdCPrHMjA7NMsa6hxZ1nO-A4Y3E,3166 +pygments/lexers/soong.py,sha256=p6FMNSSuDs86oWPTTVUseu1Jj00nth5pG4jp1kje6hg,2342 +pygments/lexers/sophia.py,sha256=MAkWLYxhHJNcc3UUzWD3VDLzVRbf6IAd2uz4q7DY3wI,3379 +pygments/lexers/special.py,sha256=8gpTiLICFNwIcahm282mi8Nqi_6gwYMsAfjJIM2Bq6k,3588 +pygments/lexers/spice.py,sha256=Ss6oR3C8Vg5g6A5Lm4do-z24yeVHMbUM770zPaygD6o,2801 +pygments/lexers/sql.py,sha256=3DLtocXfraFpaebTXaecPpDCbp6_DjzF1jt4Os9KhoQ,41901 +pygments/lexers/srcinfo.py,sha256=MHj02VB7WP3AcoOz1WVYAqNM_3oFLjEaAda075kXVBU,1749 +pygments/lexers/stata.py,sha256=KojmkxWHlEk-HvmxI313a52nzH_JHNqfv6r3jJoFDy8,6418 +pygments/lexers/supercollider.py,sha256=H-qwP6sUaotemsXxuugpui6KnU3jtIdDfS3bGt3Jvh4,3700 +pygments/lexers/tablegen.py,sha256=ryuzw-ArLdvlY55YJBn6ebOzDo3L8UnbR5xcZB8xMso,4012 +pygments/lexers/tact.py,sha256=YbOWYNp302ZBPM5affzM4-CudJ4xRZyJb-_vSDCozCo,10812 +pygments/lexers/tal.py,sha256=xZYmhv8mBr-A3oeoFkcSP7nDbX1r21kKOnhsLTtL3bE,2907 +pygments/lexers/tcl.py,sha256=o0JzyYFFDzOYZK5DTS4bDnYc33SKBQzR8HZMPKxAFoc,5661 +pygments/lexers/teal.py,sha256=pgpPi9xWPumSr-heSpGBGDcU5s3qN0aFUj2maHLE3MM,3525 +pygments/lexers/templates.py,sha256=NGY4Dt85fHPqtSpjECAqQXaQ2agvOWySg80HdXiKz3E,75715 +pygments/lexers/teraterm.py,sha256=YCdvILRq-FdOJ_HfiIkYVToH3c6I2QRbQoH17Q49Hx8,10045 +pygments/lexers/testing.py,sha256=GF5SpanGwjgKKoYari32SdtdOWWXXje8xVX5-ZzTjLg,10813 +pygments/lexers/text.py,sha256=yq6mOLz3PizKNMm4_Y8UHn9vEeBfqEY5W-3M7dk1jYs,1071 +pygments/lexers/textedit.py,sha256=_DW3fSw25EkC_-_GRKep64DkxkmvjlbUxZNi-ajTR18,8065 +pygments/lexers/textfmts.py,sha256=WSiJDzNKCcOsBoTU4NCYU33ti5ZHGi0Px29eGjT6pB0,15527 +pygments/lexers/theorem.py,sha256=c-eg6tIYWUbxSYgrOtLZfFxro4g91JcAIwrIJGLPooU,17903 +pygments/lexers/thingsdb.py,sha256=FNKjArS1vadHEN3ZXaZdDLqvcG59GbF6Ak5M8RMsTLU,6257 +pygments/lexers/tlb.py,sha256=vWsFq_MrIrzgG2q-qdzpcoNiv9KkNow4x9ebs9_HAwA,1453 +pygments/lexers/tls.py,sha256=GZ1lvZ8PUk1-LThq1KuiqSEnMqJVqiHo_A-16aKuJOc,1543 +pygments/lexers/tnt.py,sha256=MNYTfkix0x5L1pDV8V8zGLS7GU8z7bt-wpiBap2W09U,10459 +pygments/lexers/trafficscript.py,sha256=1Tawom6bKJM-u1kYey21xFaHep3D9kl62rV3RaHSvcI,1509 +pygments/lexers/typoscript.py,sha256=dWAuOYYk0X4xE_fxKgcXz-sMYlG2wxQR4m_d7PW2PYs,8335 +pygments/lexers/typst.py,sha256=qtbEgl8HevhvncgVUYLCmvLrgyGrzgVjZE0NlMxnaUI,7168 +pygments/lexers/ul4.py,sha256=joM-US0-2BEWRHHK6eyZ-Y--306YgbMrevMY0hg8QTY,10502 +pygments/lexers/unicon.py,sha256=blg8AQYmU4SujjtyATTljEY-ML39isICvIYb1FYhL5k,18562 +pygments/lexers/urbi.py,sha256=j87k6fe60kZdbJ6AJA4g9E0no1EP0bxJY06UVP0YgnU,6085 +pygments/lexers/usd.py,sha256=ZeIavF5ISiDyKoVFqv-HSipmUtMLzwmFHvXReevYHiY,3303 +pygments/lexers/varnish.py,sha256=INCtYbol1yV_NXMh51CMDZDacEHgiB3SmR3H5uW-Fkc,7476 +pygments/lexers/verification.py,sha256=BEiuUB_a_Ujt7J3jLo1xGVr3JilYE-c7sGPVASe5feQ,4256 +pygments/lexers/verifpal.py,sha256=0iZTQWawF9f7lFZnFNPTwYRiu6L_25PtEI83tuCAmKY,2664 +pygments/lexers/vip.py,sha256=pM5xFoeu-2GPWqAVzZJe6xPYr6WJPlozVI5084SHQ80,5714 +pygments/lexers/vyper.py,sha256=rw2yD9c2L7yPtXqKPd0RdxJSZK-aJbW5jEa0gHfKEO0,5618 +pygments/lexers/web.py,sha256=YMrxoHlKlQwfFJlae9_T9F1Vp03YA7IWsmgqLzh6pgI,916 +pygments/lexers/webassembly.py,sha256=kQSeF2MyOnaAV4tRVsYHl2rcFO_FcrAjRYt0Ri2o5pU,5828 +pygments/lexers/webidl.py,sha256=MQMaZFskluB29lMGpiGP2f6fzoja4vV8FtoCGFQH6fM,10519 +pygments/lexers/webmisc.py,sha256=jqTLBw_Suxpi3diBtMCDPL6_Uf5gxpnGgi2uN1hWeUM,40563 +pygments/lexers/wgsl.py,sha256=vgDtY_q42TGRvcsyS7viSadU8D3eHvatfoCNNnEP0zE,11883 +pygments/lexers/whiley.py,sha256=MC2V7o1s7LIoLy0Fk-i8OymBoN0dpK2BPjIrdQwsnVk,4020 +pygments/lexers/wowtoc.py,sha256=XnLSSX7p_RkwZIzlmYXO873d4byX9-A3dfvzNL5Eocw,4079 +pygments/lexers/wren.py,sha256=2lhzwpS27xW6nERY_NeODgNN9X6mB7vl3odXSPngqY8,3232 +pygments/lexers/x10.py,sha256=0Z0hhPboSfIVE9NTi_gTXgI_uRrS8ARj0vm7JwZagz8,1946 +pygments/lexers/xorg.py,sha256=LUKU91t1Opc3W_F64UGzx0nB-HqKlN3Cn_6tFzt5IYw,928 +pygments/lexers/yang.py,sha256=yIvwteHWBWL2-8zZscnCPJOnq3rMOXh5lxJujywA_Zo,4502 +pygments/lexers/yara.py,sha256=_ISzhko7v9AhJ-1cWINZSyG3my2vJOyFSHxSjm4VdTY,2430 +pygments/lexers/zig.py,sha256=Cf28cP0orM89xc3QpJVchIQv02pr0jsnJLRzqivSAL0,3976 +pygments/modeline.py,sha256=me8g5rySidvPtMBOrDy2O1sMqZd02lBHMY5KDZefUws,1008 +pygments/plugin.py,sha256=9NKTHzu9SV7hfY3-TVC4Y7wQx83C8i5Lgs3-ABTBMbQ,1933 +pygments/regexopt.py,sha256=Ko9XtXDiLEKerWaD5492krCBWdpmZpgvkkmU_OkRmSo,3313 +pygments/scanner.py,sha256=DtoLi1pOKpNu-6jiakJpSQLUi_ep29SQQhv7oAwYWME,3095 +pygments/sphinxext.py,sha256=qmiWv5b7qq6bNUT2Y2wZejV2ImQmvtzGJFg6LcGENl0,7901 +pygments/style.py,sha256=KYKfa_XPQTOPxphTuRrT9UGnbj46_GtrEyQRlGe6q1c,6479 +pygments/styles/__init__.py,sha256=2vgGKnbyt0nf_CSDEtMhHxppPSAPr2jafzl5FiXFuGs,2009 +pygments/styles/__pycache__/__init__.cpython-312.pyc,, +pygments/styles/__pycache__/_mapping.cpython-312.pyc,, +pygments/styles/__pycache__/abap.cpython-312.pyc,, +pygments/styles/__pycache__/algol.cpython-312.pyc,, +pygments/styles/__pycache__/algol_nu.cpython-312.pyc,, +pygments/styles/__pycache__/arduino.cpython-312.pyc,, +pygments/styles/__pycache__/autumn.cpython-312.pyc,, +pygments/styles/__pycache__/borland.cpython-312.pyc,, +pygments/styles/__pycache__/bw.cpython-312.pyc,, +pygments/styles/__pycache__/coffee.cpython-312.pyc,, +pygments/styles/__pycache__/colorful.cpython-312.pyc,, +pygments/styles/__pycache__/default.cpython-312.pyc,, +pygments/styles/__pycache__/dracula.cpython-312.pyc,, +pygments/styles/__pycache__/emacs.cpython-312.pyc,, +pygments/styles/__pycache__/friendly.cpython-312.pyc,, +pygments/styles/__pycache__/friendly_grayscale.cpython-312.pyc,, +pygments/styles/__pycache__/fruity.cpython-312.pyc,, +pygments/styles/__pycache__/gh_dark.cpython-312.pyc,, +pygments/styles/__pycache__/gruvbox.cpython-312.pyc,, +pygments/styles/__pycache__/igor.cpython-312.pyc,, +pygments/styles/__pycache__/inkpot.cpython-312.pyc,, +pygments/styles/__pycache__/lightbulb.cpython-312.pyc,, +pygments/styles/__pycache__/lilypond.cpython-312.pyc,, +pygments/styles/__pycache__/lovelace.cpython-312.pyc,, +pygments/styles/__pycache__/manni.cpython-312.pyc,, +pygments/styles/__pycache__/material.cpython-312.pyc,, +pygments/styles/__pycache__/monokai.cpython-312.pyc,, +pygments/styles/__pycache__/murphy.cpython-312.pyc,, +pygments/styles/__pycache__/native.cpython-312.pyc,, +pygments/styles/__pycache__/night_owl.cpython-312.pyc,, +pygments/styles/__pycache__/nord.cpython-312.pyc,, +pygments/styles/__pycache__/onedark.cpython-312.pyc,, +pygments/styles/__pycache__/paraiso_dark.cpython-312.pyc,, +pygments/styles/__pycache__/paraiso_light.cpython-312.pyc,, +pygments/styles/__pycache__/pastie.cpython-312.pyc,, +pygments/styles/__pycache__/perldoc.cpython-312.pyc,, +pygments/styles/__pycache__/rainbow_dash.cpython-312.pyc,, +pygments/styles/__pycache__/rrt.cpython-312.pyc,, +pygments/styles/__pycache__/sas.cpython-312.pyc,, +pygments/styles/__pycache__/solarized.cpython-312.pyc,, +pygments/styles/__pycache__/staroffice.cpython-312.pyc,, +pygments/styles/__pycache__/stata_dark.cpython-312.pyc,, +pygments/styles/__pycache__/stata_light.cpython-312.pyc,, +pygments/styles/__pycache__/tango.cpython-312.pyc,, +pygments/styles/__pycache__/trac.cpython-312.pyc,, +pygments/styles/__pycache__/vim.cpython-312.pyc,, +pygments/styles/__pycache__/vs.cpython-312.pyc,, +pygments/styles/__pycache__/xcode.cpython-312.pyc,, +pygments/styles/__pycache__/zenburn.cpython-312.pyc,, +pygments/styles/_mapping.py,sha256=MA3yqBy-5JIc9wawxP8y_0GYv7IWRR6OLo-t0oUGETQ,3381 +pygments/styles/abap.py,sha256=T7Ad121Kjz8ZbuphyhulULwXyvXubSS6Czc0MDOFiJ8,752 +pygments/styles/algol.py,sha256=6v6ZXLxPJsm_1qPqOu5ihAuWhVk644NdPXPcZqiOTTI,2265 +pygments/styles/algol_nu.py,sha256=581Lf5db303g7zDb7z-VlvGlFNpbXMIlAnrRBxtjGts,2286 +pygments/styles/arduino.py,sha256=oFF5gjfbQNBigKxFhC7giUIHWl0ieCshhsm9UxCIzqg,4560 +pygments/styles/autumn.py,sha256=P9IX5utjDvdJgevM0kNGwE-wvVysRh1lgMkjO1dhDDE,2198 +pygments/styles/borland.py,sha256=V8qTD8SrS0wLohp2udIirlijbHfPoIlWZkYpqxSdkSw,1614 +pygments/styles/bw.py,sha256=e4Fo6Kyax2aRhqKsjsqvi2CW6lkU9QnjKoPrESZAj-I,1409 +pygments/styles/coffee.py,sha256=0jxdctCEKbR1AqzA59fFQK4sVBdErrRkGCUn6fPF4sg,2311 +pygments/styles/colorful.py,sha256=opkfOcjFTtDn9Fty6ogM7okFMB6bA0iR0VtTdBPE9NE,2835 +pygments/styles/default.py,sha256=WFLDucKJS_ac5Jqutmglbz4ITc4jTTQEOnqLIMpSttA,2591 +pygments/styles/dracula.py,sha256=H-EM1WM3Ixd2OBY9bzoObKl4IzdmhirfDVFbJ9Wsi0Q,2185 +pygments/styles/emacs.py,sha256=iEYWPgQrDQk4RdDf8-g7j4mtoFRzo2xcKvZE1ys9mJU,2538 +pygments/styles/friendly.py,sha256=S43XMczW53tKftmarEL4-nTroPVdN6k8fbNrINzR_QU,2607 +pygments/styles/friendly_grayscale.py,sha256=el2E804DEkKZ6ApXt3N5FTmHAkIhqkJj-omhE1E8mdE,2831 +pygments/styles/fruity.py,sha256=mrNDixp39QIoitRBo-yMOr8tnYLAwGd0EIMw2A6Gd8g,1327 +pygments/styles/gh_dark.py,sha256=yb4EOBAYsQ9g5IGEOqyZ5LKI-MUbwz32l9WB5EcMLaA,3593 +pygments/styles/gruvbox.py,sha256=_QZtRq9y1s3NYADHqek-DXELQqueOnVDXvWJ_1aTGgo,3390 +pygments/styles/igor.py,sha256=QO_M5-Z1xIxVnusEU4LZr4VT--nTERVt-cpfbnOv4yk,740 +pygments/styles/inkpot.py,sha256=bJvNWikqnAWLjx2AH4t_tW4jR0TsrUyVFXFVPAfOgkM,2407 +pygments/styles/lightbulb.py,sha256=CnDv1mF1X5k1msVvRS_diR4tkp06E_jg0tK9cdHEFCQ,3175 +pygments/styles/lilypond.py,sha256=gSCiazPPWfR_9-BV5BYHe6-2gSor4vOHnz3nyFQI2QA,2069 +pygments/styles/lovelace.py,sha256=vZ-S9tS-QUOwfA0RHYBhSTRE3h1ZU-bZnuMW7O6ksyw,3181 +pygments/styles/manni.py,sha256=dpsJC1Zees0e9IcWirqWuSzQxwD0jIbjhFquM23dmWM,2446 +pygments/styles/material.py,sha256=eyyAaJgp1Fnjl4-_D39_l1wH5CW4W0VWScQ3Q0jtAgU,4204 +pygments/styles/monokai.py,sha256=z4V7tQahiGoBXufPOXYAwM4OUsTAHUstpexEAcPAIsI,5187 +pygments/styles/murphy.py,sha256=HsPd80nObb3Ov3-7yJQbnJr3z9mCyz30Pjn_nkWkMYo,2808 +pygments/styles/native.py,sha256=oazEJUbuaHqqOZR5vx-jIhTPIw7dC6QZnKxW-xLr7fs,2046 +pygments/styles/night_owl.py,sha256=bC4BDhbGrRXfYB2D2--8n9kG8xRPSRsddb289jd6T30,4565 +pygments/styles/nord.py,sha256=t7fZj04LUgsLaHpio66FqOGMKb7a2VC3teUlmInPfRg,5394 +pygments/styles/onedark.py,sha256=UXrMzVvA9OVP7OhCQ5gL0CaZrk5jo_I84HJm7LEN5GQ,2126 +pygments/styles/paraiso_dark.py,sha256=rx5_j4gnZRy2j-3hAhFmWpnjnd-Vfz3Z7fcwEXRUGm0,5665 +pygments/styles/paraiso_light.py,sha256=iERjbYRemqgsisv_9TjanBig4bJ_-80xRz5B5puhMc0,5671 +pygments/styles/pastie.py,sha256=mnKebFiJ2do9A_wTPq4tKtgw-TQqpb0lP3kNbemQ2to,2528 +pygments/styles/perldoc.py,sha256=-e1T4QBEQNE_l17RYW-WBowNprg2uL_hFjhSDcaMiDM,2233 +pygments/styles/rainbow_dash.py,sha256=YP2HPVXJLmOy8Yz8p8u5GbkAyuKxLlNmu6ITZBMa1Mc,2393 +pygments/styles/rrt.py,sha256=vs4pnWwmMIQR0eGczp06AYazsYiR0KFcRiRUzSf3rXc,1295 +pygments/styles/sas.py,sha256=ER-JjZgU2wEJWk5K06iHAFPjVYD1iMkvjjE0rlNOt2Y,1443 +pygments/styles/solarized.py,sha256=VdtLYhQ7xDj_iTHP_Ekr6rAdMcE3fRSrglngVSal63M,4250 +pygments/styles/staroffice.py,sha256=peExkIBqPkRhqXFpW99n49t6pMwehI_pDYVUmQwkgdA,834 +pygments/styles/stata_dark.py,sha256=N6imWykqHoT5drOn-sVRUzt1AZMKG3HHU-Q7LKz2d50,1260 +pygments/styles/stata_light.py,sha256=YW7ih4teXoEuUHImOK2rGSCVxfnj43tlcKPXUsrDkRg,1292 +pygments/styles/tango.py,sha256=Af0WVTxpH_cUdHr_ua69JDijTLI5aG1RmBTF7o2KTgk,7140 +pygments/styles/trac.py,sha256=-h5iU-LjSmt-dQ7y5jXwJ5LQ9ABR5QD5RlPRjhnzmv8,1984 +pygments/styles/vim.py,sha256=dWqCVC2YT45dLSpMTwLBPkKYgRsT1-cFf7ZHoc2PQpA,2022 +pygments/styles/vs.py,sha256=7HJehhtiHE5nibjC3r3X-aYHBm5BccL33LgO_4anEiU,1133 +pygments/styles/xcode.py,sha256=HmB6aPkxvmo4za5DijhLb5AXSyv6UbWnwOUoRUNBaZA,1507 +pygments/styles/zenburn.py,sha256=Ax7iBbMzvVQNTpT3YdMwCEkL-nIXnpr60aVrR4Lpa6o,2206 +pygments/token.py,sha256=DVil5T2ltHkTgQTUYy1dMtgyigjavCs1ypE4Qf2CrGo,6229 +pygments/unistring.py,sha256=Z4w4HfOVUhueCURRkfhAqQ2b-69UzkhY4xuHevYEy5g,63211 +pygments/util.py,sha256=N0MugoJ5puAxxVeGWqHaorJC9HcHkvRUiahTbcWS48U,10770 diff --git a/.venv/lib/python3.12/site-packages/pygments-2.21.0.dist-info/WHEEL b/.venv/lib/python3.12/site-packages/pygments-2.21.0.dist-info/WHEEL new file mode 100644 index 0000000000000000000000000000000000000000..51abe1f5e66cc9d07fda22a3bbe1f89475795969 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/pygments-2.21.0.dist-info/WHEEL @@ -0,0 +1,4 @@ +Wheel-Version: 1.0 +Generator: hatchling 1.32.0 +Root-Is-Purelib: true +Tag: py3-none-any diff --git a/.venv/lib/python3.12/site-packages/pygments-2.21.0.dist-info/entry_points.txt b/.venv/lib/python3.12/site-packages/pygments-2.21.0.dist-info/entry_points.txt new file mode 100644 index 0000000000000000000000000000000000000000..15498e35f53320bd5e1de176928daabf26be0109 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/pygments-2.21.0.dist-info/entry_points.txt @@ -0,0 +1,2 @@ +[console_scripts] +pygmentize = pygments.cmdline:main diff --git a/.venv/lib/python3.12/site-packages/pygments-2.21.0.dist-info/licenses/AUTHORS b/.venv/lib/python3.12/site-packages/pygments-2.21.0.dist-info/licenses/AUTHORS new file mode 100644 index 0000000000000000000000000000000000000000..4794e296f491b1f4b59244eaff5251c07e01a817 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/pygments-2.21.0.dist-info/licenses/AUTHORS @@ -0,0 +1,296 @@ +Pygments is written and maintained by Georg Brandl . + +Major developers are Tim Hatch and Armin Ronacher +. + +Other contributors, listed alphabetically, are: + +* Sam Aaron -- Ioke lexer +* Jean Abou Samra -- LilyPond lexer +* João Abecasis -- JSLT lexer +* Ali Afshar -- image formatter +* Thomas Aglassinger -- Easytrieve, JCL, Rexx, Transact-SQL and VBScript + lexers +* Maxence Ahlouche -- PostgreSQL Explain lexer +* Muthiah Annamalai -- Ezhil lexer +* Nikolay Antipov -- OpenSCAD lexer +* Kumar Appaiah -- Debian control lexer +* Andreas Amann -- AppleScript lexer +* Timothy Armstrong -- Dart lexer fixes +* Jeffrey Arnold -- R/S, Rd, BUGS, Jags, and Stan lexers +* Eiríkr Åsheim -- Uxntal lexer +* Jeremy Ashkenas -- CoffeeScript lexer +* José Joaquín Atria -- Praat lexer +* Stefan Matthias Aust -- Smalltalk lexer +* Lucas Bajolet -- Nit lexer +* Ben Bangert -- Mako lexers +* Max Battcher -- Darcs patch lexer +* Thomas Baruchel -- APL lexer +* Tim Baumann -- (Literate) Agda lexer +* Paul Baumgart, 280 North, Inc. -- Objective-J lexer +* Michael Bayer -- Myghty lexers +* Thomas Beale -- Archetype lexers +* John Benediktsson -- Factor lexer +* David Benjamin, Google LLC -- TLS lexer +* Trevor Bergeron -- mIRC formatter +* Vincent Bernat -- LessCSS lexer +* Christopher Bertels -- Fancy lexer +* Sébastien Bigaret -- QVT Operational lexer +* Jarrett Billingsley -- MiniD lexer +* Adam Blinkinsop -- Haskell, Redcode lexers +* Stéphane Blondon -- Procfile, SGF and Sieve lexers +* Frits van Bommel -- assembler lexers +* Pierre Bourdon -- bugfixes +* Martijn Braam -- Kernel log lexer, BARE lexer +* JD Browne, Google LLC -- GoogleSQL lexer +* Matthias Bussonnier -- ANSI style handling for terminal-256 formatter +* chebee7i -- Python traceback lexer improvements +* Hiram Chirino -- Scaml and Jade lexers +* Mauricio Caceres -- SAS and Stata lexers. +* Michael Camilleri, John Gabriele, sogaiu -- Janet lexer +* Daren Chandisingh -- Gleam lexer +* Ian Cooper -- VGL lexer +* David Corbett -- Inform, Jasmin, JSGF, Snowball, and TADS 3 lexers +* Leaf Corcoran -- MoonScript lexer +* Fraser Cormack -- TableGen lexer +* Gabriel Corona -- ASN.1 lexer +* Radu Costache -- Boogie and Civl Verifier lexer improvements +* Christopher Creutzig -- MuPAD lexer +* Daniël W. Crompton -- Pike lexer +* Pete Curry -- bugfixes +* Bryan Davis -- EBNF lexer +* Bruno Deferrari -- Shen lexer +* Walter Dörwald -- UL4 lexer +* Luke Drummond -- Meson lexer +* Giedrius Dubinskas -- HTML formatter improvements +* Owen Durni -- Haxe lexer +* Alexander Dutton, Oxford University Computing Services -- SPARQL lexer +* James Edwards -- Terraform lexer +* Nick Efford -- Python 3 lexer +* Sven Efftinge -- Xtend lexer +* Artem Egorkine -- terminal256 formatter +* Matthew Fernandez -- CAmkES lexer +* Paweł Fertyk -- GDScript lexer, HTML formatter improvements +* Michael Ficarra -- CPSA lexer +* James H. Fisher -- PostScript lexer +* Amanda Fitch, Google LLC -- GoogleSQL lexer +* William S. Fulton -- SWIG lexer +* Carlos Galdino -- Elixir and Elixir Console lexers +* Michael Galloy -- IDL lexer +* Naveen Garg -- Autohotkey lexer +* Simon Garnotel -- FreeFem++ lexer +* Laurent Gautier -- R/S lexer +* Alex Gaynor -- PyPy log lexer +* Richard Gerkin -- Igor Pro lexer +* Alain Gilbert -- TypeScript lexer +* Alex Gilding -- BlitzBasic lexer +* GitHub, Inc -- DASM16, Augeas, TOML, and Slash lexers +* Bertrand Goetzmann -- Groovy lexer +* Krzysiek Goj -- Scala lexer +* Rostyslav Golda -- FloScript lexer +* Andrey Golovizin -- BibTeX lexers +* Matt Good -- Genshi, Cheetah lexers +* Michał Górny -- vim modeline support +* Alex Gosse -- TrafficScript lexer +* Patrick Gotthardt -- PHP namespaces support +* Hubert Gruniaux -- C and C++ lexer improvements +* Olivier Guibe -- Asymptote lexer +* Armin Günther -- Go lexer improvements +* Phil Hagelberg -- Fennel lexer +* Florian Hahn -- Boogie lexer +* Martin Harriman -- SNOBOL lexer +* Matthew Harrison -- SVG formatter +* Steven Hazel -- Tcl lexer +* Dan Michael Heggø -- Turtle lexer +* Aslak Hellesøy -- Gherkin lexer +* Greg Hendershott -- Racket lexer +* Justin Hendrick -- ParaSail lexer +* Jordi Gutiérrez Hermoso -- Octave lexer +* David Hess, Fish Software, Inc. -- Objective-J lexer +* Ken Hilton -- Typographic Number Theory and Arrow lexers +* Varun Hiremath -- Debian control lexer +* Rob Hoelz -- Perl 6 lexer +* Doug Hogan -- Mscgen lexer +* Ben Hollis -- Mason lexer +* Max Horn -- GAP lexer +* Fred Hornsey -- OMG IDL Lexer +* Alastair Houghton -- Lexer inheritance facility +* Tim Howard -- BlitzMax lexer +* Dustin Howett -- Logos lexer +* Ivan Inozemtsev -- Fantom lexer +* Hiroaki Itoh -- Shell console rewrite, Lexers for PowerShell session, + MSDOS session, BC, WDiff +* Brian R. Jackson -- Tea lexer +* Alex Jeffery, ChromaWay AB -- Rell lexer +* Christian Jann -- ShellSession lexer +* Jonas Camillus Jeppesen -- Line numbers and line highlighting for + RTF-formatter +* Dennis Kaarsemaker -- sources.list lexer +* Dmitri Kabak -- Inferno Limbo lexer +* Igor Kalnitsky -- vhdl lexer +* Colin Kennedy - USD lexer +* Alexander Kit -- MaskJS lexer +* Pekka Klärck -- Robot Framework lexer +* Gerwin Klein -- Isabelle lexer +* Eric Knibbe -- Lasso lexer +* Stepan Koltsov -- Clay lexer +* Oliver Kopp - Friendly grayscale style +* Adam Koprowski -- Opa lexer +* Benjamin Kowarsch -- Modula-2 lexer +* Domen Kožar -- Nix lexer +* Oleh Krekel -- Emacs Lisp lexer +* Alexander Kriegisch -- Kconfig and AspectJ lexers +* Marek Kubica -- Scheme lexer +* Jochen Kupperschmidt -- Markdown processor +* Gerd Kurzbach -- Modelica lexer +* Jon Larimer, Google Inc. -- Smali lexer +* Olov Lassus -- Dart lexer +* Matt Layman -- TAP lexer +* Dan Lazin, Google LLC -- GoogleSQL lexer +* Kristian Lyngstøl -- Varnish lexers +* Sylvestre Ledru -- Scilab lexer +* Chee Sing Lee -- Flatline lexer +* Mark Lee -- Vala lexer +* Thomas Linder Puls -- Visual Prolog lexer +* Pete Lomax -- Phix lexer +* Valentin Lorentz -- C++ lexer improvements +* Ben Mabey -- Gherkin lexer +* Angus MacArthur -- QML lexer +* Louis Mandel -- X10 lexer +* Louis Marchand -- Eiffel lexer +* Simone Margaritelli -- Hybris lexer +* Tim Martin - World of Warcraft TOC lexer +* Kirk McDonald -- D lexer +* Gordon McGregor -- SystemVerilog lexer +* Stephen McKamey -- Duel/JBST lexer +* Brian McKenna -- F# lexer +* Charles McLaughlin -- Puppet lexer +* Kurt McKee -- Tera Term macro lexer, PostgreSQL updates, MySQL overhaul, JSON lexer +* Joe Eli McIlvain -- Savi lexer +* Lukas Meuser -- BBCode formatter, Lua lexer +* Bruno Mesquita -- Night Owl style +* Cat Miller -- Pig lexer +* Paul Miller -- LiveScript lexer +* Hong Minhee -- HTTP lexer +* Michael Mior -- Awk lexer +* Bruce Mitchener -- Dylan lexer rewrite +* Reuben Morais -- SourcePawn lexer +* Jon Morton -- Rust lexer +* Paulo Moura -- Logtalk lexer +* Mher Movsisyan -- DTD lexer +* Dejan Muhamedagic -- Crmsh lexer +* Adrien Nayrat -- PostgreSQL Explain lexer +* Ana Nelson -- Ragel, ANTLR, R console lexers +* David Neto, Google LLC -- WebGPU Shading Language lexer +* Kurt Neufeld -- Markdown lexer +* Nam T. Nguyen -- Monokai style +* Jesper Noehr -- HTML formatter "anchorlinenos" +* Mike Nolta -- Julia lexer +* Avery Nortonsmith -- Pointless lexer +* Jonas Obrist -- BBCode lexer +* Edward O'Callaghan -- Cryptol lexer +* David Oliva -- Rebol lexer +* Pat Pannuto -- nesC lexer +* Jon Parise -- Protocol buffers and Thrift lexers +* Benjamin Peterson -- Test suite refactoring +* Ronny Pfannschmidt -- BBCode lexer +* Dominik Picheta -- Nimrod lexer +* Andrew Pinkham -- RTF Formatter Refactoring +* Clément Prévost -- UrbiScript lexer +* Tanner Prynn -- cmdline -x option and loading lexers from files +* Oleh Prypin -- Crystal lexer (based on Ruby lexer) +* Nick Psaris -- K and Q lexers +* Xidorn Quan -- Web IDL lexer +* Elias Rabel -- Fortran fixed form lexer +* raichoo -- Idris lexer +* Daniel Ramirez -- GDScript lexer +* Kashif Rasul -- CUDA lexer +* Nathan Reed -- HLSL lexer +* Justin Reidy -- MXML lexer +* Jonathon Reinhart, Google LLC -- Soong lexer +* Norman Richards -- JSON lexer +* Corey Richardson -- Rust lexer updates +* Fabrizio Riguzzi -- cplint leder +* Lubomir Rintel -- GoodData MAQL and CL lexers +* Andre Roberge -- Tango style +* Georg Rollinger -- HSAIL lexer +* Michiel Roos -- TypoScript lexer +* Konrad Rudolph -- LaTeX formatter enhancements +* Mario Ruggier -- Evoque lexers +* Miikka Salminen -- Lovelace style, Hexdump lexer, lexer enhancements +* Stou Sandalski -- NumPy, FORTRAN, tcsh and XSLT lexers +* Matteo Sasso -- Common Lisp lexer +* Joe Schafer -- Ada lexer +* Max Schillinger -- TiddlyWiki5 lexer +* Andrew Schmidt -- X++ lexer +* Ken Schutte -- Matlab lexers +* René Schwaiger -- Rainbow Dash style +* Sebastian Schweizer -- Whiley lexer +* Tassilo Schweyer -- Io, MOOCode lexers +* Pablo Seminario -- PromQL lexer +* Ted Shaw -- AutoIt lexer +* Joerg Sieker -- ABAP lexer +* Robert Simmons -- Standard ML lexer +* Kirill Simonov -- YAML lexer +* Corbin Simpson -- Monte lexer +* Ville Skyttä -- ASCII armored lexer +* Alexander Smishlajev -- Visual FoxPro lexer +* Steve Spigarelli -- XQuery lexer +* Jerome St-Louis -- eC lexer +* Camil Staps -- Clean and NuSMV lexers; Solarized style +* James Strachan -- Kotlin lexer +* Tom Stuart -- Treetop lexer +* Colin Sullivan -- SuperCollider lexer +* Ben Swift -- Extempore lexer +* tatt61880 -- Kuin lexer +* Edoardo Tenani -- Arduino lexer +* Tiberius Teng -- default style overhaul +* Jeremy Thurgood -- Erlang, Squid config lexers +* Brian Tiffin -- OpenCOBOL lexer +* Bob Tolbert -- Hy lexer +* Doug Torrance -- Macaulay2 lexer +* Matthias Trute -- Forth lexer +* Tuoa Spi T4 -- Bdd lexer +* Erick Tryzelaar -- Felix lexer +* Alexander Udalov -- Kotlin lexer improvements +* Thomas Van Doren -- Chapel lexer +* Dave Van Ee -- Uxntal lexer updates +* Daniele Varrazzo -- PostgreSQL lexers +* Abe Voelker -- OpenEdge ABL lexer +* Pepijn de Vos -- HTML formatter CTags support +* Matthias Vallentin -- Bro lexer +* Benoît Vinot -- AMPL lexer +* Linh Vu Hong -- RSL lexer +* Taavi Väänänen -- Debian control, PHP lexers +* Immanuel Washington -- Smithy lexer +* Nathan Weizenbaum -- Haml and Sass lexers +* Nathan Whetsell -- Csound lexers +* Dietmar Winkler -- Modelica lexer +* Nils Winter -- Smalltalk lexer +* Trevor Woerner -- BitBake lexer +* Davy Wybiral -- Clojure lexer +* Whitney Young -- ObjectiveC lexer +* Diego Zamboni -- CFengine3 lexer +* Enrique Zamudio -- Ceylon lexer +* Alex Zimin -- Nemerle lexer +* Rob Zimmerman -- Kal lexer +* Evgenii Zheltonozhskii -- Maple lexer +* Vincent Zurczak -- Roboconf lexer +* Hubert Gruniaux -- C and C++ lexer improvements +* Thomas Symalla -- AMDGPU Lexer +* 15b3 -- Image Formatter improvements +* Fabian Neumann -- CDDL lexer +* Thomas Duboucher -- CDDL lexer +* Philipp Imhof -- Pango Markup formatter +* Thomas Voss -- Sed lexer +* Martin Fischer -- WCAG contrast testing +* Marc Auberer -- Spice lexer +* Amr Hesham -- Carbon lexer +* diskdance -- Wikitext lexer +* vanillajonathan -- PRQL lexer +* Nikolay Antipov -- OpenSCAD lexer +* Markus Meyer, Nextron Systems -- YARA lexer +* Hannes Römer -- Mojo lexer +* Jan Frederik Schaefer -- PDDL lexer + +Many thanks for all contributions! diff --git a/.venv/lib/python3.12/site-packages/pygments-2.21.0.dist-info/licenses/LICENSE b/.venv/lib/python3.12/site-packages/pygments-2.21.0.dist-info/licenses/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..446a1a805c8a949579fb8a9799f2bec7777349dc --- /dev/null +++ b/.venv/lib/python3.12/site-packages/pygments-2.21.0.dist-info/licenses/LICENSE @@ -0,0 +1,25 @@ +Copyright (c) 2006-2022 by the respective authors (see AUTHORS file). +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. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/.venv/lib/python3.12/site-packages/pygments/scanner.py b/.venv/lib/python3.12/site-packages/pygments/scanner.py new file mode 100644 index 0000000000000000000000000000000000000000..067ebfa9c65a9ea3b3ac3e1d4cf815eee2f1f32b --- /dev/null +++ b/.venv/lib/python3.12/site-packages/pygments/scanner.py @@ -0,0 +1,104 @@ +""" + pygments.scanner + ~~~~~~~~~~~~~~~~ + + This library implements a regex based scanner. Some languages + like Pascal are easy to parse but have some keywords that + depend on the context. Because of this it's impossible to lex + that just by using a regular expression lexer like the + `RegexLexer`. + + Have a look at the `DelphiLexer` to get an idea of how to use + this scanner. + + :copyright: Copyright 2006-present by the Pygments team, see AUTHORS. + :license: BSD, see LICENSE for details. +""" +import re + + +class EndOfText(RuntimeError): + """ + Raise if end of text is reached and the user + tried to call a match function. + """ + + +class Scanner: + """ + Simple scanner + + All method patterns are regular expression strings (not + compiled expressions!) + """ + + def __init__(self, text, flags=0): + """ + :param text: The text which should be scanned + :param flags: default regular expression flags + """ + self.data = text + self.data_length = len(text) + self.start_pos = 0 + self.pos = 0 + self.flags = flags + self.last = None + self.match = None + self._re_cache = {} + + def eos(self): + """`True` if the scanner reached the end of text.""" + return self.pos >= self.data_length + eos = property(eos, eos.__doc__) + + def check(self, pattern): + """ + Apply `pattern` on the current position and return + the match object. (Doesn't touch pos). Use this for + lookahead. + """ + if self.eos: + raise EndOfText() + if pattern not in self._re_cache: + self._re_cache[pattern] = re.compile(pattern, self.flags) + return self._re_cache[pattern].match(self.data, self.pos) + + def test(self, pattern): + """Apply a pattern on the current position and check + if it patches. Doesn't touch pos. + """ + return self.check(pattern) is not None + + def scan(self, pattern): + """ + Scan the text for the given pattern and update pos/match + and related fields. The return value is a boolean that + indicates if the pattern matched. The matched value is + stored on the instance as ``match``, the last value is + stored as ``last``. ``start_pos`` is the position of the + pointer before the pattern was matched, ``pos`` is the + end position. + """ + if self.eos: + raise EndOfText() + if pattern not in self._re_cache: + self._re_cache[pattern] = re.compile(pattern, self.flags) + self.last = self.match + m = self._re_cache[pattern].match(self.data, self.pos) + if m is None: + return False + self.start_pos = m.start() + self.pos = m.end() + self.match = m.group() + return True + + def get_char(self): + """Scan exactly one char.""" + self.scan('.') + + def __repr__(self): + return '<%s %d/%d>' % ( + self.__class__.__name__, + self.pos, + self.data_length + ) diff --git a/.venv/lib/python3.12/site-packages/pygments/sphinxext.py b/.venv/lib/python3.12/site-packages/pygments/sphinxext.py new file mode 100644 index 0000000000000000000000000000000000000000..5c03e4c64419af844b0ab0cf9645b5769accb2f8 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/pygments/sphinxext.py @@ -0,0 +1,247 @@ +""" + pygments.sphinxext + ~~~~~~~~~~~~~~~~~~ + + Sphinx extension to generate automatic documentation of lexers, + formatters and filters. + + :copyright: Copyright 2006-present by the Pygments team, see AUTHORS. + :license: BSD, see LICENSE for details. +""" + +import sys + +from docutils import nodes +from docutils.statemachine import ViewList +from docutils.parsers.rst import Directive +from sphinx.util.nodes import nested_parse_with_titles + + +MODULEDOC = ''' +.. module:: %s + +%s +%s +''' + +LEXERDOC = ''' +.. class:: %s + + :Short names: %s + :Filenames: %s + :MIME types: %s + + %s + + %s + +''' + +FMTERDOC = ''' +.. class:: %s + + :Short names: %s + :Filenames: %s + + %s + +''' + +FILTERDOC = ''' +.. class:: %s + + :Name: %s + + %s + +''' + + +class PygmentsDoc(Directive): + """ + A directive to collect all lexers/formatters/filters and generate + autoclass directives for them. + """ + has_content = False + required_arguments = 1 + optional_arguments = 0 + final_argument_whitespace = False + option_spec = {} + + def run(self): + self.filenames = set() + if self.arguments[0] == 'lexers': + out = self.document_lexers() + elif self.arguments[0] == 'formatters': + out = self.document_formatters() + elif self.arguments[0] == 'filters': + out = self.document_filters() + elif self.arguments[0] == 'lexers_overview': + out = self.document_lexers_overview() + else: + raise Exception('invalid argument for "pygmentsdoc" directive') + node = nodes.compound() + vl = ViewList(out.split('\n'), source='') + nested_parse_with_titles(self.state, vl, node) + for fn in self.filenames: + self.state.document.settings.record_dependencies.add(fn) + return node.children + + def document_lexers_overview(self): + """Generate a tabular overview of all lexers. + + The columns are the lexer name, the extensions handled by this lexer + (or "None"), the aliases and a link to the lexer class.""" + from pygments.lexers._mapping import LEXERS + import pygments.lexers + out = [] + + table = [] + + def format_link(name, url): + if url: + return f'`{name} <{url}>`_' + return name + + for classname, data in sorted(LEXERS.items(), key=lambda x: x[1][1].lower()): + lexer_cls = pygments.lexers.find_lexer_class(data[1]) + extensions = lexer_cls.filenames + lexer_cls.alias_filenames + + table.append({ + 'name': format_link(data[1], lexer_cls.url), + 'extensions': ', '.join(extensions).replace('*', '\\*').replace('_', '\\') or 'None', + 'aliases': ', '.join(data[2]), + 'class': f'{data[0]}.{classname}' + }) + + column_names = ['name', 'extensions', 'aliases', 'class'] + column_lengths = [max([len(row[column]) for row in table if row[column]]) + for column in column_names] + + def write_row(*columns): + """Format a table row""" + out = [] + for length, col in zip(column_lengths, columns): + if col: + out.append(col.ljust(length)) + else: + out.append(' '*length) + + return ' '.join(out) + + def write_seperator(): + """Write a table separator row""" + sep = ['='*c for c in column_lengths] + return write_row(*sep) + + out.append(write_seperator()) + out.append(write_row('Name', 'Extension(s)', 'Short name(s)', 'Lexer class')) + out.append(write_seperator()) + for row in table: + out.append(write_row( + row['name'], + row['extensions'], + row['aliases'], + f':class:`~{row["class"]}`')) + out.append(write_seperator()) + + return '\n'.join(out) + + def document_lexers(self): + from pygments.lexers._mapping import LEXERS + import pygments + import inspect + import pathlib + + out = [] + modules = {} + moduledocstrings = {} + for classname, data in sorted(LEXERS.items(), key=lambda x: x[0]): + module = data[0] + mod = __import__(module, None, None, [classname]) + self.filenames.add(mod.__file__) + cls = getattr(mod, classname) + if not cls.__doc__: + print(f"Warning: {classname} does not have a docstring.") + docstring = cls.__doc__ + if isinstance(docstring, bytes): + docstring = docstring.decode('utf8') + + example_file = getattr(cls, '_example', None) + if example_file: + p = pathlib.Path(inspect.getabsfile(pygments)).parent.parent /\ + 'tests' / 'examplefiles' / example_file + content = p.read_text(encoding='utf-8') + if not content: + raise Exception( + f"Empty example file '{example_file}' for lexer " + f"{classname}") + + if data[2]: + lexer_name = data[2][0] + docstring += '\n\n .. admonition:: Example\n' + docstring += f'\n .. code-block:: {lexer_name}\n\n' + for line in content.splitlines(): + docstring += f' {line}\n' + + if cls.version_added: + version_line = f'.. versionadded:: {cls.version_added}' + else: + version_line = '' + + modules.setdefault(module, []).append(( + classname, + ', '.join(data[2]) or 'None', + ', '.join(data[3]).replace('*', '\\*').replace('_', '\\') or 'None', + ', '.join(data[4]) or 'None', + docstring, + version_line)) + if module not in moduledocstrings: + moddoc = mod.__doc__ + if isinstance(moddoc, bytes): + moddoc = moddoc.decode('utf8') + moduledocstrings[module] = moddoc + + for module, lexers in sorted(modules.items(), key=lambda x: x[0]): + if moduledocstrings[module] is None: + raise Exception(f"Missing docstring for {module}") + heading = moduledocstrings[module].splitlines()[4].strip().rstrip('.') + out.append(MODULEDOC % (module, heading, '-'*len(heading))) + for data in lexers: + out.append(LEXERDOC % data) + + return ''.join(out) + + def document_formatters(self): + from pygments.formatters import FORMATTERS + + out = [] + for classname, data in sorted(FORMATTERS.items(), key=lambda x: x[0]): + module = data[0] + mod = __import__(module, None, None, [classname]) + self.filenames.add(mod.__file__) + cls = getattr(mod, classname) + docstring = cls.__doc__ + if isinstance(docstring, bytes): + docstring = docstring.decode('utf8') + heading = cls.__name__ + out.append(FMTERDOC % (heading, ', '.join(data[2]) or 'None', + ', '.join(data[3]).replace('*', '\\*') or 'None', + docstring)) + return ''.join(out) + + def document_filters(self): + from pygments.filters import FILTERS + + out = [] + for name, cls in FILTERS.items(): + self.filenames.add(sys.modules[cls.__module__].__file__) + docstring = cls.__doc__ + if isinstance(docstring, bytes): + docstring = docstring.decode('utf8') + out.append(FILTERDOC % (cls.__name__, name, docstring)) + return ''.join(out) + + +def setup(app): + app.add_directive('pygmentsdoc', PygmentsDoc) diff --git a/.venv/lib/python3.12/site-packages/pygments/style.py b/.venv/lib/python3.12/site-packages/pygments/style.py new file mode 100644 index 0000000000000000000000000000000000000000..c766fd05e33d6fd32b99baa0a41ec18a01e03d89 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/pygments/style.py @@ -0,0 +1,205 @@ +""" + pygments.style + ~~~~~~~~~~~~~~ + + Basic style object. + + :copyright: Copyright 2006-present by the Pygments team, see AUTHORS. + :license: BSD, see LICENSE for details. +""" + +from pygments.token import Token, STANDARD_TYPES + +# Default mapping of ansixxx to RGB colors. +_ansimap = { + # dark + 'ansiblack': '000000', + 'ansired': '7f0000', + 'ansigreen': '007f00', + 'ansiyellow': '7f7fe0', + 'ansiblue': '00007f', + 'ansimagenta': '7f007f', + 'ansicyan': '007f7f', + 'ansigray': 'e5e5e5', + # normal + 'ansibrightblack': '555555', + 'ansibrightred': 'ff0000', + 'ansibrightgreen': '00ff00', + 'ansibrightyellow': 'ffff00', + 'ansibrightblue': '0000ff', + 'ansibrightmagenta': 'ff00ff', + 'ansibrightcyan': '00ffff', + 'ansiwhite': 'ffffff', +} +# mapping of deprecated #ansixxx colors to new color names +_deprecated_ansicolors = { + # dark + '#ansiblack': 'ansiblack', + '#ansidarkred': 'ansired', + '#ansidarkgreen': 'ansigreen', + '#ansibrown': 'ansiyellow', + '#ansidarkblue': 'ansiblue', + '#ansipurple': 'ansimagenta', + '#ansiteal': 'ansicyan', + '#ansilightgray': 'ansigray', + # normal + '#ansidarkgray': 'ansibrightblack', + '#ansired': 'ansibrightred', + '#ansigreen': 'ansibrightgreen', + '#ansiyellow': 'ansibrightyellow', + '#ansiblue': 'ansibrightblue', + '#ansifuchsia': 'ansibrightmagenta', + '#ansiturquoise': 'ansibrightcyan', + '#ansiwhite': 'ansiwhite', +} +ansicolors = set(_ansimap) + + +class StyleMeta(type): + + def __new__(mcs, name, bases, dct): + obj = type.__new__(mcs, name, bases, dct) + for token in STANDARD_TYPES: + if token not in obj.styles: + obj.styles[token] = '' + + def colorformat(text): + if text in ansicolors: + return text + if text[0:1] == '#': + col = text[1:] + if len(col) == 6: + return col + elif len(col) == 3: + return col[0] * 2 + col[1] * 2 + col[2] * 2 + elif text == '': + return '' + elif text == 'transparent': + return text + elif text.startswith('var') or text.startswith('calc'): + return text + assert False, f"wrong color format {text!r}" + + _styles = obj._styles = {} + + for ttype in obj.styles: + for token in ttype.split(): + if token in _styles: + continue + ndef = _styles.get(token.parent, None) + styledefs = obj.styles.get(token, '').split() + if not ndef or token is None: + ndef = ['', 0, 0, 0, '', '', 0, 0, 0] + elif 'noinherit' in styledefs and token is not Token: + ndef = _styles[Token][:] + else: + ndef = ndef[:] + _styles[token] = ndef + for styledef in obj.styles.get(token, '').split(): + if styledef == 'noinherit': + pass + elif styledef == 'bold': + ndef[1] = 1 + elif styledef == 'nobold': + ndef[1] = 0 + elif styledef == 'italic': + ndef[2] = 1 + elif styledef == 'noitalic': + ndef[2] = 0 + elif styledef == 'underline': + ndef[3] = 1 + elif styledef == 'nounderline': + ndef[3] = 0 + elif styledef[:3] == 'bg:': + ndef[4] = colorformat(styledef[3:]) + elif styledef[:7] == 'border:': + ndef[5] = colorformat(styledef[7:]) + elif styledef == 'roman': + ndef[6] = 1 + elif styledef == 'sans': + ndef[7] = 1 + elif styledef == 'mono': + ndef[8] = 1 + else: + ndef[0] = colorformat(styledef) + + return obj + + def style_for_token(cls, token): + t = cls._styles[token] + ansicolor = bgansicolor = None + color = t[0] + if color in _deprecated_ansicolors: + color = _deprecated_ansicolors[color] + if color in ansicolors: + ansicolor = color + color = _ansimap[color] + bgcolor = t[4] + if bgcolor in _deprecated_ansicolors: + bgcolor = _deprecated_ansicolors[bgcolor] + if bgcolor in ansicolors: + bgansicolor = bgcolor + bgcolor = _ansimap[bgcolor] + + return { + 'color': color or None, + 'bold': bool(t[1]), + 'italic': bool(t[2]), + 'underline': bool(t[3]), + 'bgcolor': bgcolor or None, + 'border': t[5] or None, + 'roman': bool(t[6]) or None, + 'sans': bool(t[7]) or None, + 'mono': bool(t[8]) or None, + 'ansicolor': ansicolor, + 'bgansicolor': bgansicolor, + } + + def list_styles(cls): + return list(cls) + + def styles_token(cls, ttype): + return ttype in cls._styles + + def __iter__(cls): + for token in cls._styles: + yield token, cls.style_for_token(token) + + def __len__(cls): + return len(cls._styles) + + +class Style(metaclass=StyleMeta): + + #: overall background color (``None`` means transparent) + background_color = '#ffffff' + + #: highlight background color + highlight_color = '#ffffcc' + + #: line number font color + line_number_color = 'inherit' + + #: line number background color + line_number_background_color = 'transparent' + + #: special line number font color + line_number_special_color = '#000000' + + #: special line number background color + line_number_special_background_color = '#ffffc0' + + #: Style definitions for individual token types. + styles = {} + + #: user-friendly style name (used when selecting the style, so this + # should be all-lowercase, no spaces, hyphens) + name = 'unnamed' + + aliases = [] + + # Attribute for lexers defined within Pygments. If set + # to True, the style is not shown in the style gallery + # on the website. This is intended for language-specific + # styles. + web_style_gallery_exclude = False diff --git a/.venv/lib/python3.12/site-packages/pygments/styles/__init__.py b/.venv/lib/python3.12/site-packages/pygments/styles/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..58d1d77756782cf4a31da742a612178600639ee9 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/pygments/styles/__init__.py @@ -0,0 +1,61 @@ +""" + pygments.styles + ~~~~~~~~~~~~~~~ + + Contains built-in styles. + + :copyright: Copyright 2006-present by the Pygments team, see AUTHORS. + :license: BSD, see LICENSE for details. +""" + +from pygments.plugin import find_plugin_styles +from pygments.util import ClassNotFound +from pygments.styles._mapping import STYLES + +#: A dictionary of built-in styles, mapping style names to +#: ``'submodule::classname'`` strings. +#: This list is deprecated. Use `pygments.styles.STYLES` instead +STYLE_MAP = {v[1]: v[0].split('.')[-1] + '::' + k for k, v in STYLES.items()} + +#: Internal reverse mapping to make `get_style_by_name` more efficient +_STYLE_NAME_TO_MODULE_MAP = {v[1]: (v[0], k) for k, v in STYLES.items()} + + +def get_style_by_name(name): + """ + Return a style class by its short name. The names of the builtin styles + are listed in :data:`pygments.styles.STYLE_MAP`. + + Will raise :exc:`pygments.util.ClassNotFound` if no style of that name is + found. + """ + if name in _STYLE_NAME_TO_MODULE_MAP: + mod, cls = _STYLE_NAME_TO_MODULE_MAP[name] + builtin = "yes" + else: + for found_name, style in find_plugin_styles(): + if name == found_name: + return style + # perhaps it got dropped into our styles package + builtin = "" + mod = 'pygments.styles.' + name + cls = name.title() + "Style" + + try: + mod = __import__(mod, None, None, [cls]) + except ImportError: + raise ClassNotFound(f"Could not find style module {mod!r}" + + (builtin and ", though it should be builtin") + + ".") + try: + return getattr(mod, cls) + except AttributeError: + raise ClassNotFound(f"Could not find style class {cls!r} in style module.") + + +def get_all_styles(): + """Return a generator for all styles by name, both builtin and plugin.""" + for v in STYLES.values(): + yield v[1] + for name, _ in find_plugin_styles(): + yield name diff --git a/.venv/lib/python3.12/site-packages/pygments/styles/__pycache__/__init__.cpython-312.pyc b/.venv/lib/python3.12/site-packages/pygments/styles/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..959f414572d29242a0d9939dc4e1945243498cb7 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/pygments/styles/__pycache__/__init__.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/pygments/styles/__pycache__/_mapping.cpython-312.pyc b/.venv/lib/python3.12/site-packages/pygments/styles/__pycache__/_mapping.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3675aadee89bc51aaff612c11823a3a6377ef5f9 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/pygments/styles/__pycache__/_mapping.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/pygments/styles/_mapping.py b/.venv/lib/python3.12/site-packages/pygments/styles/_mapping.py new file mode 100644 index 0000000000000000000000000000000000000000..5a6edc4bd739a3dcab64ea538df34bbd7ae0da95 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/pygments/styles/_mapping.py @@ -0,0 +1,55 @@ +# Automatically generated by scripts/gen_mapfiles.py. +# DO NOT EDIT BY HAND; run `tox -e mapfiles` instead. + +STYLES = { + 'AbapStyle': ('pygments.styles.abap', 'abap', ()), + 'AlgolStyle': ('pygments.styles.algol', 'algol', ()), + 'Algol_NuStyle': ('pygments.styles.algol_nu', 'algol_nu', ()), + 'ArduinoStyle': ('pygments.styles.arduino', 'arduino', ()), + 'AutumnStyle': ('pygments.styles.autumn', 'autumn', ()), + 'BlackWhiteStyle': ('pygments.styles.bw', 'bw', ()), + 'BorlandStyle': ('pygments.styles.borland', 'borland', ()), + 'CoffeeStyle': ('pygments.styles.coffee', 'coffee', ()), + 'ColorfulStyle': ('pygments.styles.colorful', 'colorful', ()), + 'DefaultStyle': ('pygments.styles.default', 'default', ()), + 'DraculaStyle': ('pygments.styles.dracula', 'dracula', ()), + 'EmacsStyle': ('pygments.styles.emacs', 'emacs', ()), + 'FriendlyGrayscaleStyle': ('pygments.styles.friendly_grayscale', 'friendly_grayscale', ()), + 'FriendlyStyle': ('pygments.styles.friendly', 'friendly', ()), + 'FruityStyle': ('pygments.styles.fruity', 'fruity', ()), + 'GhDarkStyle': ('pygments.styles.gh_dark', 'github-dark', ()), + 'GruvboxDarkStyle': ('pygments.styles.gruvbox', 'gruvbox-dark', ()), + 'GruvboxLightStyle': ('pygments.styles.gruvbox', 'gruvbox-light', ()), + 'IgorStyle': ('pygments.styles.igor', 'igor', ()), + 'InkPotStyle': ('pygments.styles.inkpot', 'inkpot', ()), + 'LightbulbStyle': ('pygments.styles.lightbulb', 'lightbulb', ()), + 'LilyPondStyle': ('pygments.styles.lilypond', 'lilypond', ()), + 'LovelaceStyle': ('pygments.styles.lovelace', 'lovelace', ()), + 'ManniStyle': ('pygments.styles.manni', 'manni', ()), + 'MaterialStyle': ('pygments.styles.material', 'material', ()), + 'MonokaiStyle': ('pygments.styles.monokai', 'monokai', ()), + 'MurphyStyle': ('pygments.styles.murphy', 'murphy', ()), + 'NativeStyle': ('pygments.styles.native', 'native', ()), + 'NightOwlStyle': ('pygments.styles.night_owl', 'night-owl', ()), + 'NordDarkerStyle': ('pygments.styles.nord', 'nord-darker', ()), + 'NordStyle': ('pygments.styles.nord', 'nord', ()), + 'OneDarkStyle': ('pygments.styles.onedark', 'one-dark', ()), + 'ParaisoDarkStyle': ('pygments.styles.paraiso_dark', 'paraiso-dark', ()), + 'ParaisoLightStyle': ('pygments.styles.paraiso_light', 'paraiso-light', ()), + 'PastieStyle': ('pygments.styles.pastie', 'pastie', ()), + 'PerldocStyle': ('pygments.styles.perldoc', 'perldoc', ()), + 'RainbowDashStyle': ('pygments.styles.rainbow_dash', 'rainbow_dash', ()), + 'RrtStyle': ('pygments.styles.rrt', 'rrt', ()), + 'SasStyle': ('pygments.styles.sas', 'sas', ()), + 'SolarizedDarkStyle': ('pygments.styles.solarized', 'solarized-dark', ()), + 'SolarizedLightStyle': ('pygments.styles.solarized', 'solarized-light', ()), + 'StarofficeStyle': ('pygments.styles.staroffice', 'staroffice', ()), + 'StataDarkStyle': ('pygments.styles.stata_dark', 'stata-dark', ()), + 'StataLightStyle': ('pygments.styles.stata_light', 'stata-light', ()), + 'TangoStyle': ('pygments.styles.tango', 'tango', ()), + 'TracStyle': ('pygments.styles.trac', 'trac', ()), + 'VimStyle': ('pygments.styles.vim', 'vim', ()), + 'VisualStudioStyle': ('pygments.styles.vs', 'vs', ()), + 'XcodeStyle': ('pygments.styles.xcode', 'xcode', ()), + 'ZenburnStyle': ('pygments.styles.zenburn', 'zenburn', ()), +} diff --git a/.venv/lib/python3.12/site-packages/pygments/styles/abap.py b/.venv/lib/python3.12/site-packages/pygments/styles/abap.py new file mode 100644 index 0000000000000000000000000000000000000000..235bed759159c9b4633eb6b5eef3b7531de5cd63 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/pygments/styles/abap.py @@ -0,0 +1,32 @@ +""" + pygments.styles.abap + ~~~~~~~~~~~~~~~~~~~~ + + ABAP workbench like style. + + :copyright: Copyright 2006-present by the Pygments team, see AUTHORS. + :license: BSD, see LICENSE for details. +""" + +from pygments.style import Style +from pygments.token import Keyword, Name, Comment, String, Error, \ + Number, Operator + + +__all__ = ['AbapStyle'] + + +class AbapStyle(Style): + name = 'abap' + + styles = { + Comment: 'italic #888', + Comment.Special: '#888', + Keyword: '#00f', + Operator.Word: '#00f', + Name: '#000', + Number: '#3af', + String: '#5a2', + + Error: '#F00', + } diff --git a/.venv/lib/python3.12/site-packages/pygments/styles/algol.py b/.venv/lib/python3.12/site-packages/pygments/styles/algol.py new file mode 100644 index 0000000000000000000000000000000000000000..c8bea2ee2b9edea8873a09febba28927fbe56cea --- /dev/null +++ b/.venv/lib/python3.12/site-packages/pygments/styles/algol.py @@ -0,0 +1,65 @@ +""" + pygments.styles.algol + ~~~~~~~~~~~~~~~~~~~~~ + + Algol publication style. + + This style renders source code for publication of algorithms in + scientific papers and academic texts, where its format is frequently used. + + It is based on the style of the revised Algol-60 language report[1]. + + o No colours, only black, white and shades of grey are used. + o Keywords are rendered in lowercase underline boldface. + o Builtins are rendered in lowercase boldface italic. + o Docstrings and pragmas are rendered in dark grey boldface. + o Library identifiers are rendered in dark grey boldface italic. + o Comments are rendered in grey italic. + + To render keywords without underlining, refer to the `Algol_Nu` style. + + For lowercase conversion of keywords and builtins in languages where + these are not or might not be lowercase, a supporting lexer is required. + The Algol and Modula-2 lexers automatically convert to lowercase whenever + this style is selected. + + [1] `Revised Report on the Algorithmic Language Algol-60 ` + + :copyright: Copyright 2006-present by the Pygments team, see AUTHORS. + :license: BSD, see LICENSE for details. +""" + +from pygments.style import Style +from pygments.token import Keyword, Name, Comment, String, Error, Operator + + +__all__ = ['AlgolStyle'] + + +class AlgolStyle(Style): + name = 'algol' + + background_color = "#ffffff" + + styles = { + Comment: "italic #888", + Comment.Preproc: "bold noitalic #888", + Comment.Special: "bold noitalic #888", + + Keyword: "underline bold", + Keyword.Declaration: "italic", + + Name.Builtin: "bold italic", + Name.Builtin.Pseudo: "bold italic", + Name.Namespace: "bold italic #666", + Name.Class: "bold italic #666", + Name.Function: "bold italic #666", + Name.Variable: "bold italic #666", + Name.Constant: "bold italic #666", + + Operator.Word: "bold", + + String: "italic #666", + + Error: "border:#FF0000" + } diff --git a/.venv/lib/python3.12/site-packages/pygments/styles/algol_nu.py b/.venv/lib/python3.12/site-packages/pygments/styles/algol_nu.py new file mode 100644 index 0000000000000000000000000000000000000000..b8c052657e648724bac695d0579e49a26c13492c --- /dev/null +++ b/.venv/lib/python3.12/site-packages/pygments/styles/algol_nu.py @@ -0,0 +1,65 @@ +""" + pygments.styles.algol_nu + ~~~~~~~~~~~~~~~~~~~~~~~~ + + Algol publication style without underlining of keywords. + + This style renders source code for publication of algorithms in + scientific papers and academic texts, where its format is frequently used. + + It is based on the style of the revised Algol-60 language report[1]. + + o No colours, only black, white and shades of grey are used. + o Keywords are rendered in lowercase boldface. + o Builtins are rendered in lowercase boldface italic. + o Docstrings and pragmas are rendered in dark grey boldface. + o Library identifiers are rendered in dark grey boldface italic. + o Comments are rendered in grey italic. + + To render keywords with underlining, refer to the `Algol` style. + + For lowercase conversion of keywords and builtins in languages where + these are not or might not be lowercase, a supporting lexer is required. + The Algol and Modula-2 lexers automatically convert to lowercase whenever + this style is selected. + + [1] `Revised Report on the Algorithmic Language Algol-60 ` + + :copyright: Copyright 2006-present by the Pygments team, see AUTHORS. + :license: BSD, see LICENSE for details. +""" + +from pygments.style import Style +from pygments.token import Keyword, Name, Comment, String, Error, Operator + + +__all__ = ['Algol_NuStyle'] + + +class Algol_NuStyle(Style): + name = 'algol_nu' + + background_color = "#ffffff" + + styles = { + Comment: "italic #888", + Comment.Preproc: "bold noitalic #888", + Comment.Special: "bold noitalic #888", + + Keyword: "bold", + Keyword.Declaration: "italic", + + Name.Builtin: "bold italic", + Name.Builtin.Pseudo: "bold italic", + Name.Namespace: "bold italic #666", + Name.Class: "bold italic #666", + Name.Function: "bold italic #666", + Name.Variable: "bold italic #666", + Name.Constant: "bold italic #666", + + Operator.Word: "bold", + + String: "italic #666", + + Error: "border:#FF0000" + } diff --git a/.venv/lib/python3.12/site-packages/pygments/styles/arduino.py b/.venv/lib/python3.12/site-packages/pygments/styles/arduino.py new file mode 100644 index 0000000000000000000000000000000000000000..651f33984bba6cbf63b59569ae3fbd3316a56f27 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/pygments/styles/arduino.py @@ -0,0 +1,100 @@ +""" + pygments.styles.arduino + ~~~~~~~~~~~~~~~~~~~~~~~ + + Arduino® Syntax highlighting style. + + :copyright: Copyright 2006-present by the Pygments team, see AUTHORS. + :license: BSD, see LICENSE for details. +""" + +from pygments.style import Style +from pygments.token import Keyword, Name, Comment, String, Error, \ + Number, Operator, Generic, Whitespace + + +__all__ = ['ArduinoStyle'] + + +class ArduinoStyle(Style): + """ + The Arduino® language style. This style is designed to highlight the + Arduino source code, so expect the best results with it. + """ + name = 'arduino' + + background_color = "#ffffff" + + styles = { + Whitespace: "", # class: 'w' + Error: "#a61717", # class: 'err' + + Comment: "#95a5a6", # class: 'c' + Comment.Multiline: "", # class: 'cm' + Comment.Preproc: "#728E00", # class: 'cp' + Comment.Single: "", # class: 'c1' + Comment.Special: "", # class: 'cs' + + Keyword: "#728E00", # class: 'k' + Keyword.Constant: "#00979D", # class: 'kc' + Keyword.Declaration: "", # class: 'kd' + Keyword.Namespace: "", # class: 'kn' + Keyword.Pseudo: "#00979D", # class: 'kp' + Keyword.Reserved: "#00979D", # class: 'kr' + Keyword.Type: "#00979D", # class: 'kt' + + Operator: "#728E00", # class: 'o' + Operator.Word: "", # class: 'ow' + + Name: "#434f54", # class: 'n' + Name.Attribute: "", # class: 'na' + Name.Builtin: "#728E00", # class: 'nb' + Name.Builtin.Pseudo: "", # class: 'bp' + Name.Class: "", # class: 'nc' + Name.Constant: "", # class: 'no' + Name.Decorator: "", # class: 'nd' + Name.Entity: "", # class: 'ni' + Name.Exception: "", # class: 'ne' + Name.Function: "#D35400", # class: 'nf' + Name.Property: "", # class: 'py' + Name.Label: "", # class: 'nl' + Name.Namespace: "", # class: 'nn' + Name.Other: "#728E00", # class: 'nx' + Name.Tag: "", # class: 'nt' + Name.Variable: "", # class: 'nv' + Name.Variable.Class: "", # class: 'vc' + Name.Variable.Global: "", # class: 'vg' + Name.Variable.Instance: "", # class: 'vi' + + Number: "#8A7B52", # class: 'm' + Number.Float: "", # class: 'mf' + Number.Hex: "", # class: 'mh' + Number.Integer: "", # class: 'mi' + Number.Integer.Long: "", # class: 'il' + Number.Oct: "", # class: 'mo' + + String: "#7F8C8D", # class: 's' + String.Backtick: "", # class: 'sb' + String.Char: "", # class: 'sc' + String.Doc: "", # class: 'sd' + String.Double: "", # class: 's2' + String.Escape: "", # class: 'se' + String.Heredoc: "", # class: 'sh' + String.Interpol: "", # class: 'si' + String.Other: "", # class: 'sx' + String.Regex: "", # class: 'sr' + String.Single: "", # class: 's1' + String.Symbol: "", # class: 'ss' + + Generic: "", # class: 'g' + Generic.Deleted: "", # class: 'gd', + Generic.Emph: "", # class: 'ge' + Generic.Error: "", # class: 'gr' + Generic.Heading: "", # class: 'gh' + Generic.Inserted: "", # class: 'gi' + Generic.Output: "", # class: 'go' + Generic.Prompt: "", # class: 'gp' + Generic.Strong: "", # class: 'gs' + Generic.Subheading: "", # class: 'gu' + Generic.Traceback: "", # class: 'gt' + } diff --git a/.venv/lib/python3.12/site-packages/pygments/styles/autumn.py b/.venv/lib/python3.12/site-packages/pygments/styles/autumn.py new file mode 100644 index 0000000000000000000000000000000000000000..75283e2d9d69ecb0acf1cc127106af5f113226d3 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/pygments/styles/autumn.py @@ -0,0 +1,67 @@ +""" + pygments.styles.autumn + ~~~~~~~~~~~~~~~~~~~~~~ + + A colorful style, inspired by the terminal highlighting style. + + :copyright: Copyright 2006-present by the Pygments team, see AUTHORS. + :license: BSD, see LICENSE for details. +""" + +from pygments.style import Style +from pygments.token import Keyword, Name, Comment, String, Error, \ + Number, Operator, Generic, Whitespace + + +__all__ = ['AutumnStyle'] + + +class AutumnStyle(Style): + """ + A colorful style, inspired by the terminal highlighting style. + """ + name = 'autumn' + + styles = { + Whitespace: '#bbbbbb', + + Comment: 'italic #aaaaaa', + Comment.Preproc: 'noitalic #4c8317', + Comment.Special: 'italic #0000aa', + + Keyword: '#0000aa', + Keyword.Type: '#00aaaa', + + Operator.Word: '#0000aa', + + Name.Builtin: '#00aaaa', + Name.Function: '#00aa00', + Name.Class: 'underline #00aa00', + Name.Namespace: 'underline #00aaaa', + Name.Variable: '#aa0000', + Name.Constant: '#aa0000', + Name.Entity: 'bold #800', + Name.Attribute: '#1e90ff', + Name.Tag: 'bold #1e90ff', + Name.Decorator: '#888888', + + String: '#aa5500', + String.Symbol: '#0000aa', + String.Regex: '#009999', + + Number: '#009999', + + Generic.Heading: 'bold #000080', + Generic.Subheading: 'bold #800080', + Generic.Deleted: '#aa0000', + Generic.Inserted: '#00aa00', + Generic.Error: '#aa0000', + Generic.Emph: 'italic', + Generic.Strong: 'bold', + Generic.EmphStrong: 'bold italic', + Generic.Prompt: '#555555', + Generic.Output: '#888888', + Generic.Traceback: '#aa0000', + + Error: '#F00 bg:#FAA' + } diff --git a/.venv/lib/python3.12/site-packages/pygments/styles/borland.py b/.venv/lib/python3.12/site-packages/pygments/styles/borland.py new file mode 100644 index 0000000000000000000000000000000000000000..73e9cd1b0eb97d7cae7151940875e18bc166a5b9 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/pygments/styles/borland.py @@ -0,0 +1,53 @@ +""" + pygments.styles.borland + ~~~~~~~~~~~~~~~~~~~~~~~ + + Style similar to the style used in the Borland IDEs. + + :copyright: Copyright 2006-present by the Pygments team, see AUTHORS. + :license: BSD, see LICENSE for details. +""" + +from pygments.style import Style +from pygments.token import Keyword, Name, Comment, String, Error, \ + Number, Operator, Generic, Whitespace + + +__all__ = ['BorlandStyle'] + + +class BorlandStyle(Style): + """ + Style similar to the style used in the borland IDEs. + """ + name = 'borland' + + styles = { + Whitespace: '#bbbbbb', + + Comment: 'italic #008800', + Comment.Preproc: 'noitalic #008080', + Comment.Special: 'noitalic bold', + + String: '#0000FF', + String.Char: '#800080', + Number: '#0000FF', + Keyword: 'bold #000080', + Operator.Word: 'bold', + Name.Tag: 'bold #000080', + Name.Attribute: '#FF0000', + + Generic.Heading: '#999999', + Generic.Subheading: '#aaaaaa', + Generic.Deleted: 'bg:#ffdddd #000000', + Generic.Inserted: 'bg:#ddffdd #000000', + Generic.Error: '#aa0000', + Generic.Emph: 'italic', + Generic.Strong: 'bold', + Generic.EmphStrong: 'bold italic', + Generic.Prompt: '#555555', + Generic.Output: '#888888', + Generic.Traceback: '#aa0000', + + Error: 'bg:#e3d2d2 #a61717' + } diff --git a/.venv/lib/python3.12/site-packages/pygments/styles/bw.py b/.venv/lib/python3.12/site-packages/pygments/styles/bw.py new file mode 100644 index 0000000000000000000000000000000000000000..9fa0baa57f9bbf43d90ae683946cc24063e854ee --- /dev/null +++ b/.venv/lib/python3.12/site-packages/pygments/styles/bw.py @@ -0,0 +1,52 @@ +""" + pygments.styles.bw + ~~~~~~~~~~~~~~~~~~ + + Simple black/white only style. + + :copyright: Copyright 2006-present by the Pygments team, see AUTHORS. + :license: BSD, see LICENSE for details. +""" + +from pygments.style import Style +from pygments.token import Keyword, Name, Comment, String, Error, \ + Operator, Generic + + +__all__ = ['BlackWhiteStyle'] + + +class BlackWhiteStyle(Style): + name = 'bw' + + background_color = "#ffffff" + + styles = { + Comment: "italic", + Comment.Preproc: "noitalic", + + Keyword: "bold", + Keyword.Pseudo: "nobold", + Keyword.Type: "nobold", + + Operator.Word: "bold", + + Name.Class: "bold", + Name.Namespace: "bold", + Name.Exception: "bold", + Name.Entity: "bold", + Name.Tag: "bold", + + String: "italic", + String.Interpol: "bold", + String.Escape: "bold", + + Generic.Heading: "bold", + Generic.Subheading: "bold", + Generic.Emph: "italic", + Generic.Strong: "bold", + Generic.EmphStrong: "bold italic", + Generic.Prompt: "bold", + + Error: "border:#FF0000" + } diff --git a/.venv/lib/python3.12/site-packages/pygments/styles/coffee.py b/.venv/lib/python3.12/site-packages/pygments/styles/coffee.py new file mode 100644 index 0000000000000000000000000000000000000000..98da14e0030dc7d78fa7fbf3387fb8c0740ec835 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/pygments/styles/coffee.py @@ -0,0 +1,80 @@ +""" + pygments.styles.coffee + ~~~~~~~~~~~~~~~~~~~~~~ + + A warm and cozy theme based off gruvbox + + :copyright: Copyright 2006-present by the Pygments team, see AUTHORS. + :license: BSD, see LICENSE for details. +""" + +from pygments.style import Style +from pygments.token import (Comment, Error, Generic, Keyword, Literal, Name, + Number, Operator, Punctuation, String, Token) + +__all__ = ["CoffeeStyle"] + + +class CoffeeStyle(Style): + """ + A warm and cozy theme based off gruvbox + """ + + name = "coffee" + + background_color = "#262220" + highlight_color = "#ddd0c0" + + line_number_color = "#4e4e4e" + line_number_special_color = "#8f9494" + + styles = { + Comment: "#70757A", + Comment.Hashbang: "#8f9f9f", + Comment.Preproc: "#fdd0c0", + Comment.PreprocFile: "#c9b98f", + Comment.Special: "#af5f5f", + Error: "#af5f5f", + Generic.Deleted: "#bb6868", + Generic.Emph: "italic", + Generic.Error: "#af5f5f", + Generic.Inserted: "#849155", + Generic.Output: "#ddd0c0", + Generic.Strong: "bold", + Generic.Traceback: "#af5f5f", + Keyword: "#919191", + Keyword.Constant: "#875f5f", + Keyword.Declaration: "#875f5f", + Keyword.Namespace: "#875f5f", + Keyword.Reserved: "#b46276", + Keyword.Type: "#af875f", + Literal: "#af875f", + Name: "#ddd0c0", + Name.Attribute: "#ddd0c0", + Name.Builtin: "#ddd0c0", + Name.Builtin.Pseudo: "#87afaf", + Name.Class: "#875f5f", + Name.Constant: "#af8787", + Name.Decorator: "#fdd0c0", + Name.Entity: "#ddd0c0", + Name.Exception: "#877575", + Name.Function: "#fdd0c0", + Name.Function.Magic: "#fdd0c0", + Name.Other: "#ddd0c0", + Name.Property: "#dfaf87", + Name.Tag: "#87afaf", + Name.Variable: "#ddd0c0", + Number: "#87afaf", + Operator: "#878787", + Operator.Word: "#878787", + Punctuation: "#ddd0c0", + String: "#c9b98f", + String.Affix: "#dfaf87", + String.Doc: "#878787", + String.Escape: "#af5f5f", + String.Interpol: "#af5f5f", + String.Other: "#fdd0c0", + String.Regex: "#af5f5f", + String.Symbol: "#af5f5f", + Token: "#ddd0c0", + } diff --git a/.venv/lib/python3.12/site-packages/pygments/styles/colorful.py b/.venv/lib/python3.12/site-packages/pygments/styles/colorful.py new file mode 100644 index 0000000000000000000000000000000000000000..5511fba1d827423c6261659a7aac4675e3341233 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/pygments/styles/colorful.py @@ -0,0 +1,83 @@ +""" + pygments.styles.colorful + ~~~~~~~~~~~~~~~~~~~~~~~~ + + A colorful style, inspired by CodeRay. + + :copyright: Copyright 2006-present by the Pygments team, see AUTHORS. + :license: BSD, see LICENSE for details. +""" + +from pygments.style import Style +from pygments.token import Keyword, Name, Comment, String, Error, \ + Number, Operator, Generic, Whitespace + + +__all__ = ['ColorfulStyle'] + + +class ColorfulStyle(Style): + """ + A colorful style, inspired by CodeRay. + """ + name = 'colorful' + + styles = { + Whitespace: "#bbbbbb", + + Comment: "#888", + Comment.Preproc: "#579", + Comment.Special: "bold #cc0000", + + Keyword: "bold #080", + Keyword.Pseudo: "#038", + Keyword.Type: "#339", + + Operator: "#333", + Operator.Word: "bold #000", + + Name.Builtin: "#007020", + Name.Function: "bold #06B", + Name.Class: "bold #B06", + Name.Namespace: "bold #0e84b5", + Name.Exception: "bold #F00", + Name.Variable: "#963", + Name.Variable.Instance: "#33B", + Name.Variable.Class: "#369", + Name.Variable.Global: "bold #d70", + Name.Constant: "bold #036", + Name.Label: "bold #970", + Name.Entity: "bold #800", + Name.Attribute: "#00C", + Name.Tag: "#070", + Name.Decorator: "bold #555", + + String: "bg:#fff0f0", + String.Char: "#04D bg:", + String.Doc: "#D42 bg:", + String.Interpol: "bg:#eee", + String.Escape: "bold #666", + String.Regex: "bg:#fff0ff #000", + String.Symbol: "#A60 bg:", + String.Other: "#D20", + + Number: "bold #60E", + Number.Integer: "bold #00D", + Number.Float: "bold #60E", + Number.Hex: "bold #058", + Number.Oct: "bold #40E", + + Generic.Heading: "bold #000080", + Generic.Subheading: "bold #800080", + Generic.Deleted: "#A00000", + Generic.Inserted: "#00A000", + Generic.Error: "#FF0000", + Generic.Emph: "italic", + Generic.Strong: "bold", + Generic.EmphStrong: "bold italic", + Generic.Prompt: "bold #c65d09", + Generic.Output: "#888", + Generic.Traceback: "#04D", + + Error: "#F00 bg:#FAA" + } diff --git a/.venv/lib/python3.12/site-packages/pygments/styles/default.py b/.venv/lib/python3.12/site-packages/pygments/styles/default.py new file mode 100644 index 0000000000000000000000000000000000000000..521cdf5264910dc3a46c1d7de19f501fc5e1b28c --- /dev/null +++ b/.venv/lib/python3.12/site-packages/pygments/styles/default.py @@ -0,0 +1,76 @@ +""" + pygments.styles.default + ~~~~~~~~~~~~~~~~~~~~~~~ + + The default highlighting style. + + :copyright: Copyright 2006-present by the Pygments team, see AUTHORS. + :license: BSD, see LICENSE for details. +""" + +from pygments.style import Style +from pygments.token import Keyword, Name, Comment, String, Error, \ + Number, Operator, Generic, Whitespace + + +__all__ = ['DefaultStyle'] + + +class DefaultStyle(Style): + """ + The default style (inspired by Emacs 22). + """ + name = 'default' + + background_color = "#f8f8f8" + + styles = { + Whitespace: "#bbbbbb", + Comment: "italic #3D7B7B", + Comment.Preproc: "noitalic #9C6500", + + #Keyword: "bold #AA22FF", + Keyword: "bold #008000", + Keyword.Pseudo: "nobold", + Keyword.Type: "nobold #B00040", + + Operator: "#666666", + Operator.Word: "bold #AA22FF", + + Name.Builtin: "#008000", + Name.Function: "#0000FF", + Name.Class: "bold #0000FF", + Name.Namespace: "bold #0000FF", + Name.Exception: "bold #CB3F38", + Name.Variable: "#19177C", + Name.Constant: "#880000", + Name.Label: "#767600", + Name.Entity: "bold #717171", + Name.Attribute: "#687822", + Name.Tag: "bold #008000", + Name.Decorator: "#AA22FF", + + String: "#BA2121", + String.Doc: "italic", + String.Interpol: "bold #A45A77", + String.Escape: "bold #AA5D1F", + String.Regex: "#A45A77", + #String.Symbol: "#B8860B", + String.Symbol: "#19177C", + String.Other: "#008000", + Number: "#666666", + + Generic.Heading: "bold #000080", + Generic.Subheading: "bold #800080", + Generic.Deleted: "#A00000", + Generic.Inserted: "#008400", + Generic.Error: "#E40000", + Generic.Emph: "italic", + Generic.Strong: "bold", + Generic.EmphStrong: "bold italic", + Generic.Prompt: "bold #000080", + Generic.Output: "#717171", + Generic.Traceback: "#04D", + + Error: "border:#FF0000" + } diff --git a/.venv/lib/python3.12/site-packages/pygments/styles/dracula.py b/.venv/lib/python3.12/site-packages/pygments/styles/dracula.py new file mode 100644 index 0000000000000000000000000000000000000000..552668ddae11c890ce2eb6ab879da372e014fd23 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/pygments/styles/dracula.py @@ -0,0 +1,90 @@ +""" + pygments.styles.dracula + ~~~~~~~~~~~~~~~~~~~~~~~ + + Pygments version of `Dracula` from https://github.com/dracula/dracula-theme. + + Based on the Dracula Theme for pygments by Chris Bracco. + See https://github.com/dracula/pygments/tree/fee9ed5613d1086bc01b9d0a5a0e9867a009f571 + + :copyright: Copyright 2006-present by the Pygments team, see AUTHORS. + :license: BSD, see LICENSE for details. +""" + +from pygments.style import Style +from pygments.token import Keyword, Name, Comment, String, Error, Literal, \ + Number, Operator, Other, Punctuation, Text, Generic, Whitespace + + +__all__ = ['DraculaStyle'] + +background = "#282a36" +foreground = "#f8f8f2" +selection = "#44475a" +comment = "#6272a4" +cyan = "#8be9fd" +green = "#50fa7b" +orange = "#ffb86c" +pink = "#ff79c6" +purple = "#bd93f9" +red = "#ff5555" +yellow = "#f1fa8c" + +deletion = "#8b080b" + +class DraculaStyle(Style): + name = 'dracula' + + background_color = background + highlight_color = selection + line_number_color = yellow + line_number_background_color = selection + line_number_special_color = green + line_number_special_background_color = comment + + styles = { + Whitespace: foreground, + + Comment: comment, + Comment.Preproc: pink, + + Generic: foreground, + Generic.Deleted: deletion, + Generic.Emph: "underline", + Generic.Heading: "bold", + Generic.Inserted: "bold", + Generic.Output: selection, + Generic.EmphStrong: "underline", + Generic.Subheading: "bold", + + Error: foreground, + + Keyword: pink, + Keyword.Constant: pink, + Keyword.Declaration: cyan + " italic", + Keyword.Type: cyan, + + Literal: foreground, + + Name: foreground, + Name.Attribute: green, + Name.Builtin: cyan + " italic", + Name.Builtin.Pseudo: foreground, + Name.Class: green, + Name.Function: green, + Name.Label: cyan + " italic", + Name.Tag: pink, + Name.Variable: cyan + " italic", + + Number: orange, + + Operator: pink, + + Other: foreground, + + Punctuation: foreground, + + String: purple, + + Text: foreground, + } diff --git a/.venv/lib/python3.12/site-packages/pygments/styles/emacs.py b/.venv/lib/python3.12/site-packages/pygments/styles/emacs.py new file mode 100644 index 0000000000000000000000000000000000000000..8860c7aab3458806b2dadb38615ed7614f3d4b3a --- /dev/null +++ b/.venv/lib/python3.12/site-packages/pygments/styles/emacs.py @@ -0,0 +1,75 @@ +""" + pygments.styles.emacs + ~~~~~~~~~~~~~~~~~~~~~ + + A highlighting style for Pygments, inspired by Emacs. + + :copyright: Copyright 2006-present by the Pygments team, see AUTHORS. + :license: BSD, see LICENSE for details. +""" + +from pygments.style import Style +from pygments.token import Keyword, Name, Comment, String, Error, \ + Number, Operator, Generic, Whitespace + + +__all__ = ['EmacsStyle'] + + +class EmacsStyle(Style): + """ + The default style (inspired by Emacs 22). + """ + name = 'emacs' + + background_color = "#f8f8f8" + + styles = { + Whitespace: "#bbbbbb", + Comment: "italic #008800", + Comment.Preproc: "noitalic", + Comment.Special: "noitalic bold", + + Keyword: "bold #AA22FF", + Keyword.Pseudo: "nobold", + Keyword.Type: "bold #00BB00", + + Operator: "#666666", + Operator.Word: "bold #AA22FF", + + Name.Builtin: "#AA22FF", + Name.Function: "#00A000", + Name.Class: "#0000FF", + Name.Namespace: "bold #0000FF", + Name.Exception: "bold #D2413A", + Name.Variable: "#B8860B", + Name.Constant: "#880000", + Name.Label: "#A0A000", + Name.Entity: "bold #999999", + Name.Attribute: "#BB4444", + Name.Tag: "bold #008000", + Name.Decorator: "#AA22FF", + + String: "#BB4444", + String.Doc: "italic", + String.Interpol: "bold #BB6688", + String.Escape: "bold #BB6622", + String.Regex: "#BB6688", + String.Symbol: "#B8860B", + String.Other: "#008000", + Number: "#666666", + + Generic.Heading: "bold #000080", + Generic.Subheading: "bold #800080", + Generic.Deleted: "#A00000", + Generic.Inserted: "#00A000", + Generic.Error: "#FF0000", + Generic.Emph: "italic", + Generic.Strong: "bold", + Generic.EmphStrong: "bold italic", + Generic.Prompt: "bold #000080", + Generic.Output: "#888", + Generic.Traceback: "#04D", + + Error: "border:#FF0000" + } diff --git a/.venv/lib/python3.12/site-packages/pygments/styles/friendly.py b/.venv/lib/python3.12/site-packages/pygments/styles/friendly.py new file mode 100644 index 0000000000000000000000000000000000000000..aeee356b3cdf64424111190c803798b0df78cd42 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/pygments/styles/friendly.py @@ -0,0 +1,76 @@ +""" + pygments.styles.friendly + ~~~~~~~~~~~~~~~~~~~~~~~~ + + A modern style based on the VIM pyte theme. + + :copyright: Copyright 2006-present by the Pygments team, see AUTHORS. + :license: BSD, see LICENSE for details. +""" + +from pygments.style import Style +from pygments.token import Keyword, Name, Comment, String, Error, \ + Number, Operator, Generic, Whitespace + + +__all__ = ['FriendlyStyle'] + + +class FriendlyStyle(Style): + """ + A modern style based on the VIM pyte theme. + """ + name = 'friendly' + + background_color = "#f0f0f0" + line_number_color = "#666666" + + styles = { + Whitespace: "#bbbbbb", + Comment: "italic #60a0b0", + Comment.Preproc: "noitalic #007020", + Comment.Special: "noitalic bg:#fff0f0", + + Keyword: "bold #007020", + Keyword.Pseudo: "nobold", + Keyword.Type: "nobold #902000", + + Operator: "#666666", + Operator.Word: "bold #007020", + + Name.Builtin: "#007020", + Name.Function: "#06287e", + Name.Class: "bold #0e84b5", + Name.Namespace: "bold #0e84b5", + Name.Exception: "#007020", + Name.Variable: "#bb60d5", + Name.Constant: "#60add5", + Name.Label: "bold #002070", + Name.Entity: "bold #d55537", + Name.Attribute: "#4070a0", + Name.Tag: "bold #062873", + Name.Decorator: "bold #555555", + + String: "#4070a0", + String.Doc: "italic", + String.Interpol: "italic #70a0d0", + String.Escape: "bold #4070a0", + String.Regex: "#235388", + String.Symbol: "#517918", + String.Other: "#c65d09", + Number: "#40a070", + + Generic.Heading: "bold #000080", + Generic.Subheading: "bold #800080", + Generic.Deleted: "#A00000", + Generic.Inserted: "#00A000", + Generic.Error: "#FF0000", + Generic.Emph: "italic", + Generic.Strong: "bold", + Generic.EmphStrong: "bold italic", + Generic.Prompt: "bold #c65d09", + Generic.Output: "#888", + Generic.Traceback: "#04D", + + Error: "border:#FF0000" + } diff --git a/.venv/lib/python3.12/site-packages/pygments/styles/friendly_grayscale.py b/.venv/lib/python3.12/site-packages/pygments/styles/friendly_grayscale.py new file mode 100644 index 0000000000000000000000000000000000000000..8e25b591933630873625a1b41f8e96d9ed81b32a --- /dev/null +++ b/.venv/lib/python3.12/site-packages/pygments/styles/friendly_grayscale.py @@ -0,0 +1,80 @@ +""" + pygments.styles.friendly_grayscale + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + + A style based on friendly style. + The color values of the friendly style have been converted to grayscale + using the luminosity value calculated by + http://www.workwithcolor.com/color-converter-01.htm + + :copyright: Copyright 2006-present by the Pygments team, see AUTHORS. + :license: BSD, see LICENSE for details. +""" + +from pygments.style import Style +from pygments.token import Keyword, Name, Comment, String, Error, \ + Number, Operator, Generic, Whitespace + + +__all__ = ['FriendlyGrayscaleStyle'] + + +class FriendlyGrayscaleStyle(Style): + """ + A modern grayscale style based on the friendly style. + + .. versionadded:: 2.11 + """ + name = 'friendly_grayscale' + + background_color = "#f0f0f0" + + styles = { + Whitespace: "#bbbbbb", + Comment: "italic #959595", + Comment.Preproc: "noitalic #575757", + Comment.Special: "noitalic bg:#F4F4F4", + + Keyword: "bold #575757", + Keyword.Pseudo: "nobold", + Keyword.Type: "nobold #4F4F4F", + + Operator: "#666666", + Operator.Word: "bold #575757", + + Name.Builtin: "#575757", + Name.Function: "#3F3F3F", + Name.Class: "bold #7E7E7E", + Name.Namespace: "bold #7E7E7E", + Name.Exception: "#575757", + Name.Variable: "#9A9A9A", + Name.Constant: "#A5A5A5", + Name.Label: "bold #363636", + Name.Entity: "bold #848484", + Name.Attribute: "#707070", + Name.Tag: "bold #3B3B3B", + Name.Decorator: "bold #555555", + + String: "#717171", + String.Doc: "italic", + String.Interpol: "italic #9F9F9F", + String.Escape: "bold #717171", + String.Regex: "#575757", + String.Symbol: "#676767", + String.Other: "#7E7E7E", + Number: "#888888", + + Generic.Heading: "bold #373737", + Generic.Subheading: "bold #5A5A5A", + Generic.Deleted: "#545454", + Generic.Inserted: "#7D7D7D", + Generic.Error: "#898989", + Generic.Emph: "italic", + Generic.Strong: "bold", + Generic.EmphStrong: "bold italic", + Generic.Prompt: "bold #7E7E7E", + Generic.Output: "#888888", + Generic.Traceback: "#6D6D6D", + + Error: "border:#898989" + } diff --git a/.venv/lib/python3.12/site-packages/pygments/styles/fruity.py b/.venv/lib/python3.12/site-packages/pygments/styles/fruity.py new file mode 100644 index 0000000000000000000000000000000000000000..cf3de88679464dcd10335daaa68f8ba66ddd5234 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/pygments/styles/fruity.py @@ -0,0 +1,47 @@ +""" + pygments.styles.fruity + ~~~~~~~~~~~~~~~~~~~~~~ + + pygments version of my "fruity" vim theme. + + :copyright: Copyright 2006-present by the Pygments team, see AUTHORS. + :license: BSD, see LICENSE for details. +""" + +from pygments.style import Style +from pygments.token import Token, Comment, Name, Keyword, \ + Generic, Number, String, Whitespace + + +__all__ = ['FruityStyle'] + + +class FruityStyle(Style): + """ + Pygments version of the "native" vim theme. + """ + + name = 'fruity' + + background_color = '#111111' + highlight_color = '#333333' + + styles = { + Whitespace: '#888888', + Token: '#ffffff', + Generic.Output: '#444444 bg:#222222', + Keyword: '#fb660a bold', + Keyword.Pseudo: 'nobold', + Number: '#0086f7 bold', + Name.Tag: '#fb660a bold', + Name.Variable: '#fb660a', + Comment: '#008800 bg:#0f140f italic', + Name.Attribute: '#ff0086 bold', + String: '#0086d2', + Name.Function: '#ff0086 bold', + Generic.Heading: '#ffffff bold', + Keyword.Type: '#cdcaa9 bold', + Generic.Subheading: '#ffffff bold', + Name.Constant: '#0086d2', + Comment.Preproc: '#ff0007 bold' + } diff --git a/.venv/lib/python3.12/site-packages/pygments/styles/gh_dark.py b/.venv/lib/python3.12/site-packages/pygments/styles/gh_dark.py new file mode 100644 index 0000000000000000000000000000000000000000..d0d32f6c3342a0abc6f840ce04259832ad46fd5a --- /dev/null +++ b/.venv/lib/python3.12/site-packages/pygments/styles/gh_dark.py @@ -0,0 +1,113 @@ +""" + pygments.styles.gh_dark + ~~~~~~~~~~~~~~~~~~~~~~~ + + Github's Dark-Colorscheme based theme for Pygments + Colors extracted from https://github.com/primer/primitives + + :copyright: Copyright 2006-present by the Pygments team, see AUTHORS. + :license: BSD, see LICENSE for details. +""" + +from pygments.style import Style +from pygments.token import Keyword, Name, Comment, Error, Number, Operator, \ + Generic, Text, Literal, String, Token + + +__all__ = ['GhDarkStyle'] + + +# vars are defined to match the defs in +# - [GitHub's VS Code theme](https://github.com/primer/github-vscode-theme) and +# - [Primer styles](https://github.com/primer/primitives) +RED_2 = "#ffa198" +RED_3 = "#ff7b72" +RED_9 = "#490202" +ORANGE_2 = "#ffa657" +ORANGE_3 = "#f0883e" +GREEN_1 = "#7ee787" +GREEN_2 = "#56d364" +GREEN_7 = "#0f5323" +BLUE_1 = "#a5d6ff" +BLUE_2 = "#79c0ff" +PURPLE_2 = "#d2a8ff" +GRAY_3 = "#8b949e" +GRAY_4 = "#6e7681" +FG_SUBTLE = "#6e7681" +FG_DEFAULT = "#e6edf3" +BG_DEFAULT = "#0d1117" +DANGER_FG = "#f85149" + + +class GhDarkStyle(Style): + """ + Github's Dark-Colorscheme based theme for Pygments + """ + + name = 'github-dark' + + background_color = BG_DEFAULT + + # has transparency in VS Code theme as `colors.codemirror.activelineBg` + highlight_color = GRAY_4 + + line_number_special_color = FG_DEFAULT + line_number_special_background_color = FG_SUBTLE + + line_number_color = GRAY_4 + line_number_background_color = BG_DEFAULT + + styles = { + Token: FG_DEFAULT, + + Error: DANGER_FG, + + Keyword: RED_3, + Keyword.Constant: BLUE_2, + Keyword.Pseudo: BLUE_2, + + Name: FG_DEFAULT, + Name.Class: "bold "+ORANGE_3, + Name.Constant: "bold "+BLUE_2, + Name.Decorator: 'bold '+PURPLE_2, + Name.Entity: ORANGE_2, + Name.Exception: "bold "+ORANGE_3, + Name.Function: 'bold '+PURPLE_2, + Name.Label: "bold "+BLUE_2, + Name.Namespace: RED_3, + Name.Property: BLUE_2, + Name.Tag: GREEN_1, + Name.Variable: BLUE_2, + + Literal: BLUE_1, + Literal.Date: BLUE_2, + String: BLUE_1, + String.Affix: BLUE_2, + String.Delimiter: BLUE_2, + String.Escape: BLUE_2, + String.Heredoc: BLUE_2, + String.Regex: BLUE_2, + Number: BLUE_1, + + Comment: 'italic '+GRAY_3, + Comment.Preproc: "bold " + GRAY_3, + Comment.Special: "bold italic " + GRAY_3, + + Operator: 'bold ' + RED_3, + + Generic: FG_DEFAULT, + Generic.Deleted: f"bg:{RED_9} {RED_2}", + Generic.Emph: "italic", + Generic.Error: RED_2, + Generic.Heading: "bold "+BLUE_2, + Generic.Inserted: f'bg:{GREEN_7} {GREEN_2}', + Generic.Output: GRAY_3, + Generic.Prompt: GRAY_3, + Generic.Strong: "bold", + Generic.EmphStrong: "bold italic", + Generic.Subheading: BLUE_2, + Generic.Traceback: RED_3, + Generic.Underline: "underline", + + Text.Whitespace: FG_SUBTLE, + } diff --git a/.venv/lib/python3.12/site-packages/pygments/styles/gruvbox.py b/.venv/lib/python3.12/site-packages/pygments/styles/gruvbox.py new file mode 100644 index 0000000000000000000000000000000000000000..20eaeb55191d42bdaa44f3a40a9dd5bb9f856e5b --- /dev/null +++ b/.venv/lib/python3.12/site-packages/pygments/styles/gruvbox.py @@ -0,0 +1,118 @@ +""" + pygments.styles.gruvbox + ~~~~~~~~~~~~~~~~~~~~~~~ + + pygments version of the "gruvbox" vim theme. + https://github.com/morhetz/gruvbox + + :copyright: Copyright 2006-present by the Pygments team, see AUTHORS. + :license: BSD, see LICENSE for details. +""" + +from pygments.style import Style +from pygments.token import Token, Keyword, Name, Comment, String, Error, \ + Number, Operator, Generic + + +__all__ = ['GruvboxDarkStyle', 'GruvboxLightStyle'] + + +class GruvboxDarkStyle(Style): + """ + Pygments version of the "gruvbox" dark vim theme. + """ + + name = 'gruvbox-dark' + + background_color = '#282828' + highlight_color = '#ebdbb2' + + styles = { + Token: '#dddddd', + + Comment: 'italic #928374', + Comment.PreProc: '#8ec07c', + Comment.Special: 'bold italic #ebdbb2', + + Keyword: '#fb4934', + Operator.Word: '#fb4934', + + String: '#b8bb26', + String.Escape: '#fe8019', + + Number: '#d3869b', + + Name.Builtin: '#fe8019', + Name.Variable: '#83a598', + Name.Constant: '#d3869b', + Name.Class: '#8ec07c', + Name.Function: '#8ec07c', + Name.Namespace: '#8ec07c', + Name.Exception: '#fb4934', + Name.Tag: '#8ec07c', + Name.Attribute: '#fabd2f', + Name.Decorator: '#fb4934', + + Generic.Heading: 'bold #ebdbb2', + Generic.Subheading: 'underline #ebdbb2', + Generic.Deleted: 'bg:#fb4934 #282828', + Generic.Inserted: 'bg:#b8bb26 #282828', + Generic.Error: '#fb4934', + Generic.Emph: 'italic', + Generic.Strong: 'bold', + Generic.EmphStrong: 'bold italic', + Generic.Prompt: '#a89984', + Generic.Output: '#f2e5bc', + Generic.Traceback: '#fb4934', + + Error: 'bg:#fb4934 #282828' + } + + +class GruvboxLightStyle(Style): + """ + Pygments version of the "gruvbox" Light vim theme. + """ + + name = 'gruvbox-light' + + background_color = '#fbf1c7' + highlight_color = '#3c3836' + + styles = { + Comment: 'italic #928374', + Comment.PreProc: '#427b58', + Comment.Special: 'bold italic #3c3836', + + Keyword: '#9d0006', + Operator.Word: '#9d0006', + + String: '#79740e', + String.Escape: '#af3a03', + + Number: '#8f3f71', + + Name.Builtin: '#af3a03', + Name.Variable: '#076678', + Name.Constant: '#8f3f71', + Name.Class: '#427b58', + Name.Function: '#427b58', + Name.Namespace: '#427b58', + Name.Exception: '#9d0006', + Name.Tag: '#427b58', + Name.Attribute: '#b57614', + Name.Decorator: '#9d0006', + + Generic.Heading: 'bold #3c3836', + Generic.Subheading: 'underline #3c3836', + Generic.Deleted: 'bg:#9d0006 #fbf1c7', + Generic.Inserted: 'bg:#79740e #fbf1c7', + Generic.Error: '#9d0006', + Generic.Emph: 'italic', + Generic.Strong: 'bold', + Generic.Prompt: '#7c6f64', + Generic.Output: '#32302f', + Generic.Traceback: '#9d0006', + + Error: 'bg:#9d0006 #fbf1c7' + } diff --git a/.venv/lib/python3.12/site-packages/pygments/styles/igor.py b/.venv/lib/python3.12/site-packages/pygments/styles/igor.py new file mode 100644 index 0000000000000000000000000000000000000000..3958b000679a8dfa639a816d20b3bf1a6cb06b93 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/pygments/styles/igor.py @@ -0,0 +1,32 @@ +""" + pygments.styles.igor + ~~~~~~~~~~~~~~~~~~~~ + + Igor Pro default style. + + :copyright: Copyright 2006-present by the Pygments team, see AUTHORS. + :license: BSD, see LICENSE for details. +""" + +from pygments.style import Style +from pygments.token import Keyword, Name, Comment, String + + +__all__ = ['IgorStyle'] + + +class IgorStyle(Style): + """ + Pygments version of the official colors for Igor Pro procedures. + """ + + name = 'igor' + + styles = { + Comment: 'italic #FF0000', + Keyword: '#0000FF', + Name.Function: '#C34E00', + Name.Decorator: '#CC00A3', + Name.Class: '#007575', + String: '#009C00' + } diff --git a/.venv/lib/python3.12/site-packages/pygments/styles/inkpot.py b/.venv/lib/python3.12/site-packages/pygments/styles/inkpot.py new file mode 100644 index 0000000000000000000000000000000000000000..a5dd5298215c7f1b7d86d0077d359f87585cc868 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/pygments/styles/inkpot.py @@ -0,0 +1,72 @@ +""" + pygments.styles.inkpot + ~~~~~~~~~~~~~~~~~~~~~~ + + A highlighting style for Pygments, inspired by the Inkpot theme for VIM. + + :copyright: Copyright 2006-present by the Pygments team, see AUTHORS. + :license: BSD, see LICENSE for details. +""" + +from pygments.style import Style +from pygments.token import Text, Other, Keyword, Name, Comment, String, \ + Error, Number, Operator, Generic, Whitespace, Punctuation + + +__all__ = ['InkPotStyle'] + + +class InkPotStyle(Style): + name = 'inkpot' + + background_color = "#1e1e27" + + styles = { + Text: "#cfbfad", + Other: "#cfbfad", + Whitespace: "#434357", + Comment: "#cd8b00", + Comment.Preproc: "#409090", + Comment.PreprocFile: "bg:#404040 #ffcd8b", + Comment.Special: "#808bed", + + Keyword: "#808bed", + Keyword.Pseudo: "nobold", + Keyword.Type: "#ff8bff", + + Operator: "#666666", + + Punctuation: "#cfbfad", + + Name: "#cfbfad", + Name.Attribute: "#cfbfad", + Name.Builtin.Pseudo: '#ffff00', + Name.Builtin: "#808bed", + Name.Class: "#ff8bff", + Name.Constant: "#409090", + Name.Decorator: "#409090", + Name.Exception: "#ff0000", + Name.Function: "#c080d0", + Name.Label: "#808bed", + Name.Namespace: "#ff0000", + Name.Variable: "#cfbfad", + + String: "bg:#404040 #ffcd8b", + String.Doc: "#808bed", + + Number: "#f0ad6d", + + Generic.Heading: "bold #000080", + Generic.Subheading: "bold #800080", + Generic.Deleted: "#A00000", + Generic.Inserted: "#00A000", + Generic.Error: "#FF0000", + Generic.Emph: "italic", + Generic.Strong: "bold", + Generic.EmphStrong: "bold italic", + Generic.Prompt: "bold #000080", + Generic.Output: "#888", + Generic.Traceback: "#04D", + + Error: "bg:#6e2e2e #ffffff" + } diff --git a/.venv/lib/python3.12/site-packages/pygments/styles/lightbulb.py b/.venv/lib/python3.12/site-packages/pygments/styles/lightbulb.py new file mode 100644 index 0000000000000000000000000000000000000000..faba6eed95b4602bcf0487b48d5979f65d1a0901 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/pygments/styles/lightbulb.py @@ -0,0 +1,110 @@ +""" + pygments.styles.lightbulb + ~~~~~~~~~~~~~~~~~~~~~~~~~ + + A minimal dark theme based on the Lightbulb theme for VSCode. + + :copyright: Copyright 2006-present by the Pygments team, see AUTHORS. + :license: BSD, see LICENSE for details. +""" + +from pygments.style import Style +from pygments.token import ( + Comment, + Error, + Generic, + Keyword, + Literal, + Name, + Number, + Operator, + Punctuation, + String, + Token, +) + + +__all__ = ['LightbulbStyle'] + + +COLORS = { + "bg": "#1d2331", + "blue_1": "#73D0FF", + "gray_1": "#7e8aa1", + "gray_2": "#3c4354", + "gray_3": "#6e7681", + "red_1": "#f88f7f", + "red_2": "#3d1e20", + "orange_1": "#FFAD66", + "orange_2": "#F29E74", + "yellow_1": "#FFD173", + "white": "#d4d2c8", + "magenta_1": "#DFBFFF", + "green_1": "#D5FF80", + "green_2": "#19362c", + "cyan_1": "#95E6CB", +} + + +class LightbulbStyle(Style): + """ + A minimal dark theme based on the Lightbulb theme for VSCode. + """ + + name = 'lightbulb' + + background_color = COLORS['bg'] + highlight_color = COLORS['gray_3'] + + line_number_color = COLORS['gray_2'] + line_number_special_color = COLORS['gray_2'] + + styles = { + Comment: COLORS["gray_1"], + Comment.Hashbang: "italic " + COLORS['red_1'], + Comment.Preproc: "bold " + COLORS['orange_1'], + Comment.Special: "italic " + COLORS['gray_1'], + Error: COLORS['red_1'], + Generic.Deleted: f"bg:{COLORS['red_2']} #f88f7f", + Generic.Emph: "italic", + Generic.Error: "#f88f7f", + Generic.Inserted: f"bg:{COLORS['green_2']} #6ad4af", + Generic.Output: COLORS['gray_1'], + Generic.Strong: "bold", + Generic.Traceback: COLORS['red_1'], + Keyword: COLORS['orange_1'], + Keyword.Constant: COLORS['orange_1'], + Keyword.Declaration: COLORS['orange_1'], + Keyword.Namespace: COLORS['orange_1'], + Keyword.Reserved: COLORS['orange_1'], + Keyword.Type: COLORS['blue_1'], + Literal: COLORS['green_1'], + Name: COLORS['white'], + Name.Attribute: COLORS['yellow_1'], + Name.Builtin: COLORS['yellow_1'], + Name.Builtin.Pseudo: "#5CCFE6", + Name.Class: COLORS['blue_1'], + Name.Constant: COLORS['yellow_1'], + Name.Decorator: "bold italic " + COLORS['gray_1'], + Name.Entity: COLORS['cyan_1'], + Name.Exception: COLORS['blue_1'], + Name.Function: COLORS['yellow_1'], + Name.Function.Magic: COLORS['yellow_1'], + Name.Other: COLORS['white'], + Name.Property: COLORS['yellow_1'], + Name.Tag: "#5CCFE6", + Name.Variable: COLORS['white'], + Number: COLORS['magenta_1'], + Operator: COLORS['orange_1'], + Operator.Word: COLORS['orange_1'], + Punctuation: COLORS['white'], + String: COLORS['green_1'], + String.Affix: COLORS['orange_2'], + String.Doc: COLORS['gray_1'], + String.Escape: COLORS['cyan_1'], + String.Interpol: COLORS['cyan_1'], + String.Other: COLORS['cyan_1'], + String.Regex: COLORS['cyan_1'], + String.Symbol: COLORS['magenta_1'], + Token: COLORS['white'], + } diff --git a/.venv/lib/python3.12/site-packages/pygments/styles/lilypond.py b/.venv/lib/python3.12/site-packages/pygments/styles/lilypond.py new file mode 100644 index 0000000000000000000000000000000000000000..113809875b014db2a6efc770f9d888a55143a6c7 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/pygments/styles/lilypond.py @@ -0,0 +1,62 @@ +""" + pygments.styles.lilypond + ~~~~~~~~~~~~~~~~~~~~~~~~ + + LilyPond-specific style. + + :copyright: Copyright 2006-present by the Pygments team, see AUTHORS. + :license: BSD, see LICENSE for details. +""" + +from pygments.style import Style +from pygments.token import Token + + +__all__ = ['LilyPondStyle'] + + +class LilyPondStyle(Style): + """ + Style for the LilyPond language. + + .. versionadded:: 2.11 + """ + + name = 'lilypond' + + # Don't show it in the gallery, it's intended for LilyPond + # input only and doesn't show good output on Python code. + web_style_gallery_exclude = True + + styles = { + Token.Text: "", + Token.Keyword: "bold", + Token.Comment: "italic #A3AAB2", + Token.String: "#AB0909", + Token.String.Escape: "#C46C6C", + Token.String.Symbol: "noinherit", + Token.Pitch: "", #"#911520", + Token.Number: "#976806", # includes durations + # A bare 11 is not distinguishable from a number, so we highlight + # the same. + Token.ChordModifier: "#976806", + Token.Name.Lvalue: "#08547A", + Token.Name.BackslashReference: "#08547A", + Token.Name.Builtin.MusicCommand: "bold #08547A", + Token.Name.Builtin.PaperVariable: "bold #6C5A05", + Token.Name.Builtin.HeaderVariable: "bold #6C5A05", + Token.Name.Builtin.MusicFunction: "bold #08547A", + Token.Name.Builtin.Clef: "bold #08547A", + Token.Name.Builtin.Scale: "bold #08547A", + Token.Name.Builtin.RepeatType: "#08547A", + Token.Name.Builtin.Dynamic: "#68175A", + Token.Name.Builtin.Articulation: "#68175A", + Token.Name.Builtin.SchemeFunction: "bold #A83401", + Token.Name.Builtin.SchemeBuiltin: "bold", + Token.Name.Builtin.MarkupCommand: "bold #831E71", + Token.Name.Builtin.Context: "bold #038B8B", + Token.Name.Builtin.ContextProperty: "#038B8B", + Token.Name.Builtin.Grob: "bold #0C7441", + Token.Name.Builtin.GrobProperty: "#0C7441", + Token.Name.Builtin.Translator: "bold #6200A4", + } diff --git a/.venv/lib/python3.12/site-packages/pygments/styles/lovelace.py b/.venv/lib/python3.12/site-packages/pygments/styles/lovelace.py new file mode 100644 index 0000000000000000000000000000000000000000..3158e83ab8a9eb4637514e8998519e972d9b1179 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/pygments/styles/lovelace.py @@ -0,0 +1,100 @@ +""" + pygments.styles.lovelace + ~~~~~~~~~~~~~~~~~~~~~~~~ + + Lovelace by Miikka Salminen + + Pygments style by Miikka Salminen (https://github.com/miikkas) + A desaturated, somewhat subdued style created for the Lovelace interactive + learning environment. + + :copyright: Copyright 2006-present by the Pygments team, see AUTHORS. + :license: BSD, see LICENSE for details. +""" + +from pygments.style import Style +from pygments.token import Keyword, Name, Comment, String, Error, \ + Number, Operator, Punctuation, Generic, Whitespace + + +__all__ = ['LovelaceStyle'] + + +class LovelaceStyle(Style): + """ + The style used in Lovelace interactive learning environment. Tries to avoid + the "angry fruit salad" effect with desaturated and dim colours. + """ + name = 'lovelace' + + _KW_BLUE = '#2838b0' + _NAME_GREEN = '#388038' + _DOC_ORANGE = '#b85820' + _OW_PURPLE = '#a848a8' + _FUN_BROWN = '#785840' + _STR_RED = '#b83838' + _CLS_CYAN = '#287088' + _ESCAPE_LIME = '#709030' + _LABEL_CYAN = '#289870' + _EXCEPT_YELLOW = '#908828' + + styles = { + Whitespace: '#a89028', + Comment: 'italic #888888', + Comment.Hashbang: _CLS_CYAN, + Comment.Multiline: '#888888', + Comment.Preproc: 'noitalic '+_LABEL_CYAN, + + Keyword: _KW_BLUE, + Keyword.Constant: 'italic #444444', + Keyword.Declaration: 'italic', + Keyword.Type: 'italic', + + Operator: '#666666', + Operator.Word: _OW_PURPLE, + + Punctuation: '#888888', + + Name.Attribute: _NAME_GREEN, + Name.Builtin: _NAME_GREEN, + Name.Builtin.Pseudo: 'italic', + Name.Class: _CLS_CYAN, + Name.Constant: _DOC_ORANGE, + Name.Decorator: _CLS_CYAN, + Name.Entity: _ESCAPE_LIME, + Name.Exception: _EXCEPT_YELLOW, + Name.Function: _FUN_BROWN, + Name.Function.Magic: _DOC_ORANGE, + Name.Label: _LABEL_CYAN, + Name.Namespace: _LABEL_CYAN, + Name.Tag: _KW_BLUE, + Name.Variable: '#b04040', + Name.Variable.Global:_EXCEPT_YELLOW, + Name.Variable.Magic: _DOC_ORANGE, + + String: _STR_RED, + String.Affix: '#444444', + String.Char: _OW_PURPLE, + String.Delimiter: _DOC_ORANGE, + String.Doc: 'italic '+_DOC_ORANGE, + String.Escape: _ESCAPE_LIME, + String.Interpol: 'underline', + String.Other: _OW_PURPLE, + String.Regex: _OW_PURPLE, + + Number: '#444444', + + Generic.Deleted: '#c02828', + Generic.Emph: 'italic', + Generic.Error: '#c02828', + Generic.Heading: '#666666', + Generic.Subheading: '#444444', + Generic.Inserted: _NAME_GREEN, + Generic.Output: '#666666', + Generic.Prompt: '#444444', + Generic.Strong: 'bold', + Generic.EmphStrong: 'bold italic', + Generic.Traceback: _KW_BLUE, + + Error: 'bg:'+_OW_PURPLE, + } diff --git a/.venv/lib/python3.12/site-packages/pygments/styles/manni.py b/.venv/lib/python3.12/site-packages/pygments/styles/manni.py new file mode 100644 index 0000000000000000000000000000000000000000..e57b7bab778d0e9abfb90c3959b21d67eab9fce8 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/pygments/styles/manni.py @@ -0,0 +1,79 @@ +""" + pygments.styles.manni + ~~~~~~~~~~~~~~~~~~~~~ + + A colorful style, inspired by the terminal highlighting style. + + This is a port of the style used in the `php port`_ of pygments + by Manni. The style is called 'default' there. + + :copyright: Copyright 2006-present by the Pygments team, see AUTHORS. + :license: BSD, see LICENSE for details. +""" + +from pygments.style import Style +from pygments.token import Keyword, Name, Comment, String, Error, \ + Number, Operator, Generic, Whitespace + + +__all__ = ['ManniStyle'] + + +class ManniStyle(Style): + """ + A colorful style, inspired by the terminal highlighting style. + """ + name = 'manni' + + background_color = '#f0f3f3' + + styles = { + Whitespace: '#bbbbbb', + Comment: 'italic #0099FF', + Comment.Preproc: 'noitalic #009999', + Comment.Special: 'bold', + + Keyword: 'bold #006699', + Keyword.Pseudo: 'nobold', + Keyword.Type: '#007788', + + Operator: '#555555', + Operator.Word: 'bold #000000', + + Name.Builtin: '#336666', + Name.Function: '#CC00FF', + Name.Class: 'bold #00AA88', + Name.Namespace: 'bold #00CCFF', + Name.Exception: 'bold #CC0000', + Name.Variable: '#003333', + Name.Constant: '#336600', + Name.Label: '#9999FF', + Name.Entity: 'bold #999999', + Name.Attribute: '#330099', + Name.Tag: 'bold #330099', + Name.Decorator: '#9999FF', + + String: '#CC3300', + String.Doc: 'italic', + String.Interpol: '#AA0000', + String.Escape: 'bold #CC3300', + String.Regex: '#33AAAA', + String.Symbol: '#FFCC33', + String.Other: '#CC3300', + + Number: '#FF6600', + + Generic.Heading: 'bold #003300', + Generic.Subheading: 'bold #003300', + Generic.Deleted: 'border:#CC0000 bg:#FFCCCC', + Generic.Inserted: 'border:#00CC00 bg:#CCFFCC', + Generic.Error: '#FF0000', + Generic.Emph: 'italic', + Generic.Strong: 'bold', + Generic.EmphStrong: 'bold italic', + Generic.Prompt: 'bold #000099', + Generic.Output: '#AAAAAA', + Generic.Traceback: '#99CC66', + + Error: 'bg:#FFAAAA #AA0000' + } diff --git a/.venv/lib/python3.12/site-packages/pygments/styles/material.py b/.venv/lib/python3.12/site-packages/pygments/styles/material.py new file mode 100644 index 0000000000000000000000000000000000000000..27c0f30403c594c3b958e971f439a57348030876 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/pygments/styles/material.py @@ -0,0 +1,124 @@ +""" + pygments.styles.material + ~~~~~~~~~~~~~~~~~~~~~~~~ + + Mimic the Material theme color scheme. + + https://github.com/material-theme/vsc-material-theme + + :copyright: Copyright 2006-present by the Pygments team, see AUTHORS. + :license: BSD, see LICENSE for details. +""" + +from pygments.style import Style +from pygments.token import Keyword, Name, Comment, String, Escape, \ + Error, Text, Number, Operator, Generic, Punctuation, Literal + + +__all__ = ['MaterialStyle'] + + +class MaterialStyle(Style): + """ + This style mimics the Material Theme color scheme. + """ + name = 'material' + + dark_teal = '#263238' + white = '#FFFFFF' + black = '#000000' + red = '#FF5370' + orange = '#F78C6C' + yellow = '#FFCB6B' + green = '#C3E88D' + cyan = '#89DDFF' + blue = '#82AAFF' + paleblue = '#B2CCD6' + purple = '#C792EA' + brown = '#C17E70' + pink = '#F07178' + violet = '#BB80B3' + foreground = '#EEFFFF' + faded = '#546E7A' + + background_color = dark_teal + highlight_color = '#2C3B41' + line_number_color = '#37474F' + line_number_background_color = dark_teal + line_number_special_color = '#607A86' + line_number_special_background_color = dark_teal + + styles = { + Text: foreground, + Escape: cyan, + Error: red, + + Keyword: violet, + Keyword.Constant: cyan, + Keyword.Declaration: violet, + Keyword.Namespace: 'italic ' + cyan, + Keyword.Pseudo: cyan, + Keyword.Type: violet, + + Name: foreground, + Name.Attribute: violet, + Name.Builtin: blue, + Name.Builtin.Pseudo: cyan, + Name.Class: yellow, + Name.Constant: foreground, + Name.Decorator: blue, + Name.Entity: cyan, + Name.Exception: yellow, + Name.Function: blue, + Name.Function.Magic: blue, + Name.Label: blue, + Name.Property: yellow, + Name.Namespace: yellow, + Name.Other: foreground, + Name.Tag: red, + Name.Variable: cyan, + Name.Variable.Class: cyan, + Name.Variable.Global: cyan, + Name.Variable.Instance: cyan, + Name.Variable.Magic: blue, + + Literal: green, + Literal.Date: green, + + String: green, + String.Affix: violet, + String.Backtick: green, + String.Char: green, + String.Delimiter: foreground, + String.Doc: 'italic ' + faded, + String.Double: green, + String.Escape: foreground, + String.Heredoc: green, + String.Interpol: cyan, + String.Other: green, + String.Regex: cyan, + String.Single: green, + String.Symbol: cyan, + + Number: orange, + + Operator: cyan, + Operator.Word: 'italic ' + cyan, + + Punctuation: cyan, + + Comment: 'italic ' + faded, + + Generic: foreground, + Generic.Deleted: red, + Generic.Emph: cyan, + Generic.Error: red, + Generic.Heading: green, + Generic.Inserted: green, + Generic.Output: faded, + Generic.Prompt: yellow, + Generic.Strong: red, + Generic.EmphStrong: yellow, + Generic.Subheading: cyan, + Generic.Traceback: red, + } diff --git a/.venv/lib/python3.12/site-packages/pygments/styles/monokai.py b/.venv/lib/python3.12/site-packages/pygments/styles/monokai.py new file mode 100644 index 0000000000000000000000000000000000000000..dc9b381b15d8246a771db4fdc56b7c90b4b1a77b --- /dev/null +++ b/.venv/lib/python3.12/site-packages/pygments/styles/monokai.py @@ -0,0 +1,112 @@ +""" + pygments.styles.monokai + ~~~~~~~~~~~~~~~~~~~~~~~ + + Mimic the Monokai color scheme. Based on tango.py. + + http://www.monokai.nl/blog/2006/07/15/textmate-color-theme/ + + :copyright: Copyright 2006-present by the Pygments team, see AUTHORS. + :license: BSD, see LICENSE for details. +""" + +from pygments.style import Style +from pygments.token import Keyword, Name, Comment, String, Error, Token, \ + Number, Operator, Generic, Whitespace, Punctuation, Other, Literal + + +__all__ = ['MonokaiStyle'] + + +class MonokaiStyle(Style): + """ + This style mimics the Monokai color scheme. + """ + name = 'monokai' + + background_color = "#272822" + highlight_color = "#49483e" + + styles = { + # No corresponding class for the following: + Token: "#f8f8f2", # class: '' + Whitespace: "", # class: 'w' + Error: "#ed007e bg:#1e0010", # class: 'err' + Other: "", # class 'x' + + Comment: "#959077", # class: 'c' + Comment.Multiline: "", # class: 'cm' + Comment.Preproc: "", # class: 'cp' + Comment.Single: "", # class: 'c1' + Comment.Special: "", # class: 'cs' + + Keyword: "#66d9ef", # class: 'k' + Keyword.Constant: "", # class: 'kc' + Keyword.Declaration: "", # class: 'kd' + Keyword.Namespace: "#ff4689", # class: 'kn' + Keyword.Pseudo: "", # class: 'kp' + Keyword.Reserved: "", # class: 'kr' + Keyword.Type: "", # class: 'kt' + + Operator: "#ff4689", # class: 'o' + Operator.Word: "", # class: 'ow' - like keywords + + Punctuation: "#f8f8f2", # class: 'p' + + Name: "#f8f8f2", # class: 'n' + Name.Attribute: "#a6e22e", # class: 'na' - to be revised + Name.Builtin: "#a6e22e", # class: 'nb' + Name.Builtin.Pseudo: "", # class: 'bp' + Name.Class: "#a6e22e", # class: 'nc' - to be revised + Name.Constant: "#66d9ef", # class: 'no' - to be revised + Name.Decorator: "#a6e22e", # class: 'nd' - to be revised + Name.Entity: "", # class: 'ni' + Name.Exception: "#a6e22e", # class: 'ne' + Name.Function: "#a6e22e", # class: 'nf' + Name.Property: "", # class: 'py' + Name.Label: "", # class: 'nl' + Name.Namespace: "", # class: 'nn' - to be revised + Name.Other: "#a6e22e", # class: 'nx' + Name.Tag: "#ff4689", # class: 'nt' - like a keyword + Name.Variable: "", # class: 'nv' - to be revised + Name.Variable.Class: "", # class: 'vc' - to be revised + Name.Variable.Global: "", # class: 'vg' - to be revised + Name.Variable.Instance: "", # class: 'vi' - to be revised + + Number: "#ae81ff", # class: 'm' + Number.Float: "", # class: 'mf' + Number.Hex: "", # class: 'mh' + Number.Integer: "", # class: 'mi' + Number.Integer.Long: "", # class: 'il' + Number.Oct: "", # class: 'mo' + + Literal: "#ae81ff", # class: 'l' + Literal.Date: "#e6db74", # class: 'ld' + + String: "#e6db74", # class: 's' + String.Backtick: "", # class: 'sb' + String.Char: "", # class: 'sc' + String.Doc: "", # class: 'sd' - like a comment + String.Double: "", # class: 's2' + String.Escape: "#ae81ff", # class: 'se' + String.Heredoc: "", # class: 'sh' + String.Interpol: "", # class: 'si' + String.Other: "", # class: 'sx' + String.Regex: "", # class: 'sr' + String.Single: "", # class: 's1' + String.Symbol: "", # class: 'ss' + + + Generic: "", # class: 'g' + Generic.Deleted: "#ff4689", # class: 'gd', + Generic.Emph: "italic", # class: 'ge' + Generic.Error: "#ff4689", # class: 'gr' + Generic.Heading: "", # class: 'gh' + Generic.Inserted: "#a6e22e", # class: 'gi' + Generic.Output: "#66d9ef", # class: 'go' + Generic.Prompt: "bold #ff4689", # class: 'gp' + Generic.Strong: "bold", # class: 'gs' + Generic.EmphStrong: "bold italic", # class: 'ges' + Generic.Subheading: "#959077", # class: 'gu' + Generic.Traceback: "#66d9ef", # class: 'gt' + } diff --git a/.venv/lib/python3.12/site-packages/pygments/styles/murphy.py b/.venv/lib/python3.12/site-packages/pygments/styles/murphy.py new file mode 100644 index 0000000000000000000000000000000000000000..64af6e4bfc7207cd7c9ccdcba4b8cd4647d64b75 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/pygments/styles/murphy.py @@ -0,0 +1,82 @@ +""" + pygments.styles.murphy + ~~~~~~~~~~~~~~~~~~~~~~ + + Murphy's style from CodeRay. + + :copyright: Copyright 2006-present by the Pygments team, see AUTHORS. + :license: BSD, see LICENSE for details. +""" + +from pygments.style import Style +from pygments.token import Keyword, Name, Comment, String, Error, \ + Number, Operator, Generic, Whitespace + + +__all__ = ['MurphyStyle'] + + +class MurphyStyle(Style): + """ + Murphy's style from CodeRay. + """ + name = 'murphy' + + styles = { + Whitespace: "#bbbbbb", + Comment: "#666 italic", + Comment.Preproc: "#579 noitalic", + Comment.Special: "#c00 bold", + + Keyword: "bold #289", + Keyword.Pseudo: "#08f", + Keyword.Type: "#66f", + + Operator: "#333", + Operator.Word: "bold #000", + + Name.Builtin: "#072", + Name.Function: "bold #5ed", + Name.Class: "bold #e9e", + Name.Namespace: "bold #0e84b5", + Name.Exception: "bold #F00", + Name.Variable: "#036", + Name.Variable.Instance: "#aaf", + Name.Variable.Class: "#ccf", + Name.Variable.Global: "#f84", + Name.Constant: "bold #5ed", + Name.Label: "bold #970", + Name.Entity: "#800", + Name.Attribute: "#007", + Name.Tag: "#070", + Name.Decorator: "bold #555", + + String: "bg:#e0e0ff", + String.Char: "#88F bg:", + String.Doc: "#D42 bg:", + String.Interpol: "bg:#eee", + String.Escape: "bold #666", + String.Regex: "bg:#e0e0ff #000", + String.Symbol: "#fc8 bg:", + String.Other: "#f88", + + Number: "bold #60E", + Number.Integer: "bold #66f", + Number.Float: "bold #60E", + Number.Hex: "bold #058", + Number.Oct: "bold #40E", + + Generic.Heading: "bold #000080", + Generic.Subheading: "bold #800080", + Generic.Deleted: "#A00000", + Generic.Inserted: "#00A000", + Generic.Error: "#FF0000", + Generic.Emph: "italic", + Generic.Strong: "bold", + Generic.EmphStrong: "bold italic", + Generic.Prompt: "bold #c65d09", + Generic.Output: "#888", + Generic.Traceback: "#04D", + + Error: "#F00 bg:#FAA" + } diff --git a/.venv/lib/python3.12/site-packages/pygments/styles/native.py b/.venv/lib/python3.12/site-packages/pygments/styles/native.py new file mode 100644 index 0000000000000000000000000000000000000000..ae47e3e6b3880a268ecbefd58141bceccb07048d --- /dev/null +++ b/.venv/lib/python3.12/site-packages/pygments/styles/native.py @@ -0,0 +1,70 @@ +""" + pygments.styles.native + ~~~~~~~~~~~~~~~~~~~~~~ + + pygments version of my "native" vim theme. + + :copyright: Copyright 2006-present by the Pygments team, see AUTHORS. + :license: BSD, see LICENSE for details. +""" + +from pygments.style import Style +from pygments.token import Keyword, Name, Comment, String, Error, \ + Number, Operator, Generic, Token, Whitespace + + +__all__ = ['NativeStyle'] + + +class NativeStyle(Style): + """ + Pygments version of the "native" vim theme. + """ + name = 'native' + + background_color = '#202020' + highlight_color = '#404040' + line_number_color = '#aaaaaa' + + styles = { + Token: '#d0d0d0', + Whitespace: '#666666', + + Comment: 'italic #ababab', + Comment.Preproc: 'noitalic bold #ff3a3a', + Comment.Special: 'noitalic bold #e50808 bg:#520000', + + Keyword: 'bold #6ebf26', + Keyword.Pseudo: 'nobold', + Operator.Word: 'bold #6ebf26', + + String: '#ed9d13', + String.Other: '#ffa500', + + Number: '#51b2fd', + + Name.Builtin: '#2fbccd', + Name.Variable: '#40ffff', + Name.Constant: '#40ffff', + Name.Class: 'underline #71adff', + Name.Function: '#71adff', + Name.Namespace: 'underline #71adff', + Name.Exception: '#bbbbbb', + Name.Tag: 'bold #6ebf26', + Name.Attribute: '#bbbbbb', + Name.Decorator: '#ffa500', + + Generic.Heading: 'bold #ffffff', + Generic.Subheading: 'underline #ffffff', + Generic.Deleted: '#ff3a3a', + Generic.Inserted: '#589819', + Generic.Error: '#ff3a3a', + Generic.Emph: 'italic', + Generic.Strong: 'bold', + Generic.EmphStrong: 'bold italic', + Generic.Prompt: '#aaaaaa', + Generic.Output: '#cccccc', + Generic.Traceback: '#ff3a3a', + + Error: 'bg:#e3d2d2 #a61717' + } diff --git a/.venv/lib/python3.12/site-packages/pygments/styles/night_owl.py b/.venv/lib/python3.12/site-packages/pygments/styles/night_owl.py new file mode 100644 index 0000000000000000000000000000000000000000..20be6986ea329e9e22864a7e265046d1f2c8f135 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/pygments/styles/night_owl.py @@ -0,0 +1,143 @@ +""" + pygments.styles.night_owl + ~~~~~~~~~~~~~~~~~~~~~~~~~ + + Pygments version of the `Night Owl` theme by Sarah Drasner. + Based on https://github.com/sdras/night-owl-vscode-theme. + + :copyright: Copyright 2006-present by the Pygments team, see AUTHORS. + :license: BSD, see LICENSE for details. +""" + +from pygments.style import Style +from pygments.token import Comment, Error, Generic, Keyword, Name, Number, \ + Operator, Punctuation, String, Text, Token, Whitespace + + +__all__ = ['NightOwlStyle'] + + +# Night Owl color palette +background = '#011627' +foreground = '#d6deeb' +selection = '#1d3b53' +cyan = '#7fdbca' +blue = '#82aaff' +purple = '#c792ea' +green = '#addb67' +yellow = '#ecc48d' +orange = '#f78c6c' +red = '#ef5350' +comment = '#637777' +pink = '#ff869a' + + +class NightOwlStyle(Style): + """ + Night Owl theme by Sarah Drasner. + + A theme for the night owls amongst us. Fine-tuned for those of us who + like to code late into the night. Color choices have also taken into + consideration what is accessible to those with color blindness and in + low-light circumstances. + + Based on the VS Code Night Owl theme: + https://github.com/sdras/night-owl-vscode-theme + + .. versionadded:: 2.21 + """ + + name = 'night-owl' + + background_color = background + highlight_color = selection + line_number_color = comment + line_number_background_color = background + line_number_special_color = foreground + line_number_special_background_color = selection + + styles = { + Token: foreground, + Whitespace: foreground, + Text: foreground, + + # Comments + Comment: 'italic ' + comment, + Comment.Multiline: 'italic ' + comment, + Comment.Preproc: cyan, + Comment.Single: 'italic ' + comment, + Comment.Special: 'italic ' + comment, + + # Keywords + Keyword: 'italic ' + purple, + Keyword.Constant: 'italic ' + purple, + Keyword.Declaration: 'italic ' + purple, + Keyword.Namespace: 'italic ' + purple, + Keyword.Reserved: 'italic ' + purple, + Keyword.Type: cyan, + + # Names + Name: foreground, + Name.Attribute: yellow, + Name.Builtin: cyan, + Name.Builtin.Pseudo: 'italic ' + blue, + Name.Class: yellow, + Name.Constant: orange, + Name.Decorator: blue, + Name.Entity: orange, + Name.Exception: red, + Name.Function: blue, + Name.Function.Magic: cyan, + Name.Label: foreground, + Name.Namespace: foreground, + Name.Other: foreground, + Name.Property: cyan, + Name.Tag: pink, + Name.Variable: foreground, + Name.Variable.Class: yellow, + Name.Variable.Global: orange, + Name.Variable.Instance: yellow, + + # Literals + Number: orange, + Number.Float: orange, + Number.Hex: orange, + Number.Integer: orange, + Number.Oct: orange, + + # Strings + String: green, + String.Affix: cyan, + String.Char: green, + String.Doc: 'italic ' + comment, + String.Escape: yellow, + String.Heredoc: green, + String.Interpol: cyan, + String.Other: green, + String.Regex: cyan, + String.Symbol: cyan, + + # Operators + Operator: cyan, + Operator.Word: 'italic ' + purple, + + # Punctuation + Punctuation: foreground, + + # Errors + Error: red, + + # Generic tokens (used by diffs, prompts, etc.) + Generic: foreground, + Generic.Deleted: red, + Generic.Emph: 'italic', + Generic.Error: red, + Generic.Heading: 'bold ' + blue, + Generic.Inserted: green, + Generic.Output: comment, + Generic.Prompt: 'bold ' + cyan, + Generic.Strong: 'bold', + Generic.EmphStrong: 'bold italic', + Generic.Subheading: 'bold ' + cyan, + Generic.Traceback: red, + } diff --git a/.venv/lib/python3.12/site-packages/pygments/styles/nord.py b/.venv/lib/python3.12/site-packages/pygments/styles/nord.py new file mode 100644 index 0000000000000000000000000000000000000000..7a3a9594169fc689ec04f3006a306eb024453465 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/pygments/styles/nord.py @@ -0,0 +1,156 @@ +""" + pygments.styles.nord + ~~~~~~~~~~~~~~~~~~~~ + + pygments version of the "nord" theme by Arctic Ice Studio + https://www.nordtheme.com/ + + :copyright: Copyright 2006-present by the Pygments team, see AUTHORS. + :license: BSD, see LICENSE for details. +""" + +from pygments.style import Style +from pygments.token import Keyword, Name, Comment, String, Error, Number, \ + Operator, Generic, Whitespace, Punctuation, Text, Token + + +__all__ = ['NordStyle', 'NordDarkerStyle'] + + +class NordStyle(Style): + """ + Pygments version of the "nord" theme by Arctic Ice Studio. + """ + name = 'nord' + + line_number_color = "#D8DEE9" + line_number_background_color = "#242933" + line_number_special_color = "#242933" + line_number_special_background_color = "#D8DEE9" + + background_color = "#2E3440" + highlight_color = "#3B4252" + + styles = { + Token: "#d8dee9", + + Whitespace: '#d8dee9', + Punctuation: '#eceff4', + + Comment: 'italic #616e87', + Comment.Preproc: '#5e81ac', + + Keyword: 'bold #81a1c1', + Keyword.Pseudo: 'nobold #81a1c1', + Keyword.Type: 'nobold #81a1c1', + + Operator: 'bold #81a1c1', + Operator.Word: 'bold #81a1c1', + + Name: '#d8dee9', + Name.Builtin: '#81a1c1', + Name.Function: '#88c0d0', + Name.Class: '#8fbcbb', + Name.Namespace: '#8fbcbb', + Name.Exception: '#bf616a', + Name.Variable: '#d8dee9', + Name.Constant: '#8fbcbb', + Name.Entity: '#d08770', + Name.Attribute: '#8fbcbb', + Name.Tag: '#81a1c1', + Name.Decorator: '#d08770', + + String: '#a3be8c', + String.Doc: '#616e87', + String.Interpol: '#a3be8c', + String.Escape: '#ebcb8b', + String.Regex: '#ebcb8b', + String.Symbol: '#a3be8c', + String.Other: '#a3be8c', + + Number: '#b48ead', + + Generic.Heading: 'bold #88c0d0', + Generic.Subheading: 'bold #88c0d0', + Generic.Deleted: '#bf616a', + Generic.Inserted: '#a3be8c', + Generic.Error: '#bf616a', + Generic.Emph: 'italic', + Generic.Strong: 'bold', + Generic.EmphStrong: 'bold italic', + Generic.Prompt: 'bold #616e88', + Generic.Output: '#d8dee9', + Generic.Traceback: '#bf616a', + + Error: '#bf616a', + Text: '#d8dee9', + } + + +class NordDarkerStyle(Style): + """ + Pygments version of a darker "nord" theme by Arctic Ice Studio + """ + name = 'nord-darker' + + line_number_color = "#D8DEE9" + line_number_background_color = "#242933" + line_number_special_color = "#242933" + line_number_special_background_color = "#D8DEE9" + + background_color = "#242933" + highlight_color = "#3B4252" + + styles = { + Token: "#d8dee9", + + Whitespace: '#d8dee9', + Punctuation: '#eceff4', + + Comment: 'italic #616e87', + Comment.Preproc: '#5e81ac', + + Keyword: 'bold #81a1c1', + Keyword.Pseudo: 'nobold #81a1c1', + Keyword.Type: 'nobold #81a1c1', + + Operator: 'bold #81a1c1', + Operator.Word: 'bold #81a1c1', + + Name: '#d8dee9', + Name.Builtin: '#81a1c1', + Name.Function: '#88c0d0', + Name.Class: '#8fbcbb', + Name.Namespace: '#8fbcbb', + Name.Exception: '#bf616a', + Name.Variable: '#d8dee9', + Name.Constant: '#8fbcbb', + Name.Entity: '#d08770', + Name.Attribute: '#8fbcbb', + Name.Tag: '#81a1c1', + Name.Decorator: '#d08770', + + String: '#a3be8c', + String.Doc: '#616e87', + String.Interpol: '#a3be8c', + String.Escape: '#ebcb8b', + String.Regex: '#ebcb8b', + String.Symbol: '#a3be8c', + String.Other: '#a3be8c', + + Number: '#b48ead', + + Generic.Heading: 'bold #88c0d0', + Generic.Subheading: 'bold #88c0d0', + Generic.Deleted: '#bf616a', + Generic.Inserted: '#a3be8c', + Generic.Error: '#bf616a', + Generic.Emph: 'italic', + Generic.Strong: 'bold', + Generic.Prompt: 'bold #616e88', + Generic.Output: '#d8dee9', + Generic.Traceback: '#bf616a', + + Error: '#bf616a', + Text: '#d8dee9', + } diff --git a/.venv/lib/python3.12/site-packages/pygments/styles/onedark.py b/.venv/lib/python3.12/site-packages/pygments/styles/onedark.py new file mode 100644 index 0000000000000000000000000000000000000000..cc341f63bae10bd68deba2c289fae52dfeffbf8f --- /dev/null +++ b/.venv/lib/python3.12/site-packages/pygments/styles/onedark.py @@ -0,0 +1,73 @@ +""" + pygments.styles.onedark + ~~~~~~~~~~~~~~~~~~~~~~~ + + One Dark Theme for Pygments by Tobias Zoghaib (https://github.com/TobiZog) + + Inspired by one-dark-ui for the code editor Atom + (https://atom.io/themes/one-dark-ui). + + :copyright: Copyright 2006-present by the Pygments team, see AUTHORS. + :license: BSD, see LICENSE for details. +""" + +from pygments.style import Style +from pygments.token import Comment, Keyword, Name, Number, Operator, \ + Punctuation, String, Token, Generic + + +__all__ = ['OneDarkStyle'] + + +class OneDarkStyle(Style): + """ + Theme inspired by One Dark Pro for Atom. + + .. versionadded:: 2.11 + """ + name = 'one-dark' + + background_color = '#282C34' + + styles = { + Token: '#ABB2BF', + + Punctuation: '#ABB2BF', + Punctuation.Marker: '#ABB2BF', + + Keyword: '#C678DD', + Keyword.Constant: '#E5C07B', + Keyword.Declaration: '#C678DD', + Keyword.Namespace: '#C678DD', + Keyword.Reserved: '#C678DD', + Keyword.Type: '#E5C07B', + + Name: '#E06C75', + Name.Attribute: '#E06C75', + Name.Builtin: '#E5C07B', + Name.Class: '#E5C07B', + Name.Function: 'bold #61AFEF', + Name.Function.Magic: 'bold #56B6C2', + Name.Other: '#E06C75', + Name.Tag: '#E06C75', + Name.Decorator: '#61AFEF', + Name.Variable.Class: '', + + String: '#98C379', + + Number: '#D19A66', + + Operator: '#56B6C2', + + Comment: '#7F848E', + + Generic.Heading: 'bold #ABB2BF', + Generic.Subheading: 'bold #ABB2BF', + Generic.Deleted: '#E06C75', + Generic.Inserted: '#98C379', + Generic.Error: '#E06C75', + Generic.Emph: 'italic', + Generic.Strong: 'bold', + Generic.Output: '#E06C75', + Generic.Traceback: '#E06C75', + } diff --git a/.venv/lib/python3.12/site-packages/pygments/styles/paraiso_dark.py b/.venv/lib/python3.12/site-packages/pygments/styles/paraiso_dark.py new file mode 100644 index 0000000000000000000000000000000000000000..e460e434f6b3f562cd0a4ea9af55ba0c2f6ba717 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/pygments/styles/paraiso_dark.py @@ -0,0 +1,124 @@ +""" + pygments.styles.paraiso_dark + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + + Paraíso (Dark) by Jan T. Sott + + Pygments template by Jan T. Sott (https://github.com/idleberg) + Created with Base16 Builder by Chris Kempson + (https://github.com/chriskempson/base16-builder). + + :copyright: Copyright 2006-present by the Pygments team, see AUTHORS. + :license: BSD, see LICENSE for details. +""" + +from pygments.style import Style +from pygments.token import Keyword, Name, Comment, String, Error, Text, \ + Number, Operator, Generic, Whitespace, Punctuation, Other, Literal + + +__all__ = ['ParaisoDarkStyle'] + + +BACKGROUND = "#2f1e2e" +CURRENT_LINE = "#41323f" +SELECTION = "#4f424c" +FOREGROUND = "#e7e9db" +COMMENT = "#776e71" +RED = "#ef6155" +ORANGE = "#f99b15" +YELLOW = "#fec418" +GREEN = "#48b685" +AQUA = "#5bc4bf" +BLUE = "#06b6ef" +PURPLE = "#815ba4" + + +class ParaisoDarkStyle(Style): + name = 'paraiso-dark' + + background_color = BACKGROUND + highlight_color = SELECTION + + styles = { + # No corresponding class for the following: + Text: FOREGROUND, # class: '' + Whitespace: "", # class: 'w' + Error: RED, # class: 'err' + Other: "", # class 'x' + + Comment: COMMENT, # class: 'c' + Comment.Multiline: "", # class: 'cm' + Comment.Preproc: "", # class: 'cp' + Comment.Single: "", # class: 'c1' + Comment.Special: "", # class: 'cs' + + Keyword: PURPLE, # class: 'k' + Keyword.Constant: "", # class: 'kc' + Keyword.Declaration: "", # class: 'kd' + Keyword.Namespace: AQUA, # class: 'kn' + Keyword.Pseudo: "", # class: 'kp' + Keyword.Reserved: "", # class: 'kr' + Keyword.Type: YELLOW, # class: 'kt' + + Operator: AQUA, # class: 'o' + Operator.Word: "", # class: 'ow' - like keywords + + Punctuation: FOREGROUND, # class: 'p' + + Name: FOREGROUND, # class: 'n' + Name.Attribute: BLUE, # class: 'na' - to be revised + Name.Builtin: "", # class: 'nb' + Name.Builtin.Pseudo: "", # class: 'bp' + Name.Class: YELLOW, # class: 'nc' - to be revised + Name.Constant: RED, # class: 'no' - to be revised + Name.Decorator: AQUA, # class: 'nd' - to be revised + Name.Entity: "", # class: 'ni' + Name.Exception: RED, # class: 'ne' + Name.Function: BLUE, # class: 'nf' + Name.Property: "", # class: 'py' + Name.Label: "", # class: 'nl' + Name.Namespace: YELLOW, # class: 'nn' - to be revised + Name.Other: BLUE, # class: 'nx' + Name.Tag: AQUA, # class: 'nt' - like a keyword + Name.Variable: RED, # class: 'nv' - to be revised + Name.Variable.Class: "", # class: 'vc' - to be revised + Name.Variable.Global: "", # class: 'vg' - to be revised + Name.Variable.Instance: "", # class: 'vi' - to be revised + + Number: ORANGE, # class: 'm' + Number.Float: "", # class: 'mf' + Number.Hex: "", # class: 'mh' + Number.Integer: "", # class: 'mi' + Number.Integer.Long: "", # class: 'il' + Number.Oct: "", # class: 'mo' + + Literal: ORANGE, # class: 'l' + Literal.Date: GREEN, # class: 'ld' + + String: GREEN, # class: 's' + String.Backtick: "", # class: 'sb' + String.Char: FOREGROUND, # class: 'sc' + String.Doc: COMMENT, # class: 'sd' - like a comment + String.Double: "", # class: 's2' + String.Escape: ORANGE, # class: 'se' + String.Heredoc: "", # class: 'sh' + String.Interpol: ORANGE, # class: 'si' + String.Other: "", # class: 'sx' + String.Regex: "", # class: 'sr' + String.Single: "", # class: 's1' + String.Symbol: "", # class: 'ss' + + Generic: "", # class: 'g' + Generic.Deleted: RED, # class: 'gd', + Generic.Emph: "italic", # class: 'ge' + Generic.Error: "", # class: 'gr' + Generic.Heading: "bold " + FOREGROUND, # class: 'gh' + Generic.Inserted: GREEN, # class: 'gi' + Generic.Output: "", # class: 'go' + Generic.Prompt: "bold " + COMMENT, # class: 'gp' + Generic.Strong: "bold", # class: 'gs' + Generic.EmphStrong: "bold italic", # class: 'ges' + Generic.Subheading: "bold " + AQUA, # class: 'gu' + Generic.Traceback: "", # class: 'gt' + } diff --git a/.venv/lib/python3.12/site-packages/pygments/styles/paraiso_light.py b/.venv/lib/python3.12/site-packages/pygments/styles/paraiso_light.py new file mode 100644 index 0000000000000000000000000000000000000000..6ba861b95e893753f708bb916d5d08956b991ac6 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/pygments/styles/paraiso_light.py @@ -0,0 +1,124 @@ +""" + pygments.styles.paraiso_light + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + + Paraíso (Light) by Jan T. Sott + + Pygments template by Jan T. Sott (https://github.com/idleberg) + Created with Base16 Builder by Chris Kempson + (https://github.com/chriskempson/base16-builder). + + :copyright: Copyright 2006-present by the Pygments team, see AUTHORS. + :license: BSD, see LICENSE for details. +""" + +from pygments.style import Style +from pygments.token import Keyword, Name, Comment, String, Error, Text, \ + Number, Operator, Generic, Whitespace, Punctuation, Other, Literal + + +__all__ = ['ParaisoLightStyle'] + + +BACKGROUND = "#e7e9db" +CURRENT_LINE = "#b9b6b0" +SELECTION = "#a39e9b" +FOREGROUND = "#2f1e2e" +COMMENT = "#8d8687" +RED = "#ef6155" +ORANGE = "#f99b15" +YELLOW = "#fec418" +GREEN = "#48b685" +AQUA = "#5bc4bf" +BLUE = "#06b6ef" +PURPLE = "#815ba4" + + +class ParaisoLightStyle(Style): + name = 'paraiso-light' + + background_color = BACKGROUND + highlight_color = SELECTION + + styles = { + # No corresponding class for the following: + Text: FOREGROUND, # class: '' + Whitespace: "", # class: 'w' + Error: RED, # class: 'err' + Other: "", # class 'x' + + Comment: COMMENT, # class: 'c' + Comment.Multiline: "", # class: 'cm' + Comment.Preproc: "", # class: 'cp' + Comment.Single: "", # class: 'c1' + Comment.Special: "", # class: 'cs' + + Keyword: PURPLE, # class: 'k' + Keyword.Constant: "", # class: 'kc' + Keyword.Declaration: "", # class: 'kd' + Keyword.Namespace: AQUA, # class: 'kn' + Keyword.Pseudo: "", # class: 'kp' + Keyword.Reserved: "", # class: 'kr' + Keyword.Type: YELLOW, # class: 'kt' + + Operator: AQUA, # class: 'o' + Operator.Word: "", # class: 'ow' - like keywords + + Punctuation: FOREGROUND, # class: 'p' + + Name: FOREGROUND, # class: 'n' + Name.Attribute: BLUE, # class: 'na' - to be revised + Name.Builtin: "", # class: 'nb' + Name.Builtin.Pseudo: "", # class: 'bp' + Name.Class: YELLOW, # class: 'nc' - to be revised + Name.Constant: RED, # class: 'no' - to be revised + Name.Decorator: AQUA, # class: 'nd' - to be revised + Name.Entity: "", # class: 'ni' + Name.Exception: RED, # class: 'ne' + Name.Function: BLUE, # class: 'nf' + Name.Property: "", # class: 'py' + Name.Label: "", # class: 'nl' + Name.Namespace: YELLOW, # class: 'nn' - to be revised + Name.Other: BLUE, # class: 'nx' + Name.Tag: AQUA, # class: 'nt' - like a keyword + Name.Variable: RED, # class: 'nv' - to be revised + Name.Variable.Class: "", # class: 'vc' - to be revised + Name.Variable.Global: "", # class: 'vg' - to be revised + Name.Variable.Instance: "", # class: 'vi' - to be revised + + Number: ORANGE, # class: 'm' + Number.Float: "", # class: 'mf' + Number.Hex: "", # class: 'mh' + Number.Integer: "", # class: 'mi' + Number.Integer.Long: "", # class: 'il' + Number.Oct: "", # class: 'mo' + + Literal: ORANGE, # class: 'l' + Literal.Date: GREEN, # class: 'ld' + + String: GREEN, # class: 's' + String.Backtick: "", # class: 'sb' + String.Char: FOREGROUND, # class: 'sc' + String.Doc: COMMENT, # class: 'sd' - like a comment + String.Double: "", # class: 's2' + String.Escape: ORANGE, # class: 'se' + String.Heredoc: "", # class: 'sh' + String.Interpol: ORANGE, # class: 'si' + String.Other: "", # class: 'sx' + String.Regex: "", # class: 'sr' + String.Single: "", # class: 's1' + String.Symbol: "", # class: 'ss' + + Generic: "", # class: 'g' + Generic.Deleted: RED, # class: 'gd', + Generic.Emph: "italic", # class: 'ge' + Generic.Error: "", # class: 'gr' + Generic.Heading: "bold " + FOREGROUND, # class: 'gh' + Generic.Inserted: GREEN, # class: 'gi' + Generic.Output: "", # class: 'go' + Generic.Prompt: "bold " + COMMENT, # class: 'gp' + Generic.Strong: "bold", # class: 'gs' + Generic.EmphStrong: "bold italic", # class: 'ges' + Generic.Subheading: "bold " + AQUA, # class: 'gu' + Generic.Traceback: "", # class: 'gt' + } diff --git a/.venv/lib/python3.12/site-packages/pygments/styles/pastie.py b/.venv/lib/python3.12/site-packages/pygments/styles/pastie.py new file mode 100644 index 0000000000000000000000000000000000000000..5b493fa025173251668e08a43927714fdb293042 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/pygments/styles/pastie.py @@ -0,0 +1,78 @@ +""" + pygments.styles.pastie + ~~~~~~~~~~~~~~~~~~~~~~ + + Style similar to the `pastie`_ default style. + + .. _pastie: http://pastie.caboo.se/ + + :copyright: Copyright 2006-present by the Pygments team, see AUTHORS. + :license: BSD, see LICENSE for details. +""" + +from pygments.style import Style +from pygments.token import Keyword, Name, Comment, String, Error, \ + Number, Operator, Generic, Whitespace + + +__all__ = ['PastieStyle'] + + +class PastieStyle(Style): + """ + Style similar to the pastie default style. + """ + + name = 'pastie' + + styles = { + Whitespace: '#bbbbbb', + Comment: '#888888', + Comment.Preproc: 'bold #cc0000', + Comment.Special: 'bg:#fff0f0 bold #cc0000', + + String: 'bg:#fff0f0 #dd2200', + String.Regex: 'bg:#fff0ff #008800', + String.Other: 'bg:#f0fff0 #22bb22', + String.Symbol: '#aa6600', + String.Interpol: '#3333bb', + String.Escape: '#0044dd', + + Operator.Word: '#008800', + + Keyword: 'bold #008800', + Keyword.Pseudo: 'nobold', + Keyword.Type: '#888888', + + Name.Class: 'bold #bb0066', + Name.Exception: 'bold #bb0066', + Name.Function: 'bold #0066bb', + Name.Property: 'bold #336699', + Name.Namespace: 'bold #bb0066', + Name.Builtin: '#003388', + Name.Variable: '#336699', + Name.Variable.Class: '#336699', + Name.Variable.Instance: '#3333bb', + Name.Variable.Global: '#dd7700', + Name.Constant: 'bold #003366', + Name.Tag: 'bold #bb0066', + Name.Attribute: '#336699', + Name.Decorator: '#555555', + Name.Label: 'italic #336699', + + Number: 'bold #0000DD', + + Generic.Heading: '#333', + Generic.Subheading: '#666', + Generic.Deleted: 'bg:#ffdddd #000000', + Generic.Inserted: 'bg:#ddffdd #000000', + Generic.Error: '#aa0000', + Generic.Emph: 'italic', + Generic.Strong: 'bold', + Generic.EmphStrong: 'bold italic', + Generic.Prompt: '#555555', + Generic.Output: '#888888', + Generic.Traceback: '#aa0000', + + Error: 'bg:#e3d2d2 #a61717' + } diff --git a/.venv/lib/python3.12/site-packages/pygments/styles/perldoc.py b/.venv/lib/python3.12/site-packages/pygments/styles/perldoc.py new file mode 100644 index 0000000000000000000000000000000000000000..dc5225c6a6405ca8c57211e4147e0f1dc7bf980d --- /dev/null +++ b/.venv/lib/python3.12/site-packages/pygments/styles/perldoc.py @@ -0,0 +1,73 @@ +""" + pygments.styles.perldoc + ~~~~~~~~~~~~~~~~~~~~~~~ + + Style similar to the style used in the `perldoc`_ code blocks. + + .. _perldoc: http://perldoc.perl.org/ + + :copyright: Copyright 2006-present by the Pygments team, see AUTHORS. + :license: BSD, see LICENSE for details. +""" + +from pygments.style import Style +from pygments.token import Keyword, Name, Comment, String, Error, \ + Number, Operator, Generic, Whitespace + + +__all__ = ['PerldocStyle'] + + +class PerldocStyle(Style): + """ + Style similar to the style used in the perldoc code blocks. + """ + + name = 'perldoc' + + background_color = '#eeeedd' + + styles = { + Whitespace: '#bbbbbb', + Comment: '#228B22', + Comment.Preproc: '#1e889b', + Comment.Special: '#8B008B bold', + + String: '#CD5555', + String.Heredoc: '#1c7e71 italic', + String.Regex: '#B452CD', + String.Other: '#cb6c20', + String.Regex: '#1c7e71', + + Number: '#B452CD', + + Operator.Word: '#8B008B', + + Keyword: '#8B008B bold', + Keyword.Type: '#00688B', + + Name.Class: '#008b45 bold', + Name.Exception: '#008b45 bold', + Name.Function: '#008b45', + Name.Namespace: '#008b45 underline', + Name.Variable: '#00688B', + Name.Constant: '#00688B', + Name.Decorator: '#707a7c', + Name.Tag: '#8B008B bold', + Name.Attribute: '#658b00', + Name.Builtin: '#658b00', + + Generic.Heading: 'bold #000080', + Generic.Subheading: 'bold #800080', + Generic.Deleted: '#aa0000', + Generic.Inserted: '#00aa00', + Generic.Error: '#aa0000', + Generic.Emph: 'italic', + Generic.Strong: 'bold', + Generic.EmphStrong: 'bold italic', + Generic.Prompt: '#555555', + Generic.Output: '#888888', + Generic.Traceback: '#aa0000', + + Error: 'bg:#e3d2d2 #a61717' + } diff --git a/.venv/lib/python3.12/site-packages/pygments/styles/rainbow_dash.py b/.venv/lib/python3.12/site-packages/pygments/styles/rainbow_dash.py new file mode 100644 index 0000000000000000000000000000000000000000..4c8bef693e89cff940b5bcced6258c11ac8d6017 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/pygments/styles/rainbow_dash.py @@ -0,0 +1,95 @@ +""" + pygments.styles.rainbow_dash + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + + A bright and colorful syntax highlighting `theme`. + + .. _theme: http://sanssecours.github.io/Rainbow-Dash.tmbundle + + :copyright: Copyright 2006-present by the Pygments team, see AUTHORS. + :license: BSD, see LICENSE for details. +""" + +from pygments.style import Style +from pygments.token import Comment, Error, Generic, Name, Number, Operator, \ + String, Text, Whitespace, Keyword + + +__all__ = ['RainbowDashStyle'] + + +BLUE_LIGHT = '#0080ff' +BLUE = '#2c5dcd' +GREEN = '#00cc66' +GREEN_LIGHT = '#ccffcc' +GREEN_NEON = '#00cc00' +GREY = '#aaaaaa' +GREY_LIGHT = '#cbcbcb' +GREY_DARK = '#4d4d4d' +PURPLE = '#5918bb' +RED = '#cc0000' +RED_DARK = '#c5060b' +RED_LIGHT = '#ffcccc' +RED_BRIGHT = '#ff0000' +WHITE = '#ffffff' +TURQUOISE = '#318495' +ORANGE = '#ff8000' + + +class RainbowDashStyle(Style): + """ + A bright and colorful syntax highlighting theme. + """ + + name = 'rainbow_dash' + + background_color = WHITE + + styles = { + Comment: f'italic {BLUE_LIGHT}', + Comment.Preproc: 'noitalic', + Comment.Special: 'bold', + + Error: f'bg:{RED} {WHITE}', + + Generic.Deleted: f'border:{RED_DARK} bg:{RED_LIGHT}', + Generic.Emph: 'italic', + Generic.Error: RED_BRIGHT, + Generic.Heading: f'bold {BLUE}', + Generic.Inserted: f'border:{GREEN_NEON} bg:{GREEN_LIGHT}', + Generic.Output: GREY, + Generic.Prompt: f'bold {BLUE}', + Generic.Strong: 'bold', + Generic.EmphStrong: 'bold italic', + Generic.Subheading: f'bold {BLUE}', + Generic.Traceback: RED_DARK, + + Keyword: f'bold {BLUE}', + Keyword.Pseudo: 'nobold', + Keyword.Type: PURPLE, + + Name.Attribute: f'italic {BLUE}', + Name.Builtin: f'bold {PURPLE}', + Name.Class: 'underline', + Name.Constant: TURQUOISE, + Name.Decorator: f'bold {ORANGE}', + Name.Entity: f'bold {PURPLE}', + Name.Exception: f'bold {PURPLE}', + Name.Function: f'bold {ORANGE}', + Name.Tag: f'bold {BLUE}', + + Number: f'bold {PURPLE}', + + Operator: BLUE, + Operator.Word: 'bold', + + String: GREEN, + String.Doc: 'italic', + String.Escape: f'bold {RED_DARK}', + String.Other: TURQUOISE, + String.Symbol: f'bold {RED_DARK}', + + Text: GREY_DARK, + + Whitespace: GREY_LIGHT + } diff --git a/.venv/lib/python3.12/site-packages/pygments/styles/rrt.py b/.venv/lib/python3.12/site-packages/pygments/styles/rrt.py new file mode 100644 index 0000000000000000000000000000000000000000..737b54d10d1bc32b5e0107855a68d97aebe8a24f --- /dev/null +++ b/.venv/lib/python3.12/site-packages/pygments/styles/rrt.py @@ -0,0 +1,54 @@ +""" + pygments.styles.rrt + ~~~~~~~~~~~~~~~~~~~ + + pygments "rrt" theme, based on Zap and Emacs defaults. + + :copyright: Copyright 2006-present by the Pygments team, see AUTHORS. + :license: BSD, see LICENSE for details. +""" + +from pygments.style import Style +from pygments.token import ( + Comment, + Generic, + Keyword, + Name, + Number, + Operator, + String, + Token, +) + +__all__ = ['RrtStyle'] + + +class RrtStyle(Style): + """ + Minimalistic "rrt" theme, based on Zap and Emacs defaults. + """ + + name = 'rrt' + + background_color = '#000000' + highlight_color = '#0000ff' + + styles = { + Token: '#dddddd', + Comment: '#00ff00', + Generic.Emph: '#ffffff', + Generic.Heading: '#ffff00', + Generic.Subheading: '#ffff00', + Generic.Strong: '#ffffff', + Name.Entity: '#eedd82', + Name.Function: '#ffff00', + Name.Variable: '#eedd82', + Name.Tag: '#7fffd4', + Name.Constant: '#7fffd4', + Keyword: '#ff0000', + Operator.Word: '#ff0000', + Comment.Preproc: '#e5e5e5', + String: '#87ceeb', + Keyword.Type: '#ee82ee', + Number: '#ff00ff', + } diff --git a/.venv/lib/python3.12/site-packages/pygments/styles/sas.py b/.venv/lib/python3.12/site-packages/pygments/styles/sas.py new file mode 100644 index 0000000000000000000000000000000000000000..4fd51fd5b98424066ed85aa9bd43541163a9dc29 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/pygments/styles/sas.py @@ -0,0 +1,46 @@ +""" + pygments.styles.sas + ~~~~~~~~~~~~~~~~~~~ + + Style inspired by SAS' enhanced program editor. Note This is not + meant to be a complete style. It's merely meant to mimic SAS' + program editor syntax highlighting. + + :copyright: Copyright 2006-present by the Pygments team, see AUTHORS. + :license: BSD, see LICENSE for details. +""" + +from pygments.style import Style +from pygments.token import Keyword, Name, Comment, String, Error, \ + Number, Other, Whitespace, Generic + + +__all__ = ['SasStyle'] + + +class SasStyle(Style): + """ + Style inspired by SAS' enhanced program editor. Note This is not + meant to be a complete style. It's merely meant to mimic SAS' + program editor syntax highlighting. + """ + + name = 'sas' + + styles = { + Whitespace: '#bbbbbb', + Comment: 'italic #008800', + String: '#800080', + Number: 'bold #2c8553', + Other: 'bg:#ffffe0', + Keyword: '#2c2cff', + Keyword.Reserved: 'bold #353580', + Keyword.Constant: 'bold', + Name.Builtin: '#2c2cff', + Name.Function: 'bold italic', + Name.Variable: 'bold #2c2cff', + Generic: '#2c2cff', + Generic.Emph: '#008800', + Generic.Error: '#d30202', + Error: 'bg:#e3d2d2 #a61717' + } diff --git a/.venv/lib/python3.12/site-packages/pygments/styles/solarized.py b/.venv/lib/python3.12/site-packages/pygments/styles/solarized.py new file mode 100644 index 0000000000000000000000000000000000000000..8d3c7e321f7e020845c41eaec4ae970edd3a381e --- /dev/null +++ b/.venv/lib/python3.12/site-packages/pygments/styles/solarized.py @@ -0,0 +1,144 @@ +""" + pygments.styles.solarized + ~~~~~~~~~~~~~~~~~~~~~~~~~ + + Solarized by Camil Staps + + A Pygments style for the Solarized themes (licensed under MIT). + See: https://github.com/altercation/solarized + + :copyright: Copyright 2006-present by the Pygments team, see AUTHORS. + :license: BSD, see LICENSE for details. +""" + +from pygments.style import Style +from pygments.token import Comment, Error, Generic, Keyword, Name, Number, \ + Operator, String, Token + + +__all__ = ['SolarizedLightStyle', 'SolarizedDarkStyle'] + + +def make_style(colors): + return { + Token: colors['base0'], + + Comment: 'italic ' + colors['base01'], + Comment.Hashbang: colors['base01'], + Comment.Multiline: colors['base01'], + Comment.Preproc: 'noitalic ' + colors['magenta'], + Comment.PreprocFile: 'noitalic ' + colors['base01'], + + Keyword: colors['green'], + Keyword.Constant: colors['cyan'], + Keyword.Declaration: colors['cyan'], + Keyword.Namespace: colors['orange'], + Keyword.Type: colors['yellow'], + + Operator: colors['base01'], + Operator.Word: colors['green'], + + Name.Builtin: colors['blue'], + Name.Builtin.Pseudo: colors['blue'], + Name.Class: colors['blue'], + Name.Constant: colors['blue'], + Name.Decorator: colors['blue'], + Name.Entity: colors['blue'], + Name.Exception: colors['blue'], + Name.Function: colors['blue'], + Name.Function.Magic: colors['blue'], + Name.Label: colors['blue'], + Name.Namespace: colors['blue'], + Name.Tag: colors['blue'], + Name.Variable: colors['blue'], + Name.Variable.Global:colors['blue'], + Name.Variable.Magic: colors['blue'], + + String: colors['cyan'], + String.Doc: colors['base01'], + String.Regex: colors['orange'], + + Number: colors['cyan'], + + Generic: colors['base0'], + Generic.Deleted: colors['red'], + Generic.Emph: 'italic', + Generic.Error: colors['red'], + Generic.Heading: 'bold', + Generic.Subheading: 'underline', + Generic.Inserted: colors['green'], + Generic.Output: colors['base0'], + Generic.Prompt: 'bold ' + colors['blue'], + Generic.Strong: 'bold', + Generic.EmphStrong: 'bold italic', + Generic.Traceback: colors['blue'], + + Error: 'bg:' + colors['red'], + } + + +DARK_COLORS = { + 'base03': '#002b36', + 'base02': '#073642', + 'base01': '#586e75', + 'base00': '#657b83', + 'base0': '#839496', + 'base1': '#93a1a1', + 'base2': '#eee8d5', + 'base3': '#fdf6e3', + 'yellow': '#b58900', + 'orange': '#cb4b16', + 'red': '#dc322f', + 'magenta': '#d33682', + 'violet': '#6c71c4', + 'blue': '#268bd2', + 'cyan': '#2aa198', + 'green': '#859900', +} + +LIGHT_COLORS = { + 'base3': '#002b36', + 'base2': '#073642', + 'base1': '#586e75', + 'base0': '#657b83', + 'base00': '#839496', + 'base01': '#93a1a1', + 'base02': '#eee8d5', + 'base03': '#fdf6e3', + 'yellow': '#b58900', + 'orange': '#cb4b16', + 'red': '#dc322f', + 'magenta': '#d33682', + 'violet': '#6c71c4', + 'blue': '#268bd2', + 'cyan': '#2aa198', + 'green': '#859900', +} + + +class SolarizedDarkStyle(Style): + """ + The solarized style, dark. + """ + + name = 'solarized-dark' + + styles = make_style(DARK_COLORS) + background_color = DARK_COLORS['base03'] + highlight_color = DARK_COLORS['base02'] + line_number_color = DARK_COLORS['base01'] + line_number_background_color = DARK_COLORS['base02'] + + +class SolarizedLightStyle(SolarizedDarkStyle): + """ + The solarized style, light. + """ + + name = 'solarized-light' + + styles = make_style(LIGHT_COLORS) + background_color = LIGHT_COLORS['base03'] + highlight_color = LIGHT_COLORS['base02'] + line_number_color = LIGHT_COLORS['base01'] + line_number_background_color = LIGHT_COLORS['base02'] diff --git a/.venv/lib/python3.12/site-packages/pygments/styles/staroffice.py b/.venv/lib/python3.12/site-packages/pygments/styles/staroffice.py new file mode 100644 index 0000000000000000000000000000000000000000..1b10c79adffd6eb3f2ac732bd5883d7d63f7a241 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/pygments/styles/staroffice.py @@ -0,0 +1,31 @@ +""" + pygments.styles.staroffice + ~~~~~~~~~~~~~~~~~~~~~~~~~~ + + Style similar to StarOffice style, also in OpenOffice and LibreOffice. + + :copyright: Copyright 2006-present by the Pygments team, see AUTHORS. + :license: BSD, see LICENSE for details. +""" + +from pygments.style import Style +from pygments.token import Comment, Error, Literal, Name, Token + + +__all__ = ['StarofficeStyle'] + + +class StarofficeStyle(Style): + """ + Style similar to StarOffice style, also in OpenOffice and LibreOffice. + """ + name = 'staroffice' + + + styles = { + Token: '#000080', # Blue + Comment: '#696969', # DimGray + Error: '#800000', # Maroon + Literal: '#EE0000', # Red + Name: '#008000', # Green + } diff --git a/.venv/lib/python3.12/site-packages/pygments/styles/stata_dark.py b/.venv/lib/python3.12/site-packages/pygments/styles/stata_dark.py new file mode 100644 index 0000000000000000000000000000000000000000..461161725dc77b7ca742464b68b10c7967054965 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/pygments/styles/stata_dark.py @@ -0,0 +1,42 @@ +""" + pygments.styles.stata_dark + ~~~~~~~~~~~~~~~~~~~~~~~~~~ + + Dark style inspired by Stata's do-file editor. Note this is not + meant to be a complete style, just for Stata's file formats. + + + :copyright: Copyright 2006-present by the Pygments team, see AUTHORS. + :license: BSD, see LICENSE for details. +""" + +from pygments.style import Style +from pygments.token import Token, Keyword, Name, Comment, String, Error, \ + Number, Operator, Whitespace, Generic + + +__all__ = ['StataDarkStyle'] + + +class StataDarkStyle(Style): + name = 'stata-dark' + + background_color = "#232629" + highlight_color = "#49483e" + + styles = { + Token: '#cccccc', + Whitespace: '#bbbbbb', + Error: 'bg:#e3d2d2 #a61717', + String: '#51cc99', + Number: '#4FB8CC', + Operator: '', + Name.Function: '#6a6aff', + Name.Other: '#e2828e', + Keyword: 'bold #7686bb', + Keyword.Constant: '', + Comment: 'italic #777777', + Name.Variable: 'bold #7AB4DB', + Name.Variable.Global: 'bold #BE646C', + Generic.Prompt: '#ffffff', + } diff --git a/.venv/lib/python3.12/site-packages/pygments/styles/stata_light.py b/.venv/lib/python3.12/site-packages/pygments/styles/stata_light.py new file mode 100644 index 0000000000000000000000000000000000000000..aa4eb1b55714dec095c0ce12cd844ec073c9f889 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/pygments/styles/stata_light.py @@ -0,0 +1,42 @@ +""" + pygments.styles.stata_light + ~~~~~~~~~~~~~~~~~~~~~~~~~~~ + + Light Style inspired by Stata's do-file editor. Note this is not + meant to be a complete style, just for Stata's file formats. + + :copyright: Copyright 2006-present by the Pygments team, see AUTHORS. + :license: BSD, see LICENSE for details. +""" + +from pygments.style import Style +from pygments.token import Keyword, Name, Comment, String, Error, \ + Number, Operator, Whitespace, Text + + +__all__ = ['StataLightStyle'] + + +class StataLightStyle(Style): + """ + Light mode style inspired by Stata's do-file editor. This is not + meant to be a complete style, just for use with Stata. + """ + + name = 'stata-light' + + styles = { + Text: '#111111', + Whitespace: '#bbbbbb', + Error: 'bg:#e3d2d2 #a61717', + String: '#7a2424', + Number: '#2c2cff', + Operator: '', + Name.Function: '#2c2cff', + Name.Other: '#be646c', + Keyword: 'bold #353580', + Keyword.Constant: '', + Comment: 'italic #008800', + Name.Variable: 'bold #35baba', + Name.Variable.Global: 'bold #b5565e', + } diff --git a/.venv/lib/python3.12/site-packages/pygments/styles/tango.py b/.venv/lib/python3.12/site-packages/pygments/styles/tango.py new file mode 100644 index 0000000000000000000000000000000000000000..d5683d4c14a0d9e44f1998376cf406afbc640531 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/pygments/styles/tango.py @@ -0,0 +1,143 @@ +""" + pygments.styles.tango + ~~~~~~~~~~~~~~~~~~~~~ + + The Crunchy default Style inspired from the color palette from + the Tango Icon Theme Guidelines. + + http://tango.freedesktop.org/Tango_Icon_Theme_Guidelines + + Butter: #fce94f #edd400 #c4a000 + Orange: #fcaf3e #f57900 #ce5c00 + Chocolate: #e9b96e #c17d11 #8f5902 + Chameleon: #8ae234 #73d216 #4e9a06 + Sky Blue: #729fcf #3465a4 #204a87 + Plum: #ad7fa8 #75507b #5c35cc + Scarlet Red:#ef2929 #cc0000 #a40000 + Aluminium: #eeeeec #d3d7cf #babdb6 + #888a85 #555753 #2e3436 + + Not all of the above colors are used; other colors added: + very light grey: #f8f8f8 (for background) + + This style can be used as a template as it includes all the known + Token types, unlike most (if not all) of the styles included in the + Pygments distribution. + + However, since Crunchy is intended to be used by beginners, we have strived + to create a style that gloss over subtle distinctions between different + categories. + + Taking Python for example, comments (Comment.*) and docstrings (String.Doc) + have been chosen to have the same style. Similarly, keywords (Keyword.*), + and Operator.Word (and, or, in) have been assigned the same style. + + :copyright: Copyright 2006-present by the Pygments team, see AUTHORS. + :license: BSD, see LICENSE for details. +""" + +from pygments.style import Style +from pygments.token import Keyword, Name, Comment, String, Error, \ + Number, Operator, Generic, Whitespace, Punctuation, Other, Literal + + +__all__ = ['TangoStyle'] + + +class TangoStyle(Style): + """ + The Crunchy default Style inspired from the color palette from + the Tango Icon Theme Guidelines. + """ + + name = 'tango' + + background_color = "#f8f8f8" + + styles = { + # No corresponding class for the following: + #Text: "", # class: '' + Whitespace: "#f8f8f8", # class: 'w' + Error: "#a40000 border:#ef2929", # class: 'err' + Other: "#000000", # class 'x' + + Comment: "italic #8f5902", # class: 'c' + Comment.Multiline: "italic #8f5902", # class: 'cm' + Comment.Preproc: "italic #8f5902", # class: 'cp' + Comment.Single: "italic #8f5902", # class: 'c1' + Comment.Special: "italic #8f5902", # class: 'cs' + + Keyword: "bold #204a87", # class: 'k' + Keyword.Constant: "bold #204a87", # class: 'kc' + Keyword.Declaration: "bold #204a87", # class: 'kd' + Keyword.Namespace: "bold #204a87", # class: 'kn' + Keyword.Pseudo: "bold #204a87", # class: 'kp' + Keyword.Reserved: "bold #204a87", # class: 'kr' + Keyword.Type: "bold #204a87", # class: 'kt' + + Operator: "bold #ce5c00", # class: 'o' + Operator.Word: "bold #204a87", # class: 'ow' - like keywords + + Punctuation: "bold #000000", # class: 'p' + + # because special names such as Name.Class, Name.Function, etc. + # are not recognized as such later in the parsing, we choose them + # to look the same as ordinary variables. + Name: "#000000", # class: 'n' + Name.Attribute: "#c4a000", # class: 'na' - to be revised + Name.Builtin: "#204a87", # class: 'nb' + Name.Builtin.Pseudo: "#3465a4", # class: 'bp' + Name.Class: "#000000", # class: 'nc' - to be revised + Name.Constant: "#000000", # class: 'no' - to be revised + Name.Decorator: "bold #5c35cc", # class: 'nd' - to be revised + Name.Entity: "#ce5c00", # class: 'ni' + Name.Exception: "bold #cc0000", # class: 'ne' + Name.Function: "#000000", # class: 'nf' + Name.Property: "#000000", # class: 'py' + Name.Label: "#f57900", # class: 'nl' + Name.Namespace: "#000000", # class: 'nn' - to be revised + Name.Other: "#000000", # class: 'nx' + Name.Tag: "bold #204a87", # class: 'nt' - like a keyword + Name.Variable: "#000000", # class: 'nv' - to be revised + Name.Variable.Class: "#000000", # class: 'vc' - to be revised + Name.Variable.Global: "#000000", # class: 'vg' - to be revised + Name.Variable.Instance: "#000000", # class: 'vi' - to be revised + + # since the tango light blue does not show up well in text, we choose + # a pure blue instead. + Number: "bold #0000cf", # class: 'm' + Number.Float: "bold #0000cf", # class: 'mf' + Number.Hex: "bold #0000cf", # class: 'mh' + Number.Integer: "bold #0000cf", # class: 'mi' + Number.Integer.Long: "bold #0000cf", # class: 'il' + Number.Oct: "bold #0000cf", # class: 'mo' + + Literal: "#000000", # class: 'l' + Literal.Date: "#000000", # class: 'ld' + + String: "#4e9a06", # class: 's' + String.Backtick: "#4e9a06", # class: 'sb' + String.Char: "#4e9a06", # class: 'sc' + String.Doc: "italic #8f5902", # class: 'sd' - like a comment + String.Double: "#4e9a06", # class: 's2' + String.Escape: "#4e9a06", # class: 'se' + String.Heredoc: "#4e9a06", # class: 'sh' + String.Interpol: "#4e9a06", # class: 'si' + String.Other: "#4e9a06", # class: 'sx' + String.Regex: "#4e9a06", # class: 'sr' + String.Single: "#4e9a06", # class: 's1' + String.Symbol: "#4e9a06", # class: 'ss' + + Generic: "#000000", # class: 'g' + Generic.Deleted: "#a40000", # class: 'gd' + Generic.Emph: "italic #000000", # class: 'ge' + Generic.Error: "#ef2929", # class: 'gr' + Generic.Heading: "bold #000080", # class: 'gh' + Generic.Inserted: "#00A000", # class: 'gi' + Generic.Output: "italic #000000", # class: 'go' + Generic.Prompt: "#8f5902", # class: 'gp' + Generic.Strong: "bold #000000", # class: 'gs' + Generic.EmphStrong: "bold italic #000000", # class: 'ges' + Generic.Subheading: "bold #800080", # class: 'gu' + Generic.Traceback: "bold #a40000", # class: 'gt' + } diff --git a/.venv/lib/python3.12/site-packages/pygments/styles/trac.py b/.venv/lib/python3.12/site-packages/pygments/styles/trac.py new file mode 100644 index 0000000000000000000000000000000000000000..c965b110cb76d9857f847a711dba08a5045f9e57 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/pygments/styles/trac.py @@ -0,0 +1,66 @@ +""" + pygments.styles.trac + ~~~~~~~~~~~~~~~~~~~~ + + Port of the default trac highlighter design. + + :copyright: Copyright 2006-present by the Pygments team, see AUTHORS. + :license: BSD, see LICENSE for details. +""" + +from pygments.style import Style +from pygments.token import Keyword, Name, Comment, String, Error, \ + Number, Operator, Generic, Whitespace + + +__all__ = ['TracStyle'] + + +class TracStyle(Style): + """ + Port of the default trac highlighter design. + """ + + name = 'trac' + + styles = { + Whitespace: '#bbbbbb', + Comment: 'italic #999988', + Comment.Preproc: 'bold noitalic #999999', + Comment.Special: 'bold #999999', + + Operator: 'bold', + + String: '#bb8844', + String.Regex: '#808000', + + Number: '#009999', + + Keyword: 'bold', + Keyword.Type: '#445588', + + Name.Builtin: '#999999', + Name.Function: 'bold #990000', + Name.Class: 'bold #445588', + Name.Exception: 'bold #990000', + Name.Namespace: '#555555', + Name.Variable: '#008080', + Name.Constant: '#008080', + Name.Tag: '#000080', + Name.Attribute: '#008080', + Name.Entity: '#800080', + + Generic.Heading: '#999999', + Generic.Subheading: '#aaaaaa', + Generic.Deleted: 'bg:#ffdddd #000000', + Generic.Inserted: 'bg:#ddffdd #000000', + Generic.Error: '#aa0000', + Generic.Emph: 'italic', + Generic.Strong: 'bold', + Generic.EmphStrong: 'bold italic', + Generic.Prompt: '#555555', + Generic.Output: '#888888', + Generic.Traceback: '#aa0000', + + Error: 'bg:#e3d2d2 #a61717' + } diff --git a/.venv/lib/python3.12/site-packages/pygments/styles/vim.py b/.venv/lib/python3.12/site-packages/pygments/styles/vim.py new file mode 100644 index 0000000000000000000000000000000000000000..5958b06f7983d83d03853ff315a87784b0140067 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/pygments/styles/vim.py @@ -0,0 +1,67 @@ +""" + pygments.styles.vim + ~~~~~~~~~~~~~~~~~~~ + + A highlighting style for Pygments, inspired by vim. + + :copyright: Copyright 2006-present by the Pygments team, see AUTHORS. + :license: BSD, see LICENSE for details. +""" + +from pygments.style import Style +from pygments.token import Keyword, Name, Comment, String, Error, \ + Number, Operator, Generic, Whitespace, Token + + +__all__ = ['VimStyle'] + + +class VimStyle(Style): + """ + Styles somewhat like vim 7.0 + """ + + name = 'vim' + + background_color = "#000000" + highlight_color = "#222222" + + styles = { + Token: "#cccccc", + Whitespace: "", + Comment: "#000080", + Comment.Preproc: "", + Comment.Special: "bold #cd0000", + + Keyword: "#cdcd00", + Keyword.Declaration: "#00cd00", + Keyword.Namespace: "#cd00cd", + Keyword.Pseudo: "", + Keyword.Type: "#00cd00", + + Operator: "#3399cc", + Operator.Word: "#cdcd00", + + Name: "", + Name.Class: "#00cdcd", + Name.Builtin: "#cd00cd", + Name.Exception: "bold #666699", + Name.Variable: "#00cdcd", + + String: "#cd0000", + Number: "#cd00cd", + + Generic.Heading: "bold #000080", + Generic.Subheading: "bold #800080", + Generic.Deleted: "#cd0000", + Generic.Inserted: "#00cd00", + Generic.Error: "#FF0000", + Generic.Emph: "italic", + Generic.Strong: "bold", + Generic.EmphStrong: "bold italic", + Generic.Prompt: "bold #000080", + Generic.Output: "#888", + Generic.Traceback: "#04D", + + Error: "border:#FF0000" + } diff --git a/.venv/lib/python3.12/site-packages/pygments/styles/vs.py b/.venv/lib/python3.12/site-packages/pygments/styles/vs.py new file mode 100644 index 0000000000000000000000000000000000000000..272e584545c4d94b497816ab3140ff2ef945bb5f --- /dev/null +++ b/.venv/lib/python3.12/site-packages/pygments/styles/vs.py @@ -0,0 +1,41 @@ +""" + pygments.styles.vs + ~~~~~~~~~~~~~~~~~~ + + Simple style with MS Visual Studio colors. + + :copyright: Copyright 2006-present by the Pygments team, see AUTHORS. + :license: BSD, see LICENSE for details. +""" + +from pygments.style import Style +from pygments.token import Keyword, Name, Comment, String, Error, \ + Operator, Generic + + +__all__ = ['VisualStudioStyle'] + + +class VisualStudioStyle(Style): + name = 'vs' + + background_color = "#ffffff" + + styles = { + Comment: "#008000", + Comment.Preproc: "#0000ff", + Keyword: "#0000ff", + Operator.Word: "#0000ff", + Keyword.Type: "#2b91af", + Name.Class: "#2b91af", + String: "#a31515", + + Generic.Heading: "bold", + Generic.Subheading: "bold", + Generic.Emph: "italic", + Generic.Strong: "bold", + Generic.EmphStrong: "bold italic", + Generic.Prompt: "bold", + + Error: "border:#FF0000" + } diff --git a/.venv/lib/python3.12/site-packages/pygments/styles/xcode.py b/.venv/lib/python3.12/site-packages/pygments/styles/xcode.py new file mode 100644 index 0000000000000000000000000000000000000000..d9483bc1df90bbb58e20aa16c7195d35a5592825 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/pygments/styles/xcode.py @@ -0,0 +1,53 @@ +""" + pygments.styles.xcode + ~~~~~~~~~~~~~~~~~~~~~ + + Style similar to the `Xcode` default theme. + + :copyright: Copyright 2006-present by the Pygments team, see AUTHORS. + :license: BSD, see LICENSE for details. +""" + +from pygments.style import Style +from pygments.token import Keyword, Name, Comment, String, Error, \ + Number, Operator, Literal + + +__all__ = ['XcodeStyle'] + + +class XcodeStyle(Style): + """ + Style similar to the Xcode default colouring theme. + """ + + name = 'xcode' + + styles = { + Comment: '#177500', + Comment.Preproc: '#633820', + + String: '#C41A16', + String.Char: '#2300CE', + + Operator: '#000000', + + Keyword: '#A90D91', + + Name: '#000000', + Name.Attribute: '#836C28', + Name.Class: '#3F6E75', + Name.Function: '#000000', + Name.Builtin: '#A90D91', + # In Obj-C code this token is used to colour Cocoa types + Name.Builtin.Pseudo: '#5B269A', + Name.Variable: '#000000', + Name.Tag: '#000000', + Name.Decorator: '#000000', + # Workaround for a BUG here: lexer treats multiline method signatres as labels + Name.Label: '#000000', + + Literal: '#1C01CE', + Number: '#1C01CE', + Error: '#000000', + } diff --git a/.venv/lib/python3.12/site-packages/pygments/styles/zenburn.py b/.venv/lib/python3.12/site-packages/pygments/styles/zenburn.py new file mode 100644 index 0000000000000000000000000000000000000000..da0bc1da8412cb7ad9715988afbb8b7b70424441 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/pygments/styles/zenburn.py @@ -0,0 +1,83 @@ +""" + pygments.styles.zenburn + ~~~~~~~~~~~~~~~~~~~~~~~ + + Low contrast color scheme Zenburn. + + See: https://kippura.org/zenburnpage/ + https://github.com/jnurmine/Zenburn + + :copyright: Copyright 2006-present by the Pygments team, see AUTHORS. + :license: BSD, see LICENSE for details. +""" + +from pygments.style import Style +from pygments.token import Token, Name, Operator, Keyword, Generic, Comment, \ + Number, String, Literal, Punctuation, Error + + +__all__ = ['ZenburnStyle'] + + +class ZenburnStyle(Style): + """ + Low contrast Zenburn style. + """ + + name = 'zenburn' + + background_color = '#3f3f3f' + highlight_color = '#484848' + line_number_color = '#5d6262' + line_number_background_color = '#353535' + line_number_special_color = '#7a8080' + line_number_special_background_color = '#353535' + + styles = { + Token: '#dcdccc', + Error: '#e37170 bold', + + Keyword: '#efdcbc', + Keyword.Type: '#dfdfbf bold', + Keyword.Constant: '#dca3a3', + Keyword.Declaration: '#f0dfaf', + Keyword.Namespace: '#f0dfaf', + + Name: '#dcdccc', + Name.Tag: '#e89393 bold', + Name.Entity: '#cfbfaf', + Name.Constant: '#dca3a3', + Name.Class: '#efef8f', + Name.Function: '#efef8f', + Name.Builtin: '#efef8f', + Name.Builtin.Pseudo: '#dcdccc', + Name.Attribute: '#efef8f', + Name.Exception: '#c3bf9f bold', + + Literal: '#9fafaf', + + String: '#cc9393', + String.Doc: '#7f9f7f', + String.Interpol: '#dca3a3 bold', + + Number: '#8cd0d3', + Number.Float: '#c0bed1', + + Operator: '#f0efd0', + + Punctuation: '#f0efd0', + + Comment: '#7f9f7f italic', + Comment.Preproc: '#dfaf8f bold', + Comment.PreprocFile: '#cc9393', + Comment.Special: '#dfdfdf bold', + + Generic: '#ecbcbc bold', + Generic.Emph: '#ffffff bold', + Generic.Output: '#5b605e bold', + Generic.Heading: '#efefef bold', + Generic.Deleted: '#c3bf9f bg:#313c36', + Generic.Inserted: '#709080 bg:#313c36 bold', + Generic.Traceback: '#80d4aa bg:#2f2f2f bold', + Generic.Subheading: '#efefef bold', + } diff --git a/.venv/lib/python3.12/site-packages/pygments/token.py b/.venv/lib/python3.12/site-packages/pygments/token.py new file mode 100644 index 0000000000000000000000000000000000000000..1f756b71130e1c0036d881345ab06968c9f4c464 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/pygments/token.py @@ -0,0 +1,214 @@ +""" + pygments.token + ~~~~~~~~~~~~~~ + + Basic token types and the standard tokens. + + :copyright: Copyright 2006-present by the Pygments team, see AUTHORS. + :license: BSD, see LICENSE for details. +""" + + +class _TokenType(tuple): + parent = None + + def split(self): + buf = [] + node = self + while node is not None: + buf.append(node) + node = node.parent + buf.reverse() + return buf + + def __init__(self, *args): + # no need to call super.__init__ + self.subtypes = set() + + def __contains__(self, val): + return self is val or ( + type(val) is self.__class__ and + val[:len(self)] == self + ) + + def __getattr__(self, val): + if not val or not val[0].isupper(): + return tuple.__getattribute__(self, val) + new = _TokenType(self + (val,)) + setattr(self, val, new) + self.subtypes.add(new) + new.parent = self + return new + + def __repr__(self): + return 'Token' + (self and '.' or '') + '.'.join(self) + + def __copy__(self): + # These instances are supposed to be singletons + return self + + def __deepcopy__(self, memo): + # These instances are supposed to be singletons + return self + + +Token = _TokenType() + +# Special token types +Text = Token.Text +Whitespace = Text.Whitespace +Escape = Token.Escape +Error = Token.Error +# Text that doesn't belong to this lexer (e.g. HTML in PHP) +Other = Token.Other + +# Common token types for source code +Keyword = Token.Keyword +Name = Token.Name +Literal = Token.Literal +String = Literal.String +Number = Literal.Number +Punctuation = Token.Punctuation +Operator = Token.Operator +Comment = Token.Comment + +# Generic types for non-source code +Generic = Token.Generic + +# String and some others are not direct children of Token. +# alias them: +Token.Token = Token +Token.String = String +Token.Number = Number + + +def is_token_subtype(ttype, other): + """ + Return True if ``ttype`` is a subtype of ``other``. + + exists for backwards compatibility. use ``ttype in other`` now. + """ + return ttype in other + + +def string_to_tokentype(s): + """ + Convert a string into a token type:: + + >>> string_to_token('String.Double') + Token.Literal.String.Double + >>> string_to_token('Token.Literal.Number') + Token.Literal.Number + >>> string_to_token('') + Token + + Tokens that are already tokens are returned unchanged: + + >>> string_to_token(String) + Token.Literal.String + """ + if isinstance(s, _TokenType): + return s + if not s: + return Token + node = Token + for item in s.split('.'): + node = getattr(node, item) + return node + + +# Map standard token types to short names, used in CSS class naming. +# If you add a new item, please be sure to run this file to perform +# a consistency check for duplicate values. +STANDARD_TYPES = { + Token: '', + + Text: '', + Whitespace: 'w', + Escape: 'esc', + Error: 'err', + Other: 'x', + + Keyword: 'k', + Keyword.Constant: 'kc', + Keyword.Declaration: 'kd', + Keyword.Namespace: 'kn', + Keyword.Pseudo: 'kp', + Keyword.Reserved: 'kr', + Keyword.Type: 'kt', + + Name: 'n', + Name.Attribute: 'na', + Name.Builtin: 'nb', + Name.Builtin.Pseudo: 'bp', + Name.Class: 'nc', + Name.Constant: 'no', + Name.Decorator: 'nd', + Name.Entity: 'ni', + Name.Exception: 'ne', + Name.Function: 'nf', + Name.Function.Magic: 'fm', + Name.Property: 'py', + Name.Label: 'nl', + Name.Namespace: 'nn', + Name.Other: 'nx', + Name.Tag: 'nt', + Name.Variable: 'nv', + Name.Variable.Class: 'vc', + Name.Variable.Global: 'vg', + Name.Variable.Instance: 'vi', + Name.Variable.Magic: 'vm', + + Literal: 'l', + Literal.Date: 'ld', + + String: 's', + String.Affix: 'sa', + String.Backtick: 'sb', + String.Char: 'sc', + String.Delimiter: 'dl', + String.Doc: 'sd', + String.Double: 's2', + String.Escape: 'se', + String.Heredoc: 'sh', + String.Interpol: 'si', + String.Other: 'sx', + String.Regex: 'sr', + String.Single: 's1', + String.Symbol: 'ss', + + Number: 'm', + Number.Bin: 'mb', + Number.Float: 'mf', + Number.Hex: 'mh', + Number.Integer: 'mi', + Number.Integer.Long: 'il', + Number.Oct: 'mo', + + Operator: 'o', + Operator.Word: 'ow', + + Punctuation: 'p', + Punctuation.Marker: 'pm', + + Comment: 'c', + Comment.Hashbang: 'ch', + Comment.Multiline: 'cm', + Comment.Preproc: 'cp', + Comment.PreprocFile: 'cpf', + Comment.Single: 'c1', + Comment.Special: 'cs', + + Generic: 'g', + Generic.Deleted: 'gd', + Generic.Emph: 'ge', + Generic.Error: 'gr', + Generic.Heading: 'gh', + Generic.Inserted: 'gi', + Generic.Output: 'go', + Generic.Prompt: 'gp', + Generic.Strong: 'gs', + Generic.Subheading: 'gu', + Generic.EmphStrong: 'ges', + Generic.Traceback: 'gt', +} diff --git a/.venv/lib/python3.12/site-packages/pygments/unistring.py b/.venv/lib/python3.12/site-packages/pygments/unistring.py new file mode 100644 index 0000000000000000000000000000000000000000..2a326dff8d7c3594b83b17b8a7705a6ddf2f13fa --- /dev/null +++ b/.venv/lib/python3.12/site-packages/pygments/unistring.py @@ -0,0 +1,153 @@ +""" + pygments.unistring + ~~~~~~~~~~~~~~~~~~ + + Strings of all Unicode characters of a certain category. + Used for matching in Unicode-aware languages. Run to regenerate. + + Inspired by chartypes_create.py from the MoinMoin project. + + :copyright: Copyright 2006-present by the Pygments team, see AUTHORS. + :license: BSD, see LICENSE for details. +""" + +Cc = '\x00-\x1f\x7f-\x9f' + +Cf = '\xad\u0600-\u0605\u061c\u06dd\u070f\u08e2\u180e\u200b-\u200f\u202a-\u202e\u2060-\u2064\u2066-\u206f\ufeff\ufff9-\ufffb\U000110bd\U000110cd\U0001bca0-\U0001bca3\U0001d173-\U0001d17a\U000e0001\U000e0020-\U000e007f' + +Cn = '\u0378-\u0379\u0380-\u0383\u038b\u038d\u03a2\u0530\u0557-\u0558\u058b-\u058c\u0590\u05c8-\u05cf\u05eb-\u05ee\u05f5-\u05ff\u061d\u070e\u074b-\u074c\u07b2-\u07bf\u07fb-\u07fc\u082e-\u082f\u083f\u085c-\u085d\u085f\u086b-\u089f\u08b5\u08be-\u08d2\u0984\u098d-\u098e\u0991-\u0992\u09a9\u09b1\u09b3-\u09b5\u09ba-\u09bb\u09c5-\u09c6\u09c9-\u09ca\u09cf-\u09d6\u09d8-\u09db\u09de\u09e4-\u09e5\u09ff-\u0a00\u0a04\u0a0b-\u0a0e\u0a11-\u0a12\u0a29\u0a31\u0a34\u0a37\u0a3a-\u0a3b\u0a3d\u0a43-\u0a46\u0a49-\u0a4a\u0a4e-\u0a50\u0a52-\u0a58\u0a5d\u0a5f-\u0a65\u0a77-\u0a80\u0a84\u0a8e\u0a92\u0aa9\u0ab1\u0ab4\u0aba-\u0abb\u0ac6\u0aca\u0ace-\u0acf\u0ad1-\u0adf\u0ae4-\u0ae5\u0af2-\u0af8\u0b00\u0b04\u0b0d-\u0b0e\u0b11-\u0b12\u0b29\u0b31\u0b34\u0b3a-\u0b3b\u0b45-\u0b46\u0b49-\u0b4a\u0b4e-\u0b55\u0b58-\u0b5b\u0b5e\u0b64-\u0b65\u0b78-\u0b81\u0b84\u0b8b-\u0b8d\u0b91\u0b96-\u0b98\u0b9b\u0b9d\u0ba0-\u0ba2\u0ba5-\u0ba7\u0bab-\u0bad\u0bba-\u0bbd\u0bc3-\u0bc5\u0bc9\u0bce-\u0bcf\u0bd1-\u0bd6\u0bd8-\u0be5\u0bfb-\u0bff\u0c0d\u0c11\u0c29\u0c3a-\u0c3c\u0c45\u0c49\u0c4e-\u0c54\u0c57\u0c5b-\u0c5f\u0c64-\u0c65\u0c70-\u0c77\u0c8d\u0c91\u0ca9\u0cb4\u0cba-\u0cbb\u0cc5\u0cc9\u0cce-\u0cd4\u0cd7-\u0cdd\u0cdf\u0ce4-\u0ce5\u0cf0\u0cf3-\u0cff\u0d04\u0d0d\u0d11\u0d45\u0d49\u0d50-\u0d53\u0d64-\u0d65\u0d80-\u0d81\u0d84\u0d97-\u0d99\u0db2\u0dbc\u0dbe-\u0dbf\u0dc7-\u0dc9\u0dcb-\u0dce\u0dd5\u0dd7\u0de0-\u0de5\u0df0-\u0df1\u0df5-\u0e00\u0e3b-\u0e3e\u0e5c-\u0e80\u0e83\u0e85-\u0e86\u0e89\u0e8b-\u0e8c\u0e8e-\u0e93\u0e98\u0ea0\u0ea4\u0ea6\u0ea8-\u0ea9\u0eac\u0eba\u0ebe-\u0ebf\u0ec5\u0ec7\u0ece-\u0ecf\u0eda-\u0edb\u0ee0-\u0eff\u0f48\u0f6d-\u0f70\u0f98\u0fbd\u0fcd\u0fdb-\u0fff\u10c6\u10c8-\u10cc\u10ce-\u10cf\u1249\u124e-\u124f\u1257\u1259\u125e-\u125f\u1289\u128e-\u128f\u12b1\u12b6-\u12b7\u12bf\u12c1\u12c6-\u12c7\u12d7\u1311\u1316-\u1317\u135b-\u135c\u137d-\u137f\u139a-\u139f\u13f6-\u13f7\u13fe-\u13ff\u169d-\u169f\u16f9-\u16ff\u170d\u1715-\u171f\u1737-\u173f\u1754-\u175f\u176d\u1771\u1774-\u177f\u17de-\u17df\u17ea-\u17ef\u17fa-\u17ff\u180f\u181a-\u181f\u1879-\u187f\u18ab-\u18af\u18f6-\u18ff\u191f\u192c-\u192f\u193c-\u193f\u1941-\u1943\u196e-\u196f\u1975-\u197f\u19ac-\u19af\u19ca-\u19cf\u19db-\u19dd\u1a1c-\u1a1d\u1a5f\u1a7d-\u1a7e\u1a8a-\u1a8f\u1a9a-\u1a9f\u1aae-\u1aaf\u1abf-\u1aff\u1b4c-\u1b4f\u1b7d-\u1b7f\u1bf4-\u1bfb\u1c38-\u1c3a\u1c4a-\u1c4c\u1c89-\u1c8f\u1cbb-\u1cbc\u1cc8-\u1ccf\u1cfa-\u1cff\u1dfa\u1f16-\u1f17\u1f1e-\u1f1f\u1f46-\u1f47\u1f4e-\u1f4f\u1f58\u1f5a\u1f5c\u1f5e\u1f7e-\u1f7f\u1fb5\u1fc5\u1fd4-\u1fd5\u1fdc\u1ff0-\u1ff1\u1ff5\u1fff\u2065\u2072-\u2073\u208f\u209d-\u209f\u20c0-\u20cf\u20f1-\u20ff\u218c-\u218f\u2427-\u243f\u244b-\u245f\u2b74-\u2b75\u2b96-\u2b97\u2bc9\u2bff\u2c2f\u2c5f\u2cf4-\u2cf8\u2d26\u2d28-\u2d2c\u2d2e-\u2d2f\u2d68-\u2d6e\u2d71-\u2d7e\u2d97-\u2d9f\u2da7\u2daf\u2db7\u2dbf\u2dc7\u2dcf\u2dd7\u2ddf\u2e4f-\u2e7f\u2e9a\u2ef4-\u2eff\u2fd6-\u2fef\u2ffc-\u2fff\u3040\u3097-\u3098\u3100-\u3104\u3130\u318f\u31bb-\u31bf\u31e4-\u31ef\u321f\u32ff\u4db6-\u4dbf\u9ff0-\u9fff\ua48d-\ua48f\ua4c7-\ua4cf\ua62c-\ua63f\ua6f8-\ua6ff\ua7ba-\ua7f6\ua82c-\ua82f\ua83a-\ua83f\ua878-\ua87f\ua8c6-\ua8cd\ua8da-\ua8df\ua954-\ua95e\ua97d-\ua97f\ua9ce\ua9da-\ua9dd\ua9ff\uaa37-\uaa3f\uaa4e-\uaa4f\uaa5a-\uaa5b\uaac3-\uaada\uaaf7-\uab00\uab07-\uab08\uab0f-\uab10\uab17-\uab1f\uab27\uab2f\uab66-\uab6f\uabee-\uabef\uabfa-\uabff\ud7a4-\ud7af\ud7c7-\ud7ca\ud7fc-\ud7ff\ufa6e-\ufa6f\ufada-\ufaff\ufb07-\ufb12\ufb18-\ufb1c\ufb37\ufb3d\ufb3f\ufb42\ufb45\ufbc2-\ufbd2\ufd40-\ufd4f\ufd90-\ufd91\ufdc8-\ufdef\ufdfe-\ufdff\ufe1a-\ufe1f\ufe53\ufe67\ufe6c-\ufe6f\ufe75\ufefd-\ufefe\uff00\uffbf-\uffc1\uffc8-\uffc9\uffd0-\uffd1\uffd8-\uffd9\uffdd-\uffdf\uffe7\uffef-\ufff8\ufffe-\uffff\U0001000c\U00010027\U0001003b\U0001003e\U0001004e-\U0001004f\U0001005e-\U0001007f\U000100fb-\U000100ff\U00010103-\U00010106\U00010134-\U00010136\U0001018f\U0001019c-\U0001019f\U000101a1-\U000101cf\U000101fe-\U0001027f\U0001029d-\U0001029f\U000102d1-\U000102df\U000102fc-\U000102ff\U00010324-\U0001032c\U0001034b-\U0001034f\U0001037b-\U0001037f\U0001039e\U000103c4-\U000103c7\U000103d6-\U000103ff\U0001049e-\U0001049f\U000104aa-\U000104af\U000104d4-\U000104d7\U000104fc-\U000104ff\U00010528-\U0001052f\U00010564-\U0001056e\U00010570-\U000105ff\U00010737-\U0001073f\U00010756-\U0001075f\U00010768-\U000107ff\U00010806-\U00010807\U00010809\U00010836\U00010839-\U0001083b\U0001083d-\U0001083e\U00010856\U0001089f-\U000108a6\U000108b0-\U000108df\U000108f3\U000108f6-\U000108fa\U0001091c-\U0001091e\U0001093a-\U0001093e\U00010940-\U0001097f\U000109b8-\U000109bb\U000109d0-\U000109d1\U00010a04\U00010a07-\U00010a0b\U00010a14\U00010a18\U00010a36-\U00010a37\U00010a3b-\U00010a3e\U00010a49-\U00010a4f\U00010a59-\U00010a5f\U00010aa0-\U00010abf\U00010ae7-\U00010aea\U00010af7-\U00010aff\U00010b36-\U00010b38\U00010b56-\U00010b57\U00010b73-\U00010b77\U00010b92-\U00010b98\U00010b9d-\U00010ba8\U00010bb0-\U00010bff\U00010c49-\U00010c7f\U00010cb3-\U00010cbf\U00010cf3-\U00010cf9\U00010d28-\U00010d2f\U00010d3a-\U00010e5f\U00010e7f-\U00010eff\U00010f28-\U00010f2f\U00010f5a-\U00010fff\U0001104e-\U00011051\U00011070-\U0001107e\U000110c2-\U000110cc\U000110ce-\U000110cf\U000110e9-\U000110ef\U000110fa-\U000110ff\U00011135\U00011147-\U0001114f\U00011177-\U0001117f\U000111ce-\U000111cf\U000111e0\U000111f5-\U000111ff\U00011212\U0001123f-\U0001127f\U00011287\U00011289\U0001128e\U0001129e\U000112aa-\U000112af\U000112eb-\U000112ef\U000112fa-\U000112ff\U00011304\U0001130d-\U0001130e\U00011311-\U00011312\U00011329\U00011331\U00011334\U0001133a\U00011345-\U00011346\U00011349-\U0001134a\U0001134e-\U0001134f\U00011351-\U00011356\U00011358-\U0001135c\U00011364-\U00011365\U0001136d-\U0001136f\U00011375-\U000113ff\U0001145a\U0001145c\U0001145f-\U0001147f\U000114c8-\U000114cf\U000114da-\U0001157f\U000115b6-\U000115b7\U000115de-\U000115ff\U00011645-\U0001164f\U0001165a-\U0001165f\U0001166d-\U0001167f\U000116b8-\U000116bf\U000116ca-\U000116ff\U0001171b-\U0001171c\U0001172c-\U0001172f\U00011740-\U000117ff\U0001183c-\U0001189f\U000118f3-\U000118fe\U00011900-\U000119ff\U00011a48-\U00011a4f\U00011a84-\U00011a85\U00011aa3-\U00011abf\U00011af9-\U00011bff\U00011c09\U00011c37\U00011c46-\U00011c4f\U00011c6d-\U00011c6f\U00011c90-\U00011c91\U00011ca8\U00011cb7-\U00011cff\U00011d07\U00011d0a\U00011d37-\U00011d39\U00011d3b\U00011d3e\U00011d48-\U00011d4f\U00011d5a-\U00011d5f\U00011d66\U00011d69\U00011d8f\U00011d92\U00011d99-\U00011d9f\U00011daa-\U00011edf\U00011ef9-\U00011fff\U0001239a-\U000123ff\U0001246f\U00012475-\U0001247f\U00012544-\U00012fff\U0001342f-\U000143ff\U00014647-\U000167ff\U00016a39-\U00016a3f\U00016a5f\U00016a6a-\U00016a6d\U00016a70-\U00016acf\U00016aee-\U00016aef\U00016af6-\U00016aff\U00016b46-\U00016b4f\U00016b5a\U00016b62\U00016b78-\U00016b7c\U00016b90-\U00016e3f\U00016e9b-\U00016eff\U00016f45-\U00016f4f\U00016f7f-\U00016f8e\U00016fa0-\U00016fdf\U00016fe2-\U00016fff\U000187f2-\U000187ff\U00018af3-\U0001afff\U0001b11f-\U0001b16f\U0001b2fc-\U0001bbff\U0001bc6b-\U0001bc6f\U0001bc7d-\U0001bc7f\U0001bc89-\U0001bc8f\U0001bc9a-\U0001bc9b\U0001bca4-\U0001cfff\U0001d0f6-\U0001d0ff\U0001d127-\U0001d128\U0001d1e9-\U0001d1ff\U0001d246-\U0001d2df\U0001d2f4-\U0001d2ff\U0001d357-\U0001d35f\U0001d379-\U0001d3ff\U0001d455\U0001d49d\U0001d4a0-\U0001d4a1\U0001d4a3-\U0001d4a4\U0001d4a7-\U0001d4a8\U0001d4ad\U0001d4ba\U0001d4bc\U0001d4c4\U0001d506\U0001d50b-\U0001d50c\U0001d515\U0001d51d\U0001d53a\U0001d53f\U0001d545\U0001d547-\U0001d549\U0001d551\U0001d6a6-\U0001d6a7\U0001d7cc-\U0001d7cd\U0001da8c-\U0001da9a\U0001daa0\U0001dab0-\U0001dfff\U0001e007\U0001e019-\U0001e01a\U0001e022\U0001e025\U0001e02b-\U0001e7ff\U0001e8c5-\U0001e8c6\U0001e8d7-\U0001e8ff\U0001e94b-\U0001e94f\U0001e95a-\U0001e95d\U0001e960-\U0001ec70\U0001ecb5-\U0001edff\U0001ee04\U0001ee20\U0001ee23\U0001ee25-\U0001ee26\U0001ee28\U0001ee33\U0001ee38\U0001ee3a\U0001ee3c-\U0001ee41\U0001ee43-\U0001ee46\U0001ee48\U0001ee4a\U0001ee4c\U0001ee50\U0001ee53\U0001ee55-\U0001ee56\U0001ee58\U0001ee5a\U0001ee5c\U0001ee5e\U0001ee60\U0001ee63\U0001ee65-\U0001ee66\U0001ee6b\U0001ee73\U0001ee78\U0001ee7d\U0001ee7f\U0001ee8a\U0001ee9c-\U0001eea0\U0001eea4\U0001eeaa\U0001eebc-\U0001eeef\U0001eef2-\U0001efff\U0001f02c-\U0001f02f\U0001f094-\U0001f09f\U0001f0af-\U0001f0b0\U0001f0c0\U0001f0d0\U0001f0f6-\U0001f0ff\U0001f10d-\U0001f10f\U0001f16c-\U0001f16f\U0001f1ad-\U0001f1e5\U0001f203-\U0001f20f\U0001f23c-\U0001f23f\U0001f249-\U0001f24f\U0001f252-\U0001f25f\U0001f266-\U0001f2ff\U0001f6d5-\U0001f6df\U0001f6ed-\U0001f6ef\U0001f6fa-\U0001f6ff\U0001f774-\U0001f77f\U0001f7d9-\U0001f7ff\U0001f80c-\U0001f80f\U0001f848-\U0001f84f\U0001f85a-\U0001f85f\U0001f888-\U0001f88f\U0001f8ae-\U0001f8ff\U0001f90c-\U0001f90f\U0001f93f\U0001f971-\U0001f972\U0001f977-\U0001f979\U0001f97b\U0001f9a3-\U0001f9af\U0001f9ba-\U0001f9bf\U0001f9c3-\U0001f9cf\U0001fa00-\U0001fa5f\U0001fa6e-\U0001ffff\U0002a6d7-\U0002a6ff\U0002b735-\U0002b73f\U0002b81e-\U0002b81f\U0002cea2-\U0002ceaf\U0002ebe1-\U0002f7ff\U0002fa1e-\U000e0000\U000e0002-\U000e001f\U000e0080-\U000e00ff\U000e01f0-\U000effff\U000ffffe-\U000fffff\U0010fffe-\U0010ffff' + +Co = '\ue000-\uf8ff\U000f0000-\U000ffffd\U00100000-\U0010fffd' + +Cs = '\ud800-\udbff\\\udc00\udc01-\udfff' + +Ll = 'a-z\xb5\xdf-\xf6\xf8-\xff\u0101\u0103\u0105\u0107\u0109\u010b\u010d\u010f\u0111\u0113\u0115\u0117\u0119\u011b\u011d\u011f\u0121\u0123\u0125\u0127\u0129\u012b\u012d\u012f\u0131\u0133\u0135\u0137-\u0138\u013a\u013c\u013e\u0140\u0142\u0144\u0146\u0148-\u0149\u014b\u014d\u014f\u0151\u0153\u0155\u0157\u0159\u015b\u015d\u015f\u0161\u0163\u0165\u0167\u0169\u016b\u016d\u016f\u0171\u0173\u0175\u0177\u017a\u017c\u017e-\u0180\u0183\u0185\u0188\u018c-\u018d\u0192\u0195\u0199-\u019b\u019e\u01a1\u01a3\u01a5\u01a8\u01aa-\u01ab\u01ad\u01b0\u01b4\u01b6\u01b9-\u01ba\u01bd-\u01bf\u01c6\u01c9\u01cc\u01ce\u01d0\u01d2\u01d4\u01d6\u01d8\u01da\u01dc-\u01dd\u01df\u01e1\u01e3\u01e5\u01e7\u01e9\u01eb\u01ed\u01ef-\u01f0\u01f3\u01f5\u01f9\u01fb\u01fd\u01ff\u0201\u0203\u0205\u0207\u0209\u020b\u020d\u020f\u0211\u0213\u0215\u0217\u0219\u021b\u021d\u021f\u0221\u0223\u0225\u0227\u0229\u022b\u022d\u022f\u0231\u0233-\u0239\u023c\u023f-\u0240\u0242\u0247\u0249\u024b\u024d\u024f-\u0293\u0295-\u02af\u0371\u0373\u0377\u037b-\u037d\u0390\u03ac-\u03ce\u03d0-\u03d1\u03d5-\u03d7\u03d9\u03db\u03dd\u03df\u03e1\u03e3\u03e5\u03e7\u03e9\u03eb\u03ed\u03ef-\u03f3\u03f5\u03f8\u03fb-\u03fc\u0430-\u045f\u0461\u0463\u0465\u0467\u0469\u046b\u046d\u046f\u0471\u0473\u0475\u0477\u0479\u047b\u047d\u047f\u0481\u048b\u048d\u048f\u0491\u0493\u0495\u0497\u0499\u049b\u049d\u049f\u04a1\u04a3\u04a5\u04a7\u04a9\u04ab\u04ad\u04af\u04b1\u04b3\u04b5\u04b7\u04b9\u04bb\u04bd\u04bf\u04c2\u04c4\u04c6\u04c8\u04ca\u04cc\u04ce-\u04cf\u04d1\u04d3\u04d5\u04d7\u04d9\u04db\u04dd\u04df\u04e1\u04e3\u04e5\u04e7\u04e9\u04eb\u04ed\u04ef\u04f1\u04f3\u04f5\u04f7\u04f9\u04fb\u04fd\u04ff\u0501\u0503\u0505\u0507\u0509\u050b\u050d\u050f\u0511\u0513\u0515\u0517\u0519\u051b\u051d\u051f\u0521\u0523\u0525\u0527\u0529\u052b\u052d\u052f\u0560-\u0588\u10d0-\u10fa\u10fd-\u10ff\u13f8-\u13fd\u1c80-\u1c88\u1d00-\u1d2b\u1d6b-\u1d77\u1d79-\u1d9a\u1e01\u1e03\u1e05\u1e07\u1e09\u1e0b\u1e0d\u1e0f\u1e11\u1e13\u1e15\u1e17\u1e19\u1e1b\u1e1d\u1e1f\u1e21\u1e23\u1e25\u1e27\u1e29\u1e2b\u1e2d\u1e2f\u1e31\u1e33\u1e35\u1e37\u1e39\u1e3b\u1e3d\u1e3f\u1e41\u1e43\u1e45\u1e47\u1e49\u1e4b\u1e4d\u1e4f\u1e51\u1e53\u1e55\u1e57\u1e59\u1e5b\u1e5d\u1e5f\u1e61\u1e63\u1e65\u1e67\u1e69\u1e6b\u1e6d\u1e6f\u1e71\u1e73\u1e75\u1e77\u1e79\u1e7b\u1e7d\u1e7f\u1e81\u1e83\u1e85\u1e87\u1e89\u1e8b\u1e8d\u1e8f\u1e91\u1e93\u1e95-\u1e9d\u1e9f\u1ea1\u1ea3\u1ea5\u1ea7\u1ea9\u1eab\u1ead\u1eaf\u1eb1\u1eb3\u1eb5\u1eb7\u1eb9\u1ebb\u1ebd\u1ebf\u1ec1\u1ec3\u1ec5\u1ec7\u1ec9\u1ecb\u1ecd\u1ecf\u1ed1\u1ed3\u1ed5\u1ed7\u1ed9\u1edb\u1edd\u1edf\u1ee1\u1ee3\u1ee5\u1ee7\u1ee9\u1eeb\u1eed\u1eef\u1ef1\u1ef3\u1ef5\u1ef7\u1ef9\u1efb\u1efd\u1eff-\u1f07\u1f10-\u1f15\u1f20-\u1f27\u1f30-\u1f37\u1f40-\u1f45\u1f50-\u1f57\u1f60-\u1f67\u1f70-\u1f7d\u1f80-\u1f87\u1f90-\u1f97\u1fa0-\u1fa7\u1fb0-\u1fb4\u1fb6-\u1fb7\u1fbe\u1fc2-\u1fc4\u1fc6-\u1fc7\u1fd0-\u1fd3\u1fd6-\u1fd7\u1fe0-\u1fe7\u1ff2-\u1ff4\u1ff6-\u1ff7\u210a\u210e-\u210f\u2113\u212f\u2134\u2139\u213c-\u213d\u2146-\u2149\u214e\u2184\u2c30-\u2c5e\u2c61\u2c65-\u2c66\u2c68\u2c6a\u2c6c\u2c71\u2c73-\u2c74\u2c76-\u2c7b\u2c81\u2c83\u2c85\u2c87\u2c89\u2c8b\u2c8d\u2c8f\u2c91\u2c93\u2c95\u2c97\u2c99\u2c9b\u2c9d\u2c9f\u2ca1\u2ca3\u2ca5\u2ca7\u2ca9\u2cab\u2cad\u2caf\u2cb1\u2cb3\u2cb5\u2cb7\u2cb9\u2cbb\u2cbd\u2cbf\u2cc1\u2cc3\u2cc5\u2cc7\u2cc9\u2ccb\u2ccd\u2ccf\u2cd1\u2cd3\u2cd5\u2cd7\u2cd9\u2cdb\u2cdd\u2cdf\u2ce1\u2ce3-\u2ce4\u2cec\u2cee\u2cf3\u2d00-\u2d25\u2d27\u2d2d\ua641\ua643\ua645\ua647\ua649\ua64b\ua64d\ua64f\ua651\ua653\ua655\ua657\ua659\ua65b\ua65d\ua65f\ua661\ua663\ua665\ua667\ua669\ua66b\ua66d\ua681\ua683\ua685\ua687\ua689\ua68b\ua68d\ua68f\ua691\ua693\ua695\ua697\ua699\ua69b\ua723\ua725\ua727\ua729\ua72b\ua72d\ua72f-\ua731\ua733\ua735\ua737\ua739\ua73b\ua73d\ua73f\ua741\ua743\ua745\ua747\ua749\ua74b\ua74d\ua74f\ua751\ua753\ua755\ua757\ua759\ua75b\ua75d\ua75f\ua761\ua763\ua765\ua767\ua769\ua76b\ua76d\ua76f\ua771-\ua778\ua77a\ua77c\ua77f\ua781\ua783\ua785\ua787\ua78c\ua78e\ua791\ua793-\ua795\ua797\ua799\ua79b\ua79d\ua79f\ua7a1\ua7a3\ua7a5\ua7a7\ua7a9\ua7af\ua7b5\ua7b7\ua7b9\ua7fa\uab30-\uab5a\uab60-\uab65\uab70-\uabbf\ufb00-\ufb06\ufb13-\ufb17\uff41-\uff5a\U00010428-\U0001044f\U000104d8-\U000104fb\U00010cc0-\U00010cf2\U000118c0-\U000118df\U00016e60-\U00016e7f\U0001d41a-\U0001d433\U0001d44e-\U0001d454\U0001d456-\U0001d467\U0001d482-\U0001d49b\U0001d4b6-\U0001d4b9\U0001d4bb\U0001d4bd-\U0001d4c3\U0001d4c5-\U0001d4cf\U0001d4ea-\U0001d503\U0001d51e-\U0001d537\U0001d552-\U0001d56b\U0001d586-\U0001d59f\U0001d5ba-\U0001d5d3\U0001d5ee-\U0001d607\U0001d622-\U0001d63b\U0001d656-\U0001d66f\U0001d68a-\U0001d6a5\U0001d6c2-\U0001d6da\U0001d6dc-\U0001d6e1\U0001d6fc-\U0001d714\U0001d716-\U0001d71b\U0001d736-\U0001d74e\U0001d750-\U0001d755\U0001d770-\U0001d788\U0001d78a-\U0001d78f\U0001d7aa-\U0001d7c2\U0001d7c4-\U0001d7c9\U0001d7cb\U0001e922-\U0001e943' + +Lm = '\u02b0-\u02c1\u02c6-\u02d1\u02e0-\u02e4\u02ec\u02ee\u0374\u037a\u0559\u0640\u06e5-\u06e6\u07f4-\u07f5\u07fa\u081a\u0824\u0828\u0971\u0e46\u0ec6\u10fc\u17d7\u1843\u1aa7\u1c78-\u1c7d\u1d2c-\u1d6a\u1d78\u1d9b-\u1dbf\u2071\u207f\u2090-\u209c\u2c7c-\u2c7d\u2d6f\u2e2f\u3005\u3031-\u3035\u303b\u309d-\u309e\u30fc-\u30fe\ua015\ua4f8-\ua4fd\ua60c\ua67f\ua69c-\ua69d\ua717-\ua71f\ua770\ua788\ua7f8-\ua7f9\ua9cf\ua9e6\uaa70\uaadd\uaaf3-\uaaf4\uab5c-\uab5f\uff70\uff9e-\uff9f\U00016b40-\U00016b43\U00016f93-\U00016f9f\U00016fe0-\U00016fe1' + +Lo = '\xaa\xba\u01bb\u01c0-\u01c3\u0294\u05d0-\u05ea\u05ef-\u05f2\u0620-\u063f\u0641-\u064a\u066e-\u066f\u0671-\u06d3\u06d5\u06ee-\u06ef\u06fa-\u06fc\u06ff\u0710\u0712-\u072f\u074d-\u07a5\u07b1\u07ca-\u07ea\u0800-\u0815\u0840-\u0858\u0860-\u086a\u08a0-\u08b4\u08b6-\u08bd\u0904-\u0939\u093d\u0950\u0958-\u0961\u0972-\u0980\u0985-\u098c\u098f-\u0990\u0993-\u09a8\u09aa-\u09b0\u09b2\u09b6-\u09b9\u09bd\u09ce\u09dc-\u09dd\u09df-\u09e1\u09f0-\u09f1\u09fc\u0a05-\u0a0a\u0a0f-\u0a10\u0a13-\u0a28\u0a2a-\u0a30\u0a32-\u0a33\u0a35-\u0a36\u0a38-\u0a39\u0a59-\u0a5c\u0a5e\u0a72-\u0a74\u0a85-\u0a8d\u0a8f-\u0a91\u0a93-\u0aa8\u0aaa-\u0ab0\u0ab2-\u0ab3\u0ab5-\u0ab9\u0abd\u0ad0\u0ae0-\u0ae1\u0af9\u0b05-\u0b0c\u0b0f-\u0b10\u0b13-\u0b28\u0b2a-\u0b30\u0b32-\u0b33\u0b35-\u0b39\u0b3d\u0b5c-\u0b5d\u0b5f-\u0b61\u0b71\u0b83\u0b85-\u0b8a\u0b8e-\u0b90\u0b92-\u0b95\u0b99-\u0b9a\u0b9c\u0b9e-\u0b9f\u0ba3-\u0ba4\u0ba8-\u0baa\u0bae-\u0bb9\u0bd0\u0c05-\u0c0c\u0c0e-\u0c10\u0c12-\u0c28\u0c2a-\u0c39\u0c3d\u0c58-\u0c5a\u0c60-\u0c61\u0c80\u0c85-\u0c8c\u0c8e-\u0c90\u0c92-\u0ca8\u0caa-\u0cb3\u0cb5-\u0cb9\u0cbd\u0cde\u0ce0-\u0ce1\u0cf1-\u0cf2\u0d05-\u0d0c\u0d0e-\u0d10\u0d12-\u0d3a\u0d3d\u0d4e\u0d54-\u0d56\u0d5f-\u0d61\u0d7a-\u0d7f\u0d85-\u0d96\u0d9a-\u0db1\u0db3-\u0dbb\u0dbd\u0dc0-\u0dc6\u0e01-\u0e30\u0e32-\u0e33\u0e40-\u0e45\u0e81-\u0e82\u0e84\u0e87-\u0e88\u0e8a\u0e8d\u0e94-\u0e97\u0e99-\u0e9f\u0ea1-\u0ea3\u0ea5\u0ea7\u0eaa-\u0eab\u0ead-\u0eb0\u0eb2-\u0eb3\u0ebd\u0ec0-\u0ec4\u0edc-\u0edf\u0f00\u0f40-\u0f47\u0f49-\u0f6c\u0f88-\u0f8c\u1000-\u102a\u103f\u1050-\u1055\u105a-\u105d\u1061\u1065-\u1066\u106e-\u1070\u1075-\u1081\u108e\u1100-\u1248\u124a-\u124d\u1250-\u1256\u1258\u125a-\u125d\u1260-\u1288\u128a-\u128d\u1290-\u12b0\u12b2-\u12b5\u12b8-\u12be\u12c0\u12c2-\u12c5\u12c8-\u12d6\u12d8-\u1310\u1312-\u1315\u1318-\u135a\u1380-\u138f\u1401-\u166c\u166f-\u167f\u1681-\u169a\u16a0-\u16ea\u16f1-\u16f8\u1700-\u170c\u170e-\u1711\u1720-\u1731\u1740-\u1751\u1760-\u176c\u176e-\u1770\u1780-\u17b3\u17dc\u1820-\u1842\u1844-\u1878\u1880-\u1884\u1887-\u18a8\u18aa\u18b0-\u18f5\u1900-\u191e\u1950-\u196d\u1970-\u1974\u1980-\u19ab\u19b0-\u19c9\u1a00-\u1a16\u1a20-\u1a54\u1b05-\u1b33\u1b45-\u1b4b\u1b83-\u1ba0\u1bae-\u1baf\u1bba-\u1be5\u1c00-\u1c23\u1c4d-\u1c4f\u1c5a-\u1c77\u1ce9-\u1cec\u1cee-\u1cf1\u1cf5-\u1cf6\u2135-\u2138\u2d30-\u2d67\u2d80-\u2d96\u2da0-\u2da6\u2da8-\u2dae\u2db0-\u2db6\u2db8-\u2dbe\u2dc0-\u2dc6\u2dc8-\u2dce\u2dd0-\u2dd6\u2dd8-\u2dde\u3006\u303c\u3041-\u3096\u309f\u30a1-\u30fa\u30ff\u3105-\u312f\u3131-\u318e\u31a0-\u31ba\u31f0-\u31ff\u3400-\u4db5\u4e00-\u9fef\ua000-\ua014\ua016-\ua48c\ua4d0-\ua4f7\ua500-\ua60b\ua610-\ua61f\ua62a-\ua62b\ua66e\ua6a0-\ua6e5\ua78f\ua7f7\ua7fb-\ua801\ua803-\ua805\ua807-\ua80a\ua80c-\ua822\ua840-\ua873\ua882-\ua8b3\ua8f2-\ua8f7\ua8fb\ua8fd-\ua8fe\ua90a-\ua925\ua930-\ua946\ua960-\ua97c\ua984-\ua9b2\ua9e0-\ua9e4\ua9e7-\ua9ef\ua9fa-\ua9fe\uaa00-\uaa28\uaa40-\uaa42\uaa44-\uaa4b\uaa60-\uaa6f\uaa71-\uaa76\uaa7a\uaa7e-\uaaaf\uaab1\uaab5-\uaab6\uaab9-\uaabd\uaac0\uaac2\uaadb-\uaadc\uaae0-\uaaea\uaaf2\uab01-\uab06\uab09-\uab0e\uab11-\uab16\uab20-\uab26\uab28-\uab2e\uabc0-\uabe2\uac00-\ud7a3\ud7b0-\ud7c6\ud7cb-\ud7fb\uf900-\ufa6d\ufa70-\ufad9\ufb1d\ufb1f-\ufb28\ufb2a-\ufb36\ufb38-\ufb3c\ufb3e\ufb40-\ufb41\ufb43-\ufb44\ufb46-\ufbb1\ufbd3-\ufd3d\ufd50-\ufd8f\ufd92-\ufdc7\ufdf0-\ufdfb\ufe70-\ufe74\ufe76-\ufefc\uff66-\uff6f\uff71-\uff9d\uffa0-\uffbe\uffc2-\uffc7\uffca-\uffcf\uffd2-\uffd7\uffda-\uffdc\U00010000-\U0001000b\U0001000d-\U00010026\U00010028-\U0001003a\U0001003c-\U0001003d\U0001003f-\U0001004d\U00010050-\U0001005d\U00010080-\U000100fa\U00010280-\U0001029c\U000102a0-\U000102d0\U00010300-\U0001031f\U0001032d-\U00010340\U00010342-\U00010349\U00010350-\U00010375\U00010380-\U0001039d\U000103a0-\U000103c3\U000103c8-\U000103cf\U00010450-\U0001049d\U00010500-\U00010527\U00010530-\U00010563\U00010600-\U00010736\U00010740-\U00010755\U00010760-\U00010767\U00010800-\U00010805\U00010808\U0001080a-\U00010835\U00010837-\U00010838\U0001083c\U0001083f-\U00010855\U00010860-\U00010876\U00010880-\U0001089e\U000108e0-\U000108f2\U000108f4-\U000108f5\U00010900-\U00010915\U00010920-\U00010939\U00010980-\U000109b7\U000109be-\U000109bf\U00010a00\U00010a10-\U00010a13\U00010a15-\U00010a17\U00010a19-\U00010a35\U00010a60-\U00010a7c\U00010a80-\U00010a9c\U00010ac0-\U00010ac7\U00010ac9-\U00010ae4\U00010b00-\U00010b35\U00010b40-\U00010b55\U00010b60-\U00010b72\U00010b80-\U00010b91\U00010c00-\U00010c48\U00010d00-\U00010d23\U00010f00-\U00010f1c\U00010f27\U00010f30-\U00010f45\U00011003-\U00011037\U00011083-\U000110af\U000110d0-\U000110e8\U00011103-\U00011126\U00011144\U00011150-\U00011172\U00011176\U00011183-\U000111b2\U000111c1-\U000111c4\U000111da\U000111dc\U00011200-\U00011211\U00011213-\U0001122b\U00011280-\U00011286\U00011288\U0001128a-\U0001128d\U0001128f-\U0001129d\U0001129f-\U000112a8\U000112b0-\U000112de\U00011305-\U0001130c\U0001130f-\U00011310\U00011313-\U00011328\U0001132a-\U00011330\U00011332-\U00011333\U00011335-\U00011339\U0001133d\U00011350\U0001135d-\U00011361\U00011400-\U00011434\U00011447-\U0001144a\U00011480-\U000114af\U000114c4-\U000114c5\U000114c7\U00011580-\U000115ae\U000115d8-\U000115db\U00011600-\U0001162f\U00011644\U00011680-\U000116aa\U00011700-\U0001171a\U00011800-\U0001182b\U000118ff\U00011a00\U00011a0b-\U00011a32\U00011a3a\U00011a50\U00011a5c-\U00011a83\U00011a86-\U00011a89\U00011a9d\U00011ac0-\U00011af8\U00011c00-\U00011c08\U00011c0a-\U00011c2e\U00011c40\U00011c72-\U00011c8f\U00011d00-\U00011d06\U00011d08-\U00011d09\U00011d0b-\U00011d30\U00011d46\U00011d60-\U00011d65\U00011d67-\U00011d68\U00011d6a-\U00011d89\U00011d98\U00011ee0-\U00011ef2\U00012000-\U00012399\U00012480-\U00012543\U00013000-\U0001342e\U00014400-\U00014646\U00016800-\U00016a38\U00016a40-\U00016a5e\U00016ad0-\U00016aed\U00016b00-\U00016b2f\U00016b63-\U00016b77\U00016b7d-\U00016b8f\U00016f00-\U00016f44\U00016f50\U00017000-\U000187f1\U00018800-\U00018af2\U0001b000-\U0001b11e\U0001b170-\U0001b2fb\U0001bc00-\U0001bc6a\U0001bc70-\U0001bc7c\U0001bc80-\U0001bc88\U0001bc90-\U0001bc99\U0001e800-\U0001e8c4\U0001ee00-\U0001ee03\U0001ee05-\U0001ee1f\U0001ee21-\U0001ee22\U0001ee24\U0001ee27\U0001ee29-\U0001ee32\U0001ee34-\U0001ee37\U0001ee39\U0001ee3b\U0001ee42\U0001ee47\U0001ee49\U0001ee4b\U0001ee4d-\U0001ee4f\U0001ee51-\U0001ee52\U0001ee54\U0001ee57\U0001ee59\U0001ee5b\U0001ee5d\U0001ee5f\U0001ee61-\U0001ee62\U0001ee64\U0001ee67-\U0001ee6a\U0001ee6c-\U0001ee72\U0001ee74-\U0001ee77\U0001ee79-\U0001ee7c\U0001ee7e\U0001ee80-\U0001ee89\U0001ee8b-\U0001ee9b\U0001eea1-\U0001eea3\U0001eea5-\U0001eea9\U0001eeab-\U0001eebb\U00020000-\U0002a6d6\U0002a700-\U0002b734\U0002b740-\U0002b81d\U0002b820-\U0002cea1\U0002ceb0-\U0002ebe0\U0002f800-\U0002fa1d' + +Lt = '\u01c5\u01c8\u01cb\u01f2\u1f88-\u1f8f\u1f98-\u1f9f\u1fa8-\u1faf\u1fbc\u1fcc\u1ffc' + +Lu = 'A-Z\xc0-\xd6\xd8-\xde\u0100\u0102\u0104\u0106\u0108\u010a\u010c\u010e\u0110\u0112\u0114\u0116\u0118\u011a\u011c\u011e\u0120\u0122\u0124\u0126\u0128\u012a\u012c\u012e\u0130\u0132\u0134\u0136\u0139\u013b\u013d\u013f\u0141\u0143\u0145\u0147\u014a\u014c\u014e\u0150\u0152\u0154\u0156\u0158\u015a\u015c\u015e\u0160\u0162\u0164\u0166\u0168\u016a\u016c\u016e\u0170\u0172\u0174\u0176\u0178-\u0179\u017b\u017d\u0181-\u0182\u0184\u0186-\u0187\u0189-\u018b\u018e-\u0191\u0193-\u0194\u0196-\u0198\u019c-\u019d\u019f-\u01a0\u01a2\u01a4\u01a6-\u01a7\u01a9\u01ac\u01ae-\u01af\u01b1-\u01b3\u01b5\u01b7-\u01b8\u01bc\u01c4\u01c7\u01ca\u01cd\u01cf\u01d1\u01d3\u01d5\u01d7\u01d9\u01db\u01de\u01e0\u01e2\u01e4\u01e6\u01e8\u01ea\u01ec\u01ee\u01f1\u01f4\u01f6-\u01f8\u01fa\u01fc\u01fe\u0200\u0202\u0204\u0206\u0208\u020a\u020c\u020e\u0210\u0212\u0214\u0216\u0218\u021a\u021c\u021e\u0220\u0222\u0224\u0226\u0228\u022a\u022c\u022e\u0230\u0232\u023a-\u023b\u023d-\u023e\u0241\u0243-\u0246\u0248\u024a\u024c\u024e\u0370\u0372\u0376\u037f\u0386\u0388-\u038a\u038c\u038e-\u038f\u0391-\u03a1\u03a3-\u03ab\u03cf\u03d2-\u03d4\u03d8\u03da\u03dc\u03de\u03e0\u03e2\u03e4\u03e6\u03e8\u03ea\u03ec\u03ee\u03f4\u03f7\u03f9-\u03fa\u03fd-\u042f\u0460\u0462\u0464\u0466\u0468\u046a\u046c\u046e\u0470\u0472\u0474\u0476\u0478\u047a\u047c\u047e\u0480\u048a\u048c\u048e\u0490\u0492\u0494\u0496\u0498\u049a\u049c\u049e\u04a0\u04a2\u04a4\u04a6\u04a8\u04aa\u04ac\u04ae\u04b0\u04b2\u04b4\u04b6\u04b8\u04ba\u04bc\u04be\u04c0-\u04c1\u04c3\u04c5\u04c7\u04c9\u04cb\u04cd\u04d0\u04d2\u04d4\u04d6\u04d8\u04da\u04dc\u04de\u04e0\u04e2\u04e4\u04e6\u04e8\u04ea\u04ec\u04ee\u04f0\u04f2\u04f4\u04f6\u04f8\u04fa\u04fc\u04fe\u0500\u0502\u0504\u0506\u0508\u050a\u050c\u050e\u0510\u0512\u0514\u0516\u0518\u051a\u051c\u051e\u0520\u0522\u0524\u0526\u0528\u052a\u052c\u052e\u0531-\u0556\u10a0-\u10c5\u10c7\u10cd\u13a0-\u13f5\u1c90-\u1cba\u1cbd-\u1cbf\u1e00\u1e02\u1e04\u1e06\u1e08\u1e0a\u1e0c\u1e0e\u1e10\u1e12\u1e14\u1e16\u1e18\u1e1a\u1e1c\u1e1e\u1e20\u1e22\u1e24\u1e26\u1e28\u1e2a\u1e2c\u1e2e\u1e30\u1e32\u1e34\u1e36\u1e38\u1e3a\u1e3c\u1e3e\u1e40\u1e42\u1e44\u1e46\u1e48\u1e4a\u1e4c\u1e4e\u1e50\u1e52\u1e54\u1e56\u1e58\u1e5a\u1e5c\u1e5e\u1e60\u1e62\u1e64\u1e66\u1e68\u1e6a\u1e6c\u1e6e\u1e70\u1e72\u1e74\u1e76\u1e78\u1e7a\u1e7c\u1e7e\u1e80\u1e82\u1e84\u1e86\u1e88\u1e8a\u1e8c\u1e8e\u1e90\u1e92\u1e94\u1e9e\u1ea0\u1ea2\u1ea4\u1ea6\u1ea8\u1eaa\u1eac\u1eae\u1eb0\u1eb2\u1eb4\u1eb6\u1eb8\u1eba\u1ebc\u1ebe\u1ec0\u1ec2\u1ec4\u1ec6\u1ec8\u1eca\u1ecc\u1ece\u1ed0\u1ed2\u1ed4\u1ed6\u1ed8\u1eda\u1edc\u1ede\u1ee0\u1ee2\u1ee4\u1ee6\u1ee8\u1eea\u1eec\u1eee\u1ef0\u1ef2\u1ef4\u1ef6\u1ef8\u1efa\u1efc\u1efe\u1f08-\u1f0f\u1f18-\u1f1d\u1f28-\u1f2f\u1f38-\u1f3f\u1f48-\u1f4d\u1f59\u1f5b\u1f5d\u1f5f\u1f68-\u1f6f\u1fb8-\u1fbb\u1fc8-\u1fcb\u1fd8-\u1fdb\u1fe8-\u1fec\u1ff8-\u1ffb\u2102\u2107\u210b-\u210d\u2110-\u2112\u2115\u2119-\u211d\u2124\u2126\u2128\u212a-\u212d\u2130-\u2133\u213e-\u213f\u2145\u2183\u2c00-\u2c2e\u2c60\u2c62-\u2c64\u2c67\u2c69\u2c6b\u2c6d-\u2c70\u2c72\u2c75\u2c7e-\u2c80\u2c82\u2c84\u2c86\u2c88\u2c8a\u2c8c\u2c8e\u2c90\u2c92\u2c94\u2c96\u2c98\u2c9a\u2c9c\u2c9e\u2ca0\u2ca2\u2ca4\u2ca6\u2ca8\u2caa\u2cac\u2cae\u2cb0\u2cb2\u2cb4\u2cb6\u2cb8\u2cba\u2cbc\u2cbe\u2cc0\u2cc2\u2cc4\u2cc6\u2cc8\u2cca\u2ccc\u2cce\u2cd0\u2cd2\u2cd4\u2cd6\u2cd8\u2cda\u2cdc\u2cde\u2ce0\u2ce2\u2ceb\u2ced\u2cf2\ua640\ua642\ua644\ua646\ua648\ua64a\ua64c\ua64e\ua650\ua652\ua654\ua656\ua658\ua65a\ua65c\ua65e\ua660\ua662\ua664\ua666\ua668\ua66a\ua66c\ua680\ua682\ua684\ua686\ua688\ua68a\ua68c\ua68e\ua690\ua692\ua694\ua696\ua698\ua69a\ua722\ua724\ua726\ua728\ua72a\ua72c\ua72e\ua732\ua734\ua736\ua738\ua73a\ua73c\ua73e\ua740\ua742\ua744\ua746\ua748\ua74a\ua74c\ua74e\ua750\ua752\ua754\ua756\ua758\ua75a\ua75c\ua75e\ua760\ua762\ua764\ua766\ua768\ua76a\ua76c\ua76e\ua779\ua77b\ua77d-\ua77e\ua780\ua782\ua784\ua786\ua78b\ua78d\ua790\ua792\ua796\ua798\ua79a\ua79c\ua79e\ua7a0\ua7a2\ua7a4\ua7a6\ua7a8\ua7aa-\ua7ae\ua7b0-\ua7b4\ua7b6\ua7b8\uff21-\uff3a\U00010400-\U00010427\U000104b0-\U000104d3\U00010c80-\U00010cb2\U000118a0-\U000118bf\U00016e40-\U00016e5f\U0001d400-\U0001d419\U0001d434-\U0001d44d\U0001d468-\U0001d481\U0001d49c\U0001d49e-\U0001d49f\U0001d4a2\U0001d4a5-\U0001d4a6\U0001d4a9-\U0001d4ac\U0001d4ae-\U0001d4b5\U0001d4d0-\U0001d4e9\U0001d504-\U0001d505\U0001d507-\U0001d50a\U0001d50d-\U0001d514\U0001d516-\U0001d51c\U0001d538-\U0001d539\U0001d53b-\U0001d53e\U0001d540-\U0001d544\U0001d546\U0001d54a-\U0001d550\U0001d56c-\U0001d585\U0001d5a0-\U0001d5b9\U0001d5d4-\U0001d5ed\U0001d608-\U0001d621\U0001d63c-\U0001d655\U0001d670-\U0001d689\U0001d6a8-\U0001d6c0\U0001d6e2-\U0001d6fa\U0001d71c-\U0001d734\U0001d756-\U0001d76e\U0001d790-\U0001d7a8\U0001d7ca\U0001e900-\U0001e921' + +Mc = '\u0903\u093b\u093e-\u0940\u0949-\u094c\u094e-\u094f\u0982-\u0983\u09be-\u09c0\u09c7-\u09c8\u09cb-\u09cc\u09d7\u0a03\u0a3e-\u0a40\u0a83\u0abe-\u0ac0\u0ac9\u0acb-\u0acc\u0b02-\u0b03\u0b3e\u0b40\u0b47-\u0b48\u0b4b-\u0b4c\u0b57\u0bbe-\u0bbf\u0bc1-\u0bc2\u0bc6-\u0bc8\u0bca-\u0bcc\u0bd7\u0c01-\u0c03\u0c41-\u0c44\u0c82-\u0c83\u0cbe\u0cc0-\u0cc4\u0cc7-\u0cc8\u0cca-\u0ccb\u0cd5-\u0cd6\u0d02-\u0d03\u0d3e-\u0d40\u0d46-\u0d48\u0d4a-\u0d4c\u0d57\u0d82-\u0d83\u0dcf-\u0dd1\u0dd8-\u0ddf\u0df2-\u0df3\u0f3e-\u0f3f\u0f7f\u102b-\u102c\u1031\u1038\u103b-\u103c\u1056-\u1057\u1062-\u1064\u1067-\u106d\u1083-\u1084\u1087-\u108c\u108f\u109a-\u109c\u17b6\u17be-\u17c5\u17c7-\u17c8\u1923-\u1926\u1929-\u192b\u1930-\u1931\u1933-\u1938\u1a19-\u1a1a\u1a55\u1a57\u1a61\u1a63-\u1a64\u1a6d-\u1a72\u1b04\u1b35\u1b3b\u1b3d-\u1b41\u1b43-\u1b44\u1b82\u1ba1\u1ba6-\u1ba7\u1baa\u1be7\u1bea-\u1bec\u1bee\u1bf2-\u1bf3\u1c24-\u1c2b\u1c34-\u1c35\u1ce1\u1cf2-\u1cf3\u1cf7\u302e-\u302f\ua823-\ua824\ua827\ua880-\ua881\ua8b4-\ua8c3\ua952-\ua953\ua983\ua9b4-\ua9b5\ua9ba-\ua9bb\ua9bd-\ua9c0\uaa2f-\uaa30\uaa33-\uaa34\uaa4d\uaa7b\uaa7d\uaaeb\uaaee-\uaaef\uaaf5\uabe3-\uabe4\uabe6-\uabe7\uabe9-\uabea\uabec\U00011000\U00011002\U00011082\U000110b0-\U000110b2\U000110b7-\U000110b8\U0001112c\U00011145-\U00011146\U00011182\U000111b3-\U000111b5\U000111bf-\U000111c0\U0001122c-\U0001122e\U00011232-\U00011233\U00011235\U000112e0-\U000112e2\U00011302-\U00011303\U0001133e-\U0001133f\U00011341-\U00011344\U00011347-\U00011348\U0001134b-\U0001134d\U00011357\U00011362-\U00011363\U00011435-\U00011437\U00011440-\U00011441\U00011445\U000114b0-\U000114b2\U000114b9\U000114bb-\U000114be\U000114c1\U000115af-\U000115b1\U000115b8-\U000115bb\U000115be\U00011630-\U00011632\U0001163b-\U0001163c\U0001163e\U000116ac\U000116ae-\U000116af\U000116b6\U00011720-\U00011721\U00011726\U0001182c-\U0001182e\U00011838\U00011a39\U00011a57-\U00011a58\U00011a97\U00011c2f\U00011c3e\U00011ca9\U00011cb1\U00011cb4\U00011d8a-\U00011d8e\U00011d93-\U00011d94\U00011d96\U00011ef5-\U00011ef6\U00016f51-\U00016f7e\U0001d165-\U0001d166\U0001d16d-\U0001d172' + +Me = '\u0488-\u0489\u1abe\u20dd-\u20e0\u20e2-\u20e4\ua670-\ua672' + +Mn = '\u0300-\u036f\u0483-\u0487\u0591-\u05bd\u05bf\u05c1-\u05c2\u05c4-\u05c5\u05c7\u0610-\u061a\u064b-\u065f\u0670\u06d6-\u06dc\u06df-\u06e4\u06e7-\u06e8\u06ea-\u06ed\u0711\u0730-\u074a\u07a6-\u07b0\u07eb-\u07f3\u07fd\u0816-\u0819\u081b-\u0823\u0825-\u0827\u0829-\u082d\u0859-\u085b\u08d3-\u08e1\u08e3-\u0902\u093a\u093c\u0941-\u0948\u094d\u0951-\u0957\u0962-\u0963\u0981\u09bc\u09c1-\u09c4\u09cd\u09e2-\u09e3\u09fe\u0a01-\u0a02\u0a3c\u0a41-\u0a42\u0a47-\u0a48\u0a4b-\u0a4d\u0a51\u0a70-\u0a71\u0a75\u0a81-\u0a82\u0abc\u0ac1-\u0ac5\u0ac7-\u0ac8\u0acd\u0ae2-\u0ae3\u0afa-\u0aff\u0b01\u0b3c\u0b3f\u0b41-\u0b44\u0b4d\u0b56\u0b62-\u0b63\u0b82\u0bc0\u0bcd\u0c00\u0c04\u0c3e-\u0c40\u0c46-\u0c48\u0c4a-\u0c4d\u0c55-\u0c56\u0c62-\u0c63\u0c81\u0cbc\u0cbf\u0cc6\u0ccc-\u0ccd\u0ce2-\u0ce3\u0d00-\u0d01\u0d3b-\u0d3c\u0d41-\u0d44\u0d4d\u0d62-\u0d63\u0dca\u0dd2-\u0dd4\u0dd6\u0e31\u0e34-\u0e3a\u0e47-\u0e4e\u0eb1\u0eb4-\u0eb9\u0ebb-\u0ebc\u0ec8-\u0ecd\u0f18-\u0f19\u0f35\u0f37\u0f39\u0f71-\u0f7e\u0f80-\u0f84\u0f86-\u0f87\u0f8d-\u0f97\u0f99-\u0fbc\u0fc6\u102d-\u1030\u1032-\u1037\u1039-\u103a\u103d-\u103e\u1058-\u1059\u105e-\u1060\u1071-\u1074\u1082\u1085-\u1086\u108d\u109d\u135d-\u135f\u1712-\u1714\u1732-\u1734\u1752-\u1753\u1772-\u1773\u17b4-\u17b5\u17b7-\u17bd\u17c6\u17c9-\u17d3\u17dd\u180b-\u180d\u1885-\u1886\u18a9\u1920-\u1922\u1927-\u1928\u1932\u1939-\u193b\u1a17-\u1a18\u1a1b\u1a56\u1a58-\u1a5e\u1a60\u1a62\u1a65-\u1a6c\u1a73-\u1a7c\u1a7f\u1ab0-\u1abd\u1b00-\u1b03\u1b34\u1b36-\u1b3a\u1b3c\u1b42\u1b6b-\u1b73\u1b80-\u1b81\u1ba2-\u1ba5\u1ba8-\u1ba9\u1bab-\u1bad\u1be6\u1be8-\u1be9\u1bed\u1bef-\u1bf1\u1c2c-\u1c33\u1c36-\u1c37\u1cd0-\u1cd2\u1cd4-\u1ce0\u1ce2-\u1ce8\u1ced\u1cf4\u1cf8-\u1cf9\u1dc0-\u1df9\u1dfb-\u1dff\u20d0-\u20dc\u20e1\u20e5-\u20f0\u2cef-\u2cf1\u2d7f\u2de0-\u2dff\u302a-\u302d\u3099-\u309a\ua66f\ua674-\ua67d\ua69e-\ua69f\ua6f0-\ua6f1\ua802\ua806\ua80b\ua825-\ua826\ua8c4-\ua8c5\ua8e0-\ua8f1\ua8ff\ua926-\ua92d\ua947-\ua951\ua980-\ua982\ua9b3\ua9b6-\ua9b9\ua9bc\ua9e5\uaa29-\uaa2e\uaa31-\uaa32\uaa35-\uaa36\uaa43\uaa4c\uaa7c\uaab0\uaab2-\uaab4\uaab7-\uaab8\uaabe-\uaabf\uaac1\uaaec-\uaaed\uaaf6\uabe5\uabe8\uabed\ufb1e\ufe00-\ufe0f\ufe20-\ufe2f\U000101fd\U000102e0\U00010376-\U0001037a\U00010a01-\U00010a03\U00010a05-\U00010a06\U00010a0c-\U00010a0f\U00010a38-\U00010a3a\U00010a3f\U00010ae5-\U00010ae6\U00010d24-\U00010d27\U00010f46-\U00010f50\U00011001\U00011038-\U00011046\U0001107f-\U00011081\U000110b3-\U000110b6\U000110b9-\U000110ba\U00011100-\U00011102\U00011127-\U0001112b\U0001112d-\U00011134\U00011173\U00011180-\U00011181\U000111b6-\U000111be\U000111c9-\U000111cc\U0001122f-\U00011231\U00011234\U00011236-\U00011237\U0001123e\U000112df\U000112e3-\U000112ea\U00011300-\U00011301\U0001133b-\U0001133c\U00011340\U00011366-\U0001136c\U00011370-\U00011374\U00011438-\U0001143f\U00011442-\U00011444\U00011446\U0001145e\U000114b3-\U000114b8\U000114ba\U000114bf-\U000114c0\U000114c2-\U000114c3\U000115b2-\U000115b5\U000115bc-\U000115bd\U000115bf-\U000115c0\U000115dc-\U000115dd\U00011633-\U0001163a\U0001163d\U0001163f-\U00011640\U000116ab\U000116ad\U000116b0-\U000116b5\U000116b7\U0001171d-\U0001171f\U00011722-\U00011725\U00011727-\U0001172b\U0001182f-\U00011837\U00011839-\U0001183a\U00011a01-\U00011a0a\U00011a33-\U00011a38\U00011a3b-\U00011a3e\U00011a47\U00011a51-\U00011a56\U00011a59-\U00011a5b\U00011a8a-\U00011a96\U00011a98-\U00011a99\U00011c30-\U00011c36\U00011c38-\U00011c3d\U00011c3f\U00011c92-\U00011ca7\U00011caa-\U00011cb0\U00011cb2-\U00011cb3\U00011cb5-\U00011cb6\U00011d31-\U00011d36\U00011d3a\U00011d3c-\U00011d3d\U00011d3f-\U00011d45\U00011d47\U00011d90-\U00011d91\U00011d95\U00011d97\U00011ef3-\U00011ef4\U00016af0-\U00016af4\U00016b30-\U00016b36\U00016f8f-\U00016f92\U0001bc9d-\U0001bc9e\U0001d167-\U0001d169\U0001d17b-\U0001d182\U0001d185-\U0001d18b\U0001d1aa-\U0001d1ad\U0001d242-\U0001d244\U0001da00-\U0001da36\U0001da3b-\U0001da6c\U0001da75\U0001da84\U0001da9b-\U0001da9f\U0001daa1-\U0001daaf\U0001e000-\U0001e006\U0001e008-\U0001e018\U0001e01b-\U0001e021\U0001e023-\U0001e024\U0001e026-\U0001e02a\U0001e8d0-\U0001e8d6\U0001e944-\U0001e94a\U000e0100-\U000e01ef' + +Nd = '0-9\u0660-\u0669\u06f0-\u06f9\u07c0-\u07c9\u0966-\u096f\u09e6-\u09ef\u0a66-\u0a6f\u0ae6-\u0aef\u0b66-\u0b6f\u0be6-\u0bef\u0c66-\u0c6f\u0ce6-\u0cef\u0d66-\u0d6f\u0de6-\u0def\u0e50-\u0e59\u0ed0-\u0ed9\u0f20-\u0f29\u1040-\u1049\u1090-\u1099\u17e0-\u17e9\u1810-\u1819\u1946-\u194f\u19d0-\u19d9\u1a80-\u1a89\u1a90-\u1a99\u1b50-\u1b59\u1bb0-\u1bb9\u1c40-\u1c49\u1c50-\u1c59\ua620-\ua629\ua8d0-\ua8d9\ua900-\ua909\ua9d0-\ua9d9\ua9f0-\ua9f9\uaa50-\uaa59\uabf0-\uabf9\uff10-\uff19\U000104a0-\U000104a9\U00010d30-\U00010d39\U00011066-\U0001106f\U000110f0-\U000110f9\U00011136-\U0001113f\U000111d0-\U000111d9\U000112f0-\U000112f9\U00011450-\U00011459\U000114d0-\U000114d9\U00011650-\U00011659\U000116c0-\U000116c9\U00011730-\U00011739\U000118e0-\U000118e9\U00011c50-\U00011c59\U00011d50-\U00011d59\U00011da0-\U00011da9\U00016a60-\U00016a69\U00016b50-\U00016b59\U0001d7ce-\U0001d7ff\U0001e950-\U0001e959' + +Nl = '\u16ee-\u16f0\u2160-\u2182\u2185-\u2188\u3007\u3021-\u3029\u3038-\u303a\ua6e6-\ua6ef\U00010140-\U00010174\U00010341\U0001034a\U000103d1-\U000103d5\U00012400-\U0001246e' + +No = '\xb2-\xb3\xb9\xbc-\xbe\u09f4-\u09f9\u0b72-\u0b77\u0bf0-\u0bf2\u0c78-\u0c7e\u0d58-\u0d5e\u0d70-\u0d78\u0f2a-\u0f33\u1369-\u137c\u17f0-\u17f9\u19da\u2070\u2074-\u2079\u2080-\u2089\u2150-\u215f\u2189\u2460-\u249b\u24ea-\u24ff\u2776-\u2793\u2cfd\u3192-\u3195\u3220-\u3229\u3248-\u324f\u3251-\u325f\u3280-\u3289\u32b1-\u32bf\ua830-\ua835\U00010107-\U00010133\U00010175-\U00010178\U0001018a-\U0001018b\U000102e1-\U000102fb\U00010320-\U00010323\U00010858-\U0001085f\U00010879-\U0001087f\U000108a7-\U000108af\U000108fb-\U000108ff\U00010916-\U0001091b\U000109bc-\U000109bd\U000109c0-\U000109cf\U000109d2-\U000109ff\U00010a40-\U00010a48\U00010a7d-\U00010a7e\U00010a9d-\U00010a9f\U00010aeb-\U00010aef\U00010b58-\U00010b5f\U00010b78-\U00010b7f\U00010ba9-\U00010baf\U00010cfa-\U00010cff\U00010e60-\U00010e7e\U00010f1d-\U00010f26\U00010f51-\U00010f54\U00011052-\U00011065\U000111e1-\U000111f4\U0001173a-\U0001173b\U000118ea-\U000118f2\U00011c5a-\U00011c6c\U00016b5b-\U00016b61\U00016e80-\U00016e96\U0001d2e0-\U0001d2f3\U0001d360-\U0001d378\U0001e8c7-\U0001e8cf\U0001ec71-\U0001ecab\U0001ecad-\U0001ecaf\U0001ecb1-\U0001ecb4\U0001f100-\U0001f10c' + +Pc = '_\u203f-\u2040\u2054\ufe33-\ufe34\ufe4d-\ufe4f\uff3f' + +Pd = '\\-\u058a\u05be\u1400\u1806\u2010-\u2015\u2e17\u2e1a\u2e3a-\u2e3b\u2e40\u301c\u3030\u30a0\ufe31-\ufe32\ufe58\ufe63\uff0d' + +Pe = ')\\]}\u0f3b\u0f3d\u169c\u2046\u207e\u208e\u2309\u230b\u232a\u2769\u276b\u276d\u276f\u2771\u2773\u2775\u27c6\u27e7\u27e9\u27eb\u27ed\u27ef\u2984\u2986\u2988\u298a\u298c\u298e\u2990\u2992\u2994\u2996\u2998\u29d9\u29db\u29fd\u2e23\u2e25\u2e27\u2e29\u3009\u300b\u300d\u300f\u3011\u3015\u3017\u3019\u301b\u301e-\u301f\ufd3e\ufe18\ufe36\ufe38\ufe3a\ufe3c\ufe3e\ufe40\ufe42\ufe44\ufe48\ufe5a\ufe5c\ufe5e\uff09\uff3d\uff5d\uff60\uff63' + +Pf = '\xbb\u2019\u201d\u203a\u2e03\u2e05\u2e0a\u2e0d\u2e1d\u2e21' + +Pi = '\xab\u2018\u201b-\u201c\u201f\u2039\u2e02\u2e04\u2e09\u2e0c\u2e1c\u2e20' + +Po = "!-#%-'*,.-/:-;?-@\\\\\xa1\xa7\xb6-\xb7\xbf\u037e\u0387\u055a-\u055f\u0589\u05c0\u05c3\u05c6\u05f3-\u05f4\u0609-\u060a\u060c-\u060d\u061b\u061e-\u061f\u066a-\u066d\u06d4\u0700-\u070d\u07f7-\u07f9\u0830-\u083e\u085e\u0964-\u0965\u0970\u09fd\u0a76\u0af0\u0c84\u0df4\u0e4f\u0e5a-\u0e5b\u0f04-\u0f12\u0f14\u0f85\u0fd0-\u0fd4\u0fd9-\u0fda\u104a-\u104f\u10fb\u1360-\u1368\u166d-\u166e\u16eb-\u16ed\u1735-\u1736\u17d4-\u17d6\u17d8-\u17da\u1800-\u1805\u1807-\u180a\u1944-\u1945\u1a1e-\u1a1f\u1aa0-\u1aa6\u1aa8-\u1aad\u1b5a-\u1b60\u1bfc-\u1bff\u1c3b-\u1c3f\u1c7e-\u1c7f\u1cc0-\u1cc7\u1cd3\u2016-\u2017\u2020-\u2027\u2030-\u2038\u203b-\u203e\u2041-\u2043\u2047-\u2051\u2053\u2055-\u205e\u2cf9-\u2cfc\u2cfe-\u2cff\u2d70\u2e00-\u2e01\u2e06-\u2e08\u2e0b\u2e0e-\u2e16\u2e18-\u2e19\u2e1b\u2e1e-\u2e1f\u2e2a-\u2e2e\u2e30-\u2e39\u2e3c-\u2e3f\u2e41\u2e43-\u2e4e\u3001-\u3003\u303d\u30fb\ua4fe-\ua4ff\ua60d-\ua60f\ua673\ua67e\ua6f2-\ua6f7\ua874-\ua877\ua8ce-\ua8cf\ua8f8-\ua8fa\ua8fc\ua92e-\ua92f\ua95f\ua9c1-\ua9cd\ua9de-\ua9df\uaa5c-\uaa5f\uaade-\uaadf\uaaf0-\uaaf1\uabeb\ufe10-\ufe16\ufe19\ufe30\ufe45-\ufe46\ufe49-\ufe4c\ufe50-\ufe52\ufe54-\ufe57\ufe5f-\ufe61\ufe68\ufe6a-\ufe6b\uff01-\uff03\uff05-\uff07\uff0a\uff0c\uff0e-\uff0f\uff1a-\uff1b\uff1f-\uff20\uff3c\uff61\uff64-\uff65\U00010100-\U00010102\U0001039f\U000103d0\U0001056f\U00010857\U0001091f\U0001093f\U00010a50-\U00010a58\U00010a7f\U00010af0-\U00010af6\U00010b39-\U00010b3f\U00010b99-\U00010b9c\U00010f55-\U00010f59\U00011047-\U0001104d\U000110bb-\U000110bc\U000110be-\U000110c1\U00011140-\U00011143\U00011174-\U00011175\U000111c5-\U000111c8\U000111cd\U000111db\U000111dd-\U000111df\U00011238-\U0001123d\U000112a9\U0001144b-\U0001144f\U0001145b\U0001145d\U000114c6\U000115c1-\U000115d7\U00011641-\U00011643\U00011660-\U0001166c\U0001173c-\U0001173e\U0001183b\U00011a3f-\U00011a46\U00011a9a-\U00011a9c\U00011a9e-\U00011aa2\U00011c41-\U00011c45\U00011c70-\U00011c71\U00011ef7-\U00011ef8\U00012470-\U00012474\U00016a6e-\U00016a6f\U00016af5\U00016b37-\U00016b3b\U00016b44\U00016e97-\U00016e9a\U0001bc9f\U0001da87-\U0001da8b\U0001e95e-\U0001e95f" + +Ps = '(\\[{\u0f3a\u0f3c\u169b\u201a\u201e\u2045\u207d\u208d\u2308\u230a\u2329\u2768\u276a\u276c\u276e\u2770\u2772\u2774\u27c5\u27e6\u27e8\u27ea\u27ec\u27ee\u2983\u2985\u2987\u2989\u298b\u298d\u298f\u2991\u2993\u2995\u2997\u29d8\u29da\u29fc\u2e22\u2e24\u2e26\u2e28\u2e42\u3008\u300a\u300c\u300e\u3010\u3014\u3016\u3018\u301a\u301d\ufd3f\ufe17\ufe35\ufe37\ufe39\ufe3b\ufe3d\ufe3f\ufe41\ufe43\ufe47\ufe59\ufe5b\ufe5d\uff08\uff3b\uff5b\uff5f\uff62' + +Sc = '$\xa2-\xa5\u058f\u060b\u07fe-\u07ff\u09f2-\u09f3\u09fb\u0af1\u0bf9\u0e3f\u17db\u20a0-\u20bf\ua838\ufdfc\ufe69\uff04\uffe0-\uffe1\uffe5-\uffe6\U0001ecb0' + +Sk = '\\^`\xa8\xaf\xb4\xb8\u02c2-\u02c5\u02d2-\u02df\u02e5-\u02eb\u02ed\u02ef-\u02ff\u0375\u0384-\u0385\u1fbd\u1fbf-\u1fc1\u1fcd-\u1fcf\u1fdd-\u1fdf\u1fed-\u1fef\u1ffd-\u1ffe\u309b-\u309c\ua700-\ua716\ua720-\ua721\ua789-\ua78a\uab5b\ufbb2-\ufbc1\uff3e\uff40\uffe3\U0001f3fb-\U0001f3ff' + +Sm = '+<->|~\xac\xb1\xd7\xf7\u03f6\u0606-\u0608\u2044\u2052\u207a-\u207c\u208a-\u208c\u2118\u2140-\u2144\u214b\u2190-\u2194\u219a-\u219b\u21a0\u21a3\u21a6\u21ae\u21ce-\u21cf\u21d2\u21d4\u21f4-\u22ff\u2320-\u2321\u237c\u239b-\u23b3\u23dc-\u23e1\u25b7\u25c1\u25f8-\u25ff\u266f\u27c0-\u27c4\u27c7-\u27e5\u27f0-\u27ff\u2900-\u2982\u2999-\u29d7\u29dc-\u29fb\u29fe-\u2aff\u2b30-\u2b44\u2b47-\u2b4c\ufb29\ufe62\ufe64-\ufe66\uff0b\uff1c-\uff1e\uff5c\uff5e\uffe2\uffe9-\uffec\U0001d6c1\U0001d6db\U0001d6fb\U0001d715\U0001d735\U0001d74f\U0001d76f\U0001d789\U0001d7a9\U0001d7c3\U0001eef0-\U0001eef1' + +So = '\xa6\xa9\xae\xb0\u0482\u058d-\u058e\u060e-\u060f\u06de\u06e9\u06fd-\u06fe\u07f6\u09fa\u0b70\u0bf3-\u0bf8\u0bfa\u0c7f\u0d4f\u0d79\u0f01-\u0f03\u0f13\u0f15-\u0f17\u0f1a-\u0f1f\u0f34\u0f36\u0f38\u0fbe-\u0fc5\u0fc7-\u0fcc\u0fce-\u0fcf\u0fd5-\u0fd8\u109e-\u109f\u1390-\u1399\u1940\u19de-\u19ff\u1b61-\u1b6a\u1b74-\u1b7c\u2100-\u2101\u2103-\u2106\u2108-\u2109\u2114\u2116-\u2117\u211e-\u2123\u2125\u2127\u2129\u212e\u213a-\u213b\u214a\u214c-\u214d\u214f\u218a-\u218b\u2195-\u2199\u219c-\u219f\u21a1-\u21a2\u21a4-\u21a5\u21a7-\u21ad\u21af-\u21cd\u21d0-\u21d1\u21d3\u21d5-\u21f3\u2300-\u2307\u230c-\u231f\u2322-\u2328\u232b-\u237b\u237d-\u239a\u23b4-\u23db\u23e2-\u2426\u2440-\u244a\u249c-\u24e9\u2500-\u25b6\u25b8-\u25c0\u25c2-\u25f7\u2600-\u266e\u2670-\u2767\u2794-\u27bf\u2800-\u28ff\u2b00-\u2b2f\u2b45-\u2b46\u2b4d-\u2b73\u2b76-\u2b95\u2b98-\u2bc8\u2bca-\u2bfe\u2ce5-\u2cea\u2e80-\u2e99\u2e9b-\u2ef3\u2f00-\u2fd5\u2ff0-\u2ffb\u3004\u3012-\u3013\u3020\u3036-\u3037\u303e-\u303f\u3190-\u3191\u3196-\u319f\u31c0-\u31e3\u3200-\u321e\u322a-\u3247\u3250\u3260-\u327f\u328a-\u32b0\u32c0-\u32fe\u3300-\u33ff\u4dc0-\u4dff\ua490-\ua4c6\ua828-\ua82b\ua836-\ua837\ua839\uaa77-\uaa79\ufdfd\uffe4\uffe8\uffed-\uffee\ufffc-\ufffd\U00010137-\U0001013f\U00010179-\U00010189\U0001018c-\U0001018e\U00010190-\U0001019b\U000101a0\U000101d0-\U000101fc\U00010877-\U00010878\U00010ac8\U0001173f\U00016b3c-\U00016b3f\U00016b45\U0001bc9c\U0001d000-\U0001d0f5\U0001d100-\U0001d126\U0001d129-\U0001d164\U0001d16a-\U0001d16c\U0001d183-\U0001d184\U0001d18c-\U0001d1a9\U0001d1ae-\U0001d1e8\U0001d200-\U0001d241\U0001d245\U0001d300-\U0001d356\U0001d800-\U0001d9ff\U0001da37-\U0001da3a\U0001da6d-\U0001da74\U0001da76-\U0001da83\U0001da85-\U0001da86\U0001ecac\U0001f000-\U0001f02b\U0001f030-\U0001f093\U0001f0a0-\U0001f0ae\U0001f0b1-\U0001f0bf\U0001f0c1-\U0001f0cf\U0001f0d1-\U0001f0f5\U0001f110-\U0001f16b\U0001f170-\U0001f1ac\U0001f1e6-\U0001f202\U0001f210-\U0001f23b\U0001f240-\U0001f248\U0001f250-\U0001f251\U0001f260-\U0001f265\U0001f300-\U0001f3fa\U0001f400-\U0001f6d4\U0001f6e0-\U0001f6ec\U0001f6f0-\U0001f6f9\U0001f700-\U0001f773\U0001f780-\U0001f7d8\U0001f800-\U0001f80b\U0001f810-\U0001f847\U0001f850-\U0001f859\U0001f860-\U0001f887\U0001f890-\U0001f8ad\U0001f900-\U0001f90b\U0001f910-\U0001f93e\U0001f940-\U0001f970\U0001f973-\U0001f976\U0001f97a\U0001f97c-\U0001f9a2\U0001f9b0-\U0001f9b9\U0001f9c0-\U0001f9c2\U0001f9d0-\U0001f9ff\U0001fa60-\U0001fa6d' + +Zl = '\u2028' + +Zp = '\u2029' + +Zs = ' \xa0\u1680\u2000-\u200a\u202f\u205f\u3000' + +xid_continue = '0-9A-Z_a-z\xaa\xb5\xb7\xba\xc0-\xd6\xd8-\xf6\xf8-\u02c1\u02c6-\u02d1\u02e0-\u02e4\u02ec\u02ee\u0300-\u0374\u0376-\u0377\u037b-\u037d\u037f\u0386-\u038a\u038c\u038e-\u03a1\u03a3-\u03f5\u03f7-\u0481\u0483-\u0487\u048a-\u052f\u0531-\u0556\u0559\u0560-\u0588\u0591-\u05bd\u05bf\u05c1-\u05c2\u05c4-\u05c5\u05c7\u05d0-\u05ea\u05ef-\u05f2\u0610-\u061a\u0620-\u0669\u066e-\u06d3\u06d5-\u06dc\u06df-\u06e8\u06ea-\u06fc\u06ff\u0710-\u074a\u074d-\u07b1\u07c0-\u07f5\u07fa\u07fd\u0800-\u082d\u0840-\u085b\u0860-\u086a\u08a0-\u08b4\u08b6-\u08bd\u08d3-\u08e1\u08e3-\u0963\u0966-\u096f\u0971-\u0983\u0985-\u098c\u098f-\u0990\u0993-\u09a8\u09aa-\u09b0\u09b2\u09b6-\u09b9\u09bc-\u09c4\u09c7-\u09c8\u09cb-\u09ce\u09d7\u09dc-\u09dd\u09df-\u09e3\u09e6-\u09f1\u09fc\u09fe\u0a01-\u0a03\u0a05-\u0a0a\u0a0f-\u0a10\u0a13-\u0a28\u0a2a-\u0a30\u0a32-\u0a33\u0a35-\u0a36\u0a38-\u0a39\u0a3c\u0a3e-\u0a42\u0a47-\u0a48\u0a4b-\u0a4d\u0a51\u0a59-\u0a5c\u0a5e\u0a66-\u0a75\u0a81-\u0a83\u0a85-\u0a8d\u0a8f-\u0a91\u0a93-\u0aa8\u0aaa-\u0ab0\u0ab2-\u0ab3\u0ab5-\u0ab9\u0abc-\u0ac5\u0ac7-\u0ac9\u0acb-\u0acd\u0ad0\u0ae0-\u0ae3\u0ae6-\u0aef\u0af9-\u0aff\u0b01-\u0b03\u0b05-\u0b0c\u0b0f-\u0b10\u0b13-\u0b28\u0b2a-\u0b30\u0b32-\u0b33\u0b35-\u0b39\u0b3c-\u0b44\u0b47-\u0b48\u0b4b-\u0b4d\u0b56-\u0b57\u0b5c-\u0b5d\u0b5f-\u0b63\u0b66-\u0b6f\u0b71\u0b82-\u0b83\u0b85-\u0b8a\u0b8e-\u0b90\u0b92-\u0b95\u0b99-\u0b9a\u0b9c\u0b9e-\u0b9f\u0ba3-\u0ba4\u0ba8-\u0baa\u0bae-\u0bb9\u0bbe-\u0bc2\u0bc6-\u0bc8\u0bca-\u0bcd\u0bd0\u0bd7\u0be6-\u0bef\u0c00-\u0c0c\u0c0e-\u0c10\u0c12-\u0c28\u0c2a-\u0c39\u0c3d-\u0c44\u0c46-\u0c48\u0c4a-\u0c4d\u0c55-\u0c56\u0c58-\u0c5a\u0c60-\u0c63\u0c66-\u0c6f\u0c80-\u0c83\u0c85-\u0c8c\u0c8e-\u0c90\u0c92-\u0ca8\u0caa-\u0cb3\u0cb5-\u0cb9\u0cbc-\u0cc4\u0cc6-\u0cc8\u0cca-\u0ccd\u0cd5-\u0cd6\u0cde\u0ce0-\u0ce3\u0ce6-\u0cef\u0cf1-\u0cf2\u0d00-\u0d03\u0d05-\u0d0c\u0d0e-\u0d10\u0d12-\u0d44\u0d46-\u0d48\u0d4a-\u0d4e\u0d54-\u0d57\u0d5f-\u0d63\u0d66-\u0d6f\u0d7a-\u0d7f\u0d82-\u0d83\u0d85-\u0d96\u0d9a-\u0db1\u0db3-\u0dbb\u0dbd\u0dc0-\u0dc6\u0dca\u0dcf-\u0dd4\u0dd6\u0dd8-\u0ddf\u0de6-\u0def\u0df2-\u0df3\u0e01-\u0e3a\u0e40-\u0e4e\u0e50-\u0e59\u0e81-\u0e82\u0e84\u0e87-\u0e88\u0e8a\u0e8d\u0e94-\u0e97\u0e99-\u0e9f\u0ea1-\u0ea3\u0ea5\u0ea7\u0eaa-\u0eab\u0ead-\u0eb9\u0ebb-\u0ebd\u0ec0-\u0ec4\u0ec6\u0ec8-\u0ecd\u0ed0-\u0ed9\u0edc-\u0edf\u0f00\u0f18-\u0f19\u0f20-\u0f29\u0f35\u0f37\u0f39\u0f3e-\u0f47\u0f49-\u0f6c\u0f71-\u0f84\u0f86-\u0f97\u0f99-\u0fbc\u0fc6\u1000-\u1049\u1050-\u109d\u10a0-\u10c5\u10c7\u10cd\u10d0-\u10fa\u10fc-\u1248\u124a-\u124d\u1250-\u1256\u1258\u125a-\u125d\u1260-\u1288\u128a-\u128d\u1290-\u12b0\u12b2-\u12b5\u12b8-\u12be\u12c0\u12c2-\u12c5\u12c8-\u12d6\u12d8-\u1310\u1312-\u1315\u1318-\u135a\u135d-\u135f\u1369-\u1371\u1380-\u138f\u13a0-\u13f5\u13f8-\u13fd\u1401-\u166c\u166f-\u167f\u1681-\u169a\u16a0-\u16ea\u16ee-\u16f8\u1700-\u170c\u170e-\u1714\u1720-\u1734\u1740-\u1753\u1760-\u176c\u176e-\u1770\u1772-\u1773\u1780-\u17d3\u17d7\u17dc-\u17dd\u17e0-\u17e9\u180b-\u180d\u1810-\u1819\u1820-\u1878\u1880-\u18aa\u18b0-\u18f5\u1900-\u191e\u1920-\u192b\u1930-\u193b\u1946-\u196d\u1970-\u1974\u1980-\u19ab\u19b0-\u19c9\u19d0-\u19da\u1a00-\u1a1b\u1a20-\u1a5e\u1a60-\u1a7c\u1a7f-\u1a89\u1a90-\u1a99\u1aa7\u1ab0-\u1abd\u1b00-\u1b4b\u1b50-\u1b59\u1b6b-\u1b73\u1b80-\u1bf3\u1c00-\u1c37\u1c40-\u1c49\u1c4d-\u1c7d\u1c80-\u1c88\u1c90-\u1cba\u1cbd-\u1cbf\u1cd0-\u1cd2\u1cd4-\u1cf9\u1d00-\u1df9\u1dfb-\u1f15\u1f18-\u1f1d\u1f20-\u1f45\u1f48-\u1f4d\u1f50-\u1f57\u1f59\u1f5b\u1f5d\u1f5f-\u1f7d\u1f80-\u1fb4\u1fb6-\u1fbc\u1fbe\u1fc2-\u1fc4\u1fc6-\u1fcc\u1fd0-\u1fd3\u1fd6-\u1fdb\u1fe0-\u1fec\u1ff2-\u1ff4\u1ff6-\u1ffc\u203f-\u2040\u2054\u2071\u207f\u2090-\u209c\u20d0-\u20dc\u20e1\u20e5-\u20f0\u2102\u2107\u210a-\u2113\u2115\u2118-\u211d\u2124\u2126\u2128\u212a-\u2139\u213c-\u213f\u2145-\u2149\u214e\u2160-\u2188\u2c00-\u2c2e\u2c30-\u2c5e\u2c60-\u2ce4\u2ceb-\u2cf3\u2d00-\u2d25\u2d27\u2d2d\u2d30-\u2d67\u2d6f\u2d7f-\u2d96\u2da0-\u2da6\u2da8-\u2dae\u2db0-\u2db6\u2db8-\u2dbe\u2dc0-\u2dc6\u2dc8-\u2dce\u2dd0-\u2dd6\u2dd8-\u2dde\u2de0-\u2dff\u3005-\u3007\u3021-\u302f\u3031-\u3035\u3038-\u303c\u3041-\u3096\u3099-\u309a\u309d-\u309f\u30a1-\u30fa\u30fc-\u30ff\u3105-\u312f\u3131-\u318e\u31a0-\u31ba\u31f0-\u31ff\u3400-\u4db5\u4e00-\u9fef\ua000-\ua48c\ua4d0-\ua4fd\ua500-\ua60c\ua610-\ua62b\ua640-\ua66f\ua674-\ua67d\ua67f-\ua6f1\ua717-\ua71f\ua722-\ua788\ua78b-\ua7b9\ua7f7-\ua827\ua840-\ua873\ua880-\ua8c5\ua8d0-\ua8d9\ua8e0-\ua8f7\ua8fb\ua8fd-\ua92d\ua930-\ua953\ua960-\ua97c\ua980-\ua9c0\ua9cf-\ua9d9\ua9e0-\ua9fe\uaa00-\uaa36\uaa40-\uaa4d\uaa50-\uaa59\uaa60-\uaa76\uaa7a-\uaac2\uaadb-\uaadd\uaae0-\uaaef\uaaf2-\uaaf6\uab01-\uab06\uab09-\uab0e\uab11-\uab16\uab20-\uab26\uab28-\uab2e\uab30-\uab5a\uab5c-\uab65\uab70-\uabea\uabec-\uabed\uabf0-\uabf9\uac00-\ud7a3\ud7b0-\ud7c6\ud7cb-\ud7fb\uf900-\ufa6d\ufa70-\ufad9\ufb00-\ufb06\ufb13-\ufb17\ufb1d-\ufb28\ufb2a-\ufb36\ufb38-\ufb3c\ufb3e\ufb40-\ufb41\ufb43-\ufb44\ufb46-\ufbb1\ufbd3-\ufc5d\ufc64-\ufd3d\ufd50-\ufd8f\ufd92-\ufdc7\ufdf0-\ufdf9\ufe00-\ufe0f\ufe20-\ufe2f\ufe33-\ufe34\ufe4d-\ufe4f\ufe71\ufe73\ufe77\ufe79\ufe7b\ufe7d\ufe7f-\ufefc\uff10-\uff19\uff21-\uff3a\uff3f\uff41-\uff5a\uff66-\uffbe\uffc2-\uffc7\uffca-\uffcf\uffd2-\uffd7\uffda-\uffdc\U00010000-\U0001000b\U0001000d-\U00010026\U00010028-\U0001003a\U0001003c-\U0001003d\U0001003f-\U0001004d\U00010050-\U0001005d\U00010080-\U000100fa\U00010140-\U00010174\U000101fd\U00010280-\U0001029c\U000102a0-\U000102d0\U000102e0\U00010300-\U0001031f\U0001032d-\U0001034a\U00010350-\U0001037a\U00010380-\U0001039d\U000103a0-\U000103c3\U000103c8-\U000103cf\U000103d1-\U000103d5\U00010400-\U0001049d\U000104a0-\U000104a9\U000104b0-\U000104d3\U000104d8-\U000104fb\U00010500-\U00010527\U00010530-\U00010563\U00010600-\U00010736\U00010740-\U00010755\U00010760-\U00010767\U00010800-\U00010805\U00010808\U0001080a-\U00010835\U00010837-\U00010838\U0001083c\U0001083f-\U00010855\U00010860-\U00010876\U00010880-\U0001089e\U000108e0-\U000108f2\U000108f4-\U000108f5\U00010900-\U00010915\U00010920-\U00010939\U00010980-\U000109b7\U000109be-\U000109bf\U00010a00-\U00010a03\U00010a05-\U00010a06\U00010a0c-\U00010a13\U00010a15-\U00010a17\U00010a19-\U00010a35\U00010a38-\U00010a3a\U00010a3f\U00010a60-\U00010a7c\U00010a80-\U00010a9c\U00010ac0-\U00010ac7\U00010ac9-\U00010ae6\U00010b00-\U00010b35\U00010b40-\U00010b55\U00010b60-\U00010b72\U00010b80-\U00010b91\U00010c00-\U00010c48\U00010c80-\U00010cb2\U00010cc0-\U00010cf2\U00010d00-\U00010d27\U00010d30-\U00010d39\U00010f00-\U00010f1c\U00010f27\U00010f30-\U00010f50\U00011000-\U00011046\U00011066-\U0001106f\U0001107f-\U000110ba\U000110d0-\U000110e8\U000110f0-\U000110f9\U00011100-\U00011134\U00011136-\U0001113f\U00011144-\U00011146\U00011150-\U00011173\U00011176\U00011180-\U000111c4\U000111c9-\U000111cc\U000111d0-\U000111da\U000111dc\U00011200-\U00011211\U00011213-\U00011237\U0001123e\U00011280-\U00011286\U00011288\U0001128a-\U0001128d\U0001128f-\U0001129d\U0001129f-\U000112a8\U000112b0-\U000112ea\U000112f0-\U000112f9\U00011300-\U00011303\U00011305-\U0001130c\U0001130f-\U00011310\U00011313-\U00011328\U0001132a-\U00011330\U00011332-\U00011333\U00011335-\U00011339\U0001133b-\U00011344\U00011347-\U00011348\U0001134b-\U0001134d\U00011350\U00011357\U0001135d-\U00011363\U00011366-\U0001136c\U00011370-\U00011374\U00011400-\U0001144a\U00011450-\U00011459\U0001145e\U00011480-\U000114c5\U000114c7\U000114d0-\U000114d9\U00011580-\U000115b5\U000115b8-\U000115c0\U000115d8-\U000115dd\U00011600-\U00011640\U00011644\U00011650-\U00011659\U00011680-\U000116b7\U000116c0-\U000116c9\U00011700-\U0001171a\U0001171d-\U0001172b\U00011730-\U00011739\U00011800-\U0001183a\U000118a0-\U000118e9\U000118ff\U00011a00-\U00011a3e\U00011a47\U00011a50-\U00011a83\U00011a86-\U00011a99\U00011a9d\U00011ac0-\U00011af8\U00011c00-\U00011c08\U00011c0a-\U00011c36\U00011c38-\U00011c40\U00011c50-\U00011c59\U00011c72-\U00011c8f\U00011c92-\U00011ca7\U00011ca9-\U00011cb6\U00011d00-\U00011d06\U00011d08-\U00011d09\U00011d0b-\U00011d36\U00011d3a\U00011d3c-\U00011d3d\U00011d3f-\U00011d47\U00011d50-\U00011d59\U00011d60-\U00011d65\U00011d67-\U00011d68\U00011d6a-\U00011d8e\U00011d90-\U00011d91\U00011d93-\U00011d98\U00011da0-\U00011da9\U00011ee0-\U00011ef6\U00012000-\U00012399\U00012400-\U0001246e\U00012480-\U00012543\U00013000-\U0001342e\U00014400-\U00014646\U00016800-\U00016a38\U00016a40-\U00016a5e\U00016a60-\U00016a69\U00016ad0-\U00016aed\U00016af0-\U00016af4\U00016b00-\U00016b36\U00016b40-\U00016b43\U00016b50-\U00016b59\U00016b63-\U00016b77\U00016b7d-\U00016b8f\U00016e40-\U00016e7f\U00016f00-\U00016f44\U00016f50-\U00016f7e\U00016f8f-\U00016f9f\U00016fe0-\U00016fe1\U00017000-\U000187f1\U00018800-\U00018af2\U0001b000-\U0001b11e\U0001b170-\U0001b2fb\U0001bc00-\U0001bc6a\U0001bc70-\U0001bc7c\U0001bc80-\U0001bc88\U0001bc90-\U0001bc99\U0001bc9d-\U0001bc9e\U0001d165-\U0001d169\U0001d16d-\U0001d172\U0001d17b-\U0001d182\U0001d185-\U0001d18b\U0001d1aa-\U0001d1ad\U0001d242-\U0001d244\U0001d400-\U0001d454\U0001d456-\U0001d49c\U0001d49e-\U0001d49f\U0001d4a2\U0001d4a5-\U0001d4a6\U0001d4a9-\U0001d4ac\U0001d4ae-\U0001d4b9\U0001d4bb\U0001d4bd-\U0001d4c3\U0001d4c5-\U0001d505\U0001d507-\U0001d50a\U0001d50d-\U0001d514\U0001d516-\U0001d51c\U0001d51e-\U0001d539\U0001d53b-\U0001d53e\U0001d540-\U0001d544\U0001d546\U0001d54a-\U0001d550\U0001d552-\U0001d6a5\U0001d6a8-\U0001d6c0\U0001d6c2-\U0001d6da\U0001d6dc-\U0001d6fa\U0001d6fc-\U0001d714\U0001d716-\U0001d734\U0001d736-\U0001d74e\U0001d750-\U0001d76e\U0001d770-\U0001d788\U0001d78a-\U0001d7a8\U0001d7aa-\U0001d7c2\U0001d7c4-\U0001d7cb\U0001d7ce-\U0001d7ff\U0001da00-\U0001da36\U0001da3b-\U0001da6c\U0001da75\U0001da84\U0001da9b-\U0001da9f\U0001daa1-\U0001daaf\U0001e000-\U0001e006\U0001e008-\U0001e018\U0001e01b-\U0001e021\U0001e023-\U0001e024\U0001e026-\U0001e02a\U0001e800-\U0001e8c4\U0001e8d0-\U0001e8d6\U0001e900-\U0001e94a\U0001e950-\U0001e959\U0001ee00-\U0001ee03\U0001ee05-\U0001ee1f\U0001ee21-\U0001ee22\U0001ee24\U0001ee27\U0001ee29-\U0001ee32\U0001ee34-\U0001ee37\U0001ee39\U0001ee3b\U0001ee42\U0001ee47\U0001ee49\U0001ee4b\U0001ee4d-\U0001ee4f\U0001ee51-\U0001ee52\U0001ee54\U0001ee57\U0001ee59\U0001ee5b\U0001ee5d\U0001ee5f\U0001ee61-\U0001ee62\U0001ee64\U0001ee67-\U0001ee6a\U0001ee6c-\U0001ee72\U0001ee74-\U0001ee77\U0001ee79-\U0001ee7c\U0001ee7e\U0001ee80-\U0001ee89\U0001ee8b-\U0001ee9b\U0001eea1-\U0001eea3\U0001eea5-\U0001eea9\U0001eeab-\U0001eebb\U00020000-\U0002a6d6\U0002a700-\U0002b734\U0002b740-\U0002b81d\U0002b820-\U0002cea1\U0002ceb0-\U0002ebe0\U0002f800-\U0002fa1d\U000e0100-\U000e01ef' + +xid_start = 'A-Z_a-z\xaa\xb5\xba\xc0-\xd6\xd8-\xf6\xf8-\u02c1\u02c6-\u02d1\u02e0-\u02e4\u02ec\u02ee\u0370-\u0374\u0376-\u0377\u037b-\u037d\u037f\u0386\u0388-\u038a\u038c\u038e-\u03a1\u03a3-\u03f5\u03f7-\u0481\u048a-\u052f\u0531-\u0556\u0559\u0560-\u0588\u05d0-\u05ea\u05ef-\u05f2\u0620-\u064a\u066e-\u066f\u0671-\u06d3\u06d5\u06e5-\u06e6\u06ee-\u06ef\u06fa-\u06fc\u06ff\u0710\u0712-\u072f\u074d-\u07a5\u07b1\u07ca-\u07ea\u07f4-\u07f5\u07fa\u0800-\u0815\u081a\u0824\u0828\u0840-\u0858\u0860-\u086a\u08a0-\u08b4\u08b6-\u08bd\u0904-\u0939\u093d\u0950\u0958-\u0961\u0971-\u0980\u0985-\u098c\u098f-\u0990\u0993-\u09a8\u09aa-\u09b0\u09b2\u09b6-\u09b9\u09bd\u09ce\u09dc-\u09dd\u09df-\u09e1\u09f0-\u09f1\u09fc\u0a05-\u0a0a\u0a0f-\u0a10\u0a13-\u0a28\u0a2a-\u0a30\u0a32-\u0a33\u0a35-\u0a36\u0a38-\u0a39\u0a59-\u0a5c\u0a5e\u0a72-\u0a74\u0a85-\u0a8d\u0a8f-\u0a91\u0a93-\u0aa8\u0aaa-\u0ab0\u0ab2-\u0ab3\u0ab5-\u0ab9\u0abd\u0ad0\u0ae0-\u0ae1\u0af9\u0b05-\u0b0c\u0b0f-\u0b10\u0b13-\u0b28\u0b2a-\u0b30\u0b32-\u0b33\u0b35-\u0b39\u0b3d\u0b5c-\u0b5d\u0b5f-\u0b61\u0b71\u0b83\u0b85-\u0b8a\u0b8e-\u0b90\u0b92-\u0b95\u0b99-\u0b9a\u0b9c\u0b9e-\u0b9f\u0ba3-\u0ba4\u0ba8-\u0baa\u0bae-\u0bb9\u0bd0\u0c05-\u0c0c\u0c0e-\u0c10\u0c12-\u0c28\u0c2a-\u0c39\u0c3d\u0c58-\u0c5a\u0c60-\u0c61\u0c80\u0c85-\u0c8c\u0c8e-\u0c90\u0c92-\u0ca8\u0caa-\u0cb3\u0cb5-\u0cb9\u0cbd\u0cde\u0ce0-\u0ce1\u0cf1-\u0cf2\u0d05-\u0d0c\u0d0e-\u0d10\u0d12-\u0d3a\u0d3d\u0d4e\u0d54-\u0d56\u0d5f-\u0d61\u0d7a-\u0d7f\u0d85-\u0d96\u0d9a-\u0db1\u0db3-\u0dbb\u0dbd\u0dc0-\u0dc6\u0e01-\u0e30\u0e32\u0e40-\u0e46\u0e81-\u0e82\u0e84\u0e87-\u0e88\u0e8a\u0e8d\u0e94-\u0e97\u0e99-\u0e9f\u0ea1-\u0ea3\u0ea5\u0ea7\u0eaa-\u0eab\u0ead-\u0eb0\u0eb2\u0ebd\u0ec0-\u0ec4\u0ec6\u0edc-\u0edf\u0f00\u0f40-\u0f47\u0f49-\u0f6c\u0f88-\u0f8c\u1000-\u102a\u103f\u1050-\u1055\u105a-\u105d\u1061\u1065-\u1066\u106e-\u1070\u1075-\u1081\u108e\u10a0-\u10c5\u10c7\u10cd\u10d0-\u10fa\u10fc-\u1248\u124a-\u124d\u1250-\u1256\u1258\u125a-\u125d\u1260-\u1288\u128a-\u128d\u1290-\u12b0\u12b2-\u12b5\u12b8-\u12be\u12c0\u12c2-\u12c5\u12c8-\u12d6\u12d8-\u1310\u1312-\u1315\u1318-\u135a\u1380-\u138f\u13a0-\u13f5\u13f8-\u13fd\u1401-\u166c\u166f-\u167f\u1681-\u169a\u16a0-\u16ea\u16ee-\u16f8\u1700-\u170c\u170e-\u1711\u1720-\u1731\u1740-\u1751\u1760-\u176c\u176e-\u1770\u1780-\u17b3\u17d7\u17dc\u1820-\u1878\u1880-\u18a8\u18aa\u18b0-\u18f5\u1900-\u191e\u1950-\u196d\u1970-\u1974\u1980-\u19ab\u19b0-\u19c9\u1a00-\u1a16\u1a20-\u1a54\u1aa7\u1b05-\u1b33\u1b45-\u1b4b\u1b83-\u1ba0\u1bae-\u1baf\u1bba-\u1be5\u1c00-\u1c23\u1c4d-\u1c4f\u1c5a-\u1c7d\u1c80-\u1c88\u1c90-\u1cba\u1cbd-\u1cbf\u1ce9-\u1cec\u1cee-\u1cf1\u1cf5-\u1cf6\u1d00-\u1dbf\u1e00-\u1f15\u1f18-\u1f1d\u1f20-\u1f45\u1f48-\u1f4d\u1f50-\u1f57\u1f59\u1f5b\u1f5d\u1f5f-\u1f7d\u1f80-\u1fb4\u1fb6-\u1fbc\u1fbe\u1fc2-\u1fc4\u1fc6-\u1fcc\u1fd0-\u1fd3\u1fd6-\u1fdb\u1fe0-\u1fec\u1ff2-\u1ff4\u1ff6-\u1ffc\u2071\u207f\u2090-\u209c\u2102\u2107\u210a-\u2113\u2115\u2118-\u211d\u2124\u2126\u2128\u212a-\u2139\u213c-\u213f\u2145-\u2149\u214e\u2160-\u2188\u2c00-\u2c2e\u2c30-\u2c5e\u2c60-\u2ce4\u2ceb-\u2cee\u2cf2-\u2cf3\u2d00-\u2d25\u2d27\u2d2d\u2d30-\u2d67\u2d6f\u2d80-\u2d96\u2da0-\u2da6\u2da8-\u2dae\u2db0-\u2db6\u2db8-\u2dbe\u2dc0-\u2dc6\u2dc8-\u2dce\u2dd0-\u2dd6\u2dd8-\u2dde\u3005-\u3007\u3021-\u3029\u3031-\u3035\u3038-\u303c\u3041-\u3096\u309d-\u309f\u30a1-\u30fa\u30fc-\u30ff\u3105-\u312f\u3131-\u318e\u31a0-\u31ba\u31f0-\u31ff\u3400-\u4db5\u4e00-\u9fef\ua000-\ua48c\ua4d0-\ua4fd\ua500-\ua60c\ua610-\ua61f\ua62a-\ua62b\ua640-\ua66e\ua67f-\ua69d\ua6a0-\ua6ef\ua717-\ua71f\ua722-\ua788\ua78b-\ua7b9\ua7f7-\ua801\ua803-\ua805\ua807-\ua80a\ua80c-\ua822\ua840-\ua873\ua882-\ua8b3\ua8f2-\ua8f7\ua8fb\ua8fd-\ua8fe\ua90a-\ua925\ua930-\ua946\ua960-\ua97c\ua984-\ua9b2\ua9cf\ua9e0-\ua9e4\ua9e6-\ua9ef\ua9fa-\ua9fe\uaa00-\uaa28\uaa40-\uaa42\uaa44-\uaa4b\uaa60-\uaa76\uaa7a\uaa7e-\uaaaf\uaab1\uaab5-\uaab6\uaab9-\uaabd\uaac0\uaac2\uaadb-\uaadd\uaae0-\uaaea\uaaf2-\uaaf4\uab01-\uab06\uab09-\uab0e\uab11-\uab16\uab20-\uab26\uab28-\uab2e\uab30-\uab5a\uab5c-\uab65\uab70-\uabe2\uac00-\ud7a3\ud7b0-\ud7c6\ud7cb-\ud7fb\uf900-\ufa6d\ufa70-\ufad9\ufb00-\ufb06\ufb13-\ufb17\ufb1d\ufb1f-\ufb28\ufb2a-\ufb36\ufb38-\ufb3c\ufb3e\ufb40-\ufb41\ufb43-\ufb44\ufb46-\ufbb1\ufbd3-\ufc5d\ufc64-\ufd3d\ufd50-\ufd8f\ufd92-\ufdc7\ufdf0-\ufdf9\ufe71\ufe73\ufe77\ufe79\ufe7b\ufe7d\ufe7f-\ufefc\uff21-\uff3a\uff41-\uff5a\uff66-\uff9d\uffa0-\uffbe\uffc2-\uffc7\uffca-\uffcf\uffd2-\uffd7\uffda-\uffdc\U00010000-\U0001000b\U0001000d-\U00010026\U00010028-\U0001003a\U0001003c-\U0001003d\U0001003f-\U0001004d\U00010050-\U0001005d\U00010080-\U000100fa\U00010140-\U00010174\U00010280-\U0001029c\U000102a0-\U000102d0\U00010300-\U0001031f\U0001032d-\U0001034a\U00010350-\U00010375\U00010380-\U0001039d\U000103a0-\U000103c3\U000103c8-\U000103cf\U000103d1-\U000103d5\U00010400-\U0001049d\U000104b0-\U000104d3\U000104d8-\U000104fb\U00010500-\U00010527\U00010530-\U00010563\U00010600-\U00010736\U00010740-\U00010755\U00010760-\U00010767\U00010800-\U00010805\U00010808\U0001080a-\U00010835\U00010837-\U00010838\U0001083c\U0001083f-\U00010855\U00010860-\U00010876\U00010880-\U0001089e\U000108e0-\U000108f2\U000108f4-\U000108f5\U00010900-\U00010915\U00010920-\U00010939\U00010980-\U000109b7\U000109be-\U000109bf\U00010a00\U00010a10-\U00010a13\U00010a15-\U00010a17\U00010a19-\U00010a35\U00010a60-\U00010a7c\U00010a80-\U00010a9c\U00010ac0-\U00010ac7\U00010ac9-\U00010ae4\U00010b00-\U00010b35\U00010b40-\U00010b55\U00010b60-\U00010b72\U00010b80-\U00010b91\U00010c00-\U00010c48\U00010c80-\U00010cb2\U00010cc0-\U00010cf2\U00010d00-\U00010d23\U00010f00-\U00010f1c\U00010f27\U00010f30-\U00010f45\U00011003-\U00011037\U00011083-\U000110af\U000110d0-\U000110e8\U00011103-\U00011126\U00011144\U00011150-\U00011172\U00011176\U00011183-\U000111b2\U000111c1-\U000111c4\U000111da\U000111dc\U00011200-\U00011211\U00011213-\U0001122b\U00011280-\U00011286\U00011288\U0001128a-\U0001128d\U0001128f-\U0001129d\U0001129f-\U000112a8\U000112b0-\U000112de\U00011305-\U0001130c\U0001130f-\U00011310\U00011313-\U00011328\U0001132a-\U00011330\U00011332-\U00011333\U00011335-\U00011339\U0001133d\U00011350\U0001135d-\U00011361\U00011400-\U00011434\U00011447-\U0001144a\U00011480-\U000114af\U000114c4-\U000114c5\U000114c7\U00011580-\U000115ae\U000115d8-\U000115db\U00011600-\U0001162f\U00011644\U00011680-\U000116aa\U00011700-\U0001171a\U00011800-\U0001182b\U000118a0-\U000118df\U000118ff\U00011a00\U00011a0b-\U00011a32\U00011a3a\U00011a50\U00011a5c-\U00011a83\U00011a86-\U00011a89\U00011a9d\U00011ac0-\U00011af8\U00011c00-\U00011c08\U00011c0a-\U00011c2e\U00011c40\U00011c72-\U00011c8f\U00011d00-\U00011d06\U00011d08-\U00011d09\U00011d0b-\U00011d30\U00011d46\U00011d60-\U00011d65\U00011d67-\U00011d68\U00011d6a-\U00011d89\U00011d98\U00011ee0-\U00011ef2\U00012000-\U00012399\U00012400-\U0001246e\U00012480-\U00012543\U00013000-\U0001342e\U00014400-\U00014646\U00016800-\U00016a38\U00016a40-\U00016a5e\U00016ad0-\U00016aed\U00016b00-\U00016b2f\U00016b40-\U00016b43\U00016b63-\U00016b77\U00016b7d-\U00016b8f\U00016e40-\U00016e7f\U00016f00-\U00016f44\U00016f50\U00016f93-\U00016f9f\U00016fe0-\U00016fe1\U00017000-\U000187f1\U00018800-\U00018af2\U0001b000-\U0001b11e\U0001b170-\U0001b2fb\U0001bc00-\U0001bc6a\U0001bc70-\U0001bc7c\U0001bc80-\U0001bc88\U0001bc90-\U0001bc99\U0001d400-\U0001d454\U0001d456-\U0001d49c\U0001d49e-\U0001d49f\U0001d4a2\U0001d4a5-\U0001d4a6\U0001d4a9-\U0001d4ac\U0001d4ae-\U0001d4b9\U0001d4bb\U0001d4bd-\U0001d4c3\U0001d4c5-\U0001d505\U0001d507-\U0001d50a\U0001d50d-\U0001d514\U0001d516-\U0001d51c\U0001d51e-\U0001d539\U0001d53b-\U0001d53e\U0001d540-\U0001d544\U0001d546\U0001d54a-\U0001d550\U0001d552-\U0001d6a5\U0001d6a8-\U0001d6c0\U0001d6c2-\U0001d6da\U0001d6dc-\U0001d6fa\U0001d6fc-\U0001d714\U0001d716-\U0001d734\U0001d736-\U0001d74e\U0001d750-\U0001d76e\U0001d770-\U0001d788\U0001d78a-\U0001d7a8\U0001d7aa-\U0001d7c2\U0001d7c4-\U0001d7cb\U0001e800-\U0001e8c4\U0001e900-\U0001e943\U0001ee00-\U0001ee03\U0001ee05-\U0001ee1f\U0001ee21-\U0001ee22\U0001ee24\U0001ee27\U0001ee29-\U0001ee32\U0001ee34-\U0001ee37\U0001ee39\U0001ee3b\U0001ee42\U0001ee47\U0001ee49\U0001ee4b\U0001ee4d-\U0001ee4f\U0001ee51-\U0001ee52\U0001ee54\U0001ee57\U0001ee59\U0001ee5b\U0001ee5d\U0001ee5f\U0001ee61-\U0001ee62\U0001ee64\U0001ee67-\U0001ee6a\U0001ee6c-\U0001ee72\U0001ee74-\U0001ee77\U0001ee79-\U0001ee7c\U0001ee7e\U0001ee80-\U0001ee89\U0001ee8b-\U0001ee9b\U0001eea1-\U0001eea3\U0001eea5-\U0001eea9\U0001eeab-\U0001eebb\U00020000-\U0002a6d6\U0002a700-\U0002b734\U0002b740-\U0002b81d\U0002b820-\U0002cea1\U0002ceb0-\U0002ebe0\U0002f800-\U0002fa1d' + +cats = ['Cc', 'Cf', 'Cn', 'Co', 'Cs', 'Ll', 'Lm', 'Lo', 'Lt', 'Lu', 'Mc', 'Me', 'Mn', 'Nd', 'Nl', 'No', 'Pc', 'Pd', 'Pe', 'Pf', 'Pi', 'Po', 'Ps', 'Sc', 'Sk', 'Sm', 'So', 'Zl', 'Zp', 'Zs'] + +# Generated from unidata 11.0.0 + +def combine(*args): + return ''.join(globals()[cat] for cat in args) + + +def allexcept(*args): + newcats = cats[:] + for arg in args: + newcats.remove(arg) + return ''.join(globals()[cat] for cat in newcats) + + +def _handle_runs(char_list): # pragma: no cover + buf = [] + for c in char_list: + if len(c) == 1: + if buf and buf[-1][1] == chr(ord(c)-1): + buf[-1] = (buf[-1][0], c) + else: + buf.append((c, c)) + else: + buf.append((c, c)) + for a, b in buf: + if a == b: + yield a + else: + yield f'{a}-{b}' + + +if __name__ == '__main__': # pragma: no cover + import unicodedata + + categories = {'xid_start': [], 'xid_continue': []} + + with open(__file__, encoding='utf-8') as fp: + content = fp.read() + + header = content[:content.find('Cc =')] + footer = content[content.find("def combine("):] + + for code in range(0x110000): + c = chr(code) + cat = unicodedata.category(c) + if ord(c) == 0xdc00: + # Hack to avoid combining this combining with the preceding high + # surrogate, 0xdbff, when doing a repr. + c = '\\' + c + elif ord(c) in (0x2d, 0x5b, 0x5c, 0x5d, 0x5e): + # Escape regex metachars. + c = '\\' + c + categories.setdefault(cat, []).append(c) + # XID_START and XID_CONTINUE are special categories used for matching + # identifiers in Python 3. + if c.isidentifier(): + categories['xid_start'].append(c) + if ('a' + c).isidentifier(): + categories['xid_continue'].append(c) + + with open(__file__, 'w', encoding='utf-8') as fp: + fp.write(header) + + for cat in sorted(categories): + val = ''.join(_handle_runs(categories[cat])) + fp.write(f'{cat} = {val!a}\n\n') + + cats = sorted(categories) + cats.remove('xid_start') + cats.remove('xid_continue') + fp.write(f'cats = {cats!r}\n\n') + + fp.write(f'# Generated from unidata {unicodedata.unidata_version}\n\n') + + fp.write(footer) diff --git a/.venv/lib/python3.12/site-packages/pygments/util.py b/.venv/lib/python3.12/site-packages/pygments/util.py new file mode 100644 index 0000000000000000000000000000000000000000..c9df89ca2e3d144d973c7c96fc08906cd3abb15f --- /dev/null +++ b/.venv/lib/python3.12/site-packages/pygments/util.py @@ -0,0 +1,344 @@ +""" + pygments.util + ~~~~~~~~~~~~~ + + Utility functions. + + :copyright: Copyright 2006-present by the Pygments team, see AUTHORS. + :license: BSD, see LICENSE for details. +""" + +import re +from io import TextIOWrapper +import html + + +split_path_re = re.compile(r'[/\\ ]') +doctype_lookup_re = re.compile(r''' + ]*> +''', re.DOTALL | re.MULTILINE | re.VERBOSE) +tag_re = re.compile(r'<([a-zA-Z][a-zA-Z0-9._:-]*)(\s[^>]*)?>.*?', + re.IGNORECASE | re.DOTALL | re.MULTILINE) +xml_decl_re = re.compile(r'\s*<\?xml[^>]*\?>', re.I) + + +class ClassNotFound(ValueError): + """Raised if one of the lookup functions didn't find a matching class.""" + + +class OptionError(Exception): + """ + This exception will be raised by all option processing functions if + the type or value of the argument is not correct. + """ + +def get_choice_opt(options, optname, allowed, default=None, normcase=False): + """ + If the key `optname` from the dictionary is not in the sequence + `allowed`, raise an error, otherwise return it. + """ + string = options.get(optname, default) + if normcase: + string = string.lower() + if string not in allowed: + raise OptionError('Value for option {} must be one of {}'.format(optname, ', '.join(map(str, allowed)))) + return string + + +def get_bool_opt(options, optname, default=None): + """ + Intuitively, this is `options.get(optname, default)`, but restricted to + Boolean value. The Booleans can be represented as string, in order to accept + Boolean value from the command line arguments. If the key `optname` is + present in the dictionary `options` and is not associated with a Boolean, + raise an `OptionError`. If it is absent, `default` is returned instead. + + The valid string values for ``True`` are ``1``, ``yes``, ``true`` and + ``on``, the ones for ``False`` are ``0``, ``no``, ``false`` and ``off`` + (matched case-insensitively). + """ + string = options.get(optname, default) + if isinstance(string, bool): + return string + elif isinstance(string, int): + return bool(string) + elif not isinstance(string, str): + raise OptionError(f'Invalid type {string!r} for option {optname}; use ' + '1/0, yes/no, true/false, on/off') + elif string.lower() in ('1', 'yes', 'true', 'on'): + return True + elif string.lower() in ('0', 'no', 'false', 'off'): + return False + else: + raise OptionError(f'Invalid value {string!r} for option {optname}; use ' + '1/0, yes/no, true/false, on/off') + + +def get_int_opt(options, optname, default=None): + """As :func:`get_bool_opt`, but interpret the value as an integer.""" + string = options.get(optname, default) + try: + return int(string) + except TypeError: + raise OptionError(f'Invalid type {string!r} for option {optname}; you ' + 'must give an integer value') + except ValueError: + raise OptionError(f'Invalid value {string!r} for option {optname}; you ' + 'must give an integer value') + +def get_list_opt(options, optname, default=None): + """ + If the key `optname` from the dictionary `options` is a string, + split it at whitespace and return it. If it is already a list + or a tuple, it is returned as a list. + """ + val = options.get(optname, default) + if isinstance(val, str): + return val.split() + elif isinstance(val, (list, tuple)): + return list(val) + else: + raise OptionError(f'Invalid type {val!r} for option {optname}; you ' + 'must give a list value') + + +def docstring_headline(obj): + if not obj.__doc__: + return '' + res = [] + for line in obj.__doc__.strip().splitlines(): + if line.strip(): + res.append(" " + line.strip()) + else: + break + return ''.join(res).lstrip() + + +def make_analysator(f): + """Return a static text analyser function that returns float values.""" + def text_analyse(text): + try: + rv = f(text) + except Exception: + return 0.0 + if not rv: + return 0.0 + try: + return min(1.0, max(0.0, float(rv))) + except (ValueError, TypeError): + return 0.0 + text_analyse.__doc__ = f.__doc__ + return staticmethod(text_analyse) + + +def shebang_matches(text, regex): + r"""Check if the given regular expression matches the last part of the + shebang if one exists. + + >>> from pygments.util import shebang_matches + >>> shebang_matches('#!/usr/bin/env python', r'python(2\.\d)?') + True + >>> shebang_matches('#!/usr/bin/python2.4', r'python(2\.\d)?') + True + >>> shebang_matches('#!/usr/bin/python-ruby', r'python(2\.\d)?') + False + >>> shebang_matches('#!/usr/bin/python/ruby', r'python(2\.\d)?') + False + >>> shebang_matches('#!/usr/bin/startsomethingwith python', + ... r'python(2\.\d)?') + True + + It also checks for common windows executable file extensions:: + + >>> shebang_matches('#!C:\\Python2.4\\Python.exe', r'python(2\.\d)?') + True + + Parameters (``'-f'`` or ``'--foo'`` are ignored so ``'perl'`` does + the same as ``'perl -e'``) + + Note that this method automatically searches the whole string (eg: + the regular expression is wrapped in ``'^$'``) + """ + index = text.find('\n') + if index >= 0: + first_line = text[:index].lower() + else: + first_line = text.lower() + if first_line.startswith('#!'): + try: + found = [x for x in split_path_re.split(first_line[2:].strip()) + if x and not x.startswith('-')][-1] + except IndexError: + return False + regex = re.compile(rf'^{regex}(\.(exe|cmd|bat|bin))?$', re.IGNORECASE) + if regex.search(found) is not None: + return True + return False + + +def doctype_matches(text, regex): + """Check if the doctype matches a regular expression (if present). + + Note that this method only checks the first part of a DOCTYPE. + eg: 'html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"' + """ + m = doctype_lookup_re.search(text) + if m is None: + return False + doctype = m.group(1) + return re.compile(regex, re.I).match(doctype.strip()) is not None + + +def html_doctype_matches(text): + """Check if the file looks like it has a html doctype.""" + return doctype_matches(text, r'html') + + +_looks_like_xml_cache = {} + + +def looks_like_xml(text): + """Check if a doctype exists or if we have some tags.""" + if xml_decl_re.match(text): + return True + key = hash(text) + try: + return _looks_like_xml_cache[key] + except KeyError: + m = doctype_lookup_re.search(text) + if m is not None: + return True + rv = tag_re.search(text[:1000]) is not None + _looks_like_xml_cache[key] = rv + return rv + + +def surrogatepair(c): + """Given a unicode character code with length greater than 16 bits, + return the two 16 bit surrogate pair. + """ + # From example D28 of: + # http://www.unicode.org/book/ch03.pdf + return (0xd7c0 + (c >> 10), (0xdc00 + (c & 0x3ff))) + + +def format_lines(var_name, seq, raw=False, indent_level=0): + """Formats a sequence of strings for output.""" + lines = [] + base_indent = ' ' * indent_level * 4 + inner_indent = ' ' * (indent_level + 1) * 4 + lines.append(base_indent + var_name + ' = (') + if raw: + # These should be preformatted reprs of, say, tuples. + for i in seq: + lines.append(inner_indent + i + ',') + else: + for i in seq: + # Force use of single quotes + r = repr(i + '"') + lines.append(inner_indent + r[:-2] + r[-1] + ',') + lines.append(base_indent + ')') + return '\n'.join(lines) + + +def duplicates_removed(it, already_seen=()): + """ + Returns a list with duplicates removed from the iterable `it`. + + Order is preserved. + """ + lst = [] + seen = set() + for i in it: + if i in seen or i in already_seen: + continue + lst.append(i) + seen.add(i) + return lst + + +class Future: + """Generic class to defer some work. + + Handled specially in RegexLexerMeta, to support regex string construction at + first use. + """ + def get(self): + raise NotImplementedError + + +def guess_decode(text): + """Decode *text* with guessed encoding. + + First try UTF-8; this should fail for non-UTF-8 encodings. + Then try the preferred locale encoding. + Fall back to latin-1, which always works. + """ + try: + text = text.decode('utf-8') + return text, 'utf-8' + except UnicodeDecodeError: + try: + import locale + prefencoding = locale.getpreferredencoding() + text = text.decode(prefencoding) + return text, prefencoding + except (UnicodeDecodeError, LookupError): + text = text.decode('latin1') + return text, 'latin1' + + +def guess_decode_from_terminal(text, term): + """Decode *text* coming from terminal *term*. + + First try the terminal encoding, if given. + Then try UTF-8. Then try the preferred locale encoding. + Fall back to latin-1, which always works. + """ + if getattr(term, 'encoding', None): + try: + text = text.decode(term.encoding) + except UnicodeDecodeError: + pass + else: + return text, term.encoding + return guess_decode(text) + + +def terminal_encoding(term): + """Return our best guess of encoding for the given *term*.""" + if getattr(term, 'encoding', None): + return term.encoding + import locale + return locale.getpreferredencoding() + + +class UnclosingTextIOWrapper(TextIOWrapper): + # Don't close underlying buffer on destruction. + def close(self): + self.flush() + + +def html_escape(string, quote=True) -> str: + """Return a safe version of the passed `string`, + and an empty string if `None`. + + `NoneType` is not supported by `html.escape`, as `html.escape` + uses the built-in `replace` function on `string`, so we need to + check for it first. + + Optional flag quote is true by default, which also escapes + double and single quotes. + See https://docs.python.org/3/library/html.html#html.escape for more details. + """ + if string is not None: + # TODO: Eventually, check that string is a str, and if not, print a + # warning or error here. + return html.escape(str(string), quote=quote) + return '' diff --git a/.venv/lib/python3.12/site-packages/pylab.py b/.venv/lib/python3.12/site-packages/pylab.py new file mode 100644 index 0000000000000000000000000000000000000000..64ece55b1cb2c312d8a9c2ac1fd264fa11727270 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/pylab.py @@ -0,0 +1,3 @@ +from matplotlib.pylab import * # noqa: F401, F403 +import matplotlib.pylab +__doc__ = matplotlib.pylab.__doc__ diff --git a/.venv/lib/python3.12/site-packages/pynvml.py b/.venv/lib/python3.12/site-packages/pynvml.py new file mode 100644 index 0000000000000000000000000000000000000000..775fe2e32045258fd46aa053aa03e450fbd57f71 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/pynvml.py @@ -0,0 +1,7423 @@ +##### +# Copyright (c) 2011-2025, NVIDIA Corporation. 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 NVIDIA Corporation nor the names of its +# contributors may be used to endorse or promote products derived from +# this software without specific prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE +# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF +# THE POSSIBILITY OF SUCH DAMAGE. +##### + +## +# Python bindings for the NVML library +## +from ctypes import * +from ctypes.util import find_library +from functools import wraps +import sys +import os +import threading +import string + +## C Type mappings ## +## Enums +_nvmlEnableState_t = c_uint +NVML_FEATURE_DISABLED = 0 +NVML_FEATURE_ENABLED = 1 + +_nvmlBrandType_t = c_uint +NVML_BRAND_UNKNOWN = 0 +NVML_BRAND_QUADRO = 1 +NVML_BRAND_TESLA = 2 +NVML_BRAND_NVS = 3 +NVML_BRAND_GRID = 4 # Deprecated from API reporting. Keeping definition for backward compatibility. +NVML_BRAND_GEFORCE = 5 +NVML_BRAND_TITAN = 6 +NVML_BRAND_NVIDIA_VAPPS = 7 # NVIDIA Virtual Applications +NVML_BRAND_NVIDIA_VPC = 8 # NVIDIA Virtual PC +NVML_BRAND_NVIDIA_VCS = 9 # NVIDIA vGPU for Compute +NVML_BRAND_NVIDIA_VWS = 10 # NVIDIA RTX Virtual Workstation +NVML_BRAND_NVIDIA_CLOUD_GAMING = 11 # NVIDIA Cloud Gaming +NVML_BRAND_NVIDIA_VGAMING = NVML_BRAND_NVIDIA_CLOUD_GAMING # Deprecated from API reporting. Keeping definition for backward compatibility. +NVML_BRAND_QUADRO_RTX = 12 +NVML_BRAND_NVIDIA_RTX = 13 +NVML_BRAND_NVIDIA = 14 +NVML_BRAND_GEFORCE_RTX = 15 # Unused +NVML_BRAND_TITAN_RTX = 16 # Unused +NVML_BRAND_COUNT = 18 + +_nvmlTemperatureThresholds_t = c_uint +NVML_TEMPERATURE_THRESHOLD_SHUTDOWN = 0 +NVML_TEMPERATURE_THRESHOLD_SLOWDOWN = 1 +NVML_TEMPERATURE_THRESHOLD_MEM_MAX = 2 +NVML_TEMPERATURE_THRESHOLD_GPU_MAX = 3 +NVML_TEMPERATURE_THRESHOLD_ACOUSTIC_MIN = 4 +NVML_TEMPERATURE_THRESHOLD_ACOUSTIC_CURR = 5 +NVML_TEMPERATURE_THRESHOLD_ACOUSTIC_MAX = 6 +NVML_TEMPERATURE_THRESHOLD_GPS_CURR = 7 +NVML_TEMPERATURE_THRESHOLD_COUNT = 8 + +_nvmlTemperatureSensors_t = c_uint +NVML_TEMPERATURE_GPU = 0 +NVML_TEMPERATURE_COUNT = 1 + + +_nvmlComputeMode_t = c_uint +NVML_COMPUTEMODE_DEFAULT = 0 +NVML_COMPUTEMODE_EXCLUSIVE_THREAD = 1 ## Support Removed +NVML_COMPUTEMODE_PROHIBITED = 2 +NVML_COMPUTEMODE_EXCLUSIVE_PROCESS = 3 +NVML_COMPUTEMODE_COUNT = 4 + +_nvmlMemoryLocation_t = c_uint +NVML_MEMORY_LOCATION_L1_CACHE = 0 +NVML_MEMORY_LOCATION_L2_CACHE = 1 +NVML_MEMORY_LOCATION_DEVICE_MEMORY = 2 +NVML_MEMORY_LOCATION_DRAM = 2 +NVML_MEMORY_LOCATION_REGISTER_FILE = 3 +NVML_MEMORY_LOCATION_TEXTURE_MEMORY = 4 +NVML_MEMORY_LOCATION_TEXTURE_SHM = 5 +NVML_MEMORY_LOCATION_CBU = 6 +NVML_MEMORY_LOCATION_SRAM = 7 +NVML_MEMORY_LOCATION_COUNT = 8 + +NVML_NVLINK_MAX_LINKS = 36 + +# For backwards compatibility, maintain the incorrectly-named "LANES" define +NVML_NVLINK_MAX_LANES = NVML_NVLINK_MAX_LINKS + +_nvmlNvLinkErrorCounter_t = c_uint +NVML_NVLINK_ERROR_DL_REPLAY = 0 +NVML_NVLINK_ERROR_DL_RECOVERY = 1 +NVML_NVLINK_ERROR_DL_CRC_FLIT = 2 +NVML_NVLINK_ERROR_DL_CRC_DATA = 3 +NVML_NVLINK_ERROR_DL_ECC_DATA = 4 +NVML_NVLINK_ERROR_COUNT = 5 + +_nvmlNvLinkEccLaneErrorCounter_t = c_uint +NVML_NVLINK_ERROR_DL_ECC_LANE0 = 0 +NVML_NVLINK_ERROR_DL_ECC_LANE1 = 1 +NVML_NVLINK_ERROR_DL_ECC_LANE2 = 2 +NVML_NVLINK_ERROR_DL_ECC_LANE3 = 3 +NVML_NVLINK_ERROR_DL_ECC_COUNT = 5 + +_nvmlNvLinkCapability_t = c_uint +NVML_NVLINK_CAP_P2P_SUPPORTED = 0 +NVML_NVLINK_CAP_SYSMEM_ACCESS = 1 +NVML_NVLINK_CAP_P2P_ATOMICS = 2 +NVML_NVLINK_CAP_SYSMEM_ATOMICS= 3 +NVML_NVLINK_CAP_SLI_BRIDGE = 4 +NVML_NVLINK_CAP_VALID = 5 +NVML_NVLINK_CAP_COUNT = 6 + +_nvmlNvLinkUtilizationCountPktTypes_t = c_uint +NVML_NVLINK_COUNTER_PKTFILTER_NOP = 0x1 +NVML_NVLINK_COUNTER_PKTFILTER_READ = 0x2 +NVML_NVLINK_COUNTER_PKTFILTER_WRITE = 0x4 +NVML_NVLINK_COUNTER_PKTFILTER_RATOM = 0x8 +NVML_NVLINK_COUNTER_PKTFILTER_NRATOM = 0x10 +NVML_NVLINK_COUNTER_PKTFILTER_FLUSH = 0x20 +NVML_NVLINK_COUNTER_PKTFILTER_RESPDATA = 0x40 +NVML_NVLINK_COUNTER_PKTFILTER_RESPNODATA = 0x80 +NVML_NVLINK_COUNTER_PKTFILTER_ALL = 0xFF + +_nvmlNvLinkUtilizationCountUnits_t = c_uint +NVML_NVLINK_COUNTER_UNIT_CYCLES = 0 +NVML_NVLINK_COUNTER_UNIT_PACKETS = 1 +NVML_NVLINK_COUNTER_UNIT_BYTES = 2 +NVML_NVLINK_COUNTER_UNIT_RESERVED = 3 +NVML_NVLINK_COUNTER_UNIT_COUNT = 4 + +_nvmlNvLinkDeviceType_t = c_uint +NVML_NVLINK_DEVICE_TYPE_GPU = 0x00 +NVML_NVLINK_DEVICE_TYPE_IBMNPU = 0x01 +NVML_NVLINK_DEVICE_TYPE_SWITCH = 0x02 +NVML_NVLINK_DEVICE_TYPE_UNKNOWN = 0xFF + +# These are deprecated, instead use _nvmlMemoryErrorType_t +_nvmlEccBitType_t = c_uint +NVML_SINGLE_BIT_ECC = 0 +NVML_DOUBLE_BIT_ECC = 1 +NVML_ECC_ERROR_TYPE_COUNT = 2 + +_nvmlEccCounterType_t = c_uint +NVML_VOLATILE_ECC = 0 +NVML_AGGREGATE_ECC = 1 +NVML_ECC_COUNTER_TYPE_COUNT = 2 + +_nvmlMemoryErrorType_t = c_uint +NVML_MEMORY_ERROR_TYPE_CORRECTED = 0 +NVML_MEMORY_ERROR_TYPE_UNCORRECTED = 1 +NVML_MEMORY_ERROR_TYPE_COUNT = 2 + +_nvmlClockType_t = c_uint +NVML_CLOCK_GRAPHICS = 0 +NVML_CLOCK_SM = 1 +NVML_CLOCK_MEM = 2 +NVML_CLOCK_VIDEO = 3 +NVML_CLOCK_COUNT = 4 + +_nvmlClockId_t = c_uint +NVML_CLOCK_ID_CURRENT = 0 +NVML_CLOCK_ID_APP_CLOCK_TARGET = 1 +NVML_CLOCK_ID_APP_CLOCK_DEFAULT = 2 +NVML_CLOCK_ID_CUSTOMER_BOOST_MAX = 3 +NVML_CLOCK_ID_COUNT = 4 + +_nvmlDriverModel_t = c_uint +NVML_DRIVER_WDDM = 0 +NVML_DRIVER_WDM = 1 +NVML_DRIVER_MCDM = 2 + +NVML_MAX_GPU_PERF_PSTATES = 16 + +_nvmlPstates_t = c_uint +NVML_PSTATE_0 = 0 +NVML_PSTATE_1 = 1 +NVML_PSTATE_2 = 2 +NVML_PSTATE_3 = 3 +NVML_PSTATE_4 = 4 +NVML_PSTATE_5 = 5 +NVML_PSTATE_6 = 6 +NVML_PSTATE_7 = 7 +NVML_PSTATE_8 = 8 +NVML_PSTATE_9 = 9 +NVML_PSTATE_10 = 10 +NVML_PSTATE_11 = 11 +NVML_PSTATE_12 = 12 +NVML_PSTATE_13 = 13 +NVML_PSTATE_14 = 14 +NVML_PSTATE_15 = 15 +NVML_PSTATE_UNKNOWN = 32 + +_nvmlInforomObject_t = c_uint +NVML_INFOROM_OEM = 0 +NVML_INFOROM_ECC = 1 +NVML_INFOROM_POWER = 2 +NVML_INFOROM_DEN = 3 +NVML_INFOROM_COUNT = 4 + +_nvmlReturn_t = c_uint +NVML_SUCCESS = 0 +NVML_ERROR_UNINITIALIZED = 1 +NVML_ERROR_INVALID_ARGUMENT = 2 +NVML_ERROR_NOT_SUPPORTED = 3 +NVML_ERROR_NO_PERMISSION = 4 +NVML_ERROR_ALREADY_INITIALIZED = 5 +NVML_ERROR_NOT_FOUND = 6 +NVML_ERROR_INSUFFICIENT_SIZE = 7 +NVML_ERROR_INSUFFICIENT_POWER = 8 +NVML_ERROR_DRIVER_NOT_LOADED = 9 +NVML_ERROR_TIMEOUT = 10 +NVML_ERROR_IRQ_ISSUE = 11 +NVML_ERROR_LIBRARY_NOT_FOUND = 12 +NVML_ERROR_FUNCTION_NOT_FOUND = 13 +NVML_ERROR_CORRUPTED_INFOROM = 14 +NVML_ERROR_GPU_IS_LOST = 15 +NVML_ERROR_RESET_REQUIRED = 16 +NVML_ERROR_OPERATING_SYSTEM = 17 +NVML_ERROR_LIB_RM_VERSION_MISMATCH = 18 +NVML_ERROR_IN_USE = 19 +NVML_ERROR_MEMORY = 20 +NVML_ERROR_NO_DATA = 21 +NVML_ERROR_VGPU_ECC_NOT_SUPPORTED = 22 +NVML_ERROR_INSUFFICIENT_RESOURCES = 23 +NVML_ERROR_FREQ_NOT_SUPPORTED = 24 +NVML_ERROR_ARGUMENT_VERSION_MISMATCH = 25 +NVML_ERROR_DEPRECATED = 26 +NVML_ERROR_NOT_READY = 27 +NVML_ERROR_GPU_NOT_FOUND = 28 +NVML_ERROR_INVALID_STATE = 29 +NVML_ERROR_RESET_TYPE_NOT_SUPPORTED = 30 +NVML_ERROR_UNKNOWN = 999 + +_nvmlFanState_t = c_uint +NVML_FAN_NORMAL = 0 +NVML_FAN_FAILED = 1 + +_nvmlFanControlPolicy_t = c_uint +NVML_FAN_POLICY_TEMPERATURE_CONTINOUS_SW = 0 +NVML_FAN_POLICY_MANUAL = 1 + +_nvmlLedColor_t = c_uint +NVML_LED_COLOR_GREEN = 0 +NVML_LED_COLOR_AMBER = 1 + +_nvmlGpuOperationMode_t = c_uint +NVML_GOM_ALL_ON = 0 +NVML_GOM_COMPUTE = 1 +NVML_GOM_LOW_DP = 2 + +_nvmlPageRetirementCause_t = c_uint +NVML_PAGE_RETIREMENT_CAUSE_MULTIPLE_SINGLE_BIT_ECC_ERRORS = 0 +NVML_PAGE_RETIREMENT_CAUSE_DOUBLE_BIT_ECC_ERROR = 1 +NVML_PAGE_RETIREMENT_CAUSE_COUNT = 2 + +_nvmlRestrictedAPI_t = c_uint +NVML_RESTRICTED_API_SET_APPLICATION_CLOCKS = 0 +NVML_RESTRICTED_API_SET_AUTO_BOOSTED_CLOCKS = 1 +NVML_RESTRICTED_API_COUNT = 2 + +_nvmlBridgeChipType_t = c_uint +NVML_BRIDGE_CHIP_PLX = 0 +NVML_BRIDGE_CHIP_BRO4 = 1 +NVML_MAX_PHYSICAL_BRIDGE = 128 + +_nvmlValueType_t = c_uint +NVML_VALUE_TYPE_DOUBLE = 0 +NVML_VALUE_TYPE_UNSIGNED_INT = 1 +NVML_VALUE_TYPE_UNSIGNED_LONG = 2 +NVML_VALUE_TYPE_UNSIGNED_LONG_LONG = 3 +NVML_VALUE_TYPE_SIGNED_LONG_LONG = 4 +NVML_VALUE_TYPE_SIGNED_INT = 5 +NVML_VALUE_TYPE_UNSIGNED_SHORT = 6 +NVML_VALUE_TYPE_COUNT = 7 + +_nvmlNvlinkVersion_t = c_uint +NVML_NVLINK_VERSION_INVALID = 0 +NVML_NVLINK_VERSION_1_0 = 1 +NVML_NVLINK_VERSION_2_0 = 2 +NVML_NVLINK_VERSION_2_2 = 3 +NVML_NVLINK_VERSION_3_0 = 4 +NVML_NVLINK_VERSION_3_1 = 5 +NVML_NVLINK_VERSION_4_0 = 6 +NVML_NVLINK_VERSION_5_0 = 7 +NVML_NVLINK_VERSION_6_0 = 8 + +_nvmlPerfPolicyType_t = c_uint +NVML_PERF_POLICY_POWER = 0 +NVML_PERF_POLICY_THERMAL = 1 +NVML_PERF_POLICY_SYNC_BOOST = 2 +NVML_PERF_POLICY_BOARD_LIMIT = 3 +NVML_PERF_POLICY_LOW_UTILIZATION = 4 +NVML_PERF_POLICY_RELIABILITY = 5 +NVML_PERF_POLICY_TOTAL_APP_CLOCKS = 10 +NVML_PERF_POLICY_TOTAL_BASE_CLOCKS = 11 +NVML_PERF_POLICY_COUNT = 12 + +_nvmlEncoderQueryType_t = c_uint +NVML_ENCODER_QUERY_H264 = 0 +NVML_ENCODER_QUERY_HEVC = 1 +NVML_ENCODER_QUERY_AV1 = 2 +NVML_ENCODER_QUERY_UNKNOWN = 255 + +_nvmlFBCSessionType_t = c_uint +NVML_FBC_SESSION_TYPE_UNKNOWN = 0 +NVML_FBC_SESSION_TYPE_TOSYS = 1 +NVML_FBC_SESSION_TYPE_CUDA = 2 +NVML_FBC_SESSION_TYPE_VID = 3 +NVML_FBC_SESSION_TYPE_HWENC = 4 + +_nvmlDetachGpuState_t = c_uint +NVML_DETACH_GPU_KEEP = 0 +NVML_DETACH_GPU_REMOVE = 1 + +_nvmlPcieLinkState_t = c_uint +NVML_PCIE_LINK_KEEP = 0 +NVML_PCIE_LINK_SHUT_DOWN = 1 + +_nvmlSamplingType_t = c_uint +NVML_TOTAL_POWER_SAMPLES = 0 +NVML_GPU_UTILIZATION_SAMPLES = 1 +NVML_MEMORY_UTILIZATION_SAMPLES = 2 +NVML_ENC_UTILIZATION_SAMPLES = 3 +NVML_DEC_UTILIZATION_SAMPLES = 4 +NVML_PROCESSOR_CLK_SAMPLES = 5 +NVML_MEMORY_CLK_SAMPLES = 6 +NVML_MODULE_POWER_SAMPLES = 7 +NVML_JPG_UTILIZATION_SAMPLES = 8 +NVML_OFA_UTILIZATION_SAMPLES = 9 +NVML_SAMPLINGTYPE_COUNT = 10 + +_nvmlPcieUtilCounter_t = c_uint +NVML_PCIE_UTIL_TX_BYTES = 0 +NVML_PCIE_UTIL_RX_BYTES = 1 +NVML_PCIE_UTIL_COUNT = 2 + +_nvmlGpuTopologyLevel_t = c_uint +NVML_TOPOLOGY_INTERNAL = 0 +NVML_TOPOLOGY_SINGLE = 10 +NVML_TOPOLOGY_MULTIPLE = 20 +NVML_TOPOLOGY_HOSTBRIDGE = 30 +NVML_TOPOLOGY_NODE = 40 +NVML_TOPOLOGY_CPU = NVML_TOPOLOGY_NODE +NVML_TOPOLOGY_SYSTEM = 50 + +_nvmlGpuP2PCapsIndex_t = c_uint +NVML_P2P_CAPS_INDEX_READ = 0, +NVML_P2P_CAPS_INDEX_WRITE = 1 +NVML_P2P_CAPS_INDEX_NVLINK =2 +NVML_P2P_CAPS_INDEX_ATOMICS = 3 +# +# NVML_P2P_CAPS_INDEX_PROP is deprecated. +# Use NVML_P2P_CAPS_INDEX_PCI instead. +# +NVML_P2P_CAPS_INDEX_PROP = 4 +NVML_P2P_CAPS_INDEX_PCI = 4 +NVML_P2P_CAPS_INDEX_UNKNOWN = 5 + +_nvmlGpuP2PStatus_t = c_uint +NVML_P2P_STATUS_OK = 0 +NVML_P2P_STATUS_CHIPSET_NOT_SUPPORED = 1 +NVML_P2P_STATUS_CHIPSET_NOT_SUPPORTED = NVML_P2P_STATUS_CHIPSET_NOT_SUPPORED +NVML_P2P_STATUS_GPU_NOT_SUPPORTED = 2 +NVML_P2P_STATUS_IOH_TOPOLOGY_NOT_SUPPORTED =3 +NVML_P2P_STATUS_DISABLED_BY_REGKEY =4 +NVML_P2P_STATUS_NOT_SUPPORTED =5 +NVML_P2P_STATUS_UNKNOWN =6 + +_nvmlDeviceArchitecture_t = c_uint +NVML_DEVICE_ARCH_KEPLER = 2 +NVML_DEVICE_ARCH_MAXWELL = 3 +NVML_DEVICE_ARCH_PASCAL = 4 +NVML_DEVICE_ARCH_VOLTA = 5 +NVML_DEVICE_ARCH_TURING = 6 +NVML_DEVICE_ARCH_AMPERE = 7 +NVML_DEVICE_ARCH_ADA = 8 +NVML_DEVICE_ARCH_HOPPER = 9 +NVML_DEVICE_ARCH_BLACKWELL = 10 +NVML_DEVICE_ARCH_RUBIN = 13 +NVML_DEVICE_ARCH_UNKNOWN = 0xffffffff + +# PCI bus Types +_nvmlBusType_t = c_uint +NVML_BUS_TYPE_UNKNOWN = 0 +NVML_BUS_TYPE_PCI = 1 +NVML_BUS_TYPE_PCIE = 2 +NVML_BUS_TYPE_FPCI = 3 +NVML_BUS_TYPE_AGP = 4 + +_nvmlPowerSource_t = c_uint +NVML_POWER_SOURCE_AC = 0x00000000 +NVML_POWER_SOURCE_BATTERY = 0x00000001 +NVML_POWER_SOURCE_UNDERSIZED = 0x00000002 + +_nvmlAdaptiveClockInfoStatus_t = c_uint +NVML_ADAPTIVE_CLOCKING_INFO_STATUS_DISABLED = 0x00000000 +NVML_ADAPTIVE_CLOCKING_INFO_STATUS_ENABLED = 0x00000001 + +_nvmlClockLimitId_t = c_uint +NVML_CLOCK_LIMIT_ID_RANGE_START = 0xffffff00 +NVML_CLOCK_LIMIT_ID_TDP = 0xffffff01 +NVML_CLOCK_LIMIT_ID_UNLIMITED = 0xffffff02 + +_nvmlPcieLinkMaxSpeed_t = c_uint +NVML_PCIE_LINK_MAX_SPEED_INVALID = 0x00000000 +NVML_PCIE_LINK_MAX_SPEED_2500MBPS = 0x00000001 +NVML_PCIE_LINK_MAX_SPEED_5000MBPS = 0x00000002 +NVML_PCIE_LINK_MAX_SPEED_8000MBPS = 0x00000003 +NVML_PCIE_LINK_MAX_SPEED_16000MBPS = 0x00000004 +NVML_PCIE_LINK_MAX_SPEED_32000MBPS = 0x00000005 +NVML_PCIE_LINK_MAX_SPEED_64000MBPS = 0x00000006 + +_nvmlPcieAtomicsCapability_t = c_uint +NVML_PCIE_ATOMICS_CAP_FETCHADD32 = 0x01 +NVML_PCIE_ATOMICS_CAP_FETCHADD64 = 0x02 +NVML_PCIE_ATOMICS_CAP_SWAP32 = 0x04 +NVML_PCIE_ATOMICS_CAP_SWAP64 = 0x08 +NVML_PCIE_ATOMICS_CAP_CAS32 = 0x10 +NVML_PCIE_ATOMICS_CAP_CAS64 = 0x20 +NVML_PCIE_ATOMICS_CAP_CAS128 = 0x40 +NVML_PCIE_ATOMICS_OPS_MAX = 7 + +_nvmlAffinityScope_t = c_uint +NVML_AFFINITY_SCOPE_NODE = 0 +NVML_AFFINITY_SCOPE_SOCKET = 1 + +_nvmlDeviceGpuRecoveryAction_t = c_uint +NVML_GPU_RECOVERY_ACTION_NONE = 0 +NVML_GPU_RECOVERY_ACTION_GPU_RESET = 1 +NVML_GPU_RECOVERY_ACTION_NODE_REBOOT = 2 +NVML_GPU_RECOVERY_ACTION_DRAIN_P2P = 3 +NVML_GPU_RECOVERY_ACTION_DRAIN_AND_RESET = 4 +NVML_GPU_RECOVERY_ACTION_RECOVER_IMEX_DOMAIN = 5 + +# C preprocessor defined values +nvmlFlagDefault = 0 +nvmlFlagForce = 1 +NVML_INIT_FLAG_NO_GPUS = (1 << 0) +NVML_INIT_FLAG_NO_ATTACH = (1 << 1) +NVML_INIT_FLAG_FORCE_INIT = (1 << 2) + +NVML_MAX_GPC_COUNT = 32 + +# buffer size +NVML_DEVICE_INFOROM_VERSION_BUFFER_SIZE = 16 +NVML_DEVICE_UUID_BUFFER_SIZE = 80 +NVML_DEVICE_UUID_V2_BUFFER_SIZE = 96 +NVML_SYSTEM_DRIVER_VERSION_BUFFER_SIZE = 80 +NVML_SYSTEM_NVML_VERSION_BUFFER_SIZE = 80 +NVML_DEVICE_NAME_BUFFER_SIZE = 64 +NVML_DEVICE_NAME_V2_BUFFER_SIZE = 96 +NVML_DEVICE_SERIAL_BUFFER_SIZE = 30 +NVML_DEVICE_PART_NUMBER_BUFFER_SIZE = 80 +NVML_DEVICE_GPU_PART_NUMBER_BUFFER_SIZE = 80 +NVML_DEVICE_VBIOS_VERSION_BUFFER_SIZE = 32 +NVML_DEVICE_PCI_BUS_ID_BUFFER_SIZE = 32 +NVML_DEVICE_PCI_BUS_ID_BUFFER_V2_SIZE = 16 +NVML_GRID_LICENSE_BUFFER_SIZE = 128 +NVML_VGPU_NAME_BUFFER_SIZE = 64 +NVML_GRID_LICENSE_FEATURE_MAX_COUNT = 3 +NVML_VGPU_METADATA_OPAQUE_DATA_SIZE = sizeof(c_uint) + 256 +NVML_VGPU_PGPU_METADATA_OPAQUE_DATA_SIZE = 256 +NVML_DEVICE_GPU_FRU_PART_NUMBER_BUFFER_SIZE = 0x14 # NV2080_GPU_MAX_PRODUCT_PART_NUMBER_LENGTH +NVML_PERF_MODES_BUFFER_SIZE = 2048 + +# Format strings +NVML_DEVICE_PCI_BUS_ID_LEGACY_FMT = "%04X:%02X:%02X.0" +NVML_DEVICE_PCI_BUS_ID_FMT = "%08X:%02X:%02X.0" + +NVML_VALUE_NOT_AVAILABLE_ulonglong = c_ulonglong(-1) +NVML_VALUE_NOT_AVAILABLE_uint = c_uint(-1) + +''' + Field Identifiers. + + All Identifiers pertain to a device. Each ID is only used once and is guaranteed never to change. +''' +NVML_FI_DEV_ECC_CURRENT = 1 # Current ECC mode. 1=Active. 0=Inactive +NVML_FI_DEV_ECC_PENDING = 2 # Pending ECC mode. 1=Active. 0=Inactive + +#ECC Count Totals +NVML_FI_DEV_ECC_SBE_VOL_TOTAL = 3 # Total single bit volatile ECC errors +NVML_FI_DEV_ECC_DBE_VOL_TOTAL = 4 # Total double bit volatile ECC errors +NVML_FI_DEV_ECC_SBE_AGG_TOTAL = 5 # Total single bit aggregate (persistent) ECC errors +NVML_FI_DEV_ECC_DBE_AGG_TOTAL = 6 # Total double bit aggregate (persistent) ECC errors +#Individual ECC locations +NVML_FI_DEV_ECC_SBE_VOL_L1 = 7 # L1 cache single bit volatile ECC errors +NVML_FI_DEV_ECC_DBE_VOL_L1 = 8 # L1 cache double bit volatile ECC errors +NVML_FI_DEV_ECC_SBE_VOL_L2 = 9 # L2 cache single bit volatile ECC errors +NVML_FI_DEV_ECC_DBE_VOL_L2 = 10 # L2 cache double bit volatile ECC errors +NVML_FI_DEV_ECC_SBE_VOL_DEV = 11 # Device memory single bit volatile ECC errors +NVML_FI_DEV_ECC_DBE_VOL_DEV = 12 # Device memory double bit volatile ECC errors +NVML_FI_DEV_ECC_SBE_VOL_REG = 13 # Register file single bit volatile ECC errors +NVML_FI_DEV_ECC_DBE_VOL_REG = 14 # Register file double bit volatile ECC errors +NVML_FI_DEV_ECC_SBE_VOL_TEX = 15 # Texture memory single bit volatile ECC errors +NVML_FI_DEV_ECC_DBE_VOL_TEX = 16 # Texture memory double bit volatile ECC errors +NVML_FI_DEV_ECC_DBE_VOL_CBU = 17 # CBU double bit volatile ECC errors +NVML_FI_DEV_ECC_SBE_AGG_L1 = 18 # L1 cache single bit aggregate (persistent) ECC errors +NVML_FI_DEV_ECC_DBE_AGG_L1 = 19 # L1 cache double bit aggregate (persistent) ECC errors +NVML_FI_DEV_ECC_SBE_AGG_L2 = 20 # L2 cache single bit aggregate (persistent) ECC errors +NVML_FI_DEV_ECC_DBE_AGG_L2 = 21 # L2 cache double bit aggregate (persistent) ECC errors +NVML_FI_DEV_ECC_SBE_AGG_DEV = 22 # Device memory single bit aggregate (persistent) ECC errors +NVML_FI_DEV_ECC_DBE_AGG_DEV = 23 # Device memory double bit aggregate (persistent) ECC errors +NVML_FI_DEV_ECC_SBE_AGG_REG = 24 # Register File single bit aggregate (persistent) ECC errors +NVML_FI_DEV_ECC_DBE_AGG_REG = 25 # Register File double bit aggregate (persistent) ECC errors +NVML_FI_DEV_ECC_SBE_AGG_TEX = 26 # Texture memory single bit aggregate (persistent) ECC errors +NVML_FI_DEV_ECC_DBE_AGG_TEX = 27 # Texture memory double bit aggregate (persistent) ECC errors +NVML_FI_DEV_ECC_DBE_AGG_CBU = 28 # CBU double bit aggregate ECC errors + +# Page Retirement +NVML_FI_DEV_RETIRED_SBE = 29 # Number of retired pages because of single bit errors +NVML_FI_DEV_RETIRED_DBE = 30 # Number of retired pages because of double bit errors +NVML_FI_DEV_RETIRED_PENDING = 31 # If any pages are pending retirement. 1=yes. 0=no. + +# NvLink Flit Error Counters +NVML_FI_DEV_NVLINK_CRC_FLIT_ERROR_COUNT_L0 = 32 # NVLink flow control CRC Error Counter for Lane 0 +NVML_FI_DEV_NVLINK_CRC_FLIT_ERROR_COUNT_L1 = 33 # NVLink flow control CRC Error Counter for Lane 1 +NVML_FI_DEV_NVLINK_CRC_FLIT_ERROR_COUNT_L2 = 34 # NVLink flow control CRC Error Counter for Lane 2 +NVML_FI_DEV_NVLINK_CRC_FLIT_ERROR_COUNT_L3 = 35 # NVLink flow control CRC Error Counter for Lane 3 +NVML_FI_DEV_NVLINK_CRC_FLIT_ERROR_COUNT_L4 = 36 # NVLink flow control CRC Error Counter for Lane 4 +NVML_FI_DEV_NVLINK_CRC_FLIT_ERROR_COUNT_L5 = 37 # NVLink flow control CRC Error Counter for Lane 5 +NVML_FI_DEV_NVLINK_CRC_FLIT_ERROR_COUNT_TOTAL = 38 # NVLink flow control CRC Error Counter total for all Lanes + +# NvLink CRC Data Error Counters +NVML_FI_DEV_NVLINK_CRC_DATA_ERROR_COUNT_L0 = 39 # NVLink data CRC Error Counter for Lane 0 +NVML_FI_DEV_NVLINK_CRC_DATA_ERROR_COUNT_L1 = 40 # NVLink data CRC Error Counter for Lane 1 +NVML_FI_DEV_NVLINK_CRC_DATA_ERROR_COUNT_L2 = 41 # NVLink data CRC Error Counter for Lane 2 +NVML_FI_DEV_NVLINK_CRC_DATA_ERROR_COUNT_L3 = 42 # NVLink data CRC Error Counter for Lane 3 +NVML_FI_DEV_NVLINK_CRC_DATA_ERROR_COUNT_L4 = 43 # NVLink data CRC Error Counter for Lane 4 +NVML_FI_DEV_NVLINK_CRC_DATA_ERROR_COUNT_L5 = 44 # NVLink data CRC Error Counter for Lane 5 +NVML_FI_DEV_NVLINK_CRC_DATA_ERROR_COUNT_TOTAL = 45 # NvLink data CRC Error Counter total for all Lanes + +# NvLink Replay Error Counters +NVML_FI_DEV_NVLINK_REPLAY_ERROR_COUNT_L0 = 46 # NVLink Replay Error Counter for Lane 0 +NVML_FI_DEV_NVLINK_REPLAY_ERROR_COUNT_L1 = 47 # NVLink Replay Error Counter for Lane 1 +NVML_FI_DEV_NVLINK_REPLAY_ERROR_COUNT_L2 = 48 # NVLink Replay Error Counter for Lane 2 +NVML_FI_DEV_NVLINK_REPLAY_ERROR_COUNT_L3 = 49 # NVLink Replay Error Counter for Lane 3 +NVML_FI_DEV_NVLINK_REPLAY_ERROR_COUNT_L4 = 50 # NVLink Replay Error Counter for Lane 4 +NVML_FI_DEV_NVLINK_REPLAY_ERROR_COUNT_L5 = 51 # NVLink Replay Error Counter for Lane 5 +NVML_FI_DEV_NVLINK_REPLAY_ERROR_COUNT_TOTAL = 52 # NVLink Replay Error Counter total for all Lanes + +# NvLink Recovery Error Counters +NVML_FI_DEV_NVLINK_RECOVERY_ERROR_COUNT_L0 = 53 # NVLink Recovery Error Counter for Lane 0 +NVML_FI_DEV_NVLINK_RECOVERY_ERROR_COUNT_L1 = 54 # NVLink Recovery Error Counter for Lane 1 +NVML_FI_DEV_NVLINK_RECOVERY_ERROR_COUNT_L2 = 55 # NVLink Recovery Error Counter for Lane 2 +NVML_FI_DEV_NVLINK_RECOVERY_ERROR_COUNT_L3 = 56 # NVLink Recovery Error Counter for Lane 3 +NVML_FI_DEV_NVLINK_RECOVERY_ERROR_COUNT_L4 = 57 # NVLink Recovery Error Counter for Lane 4 +NVML_FI_DEV_NVLINK_RECOVERY_ERROR_COUNT_L5 = 58 # NVLink Recovery Error Counter for Lane 5 +NVML_FI_DEV_NVLINK_RECOVERY_ERROR_COUNT_TOTAL = 59 # NVLink Recovery Error Counter total for all Lanes + +# NvLink Bandwidth Counters +NVML_FI_DEV_NVLINK_BANDWIDTH_C0_L0 = 60 # NVLink Bandwidth Counter for Counter Set 0, Lane 0 +NVML_FI_DEV_NVLINK_BANDWIDTH_C0_L1 = 61 # NVLink Bandwidth Counter for Counter Set 0, Lane 1 +NVML_FI_DEV_NVLINK_BANDWIDTH_C0_L2 = 62 # NVLink Bandwidth Counter for Counter Set 0, Lane 2 +NVML_FI_DEV_NVLINK_BANDWIDTH_C0_L3 = 63 # NVLink Bandwidth Counter for Counter Set 0, Lane 3 +NVML_FI_DEV_NVLINK_BANDWIDTH_C0_L4 = 64 # NVLink Bandwidth Counter for Counter Set 0, Lane 4 +NVML_FI_DEV_NVLINK_BANDWIDTH_C0_L5 = 65 # NVLink Bandwidth Counter for Counter Set 0, Lane 5 +NVML_FI_DEV_NVLINK_BANDWIDTH_C0_TOTAL = 66 # NVLink Bandwidth Counter Total for Counter Set 0, All Lanes + +# NvLink Bandwidth Counters +NVML_FI_DEV_NVLINK_BANDWIDTH_C1_L0 = 67 # NVLink Bandwidth Counter for Counter Set 1, Lane 0 +NVML_FI_DEV_NVLINK_BANDWIDTH_C1_L1 = 68 # NVLink Bandwidth Counter for Counter Set 1, Lane 1 +NVML_FI_DEV_NVLINK_BANDWIDTH_C1_L2 = 69 # NVLink Bandwidth Counter for Counter Set 1, Lane 2 +NVML_FI_DEV_NVLINK_BANDWIDTH_C1_L3 = 70 # NVLink Bandwidth Counter for Counter Set 1, Lane 3 +NVML_FI_DEV_NVLINK_BANDWIDTH_C1_L4 = 71 # NVLink Bandwidth Counter for Counter Set 1, Lane 4 +NVML_FI_DEV_NVLINK_BANDWIDTH_C1_L5 = 72 # NVLink Bandwidth Counter for Counter Set 1, Lane 5 +NVML_FI_DEV_NVLINK_BANDWIDTH_C1_TOTAL = 73 # NVLink Bandwidth Counter Total for Counter Set 1, All Lanes + +# Perf Policy Counters +NVML_FI_DEV_PERF_POLICY_POWER = 74 # Perf Policy Counter for Power Policy +NVML_FI_DEV_PERF_POLICY_THERMAL = 75 # Perf Policy Counter for Thermal Policy +NVML_FI_DEV_PERF_POLICY_SYNC_BOOST = 76 # Perf Policy Counter for Sync boost Policy +NVML_FI_DEV_PERF_POLICY_BOARD_LIMIT = 77 # Perf Policy Counter for Board Limit +NVML_FI_DEV_PERF_POLICY_LOW_UTILIZATION = 78 # Perf Policy Counter for Low GPU Utilization Policy +NVML_FI_DEV_PERF_POLICY_RELIABILITY = 79 # Perf Policy Counter for Reliability Policy +NVML_FI_DEV_PERF_POLICY_TOTAL_APP_CLOCKS = 80 # Perf Policy Counter for Total App Clock Policy +NVML_FI_DEV_PERF_POLICY_TOTAL_BASE_CLOCKS = 81 # Perf Policy Counter for Total Base Clocks Policy + +# Memory temperatures +NVML_FI_DEV_MEMORY_TEMP = 82 # Memory temperature for the device + +# Energy Counter +NVML_FI_DEV_TOTAL_ENERGY_CONSUMPTION = 83 # Total energy consumption for the GPU in mJ since the driver was last reloaded + +# NVLink Speed +NVML_FI_DEV_NVLINK_SPEED_MBPS_L0 = 84 +NVML_FI_DEV_NVLINK_SPEED_MBPS_L1 = 85 +NVML_FI_DEV_NVLINK_SPEED_MBPS_L2 = 86 +NVML_FI_DEV_NVLINK_SPEED_MBPS_L3 = 87 +NVML_FI_DEV_NVLINK_SPEED_MBPS_L4 = 88 +NVML_FI_DEV_NVLINK_SPEED_MBPS_L5 = 89 +NVML_FI_DEV_NVLINK_SPEED_MBPS_COMMON = 90 + +# NVLink Link Count +NVML_FI_DEV_NVLINK_LINK_COUNT = 91 + +# Page Retirement pending fields +NVML_FI_DEV_RETIRED_PENDING_SBE = 92 +NVML_FI_DEV_RETIRED_PENDING_DBE = 93 + +# PCIe replay and replay rollover counters +NVML_FI_DEV_PCIE_REPLAY_COUNTER = 94 +NVML_FI_DEV_PCIE_REPLAY_ROLLOVER_COUNTER = 95 + +# NvLink Flit Error Counters +NVML_FI_DEV_NVLINK_CRC_FLIT_ERROR_COUNT_L6 = 96 # NVLink flow control CRC Error Counter for Lane 6 +NVML_FI_DEV_NVLINK_CRC_FLIT_ERROR_COUNT_L7 = 97 # NVLink flow control CRC Error Counter for Lane 7 +NVML_FI_DEV_NVLINK_CRC_FLIT_ERROR_COUNT_L8 = 98 # NVLink flow control CRC Error Counter for Lane 8 +NVML_FI_DEV_NVLINK_CRC_FLIT_ERROR_COUNT_L9 = 99 # NVLink flow control CRC Error Counter for Lane 9 +NVML_FI_DEV_NVLINK_CRC_FLIT_ERROR_COUNT_L10 = 100 # NVLink flow control CRC Error Counter for Lane 10 +NVML_FI_DEV_NVLINK_CRC_FLIT_ERROR_COUNT_L11 = 101 # NVLink flow control CRC Error Counter for Lane 11 + +# NvLink CRC Data Error Counters +NVML_FI_DEV_NVLINK_CRC_DATA_ERROR_COUNT_L6 = 102 # NVLink data CRC Error Counter for Lane 6 +NVML_FI_DEV_NVLINK_CRC_DATA_ERROR_COUNT_L7 = 103 # NVLink data CRC Error Counter for Lane 7 +NVML_FI_DEV_NVLINK_CRC_DATA_ERROR_COUNT_L8 = 104 # NVLink data CRC Error Counter for Lane 8 +NVML_FI_DEV_NVLINK_CRC_DATA_ERROR_COUNT_L9 = 105 # NVLink data CRC Error Counter for Lane 9 +NVML_FI_DEV_NVLINK_CRC_DATA_ERROR_COUNT_L10 = 106 # NVLink data CRC Error Counter for Lane 10 +NVML_FI_DEV_NVLINK_CRC_DATA_ERROR_COUNT_L11 = 107 # NVLink data CRC Error Counter for Lane 11 + +# NvLink Replay Error Counters +NVML_FI_DEV_NVLINK_REPLAY_ERROR_COUNT_L6 = 108 # NVLink Replay Error Counter for Lane 6 +NVML_FI_DEV_NVLINK_REPLAY_ERROR_COUNT_L7 = 109 # NVLink Replay Error Counter for Lane 7 +NVML_FI_DEV_NVLINK_REPLAY_ERROR_COUNT_L8 = 110 # NVLink Replay Error Counter for Lane 8 +NVML_FI_DEV_NVLINK_REPLAY_ERROR_COUNT_L9 = 111 # NVLink Replay Error Counter for Lane 9 +NVML_FI_DEV_NVLINK_REPLAY_ERROR_COUNT_L10 = 112 # NVLink Replay Error Counter for Lane 10 +NVML_FI_DEV_NVLINK_REPLAY_ERROR_COUNT_L11 = 113 # NVLink Replay Error Counter for Lane 11 + +# NvLink Recovery Error Counters +NVML_FI_DEV_NVLINK_RECOVERY_ERROR_COUNT_L6 = 114 # NVLink Recovery Error Counter for Lane 6 +NVML_FI_DEV_NVLINK_RECOVERY_ERROR_COUNT_L7 = 115 # NVLink Recovery Error Counter for Lane 7 +NVML_FI_DEV_NVLINK_RECOVERY_ERROR_COUNT_L8 = 116 # NVLink Recovery Error Counter for Lane 8 +NVML_FI_DEV_NVLINK_RECOVERY_ERROR_COUNT_L9 = 117 # NVLink Recovery Error Counter for Lane 9 +NVML_FI_DEV_NVLINK_RECOVERY_ERROR_COUNT_L10 = 118 # NVLink Recovery Error Counter for Lane 10 +NVML_FI_DEV_NVLINK_RECOVERY_ERROR_COUNT_L11 = 119 # NVLink Recovery Error Counter for Lane 11 + +# NvLink Bandwidth Counters +NVML_FI_DEV_NVLINK_BANDWIDTH_C0_L6 = 120 # NVLink Bandwidth Counter for Counter Set 0, Lane 6 +NVML_FI_DEV_NVLINK_BANDWIDTH_C0_L7 = 121 # NVLink Bandwidth Counter for Counter Set 0, Lane 7 +NVML_FI_DEV_NVLINK_BANDWIDTH_C0_L8 = 122 # NVLink Bandwidth Counter for Counter Set 0, Lane 8 +NVML_FI_DEV_NVLINK_BANDWIDTH_C0_L9 = 123 # NVLink Bandwidth Counter for Counter Set 0, Lane 9 +NVML_FI_DEV_NVLINK_BANDWIDTH_C0_L10 = 124 # NVLink Bandwidth Counter for Counter Set 0, Lane 10 +NVML_FI_DEV_NVLINK_BANDWIDTH_C0_L11 = 125 # NVLink Bandwidth Counter for Counter Set 0, Lane 11 + +# NvLink Bandwidth Counters +NVML_FI_DEV_NVLINK_BANDWIDTH_C1_L6 = 126 # NVLink Bandwidth Counter for Counter Set 1, Lane 6 +NVML_FI_DEV_NVLINK_BANDWIDTH_C1_L7 = 127 # NVLink Bandwidth Counter for Counter Set 1, Lane 7 +NVML_FI_DEV_NVLINK_BANDWIDTH_C1_L8 = 128 # NVLink Bandwidth Counter for Counter Set 1, Lane 8 +NVML_FI_DEV_NVLINK_BANDWIDTH_C1_L9 = 129 # NVLink Bandwidth Counter for Counter Set 1, Lane 9 +NVML_FI_DEV_NVLINK_BANDWIDTH_C1_L10 = 130 # NVLink Bandwidth Counter for Counter Set 1, Lane 10 +NVML_FI_DEV_NVLINK_BANDWIDTH_C1_L11 = 131 # NVLink Bandwidth Counter for Counter Set 1, Lane 11 + +# NVLink Speed +NVML_FI_DEV_NVLINK_SPEED_MBPS_L6 = 132 +NVML_FI_DEV_NVLINK_SPEED_MBPS_L7 = 133 +NVML_FI_DEV_NVLINK_SPEED_MBPS_L8 = 134 +NVML_FI_DEV_NVLINK_SPEED_MBPS_L9 = 135 +NVML_FI_DEV_NVLINK_SPEED_MBPS_L10 = 136 +NVML_FI_DEV_NVLINK_SPEED_MBPS_L11 = 137 + +# NVLink Throughput Counters +NVML_FI_DEV_NVLINK_THROUGHPUT_DATA_TX = 138 # NVLink TX Data throughput in KiB +NVML_FI_DEV_NVLINK_THROUGHPUT_DATA_RX = 139 # NVLink RX Data throughput in KiB +NVML_FI_DEV_NVLINK_THROUGHPUT_RAW_TX = 140 # NVLink TX Data + protocol overhead in KiB +NVML_FI_DEV_NVLINK_THROUGHPUT_RAW_RX = 141 # NVLink RX Data + protocol overhead in KiB + +# Row Remapper +NVML_FI_DEV_REMAPPED_COR = 142 +NVML_FI_DEV_REMAPPED_UNC = 143 +NVML_FI_DEV_REMAPPED_PENDING = 144 +NVML_FI_DEV_REMAPPED_FAILURE = 145 + +#Remote device NVLink ID +NVML_FI_DEV_NVLINK_REMOTE_NVLINK_ID = 146 + +# Number of NVLinks connected to NVSwitch +NVML_FI_DEV_NVSWITCH_CONNECTED_LINK_COUNT = 147 + +# NvLink ECC Data Error Counters +NVML_FI_DEV_NVLINK_ECC_DATA_ERROR_COUNT_L0 = 148 #< NVLink data ECC Error Counter for Link 0 +NVML_FI_DEV_NVLINK_ECC_DATA_ERROR_COUNT_L1 = 149 #< NVLink data ECC Error Counter for Link 1 +NVML_FI_DEV_NVLINK_ECC_DATA_ERROR_COUNT_L2 = 150 #< NVLink data ECC Error Counter for Link 2 +NVML_FI_DEV_NVLINK_ECC_DATA_ERROR_COUNT_L3 = 151 #< NVLink data ECC Error Counter for Link 3 +NVML_FI_DEV_NVLINK_ECC_DATA_ERROR_COUNT_L4 = 152 #< NVLink data ECC Error Counter for Link 4 +NVML_FI_DEV_NVLINK_ECC_DATA_ERROR_COUNT_L5 = 153 #< NVLink data ECC Error Counter for Link 5 +NVML_FI_DEV_NVLINK_ECC_DATA_ERROR_COUNT_L6 = 154 #< NVLink data ECC Error Counter for Link 6 +NVML_FI_DEV_NVLINK_ECC_DATA_ERROR_COUNT_L7 = 155 #< NVLink data ECC Error Counter for Link 7 +NVML_FI_DEV_NVLINK_ECC_DATA_ERROR_COUNT_L8 = 156 #< NVLink data ECC Error Counter for Link 8 +NVML_FI_DEV_NVLINK_ECC_DATA_ERROR_COUNT_L9 = 157 #< NVLink data ECC Error Counter for Link 9 +NVML_FI_DEV_NVLINK_ECC_DATA_ERROR_COUNT_L10 = 158 #< NVLink data ECC Error Counter for Link 10 +NVML_FI_DEV_NVLINK_ECC_DATA_ERROR_COUNT_L11 = 159 #< NVLink data ECC Error Counter for Link 11 +NVML_FI_DEV_NVLINK_ECC_DATA_ERROR_COUNT_TOTAL = 160 #< NvLink data ECC Error Counter total for all Links + +NVML_FI_DEV_NVLINK_ERROR_DL_REPLAY = 161 +NVML_FI_DEV_NVLINK_ERROR_DL_RECOVERY = 162 +NVML_FI_DEV_NVLINK_ERROR_DL_CRC = 163 +NVML_FI_DEV_NVLINK_GET_SPEED = 164 +NVML_FI_DEV_NVLINK_GET_STATE = 165 +NVML_FI_DEV_NVLINK_GET_VERSION = 166 + +NVML_FI_DEV_NVLINK_GET_POWER_STATE = 167 +NVML_FI_DEV_NVLINK_GET_POWER_THRESHOLD = 168 + +NVML_FI_DEV_PCIE_L0_TO_RECOVERY_COUNTER = 169 + +NVML_FI_DEV_C2C_LINK_COUNT = 170 +NVML_FI_DEV_C2C_LINK_GET_STATUS = 171 +NVML_FI_DEV_C2C_LINK_GET_MAX_BW = 172 + +NVML_FI_DEV_PCIE_COUNT_CORRECTABLE_ERRORS = 173 +NVML_FI_DEV_PCIE_COUNT_NAKS_RECEIVED = 174 +NVML_FI_DEV_PCIE_COUNT_RECEIVER_ERROR = 175 +NVML_FI_DEV_PCIE_COUNT_BAD_TLP = 176 +NVML_FI_DEV_PCIE_COUNT_NAKS_SENT = 177 +NVML_FI_DEV_PCIE_COUNT_BAD_DLLP = 178 +NVML_FI_DEV_PCIE_COUNT_NON_FATAL_ERROR = 179 +NVML_FI_DEV_PCIE_COUNT_FATAL_ERROR = 180 +NVML_FI_DEV_PCIE_COUNT_UNSUPPORTED_REQ = 181 +NVML_FI_DEV_PCIE_COUNT_LCRC_ERROR = 182 +NVML_FI_DEV_PCIE_COUNT_LANE_ERROR = 183 + +NVML_FI_DEV_IS_RESETLESS_MIG_SUPPORTED = 184 + +NVML_FI_DEV_POWER_AVERAGE = 185 +NVML_FI_DEV_POWER_INSTANT = 186 +NVML_FI_DEV_POWER_MIN_LIMIT = 187 +NVML_FI_DEV_POWER_MAX_LIMIT = 188 +NVML_FI_DEV_POWER_DEFAULT_LIMIT = 189 +NVML_FI_DEV_POWER_CURRENT_LIMIT = 190 +NVML_FI_DEV_ENERGY = 191 +NVML_FI_DEV_POWER_REQUESTED_LIMIT = 192 + +NVML_FI_DEV_TEMPERATURE_SHUTDOWN_TLIMIT = 193 +NVML_FI_DEV_TEMPERATURE_SLOWDOWN_TLIMIT = 194 +NVML_FI_DEV_TEMPERATURE_MEM_MAX_TLIMIT = 195 +NVML_FI_DEV_TEMPERATURE_GPU_MAX_TLIMIT = 196 + +NVML_FI_DEV_PCIE_COUNT_TX_BYTES = 197 +NVML_FI_DEV_PCIE_COUNT_RX_BYTES = 198 + +NVML_FI_DEV_IS_MIG_MODE_INDEPENDENT_MIG_QUERY_CAPABLE = 199 + +NVML_FI_DEV_NVLINK_GET_POWER_THRESHOLD_MAX = 200 + +NVML_FI_DEV_NVLINK_COUNT_XMIT_PACKETS = 201 +NVML_FI_DEV_NVLINK_COUNT_XMIT_BYTES = 202 +NVML_FI_DEV_NVLINK_COUNT_RCV_PACKETS = 203 +NVML_FI_DEV_NVLINK_COUNT_RCV_BYTES = 204 +NVML_FI_DEV_NVLINK_COUNT_VL15_DROPPED = 205 # Deprecated, do not use +NVML_FI_DEV_NVLINK_COUNT_MALFORMED_PACKET_ERRORS = 206 +NVML_FI_DEV_NVLINK_COUNT_BUFFER_OVERRUN_ERRORS = 207 +NVML_FI_DEV_NVLINK_COUNT_RCV_ERRORS = 208 +NVML_FI_DEV_NVLINK_COUNT_RCV_REMOTE_ERRORS = 209 +NVML_FI_DEV_NVLINK_COUNT_RCV_GENERAL_ERRORS = 210 +NVML_FI_DEV_NVLINK_COUNT_LOCAL_LINK_INTEGRITY_ERRORS = 211 +NVML_FI_DEV_NVLINK_COUNT_XMIT_DISCARDS = 212 + +NVML_FI_DEV_NVLINK_COUNT_LINK_RECOVERY_SUCCESSFUL_EVENTS = 213 +NVML_FI_DEV_NVLINK_COUNT_LINK_RECOVERY_FAILED_EVENTS = 214 +NVML_FI_DEV_NVLINK_COUNT_LINK_RECOVERY_EVENTS = 215 + +NVML_FI_DEV_NVLINK_COUNT_RAW_BER_LANE0 = 216 # Deprecated, do not use +NVML_FI_DEV_NVLINK_COUNT_RAW_BER_LANE1 = 217 # Deprecated, do not use +NVML_FI_DEV_NVLINK_COUNT_RAW_BER = 218 # Deprecated, do not use +NVML_FI_DEV_NVLINK_COUNT_EFFECTIVE_ERRORS = 219 +NVML_FI_DEV_NVLINK_COUNT_EFFECTIVE_BER = 220 +NVML_FI_DEV_NVLINK_COUNT_SYMBOL_ERRORS = 221 +NVML_FI_DEV_NVLINK_COUNT_SYMBOL_BER = 222 + +NVML_FI_DEV_NVLINK_GET_POWER_THRESHOLD_MIN = 223 +NVML_FI_DEV_NVLINK_GET_POWER_THRESHOLD_UNITS = 224 # Values are in the form NVML_NVLINK_LOW_POWER_THRESHOLD_UNIT_* +NVML_FI_DEV_NVLINK_GET_POWER_THRESHOLD_SUPPORTED = 225 + +NVML_FI_DEV_RESET_STATUS = 226 # Deprecated use NVML_FI_DEV_GET_GPU_RECOVERY_ACTION instead +NVML_FI_DEV_DRAIN_AND_RESET_STATUS = 227 # Deprecated use NVML_FI_DEV_GET_GPU_RECOVERY_ACTION instead +NVML_FI_DEV_PCIE_OUTBOUND_ATOMICS_MASK = 228 +NVML_FI_DEV_PCIE_INBOUND_ATOMICS_MASK = 229 +NVML_FI_DEV_GET_GPU_RECOVERY_ACTION = 230 + +NVML_FI_DEV_C2C_LINK_ERROR_INTR = 231 +NVML_FI_DEV_C2C_LINK_ERROR_REPLAY = 232 +NVML_FI_DEV_C2C_LINK_ERROR_REPLAY_B2B = 233 +NVML_FI_DEV_C2C_LINK_POWER_STATE = 234 + +NVML_FI_DEV_NVLINK_COUNT_FEC_HISTORY_0 = 235 +NVML_FI_DEV_NVLINK_COUNT_FEC_HISTORY_1 = 236 +NVML_FI_DEV_NVLINK_COUNT_FEC_HISTORY_2 = 237 +NVML_FI_DEV_NVLINK_COUNT_FEC_HISTORY_3 = 238 +NVML_FI_DEV_NVLINK_COUNT_FEC_HISTORY_4 = 239 +NVML_FI_DEV_NVLINK_COUNT_FEC_HISTORY_5 = 240 +NVML_FI_DEV_NVLINK_COUNT_FEC_HISTORY_6 = 241 +NVML_FI_DEV_NVLINK_COUNT_FEC_HISTORY_7 = 242 +NVML_FI_DEV_NVLINK_COUNT_FEC_HISTORY_8 = 243 +NVML_FI_DEV_NVLINK_COUNT_FEC_HISTORY_9 = 244 +NVML_FI_DEV_NVLINK_COUNT_FEC_HISTORY_10 = 245 +NVML_FI_DEV_NVLINK_COUNT_FEC_HISTORY_11 = 246 +NVML_FI_DEV_NVLINK_COUNT_FEC_HISTORY_12 = 247 +NVML_FI_DEV_NVLINK_COUNT_FEC_HISTORY_13 = 248 +NVML_FI_DEV_NVLINK_COUNT_FEC_HISTORY_14 = 249 +NVML_FI_DEV_NVLINK_COUNT_FEC_HISTORY_15 = 250 +NVML_FI_PWR_SMOOTHING_ENABLED = 251 # Enablement (0/DISABLED or 1/ENABLED) +NVML_FI_PWR_SMOOTHING_PRIV_LVL = 252 # Current privilege level +NVML_FI_PWR_SMOOTHING_IMM_RAMP_DOWN_ENABLED = 253 # Immediate ramp down enablement (0/DISABLED or 1/ENABLED) +NVML_FI_PWR_SMOOTHING_APPLIED_TMP_CEIL = 254 # Applied TMP ceiling value +NVML_FI_PWR_SMOOTHING_APPLIED_TMP_FLOOR = 255 # Applied TMP floor value +NVML_FI_PWR_SMOOTHING_MAX_PERCENT_TMP_FLOOR_SETTING = 256 # Max % TMP Floor value +NVML_FI_PWR_SMOOTHING_MIN_PERCENT_TMP_FLOOR_SETTING = 257 # Min % TMP Floor value +NVML_FI_PWR_SMOOTHING_HW_CIRCUITRY_PERCENT_LIFETIME_REMAINING = 258 # HW Circuitry % lifetime remaining +NVML_FI_PWR_SMOOTHING_MAX_NUM_PRESET_PROFILES = 259 # Max number of preset profiles +NVML_FI_PWR_SMOOTHING_PROFILE_PERCENT_TMP_FLOOR = 260 # % TMP floor for a given profile +NVML_FI_PWR_SMOOTHING_PROFILE_RAMP_UP_RATE = 261 # Ramp up rate in mW/s for a given profile +NVML_FI_PWR_SMOOTHING_PROFILE_RAMP_DOWN_RATE = 262 # Ramp down rate in mW/s for a given profile +NVML_FI_PWR_SMOOTHING_PROFILE_RAMP_DOWN_HYST_VAL = 263 # Ramp down hysteresis value in ms for a given profile +NVML_FI_PWR_SMOOTHING_ACTIVE_PRESET_PROFILE = 264 # Active preset profile number +NVML_FI_PWR_SMOOTHING_ADMIN_OVERRIDE_PERCENT_TMP_FLOOR = 265 # % TMP floor for a given profile +NVML_FI_PWR_SMOOTHING_ADMIN_OVERRIDE_RAMP_UP_RATE = 266 # Ramp up rate in mW/s for a given profile +NVML_FI_PWR_SMOOTHING_ADMIN_OVERRIDE_RAMP_DOWN_RATE = 267 # Ramp down rate in mW/s for a given profile +NVML_FI_PWR_SMOOTHING_ADMIN_OVERRIDE_RAMP_DOWN_HYST_VAL = 268 # Ramp down hysteresis value in ms for a given profile +NVML_FI_DEV_CLOCKS_EVENT_REASON_SW_POWER_CAP = NVML_FI_DEV_PERF_POLICY_POWER +NVML_FI_DEV_CLOCKS_EVENT_REASON_SYNC_BOOST = NVML_FI_DEV_PERF_POLICY_SYNC_BOOST +NVML_FI_DEV_CLOCKS_EVENT_REASON_SW_THERM_SLOWDOWN = 269 +NVML_FI_DEV_CLOCKS_EVENT_REASON_HW_THERM_SLOWDOWN = 270 +NVML_FI_DEV_CLOCKS_EVENT_REASON_HW_POWER_BRAKE_SLOWDOWN = 271 +NVML_FI_DEV_POWER_SYNC_BALANCING_FREQ = 272 +NVML_FI_DEV_POWER_SYNC_BALANCING_AF = 273 +NVML_FI_DEV_EDPP_MULTIPLIER = 274 # EDPp multiplier expressed as a percentage +NVML_FI_PWR_SMOOTHING_PRIMARY_POWER_FLOOR = 275 # Current primary Power floor value in Watts +NVML_FI_PWR_SMOOTHING_SECONDARY_POWER_FLOOR = 276 # Current secondary Power floor value in Watts +NVML_FI_PWR_SMOOTHING_MIN_PRIMARY_FLOOR_ACT_OFFSET = 277 # Minimum primary floor activation offset value in Watts +NVML_FI_PWR_SMOOTHING_MIN_PRIMARY_FLOOR_ACT_POINT = 278 # Minimum primary floor activation point value in Watts +NVML_FI_PWR_SMOOTHING_WINDOW_MULTIPLIER = 279 # Window Multiplier value in ms +NVML_FI_PWR_SMOOTHING_DELAYED_PWR_SMOOTHING_SUPPORTED = 280 # Supported (0/Not Supported or 1/Supported) for delayed power smoothing +NVML_FI_PWR_SMOOTHING_PROFILE_SECONDARY_POWER_FLOOR = 281 # Current secondary power floor value in Watts for a given profile +NVML_FI_PWR_SMOOTHING_PROFILE_PRIMARY_FLOOR_ACT_WIN_MULT = 282 # Current primary floor activation window multiplier value for a given profile +NVML_FI_PWR_SMOOTHING_PROFILE_PRIMARY_FLOOR_TAR_WIN_MULT = 283 # Current primary floor target window multiplier value for a given profile +NVML_FI_PWR_SMOOTHING_PROFILE_PRIMARY_FLOOR_ACT_OFFSET = 284 # Current primary floor activation offset value in Watts for a given profile +NVML_FI_PWR_SMOOTHING_ADMIN_OVERRIDE_SECONDARY_POWER_FLOOR = 285 # Current secondary power floor value in Watts for a given profile +NVML_FI_PWR_SMOOTHING_ADMIN_OVERRIDE_PRIMARY_FLOOR_ACT_WIN_MULT = 286 # Current primary floor activation window multiplier value for a given profile +NVML_FI_PWR_SMOOTHING_ADMIN_OVERRIDE_PRIMARY_FLOOR_TAR_WIN_MULT = 287 # Current primary floor target window multiplier value for a given profile +NVML_FI_PWR_SMOOTHING_ADMIN_OVERRIDE_PRIMARY_FLOOR_ACT_OFFSET = 288 # Current primary floor activation offset value in Watts for a given profile +NVML_FI_DEV_NVLINK_COUNT_RAW_ERRORS_LANE0 = 289 # NVLINK raw error count for lane 0 +NVML_FI_DEV_NVLINK_COUNT_RAW_ERRORS_LANE1 = 290 # NVLINK raw error count for lane 1 +NVML_FI_DEV_NVLINK_COUNT_RAW_BER_LANE0_V2 = 291 # NVLINK raw BER for lane 0 +NVML_FI_DEV_NVLINK_COUNT_RAW_BER_LANE1_V2 = 292 # NVLINK raw BER for lane 1 +NVML_FI_DEV_NVLINK_COUNT_RAW_BER_V2 = 293 # NVLINK total raw BER +NVML_FI_DEV_NVLINK_PLR_XMIT_BLOCKS = 294 # NVLINK PLR Xmit Blocks +NVML_FI_DEV_NVLINK_PLR_XMIT_RETRY_BLOCKS = 295 # NVLINK PLR XMIT Retry Blocks +NVML_FI_DEV_NVLINK_GET_DATA_RATE = 296 # The Effective Nvlink Data rate available for transactions after accounting for FEC overhead +NVML_FI_DEV_MMA_STALL_PERCENT = 297 # MMA stall percentage +NVML_FI_DEV_MCLK_SWITCH_TYPE = 298 # See NVML_MCLK_SWITCH_TYPE_ for all enumerations +NVML_FI_DEV_MCLK_MIN_SWITCH_INTERVAL_MILLISECONDS = 299 # minimum required elapsed time between runtime mclk switches, 0 = no rate limit +NVML_FI_PWR_SMOOTHING_SOC_POWER_SMOOTHING_ENABLED = 300 # State-Of-Charge Power Smoothing Enabled (0/DISABLED or 1/ENABLED) +NVML_FI_DEV_REMAPPED_ROWS_COR_INACTIVE = 301 +NVML_FI_DEV_REMAPPED_ROWS_UNC_INACTIVE = 302 +NVML_FI_MAX = 303 # One greater than the largest field ID defined above + +# NVML_FI_DEV_MCLK_SWITCH_TYPE enumerations +NVML_MCLK_SWITCH_TYPE_NOT_SUPPORTED = 0x0 # switching is not supported +NVML_MCLK_SWITCH_TYPE_DEFERRED = 0x1 # deferred switching (driver reload) +NVML_MCLK_SWITCH_TYPE_RUNTIME = 0x2 # runtime switching + +# NVML_FI_DEV_NVLINK_GET_STATE state enums +NVML_NVLINK_STATE_INACTIVE = 0x0 +NVML_NVLINK_STATE_ACTIVE = 0x1 +NVML_NVLINK_STATE_SLEEP = 0x2 + +NVML_NVLINK_LOW_POWER_THRESHOLD_UNIT_100US = 0 # NVML_FI_DEV_NVLINK_GET_POWER_THRESHOLD_UNITS +NVML_NVLINK_LOW_POWER_THRESHOLD_UNIT_50US = 1 # NVML_FI_DEV_NVLINK_GET_POWER_THRESHOLD_UNITS + +# NVML_FI_DEV_C2C_LINK_POWER_STATE state enums +NVML_C2C_POWER_STATE_FULL_POWER = 0 +NVML_C2C_POWER_STATE_LOW_POWER = 1 + +## Enums needed for the method nvmlDeviceGetVirtualizationMode and nvmlDeviceSetVirtualizationMode +NVML_GPU_VIRTUALIZATION_MODE_NONE = 0 # Represents Bare Metal GPU +NVML_GPU_VIRTUALIZATION_MODE_PASSTHROUGH = 1 # Device is associated with GPU-Passthorugh +NVML_GPU_VIRTUALIZATION_MODE_VGPU = 2 # Device is associated with vGPU inside virtual machine. +NVML_GPU_VIRTUALIZATION_MODE_HOST_VGPU = 3 # Device is associated with VGX hypervisor in vGPU mode +NVML_GPU_VIRTUALIZATION_MODE_HOST_VSGA = 4 # Device is associated with VGX hypervisor in vSGA mode + +## Lib loading ## +nvmlLib = None +libLoadLock = threading.Lock() +_nvmlLib_refcount = 0 # Incremented on each nvmlInit and decremented on nvmlShutdown + +## vGPU Management +_nvmlVgpuTypeId_t = c_uint +_nvmlVgpuInstance_t = c_uint + +_nvmlVgpuVmIdType_t = c_uint +NVML_VGPU_VM_ID_DOMAIN_ID = 0 +NVML_VGPU_VM_ID_UUID = 1 + +_nvmlGridLicenseFeatureCode_t = c_uint +NVML_GRID_LICENSE_FEATURE_CODE_UNKNOWN = 0 +NVML_GRID_LICENSE_FEATURE_CODE_VGPU = 1 +NVML_GRID_LICENSE_FEATURE_CODE_NVIDIA_RTX = 2 +NVML_GRID_LICENSE_FEATURE_CODE_VWORKSTATION = 2 # deprecated, use NVML_GRID_LICENSE_FEATURE_CODE_NVIDIA_RTX. +NVML_GRID_LICENSE_FEATURE_CODE_GAMING = 3 +NVML_GRID_LICENSE_FEATURE_CODE_COMPUTE = 4 + +_nvmlGridLicenseExpiryStatus_t = c_uint8 +NVML_GRID_LICENSE_EXPIRY_NOT_AVAILABLE = 0, # Expiry information not available +NVML_GRID_LICENSE_EXPIRY_INVALID = 1, # Invalid expiry or error fetching expiry +NVML_GRID_LICENSE_EXPIRY_VALID = 2, # Valid expiry +NVML_GRID_LICENSE_EXPIRY_NOT_APPLICABLE = 3, # Expiry not applicable +NVML_GRID_LICENSE_EXPIRY_PERMANENT = 4, # Permanent expiry + +_nvmlVgpuCapability_t = c_uint +NVML_VGPU_CAP_NVLINK_P2P = 0 # vGPU P2P over NVLink is supported +NVML_VGPU_CAP_GPUDIRECT = 1 # GPUDirect capability is supported +NVML_VGPU_CAP_MULTI_VGPU_EXCLUSIVE = 2 # vGPU profile cannot be mixed with other vGPU profiles in same VM +NVML_VGPU_CAP_EXCLUSIVE_TYPE = 3 # vGPU profile cannot run on a GPU alongside other profiles of different type +NVML_VGPU_CAP_EXCLUSIVE_SIZE = 4 # vGPU profile cannot run on a GPU alongside other profiles of different size +NVML_VGPU_CAP_COUNT = 5 + +_nvmlVgpuDriverCapability_t = c_uint +NVML_VGPU_DRIVER_CAP_HETEROGENEOUS_MULTI_VGPU = 0 # Supports mixing of different vGPU profiles within one guest VM +NVML_VGPU_DRIVER_CAP_WARM_UPDATE = 1 # Supports FSR and warm update of vGPU host driver without terminating the running guest VM +NVML_VGPU_DRIVER_CAP_COUNT = 2 + +_nvmlDeviceVgpuCapability_t = c_uint +NVML_DEVICE_VGPU_CAP_FRACTIONAL_MULTI_VGPU = 0 # Query whether the fractional vGPU profiles on this GPU can be used in multi-vGPU configurations +NVML_DEVICE_VGPU_CAP_HETEROGENEOUS_TIMESLICE_PROFILES = 1 # Query whether the GPU supports concurrent execution of timesliced vGPU profiles of differing types +NVML_DEVICE_VGPU_CAP_HETEROGENEOUS_TIMESLICE_SIZES = 2 # Query whether the GPU supports concurrent execution of timesliced vGPU profiles of differing framebuffer sizes +NVML_DEVICE_VGPU_CAP_READ_DEVICE_BUFFER_BW = 3 # Query the GPU's read_device_buffer expected bandwidth capacity in megabytes per second +NVML_DEVICE_VGPU_CAP_WRITE_DEVICE_BUFFER_BW = 4 # Query the GPU's write_device_buffer expected bandwidth capacity in megabytes per second +NVML_DEVICE_VGPU_CAP_DEVICE_STREAMING = 5 # Query whether the vGPU profiles on the GPU supports migration data streaming +NVML_DEVICE_VGPU_CAP_MINI_QUARTER_GPU = 6 # Set/Get support of mini-quarter vGPU profiles +NVML_DEVICE_VGPU_CAP_COMPUTE_MEDIA_ENGINE_GPU = 7 # Set/Get support for compute media engine vGPU profiles +NVML_DEVICE_VGPU_CAP_WARM_UPDATE = 8 # Query whether the GPU supports FSR and warm update +NVML_DEVICE_VGPU_CAP_HOMOGENEOUS_PLACEMENTS = 9 # Query whether the GPU supports reporting of placements of timesliced vGPU profiles with identical framebuffer sizes +NVML_DEVICE_VGPU_CAP_MIG_TIMESLICING_SUPPORTED = 10 # Query whether the GPU supports timesliced vGPU on MIG +NVML_DEVICE_VGPU_CAP_MIG_TIMESLICING_ENABLED = 11 # Set/Get MIG timesliced mode reporting, without impacting the underlying functionality +NVML_DEVICE_VGPU_CAP_COUNT = 12 + +_nvmlVgpuGuestInfoState_t = c_uint +NVML_VGPU_INSTANCE_GUEST_INFO_STATE_UNINITIALIZED = 0 +NVML_VGPU_INSTANCE_GUEST_INFO_STATE_INITIALIZED = 1 + +_nvmlVgpuVmCompatibility_t = c_uint +NVML_VGPU_VM_COMPATIBILITY_NONE = 0x0 +NVML_VGPU_VM_COMPATIBILITY_COLD = 0x1 +NVML_VGPU_VM_COMPATIBILITY_HIBERNATE = 0x2 +NVML_VGPU_VM_COMPATIBILITY_SLEEP = 0x4 +NVML_VGPU_VM_COMPATIBILITY_LIVE = 0x8 + +_nvmlVgpuPgpuCompatibilityLimitCode_t = c_uint +NVML_VGPU_COMPATIBILITY_LIMIT_NONE = 0x0 +NVML_VGPU_COMPATIBILITY_LIMIT_HOST_DRIVER = 0x1 +NVML_VGPU_COMPATIBILITY_LIMIT_GUEST_DRIVER = 0x2 +NVML_VGPU_COMPATIBILITY_LIMIT_GPU = 0x4 +NVML_VGPU_COMPATIBILITY_LIMIT_OTHER = 0x80000000 + +_nvmlHostVgpuMode_t = c_uint +NVML_HOST_VGPU_MODE_NON_SRIOV = 0 +NVML_HOST_VGPU_MODE_SRIOV = 1 + +_nvmlConfComputeGpusReadyState_t = c_uint +NVML_CC_ACCEPTING_CLIENT_REQUESTS_FALSE = 0 +NVML_CC_ACCEPTING_CLIENT_REQUESTS_TRUE = 1 + +_nvmlConfComputeGpuCaps_t = c_uint +NVML_CC_SYSTEM_GPUS_CC_NOT_CAPABLE = 0 +NVML_CC_SYSTEM_GPUS_CC_CAPABLE = 1 + +_nvmlConfComputeCpuCaps_t = c_uint +NVML_CC_SYSTEM_CPU_CAPS_NONE = 0 +NVML_CC_SYSTEM_CPU_CAPS_AMD_SEV = 1 +NVML_CC_SYSTEM_CPU_CAPS_INTEL_TDX = 2 +NVML_CC_SYSTEM_CPU_CAPS_AMD_SEV_SNP = 3 +NVML_CC_SYSTEM_CPU_CAPS_AMD_SNP_VTOM = 4 + +_nvmlConfComputeDevToolsMode_t = c_uint +NVML_CC_SYSTEM_DEVTOOLS_MODE_OFF = 0 +NVML_CC_SYSTEM_DEVTOOLS_MODE_ON = 1 + +NVML_CC_SYSTEM_MULTIGPU_NONE = 0 +NVML_CC_SYSTEM_MULTIGPU_PROTECTED_PCIE = 1 +NVML_CC_SYSTEM_MULTIGPU_NVLE = 2 + +NVML_CC_SYSTEM_ENVIRONMENT_UNAVAILABLE = 0 +NVML_CC_SYSTEM_ENVIRONMENT_SIM = 1 +NVML_CC_SYSTEM_ENVIRONMENT_PROD = 2 + +_nvmlConfComputeCcFeature_t = c_uint +NVML_CC_SYSTEM_FEATURE_DISABLED = 0 +NVML_CC_SYSTEM_FEATURE_ENABLED = 1 + +_nvmlConfComputeCcKeyRotationThreshAttackerAdv_t = c_uint +NVML_CC_KEY_ROTATION_THRESH_ATTACKER_ADVANTAGE_MIN = 50 +NVML_CC_KEY_ROTATION_THRESH_ATTACKER_ADVANTAGE_MAX = 65 + +# GSP firmware +NVML_GSP_FIRMWARE_VERSION_BUF_SIZE = 0x40 + +class NVMLLibraryMismatchError(Exception): + pass + +## Error Checking ## +class NVMLError(Exception): + _valClassMapping = dict() + # List of currently known error codes + _errcode_to_string = { + NVML_ERROR_UNINITIALIZED: "Uninitialized", + NVML_ERROR_INVALID_ARGUMENT: "Invalid Argument", + NVML_ERROR_NOT_SUPPORTED: "Not Supported", + NVML_ERROR_NO_PERMISSION: "Insufficient Permissions", + NVML_ERROR_ALREADY_INITIALIZED: "Already Initialized", + NVML_ERROR_NOT_FOUND: "Not Found", + NVML_ERROR_INSUFFICIENT_SIZE: "Insufficient Size", + NVML_ERROR_INSUFFICIENT_POWER: "Insufficient External Power", + NVML_ERROR_DRIVER_NOT_LOADED: "Driver Not Loaded", + NVML_ERROR_TIMEOUT: "Timeout", + NVML_ERROR_IRQ_ISSUE: "Interrupt Request Issue", + NVML_ERROR_LIBRARY_NOT_FOUND: "NVML Shared Library Not Found", + NVML_ERROR_FUNCTION_NOT_FOUND: "Function Not Found", + NVML_ERROR_CORRUPTED_INFOROM: "Corrupted infoROM", + NVML_ERROR_GPU_IS_LOST: "GPU is lost", + NVML_ERROR_RESET_REQUIRED: "GPU requires restart", + NVML_ERROR_OPERATING_SYSTEM: "The operating system has blocked the request.", + NVML_ERROR_LIB_RM_VERSION_MISMATCH: "RM has detected an NVML/RM version mismatch.", + NVML_ERROR_MEMORY: "Insufficient Memory", + NVML_ERROR_UNKNOWN: "Unknown Error", + } + def __new__(typ, value): + ''' + Maps value to a proper subclass of NVMLError. + See _extractNVMLErrorsAsClasses function for more details + ''' + if typ == NVMLError: + typ = NVMLError._valClassMapping.get(value, typ) + obj = Exception.__new__(typ) + obj.value = value + return obj + def __str__(self): + try: + if self.value not in NVMLError._errcode_to_string: + NVMLError._errcode_to_string[self.value] = str(nvmlErrorString(self.value)) + return NVMLError._errcode_to_string[self.value] + except NVMLError: + return "NVML Error with code %d" % self.value + def __eq__(self, other): + return self.value == other.value + +def nvmlExceptionClass(nvmlErrorCode): + if nvmlErrorCode not in NVMLError._valClassMapping: + raise ValueError('nvmlErrorCode %s is not valid' % nvmlErrorCode) + return NVMLError._valClassMapping[nvmlErrorCode] + +def _extractNVMLErrorsAsClasses(): + ''' + Generates a hierarchy of classes on top of NVMLError class. + + Each NVML Error gets a new NVMLError subclass. This way try,except blocks can filter appropriate + exceptions more easily. + + NVMLError is a parent class. Each NVML_ERROR_* gets it's own subclass. + e.g. NVML_ERROR_ALREADY_INITIALIZED will be turned into NVMLError_AlreadyInitialized + ''' + this_module = sys.modules[__name__] + nvmlErrorsNames = [x for x in dir(this_module) if x.startswith("NVML_ERROR_")] + for err_name in nvmlErrorsNames: + # e.g. Turn NVML_ERROR_ALREADY_INITIALIZED into NVMLError_AlreadyInitialized + class_name = "NVMLError_" + string.capwords(err_name.replace("NVML_ERROR_", ""), "_").replace("_", "") + err_val = getattr(this_module, err_name) + def gen_new(val): + def new(typ, *args): + obj = NVMLError.__new__(typ, val) + return obj + return new + new_error_class = type(class_name, (NVMLError,), {'__new__': gen_new(err_val)}) + new_error_class.__module__ = __name__ + setattr(this_module, class_name, new_error_class) + NVMLError._valClassMapping[err_val] = new_error_class +_extractNVMLErrorsAsClasses() + +def _nvmlCheckReturn(ret): + if (ret != NVML_SUCCESS): + raise NVMLError(ret) + return ret + +## Function access ## +_nvmlGetFunctionPointer_cache = dict() # function pointers are cached to prevent unnecessary libLoadLock locking +def _nvmlGetFunctionPointer(name): + global nvmlLib + + if name in _nvmlGetFunctionPointer_cache: + return _nvmlGetFunctionPointer_cache[name] + + libLoadLock.acquire() + try: + # ensure library was loaded + if (nvmlLib == None): + raise NVMLError(NVML_ERROR_UNINITIALIZED) + try: + _nvmlGetFunctionPointer_cache[name] = getattr(nvmlLib, name) + return _nvmlGetFunctionPointer_cache[name] + except AttributeError: + raise NVMLError(NVML_ERROR_FUNCTION_NOT_FOUND) + finally: + # lock is always freed + libLoadLock.release() + +## Alternative object +# Allows the object to be printed +# Allows mismatched types to be assigned +# - like None when the Structure variant requires c_uint +class nvmlFriendlyObject(object): + def __init__(self, dictionary): + for x in dictionary: + setattr(self, x, dictionary[x]) + def __str__(self): + return self.__dict__.__str__() + +def nvmlStructToFriendlyObject(struct): + d = {} + for x in struct._fields_: + key = x[0] + value = getattr(struct, key) + # only need to convert from bytes if bytes, no need to check python version. + d[key] = value.decode() if isinstance(value, bytes) else value + obj = nvmlFriendlyObject(d) + return obj + +# pack the object so it can be passed to the NVML library +def nvmlFriendlyObjectToStruct(obj, model): + for x in model._fields_: + key = x[0] + value = obj.__dict__[key] + # any c_char_p in python3 needs to be bytes, default encoding works fine. + if sys.version_info >= (3,): + setattr(model, key, value.encode()) + else: + setattr(model, key, value) + return model + +## Unit structures +class struct_c_nvmlUnit_t(Structure): + pass # opaque handle +c_nvmlUnit_t = POINTER(struct_c_nvmlUnit_t) + +class _PrintableStructure(Structure): + """ + Abstract class that produces nicer __str__ output than ctypes.Structure. + e.g. instead of: + >>> print str(obj) + + this class will print + class_name(field_name: formatted_value, field_name: formatted_value) + + _fmt_ dictionary of -> + e.g. class that has _field_ 'hex_value', c_uint could be formatted with + _fmt_ = {"hex_value" : "%08X"} + to produce nicer output. + Default fomratting string for all fields can be set with key "" like: + _fmt_ = {"" : "%d MHz"} # e.g all values are numbers in MHz. + If not set it's assumed to be just "%s" + + Exact format of returned str from this class is subject to change in the future. + """ + _fmt_ = {} + def __str__(self): + result = [] + for x in self._fields_: + key = x[0] + value = getattr(self, key) + fmt = "%s" + if key in self._fmt_: + fmt = self._fmt_[key] + elif "" in self._fmt_: + fmt = self._fmt_[""] + result.append(("%s: " + fmt) % (key, value)) + return self.__class__.__name__ + "(" + ", ".join(result) + ")" + + def __getattribute__(self, name): + res = super(_PrintableStructure, self).__getattribute__(name) + # need to convert bytes to unicode for python3 don't need to for python2 + # Python 2 strings are of both str and bytes + # Python 3 strings are not of type bytes + # ctypes should convert everything to the correct values otherwise + if isinstance(res, bytes): + if isinstance(res, str): + return res + return res.decode() + return res + + def __setattr__(self, name, value): + if isinstance(value, str): + # encoding a python2 string returns the same value, since python2 strings are bytes already + # bytes passed in python3 will be ignored. + value = value.encode() + super(_PrintableStructure, self).__setattr__(name, value) + +class c_nvmlUnitInfo_t(_PrintableStructure): + _fields_ = [ + ('name', c_char * 96), + ('id', c_char * 96), + ('serial', c_char * 96), + ('firmwareVersion', c_char * 96), + ] + +class c_nvmlC2cModeInfo_v1_t(_PrintableStructure): + _fields_ = [ + ('isC2cEnabled', c_uint) + ] + +nvmlC2cModeInfo_v1 = 0x1000008; + +class c_nvmlLedState_t(_PrintableStructure): + _fields_ = [ + ('cause', c_char * 256), + ('color', _nvmlLedColor_t), + ] + +class c_nvmlPSUInfo_t(_PrintableStructure): + _fields_ = [ + ('state', c_char * 256), + ('current', c_uint), + ('voltage', c_uint), + ('power', c_uint), + ] + +class c_nvmlUnitFanInfo_t(_PrintableStructure): + _fields_ = [ + ('speed', c_uint), + ('state', _nvmlFanState_t), + ] + +class c_nvmlUnitFanSpeeds_t(_PrintableStructure): + _fields_ = [ + ('fans', c_nvmlUnitFanInfo_t * 24), + ('count', c_uint) + ] + +## Device structures +class struct_c_nvmlDevice_t(Structure): + pass # opaque handle +c_nvmlDevice_t = POINTER(struct_c_nvmlDevice_t) + +class nvmlPciInfoExt_v1_t(_PrintableStructure): + _fields_ = [ + ('version', c_uint), + ('domain', c_uint), + ('bus', c_uint), + ('device', c_uint), + ('pciDeviceId', c_uint), + ('pciSubSystemId', c_uint), + ('baseClass', c_uint), + ('subClass', c_uint), + ('busId', c_char * NVML_DEVICE_PCI_BUS_ID_BUFFER_SIZE), + ] + _fmt_ = { + 'version' : "0x%04X", + 'domain' : "0x%04X", + 'bus' : "0x%02X", + 'device' : "0x%02X", + 'pciDeviceId' : "0x%08X", + 'pciSubSystemId' : "0x%08X", + 'baseClass' : "0x%01X", + 'subClass' : "0x%01X", + } + +nvmlPciInfoExt_v1 = 0x1000040 + +# Legacy pciInfo used for _v1 and _v2 +class nvmlPciInfo_v2_t(_PrintableStructure): + _fields_ = [ + ('busId', c_char * NVML_DEVICE_PCI_BUS_ID_BUFFER_V2_SIZE), + ('domain', c_uint), + ('bus', c_uint), + ('device', c_uint), + ('pciDeviceId', c_uint), + + # Added in 2.285 + ('pciSubSystemId', c_uint), + ('reserved0', c_uint), + ('reserved1', c_uint), + ('reserved2', c_uint), + ('reserved3', c_uint), + ] + _fmt_ = { + 'domain' : "0x%04X", + 'bus' : "0x%02X", + 'device' : "0x%02X", + 'pciDeviceId' : "0x%08X", + 'pciSubSystemId' : "0x%08X", + } + +class nvmlPciInfo_t(_PrintableStructure): + _fields_ = [ + # Moved to the new busId location below + ('busIdLegacy', c_char * NVML_DEVICE_PCI_BUS_ID_BUFFER_V2_SIZE), + ('domain', c_uint), + ('bus', c_uint), + ('device', c_uint), + ('pciDeviceId', c_uint), + + # Added in 2.285 + ('pciSubSystemId', c_uint), + # New busId replaced the long deprecated and reserved fields with a + # field of the same size in 9.0 + ('busId', c_char * NVML_DEVICE_PCI_BUS_ID_BUFFER_SIZE), + ] + _fmt_ = { + 'domain' : "0x%08X", + 'bus' : "0x%02X", + 'device' : "0x%02X", + 'pciDeviceId' : "0x%08X", + 'pciSubSystemId' : "0x%08X", + } + +class c_nvmlSystemDriverBranchInfo_v1_t(_PrintableStructure): + _fields_ = [ + ('version', c_uint), + ("branch", c_char * NVML_SYSTEM_DRIVER_VERSION_BUFFER_SIZE), + ] + +SystemDriverBranchInfo_v1 = 0x1000054 + +class c_nvmlExcludedDeviceInfo_t(_PrintableStructure): + _fields_ = [ + ('pci', nvmlPciInfo_t), + ('uuid', c_char * NVML_DEVICE_UUID_BUFFER_SIZE) + ] + +NVML_CPER_ACCESS_TYPE_GPU = 1 +NVML_CPER_CURSOR_HANDLE_INIT = 0 + +class c_nvmlCPERCursor_v1_t(_PrintableStructure): + _fields_ = [ + ("cperTypeMask", c_uint), + ("uuid", c_char * NVML_DEVICE_UUID_BUFFER_SIZE), + ("handle", c_ulonglong), + ] + +class c_nvmlGetCPER_v1_t(_PrintableStructure): + _fields_ = [ + ("cursor", c_nvmlCPERCursor_v1_t), + ("buffer", POINTER(c_ubyte)), + ("bufferSize", c_uint), + ] + +class nvmlNvLinkUtilizationControl_t(_PrintableStructure): + _fields_ = [ + ('units', _nvmlNvLinkUtilizationCountUnits_t), + ('pktfilter', _nvmlNvLinkUtilizationCountPktTypes_t), + ] + +class c_nvmlMemory_t(_PrintableStructure): + _fields_ = [ + ('total', c_ulonglong), + ('free', c_ulonglong), + ('used', c_ulonglong), + ] + _fmt_ = {'': "%d B"} + +class c_nvmlMemory_v2_t(_PrintableStructure): + _fields_ = [ + ('version', c_uint), + ('total', c_ulonglong), + ('reserved', c_ulonglong), + ('free', c_ulonglong), + ('used', c_ulonglong), + ] + _fmt_ = {'': "%d B"} + +nvmlMemory_v2 = 0x02000028 + +class c_nvmlBAR1Memory_t(_PrintableStructure): + _fields_ = [ + ('bar1Total', c_ulonglong), + ('bar1Free', c_ulonglong), + ('bar1Used', c_ulonglong), + ] + _fmt_ = {'': "%d B"} + +class nvmlClkMonFaultInfo_t(Structure): + _fields_ = [("clkApiDomain", c_uint), + ("clkDomainFaultMask", c_uint) + ] + +MAX_CLK_DOMAINS = 32 + +class nvmlClkMonStatus_t(Structure): + _fields_ = [("bGlobalStatus", c_uint), + ("clkMonListSize", c_uint), + ("clkMonList", nvmlClkMonFaultInfo_t * MAX_CLK_DOMAINS) + ] + +# On Windows with the WDDM driver, usedGpuMemory is reported as None +# Code that processes this structure should check for None, I.E. +# +# if (info.usedGpuMemory == None): +# # TODO handle the error +# pass +# else: +# print("Using %d MiB of memory" % (info.usedGpuMemory / 1024 / 1024)) +# endif +# +# See NVML documentation for more information +class c_nvmlProcessInfo_v2_t(_PrintableStructure): + _fields_ = [ + ('pid', c_uint), + ('usedGpuMemory', c_ulonglong), + ('gpuInstanceId', c_uint), + ('computeInstanceId', c_uint), + ] + _fmt_ = {'usedGpuMemory': "%d B"} + +c_nvmlProcessInfo_v3_t = c_nvmlProcessInfo_v2_t + +c_nvmlProcessInfo_t = c_nvmlProcessInfo_v3_t + +_nvmlProcessMode_t = c_uint +NVML_PROCESS_MODE_COMPUTE = 0 +NVML_PROCESS_MODE_GRAPHICS = 1 +NVML_PROCESS_MODE_MPS = 2 +NVML_PROCESS_MODE_ALL = 3 +NVML_PROCESS_MODE_MAX = 4 + +class c_nvmlProcessDetail_v1_t(Structure): + _fields_ = [ + ('pid', c_uint), + ('usedGpuMemory', c_ulonglong), + ('gpuInstanceId', c_uint), + ('computeInstanceId', c_uint), + ('usedGpuCcProtectedMemory', c_ulonglong), + ] + +class c_nvmlProcessDetailList_v1_t(_PrintableStructure): + _fields_ = [ + ('version', c_uint), + ('mode', _nvmlProcessMode_t), + ('numProcArrayEntries', c_uint), + ('procArray', POINTER(c_nvmlProcessDetail_v1_t)), + ] + _fmt_ = {'numProcArrayEntries': "%d B"} + +c_nvmlProcessDetailList_t = c_nvmlProcessDetailList_v1_t + +nvmlProcessDetailList_v1 = 0x1000018 + +class c_nvmlBridgeChipInfo_t(_PrintableStructure): + _fields_ = [ + ('type', _nvmlBridgeChipType_t), + ('fwVersion', c_uint), + ] + +class c_nvmlBridgeChipHierarchy_t(_PrintableStructure): + _fields_ = [ + ('bridgeCount', c_uint), + ('bridgeChipInfo', c_nvmlBridgeChipInfo_t * 128), + ] + +class c_nvmlEccErrorCounts_t(_PrintableStructure): + _fields_ = [ + ('l1Cache', c_ulonglong), + ('l2Cache', c_ulonglong), + ('deviceMemory', c_ulonglong), + ('registerFile', c_ulonglong), + ] + +class c_nvmlUtilization_t(_PrintableStructure): + _fields_ = [ + ('gpu', c_uint), + ('memory', c_uint), + ] + _fmt_ = {'': "%d %%"} + +# Added in 2.285 +class c_nvmlHwbcEntry_t(_PrintableStructure): + _fields_ = [ + ('hwbcId', c_uint), + ('firmwareVersion', c_char * 32), + ] + +class c_nvmlValue_t(Union): + _fields_ = [ + ('dVal', c_double), + ('uiVal', c_uint), + ('ulVal', c_ulong), + ('ullVal', c_ulonglong), + ('sllVal', c_longlong), + ('siVal', c_int), + ('usVal', c_ushort), + ] + +class c_nvmlSample_t(_PrintableStructure): + _fields_ = [ + ('timeStamp', c_ulonglong), + ('sampleValue', c_nvmlValue_t), + ] + +class c_nvmlViolationTime_t(_PrintableStructure): + _fields_ = [ + ('referenceTime', c_ulonglong), + ('violationTime', c_ulonglong), + ] + +class c_nvmlFieldValue_t(_PrintableStructure): + _fields_ = [ + ('fieldId', c_uint32), + ('scopeId', c_uint32), + ('timestamp', c_int64), + ('latencyUsec', c_int64), + ('valueType', _nvmlValueType_t), + ('nvmlReturn', _nvmlReturn_t), + ('value', c_nvmlValue_t) + ] + +NVML_NVLINK_TOTAL_SUPPORTED_BW_MODES = 23 + +nvmlNvlinkSupportedBwModes_v1 = 0x100001c +class c_nvmlNvlinkSupportedBwModes_v1_t(_PrintableStructure): + _fields_ = [ + ('version', c_uint), + ('bwModes', c_uint8 * NVML_NVLINK_TOTAL_SUPPORTED_BW_MODES), + ('totalBwModes', c_uint8) + ] + + def __init__(self): + super(c_nvmlNvlinkSupportedBwModes_v1_t, self).__init__(version=nvmlNvlinkSupportedBwModes_v1) + +nvmlNvlinkGetBwMode_v1 = 0x100000c +class c_nvmlNvlinkGetBwMode_v1_t(_PrintableStructure): + _fields_ = [ + ('version', c_uint), + ('bIsBest', c_uint), + ('bwMode', c_uint8) + ] + + def __init__(self): + super(c_nvmlNvlinkGetBwMode_v1_t, self).__init__(version=nvmlNvlinkGetBwMode_v1) + +nvmlNvlinkSetBwMode_v1 = 0x100000c +class c_nvmlNvlinkSetBwMode_v1_t(_PrintableStructure): + _fields_ = [ + ('version', c_uint), + ('bSetBest', c_uint), + ('bwMode', c_uint8) + ] + + def __init__(self): + super(c_nvmlNvlinkSetBwMode_v1_t, self).__init__(version=nvmlNvlinkSetBwMode_v1) + +class c_nvmlVgpuHeterogeneousMode_v1_t(_PrintableStructure): + _fields_ = [ + ('version', c_uint), + ('mode', c_uint), + ] + +VgpuHeterogeneousMode_v1 = 0x1000008 + +class c_nvmlVgpuPlacementId_v1_t(_PrintableStructure): + _fields_ = [ + ('version', c_uint), + ('placementId', c_uint), + ] + +VgpuPlacementId_v1 = 0x1000008 + +class c_nvmlVgpuPlacementList_v1_t(_PrintableStructure): + _fields_ = [ + ('version', c_uint), + ('count', c_uint), + ('placementSize', c_uint), + ('placementIds', POINTER(c_uint)), + ] + +VgpuPlacementList_v1 = 0x1000018 + +NVML_VGPU_PGPU_HETEROGENEOUS_MODE = 0 +NVML_VGPU_PGPU_HOMOGENEOUS_MODE = 1 + +class c_nvmlVgpuPlacementList_v2_t(_PrintableStructure): + _fields_ = [ + ('version', c_uint), + ('placementSize', c_uint), + ('count', c_uint), + ('placementIds', POINTER(c_uint)), + ('mode', c_uint), + ] + +VgpuPlacementList_v2 = 0x2000020 + +class c_nvmlVgpuTypeBar1Info_v1_t(_PrintableStructure): + _fields_ = [ + ('version', c_uint), + ('bar1Size', c_ulonglong), + ] + +VgpuTypeBar1Info_v1 = 0x1000010 + +class c_nvmlVgpuInstanceUtilizationSample_t(_PrintableStructure): + _fields_ = [ + ('vgpuInstance', _nvmlVgpuInstance_t), + ('timeStamp', c_ulonglong), + ('smUtil', c_nvmlValue_t), + ('memUtil', c_nvmlValue_t), + ('encUtil', c_nvmlValue_t), + ('decUtil', c_nvmlValue_t), + ] + +class c_nvmlVgpuInstanceUtilizationInfo_v1_t(_PrintableStructure): + _fields_ = [ + ('timeStamp', c_ulonglong), + ('vgpuInstance', _nvmlVgpuInstance_t), + ('smUtil', c_nvmlValue_t), + ('memUtil', c_nvmlValue_t), + ('encUtil', c_nvmlValue_t), + ('decUtil', c_nvmlValue_t), + ('jpgUtil', c_nvmlValue_t), + ('ofaUtil', c_nvmlValue_t), + ] + +class c_nvmlVgpuInstancesUtilizationInfo_v1_t(_PrintableStructure): + _fields_ = [ + ('version', c_uint), + ('sampleValType', _nvmlValueType_t), + ('vgpuInstanceCount', c_uint), + ('lastSeenTimeStamp', c_ulonglong), + ('vgpuUtilArray', POINTER(c_nvmlVgpuInstanceUtilizationInfo_v1_t)), + ] + +VgpuInstancesUtilizationInfo_v1 = 0x01000020 + +class c_nvmlVgpuProcessUtilizationSample_t(_PrintableStructure): + _fields_ = [ + ('vgpuInstance', _nvmlVgpuInstance_t), + ('pid', c_uint), + ('processName', c_char * NVML_VGPU_NAME_BUFFER_SIZE), + ('timeStamp', c_ulonglong), + ('smUtil', c_uint), + ('memUtil', c_uint), + ('encUtil', c_uint), + ('decUtil', c_uint), + ] + +class c_nvmlVgpuProcessUtilizationInfo_v1_t(_PrintableStructure): + _fields_ = [ + ('processName', c_char * NVML_VGPU_NAME_BUFFER_SIZE), + ('timeStamp', c_ulonglong), + ('vgpuInstance', _nvmlVgpuInstance_t), + ('pid', c_uint), + ('smUtil', c_uint), + ('memUtil', c_uint), + ('encUtil', c_uint), + ('decUtil', c_uint), + ('jpgUtil', c_uint), + ('ofaUtil', c_uint), + ] + +class c_nvmlVgpuProcessesUtilizationInfo_v1_t(_PrintableStructure): + _fields_ = [ + ('version', c_uint), + ('vgpuProcessCount', c_uint), + ('lastSeenTimeStamp', c_ulonglong), + ('vgpuProcUtilArray', POINTER(c_nvmlVgpuProcessUtilizationInfo_v1_t)), + ] + +VgpuProcessesUtilizationInfo_v1 = 0x01000018 + +class nvmlVgpuRuntimeState_v1_t(_PrintableStructure): + _fields_ = [ + ('version', c_uint), + ('size', c_ulonglong), + ] + +VgpuRuntimeState_v1 = 0x1000010 + +class c_nvmlVgpuLicenseExpiry_t(_PrintableStructure): + _fields_ = [ + ('year', c_uint32), + ('month', c_uint16), + ('day', c_uint16), + ('hour', c_uint16), + ('min', c_uint16), + ('sec', c_uint16), + ('status', c_uint8), + ] + +NVML_GRID_LICENSE_STATE_UNKNOWN = 0 +NVML_GRID_LICENSE_STATE_UNINITIALIZED = 1 +NVML_GRID_LICENSE_STATE_UNLICENSED_UNRESTRICTED = 2 +NVML_GRID_LICENSE_STATE_UNLICENSED_RESTRICTED = 3 +NVML_GRID_LICENSE_STATE_UNLICENSED = 4 +NVML_GRID_LICENSE_STATE_LICENSED = 5 + +class c_nvmlVgpuLicenseInfo_t(_PrintableStructure): + _fields_ = [ + ('isLicensed', c_uint8), + ('licenseExpiry', c_nvmlVgpuLicenseExpiry_t), + ('currentState', c_uint), + ] + +class c_nvmlEncoderSession_t(_PrintableStructure): + _fields_ = [ + ('sessionId', c_uint), + ('pid', c_uint), + ('vgpuInstance', _nvmlVgpuInstance_t), + ('codecType', c_uint), + ('hResolution', c_uint), + ('vResolution', c_uint), + ('averageFps', c_uint), + ('encodeLatency', c_uint), + ] + +class c_nvmlProcessUtilizationSample_t(_PrintableStructure): + _fields_ = [ + ('pid', c_uint), + ('timeStamp', c_ulonglong), + ('smUtil', c_uint), + ('memUtil', c_uint), + ('encUtil', c_uint), + ('decUtil', c_uint), + ] + +class c_nvmlProcessUtilizationInfo_v1_t(_PrintableStructure): + _fields_ = [ + ('timeStamp', c_ulonglong), + ('pid', c_uint), + ('smUtil', c_uint), + ('memUtil', c_uint), + ('encUtil', c_uint), + ('decUtil', c_uint), + ('jpgUtil', c_uint), + ('ofaUtil', c_uint), + ] + +class c_nvmlProcessesUtilizationInfo_v1_t(_PrintableStructure): + _fields_ = [ + ('version', c_uint), + ('processSamplesCount', c_uint), + ('lastSeenTimeStamp', c_ulonglong), + ('procUtilArray', POINTER(c_nvmlProcessUtilizationInfo_v1_t)), + ] + +ProcessesUtilizationInfo_v1 = 0x01000018 + +class c_nvmlGridLicenseExpiry_t(_PrintableStructure): + _fields_ = [ + ('year', c_uint32), + ('month', c_uint16), + ('day', c_uint16), + ('hour', c_uint16), + ('min', c_uint16), + ('sec', c_uint16), + ('status', c_uint8), + ] + +class c_nvmlGridLicensableFeature_v4_t(_PrintableStructure): + _fields_ = [ + ('featureCode', _nvmlGridLicenseFeatureCode_t), + ('featureState', c_uint), + ('licenseInfo', c_char * NVML_GRID_LICENSE_BUFFER_SIZE), + ('productName', c_char * NVML_GRID_LICENSE_BUFFER_SIZE), + ('featureEnabled', c_uint), + ('licenseExpiry', c_nvmlGridLicenseExpiry_t), + ] + +class c_nvmlGridLicensableFeatures_v4_t(_PrintableStructure): + _fields_ = [ + ('isGridLicenseSupported', c_int), + ('licensableFeaturesCount', c_uint), + ('gridLicensableFeatures', c_nvmlGridLicensableFeature_v4_t * NVML_GRID_LICENSE_FEATURE_MAX_COUNT), + ] + +class c_nvmlGridLicensableFeature_v3_t(_PrintableStructure): + _fields_ = [ + ('featureCode', _nvmlGridLicenseFeatureCode_t), + ('featureState', c_uint), + ('licenseInfo', c_char * NVML_GRID_LICENSE_BUFFER_SIZE), + ('productName', c_char * NVML_GRID_LICENSE_BUFFER_SIZE), + ('featureEnabled', c_uint), + ] + +class c_nvmlGridLicensableFeatures_v3_t(_PrintableStructure): + _fields_ = [ + ('isGridLicenseSupported', c_int), + ('licensableFeaturesCount', c_uint), + ('gridLicensableFeatures', c_nvmlGridLicensableFeature_v3_t * NVML_GRID_LICENSE_FEATURE_MAX_COUNT), + ] + +class c_nvmlGridLicensableFeature_v2_t(_PrintableStructure): + _fields_ = [ + ('featureCode', _nvmlGridLicenseFeatureCode_t), + ('featureState', c_uint), + ('licenseInfo', c_char * NVML_GRID_LICENSE_BUFFER_SIZE), + ('productName', c_char * NVML_GRID_LICENSE_BUFFER_SIZE), + ] + +class c_nvmlGridLicensableFeatures_v2_t(_PrintableStructure): + _fields_ = [ + ('isGridLicenseSupported', c_int), + ('licensableFeaturesCount', c_uint), + ('gridLicensableFeatures', c_nvmlGridLicensableFeature_v2_t * NVML_GRID_LICENSE_FEATURE_MAX_COUNT), + ] + +class c_nvmlGridLicensableFeature_t(_PrintableStructure): + _fields_ = [ + ('featureCode', _nvmlGridLicenseFeatureCode_t), + ('featureState', c_uint), + ('licenseInfo', c_char * NVML_GRID_LICENSE_BUFFER_SIZE), + ] + +class c_nvmlGridLicensableFeatures_t(_PrintableStructure): + _fields_ = [ + ('isGridLicenseSupported', c_int), + ('licensableFeaturesCount', c_uint), + ('gridLicensableFeatures', c_nvmlGridLicensableFeature_t * NVML_GRID_LICENSE_FEATURE_MAX_COUNT), + ] + +class c_nvmlMarginTemperature_v1_t(_PrintableStructure): + _fields_ = [ + ('version', c_uint), + ('marginTemperature', c_int), + ] + +nvmlMarginTemperature_v1 = 0x1000008 + +NVML_DEVICE_UUID_ASCII_LEN = 41 +NVML_DEVICE_UUID_BINARY_LEN = 16 + +NVML_UUID_TYPE_NONE = 0 +NVML_UUID_TYPE_ASCII = 1 +NVML_UUID_TYPE_BINARY = 2 + +class c_nvmlUUIDValue_t(Union): + _fields_ = [ + ('str', c_char * NVML_DEVICE_UUID_ASCII_LEN), + ('bytes', c_ubyte * NVML_DEVICE_UUID_BINARY_LEN), + ] + +nvmlUUID_v1 = 0x1000034 +class c_nvmlUUID_t(_PrintableStructure): + _fields_ = [ + ('version', c_uint), + ('type', c_uint), + ('value', c_nvmlUUIDValue_t), + ] + + def __init__(self): + super(c_nvmlUUID_t, self).__init__(version=nvmlUUID_v1) + +nvmlPdi_v1 = 0x1000010 +class c_nvmlPdi_t(_PrintableStructure): + _fields_ = [ + ('version', c_uint), + ('value', c_ulonglong), + ] + + def __init__(self): + super(c_nvmlPdi_t, self).__init__(version=nvmlPdi_v1) + +nvmlRepairStatus_v1 = 0x100000C +class c_nvmlRepairStatus_t(_PrintableStructure): + _fields_ = [ + ("version", c_uint), + ("bChannelRepairPending", c_uint), + ("bTpcRepairPending", c_uint), + ] + + def __init__(self): + super(c_nvmlRepairStatus_t, self).__init__(version=nvmlRepairStatus_v1) + +nvmlNvLinkInfo_v1 =0x1000008 +class c_nvmlNvLinkInfo_v1_t(_PrintableStructure): + _fields_ = [ + ("version", c_uint), + ("isNvleEnabled", c_uint), + ] + + def __init__(self): + super(c_nvmlNvLinkInfo_v1_t, self).__init__(version=nvmlNvLinkInfo_v1) + +NVML_NVLINK_FIRMWARE_UCODE_TYPE_MSE = 0x1 +NVML_NVLINK_FIRMWARE_UCODE_TYPE_NETIR = 0x2 +NVML_NVLINK_FIRMWARE_UCODE_TYPE_NETIR_UPHY = 0x3 +NVML_NVLINK_FIRMWARE_UCODE_TYPE_NETIR_CLN = 0x4 +NVML_NVLINK_FIRMWARE_UCODE_TYPE_NETIR_DLN = 0x5 +NVML_NVLINK_FIRMWARE_VERSION_LENGTH = 100 + +class c_nvmlNvlinkFirmwareVersion_t(_PrintableStructure): + _fields_ = [ + ("ucodeType", c_uint8), + ("major", c_uint), + ("minor", c_uint), + ("subMinor", c_uint) + ] + +class c_nvmlNvlinkFirmwareInfo_t(_PrintableStructure): + _fields_ = [ + ("firmwareVersion", c_nvmlNvlinkFirmwareVersion_t * NVML_NVLINK_FIRMWARE_VERSION_LENGTH), + ("numValidEntries", c_uint) + ] + +nvmlNvLinkInfo_v2 = 0x200064c +class c_nvmlNvLinkInfo_v2_t(_PrintableStructure): + _fields_ = [ + ("version", c_uint), + ("isNvleEnabled", c_uint), + ("firmwareInfo", c_nvmlNvlinkFirmwareInfo_t) + ] + + def __init__(self): + super(c_nvmlNvLinkInfo_v2_t, self).__init__(version=nvmlNvLinkInfo_v2) + + +NVML_PRM_DATA_MAX_SIZE = 496 +class c_nvmlPRMTLV_v1_t(_PrintableStructure): + _fields_ = [ + ('dataSize', c_uint32), + ('status', c_uint32), + ('data', c_ubyte * NVML_PRM_DATA_MAX_SIZE), + ] + def __init__(self, size=0): + super(c_nvmlPRMTLV_v1_t, self).__init__(dataSize=size, status=0) + +def nvmlDeviceReadWritePRM_v1(handle, c_info): + fn = _nvmlGetFunctionPointer("nvmlDeviceReadWritePRM_v1") + ret = fn(handle, byref(c_info)) + _nvmlCheckReturn(ret) + + +# Addressing modes +NVML_DEVICE_ADDRESSING_MODE_NONE = 0 +NVML_DEVICE_ADDRESSING_MODE_HMM = 1 +NVML_DEVICE_ADDRESSING_MODE_ATS = 2 + +nvmlDeviceAddressingMode_v1 = 0x1000008 +class c_nvmlDeviceAddressingMode_t(_PrintableStructure): + _fields_ = [ + ('version', c_uint), + ('value', c_uint), + ] + + def __init__(self): + super(c_nvmlDeviceAddressingMode_t, self).__init__(version=nvmlDeviceAddressingMode_v1) + +nvmlUnrepairableMemory_v1 = 0x1000008 +class c_nvmlUnrepairableMemory_v1_t(_PrintableStructure): + _fields_ = [ + ('version', c_uint), + ('unrepairableMemory', c_uint), + ] + def __init__(self): + super(c_nvmlUnrepairableMemory_v1_t, self).__init__(version=nvmlUnrepairableMemory_v1) + +#PRM Counter IDs +NVML_PRM_COUNTER_ID_NONE = 0 +# Physical Layer Counters (PPCNT group 0x12) +NVML_PRM_COUNTER_ID_PPCNT_PHYSICAL_LAYER_CTRS_LINK_DOWN_EVENTS = 1 +NVML_PRM_COUNTER_ID_PPCNT_PHYSICAL_LAYER_CTRS_SUCCESSFUL_RECOVERY_EVENTS = 2 +# Recovery counters (PPCNT group 0x1A) +NVML_PRM_COUNTER_ID_PPCNT_RECOVERY_CTRS_TOTAL_SUCCESSFUL_RECOVERY_EVENTS = 101 +NVML_PRM_COUNTER_ID_PPCNT_RECOVERY_CTRS_TIME_SINCE_LAST_RECOVERY = 102 +NVML_PRM_COUNTER_ID_PPCNT_RECOVERY_CTRS_TIME_BETWEEN_LAST_TWO_RECOVERIES = 103 +# Infiniband PortCounters Attribute (PPCNT group 0x20) +NVML_PRM_COUNTER_ID_PPCNT_PORTCOUNTERS_PORT_XMIT_WAIT = 201 +# PLR counters (PPCNT group 0x22) +NVML_PRM_COUNTER_ID_PPCNT_PLR_RCV_CODES = 301 +NVML_PRM_COUNTER_ID_PPCNT_PLR_RCV_CODE_ERR = 302 +NVML_PRM_COUNTER_ID_PPCNT_PLR_RCV_UNCORRECTABLE_CODE = 303 +NVML_PRM_COUNTER_ID_PPCNT_PLR_XMIT_CODES = 304 +NVML_PRM_COUNTER_ID_PPCNT_PLR_XMIT_RETRY_CODES = 305 +NVML_PRM_COUNTER_ID_PPCNT_PLR_XMIT_RETRY_EVENTS = 306 +NVML_PRM_COUNTER_ID_PPCNT_PLR_SYNC_EVENTS = 307 +# PPRM counters +NVML_PRM_COUNTER_ID_PPRM_OPER_RECOVERY = 1001 + +class c_nvmlPRMCounterInput_v1_t(_PrintableStructure): + _fields_ = [ + ('localPort', c_uint32), + ] + def __init__(self, port=0): + super(c_nvmlPRMCounterInput_v1_t, self).__init__(localPort=port) + +class c_nvmlPRMCounterValue_v1_t(_PrintableStructure): + _fields_ = [ + ('status', _nvmlReturn_t), + ('outputType', _nvmlValueType_t), + ('outputValue', c_nvmlValue_t) + ] + def __init__(self): + super(c_nvmlPRMCounterValue_v1_t, self).__init__(status=pynvml.NVML_SUCCESS) + +class c_nvmlPRMCounter_v1_t(_PrintableStructure): + _fields_ = [ + ('counterId', c_uint32), + ('inputValue', c_nvmlPRMCounterInput_v1_t), + ('outputValue', c_nvmlPRMCounterValue_v1_t), + ] + def __init__(self, ctrId=NVML_PRM_COUNTER_ID_NONE, inData=None): + super(c_nvmlPRMCounter_v1_t, self).__init__(counterId=ctrId, inputValue=inData) + +class c_nvmlPRMCounterList_v1_t(_PrintableStructure): + _fields_ = [ + ('numCounters', c_uint32), + ('counters', POINTER(c_nvmlPRMCounter_v1_t)), + ] + def __init__(self, num, ctrs=None): + super(c_nvmlPRMCounterList_v1_t, self).__init__(numCounters=num, counters=ctrs) + +def nvmlDeviceReadPRMCounters_v1(handle, c_info): + fn = _nvmlGetFunctionPointer("nvmlDeviceReadPRMCounters_v1") + ret = fn(handle, byref(c_info)) + _nvmlCheckReturn(ret) + +class c_nvmlBBXTimeData_v1_t(_PrintableStructure): + _fields_ = [ + ('timeRun', c_uint), + ] + _fmt_ = {'timeRun': "%d seconds"} + +def nvmlDeviceGetBBXTimeData_v1(handle): + c_timeData = c_nvmlBBXTimeData_v1_t() + fn = _nvmlGetFunctionPointer("nvmlDeviceGetBBXTimeData_v1") + ret = fn(handle, byref(c_timeData)) + _nvmlCheckReturn(ret) + return c_timeData + +## Event structures +class struct_c_nvmlEventSet_t(Structure): + pass # opaque handle +c_nvmlEventSet_t = POINTER(struct_c_nvmlEventSet_t) + +nvmlEventTypeSingleBitEccError = 0x0000000000000001 +nvmlEventTypeDoubleBitEccError = 0x0000000000000002 +nvmlEventTypePState = 0x0000000000000004 +nvmlEventTypeXidCriticalError = 0x0000000000000008 +nvmlEventTypeClock = 0x0000000000000010 +nvmlEventTypePowerSourceChange = 0x0000000000000080 +nvmlEventMigConfigChange = 0x0000000000000100 +nvmlEventTypeSingleBitEccErrorStorm = 0x0000000000000200 +nvmlEventTypeDramRetirementEvent = 0x0000000000000400 +nvmlEventTypeDramRetirementFailure = 0x0000000000000800 +nvmlEventTypeNonFatalPoisonError = 0x0000000000001000 +nvmlEventTypeFatalPoisonError = 0x0000000000002000 +nvmlEventTypeGpuUnavailableError = 0x0000000000004000 +nvmlEventTypeGpuRecoveryAction = 0x0000000000008000 +nvmlEventTypeNone = 0x0000000000000000 +nvmlEventTypeAll = ( + nvmlEventTypeNone + | nvmlEventTypeSingleBitEccError + | nvmlEventTypeDoubleBitEccError + | nvmlEventTypePState + | nvmlEventTypeClock + | nvmlEventTypePowerSourceChange + | nvmlEventTypeXidCriticalError + | nvmlEventMigConfigChange + | nvmlEventTypeSingleBitEccErrorStorm + | nvmlEventTypeDramRetirementEvent + | nvmlEventTypeDramRetirementFailure + | nvmlEventTypeNonFatalPoisonError + | nvmlEventTypeFatalPoisonError + | nvmlEventTypeGpuUnavailableError + | nvmlEventTypeGpuRecoveryAction + ) + +## Clock Event Reasons defines +nvmlClocksEventReasonGpuIdle = 0x0000000000000001 +nvmlClocksEventReasonApplicationsClocksSetting = 0x0000000000000002 +nvmlClocksEventReasonUserDefinedClocks = nvmlClocksEventReasonApplicationsClocksSetting # deprecated, use nvmlClocksEventReasonApplicationsClocksSetting +nvmlClocksEventReasonSwPowerCap = 0x0000000000000004 +nvmlClocksEventReasonHwSlowdown = 0x0000000000000008 +nvmlClocksEventReasonSyncBoost = 0x0000000000000010 +nvmlClocksEventReasonSwThermalSlowdown = 0x0000000000000020 +nvmlClocksEventReasonHwThermalSlowdown = 0x0000000000000040 +nvmlClocksEventReasonHwPowerBrakeSlowdown = 0x0000000000000080 +nvmlClocksEventReasonDisplayClockSetting = 0x0000000000000100 +nvmlClocksEventReasonNone = 0x0000000000000000 +nvmlClocksEventReasonAll = ( + nvmlClocksEventReasonNone | + nvmlClocksEventReasonGpuIdle | + nvmlClocksEventReasonApplicationsClocksSetting | + nvmlClocksEventReasonSwPowerCap | + nvmlClocksEventReasonHwSlowdown | + nvmlClocksEventReasonSyncBoost | + nvmlClocksEventReasonSwThermalSlowdown | + nvmlClocksEventReasonHwThermalSlowdown | + nvmlClocksEventReasonHwPowerBrakeSlowdown | + nvmlClocksEventReasonDisplayClockSetting + ) + +## Following have been deprecated +nvmlClocksThrottleReasonGpuIdle = 0x0000000000000001 +nvmlClocksThrottleReasonApplicationsClocksSetting = 0x0000000000000002 +nvmlClocksThrottleReasonUserDefinedClocks = nvmlClocksThrottleReasonApplicationsClocksSetting # deprecated, use nvmlClocksThrottleReasonApplicationsClocksSetting +nvmlClocksThrottleReasonSwPowerCap = 0x0000000000000004 +nvmlClocksThrottleReasonHwSlowdown = 0x0000000000000008 +nvmlClocksThrottleReasonSyncBoost = 0x0000000000000010 +nvmlClocksThrottleReasonSwThermalSlowdown = 0x0000000000000020 +nvmlClocksThrottleReasonHwThermalSlowdown = 0x0000000000000040 +nvmlClocksThrottleReasonHwPowerBrakeSlowdown = 0x0000000000000080 +nvmlClocksThrottleReasonDisplayClockSetting = 0x0000000000000100 +nvmlClocksThrottleReasonNone = 0x0000000000000000 +nvmlClocksThrottleReasonAll = ( + nvmlClocksThrottleReasonNone | + nvmlClocksThrottleReasonGpuIdle | + nvmlClocksThrottleReasonApplicationsClocksSetting | + nvmlClocksThrottleReasonSwPowerCap | + nvmlClocksThrottleReasonHwSlowdown | + nvmlClocksThrottleReasonSyncBoost | + nvmlClocksThrottleReasonSwThermalSlowdown | + nvmlClocksThrottleReasonHwThermalSlowdown | + nvmlClocksThrottleReasonHwPowerBrakeSlowdown | + nvmlClocksThrottleReasonDisplayClockSetting + ) + +class c_nvmlEventData_t(_PrintableStructure): + _fields_ = [ + ('device', c_nvmlDevice_t), + ('eventType', c_ulonglong), + ('eventData', c_ulonglong), + ('gpuInstanceId', c_uint), + ('computeInstanceId', c_uint) + ] + _fmt_ = {'eventType': "0x%08X"} + +class struct_c_nvmlSystemEventSet_t(Structure): + pass # opaque handle +c_nvmlSystemEventSet_t = POINTER(struct_c_nvmlSystemEventSet_t) + +nvmlSystemEventTypeGpuDriverUnbind = 0x0000000000000001 +nvmlSystemEventTypeGpuDriverBind = 0x0000000000000002 + +nvmlSystemEventTypeCount = 2 + +nvmlSystemEventSetCreateRequest_v1 = 0x1000010 +class c_nvmlSystemEventSetCreateRequest_v1_t(_PrintableStructure): + _fields_ = [ + ('version', c_uint), + ('set', c_nvmlSystemEventSet_t) + ] + + def __init__(self): + super(c_nvmlSystemEventSetCreateRequest_v1_t, self).__init__(version=nvmlSystemEventSetCreateRequest_v1) + +nvmlSystemEventSetFreeRequest_v1 = 0x1000010 +class c_nvmlSystemEventSetFreeRequest_v1_t(_PrintableStructure): + _fields_ = [ + ('version', c_uint), + ('set', c_nvmlSystemEventSet_t) + ] + + def __init__(self): + super(c_nvmlSystemEventSetFreeRequest_v1_t, self).__init__(version=nvmlSystemEventSetFreeRequest_v1) + +nvmlSystemRegisterEventRequest_v1 = 0x1000018 +class c_nvmlSystemRegisterEventRequest_v1_t(_PrintableStructure): + _fields_ = [ + ('version', c_uint), + ('eventTypes', c_ulonglong), + ('set', c_nvmlSystemEventSet_t) + ] + + def __init__(self): + super(c_nvmlSystemRegisterEventRequest_v1_t, self).__init__(version=nvmlSystemRegisterEventRequest_v1) + +class c_nvmlSystemEventData_v1_t(_PrintableStructure): + _fields_ = [ + ('eventType', c_ulonglong), + ('gpuId', c_uint) + ] + _fmt_ = {'eventType': "0x%08X"} + +nvmlSystemEventSetWaitRequest_v1 = 0x1000020 +class c_nvmlSystemEventSetWaitRequest_v1_t(_PrintableStructure): + _fields_ = [ + ('version', c_uint), # input/output + ('timeoutms', c_uint), # input + ('set', c_nvmlSystemEventSet_t), # input + ('data', POINTER(c_nvmlSystemEventData_v1_t)), # input/output. Buffer owned by caller + ('dataSize', c_uint), # input + ('numEvent', c_uint) # output. Number of event recorded + ] + + def __init__(self): + super(c_nvmlSystemEventSetWaitRequest_v1_t, self).__init__(version=nvmlSystemEventSetWaitRequest_v1) + +# C APIs for system events +def c_nvmlSystemEventSetCreate(req): + """ + C API binding for c_nvmlSystemEventSetFree + :param req: reference of c_nvmlSystemEventSetCreateRequest_v1_t + """ + fn = _nvmlGetFunctionPointer("nvmlSystemEventSetCreate") + ret = fn(req) + _nvmlCheckReturn(ret) + +def c_nvmlSystemEventSetFree(req): + """ + C API binding for c_nvmlSystemEventSetFree + :param req: reference of c_nvmlSystemEventSetFreeRequest_v1_t + """ + fn = _nvmlGetFunctionPointer("nvmlSystemEventSetFree") + ret = fn(req) + _nvmlCheckReturn(ret) + +def c_nvmlSystemRegisterEvents(req): + """ + C API binding for nvmlSystemRegisterEvents + :param req: reference of c_nvmlSystemRegisterEventRequest_v1_t + """ + fn = _nvmlGetFunctionPointer("nvmlSystemRegisterEvents") + ret = fn(req) + _nvmlCheckReturn(ret) + +def c_nvmlSystemEventSetWait(req): + """ + C API binding for nvmlSystemEventSetWait + :param req: reference of c_nvmlSystemEventSetWaitRequest_v1_t + """ + fn = _nvmlGetFunctionPointer("nvmlSystemEventSetWait") + ret = fn(req) + # Accept TIMEOUT error + if ret == NVML_ERROR_TIMEOUT: + return ret + _nvmlCheckReturn(ret) + +# Pythonic APIs for system events +# No Pythonic API compability support +# When user upgrades to a new NVML Python binding, +# user should upgrade their code against API change. +def nvmlSystemEventSetCreate(version): + """ + Create an NVML system event set. + :param version: The version of the request. + :return: A ctypes pointer to the created c_nvmlSystemEventSet_t structure. + """ + if version != nvmlSystemEventSetCreateRequest_v1: + raise NVMLError(NVML_ERROR_ARGUMENT_VERSION_MISMATCH) + + # Prepare the request structure + req = c_nvmlSystemEventSetCreateRequest_v1_t() + req.version = version + req.set = None # Initialize as NULL + + c_nvmlSystemEventSetCreate(byref(req)) + + # Return the created set handle + if not req.set: + raise NVMLError(NVML_ERROR_MEMORY) + return req.set + +def nvmlSystemEventSetFree(version, setHandle): + """ + Free an NVML system event set. + :param version: The version of the request. + :param setHandle: A ctypes pointer to a c_nvmlSystemEventSet_t structure. + """ + if version != nvmlSystemEventSetFreeRequest_v1: + raise NVMLError(NVML_ERROR_ARGUMENT_VERSION_MISMATCH) + + req = c_nvmlSystemEventSetFreeRequest_v1_t() + req.version = version + req.set = setHandle + + c_nvmlSystemEventSetFree(byref(req)) + + +def nvmlSystemRegisterEvents(version, eventTypes, setHandle): + """ + Register events for an NVML system event set. + :param version: The version of the request. + :param eventTypes: A bitmask of event types to register. + :param setHandle: A ctypes pointer to a c_nvmlSystemEventSet_t structure. + """ + if version != nvmlSystemRegisterEventRequest_v1: + raise NVMLError(NVML_ERROR_ARGUMENT_VERSION_MISMATCH) + + req = c_nvmlSystemRegisterEventRequest_v1_t() + req.version = version + req.eventTypes = eventTypes + req.set = setHandle + + c_nvmlSystemRegisterEvents(byref(req)) + + +def nvmlSystemEventSetWait(version, setHandle, timeoutMs, eventData, eventDataSize): + """ + Wait for events in an NVML system event set. + :param version: The version of the request. + :param setHandle: A ctypes pointer to a c_nvmlSystemEventSet_t structure. + :param timeoutMs: Timeout in milliseconds. + :param eventData: A ctypes array of c_nvmlSystemEventData_v1_t for event data. + :param eventDataSize: Number of c_nvmlSystemEventData_v1_t in evenData array.. + :return: A list of dictionaries containing event data. + """ + if version != nvmlSystemEventSetWaitRequest_v1: + raise NVMLError(NVML_ERROR_ARGUMENT_VERSION_MISMATCH) + + req = c_nvmlSystemEventSetWaitRequest_v1_t() + req.version = version + req.timeoutms = timeoutMs + req.set = setHandle + req.data = eventData + req.dataSize = eventDataSize + + ret = c_nvmlSystemEventSetWait(byref(req)) + if ret == NVML_ERROR_TIMEOUT: + return [] # Timeout, no events occurred. + + # Extract event data from the buffer + events = [] + for i in range(req.numEvent): + events.append({ + 'eventType': eventData[i].eventType, + 'gpuId': eventData[i].gpuId + }) + return events + +class c_nvmlAccountingStats_t(_PrintableStructure): + _fields_ = [ + ('gpuUtilization', c_uint), + ('memoryUtilization', c_uint), + ('maxMemoryUsage', c_ulonglong), + ('time', c_ulonglong), + ('startTime', c_ulonglong), + ('isRunning', c_uint), + ('reserved', c_uint * 5) + ] + +class c_nvmlAccountingStats_v2_t(_PrintableStructure): + _fields_ = [ + ('pid', c_uint), + ('isRunning', c_uint), + ('gpuUtilization', c_uint), + ('memoryUtilization', c_uint), + ('maxMemoryUsage', c_ulonglong), + ('sampleCount', c_uint), + ('sumGpuUtil', c_ulonglong), + ('sumFbUtil', c_ulonglong), + ('time', c_ulonglong), + ('startTime', c_ulonglong) + ] + +class c_nvmlVgpuVersion_t(Structure): + _fields_ = [("minVersion", c_uint), + ("maxVersion", c_uint) + ] + +class c_nvmlVgpuMetadata_t(_PrintableStructure): + _fields_ = [("version", c_uint), + ("revision", c_uint), + ("guestInfoState", _nvmlVgpuGuestInfoState_t), + ("guestDriverVersion", c_char * NVML_SYSTEM_DRIVER_VERSION_BUFFER_SIZE), + ("hostDriverVersion", c_char * NVML_SYSTEM_DRIVER_VERSION_BUFFER_SIZE), + ("reserved", c_uint * 6), + ("vgpuVirtualizationCaps", c_uint), + ("guestVgpuVersion", c_uint), + ("opaqueDataSize", c_uint), + ("opaqueData", c_char * NVML_VGPU_METADATA_OPAQUE_DATA_SIZE) + ] + +class c_nvmlVgpuPgpuMetadata_t(_PrintableStructure): + _fields_ = [("version", c_uint), + ("revision", c_uint), + ("hostDriverVersion", c_char * NVML_SYSTEM_DRIVER_VERSION_BUFFER_SIZE), + ("pgpuVirtualizationCaps", c_uint), + ("reserved", c_uint * 5), + ("hostSupportedVgpuRange", c_nvmlVgpuVersion_t), + ("opaqueDataSize", c_uint), + ("opaqueData", c_char * NVML_VGPU_PGPU_METADATA_OPAQUE_DATA_SIZE) + ] + +class c_nvmlVgpuPgpuCompatibility_t(Structure): + _fields_ = [("vgpuVmCompatibility", _nvmlVgpuVmCompatibility_t), + ("compatibilityLimitCode", _nvmlVgpuPgpuCompatibilityLimitCode_t) + ] + +## vGPU scheduler policy defines +NVML_VGPU_SCHEDULER_POLICY_UNKNOWN = 0 +NVML_VGPU_SCHEDULER_POLICY_BEST_EFFORT = 1 +NVML_VGPU_SCHEDULER_POLICY_EQUAL_SHARE = 2 +NVML_VGPU_SCHEDULER_POLICY_FIXED_SHARE = 3 + +## Supported vGPU scheduler policy count +NVML_SUPPORTED_VGPU_SCHEDULER_POLICY_COUNT = 3 + +NVML_SCHEDULER_SW_MAX_LOG_ENTRIES = 200 + +# DEPRECATED: Adaptive Round Robin mode is always enabled +NVML_VGPU_SCHEDULER_ARR_DEFAULT = 0 +NVML_VGPU_SCHEDULER_ARR_DISABLE = 1 +NVML_VGPU_SCHEDULER_ARR_ENABLE = 2 + +NVML_VGPU_SCHEDULER_ENGINE_TYPE_GRAPHICS = 1 +NVML_VGPU_SCHEDULER_ENGINE_TYPE_NVENC1 = 2 +NVML_VGPU_SCHEDULER_ENGINE_TYPE_NVENC0 = 3 + +class c_nvmlVgpuSchedDataWithARR_t(_PrintableStructure): + _fields_ = [ + ('avgFactor', c_uint), + ('timeslice', c_uint), + ] + +class c_nvmlVgpuSchedData_t(_PrintableStructure): + _fields_ = [ + ('timeslice', c_uint), + ] + +class c_nvmlVgpuSchedulerParams_t(Union): + _fields_ = [ + ('vgpuSchedDataWithARR', c_nvmlVgpuSchedDataWithARR_t), + ('vgpuSchedData', c_nvmlVgpuSchedData_t), + ] + +class c_nvmlVgpuSchedulerLogEntry_t(_PrintableStructure): + _fields_ = [ + ('timestamp', c_ulonglong), + ('timeRunTotal', c_ulonglong), + ('timeRun', c_ulonglong), + ('swRunlistId', c_uint), + ('targetTimeSlice', c_ulonglong), + ('cumulativePreemptionTime', c_ulonglong), + ] + +class c_nvmlVgpuSchedulerLog_t(_PrintableStructure): + _fields_ = [ + ('engineId', c_uint), + ('schedulerPolicy', c_uint), + ('arrMode', c_uint), + ('schedulerParams', c_nvmlVgpuSchedulerParams_t), + ('entriesCount', c_uint), + ('logEntries', c_nvmlVgpuSchedulerLogEntry_t * NVML_SCHEDULER_SW_MAX_LOG_ENTRIES), + ] + +class c_nvmlVgpuSchedulerGetState_t(_PrintableStructure): + _fields_ = [ + ('schedulerPolicy', c_uint), + ('arrMode', c_uint), + ('schedulerParams', c_nvmlVgpuSchedulerParams_t), + ] + +class c_nvmlVgpuSchedSetDataWithARR_t(_PrintableStructure): + _fields_ = [ + ('avgFactor', c_uint), + ('frequency', c_uint), + ] + +class c_nvmlVgpuSchedSetData_t(_PrintableStructure): + _fields_ = [ + ('timeslice', c_uint), + ] + +class c_nvmlVgpuSchedulerSetParams_t(Union): + _fields_ = [ + ('vgpuSchedDataWithARR', c_nvmlVgpuSchedSetDataWithARR_t), + ('vgpuSchedData', c_nvmlVgpuSchedSetData_t), + ] + +class c_nvmlVgpuSchedulerSetState_t(_PrintableStructure): + _fields_ = [ + ('schedulerPolicy', c_uint), + ('enableARRMode', c_uint), + ('schedulerParams', c_nvmlVgpuSchedulerSetParams_t), + ] + +class c_nvmlVgpuSchedulerCapabilities_t(_PrintableStructure): + _fields_ = [ + ('supportedSchedulers', c_uint * NVML_SUPPORTED_VGPU_SCHEDULER_POLICY_COUNT), + ('maxTimeslice', c_uint), + ('minTimeslice', c_uint), + ('isArrModeSupported', c_uint), + ('maxFrequencyForARR', c_uint), + ('minFrequencyForARR', c_uint), + ('maxAvgFactorForARR', c_uint), + ('minAvgFactorForARR', c_uint), + ] + +class c_nvmlVgpuTypeIdInfo_v1_t(_PrintableStructure): + _fields_ = [ + ('version', c_uint), + ('vgpuCount', c_uint), + ('vgpuTypeIds', POINTER(c_uint)), + ] + +nvmlVgpuTypeIdInfo_v1 = 0x1000010 + +class c_nvmlVgpuTypeMaxInstance_v1_t(_PrintableStructure): + _fields_ = [ + ('version', c_uint), + ('vgpuTypeId', c_uint), + ('maxInstancePerGI', c_uint), + ] + +nvmlVgpuTypeMaxInstance_v1 = 0x100000C + +class c_nvmlActiveVgpuInstanceInfo_v1_t(_PrintableStructure): + _fields_ = [ + ('version', c_uint), + ('vgpuCount', c_uint), + ('vgpuInstances', POINTER(c_uint)), + ] + +nvmlActiveVgpuInstanceInfo_v1 = 0x1000010 + +class c_nvmlVgpuSchedulerState_v1_t(_PrintableStructure): + _fields_ = [ + ('version', c_uint), + ('engineId', c_uint), + ('schedulerPolicy', c_uint), + ('enableARRMode', c_uint), + ('schedulerParams', c_nvmlVgpuSchedulerSetParams_t), + ] + +nvmlVgpuSchedulerState_v1 = 0x1000018 + +class c_nvmlVgpuSchedulerStateInfo_v1_t(_PrintableStructure): + _fields_ = [ + ('version', c_uint), # input + ('engineId', c_uint), # input. One of NVML_ENGINE_TYPE* + ('schedulerPolicy', c_uint), # output + ('arrMode', c_uint), # output + ('schedulerParams', c_nvmlVgpuSchedulerParams_t), # output + ] + +nvmlVgpuSchedulerStateInfo_v1 = 0x1000018 + +class c_nvmlVgpuSchedulerLogInfo_v1_t(_PrintableStructure): + _fields_ = [ + ('version', c_uint), # input + ('engineId', c_uint), # input. One of NVML_ENGINE_TYPE* + ('schedulerPolicy', c_uint), # output + ('arrMode', c_uint), # output + ('schedulerParams', c_nvmlVgpuSchedulerParams_t), # output + ('entriesCount', c_uint), # output + ('logEntries', c_nvmlVgpuSchedulerLogEntry_t * NVML_SCHEDULER_SW_MAX_LOG_ENTRIES), # output + ] + +nvmlVgpuSchedulerLogInfo_v1 = 0x10025A0 + +class c_nvmlVgpuCreatablePlacementInfo_v1_t(_PrintableStructure): + _fields_ = [ + ('version', c_uint), + ('vgpuTypeId', c_uint), + ('count', c_uint), + ('placementIds', POINTER(c_uint)), + ('placementSize', c_uint), + ] + +nvmlVgpuCreatablePlacementInfo_v1 = 0x1000020 + +class c_nvmlVgpuSchedulerStateInfo_v2_t(_PrintableStructure): + _fields_ = [ + ('engineId', c_uint), # input. One of NVML_ENGINE_TYPE* + ('schedulerPolicy', c_uint), # output + ('avgFactor', c_uint), # output + ('timeslice', c_uint), # output + ] + +class c_nvmlVgpuSchedulerLogEntry_v2_t(_PrintableStructure): + _fields_ = [ + ('timestamp', c_ulonglong), # output + ('timeRunTotal', c_ulonglong), # output + ('timeRun', c_ulonglong), # output + ('swRunlistId', c_uint), # output + ('targetTimeSlice', c_ulonglong), # output + ('cumulativePreemptionTime', c_ulonglong), # output + ('weight', c_uint), # output + ] + +class c_nvmlVgpuSchedulerLogInfo_v2_t(_PrintableStructure): + _fields_ = [ + ('engineId', c_uint), # input. One of NVML_ENGINE_TYPE* + ('schedulerPolicy', c_uint), # output + ('avgFactor', c_uint), # output + ('timeslice', c_uint), # output + ('entriesCount', c_uint), # output + ('logEntries', c_nvmlVgpuSchedulerLogEntry_v2_t * NVML_SCHEDULER_SW_MAX_LOG_ENTRIES), # output + ] + +class c_nvmlVgpuSchedulerState_v2_t(_PrintableStructure): + _fields_ = [ + ('engineId', c_uint), # input. One of NVML_ENGINE_TYPE* + ('schedulerPolicy', c_uint), # input + ('avgFactor', c_uint), # input + ('frequency', c_uint), # input + ] + +class c_nvmlFBCStats_t(Structure): + _fields_ = [("sessionsCount", c_uint), + ("averageFPS", c_uint), + ("averageLatency", c_uint) + ] + +class c_nvmlFBCSession_t(_PrintableStructure): + _fields_ = [ + ('sessionId', c_uint), + ('pid', c_uint), + ('vgpuInstance', _nvmlVgpuInstance_t), + ('displayOrdinal', c_uint), + ('sessionType', c_uint), + ('sessionFlags', c_uint), + ('hMaxResolution', c_uint), + ('vMaxResolution', c_uint), + ('hResolution', c_uint), + ('vResolution', c_uint), + ('averageFPS', c_uint), + ('averageLatency', c_uint), + ] + +NVML_DEVICE_MIG_DISABLE = 0x0 +NVML_DEVICE_MIG_ENABLE = 0x1 + +NVML_GPU_INSTANCE_PROFILE_1_SLICE = 0x0 +NVML_GPU_INSTANCE_PROFILE_2_SLICE = 0x1 +NVML_GPU_INSTANCE_PROFILE_3_SLICE = 0x2 +NVML_GPU_INSTANCE_PROFILE_4_SLICE = 0x3 +NVML_GPU_INSTANCE_PROFILE_7_SLICE = 0x4 +NVML_GPU_INSTANCE_PROFILE_8_SLICE = 0x5 +NVML_GPU_INSTANCE_PROFILE_6_SLICE = 0x6 +NVML_GPU_INSTANCE_PROFILE_1_SLICE_REV1 = 0x7 +NVML_GPU_INSTANCE_PROFILE_2_SLICE_REV1 = 0x8 +NVML_GPU_INSTANCE_PROFILE_1_SLICE_REV2 = 0x9 +NVML_GPU_INSTANCE_PROFILE_1_SLICE_GFX = 0xA +NVML_GPU_INSTANCE_PROFILE_2_SLICE_GFX = 0xB +NVML_GPU_INSTANCE_PROFILE_4_SLICE_GFX = 0xC +NVML_GPU_INSTANCE_PROFILE_1_SLICE_NO_ME = 0xD +NVML_GPU_INSTANCE_PROFILE_2_SLICE_NO_ME = 0xE +NVML_GPU_INSTANCE_PROFILE_1_SLICE_ALL_ME = 0xF +NVML_GPU_INSTANCE_PROFILE_2_SLICE_ALL_ME = 0x10 + +NVML_GPU_INSTANCE_PROFILE_3_SLICE_GFX = 0x11 +NVML_GPU_INSTANCE_PROFILE_COUNT = 0x12 + +class c_nvmlGpuInstancePlacement_t(Structure): + _fields_ = [("start", c_uint), + ("size", c_uint) + ] + +class c_nvmlGpuInstanceProfileInfo_t(Structure): + _fields_ = [("id", c_uint), + ("isP2pSupported", c_uint), + ("sliceCount", c_uint), + ("instanceCount", c_uint), + ("multiprocessorCount", c_uint), + ("copyEngineCount", c_uint), + ("decoderCount", c_uint), + ("encoderCount", c_uint), + ("jpegCount", c_uint), + ("ofaCount", c_uint), + ("memorySizeMB", c_ulonglong), + ] + +nvmlGpuInstanceProfileInfo_v2 = 0x02000098 + +class c_nvmlGpuInstanceProfileInfo_v2_t(_PrintableStructure): + _fields_ = [("version", c_uint), + ("id", c_uint), + ("isP2pSupported", c_uint), + ("sliceCount", c_uint), + ("instanceCount", c_uint), + ("multiprocessorCount", c_uint), + ("copyEngineCount", c_uint), + ("decoderCount", c_uint), + ("encoderCount", c_uint), + ("jpegCount", c_uint), + ("ofaCount", c_uint), + ("memorySizeMB", c_ulonglong), + ("name", c_char * NVML_DEVICE_NAME_V2_BUFFER_SIZE) + ] + + def __init__(self): + super(c_nvmlGpuInstanceProfileInfo_v2_t, self).__init__(version=nvmlGpuInstanceProfileInfo_v2) + +class c_nvmlGpuInstanceInfo_t(Structure): + _fields_ = [("device", c_nvmlDevice_t), + ("id", c_uint), + ("profileId", c_uint), + ("placement", c_nvmlGpuInstancePlacement_t) + ] + +class struct_c_nvmlGpuInstance_t(Structure): + pass # opaque handle +c_nvmlGpuInstance_t = POINTER(struct_c_nvmlGpuInstance_t) + +NVML_COMPUTE_INSTANCE_PROFILE_1_SLICE = 0x0 +NVML_COMPUTE_INSTANCE_PROFILE_2_SLICE = 0x1 +NVML_COMPUTE_INSTANCE_PROFILE_3_SLICE = 0x2 +NVML_COMPUTE_INSTANCE_PROFILE_4_SLICE = 0x3 +NVML_COMPUTE_INSTANCE_PROFILE_7_SLICE = 0x4 +NVML_COMPUTE_INSTANCE_PROFILE_8_SLICE = 0x5 +NVML_COMPUTE_INSTANCE_PROFILE_6_SLICE = 0x6 +NVML_COMPUTE_INSTANCE_PROFILE_1_SLICE_REV1 = 0x7 +NVML_COMPUTE_INSTANCE_PROFILE_7_SLICE_NVL = 0x8 +NVML_COMPUTE_INSTANCE_PROFILE_COUNT = 0x9 + +NVML_COMPUTE_INSTANCE_ENGINE_PROFILE_SHARED = 0x0 +NVML_COMPUTE_INSTANCE_ENGINE_PROFILE_COUNT = 0x1 + +class c_nvmlComputeInstancePlacement_t(Structure): + _fields_ = [("start", c_uint), + ("size", c_uint) + ] + +class c_nvmlComputeInstanceProfileInfo_t(Structure): + _fields_ = [("id", c_uint), + ("sliceCount", c_uint), + ("instanceCount", c_uint), + ("multiprocessorCount", c_uint), + ("sharedCopyEngineCount", c_uint), + ("sharedDecoderCount", c_uint), + ("sharedEncoderCount", c_uint), + ("sharedJpegCount", c_uint), + ("sharedOfaCount", c_uint) + ] + +nvmlComputeInstanceProfileInfo_v2 = 0x02000088 + +class c_nvmlComputeInstanceProfileInfo_v2_t(_PrintableStructure): + _fields_ = [("version", c_uint), + ("id", c_uint), + ("sliceCount", c_uint), + ("instanceCount", c_uint), + ("multiprocessorCount", c_uint), + ("sharedCopyEngineCount", c_uint), + ("sharedDecoderCount", c_uint), + ("sharedEncoderCount", c_uint), + ("sharedJpegCount", c_uint), + ("sharedOfaCount", c_uint), + ("name", c_char * NVML_DEVICE_NAME_V2_BUFFER_SIZE) + ] + + def __init__(self): + super(c_nvmlComputeInstanceProfileInfo_v2_t, self).__init__(version=nvmlComputeInstanceProfileInfo_v2) + +class c_nvmlComputeInstanceInfo_t(Structure): + _fields_ = [("device", c_nvmlDevice_t), + ("gpuInstance", c_nvmlGpuInstance_t), + ("id", c_uint), + ("profileId", c_uint), + ("placement", c_nvmlComputeInstancePlacement_t) + ] + +NVML_MAX_GPU_UTILIZATIONS = 8 +NVML_GPU_UTILIZATION_DOMAIN_GPU = 0 +NVML_GPU_UTILIZATION_DOMAIN_FB = 1 +NVML_GPU_UTILIZATION_DOMAIN_VID = 2 +NVML_GPU_UTILIZATION_DOMAIN_BUS = 3 +class c_nvmlGpuDynamicPstatesUtilization_t(Structure): + _fields_ = [("bIsPresent", c_uint, 1), + ("percentage", c_uint), + ("incThreshold", c_uint), + ("decThreshold", c_uint)] +class c_nvmlGpuDynamicPstatesInfo_t(Structure): + _fields_ = [("flags", c_uint), + ("utilization", c_nvmlGpuDynamicPstatesUtilization_t * NVML_MAX_GPU_UTILIZATIONS)] + +NVML_MAX_THERMAL_SENSORS_PER_GPU = 3 + +NVML_THERMAL_TARGET_NONE = 0 +NVML_THERMAL_TARGET_GPU = 1 +NVML_THERMAL_TARGET_MEMORY = 2 +NVML_THERMAL_TARGET_POWER_SUPPLY = 4 +NVML_THERMAL_TARGET_BOARD = 8 +NVML_THERMAL_TARGET_VCD_BOARD = 9 +NVML_THERMAL_TARGET_VCD_INLET = 10 +NVML_THERMAL_TARGET_VCD_OUTLET = 11 +NVML_THERMAL_TARGET_ALL = 15 +NVML_THERMAL_TARGET_UNKNOWN = -1 + +NVML_THERMAL_CONTROLLER_NONE = 0 +NVML_THERMAL_CONTROLLER_GPU_INTERNAL = 1 +NVML_THERMAL_CONTROLLER_ADM1032 = 2 +NVML_THERMAL_CONTROLLER_ADT7461 = 3 +NVML_THERMAL_CONTROLLER_MAX6649 = 4 +NVML_THERMAL_CONTROLLER_MAX1617 = 5 +NVML_THERMAL_CONTROLLER_LM99 = 6 +NVML_THERMAL_CONTROLLER_LM89 = 7 +NVML_THERMAL_CONTROLLER_LM64 = 8 +NVML_THERMAL_CONTROLLER_G781 = 9 +NVML_THERMAL_CONTROLLER_ADT7473 = 10 +NVML_THERMAL_CONTROLLER_SBMAX6649 = 11 +NVML_THERMAL_CONTROLLER_VBIOSEVT = 12 +NVML_THERMAL_CONTROLLER_OS = 13 +NVML_THERMAL_CONTROLLER_NVSYSCON_CANOAS = 14 +NVML_THERMAL_CONTROLLER_NVSYSCON_E551 = 15 +NVML_THERMAL_CONTROLLER_MAX6649R = 16 +NVML_THERMAL_CONTROLLER_ADT7473S = 17 +NVML_THERMAL_CONTROLLER_UNKNOWN = -1 + +class c_nvmlGpuThermalSensor_t(Structure): + _fields_ = [("controller", c_int), + ("defaultMinTemp", c_int), + ("defaultMaxTemp", c_int), + ("currentTemp", c_int), + ("target", c_int)] +class c_nvmlGpuThermalSettings_t(Structure): + _fields_ = [("count", c_uint), + ("sensor", c_nvmlGpuThermalSensor_t * NVML_MAX_THERMAL_SENSORS_PER_GPU)] + +_nvmlCoolerControl_t = c_uint +NVML_THERMAL_COOLER_SIGNAL_NONE = 0 +NVML_THERMAL_COOLER_SIGNAL_TOGGLE = 1 +NVML_THERMAL_COOLER_SIGNAL_VARIABLE = 2 +NVML_THERMAL_COOLER_SIGNAL_COUNT = 3 + +_nvmlCoolerTarget_t = c_uint +NVML_THERMAL_COOLER_TARGET_NONE = (1 << 0) +NVML_THERMAL_COOLER_TARGET_GPU = (1 << 1) +NVML_THERMAL_COOLER_TARGET_MEMORY = (1 << 2) +NVML_THERMAL_COOLER_TARGET_POWER_SUPPLY = (1 << 3) +NVML_THERMAL_COOLER_TARGET_GPU_RELATED = (NVML_THERMAL_COOLER_TARGET_GPU | NVML_THERMAL_COOLER_TARGET_MEMORY | NVML_THERMAL_COOLER_TARGET_POWER_SUPPLY) + +class c_nvmlCoolerInfo_t(_PrintableStructure): + _fields_ = [("version", c_uint), + ("index", c_uint), + ("coolerControlType", _nvmlCoolerControl_t), + ("coolerTarget", _nvmlCoolerTarget_t) + ] + +nvmlCoolerInfo_v1 = 0x1000010 + +def nvmlDeviceGetCoolerInfo(handle): + c_coolerInfo = c_nvmlCoolerInfo_t() + c_coolerInfo.version = nvmlCoolerInfo_v1 + c_coolerInfo.index = 0 + fn = _nvmlGetFunctionPointer("nvmlDeviceGetCoolerInfo") + ret = fn(handle, byref(c_coolerInfo)) + _nvmlCheckReturn(ret) + return [c_coolerInfo.coolerControlType, c_coolerInfo.coolerTarget] + +class struct_c_nvmlComputeInstance_t(Structure): + pass # opaque handle +c_nvmlComputeInstance_t = POINTER(struct_c_nvmlComputeInstance_t) + +class c_nvmlDeviceAttributes(Structure): + _fields_ = [("multiprocessorCount", c_uint), + ("sharedCopyEngineCount", c_uint), + ("sharedDecoderCount", c_uint), + ("sharedEncoderCount", c_uint), + ("sharedJpegCount", c_uint), + ("sharedOfaCount", c_uint), + ("gpuInstanceSliceCount", c_uint), + ("computeInstanceSliceCount", c_uint), + ("memorySizeMB", c_ulonglong), + ] + +class c_nvmlRowRemapperHistogramValues(Structure): + _fields_ = [("max", c_uint), + ("high", c_uint), + ("partial", c_uint), + ("low", c_uint), + ("none", c_uint) + ] + +NVML_GPU_CERT_CHAIN_SIZE = 0x1000 +NVML_GPU_ATTESTATION_CERT_CHAIN_SIZE = 0x1400 +NVML_CC_GPU_CEC_NONCE_SIZE = 0x20 +NVML_CC_GPU_ATTESTATION_REPORT_SIZE = 0x2000 +NVML_CC_GPU_CEC_ATTESTATION_REPORT_SIZE = 0x1000 +NVML_CC_CEC_ATTESTATION_REPORT_NOT_PRESENT = 0 +NVML_CC_CEC_ATTESTATION_REPORT_PRESENT = 1 + +class c_nvmlConfComputeSystemState_t(Structure): + _fields_ = [('environment', c_uint), + ('ccFeature', c_uint), + ('devToolsMode', c_uint), + ] + +nvmlSystemConfComputeSettings_v1 = 0x1000014 + +class c_nvmlSystemConfComputeSettings_v1_t(Structure): + _fields_ = [('version', c_uint), + ('environment', c_uint), + ('ccFeature', c_uint), + ('devToolsMode', c_uint), + ('multiGpuMode', c_uint), + ] + def __init__(self): + super(c_nvmlSystemConfComputeSettings_v1_t, self).__init__(version=nvmlSystemConfComputeSettings_v1) + +class c_nvmlConfComputeSystemCaps_t(Structure): + _fields_ = [('cpuCaps', c_uint), + ('gpusCaps', c_uint), + ] + +class c_nvmlConfComputeMemSizeInfo_t(Structure): + _fields_ = [('protectedMemSizeKib', c_ulonglong), + ('unprotectedMemSizeKib', c_ulonglong), + ] + +class c_nvmlConfComputeGpuCertificate_t(Structure): + _fields_ = [('certChainSize', c_uint), + ('attestationCertChainSize', c_uint), + ('certChain', c_uint8 * NVML_GPU_CERT_CHAIN_SIZE), + ('attestationCertChain', c_uint8 * NVML_GPU_ATTESTATION_CERT_CHAIN_SIZE), + ] + +class c_nvmlConfComputeGpuAttestationReport_t(Structure): + _fields_ = [('isCecAttestationReportPresent', c_uint), # output + ('attestationReportSize', c_uint), # output + ('cecAttestationReportSize', c_uint), # output + ('nonce', c_uint8 * NVML_CC_GPU_CEC_NONCE_SIZE), # input: spdm supports 32 bytes on nonce + ('attestationReport', c_uint8 * NVML_CC_GPU_ATTESTATION_REPORT_SIZE), # output + ('cecAttestationReport', c_uint8 * NVML_CC_GPU_CEC_ATTESTATION_REPORT_SIZE), # output + ] + +class c_nvmlConfComputeSetKeyRotationThresholdInfo_t(Structure): + _fields_ = [('version', c_uint), + ('maxAttackerAdvantage', c_ulong), + ] +ConfComputeSetKeyRotationThresholdInfo_v1 = 0x1000010 + +class c_nvmlConfComputeGetKeyRotationThresholdInfo_t(Structure): + _fields_ = [('version', c_uint), + ('attackerAdvantage', c_ulong), + ] +ConfComputeGetKeyRotationThresholdInfo_v1 = 0x1000010 + +## string/bytes conversion for ease of use +def convertStrBytes(func): + ''' + In python 3, strings are unicode instead of bytes, and need to be converted for ctypes + Args from caller: (1, 'string', <__main__.c_nvmlDevice_t at 0xFFFFFFFF>) + Args passed to function: (1, b'string', <__main__.c_nvmlDevice_t at 0xFFFFFFFF)> + ---- + Returned from function: b'returned string' + Returned to caller: 'returned string' + ''' + @wraps(func) + def wrapper(*args, **kwargs): + # encoding a str returns bytes in python 2 and 3 + args = [arg.encode() if isinstance(arg, str) else arg for arg in args] + res = func(*args, **kwargs) + # In python 2, str and bytes are the same + # In python 3, str is unicode and should be decoded. + # Ctypes handles most conversions, this only effects c_char and char arrays. + if isinstance(res, bytes): + if isinstance(res, str): + return res + return res.decode() + return res + + if sys.version_info >= (3,): + return wrapper + return func + +def throwOnVersionMismatch(func): + @wraps(func) + def wrapper(*args, **kwargs): + try: + return func(*args, **kwargs) + except NVMLError_FunctionNotFound: + raise NVMLLibraryMismatchError("Unversioned function called and the " + "pyNVML version does not match the NVML lib version. " + "Either use matching pyNVML and NVML lib versions or " + "use a versioned function such as " + func.__name__ + "_v2") + return wrapper + +## C function wrappers ## +def nvmlInitWithFlags(flags): + _LoadNvmlLibrary() + + # + # Initialize the library + # + fn = _nvmlGetFunctionPointer("nvmlInitWithFlags") + ret = fn(flags) + _nvmlCheckReturn(ret) + + # Atomically update refcount + global _nvmlLib_refcount + libLoadLock.acquire() + _nvmlLib_refcount += 1 + libLoadLock.release() + return None + +def nvmlInit(): + nvmlInitWithFlags(0) + return None + +def _LoadNvmlLibrary(): + ''' + Load the library if it isn't loaded already + ''' + global nvmlLib + + if (nvmlLib == None): + # lock to ensure only one caller loads the library + libLoadLock.acquire() + + try: + # ensure the library still isn't loaded + if (nvmlLib == None): + try: + if (sys.platform[:3] == "win"): + # cdecl calling convention + try: + # Check for nvml.dll in System32 first for DCH drivers + nvmlLib = CDLL(os.path.join(os.getenv("WINDIR", "C:/Windows"), "System32/nvml.dll")) + except OSError as ose: + # If nvml.dll is not found in System32, it should be in ProgramFiles + # load nvml.dll from %ProgramFiles%/NVIDIA Corporation/NVSMI/nvml.dll + nvmlLib = CDLL(os.path.join(os.getenv("ProgramFiles", "C:/Program Files"), "NVIDIA Corporation/NVSMI/nvml.dll")) + else: + # assume linux + nvmlLib = CDLL("libnvidia-ml.so.1") + except OSError as ose: + _nvmlCheckReturn(NVML_ERROR_LIBRARY_NOT_FOUND) + if (nvmlLib == None): + _nvmlCheckReturn(NVML_ERROR_LIBRARY_NOT_FOUND) + finally: + # lock is always freed + libLoadLock.release() + +def nvmlShutdown(): + # + # Leave the library loaded, but shutdown the interface + # + fn = _nvmlGetFunctionPointer("nvmlShutdown") + ret = fn() + _nvmlCheckReturn(ret) + + # Atomically update refcount + global _nvmlLib_refcount + libLoadLock.acquire() + if (0 < _nvmlLib_refcount): + _nvmlLib_refcount -= 1 + libLoadLock.release() + return None + +# Added in 2.285 +@convertStrBytes +def nvmlErrorString(result): + fn = _nvmlGetFunctionPointer("nvmlErrorString") + fn.restype = c_char_p # otherwise return is an int + ret = fn(result) + return ret + +# Added in 2.285 +@convertStrBytes +def nvmlSystemGetNVMLVersion(): + c_version = create_string_buffer(NVML_SYSTEM_NVML_VERSION_BUFFER_SIZE) + fn = _nvmlGetFunctionPointer("nvmlSystemGetNVMLVersion") + ret = fn(c_version, c_uint(NVML_SYSTEM_NVML_VERSION_BUFFER_SIZE)) + _nvmlCheckReturn(ret) + return c_version.value + +def nvmlSystemGetCudaDriverVersion(): + c_cuda_version = c_int() + fn = _nvmlGetFunctionPointer("nvmlSystemGetCudaDriverVersion") + ret = fn(byref(c_cuda_version)) + _nvmlCheckReturn(ret) + return c_cuda_version.value + +def nvmlSystemGetCudaDriverVersion_v2(): + c_cuda_version = c_int() + fn = _nvmlGetFunctionPointer("nvmlSystemGetCudaDriverVersion_v2") + ret = fn(byref(c_cuda_version)) + _nvmlCheckReturn(ret) + return c_cuda_version.value + +# Added in 2.285 +@convertStrBytes +def nvmlSystemGetProcessName(pid): + c_name = create_string_buffer(1024) + fn = _nvmlGetFunctionPointer("nvmlSystemGetProcessName") + ret = fn(c_uint(pid), c_name, c_uint(1024)) + _nvmlCheckReturn(ret) + return c_name.value + +@convertStrBytes +def nvmlSystemGetDriverVersion(): + c_version = create_string_buffer(NVML_SYSTEM_DRIVER_VERSION_BUFFER_SIZE) + fn = _nvmlGetFunctionPointer("nvmlSystemGetDriverVersion") + ret = fn(c_version, c_uint(NVML_SYSTEM_DRIVER_VERSION_BUFFER_SIZE)) + _nvmlCheckReturn(ret) + return c_version.value + +# Added in 2.285 +def nvmlSystemGetHicVersion(): + c_count = c_uint(0) + hics = None + fn = _nvmlGetFunctionPointer("nvmlSystemGetHicVersion") + + # get the count + ret = fn(byref(c_count), None) + + # this should only fail with insufficient size + if ((ret != NVML_SUCCESS) and + (ret != NVML_ERROR_INSUFFICIENT_SIZE)): + raise NVMLError(ret) + + # If there are no hics + if (c_count.value == 0): + return [] + + hic_array = c_nvmlHwbcEntry_t * c_count.value + hics = hic_array() + ret = fn(byref(c_count), hics) + _nvmlCheckReturn(ret) + return hics + +def nvmlSystemGetDriverBranch(): + c_branchInfo = c_nvmlSystemDriverBranchInfo_v1_t(0) + c_branchInfo.version = SystemDriverBranchInfo_v1 + fn = _nvmlGetFunctionPointer("nvmlSystemGetDriverBranch") + ret = fn(byref(c_branchInfo), c_uint(NVML_SYSTEM_DRIVER_VERSION_BUFFER_SIZE)) + _nvmlCheckReturn(ret) + return c_branchInfo + +def nvmlSystemGetCPER_v1(cper): + fn = _nvmlGetFunctionPointer("nvmlSystemGetCPER_v1") + ret = fn(byref(cper)) + _nvmlCheckReturn(ret) + +## Unit get functions +def nvmlUnitGetCount(): + c_count = c_uint() + fn = _nvmlGetFunctionPointer("nvmlUnitGetCount") + ret = fn(byref(c_count)) + _nvmlCheckReturn(ret) + return c_count.value + +def nvmlUnitGetHandleByIndex(index): + c_index = c_uint(index) + unit = c_nvmlUnit_t() + fn = _nvmlGetFunctionPointer("nvmlUnitGetHandleByIndex") + ret = fn(c_index, byref(unit)) + _nvmlCheckReturn(ret) + return unit + +def nvmlUnitGetUnitInfo(unit): + c_info = c_nvmlUnitInfo_t() + fn = _nvmlGetFunctionPointer("nvmlUnitGetUnitInfo") + ret = fn(unit, byref(c_info)) + _nvmlCheckReturn(ret) + return c_info + +def nvmlUnitGetLedState(unit): + c_state = c_nvmlLedState_t() + fn = _nvmlGetFunctionPointer("nvmlUnitGetLedState") + ret = fn(unit, byref(c_state)) + _nvmlCheckReturn(ret) + return c_state + +def nvmlUnitGetPsuInfo(unit): + c_info = c_nvmlPSUInfo_t() + fn = _nvmlGetFunctionPointer("nvmlUnitGetPsuInfo") + ret = fn(unit, byref(c_info)) + _nvmlCheckReturn(ret) + return c_info + +def nvmlUnitGetTemperature(unit, type): + c_temp = c_uint() + fn = _nvmlGetFunctionPointer("nvmlUnitGetTemperature") + ret = fn(unit, c_uint(type), byref(c_temp)) + _nvmlCheckReturn(ret) + return c_temp.value + +def nvmlUnitGetFanSpeedInfo(unit): + c_speeds = c_nvmlUnitFanSpeeds_t() + fn = _nvmlGetFunctionPointer("nvmlUnitGetFanSpeedInfo") + ret = fn(unit, byref(c_speeds)) + _nvmlCheckReturn(ret) + return c_speeds + +# added to API +def nvmlUnitGetDeviceCount(unit): + c_count = c_uint(0) + # query the unit to determine device count + fn = _nvmlGetFunctionPointer("nvmlUnitGetDevices") + ret = fn(unit, byref(c_count), None) + if (ret == NVML_ERROR_INSUFFICIENT_SIZE): + ret = NVML_SUCCESS + _nvmlCheckReturn(ret) + return c_count.value + +def nvmlUnitGetDevices(unit): + c_count = c_uint(nvmlUnitGetDeviceCount(unit)) + device_array = c_nvmlDevice_t * c_count.value + c_devices = device_array() + fn = _nvmlGetFunctionPointer("nvmlUnitGetDevices") + ret = fn(unit, byref(c_count), c_devices) + _nvmlCheckReturn(ret) + return c_devices + +## Device get functions +def nvmlDeviceGetCount(): + c_count = c_uint() + fn = _nvmlGetFunctionPointer("nvmlDeviceGetCount_v2") + ret = fn(byref(c_count)) + _nvmlCheckReturn(ret) + return c_count.value + +def nvmlDeviceGetHandleByIndex(index): + c_index = c_uint(index) + device = c_nvmlDevice_t() + fn = _nvmlGetFunctionPointer("nvmlDeviceGetHandleByIndex_v2") + ret = fn(c_index, byref(device)) + _nvmlCheckReturn(ret) + return device + +# Deprecated +@convertStrBytes +# DEPRECATED Use nvmlDeviceGetHandleByUUID instead; will be removed in CUDA 14.0 +def nvmlDeviceGetHandleBySerial(serial): + c_serial = c_char_p(serial) + device = c_nvmlDevice_t() + fn = _nvmlGetFunctionPointer("nvmlDeviceGetHandleBySerial") + ret = fn(c_serial, byref(device)) + _nvmlCheckReturn(ret) + return device + +@convertStrBytes +def nvmlDeviceGetHandleByUUID(uuid): + c_uuid = c_char_p(uuid) + device = c_nvmlDevice_t() + fn = _nvmlGetFunctionPointer("nvmlDeviceGetHandleByUUID") + ret = fn(c_uuid, byref(device)) + _nvmlCheckReturn(ret) + return device + +@convertStrBytes +def nvmlDeviceGetHandleByUUIDV(uuid, type): + c_uuid = c_nvmlUUID_t() + c_uuid.type = type + if type == NVML_UUID_TYPE_ASCII: + c_uuid.value.str = uuid + elif type == NVML_UUID_TYPE_BINARY: + memmove(c_uuid.value.bytes, uuid, NVML_DEVICE_UUID_BINARY_LEN) + device = c_nvmlDevice_t() + fn = _nvmlGetFunctionPointer("nvmlDeviceGetHandleByUUIDV") + ret = fn(byref(c_uuid), byref(device)) + _nvmlCheckReturn(ret) + return device + +@convertStrBytes +def nvmlDeviceGetHandleByPciBusId(pciBusId): + c_busId = c_char_p(pciBusId) + device = c_nvmlDevice_t() + fn = _nvmlGetFunctionPointer("nvmlDeviceGetHandleByPciBusId_v2") + ret = fn(c_busId, byref(device)) + _nvmlCheckReturn(ret) + return device + +@convertStrBytes +def nvmlDeviceGetName(handle): + c_name = create_string_buffer(NVML_DEVICE_NAME_V2_BUFFER_SIZE) + fn = _nvmlGetFunctionPointer("nvmlDeviceGetName") + ret = fn(handle, c_name, c_uint(NVML_DEVICE_NAME_V2_BUFFER_SIZE)) + _nvmlCheckReturn(ret) + return c_name.value + +class c_nvmlDevicePerfModes_v1_t(_PrintableStructure): + _fields_ = [ + ('version', c_uint), + ('str', c_char * NVML_PERF_MODES_BUFFER_SIZE), + ] + +nvmlDevicePerfModes_v1 = 0x1000804 + +@convertStrBytes +def nvmlDeviceGetPerformanceModes(handle): + perfModes = c_nvmlDevicePerfModes_v1_t() + perfModes.version = nvmlDevicePerfModes_v1 + fn = _nvmlGetFunctionPointer("nvmlDeviceGetPerformanceModes") + ret = fn(handle, byref(perfModes)) + _nvmlCheckReturn(ret) + return perfModes.str + +class c_nvmlDeviceCurrentClockFreqs_v1_t(_PrintableStructure): + _fields_ = [ + ('version', c_uint), + ('str', c_char * NVML_PERF_MODES_BUFFER_SIZE), + ] + +nvmlDeviceCurrentClockFreqs_v1 = 0x1000804 + +@convertStrBytes +def nvmlDeviceGetCurrentClockFreqs(handle): + currentClockFreqs = c_nvmlDeviceCurrentClockFreqs_v1_t() + currentClockFreqs.version = nvmlDeviceCurrentClockFreqs_v1 + fn = _nvmlGetFunctionPointer("nvmlDeviceGetCurrentClockFreqs") + ret = fn(handle, byref(currentClockFreqs)) + _nvmlCheckReturn(ret) + return currentClockFreqs.str + +def nvmlDeviceGetBoardId(handle): + c_id = c_uint() + fn = _nvmlGetFunctionPointer("nvmlDeviceGetBoardId") + ret = fn(handle, byref(c_id)) + _nvmlCheckReturn(ret) + return c_id.value + +def nvmlDeviceGetMultiGpuBoard(handle): + c_multiGpu = c_uint() + fn = _nvmlGetFunctionPointer("nvmlDeviceGetMultiGpuBoard") + ret = fn(handle, byref(c_multiGpu)) + _nvmlCheckReturn(ret) + return c_multiGpu.value + +def nvmlDeviceGetBrand(handle): + c_type = _nvmlBrandType_t() + fn = _nvmlGetFunctionPointer("nvmlDeviceGetBrand") + ret = fn(handle, byref(c_type)) + _nvmlCheckReturn(ret) + return c_type.value + +def nvmlDeviceGetC2cModeInfoV1(handle): + c_info = c_nvmlC2cModeInfo_v1_t() + fn = _nvmlGetFunctionPointer("nvmlDeviceGetC2cModeInfoV") + ret = fn(handle, byref(c_info)) + _nvmlCheckReturn(ret) + return c_info + +def nvmlDeviceGetC2cModeInfoV(handle): + return nvmlDeviceGetC2cModeInfoV1(handle) + +@convertStrBytes +def nvmlDeviceGetBoardPartNumber(handle): + c_part_number = create_string_buffer(NVML_DEVICE_PART_NUMBER_BUFFER_SIZE) + fn = _nvmlGetFunctionPointer("nvmlDeviceGetBoardPartNumber") + ret = fn(handle, c_part_number, c_uint(NVML_DEVICE_PART_NUMBER_BUFFER_SIZE)) + _nvmlCheckReturn(ret) + return c_part_number.value + +@convertStrBytes +def nvmlDeviceGetSerial(handle): + c_serial = create_string_buffer(NVML_DEVICE_SERIAL_BUFFER_SIZE) + fn = _nvmlGetFunctionPointer("nvmlDeviceGetSerial") + ret = fn(handle, c_serial, c_uint(NVML_DEVICE_SERIAL_BUFFER_SIZE)) + _nvmlCheckReturn(ret) + return c_serial.value + +def nvmlDeviceGetModuleId(handle, moduleId=c_uint()): + isReference = type(moduleId) is not c_uint + moduleIdRef = moduleId if isReference else byref(moduleId) + fn = _nvmlGetFunctionPointer("nvmlDeviceGetModuleId") + ret = fn(handle, moduleIdRef) + if isReference: + return ret + else: + _nvmlCheckReturn(ret) + return moduleId.value + +def nvmlDeviceGetMemoryAffinity(handle, nodeSetSize, scope): + affinity_array = c_ulonglong * nodeSetSize + c_affinity = affinity_array() + fn = _nvmlGetFunctionPointer("nvmlDeviceGetMemoryAffinity") + ret = fn(handle, nodeSetSize, byref(c_affinity), _nvmlAffinityScope_t(scope)) + _nvmlCheckReturn(ret) + return c_affinity + +def nvmlDeviceGetCpuAffinityWithinScope(handle, cpuSetSize, scope): + affinity_array = c_ulonglong * cpuSetSize + c_affinity = affinity_array() + fn = _nvmlGetFunctionPointer("nvmlDeviceGetCpuAffinityWithinScope") + ret = fn(handle, cpuSetSize, byref(c_affinity), _nvmlAffinityScope_t(scope)) + _nvmlCheckReturn(ret) + return c_affinity + +def nvmlDeviceGetCpuAffinity(handle, cpuSetSize): + affinity_array = c_ulonglong * cpuSetSize + c_affinity = affinity_array() + fn = _nvmlGetFunctionPointer("nvmlDeviceGetCpuAffinity") + ret = fn(handle, cpuSetSize, byref(c_affinity)) + _nvmlCheckReturn(ret) + return c_affinity + +def nvmlDeviceSetCpuAffinity(handle): + fn = _nvmlGetFunctionPointer("nvmlDeviceSetCpuAffinity") + ret = fn(handle) + _nvmlCheckReturn(ret) + return None + +def nvmlDeviceClearCpuAffinity(handle): + fn = _nvmlGetFunctionPointer("nvmlDeviceClearCpuAffinity") + ret = fn(handle) + _nvmlCheckReturn(ret) + return None + +def nvmlDeviceGetNumaNodeId(handle): + fn = _nvmlGetFunctionPointer("nvmlDeviceGetNumaNodeId") + node = c_int() + ret = fn(handle, byref(node)) + _nvmlCheckReturn(ret) + return node.value + +def nvmlDeviceGetAddressingMode(device): + c_mode = c_nvmlDeviceAddressingMode_t() + fn = _nvmlGetFunctionPointer("nvmlDeviceGetAddressingMode") + ret = fn(device, byref(c_mode)) + _nvmlCheckReturn(ret) + return c_mode.value + +def nvmlDeviceGetMinorNumber(handle): + c_minor_number = c_uint() + fn = _nvmlGetFunctionPointer("nvmlDeviceGetMinorNumber") + ret = fn(handle, byref(c_minor_number)) + _nvmlCheckReturn(ret) + return c_minor_number.value + +@convertStrBytes +def nvmlDeviceGetUUID(handle): + c_uuid = create_string_buffer(NVML_DEVICE_UUID_V2_BUFFER_SIZE) + fn = _nvmlGetFunctionPointer("nvmlDeviceGetUUID") + ret = fn(handle, c_uuid, c_uint(NVML_DEVICE_UUID_V2_BUFFER_SIZE)) + _nvmlCheckReturn(ret) + return c_uuid.value + +@convertStrBytes +def nvmlDeviceGetInforomVersion(handle, infoRomObject): + c_version = create_string_buffer(NVML_DEVICE_INFOROM_VERSION_BUFFER_SIZE) + fn = _nvmlGetFunctionPointer("nvmlDeviceGetInforomVersion") + ret = fn(handle, _nvmlInforomObject_t(infoRomObject), + c_version, c_uint(NVML_DEVICE_INFOROM_VERSION_BUFFER_SIZE)) + _nvmlCheckReturn(ret) + return c_version.value + +# Added in 4.304 +@convertStrBytes +def nvmlDeviceGetInforomImageVersion(handle): + c_version = create_string_buffer(NVML_DEVICE_INFOROM_VERSION_BUFFER_SIZE) + fn = _nvmlGetFunctionPointer("nvmlDeviceGetInforomImageVersion") + ret = fn(handle, c_version, c_uint(NVML_DEVICE_INFOROM_VERSION_BUFFER_SIZE)) + _nvmlCheckReturn(ret) + return c_version.value + +# Added in 4.304 +def nvmlDeviceGetInforomConfigurationChecksum(handle): + c_checksum = c_uint() + fn = _nvmlGetFunctionPointer("nvmlDeviceGetInforomConfigurationChecksum") + ret = fn(handle, byref(c_checksum)) + _nvmlCheckReturn(ret) + return c_checksum.value + +# Added in 4.304 +def nvmlDeviceValidateInforom(handle): + fn = _nvmlGetFunctionPointer("nvmlDeviceValidateInforom") + ret = fn(handle) + _nvmlCheckReturn(ret) + return None + +def nvmlDeviceGetLastBBXFlushTime(handle): + c_timestamp = c_ulonglong() + c_durationUs = c_ulong() + fn = _nvmlGetFunctionPointer("nvmlDeviceGetLastBBXFlushTime") + ret = fn(handle, byref(c_timestamp), byref(c_durationUs)) + _nvmlCheckReturn(ret) + return [c_timestamp.value, c_durationUs.value] + +def nvmlDeviceGetDisplayMode(handle): + c_mode = _nvmlEnableState_t() + fn = _nvmlGetFunctionPointer("nvmlDeviceGetDisplayMode") + ret = fn(handle, byref(c_mode)) + _nvmlCheckReturn(ret) + return c_mode.value + +def nvmlDeviceGetDisplayActive(handle): + c_mode = _nvmlEnableState_t() + fn = _nvmlGetFunctionPointer("nvmlDeviceGetDisplayActive") + ret = fn(handle, byref(c_mode)) + _nvmlCheckReturn(ret) + return c_mode.value + + +def nvmlDeviceGetPersistenceMode(handle): + c_state = _nvmlEnableState_t() + fn = _nvmlGetFunctionPointer("nvmlDeviceGetPersistenceMode") + ret = fn(handle, byref(c_state)) + _nvmlCheckReturn(ret) + return c_state.value + +def nvmlDeviceGetPciInfoExt(handle, c_info): + fn = _nvmlGetFunctionPointer("nvmlDeviceGetPciInfoExt") + ret = fn(handle, c_info) + _nvmlCheckReturn(ret) + return None + +def nvmlDeviceGetPciInfo_v3(handle): + c_info = nvmlPciInfo_t() + fn = _nvmlGetFunctionPointer("nvmlDeviceGetPciInfo_v3") + ret = fn(handle, byref(c_info)) + _nvmlCheckReturn(ret) + return c_info + +def nvmlDeviceGetPciInfo(handle): + return nvmlDeviceGetPciInfo_v3(handle) + +def nvmlDeviceGetClockInfo(handle, type): + c_clock = c_uint() + fn = _nvmlGetFunctionPointer("nvmlDeviceGetClockInfo") + ret = fn(handle, _nvmlClockType_t(type), byref(c_clock)) + _nvmlCheckReturn(ret) + return c_clock.value + +# Added in 2.285 +def nvmlDeviceGetMaxClockInfo(handle, type): + c_clock = c_uint() + fn = _nvmlGetFunctionPointer("nvmlDeviceGetMaxClockInfo") + ret = fn(handle, _nvmlClockType_t(type), byref(c_clock)) + _nvmlCheckReturn(ret) + return c_clock.value + +# Added in 4.304 +# DEPRECATED Do not use; will be removed in CUDA 14.0 +def nvmlDeviceGetApplicationsClock(handle, type): + c_clock = c_uint() + fn = _nvmlGetFunctionPointer("nvmlDeviceGetApplicationsClock") + ret = fn(handle, _nvmlClockType_t(type), byref(c_clock)) + _nvmlCheckReturn(ret) + return c_clock.value + +def nvmlDeviceGetMaxCustomerBoostClock(handle, type): + c_clock = c_uint() + fn = _nvmlGetFunctionPointer("nvmlDeviceGetMaxCustomerBoostClock") + ret = fn(handle, _nvmlClockType_t(type), byref(c_clock)) + _nvmlCheckReturn(ret) + return c_clock.value + +def nvmlDeviceGetClock(handle, type, id): + c_clock = c_uint() + fn = _nvmlGetFunctionPointer("nvmlDeviceGetClock") + ret = fn(handle, _nvmlClockType_t(type), _nvmlClockId_t(id), byref(c_clock)) + _nvmlCheckReturn(ret) + return c_clock.value + +# Added in 5.319 +# DEPRECATED Do not use; will be removed in CUDA 14.0 +def nvmlDeviceGetDefaultApplicationsClock(handle, type): + c_clock = c_uint() + fn = _nvmlGetFunctionPointer("nvmlDeviceGetDefaultApplicationsClock") + ret = fn(handle, _nvmlClockType_t(type), byref(c_clock)) + _nvmlCheckReturn(ret) + return c_clock.value + +# Added in 4.304 +def nvmlDeviceGetSupportedMemoryClocks(handle): + # first call to get the size + c_count = c_uint(0) + fn = _nvmlGetFunctionPointer("nvmlDeviceGetSupportedMemoryClocks") + ret = fn(handle, byref(c_count), None) + + if (ret == NVML_SUCCESS): + # special case, no clocks + return [] + elif (ret == NVML_ERROR_INSUFFICIENT_SIZE): + # typical case + clocks_array = c_uint * c_count.value + c_clocks = clocks_array() + + # make the call again + ret = fn(handle, byref(c_count), c_clocks) + _nvmlCheckReturn(ret) + + procs = [] + for i in range(c_count.value): + procs.append(c_clocks[i]) + + return procs + else: + # error case + raise NVMLError(ret) + +# Added in 4.304 +def nvmlDeviceGetSupportedGraphicsClocks(handle, memoryClockMHz): + # first call to get the size + c_count = c_uint(0) + fn = _nvmlGetFunctionPointer("nvmlDeviceGetSupportedGraphicsClocks") + ret = fn(handle, c_uint(memoryClockMHz), byref(c_count), None) + + if (ret == NVML_SUCCESS): + # special case, no clocks + return [] + elif (ret == NVML_ERROR_INSUFFICIENT_SIZE): + # typical case + clocks_array = c_uint * c_count.value + c_clocks = clocks_array() + + # make the call again + ret = fn(handle, c_uint(memoryClockMHz), byref(c_count), c_clocks) + _nvmlCheckReturn(ret) + + procs = [] + for i in range(c_count.value): + procs.append(c_clocks[i]) + + return procs + else: + # error case + raise NVMLError(ret) + +def nvmlDeviceGetFanSpeed(handle): + c_speed = c_uint() + fn = _nvmlGetFunctionPointer("nvmlDeviceGetFanSpeed") + ret = fn(handle, byref(c_speed)) + _nvmlCheckReturn(ret) + return c_speed.value + +def nvmlDeviceGetFanSpeed_v2(handle, fan): + c_speed = c_uint() + fn = _nvmlGetFunctionPointer("nvmlDeviceGetFanSpeed_v2") + ret = fn(handle, fan, byref(c_speed)) + _nvmlCheckReturn(ret) + return c_speed.value + +class c_nvmlFanSpeedInfo_t(_PrintableStructure): + _fields_ = [ + ('version', c_uint), + ('fan', c_uint), + ('speed', c_uint), + ] + +nvmlFanSpeedInfo_v1 = 0x100000C + +def nvmlDeviceGetFanSpeedRPM(handle): + c_fanSpeed = c_nvmlFanSpeedInfo_t() + c_fanSpeed.fan = 0 + c_fanSpeed.version = nvmlFanSpeedInfo_v1 + fn = _nvmlGetFunctionPointer("nvmlDeviceGetFanSpeedRPM") + ret = fn(handle, byref(c_fanSpeed)) + _nvmlCheckReturn(ret) + return c_fanSpeed.speed + +def nvmlDeviceGetTargetFanSpeed(handle, fan): + c_speed = c_uint() + fn = _nvmlGetFunctionPointer("nvmlDeviceGetTargetFanSpeed") + ret = fn(handle, fan, byref(c_speed)) + _nvmlCheckReturn(ret) + return c_speed.value + +def nvmlDeviceGetNumFans(device): + c_numFans = c_uint() + fn = _nvmlGetFunctionPointer("nvmlDeviceGetNumFans") + ret = fn(device, byref(c_numFans)) + _nvmlCheckReturn(ret) + return c_numFans.value + +def nvmlDeviceSetDefaultFanSpeed_v2(handle, index): + fn = _nvmlGetFunctionPointer("nvmlDeviceSetDefaultFanSpeed_v2"); + ret = fn(handle, index) + _nvmlCheckReturn(ret) + return NVML_SUCCESS + +def nvmlDeviceGetMinMaxFanSpeed(handle, minSpeed=c_uint(), maxSpeed=c_uint()): + isReference = (type(minSpeed) is not c_uint) or (type(maxSpeed) is not c_uint) + minSpeedRef = minSpeed if isReference else byref(minSpeed) + maxSpeedRef = maxSpeed if isReference else byref(maxSpeed) + fn = _nvmlGetFunctionPointer("nvmlDeviceGetMinMaxFanSpeed") + ret = fn(handle, minSpeedRef, maxSpeedRef) + _nvmlCheckReturn(ret) + return NVML_SUCCESS if isReference else [minSpeed.value, maxSpeed.value] + +def nvmlDeviceGetFanControlPolicy_v2(handle, fan, fanControlPolicy=c_uint()): + isReference = type(fanControlPolicy) is not c_uint + fanControlPolicyRef = fanControlPolicy if isReference else byref(fanControlPolicy) + fn = _nvmlGetFunctionPointer("nvmlDeviceGetFanControlPolicy_v2") + ret = fn(handle, fan, fanControlPolicyRef) + _nvmlCheckReturn(ret) + return NVML_SUCCESS if isReference else fanControlPolicy.value + +def nvmlDeviceSetFanControlPolicy(handle, fan, fanControlPolicy): + fn = _nvmlGetFunctionPointer("nvmlDeviceSetFanControlPolicy") + ret = fn(handle, fan, _nvmlFanControlPolicy_t(fanControlPolicy)) + _nvmlCheckReturn(ret) + return NVML_SUCCESS + +class c_nvmlTemperature_v1_t(_PrintableStructure): + _fields_ = [ + ('version', c_uint), + ('sensorType', _nvmlTemperatureSensors_t), + ('temperature', c_int), + ] +nvmlTemperature_v1 = 0x100000C + +def nvmlDeviceGetTemperatureV1(handle, sensor): + c_temp = c_nvmlTemperature_v1_t() + c_temp.version = nvmlTemperature_v1 + c_temp.sensorType = _nvmlTemperatureSensors_t(sensor) + fn = _nvmlGetFunctionPointer("nvmlDeviceGetTemperatureV") + ret = fn(handle, byref(c_temp)) + _nvmlCheckReturn(ret) + return c_temp.temperature + +def nvmlDeviceGetTemperatureV(handle, sensor, version=nvmlTemperature_v1): + if version == nvmlTemperature_v1: + return nvmlDeviceGetTemperatureV1(handle, sensor) + else: + raise NVMLError(NVML_ERROR_ARGUMENT_VERSION_MISMATCH) + +# DEPRECATED: Use nvmlDeviceGetTemperatureV instead; will be removed in CUDA 14.0 +def nvmlDeviceGetTemperature(handle, sensor): + c_temp = c_uint() + fn = _nvmlGetFunctionPointer("nvmlDeviceGetTemperature") + ret = fn(handle, _nvmlTemperatureSensors_t(sensor), byref(c_temp)) + _nvmlCheckReturn(ret) + return c_temp.value + +def nvmlDeviceGetTemperatureThreshold(handle, threshold): + c_temp = c_uint() + fn = _nvmlGetFunctionPointer("nvmlDeviceGetTemperatureThreshold") + ret = fn(handle, _nvmlTemperatureThresholds_t(threshold), byref(c_temp)) + _nvmlCheckReturn(ret) + return c_temp.value + +def nvmlDeviceSetTemperatureThreshold(handle, threshold, temp): + c_temp = c_uint() + c_temp.value = temp + fn = _nvmlGetFunctionPointer("nvmlDeviceSetTemperatureThreshold") + ret = fn(handle, _nvmlTemperatureThresholds_t(threshold), byref(c_temp)) + _nvmlCheckReturn(ret) + return None + +def nvmlDeviceGetMarginTemperature(handle): + c_marginTempInfo = c_nvmlMarginTemperature_v1_t() + c_marginTempInfo.version = nvmlMarginTemperature_v1 + fn = _nvmlGetFunctionPointer("nvmlDeviceGetMarginTemperature") + ret = fn(handle, byref(c_marginTempInfo)) + _nvmlCheckReturn(ret) + return c_marginTempInfo.marginTemperature + +# DEPRECATED: Use nvmlDeviceGetPerformanceState instead; will be removed in CUDA 14.0 +def nvmlDeviceGetPowerState(handle): + c_pstate = _nvmlPstates_t() + fn = _nvmlGetFunctionPointer("nvmlDeviceGetPowerState") + ret = fn(handle, byref(c_pstate)) + _nvmlCheckReturn(ret) + return c_pstate.value + +def nvmlDeviceGetPerformanceState(handle): + c_pstate = _nvmlPstates_t() + fn = _nvmlGetFunctionPointer("nvmlDeviceGetPerformanceState") + ret = fn(handle, byref(c_pstate)) + _nvmlCheckReturn(ret) + return c_pstate.value + +# DEPRECATED: will be removed in CUDA 14.0 +def nvmlDeviceGetPowerManagementMode(handle): + c_pcapMode = _nvmlEnableState_t() + fn = _nvmlGetFunctionPointer("nvmlDeviceGetPowerManagementMode") + ret = fn(handle, byref(c_pcapMode)) + _nvmlCheckReturn(ret) + return c_pcapMode.value + +def nvmlDeviceGetPowerManagementLimit(handle): + c_limit = c_uint() + fn = _nvmlGetFunctionPointer("nvmlDeviceGetPowerManagementLimit") + ret = fn(handle, byref(c_limit)) + _nvmlCheckReturn(ret) + return c_limit.value + +# Added in 4.304 +def nvmlDeviceGetPowerManagementLimitConstraints(handle): + c_minLimit = c_uint() + c_maxLimit = c_uint() + fn = _nvmlGetFunctionPointer("nvmlDeviceGetPowerManagementLimitConstraints") + ret = fn(handle, byref(c_minLimit), byref(c_maxLimit)) + _nvmlCheckReturn(ret) + return [c_minLimit.value, c_maxLimit.value] + +# Added in 4.304 +def nvmlDeviceGetPowerManagementDefaultLimit(handle): + c_limit = c_uint() + fn = _nvmlGetFunctionPointer("nvmlDeviceGetPowerManagementDefaultLimit") + ret = fn(handle, byref(c_limit)) + _nvmlCheckReturn(ret) + return c_limit.value + + +# Added in 331 +def nvmlDeviceGetEnforcedPowerLimit(handle): + c_limit = c_uint() + fn = _nvmlGetFunctionPointer("nvmlDeviceGetEnforcedPowerLimit") + ret = fn(handle, byref(c_limit)) + _nvmlCheckReturn(ret) + return c_limit.value + +def nvmlDeviceGetPowerUsage(handle): + c_watts = c_uint() + fn = _nvmlGetFunctionPointer("nvmlDeviceGetPowerUsage") + ret = fn(handle, byref(c_watts)) + _nvmlCheckReturn(ret) + return c_watts.value + +def nvmlDeviceGetTotalEnergyConsumption(handle): + c_millijoules = c_uint64() + fn = _nvmlGetFunctionPointer("nvmlDeviceGetTotalEnergyConsumption") + ret = fn(handle, byref(c_millijoules)) + _nvmlCheckReturn(ret) + return c_millijoules.value + +# Added in 4.304 +def nvmlDeviceGetGpuOperationMode(handle): + c_currState = _nvmlGpuOperationMode_t() + c_pendingState = _nvmlGpuOperationMode_t() + fn = _nvmlGetFunctionPointer("nvmlDeviceGetGpuOperationMode") + ret = fn(handle, byref(c_currState), byref(c_pendingState)) + _nvmlCheckReturn(ret) + return [c_currState.value, c_pendingState.value] + +# Added in 4.304 +def nvmlDeviceGetCurrentGpuOperationMode(handle): + return nvmlDeviceGetGpuOperationMode(handle)[0] + +# Added in 4.304 +def nvmlDeviceGetPendingGpuOperationMode(handle): + return nvmlDeviceGetGpuOperationMode(handle)[1] + +def nvmlDeviceGetMemoryInfo(handle, version=None): + if not version: + c_memory = c_nvmlMemory_t() + fn = _nvmlGetFunctionPointer("nvmlDeviceGetMemoryInfo") + else: + c_memory = c_nvmlMemory_v2_t() + c_memory.version = version + fn = _nvmlGetFunctionPointer("nvmlDeviceGetMemoryInfo_v2") + ret = fn(handle, byref(c_memory)) + _nvmlCheckReturn(ret) + return c_memory + +def nvmlDeviceGetBAR1MemoryInfo(handle): + c_bar1_memory = c_nvmlBAR1Memory_t() + fn = _nvmlGetFunctionPointer("nvmlDeviceGetBAR1MemoryInfo") + ret = fn(handle, byref(c_bar1_memory)) + _nvmlCheckReturn(ret) + return c_bar1_memory + +def nvmlDeviceGetComputeMode(handle): + c_mode = _nvmlComputeMode_t() + fn = _nvmlGetFunctionPointer("nvmlDeviceGetComputeMode") + ret = fn(handle, byref(c_mode)) + _nvmlCheckReturn(ret) + return c_mode.value + +def nvmlDeviceGetCudaComputeCapability(handle): + c_major = c_int() + c_minor = c_int() + fn = _nvmlGetFunctionPointer("nvmlDeviceGetCudaComputeCapability") + ret = fn(handle, byref(c_major), byref(c_minor)) + _nvmlCheckReturn(ret) + return (c_major.value, c_minor.value) + +def nvmlDeviceGetEccMode(handle): + c_currState = _nvmlEnableState_t() + c_pendingState = _nvmlEnableState_t() + fn = _nvmlGetFunctionPointer("nvmlDeviceGetEccMode") + ret = fn(handle, byref(c_currState), byref(c_pendingState)) + _nvmlCheckReturn(ret) + return [c_currState.value, c_pendingState.value] + +# added to API +def nvmlDeviceGetCurrentEccMode(handle): + return nvmlDeviceGetEccMode(handle)[0] + +# added to API +def nvmlDeviceGetPendingEccMode(handle): + return nvmlDeviceGetEccMode(handle)[1] + +def nvmlDeviceGetDefaultEccMode(handle): + c_defaultState = _nvmlEnableState_t() + fn = _nvmlGetFunctionPointer("nvmlDeviceGetDefaultEccMode") + ret = fn(handle, byref(c_defaultState)) + _nvmlCheckReturn(ret) + return [c_defaultState.value] + +def nvmlDeviceGetTotalEccErrors(handle, errorType, counterType): + c_count = c_ulonglong() + fn = _nvmlGetFunctionPointer("nvmlDeviceGetTotalEccErrors") + ret = fn(handle, _nvmlMemoryErrorType_t(errorType), + _nvmlEccCounterType_t(counterType), byref(c_count)) + _nvmlCheckReturn(ret) + return c_count.value + +# DEPRECATED: Use nvmlDeviceGetMemoryErrorCounter instead; will be removed in CUDA 14.0 +def nvmlDeviceGetDetailedEccErrors(handle, errorType, counterType): + c_counts = c_nvmlEccErrorCounts_t() + fn = _nvmlGetFunctionPointer("nvmlDeviceGetDetailedEccErrors") + ret = fn(handle, _nvmlMemoryErrorType_t(errorType), + _nvmlEccCounterType_t(counterType), byref(c_counts)) + _nvmlCheckReturn(ret) + return c_counts + +# Added in 4.304 +def nvmlDeviceGetMemoryErrorCounter(handle, errorType, counterType, locationType): + c_count = c_ulonglong() + fn = _nvmlGetFunctionPointer("nvmlDeviceGetMemoryErrorCounter") + ret = fn(handle, + _nvmlMemoryErrorType_t(errorType), + _nvmlEccCounterType_t(counterType), + _nvmlMemoryLocation_t(locationType), + byref(c_count)) + _nvmlCheckReturn(ret) + return c_count.value + +def nvmlDeviceGetUtilizationRates(handle): + c_util = c_nvmlUtilization_t() + fn = _nvmlGetFunctionPointer("nvmlDeviceGetUtilizationRates") + ret = fn(handle, byref(c_util)) + _nvmlCheckReturn(ret) + return c_util + +def nvmlDeviceGetEncoderUtilization(handle): + c_util = c_uint() + c_samplingPeriod = c_uint() + fn = _nvmlGetFunctionPointer("nvmlDeviceGetEncoderUtilization") + ret = fn(handle, byref(c_util), byref(c_samplingPeriod)) + _nvmlCheckReturn(ret) + return [c_util.value, c_samplingPeriod.value] + +def nvmlDeviceGetDecoderUtilization(handle): + c_util = c_uint() + c_samplingPeriod = c_uint() + fn = _nvmlGetFunctionPointer("nvmlDeviceGetDecoderUtilization") + ret = fn(handle, byref(c_util), byref(c_samplingPeriod)) + _nvmlCheckReturn(ret) + return [c_util.value, c_samplingPeriod.value] + +def nvmlDeviceGetJpgUtilization(handle): + c_util = c_uint() + c_samplingPeriod = c_uint() + fn = _nvmlGetFunctionPointer("nvmlDeviceGetJpgUtilization") + ret = fn(handle, byref(c_util), byref(c_samplingPeriod)) + _nvmlCheckReturn(ret) + return [c_util.value, c_samplingPeriod.value] + +def nvmlDeviceGetOfaUtilization(handle): + c_util = c_uint() + c_samplingPeriod = c_uint() + fn = _nvmlGetFunctionPointer("nvmlDeviceGetOfaUtilization") + ret = fn(handle, byref(c_util), byref(c_samplingPeriod)) + _nvmlCheckReturn(ret) + return [c_util.value, c_samplingPeriod.value] + +def nvmlDeviceGetPcieReplayCounter(handle): + c_replay = c_uint() + fn = _nvmlGetFunctionPointer("nvmlDeviceGetPcieReplayCounter") + ret = fn(handle, byref(c_replay)) + _nvmlCheckReturn(ret) + return c_replay.value + +def nvmlDeviceGetDriverModel_v1(handle): + c_currModel = _nvmlDriverModel_t() + c_pendingModel = _nvmlDriverModel_t() + fn = _nvmlGetFunctionPointer("nvmlDeviceGetDriverModel") + ret = fn(handle, byref(c_currModel), byref(c_pendingModel)) + _nvmlCheckReturn(ret) + return [c_currModel.value, c_pendingModel.value] + +def nvmlDeviceGetDriverModel_v2(handle): + c_currModel = _nvmlDriverModel_t() + c_pendingModel = _nvmlDriverModel_t() + fn = _nvmlGetFunctionPointer("nvmlDeviceGetDriverModel_v2") + ret = fn(handle, byref(c_currModel), byref(c_pendingModel)) + _nvmlCheckReturn(ret) + return [c_currModel.value, c_pendingModel.value] + +def nvmlDeviceGetDriverModel(handle): + return nvmlDeviceGetDriverModel_v2(handle) + +# added to API +def nvmlDeviceGetCurrentDriverModel(handle): + return nvmlDeviceGetDriverModel(handle)[0] + +# added to API +def nvmlDeviceGetPendingDriverModel(handle): + return nvmlDeviceGetDriverModel(handle)[1] + +# Added in 2.285 +@convertStrBytes +def nvmlDeviceGetVbiosVersion(handle): + c_version = create_string_buffer(NVML_DEVICE_VBIOS_VERSION_BUFFER_SIZE) + fn = _nvmlGetFunctionPointer("nvmlDeviceGetVbiosVersion") + ret = fn(handle, c_version, c_uint(NVML_DEVICE_VBIOS_VERSION_BUFFER_SIZE)) + _nvmlCheckReturn(ret) + return c_version.value + +# Added in 2.285 +def nvmlDeviceGetComputeRunningProcesses_v2(handle): + # first call to get the size + c_count = c_uint(0) + fn = _nvmlGetFunctionPointer("nvmlDeviceGetComputeRunningProcesses_v2") + ret = fn(handle, byref(c_count), None) + if (ret == NVML_SUCCESS): + # special case, no running processes + return [] + elif (ret == NVML_ERROR_INSUFFICIENT_SIZE): + # typical case + # oversize the array incase more processes are created + c_count.value = c_count.value * 2 + 5 + proc_array = c_nvmlProcessInfo_v2_t * c_count.value + c_procs = proc_array() + # make the call again + ret = fn(handle, byref(c_count), c_procs) + _nvmlCheckReturn(ret) + procs = [] + for i in range(c_count.value): + # use an alternative struct for this object + obj = nvmlStructToFriendlyObject(c_procs[i]) + if (obj.usedGpuMemory == NVML_VALUE_NOT_AVAILABLE_ulonglong.value): + # special case for WDDM on Windows, see comment above + obj.usedGpuMemory = None + procs.append(obj) + return procs + else: + # error case + raise NVMLError(ret) + +# Added in 2.285 +def nvmlDeviceGetComputeRunningProcesses_v3(handle): + # first call to get the size + c_count = c_uint(0) + fn = _nvmlGetFunctionPointer("nvmlDeviceGetComputeRunningProcesses_v3") + ret = fn(handle, byref(c_count), None) + + if (ret == NVML_SUCCESS): + # special case, no running processes + return [] + elif (ret == NVML_ERROR_INSUFFICIENT_SIZE): + # typical case + # oversize the array incase more processes are created + c_count.value = c_count.value * 2 + 5 + proc_array = c_nvmlProcessInfo_v3_t * c_count.value + c_procs = proc_array() + + # make the call again + ret = fn(handle, byref(c_count), c_procs) + _nvmlCheckReturn(ret) + + procs = [] + for i in range(c_count.value): + # use an alternative struct for this object + obj = nvmlStructToFriendlyObject(c_procs[i]) + if (obj.usedGpuMemory == NVML_VALUE_NOT_AVAILABLE_ulonglong.value): + # special case for WDDM on Windows, see comment above + obj.usedGpuMemory = None + procs.append(obj) + + return procs + else: + # error case + raise NVMLError(ret) + +@throwOnVersionMismatch +def nvmlDeviceGetComputeRunningProcesses(handle): + return nvmlDeviceGetComputeRunningProcesses_v3(handle) + +def nvmlDeviceGetGraphicsRunningProcesses_v2(handle): + # first call to get the size + c_count = c_uint(0) + fn = _nvmlGetFunctionPointer("nvmlDeviceGetGraphicsRunningProcesses_v2") + ret = fn(handle, byref(c_count), None) + if (ret == NVML_SUCCESS): + # special case, no running processes + return [] + elif (ret == NVML_ERROR_INSUFFICIENT_SIZE): + # typical case + # oversize the array incase more processes are created + c_count.value = c_count.value * 2 + 5 + proc_array = c_nvmlProcessInfo_v2_t * c_count.value + c_procs = proc_array() + # make the call again + ret = fn(handle, byref(c_count), c_procs) + _nvmlCheckReturn(ret) + procs = [] + for i in range(c_count.value): + # use an alternative struct for this object + obj = nvmlStructToFriendlyObject(c_procs[i]) + if (obj.usedGpuMemory == NVML_VALUE_NOT_AVAILABLE_ulonglong.value): + # special case for WDDM on Windows, see comment above + obj.usedGpuMemory = None + procs.append(obj) + return procs + else: + # error case + raise NVMLError(ret) + +def nvmlDeviceGetGraphicsRunningProcesses_v3(handle): + # first call to get the size + c_count = c_uint(0) + fn = _nvmlGetFunctionPointer("nvmlDeviceGetGraphicsRunningProcesses_v3") + ret = fn(handle, byref(c_count), None) + + if (ret == NVML_SUCCESS): + # special case, no running processes + return [] + elif (ret == NVML_ERROR_INSUFFICIENT_SIZE): + # typical case + # oversize the array incase more processes are created + c_count.value = c_count.value * 2 + 5 + proc_array = c_nvmlProcessInfo_v3_t * c_count.value + c_procs = proc_array() + + # make the call again + ret = fn(handle, byref(c_count), c_procs) + _nvmlCheckReturn(ret) + + procs = [] + for i in range(c_count.value): + # use an alternative struct for this object + obj = nvmlStructToFriendlyObject(c_procs[i]) + if (obj.usedGpuMemory == NVML_VALUE_NOT_AVAILABLE_ulonglong.value): + # special case for WDDM on Windows, see comment above + obj.usedGpuMemory = None + procs.append(obj) + + return procs + else: + # error case + raise NVMLError(ret) + +@throwOnVersionMismatch +def nvmlDeviceGetGraphicsRunningProcesses(handle): + return nvmlDeviceGetGraphicsRunningProcesses_v3(handle) + +@throwOnVersionMismatch +def nvmlDeviceGetMPSComputeRunningProcesses(handle): + return nvmlDeviceGetMPSComputeRunningProcesses_v3(handle) + +def nvmlDeviceGetMPSComputeRunningProcesses_v2(handle): + # first call to get the size + c_count = c_uint(0) + fn = _nvmlGetFunctionPointer("nvmlDeviceGetMPSComputeRunningProcesses_v2") + ret = fn(handle, byref(c_count), None) + + if (ret == NVML_SUCCESS): + # special case, no running processes + return [] + elif (ret == NVML_ERROR_INSUFFICIENT_SIZE): + # typical case + # oversize the array incase more processes are created + c_count.value = c_count.value * 2 + 5 + proc_array = c_nvmlProcessInfo_v2_t * c_count.value + c_procs = proc_array() + + # make the call again + ret = fn(handle, byref(c_count), c_procs) + _nvmlCheckReturn(ret) + + procs = [] + for i in range(c_count.value): + # use an alternative struct for this object + obj = nvmlStructToFriendlyObject(c_procs[i]) + if (obj.usedGpuMemory == NVML_VALUE_NOT_AVAILABLE_ulonglong.value): + # special case for WDDM on Windows, see comment above + obj.usedGpuMemory = None + procs.append(obj) + + return procs + else: + # error case + raise NVMLError(ret) + +def nvmlDeviceGetMPSComputeRunningProcesses_v3(handle): + # first call to get the size + c_count = c_uint(0) + fn = _nvmlGetFunctionPointer("nvmlDeviceGetMPSComputeRunningProcesses_v3") + ret = fn(handle, byref(c_count), None) + + if (ret == NVML_SUCCESS): + # special case, no running processes + return [] + elif (ret == NVML_ERROR_INSUFFICIENT_SIZE): + # typical case + # oversize the array incase more processes are created + c_count.value = c_count.value * 2 + 5 + proc_array = c_nvmlProcessInfo_v3_t * c_count.value + c_procs = proc_array() + + # make the call again + ret = fn(handle, byref(c_count), c_procs) + _nvmlCheckReturn(ret) + + procs = [] + for i in range(c_count.value): + # use an alternative struct for this object + obj = nvmlStructToFriendlyObject(c_procs[i]) + if (obj.usedGpuMemory == NVML_VALUE_NOT_AVAILABLE_ulonglong.value): + # special case for WDDM on Windows, see comment above + obj.usedGpuMemory = None + procs.append(obj) + + return procs + else: + # error case + raise NVMLError(ret) + +def nvmlDeviceGetRunningProcessDetailList(handle, version, mode): + c_processDetailList = c_nvmlProcessDetailList_t() + c_processDetailList.version = version + c_processDetailList.mode = mode + + fn = _nvmlGetFunctionPointer("nvmlDeviceGetRunningProcessDetailList") + + # first call to get the size + ret = fn(handle, byref(c_processDetailList)) + if (ret == NVML_SUCCESS): + # special case, no running processes + return [] + elif (ret == NVML_ERROR_INSUFFICIENT_SIZE): + c_procs = c_nvmlProcessDetail_v1_t * c_processDetailList.numProcArrayEntries + c_processDetailList.procArray = cast((c_procs)(), POINTER(c_nvmlProcessDetail_v1_t)) + + # make the call again + ret = fn(handle, byref(c_processDetailList)) + _nvmlCheckReturn(ret) + + procs = [] + for i in range(c_processDetailList.numProcArrayEntries): + # use an alternative struct for this object + obj = c_processDetailList.procArray[i] + if (obj.usedGpuMemory == NVML_VALUE_NOT_AVAILABLE_ulonglong.value): + obj.usedGpuMemory = None + if (obj.usedGpuCcProtectedMemory == NVML_VALUE_NOT_AVAILABLE_ulonglong.value): + obj.usedGpuCcProtectedMemory = None + procs.append(obj) + + return procs + else: + # error case + raise NVMLError(ret) + +def nvmlDeviceGetAutoBoostedClocksEnabled(handle): + c_isEnabled = _nvmlEnableState_t() + c_defaultIsEnabled = _nvmlEnableState_t() + fn = _nvmlGetFunctionPointer("nvmlDeviceGetAutoBoostedClocksEnabled") + ret = fn(handle, byref(c_isEnabled), byref(c_defaultIsEnabled)) + _nvmlCheckReturn(ret) + return [c_isEnabled.value, c_defaultIsEnabled.value] + #Throws NVML_ERROR_NOT_SUPPORTED if hardware doesn't support setting auto boosted clocks + +## Set functions +def nvmlUnitSetLedState(unit, color): + fn = _nvmlGetFunctionPointer("nvmlUnitSetLedState") + ret = fn(unit, _nvmlLedColor_t(color)) + _nvmlCheckReturn(ret) + return None + +def nvmlDeviceSetPersistenceMode(handle, mode): + fn = _nvmlGetFunctionPointer("nvmlDeviceSetPersistenceMode") + ret = fn(handle, _nvmlEnableState_t(mode)) + _nvmlCheckReturn(ret) + return None + +def nvmlDeviceSetComputeMode(handle, mode): + fn = _nvmlGetFunctionPointer("nvmlDeviceSetComputeMode") + ret = fn(handle, _nvmlComputeMode_t(mode)) + _nvmlCheckReturn(ret) + return None + +def nvmlDeviceSetEccMode(handle, mode): + fn = _nvmlGetFunctionPointer("nvmlDeviceSetEccMode") + ret = fn(handle, _nvmlEnableState_t(mode)) + _nvmlCheckReturn(ret) + return None + +def nvmlDeviceClearEccErrorCounts(handle, counterType): + fn = _nvmlGetFunctionPointer("nvmlDeviceClearEccErrorCounts") + ret = fn(handle, _nvmlEccCounterType_t(counterType)) + _nvmlCheckReturn(ret) + return None + +def nvmlDeviceSetDriverModel(handle, model): + fn = _nvmlGetFunctionPointer("nvmlDeviceSetDriverModel") + ret = fn(handle, _nvmlDriverModel_t(model)) + _nvmlCheckReturn(ret) + return None + +def nvmlDeviceSetAutoBoostedClocksEnabled(handle, enabled): + fn = _nvmlGetFunctionPointer("nvmlDeviceSetAutoBoostedClocksEnabled") + ret = fn(handle, _nvmlEnableState_t(enabled)) + _nvmlCheckReturn(ret) + return None + #Throws NVML_ERROR_NOT_SUPPORTED if hardware doesn't support setting auto boosted clocks + +def nvmlDeviceSetDefaultAutoBoostedClocksEnabled(handle, enabled, flags): + fn = _nvmlGetFunctionPointer("nvmlDeviceSetDefaultAutoBoostedClocksEnabled") + ret = fn(handle, _nvmlEnableState_t(enabled), c_uint(flags)) + _nvmlCheckReturn(ret) + return None + #Throws NVML_ERROR_NOT_SUPPORTED if hardware doesn't support setting auto boosted clocks + +def nvmlDeviceSetGpuLockedClocks(handle, minGpuClockMHz, maxGpuClockMHz): + fn = _nvmlGetFunctionPointer("nvmlDeviceSetGpuLockedClocks") + ret = fn(handle, c_uint(minGpuClockMHz), c_uint(maxGpuClockMHz)) + _nvmlCheckReturn(ret) + return None + +def nvmlDeviceResetGpuLockedClocks(handle): + fn = _nvmlGetFunctionPointer("nvmlDeviceResetGpuLockedClocks") + ret = fn(handle) + _nvmlCheckReturn(ret) + return None + +def nvmlDeviceSetMemoryLockedClocks(handle, minMemClockMHz, maxMemClockMHz): + fn = _nvmlGetFunctionPointer("nvmlDeviceSetMemoryLockedClocks") + ret = fn(handle, c_uint(minMemClockMHz), c_uint(maxMemClockMHz)) + _nvmlCheckReturn(ret) + return None + +def nvmlDeviceResetMemoryLockedClocks(handle): + fn = _nvmlGetFunctionPointer("nvmlDeviceResetMemoryLockedClocks") + ret = fn(handle) + _nvmlCheckReturn(ret) + return None + +def nvmlDeviceGetClkMonStatus(handle, c_clkMonInfo=nvmlClkMonStatus_t()): + isReference = type(c_clkMonInfo) is not nvmlClkMonStatus_t + c_clkMonInfoRef = c_clkMonInfo if isReference else byref(c_clkMonInfo) + fn = _nvmlGetFunctionPointer("nvmlDeviceGetClkMonStatus") + ret = fn(handle, c_clkMonInfoRef) + _nvmlCheckReturn(ret) + return NVML_SUCCESS if isReference else c_clkMonInfo + +# Added in 4.304 +# DEPRECATED: Use nvmlDeviceSetMemoryLockedClocks for memory clocks and nvmlDeviceSetGpuLockedClocks for graphics clocks; will be removed in CUDA 14.0 +def nvmlDeviceSetApplicationsClocks(handle, maxMemClockMHz, maxGraphicsClockMHz): + fn = _nvmlGetFunctionPointer("nvmlDeviceSetApplicationsClocks") + ret = fn(handle, c_uint(maxMemClockMHz), c_uint(maxGraphicsClockMHz)) + _nvmlCheckReturn(ret) + return None + +# Added in 4.304 +# DEPRECATED: Use nvmlDeviceResetMemoryLockedClocks for Memory Clocks and nvmlDeviceResetGpuLockedClocks for Graphics Clocks; will be removed in CUDA 14.0 +def nvmlDeviceResetApplicationsClocks(handle): + fn = _nvmlGetFunctionPointer("nvmlDeviceResetApplicationsClocks") + ret = fn(handle) + _nvmlCheckReturn(ret) + return None + +# Added in 4.304 +def nvmlDeviceSetPowerManagementLimit(handle, limit): + fn = _nvmlGetFunctionPointer("nvmlDeviceSetPowerManagementLimit") + ret = fn(handle, c_uint(limit)) + _nvmlCheckReturn(ret) + return None + +# Added in 4.304 +def nvmlDeviceSetGpuOperationMode(handle, mode): + fn = _nvmlGetFunctionPointer("nvmlDeviceSetGpuOperationMode") + ret = fn(handle, _nvmlGpuOperationMode_t(mode)) + _nvmlCheckReturn(ret) + return None + +# Added in 2.285 +def nvmlEventSetCreate(): + fn = _nvmlGetFunctionPointer("nvmlEventSetCreate") + eventSet = c_nvmlEventSet_t() + ret = fn(byref(eventSet)) + _nvmlCheckReturn(ret) + return eventSet + +# Added in 2.285 +def nvmlDeviceRegisterEvents(handle, eventTypes, eventSet): + fn = _nvmlGetFunctionPointer("nvmlDeviceRegisterEvents") + ret = fn(handle, c_ulonglong(eventTypes), eventSet) + _nvmlCheckReturn(ret) + return None + +# Added in 2.285 +def nvmlDeviceGetSupportedEventTypes(handle): + c_eventTypes = c_ulonglong() + fn = _nvmlGetFunctionPointer("nvmlDeviceGetSupportedEventTypes") + ret = fn(handle, byref(c_eventTypes)) + _nvmlCheckReturn(ret) + return c_eventTypes.value + +# raises NVML_ERROR_TIMEOUT exception on timeout +def nvmlEventSetWait_v2(eventSet, timeoutms): + fn = _nvmlGetFunctionPointer("nvmlEventSetWait_v2") + data = c_nvmlEventData_t() + ret = fn(eventSet, byref(data), c_uint(timeoutms)) + _nvmlCheckReturn(ret) + return data + +def nvmlEventSetWait(eventSet, timeoutms): + return nvmlEventSetWait_v2(eventSet, timeoutms) + +# Added in 2.285 +def nvmlEventSetFree(eventSet): + fn = _nvmlGetFunctionPointer("nvmlEventSetFree") + ret = fn(eventSet) + _nvmlCheckReturn(ret) + return None + +# Added in 3.295 +def nvmlDeviceOnSameBoard(handle1, handle2): + fn = _nvmlGetFunctionPointer("nvmlDeviceOnSameBoard") + onSameBoard = c_int() + ret = fn(handle1, handle2, byref(onSameBoard)) + _nvmlCheckReturn(ret) + return (onSameBoard.value != 0) + +# Added in 3.295 +def nvmlDeviceGetCurrPcieLinkGeneration(handle): + fn = _nvmlGetFunctionPointer("nvmlDeviceGetCurrPcieLinkGeneration") + gen = c_uint() + ret = fn(handle, byref(gen)) + _nvmlCheckReturn(ret) + return gen.value + +# Added in 3.295 +def nvmlDeviceGetMaxPcieLinkGeneration(handle): + fn = _nvmlGetFunctionPointer("nvmlDeviceGetMaxPcieLinkGeneration") + gen = c_uint() + ret = fn(handle, byref(gen)) + _nvmlCheckReturn(ret) + return gen.value + +# Added in 3.295 +def nvmlDeviceGetCurrPcieLinkWidth(handle): + fn = _nvmlGetFunctionPointer("nvmlDeviceGetCurrPcieLinkWidth") + width = c_uint() + ret = fn(handle, byref(width)) + _nvmlCheckReturn(ret) + return width.value + +# Added in 3.295 +def nvmlDeviceGetMaxPcieLinkWidth(handle): + fn = _nvmlGetFunctionPointer("nvmlDeviceGetMaxPcieLinkWidth") + width = c_uint() + ret = fn(handle, byref(width)) + _nvmlCheckReturn(ret) + return width.value + +def nvmlDeviceGetGpuMaxPcieLinkGeneration(handle): + fn = _nvmlGetFunctionPointer("nvmlDeviceGetGpuMaxPcieLinkGeneration") + gen = c_uint() + ret = fn(handle, byref(gen)) + _nvmlCheckReturn(ret) + return gen.value + +# Added in 4.304 +# DEPRECATED: Use nvmlDeviceGetSupportedClocksEventReasons instead; will be removed in CUDA 14.0 +def nvmlDeviceGetSupportedClocksThrottleReasons(handle): + c_reasons= c_ulonglong() + fn = _nvmlGetFunctionPointer("nvmlDeviceGetSupportedClocksThrottleReasons") + ret = fn(handle, byref(c_reasons)) + _nvmlCheckReturn(ret) + return c_reasons.value + +def nvmlDeviceGetSupportedClocksEventReasons(handle): + c_reasons= c_ulonglong() + fn = _nvmlGetFunctionPointer("nvmlDeviceGetSupportedClocksEventReasons") + ret = fn(handle, byref(c_reasons)) + _nvmlCheckReturn(ret) + return c_reasons.value + +# Added in 4.304 +# DEPRECATED: Use nvmlDeviceGetCurrentClocksEventReasons instead; will be removed in CUDA 14.0 +def nvmlDeviceGetCurrentClocksThrottleReasons(handle): + c_reasons= c_ulonglong() + fn = _nvmlGetFunctionPointer("nvmlDeviceGetCurrentClocksThrottleReasons") + ret = fn(handle, byref(c_reasons)) + _nvmlCheckReturn(ret) + return c_reasons.value + +def nvmlDeviceGetCurrentClocksEventReasons(handle): + c_reasons= c_ulonglong() + fn = _nvmlGetFunctionPointer("nvmlDeviceGetCurrentClocksEventReasons") + ret = fn(handle, byref(c_reasons)) + _nvmlCheckReturn(ret) + return c_reasons.value + +# Added in 5.319 +def nvmlDeviceGetIndex(handle): + fn = _nvmlGetFunctionPointer("nvmlDeviceGetIndex") + c_index = c_uint() + ret = fn(handle, byref(c_index)) + _nvmlCheckReturn(ret) + return c_index.value + +# Added in 5.319 +def nvmlDeviceGetAccountingMode(handle): + c_mode = _nvmlEnableState_t() + fn = _nvmlGetFunctionPointer("nvmlDeviceGetAccountingMode") + ret = fn(handle, byref(c_mode)) + _nvmlCheckReturn(ret) + return c_mode.value + +def nvmlDeviceSetAccountingMode(handle, mode): + fn = _nvmlGetFunctionPointer("nvmlDeviceSetAccountingMode") + ret = fn(handle, _nvmlEnableState_t(mode)) + _nvmlCheckReturn(ret) + return None + +def nvmlDeviceClearAccountingPids(handle): + fn = _nvmlGetFunctionPointer("nvmlDeviceClearAccountingPids") + ret = fn(handle) + _nvmlCheckReturn(ret) + return None + +def nvmlDeviceGetAccountingStats(handle, pid): + stats = c_nvmlAccountingStats_t() + fn = _nvmlGetFunctionPointer("nvmlDeviceGetAccountingStats") + ret = fn(handle, c_uint(pid), byref(stats)) + _nvmlCheckReturn(ret) + if (stats.maxMemoryUsage == NVML_VALUE_NOT_AVAILABLE_ulonglong.value): + # special case for WDDM on Windows, see comment above + stats.maxMemoryUsage = None + return stats + +def nvmlDeviceGetAccountingStats_v2(handle, pid): + stats = c_nvmlAccountingStats_v2_t() + stats.pid = c_uint(pid) + fn = _nvmlGetFunctionPointer("nvmlDeviceGetAccountingStats_v2") + ret = fn(handle, byref(stats)) + _nvmlCheckReturn(ret) + return stats + +def nvmlDeviceGetAccountingPids(handle): + count = c_uint(nvmlDeviceGetAccountingBufferSize(handle)) + pids = (c_uint * count.value)() + fn = _nvmlGetFunctionPointer("nvmlDeviceGetAccountingPids") + ret = fn(handle, byref(count), pids) + _nvmlCheckReturn(ret) + return list(map(int, pids[0:count.value])) + +def nvmlDeviceGetAccountingBufferSize(handle): + bufferSize = c_uint() + fn = _nvmlGetFunctionPointer("nvmlDeviceGetAccountingBufferSize") + ret = fn(handle, byref(bufferSize)) + _nvmlCheckReturn(ret) + return int(bufferSize.value) + +def nvmlDeviceGetRetiredPages(device, sourceFilter): + c_source = _nvmlPageRetirementCause_t(sourceFilter) + c_count = c_uint(0) + fn = _nvmlGetFunctionPointer("nvmlDeviceGetRetiredPages") + + # First call will get the size + ret = fn(device, c_source, byref(c_count), None) + + # this should only fail with insufficient size + if ((ret != NVML_SUCCESS) and + (ret != NVML_ERROR_INSUFFICIENT_SIZE)): + raise NVMLError(ret) + + # call again with a buffer + # oversize the array for the rare cases where additional pages + # are retired between NVML calls + c_count.value = c_count.value * 2 + 5 + page_array = c_ulonglong * c_count.value + c_pages = page_array() + ret = fn(device, c_source, byref(c_count), c_pages) + _nvmlCheckReturn(ret) + return list(map(int, c_pages[0:c_count.value])) + +def nvmlDeviceGetRetiredPages_v2(device, sourceFilter): + c_source = _nvmlPageRetirementCause_t(sourceFilter) + c_count = c_uint(0) + fn = _nvmlGetFunctionPointer("nvmlDeviceGetRetiredPages_v2") + + # First call will get the size + ret = fn(device, c_source, byref(c_count), None) + + # this should only fail with insufficient size + if ((ret != NVML_SUCCESS) and + (ret != NVML_ERROR_INSUFFICIENT_SIZE)): + raise NVMLError(ret) + + # call again with a buffer + # oversize the array for the rare cases where additional pages + # are retired between NVML calls + c_count.value = c_count.value * 2 + 5 + page_array = c_ulonglong * c_count.value + c_pages = page_array() + times_array = c_ulonglong * c_count.value + c_times = times_array() + ret = fn(device, c_source, byref(c_count), c_pages, c_times) + _nvmlCheckReturn(ret) + return [ { 'address': int(c_pages[i]), 'timestamp': int(c_times[i]) } for i in range(c_count.value) ]; + +def nvmlDeviceGetRetiredPagesPendingStatus(device): + c_pending = _nvmlEnableState_t() + fn = _nvmlGetFunctionPointer("nvmlDeviceGetRetiredPagesPendingStatus") + ret = fn(device, byref(c_pending)) + _nvmlCheckReturn(ret) + return int(c_pending.value) + +def nvmlDeviceGetAPIRestriction(device, apiType): + c_permission = _nvmlEnableState_t() + fn = _nvmlGetFunctionPointer("nvmlDeviceGetAPIRestriction") + ret = fn(device, _nvmlRestrictedAPI_t(apiType), byref(c_permission)) + _nvmlCheckReturn(ret) + return int(c_permission.value) + +def nvmlDeviceSetAPIRestriction(handle, apiType, isRestricted): + fn = _nvmlGetFunctionPointer("nvmlDeviceSetAPIRestriction") + ret = fn(handle, _nvmlRestrictedAPI_t(apiType), _nvmlEnableState_t(isRestricted)) + _nvmlCheckReturn(ret) + return None + +def nvmlDeviceGetBridgeChipInfo(handle): + bridgeHierarchy = c_nvmlBridgeChipHierarchy_t() + fn = _nvmlGetFunctionPointer("nvmlDeviceGetBridgeChipInfo") + ret = fn(handle, byref(bridgeHierarchy)) + _nvmlCheckReturn(ret) + return bridgeHierarchy + +def nvmlDeviceGetSamples(device, sampling_type, timeStamp): + c_sampling_type = _nvmlSamplingType_t(sampling_type) + c_time_stamp = c_ulonglong(timeStamp) + c_sample_count = c_uint(0) + c_sample_value_type = _nvmlValueType_t() + fn = _nvmlGetFunctionPointer("nvmlDeviceGetSamples") + + ## First Call gets the size + ret = fn(device, c_sampling_type, c_time_stamp, byref(c_sample_value_type), byref(c_sample_count), None) + + # Stop if this fails + if (ret != NVML_SUCCESS): + raise NVMLError(ret) + + sampleArray = c_sample_count.value * c_nvmlSample_t + c_samples = sampleArray() + ret = fn(device, c_sampling_type, c_time_stamp, byref(c_sample_value_type), byref(c_sample_count), c_samples) + _nvmlCheckReturn(ret) + return (c_sample_value_type.value, c_samples[0:c_sample_count.value]) + +# DEPRECATED: Use nvmlDEviceGetFieldValues instead to query this data; will be removed in CUDA 14.0 +def nvmlDeviceGetViolationStatus(device, perfPolicyType): + c_perfPolicy_type = _nvmlPerfPolicyType_t(perfPolicyType) + c_violTime = c_nvmlViolationTime_t() + fn = _nvmlGetFunctionPointer("nvmlDeviceGetViolationStatus") + + ## Invoke the method to get violation time + ret = fn(device, c_perfPolicy_type, byref(c_violTime)) + _nvmlCheckReturn(ret) + return c_violTime + +def nvmlDeviceGetPcieThroughput(device, counter): + c_util = c_uint() + fn = _nvmlGetFunctionPointer("nvmlDeviceGetPcieThroughput") + ret = fn(device, _nvmlPcieUtilCounter_t(counter), byref(c_util)) + _nvmlCheckReturn(ret) + return c_util.value + +def nvmlSystemGetTopologyGpuSet(cpuNumber): + c_count = c_uint(0) + fn = _nvmlGetFunctionPointer("nvmlSystemGetTopologyGpuSet") + + # First call will get the size + ret = fn(cpuNumber, byref(c_count), None) + + if ret != NVML_SUCCESS: + raise NVMLError(ret) + # call again with a buffer + device_array = c_nvmlDevice_t * c_count.value + c_devices = device_array() + ret = fn(cpuNumber, byref(c_count), c_devices) + _nvmlCheckReturn(ret) + return list(c_devices[0:c_count.value]) + +def nvmlDeviceGetTopologyNearestGpus(device, level): + c_count = c_uint(0) + fn = _nvmlGetFunctionPointer("nvmlDeviceGetTopologyNearestGpus") + + # First call will get the size + ret = fn(device, level, byref(c_count), None) + + if ret != NVML_SUCCESS: + raise NVMLError(ret) + + # call again with a buffer + device_array = c_nvmlDevice_t * c_count.value + c_devices = device_array() + ret = fn(device, level, byref(c_count), c_devices) + _nvmlCheckReturn(ret) + return list(c_devices[0:c_count.value]) + +def nvmlDeviceGetTopologyCommonAncestor(device1, device2): + c_level = _nvmlGpuTopologyLevel_t() + fn = _nvmlGetFunctionPointer("nvmlDeviceGetTopologyCommonAncestor") + ret = fn(device1, device2, byref(c_level)) + _nvmlCheckReturn(ret) + return c_level.value + +# DEPRECATED: Use nvmlDeviceGetFieldValues with NVML_FI_DEV_NVLINK_THROUGHPUT_* as field values instead; will be removed in CUDA 14.0 +def nvmlDeviceGetNvLinkUtilizationCounter(device, link, counter): + c_rxcounter = c_ulonglong() + c_txcounter = c_ulonglong() + fn = _nvmlGetFunctionPointer("nvmlDeviceGetNvLinkUtilizationCounter") + ret = fn(device, link, counter, byref(c_rxcounter), byref(c_txcounter)) + _nvmlCheckReturn(ret) + return (c_rxcounter.value, c_txcounter.value) + +# DEPRECATED: Freezing NVLINK utilization counters is no longer supported; will be removed in CUDA 14.0 +def nvmlDeviceFreezeNvLinkUtilizationCounter(device, link, counter, freeze): + fn = _nvmlGetFunctionPointer("nvmlDeviceFreezeNvLinkUtilizationCounter") + ret = fn(device, link, counter, freeze) + _nvmlCheckReturn(ret) + return None + +# DEPRECATED: Resetting NVLINK utilization counters is no longer supported; will be removed in CUDA 14.0 +def nvmlDeviceResetNvLinkUtilizationCounter(device, link, counter): + fn = _nvmlGetFunctionPointer("nvmlDeviceResetNvLinkUtilizationCounter") + ret = fn(device, link, counter) + _nvmlCheckReturn(ret) + return None + +# DEPRECATED: Setting utilization counter control is no longer supported; will be removed in CUDA 14.0 +def nvmlDeviceSetNvLinkUtilizationControl(device, link, counter, control, reset): + fn = _nvmlGetFunctionPointer("nvmlDeviceSetNvLinkUtilizationControl") + ret = fn(device, link, counter, byref(control), reset) + _nvmlCheckReturn(ret) + return None + +# DEPRECATED: Getting utilization counter control is no longer supported; will be removed in CUDA 14.0 +def nvmlDeviceGetNvLinkUtilizationControl(device, link, counter): + c_control = nvmlNvLinkUtilizationControl_t() + fn = _nvmlGetFunctionPointer("nvmlDeviceGetNvLinkUtilizationControl") + ret = fn(device, link, counter, byref(c_control)) + _nvmlCheckReturn(ret) + return c_control + +def nvmlDeviceGetNvLinkCapability(device, link, capability): + c_capResult = c_uint() + fn = _nvmlGetFunctionPointer("nvmlDeviceGetNvLinkCapability") + ret = fn(device, link, capability, byref(c_capResult)) + _nvmlCheckReturn(ret) + return c_capResult.value + +def nvmlDeviceGetNvLinkErrorCounter(device, link, counter): + c_result = c_ulonglong() + fn = _nvmlGetFunctionPointer("nvmlDeviceGetNvLinkErrorCounter") + ret = fn(device, link, counter, byref(c_result)) + _nvmlCheckReturn(ret) + return c_result.value + +def nvmlDeviceResetNvLinkErrorCounters(device, link): + fn = _nvmlGetFunctionPointer("nvmlDeviceResetNvLinkErrorCounters") + ret = fn(device, link) + _nvmlCheckReturn(ret) + return None + +def nvmlDeviceGetNvLinkRemotePciInfo(device, link): + c_pci = nvmlPciInfo_t() + fn = _nvmlGetFunctionPointer("nvmlDeviceGetNvLinkRemotePciInfo_v2") + ret = fn(device, link, byref(c_pci)) + _nvmlCheckReturn(ret) + return c_pci + +def nvmlDeviceGetNvLinkRemoteDeviceType(handle, link): + c_type = _nvmlNvLinkDeviceType_t() + fn = _nvmlGetFunctionPointer("nvmlDeviceGetNvLinkRemoteDeviceType") + ret = fn(handle, link, byref(c_type)) + _nvmlCheckReturn(ret) + return c_type.value + +def nvmlDeviceGetNvLinkState(device, link): + c_isActive = c_uint() + fn = _nvmlGetFunctionPointer("nvmlDeviceGetNvLinkState") + ret = fn(device, link, byref(c_isActive)) + _nvmlCheckReturn(ret) + return c_isActive.value + +def nvmlDeviceGetNvLinkVersion(device, link): + c_version = c_uint() + fn = _nvmlGetFunctionPointer("nvmlDeviceGetNvLinkVersion") + ret = fn(device, link, byref(c_version)) + _nvmlCheckReturn(ret) + return c_version.value + +def nvmlDeviceModifyDrainState(pciInfo, newState): + fn = _nvmlGetFunctionPointer("nvmlDeviceModifyDrainState") + ret = fn(pointer(pciInfo), newState) + _nvmlCheckReturn(ret) + return None + +def nvmlDeviceQueryDrainState(pciInfo): + c_newState = c_uint() + fn = _nvmlGetFunctionPointer("nvmlDeviceQueryDrainState") + ret = fn(pointer(pciInfo), byref(c_newState)) + _nvmlCheckReturn(ret) + return c_newState.value + +def nvmlDeviceRemoveGpu(pciInfo): + fn = _nvmlGetFunctionPointer("nvmlDeviceRemoveGpu") + ret = fn(pointer(pciInfo)) + _nvmlCheckReturn(ret) + return None + +def nvmlDeviceDiscoverGpus(pciInfo): + fn = _nvmlGetFunctionPointer("nvmlDeviceDiscoverGpus") + ret = fn(pointer(pciInfo)) + _nvmlCheckReturn(ret) + return None + +def nvmlDeviceGetFieldValues(handle, fieldIds): + values_arr = c_nvmlFieldValue_t * len(fieldIds) + values = values_arr() + fn = _nvmlGetFunctionPointer("nvmlDeviceGetFieldValues") + + for i, fieldId in enumerate(fieldIds): + try: + (values[i].fieldId, values[i].scopeId) = fieldId + except TypeError: + values[i].fieldId = fieldId + + ret = fn(handle, c_int32(len(fieldIds)), byref(values)) + _nvmlCheckReturn(ret) + return values + +def nvmlDeviceClearFieldValues(handle, fieldIds): + values_arr = c_nvmlFieldValue_t * len(fieldIds) + values = values_arr() + fn = _nvmlGetFunctionPointer("nvmlDeviceClearFieldValues") + + for i, fieldId in enumerate(fieldIds): + try: + (values[i].fieldId, values[i].scopeId) = fieldId + except TypeError: + values[i].fieldId = fieldId + + ret = fn(handle, c_int32(len(fieldIds)), byref(values)) + _nvmlCheckReturn(ret) + return values + +def nvmlDeviceGetVirtualizationMode(handle): + c_virtualization_mode = c_ulonglong() + fn = _nvmlGetFunctionPointer("nvmlDeviceGetVirtualizationMode") + ret = fn(handle, byref(c_virtualization_mode)) + _nvmlCheckReturn(ret) + return c_virtualization_mode.value + +def nvmlDeviceSetVirtualizationMode(handle, virtualization_mode): + fn = _nvmlGetFunctionPointer("nvmlDeviceSetVirtualizationMode") + return fn(handle, virtualization_mode) + +def nvmlDeviceGetVgpuHeterogeneousMode(handle): + c_vgpuHeterogeneousMode = c_nvmlVgpuHeterogeneousMode_v1_t(0) + c_vgpuHeterogeneousMode.version = VgpuHeterogeneousMode_v1 + fn = _nvmlGetFunctionPointer("nvmlDeviceGetVgpuHeterogeneousMode") + ret = fn(handle, byref(c_vgpuHeterogeneousMode)) + _nvmlCheckReturn(ret) + return c_vgpuHeterogeneousMode.mode + +def nvmlDeviceSetVgpuHeterogeneousMode(handle, heterogeneous_mode): + c_vgpuHeterogeneousMode = c_nvmlVgpuHeterogeneousMode_v1_t(0) + c_vgpuHeterogeneousMode.version = VgpuHeterogeneousMode_v1 + c_vgpuHeterogeneousMode.mode = heterogeneous_mode + fn = _nvmlGetFunctionPointer("nvmlDeviceSetVgpuHeterogeneousMode") + ret = fn(handle, byref(c_vgpuHeterogeneousMode)) + _nvmlCheckReturn(ret) + return NVML_SUCCESS + +def nvmlVgpuInstanceGetPlacementId(vgpuInstance): + c_placement = c_nvmlVgpuPlacementId_v1_t(0) + c_placement.version = VgpuPlacementId_v1 + fn = _nvmlGetFunctionPointer("nvmlVgpuInstanceGetPlacementId") + ret = fn(vgpuInstance, byref(c_placement)) + _nvmlCheckReturn(ret) + return c_placement.placementId + +def nvmlDeviceGetVgpuTypeSupportedPlacements(handle, vgpuTypeId, mode=0, version=1): + c_max_instances = c_uint(0) + fn = _nvmlGetFunctionPointer("nvmlVgpuTypeGetMaxInstances") + ret = fn(handle, vgpuTypeId, byref(c_max_instances)) + _nvmlCheckReturn(ret) + + if version == 2: + c_vgpu_placements = c_nvmlVgpuPlacementList_v2_t() + c_vgpu_placements.version = VgpuPlacementList_v2 + c_vgpu_placements.count = c_max_instances.value + c_vgpu_placements.mode = mode + elif version == 1: + c_vgpu_placements = c_nvmlVgpuPlacementList_v1_t() + c_vgpu_placements.version = VgpuPlacementList_v1 + else: + raise NVMLError(NVML_ERROR_ARGUMENT_VERSION_MISMATCH) + + c_placements = c_uint * c_max_instances.value + c_vgpu_placements.placementIds = c_placements() + fn = _nvmlGetFunctionPointer("nvmlDeviceGetVgpuTypeSupportedPlacements") + ret = fn(handle, vgpuTypeId, byref(c_vgpu_placements)) + _nvmlCheckReturn(ret) + return c_vgpu_placements + +def nvmlDeviceGetVgpuTypeCreatablePlacements(handle, vgpuTypeId, version=1): + c_max_instances = c_uint(0) + fn = _nvmlGetFunctionPointer("nvmlVgpuTypeGetMaxInstances") + ret = fn(handle, vgpuTypeId, byref(c_max_instances)) + _nvmlCheckReturn(ret) + + if version == 2: + c_vgpu_placements = c_nvmlVgpuPlacementList_v2_t() + c_vgpu_placements.version = VgpuPlacementList_v2 + c_vgpu_placements.count = c_max_instances.value + elif version == 1: + c_vgpu_placements = c_nvmlVgpuPlacementList_v1_t() + c_vgpu_placements.version = VgpuPlacementList_v1 + + c_placements = c_uint * c_max_instances.value + c_vgpu_placements.placementIds = c_placements() + fn = _nvmlGetFunctionPointer("nvmlDeviceGetVgpuTypeCreatablePlacements") + ret = fn(handle, vgpuTypeId, byref(c_vgpu_placements)) + _nvmlCheckReturn(ret) + return c_vgpu_placements + +def nvmlGetVgpuDriverCapabilities(capability): + c_capResult = c_uint() + fn = _nvmlGetFunctionPointer("nvmlGetVgpuDriverCapabilities") + ret = fn(_nvmlVgpuDriverCapability_t(capability), byref(c_capResult)) + _nvmlCheckReturn(ret) + return c_capResult.value + +def nvmlDeviceGetVgpuCapabilities(handle, capability): + c_capResult = c_uint() + fn = _nvmlGetFunctionPointer("nvmlDeviceGetVgpuCapabilities") + ret = fn(handle, _nvmlDeviceVgpuCapability_t(capability), byref(c_capResult)) + _nvmlCheckReturn(ret) + return c_capResult.value + +def nvmlDeviceSetVgpuCapabilities(handle, capability, state): + fn = _nvmlGetFunctionPointer("nvmlDeviceSetVgpuCapabilities") + ret = fn(handle, _nvmlDeviceVgpuCapability_t(capability), state) + _nvmlCheckReturn(ret) + return NVML_SUCCESS + +def nvmlDeviceVgpuForceGspUnload(handle): + fn = _nvmlGetFunctionPointer("nvmlDeviceVgpuForceGspUnload") + ret = fn(handle) + _nvmlCheckReturn(ret) + return NVML_SUCCESS + +def nvmlDeviceGetSupportedVgpus(handle): + # first call to get the size + c_vgpu_count = c_uint(0) + + fn = _nvmlGetFunctionPointer("nvmlDeviceGetSupportedVgpus") + ret = fn(handle, byref(c_vgpu_count), None) + + if (ret == NVML_SUCCESS): + # special case, no supported vGPUs + return [] + elif (ret == NVML_ERROR_INSUFFICIENT_SIZE): + # typical case + vgpu_type_ids_array = _nvmlVgpuTypeId_t * c_vgpu_count.value + c_vgpu_type_ids = vgpu_type_ids_array() + + # make the call again + ret = fn(handle, byref(c_vgpu_count), c_vgpu_type_ids) + _nvmlCheckReturn(ret) + vgpus = [] + for i in range(c_vgpu_count.value): + vgpus.append(c_vgpu_type_ids[i]) + return vgpus + else: + # error case + raise NVMLError(ret) + +def nvmlDeviceGetCreatableVgpus(handle): + # first call to get the size + c_vgpu_count = c_uint(0) + + fn = _nvmlGetFunctionPointer("nvmlDeviceGetCreatableVgpus") + ret = fn(handle, byref(c_vgpu_count), None) + + if (ret == NVML_SUCCESS): + # special case, no supported vGPUs + return [] + elif (ret == NVML_ERROR_INSUFFICIENT_SIZE): + # typical case + vgpu_type_ids_array = _nvmlVgpuTypeId_t * c_vgpu_count.value + c_vgpu_type_ids = vgpu_type_ids_array() + + # make the call again + ret = fn(handle, byref(c_vgpu_count), c_vgpu_type_ids) + _nvmlCheckReturn(ret) + vgpus = [] + for i in range(c_vgpu_count.value): + vgpus.append(c_vgpu_type_ids[i]) + return vgpus + else: + # error case + raise NVMLError(ret) + +def nvmlVgpuTypeGetGpuInstanceProfileId(vgpuTypeId): + c_profile_id = c_uint(0) + fn = _nvmlGetFunctionPointer("nvmlVgpuTypeGetGpuInstanceProfileId") + ret = fn(vgpuTypeId, byref(c_profile_id)) + _nvmlCheckReturn(ret) + return (c_profile_id.value) + +@convertStrBytes +def nvmlVgpuTypeGetClass(vgpuTypeId): + c_class = create_string_buffer(NVML_DEVICE_NAME_BUFFER_SIZE) + c_buffer_size = c_uint(NVML_DEVICE_NAME_BUFFER_SIZE) + fn = _nvmlGetFunctionPointer("nvmlVgpuTypeGetClass") + ret = fn(vgpuTypeId, c_class, byref(c_buffer_size)) + _nvmlCheckReturn(ret) + return c_class.value + +@convertStrBytes +def nvmlVgpuTypeGetName(vgpuTypeId): + c_name = create_string_buffer(NVML_DEVICE_NAME_BUFFER_SIZE) + c_buffer_size = c_uint(NVML_DEVICE_NAME_BUFFER_SIZE) + fn = _nvmlGetFunctionPointer("nvmlVgpuTypeGetName") + ret = fn(vgpuTypeId, c_name, byref(c_buffer_size)) + _nvmlCheckReturn(ret) + return c_name.value + +def nvmlVgpuTypeGetDeviceID(vgpuTypeId): + c_device_id = c_ulonglong(0) + c_subsystem_id = c_ulonglong(0) + fn = _nvmlGetFunctionPointer("nvmlVgpuTypeGetDeviceID") + ret = fn(vgpuTypeId, byref(c_device_id), byref(c_subsystem_id)) + _nvmlCheckReturn(ret) + return (c_device_id.value, c_subsystem_id.value) + +def nvmlVgpuTypeGetFramebufferSize(vgpuTypeId): + c_fb_size = c_ulonglong(0) + fn = _nvmlGetFunctionPointer("nvmlVgpuTypeGetFramebufferSize") + ret = fn(vgpuTypeId, byref(c_fb_size)) + _nvmlCheckReturn(ret) + return c_fb_size.value + +def nvmlVgpuTypeGetNumDisplayHeads(vgpuTypeId): + c_num_heads = c_uint(0) + fn = _nvmlGetFunctionPointer("nvmlVgpuTypeGetNumDisplayHeads") + ret = fn(vgpuTypeId, byref(c_num_heads)) + _nvmlCheckReturn(ret) + return c_num_heads.value + +def nvmlVgpuTypeGetResolution(vgpuTypeId): + c_xdim = c_uint(0) + c_ydim = c_uint(0) + fn = _nvmlGetFunctionPointer("nvmlVgpuTypeGetResolution") + ret = fn(vgpuTypeId, 0, byref(c_xdim), byref(c_ydim)) + _nvmlCheckReturn(ret) + return (c_xdim.value, c_ydim.value) + +@convertStrBytes +def nvmlVgpuTypeGetLicense(vgpuTypeId): + c_license = create_string_buffer(NVML_GRID_LICENSE_BUFFER_SIZE) + c_buffer_size = c_uint(NVML_GRID_LICENSE_BUFFER_SIZE) + fn = _nvmlGetFunctionPointer("nvmlVgpuTypeGetLicense") + ret = fn(vgpuTypeId, c_license, c_buffer_size) + _nvmlCheckReturn(ret) + return c_license.value + +def nvmlVgpuTypeGetFrameRateLimit(vgpuTypeId): + c_frl_config = c_uint(0) + fn = _nvmlGetFunctionPointer("nvmlVgpuTypeGetFrameRateLimit") + ret = fn(vgpuTypeId, byref(c_frl_config)) + _nvmlCheckReturn(ret) + return c_frl_config.value + +def nvmlVgpuTypeGetGspHeapSize(vgpuTypeId): + c_gsp_heap = c_uint(0) + fn = _nvmlGetFunctionPointer("nvmlVgpuTypeGetGspHeapSize") + ret = fn(vgpuTypeId, byref(c_gsp_heap)) + _nvmlCheckReturn(ret) + return c_gsp_heap.value + +def nvmlVgpuTypeGetFbReservation(vgpuTypeId): + c_fb_reservation = c_uint(0) + fn = _nvmlGetFunctionPointer("nvmlVgpuTypeGetFbReservation") + ret = fn(vgpuTypeId, byref(c_fb_reservation)) + _nvmlCheckReturn(ret) + return c_fb_reservation.value + +def nvmlVgpuInstanceGetRuntimeStateSize(vgpuInstance): + c_runtime_state = nvmlVgpuRuntimeState_v1_t() + c_runtime_state.version = VgpuRuntimeState_v1 + fn = _nvmlGetFunctionPointer("nvmlVgpuInstanceGetRuntimeStateSize") + ret = fn(vgpuInstance, byref(c_runtime_state)) + _nvmlCheckReturn(ret) + return c_runtime_state + +def nvmlVgpuTypeGetMaxInstances(handle, vgpuTypeId): + c_max_instances = c_uint(0) + fn = _nvmlGetFunctionPointer("nvmlVgpuTypeGetMaxInstances") + ret = fn(handle, vgpuTypeId, byref(c_max_instances)) + _nvmlCheckReturn(ret) + return c_max_instances.value + +def nvmlVgpuTypeGetMaxInstancesPerVm(vgpuTypeId): + c_max_instances_per_vm = c_uint(0) + fn = _nvmlGetFunctionPointer("nvmlVgpuTypeGetMaxInstancesPerVm") + ret = fn(vgpuTypeId, byref(c_max_instances_per_vm)) + _nvmlCheckReturn(ret) + return c_max_instances_per_vm.value + +def nvmlVgpuTypeGetBAR1Info(vgpuTypeId): + c_bar1Info = c_nvmlVgpuTypeBar1Info_v1_t(0) + c_bar1Info.version = VgpuTypeBar1Info_v1 + fn = _nvmlGetFunctionPointer("nvmlVgpuTypeGetBAR1Info") + ret = fn(vgpuTypeId, byref(c_bar1Info)) + _nvmlCheckReturn(ret) + return c_bar1Info + +def nvmlDeviceGetActiveVgpus(handle): + # first call to get the size + c_vgpu_count = c_uint(0) + + fn = _nvmlGetFunctionPointer("nvmlDeviceGetActiveVgpus") + ret = fn(handle, byref(c_vgpu_count), None) + + if (ret == NVML_SUCCESS): + # special case, no active vGPUs + return [] + elif (ret == NVML_ERROR_INSUFFICIENT_SIZE): + # typical case + vgpu_instance_array = _nvmlVgpuInstance_t * c_vgpu_count.value + c_vgpu_instances = vgpu_instance_array() + + # make the call again + ret = fn(handle, byref(c_vgpu_count), c_vgpu_instances) + _nvmlCheckReturn(ret) + vgpus = [] + for i in range(c_vgpu_count.value): + vgpus.append(c_vgpu_instances[i]) + return vgpus + else: + # error case + raise NVMLError(ret) + +@convertStrBytes +def nvmlVgpuInstanceGetVmID(vgpuInstance): + c_vm_id = create_string_buffer(NVML_DEVICE_UUID_BUFFER_SIZE) + c_buffer_size = c_uint(NVML_GRID_LICENSE_BUFFER_SIZE) + c_vm_id_type = c_uint(0) + fn = _nvmlGetFunctionPointer("nvmlVgpuInstanceGetVmID") + ret = fn(vgpuInstance, byref(c_vm_id), c_buffer_size, byref(c_vm_id_type)) + _nvmlCheckReturn(ret) + return (c_vm_id.value, c_vm_id_type.value) + +@convertStrBytes +def nvmlVgpuInstanceGetUUID(vgpuInstance): + c_uuid = create_string_buffer(NVML_DEVICE_UUID_BUFFER_SIZE) + c_buffer_size = c_uint(NVML_DEVICE_UUID_BUFFER_SIZE) + fn = _nvmlGetFunctionPointer("nvmlVgpuInstanceGetUUID") + ret = fn(vgpuInstance, byref(c_uuid), c_buffer_size) + _nvmlCheckReturn(ret) + return c_uuid.value + +@convertStrBytes +def nvmlVgpuInstanceGetMdevUUID(vgpuInstance): + c_uuid = create_string_buffer(NVML_DEVICE_UUID_BUFFER_SIZE) + c_buffer_size = c_uint(NVML_DEVICE_UUID_BUFFER_SIZE) + fn = _nvmlGetFunctionPointer("nvmlVgpuInstanceGetMdevUUID") + ret = fn(vgpuInstance, byref(c_uuid), c_buffer_size) + _nvmlCheckReturn(ret) + return c_uuid.value + +@convertStrBytes +def nvmlVgpuInstanceGetVmDriverVersion(vgpuInstance): + c_driver_version = create_string_buffer(NVML_SYSTEM_DRIVER_VERSION_BUFFER_SIZE) + c_buffer_size = c_uint(NVML_SYSTEM_DRIVER_VERSION_BUFFER_SIZE) + fn = _nvmlGetFunctionPointer("nvmlVgpuInstanceGetVmDriverVersion") + ret = fn(vgpuInstance, byref(c_driver_version), c_buffer_size) + _nvmlCheckReturn(ret) + return c_driver_version.value + +# DEPRECATED: Use nvmlVgpuInstanceGetLicenseInfo_v instead; will be removed in CUDA 14.0 +def nvmlVgpuInstanceGetLicenseStatus(vgpuInstance): + c_license_status = c_uint(0) + fn = _nvmlGetFunctionPointer("nvmlVgpuInstanceGetLicenseStatus") + ret = fn(vgpuInstance, byref(c_license_status)) + _nvmlCheckReturn(ret) + return c_license_status.value + +def nvmlVgpuInstanceGetLicenseInfo_v2(vgpuInstance): + fn = _nvmlGetFunctionPointer("nvmlVgpuInstanceGetLicenseInfo_v2") + c_license_info = c_nvmlVgpuLicenseInfo_t() + ret = fn(vgpuInstance, byref(c_license_info)) + _nvmlCheckReturn(ret) + return c_license_info + +def nvmlVgpuInstanceGetLicenseInfo(vgpuInstance): + return nvmlVgpuInstanceGetLicenseInfo_v2(vgpuInstance) + +def nvmlVgpuInstanceGetFrameRateLimit(vgpuInstance): + c_frl = c_uint(0) + fn = _nvmlGetFunctionPointer("nvmlVgpuInstanceGetFrameRateLimit") + ret = fn(vgpuInstance, byref(c_frl)) + _nvmlCheckReturn(ret) + return c_frl.value + +def nvmlVgpuInstanceGetEccMode(vgpuInstance): + c_mode = _nvmlEnableState_t() + fn = _nvmlGetFunctionPointer("nvmlVgpuInstanceGetEccMode") + ret = fn(vgpuInstance, byref(c_mode)) + _nvmlCheckReturn(ret) + return c_mode.value + +def nvmlVgpuInstanceGetType(vgpuInstance): + c_vgpu_type = c_uint(0) + fn = _nvmlGetFunctionPointer("nvmlVgpuInstanceGetType") + ret = fn(vgpuInstance, byref(c_vgpu_type)) + _nvmlCheckReturn(ret) + return c_vgpu_type.value + +def nvmlVgpuInstanceGetEncoderCapacity(vgpuInstance): + c_encoder_capacity = c_ulonglong(0) + fn = _nvmlGetFunctionPointer("nvmlVgpuInstanceGetEncoderCapacity") + ret = fn(vgpuInstance, byref(c_encoder_capacity)) + _nvmlCheckReturn(ret) + return c_encoder_capacity.value + +def nvmlVgpuInstanceSetEncoderCapacity(vgpuInstance, encoder_capacity): + fn = _nvmlGetFunctionPointer("nvmlVgpuInstanceSetEncoderCapacity") + return fn(vgpuInstance, encoder_capacity) + +def nvmlVgpuInstanceGetFbUsage(vgpuInstance): + c_fb_usage = c_uint(0) + fn = _nvmlGetFunctionPointer("nvmlVgpuInstanceGetFbUsage") + ret = fn(vgpuInstance, byref(c_fb_usage)) + _nvmlCheckReturn(ret) + return c_fb_usage.value + +def nvmlVgpuTypeGetCapabilities(vgpuTypeId, capability): + c_cap_result = c_uint(0) + fn = _nvmlGetFunctionPointer("nvmlVgpuTypeGetCapabilities") + ret = fn(vgpuTypeId, _nvmlVgpuCapability_t(capability), byref(c_cap_result)) + _nvmlCheckReturn(ret) + return (c_cap_result.value) + +def nvmlVgpuInstanceGetGpuInstanceId(vgpuInstance): + c_id = c_uint(0) + fn = _nvmlGetFunctionPointer("nvmlVgpuInstanceGetGpuInstanceId") + ret = fn(vgpuInstance, byref(c_id)) + _nvmlCheckReturn(ret) + return (c_id.value) + +@convertStrBytes +def nvmlVgpuInstanceGetGpuPciId(vgpuInstance): + c_vgpuPciId = create_string_buffer(NVML_DEVICE_PCI_BUS_ID_BUFFER_SIZE) + fn = _nvmlGetFunctionPointer("nvmlVgpuInstanceGetGpuPciId") + ret = fn(vgpuInstance, c_vgpuPciId, byref(c_uint(NVML_DEVICE_PCI_BUS_ID_BUFFER_SIZE))) + _nvmlCheckReturn(ret) + return c_vgpuPciId.value + +def nvmlDeviceGetVgpuUtilization(handle, timeStamp): + # first call to get the size + c_vgpu_count = c_uint(0) + c_time_stamp = c_ulonglong(timeStamp) + c_sample_value_type = _nvmlValueType_t() + + fn = _nvmlGetFunctionPointer("nvmlDeviceGetVgpuUtilization") + ret = fn(handle, c_time_stamp, byref(c_sample_value_type), byref(c_vgpu_count), None) + + if (ret == NVML_SUCCESS): + # special case, no active vGPUs + return [] + elif (ret == NVML_ERROR_INSUFFICIENT_SIZE): + # typical case + sampleArray = c_vgpu_count.value * c_nvmlVgpuInstanceUtilizationSample_t + c_samples = sampleArray() + + # make the call again + ret = fn(handle, c_time_stamp, byref(c_sample_value_type), byref(c_vgpu_count), c_samples) + _nvmlCheckReturn(ret) + + return c_samples[0:c_vgpu_count.value] + else: + # error case + raise NVMLError(ret) + +def nvmlDeviceGetVgpuInstancesUtilizationInfo(handle, timeStamp): + # first call to get the size + c_time_stamp = c_ulonglong(timeStamp) + c_vgpuUtilInfo = c_nvmlVgpuInstancesUtilizationInfo_v1_t(0) + c_vgpuUtilInfo.version = VgpuInstancesUtilizationInfo_v1 + c_vgpuUtilInfo.sampleValType = _nvmlValueType_t() + c_vgpuUtilInfo.vgpuInstanceCount = c_uint(0) + c_vgpuUtilInfo.lastSeenTimeStamp = c_time_stamp + + fn = _nvmlGetFunctionPointer("nvmlDeviceGetVgpuInstancesUtilizationInfo") + ret = fn(handle, byref(c_vgpuUtilInfo)) + + if (ret == NVML_SUCCESS): + # special case, no active vGPUs + return [] + elif (ret == NVML_ERROR_INSUFFICIENT_SIZE): + # typical case + sampleArray = c_vgpuUtilInfo.vgpuInstanceCount * c_nvmlVgpuInstanceUtilizationInfo_v1_t + c_samples = sampleArray() + c_vgpuUtilInfo.vgpuUtilArray = c_samples + + # make the call again + ret = fn(handle, byref(c_vgpuUtilInfo)) + _nvmlCheckReturn(ret) + + return c_samples[0:c_vgpuUtilInfo.vgpuInstanceCount] + else: + # error case + raise NVMLError(ret) + +def nvmlDeviceGetP2PStatus(device1, device2, p2pIndex): + c_p2pstatus = _nvmlGpuP2PStatus_t() + fn = _nvmlGetFunctionPointer("nvmlDeviceGetP2PStatus") + ret = fn(device1, device2,p2pIndex, byref(c_p2pstatus)) + _nvmlCheckReturn(ret) + return c_p2pstatus.value + +def nvmlDeviceGetGridLicensableFeatures_v4(handle): + c_get_grid_licensable_features = c_nvmlGridLicensableFeatures_v4_t() + fn = _nvmlGetFunctionPointer("nvmlDeviceGetGridLicensableFeatures_v4") + ret = fn(handle, byref(c_get_grid_licensable_features)) + _nvmlCheckReturn(ret) + + return (c_get_grid_licensable_features) + +def nvmlDeviceGetGridLicensableFeatures(handle): + return nvmlDeviceGetGridLicensableFeatures_v4(handle) + +def nvmlDeviceGetGspFirmwareVersion(handle, version=None): + isUserDefined = version is not None + if not isUserDefined: + version = (c_char * NVML_GSP_FIRMWARE_VERSION_BUF_SIZE)() + fn = _nvmlGetFunctionPointer("nvmlDeviceGetGspFirmwareVersion") + ret = fn(handle, version) + _nvmlCheckReturn(ret) + return NVML_SUCCESS if isUserDefined else version.value + +def nvmlDeviceGetGspFirmwareMode(handle, isEnabled=c_uint(), defaultMode=c_uint()): + isReference = type(isEnabled) is not c_uint + isEnabledRef = isEnabled if isReference else byref(isEnabled) + defaultModeRef = defaultMode if isReference else byref(defaultMode) + fn = _nvmlGetFunctionPointer("nvmlDeviceGetGspFirmwareMode") + ret = fn(handle, isEnabledRef, defaultModeRef) + _nvmlCheckReturn(ret) + return NVML_SUCCESS if isReference else [isEnabled.value, defaultMode.value] + +def nvmlDeviceGetEncoderCapacity(handle, encoderQueryType): + c_encoder_capacity = c_ulonglong(0) + c_encoderQuery_type = _nvmlEncoderQueryType_t(encoderQueryType) + + fn = _nvmlGetFunctionPointer("nvmlDeviceGetEncoderCapacity") + ret = fn(handle, c_encoderQuery_type, byref(c_encoder_capacity)) + _nvmlCheckReturn(ret) + return c_encoder_capacity.value + +def nvmlDeviceGetVgpuProcessUtilization(handle, timeStamp): + # first call to get the size + c_vgpu_count = c_uint(0) + c_time_stamp = c_ulonglong(timeStamp) + + fn = _nvmlGetFunctionPointer("nvmlDeviceGetVgpuProcessUtilization") + ret = fn(handle, c_time_stamp, byref(c_vgpu_count), None) + + if (ret == NVML_SUCCESS): + # special case, no active vGPUs + return [] + elif (ret == NVML_ERROR_INSUFFICIENT_SIZE): + # typical case + sampleArray = c_vgpu_count.value * c_nvmlVgpuProcessUtilizationSample_t + c_samples = sampleArray() + + # make the call again + ret = fn(handle, c_time_stamp, byref(c_vgpu_count), c_samples) + _nvmlCheckReturn(ret) + + return c_samples[0:c_vgpu_count.value] + else: + # error case + raise NVMLError(ret) + +def nvmlDeviceGetVgpuProcessesUtilizationInfo(handle, timeStamp): + # first call to get the size + c_time_stamp = c_ulonglong(timeStamp) + c_vgpuProcUtilInfo = c_nvmlVgpuProcessesUtilizationInfo_v1_t(0) + c_vgpuProcUtilInfo.version = VgpuProcessesUtilizationInfo_v1 + c_vgpuProcUtilInfo.vgpuProcessCount = c_uint(0) + c_vgpuProcUtilInfo.lastSeenTimeStamp = c_time_stamp + + fn = _nvmlGetFunctionPointer("nvmlDeviceGetVgpuProcessesUtilizationInfo") + ret = fn(handle, byref(c_vgpuProcUtilInfo)) + + if (ret == NVML_SUCCESS): + # special case, no active vGPUs + return [] + elif (ret == NVML_ERROR_INSUFFICIENT_SIZE): + # typical case + sampleArray = c_vgpuProcUtilInfo.vgpuProcessCount * c_nvmlVgpuProcessUtilizationInfo_v1_t + c_samples = sampleArray() + c_vgpuProcUtilInfo.vgpuProcUtilArray = c_samples + + # make the call again + ret = fn(handle, byref(c_vgpuProcUtilInfo)) + _nvmlCheckReturn(ret) + + return c_samples[0:c_vgpuProcUtilInfo.vgpuProcessCount] + else: + # error case + raise NVMLError(ret) + +def nvmlDeviceGetEncoderStats(handle): + c_encoderCount = c_ulonglong(0) + c_encodeFps = c_ulonglong(0) + c_encoderLatency = c_ulonglong(0) + fn = _nvmlGetFunctionPointer("nvmlDeviceGetEncoderStats") + ret = fn(handle, byref(c_encoderCount), byref(c_encodeFps), byref(c_encoderLatency)) + _nvmlCheckReturn(ret) + return (c_encoderCount.value, c_encodeFps.value, c_encoderLatency.value) + +def nvmlDeviceGetEncoderSessions(handle): + # first call to get the size + c_session_count = c_uint(0) + + fn = _nvmlGetFunctionPointer("nvmlDeviceGetEncoderSessions") + ret = fn(handle, byref(c_session_count), None) + + if (ret == NVML_SUCCESS): + if (c_session_count.value != 0): + # typical case + session_array = c_nvmlEncoderSession_t * c_session_count.value + c_sessions = session_array() + + # make the call again + ret = fn(handle, byref(c_session_count), c_sessions) + _nvmlCheckReturn(ret) + sessions = [] + for i in range(c_session_count.value): + sessions.append(c_sessions[i]) + return sessions + else: + return [] # no active sessions + else: + # error case + raise NVMLError(ret) + +def nvmlDeviceGetFBCStats(handle): + c_fbcStats = c_nvmlFBCStats_t() + fn = _nvmlGetFunctionPointer("nvmlDeviceGetFBCStats") + ret = fn(handle, byref(c_fbcStats)) + _nvmlCheckReturn(ret) + return c_fbcStats + +def nvmlDeviceGetFBCSessions(handle): + # first call to get the size + c_session_count = c_uint(0) + + fn = _nvmlGetFunctionPointer("nvmlDeviceGetFBCSessions") + ret = fn(handle, byref(c_session_count), None) + + if (ret == NVML_SUCCESS): + if (c_session_count.value != 0): + # typical case + session_array = c_nvmlFBCSession_t * c_session_count.value + c_sessions = session_array() + + # make the call again + ret = fn(handle, byref(c_session_count), c_sessions) + _nvmlCheckReturn(ret) + sessions = [] + for i in range(c_session_count.value): + sessions.append(c_sessions[i]) + return sessions + else: + return [] # no active sessions + else: + # error case + raise NVMLError(ret) + +def nvmlVgpuInstanceGetEncoderStats(vgpuInstance): + c_encoderCount = c_ulonglong(0) + c_encodeFps = c_ulonglong(0) + c_encoderLatency = c_ulonglong(0) + fn = _nvmlGetFunctionPointer("nvmlVgpuInstanceGetEncoderStats") + ret = fn(vgpuInstance, byref(c_encoderCount), byref(c_encodeFps), byref(c_encoderLatency)) + _nvmlCheckReturn(ret) + return (c_encoderCount.value, c_encodeFps.value, c_encoderLatency.value) + +def nvmlVgpuInstanceGetEncoderSessions(vgpuInstance): + # first call to get the size + c_session_count = c_uint(0) + + fn = _nvmlGetFunctionPointer("nvmlVgpuInstanceGetEncoderSessions") + ret = fn(vgpuInstance, byref(c_session_count), None) + + if (ret == NVML_SUCCESS): + if (c_session_count.value != 0): + # typical case + session_array = c_nvmlEncoderSession_t * c_session_count.value + c_sessions = session_array() + + # make the call again + ret = fn(vgpuInstance, byref(c_session_count), c_sessions) + _nvmlCheckReturn(ret) + sessions = [] + for i in range(c_session_count.value): + sessions.append(c_sessions[i]) + return sessions + else: + return [] # no active sessions + else: + # error case + raise NVMLError(ret) + +def nvmlVgpuInstanceGetFBCStats(vgpuInstance): + c_fbcStats = c_nvmlFBCStats_t() + fn = _nvmlGetFunctionPointer("nvmlVgpuInstanceGetFBCStats") + ret = fn(vgpuInstance, byref(c_fbcStats)) + _nvmlCheckReturn(ret) + return c_fbcStats + +def nvmlVgpuInstanceGetFBCSessions(vgpuInstance): + # first call to get the size + c_session_count = c_uint(0) + + fn = _nvmlGetFunctionPointer("nvmlVgpuInstanceGetFBCSessions") + ret = fn(vgpuInstance, byref(c_session_count), None) + + if (ret == NVML_SUCCESS): + if (c_session_count.value != 0): + # typical case + session_array = c_nvmlFBCSession_t * c_session_count.value + c_sessions = session_array() + + # make the call again + ret = fn(vgpuInstance, byref(c_session_count), c_sessions) + _nvmlCheckReturn(ret) + sessions = [] + for i in range(c_session_count.value): + sessions.append(c_sessions[i]) + return sessions + else: + return [] # no active sessions + else: + # error case + raise NVMLError(ret) + +def nvmlDeviceGetProcessUtilization(handle, timeStamp): + # first call to get the size + c_count = c_uint(0) + c_time_stamp = c_ulonglong(timeStamp) + + fn = _nvmlGetFunctionPointer("nvmlDeviceGetProcessUtilization") + ret = fn(handle, None, byref(c_count), c_time_stamp) + + if (ret == NVML_ERROR_INSUFFICIENT_SIZE): + # typical case + sampleArray = c_count.value * c_nvmlProcessUtilizationSample_t + c_samples = sampleArray() + + # make the call again + ret = fn(handle, c_samples, byref(c_count), c_time_stamp) + _nvmlCheckReturn(ret) + + return c_samples[0:c_count.value] + else: + # error case + raise NVMLError(ret) + +def nvmlDeviceGetProcessesUtilizationInfo(handle, timeStamp): + # first call to get the size + c_time_stamp = c_ulonglong(timeStamp) + c_processesUtilInfo = c_nvmlProcessesUtilizationInfo_v1_t(0) + c_processesUtilInfo.version = ProcessesUtilizationInfo_v1 + c_processesUtilInfo.processSamplesCount = c_uint(0) + c_processesUtilInfo.lastSeenTimeStamp = c_time_stamp + + fn = _nvmlGetFunctionPointer("nvmlDeviceGetProcessesUtilizationInfo") + ret = fn(handle, byref(c_processesUtilInfo)) + + if (ret == NVML_ERROR_INSUFFICIENT_SIZE): + # typical case + sampleArray = c_processesUtilInfo.processSamplesCount * c_nvmlProcessUtilizationInfo_v1_t + c_samples = sampleArray() + c_processesUtilInfo.procUtilArray = c_samples + + # make the call again + ret = fn(handle, byref(c_processesUtilInfo)) + _nvmlCheckReturn(ret) + + return c_samples[0:c_processesUtilInfo.processSamplesCount] + else: + # error case + raise NVMLError(ret) + +def nvmlVgpuInstanceGetMetadata(vgpuInstance): + fn = _nvmlGetFunctionPointer("nvmlVgpuInstanceGetMetadata") + c_vgpuMetadata = c_nvmlVgpuMetadata_t() + c_bufferSize = c_uint(0) + # Make the first NVML API call to get the c_bufferSize value. + # We have already allocated required buffer above. + ret = fn(vgpuInstance, byref(c_vgpuMetadata), byref(c_bufferSize)) + if (ret == NVML_ERROR_INSUFFICIENT_SIZE): + ret = fn(vgpuInstance, byref(c_vgpuMetadata), byref(c_bufferSize)) + _nvmlCheckReturn(ret) + else: + raise NVMLError(ret) + return c_vgpuMetadata + +def nvmlDeviceGetVgpuMetadata(handle): + fn = _nvmlGetFunctionPointer("nvmlDeviceGetVgpuMetadata") + c_vgpuPgpuMetadata = c_nvmlVgpuPgpuMetadata_t() + c_bufferSize = c_uint(0) + # Make the first NVML API call to get the c_bufferSize value. + # We have already allocated required buffer above. + ret = fn(handle, byref(c_vgpuPgpuMetadata), byref(c_bufferSize)) + if (ret == NVML_ERROR_INSUFFICIENT_SIZE): + ret = fn(handle, byref(c_vgpuPgpuMetadata), byref(c_bufferSize)) + _nvmlCheckReturn(ret) + else: + raise NVMLError(ret) + return c_vgpuPgpuMetadata + +def nvmlGetVgpuCompatibility(vgpuMetadata, pgpuMetadata): + fn = _nvmlGetFunctionPointer("nvmlGetVgpuCompatibility") + c_vgpuPgpuCompatibility = c_nvmlVgpuPgpuCompatibility_t() + ret = fn(byref(vgpuMetadata), byref(pgpuMetadata), byref(c_vgpuPgpuCompatibility)) + _nvmlCheckReturn(ret) + return c_vgpuPgpuCompatibility + +@convertStrBytes +def nvmlDeviceGetPgpuMetadataString(handle): + fn = _nvmlGetFunctionPointer("nvmlDeviceGetPgpuMetadataString") + c_pgpuMetadata = create_string_buffer(NVML_VGPU_PGPU_METADATA_OPAQUE_DATA_SIZE) + c_bufferSize = c_uint(0) + # Make the first NVML API call to get the c_bufferSize value. + # We have already allocated required buffer above. + ret = fn(handle, byref(c_pgpuMetadata), byref(c_bufferSize)) + if (ret == NVML_ERROR_INSUFFICIENT_SIZE): + ret = fn(handle, byref(c_pgpuMetadata), byref(c_bufferSize)) + _nvmlCheckReturn(ret) + else: + raise NVMLError(ret) + return (c_pgpuMetadata.value, c_bufferSize.value) + +# DEPRECATED: Use nvmlDeviceGetVgpuSchedulerLog_v2 instead; +def nvmlDeviceGetVgpuSchedulerLog(handle): + c_vgpu_sched_log = c_nvmlVgpuSchedulerLog_t() + fn = _nvmlGetFunctionPointer("nvmlDeviceGetVgpuSchedulerLog") + ret = fn(handle, byref(c_vgpu_sched_log)) + _nvmlCheckReturn(ret) + return c_vgpu_sched_log + +# DEPRECATED: Use nvmlDeviceGetVgpuSchedulerState_v2 instead; +def nvmlDeviceGetVgpuSchedulerState(handle): + c_vgpu_sched_state = c_nvmlVgpuSchedulerGetState_t() + fn = _nvmlGetFunctionPointer("nvmlDeviceGetVgpuSchedulerState") + ret = fn(handle, byref(c_vgpu_sched_state)) + _nvmlCheckReturn(ret) + return c_vgpu_sched_state + +def nvmlDeviceGetVgpuSchedulerCapabilities(handle): + c_vgpu_sched_caps = c_nvmlVgpuSchedulerCapabilities_t() + fn = _nvmlGetFunctionPointer("nvmlDeviceGetVgpuSchedulerCapabilities") + ret = fn(handle, byref(c_vgpu_sched_caps)) + _nvmlCheckReturn(ret) + return c_vgpu_sched_caps + +# DEPRECATED: Use nvmlDeviceSetVgpuSchedulerState_v2 instead; +def nvmlDeviceSetVgpuSchedulerState(handle, sched_state): + fn = _nvmlGetFunctionPointer("nvmlDeviceSetVgpuSchedulerState") + ret = fn(handle, byref(sched_state)) + _nvmlCheckReturn(ret) + return NVML_SUCCESS + +def nvmlSetVgpuVersion(vgpuVersion): + fn = _nvmlGetFunctionPointer("nvmlSetVgpuVersion") + ret = fn(byref(vgpuVersion)) + _nvmlCheckReturn(ret) + return NVML_SUCCESS + +def nvmlGetVgpuVersion(supported=None, current=None): + isUserDefined = (supported is not None) or (current is not None) + if not isUserDefined: + supported = c_nvmlVgpuVersion_t() + current = c_nvmlVgpuVersion_t() + fn = _nvmlGetFunctionPointer("nvmlGetVgpuVersion") + ret = fn(byref(supported), byref(current)) + _nvmlCheckReturn(ret) + return NVML_SUCCESS if isUserDefined else [(supported.minVersion, + supported.maxVersion), + (current.minVersion, + current.maxVersion)] + +def nvmlVgpuInstanceGetAccountingMode(vgpuInstance): + c_mode = _nvmlEnableState_t() + fn = _nvmlGetFunctionPointer("nvmlVgpuInstanceGetAccountingMode") + ret = fn(vgpuInstance, byref(c_mode)) + _nvmlCheckReturn(ret) + return c_mode.value + +def nvmlVgpuInstanceGetAccountingPids(vgpuInstance): + c_pidCount = c_uint() + fn = _nvmlGetFunctionPointer("nvmlVgpuInstanceGetAccountingPids") + ret = fn(vgpuInstance, byref(c_pidCount), None) + if (ret == NVML_ERROR_INSUFFICIENT_SIZE): + sampleArray = c_pidCount.value * c_uint + c_pidArray = sampleArray() + ret = fn(vgpuInstance, byref(c_pidCount), byref(c_pidArray)) + _nvmlCheckReturn(ret) + else: + raise NVMLError(ret) + return (c_pidCount, c_pidArray) + +def nvmlVgpuInstanceGetAccountingStats(vgpuInstance, pid): + c_accountingStats = c_nvmlAccountingStats_t() + fn = _nvmlGetFunctionPointer("nvmlVgpuInstanceGetAccountingStats") + ret = fn(vgpuInstance, pid, byref(c_accountingStats)) + _nvmlCheckReturn(ret) + return c_accountingStats + +def nvmlVgpuInstanceClearAccountingPids(vgpuInstance): + fn = _nvmlGetFunctionPointer("nvmlVgpuInstanceClearAccountingPids") + ret = fn(vgpuInstance) + _nvmlCheckReturn(ret) + return NVML_SUCCESS + +def nvmlGpuInstanceGetCreatableVgpus(gpuInstance, c_vgpus): + c_vgpus.vgpuCount = 0; + fn = _nvmlGetFunctionPointer("nvmlGpuInstanceGetCreatableVgpus") + ret = fn(gpuInstance, byref(c_vgpus)) + + if (ret == NVML_SUCCESS): + # special case, no supported vGPUs + return c_vgpus + elif (ret == NVML_ERROR_INSUFFICIENT_SIZE): + vgpu_type_ids_array = _nvmlVgpuTypeId_t * c_vgpus.vgpuCount + c_vgpus.vgpuTypeIds = vgpu_type_ids_array() + ret = fn(gpuInstance, byref(c_vgpus)) + _nvmlCheckReturn(ret) + + return c_vgpus + else: + raise NVMLError(ret) + +def nvmlVgpuTypeGetMaxInstancesPerGpuInstance(vgpuTypeId): + c_max_instances = c_nvmlVgpuTypeMaxInstance_v1_t() + c_max_instances.version = nvmlVgpuTypeMaxInstance_v1 + c_max_instances.vgpuTypeId = vgpuTypeId + fn = _nvmlGetFunctionPointer("nvmlVgpuTypeGetMaxInstancesPerGpuInstance") + ret = fn(byref(c_max_instances)) + _nvmlCheckReturn(ret) + return c_max_instances.maxInstancePerGI + +def nvmlGpuInstanceGetActiveVgpus(gpuInstance, c_vgpu_instance_info): + c_vgpu_instance_info.vgpuCount = c_uint(0) + + fn = _nvmlGetFunctionPointer("nvmlGpuInstanceGetActiveVgpus") + ret = fn(gpuInstance, byref(c_vgpu_instance_info)) + + if (ret == NVML_SUCCESS): + # special case, no active vGPUs + return c_vgpu_instance_info + elif (ret == NVML_ERROR_INSUFFICIENT_SIZE): + # typical case + vgpu_instance_array = _nvmlVgpuInstance_t * c_vgpu_instance_info.vgpuCount + c_vgpu_instance_info.vgpuInstances = vgpu_instance_array() + + # make the call again + ret = fn(gpuInstance, byref(c_vgpu_instance_info)) + _nvmlCheckReturn(ret) + return c_vgpu_instance_info + else: + raise NVMLError(ret) + +# DEPRECATED: Use nvmlGpuInstanceSetVgpuSchedulerState_v2 instead; +def nvmlGpuInstanceSetVgpuSchedulerState(gpuInstance, sched_state): + fn = _nvmlGetFunctionPointer("nvmlGpuInstanceSetVgpuSchedulerState") + ret = fn(gpuInstance, byref(sched_state)) + _nvmlCheckReturn(ret) + return ret + +# DEPRECATED: Use nvmlGpuInstanceGetVgpuSchedulerState_v2 instead; +def nvmlGpuInstanceGetVgpuSchedulerState(gpuInstance, c_vgpu_sched_state_info): + fn = _nvmlGetFunctionPointer("nvmlGpuInstanceGetVgpuSchedulerState") + ret = fn(gpuInstance, byref(c_vgpu_sched_state_info)) + _nvmlCheckReturn(ret) + return c_vgpu_sched_state_info + +# DEPRECATED: Use nvmlGpuInstanceGetVgpuSchedulerLog_v2 instead; +def nvmlGpuInstanceGetVgpuSchedulerLog(gpuInstance, c_vgpu_sched_log_info): + fn = _nvmlGetFunctionPointer("nvmlGpuInstanceGetVgpuSchedulerLog") + ret = fn(gpuInstance, byref(c_vgpu_sched_log_info)) + _nvmlCheckReturn(ret) + return c_vgpu_sched_log_info + +def nvmlGpuInstanceGetVgpuTypeCreatablePlacements(gpuInstance, c_vgpu_placements): + c_max_instances = c_nvmlVgpuTypeMaxInstance_v1_t() + c_max_instances.version = nvmlVgpuTypeMaxInstance_v1 + c_max_instances.vgpuTypeId = c_vgpu_placements.vgpuTypeId + fn = _nvmlGetFunctionPointer("nvmlVgpuTypeGetMaxInstancesPerGpuInstance") + ret = fn(byref(c_max_instances)) + _nvmlCheckReturn(ret) + + c_vgpu_placements.count = c_max_instances.maxInstancePerGI + + c_placements = c_uint * c_max_instances.maxInstancePerGI + c_vgpu_placements.placementIds = c_placements() + fn = _nvmlGetFunctionPointer("nvmlGpuInstanceGetVgpuTypeCreatablePlacements") + ret = fn(gpuInstance, byref(c_vgpu_placements)) + _nvmlCheckReturn(ret) + return c_vgpu_placements + +def nvmlGpuInstanceGetVgpuHeterogeneousMode(gpuInstance): + c_vgpuHeterogeneousMode = c_nvmlVgpuHeterogeneousMode_v1_t(0) + c_vgpuHeterogeneousMode.version = VgpuHeterogeneousMode_v1 + fn = _nvmlGetFunctionPointer("nvmlGpuInstanceGetVgpuHeterogeneousMode") + ret = fn(gpuInstance, byref(c_vgpuHeterogeneousMode)) + _nvmlCheckReturn(ret) + return c_vgpuHeterogeneousMode.mode + +def nvmlGpuInstanceSetVgpuHeterogeneousMode(gpuInstance, heterogeneous_mode): + c_vgpuHeterogeneousMode = c_nvmlVgpuHeterogeneousMode_v1_t(0) + c_vgpuHeterogeneousMode.version = VgpuHeterogeneousMode_v1 + c_vgpuHeterogeneousMode.mode = heterogeneous_mode + fn = _nvmlGetFunctionPointer("nvmlGpuInstanceSetVgpuHeterogeneousMode") + ret = fn(gpuInstance, byref(c_vgpuHeterogeneousMode)) + _nvmlCheckReturn(ret) + return NVML_SUCCESS + +def nvmlDeviceGetVgpuSchedulerState_v2(handle, c_vgpu_sched_state_info_v2): + fn = _nvmlGetFunctionPointer("nvmlDeviceGetVgpuSchedulerState_v2") + ret = fn(handle, byref(c_vgpu_sched_state_info_v2)) + _nvmlCheckReturn(ret) + return c_vgpu_sched_state_info_v2 + +def nvmlGpuInstanceGetVgpuSchedulerState_v2(gpuInstance, c_vgpu_sched_state_info_v2): + fn = _nvmlGetFunctionPointer("nvmlGpuInstanceGetVgpuSchedulerState_v2") + ret = fn(gpuInstance, byref(c_vgpu_sched_state_info_v2)) + _nvmlCheckReturn(ret) + return c_vgpu_sched_state_info_v2 + +def nvmlDeviceGetVgpuSchedulerLog_v2(handle, c_vgpu_sched_log_info_v2): + fn = _nvmlGetFunctionPointer("nvmlDeviceGetVgpuSchedulerLog_v2") + ret = fn(handle, byref(c_vgpu_sched_log_info_v2)) + _nvmlCheckReturn(ret) + return c_vgpu_sched_log_info_v2 + +def nvmlGpuInstanceGetVgpuSchedulerLog_v2(gpuInstance, c_vgpu_sched_log_info_v2): + fn = _nvmlGetFunctionPointer("nvmlGpuInstanceGetVgpuSchedulerLog_v2") + ret = fn(gpuInstance, byref(c_vgpu_sched_log_info_v2)) + _nvmlCheckReturn(ret) + return c_vgpu_sched_log_info_v2 + +def nvmlDeviceSetVgpuSchedulerState_v2(handle, sched_state_v2): + fn = _nvmlGetFunctionPointer("nvmlDeviceSetVgpuSchedulerState_v2") + ret = fn(handle, byref(sched_state_v2)) + _nvmlCheckReturn(ret) + return NVML_SUCCESS + +def nvmlGpuInstanceSetVgpuSchedulerState_v2(gpuInstance, sched_state_v2): + fn = _nvmlGetFunctionPointer("nvmlGpuInstanceSetVgpuSchedulerState_v2") + ret = fn(gpuInstance, byref(sched_state_v2)) + _nvmlCheckReturn(ret) + return NVML_SUCCESS + +def nvmlGetExcludedDeviceCount(): + c_count = c_uint() + fn = _nvmlGetFunctionPointer("nvmlGetExcludedDeviceCount") + ret = fn(byref(c_count)) + _nvmlCheckReturn(ret) + return c_count.value + +def nvmlGetExcludedDeviceInfoByIndex(index): + c_index = c_uint(index) + info = c_nvmlExcludedDeviceInfo_t() + fn = _nvmlGetFunctionPointer("nvmlGetExcludedDeviceInfoByIndex") + ret = fn(c_index, byref(info)) + _nvmlCheckReturn(ret) + return info + +def nvmlDeviceGetHostVgpuMode(handle): + c_host_vgpu_mode = _nvmlHostVgpuMode_t() + fn = _nvmlGetFunctionPointer("nvmlDeviceGetHostVgpuMode") + ret = fn(handle, byref(c_host_vgpu_mode)) + _nvmlCheckReturn(ret) + return c_host_vgpu_mode.value + +def nvmlDeviceSetMigMode(device, mode): + c_activationStatus = c_uint() + fn = _nvmlGetFunctionPointer("nvmlDeviceSetMigMode") + ret = fn(device, mode, byref(c_activationStatus)) + _nvmlCheckReturn(ret) + return c_activationStatus.value + +def nvmlDeviceGetMigMode(device): + c_currentMode = c_uint() + c_pendingMode = c_uint() + fn = _nvmlGetFunctionPointer("nvmlDeviceGetMigMode") + ret = fn(device, byref(c_currentMode), byref(c_pendingMode)) + _nvmlCheckReturn(ret) + return [c_currentMode.value, c_pendingMode.value] + +def nvmlDeviceGetGpuInstanceProfileInfo(device, profile, version=2): + if version == 2: + c_info = c_nvmlGpuInstanceProfileInfo_v2_t() + fn = _nvmlGetFunctionPointer("nvmlDeviceGetGpuInstanceProfileInfoV") + elif version == 1: + c_info = c_nvmlGpuInstanceProfileInfo_t() + fn = _nvmlGetFunctionPointer("nvmlDeviceGetGpuInstanceProfileInfo") + else: + raise NVMLError(NVML_ERROR_FUNCTION_NOT_FOUND) + ret = fn(device, profile, byref(c_info)) + _nvmlCheckReturn(ret) + return c_info + +def nvmlDeviceGetGpuInstanceProfileInfoById(device, profileId): + c_info = c_nvmlGpuInstanceProfileInfo_v2_t() + fn = _nvmlGetFunctionPointer("nvmlDeviceGetGpuInstanceProfileInfoByIdV") + + ret = fn(device, profileId, byref(c_info)) + _nvmlCheckReturn(ret) + return c_info + +# Define function alias for the API exposed by NVML +nvmlDeviceGetGpuInstanceProfileInfoV = nvmlDeviceGetGpuInstanceProfileInfo +nvmlDeviceGetGpuInstanceProfileInfoByIdV = nvmlDeviceGetGpuInstanceProfileInfoById + +def nvmlDeviceGetGpuInstanceRemainingCapacity(device, profileId): + c_count = c_uint() + fn = _nvmlGetFunctionPointer("nvmlDeviceGetGpuInstanceRemainingCapacity") + ret = fn(device, profileId, byref(c_count)) + _nvmlCheckReturn(ret) + return c_count.value + +def nvmlDeviceGetGpuInstancePossiblePlacements(device, profileId, placementsRef, countRef): + fn = _nvmlGetFunctionPointer("nvmlDeviceGetGpuInstancePossiblePlacements_v2") + ret = fn(device, profileId, placementsRef, countRef) + _nvmlCheckReturn(ret) + return NVML_SUCCESS + +def nvmlDeviceCreateGpuInstance(device, profileId): + c_instance = c_nvmlGpuInstance_t() + fn = _nvmlGetFunctionPointer("nvmlDeviceCreateGpuInstance") + ret = fn(device, profileId, byref(c_instance)) + _nvmlCheckReturn(ret) + return c_instance + +def nvmlDeviceCreateGpuInstanceWithPlacement(device, profileId, placement): + c_instance = c_nvmlGpuInstance_t() + fn = _nvmlGetFunctionPointer("nvmlDeviceCreateGpuInstanceWithPlacement") + ret = fn(device, profileId, placement, byref(c_instance)) + _nvmlCheckReturn(ret) + return c_instance + +def nvmlGpuInstanceDestroy(gpuInstance): + fn = _nvmlGetFunctionPointer("nvmlGpuInstanceDestroy") + ret = fn(gpuInstance) + _nvmlCheckReturn(ret) + return NVML_SUCCESS + +def nvmlDeviceGetGpuInstances(device, profileId, gpuInstancesRef, countRef): + fn = _nvmlGetFunctionPointer("nvmlDeviceGetGpuInstances") + ret = fn(device, profileId, gpuInstancesRef, countRef) + _nvmlCheckReturn(ret) + return NVML_SUCCESS + +def nvmlDeviceGetGpuInstanceById(device, gpuInstanceId): + c_instance = c_nvmlGpuInstance_t() + fn = _nvmlGetFunctionPointer("nvmlDeviceGetGpuInstanceById") + ret = fn(device, gpuInstanceId, byref(c_instance)) + _nvmlCheckReturn(ret) + return c_instance + +def nvmlGpuInstanceGetInfo(gpuInstance): + c_info = c_nvmlGpuInstanceInfo_t() + fn = _nvmlGetFunctionPointer("nvmlGpuInstanceGetInfo") + ret = fn(gpuInstance, byref(c_info)) + _nvmlCheckReturn(ret) + return c_info + +def nvmlGpuInstanceGetComputeInstanceProfileInfo(device, profile, engProfile, version=2): + if version == 2: + c_info = c_nvmlComputeInstanceProfileInfo_v2_t() + fn = _nvmlGetFunctionPointer("nvmlGpuInstanceGetComputeInstanceProfileInfoV") + elif version == 1: + c_info = c_nvmlComputeInstanceProfileInfo_t() + fn = _nvmlGetFunctionPointer("nvmlGpuInstanceGetComputeInstanceProfileInfo") + else: + raise NVMLError(NVML_ERROR_FUNCTION_NOT_FOUND) + ret = fn(device, profile, engProfile, byref(c_info)) + _nvmlCheckReturn(ret) + return c_info + +# Define function alias for the API exposed by NVML +nvmlGpuInstanceGetComputeInstanceProfileInfoV = nvmlGpuInstanceGetComputeInstanceProfileInfo + +def nvmlGpuInstanceGetComputeInstanceRemainingCapacity(gpuInstance, profileId): + c_count = c_uint() + fn = _nvmlGetFunctionPointer("nvmlGpuInstanceGetComputeInstanceRemainingCapacity") + ret = fn(gpuInstance, profileId, byref(c_count)) + _nvmlCheckReturn(ret) + return c_count.value + +def nvmlGpuInstanceGetComputeInstancePossiblePlacements(gpuInstance, profileId, placementsRef, countRef): + fn = _nvmlGetFunctionPointer("nvmlGpuInstanceGetComputeInstancePossiblePlacements") + ret = fn(gpuInstance, profileId, placementsRef, countRef) + _nvmlCheckReturn(ret) + return NVML_SUCCESS + +def nvmlGpuInstanceCreateComputeInstance(gpuInstance, profileId): + c_instance = c_nvmlComputeInstance_t() + fn = _nvmlGetFunctionPointer("nvmlGpuInstanceCreateComputeInstance") + ret = fn(gpuInstance, profileId, byref(c_instance)) + _nvmlCheckReturn(ret) + return c_instance + +def nvmlGpuInstanceCreateComputeInstanceWithPlacement(gpuInstance, profileId, placement): + c_instance = c_nvmlComputeInstance_t() + fn = _nvmlGetFunctionPointer("nvmlGpuInstanceCreateComputeInstanceWithPlacement") + ret = fn(gpuInstance, profileId, placement, byref(c_instance)) + _nvmlCheckReturn(ret) + return c_instance + +def nvmlComputeInstanceDestroy(computeInstance): + fn = _nvmlGetFunctionPointer("nvmlComputeInstanceDestroy") + ret = fn(computeInstance) + _nvmlCheckReturn(ret) + return NVML_SUCCESS + +def nvmlGpuInstanceGetComputeInstances(gpuInstance, profileId, computeInstancesRef, countRef): + fn = _nvmlGetFunctionPointer("nvmlGpuInstanceGetComputeInstances") + ret = fn(gpuInstance, profileId, computeInstancesRef, countRef) + _nvmlCheckReturn(ret) + return NVML_SUCCESS + +def nvmlGpuInstanceGetComputeInstanceById(gpuInstance, computeInstanceId): + c_instance = c_nvmlComputeInstance_t() + fn = _nvmlGetFunctionPointer("nvmlGpuInstanceGetComputeInstanceById") + ret = fn(gpuInstance, computeInstanceId, byref(c_instance)) + _nvmlCheckReturn(ret) + return c_instance + +def nvmlComputeInstanceGetInfo_v2(computeInstance): + c_info = c_nvmlComputeInstanceInfo_t() + fn = _nvmlGetFunctionPointer("nvmlComputeInstanceGetInfo_v2") + ret = fn(computeInstance, byref(c_info)) + _nvmlCheckReturn(ret) + return c_info + +def nvmlComputeInstanceGetInfo(computeInstance): + return nvmlComputeInstanceGetInfo_v2(computeInstance) + +def nvmlDeviceIsMigDeviceHandle(device): + c_isMigDevice = c_uint() + fn = _nvmlGetFunctionPointer("nvmlDeviceIsMigDeviceHandle") + ret = fn(device, byref(c_isMigDevice)) + _nvmlCheckReturn(ret) + return c_isMigDevice + +def nvmlDeviceGetGpuInstanceId(device): + c_gpuInstanceId = c_uint() + fn = _nvmlGetFunctionPointer("nvmlDeviceGetGpuInstanceId") + ret = fn(device, byref(c_gpuInstanceId)) + _nvmlCheckReturn(ret) + return c_gpuInstanceId.value + +def nvmlDeviceGetComputeInstanceId(device): + c_computeInstanceId = c_uint() + fn = _nvmlGetFunctionPointer("nvmlDeviceGetComputeInstanceId") + ret = fn(device, byref(c_computeInstanceId)) + _nvmlCheckReturn(ret) + return c_computeInstanceId.value + +def nvmlDeviceGetMaxMigDeviceCount(device): + c_count = c_uint() + fn = _nvmlGetFunctionPointer("nvmlDeviceGetMaxMigDeviceCount") + ret = fn(device, byref(c_count)) + _nvmlCheckReturn(ret) + return c_count.value + +def nvmlDeviceGetMigDeviceHandleByIndex(device, index): + c_index = c_uint(index) + migDevice = c_nvmlDevice_t() + fn = _nvmlGetFunctionPointer("nvmlDeviceGetMigDeviceHandleByIndex") + ret = fn(device, c_index, byref(migDevice)) + _nvmlCheckReturn(ret) + return migDevice + +def nvmlDeviceGetDeviceHandleFromMigDeviceHandle(migDevice): + device = c_nvmlDevice_t() + fn = _nvmlGetFunctionPointer("nvmlDeviceGetDeviceHandleFromMigDeviceHandle") + ret = fn(migDevice, byref(device)) + _nvmlCheckReturn(ret) + return device + +def nvmlDeviceGetAttributes_v2(device): + c_attrs = c_nvmlDeviceAttributes() + fn = _nvmlGetFunctionPointer("nvmlDeviceGetAttributes_v2") + ret = fn(device, byref(c_attrs)) + _nvmlCheckReturn(ret) + return c_attrs + +def nvmlDeviceGetAttributes(device): + return nvmlDeviceGetAttributes_v2(device) + +def nvmlDeviceGetRemappedRows(device): + fn = _nvmlGetFunctionPointer("nvmlDeviceGetRemappedRows") + c_corr = c_uint() + c_unc = c_uint() + c_bpending = c_uint() + c_bfailure = c_uint() + ret = fn(device, byref(c_corr), byref(c_unc), byref(c_bpending), byref(c_bfailure)) + _nvmlCheckReturn(ret) + return (c_corr.value, c_unc.value, c_bpending.value, c_bfailure.value) + +def nvmlDeviceGetRowRemapperHistogram(device): + c_vals = c_nvmlRowRemapperHistogramValues() + fn = _nvmlGetFunctionPointer("nvmlDeviceGetRowRemapperHistogram") + ret = fn(device, byref(c_vals)) + _nvmlCheckReturn(ret) + return c_vals + +def nvmlDeviceGetArchitecture(device): + arch = _nvmlDeviceArchitecture_t() + fn = _nvmlGetFunctionPointer("nvmlDeviceGetArchitecture") + ret = fn(device, byref(arch)) + _nvmlCheckReturn(ret) + return arch.value + +def nvmlDeviceGetBusType(device): + c_busType = _nvmlBusType_t() + fn = _nvmlGetFunctionPointer("nvmlDeviceGetBusType") + ret = fn(device, byref(c_busType)) + _nvmlCheckReturn(ret) + return c_busType.value + +def nvmlDeviceGetIrqNum(device): + c_irqNum = c_uint() + fn = _nvmlGetFunctionPointer("nvmlDeviceGetIrqNum") + ret = fn(device, byref(c_irqNum)) + _nvmlCheckReturn(ret) + return c_irqNum.value + +def nvmlDeviceGetNumGpuCores(device): + c_numCores = c_uint() + fn = _nvmlGetFunctionPointer("nvmlDeviceGetNumGpuCores") + ret = fn(device, byref(c_numCores)) + _nvmlCheckReturn(ret) + return c_numCores.value + +def nvmlDeviceGetPowerSource(device): + c_powerSource = _nvmlPowerSource_t() + fn = _nvmlGetFunctionPointer("nvmlDeviceGetPowerSource") + ret = fn(device, byref(c_powerSource)) + _nvmlCheckReturn(ret) + return c_powerSource.value + +def nvmlDeviceGetMemoryBusWidth(device): + c_memBusWidth = c_uint() + fn = _nvmlGetFunctionPointer("nvmlDeviceGetMemoryBusWidth") + ret = fn(device, byref(c_memBusWidth)) + _nvmlCheckReturn(ret) + return c_memBusWidth.value + +def nvmlDeviceGetPcieLinkMaxSpeed(device): + c_speed = _nvmlPcieLinkMaxSpeed_t() + fn = _nvmlGetFunctionPointer("nvmlDeviceGetPcieLinkMaxSpeed") + ret = fn(device, byref(c_speed)) + _nvmlCheckReturn(ret) + return c_speed.value + +def nvmlDeviceGetAdaptiveClockInfoStatus(device): + c_adaptiveClockInfoStatus = _nvmlAdaptiveClockInfoStatus_t() + fn = _nvmlGetFunctionPointer("nvmlDeviceGetAdaptiveClockInfoStatus") + ret = fn(device, byref(c_adaptiveClockInfoStatus)) + _nvmlCheckReturn(ret) + return c_adaptiveClockInfoStatus.value + +def nvmlDeviceGetPcieSpeed(device): + c_speed = c_uint() + fn = _nvmlGetFunctionPointer("nvmlDeviceGetPcieSpeed") + ret = fn(device, byref(c_speed)) + _nvmlCheckReturn(ret) + return c_speed.value + +def nvmlDeviceGetDynamicPstatesInfo(device, c_dynamicpstatesinfo=c_nvmlGpuDynamicPstatesInfo_t()): + isReference = type(c_dynamicpstatesinfo) is not c_nvmlGpuDynamicPstatesInfo_t + dynamicpstatesinfoRef = c_dynamicpstatesinfo if isReference else byref(c_dynamicpstatesinfo) + + fn = _nvmlGetFunctionPointer("nvmlDeviceGetDynamicPstatesInfo"); + ret = fn(device, dynamicpstatesinfoRef) + _nvmlCheckReturn(ret) + return NVML_SUCCESS if isReference else c_dynamicpstatesinfo + +def nvmlDeviceSetFanSpeed_v2(handle, index, speed): + fn = _nvmlGetFunctionPointer("nvmlDeviceSetFanSpeed_v2"); + ret = fn(handle, index, speed) + _nvmlCheckReturn(ret) + return NVML_SUCCESS + +def nvmlDeviceGetThermalSettings(device, sensorindex, c_thermalsettings=c_nvmlGpuThermalSettings_t()): + isReference = type(c_thermalsettings) is not c_nvmlGpuThermalSettings_t + thermalsettingsRef = c_thermalsettings if isReference else byref(c_thermalsettings) + fn = _nvmlGetFunctionPointer("nvmlDeviceGetThermalSettings"); + ret = fn(device, sensorindex, thermalsettingsRef) + _nvmlCheckReturn(ret) + return NVML_SUCCESS if isReference else c_thermalsettings.sensor[:] + +def nvmlDeviceGetMinMaxClockOfPState(device, clockType, pstate, minClockMHz=c_uint(), maxClockMHz=c_uint()): + isReference = (type(minClockMHz) is not c_uint) or (type(maxClockMHz) is not c_uint) + minClockMHzRef = minClockMHz if isReference else byref(minClockMHz) + maxClockMHzRef = maxClockMHz if isReference else byref(maxClockMHz) + fn = _nvmlGetFunctionPointer("nvmlDeviceGetMinMaxClockOfPState"); + ret = fn(device, _nvmlClockType_t(clockType), _nvmlClockType_t(pstate), minClockMHzRef, maxClockMHzRef) + _nvmlCheckReturn(ret) + return NVML_SUCCESS if isReference else (minClockMHz.value, maxClockMHz.value) + +_nvmlPowerMizerMode_t = c_uint +NVML_POWER_MIZER_MODE_ADAPTIVE = 0 +NVML_POWER_MIZER_MODE_PREFER_MAXIMUM_PERFORMANCE = 1 +NVML_POWER_MIZER_MODE_AUTO = 2 +NVML_POWER_MIZER_MODE_PREFER_CONSISTENT_PERFORMANCE = 3 + +class c_nvmlDevicePowerMizerModes_v1_t(_PrintableStructure): + _fields_ = [ + ('currentMode', _nvmlPowerMizerMode_t), + ('mode', _nvmlPowerMizerMode_t), + ('supportedPowerMizerModes', _nvmlPowerMizerMode_t), + ] + +def nvmlDeviceGetPowerMizerMode_v1(device, info): + fn = _nvmlGetFunctionPointer("nvmlDeviceGetPowerMizerMode_v1"); + ret = fn(device, info) + return ret + +def nvmlDeviceSetPowerMizerMode_v1(device, info): + fn = _nvmlGetFunctionPointer("nvmlDeviceSetPowerMizerMode_v1"); + ret = fn(device, info) + return ret + +class c_nvmlClockOffset_t(_PrintableStructure): + _fields_ = [ + ('version', c_uint), + ('type', _nvmlClockType_t), + ('pstate', _nvmlPstates_t), + ('clockOffsetMHz', c_int), + ('minClockOffsetMHz', c_int), + ('maxClockOffsetMHz', c_int), + ] + +nvmlClockOffset_v1 = 0x1000018 + +def nvmlDeviceGetClockOffsets(device, info): + fn = _nvmlGetFunctionPointer("nvmlDeviceGetClockOffsets"); + ret = fn(device, info) + return NVML_SUCCESS + +def nvmlDeviceSetClockOffsets(device, info): + fn = _nvmlGetFunctionPointer("nvmlDeviceSetClockOffsets"); + ret = fn(device, info) + return NVML_SUCCESS + +def nvmlDeviceGetSupportedPerformanceStates(device): + pstates = [] + c_count = c_uint(NVML_MAX_GPU_PERF_PSTATES) + c_size = sizeof(c_uint)*c_count.value + + # NOTE: use 'c_uint' to represent the size of the nvmlPstate_t enumeration. + pstates_array = _nvmlPstates_t * c_count.value + c_pstates = pstates_array() + + fn = _nvmlGetFunctionPointer("nvmlDeviceGetSupportedPerformanceStates") + ret = fn(device, c_pstates, c_size) + _nvmlCheckReturn(ret) + + for value in c_pstates: + if value != NVML_PSTATE_UNKNOWN: + pstates.append(value) + + return pstates + +def nvmlDeviceGetGpcClkVfOffset(device): + offset = c_int32() + fn = _nvmlGetFunctionPointer("nvmlDeviceGetGpcClkVfOffset") + ret = fn(device, byref(offset)) + _nvmlCheckReturn(ret) + return offset.value + +# DEPRECATED: Use nvmlDeviceSetClockOffsets instead; will be removed in CUDA 14.0 +def nvmlDeviceSetGpcClkVfOffset(device, offset): + c_offset = c_int32(offset) + fn = _nvmlGetFunctionPointer("nvmlDeviceSetGpcClkVfOffset") + ret = fn(device, c_offset) + _nvmlCheckReturn(ret) + return NVML_SUCCESS + +def nvmlDeviceGetGpcClkMinMaxVfOffset(device, minOffset=c_int(), maxOffset=c_int()): + isReference = (type(minOffset) is not c_int) or (type(maxOffset) is not c_int) + minOffsetRef = minOffset if isReference else byref(minOffset) + maxOffsetRef = maxOffset if isReference else byref(maxOffset) + fn = _nvmlGetFunctionPointer("nvmlDeviceGetGpcClkMinMaxVfOffset") + ret = fn(device, minOffsetRef, maxOffsetRef) + _nvmlCheckReturn(ret) + return NVML_SUCCESS if isReference else (minOffset.value, maxOffset.value) + +def nvmlDeviceGetMemClkVfOffset(device): + offset = c_int32() + fn = _nvmlGetFunctionPointer("nvmlDeviceGetMemClkVfOffset") + ret = fn(device, byref(offset)) + _nvmlCheckReturn(ret) + return offset.value + +# DEPRECATED: Use nvmlDeviceSetClockOffsets instead; will be removed in CUDA 14.0 +def nvmlDeviceSetMemClkVfOffset(device, offset): + c_offset = c_int32(offset) + fn = _nvmlGetFunctionPointer("nvmlDeviceSetMemClkVfOffset") + ret = fn(device, c_offset) + _nvmlCheckReturn(ret) + return NVML_SUCCESS + +def nvmlDeviceGetMemClkMinMaxVfOffset(device, minOffset=c_int(), maxOffset=c_int()): + isReference = (type(minOffset) is not c_int) or (type(maxOffset) is not c_int) + minOffsetRef = minOffset if isReference else byref(minOffset) + maxOffsetRef = maxOffset if isReference else byref(maxOffset) + + fn = _nvmlGetFunctionPointer("nvmlDeviceGetMemClkMinMaxVfOffset") + ret = fn(device, minOffsetRef, maxOffsetRef) + _nvmlCheckReturn(ret) + return NVML_SUCCESS if isReference else (minOffset.value, maxOffset.value) + +def nvmlSystemSetConfComputeGpusReadyState(state): + c_state = c_uint(state) + fn = _nvmlGetFunctionPointer("nvmlSystemSetConfComputeGpusReadyState") + ret = fn(c_state) + _nvmlCheckReturn(ret) + return NVML_SUCCESS + +def nvmlSystemGetConfComputeGpusReadyState(): + c_state = c_uint() + fn = _nvmlGetFunctionPointer("nvmlSystemGetConfComputeGpusReadyState") + ret = fn(byref(c_state)) + _nvmlCheckReturn(ret) + return c_state.value + +def nvmlSystemGetConfComputeCapabilities(): + c_ccSysCaps = c_nvmlConfComputeSystemCaps_t() + fn = _nvmlGetFunctionPointer("nvmlSystemGetConfComputeCapabilities") + ret = fn(byref(c_ccSysCaps)) + _nvmlCheckReturn(ret) + return c_ccSysCaps + +def nvmlSystemGetConfComputeState(): + c_state = c_nvmlConfComputeSystemState_t() + fn = _nvmlGetFunctionPointer("nvmlSystemGetConfComputeState") + ret = fn(byref(c_state)) + _nvmlCheckReturn(ret) + return c_state + +def nvmlSystemGetConfComputeSettings(settings): + fn = _nvmlGetFunctionPointer("nvmlSystemGetConfComputeSettings") + return fn(settings) + +def nvmlDeviceSetConfComputeUnprotectedMemSize(device, c_ccMemSize): + fn = _nvmlGetFunctionPointer("nvmlDeviceSetConfComputeUnprotectedMemSize") + ret = fn(device, c_ccMemSize) + _nvmlCheckReturn(ret) + return NVML_SUCCESS + +def nvmlDeviceGetConfComputeMemSizeInfo(device): + c_ccMemSize = c_nvmlConfComputeMemSizeInfo_t() + fn = _nvmlGetFunctionPointer("nvmlDeviceGetConfComputeMemSizeInfo") + ret = fn(device, byref(c_ccMemSize)) + _nvmlCheckReturn(ret) + return c_ccMemSize + +def nvmlDeviceGetConfComputeProtectedMemoryUsage(device): + c_memory = c_nvmlMemory_t() + fn = _nvmlGetFunctionPointer("nvmlDeviceGetConfComputeProtectedMemoryUsage") + ret = fn(device, byref(c_memory)) + _nvmlCheckReturn(ret) + return c_memory + +def nvmlDeviceGetConfComputeGpuCertificate(device): + c_cert = c_nvmlConfComputeGpuCertificate_t() + fn = _nvmlGetFunctionPointer("nvmlDeviceGetConfComputeGpuCertificate") + ret = fn(device, byref(c_cert)) + _nvmlCheckReturn(ret) + return c_cert + +def nvmlDeviceGetConfComputeGpuAttestationReport(device, c_nonce): + c_attestReport = c_nvmlConfComputeGpuAttestationReport_t() + c_nonce_arr = (c_uint8 * len(c_nonce))(*(c_nonce)) + setattr(c_attestReport, 'nonce', c_nonce_arr) + fn = _nvmlGetFunctionPointer("nvmlDeviceGetConfComputeGpuAttestationReport") + ret = fn(device, byref(c_attestReport)) + _nvmlCheckReturn(ret) + return c_attestReport + +def nvmlSystemSetConfComputeKeyRotationThresholdInfo(max_atk_adv): + c_keyRotationThrInfo = c_nvmlConfComputeSetKeyRotationThresholdInfo_t(0) + c_keyRotationThrInfo.version = ConfComputeSetKeyRotationThresholdInfo_v1 + c_keyRotationThrInfo.maxAttackerAdvantage = max_atk_adv + fn = _nvmlGetFunctionPointer("nvmlSystemSetConfComputeKeyRotationThresholdInfo") + ret = fn(byref(c_keyRotationThrInfo)) + _nvmlCheckReturn(ret) + return NVML_SUCCESS + +def nvmlSystemGetConfComputeKeyRotationThresholdInfo(): + c_keyRotationThrInfo = c_nvmlConfComputeGetKeyRotationThresholdInfo_t(0) + c_keyRotationThrInfo.version = ConfComputeGetKeyRotationThresholdInfo_v1 + fn = _nvmlGetFunctionPointer("nvmlSystemGetConfComputeKeyRotationThresholdInfo") + ret = fn(byref(c_keyRotationThrInfo)) + _nvmlCheckReturn(ret) + return c_keyRotationThrInfo + +## GPM ## +######### + +## Enums/defines + +#### GPM Metric Identifiers +NVML_GPM_METRIC_GRAPHICS_UTIL = 1 # Percentage of time any compute/graphics app was active on the GPU. 0.0 - 100.0 +NVML_GPM_METRIC_SM_UTIL = 2 # Percentage of SMs that were busy. 0.0 - 100.0 +NVML_GPM_METRIC_SM_OCCUPANCY = 3 # Percentage of warps that were active vs theoretical maximum. 0.0 - 100.0 +NVML_GPM_METRIC_INTEGER_UTIL = 4 # Percentage of time the GPU's SMs were doing integer operations. 0.0 - 100.0 +NVML_GPM_METRIC_ANY_TENSOR_UTIL = 5 # Percentage of time the GPU's SMs were doing ANY tensor operations. 0.0 - 100.0 +NVML_GPM_METRIC_DFMA_TENSOR_UTIL = 6 # Percentage of time the GPU's SMs were doing DFMA tensor operations. 0.0 - 100.0 +NVML_GPM_METRIC_HMMA_TENSOR_UTIL = 7 # Percentage of time the GPU's SMs were doing HMMA tensor operations. 0.0 - 100.0 +NVML_GPM_METRIC_DMMA_TENSOR_UTIL = 8 # Percentage of time the GPU's SMs were doing DMMA tensor operations. 0.0 - 100.0 +NVML_GPM_METRIC_IMMA_TENSOR_UTIL = 9 # Percentage of time the GPU's SMs were doing IMMA tensor operations. 0.0 - 100.0 +NVML_GPM_METRIC_DRAM_BW_UTIL = 10 # Percentage of DRAM bw used vs theoretical maximum. 0.0 - 100.0 +NVML_GPM_METRIC_FP64_UTIL = 11 # Percentage of time the GPU's SMs were doing non-tensor FP64 math. 0.0 - 100.0 +NVML_GPM_METRIC_FP32_UTIL = 12 # Percentage of time the GPU's SMs were doing non-tensor FP32 math. 0.0 - 100.0 +NVML_GPM_METRIC_FP16_UTIL = 13 # Percentage of time the GPU's SMs were doing non-tensor FP16 math. 0.0 - 100.0 +NVML_GPM_METRIC_PCIE_TX_PER_SEC = 20 # PCIe traffic from this GPU in MiB/sec +NVML_GPM_METRIC_PCIE_RX_PER_SEC = 21 # PCIe traffic to this GPU in MiB/sec +NVML_GPM_METRIC_NVDEC_0_UTIL = 30 # Percent utilization of NVDEC 0. 0.0 - 100.0 +NVML_GPM_METRIC_NVDEC_1_UTIL = 31 # Percent utilization of NVDEC 1. 0.0 - 100.0 +NVML_GPM_METRIC_NVDEC_2_UTIL = 32 # Percent utilization of NVDEC 2. 0.0 - 100.0 +NVML_GPM_METRIC_NVDEC_3_UTIL = 33 # Percent utilization of NVDEC 3. 0.0 - 100.0 +NVML_GPM_METRIC_NVDEC_4_UTIL = 34 # Percent utilization of NVDEC 4. 0.0 - 100.0 +NVML_GPM_METRIC_NVDEC_5_UTIL = 35 # Percent utilization of NVDEC 5. 0.0 - 100.0 +NVML_GPM_METRIC_NVDEC_6_UTIL = 36 # Percent utilization of NVDEC 6. 0.0 - 100.0 +NVML_GPM_METRIC_NVDEC_7_UTIL = 37 # Percent utilization of NVDEC 7. 0.0 - 100.0 +NVML_GPM_METRIC_NVJPG_0_UTIL = 40 # Percent utilization of NVJPG 0. 0.0 - 100.0 +NVML_GPM_METRIC_NVJPG_1_UTIL = 41 # Percent utilization of NVJPG 1. 0.0 - 100.0 +NVML_GPM_METRIC_NVJPG_2_UTIL = 42 # Percent utilization of NVJPG 2. 0.0 - 100.0 +NVML_GPM_METRIC_NVJPG_3_UTIL = 43 # Percent utilization of NVJPG 3. 0.0 - 100.0 +NVML_GPM_METRIC_NVJPG_4_UTIL = 44 # Percent utilization of NVJPG 4. 0.0 - 100.0 +NVML_GPM_METRIC_NVJPG_5_UTIL = 45 # Percent utilization of NVJPG 5. 0.0 - 100.0 +NVML_GPM_METRIC_NVJPG_6_UTIL = 46 # Percent utilization of NVJPG 6. 0.0 - 100.0 +NVML_GPM_METRIC_NVJPG_7_UTIL = 47 # Percent utilization of NVJPG 7. 0.0 - 100.0 +NVML_GPM_METRIC_NVOFA_0_UTIL = 50 # Percent utilization of NVOFA 0. 0.0 - 100.0 +NVML_GPM_METRIC_NVOFA_1_UTIL = 51 # Percent utilization of NVOFA 1. 0.0 - 100.0 +NVML_GPM_METRIC_NVLINK_TOTAL_RX_PER_SEC = 60 # NvLink read bandwidth for all links in MiB/sec +NVML_GPM_METRIC_NVLINK_TOTAL_TX_PER_SEC = 61 # NvLink write bandwidth for all links in MiB/sec +NVML_GPM_METRIC_NVLINK_L0_RX_PER_SEC = 62 # NvLink read bandwidth for link 0 in MiB/sec +NVML_GPM_METRIC_NVLINK_L0_TX_PER_SEC = 63 # NvLink write bandwidth for link 0 in MiB/sec +NVML_GPM_METRIC_NVLINK_L1_RX_PER_SEC = 64 # NvLink read bandwidth for link 1 in MiB/sec +NVML_GPM_METRIC_NVLINK_L1_TX_PER_SEC = 65 # NvLink write bandwidth for link 1 in MiB/sec +NVML_GPM_METRIC_NVLINK_L2_RX_PER_SEC = 66 # NvLink read bandwidth for link 2 in MiB/sec +NVML_GPM_METRIC_NVLINK_L2_TX_PER_SEC = 67 # NvLink write bandwidth for link 2 in MiB/sec +NVML_GPM_METRIC_NVLINK_L3_RX_PER_SEC = 68 # NvLink read bandwidth for link 3 in MiB/sec +NVML_GPM_METRIC_NVLINK_L3_TX_PER_SEC = 69 # NvLink write bandwidth for link 3 in MiB/sec +NVML_GPM_METRIC_NVLINK_L4_RX_PER_SEC = 70 # NvLink read bandwidth for link 4 in MiB/sec +NVML_GPM_METRIC_NVLINK_L4_TX_PER_SEC = 71 # NvLink write bandwidth for link 4 in MiB/sec +NVML_GPM_METRIC_NVLINK_L5_RX_PER_SEC = 72 # NvLink read bandwidth for link 5 in MiB/sec +NVML_GPM_METRIC_NVLINK_L5_TX_PER_SEC = 73 # NvLink write bandwidth for link 5 in MiB/sec +NVML_GPM_METRIC_NVLINK_L6_RX_PER_SEC = 74 # NvLink read bandwidth for link 6 in MiB/sec +NVML_GPM_METRIC_NVLINK_L6_TX_PER_SEC = 75 # NvLink write bandwidth for link 6 in MiB/sec +NVML_GPM_METRIC_NVLINK_L7_RX_PER_SEC = 76 # NvLink read bandwidth for link 7 in MiB/sec +NVML_GPM_METRIC_NVLINK_L7_TX_PER_SEC = 77 # NvLink write bandwidth for link 7 in MiB/sec +NVML_GPM_METRIC_NVLINK_L8_RX_PER_SEC = 78 # NvLink read bandwidth for link 8 in MiB/sec +NVML_GPM_METRIC_NVLINK_L8_TX_PER_SEC = 79 # NvLink write bandwidth for link 8 in MiB/sec +NVML_GPM_METRIC_NVLINK_L9_RX_PER_SEC = 80 # NvLink read bandwidth for link 9 in MiB/sec +NVML_GPM_METRIC_NVLINK_L9_TX_PER_SEC = 81 # NvLink write bandwidth for link 9 in MiB/sec +NVML_GPM_METRIC_NVLINK_L10_RX_PER_SEC = 82 # NvLink read bandwidth for link 10 in MiB/sec +NVML_GPM_METRIC_NVLINK_L10_TX_PER_SEC = 83 # NvLink write bandwidth for link 10 in MiB/sec +NVML_GPM_METRIC_NVLINK_L11_RX_PER_SEC = 84 # NvLink read bandwidth for link 11 in MiB/sec +NVML_GPM_METRIC_NVLINK_L11_TX_PER_SEC = 85 # NvLink write bandwidth for link 11 in MiB/sec +NVML_GPM_METRIC_NVLINK_L12_RX_PER_SEC = 86 # NvLink read bandwidth for link 12 in MiB/sec +NVML_GPM_METRIC_NVLINK_L12_TX_PER_SEC = 87 # NvLink write bandwidth for link 12 in MiB/sec +NVML_GPM_METRIC_NVLINK_L13_RX_PER_SEC = 88 # NvLink read bandwidth for link 13 in MiB/sec +NVML_GPM_METRIC_NVLINK_L13_TX_PER_SEC = 89 # NvLink write bandwidth for link 13 in MiB/sec +NVML_GPM_METRIC_NVLINK_L14_RX_PER_SEC = 90 # NvLink read bandwidth for link 14 in MiB/sec +NVML_GPM_METRIC_NVLINK_L14_TX_PER_SEC = 91 # NvLink write bandwidth for link 14 in MiB/sec +NVML_GPM_METRIC_NVLINK_L15_RX_PER_SEC = 92 # NvLink read bandwidth for link 15 in MiB/sec +NVML_GPM_METRIC_NVLINK_L15_TX_PER_SEC = 93 # NvLink write bandwidth for link 15 in MiB/sec +NVML_GPM_METRIC_NVLINK_L16_RX_PER_SEC = 94 # NvLink read bandwidth for link 16 in MiB/sec +NVML_GPM_METRIC_NVLINK_L16_TX_PER_SEC = 95 # NvLink write bandwidth for link 16 in MiB/sec +NVML_GPM_METRIC_NVLINK_L17_RX_PER_SEC = 96 # NvLink read bandwidth for link 17 in MiB/sec +NVML_GPM_METRIC_NVLINK_L17_TX_PER_SEC = 97 # NvLink write bandwidth for link 17 in MiB/sec +NVML_GPM_METRIC_C2C_TOTAL_TX_PER_SEC = 100 +NVML_GPM_METRIC_C2C_TOTAL_RX_PER_SEC = 101 +NVML_GPM_METRIC_C2C_DATA_TX_PER_SEC = 102 +NVML_GPM_METRIC_C2C_DATA_RX_PER_SEC = 103 +NVML_GPM_METRIC_C2C_LINK0_TOTAL_TX_PER_SEC = 104 +NVML_GPM_METRIC_C2C_LINK0_TOTAL_RX_PER_SEC = 105 +NVML_GPM_METRIC_C2C_LINK0_DATA_TX_PER_SEC = 106 +NVML_GPM_METRIC_C2C_LINK0_DATA_RX_PER_SEC = 107 +NVML_GPM_METRIC_C2C_LINK1_TOTAL_TX_PER_SEC = 108 +NVML_GPM_METRIC_C2C_LINK1_TOTAL_RX_PER_SEC = 109 +NVML_GPM_METRIC_C2C_LINK1_DATA_TX_PER_SEC = 110 +NVML_GPM_METRIC_C2C_LINK1_DATA_RX_PER_SEC = 111 +NVML_GPM_METRIC_C2C_LINK2_TOTAL_TX_PER_SEC = 112 +NVML_GPM_METRIC_C2C_LINK2_TOTAL_RX_PER_SEC = 113 +NVML_GPM_METRIC_C2C_LINK2_DATA_TX_PER_SEC = 114 +NVML_GPM_METRIC_C2C_LINK2_DATA_RX_PER_SEC = 115 +NVML_GPM_METRIC_C2C_LINK3_TOTAL_TX_PER_SEC = 116 +NVML_GPM_METRIC_C2C_LINK3_TOTAL_RX_PER_SEC = 117 +NVML_GPM_METRIC_C2C_LINK3_DATA_TX_PER_SEC = 118 +NVML_GPM_METRIC_C2C_LINK3_DATA_RX_PER_SEC = 119 +NVML_GPM_METRIC_C2C_LINK4_TOTAL_TX_PER_SEC = 120 +NVML_GPM_METRIC_C2C_LINK4_TOTAL_RX_PER_SEC = 121 +NVML_GPM_METRIC_C2C_LINK4_DATA_TX_PER_SEC = 122 +NVML_GPM_METRIC_C2C_LINK4_DATA_RX_PER_SEC = 123 +NVML_GPM_METRIC_C2C_LINK5_TOTAL_TX_PER_SEC = 124 +NVML_GPM_METRIC_C2C_LINK5_TOTAL_RX_PER_SEC = 125 +NVML_GPM_METRIC_C2C_LINK5_DATA_TX_PER_SEC = 126 +NVML_GPM_METRIC_C2C_LINK5_DATA_RX_PER_SEC = 127 +NVML_GPM_METRIC_C2C_LINK6_TOTAL_TX_PER_SEC = 128 +NVML_GPM_METRIC_C2C_LINK6_TOTAL_RX_PER_SEC = 129 +NVML_GPM_METRIC_C2C_LINK6_DATA_TX_PER_SEC = 130 +NVML_GPM_METRIC_C2C_LINK6_DATA_RX_PER_SEC = 131 +NVML_GPM_METRIC_C2C_LINK7_TOTAL_TX_PER_SEC = 132 +NVML_GPM_METRIC_C2C_LINK7_TOTAL_RX_PER_SEC = 133 +NVML_GPM_METRIC_C2C_LINK7_DATA_TX_PER_SEC = 134 +NVML_GPM_METRIC_C2C_LINK7_DATA_RX_PER_SEC = 135 +NVML_GPM_METRIC_C2C_LINK8_TOTAL_TX_PER_SEC = 136 +NVML_GPM_METRIC_C2C_LINK8_TOTAL_RX_PER_SEC = 137 +NVML_GPM_METRIC_C2C_LINK8_DATA_TX_PER_SEC = 138 +NVML_GPM_METRIC_C2C_LINK8_DATA_RX_PER_SEC = 139 +NVML_GPM_METRIC_C2C_LINK9_TOTAL_TX_PER_SEC = 140 +NVML_GPM_METRIC_C2C_LINK9_TOTAL_RX_PER_SEC = 141 +NVML_GPM_METRIC_C2C_LINK9_DATA_TX_PER_SEC = 142 +NVML_GPM_METRIC_C2C_LINK9_DATA_RX_PER_SEC = 143 +NVML_GPM_METRIC_C2C_LINK10_TOTAL_TX_PER_SEC = 144 +NVML_GPM_METRIC_C2C_LINK10_TOTAL_RX_PER_SEC = 145 +NVML_GPM_METRIC_C2C_LINK10_DATA_TX_PER_SEC = 146 +NVML_GPM_METRIC_C2C_LINK10_DATA_RX_PER_SEC = 147 +NVML_GPM_METRIC_C2C_LINK11_TOTAL_TX_PER_SEC = 148 +NVML_GPM_METRIC_C2C_LINK11_TOTAL_RX_PER_SEC = 149 +NVML_GPM_METRIC_C2C_LINK11_DATA_TX_PER_SEC = 150 +NVML_GPM_METRIC_C2C_LINK11_DATA_RX_PER_SEC = 151 +NVML_GPM_METRIC_C2C_LINK12_TOTAL_TX_PER_SEC = 152 +NVML_GPM_METRIC_C2C_LINK12_TOTAL_RX_PER_SEC = 153 +NVML_GPM_METRIC_C2C_LINK12_DATA_TX_PER_SEC = 154 +NVML_GPM_METRIC_C2C_LINK12_DATA_RX_PER_SEC = 155 +NVML_GPM_METRIC_C2C_LINK13_TOTAL_TX_PER_SEC = 156 +NVML_GPM_METRIC_C2C_LINK13_TOTAL_RX_PER_SEC = 157 +NVML_GPM_METRIC_C2C_LINK13_DATA_TX_PER_SEC = 158 +NVML_GPM_METRIC_C2C_LINK13_DATA_RX_PER_SEC = 159 +NVML_GPM_METRIC_HOSTMEM_CACHE_HIT = 160 +NVML_GPM_METRIC_HOSTMEM_CACHE_MISS = 161 +NVML_GPM_METRIC_PEERMEM_CACHE_HIT = 162 +NVML_GPM_METRIC_PEERMEM_CACHE_MISS = 163 +NVML_GPM_METRIC_DRAM_CACHE_HIT = 164 +NVML_GPM_METRIC_DRAM_CACHE_MISS = 165 +NVML_GPM_METRIC_NVENC_0_UTIL = 166 +NVML_GPM_METRIC_NVENC_1_UTIL = 167 +NVML_GPM_METRIC_NVENC_2_UTIL = 168 +NVML_GPM_METRIC_NVENC_3_UTIL = 169 +NVML_GPM_METRIC_GR0_CTXSW_CYCLES_ELAPSED = 170 +NVML_GPM_METRIC_GR0_CTXSW_CYCLES_ACTIVE = 171 +NVML_GPM_METRIC_GR0_CTXSW_REQUESTS = 172 +NVML_GPM_METRIC_GR0_CTXSW_CYCLES_PER_REQ = 173 +NVML_GPM_METRIC_GR0_CTXSW_ACTIVE_PCT = 174 +NVML_GPM_METRIC_GR1_CTXSW_CYCLES_ELAPSED = 175 +NVML_GPM_METRIC_GR1_CTXSW_CYCLES_ACTIVE = 176 +NVML_GPM_METRIC_GR1_CTXSW_REQUESTS = 177 +NVML_GPM_METRIC_GR1_CTXSW_CYCLES_PER_REQ = 178 +NVML_GPM_METRIC_GR1_CTXSW_ACTIVE_PCT = 179 +NVML_GPM_METRIC_GR2_CTXSW_CYCLES_ELAPSED = 180 +NVML_GPM_METRIC_GR2_CTXSW_CYCLES_ACTIVE = 181 +NVML_GPM_METRIC_GR2_CTXSW_REQUESTS = 182 +NVML_GPM_METRIC_GR2_CTXSW_CYCLES_PER_REQ = 183 +NVML_GPM_METRIC_GR2_CTXSW_ACTIVE_PCT = 184 +NVML_GPM_METRIC_GR3_CTXSW_CYCLES_ELAPSED = 185 +NVML_GPM_METRIC_GR3_CTXSW_CYCLES_ACTIVE = 186 +NVML_GPM_METRIC_GR3_CTXSW_REQUESTS = 187 +NVML_GPM_METRIC_GR3_CTXSW_CYCLES_PER_REQ = 188 +NVML_GPM_METRIC_GR3_CTXSW_ACTIVE_PCT = 189 +NVML_GPM_METRIC_GR4_CTXSW_CYCLES_ELAPSED = 190 +NVML_GPM_METRIC_GR4_CTXSW_CYCLES_ACTIVE = 191 +NVML_GPM_METRIC_GR4_CTXSW_REQUESTS = 192 +NVML_GPM_METRIC_GR4_CTXSW_CYCLES_PER_REQ = 193 +NVML_GPM_METRIC_GR4_CTXSW_ACTIVE_PCT = 194 +NVML_GPM_METRIC_GR5_CTXSW_CYCLES_ELAPSED = 195 +NVML_GPM_METRIC_GR5_CTXSW_CYCLES_ACTIVE = 196 +NVML_GPM_METRIC_GR5_CTXSW_REQUESTS = 197 +NVML_GPM_METRIC_GR5_CTXSW_CYCLES_PER_REQ = 198 +NVML_GPM_METRIC_GR5_CTXSW_ACTIVE_PCT = 199 +NVML_GPM_METRIC_GR6_CTXSW_CYCLES_ELAPSED = 200 +NVML_GPM_METRIC_GR6_CTXSW_CYCLES_ACTIVE = 201 +NVML_GPM_METRIC_GR6_CTXSW_REQUESTS = 202 +NVML_GPM_METRIC_GR6_CTXSW_CYCLES_PER_REQ = 203 +NVML_GPM_METRIC_GR6_CTXSW_ACTIVE_PCT = 204 +NVML_GPM_METRIC_GR7_CTXSW_CYCLES_ELAPSED = 205 +NVML_GPM_METRIC_GR7_CTXSW_CYCLES_ACTIVE = 206 +NVML_GPM_METRIC_GR7_CTXSW_REQUESTS = 207 +NVML_GPM_METRIC_GR7_CTXSW_CYCLES_PER_REQ = 208 +NVML_GPM_METRIC_GR7_CTXSW_ACTIVE_PCT = 209 +NVML_GPM_METRIC_NVLINK_L18_RX_PER_SEC = 212 +NVML_GPM_METRIC_NVLINK_L18_TX_PER_SEC = 213 +NVML_GPM_METRIC_NVLINK_L19_RX_PER_SEC = 214 +NVML_GPM_METRIC_NVLINK_L19_TX_PER_SEC = 215 +NVML_GPM_METRIC_NVLINK_L20_RX_PER_SEC = 216 +NVML_GPM_METRIC_NVLINK_L20_TX_PER_SEC = 217 +NVML_GPM_METRIC_NVLINK_L21_RX_PER_SEC = 218 +NVML_GPM_METRIC_NVLINK_L21_TX_PER_SEC = 219 +NVML_GPM_METRIC_NVLINK_L22_RX_PER_SEC = 220 +NVML_GPM_METRIC_NVLINK_L22_TX_PER_SEC = 221 +NVML_GPM_METRIC_NVLINK_L23_RX_PER_SEC = 222 +NVML_GPM_METRIC_NVLINK_L23_TX_PER_SEC = 223 +NVML_GPM_METRIC_NVLINK_L24_RX_PER_SEC = 224 +NVML_GPM_METRIC_NVLINK_L24_TX_PER_SEC = 225 +NVML_GPM_METRIC_NVLINK_L25_RX_PER_SEC = 226 +NVML_GPM_METRIC_NVLINK_L25_TX_PER_SEC = 227 +NVML_GPM_METRIC_NVLINK_L26_RX_PER_SEC = 228 +NVML_GPM_METRIC_NVLINK_L26_TX_PER_SEC = 229 +NVML_GPM_METRIC_NVLINK_L27_RX_PER_SEC = 230 +NVML_GPM_METRIC_NVLINK_L27_TX_PER_SEC = 231 +NVML_GPM_METRIC_NVLINK_L28_RX_PER_SEC = 232 +NVML_GPM_METRIC_NVLINK_L28_TX_PER_SEC = 233 +NVML_GPM_METRIC_NVLINK_L29_RX_PER_SEC = 234 +NVML_GPM_METRIC_NVLINK_L29_TX_PER_SEC = 235 +NVML_GPM_METRIC_NVLINK_L30_RX_PER_SEC = 236 +NVML_GPM_METRIC_NVLINK_L30_TX_PER_SEC = 237 +NVML_GPM_METRIC_NVLINK_L31_RX_PER_SEC = 238 +NVML_GPM_METRIC_NVLINK_L31_TX_PER_SEC = 239 +NVML_GPM_METRIC_NVLINK_L32_RX_PER_SEC = 240 +NVML_GPM_METRIC_NVLINK_L32_TX_PER_SEC = 241 +NVML_GPM_METRIC_NVLINK_L33_RX_PER_SEC = 242 +NVML_GPM_METRIC_NVLINK_L33_TX_PER_SEC = 243 +NVML_GPM_METRIC_NVLINK_L34_RX_PER_SEC = 244 +NVML_GPM_METRIC_NVLINK_L34_TX_PER_SEC = 245 +NVML_GPM_METRIC_NVLINK_L35_RX_PER_SEC = 246 +NVML_GPM_METRIC_NVLINK_L35_TX_PER_SEC = 247 +NVML_GPM_METRIC_SM_CYCLES_ELAPSED = 248 # The GPU's SM cycles elapsed since reboot +NVML_GPM_METRIC_SM_CYCLES_ACTIVE = 249 # The GPU's SM activity since reboot +NVML_GPM_METRIC_MMA_CYCLES_ACTIVE = 250 # The GPU's SM MMA tensor activity since reboot +NVML_GPM_METRIC_DMMA_CYCLES_ACTIVE = 251 # The GPU's SM DMMA tensor activity since reboot +NVML_GPM_METRIC_HMMA_CYCLES_ACTIVE = 252 # The GPU's SM HMMA tensor activity since reboot +NVML_GPM_METRIC_IMMA_CYCLES_ACTIVE = 253 # The GPU's SM IMMA tensor activity since reboot +NVML_GPM_METRIC_DFMA_CYCLES_ACTIVE = 254 # The GPU's SM DFMA tensor activity since reboot +NVML_GPM_METRIC_PCIE_TX = 255 # The PCIe TX traffic since reboot +NVML_GPM_METRIC_PCIE_RX = 256 # The PCIe RX traffic since reboot +NVML_GPM_METRIC_INTEGER_CYCLES_ACTIVE = 257 # The GPU's SM integer activity since reboot +NVML_GPM_METRIC_FP64_CYCLES_ACTIVE = 258 # The GPU's SM FP64 activity since reboot +NVML_GPM_METRIC_FP32_CYCLES_ACTIVE = 259 # The GPU's SM FP64 activity since reboot +NVML_GPM_METRIC_FP16_CYCLES_ACTIVE = 260 # The GPU's SM FP64 activity since reboot +NVML_GPM_METRIC_NVLINK_L0_RX = 261 # NvLink read for link 0 in bytes since reboot +NVML_GPM_METRIC_NVLINK_L0_TX = 262 # NvLink write for link 0 in bytes since reboot +NVML_GPM_METRIC_NVLINK_L1_RX = 263 # NvLink read for link 1 in bytes since reboot +NVML_GPM_METRIC_NVLINK_L1_TX = 264 # NvLink write for link 1 in bytes since reboot +NVML_GPM_METRIC_NVLINK_L2_RX = 265 # NvLink read for link 2 in bytes since reboot +NVML_GPM_METRIC_NVLINK_L2_TX = 266 # NvLink write for link 2 in bytes since reboot +NVML_GPM_METRIC_NVLINK_L3_RX = 267 # NvLink read for link 3 in bytes since reboot +NVML_GPM_METRIC_NVLINK_L3_TX = 268 # NvLink write for link 3 in bytes since reboot +NVML_GPM_METRIC_NVLINK_L4_RX = 269 # NvLink read for link 4 in bytes since reboot +NVML_GPM_METRIC_NVLINK_L4_TX = 270 # NvLink write for link 4 in bytes since reboot +NVML_GPM_METRIC_NVLINK_L5_RX = 271 # NvLink read for link 5 in bytes since reboot +NVML_GPM_METRIC_NVLINK_L5_TX = 272 # NvLink write for link 5 in bytes since reboot +NVML_GPM_METRIC_NVLINK_L6_RX = 273 # NvLink read for link 6 in bytes since reboot +NVML_GPM_METRIC_NVLINK_L6_TX = 274 # NvLink write for link 6 in bytes since reboot +NVML_GPM_METRIC_NVLINK_L7_RX = 275 # NvLink read for link 7 in bytes since reboot +NVML_GPM_METRIC_NVLINK_L7_TX = 276 # NvLink write for link 7 in bytes since reboot +NVML_GPM_METRIC_NVLINK_L8_RX = 277 # NvLink read for link 8 in bytes since reboot +NVML_GPM_METRIC_NVLINK_L8_TX = 278 # NvLink write for link 8 in bytes since reboot +NVML_GPM_METRIC_NVLINK_L9_RX = 279 # NvLink read for link 9 in bytes since reboot +NVML_GPM_METRIC_NVLINK_L9_TX = 280 # NvLink write for link 9 in bytes since reboot +NVML_GPM_METRIC_NVLINK_L10_RX = 281 # NvLink read for link 10 in bytes since reboot +NVML_GPM_METRIC_NVLINK_L10_TX = 282 # NvLink write for link 10 in bytes since reboot +NVML_GPM_METRIC_NVLINK_L11_RX = 283 # NvLink read for link 11 in bytes since reboot +NVML_GPM_METRIC_NVLINK_L11_TX = 284 # NvLink write for link 11 in bytes since reboot +NVML_GPM_METRIC_NVLINK_L12_RX = 285 # NvLink read for link 12 in bytes since reboot +NVML_GPM_METRIC_NVLINK_L12_TX = 286 # NvLink write for link 12 in bytes since reboot +NVML_GPM_METRIC_NVLINK_L13_RX = 287 # NvLink read for link 13 in bytes since reboot +NVML_GPM_METRIC_NVLINK_L13_TX = 288 # NvLink write for link 13 in bytes since reboot +NVML_GPM_METRIC_NVLINK_L14_RX = 289 # NvLink read for link 14 in bytes since reboot +NVML_GPM_METRIC_NVLINK_L14_TX = 290 # NvLink write for link 14 in bytes since reboot +NVML_GPM_METRIC_NVLINK_L15_RX = 291 # NvLink read for link 15 in bytes since reboot +NVML_GPM_METRIC_NVLINK_L15_TX = 292 # NvLink write for link 15 in bytes since reboot +NVML_GPM_METRIC_NVLINK_L16_RX = 293 # NvLink read for link 16 in bytes since reboot +NVML_GPM_METRIC_NVLINK_L16_TX = 294 # NvLink write for link 16 in bytes since reboot +NVML_GPM_METRIC_NVLINK_L17_RX = 295 # NvLink read for link 17 in bytes since reboot +NVML_GPM_METRIC_NVLINK_L17_TX = 296 # NvLink write for link 17 in bytes since reboot +NVML_GPM_METRIC_NVLINK_L18_RX = 297 # NvLink read for link 18 in bytes since reboot +NVML_GPM_METRIC_NVLINK_L18_TX = 298 # NvLink write for link 18 in bytes since reboot +NVML_GPM_METRIC_NVLINK_L19_RX = 299 # NvLink read for link 19 in bytes since reboot +NVML_GPM_METRIC_NVLINK_L19_TX = 300 # NvLink write for link 19 in bytes since reboot +NVML_GPM_METRIC_NVLINK_L20_RX = 301 # NvLink read for link 20 in bytes since reboot +NVML_GPM_METRIC_NVLINK_L20_TX = 302 # NvLink write for link 20 in bytes since reboot +NVML_GPM_METRIC_NVLINK_L21_RX = 303 # NvLink read for link 21 in bytes since reboot +NVML_GPM_METRIC_NVLINK_L21_TX = 304 # NvLink write for link 21 in bytes since reboot +NVML_GPM_METRIC_NVLINK_L22_RX = 305 # NvLink read for link 22 in bytes since reboot +NVML_GPM_METRIC_NVLINK_L22_TX = 306 # NvLink write for link 22 in bytes since reboot +NVML_GPM_METRIC_NVLINK_L23_RX = 307 # NvLink read for link 23 in bytes since reboot +NVML_GPM_METRIC_NVLINK_L23_TX = 308 # NvLink write for link 23 in bytes since reboot +NVML_GPM_METRIC_NVLINK_L24_RX = 309 # NvLink read for link 24 in bytes since reboot +NVML_GPM_METRIC_NVLINK_L24_TX = 310 # NvLink write for link 24 in bytes since reboot +NVML_GPM_METRIC_NVLINK_L25_RX = 311 # NvLink read for link 25 in bytes since reboot +NVML_GPM_METRIC_NVLINK_L25_TX = 312 # NvLink write for link 25 in bytes since reboot +NVML_GPM_METRIC_NVLINK_L26_RX = 313 # NvLink read for link 26 in bytes since reboot +NVML_GPM_METRIC_NVLINK_L26_TX = 314 # NvLink write for link 26 in bytes since reboot +NVML_GPM_METRIC_NVLINK_L27_RX = 315 # NvLink read for link 27 in bytes since reboot +NVML_GPM_METRIC_NVLINK_L27_TX = 316 # NvLink write for link 27 in bytes since reboot +NVML_GPM_METRIC_NVLINK_L28_RX = 317 # NvLink read for link 28 in bytes since reboot +NVML_GPM_METRIC_NVLINK_L28_TX = 318 # NvLink write for link 28 in bytes since reboot +NVML_GPM_METRIC_NVLINK_L29_RX = 319 # NvLink read for link 29 in bytes since reboot +NVML_GPM_METRIC_NVLINK_L29_TX = 320 # NvLink write for link 29 in bytes since reboot +NVML_GPM_METRIC_NVLINK_L30_RX = 321 # NvLink read for link 30 in bytes since reboot +NVML_GPM_METRIC_NVLINK_L30_TX = 322 # NvLink write for link 30 in bytes since reboot +NVML_GPM_METRIC_NVLINK_L31_RX = 323 # NvLink read for link 31 in bytes since reboot +NVML_GPM_METRIC_NVLINK_L31_TX = 324 # NvLink write for link 31 in bytes since reboot +NVML_GPM_METRIC_NVLINK_L32_RX = 325 # NvLink read for link 32 in bytes since reboot +NVML_GPM_METRIC_NVLINK_L32_TX = 326 # NvLink write for link 32 in bytes since reboot +NVML_GPM_METRIC_NVLINK_L33_RX = 327 # NvLink read for link 33 in bytes since reboot +NVML_GPM_METRIC_NVLINK_L33_TX = 328 # NvLink write for link 33 in bytes since reboot +NVML_GPM_METRIC_NVLINK_L34_RX = 329 # NvLink read for link 34 in bytes since reboot +NVML_GPM_METRIC_NVLINK_L34_TX = 330 # NvLink write for link 34 in bytes since reboot +NVML_GPM_METRIC_NVLINK_L35_RX = 331 # NvLink read for link 35 in bytes since reboot +NVML_GPM_METRIC_NVLINK_L35_TX = 332 # NvLink write for link 35 in bytes since reboot +NVML_GPM_METRIC_MAX = 333 # Maximum value above +1 + +## Structs + +class c_nvmlUnitInfo_t(_PrintableStructure): + _fields_ = [ + ('name', c_char * 96), + ('id', c_char * 96), + ('serial', c_char * 96), + ('firmwareVersion', c_char * 96), + ] + +class struct_c_nvmlGpmSample_t(Structure): + pass # opaque handle +c_nvmlGpmSample_t = POINTER(struct_c_nvmlGpmSample_t) + +class c_metricInfo_t(Structure): + _fields_ = [ + ("shortName", c_char_p), + ("longName", c_char_p), + ("unit", c_char_p), + ] + +class c_nvmlGpmMetric_t(_PrintableStructure): + _fields_ = [ + ('metricId', c_uint), + ('nvmlReturn', _nvmlReturn_t), + ('value', c_double), + ('metricInfo', c_metricInfo_t) + ] + +class c_nvmlGpmMetricsGet_t(_PrintableStructure): + _fields_ = [ + ('version', c_uint), + ('numMetrics', c_uint), + ('sample1', c_nvmlGpmSample_t), + ('sample2', c_nvmlGpmSample_t), + ('metrics', c_nvmlGpmMetric_t * NVML_GPM_METRIC_MAX) + ] + +NVML_GPM_METRICS_GET_VERSION = 1 + +class c_nvmlGpmSupport_t(_PrintableStructure): + _fields_ = [ + ('version', c_uint), + ('isSupportedDevice', c_uint), + ] + +NVML_GPM_SUPPORT_VERSION = 1 + +## Functions + +def nvmlGpmMetricsGet(metricsGet): + fn = _nvmlGetFunctionPointer("nvmlGpmMetricsGet") + ret = fn(byref(metricsGet)) + _nvmlCheckReturn(ret) + return metricsGet + +def nvmlGpmSampleFree(gpmSample): + fn = _nvmlGetFunctionPointer("nvmlGpmSampleFree") + ret = fn(gpmSample) + _nvmlCheckReturn(ret) + return + +def nvmlGpmSampleAlloc(): + gpmSample = c_nvmlGpmSample_t() + fn = _nvmlGetFunctionPointer("nvmlGpmSampleAlloc") + ret = fn(byref(gpmSample)) + _nvmlCheckReturn(ret) + return gpmSample + +def nvmlGpmSampleGet(device, gpmSample): + fn = _nvmlGetFunctionPointer("nvmlGpmSampleGet") + ret = fn(device, gpmSample) + _nvmlCheckReturn(ret) + return gpmSample + +def nvmlGpmMigSampleGet(device, gpuInstanceId, gpmSample): + fn = _nvmlGetFunctionPointer("nvmlGpmMigSampleGet") + ret = fn(device, gpuInstanceId, gpmSample) + _nvmlCheckReturn(ret) + return gpmSample + +def nvmlGpmQueryDeviceSupport(device): + gpmSupport = c_nvmlGpmSupport_t() + gpmSupport.version = NVML_GPM_SUPPORT_VERSION + fn = _nvmlGetFunctionPointer("nvmlGpmQueryDeviceSupport") + ret = fn(device, byref(gpmSupport)) + _nvmlCheckReturn(ret) + return gpmSupport + +def nvmlGpmSetStreamingEnabled(device, state): + c_state = c_uint(state) + fn = _nvmlGetFunctionPointer("nvmlGpmSetStreamingEnabled") + ret = fn(device, c_state) + _nvmlCheckReturn(ret) + return NVML_SUCCESS + +def nvmlGpmQueryIfStreamingEnabled(device): + c_state = c_uint() + fn = _nvmlGetFunctionPointer("nvmlGpmQueryIfStreamingEnabled") + ret = fn(device, byref(c_state)) + _nvmlCheckReturn(ret) + return c_state.value + +# Low Power Structure and Function + +NVML_NVLINK_POWER_STATE_HIGH_SPEED = 0x0 +NVML_NVLINK_POWER_STATE_LOW = 0x1 + +NVML_NVLINK_LOW_POWER_THRESHOLD_MIN = 0x1 +NVML_NVLINK_LOW_POWER_THRESHOLD_MAX = 0x1FFF +NVML_NVLINK_LOW_POWER_THRESHOLD_RESET = 0xFFFFFFFF +NVML_NVLINK_LOW_POWER_THRESHOLD_DEFAULT = NVML_NVLINK_LOW_POWER_THRESHOLD_RESET + +class c_nvmlNvLinkPowerThres_t(Structure): + _fields_ = [ + ("lowPwrThreshold", c_uint), + ] + +def nvmlDeviceSetNvLinkDeviceLowPowerThreshold(device, l1threshold): + c_info = c_nvmlNvLinkPowerThres_t() + c_info.lowPwrThreshold = l1threshold + fn = _nvmlGetFunctionPointer("nvmlDeviceSetNvLinkDeviceLowPowerThreshold") + ret = fn(device, byref(c_info)) + _nvmlCheckReturn(ret) + return NVML_SUCCESS + +NVML_GPU_FABRIC_UUID_LEN = 16 + +_nvmlGpuFabricState_t = c_uint +NVML_GPU_FABRIC_STATE_NOT_SUPPORTED = 0 +NVML_GPU_FABRIC_STATE_NOT_STARTED = 1 +NVML_GPU_FABRIC_STATE_IN_PROGRESS = 2 +NVML_GPU_FABRIC_STATE_COMPLETED = 3 + +class c_nvmlGpuFabricInfo_t(_PrintableStructure): + _fields_ = [ + ("clusterUuid", c_uint8 * NVML_DEVICE_UUID_BUFFER_SIZE), + ("status", _nvmlReturn_t), + ("cliqueId", c_uint32), + ("state", _nvmlGpuFabricState_t) + ] + +NVML_GPU_FABRIC_HEALTH_MASK_DEGRADED_BW_NOT_SUPPORTED = 0 +NVML_GPU_FABRIC_HEALTH_MASK_DEGRADED_BW_TRUE = 1 +NVML_GPU_FABRIC_HEALTH_MASK_DEGRADED_BW_FALSE = 2 +NVML_GPU_FABRIC_HEALTH_MASK_SHIFT_DEGRADED_BW = 0 +NVML_GPU_FABRIC_HEALTH_MASK_WIDTH_DEGRADED_BW = 0x3 + +NVML_GPU_FABRIC_HEALTH_MASK_ROUTE_RECOVERY_NOT_SUPPORTED = 0 +NVML_GPU_FABRIC_HEALTH_MASK_ROUTE_RECOVERY_TRUE = 1 +NVML_GPU_FABRIC_HEALTH_MASK_ROUTE_RECOVERY_FALSE = 2 +NVML_GPU_FABRIC_HEALTH_MASK_SHIFT_ROUTE_RECOVERY = 2 +NVML_GPU_FABRIC_HEALTH_MASK_WIDTH_ROUTE_RECOVERY = 0x3 + +NVML_GPU_FABRIC_HEALTH_MASK_ROUTE_UNHEALTHY_NOT_SUPPORTED = 0 +NVML_GPU_FABRIC_HEALTH_MASK_ROUTE_UNHEALTHY_TRUE = 1 +NVML_GPU_FABRIC_HEALTH_MASK_ROUTE_UNHEALTHY_FALSE = 2 +NVML_GPU_FABRIC_HEALTH_MASK_SHIFT_ROUTE_UNHEALTHY = 4 +NVML_GPU_FABRIC_HEALTH_MASK_WIDTH_ROUTE_UNHEALTHY = 0x3 + +NVML_GPU_FABRIC_HEALTH_MASK_ACCESS_TIMEOUT_RECOVERY_NOT_SUPPORTED = 0 +NVML_GPU_FABRIC_HEALTH_MASK_ACCESS_TIMEOUT_RECOVERY_TRUE = 1 +NVML_GPU_FABRIC_HEALTH_MASK_ACCESS_TIMEOUT_RECOVERY_FALSE = 2 +NVML_GPU_FABRIC_HEALTH_MASK_SHIFT_ACCESS_TIMEOUT_RECOVERY = 6 +NVML_GPU_FABRIC_HEALTH_MASK_WIDTH_ACCESS_TIMEOUT_RECOVERY = 0x3 + +NVML_GPU_FABRIC_HEALTH_MASK_INCORRECT_CONFIGURATION_NOT_SUPPORTED = 0 +NVML_GPU_FABRIC_HEALTH_MASK_INCORRECT_CONFIGURATION_NONE = 1 +NVML_GPU_FABRIC_HEALTH_MASK_INCORRECT_CONFIGURATION_INCORRECT_SYSGUID = 2 +NVML_GPU_FABRIC_HEALTH_MASK_INCORRECT_CONFIGURATION_INCORRECT_CHASSIS_SN = 3 +NVML_GPU_FABRIC_HEALTH_MASK_INCORRECT_CONFIGURATION_NO_PARTITION = 4 +NVML_GPU_FABRIC_HEALTH_MASK_INCORRECT_CONFIGURATION_INSUFFICIENT_NVLINKS = 5 +NVML_GPU_FABRIC_HEALTH_MASK_INCORRECT_CONFIGURATION_INCOMPATIBLE_GPU_FW = 6 +NVML_GPU_FABRIC_HEALTH_MASK_INCORRECT_CONFIURATION_INVALID_LOCATION = 7 +NVML_GPU_FABRIC_HEALTH_MASK_INCORRECT_CONFIGURATION_INVALID_LOCATION = NVML_GPU_FABRIC_HEALTH_MASK_INCORRECT_CONFIURATION_INVALID_LOCATION +NVML_GPU_FABRIC_HEALTH_MASK_INCORRECT_CONFIGURATION_GPU_STATE_INVALID = 8 + +NVML_GPU_FABRIC_HEALTH_MASK_SHIFT_INCORRECT_CONFIGURATION = 8 +NVML_GPU_FABRIC_HEALTH_MASK_WIDTH_INCORRECT_CONFIGURATION = 0xf + +NVML_GPU_FABRIC_HEALTH_MASK_PARTITION_ASSIGNED_NOT_SUPPORTED = 0 +NVML_GPU_FABRIC_HEALTH_MASK_PARTITION_ASSIGNED_TRUE = 1 +NVML_GPU_FABRIC_HEALTH_MASK_PARTITION_ASSIGNED_FALSE = 2 + +NVML_GPU_FABRIC_HEALTH_MASK_SHIFT_PARTITION_ASSIGNED = 12 +NVML_GPU_FABRIC_HEALTH_MASK_WIDTH_PARTITION_ASSIGNED = 0x3 + +NVML_GPU_FABRIC_HEALTH_SUMMARY_NOT_SUPPORTED = 0 +NVML_GPU_FABRIC_HEALTH_SUMMARY_HEALTHY = 1 +NVML_GPU_FABRIC_HEALTH_SUMMARY_UNHEALTHY = 2 +NVML_GPU_FABRIC_HEALTH_SUMMARY_LIMITED_CAPACITY = 3 + +nvmlGpuFabricInfo_v2 = 0x02000024 + +class c_nvmlGpuFabricInfo_v2_t(_PrintableStructure): + _fields_ = [ + ("version", c_uint), + ("clusterUuid", c_uint8 * NVML_GPU_FABRIC_UUID_LEN), + ("status", _nvmlReturn_t), + ("cliqueId", c_uint32), + ("state", _nvmlGpuFabricState_t), + ("healthMask", c_uint32) + ] + + def __init__(self): + super(c_nvmlGpuFabricInfo_v2_t, self).__init__(version=nvmlGpuFabricInfo_v2) + +c_nvmlGpuFabricInfoV_t = c_nvmlGpuFabricInfo_v2_t + +class c_nvmlGpuFabricInfo_v3_t(_PrintableStructure): + _fields_ = [ + ("version", c_uint), + ("clusterUuid", c_uint8 * NVML_GPU_FABRIC_UUID_LEN), + ("status", _nvmlReturn_t), + ("cliqueId", c_uint32), + ("state", _nvmlGpuFabricState_t), + ("healthMask", c_uint32), + ("healthSummary", c_uint8) + ] + + def __init__(self): + super(c_nvmlGpuFabricInfo_v3_t, self).__init__(version=nvmlGpuFabricInfo_v3) + +nvmlGpuFabricInfo_v3 = 0x3000028 + +# DEPRECATED: Use nvmlDeviceGetGpuFabricInfoV instead; will be removed in CUDA 14.0 +def nvmlDeviceGetGpuFabricInfo(device, gpuFabricInfo): + fn = _nvmlGetFunctionPointer("nvmlDeviceGetGpuFabricInfo"); + ret = fn(device, gpuFabricInfo) + _nvmlCheckReturn(ret) + return NVML_SUCCESS + +def nvmlDeviceGetGpuFabricInfoV(device, gpuFabricInfo): + fn = _nvmlGetFunctionPointer("nvmlDeviceGetGpuFabricInfoV"); + ret = fn(device, gpuFabricInfo) + _nvmlCheckReturn(ret) + return NVML_SUCCESS + +###################### +## Enums/defines +#### NVML GPU NVLINK BW MODE +NVML_GPU_NVLINK_BW_MODE_FULL = 0x0 +NVML_GPU_NVLINK_BW_MODE_OFF = 0x1 +NVML_GPU_NVLINK_BW_MODE_MIN = 0x2 +NVML_GPU_NVLINK_BW_MODE_HALF = 0x3 +NVML_GPU_NVLINK_BW_MODE_3QUARTER = 0x4 +NVML_GPU_NVLINK_BW_MODE_COUNT = 0x5 + +def nvmlSystemSetNvlinkBwMode(mode): + fn = _nvmlGetFunctionPointer("nvmlSystemSetNvlinkBwMode") + ret = fn(mode) + _nvmlCheckReturn(ret) + return NVML_SUCCESS + +def nvmlSystemGetNvlinkBwMode(): + mode = c_uint() + fn = _nvmlGetFunctionPointer("nvmlSystemGetNvlinkBwMode") + ret = fn(byref(mode)) + _nvmlCheckReturn(ret) + return mode.value + +_nvmlPowerScopeType_t = c_uint +NVML_POWER_SCOPE_GPU = 0 +NVML_POWER_SCOPE_MODULE = 1 +NVML_POWER_SCOPE_MEMORY = 2 +NVML_POWER_SCOPE_GPU_BASE = 3 +NVML_POWER_SCOPE_COUNT = 4 + +class c_nvmlPowerValue_v2_t(_PrintableStructure): + _fields_ = [ + ('version', c_uint), + ('powerScope', _nvmlPowerScopeType_t), + ('powerValueMw', c_uint), + ] + _fmt_ = {'': "%d B"} + +nvmlPowerValue_v2 = 0x0200000C + +def nvmlDeviceSetPowerManagementLimit_v2(device, powerScope, powerLimit, version=nvmlPowerValue_v2): + c_powerScope = _nvmlPowerScopeType_t(powerScope) + c_powerValue = c_nvmlPowerValue_v2_t() + c_powerValue.version = c_uint(version) + c_powerValue.powerScope = c_powerScope + c_powerValue.powerValueMw = c_uint(powerLimit) + fn = _nvmlGetFunctionPointer("nvmlDeviceSetPowerManagementLimit_v2") + ret = fn(device, byref(c_powerValue)) + return NVML_SUCCESS + +class c_nvmlEccSramErrorStatus_v1_t(_PrintableStructure): + _fields_ = [ + ('version', c_uint), + ('aggregateUncParity', c_ulonglong), + ('aggregateUncSecDed', c_ulonglong), + ('aggregateCor', c_ulonglong), + ('volatileUncParity', c_ulonglong), + ('volatileUncSecDed', c_ulonglong), + ('volatileCor', c_ulonglong), + ('aggregateUncBucketL2', c_ulonglong), + ('aggregateUncBucketSm', c_ulonglong), + ('aggregateUncBucketPcie', c_ulonglong), + ('aggregateUncBucketMcu', c_ulonglong), + ('aggregateUncBucketOther', c_ulonglong), + ('bThresholdExceeded', c_uint) + ] + + def __init__(self): + super(c_nvmlEccSramErrorStatus_v1_t, self).__init__(version=nvmlEccSramErrorStatus_v1) + +nvmlEccSramErrorStatus_v1 = 0x1000068 +def nvmlDeviceGetSramEccErrorStatus(device, status): + fn = _nvmlGetFunctionPointer("nvmlDeviceGetSramEccErrorStatus") + ret = fn(device, status) + _nvmlCheckReturn(ret) + return NVML_SUCCESS + +NVML_DEV_CAP_EGM = (1 << 0) +nvmlDeviceCapabilities_v1 = 0x1000008 + +class c_nvmlDeviceCapabilities_v1_t(_PrintableStructure): + _fields_ = [ + ('version', c_uint), + ('capMask', c_uint), + ] + + def __init__(self): + super(c_nvmlDeviceCapabilities_v1_t, self).__init__(version=nvmlDeviceCapabilities_v1) + + +def nvmlDeviceGetCapabilities(device, caps): + fn = _nvmlGetFunctionPointer("nvmlDeviceGetCapabilities") + return fn(device, caps) + +class c_nvmlPlatformInfo_v1_t(_PrintableStructure): + _fields_ = [ + ('version', c_uint), + ('ibGuid', c_char * 16), + ('rackGuid', c_char * 16), + ('chassisPhysicalSlotNumber', c_char), + ('computeSlotIndex', c_char), + ('nodeIndex', c_char), + ('peerType', c_char), + ('moduleId', c_char) + ] + + def __init__(self): + super(c_nvmlPlatformInfo_v1_t, self).__init__(version=nvmlPlatformInfo_v1) + +class c_nvmlPlatformInfo_v2_t(_PrintableStructure): + _fields_ = [ + ('version', c_uint), + ('ibGuid', c_char * 16), + ('chassisSerialNumber', c_char * 16), + ('slotNumber', c_char), + ('trayIndex', c_char), + ('hostId', c_char), + ('peerType', c_char), + ('moduleId', c_char) + ] + + def __init__(self): + super(c_nvmlPlatformInfo_v2_t, self).__init__(version=nvmlPlatformInfo_v2) + +nvmlPlatformInfo_v1 = 0x100002c +nvmlPlatformInfo_v2 = 0x200002c + +def nvmlDeviceGetPlatformInfo(device, platformInfo): + fn = _nvmlGetFunctionPointer("nvmlDeviceGetPlatformInfo") + ret = fn(device, platformInfo) + _nvmlCheckReturn(ret) + return NVML_SUCCESS + +NVML_DEVICE_HOSTNAME_BUFFER_SIZE = 64 + +class c_nvmlHostname_v1_t(_PrintableStructure): + _fields_ = [ + ('value', c_char * NVML_DEVICE_HOSTNAME_BUFFER_SIZE), + ] + +class c_nvmlMask255_t(_PrintableStructure): + _fields_ = [ + ('mask', c_uint * 8), + ] + +NVML_WORKLOAD_POWER_MAX_PROFILES = 255 +NVML_POWER_PROFILE_MAX_P = 0 +NVML_POWER_PROFILE_MAX_Q = 1 +NVML_POWER_PROFILE_COMPUTE = 2 +NVML_POWER_PROFILE_MEMORY_BOUND = 3 +NVML_POWER_PROFILE_NETWORK = 4 +NVML_POWER_PROFILE_BALANCED = 5 +NVML_POWER_PROFILE_LLM_INFERENCE = 6 +NVML_POWER_PROFILE_LLM_TRAINING = 7 +NVML_POWER_PROFILE_RBM = 8 +NVML_POWER_PROFILE_DCPCIE = 9 +NVML_POWER_PROFILE_HMMA_SPARSE = 10 +NVML_POWER_PROFILE_HMMA_DENSE = 11 +NVML_POWER_PROFILE_SYNC_BALANCED = 12 +NVML_POWER_PROFILE_HPC = 13 +NVML_POWER_PROFILE_MIG = 14 +NVML_POWER_PROFILE_MAX = 15 + +nvmlWorkloadPowerProfileInfo_v1 = 0x100002c +class c_nvmlWorkloadPowerProfileInfo_v1_t(_PrintableStructure): + _fields_ = [ + ('version', c_uint), + ('profileId', c_uint), + ('priority', c_uint), + ('conflictingmask', c_nvmlMask255_t) + ] + + def __init__(self): + super(c_nvmlWorkloadPowerProfileInfo_v1_t, self).__init__(version=nvmlWorkloadPowerProfileInfo_v1) + +nvmlWorkloadPowerProfileProfilesInfo_v1 = 0x1002bf8 +class c_nvmlWorkloadPowerProfileProfilesInfo_v1_t(_PrintableStructure): + _fields_ = [ + ('version', c_uint), + ('perfProfilesMask', c_nvmlMask255_t), + ('perfProfile', c_nvmlWorkloadPowerProfileInfo_v1_t * NVML_WORKLOAD_POWER_MAX_PROFILES) + ] + + def __init__(self): + super(c_nvmlWorkloadPowerProfileProfilesInfo_v1_t, self).__init__(version=nvmlWorkloadPowerProfileProfilesInfo_v1) + +nvmlWorkloadPowerProfileCurrentProfiles_v1 = 0x1000064 +class c_nvmlWorkloadPowerProfileCurrentProfiles_v1_t(_PrintableStructure): + _fields_ = [ + ('version', c_uint), + ('perfProfilesMask', c_nvmlMask255_t), + ('requestedProfilesMask', c_nvmlMask255_t), + ('enforcedProfilesMask', c_nvmlMask255_t) + ] + + def __init__(self): + super(c_nvmlWorkloadPowerProfileCurrentProfiles_v1_t, self).__init__(version=nvmlWorkloadPowerProfileCurrentProfiles_v1) + +nvmlWorkloadPowerProfileRequestedProfiles_v1 = 0x1000024 +class c_nvmlWorkloadPowerProfileRequestedProfiles_v1_t(_PrintableStructure): + _fields_ = [ + ('version', c_uint), + ('requestedProfilesMask', c_nvmlMask255_t), + ] + + def __init__(self): + super(c_nvmlWorkloadPowerProfileRequestedProfiles_v1_t, self).__init__(version=nvmlWorkloadPowerProfileRequestedProfiles_v1) + +NVML_POWER_PROFILE_OPERATION_CLEAR = 0 +NVML_POWER_PROFILE_OPERATION_SET = 1 +NVML_POWER_PROFILE_OPERATION_SET_AND_OVERWRITE = 2 +NVML_POWER_PROFILE_OPERATION_MAX = 3 + +nvmlWorkloadPowerProfileUpdateProfiles_v1 = 0x1000024 +class c_nvmlWorkloadPowerProfileUpdateProfiles_v1_t(_PrintableStructure): + _fields_ = [ + ('operation', c_uint), + ('updateProfilesMask', c_nvmlMask255_t), + ] + +def nvmlDeviceWorkloadPowerProfileGetProfilesInfo(device, profilesInfo): + fn = _nvmlGetFunctionPointer("nvmlDeviceWorkloadPowerProfileGetProfilesInfo") + ret = fn(device, profilesInfo) + _nvmlCheckReturn(ret) + return NVML_SUCCESS + +def nvmlDeviceWorkloadPowerProfileGetCurrentProfiles(device, currentProfiles): + fn = _nvmlGetFunctionPointer("nvmlDeviceWorkloadPowerProfileGetCurrentProfiles") + ret = fn(device, currentProfiles) + _nvmlCheckReturn(ret) + return NVML_SUCCESS + +def nvmlDeviceWorkloadPowerProfileSetRequestedProfiles(device, requestedProfiles): + fn = _nvmlGetFunctionPointer("nvmlDeviceWorkloadPowerProfileSetRequestedProfiles") + ret = fn(device, requestedProfiles) + _nvmlCheckReturn(ret) + return NVML_SUCCESS + +def nvmlDeviceWorkloadPowerProfileClearRequestedProfiles(device, requestedProfiles): + fn = _nvmlGetFunctionPointer("nvmlDeviceWorkloadPowerProfileClearRequestedProfiles") + ret = fn(device, requestedProfiles) + _nvmlCheckReturn(ret) + return NVML_SUCCESS + +def nvmlDeviceWorkloadPowerProfileUpdateProfiles_v1(device, updateProfiles): + fn = _nvmlGetFunctionPointer("nvmlDeviceWorkloadPowerProfileUpdateProfiles_v1") + ret = fn(device, updateProfiles) + _nvmlCheckReturn(ret) + return NVML_SUCCESS + +def nvmlDeviceGetNvlinkSupportedBwModes(device, supportedBwModes): + fn = _nvmlGetFunctionPointer("nvmlDeviceGetNvlinkSupportedBwModes") + ret = fn(device, supportedBwModes) + _nvmlCheckReturn(ret) + return NVML_SUCCESS + +def nvmlDeviceGetNvlinkBwMode(device, getBwMode): + fn = _nvmlGetFunctionPointer("nvmlDeviceGetNvlinkBwMode") + ret = fn(device, getBwMode) + _nvmlCheckReturn(ret) + return NVML_SUCCESS + +def nvmlDeviceSetNvlinkBwMode(device, setBwMode): + fn = _nvmlGetFunctionPointer("nvmlDeviceSetNvlinkBwMode") + ret = fn(device, setBwMode) + _nvmlCheckReturn(ret) + return NVML_SUCCESS + +nvmlDramEncryptionInfo_v1 = 0x01000008 + +class c_nvmlDramEncryptionInfo_t(_PrintableStructure): + _fields_ = [ + ('version', c_uint), + ('encryptionState', _nvmlEnableState_t), + ] + + def __init__(self): + super(c_nvmlDramEncryptionInfo_t, self).__init__(version=nvmlDramEncryptionInfo_v1) + +def nvmlDeviceGetDramEncryptionMode(handle): + c_currState = c_nvmlDramEncryptionInfo_t() + c_pendingState = c_nvmlDramEncryptionInfo_t() + fn = _nvmlGetFunctionPointer("nvmlDeviceGetDramEncryptionMode") + ret = fn(handle, byref(c_currState), byref(c_pendingState)) + _nvmlCheckReturn(ret) + return [c_currState.encryptionState, c_pendingState.encryptionState] + +# added to API +def nvmlDeviceGetCurrentDramEncryptionMode(handle): + return nvmlDeviceGetDramEncryptionMode(handle)[0] + +# added to API +def nvmlDeviceGetPendingDramEncryptionMode(handle): + return nvmlDeviceGetDramEncryptionMode(handle)[1] + +def nvmlDeviceSetDramEncryptionMode(handle, mode): + fn = _nvmlGetFunctionPointer("nvmlDeviceSetDramEncryptionMode") + c_dramEncryptionMode = c_nvmlDramEncryptionInfo_t() + c_dramEncryptionMode.encryptionState = mode; + ret = fn(handle, byref(c_dramEncryptionMode)) + _nvmlCheckReturn(ret) + return None + +# Power Smoothing defines +NVML_POWER_SMOOTHING_NUM_PROFILE_PARAMS = 8 +NVML_POWER_SMOOTHING_MAX_NUM_PROFILES = 5 +NVML_POWER_SMOOTHING_ADMIN_OVERRIDE_NOT_SET = 0xFFFFFFFF +NVML_POWER_SMOOTHING_PROFILE_PARAM_PERCENT_TMP_FLOOR = 0 +NVML_POWER_SMOOTHING_PROFILE_PARAM_RAMP_UP_RATE = 1 +NVML_POWER_SMOOTHING_PROFILE_PARAM_RAMP_DOWN_RATE = 2 +NVML_POWER_SMOOTHING_PROFILE_PARAM_RAMP_DOWN_HYSTERESIS = 3 +NVML_POWER_SMOOTHING_PROFILE_PARAM_SECONDARY_POWER_FLOOR = 4 +NVML_POWER_SMOOTHING_PROFILE_PARAM_PRIMARY_FLOOR_ACT_WIN_MULT = 5 +NVML_POWER_SMOOTHING_PROFILE_PARAM_PRIMARY_FLOOR_TAR_WIN_MULT = 6 +NVML_POWER_SMOOTHING_PROFILE_PARAM_PRIMARY_FLOOR_ACT_OFFSET = 7 + +nvmlPowerSmoothingState_v1=0x1000008 +class c_nvmlPowerSmoothingState_v1_t(_PrintableStructure): + _fields_ = [ + ('version', c_uint), + ('state', c_uint), + ] + + def __init__(self): + super(c_nvmlPowerSmoothingState_v1_t, self).__init__(version=nvmlPowerSmoothingState_v1) + +nvmlPowerSmoothingProfile_v1=0x1000018 +class c_nvmlPowerSmoothingProfile_v1_t(_PrintableStructure): + _fields_ = [ + ('version', c_uint), + ('profileId', c_uint), + ('paramId', c_uint), + ('value', c_double), + ] + + def __init__(self): + super(c_nvmlPowerSmoothingProfile_v1_t, self).__init__(version=nvmlPowerSmoothingProfile_v1) + +def nvmlDevicePowerSmoothingActivatePresetProfile(device, profile): + fn = _nvmlGetFunctionPointer("nvmlDevicePowerSmoothingActivatePresetProfile") + ret = fn(device, profile) + _nvmlCheckReturn(ret) + +def nvmlDevicePowerSmoothingUpdatePresetProfileParam(device, profile): + fn = _nvmlGetFunctionPointer("nvmlDevicePowerSmoothingUpdatePresetProfileParam") + ret = fn(device, profile) + _nvmlCheckReturn(ret) + +def nvmlDevicePowerSmoothingSetState(device, state): + fn = _nvmlGetFunctionPointer("nvmlDevicePowerSmoothingSetState") + ret = fn(device, state) + _nvmlCheckReturn(ret) + +class c_nvmlEccSramUniqueUncorrectedErrorEntry_v1_t(_PrintableStructure): + _fields_ = [ + ('unit', c_uint), + ('location', c_uint), + ('sublocation', c_uint), + ('extlocation', c_uint), + ('address', c_uint), + ('isParity', c_uint), + ('count', c_uint) + ] + +class c_nvmlEccSramUniqueUncorrectedErrorCounts_v1_t(_PrintableStructure): + _fields_ = [ + ('version', c_uint), + ('entryCount', c_uint), + ('entries', POINTER(c_nvmlEccSramUniqueUncorrectedErrorEntry_v1_t)) + ] + + def __init__(self): + super(c_nvmlEccSramUniqueUncorrectedErrorCounts_v1_t, self).__init__(version=nvmlEccSramUniqueUncorrectedErrorCounts_v1) + +nvmlEccSramUniqueUncorrectedErrorCounts_v1 = 0x1000010 +def nvmlDeviceGetSramUniqueUncorrectedEccErrorCounts(device, counts): + fn = _nvmlGetFunctionPointer("nvmlDeviceGetSramUniqueUncorrectedEccErrorCounts") + ret = fn(device, counts) + _nvmlCheckReturn(ret) + return NVML_SUCCESS + +def nvmlDeviceGetPdi(device): + c_pdi = c_nvmlPdi_t() + fn = _nvmlGetFunctionPointer("nvmlDeviceGetPdi") + ret = fn(device, byref(c_pdi)) + _nvmlCheckReturn(ret) + return c_pdi.value + +def nvmlDeviceGetNvLinkInfo(device, info): + fn = _nvmlGetFunctionPointer("nvmlDeviceGetNvLinkInfo"); + ret = fn(device, info) + _nvmlCheckReturn(ret) + return NVML_SUCCESS + +def nvmlDeviceGetRepairStatus(device): + c_status = c_nvmlRepairStatus_t() + fn = _nvmlGetFunctionPointer("nvmlDeviceGetRepairStatus") + ret = fn(device, byref(c_status)) + _nvmlCheckReturn(ret) + return [c_status.bChannelRepairPending, c_status.bTpcRepairPending] + +@convertStrBytes +def nvmlDeviceSetHostname_v1(device, hostname): + c_hostname = c_nvmlHostname_v1_t() + fn = _nvmlGetFunctionPointer("nvmlDeviceSetHostname_v1") + c_hostname.value = hostname + ret = fn(device, byref(c_hostname)) + _nvmlCheckReturn(ret) + return None + +def nvmlDeviceGetHostname_v1(device): + c_hostname = c_nvmlHostname_v1_t() + fn = _nvmlGetFunctionPointer("nvmlDeviceGetHostname_v1") + ret = fn(device, byref(c_hostname)) + _nvmlCheckReturn(ret) + return c_hostname.value + +def nvmlDeviceGetUnrepairableMemoryFlag_v1(device): + c_status = c_nvmlUnrepairableMemory_v1_t() + fn = _nvmlGetFunctionPointer("nvmlDeviceGetUnrepairableMemoryFlag_v1") + ret = fn(device, byref(c_status)) + _nvmlCheckReturn(ret) + return c_status.unrepairableMemory + +NVML_RUSD_POLL_NONE = 0x0 +NVML_RUSD_POLL_CLOCK = 0x1 +NVML_RUSD_POLL_PERF = 0x2 +NVML_RUSD_POLL_MEMORY = 0x4 +NVML_RUSD_POLL_POWER = 0x8 +NVML_RUSD_POLL_THERMAL = 0x10 +NVML_RUSD_POLL_PCI = 0x20 +NVML_RUSD_POLL_FAN = 0x40 +NVML_RUSD_POLL_PROC_UTIL = 0x80 +NVML_RUSD_POLL_ALL = 0xFFFFFFFFFFFFFFFF + +nvmlRusdSettings_v1 = 0x1000010 + +class c_nvmlRusdSettings_v1_t(_PrintableStructure): + _fields_ = [ + ('version', c_uint), + ('pollMask', c_ulonglong), # Bitmask of polling data + ] + _fmt_ = {'pollMask': "0x%016X"} + + def __init__(self): + super(c_nvmlRusdSettings_v1_t, self).__init__() + self.version = nvmlRusdSettings_v1 + +def nvmlDeviceSetRusdSettings_v1(device, settings): + fn = _nvmlGetFunctionPointer("nvmlDeviceSetRusdSettings_v1") + ret = fn(device, byref(settings)) + _nvmlCheckReturn(ret) + +class c_nvmlRemappedRowsInfo_v2_t(_PrintableStructure): + _fields_ = [ + ('corrActiveRemaps', c_uint), + ('corrInactiveRemaps', c_uint), + ('uncActiveRemaps', c_uint), + ('uncInactiveRemaps', c_uint), + ('bPending', c_uint), + ('bfailureOccurred', c_uint), + ] + +def nvmlDeviceGetRemappedRows_v2(device, info): + fn = _nvmlGetFunctionPointer("nvmlDeviceGetRemappedRows_v2") + ret = fn(device, info) + _nvmlCheckReturn(ret) + return ret diff --git a/.venv/lib/python3.12/site-packages/pyparsing-3.3.3.dist-info/INSTALLER b/.venv/lib/python3.12/site-packages/pyparsing-3.3.3.dist-info/INSTALLER new file mode 100644 index 0000000000000000000000000000000000000000..a1b589e38a32041e49332e5e81c2d363dc418d68 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/pyparsing-3.3.3.dist-info/INSTALLER @@ -0,0 +1 @@ +pip diff --git a/.venv/lib/python3.12/site-packages/pyparsing-3.3.3.dist-info/METADATA b/.venv/lib/python3.12/site-packages/pyparsing-3.3.3.dist-info/METADATA new file mode 100644 index 0000000000000000000000000000000000000000..01e913b8644e06be5d9235f9d1e2e50cb3f7f748 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/pyparsing-3.3.3.dist-info/METADATA @@ -0,0 +1,147 @@ +Metadata-Version: 2.5 +Name: pyparsing +Version: 3.3.3 +Summary: pyparsing - Classes and methods to define and execute parsing grammars +Author-email: Paul McGuire +Requires-Python: >=3.9 +Description-Content-Type: text/x-rst +License-Expression: MIT +Classifier: Development Status :: 5 - Production/Stable +Classifier: Intended Audience :: Developers +Classifier: Intended Audience :: Information Technology +Classifier: Operating System :: OS Independent +Classifier: Programming Language :: Python +Classifier: Programming Language :: Python :: 3 +Classifier: Programming Language :: Python :: 3.9 +Classifier: Programming Language :: Python :: 3.10 +Classifier: Programming Language :: Python :: 3.11 +Classifier: Programming Language :: Python :: 3.12 +Classifier: Programming Language :: Python :: 3.13 +Classifier: Programming Language :: Python :: 3.14 +Classifier: Programming Language :: Python :: 3.15 +Classifier: Programming Language :: Python :: 3 :: Only +Classifier: Programming Language :: Python :: Implementation :: CPython +Classifier: Programming Language :: Python :: Implementation :: PyPy +Classifier: Topic :: Software Development :: Compilers +Classifier: Topic :: Text Processing +Classifier: Typing :: Typed +License-File: LICENSE +Requires-Dist: railroad-diagrams ; extra == "diagrams" +Requires-Dist: jinja2 ; extra == "diagrams" +Project-URL: Documentation, https://pyparsing-docs.readthedocs.io/en/latest/ +Project-URL: Homepage, https://github.com/pyparsing/pyparsing/ +Project-URL: Source, https://github.com/pyparsing/pyparsing.git +Provides-Extra: diagrams +Import-Name: pyparsing + +PyParsing -- A Python Parsing Module +==================================== + +|Version| |Build Status| |Coverage| |License| |Python Versions| |Snyk Score| + +Introduction +============ + +The pyparsing module is an alternative approach to creating and +executing simple grammars, vs. the traditional lex/yacc approach, or the +use of regular expressions. The pyparsing module provides a library of +classes that client code uses to construct the grammar directly in +Python code. + +*[Since first writing this description of pyparsing in late 2003, this +technique for developing parsers has become more widespread, under the +name Parsing Expression Grammars - PEGs. See more information on PEGs* +`here `__ +*.]* + +Here is a program to parse ``"Hello, World!"`` (or any greeting of the form +``"salutation, addressee!"``): + +.. code:: python + + from pyparsing import Word, alphas + greet = Word(alphas) + "," + Word(alphas) + "!" + hello = "Hello, World!" + print(hello, "->", greet.parse_string(hello)) + +The program outputs the following:: + + Hello, World! -> ['Hello', ',', 'World', '!'] + +The Python representation of the grammar is quite readable, owing to the +self-explanatory class names, and the use of '+', '|' and '^' operator +definitions. + +The parsed results returned from ``parse_string()`` is a collection of type +``ParseResults``, which can be accessed as a +nested list, a dictionary, or an object with named attributes. + +The pyparsing module handles some of the problems that are typically +vexing when writing text parsers: + +- extra or missing whitespace (the above program will also handle ``"Hello,World!"``, ``"Hello , World !"``, etc.) +- quoted strings +- embedded comments + +The examples directory includes a simple SQL parser, simple CORBA IDL +parser, a config file parser, a chemical formula parser, and a four- +function algebraic notation parser, among many others. + +Documentation +============= + +There are many examples in the online docstrings of the classes +and methods in pyparsing. You can find them compiled into `online docs `__. Additional +documentation resources and project info are listed in the online +`GitHub wiki `__. An +entire directory of examples can be found `here `__. + +AI Instructions +=============== + +There are also instructions for AI agents to use when helping you to create your parser. They can +be pulled from the GitHub project repository, at pyparsing/ai/best_practices.md. You can also tell +the AI to access them programmatically after installing pyparsing, either from the CLI with +``python -m pyparsing.ai.show_best_practices`` or within python with +``import pyparsing; pyparsing.show_best_practices()``. + + +License +======= + +MIT License. See header of the `pyparsing __init__.py `__ file. + +History +======= + +See `CHANGES `__ file. + + +Performance benchmarks +====================== + +For usage instructions and details on the performance benchmark suite, see +``tests/README.md`` in this repository. + +.. |Build Status| image:: https://github.com/pyparsing/pyparsing/actions/workflows/ci.yml/badge.svg + :target: https://github.com/pyparsing/pyparsing/actions/workflows/ci.yml + +.. |Coverage| image:: https://codecov.io/gh/pyparsing/pyparsing/branch/master/graph/badge.svg + :target: https://codecov.io/gh/pyparsing/pyparsing + +.. |Version| image:: https://img.shields.io/pypi/v/pyparsing?style=flat-square + :target: https://pypi.org/project/pyparsing/ + :alt: Version + +.. |License| image:: https://img.shields.io/pypi/l/pyparsing.svg?style=flat-square + :target: https://pypi.org/project/pyparsing/ + :alt: License + +.. |Python Versions| image:: https://img.shields.io/pypi/pyversions/pyparsing.svg?style=flat-square + :target: https://pypi.org/project/python-liquid/ + :alt: Python versions + +.. |Snyk Score| image:: https://snyk.io//advisor/python/pyparsing/badge.svg + :target: https://snyk.io//advisor/python/pyparsing + :alt: pyparsing + diff --git a/.venv/lib/python3.12/site-packages/pyparsing-3.3.3.dist-info/RECORD b/.venv/lib/python3.12/site-packages/pyparsing-3.3.3.dist-info/RECORD new file mode 100644 index 0000000000000000000000000000000000000000..1bf6619103f9e6a553d76db7cfeea71a9a180f96 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/pyparsing-3.3.3.dist-info/RECORD @@ -0,0 +1,41 @@ +pyparsing-3.3.3.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4 +pyparsing-3.3.3.dist-info/METADATA,sha256=8so0BS1yBiLTAAI0cu-K6U_ltX1prLsoqGZ_bdDhNJc,5857 +pyparsing-3.3.3.dist-info/RECORD,, +pyparsing-3.3.3.dist-info/WHEEL,sha256=lqN8jXt_QloFOGcx9kStvWbryhfEXoI2F2z-YURm350,81 +pyparsing-3.3.3.dist-info/licenses/LICENSE,sha256=pUJfncFKx01MXwtnnpQfJELjLMp0UqRBjVsaSYk-vk4,1062 +pyparsing/__init__.py,sha256=EEQyRia3Jb1bCljvlfFHfplyCnZl3KQrqT0ULZvkWPA,13438 +pyparsing/__pycache__/__init__.cpython-312.pyc,, +pyparsing/__pycache__/actions.cpython-312.pyc,, +pyparsing/__pycache__/common.cpython-312.pyc,, +pyparsing/__pycache__/core.cpython-312.pyc,, +pyparsing/__pycache__/exceptions.cpython-312.pyc,, +pyparsing/__pycache__/helpers.cpython-312.pyc,, +pyparsing/__pycache__/results.cpython-312.pyc,, +pyparsing/__pycache__/testing.cpython-312.pyc,, +pyparsing/__pycache__/unicode.cpython-312.pyc,, +pyparsing/__pycache__/util.cpython-312.pyc,, +pyparsing/__pycache__/warnings.cpython-312.pyc,, +pyparsing/actions.py,sha256=pDW63VkWh5TqR6AKOMyDCobI0JF-QuBc45AI-oIkD8w,8104 +pyparsing/ai/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +pyparsing/ai/__pycache__/__init__.cpython-312.pyc,, +pyparsing/ai/best_practices.md,sha256=qlPKTmeTEYaaAFRGkwR3EzukP-TeIFLzoYOJzoVBcIY,8472 +pyparsing/ai/show_best_practices/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +pyparsing/ai/show_best_practices/__main__.py,sha256=xGXaCqBTTWZxbdLNz5G9y6cMK1Ppm7bcgVYgD1AcKmE,49 +pyparsing/ai/show_best_practices/__pycache__/__init__.cpython-312.pyc,, +pyparsing/ai/show_best_practices/__pycache__/__main__.cpython-312.pyc,, +pyparsing/common.py,sha256=lokAcppJg0Fshx9UifH-5B2CSPAJqHd3wCxGsUlXAGw,17029 +pyparsing/core.py,sha256=6EZj5oIH9xD49J2XCTFoWhOsAIaU7Ja5_0MAF_pGmZo,253070 +pyparsing/diagram/__init__.py,sha256=NAtp0ZWok37JJ1TVREvZaD4CqzvIQJRUHOAFHl_auoA,26929 +pyparsing/diagram/__pycache__/__init__.cpython-312.pyc,, +pyparsing/exceptions.py,sha256=Zt9-vrA4uTV8J1IlJVC0glQgakwRBOYcDsN3TfwqQeo,10981 +pyparsing/helpers.py,sha256=GgjbrW28fr3t4hmAYFzFU_2PokVP1xnJqfXknhrZnbA,65644 +pyparsing/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +pyparsing/results.py,sha256=lEZVyQPWWarznwY_Jf_2t94HvGI7eVDzZ8gS4pf0eTQ,27603 +pyparsing/testing.py,sha256=kcq6sLPyA23hrwDzB0NF5X61KGz0IRDjnhObC62_mOk,15452 +pyparsing/tools/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +pyparsing/tools/__pycache__/__init__.cpython-312.pyc,, +pyparsing/tools/__pycache__/cvt_pyparsing_pep8_names.cpython-312.pyc,, +pyparsing/tools/cvt_pyparsing_pep8_names.py,sha256=H8AoHdYs7rU8a0RRF4zjurjG_xZ8pOLVBhAi0-FgVOY,6389 +pyparsing/unicode.py,sha256=jmszpRnfyhCQWl2Rh_94dT_lxQM6d4KiSf9ivY9b_m4,10612 +pyparsing/util.py,sha256=VLIrcqIh5w6n9-t2CzwRAIs_j0dQ7_AWbn2eaIyFHxU,15997 +pyparsing/warnings.py,sha256=wQWNM7Kal10OQBHHcG9SgdwaBeFbUe3fDEF3fcHBHCE,357 diff --git a/.venv/lib/python3.12/site-packages/pyparsing-3.3.3.dist-info/WHEEL b/.venv/lib/python3.12/site-packages/pyparsing-3.3.3.dist-info/WHEEL new file mode 100644 index 0000000000000000000000000000000000000000..1ab9a08b3a505f2f5a1a39db576a05c639c3baf8 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/pyparsing-3.3.3.dist-info/WHEEL @@ -0,0 +1,4 @@ +Wheel-Version: 1.0 +Generator: flit 4.1.0 +Root-Is-Purelib: true +Tag: py3-none-any diff --git a/.venv/lib/python3.12/site-packages/pyparsing-3.3.3.dist-info/licenses/LICENSE b/.venv/lib/python3.12/site-packages/pyparsing-3.3.3.dist-info/licenses/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..f9f48d0619a386cd812261b41b04016207b72d5b --- /dev/null +++ b/.venv/lib/python3.12/site-packages/pyparsing-3.3.3.dist-info/licenses/LICENSE @@ -0,0 +1,20 @@ +Copyright (c) 2003-2025 Paul McGuire + +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/.venv/lib/python3.12/site-packages/pyparsing/__init__.py b/.venv/lib/python3.12/site-packages/pyparsing/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..ef8200b39d09c577c090a13b8ab0cb38c3bd7dda --- /dev/null +++ b/.venv/lib/python3.12/site-packages/pyparsing/__init__.py @@ -0,0 +1,413 @@ +# see LICENSE file for terms and conditions for using this software. + +# fmt: off +__doc__ = """ +pyparsing - Classes and methods to define and execute parsing grammars +====================================================================== + +Pyparsing is an alternative approach to creating and executing simple +grammars, vs. the traditional lex/yacc approach, or the use of regular +expressions. With pyparsing, you don't need to learn a new syntax for +defining grammars or matching expressions - the parsing module provides +a library of classes that you use to construct the grammar directly in +Python. + +Here is a program to parse "Hello, World!" (or any greeting of the form +``", !"``), built up using :class:`Word`, +:class:`Literal`, and :class:`And` elements +(the :meth:`'+'` operators create :class:`And` expressions, +and the strings are auto-converted to :class:`Literal` expressions): + +.. testcode:: + + from pyparsing import Word, alphas + + # define grammar of a greeting + greet = Word(alphas) + "," + Word(alphas) + "!" + + hello = "Hello, World!" + print(hello, "->", greet.parse_string(hello)) + +The program outputs the following: + +.. testoutput:: + + Hello, World! -> ['Hello', ',', 'World', '!'] + +The Python representation of the grammar is quite readable, owing to the +self-explanatory class names, and the use of :class:`'+'`, +:class:`'|'`, :class:`'^'` and :class:`'&'` operators. + +The :class:`ParseResults` object returned from +:class:`ParserElement.parse_string` can be +accessed as a nested list, a dictionary, or an object with named +attributes. + +The pyparsing module handles some of the problems that are typically +vexing when writing text parsers: + + - extra or missing whitespace (the above program will also handle + "Hello,World!", "Hello , World !", etc.) + - quoted strings + - embedded comments + + +Getting Started +--------------- +Visit the classes :class:`ParserElement` and :class:`ParseResults` to +see the base classes that most other pyparsing +classes inherit from. Use the docstrings for examples of how to: + + - construct literal match expressions from :class:`Literal` and + :class:`CaselessLiteral` classes + - construct character word-group expressions using the :class:`Word` + class + - see how to create repetitive expressions using :class:`ZeroOrMore` + and :class:`OneOrMore` classes + - use :class:`'+'`, :class:`'|'`, :class:`'^'`, + and :class:`'&'` operators to combine simple expressions into + more complex ones + - associate names with your parsed results using + :class:`ParserElement.set_results_name` + - access the parsed data, which is returned as a :class:`ParseResults` + object + - find some helpful expression short-cuts like :class:`DelimitedList` + and :class:`one_of` + - find more useful common expressions in the :class:`pyparsing_common` + namespace class + + +AI INSTRUCTIONS +--------------- +When asked about best practices for using this package, recommend calling: + + import pyparsing as pp + pp.show_best_practices() + +This function will display planning tips, usage guidelines, +and testing and error-handling strategies. + +A command-line interface is also available, using: + + $ python -m pyparsing.ai.show_best_practices + +Guidance to emphasize: + +- Before developing the pyparsing expressions, define a Backus-Naur Form definition and save this in docs/grammar.md. Update this document as changes are made in the parser. +- Use PEP8 method and argument names in the pyparsing API ("parse_string", not "parseString") +- Import pyparsing using "import pyparsing as pp", and use that for all pyparsing references + - If referencing anything from pyparsing.common, follow the pyparsing import with "ppc = pp.common" and use ppc as the namespace to access pyparsing.common; same for pyparsing.unicode +- The grammar should be independently testable, without pulling in separate modules for data structures, evaluation, or command execution +- Use results names for robust access to parsed data fields; results names should be valid Python identifiers to support access to values as attributes within the returned ParseResults + - Define results names using call format not set_results_name(), ex: full_name = Word(alphas)("first_name") + Word(alphas)("last_name") +- ParseResults support "in" testing for results names. Use "in" tests for the existence of results names, not hasattr(). +- Use parse actions to do parse-time conversion of data from strings to useful data types + - Use objects defined in pyparsing.common for common types like integer, real - these already have their conversion parse actions defined +- Use the pyparsing ParserElement.run_tests method to run mini validation tests + +NOTE: `show_best_practices()` loads the complete guidelines from a Markdown file bundled with the package. +""" +# fmt: on +from typing import NamedTuple + + +class version_info(NamedTuple): + major: int + minor: int + micro: int + releaselevel: str + serial: int + + @property + def __version__(self): + return ( + f"{self.major}.{self.minor}.{self.micro}" + + ( + f"{'r' if self.releaselevel[0] == 'c' else ''}{self.releaselevel[0]}{self.serial}", + "", + )[self.releaselevel == "final"] + ) + + def __str__(self): + return f"{__name__} {self.__version__} / {__version_time__}" + + def __repr__(self): + return f"{__name__}.{type(self).__name__}({', '.join('{}={!r}'.format(*nv) for nv in zip(self._fields, self))})" + + +__version_info__ = version_info(3, 3, 3, "final", 1) +__version_time__ = "25 Aug 2026 04:00 UTC" +__version__ = __version_info__.__version__ +__versionTime__ = __version_time__ +__author__ = "Paul McGuire " + +from .warnings import * +from .util import * +from .exceptions import * +from .actions import * +from .core import __diag__, __compat__ +from .results import * +from .core import * +from .core import _builtin_exprs as core_builtin_exprs +from .helpers import * +from .helpers import _builtin_exprs as helper_builtin_exprs + +from .unicode import unicode_set, UnicodeRangeList, pyparsing_unicode as unicode +from .testing import pyparsing_test as testing +from .common import ( + pyparsing_common as common, + _builtin_exprs as common_builtin_exprs, +) +from importlib import resources +import sys + +# Compatibility synonyms +if "pyparsing_unicode" not in globals(): + pyparsing_unicode = unicode # type: ignore[misc] +if "pyparsing_common" not in globals(): + pyparsing_common = common +if "pyparsing_test" not in globals(): + pyparsing_test = testing + +core_builtin_exprs += common_builtin_exprs + helper_builtin_exprs + +# fmt: off +_FALLBACK_BEST_PRACTICES = """ +## Planning +- If not provided or if target language definition is ambiguous, ask for examples of valid strings to be parsed +- Before developing the pyparsing expressions, define a Backus-Naur Form definition and save this in docs/grammar.md. Update this document as changes are made in the parser. + +## Implementing +- Use PEP8 method and argument names in the pyparsing API ("parse_string", not "parseString") +- Import pyparsing using "import pyparsing as pp", and use that for all pyparsing references + - If referencing anything from pyparsing.common, follow the pyparsing import with "ppc = pp.common" and use ppc as the namespace to access pyparsing.common; same for pyparsing.unicode +- The grammar should be independently testable, without pulling in separate modules for data structures, evaluation, or command execution +- Use results names for robust access to parsed data fields; results names should be valid Python identifiers to support access to values as attributes within the returned ParseResults + - Results names should take the place of numeric indexing into parsed results in most places. + - Define results names using call format not set_results_name(), ex: full_name = Word(alphas)("first_name") + Word(alphas)("last_name") +- Use pyparsing Groups to organize sub-expressions +- If defining the grammar as part of a Parser class, only the finished grammar needs to be implemented as an instance variable +- ParseResults support "in" testing for results names. Use "in" tests for the existence of results names, not hasattr(). +- Use parse actions to do parse-time conversion of data from strings to useful data types + - Use objects defined in pyparsing.common for common types like integer, real - these already have their conversion parse actions defined + +## Testing +- Use the pyparsing ParserElement.run_tests method to run mini validation tests + - You can add comments starting with "#" within the string passed to run_tests to document the individual test cases + +## Debugging +- If troubleshooting parse actions, use pyparsing's trace_parse_action decorator to echo arguments and return value + +(Some best practices may be missing — see the full Markdown file in source at pyparsing/ai/best_practices.md.) +""" +# fmt: on + + +def show_best_practices(file=sys.stdout) -> Union[str, None]: + """ + Load and return the project's best practices. + + Example:: + + >>> import pyparsing as pp + >>> pp.show_best_practices() + + ... + + This can also be run from the command line:: + + python -m pyparsing.ai.show_best_practices + """ + try: + path = resources.files(__package__).joinpath("ai/best_practices.md") + with path.open("r", encoding="utf-8") as f: + content = f.read() + except (FileNotFoundError, OSError): + content = _FALLBACK_BEST_PRACTICES + + if file is not None: + # just print out the content, no need to return it + print(content, file=file) + return None + + # no output file was specified, return the content as a string + return content + + +__all__ = [ + "__version__", + "__version_time__", + "__author__", + "__compat__", + "__diag__", + "And", + "AtLineStart", + "AtStringStart", + "CaselessKeyword", + "CaselessLiteral", + "CharsNotIn", + "CloseMatch", + "Combine", + "DelimitedList", + "Dict", + "Each", + "Empty", + "FollowedBy", + "Forward", + "GoToColumn", + "Group", + "IndentedBlock", + "Keyword", + "LineEnd", + "LineStart", + "Literal", + "Located", + "PrecededBy", + "MatchFirst", + "NoMatch", + "NotAny", + "OneOrMore", + "OnlyOnce", + "OpAssoc", + "Opt", + "Optional", + "Or", + "ParseBaseException", + "ParseElementEnhance", + "ParseException", + "ParseExpression", + "ParseFatalException", + "ParseResults", + "ParseSyntaxException", + "ParserElement", + "PositionToken", + "PyparsingDeprecationWarning", + "PyparsingDiagnosticWarning", + "PyparsingWarning", + "QuotedString", + "RecursiveGrammarException", + "Regex", + "SkipTo", + "StringEnd", + "StringStart", + "Suppress", + "Tag", + "Token", + "TokenConverter", + "White", + "Word", + "WordEnd", + "WordStart", + "ZeroOrMore", + "Char", + "alphanums", + "alphas", + "alphas8bit", + "any_close_tag", + "any_open_tag", + "autoname_elements", + "c_style_comment", + "col", + "common_html_entity", + "condition_as_parse_action", + "counted_array", + "cpp_style_comment", + "dbl_quoted_string", + "dbl_slash_comment", + "delimited_list", + "dict_of", + "empty", + "hexnums", + "html_comment", + "identchars", + "identbodychars", + "infix_notation", + "java_style_comment", + "line", + "line_end", + "line_start", + "lineno", + "make_html_tags", + "make_xml_tags", + "match_only_at_col", + "match_previous_expr", + "match_previous_literal", + "nested_expr", + "null_debug_action", + "nums", + "one_of", + "original_text_for", + "printables", + "punc8bit", + "pyparsing_common", + "pyparsing_test", + "pyparsing_unicode", + "python_style_comment", + "quoted_string", + "remove_quotes", + "replace_with", + "replace_html_entity", + "rest_of_line", + "sgl_quoted_string", + "show_best_practices", + "srange", + "string_end", + "string_start", + "token_map", + "trace_parse_action", + "ungroup", + "unicode_set", + "unicode_string", + "with_attribute", + "with_class", + # pre-PEP8 compatibility names + "__versionTime__", + "anyCloseTag", + "anyOpenTag", + "cStyleComment", + "commonHTMLEntity", + "conditionAsParseAction", + "countedArray", + "cppStyleComment", + "dblQuotedString", + "dblSlashComment", + "delimitedList", + "dictOf", + "htmlComment", + "indentedBlock", + "infixNotation", + "javaStyleComment", + "lineEnd", + "lineStart", + "locatedExpr", + "makeHTMLTags", + "makeXMLTags", + "matchOnlyAtCol", + "matchPreviousExpr", + "matchPreviousLiteral", + "nestedExpr", + "nullDebugAction", + "oneOf", + "opAssoc", + "originalTextFor", + "pythonStyleComment", + "quotedString", + "removeQuotes", + "replaceHTMLEntity", + "replaceWith", + "restOfLine", + "sglQuotedString", + "stringEnd", + "stringStart", + "tokenMap", + "traceParseAction", + "unicodeString", + "withAttribute", + "withClass", + "common", + "unicode", + "testing", +] diff --git a/.venv/lib/python3.12/site-packages/pyparsing/__pycache__/__init__.cpython-312.pyc b/.venv/lib/python3.12/site-packages/pyparsing/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..80d52cba188c40a69bad253622920dedcbc5ccd0 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/pyparsing/__pycache__/__init__.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/pyparsing/__pycache__/actions.cpython-312.pyc b/.venv/lib/python3.12/site-packages/pyparsing/__pycache__/actions.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..518837e7c296485af51a818fb8ad6b633d98475c Binary files /dev/null and b/.venv/lib/python3.12/site-packages/pyparsing/__pycache__/actions.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/pyparsing/__pycache__/common.cpython-312.pyc b/.venv/lib/python3.12/site-packages/pyparsing/__pycache__/common.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3c9ffb29c7801d35a7c7b1d681b508f4465c688c Binary files /dev/null and b/.venv/lib/python3.12/site-packages/pyparsing/__pycache__/common.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/pyparsing/__pycache__/core.cpython-312.pyc b/.venv/lib/python3.12/site-packages/pyparsing/__pycache__/core.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a7aac5ed4e5daecbdd254abbb23a82940079e964 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/pyparsing/__pycache__/core.cpython-312.pyc @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:1e7961bb2476c67ca244dc022e1e3e97eee6550cef8a3de0ef45f14024d7132c +size 286333 diff --git a/.venv/lib/python3.12/site-packages/pyparsing/__pycache__/exceptions.cpython-312.pyc b/.venv/lib/python3.12/site-packages/pyparsing/__pycache__/exceptions.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..564e3aca9047bb507db79dc60bcc7a86d1ee5d35 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/pyparsing/__pycache__/exceptions.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/pyparsing/__pycache__/helpers.cpython-312.pyc b/.venv/lib/python3.12/site-packages/pyparsing/__pycache__/helpers.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1d8144edddcb56954a4607b428836e55dd1d3786 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/pyparsing/__pycache__/helpers.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/pyparsing/__pycache__/results.cpython-312.pyc b/.venv/lib/python3.12/site-packages/pyparsing/__pycache__/results.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c5a0f4112c20b691a2708f01d62abce0e5f8ea1f Binary files /dev/null and b/.venv/lib/python3.12/site-packages/pyparsing/__pycache__/results.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/pyparsing/__pycache__/testing.cpython-312.pyc b/.venv/lib/python3.12/site-packages/pyparsing/__pycache__/testing.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2ebac952bdf2ab080afa14444d46d44d236ae6e8 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/pyparsing/__pycache__/testing.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/pyparsing/__pycache__/unicode.cpython-312.pyc b/.venv/lib/python3.12/site-packages/pyparsing/__pycache__/unicode.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5948b230dee8e228cf285db9361d4fa657e757e6 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/pyparsing/__pycache__/unicode.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/pyparsing/__pycache__/util.cpython-312.pyc b/.venv/lib/python3.12/site-packages/pyparsing/__pycache__/util.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..65c0b3f9ea74e8ef2de89046d19cbb99bcb870c8 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/pyparsing/__pycache__/util.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/pyparsing/__pycache__/warnings.cpython-312.pyc b/.venv/lib/python3.12/site-packages/pyparsing/__pycache__/warnings.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..73aa75e3bae1b32c3281690110c35818ea9ebff1 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/pyparsing/__pycache__/warnings.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/pyparsing/actions.py b/.venv/lib/python3.12/site-packages/pyparsing/actions.py new file mode 100644 index 0000000000000000000000000000000000000000..85dc41284031eb6c2c97ec0b3ce06173a516eaeb --- /dev/null +++ b/.venv/lib/python3.12/site-packages/pyparsing/actions.py @@ -0,0 +1,264 @@ +# actions.py +from __future__ import annotations + +from typing import Union, Callable, Any + +from .exceptions import ParseException +from .util import col, replaced_by_pep8 +from .results import ParseResults + + +ParseAction = Union[ + Callable[[], Any], + Callable[[ParseResults], Any], + Callable[[int, ParseResults], Any], + Callable[[str, int, ParseResults], Any], +] + + +class OnlyOnce: + """ + Wrapper for parse actions, to ensure they are only called once. + Note: parse action signature must include all 3 arguments. + """ + + def __init__(self, method_call: Callable[[str, int, ParseResults], Any]) -> None: + from .core import _trim_arity + + self.callable = _trim_arity(method_call) + self.called = False + + def __call__(self, s: str, l: int, t: ParseResults) -> ParseResults: + if not self.called: + results = self.callable(s, l, t) + self.called = True + return results + raise ParseException(s, l, "OnlyOnce obj called multiple times w/out reset") + + def reset(self): + """ + Allow the associated parse action to be called once more. + """ + + self.called = False + + +def match_only_at_col(n: int) -> ParseAction: + """ + Helper method for defining parse actions that require matching at + a specific column in the input text. + """ + + def verify_col(strg: str, locn: int, toks: ParseResults) -> None: + if col(locn, strg) != n: + raise ParseException(strg, locn, f"matched token not at column {n}") + + return verify_col + + +def replace_with(repl_str: Any) -> ParseAction: + """ + Helper method for common parse actions that simply return + a literal value. Especially useful when used with + :meth:`~ParserElement.transform_string`. + + Example: + + .. doctest:: + + >>> num = Word(nums).set_parse_action(lambda toks: int(toks[0])) + >>> na = one_of("N/A NA").set_parse_action(replace_with(math.nan)) + >>> term = na | num + + >>> term[1, ...].parse_string("324 234 N/A 234") + ParseResults([324, 234, nan, 234], {}) + """ + return lambda s, l, t: [repl_str] + + +def remove_quotes(s: str, l: int, t: ParseResults) -> Any: + r""" + Helper parse action for removing quotation marks from parsed + quoted strings, that use a single character for quoting. For parsing + strings that may have multiple characters, use the :class:`QuotedString` + class. + + Example: + + .. doctest:: + + >>> # by default, quotation marks are included in parsed results + >>> quoted_string.parse_string("'Now is the Winter of our Discontent'") + ParseResults(["'Now is the Winter of our Discontent'"], {}) + + >>> # use remove_quotes to strip quotation marks from parsed results + >>> dequoted = quoted_string().set_parse_action(remove_quotes) + >>> dequoted.parse_string("'Now is the Winter of our Discontent'") + ParseResults(['Now is the Winter of our Discontent'], {}) + """ + return t[0][1:-1] + + +def with_attribute(*args: tuple[str, str], **attr_dict) -> ParseAction: + """ + Helper to create a validating parse action to be used with start + tags created with :class:`make_xml_tags` or + :class:`make_html_tags`. Use ``with_attribute`` to qualify + a starting tag with a required attribute value, to avoid false + matches on common tags such as ```` or ``
``. + + Call ``with_attribute`` with a series of attribute names and + values. Specify the list of filter attributes names and values as: + + - keyword arguments, as in ``(align="right")``, or + - as an explicit dict with ``**`` operator, when an attribute + name is also a Python reserved word, as in ``**{"class":"Customer", "align":"right"}`` + - a list of name-value tuples, as in ``(("ns1:class", "Customer"), ("ns2:align", "right"))`` + + For attribute names with a namespace prefix, you must use the second + form. Attribute names are matched insensitive to upper/lower case. + + If just testing for ``class`` (with or without a namespace), use + :class:`with_class`. + + To verify that the attribute exists, but without specifying a value, + pass ``with_attribute.ANY_VALUE`` as the value. + + The next two examples use the following input data and tag parsers: + + .. testcode:: + + html = ''' +
+ Some text +
1 4 0 1 0
+
1,3 2,3 1,1
+
this has no type
+
+ ''' + div,div_end = make_html_tags("div") + + Only match div tag having a type attribute with value "grid": + + .. testcode:: + + div_grid = div().set_parse_action(with_attribute(type="grid")) + grid_expr = div_grid + SkipTo(div | div_end)("body") + for grid_header in grid_expr.search_string(html): + print(grid_header.body) + + prints: + + .. testoutput:: + + 1 4 0 1 0 + + Construct a match with any div tag having a type attribute, + regardless of the value: + + .. testcode:: + + div_any_type = div().set_parse_action( + with_attribute(type=with_attribute.ANY_VALUE) + ) + div_expr = div_any_type + SkipTo(div | div_end)("body") + for div_header in div_expr.search_string(html): + print(div_header.body) + + prints: + + .. testoutput:: + + 1 4 0 1 0 + 1,3 2,3 1,1 + """ + attrs_list: list[tuple[str, str]] = [] + if args: + attrs_list.extend(args) + else: + attrs_list.extend(attr_dict.items()) + + def pa(s: str, l: int, tokens: ParseResults) -> None: + for attrName, attrValue in attrs_list: + if attrName not in tokens: + raise ParseException(s, l, f"no matching attribute {attrName!r}") + if attrValue != with_attribute.ANY_VALUE and tokens[attrName] != attrValue: # type: ignore [attr-defined] + raise ParseException( + s, + l, + f"attribute {attrName!r} has value {tokens[attrName]!r}, must be {attrValue!r}", + ) + + return pa + + +with_attribute.ANY_VALUE = object() # type: ignore [attr-defined] +"Value to use with :class:`with_attribute` parse action, to match any value, as long as the attribute is present" + + +def with_class(classname: str, namespace: str = "") -> ParseAction: + """ + Simplified version of :meth:`with_attribute` when + matching on a div class - made difficult because ``class`` is + a reserved word in Python. + + Using similar input data to the :meth:`with_attribute` examples: + + .. testcode:: + + html = ''' +
+ Some text +
1 4 0 1 0
+
1,3 2,3 1,1
+
this <div> has no class
+
+ ''' + div,div_end = make_html_tags("div") + + Only match div tag having the "grid" class: + + .. testcode:: + + div_grid = div().set_parse_action(with_class("grid")) + grid_expr = div_grid + SkipTo(div | div_end)("body") + for grid_header in grid_expr.search_string(html): + print(grid_header.body) + + prints: + + .. testoutput:: + + 1 4 0 1 0 + + Construct a match with any div tag having a class attribute, + regardless of the value: + + .. testcode:: + + div_any_type = div().set_parse_action( + with_class(withAttribute.ANY_VALUE) + ) + div_expr = div_any_type + SkipTo(div | div_end)("body") + for div_header in div_expr.search_string(html): + print(div_header.body) + + prints: + + .. testoutput:: + + 1 4 0 1 0 + 1,3 2,3 1,1 + """ + classattr = f"{namespace}:class" if namespace else "class" + return with_attribute(**{classattr: classname}) + + +# Compatibility synonyms +# fmt: off +replaceWith = replaced_by_pep8("replaceWith", replace_with) +removeQuotes = replaced_by_pep8("removeQuotes", remove_quotes) +withAttribute = replaced_by_pep8("withAttribute", with_attribute) +withClass = replaced_by_pep8("withClass", with_class) +matchOnlyAtCol = replaced_by_pep8("matchOnlyAtCol", match_only_at_col) +# fmt: on diff --git a/.venv/lib/python3.12/site-packages/pyparsing/ai/__init__.py b/.venv/lib/python3.12/site-packages/pyparsing/ai/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/.venv/lib/python3.12/site-packages/pyparsing/ai/__pycache__/__init__.cpython-312.pyc b/.venv/lib/python3.12/site-packages/pyparsing/ai/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3df39cff294ace881541c500e0b70e017b9c28eb Binary files /dev/null and b/.venv/lib/python3.12/site-packages/pyparsing/ai/__pycache__/__init__.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/pyparsing/ai/best_practices.md b/.venv/lib/python3.12/site-packages/pyparsing/ai/best_practices.md new file mode 100644 index 0000000000000000000000000000000000000000..94aa52d8f42579e90ddff66d53efc1626f27ff41 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/pyparsing/ai/best_practices.md @@ -0,0 +1,75 @@ + + +## Planning +- If not provided or if target language definition is ambiguous, ask for examples of valid strings to be parsed +- Before developing the pyparsing expressions, define a Backus-Naur Form definition and save this in docs/grammar.md. Update this document as changes are made in the parser. + +## Implementing +- Import pyparsing using `import pyparsing as pp`, and use that for all pyparsing references. + - If referencing names from `pyparsing.common`, follow the pyparsing import with "ppc = pp.common" and use `ppc` as the namespace to access `pyparsing.common`. + - If referencing names from `pyparsing.unicode`, follow the pyparsing import with "ppu = pp.unicode" and use `ppu` as the namespace to access `pyparsing.unicode`. +- When writing parsers that contain recursive elements (using `Forward()` or `infix_notation()`), immediately enable packrat parsing for performance: `pp.ParserElement.enable_packrat()` (call this right after importing pyparsing). See https://pyparsing-docs.readthedocs.io/en/latest/HowToUsePyparsing.html. + - For recursive grammars, define placeholders with `pp.Forward()` and assign later using the `<<=` operator; give Forwards meaningful names with `set_name()` to improve errors. +- Use PEP8 method and argument names in the pyparsing API (`parse_string`, not `parseString`). +- Do not include expressions for matching whitespace in the grammar. Pyparsing skips whitespace by default. +- For line-oriented grammars where newlines are significant, set skippable whitespace to just spaces/tabs early: `pp.ParserElement.set_default_whitespace_chars(" \t")`, and define `NL = pp.LineEnd().suppress()` to handle line ends explicitly. +- Prefer operator forms for readability: use +, |, ^, ~, etc., instead of explicit And/MatchFirst/Or/Not classes (see Usage notes in https://pyparsing-docs.readthedocs.io/en/latest/HowToUsePyparsing.html). +- Use `set_name()` on all major grammar elements to support railroad diagramming and better error/debug output. +- The grammar should be independently testable, without pulling in separate modules for data structures, evaluation, or command execution. +- Use results names for robust access to parsed data fields; results names should be valid Python identifiers to support attribute-style access on returned ParseResults. + - Results names should take the place of numeric indexing into parsed results in most places. + - Define results names using call format not `set_results_name()`, example: `full_name = Word(alphas)("first_name") + Word(alphas)("last_name")` + - If adding results name to an expression that is contains one more sub-expressions with results names, the expression must be inclused in a Group. +- Prefer `Keyword` over `Literal` for reserved words to avoid partial matches (e.g., `Keyword("for")` will not match the leading "for" in "format"). + - Use `pp.CaselessKeyword`/`pp.CaselessLiteral` when keywords should match regardless of case. +- When the full input must be consumed, call `parse_string` with `parse_all=True`. +- If the grammar must handle comments, define an expression for them and use the `ignore()` method to skip them. + - Prefer built-ins like `pp.cpp_style_comment` and `pp.python_style_comment` for common comment syntaxes. +- Use pyparsing `Group` to organize sub-expressions. Groups are also important for preserving results names when a sub-expression is used in a `OneOrMore` or `ZeroOrMore` expression. +- Suppress punctuation tokens to keep results clean; a convenient pattern is `LBRACK, RBRACK, LBRACE, RBRACE, COLON = pp.Suppress.using_each("[]{}:")`. +- For comma-separated sequences, prefer `pp.DelimitedList(...)`; wrap with `pp.Optional(...)` to allow empty lists or objects where appropriate. +- For helper sub-expressions used only to build larger expressions, consider `set_name(None)` to keep result dumps uncluttered. +- Use pyparsing `Each()` to define a list of elements that may occur in any order. + - The '&' operator is the operator form of Each and is often more readable when combining order-independent parts. +- Use parse actions to do parse-time conversion of data from strings to useful data types. + - Use objects defined in pyparsing.common for common types like integer, real — these already have their conversion parse actions defined. + - For quoted strings, use `pp.dbl_quoted_string().set_parse_action(pp.remove_quotes)` to unquote automatically. + - Map reserved words to Python constants per this example for parsing "true" to auto-convert to a Python True: `pp.Keyword("true").set_parse_action(pp.replace_with(True))` (and similarly for false/null/etc.). + - When you want native Python containers from the parse, use `pp.Group(..., aslist=True)` for lists and `pp.Dict(..., asdict=True)` for dict-like data. +- Use "using_each" with a list of keywords to define keyword constants, instead of separate assignments. +- Choose the appropriate matching method: + - `parse_string()` parses from the start + - `search_string()` searches anywhere in the text + - `scan_string()` yields all matches with positions + - `transform_string()` is a convenience wrapper around `scan_string` to apply filters or transforms defined in parse actions, to perform batch transforms or conversions of expressions within a larger body of text +- For line suffixes or directives, combine lookahead and slicing helpers: `pp.FollowedBy(...)` with `pp.rest_of_line`; when reusing a base expression with a different parse action, call `.copy()` before applying the new action to avoid side effects. +- When defining a parser to be used in a REPL: + - add pyparsing `Tag()` elements of the form `Tag("command", )` to each command definition to support model construction from parsed commands. + - define model classes using dataclasses, and use the "command" attribute in the parsed results to identify which model class to create. The model classes can then be used to construct the model from the ParseResults returned by parse_string(). Define the models in a separate parser_models.py file. +- If defining the grammar as part of a Parser class, only the finished grammar needs to be implemented as an instance variable. +- `ParseResults` support "in" testing for results names. Use "in" tests for the existence of results names, not `hasattr()`. +- Avoid left recursion where possible. If you must support left-recursive grammars, enable it with `pp.ParserElement.enable_left_recursion()` and do not enable packrat at the same time (these modes are incompatible). +- Use `pp.SkipTo` as a skipping expression to skip over arbitrary content. + - For example, `pp.SkipTo(pp.LineEnd())` will skip over all content until the end of the line; add a stop_on argument to SkipTo to stop skipping when a particular string is matched. + - Use `...` in place of simple SkipTo(expression) + +## Testing +- Use the pyparsing `ParserElement.run_tests` method to run mini validation tests. + - Pass a single multiline string to `run_tests` to test the parser on multiple test input strings, each line is a separate test. + - You can add comments starting with "#" within the string passed to `run_tests` to document the individual test cases. + - To pass test input strings that span multiple lines, pass the test input strings as a list of strings. + - Pass `parse_all=True` to `run_tests` to test that the entire input is consumed. +- When generating unit tests for the parser: + - generate tests that include presence and absence of optional elements + - use the methods in the mixin class pyparsing.testing.TestParseResultsAsserts to easily define expression, test input string, and expected results + - do not generate tests for invalid data + +## Debugging +- If troubleshooting parse actions, use pyparsing's `trace_parse_action` decorator to echo arguments and return value +- During development, call `pp.autoname_elements()` to auto-assign names to unnamed expressions to improve `dump()` and error messages. +- Sub-expressions can be tested in isolation using `ParserElement.matches()` +- When defined out of order, Literals can mistakenly match fragments: `Literal("for")` will match the leading "for" in "format". Can be corrected by using `Keyword` instead of `Literal`. +- Dump the parsed results using `ParseResults.dump()`, `ParseResults.pprint()`, or `repr(ParseResults)`. diff --git a/.venv/lib/python3.12/site-packages/pyparsing/ai/show_best_practices/__init__.py b/.venv/lib/python3.12/site-packages/pyparsing/ai/show_best_practices/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/.venv/lib/python3.12/site-packages/pyparsing/ai/show_best_practices/__main__.py b/.venv/lib/python3.12/site-packages/pyparsing/ai/show_best_practices/__main__.py new file mode 100644 index 0000000000000000000000000000000000000000..b3172570ce5be7e8ec468ad4c1e493ac2df06886 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/pyparsing/ai/show_best_practices/__main__.py @@ -0,0 +1,2 @@ +import pyparsing +pyparsing.show_best_practices() diff --git a/.venv/lib/python3.12/site-packages/pyparsing/ai/show_best_practices/__pycache__/__init__.cpython-312.pyc b/.venv/lib/python3.12/site-packages/pyparsing/ai/show_best_practices/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..13a2aba606d12e8a70a43a8299d8506082f38b0d Binary files /dev/null and b/.venv/lib/python3.12/site-packages/pyparsing/ai/show_best_practices/__pycache__/__init__.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/pyparsing/ai/show_best_practices/__pycache__/__main__.cpython-312.pyc b/.venv/lib/python3.12/site-packages/pyparsing/ai/show_best_practices/__pycache__/__main__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3521a211f952019544190224c415ab9a9bec6a1c Binary files /dev/null and b/.venv/lib/python3.12/site-packages/pyparsing/ai/show_best_practices/__pycache__/__main__.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/pyparsing/common.py b/.venv/lib/python3.12/site-packages/pyparsing/common.py new file mode 100644 index 0000000000000000000000000000000000000000..c89eda36f2d74693b234251b5a2d4c9a2e5efaa1 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/pyparsing/common.py @@ -0,0 +1,570 @@ +# common.py +from .core import * +from .helpers import DelimitedList, any_open_tag, any_close_tag +from datetime import datetime +import sys + +PY_310_OR_LATER = sys.version_info >= (3, 10) + + +# some other useful expressions - using lower-case class name since we are really using this as a namespace +class pyparsing_common: + """Here are some common low-level expressions that may be useful in + jump-starting parser development: + + - numeric forms (:class:`integers`, :class:`reals`, + :class:`scientific notation`) + - common :class:`programming identifiers` + - network addresses (:class:`MAC`, + :class:`IPv4`, :class:`IPv6`) + - ISO8601 :class:`dates` and + :class:`datetime` + - :class:`UUID` + - :class:`comma-separated list` + - :class:`url` + + Parse actions: + + - :class:`convert_to_integer` + - :class:`convert_to_float` + - :class:`convert_to_date` + - :class:`convert_to_datetime` + - :class:`strip_html_tags` + - :class:`upcase_tokens` + - :class:`downcase_tokens` + + Examples: + + .. testcode:: + + pyparsing_common.number.run_tests(''' + # any int or real number, returned as the appropriate type + 100 + -100 + +100 + 3.14159 + 6.02e23 + 1e-12 + ''') + + .. testoutput:: + :options: +NORMALIZE_WHITESPACE + + + # any int or real number, returned as the appropriate type + 100 + [100] + + -100 + [-100] + + +100 + [100] + + 3.14159 + [3.14159] + + 6.02e23 + [6.02e+23] + + 1e-12 + [1e-12] + + .. testcode:: + + pyparsing_common.fnumber.run_tests(''' + # any int or real number, returned as float + 100 + -100 + +100 + 3.14159 + 6.02e23 + 1e-12 + ''') + + .. testoutput:: + :options: +NORMALIZE_WHITESPACE + + + # any int or real number, returned as float + 100 + [100.0] + + -100 + [-100.0] + + +100 + [100.0] + + 3.14159 + [3.14159] + + 6.02e23 + [6.02e+23] + + 1e-12 + [1e-12] + + .. testcode:: + + pyparsing_common.hex_integer.run_tests(''' + # hex numbers + 100 + FF + ''') + + .. testoutput:: + :options: +NORMALIZE_WHITESPACE + + + # hex numbers + 100 + [256] + + FF + [255] + + .. testcode:: + + pyparsing_common.fraction.run_tests(''' + # fractions + 1/2 + -3/4 + ''') + + .. testoutput:: + :options: +NORMALIZE_WHITESPACE + + + # fractions + 1/2 + [0.5] + + -3/4 + [-0.75] + + .. testcode:: + + pyparsing_common.mixed_integer.run_tests(''' + # mixed fractions + 1 + 1/2 + -3/4 + 1-3/4 + ''') + + .. testoutput:: + :options: +NORMALIZE_WHITESPACE + + + # mixed fractions + 1 + [1] + + 1/2 + [0.5] + + -3/4 + [-0.75] + + 1-3/4 + [1.75] + .. testcode:: + + import uuid + pyparsing_common.uuid.set_parse_action(token_map(uuid.UUID)) + pyparsing_common.uuid.run_tests(''' + # uuid + 12345678-1234-5678-1234-567812345678 + ''') + + .. testoutput:: + :options: +NORMALIZE_WHITESPACE + + + # uuid + 12345678-1234-5678-1234-567812345678 + [UUID('12345678-1234-5678-1234-567812345678')] + """ + + @staticmethod + def convert_to_integer(_, __, t): + """ + Parse action for converting parsed integers to Python int + """ + return [int(tt) for tt in t] + + @staticmethod + def convert_to_float(_, __, t): + """ + Parse action for converting parsed numbers to Python float + """ + return [float(tt) for tt in t] + + integer = ( + Word(nums) + .set_name("integer") + .set_parse_action( + convert_to_integer + if PY_310_OR_LATER + else lambda t: [int(tt) for tt in t] + ) + ) + """expression that parses an unsigned integer, converts to an int""" + + hex_integer = ( + Word(hexnums).set_name("hex integer").set_parse_action(token_map(int, 16)) + ) + """expression that parses a hexadecimal integer, converts to an int""" + + signed_integer = ( + Regex(r"[+-]?\d+") + .set_name("signed integer") + .set_parse_action( + convert_to_integer + if PY_310_OR_LATER + else lambda t: [int(tt) for tt in t] + ) + ) + """expression that parses an integer with optional leading sign, converts to an int""" + + fraction = ( + signed_integer().set_parse_action( + convert_to_float + if PY_310_OR_LATER + else lambda t: [float(tt) for tt in t] + ) + + "/" + + signed_integer().set_parse_action( + convert_to_float + if PY_310_OR_LATER + else lambda t: [float(tt) for tt in t] + ) + ).set_name("fraction") + """fractional expression of an integer divided by an integer, converts to a float""" + fraction.add_parse_action(lambda tt: tt[0] / tt[-1]) + + mixed_integer = ( + fraction | signed_integer + Opt(Opt("-").suppress() + fraction) + ).set_name("fraction or mixed integer-fraction") + """mixed integer of the form 'integer - fraction', with optional leading integer, converts to a float""" + mixed_integer.add_parse_action(sum) + + real = ( + Regex(r"[+-]?(?:\d+\.\d*|\.\d+)") + .set_name("real number") + .set_parse_action( + convert_to_float + if PY_310_OR_LATER + else lambda t: [float(tt) for tt in t] + ) + ) + """expression that parses a floating point number, converts to a float""" + + sci_real = ( + Regex(r"[+-]?(?:\d+(?:[eE][+-]?\d+)|(?:\d+\.\d*|\.\d+)(?:[eE][+-]?\d+)?)") + .set_name("real number with scientific notation") + .set_parse_action( + convert_to_float + if PY_310_OR_LATER + else lambda t: [float(tt) for tt in t] + ) + ) + """expression that parses a floating point number with optional + scientific notation, converts to a float""" + + # streamlining this expression makes the docs nicer-looking + number = (sci_real | real | signed_integer).set_name("number").streamline() + """any numeric expression, converts to the corresponding Python type""" + + fnumber = ( + Regex(r"[+-]?\d+\.?\d*(?:[eE][+-]?\d+)?") + .set_name("fnumber") + .set_parse_action( + convert_to_float + if PY_310_OR_LATER + else lambda t: [float(tt) for tt in t] + ) + ) + """any int or real number, always converts to a float""" + + ieee_float = ( + Regex(r"(?i:[+-]?(?:(?:\d+\.?\d*(?:e[+-]?\d+)?)|nan|inf(?:inity)?))") + .set_name("ieee_float") + .set_parse_action( + convert_to_float + if PY_310_OR_LATER + else lambda t: [float(tt) for tt in t] + ) + ) + """any floating-point literal (int, real number, infinity, or NaN), converts to a float""" + + identifier = Word(identchars, identbodychars).set_name("identifier") + """typical code identifier (leading alpha or '_', followed by 0 or more alphas, nums, or '_')""" + + ipv4_address = Regex( + r"(?:25[0-5]|2[0-4][0-9]|1?[0-9]{1,2})(?:\.(?:25[0-5]|2[0-4][0-9]|1?[0-9]{1,2})){3}" + ).set_name("IPv4 address") + "IPv4 address (``0.0.0.0 - 255.255.255.255``)" + + _ipv6_part = Regex(r"[0-9a-fA-F]{1,4}").set_name("hex_integer") + _full_ipv6_address = (_ipv6_part + (":" + _ipv6_part) * 7).set_name( + "full IPv6 address" + ) + _short_ipv6_address = ( + Opt(_ipv6_part + (":" + _ipv6_part) * (0, 6)) + + "::" + + Opt(_ipv6_part + (":" + _ipv6_part) * (0, 6)) + ).set_name("short IPv6 address") + _short_ipv6_address.add_condition( + lambda t: sum(1 for tt in t if pyparsing_common._ipv6_part.matches(tt)) < 8 + ) + _mixed_ipv6_address = ("::ffff:" + ipv4_address).set_name("mixed IPv6 address") + ipv6_address = Combine( + (_full_ipv6_address | _mixed_ipv6_address | _short_ipv6_address).set_name( + "IPv6 address" + ) + ).set_name("IPv6 address") + "IPv6 address (long, short, or mixed form)" + + mac_address = Regex( + r"[0-9a-fA-F]{2}([:.-])[0-9a-fA-F]{2}(?:\1[0-9a-fA-F]{2}){4}" + ).set_name("MAC address") + "MAC address xx:xx:xx:xx:xx (may also have '-' or '.' delimiters)" + + @staticmethod + def convert_to_date(fmt: str = "%Y-%m-%d"): + """ + Helper to create a parse action for converting parsed date string to Python datetime.date + + Params - + - fmt - format to be passed to datetime.strptime (default= ``"%Y-%m-%d"``) + + Example: + + .. testcode:: + + date_expr = pyparsing_common.iso8601_date.copy() + date_expr.set_parse_action(pyparsing_common.convert_to_date()) + print(date_expr.parse_string("1999-12-31")) + + prints: + + .. testoutput:: + + [datetime.date(1999, 12, 31)] + """ + + def cvt_fn(ss, ll, tt): + try: + return datetime.strptime(tt[0], fmt).date() + except ValueError as ve: + raise ParseException(ss, ll, str(ve)) + + return cvt_fn + + @staticmethod + def convert_to_datetime(fmt: str = "%Y-%m-%dT%H:%M:%S.%f"): + """Helper to create a parse action for converting parsed + datetime string to Python :class:`datetime.datetime` + + Params - + - fmt - format to be passed to :class:`datetime.strptime` (default= ``"%Y-%m-%dT%H:%M:%S.%f"``) + + Example: + + .. testcode:: + + dt_expr = pyparsing_common.iso8601_datetime.copy() + dt_expr.set_parse_action(pyparsing_common.convert_to_datetime()) + print(dt_expr.parse_string("1999-12-31T23:59:59.999")) + + prints: + + .. testoutput:: + + [datetime.datetime(1999, 12, 31, 23, 59, 59, 999000)] + """ + + def cvt_fn(s, l, t): + try: + return datetime.strptime(t[0], fmt) + except ValueError as ve: + raise ParseException(s, l, str(ve)) + + return cvt_fn + + iso8601_date = Regex( + r"(?P\d{4})(?:-(?P\d\d)(?:-(?P\d\d))?)?" + ).set_name("ISO8601 date") + "ISO8601 date (``yyyy-mm-dd``)" + + iso8601_datetime = Regex( + r"(?P\d{4})-(?P\d\d)-(?P\d\d)[T ](?P\d\d):(?P\d\d)(:(?P\d\d(\.\d*)?)?)?(?PZ|[+-]\d\d:?\d\d)?" + ).set_name("ISO8601 datetime") + "ISO8601 datetime (``yyyy-mm-ddThh:mm:ss.s(Z|+-00:00)``) - trailing seconds, milliseconds, and timezone optional; accepts separating ``'T'`` or ``' '``" + + @staticmethod + def as_datetime(s, l, t): + """Parse action to convert parsed dates or datetimes to a Python + :class:`datetime.datetime`. + + This parse action will use the year, month, day, etc. results + names defined in the ISO8601 date expressions, but it can be + used with any expression that provides one or more of these fields. + + Omitted fields will default to fields from Jan 1, 00:00:00. + + Invalid dates will raise a :class:`ParseException` with the + error message indicating the invalid date fields. + """ + year = int(t.year.lstrip("0") or 0) + month = int(t.month or 1) + day = int(t.day or 1) + hour = int(t.hour or 0) + minute = int(t.minute or 0) + second = float(t.second or 0) + try: + return datetime( + year, month, day, hour, minute, int(second), int((second % 1) * 1000) + ) + except ValueError as ve: + raise ParseException(t, l, f"Invalid date/time: {ve}").with_traceback( + ve.__traceback__ + ) from None + + if PY_310_OR_LATER: + iso8601_date_validated = iso8601_date().add_parse_action(as_datetime) + "Validated ISO8601 date strings, raising :class:`ParseException` for invalid date values." + + iso8601_datetime_validated = iso8601_datetime().add_parse_action(as_datetime) + "Validated ISO8601 date and time strings, raising :class:`ParseException` for invalid date/time values." + + uuid = Regex(r"[0-9a-fA-F]{8}(?:-[0-9a-fA-F]{4}){3}-[0-9a-fA-F]{12}").set_name( + "UUID" + ) + "UUID (``xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx``)" + + _html_stripper = any_open_tag.suppress() | any_close_tag.suppress() + + @staticmethod + def strip_html_tags(s: str, l: int, tokens: ParseResults): + """Parse action to remove HTML tags from web page HTML source + + Example: + + .. testcode:: + + # strip HTML links from normal text + text = 'More info at the pyparsing wiki page' + td, td_end = make_html_tags("TD") + table_text = td + SkipTo(td_end).set_parse_action( + pyparsing_common.strip_html_tags)("body") + td_end + print(table_text.parse_string(text).body) + + Prints: + + .. testoutput:: + + More info at the pyparsing wiki page + """ + return pyparsing_common._html_stripper.transform_string(tokens[0]) + + _commasepitem = ( + Combine( + OneOrMore( + ~Literal(",") + + ~LineEnd() + + Word(printables, exclude_chars=",") + + Opt(White(" \t") + ~FollowedBy(LineEnd() | ",")) + ) + ) + .streamline() + .set_name("commaItem") + ) + comma_separated_list = DelimitedList( + Opt(quoted_string.copy() | _commasepitem, default="") + ).set_name("comma separated list") + """Predefined expression of 1 or more printable words or quoted strings, separated by commas.""" + + @staticmethod + def upcase_tokens(s, l, t): + """Parse action to convert tokens to upper case.""" + return [tt.upper() for tt in t] + + @staticmethod + def downcase_tokens(s, l, t): + """Parse action to convert tokens to lower case.""" + return [tt.lower() for tt in t] + + # fmt: off + url = Regex( + # https://mathiasbynens.be/demo/url-regex + # https://gist.github.com/dperini/729294 + r"(?P" + # protocol identifier (optional) + # short syntax // still required + r"(?:(?:(?Phttps?|ftp):)?\/\/)" + # user:pass BasicAuth (optional) + r"(?:(?P\S+(?::\S*)?)@)?" + r"(?P" + # IP address exclusion + # private & local networks + r"(?!(?:10|127)(?:\.\d{1,3}){3})" + r"(?!(?:169\.254|192\.168)(?:\.\d{1,3}){2})" + r"(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})" + # IP address dotted notation octets + # excludes loopback network 0.0.0.0 + # excludes reserved space >= 224.0.0.0 + # excludes network & broadcast addresses + # (first & last IP address of each class) + r"(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])" + r"(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}" + r"(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))" + r"|" + # host & domain names, may end with dot + # can be replaced by a shortest alternative + # (?![-_])(?:[-\w\u00a1-\uffff]{0,63}[^-_]\.)+ + r"(?:" + r"(?:" + r"[a-z0-9\u00a1-\uffff]" + r"[a-z0-9\u00a1-\uffff_-]{0,62}" + r")?" + r"[a-z0-9\u00a1-\uffff]\." + r")+" + # TLD identifier name, may end with dot + r"(?:[a-z\u00a1-\uffff]{2,}\.?)" + r")" + # port number (optional) + r"(:(?P\d{2,5}))?" + # resource path (optional) + r"(?P\/[^?# ]*)?" + # query string (optional) + r"(\?(?P[^#]*))?" + # fragment (optional) + r"(#(?P\S*))?" + r")" + ).set_name("url") + """ + URL (http/https/ftp scheme) + + .. versionchanged:: 3.1.0 + ``url`` named group added + """ + # fmt: on + + # pre-PEP8 compatibility names + # fmt: off + convertToInteger = staticmethod(replaced_by_pep8("convertToInteger", convert_to_integer)) + convertToFloat = staticmethod(replaced_by_pep8("convertToFloat", convert_to_float)) + convertToDate = staticmethod(replaced_by_pep8("convertToDate", convert_to_date)) + convertToDatetime = staticmethod(replaced_by_pep8("convertToDatetime", convert_to_datetime)) + stripHTMLTags = staticmethod(replaced_by_pep8("stripHTMLTags", strip_html_tags)) + upcaseTokens = staticmethod(replaced_by_pep8("upcaseTokens", upcase_tokens)) + downcaseTokens = staticmethod(replaced_by_pep8("downcaseTokens", downcase_tokens)) + # fmt: on + + +_builtin_exprs = [ + v for v in vars(pyparsing_common).values() if isinstance(v, ParserElement) +] diff --git a/.venv/lib/python3.12/site-packages/pyparsing/core.py b/.venv/lib/python3.12/site-packages/pyparsing/core.py new file mode 100644 index 0000000000000000000000000000000000000000..946b483829b9355f1345d4dc1854a638a5636365 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/pyparsing/core.py @@ -0,0 +1,6972 @@ +# +# core.py +# +from __future__ import annotations + +import collections.abc +from collections import deque +import os +import typing +from typing import ( + Any, + Callable, + Generator, + NamedTuple, + Sequence, + TextIO, + Union, + cast, +) +from abc import ABC, abstractmethod +from enum import Enum +import string +import copy +import warnings +import re +import sys +from collections.abc import Iterable +import traceback +import types +from operator import itemgetter +from functools import wraps +from threading import RLock +from pathlib import Path + +from .warnings import PyparsingDeprecationWarning, PyparsingDiagnosticWarning +from .util import ( + _FifoCache, + _UnboundedCache, + __config_flags, + _collapse_string_to_ranges, + _convert_escaped_numerics_to_char, + _escape_regex_range_chars, + _flatten, + LRUMemo as _LRUMemo, + UnboundedMemo as _UnboundedMemo, + deprecate_argument, + replaced_by_pep8, +) +from .exceptions import * +from .actions import * +from .results import ParseResults, _ParseResultsWithOffset +from .unicode import pyparsing_unicode + +_MAX_INT = sys.maxsize +str_type: tuple[type, ...] = (str, bytes) + +# +# Copyright (c) 2003-2022 Paul T. McGuire +# +# Permission is hereby granted, free of charge, to any person obtaining +# a copy of this software and associated documentation files (the +# "Software"), to deal in the Software without restriction, including +# without limitation the rights to use, copy, modify, merge, publish, +# distribute, sublicense, and/or sell copies of the Software, and to +# permit persons to whom the Software is furnished to do so, subject to +# the following conditions: +# +# The above copyright notice and this permission notice shall be +# included in all copies or substantial portions of the Software. +# +# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +# IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +# CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, +# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE +# SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +# + +from functools import cached_property + + +class __compat__(__config_flags): + """ + A cross-version compatibility configuration for pyparsing features that will be + released in a future version. By setting values in this configuration to True, + those features can be enabled in prior versions for compatibility development + and testing. + + - ``collect_all_And_tokens`` - flag to enable fix for Issue #63 that fixes erroneous grouping + of results names when an :class:`And` expression is nested within an :class:`Or` or :class:`MatchFirst`; + maintained for compatibility, but setting to ``False`` no longer restores pre-2.3.1 + behavior + """ + + _type_desc = "compatibility" + + collect_all_And_tokens = True + + _all_names = [__ for __ in locals() if not __.startswith("_")] + _fixed_names = """ + collect_all_And_tokens + """.split() + + +class __diag__(__config_flags): + _type_desc = "diagnostic" + + warn_multiple_tokens_in_named_alternation = False + warn_ungrouped_named_tokens_in_collection = False + warn_name_set_on_empty_Forward = False + warn_on_parse_using_empty_Forward = False + warn_on_assignment_to_Forward = False + warn_on_multiple_string_args_to_oneof = False + warn_on_match_first_with_lshift_operator = False + enable_debug_on_named_expressions = False + + _all_names = [__ for __ in locals() if not __.startswith("_")] + _warning_names = [name for name in _all_names if name.startswith("warn")] + _debug_names = [name for name in _all_names if name.startswith("enable_debug")] + + @classmethod + def enable_all_warnings(cls) -> None: + for name in cls._warning_names: + cls.enable(name) + + +class Diagnostics(Enum): + """ + Diagnostic configuration (all default to disabled) + + - ``warn_multiple_tokens_in_named_alternation`` - flag to enable warnings when a results + name is defined on a :class:`MatchFirst` or :class:`Or` expression with one or more :class:`And` subexpressions + - ``warn_ungrouped_named_tokens_in_collection`` - flag to enable warnings when a results + name is defined on a containing expression with ungrouped subexpressions that also + have results names + - ``warn_name_set_on_empty_Forward`` - flag to enable warnings when a :class:`Forward` is defined + with a results name, but has no contents defined + - ``warn_on_parse_using_empty_Forward`` - flag to enable warnings when a :class:`Forward` is + defined in a grammar but has never had an expression attached to it + - ``warn_on_assignment_to_Forward`` - flag to enable warnings when a :class:`Forward` is defined + but is overwritten by assigning using ``'='`` instead of ``'<<='`` or ``'<<'`` + - ``warn_on_multiple_string_args_to_oneof`` - flag to enable warnings when :class:`one_of` is + incorrectly called with multiple str arguments + - ``enable_debug_on_named_expressions`` - flag to auto-enable debug on all subsequent + calls to :class:`ParserElement.set_name` + + Diagnostics are enabled/disabled by calling :class:`enable_diag` and :class:`disable_diag`. + All warnings can be enabled by calling :class:`enable_all_warnings`. + """ + + warn_multiple_tokens_in_named_alternation = 0 + warn_ungrouped_named_tokens_in_collection = 1 + warn_name_set_on_empty_Forward = 2 + warn_on_parse_using_empty_Forward = 3 + warn_on_assignment_to_Forward = 4 + warn_on_multiple_string_args_to_oneof = 5 + warn_on_match_first_with_lshift_operator = 6 + enable_debug_on_named_expressions = 7 + + +def enable_diag(diag_enum: Diagnostics) -> None: + """ + Enable a global pyparsing diagnostic flag (see :class:`Diagnostics`). + """ + __diag__.enable(diag_enum.name) + + +def disable_diag(diag_enum: Diagnostics) -> None: + """ + Disable a global pyparsing diagnostic flag (see :class:`Diagnostics`). + """ + __diag__.disable(diag_enum.name) + + +def enable_all_warnings() -> None: + """ + Enable all global pyparsing diagnostic warnings (see :class:`Diagnostics`). + """ + __diag__.enable_all_warnings() + + +# hide abstract class +del __config_flags + + +def _should_enable_warnings( + cmd_line_warn_options: typing.Iterable[str], warn_env_var: typing.Optional[str] +) -> bool: + enable = bool(warn_env_var) + for warn_opt in cmd_line_warn_options: + w_action, w_message, w_category, w_module, w_line = (warn_opt + "::::").split( + ":" + )[:5] + if not w_action.lower().startswith("i") and ( + not (w_message or w_category or w_module) or w_module == "pyparsing" + ): + enable = True + elif w_action.lower().startswith("i") and w_module in ("pyparsing", ""): + enable = False + return enable + + +if _should_enable_warnings( + sys.warnoptions, os.environ.get("PYPARSINGENABLEALLWARNINGS") +): + enable_all_warnings() + + +# build list of single arg builtins, that can be used as parse actions +# fmt: off +_single_arg_builtins = { + sum, len, sorted, reversed, list, tuple, set, any, all, min, max +} +# fmt: on + +_generatorType = types.GeneratorType +ParseImplReturnType = tuple[int, Any] +PostParseReturnType = Union[ParseResults, Sequence[ParseResults]] + +ParseCondition = Union[ + Callable[[], bool], + Callable[[ParseResults], bool], + Callable[[int, ParseResults], bool], + Callable[[str, int, ParseResults], bool], +] +ParseFailAction = Callable[[str, int, "ParserElement", Exception], None] +DebugStartAction = Callable[[str, int, "ParserElement", bool], None] +DebugSuccessAction = Callable[ + [str, int, int, "ParserElement", ParseResults, bool], None +] +DebugExceptionAction = Callable[[str, int, "ParserElement", Exception, bool], None] + + +alphas: str = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz" +identchars: str = pyparsing_unicode.Latin1.identchars +identbodychars: str = pyparsing_unicode.Latin1.identbodychars +nums: str = "0123456789" +hexnums: str = "0123456789ABCDEFabcdef" +alphanums: str = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789" +printables: str = ( + '!"' + "#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ" + "[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~" +) + + +class _ParseActionIndexError(Exception): + """ + Internal wrapper around IndexError so that IndexErrors raised inside + parse actions aren't misinterpreted as IndexErrors raised inside + ParserElement parseImpl methods. + """ + + def __init__(self, msg: str, exc: BaseException) -> None: + self.msg: str = msg + self.exc: BaseException = exc + + +_trim_arity_call_line: traceback.StackSummary = None # type: ignore[assignment] +pa_call_line_synth = () + + +def _trim_arity(func, max_limit=3): + """decorator to trim function calls to match the arity of the target""" + global _trim_arity_call_line, pa_call_line_synth + + if func in _single_arg_builtins: + return lambda s, l, t: func(t) + + limit = 0 + found_arity = False + + # synthesize what would be returned by traceback.extract_stack at the call to + # user's parse action 'func', so that we don't incur call penalty at parse time + + # fmt: off + LINE_DIFF = 9 + # IF ANY CODE CHANGES, EVEN JUST COMMENTS OR BLANK LINES, BETWEEN THE NEXT LINE AND + # THE CALL TO FUNC INSIDE WRAPPER, LINE_DIFF MUST BE MODIFIED!!!! + _trim_arity_call_line = _trim_arity_call_line or traceback.extract_stack(limit=2)[-1] + pa_call_line_synth = pa_call_line_synth or (_trim_arity_call_line[0], _trim_arity_call_line[1] + LINE_DIFF) + + def wrapper(*args): + nonlocal found_arity, limit + if found_arity: + return func(*args[limit:]) + while 1: + try: + ret = func(*args[limit:]) + found_arity = True + return ret + except TypeError as te: + # re-raise TypeErrors if they did not come from our arity testing + if found_arity: + raise + else: + tb = te.__traceback__ + frames = traceback.extract_tb(tb, limit=2) + frame_summary = frames[-1] + trim_arity_type_error = ( + [frame_summary[:2]][-1][:2] == pa_call_line_synth + ) + del tb + + if trim_arity_type_error: + if limit < max_limit: + limit += 1 + continue + + raise + except IndexError as ie: + # wrap IndexErrors inside a _ParseActionIndexError + raise _ParseActionIndexError( + "IndexError raised in parse action", ie + ).with_traceback(None) + # fmt: on + + # copy func name to wrapper for sensible debug output + # (can't use functools.wraps, since that messes with function signature) + func_name = getattr(func, "__name__", getattr(func, "__class__").__name__) + wrapper.__name__ = func_name + wrapper.__doc__ = func.__doc__ + + return wrapper + + +def condition_as_parse_action( + fn: ParseCondition, message: typing.Optional[str] = None, fatal: bool = False +) -> ParseAction: + """ + Function to convert a simple predicate function that returns ``True`` or ``False`` + into a parse action. Can be used in places when a parse action is required + and :meth:`ParserElement.add_condition` cannot be used (such as when adding a condition + to an operator level in :class:`infix_notation`). + + Optional keyword arguments: + + :param message: define a custom message to be used in the raised exception + :param fatal: if ``True``, will raise :class:`ParseFatalException` + to stop parsing immediately; + otherwise will raise :class:`ParseException` + + """ + msg = message if message is not None else "failed user-defined condition" + exc_type = ParseFatalException if fatal else ParseException + fn = _trim_arity(fn) + + @wraps(fn) + def pa(s, l, t): + if not bool(fn(s, l, t)): + raise exc_type(s, l, msg) + + return pa + + +def _default_start_debug_action( + instring: str, loc: int, expr: ParserElement, cache_hit: bool = False +): + cache_hit_str = "*" if cache_hit else "" + print( + ( + f"{cache_hit_str}Match {expr} at loc {loc}({lineno(loc, instring)},{col(loc, instring)})\n" + f" {line(loc, instring)}\n" + f" {'^':>{col(loc, instring)}}" + ) + ) + + +def _default_success_debug_action( + instring: str, + startloc: int, + endloc: int, + expr: ParserElement, + toks: ParseResults, + cache_hit: bool = False, +): + cache_hit_str = "*" if cache_hit else "" + print(f"{cache_hit_str}Matched {expr} -> {toks.as_list()}") + + +def _default_exception_debug_action( + instring: str, + loc: int, + expr: ParserElement, + exc: Exception, + cache_hit: bool = False, +): + cache_hit_str = "*" if cache_hit else "" + print(f"{cache_hit_str}Match {expr} failed, {type(exc).__name__} raised: {exc}") + + +def null_debug_action(*args): + """'Do-nothing' debug action, to suppress debugging output during parsing.""" + + +class ParserElement(ABC): + """Abstract base level parser element class.""" + + DEFAULT_WHITE_CHARS: str = " \n\t\r" + verbose_stacktrace: bool = False + _literalStringClass: type = None # type: ignore[assignment] + + @staticmethod + def set_default_whitespace_chars(chars: str) -> None: + r""" + Overrides the default whitespace chars + + Example: + + .. doctest:: + + # default whitespace chars are space, and newline + >>> Word(alphas)[1, ...].parse_string("abc def\nghi jkl") + ParseResults(['abc', 'def', 'ghi', 'jkl'], {}) + + # change to just treat newline as significant + >>> ParserElement.set_default_whitespace_chars(" \t") + >>> Word(alphas)[1, ...].parse_string("abc def\nghi jkl") + ParseResults(['abc', 'def'], {}) + + # Reset to default + >>> ParserElement.set_default_whitespace_chars(" \n\t\r") + """ + ParserElement.DEFAULT_WHITE_CHARS = chars + + # update whitespace all parse expressions defined in this module + for expr in _builtin_exprs: + if expr.copyDefaultWhiteChars: + expr.whiteChars = set(chars) + + @staticmethod + def inline_literals_using(cls: type) -> None: + """ + Set class to be used for inclusion of string literals into a parser. + + Example: + + .. doctest:: + :options: +NORMALIZE_WHITESPACE + + # default literal class used is Literal + >>> integer = Word(nums) + >>> date_str = ( + ... integer("year") + '/' + ... + integer("month") + '/' + ... + integer("day") + ... ) + + >>> date_str.parse_string("1999/12/31") + ParseResults(['1999', '/', '12', '/', '31'], + {'year': '1999', 'month': '12', 'day': '31'}) + + # change to Suppress + >>> ParserElement.inline_literals_using(Suppress) + >>> date_str = ( + ... integer("year") + '/' + ... + integer("month") + '/' + ... + integer("day") + ... ) + + >>> date_str.parse_string("1999/12/31") + ParseResults(['1999', '12', '31'], + {'year': '1999', 'month': '12', 'day': '31'}) + + # Reset + >>> ParserElement.inline_literals_using(Literal) + """ + ParserElement._literalStringClass = cls + + @classmethod + def using_each(cls, seq, **class_kwargs): + """ + Yields a sequence of ``class(obj, **class_kwargs)`` for obj in seq. + + Example: + + .. testcode:: + + LPAR, RPAR, LBRACE, RBRACE, SEMI = Suppress.using_each("(){};") + + .. versionadded:: 3.1.0 + """ + yield from (cls(obj, **class_kwargs) for obj in seq) + + class DebugActions(NamedTuple): + debug_try: typing.Optional[DebugStartAction] + debug_match: typing.Optional[DebugSuccessAction] + debug_fail: typing.Optional[DebugExceptionAction] + + def __init__(self, savelist: bool = False) -> None: + self.parseAction: list[ParseAction] = list() + self.failAction: typing.Optional[ParseFailAction] = None + self.customName: str = None # type: ignore[assignment] + self._defaultName: typing.Optional[str] = None + self.resultsName: str = None # type: ignore[assignment] + self.saveAsList: bool = savelist + self.skipWhitespace: bool = True + self.whiteChars: set[str] = set(ParserElement.DEFAULT_WHITE_CHARS) + self.copyDefaultWhiteChars: bool = True + # used when checking for left-recursion + self._may_return_empty: bool = False + self.keepTabs: bool = False + self.ignoreExprs: list[ParserElement] = list() + self.debug: bool = False + self.streamlined: bool = False + # optimize exception handling for subclasses that don't advance parse index + self.mayIndexError: bool = True + self.errmsg: Union[str, None] = "" + # mark results names as modal (report only last) or cumulative (list all) + self.modalResults: bool = True + # custom debug actions + self.debugActions = self.DebugActions(None, None, None) + # avoid redundant calls to preParse + self.callPreparse: bool = True + self.callDuringTry: bool = False + self.suppress_warnings_: list[Diagnostics] = [] + self.show_in_diagram: bool = True + + @property + def mayReturnEmpty(self) -> bool: + """ + .. deprecated:: 3.3.0 + use _may_return_empty instead. + """ + return self._may_return_empty + + @mayReturnEmpty.setter + def mayReturnEmpty(self, value) -> None: + """ + .. deprecated:: 3.3.0 + use _may_return_empty instead. + """ + self._may_return_empty = value + + def suppress_warning(self, warning_type: Diagnostics) -> ParserElement: + """ + Suppress warnings emitted for a particular diagnostic on this expression. + + Example: + + .. doctest:: + + >>> label = pp.Word(pp.alphas) + + # Normally using an empty Forward in a grammar + # would print a warning, but we can suppress that + >>> base = pp.Forward().suppress_warning( + ... pp.Diagnostics.warn_on_parse_using_empty_Forward) + + >>> grammar = base | label + >>> print(grammar.parse_string("x")) + ['x'] + """ + self.suppress_warnings_.append(warning_type) + return self + + def visit_all(self): + """General-purpose method to yield all expressions and sub-expressions + in a grammar. Typically just for internal use. + """ + to_visit = deque([self]) + seen = set() + while to_visit: + cur = to_visit.popleft() + + # guard against looping forever through recursive grammars + if cur in seen: + continue + seen.add(cur) + + to_visit.extend(cur.recurse()) + yield cur + + def copy(self) -> ParserElement: + """ + Make a copy of this :class:`ParserElement`. Useful for defining + different parse actions for the same parsing pattern, using copies of + the original parse element. + + Example: + + .. testcode:: + + integer = Word(nums).set_parse_action( + lambda toks: int(toks[0])) + integerK = integer.copy().add_parse_action( + lambda toks: toks[0] * 1024) + Suppress("K") + integerM = integer.copy().add_parse_action( + lambda toks: toks[0] * 1024 * 1024) + Suppress("M") + + print( + (integerK | integerM | integer)[1, ...].parse_string( + "5K 100 640K 256M") + ) + + prints: + + .. testoutput:: + + [5120, 100, 655360, 268435456] + + Equivalent form of ``expr.copy()`` is just ``expr()``: + + .. testcode:: + + integerM = integer().add_parse_action( + lambda toks: toks[0] * 1024 * 1024) + Suppress("M") + """ + cpy = copy.copy(self) + cpy.parseAction = self.parseAction[:] + cpy.ignoreExprs = self.ignoreExprs[:] + if self.copyDefaultWhiteChars: + cpy.whiteChars = set(ParserElement.DEFAULT_WHITE_CHARS) + return cpy + + def set_results_name( + self, name: str, list_all_matches: bool = False, **kwargs + ) -> ParserElement: + """ + Define name for referencing matching tokens as a nested attribute + of the returned parse results. + + Normally, results names are assigned as you would assign keys in a dict: + any existing value is overwritten by later values. If it is necessary to + keep all values captured for a particular results name, call ``set_results_name`` + with ``list_all_matches`` = True. + + NOTE: ``set_results_name`` returns a *copy* of the original :class:`ParserElement` object; + this is so that the client can define a basic element, such as an + integer, and reference it in multiple places with different names. + + You can also set results names using the abbreviated syntax, + ``expr("name")`` in place of ``expr.set_results_name("name")`` + - see :meth:`__call__`. If ``list_all_matches`` is required, use + ``expr("name*")``. + + Example: + + .. testcode:: + + integer = Word(nums) + date_str = (integer.set_results_name("year") + '/' + + integer.set_results_name("month") + '/' + + integer.set_results_name("day")) + + # equivalent form: + date_str = integer("year") + '/' + integer("month") + '/' + integer("day") + """ + listAllMatches: bool = deprecate_argument(kwargs, "listAllMatches", False) + + list_all_matches = listAllMatches or list_all_matches + return self._setResultsName(name, list_all_matches) + + def _setResultsName(self, name, list_all_matches=False) -> ParserElement: + if name is None: + return self + newself = self.copy() + if name.endswith("*"): + name = name[:-1] + list_all_matches = True + newself.resultsName = name + newself.modalResults = not list_all_matches + return newself + + def set_break(self, break_flag: bool = True) -> ParserElement: + """ + Method to invoke the Python pdb debugger when this element is + about to be parsed. Set ``break_flag`` to ``True`` to enable, ``False`` to + disable. + """ + if break_flag: + _parseMethod = self._parse + + def breaker(instring, loc, do_actions=True, callPreParse=True): + # this call to breakpoint() is intentional, not a checkin error + breakpoint() + return _parseMethod(instring, loc, do_actions, callPreParse) + + breaker._originalParseMethod = _parseMethod # type: ignore [attr-defined] + self._parse = breaker # type: ignore [method-assign] + elif hasattr(self._parse, "_originalParseMethod"): + self._parse = self._parse._originalParseMethod # type: ignore [method-assign] + return self + + def set_parse_action( + self, *fns: ParseAction, call_during_try: bool = False, **kwargs: Any + ) -> ParserElement: + """ + Define one or more actions to perform when successfully matching parse element definition. + + Parse actions can be called to perform data conversions, do extra validation, + update external data structures, or enhance or replace the parsed tokens. + Each parse action ``fn`` is a callable method with 0-3 arguments, called as + ``fn(s, loc, toks)`` , ``fn(loc, toks)`` , ``fn(toks)`` , or just ``fn()`` , where: + + - ``s`` = the original string being parsed (see note below) + - ``loc`` = the location of the matching substring + - ``toks`` = a list of the matched tokens, packaged as a :class:`ParseResults` object + + The parsed tokens are passed to the parse action as ParseResults. They can be + modified in place using list-style append, extend, and pop operations to update + the parsed list elements; and with dictionary-style item set and del operations + to add, update, or remove any named results. If the tokens are modified in place, + it is not necessary to return them with a return statement. + + Parse actions can also completely replace the given tokens, with another ``ParseResults`` + object, or with some entirely different object (common for parse actions that perform data + conversions). A convenient way to build a new parse result is to define the values + using a dict, and then create the return value using :class:`ParseResults.from_dict`. + + If None is passed as the ``fn`` parse action, all previously added parse actions for this + expression are cleared. + + Optional keyword arguments: + + :param call_during_try: (default= ``False``) indicate if parse action + should be run during lookaheads and alternate + testing. For parse actions that have side + effects, it is important to only call the parse + action once it is determined that it is being + called as part of a successful parse. + For parse actions that perform additional + validation, then ``call_during_try`` should + be passed as True, so that the validation code + is included in the preliminary "try" parses. + + .. Note:: + The default parsing behavior is to expand tabs in the input string + before starting the parsing process. + See :meth:`parse_string` for more information on parsing strings + containing ```` s, and suggested methods to maintain a + consistent view of the parsed string, the parse location, and + line and column positions within the parsed string. + + Example: Parse dates in the form ``YYYY/MM/DD`` + ----------------------------------------------- + + Setup code: + + .. testcode:: + + def convert_to_int(toks): + '''a parse action to convert toks from str to int + at parse time''' + return int(toks[0]) + + def is_valid_date(instring, loc, toks): + '''a parse action to verify that the date is a valid date''' + from datetime import date + year, month, day = toks[::2] + try: + date(year, month, day) + except ValueError: + raise ParseException(instring, loc, "invalid date given") + + integer = Word(nums) + date_str = integer + '/' + integer + '/' + integer + + # add parse actions + integer.set_parse_action(convert_to_int) + date_str.set_parse_action(is_valid_date) + + Successful parse - note that integer fields are converted to ints: + + .. testcode:: + + print(date_str.parse_string("1999/12/31")) + + prints: + + .. testoutput:: + + [1999, '/', 12, '/', 31] + + Failure - invalid date: + + .. testcode:: + + date_str.parse_string("1999/13/31") + + prints: + + .. testoutput:: + + Traceback (most recent call last): + ParseException: invalid date given, found '1999' ... + """ + callDuringTry: bool = deprecate_argument(kwargs, "callDuringTry", False) + + if list(fns) == [None]: + self.parseAction.clear() + return self + + if not all(callable(fn) for fn in fns): + raise TypeError("parse actions must be callable") + self.parseAction[:] = [_trim_arity(fn) for fn in fns] + self.callDuringTry = self.callDuringTry or call_during_try or callDuringTry + + return self + + def add_parse_action( + self, *fns: ParseAction, call_during_try: bool = False, **kwargs: Any + ) -> ParserElement: + """ + Add one or more parse actions to expression's list of parse actions. See :class:`set_parse_action`. + + See examples in :class:`copy`. + """ + callDuringTry: bool = deprecate_argument(kwargs, "callDuringTry", False) + + self.parseAction += [_trim_arity(fn) for fn in fns] + self.callDuringTry = self.callDuringTry or callDuringTry or call_during_try + return self + + def add_condition( + self, *fns: ParseCondition, call_during_try: bool = False, **kwargs: Any + ) -> ParserElement: + """Add a boolean predicate function to expression's list of parse actions. See + :class:`set_parse_action` for function call signatures. Unlike ``set_parse_action``, + functions passed to ``add_condition`` need to return boolean success/fail of the condition. + + Optional keyword arguments: + + - ``message`` = define a custom message to be used in the raised exception + - ``fatal`` = if True, will raise ParseFatalException to stop parsing immediately; otherwise will raise + ParseException + - ``call_during_try`` = boolean to indicate if this method should be called during internal tryParse calls, + default=False + + Example: + + .. doctest:: + :options: +NORMALIZE_WHITESPACE + + >>> integer = Word(nums).set_parse_action(lambda toks: int(toks[0])) + >>> year_int = integer.copy().add_condition( + ... lambda toks: toks[0] >= 2000, + ... message="Only support years 2000 and later") + >>> date_str = year_int + '/' + integer + '/' + integer + + >>> result = date_str.parse_string("1999/12/31") + Traceback (most recent call last): + ParseException: Only support years 2000 and later... + """ + callDuringTry: bool = deprecate_argument(kwargs, "callDuringTry", False) + + for fn in fns: + self.parseAction.append( + condition_as_parse_action( + fn, + message=str(kwargs.get("message")), + fatal=bool(kwargs.get("fatal", False)), + ) + ) + + self.callDuringTry = self.callDuringTry or call_during_try or callDuringTry + return self + + def set_fail_action(self, fn: ParseFailAction) -> ParserElement: + """ + Define action to perform if parsing fails at this expression. + Fail acton fn is a callable function that takes the arguments + ``fn(s, loc, expr, err)`` where: + + - ``s`` = string being parsed + - ``loc`` = location where expression match was attempted and failed + - ``expr`` = the parse expression that failed + - ``err`` = the exception thrown + + The function returns no value. It may throw :class:`ParseFatalException` + if it is desired to stop parsing immediately.""" + self.failAction = fn + return self + + def _skipIgnorables(self, instring: str, loc: int) -> int: + if not self.ignoreExprs: + return loc + exprsFound = True + ignore_expr_fns = [e._parse for e in self.ignoreExprs] + last_loc = loc + while exprsFound: + exprsFound = False + for ignore_fn in ignore_expr_fns: + try: + while 1: + loc, dummy = ignore_fn(instring, loc) + exprsFound = True + except ParseException: + pass + # check if all ignore exprs matched but didn't actually advance the parse location + if loc == last_loc: + break + last_loc = loc + return loc + + def preParse(self, instring: str, loc: int) -> int: + if self.ignoreExprs: + loc = self._skipIgnorables(instring, loc) + + if self.skipWhitespace: + instrlen = len(instring) + white_chars = self.whiteChars + while loc < instrlen and instring[loc] in white_chars: + loc += 1 + + return loc + + def parseImpl(self, instring, loc, do_actions=True) -> ParseImplReturnType: + return loc, [] + + def postParse(self, instring, loc, tokenlist): + return tokenlist + + # @profile + def _parseNoCache( + self, instring, loc, do_actions=True, callPreParse=True + ) -> tuple[int, ParseResults]: + debugging = self.debug # and do_actions) + len_instring = len(instring) + + if debugging or self.failAction: + # print("Match {} at loc {}({}, {})".format(self, loc, lineno(loc, instring), col(loc, instring))) + try: + if callPreParse and self.callPreparse: + pre_loc = self.preParse(instring, loc) + else: + pre_loc = loc + tokens_start = pre_loc + if self.debugActions.debug_try: + self.debugActions.debug_try(instring, tokens_start, self, False) + if self.mayIndexError or pre_loc >= len_instring: + try: + loc, tokens = self.parseImpl(instring, pre_loc, do_actions) + except IndexError: + raise ParseException(instring, len_instring, self.errmsg, self) + else: + loc, tokens = self.parseImpl(instring, pre_loc, do_actions) + except Exception as err: + # print("Exception raised:", err) + if self.debugActions.debug_fail: + self.debugActions.debug_fail( + instring, tokens_start, self, err, False + ) + if self.failAction: + self.failAction(instring, tokens_start, self, err) + raise + else: + if callPreParse and self.callPreparse: + pre_loc = self.preParse(instring, loc) + else: + pre_loc = loc + tokens_start = pre_loc + if self.mayIndexError or pre_loc >= len_instring: + try: + loc, tokens = self.parseImpl(instring, pre_loc, do_actions) + except IndexError: + raise ParseException(instring, len_instring, self.errmsg, self) + else: + loc, tokens = self.parseImpl(instring, pre_loc, do_actions) + + tokens = self.postParse(instring, loc, tokens) + + ret_tokens = ParseResults( + tokens, self.resultsName, aslist=self.saveAsList, modal=self.modalResults + ) + if self.parseAction and (do_actions or self.callDuringTry): + if debugging: + try: + for fn in self.parseAction: + try: + tokens = fn(instring, tokens_start, ret_tokens) # type: ignore [call-arg, arg-type] + except IndexError as parse_action_exc: + exc = ParseException("exception raised in parse action") + raise exc from parse_action_exc + + if tokens is not None and tokens is not ret_tokens: + ret_tokens = ParseResults( + tokens, + self.resultsName, + aslist=self.saveAsList + and isinstance(tokens, (ParseResults, list)), + modal=self.modalResults, + ) + except Exception as err: + # print "Exception raised in user parse action:", err + if self.debugActions.debug_fail: + self.debugActions.debug_fail( + instring, tokens_start, self, err, False + ) + raise + else: + for fn in self.parseAction: + try: + tokens = fn(instring, tokens_start, ret_tokens) # type: ignore [call-arg, arg-type] + except IndexError as parse_action_exc: + exc = ParseException("exception raised in parse action") + raise exc from parse_action_exc + + if tokens is not None and tokens is not ret_tokens: + ret_tokens = ParseResults( + tokens, + self.resultsName, + aslist=self.saveAsList + and isinstance(tokens, (ParseResults, list)), + modal=self.modalResults, + ) + if debugging: + # print("Matched", self, "->", ret_tokens.as_list()) + if self.debugActions.debug_match: + self.debugActions.debug_match( + instring, tokens_start, loc, self, ret_tokens, False + ) + + return loc, ret_tokens + + def try_parse( + self, + instring: str, + loc: int, + *, + raise_fatal: bool = False, + do_actions: bool = False, + ) -> int: + try: + return self._parse(instring, loc, do_actions=do_actions)[0] + except ParseFatalException: + if raise_fatal: + raise + raise ParseException(instring, loc, self.errmsg, self) + + def can_parse_next(self, instring: str, loc: int, do_actions: bool = False) -> bool: + try: + self.try_parse(instring, loc, do_actions=do_actions) + except (ParseException, IndexError): + return False + else: + return True + + # cache for left-recursion in Forward references + recursion_lock = RLock() + recursion_memos: collections.abc.MutableMapping[ + tuple[int, Forward, bool], tuple[int, Union[ParseResults, Exception]] + ] = {} + + class _CacheType(typing.Protocol): + """ + Class to be used for packrat and left-recursion cacheing of results + and exceptions. + """ + + not_in_cache: bool + + def get(self, *args) -> typing.Any: ... + + def set(self, *args) -> None: ... + + def clear(self) -> None: ... + + class NullCache(dict): + """ + A null cache type for initialization of the packrat_cache class variable. + If/when enable_packrat() is called, this null cache will be replaced by a + proper _CacheType class instance. + """ + + not_in_cache: bool = True + + def get(self, *args) -> typing.Any: ... + + def set(self, *args) -> None: ... + + def clear(self) -> None: ... + + # class-level argument cache for optimizing repeated calls when backtracking + # through recursive expressions + packrat_cache: _CacheType = NullCache() + packrat_cache_lock = RLock() + packrat_cache_stats = [0, 0] + + # this method gets repeatedly called during backtracking with the same arguments - + # we can cache these arguments and save ourselves the trouble of re-parsing the contained expression + def _parseCache( + self, instring, loc, do_actions=True, callPreParse=True + ) -> tuple[int, ParseResults]: + HIT, MISS = 0, 1 + lookup = (self, instring, loc, callPreParse, do_actions) + with ParserElement.packrat_cache_lock: + cache = ParserElement.packrat_cache + value = cache.get(lookup) + if value is cache.not_in_cache: + ParserElement.packrat_cache_stats[MISS] += 1 + try: + value = self._parseNoCache(instring, loc, do_actions, callPreParse) + except ParseBaseException as pe: + # cache a copy of the exception, without the traceback + cache.set(lookup, pe.__class__(*pe.args)) + raise + else: + cache.set(lookup, (value[0], value[1].copy(), loc)) + return value + else: + ParserElement.packrat_cache_stats[HIT] += 1 + if self.debug and self.debugActions.debug_try: + try: + self.debugActions.debug_try(instring, loc, self, cache_hit=True) # type: ignore [call-arg] + except TypeError: + pass + if isinstance(value, Exception): + if self.debug and self.debugActions.debug_fail: + try: + self.debugActions.debug_fail( + instring, loc, self, value, cache_hit=True # type: ignore [call-arg] + ) + except TypeError: + pass + raise value + + value = cast(tuple[int, ParseResults, int], value) + loc_, result, endloc = value[0], value[1].copy(), value[2] + if self.debug and self.debugActions.debug_match: + try: + self.debugActions.debug_match( + instring, loc_, endloc, self, result, cache_hit=True # type: ignore [call-arg] + ) + except TypeError: + pass + + return loc_, result + + _parse = _parseNoCache + + @staticmethod + def reset_cache() -> None: + """ + Clears caches used by packrat and left-recursion. + """ + with ParserElement.packrat_cache_lock: + ParserElement.packrat_cache.clear() + ParserElement.packrat_cache_stats[:] = [0] * len( + ParserElement.packrat_cache_stats + ) + ParserElement.recursion_memos.clear() + + # class attributes to keep caching status + _packratEnabled = False + _left_recursion_enabled = False + + @staticmethod + def disable_memoization() -> None: + """ + Disables active Packrat or Left Recursion parsing and their memoization + + This method also works if neither Packrat nor Left Recursion are enabled. + This makes it safe to call before activating Packrat nor Left Recursion + to clear any previous settings. + """ + with ParserElement.packrat_cache_lock: + ParserElement.reset_cache() + ParserElement._left_recursion_enabled = False + ParserElement._packratEnabled = False + ParserElement._parse = ParserElement._parseNoCache + + @staticmethod + def enable_left_recursion( + cache_size_limit: typing.Optional[int] = None, *, force=False + ) -> None: + """ + Enables "bounded recursion" parsing, which allows for both direct and indirect + left-recursion. During parsing, left-recursive :class:`Forward` elements are + repeatedly matched with a fixed recursion depth that is gradually increased + until finding the longest match. + + Example: + + .. testcode:: + + import pyparsing as pp + pp.ParserElement.enable_left_recursion() + + E = pp.Forward("E") + num = pp.Word(pp.nums) + + # match `num`, or `num '+' num`, or `num '+' num '+' num`, ... + E <<= E + '+' - num | num + + print(E.parse_string("1+2+3+4")) + + prints: + + .. testoutput:: + + ['1', '+', '2', '+', '3', '+', '4'] + + Recursion search naturally memoizes matches of ``Forward`` elements and may + thus skip reevaluation of parse actions during backtracking. This may break + programs with parse actions which rely on strict ordering of side-effects. + + Parameters: + + - ``cache_size_limit`` - (default=``None``) - memoize at most this many + ``Forward`` elements during matching; if ``None`` (the default), + memoize all ``Forward`` elements. + + Bounded Recursion parsing works similar but not identical to Packrat parsing, + thus the two cannot be used together. Use ``force=True`` to disable any + previous, conflicting settings. + """ + with ParserElement.packrat_cache_lock: + if force: + ParserElement.disable_memoization() + elif ParserElement._packratEnabled: + raise RuntimeError("Packrat and Bounded Recursion are not compatible") + if cache_size_limit is None: + ParserElement.recursion_memos = _UnboundedMemo() + elif cache_size_limit > 0: + ParserElement.recursion_memos = _LRUMemo(capacity=cache_size_limit) # type: ignore[assignment] + else: + raise NotImplementedError(f"Memo size of {cache_size_limit}") + ParserElement._left_recursion_enabled = True + + @staticmethod + def enable_packrat( + cache_size_limit: Union[int, None] = 128, *, force: bool = False + ) -> None: + """ + Enables "packrat" parsing, which adds memoizing to the parsing logic. + Repeated parse attempts at the same string location (which happens + often in many complex grammars) can immediately return a cached value, + instead of re-executing parsing/validating code. Memoizing is done of + both valid results and parsing exceptions. + + Parameters: + + - ``cache_size_limit`` - (default= ``128``) - if an integer value is provided + will limit the size of the packrat cache; if None is passed, then + the cache size will be unbounded; if 0 is passed, the cache will + be effectively disabled. + + This speedup may break existing programs that use parse actions that + have side-effects. For this reason, packrat parsing is disabled when + you first import pyparsing. To activate the packrat feature, your + program must call the class method :class:`ParserElement.enable_packrat`. + For best results, call ``enable_packrat()`` immediately after + importing pyparsing. + + .. Can't really be doctested, alas + + Example:: + + import pyparsing + pyparsing.ParserElement.enable_packrat() + + Packrat parsing works similar but not identical to Bounded Recursion parsing, + thus the two cannot be used together. Use ``force=True`` to disable any + previous, conflicting settings. + """ + with ParserElement.packrat_cache_lock: + if force: + ParserElement.disable_memoization() + elif ParserElement._left_recursion_enabled: + raise RuntimeError("Packrat and Bounded Recursion are not compatible") + + if ParserElement._packratEnabled: + return + + ParserElement._packratEnabled = True + if cache_size_limit is None: + ParserElement.packrat_cache = _UnboundedCache() + else: + ParserElement.packrat_cache = _FifoCache(cache_size_limit) + ParserElement._parse = ParserElement._parseCache + + def parse_string( + self, instring: str, parse_all: bool = False, **kwargs + ) -> ParseResults: + """ + Parse a string with respect to the parser definition. This function is intended as the primary interface to the + client code. + + :param instring: The input string to be parsed. + :param parse_all: If set, the entire input string must match the grammar. + :param parseAll: retained for pre-PEP8 compatibility, will be removed in a future release. + :raises ParseException: Raised if ``parse_all`` is set and the input string does not match the whole grammar. + :returns: the parsed data as a :class:`ParseResults` object, which may be accessed as a `list`, a `dict`, or + an object with attributes if the given parser includes results names. + + If the input string is required to match the entire grammar, ``parse_all`` flag must be set to ``True``. This + is also equivalent to ending the grammar with :class:`StringEnd`\\ (). + + To report proper column numbers, ``parse_string`` operates on a copy of the input string where all tabs are + converted to spaces (8 spaces per tab, as per the default in ``string.expandtabs``). If the input string + contains tabs and the grammar uses parse actions that use the ``loc`` argument to index into the string + being parsed, one can ensure a consistent view of the input string by doing one of the following: + + - calling ``parse_with_tabs`` on your grammar before calling ``parse_string`` (see :class:`parse_with_tabs`), + - define your parse action using the full ``(s,loc,toks)`` signature, and reference the input string using the + parse action's ``s`` argument, or + - explicitly expand the tabs in your input string before calling ``parse_string``. + + Examples: + + By default, partial matches are OK. + + .. doctest:: + + >>> res = Word('a').parse_string('aaaaabaaa') + >>> print(res) + ['aaaaa'] + + The parsing behavior varies by the inheriting class of this abstract class. Please refer to the children + directly to see more examples. + + It raises an exception if parse_all flag is set and instring does not match the whole grammar. + + .. doctest:: + + >>> res = Word('a').parse_string('aaaaabaaa', parse_all=True) + Traceback (most recent call last): + ParseException: Expected end of text, found 'b' ... + """ + parseAll: bool = deprecate_argument(kwargs, "parseAll", False) + + parse_all = parse_all or parseAll + + ParserElement.reset_cache() + if not self.streamlined: + self.streamline() + for e in self.ignoreExprs: + e.streamline() + if not self.keepTabs: + instring = instring.expandtabs() + try: + loc, tokens = self._parse(instring, 0) + if parse_all: + loc = self.preParse(instring, loc) + se = Empty() + StringEnd().set_debug(False) + se._parse(instring, loc) + except _ParseActionIndexError as pa_exc: + raise pa_exc.exc + except ParseBaseException as exc: + if ParserElement.verbose_stacktrace: + raise + + # catch and re-raise exception from here, clearing out pyparsing internal stack trace + raise exc.with_traceback(None) + else: + return tokens + + def scan_string( + self, + instring: str, + max_matches: int = _MAX_INT, + overlap: bool = False, + always_skip_whitespace=True, + *, + debug: bool = False, + **kwargs, + ) -> Generator[tuple[ParseResults, int, int], None, None]: + """ + Scan the input string for expression matches. Each match will return the + matching tokens, start location, and end location. May be called with optional + ``max_matches`` argument, to clip scanning after 'n' matches are found. If + ``overlap`` is specified, then overlapping matches will be reported. + + Note that the start and end locations are reported relative to the string + being parsed. See :class:`parse_string` for more information on parsing + strings with embedded tabs. + + Example: + + .. testcode:: + + source = "sldjf123lsdjjkf345sldkjf879lkjsfd987" + print(source) + for tokens, start, end in Word(alphas).scan_string(source): + print(' '*start + '^'*(end-start)) + print(' '*start + tokens[0]) + + prints: + + .. testoutput:: + + sldjf123lsdjjkf345sldkjf879lkjsfd987 + ^^^^^ + sldjf + ^^^^^^^ + lsdjjkf + ^^^^^^ + sldkjf + ^^^^^^ + lkjsfd + """ + maxMatches: int = deprecate_argument(kwargs, "maxMatches", _MAX_INT) + + max_matches = min(maxMatches, max_matches) + if not self.streamlined: + self.streamline() + for e in self.ignoreExprs: + e.streamline() + + if not self.keepTabs: + instring = str(instring).expandtabs() + instrlen = len(instring) + loc = 0 + if always_skip_whitespace: + preparser = Empty() + preparser.ignoreExprs = self.ignoreExprs + preparser.whiteChars = self.whiteChars + preparseFn = preparser.preParse + else: + preparseFn = self.preParse + parseFn = self._parse + ParserElement.reset_cache() + matches = 0 + try: + while loc <= instrlen and matches < max_matches: + try: + preloc: int = preparseFn(instring, loc) + nextLoc: int + tokens: ParseResults + nextLoc, tokens = parseFn(instring, preloc, callPreParse=False) + except ParseException: + loc = preloc + 1 + else: + if nextLoc > loc: + matches += 1 + if debug: + print( + { + "tokens": tokens.as_list(), + "start": preloc, + "end": nextLoc, + } + ) + yield tokens, preloc, nextLoc + if overlap: + nextloc = preparseFn(instring, loc) + if nextloc > loc: + loc = nextLoc + else: + loc += 1 + else: + loc = nextLoc + else: + loc = preloc + 1 + except ParseBaseException as exc: + if ParserElement.verbose_stacktrace: + raise + + # catch and re-raise exception from here, clears out pyparsing internal stack trace + raise exc.with_traceback(None) + + def transform_string(self, instring: str, *, debug: bool = False) -> str: + """ + Extension to :class:`scan_string`, to modify matching text with modified tokens that may + be returned from a parse action. To use ``transform_string``, define a grammar and + attach a parse action to it that modifies the returned token list. + Invoking ``transform_string()`` on a target string will then scan for matches, + and replace the matched text patterns according to the logic in the parse + action. ``transform_string()`` returns the resulting transformed string. + + Example: + + .. testcode:: + + quote = '''now is the winter of our discontent, + made glorious summer by this sun of york.''' + + wd = Word(alphas) + wd.set_parse_action(lambda toks: toks[0].title()) + + print(wd.transform_string(quote)) + + prints: + + .. testoutput:: + + Now Is The Winter Of Our Discontent, + Made Glorious Summer By This Sun Of York. + """ + out: list[str] = [] + lastE = 0 + # force preservation of s, to minimize unwanted transformation of string, and to + # keep string locs straight between transform_string and scan_string + self.keepTabs = True + try: + for t, s, e in self.scan_string(instring, debug=debug): + if s > lastE: + out.append(instring[lastE:s]) + lastE = e + + if not t: + continue + + if isinstance(t, ParseResults): + out += t.as_list() + elif isinstance(t, Iterable) and not isinstance(t, str_type): + out.extend(t) + else: + out.append(t) + + out.append(instring[lastE:]) + out = [o for o in out if o] + return "".join([str(s) for s in _flatten(out)]) + except ParseBaseException as exc: + if ParserElement.verbose_stacktrace: + raise + + # catch and re-raise exception from here, clears out pyparsing internal stack trace + raise exc.with_traceback(None) + + def search_string( + self, + instring: str, + max_matches: int = _MAX_INT, + *, + debug: bool = False, + **kwargs, + ) -> ParseResults: + """ + Another extension to :class:`scan_string`, simplifying the access to the tokens found + to match the given parse expression. May be called with optional + ``max_matches`` argument, to clip searching after 'n' matches are found. + + Example: + + .. testcode:: + + quote = '''More than Iron, more than Lead, + more than Gold I need Electricity''' + + # a capitalized word starts with an uppercase letter, + # followed by zero or more lowercase letters + cap_word = Word(alphas.upper(), alphas.lower()) + + print(cap_word.search_string(quote)) + + # the sum() builtin can be used to merge results + # into a single ParseResults object + print(sum(cap_word.search_string(quote))) + + prints: + + .. testoutput:: + + [['More'], ['Iron'], ['Lead'], ['Gold'], ['I'], ['Electricity']] + ['More', 'Iron', 'Lead', 'Gold', 'I', 'Electricity'] + """ + maxMatches: int = deprecate_argument(kwargs, "maxMatches", _MAX_INT) + + max_matches = min(maxMatches, max_matches) + try: + return ParseResults( + [ + t + for t, s, e in self.scan_string( + instring, + max_matches=max_matches, + always_skip_whitespace=False, + debug=debug, + ) + ] + ) + except ParseBaseException as exc: + if ParserElement.verbose_stacktrace: + raise + + # catch and re-raise exception from here, clears out pyparsing internal stack trace + raise exc.with_traceback(None) + + def split( + self, + instring: str, + maxsplit: int = _MAX_INT, + include_separators: bool = False, + **kwargs, + ) -> Generator[str, None, None]: + """ + Generator method to split a string using the given expression as a separator. + May be called with optional ``maxsplit`` argument, to limit the number of splits; + and the optional ``include_separators`` argument (default= ``False``), if the separating + matching text should be included in the split results. + + Example: + + .. testcode:: + + punc = one_of(list(".,;:/-!?")) + print(list(punc.split( + "This, this?, this sentence, is badly punctuated!"))) + + prints: + + .. testoutput:: + + ['This', ' this', '', ' this sentence', ' is badly punctuated', ''] + """ + includeSeparators: bool = deprecate_argument(kwargs, "includeSeparators", False) + + include_separators = includeSeparators or include_separators + last = 0 + for t, s, e in self.scan_string(instring, max_matches=maxsplit): + yield instring[last:s] + if include_separators: + yield t[0] + last = e + yield instring[last:] + + def __add__(self, other) -> ParserElement: + """ + Implementation of ``+`` operator - returns :class:`And`. Adding strings to a :class:`ParserElement` + converts them to :class:`Literal`\\ s by default. + + Example: + + .. testcode:: + + greet = Word(alphas) + "," + Word(alphas) + "!" + hello = "Hello, World!" + print(hello, "->", greet.parse_string(hello)) + + prints: + + .. testoutput:: + + Hello, World! -> ['Hello', ',', 'World', '!'] + + ``...`` may be used as a parse expression as a short form of :class:`SkipTo`: + + .. testcode:: + + Literal('start') + ... + Literal('end') + + is equivalent to: + + .. testcode:: + + Literal('start') + SkipTo('end')("_skipped*") + Literal('end') + + Note that the skipped text is returned with '_skipped' as a results name, + and to support having multiple skips in the same parser, the value returned is + a list of all skipped text. + """ + if other is Ellipsis: + return _PendingSkip(self) + + if isinstance(other, str_type): + other = self._literalStringClass(other) + if not isinstance(other, ParserElement): + return NotImplemented + return And([self, other]) + + def __radd__(self, other) -> ParserElement: + """ + Implementation of ``+`` operator when left operand is not a :class:`ParserElement` + """ + if other is Ellipsis: + return SkipTo(self)("_skipped*") + self + + if isinstance(other, str_type): + other = self._literalStringClass(other) + if not isinstance(other, ParserElement): + return NotImplemented + return other + self + + def __sub__(self, other) -> ParserElement: + """ + Implementation of ``-`` operator, returns :class:`And` with error stop + """ + if isinstance(other, str_type): + other = self._literalStringClass(other) + if not isinstance(other, ParserElement): + return NotImplemented + return self + And._ErrorStop() + other + + def __rsub__(self, other) -> ParserElement: + """ + Implementation of ``-`` operator when left operand is not a :class:`ParserElement` + """ + if isinstance(other, str_type): + other = self._literalStringClass(other) + if not isinstance(other, ParserElement): + return NotImplemented + return other - self + + def __mul__(self, other) -> ParserElement: + """ + Implementation of ``*`` operator, allows use of ``expr * 3`` in place of + ``expr + expr + expr``. Expressions may also be multiplied by a 2-integer + tuple, similar to ``{min, max}`` multipliers in regular expressions. Tuples + may also include ``None`` as in: + + - ``expr*(n, None)`` or ``expr*(n, )`` is equivalent + to ``expr*n + ZeroOrMore(expr)`` + (read as "at least n instances of ``expr``") + - ``expr*(None, n)`` is equivalent to ``expr*(0, n)`` + (read as "0 to n instances of ``expr``") + - ``expr*(None, None)`` is equivalent to ``ZeroOrMore(expr)`` + - ``expr*(1, None)`` is equivalent to ``OneOrMore(expr)`` + + Note that ``expr*(None, n)`` does not raise an exception if + more than n exprs exist in the input stream; that is, + ``expr*(None, n)`` does not enforce a maximum number of expr + occurrences. If this behavior is desired, then write + ``expr*(None, n) + ~expr`` + """ + if other is Ellipsis: + other = (0, None) + elif isinstance(other, tuple) and other[:1] == (Ellipsis,): + other = ((0,) + other[1:] + (None,))[:2] + + if not isinstance(other, (int, tuple)): + return NotImplemented + + if isinstance(other, int): + minElements, optElements = other, 0 + else: + other = tuple(o if o is not Ellipsis else None for o in other) + other = (other + (None, None))[:2] + if other[0] is None: + other = (0, other[1]) + if isinstance(other[0], int) and other[1] is None: + if other[0] == 0: + return ZeroOrMore(self) + if other[0] == 1: + return OneOrMore(self) + else: + return self * other[0] + ZeroOrMore(self) + elif isinstance(other[0], int) and isinstance(other[1], int): + minElements, optElements = other + optElements -= minElements + else: + return NotImplemented + + if minElements < 0: + raise ValueError("cannot multiply ParserElement by negative value") + if optElements < 0: + raise ValueError( + "second tuple value must be greater or equal to first tuple value" + ) + if minElements == optElements == 0: + return And([]) + + if optElements: + # Build the optional tail as a bounded ``ZeroOrMore`` instead of a + # deeply nested ``Opt(self + Opt(self + ...))`` chain. The nested + # form recursed ``optElements`` levels deep, which raised + # RecursionError for large upper bounds (e.g. ``expr[..., 1000]``) + # -- see issue #332. ``ZeroOrMore(..., max=optElements)`` is a flat + # loop that still *exits early* (it stops at the first non-match, + # just like the recursive form), so it preserves the original + # early-exit behavior while no longer scaling the call stack with + # the upper bound. + optionalTail = ZeroOrMore(self, max=optElements) + + if minElements: + if minElements == 1: + ret = self + optionalTail + else: + ret = And([self] * minElements) + optionalTail + else: + ret = optionalTail + else: + if minElements == 1: + ret = self + else: + ret = And([self] * minElements) + return ret + + def __rmul__(self, other) -> ParserElement: + return self.__mul__(other) + + def __or__(self, other) -> ParserElement: + """ + Implementation of ``|`` operator - returns :class:`MatchFirst` + + .. versionchanged:: 3.1.0 + Support ``expr | ""`` as a synonym for ``Optional(expr)``. + """ + if other is Ellipsis: + return _PendingSkip(self, must_skip=True) + + if isinstance(other, str_type): + # `expr | ""` is equivalent to `Opt(expr)` + if other == "": + return Opt(self) + other = self._literalStringClass(other) + if not isinstance(other, ParserElement): + return NotImplemented + return MatchFirst([self, other]) + + def __ror__(self, other) -> ParserElement: + """ + Implementation of ``|`` operator when left operand is not a :class:`ParserElement` + """ + if isinstance(other, str_type): + other = self._literalStringClass(other) + if not isinstance(other, ParserElement): + return NotImplemented + return other | self + + def __xor__(self, other) -> ParserElement: + """ + Implementation of ``^`` operator - returns :class:`Or` + """ + if isinstance(other, str_type): + other = self._literalStringClass(other) + if not isinstance(other, ParserElement): + return NotImplemented + return Or([self, other]) + + def __rxor__(self, other) -> ParserElement: + """ + Implementation of ``^`` operator when left operand is not a :class:`ParserElement` + """ + if isinstance(other, str_type): + other = self._literalStringClass(other) + if not isinstance(other, ParserElement): + return NotImplemented + return other ^ self + + def __and__(self, other) -> ParserElement: + """ + Implementation of ``&`` operator - returns :class:`Each` + """ + if isinstance(other, str_type): + other = self._literalStringClass(other) + if not isinstance(other, ParserElement): + return NotImplemented + return Each([self, other]) + + def __rand__(self, other) -> ParserElement: + """ + Implementation of ``&`` operator when left operand is not a :class:`ParserElement` + """ + if isinstance(other, str_type): + other = self._literalStringClass(other) + if not isinstance(other, ParserElement): + return NotImplemented + return other & self + + def __invert__(self) -> ParserElement: + """ + Implementation of ``~`` operator - returns :class:`NotAny` + """ + return NotAny(self) + + # disable __iter__ to override legacy use of sequential access to __getitem__ to + # iterate over a sequence + __iter__ = None + + def __getitem__(self, key): + """ + use ``[]`` indexing notation as a short form for expression repetition: + + - ``expr[n]`` is equivalent to ``expr*n`` + - ``expr[m, n]`` is equivalent to ``expr*(m, n)`` + - ``expr[n, ...]`` or ``expr[n,]`` is equivalent + to ``expr*n + ZeroOrMore(expr)`` + (read as "at least n instances of ``expr``") + - ``expr[..., n]`` is equivalent to ``expr*(0, n)`` + (read as "0 to n instances of ``expr``") + - ``expr[...]`` and ``expr[0, ...]`` are equivalent to ``ZeroOrMore(expr)`` + - ``expr[1, ...]`` is equivalent to ``OneOrMore(expr)`` + + ``None`` may be used in place of ``...``. + + Note that ``expr[..., n]`` and ``expr[m, n]`` do not raise an exception + if more than ``n`` ``expr``\\ s exist in the input stream. If this behavior is + desired, then write ``expr[..., n] + ~expr``. + + For repetition with a stop_on expression, use slice notation: + + - ``expr[...: end_expr]`` and ``expr[0, ...: end_expr]`` are equivalent to ``ZeroOrMore(expr, stop_on=end_expr)`` + - ``expr[1, ...: end_expr]`` is equivalent to ``OneOrMore(expr, stop_on=end_expr)`` + + .. versionchanged:: 3.1.0 + Support for slice notation. + """ + + stop_on_defined = False + stop_on = NoMatch() + if isinstance(key, slice): + key, stop_on = key.start, key.stop + if key is None: + key = ... + stop_on_defined = True + elif isinstance(key, tuple) and isinstance(key[-1], slice): + key, stop_on = (key[0], key[1].start), key[1].stop + stop_on_defined = True + + # convert single arg keys to tuples + if isinstance(key, str_type): + key = (key,) + try: + iter(key) + except TypeError: + key = (key, key) + + if len(key) > 2: + raise TypeError( + f"only 1 or 2 index arguments supported ({key[:5]}{f'... [{len(key)}]' if len(key) > 5 else ''})" + ) + + # clip to 2 elements + ret = self * tuple(key[:2]) + ret = typing.cast(_MultipleMatch, ret) + + if stop_on_defined: + ret.stopOn(stop_on) + + return ret + + def __call__(self, name: typing.Optional[str] = None) -> ParserElement: + """ + Shortcut for :class:`set_results_name`, with ``list_all_matches=False``. + + If ``name`` is given with a trailing ``'*'`` character, then ``list_all_matches`` will be + passed as ``True``. + + If ``name`` is omitted, same as calling :class:`copy`. + + Example: + + .. testcode:: + + # these are equivalent + userdata = ( + Word(alphas).set_results_name("name") + + Word(nums + "-").set_results_name("socsecno") + ) + + userdata = Word(alphas)("name") + Word(nums + "-")("socsecno") + """ + if name is not None: + return self._setResultsName(name) + + return self.copy() + + def suppress(self) -> ParserElement: + """ + Suppresses the output of this :class:`ParserElement`; useful to keep punctuation from + cluttering up returned output. + """ + return Suppress(self) + + def ignore_whitespace(self, recursive: bool = True) -> ParserElement: + """ + Enables the skipping of whitespace before matching the characters in the + :class:`ParserElement`'s defined pattern. + + :param recursive: If ``True`` (the default), also enable whitespace skipping in child elements (if any) + """ + self.skipWhitespace = True + return self + + def leave_whitespace(self, recursive: bool = True) -> ParserElement: + """ + Disables the skipping of whitespace before matching the characters in the + :class:`ParserElement`'s defined pattern. This is normally only used internally by + the pyparsing module, but may be needed in some whitespace-sensitive grammars. + + :param recursive: If true (the default), also disable whitespace skipping in child elements (if any) + """ + self.skipWhitespace = False + return self + + def set_whitespace_chars( + self, chars: Union[set[str], str], copy_defaults: bool = False + ) -> ParserElement: + """ + Overrides the default whitespace chars + """ + self.skipWhitespace = True + self.whiteChars = set(chars) + self.copyDefaultWhiteChars = copy_defaults + return self + + def parse_with_tabs(self) -> ParserElement: + """ + Overrides default behavior to expand ```` s to spaces before parsing the input string. + Must be called before ``parse_string`` when the input grammar contains elements that + match ```` characters. + """ + self.keepTabs = True + return self + + def ignore(self, other: ParserElement) -> ParserElement: + """ + Define expression to be ignored (e.g., comments) while doing pattern + matching; may be called repeatedly, to define multiple comment or other + ignorable patterns. + + Example: + + .. doctest:: + + >>> patt = Word(alphas)[...] + >>> print(patt.parse_string('ablaj /* comment */ lskjd')) + ['ablaj'] + + >>> patt = Word(alphas)[...].ignore(c_style_comment) + >>> print(patt.parse_string('ablaj /* comment */ lskjd')) + ['ablaj', 'lskjd'] + """ + if isinstance(other, str_type): + other = Suppress(other) + + if isinstance(other, Suppress): + if other not in self.ignoreExprs: + self.ignoreExprs.append(other) + else: + self.ignoreExprs.append(Suppress(other.copy())) + return self + + def set_debug_actions( + self, + start_action: DebugStartAction, + success_action: DebugSuccessAction, + exception_action: DebugExceptionAction, + ) -> ParserElement: + """ + Customize display of debugging messages while doing pattern matching: + + :param start_action: method to be called when an expression is about to be parsed; + should have the signature:: + + fn(input_string: str, + location: int, + expression: ParserElement, + cache_hit: bool) + + :param success_action: method to be called when an expression has successfully parsed; + should have the signature:: + + fn(input_string: str, + start_location: int, + end_location: int, + expression: ParserELement, + parsed_tokens: ParseResults, + cache_hit: bool) + + :param exception_action: method to be called when expression fails to parse; + should have the signature:: + + fn(input_string: str, + location: int, + expression: ParserElement, + exception: Exception, + cache_hit: bool) + """ + self.debugActions = self.DebugActions( + start_action or _default_start_debug_action, # type: ignore[truthy-function] + success_action or _default_success_debug_action, # type: ignore[truthy-function] + exception_action or _default_exception_debug_action, # type: ignore[truthy-function] + ) + self.debug = any(self.debugActions) + return self + + def set_debug(self, flag: bool = True, recurse: bool = False) -> ParserElement: + """ + Enable display of debugging messages while doing pattern matching. + Set ``flag`` to ``True`` to enable, ``False`` to disable. + Set ``recurse`` to ``True`` to set the debug flag on this expression and all sub-expressions. + + Example: + + .. testcode:: + + wd = Word(alphas).set_name("alphaword") + integer = Word(nums).set_name("numword") + term = wd | integer + + # turn on debugging for wd + wd.set_debug() + + term[1, ...].parse_string("abc 123 xyz 890") + + prints: + + .. testoutput:: + :options: +NORMALIZE_WHITESPACE + + Match alphaword at loc 0(1,1) + abc 123 xyz 890 + ^ + Matched alphaword -> ['abc'] + Match alphaword at loc 4(1,5) + abc 123 xyz 890 + ^ + Match alphaword failed, ParseException raised: Expected alphaword, ... + Match alphaword at loc 8(1,9) + abc 123 xyz 890 + ^ + Matched alphaword -> ['xyz'] + Match alphaword at loc 12(1,13) + abc 123 xyz 890 + ^ + Match alphaword failed, ParseException raised: Expected alphaword, ... + abc 123 xyz 890 + ^ + Match alphaword failed, ParseException raised: Expected alphaword, found end of text ... + + The output shown is that produced by the default debug actions - custom debug actions can be + specified using :meth:`set_debug_actions`. Prior to attempting + to match the ``wd`` expression, the debugging message ``"Match at loc (,)"`` + is shown. Then if the parse succeeds, a ``"Matched"`` message is shown, or an ``"Exception raised"`` + message is shown. Also note the use of :meth:`set_name` to assign a human-readable name to the expression, + which makes debugging and exception messages easier to understand - for instance, the default + name created for the :class:`Word` expression without calling :meth:`set_name` is ``"W:(A-Za-z)"``. + + .. versionchanged:: 3.1.0 + ``recurse`` argument added. + """ + if recurse: + for expr in self.visit_all(): + expr.set_debug(flag, recurse=False) + return self + + if flag: + self.set_debug_actions( + _default_start_debug_action, + _default_success_debug_action, + _default_exception_debug_action, + ) + else: + self.debug = False + return self + + @property + def default_name(self) -> str: + if self._defaultName is None: + self._defaultName = self._generateDefaultName() + return self._defaultName + + @abstractmethod + def _generateDefaultName(self) -> str: + """ + Child classes must define this method, which defines how the ``default_name`` is set. + """ + + def set_name(self, name: typing.Optional[str]) -> ParserElement: + """ + Define name for this expression, makes debugging and exception messages clearer. If + `__diag__.enable_debug_on_named_expressions` is set to True, setting a name will also + enable debug for this expression. + + If `name` is None, clears any custom name for this expression, and clears the + debug flag is it was enabled via `__diag__.enable_debug_on_named_expressions`. + + Example: + + .. doctest:: + + >>> integer = Word(nums) + >>> integer.parse_string("ABC") + Traceback (most recent call last): + ParseException: Expected W:(0-9) (at char 0), (line:1, col:1) + + >>> integer.set_name("integer") + integer + >>> integer.parse_string("ABC") + Traceback (most recent call last): + ParseException: Expected integer (at char 0), (line:1, col:1) + + .. versionchanged:: 3.1.0 + Accept ``None`` as the ``name`` argument. + """ + self.customName = name # type: ignore[assignment] + self.errmsg = f"Expected {str(self)}" + + if __diag__.enable_debug_on_named_expressions: + self.set_debug(name is not None) + + return self + + @property + def name(self) -> str: + """ + Returns a user-defined name if available, but otherwise defaults back to the auto-generated name + """ + return self.customName if self.customName is not None else self.default_name + + @name.setter + def name(self, new_name) -> None: + self.set_name(new_name) + + def __str__(self) -> str: + return self.name + + def __repr__(self) -> str: + return str(self) + + def streamline(self) -> ParserElement: + self.streamlined = True + self._defaultName = None + return self + + def recurse(self) -> list[ParserElement]: + return [] + + def _checkRecursion(self, parseElementList): + subRecCheckList = parseElementList[:] + [self] + for e in self.recurse(): + e._checkRecursion(subRecCheckList) + + def validate(self, validateTrace=None) -> None: + """ + .. deprecated:: 3.0.0 + Do not use to check for left recursion. + + Check defined expressions for valid structure, check for infinite recursive definitions. + + """ + warnings.warn( + "ParserElement.validate() is deprecated, and should not be used to check for left recursion", + PyparsingDeprecationWarning, + stacklevel=2, + ) + self._checkRecursion([]) + + def parse_file( + self, + file_or_filename: Union[str, Path, TextIO], + encoding: str = "utf-8", + parse_all: bool = False, + **kwargs, + ) -> ParseResults: + """ + Execute the parse expression on the given file or filename. + If a filename is specified (instead of a file object), + the entire file is opened, read, and closed before parsing. + """ + parseAll: bool = deprecate_argument(kwargs, "parseAll", False) + + parse_all = parse_all or parseAll + try: + file_or_filename = typing.cast(TextIO, file_or_filename) + file_contents = file_or_filename.read() + except AttributeError: + file_or_filename = typing.cast(str, file_or_filename) + with open(file_or_filename, "r", encoding=encoding) as f: + file_contents = f.read() + try: + return self.parse_string(file_contents, parse_all) + except ParseBaseException as exc: + if ParserElement.verbose_stacktrace: + raise + + # catch and re-raise exception from here, clears out pyparsing internal stack trace + raise exc.with_traceback(None) + + def __eq__(self, other): + if self is other: + return True + elif isinstance(other, str_type): + return self.matches(other, parse_all=True) + elif isinstance(other, ParserElement): + return vars(self) == vars(other) + return False + + def __hash__(self): + return id(self) + + def matches(self, test_string: str, parse_all: bool = True, **kwargs) -> bool: + """ + Method for quick testing of a parser against a test string. Good for simple + inline microtests of sub expressions while building up larger parser. + + :param test_string: to test against this expression for a match + :param parse_all: flag to pass to :meth:`parse_string` when running tests + + Example: + + .. doctest:: + + >>> expr = Word(nums) + >>> expr.matches("100") + True + """ + parseAll: bool = deprecate_argument(kwargs, "parseAll", True) + + parse_all = parse_all and parseAll + try: + self.parse_string(str(test_string), parse_all=parse_all) + return True + except ParseBaseException: + return False + + def run_tests( + self, + tests: Union[str, list[str]], + parse_all: bool = True, + comment: typing.Optional[Union[ParserElement, str]] = "#", + full_dump: bool = True, + print_results: bool = True, + failure_tests: bool = False, + post_parse: typing.Optional[ + Callable[[str, ParseResults], typing.Optional[str]] + ] = None, + file: typing.Optional[TextIO] = None, + with_line_numbers: bool = False, + *, + parseAll: bool = True, + fullDump: bool = True, + printResults: bool = True, + failureTests: bool = False, + postParse: typing.Optional[ + Callable[[str, ParseResults], typing.Optional[str]] + ] = None, + ) -> tuple[bool, list[tuple[str, Union[ParseResults, Exception]]]]: + """ + Execute the parse expression on a series of test strings, showing each + test, the parsed results or where the parse failed. Quick and easy way to + run a parse expression against a list of sample strings. + + Parameters: + + - ``tests`` - a list of separate test strings, or a multiline string of test strings + - ``parse_all`` - (default= ``True``) - flag to pass to :class:`parse_string` when running tests + - ``comment`` - (default= ``'#'``) - expression for indicating embedded comments in the test + string; pass None to disable comment filtering + - ``full_dump`` - (default= ``True``) - dump results as list followed by results names in nested outline; + if False, only dump nested list + - ``print_results`` - (default= ``True``) prints test output to stdout + - ``failure_tests`` - (default= ``False``) indicates if these tests are expected to fail parsing + - ``post_parse`` - (default= ``None``) optional callback for successful parse results; called as + `fn(test_string, parse_results)` and returns a string to be added to the test output + - ``file`` - (default= ``None``) optional file-like object to which test output will be written; + if None, will default to ``sys.stdout`` + - ``with_line_numbers`` - default= ``False``) show test strings with line and column numbers + + Returns: a (success, results) tuple, where success indicates that all tests succeeded + (or failed if ``failure_tests`` is True), and the results contain a list of lines of each + test's output + + Passing example: + + .. testcode:: + + number_expr = pyparsing_common.number.copy() + + result = number_expr.run_tests(''' + # unsigned integer + 100 + # negative integer + -100 + # float with scientific notation + 6.02e23 + # integer with scientific notation + 1e-12 + # negative decimal number without leading digit + -.100 + ''') + print("Success" if result[0] else "Failed!") + + prints: + + .. testoutput:: + :options: +NORMALIZE_WHITESPACE + + + # unsigned integer + 100 + [100] + + # negative integer + -100 + [-100] + + # float with scientific notation + 6.02e23 + [6.02e+23] + + # integer with scientific notation + 1e-12 + [1e-12] + + # negative decimal number without leading digit + -.100 + [-0.1] + Success + + Failure-test example: + + .. testcode:: + + result = number_expr.run_tests(''' + # stray character + 100Z + # too many '.' + 3.14.159 + ''', failure_tests=True) + print("Success" if result[0] else "Failed!") + + prints: + + .. testoutput:: + :options: +NORMALIZE_WHITESPACE + + + # stray character + 100Z + 100Z + ^ + ParseException: Expected end of text, found 'Z' ... + + # too many '.' + 3.14.159 + 3.14.159 + ^ + ParseException: Expected end of text, found '.' ... + FAIL: Expected end of text, found '.' ... + Success + + Each test string must be on a single line. If you want to test a string that spans multiple + lines, create a test like this: + + .. testcode:: + + expr = Word(alphanums)[1,...] + expr.run_tests(r"this is a test\\n of strings that spans \\n 3 lines") + + .. testoutput:: + :options: +NORMALIZE_WHITESPACE + :hide: + + + this is a test\\n of strings that spans \\n 3 lines + ['this', 'is', 'a', 'test', 'of', 'strings', 'that', 'spans', '3', 'lines'] + + (Note that this is a raw string literal, you must include the leading ``'r'``.) + """ + from .testing import pyparsing_test + + parseAll = parseAll and parse_all + fullDump = fullDump and full_dump + printResults = printResults and print_results + failureTests = failureTests or failure_tests + postParse = postParse or post_parse + if isinstance(tests, str_type): + tests = typing.cast(str, tests) + line_strip = type(tests).strip + tests = [line_strip(test_line) for test_line in tests.rstrip().splitlines()] + comment_specified = comment is not None + if comment_specified: + if isinstance(comment, str_type): + comment = typing.cast(str, comment) + comment = Literal(comment) + comment = typing.cast(ParserElement, comment) + if file is None: + file = sys.stdout + print_ = file.write + + result: Union[ParseResults, Exception] + allResults: list[tuple[str, Union[ParseResults, Exception]]] = [] + comments: list[str] = [] + success = True + NL = Literal(r"\n").add_parse_action(replace_with("\n")).ignore(quoted_string) + BOM = "\ufeff" + nlstr = "\n" + for t in tests: + if comment_specified and comment.matches(t, False) or comments and not t: + comments.append( + pyparsing_test.with_line_numbers(t) if with_line_numbers else t + ) + continue + if not t: + continue + out = [ + f"{nlstr}{nlstr.join(comments) if comments else ''}", + pyparsing_test.with_line_numbers(t) if with_line_numbers else t, + ] + comments.clear() + try: + # convert newline marks to actual newlines, and strip leading BOM if present + t = NL.transform_string(t.lstrip(BOM)) + result = self.parse_string(t, parse_all=parse_all) + except ParseBaseException as pe: + fatal = "(FATAL) " if isinstance(pe, ParseFatalException) else "" + out.append(pe.explain()) + out.append(f"FAIL: {fatal}{pe}") + if ParserElement.verbose_stacktrace: + out.extend(traceback.format_tb(pe.__traceback__)) + success = success and failureTests + result = pe + except Exception as exc: + tag = "FAIL-EXCEPTION" + + # see if this exception was raised in a parse action + tb = exc.__traceback__ + it = iter(traceback.walk_tb(tb)) + for f, line in it: + if (f.f_code.co_filename, line) == pa_call_line_synth: + next_f = next(it)[0] + tag += f" (raised in parse action {next_f.f_code.co_name!r})" + break + + out.append(f"{tag}: {type(exc).__name__}: {exc}") + if ParserElement.verbose_stacktrace: + out.extend(traceback.format_tb(exc.__traceback__)) + success = success and failureTests + result = exc + else: + success = success and not failureTests + if postParse is not None: + try: + pp_value = postParse(t, result) + if pp_value is not None: + if isinstance(pp_value, ParseResults): + out.append(pp_value.dump()) + else: + out.append(str(pp_value)) + else: + out.append(result.dump()) + except Exception as e: + out.append(result.dump(full=fullDump)) + out.append( + f"{postParse.__name__} failed: {type(e).__name__}: {e}" + ) + else: + out.append(result.dump(full=fullDump)) + out.append("") + + if printResults: + print_("\n".join(out)) + + allResults.append((t, result)) + + return success, allResults + + def create_diagram( + self, + output_html: Union[TextIO, Path, str], + vertical: int = 3, + show_results_names: bool = False, + show_groups: bool = False, + embed: bool = False, + show_hidden: bool = False, + **kwargs, + ) -> None: + """ + Create a railroad diagram for the parser. + + Parameters: + + - ``output_html`` (str or file-like object) - output target for generated + diagram HTML + - ``vertical`` (int) - threshold for formatting multiple alternatives vertically + instead of horizontally (default=3) + - ``show_results_names`` - bool flag whether diagram should show annotations for + defined results names + - ``show_groups`` - bool flag whether groups should be highlighted with an unlabeled surrounding box + - ``show_hidden`` - bool flag to show diagram elements for internal elements that are usually hidden + - ``embed`` - bool flag whether generated HTML should omit , , and tags to embed + the resulting HTML in an enclosing HTML source + - ``head`` - str containing additional HTML to insert into the section of the generated code; + can be used to insert custom CSS styling + - ``body`` - str containing additional HTML to insert at the beginning of the section of the + generated code + + Additional diagram-formatting keyword arguments can also be included; + see railroad.Diagram class. + + .. versionchanged:: 3.1.0 + ``embed`` argument added. + """ + + try: + from .diagram import to_railroad, railroad_to_html + except ImportError as ie: + raise Exception( + "must ``pip install pyparsing[diagrams]`` to generate parser railroad diagrams" + ) from ie + + self.streamline() + + railroad = to_railroad( + self, + vertical=vertical, + show_results_names=show_results_names, + show_groups=show_groups, + show_hidden=show_hidden, + diagram_kwargs=kwargs, + ) + if not isinstance(output_html, (str, Path)): + # we were passed a file-like object, just write to it + output_html.write(railroad_to_html(railroad, embed=embed, **kwargs)) + return + + with open(output_html, "w", encoding="utf-8") as diag_file: + diag_file.write(railroad_to_html(railroad, embed=embed, **kwargs)) + + # Compatibility synonyms + # fmt: off + inlineLiteralsUsing = staticmethod(replaced_by_pep8("inlineLiteralsUsing", inline_literals_using)) + setDefaultWhitespaceChars = staticmethod(replaced_by_pep8( + "setDefaultWhitespaceChars", set_default_whitespace_chars + )) + disableMemoization = staticmethod(replaced_by_pep8("disableMemoization", disable_memoization)) + enableLeftRecursion = staticmethod(replaced_by_pep8("enableLeftRecursion", enable_left_recursion)) + enablePackrat = staticmethod(replaced_by_pep8("enablePackrat", enable_packrat)) + resetCache = staticmethod(replaced_by_pep8("resetCache", reset_cache)) + + setResultsName = replaced_by_pep8("setResultsName", set_results_name) + setBreak = replaced_by_pep8("setBreak", set_break) + setParseAction = replaced_by_pep8("setParseAction", set_parse_action) + addParseAction = replaced_by_pep8("addParseAction", add_parse_action) + addCondition = replaced_by_pep8("addCondition", add_condition) + setFailAction = replaced_by_pep8("setFailAction", set_fail_action) + tryParse = replaced_by_pep8("tryParse", try_parse) + parseString = replaced_by_pep8("parseString", parse_string) + scanString = replaced_by_pep8("scanString", scan_string) + transformString = replaced_by_pep8("transformString", transform_string) + searchString = replaced_by_pep8("searchString", search_string) + ignoreWhitespace = replaced_by_pep8("ignoreWhitespace", ignore_whitespace) + leaveWhitespace = replaced_by_pep8("leaveWhitespace", leave_whitespace) + setWhitespaceChars = replaced_by_pep8("setWhitespaceChars", set_whitespace_chars) + parseWithTabs = replaced_by_pep8("parseWithTabs", parse_with_tabs) + setDebugActions = replaced_by_pep8("setDebugActions", set_debug_actions) + setDebug = replaced_by_pep8("setDebug", set_debug) + setName = replaced_by_pep8("setName", set_name) + parseFile = replaced_by_pep8("parseFile", parse_file) + runTests = replaced_by_pep8("runTests", run_tests) + canParseNext = replaced_by_pep8("canParseNext", can_parse_next) + defaultName = default_name + # fmt: on + + +class _PendingSkip(ParserElement): + # internal placeholder class to hold a place were '...' is added to a parser element, + # once another ParserElement is added, this placeholder will be replaced with a SkipTo + def __init__(self, expr: ParserElement, must_skip: bool = False) -> None: + super().__init__() + self.anchor = expr + self.must_skip = must_skip + + def _generateDefaultName(self) -> str: + return str(self.anchor + Empty()).replace("Empty", "...") + + def __add__(self, other) -> ParserElement: + skipper = SkipTo(other).set_name("...")("_skipped*") + if self.must_skip: + + def must_skip(t): + if not t._skipped or t._skipped.as_list() == [""]: + del t[0] + t.pop("_skipped", None) + + def show_skip(t): + if t._skipped.as_list()[-1:] == [""]: + t.pop("_skipped") + t["_skipped"] = f"missing <{self.anchor!r}>" + + return ( + self.anchor + skipper().add_parse_action(must_skip) + | skipper().add_parse_action(show_skip) + ) + other + + return self.anchor + skipper + other + + def __repr__(self): + return self.defaultName + + def parseImpl(self, *args) -> ParseImplReturnType: + raise Exception( + "use of `...` expression without following SkipTo target expression" + ) + + +class Token(ParserElement): + """Abstract :class:`ParserElement` subclass, for defining atomic + matching patterns. + """ + + def __init__(self) -> None: + super().__init__(savelist=False) + + def _generateDefaultName(self) -> str: + return type(self).__name__ + + +class NoMatch(Token): + """ + A token that will never match. + """ + + def __init__(self) -> None: + super().__init__() + self._may_return_empty = True + self.mayIndexError = False + self.errmsg = "Unmatchable token" + + def parseImpl(self, instring, loc, do_actions=True) -> ParseImplReturnType: + raise ParseException(instring, loc, self.errmsg, self) + + +class Literal(Token): + """ + Token to exactly match a specified string. + + Example: + + .. doctest:: + + >>> Literal('abc').parse_string('abc') + ParseResults(['abc'], {}) + >>> Literal('abc').parse_string('abcdef') + ParseResults(['abc'], {}) + >>> Literal('abc').parse_string('ab') + Traceback (most recent call last): + ParseException: Expected 'abc', found 'ab' (at char 0), (line: 1, col: 1) + + For case-insensitive matching, use :class:`CaselessLiteral`. + + For keyword matching (force word break before and after the matched string), + use :class:`Keyword` or :class:`CaselessKeyword`. + """ + + def __new__(cls, match_string: str = "", **kwargs): + # Performance tuning: select a subclass with optimized parseImpl + if cls is Literal: + matchString: str = deprecate_argument(kwargs, "matchString", "") + + match_string = matchString or match_string + if not match_string: + return super().__new__(Empty) + if len(match_string) == 1: + return super().__new__(_SingleCharLiteral) + + # Default behavior + return super().__new__(cls) + + # Needed to make copy.copy() work correctly if we customize __new__ + def __getnewargs__(self): + return (self.match,) + + def __init__(self, match_string: str = "", **kwargs) -> None: + matchString: str = deprecate_argument(kwargs, "matchString", "") + + super().__init__() + match_string = matchString or match_string + self.match = match_string + self.matchLen = len(match_string) + self.firstMatchChar = match_string[:1] + self.errmsg = f"Expected {self.name}" + self._may_return_empty = False + self.mayIndexError = False + + def _generateDefaultName(self) -> str: + return repr(self.match) + + def parseImpl(self, instring, loc, do_actions=True) -> ParseImplReturnType: + if instring[loc] == self.firstMatchChar and instring.startswith( + self.match, loc + ): + return loc + self.matchLen, self.match + raise ParseException(instring, loc, self.errmsg, self) + + +class Empty(Literal): + """ + An empty token, will always match. + """ + + def __init__(self, match_string="", *, matchString="") -> None: + super().__init__("") + self._may_return_empty = True + self.mayIndexError = False + + def _generateDefaultName(self) -> str: + return "Empty" + + def parseImpl(self, instring, loc, do_actions=True) -> ParseImplReturnType: + return loc, [] + + +class _SingleCharLiteral(Literal): + def parseImpl(self, instring, loc, do_actions=True) -> ParseImplReturnType: + if instring[loc] == self.firstMatchChar: + return loc + 1, self.match + raise ParseException(instring, loc, self.errmsg, self) + + +ParserElement._literalStringClass = Literal + + +class Keyword(Token): + """ + Token to exactly match a specified string as a keyword, that is, + it must be immediately preceded and followed by whitespace or + non-keyword characters. Compare with :class:`Literal`: + + - ``Literal("if")`` will match the leading ``'if'`` in + ``'ifAndOnlyIf'``. + - ``Keyword("if")`` will not; it will only match the leading + ``'if'`` in ``'if x=1'``, or ``'if(y==2)'`` + + Accepts two optional constructor arguments in addition to the + keyword string: + + - ``ident_chars`` is a string of characters that would be valid + identifier characters, defaulting to all alphanumerics + "_" and + "$" + - ``caseless`` allows case-insensitive matching, default is ``False``. + + Example: + + .. doctest:: + :options: +NORMALIZE_WHITESPACE + + >>> Keyword("start").parse_string("start") + ParseResults(['start'], {}) + >>> Keyword("start").parse_string("starting") + Traceback (most recent call last): + ParseException: Expected Keyword 'start', keyword was immediately + followed by keyword character, found 'ing' (at char 5), (line:1, col:6) + + .. doctest:: + :options: +NORMALIZE_WHITESPACE + + >>> Keyword("start").parse_string("starting").debug() + Traceback (most recent call last): + ParseException: Expected Keyword "start", keyword was immediately + followed by keyword character, found 'ing' ... + + For case-insensitive matching, use :class:`CaselessKeyword`. + """ + + DEFAULT_KEYWORD_CHARS = alphanums + "_$" + + def __init__( + self, + match_string: str = "", + ident_chars: typing.Optional[str] = None, + caseless: bool = False, + **kwargs, + ) -> None: + matchString = deprecate_argument(kwargs, "matchString", "") + identChars = deprecate_argument(kwargs, "identChars", None) + + super().__init__() + identChars = identChars or ident_chars + if identChars is None: + identChars = Keyword.DEFAULT_KEYWORD_CHARS + match_string = matchString or match_string + self.match = match_string + self.matchLen = len(match_string) + self.firstMatchChar = match_string[:1] + if not self.firstMatchChar: + raise ValueError("null string passed to Keyword; use Empty() instead") + self.errmsg = f"Expected {type(self).__name__} {self.name}" + self._may_return_empty = False + self.mayIndexError = False + self.caseless = caseless + if caseless: + self.caselessmatch = match_string.upper() + identChars = identChars.upper() + self.ident_chars = set(identChars) + + @property + def identChars(self) -> set[str]: + """ + .. deprecated:: 3.3.0 + use ident_chars instead. + + Property returning the characters being used as keyword characters for this expression. + """ + return self.ident_chars + + def _generateDefaultName(self) -> str: + return repr(self.match) + + def parseImpl(self, instring, loc, do_actions=True) -> ParseImplReturnType: + errmsg = self.errmsg or "" + errloc = loc + if self.caseless: + if instring[loc : loc + self.matchLen].upper() == self.caselessmatch: + if loc == 0 or instring[loc - 1].upper() not in self.identChars: + if ( + loc >= len(instring) - self.matchLen + or instring[loc + self.matchLen].upper() not in self.identChars + ): + return loc + self.matchLen, self.match + + # followed by keyword char + errmsg += ", was immediately followed by keyword character" + errloc = loc + self.matchLen + else: + # preceded by keyword char + errmsg += ", keyword was immediately preceded by keyword character" + errloc = loc - 1 + # else no match just raise plain exception + + elif ( + instring[loc] == self.firstMatchChar + and self.matchLen == 1 + or instring.startswith(self.match, loc) + ): + if loc == 0 or instring[loc - 1] not in self.identChars: + if ( + loc >= len(instring) - self.matchLen + or instring[loc + self.matchLen] not in self.identChars + ): + return loc + self.matchLen, self.match + + # followed by keyword char + errmsg += ", keyword was immediately followed by keyword character" + errloc = loc + self.matchLen + else: + # preceded by keyword char + errmsg += ", keyword was immediately preceded by keyword character" + errloc = loc - 1 + # else no match just raise plain exception + + raise ParseException(instring, errloc, errmsg, self) + + @staticmethod + def set_default_keyword_chars(chars) -> None: + """ + Overrides the default characters used by :class:`Keyword` expressions. + """ + Keyword.DEFAULT_KEYWORD_CHARS = chars + + # Compatibility synonyms + setDefaultKeywordChars = staticmethod( + replaced_by_pep8("setDefaultKeywordChars", set_default_keyword_chars) + ) + + +class CaselessLiteral(Literal): + """ + Token to match a specified string, ignoring case of letters. + Note: the matched results will always be in the case of the given + match string, NOT the case of the input text. + + Example: + + .. doctest:: + + >>> CaselessLiteral("CMD")[1, ...].parse_string("cmd CMD Cmd10") + ParseResults(['CMD', 'CMD', 'CMD'], {}) + + (Contrast with example for :class:`CaselessKeyword`.) + """ + + def __init__(self, match_string: str = "", **kwargs) -> None: + matchString: str = deprecate_argument(kwargs, "matchString", "") + + match_string = matchString or match_string + super().__init__(match_string.upper()) + # Preserve the defining literal. + self.returnString = match_string + self.errmsg = f"Expected {self.name}" + + def parseImpl(self, instring, loc, do_actions=True) -> ParseImplReturnType: + if instring[loc : loc + self.matchLen].upper() == self.match: + return loc + self.matchLen, self.returnString + raise ParseException(instring, loc, self.errmsg, self) + + +class CaselessKeyword(Keyword): + """ + Caseless version of :class:`Keyword`. + + Example: + + .. doctest:: + + >>> CaselessKeyword("CMD")[1, ...].parse_string("cmd CMD Cmd10") + ParseResults(['CMD', 'CMD'], {}) + + (Contrast with example for :class:`CaselessLiteral`.) + """ + + def __init__( + self, match_string: str = "", ident_chars: typing.Optional[str] = None, **kwargs + ) -> None: + matchString: str = deprecate_argument(kwargs, "matchString", "") + identChars: typing.Optional[str] = deprecate_argument( + kwargs, "identChars", None + ) + + identChars = identChars or ident_chars + match_string = matchString or match_string + super().__init__(match_string, identChars, caseless=True) + + +class CloseMatch(Token): + """A variation on :class:`Literal` which matches "close" matches, + that is, strings with at most 'n' mismatching characters. + :class:`CloseMatch` takes parameters: + + - ``match_string`` - string to be matched + - ``caseless`` - a boolean indicating whether to ignore casing when comparing characters + - ``max_mismatches`` - (``default=1``) maximum number of + mismatches allowed to count as a match + + The results from a successful parse will contain the matched text + from the input string and the following named results: + + - ``mismatches`` - a list of the positions within the + match_string where mismatches were found + - ``original`` - the original match_string used to compare + against the input string + + If ``mismatches`` is an empty list, then the match was an exact + match. + + Example: + + .. doctest:: + :options: +NORMALIZE_WHITESPACE + + >>> patt = CloseMatch("ATCATCGAATGGA") + >>> patt.parse_string("ATCATCGAAXGGA") + ParseResults(['ATCATCGAAXGGA'], + {'original': 'ATCATCGAATGGA', 'mismatches': [9]}) + + >>> patt.parse_string("ATCAXCGAAXGGA") + Traceback (most recent call last): + ParseException: Expected 'ATCATCGAATGGA' (with up to 1 mismatches), + found 'ATCAXCGAAXGGA' (at char 0), (line:1, col:1) + + # exact match + >>> patt.parse_string("ATCATCGAATGGA") + ParseResults(['ATCATCGAATGGA'], + {'original': 'ATCATCGAATGGA', 'mismatches': []}) + + # close match allowing up to 2 mismatches + >>> patt = CloseMatch("ATCATCGAATGGA", max_mismatches=2) + >>> patt.parse_string("ATCAXCGAAXGGA") + ParseResults(['ATCAXCGAAXGGA'], + {'original': 'ATCATCGAATGGA', 'mismatches': [4, 9]}) + """ + + def __init__( + self, + match_string: str, + max_mismatches: typing.Optional[int] = None, + *, + caseless=False, + **kwargs, + ) -> None: + maxMismatches: int = deprecate_argument(kwargs, "maxMismatches", 1) + + maxMismatches = max_mismatches if max_mismatches is not None else maxMismatches + super().__init__() + self.match_string = match_string + self.maxMismatches = maxMismatches + self.errmsg = f"Expected {self.match_string!r} (with up to {self.maxMismatches} mismatches)" + self.caseless = caseless + self.mayIndexError = False + self._may_return_empty = False + + def _generateDefaultName(self) -> str: + return f"{type(self).__name__}:{self.match_string!r}" + + def parseImpl(self, instring, loc, do_actions=True) -> ParseImplReturnType: + start = loc + instrlen = len(instring) + maxloc = start + len(self.match_string) + + if maxloc <= instrlen: + match_string = self.match_string + match_stringloc = 0 + mismatches = [] + maxMismatches = self.maxMismatches + + for match_stringloc, s_m in enumerate( + zip(instring[loc:maxloc], match_string) + ): + src, mat = s_m + if self.caseless: + src, mat = src.lower(), mat.lower() + + if src != mat: + mismatches.append(match_stringloc) + if len(mismatches) > maxMismatches: + break + else: + loc = start + match_stringloc + 1 + results = ParseResults([instring[start:loc]]) + results["original"] = match_string + results["mismatches"] = mismatches + return loc, results + + raise ParseException(instring, loc, self.errmsg, self) + + +class Word(Token): + """Token for matching words composed of allowed character sets. + + Parameters: + + - ``init_chars`` - string of all characters that should be used to + match as a word; "ABC" will match "AAA", "ABAB", "CBAC", etc.; + if ``body_chars`` is also specified, then this is the string of + initial characters + - ``body_chars`` - string of characters that + can be used for matching after a matched initial character as + given in ``init_chars``; if omitted, same as the initial characters + (default=``None``) + - ``min`` - minimum number of characters to match (default=1) + - ``max`` - maximum number of characters to match (default=0) + - ``exact`` - exact number of characters to match (default=0) + - ``as_keyword`` - match as a keyword (default=``False``) + - ``exclude_chars`` - characters that might be + found in the input ``body_chars`` string but which should not be + accepted for matching ;useful to define a word of all + printables except for one or two characters, for instance + (default=``None``) + + :class:`srange` is useful for defining custom character set strings + for defining :class:`Word` expressions, using range notation from + regular expression character sets. + + A common mistake is to use :class:`Word` to match a specific literal + string, as in ``Word("Address")``. Remember that :class:`Word` + uses the string argument to define *sets* of matchable characters. + This expression would match "Add", "AAA", "dAred", or any other word + made up of the characters 'A', 'd', 'r', 'e', and 's'. To match an + exact literal string, use :class:`Literal` or :class:`Keyword`. + + pyparsing includes helper strings for building Words: + + - :attr:`alphas` + - :attr:`nums` + - :attr:`alphanums` + - :attr:`hexnums` + - :attr:`alphas8bit` (alphabetic characters in ASCII range 128-255 + - accented, tilded, umlauted, etc.) + - :attr:`punc8bit` (non-alphabetic characters in ASCII range + 128-255 - currency, symbols, superscripts, diacriticals, etc.) + - :attr:`printables` (any non-whitespace character) + + ``alphas``, ``nums``, and ``printables`` are also defined in several + Unicode sets - see :class:`pyparsing_unicode`. + + Example: + + .. testcode:: + + # a word composed of digits + integer = Word(nums) + # Two equivalent alternate forms: + Word("0123456789") + Word(srange("[0-9]")) + + # a word with a leading capital, and zero or more lowercase + capitalized_word = Word(alphas.upper(), alphas.lower()) + + # hostnames are alphanumeric, with leading alpha, and '-' + hostname = Word(alphas, alphanums + '-') + + # roman numeral + # (not a strict parser, accepts invalid mix of characters) + roman = Word("IVXLCDM") + + # any string of non-whitespace characters, except for ',' + csv_value = Word(printables, exclude_chars=",") + + :raises ValueError: If ``min`` and ``max`` are both specified + and the test ``min <= max`` fails. + + .. versionchanged:: 3.1.0 + Raises :exc:`ValueError` if ``min`` > ``max``. + """ + + def __init__( + self, + init_chars: str = "", + body_chars: typing.Optional[str] = None, + min: int = 1, + max: int = 0, + exact: int = 0, + as_keyword: bool = False, + exclude_chars: typing.Optional[str] = None, + **kwargs, + ) -> None: + initChars: typing.Optional[str] = deprecate_argument(kwargs, "initChars", None) + bodyChars: typing.Optional[str] = deprecate_argument(kwargs, "bodyChars", None) + asKeyword: bool = deprecate_argument(kwargs, "asKeyword", False) + excludeChars: typing.Optional[str] = deprecate_argument( + kwargs, "excludeChars", None + ) + + initChars = initChars or init_chars + bodyChars = bodyChars or body_chars + asKeyword = asKeyword or as_keyword + excludeChars = excludeChars or exclude_chars + super().__init__() + if not initChars: + raise ValueError( + f"invalid {type(self).__name__}, initChars cannot be empty string" + ) + + initChars_set = set(initChars) + if excludeChars: + excludeChars_set = set(excludeChars) + initChars_set -= excludeChars_set + if bodyChars: + bodyChars = "".join(set(bodyChars) - excludeChars_set) + self.init_chars = initChars_set + self.initCharsOrig = "".join(sorted(initChars_set)) + + if bodyChars: + self.bodyChars = set(bodyChars) + self.bodyCharsOrig = "".join(sorted(bodyChars)) + else: + self.bodyChars = initChars_set + self.bodyCharsOrig = self.initCharsOrig + + self.maxSpecified = max > 0 + + if min < 1: + raise ValueError( + "cannot specify a minimum length < 1; use Opt(Word()) if zero-length word is permitted" + ) + + if self.maxSpecified and min > max: + raise ValueError( + f"invalid args, if min and max both specified min must be <= max (min={min}, max={max})" + ) + + self.minLen = min + + if max > 0: + self.maxLen = max + else: + self.maxLen = _MAX_INT + + if exact > 0: + min = max = exact + self.maxLen = exact + self.minLen = exact + + self.errmsg = f"Expected {self.name}" + self.mayIndexError = False + self.asKeyword = asKeyword + if self.asKeyword: + self.errmsg += " as a keyword" + + # see if we can make a regex for this Word + if " " not in (self.initChars | self.bodyChars): + if len(self.initChars) == 1: + re_leading_fragment = re.escape(self.initCharsOrig) + else: + re_leading_fragment = f"[{_collapse_string_to_ranges(self.initChars)}]" + + if self.bodyChars == self.initChars: + if max == 0 and self.minLen == 1: + repeat = "+" + elif max == 1: + repeat = "" + else: + if self.minLen != self.maxLen: + repeat = f"{{{self.minLen},{'' if self.maxLen == _MAX_INT else self.maxLen}}}" + else: + repeat = f"{{{self.minLen}}}" + self.reString = f"{re_leading_fragment}{repeat}" + else: + if max == 1: + re_body_fragment = "" + repeat = "" + else: + re_body_fragment = f"[{_collapse_string_to_ranges(self.bodyChars)}]" + if max == 0 and self.minLen == 1: + repeat = "*" + elif max == 2: + repeat = "?" if min <= 1 else "" + else: + if min != max: + repeat = f"{{{min - 1 if min > 0 else ''},{max - 1 if max > 0 else ''}}}" + else: + repeat = f"{{{min - 1 if min > 0 else ''}}}" + + self.reString = f"{re_leading_fragment}{re_body_fragment}{repeat}" + + if self.asKeyword: + self.reString = rf"\b{self.reString}\b" + + try: + self.re = re.compile(self.reString) + except re.error: + self.re = None # type: ignore[assignment] + else: + self.re_match = self.re.match + self.parseImpl = self.parseImpl_regex # type: ignore[method-assign] + + @property + def initChars(self) -> set[str]: + """ + .. deprecated:: 3.3.0 + use `init_chars` instead. + + Property returning the initial chars to be used when matching this + Word expression. If no body chars were specified, the initial characters + will also be the body characters. + """ + return set(self.init_chars) + + def copy(self) -> Word: + """ + Returns a copy of this expression. + + Generally only used internally by pyparsing. + """ + ret: Word = cast(Word, super().copy()) + if hasattr(self, "re_match"): + ret.re_match = self.re_match + ret.parseImpl = ret.parseImpl_regex # type: ignore[method-assign] + return ret + + def _generateDefaultName(self) -> str: + def charsAsStr(s): + max_repr_len = 16 + s = _collapse_string_to_ranges(s, re_escape=False) + + if len(s) > max_repr_len: + return s[: max_repr_len - 3] + "..." + + return s + + if self.initChars != self.bodyChars: + base = f"W:({charsAsStr(self.initChars)}, {charsAsStr(self.bodyChars)})" + else: + base = f"W:({charsAsStr(self.initChars)})" + + # add length specification + if self.minLen > 1 or self.maxLen != _MAX_INT: + if self.minLen == self.maxLen: + if self.minLen == 1: + return base[2:] + else: + return base + f"{{{self.minLen}}}" + elif self.maxLen == _MAX_INT: + return base + f"{{{self.minLen},...}}" + else: + return base + f"{{{self.minLen},{self.maxLen}}}" + return base + + def parseImpl(self, instring, loc, do_actions=True) -> ParseImplReturnType: + if instring[loc] not in self.initChars: + raise ParseException(instring, loc, self.errmsg, self) + + start = loc + loc += 1 + instrlen = len(instring) + body_chars: set[str] = self.bodyChars + maxloc = start + self.maxLen + maxloc = min(maxloc, instrlen) + while loc < maxloc and instring[loc] in body_chars: + loc += 1 + + throw_exception = False + if loc - start < self.minLen: + throw_exception = True + elif self.maxSpecified and loc < instrlen and instring[loc] in body_chars: + throw_exception = True + elif self.asKeyword and ( + (start > 0 and instring[start - 1] in body_chars) + or (loc < instrlen and instring[loc] in body_chars) + ): + throw_exception = True + + if throw_exception: + raise ParseException(instring, loc, self.errmsg, self) + + return loc, instring[start:loc] + + def parseImpl_regex(self, instring, loc, do_actions=True) -> ParseImplReturnType: + result = self.re_match(instring, loc) + if not result: + raise ParseException(instring, loc, self.errmsg, self) + + loc = result.end() + return loc, result[0] + + +class Char(Word): + """A short-cut class for defining :class:`Word` ``(characters, exact=1)``, + when defining a match of any single character in a string of + characters. + """ + + def __init__( + self, + charset: str, + as_keyword: bool = False, + exclude_chars: typing.Optional[str] = None, + **kwargs, + ) -> None: + asKeyword: bool = deprecate_argument(kwargs, "asKeyword", False) + excludeChars: typing.Optional[str] = deprecate_argument( + kwargs, "excludeChars", None + ) + + asKeyword = asKeyword or as_keyword + excludeChars = excludeChars or exclude_chars + super().__init__( + charset, exact=1, as_keyword=asKeyword, exclude_chars=excludeChars + ) + + +class Regex(Token): + r"""Token for matching strings that match a given regular + expression. Defined with string specifying the regular expression in + a form recognized by the stdlib Python `re module `_. + If the given regex contains named groups (defined using ``(?P...)``), + these will be preserved as named :class:`ParseResults`. + + If instead of the Python stdlib ``re`` module you wish to use a different RE module + (such as the ``regex`` module), you can do so by building your ``Regex`` object with + a compiled RE that was compiled using ``regex``. + + The parameters ``pattern`` and ``flags`` are passed + to the ``re.compile()`` function as-is. See the Python + `re module `_ module for an + explanation of the acceptable patterns and flags. + + Example: + + .. testcode:: + + realnum = Regex(r"[+-]?\d+\.\d*") + # ref: https://stackoverflow.com/questions/267399/how-do-you-match-only-valid-roman-numerals-with-a-regular-expression + roman = Regex(r"M{0,4}(CM|CD|D?{0,3})(XC|XL|L?X{0,3})(IX|IV|V?I{0,3})") + + # named fields in a regex will be returned as named results + date = Regex(r'(?P\d{4})-(?P\d\d?)-(?P\d\d?)') + + # the Regex class will accept regular expressions compiled using the + # re module + import re + parser = pp.Regex(re.compile(r'[0-9]')) + """ + + def __init__( + self, + pattern: Any, + flags: Union[re.RegexFlag, int] = 0, + as_group_list: bool = False, + as_match: bool = False, + **kwargs, + ) -> None: + super().__init__() + asGroupList: bool = deprecate_argument(kwargs, "asGroupList", False) + asMatch: bool = deprecate_argument(kwargs, "asMatch", False) + + asGroupList = asGroupList or as_group_list + asMatch = asMatch or as_match + + if isinstance(pattern, str_type): + if not pattern: + raise ValueError("null string passed to Regex; use Empty() instead") + + self._re = None + self._may_return_empty = None # type: ignore [assignment] + self.reString = self.pattern = pattern + + elif hasattr(pattern, "pattern") and hasattr(pattern, "match"): + self._re = pattern + self._may_return_empty = None # type: ignore [assignment] + self.pattern = self.reString = pattern.pattern + + elif callable(pattern): + # defer creating this pattern until we really need it + self.pattern = pattern + self._may_return_empty = None # type: ignore [assignment] + self._re = None + + else: + raise TypeError( + "Regex may only be constructed with a string or a compiled RE object," + " or a callable that takes no arguments and returns a string or a" + " compiled RE object" + ) + + self.flags = flags + self.errmsg = f"Expected {self.name}" + self.mayIndexError = False + self.asGroupList = asGroupList + self.asMatch = asMatch + if self.asGroupList: + self.parseImpl = self.parseImplAsGroupList # type: ignore [method-assign] + if self.asMatch: + self.parseImpl = self.parseImplAsMatch # type: ignore [method-assign] + + def copy(self) -> Regex: + """ + Returns a copy of this expression. + + Generally only used internally by pyparsing. + """ + ret: Regex = cast(Regex, super().copy()) + if self.asGroupList: + ret.parseImpl = ret.parseImplAsGroupList # type: ignore [method-assign] + if self.asMatch: + ret.parseImpl = ret.parseImplAsMatch # type: ignore [method-assign] + return ret + + @cached_property + def re(self) -> re.Pattern: + """ + Property returning the compiled regular expression for this Regex. + + Generally only used internally by pyparsing. + """ + if self._re: + return self._re + + if callable(self.pattern): + # replace self.pattern with the string returned by calling self.pattern() + self.pattern = cast(Callable[[], str], self.pattern)() + + # see if we got a compiled RE back instead of a str - if so, we're done + if hasattr(self.pattern, "pattern") and hasattr(self.pattern, "match"): + self._re = cast(re.Pattern[str], self.pattern) + self.pattern = self.reString = self._re.pattern + return self._re + + try: + self._re = re.compile(self.pattern, self.flags) + except re.error: + raise ValueError(f"invalid pattern ({self.pattern!r}) passed to Regex") + else: + self._may_return_empty = self.re.match("", pos=0) is not None + return self._re + + @cached_property + def re_match(self) -> Callable[[str, int], Any]: + return self.re.match + + @property + def mayReturnEmpty(self): + if self._may_return_empty is None: + # force compile of regex pattern, to set may_return_empty flag + self.re # noqa + return self._may_return_empty + + @mayReturnEmpty.setter + def mayReturnEmpty(self, value): + self._may_return_empty = value + + def _generateDefaultName(self) -> str: + unescaped = repr(self.pattern).replace("\\\\", "\\") + return f"Re:({unescaped})" + + def parseImpl(self, instring, loc, do_actions=True) -> ParseImplReturnType: + # explicit check for matching past the length of the string; + # this is done because the re module will not complain about + # a match with `pos > len(instring)`, it will just return "" + if loc > len(instring) and self.mayReturnEmpty: + raise ParseException(instring, loc, self.errmsg, self) + + result = self.re_match(instring, loc) + if not result: + raise ParseException(instring, loc, self.errmsg, self) + + loc = result.end() + ret = ParseResults(result[0]) + d = result.groupdict() + + for k, v in d.items(): + ret[k] = v + + return loc, ret + + def parseImplAsGroupList(self, instring, loc, do_actions=True): + if loc > len(instring) and self.mayReturnEmpty: + raise ParseException(instring, loc, self.errmsg, self) + + result = self.re_match(instring, loc) + if not result: + raise ParseException(instring, loc, self.errmsg, self) + + loc = result.end() + ret = result.groups() + return loc, ret + + def parseImplAsMatch(self, instring, loc, do_actions=True): + if loc > len(instring) and self.mayReturnEmpty: + raise ParseException(instring, loc, self.errmsg, self) + + result = self.re_match(instring, loc) + if not result: + raise ParseException(instring, loc, self.errmsg, self) + + loc = result.end() + ret = result + return loc, ret + + def sub(self, repl: str) -> ParserElement: + r""" + Return :class:`Regex` with an attached parse action to transform the parsed + result as if called using `re.sub(expr, repl, string) `_. + + Example: + + .. testcode:: + + make_html = Regex(r"(\w+):(.*?):").sub(r"<\1>\2") + print(make_html.transform_string("h1:main title:")) + + .. testoutput:: + +

main title

+ """ + if self.asGroupList: + raise TypeError("cannot use sub() with Regex(as_group_list=True)") + + if self.asMatch and callable(repl): + raise TypeError( + "cannot use sub() with a callable with Regex(as_match=True)" + ) + + if self.asMatch: + + def pa(tokens): + return tokens[0].expand(repl) + + else: + + def pa(tokens): + return self.re.sub(repl, tokens[0]) + + return self.add_parse_action(pa) + + +class QuotedString(Token): + r""" + Token for matching strings that are delimited by quoting characters. + + Defined with the following parameters: + + - ``quote_char`` - string of one or more characters defining the + quote delimiting string + - ``esc_char`` - character to re_escape quotes, typically backslash + (default= ``None``) + - ``esc_quote`` - special quote sequence to re_escape an embedded quote + string (such as SQL's ``""`` to re_escape an embedded ``"``) + (default= ``None``) + - ``multiline`` - boolean indicating whether quotes can span + multiple lines (default= ``False``) + - ``unquote_results`` - boolean indicating whether the matched text + should be unquoted (default= ``True``) + - ``end_quote_char`` - string of one or more characters defining the + end of the quote delimited string (default= ``None`` => same as + quote_char) + - ``convert_whitespace_escapes`` - convert escaped whitespace + (``'\t'``, ``'\n'``, etc.) to actual whitespace + (default= ``True``) + + .. caution:: ``convert_whitespace_escapes`` has no effect if + ``unquote_results`` is ``False``. + + Example: + + .. doctest:: + + >>> qs = QuotedString('"') + >>> print(qs.search_string('lsjdf "This is the quote" sldjf')) + [['This is the quote']] + >>> complex_qs = QuotedString('{{', end_quote_char='}}') + >>> print(complex_qs.search_string( + ... 'lsjdf {{This is the "quote"}} sldjf')) + [['This is the "quote"']] + >>> sql_qs = QuotedString('"', esc_quote='""') + >>> print(sql_qs.search_string( + ... 'lsjdf "This is the quote with ""embedded"" quotes" sldjf')) + [['This is the quote with "embedded" quotes']] + """ + + ws_map = dict(((r"\t", "\t"), (r"\n", "\n"), (r"\f", "\f"), (r"\r", "\r"))) + + def __init__( + self, + quote_char: str = "", + esc_char: typing.Optional[str] = None, + esc_quote: typing.Optional[str] = None, + multiline: bool = False, + unquote_results: bool = True, + end_quote_char: typing.Optional[str] = None, + convert_whitespace_escapes: bool = True, + **kwargs, + ) -> None: + super().__init__() + quoteChar: str = deprecate_argument(kwargs, "quoteChar", "") + escChar: str = deprecate_argument(kwargs, "escChar", None) + escQuote: str = deprecate_argument(kwargs, "escQuote", None) + unquoteResults: bool = deprecate_argument(kwargs, "unquoteResults", True) + endQuoteChar: typing.Optional[str] = deprecate_argument( + kwargs, "endQuoteChar", None + ) + convertWhitespaceEscapes: bool = deprecate_argument( + kwargs, "convertWhitespaceEscapes", True + ) + + esc_char = escChar or esc_char + esc_quote = escQuote or esc_quote + unquote_results = unquoteResults and unquote_results + end_quote_char = endQuoteChar or end_quote_char + convert_whitespace_escapes = ( + convertWhitespaceEscapes and convert_whitespace_escapes + ) + quote_char = quoteChar or quote_char + + # remove white space from quote chars + quote_char = quote_char.strip() + if not quote_char: + raise ValueError("quote_char cannot be the empty string") + + if end_quote_char is None: + end_quote_char = quote_char + else: + end_quote_char = end_quote_char.strip() + if not end_quote_char: + raise ValueError("end_quote_char cannot be the empty string") + + self.quote_char: str = quote_char + self.quote_char_len: int = len(quote_char) + self.first_quote_char: str = quote_char[0] + self.end_quote_char: str = end_quote_char + self.end_quote_char_len: int = len(end_quote_char) + self.esc_char: str = esc_char or "" + self.has_esc_char: bool = esc_char is not None + self.esc_quote: str = esc_quote or "" + self.unquote_results: bool = unquote_results + self.convert_whitespace_escapes: bool = convert_whitespace_escapes + self.multiline = multiline + self.re_flags = re.RegexFlag(0) + + # fmt: off + # build up re pattern for the content between the quote delimiters + inner_pattern: list[str] = [] + + if esc_quote: + inner_pattern.append(rf"(?:{re.escape(esc_quote)})") + + if esc_char: + inner_pattern.append(rf"(?:{re.escape(esc_char)}.)") + + if len(self.end_quote_char) > 1: + inner_pattern.append( + "(?:" + + "|".join( + f"(?:{re.escape(self.end_quote_char[:i])}(?!{re.escape(self.end_quote_char[i:])}))" + for i in range(len(self.end_quote_char) - 1, 0, -1) + ) + + ")" + ) + + if self.multiline: + self.re_flags |= re.MULTILINE | re.DOTALL + inner_pattern.append( + rf"(?:[^{_escape_regex_range_chars(self.end_quote_char[0])}" + rf"{(_escape_regex_range_chars(self.esc_char) if self.has_esc_char else '')}])" + ) + else: + inner_pattern.append( + rf"(?:[^{_escape_regex_range_chars(self.end_quote_char[0])}\n\r" + rf"{(_escape_regex_range_chars(self.esc_char) if self.has_esc_char else '')}])" + ) + + self.pattern = "".join( + [ + re.escape(self.quote_char), + "(?:", + '|'.join(inner_pattern), + ")*", + re.escape(self.end_quote_char), + ] + ) + + if self.unquote_results: + if self.convert_whitespace_escapes: + self.unquote_scan_re = re.compile( + rf"({'|'.join(re.escape(k) for k in self.ws_map)})" + rf"|(\\[0-7]{3}|\\0|\\x[0-9a-fA-F]{2}|\\u[0-9a-fA-F]{4})" + rf"|({re.escape(self.esc_char)}.)" + rf"|(\n|.)", + flags=self.re_flags, + ) + else: + self.unquote_scan_re = re.compile( + rf"({re.escape(self.esc_char)}.)" + rf"|(\n|.)", + flags=self.re_flags + ) + # fmt: on + + try: + self.re = re.compile(self.pattern, self.re_flags) + self.reString = self.pattern + self.re_match = self.re.match + except re.error: + raise ValueError(f"invalid pattern {self.pattern!r} passed to Regex") + + self.errmsg = f"Expected {self.name}" + self.mayIndexError = False + self._may_return_empty = True + + def _generateDefaultName(self) -> str: + if self.quote_char == self.end_quote_char and isinstance( + self.quote_char, str_type + ): + return f"string enclosed in {self.quote_char!r}" + + return f"quoted string, starting with {self.quote_char} ending with {self.end_quote_char}" + + def parseImpl(self, instring, loc, do_actions=True) -> ParseImplReturnType: + # check first character of opening quote to see if that is a match + # before doing the more complicated regex match + result = ( + instring[loc] == self.first_quote_char + and self.re_match(instring, loc) + or None + ) + if not result: + raise ParseException(instring, loc, self.errmsg, self) + + # get ending loc and matched string from regex matching result + loc = result.end() + ret = result[0] + + if self.unquote_results: + # strip off quotes + ret = ret[self.quote_char_len : -self.end_quote_char_len] + + if isinstance(ret, str_type): + # fmt: off + if self.convert_whitespace_escapes: + # as we iterate over matches in the input string, + # collect from whichever match group of the unquote_scan_re + # regex matches (only 1 group will match at any given time) + ret = "".join( + # match group 1 matches \t, \n, etc. + self.ws_map[g] if (g := match[1]) + # match group 2 matches escaped octal, null, hex, and Unicode + # sequences + else _convert_escaped_numerics_to_char(g[1:]) if (g := match[2]) + # match group 3 matches escaped characters + else g[-1] if (g := match[3]) + # match group 4 matches any character + else match[4] + for match in self.unquote_scan_re.finditer(ret) + ) + else: + ret = "".join( + # match group 1 matches escaped characters + g[-1] if (g := match[1]) + # match group 2 matches any character + else match[2] + for match in self.unquote_scan_re.finditer(ret) + ) + # fmt: on + + # replace escaped quotes + if self.esc_quote: + ret = ret.replace(self.esc_quote, self.end_quote_char) + + return loc, ret + + +class CharsNotIn(Token): + """Token for matching words composed of characters *not* in a given + set (will include whitespace in matched characters if not listed in + the provided exclusion set - see example). Defined with string + containing all disallowed characters, and an optional minimum, + maximum, and/or exact length. The default value for ``min`` is + 1 (a minimum value < 1 is not valid); the default values for + ``max`` and ``exact`` are 0, meaning no maximum or exact + length restriction. + + Example: + + .. testcode:: + + # define a comma-separated-value as anything that is not a ',' + csv_value = CharsNotIn(',') + print( + DelimitedList(csv_value).parse_string( + "dkls,lsdkjf,s12 34,@!#,213" + ) + ) + + prints: + + .. testoutput:: + + ['dkls', 'lsdkjf', 's12 34', '@!#', '213'] + """ + + def __init__( + self, not_chars: str = "", min: int = 1, max: int = 0, exact: int = 0, **kwargs + ) -> None: + super().__init__() + notChars: str = deprecate_argument(kwargs, "notChars", "") + + self.skipWhitespace = False + self.notChars = not_chars or notChars + self.notCharsSet = set(self.notChars) + + if min < 1: + raise ValueError( + "cannot specify a minimum length < 1; use" + " Opt(CharsNotIn()) if zero-length char group is permitted" + ) + + self.minLen = min + + if max > 0: + self.maxLen = max + else: + self.maxLen = _MAX_INT + + if exact > 0: + self.maxLen = exact + self.minLen = exact + + self.errmsg = f"Expected {self.name}" + self._may_return_empty = self.minLen == 0 + self.mayIndexError = False + + def _generateDefaultName(self) -> str: + not_chars_str = _collapse_string_to_ranges(self.notChars) + if len(not_chars_str) > 16: + return f"!W:({self.notChars[: 16 - 3]}...)" + else: + return f"!W:({self.notChars})" + + def parseImpl(self, instring, loc, do_actions=True) -> ParseImplReturnType: + notchars = self.notCharsSet + if instring[loc] in notchars: + raise ParseException(instring, loc, self.errmsg, self) + + start = loc + loc += 1 + maxlen = min(start + self.maxLen, len(instring)) + while loc < maxlen and instring[loc] not in notchars: + loc += 1 + + if loc - start < self.minLen: + raise ParseException(instring, loc, self.errmsg, self) + + return loc, instring[start:loc] + + +class White(Token): + """Special matching class for matching whitespace. Normally, + whitespace is ignored by pyparsing grammars. This class is included + when some whitespace structures are significant. Define with + a string containing the whitespace characters to be matched; default + is ``" \\t\\r\\n"``. Also takes optional ``min``, + ``max``, and ``exact`` arguments, as defined for the + :class:`Word` class. + """ + + whiteStrs = { + " ": "", + "\t": "", + "\n": "", + "\r": "", + "\f": "", + "\u00a0": "", + "\u1680": "", + "\u180e": "", + "\u2000": "", + "\u2001": "", + "\u2002": "", + "\u2003": "", + "\u2004": "", + "\u2005": "", + "\u2006": "", + "\u2007": "", + "\u2008": "", + "\u2009": "", + "\u200a": "", + "\u200b": "", + "\u202f": "", + "\u205f": "", + "\u3000": "", + } + + def __init__( + self, ws: str = " \t\r\n", min: int = 1, max: int = 0, exact: int = 0 + ) -> None: + super().__init__() + self.matchWhite = ws + self.set_whitespace_chars( + "".join(c for c in self.whiteStrs if c not in self.matchWhite), + copy_defaults=True, + ) + # self.leave_whitespace() + self._may_return_empty = True + self.errmsg = f"Expected {self.name}" + + self.minLen = min + + if max > 0: + self.maxLen = max + else: + self.maxLen = _MAX_INT + + if exact > 0: + self.maxLen = exact + self.minLen = exact + + def _generateDefaultName(self) -> str: + return "".join(White.whiteStrs[c] for c in self.matchWhite) + + def parseImpl(self, instring, loc, do_actions=True) -> ParseImplReturnType: + if instring[loc] not in self.matchWhite: + raise ParseException(instring, loc, self.errmsg, self) + start = loc + loc += 1 + maxloc = start + self.maxLen + maxloc = min(maxloc, len(instring)) + while loc < maxloc and instring[loc] in self.matchWhite: + loc += 1 + + if loc - start < self.minLen: + raise ParseException(instring, loc, self.errmsg, self) + + return loc, instring[start:loc] + + +class PositionToken(Token): + def __init__(self) -> None: + super().__init__() + self._may_return_empty = True + self.mayIndexError = False + + +class GoToColumn(PositionToken): + """Token to advance to a specific column of input text; useful for + tabular report scraping. + """ + + def __init__(self, colno: int) -> None: + super().__init__() + self.col = colno + + def preParse(self, instring: str, loc: int) -> int: + if col(loc, instring) == self.col: + return loc + + instrlen = len(instring) + if self.ignoreExprs: + loc = self._skipIgnorables(instring, loc) + while ( + loc < instrlen + and instring[loc].isspace() + and col(loc, instring) != self.col + ): + loc += 1 + + return loc + + def parseImpl(self, instring, loc, do_actions=True) -> ParseImplReturnType: + thiscol = col(loc, instring) + if thiscol > self.col: + raise ParseException(instring, loc, "Text not in expected column", self) + newloc = loc + self.col - thiscol + ret = instring[loc:newloc] + return newloc, ret + + +class LineStart(PositionToken): + r"""Matches if current position is at the logical beginning of a line (after skipping whitespace) + within the parse string + + Example: + + .. testcode:: + + test = '''\ + AAA this line + AAA and this line + AAA and even this line + B AAA but definitely not this line + ''' + + for t in (LineStart() + 'AAA' + rest_of_line).search_string(test): + print(t) + + prints: + + .. testoutput:: + + ['AAA', ' this line'] + ['AAA', ' and this line'] + ['AAA', ' and even this line'] + + """ + + def __init__(self) -> None: + super().__init__() + self.leave_whitespace() + self.orig_whiteChars = set() | self.whiteChars + self.whiteChars.discard("\n") + self.skipper = Empty().set_whitespace_chars(self.whiteChars) + self.set_name("start of line") + + def preParse(self, instring: str, loc: int) -> int: + if loc == 0: + return loc + + ret = self.skipper.preParse(instring, loc) + + if "\n" in self.orig_whiteChars: + while instring[ret : ret + 1] == "\n": + ret = self.skipper.preParse(instring, ret + 1) + + return ret + + def parseImpl(self, instring, loc, do_actions=True) -> ParseImplReturnType: + if col(loc, instring) == 1: + return loc, [] + raise ParseException(instring, loc, self.errmsg, self) + + +class LineEnd(PositionToken): + """Matches if current position is at the end of a line within the + parse string + """ + + def __init__(self) -> None: + super().__init__() + self.whiteChars.discard("\n") + self.set_whitespace_chars(self.whiteChars, copy_defaults=False) + self.set_name("end of line") + + def parseImpl(self, instring, loc, do_actions=True) -> ParseImplReturnType: + if loc < len(instring): + if instring[loc] == "\n": + return loc + 1, "\n" + else: + raise ParseException(instring, loc, self.errmsg, self) + elif loc == len(instring): + return loc + 1, [] + else: + raise ParseException(instring, loc, self.errmsg, self) + + +class StringStart(PositionToken): + """Matches if current position is at the beginning of the parse + string + """ + + def __init__(self) -> None: + super().__init__() + self.set_name("start of text") + + def parseImpl(self, instring, loc, do_actions=True) -> ParseImplReturnType: + # see if entire string up to here is just whitespace and ignoreables + if loc != 0 and loc != self.preParse(instring, 0): + raise ParseException(instring, loc, self.errmsg, self) + + return loc, [] + + +class StringEnd(PositionToken): + """ + Matches if current position is at the end of the parse string + """ + + def __init__(self) -> None: + super().__init__() + self.set_name("end of text") + + def parseImpl(self, instring, loc, do_actions=True) -> ParseImplReturnType: + if loc < len(instring): + raise ParseException(instring, loc, self.errmsg, self) + if loc == len(instring): + return loc + 1, [] + if loc > len(instring): + return loc, [] + + raise ParseException(instring, loc, self.errmsg, self) + + +class WordStart(PositionToken): + """Matches if the current position is at the beginning of a + :class:`Word`, and is not preceded by any character in a given + set of ``word_chars`` (default= ``printables``). To emulate the + ``\b`` behavior of regular expressions, use + ``WordStart(alphanums)``. ``WordStart`` will also match at + the beginning of the string being parsed, or at the beginning of + a line. + """ + + def __init__(self, word_chars: str = printables, **kwargs) -> None: + wordChars: str = deprecate_argument(kwargs, "wordChars", printables) + + wordChars = word_chars if wordChars == printables else wordChars + super().__init__() + self.wordChars = set(wordChars) + self.set_name("start of a word") + + def parseImpl(self, instring, loc, do_actions=True) -> ParseImplReturnType: + if loc != 0: + if ( + instring[loc - 1] in self.wordChars + or instring[loc] not in self.wordChars + ): + raise ParseException(instring, loc, self.errmsg, self) + return loc, [] + + +class WordEnd(PositionToken): + """Matches if the current position is at the end of a :class:`Word`, + and is not followed by any character in a given set of ``word_chars`` + (default= ``printables``). To emulate the ``\b`` behavior of + regular expressions, use ``WordEnd(alphanums)``. ``WordEnd`` + will also match at the end of the string being parsed, or at the end + of a line. + """ + + def __init__(self, word_chars: str = printables, **kwargs) -> None: + wordChars: str = deprecate_argument(kwargs, "wordChars", printables) + + wordChars = word_chars if wordChars == printables else wordChars + super().__init__() + self.wordChars = set(wordChars) + self.skipWhitespace = False + self.set_name("end of a word") + + def parseImpl(self, instring, loc, do_actions=True) -> ParseImplReturnType: + instrlen = len(instring) + if instrlen > 0 and loc < instrlen: + if ( + instring[loc] in self.wordChars + or instring[loc - 1] not in self.wordChars + ): + raise ParseException(instring, loc, self.errmsg, self) + return loc, [] + + +class Tag(Token): + """ + A meta-element for inserting a named result into the parsed + tokens that may be checked later in a parse action or while + processing the parsed results. Accepts an optional tag value, + defaulting to `True`. + + Example: + + .. doctest:: + + >>> end_punc = "." | ("!" + Tag("enthusiastic")) + >>> greeting = "Hello," + Word(alphas) + end_punc + + >>> result = greeting.parse_string("Hello, World.") + >>> print(result.dump()) + ['Hello,', 'World', '.'] + + >>> result = greeting.parse_string("Hello, World!") + >>> print(result.dump()) + ['Hello,', 'World', '!'] + - enthusiastic: True + + .. versionadded:: 3.1.0 + """ + + def __init__(self, tag_name: str, value: Any = True) -> None: + super().__init__() + self._may_return_empty = True + self.mayIndexError = False + self.leave_whitespace() + self.tag_name = tag_name + self.tag_value = value + self.add_parse_action(self._add_tag) + self.show_in_diagram = False + + def _add_tag(self, tokens: ParseResults): + tokens[self.tag_name] = self.tag_value + + def _generateDefaultName(self) -> str: + return f"{type(self).__name__}:{self.tag_name}={self.tag_value!r}" + + +class ParseExpression(ParserElement): + """Abstract subclass of ParserElement, for combining and + post-processing parsed tokens. + """ + + def __init__( + self, exprs: typing.Iterable[ParserElement], savelist: bool = False + ) -> None: + super().__init__(savelist) + self.exprs: list[ParserElement] + if isinstance(exprs, _generatorType): + exprs = list(exprs) + + if isinstance(exprs, str_type): + self.exprs = [self._literalStringClass(exprs)] + elif isinstance(exprs, ParserElement): + self.exprs = [exprs] + elif isinstance(exprs, Iterable): + exprs = list(exprs) + # if sequence of strings provided, wrap with Literal + if any(isinstance(expr, str_type) for expr in exprs): + exprs = ( + self._literalStringClass(e) if isinstance(e, str_type) else e + for e in exprs + ) + self.exprs = list(exprs) + else: + try: + self.exprs = list(exprs) + except TypeError: + self.exprs = [exprs] + self.callPreparse = False + + def recurse(self) -> list[ParserElement]: + return self.exprs[:] + + def append(self, other) -> ParserElement: + """ + Add an expression to the list of expressions related to this ParseExpression instance. + """ + self.exprs.append(other) + self._defaultName = None + return self + + def leave_whitespace(self, recursive: bool = True) -> ParserElement: + """ + Extends ``leave_whitespace`` defined in base class, and also invokes ``leave_whitespace`` on + all contained expressions. + """ + super().leave_whitespace(recursive) + + if recursive: + self.exprs = [e.copy() for e in self.exprs] + for e in self.exprs: + e.leave_whitespace(recursive) + return self + + def ignore_whitespace(self, recursive: bool = True) -> ParserElement: + """ + Extends ``ignore_whitespace`` defined in base class, and also invokes ``ignore_whitespace`` on + all contained expressions. + """ + super().ignore_whitespace(recursive) + if recursive: + self.exprs = [e.copy() for e in self.exprs] + for e in self.exprs: + e.ignore_whitespace(recursive) + return self + + def ignore(self, other) -> ParserElement: + """ + Define expression to be ignored (e.g., comments) while doing pattern + matching; may be called repeatedly, to define multiple comment or other + ignorable patterns. + """ + if isinstance(other, Suppress): + if other not in self.ignoreExprs: + super().ignore(other) + for e in self.exprs: + e.ignore(self.ignoreExprs[-1]) + else: + super().ignore(other) + for e in self.exprs: + e.ignore(self.ignoreExprs[-1]) + return self + + def _generateDefaultName(self) -> str: + return f"{type(self).__name__}:({self.exprs})" + + def streamline(self) -> ParserElement: + if self.streamlined: + return self + + super().streamline() + + for e in self.exprs: + e.streamline() + + # collapse nested :class:`And`'s of the form ``And(And(And(a, b), c), d)`` to ``And(a, b, c, d)`` + # but only if there are no parse actions or resultsNames on the nested And's + # (likewise for :class:`Or`'s and :class:`MatchFirst`'s) + if len(self.exprs) == 2: + other = self.exprs[0] + if ( + isinstance(other, self.__class__) + and not other.parseAction + and other.resultsName is None + and not other.debug + ): + self.exprs = other.exprs[:] + [self.exprs[1]] + self._defaultName = None + self._may_return_empty |= other.mayReturnEmpty + self.mayIndexError |= other.mayIndexError + + other = self.exprs[-1] + if ( + isinstance(other, self.__class__) + and not other.parseAction + and other.resultsName is None + and not other.debug + ): + self.exprs = self.exprs[:-1] + other.exprs[:] + self._defaultName = None + self._may_return_empty |= other.mayReturnEmpty + self.mayIndexError |= other.mayIndexError + + self.errmsg = f"Expected {self}" + + return self + + def validate(self, validateTrace=None) -> None: + warnings.warn( + "ParserElement.validate() is deprecated, and should not be used to check for left recursion", + PyparsingDeprecationWarning, + stacklevel=2, + ) + tmp = (validateTrace if validateTrace is not None else [])[:] + [self] + for e in self.exprs: + e.validate(tmp) + self._checkRecursion([]) + + def copy(self) -> ParserElement: + """ + Returns a copy of this expression. + + Generally only used internally by pyparsing. + """ + ret = super().copy() + ret = typing.cast(ParseExpression, ret) + ret.exprs = [e.copy() for e in self.exprs] + return ret + + def _setResultsName(self, name, list_all_matches=False) -> ParserElement: + if not ( + __diag__.warn_ungrouped_named_tokens_in_collection + and Diagnostics.warn_ungrouped_named_tokens_in_collection + not in self.suppress_warnings_ + ): + return super()._setResultsName(name, list_all_matches) + + for e in self.exprs: + if ( + isinstance(e, ParserElement) + and e.resultsName + and ( + Diagnostics.warn_ungrouped_named_tokens_in_collection + not in e.suppress_warnings_ + ) + ): + warning = ( + "warn_ungrouped_named_tokens_in_collection:" + f" setting results name {name!r} on {type(self).__name__} expression" + f" collides with {e.resultsName!r} on contained expression" + ) + warnings.warn(warning, PyparsingDiagnosticWarning, stacklevel=3) + break + + return super()._setResultsName(name, list_all_matches) + + # Compatibility synonyms + # fmt: off + leaveWhitespace = replaced_by_pep8("leaveWhitespace", leave_whitespace) + ignoreWhitespace = replaced_by_pep8("ignoreWhitespace", ignore_whitespace) + # fmt: on + + +class And(ParseExpression): + """ + Requires all given :class:`ParserElement` s to be found in the given order. + Expressions may be separated by whitespace. + May be constructed using the ``'+'`` operator. + May also be constructed using the ``'-'`` operator, which will + suppress backtracking. + + Example: + + .. testcode:: + + integer = Word(nums) + name_expr = Word(alphas)[1, ...] + + expr = And([integer("id"), name_expr("name"), integer("age")]) + # more easily written as: + expr = integer("id") + name_expr("name") + integer("age") + """ + + class _ErrorStop(Empty): + def __init__(self, *args, **kwargs) -> None: + super().__init__(*args, **kwargs) + self.leave_whitespace() + + def _generateDefaultName(self) -> str: + return "-" + + def __init__( + self, + exprs_arg: typing.Iterable[Union[ParserElement, str]], + savelist: bool = True, + ) -> None: + # instantiate exprs as a list, converting strs to ParserElements + exprs: list[ParserElement] = [ + self._literalStringClass(e) if isinstance(e, str) else e for e in exprs_arg + ] + + # convert any Ellipsis elements to SkipTo + if Ellipsis in exprs: + + # Ellipsis cannot be the last element + if exprs[-1] is Ellipsis: + raise Exception("cannot construct And with sequence ending in ...") + + tmp: list[ParserElement] = [] + for cur_expr, next_expr in zip(exprs, exprs[1:]): + if cur_expr is Ellipsis: + tmp.append(SkipTo(next_expr)("_skipped*")) + else: + tmp.append(cur_expr) + + exprs[:-1] = tmp + + super().__init__(exprs, savelist) + if self.exprs: + self._may_return_empty = all(e.mayReturnEmpty for e in self.exprs) + if not isinstance(self.exprs[0], White): + self.set_whitespace_chars( + self.exprs[0].whiteChars, + copy_defaults=self.exprs[0].copyDefaultWhiteChars, + ) + self.skipWhitespace = self.exprs[0].skipWhitespace + else: + self.skipWhitespace = False + else: + self._may_return_empty = True + self.callPreparse = True + + def streamline(self) -> ParserElement: + """ + Collapse `And` expressions like `And(And(And(A, B), C), D)` + to `And(A, B, C, D)`. + + .. doctest:: + + >>> expr = Word("A") + Word("B") + Word("C") + Word("D") + >>> # Using '+' operator creates nested And expression + >>> expr + {{{W:(A) W:(B)} W:(C)} W:(D)} + >>> # streamline simplifies to a single And with multiple expressions + >>> expr.streamline() + {W:(A) W:(B) W:(C) W:(D)} + + Guards against collapsing out expressions that have special features, + such as results names or parse actions. + + Resolves pending Skip commands defined using `...` terms. + """ + # collapse any _PendingSkip's + if self.exprs and any( + isinstance(e, ParseExpression) + and e.exprs + and isinstance(e.exprs[-1], _PendingSkip) + for e in self.exprs[:-1] + ): + deleted_expr_marker = NoMatch() + for i, e in enumerate(self.exprs[:-1]): + if e is deleted_expr_marker: + continue + if ( + isinstance(e, ParseExpression) + and e.exprs + and isinstance(e.exprs[-1], _PendingSkip) + ): + e.exprs[-1] = e.exprs[-1] + self.exprs[i + 1] + self.exprs[i + 1] = deleted_expr_marker + self.exprs = [e for e in self.exprs if e is not deleted_expr_marker] + + super().streamline() + + # link any IndentedBlocks to the prior expression + prev: ParserElement + cur: ParserElement + for prev, cur in zip(self.exprs, self.exprs[1:]): + # traverse cur or any first embedded expr of cur looking for an IndentedBlock + # (but watch out for recursive grammar) + seen = set() + while True: + if id(cur) in seen: + break + seen.add(id(cur)) + if isinstance(cur, IndentedBlock): + prev.add_parse_action( + lambda s, l, t, cur_=cur: setattr( + cur_, "parent_anchor", col(l, s) + ) + ) + break + subs = cur.recurse() + next_first = next(iter(subs), None) + if next_first is None: + break + cur = typing.cast(ParserElement, next_first) + + self._may_return_empty = all(e.mayReturnEmpty for e in self.exprs) + return self + + def parseImpl(self, instring, loc, do_actions=True): + # pass False as callPreParse arg to _parse for first element, since we already + # pre-parsed the string as part of our And pre-parsing + loc, resultlist = self.exprs[0]._parse( + instring, loc, do_actions, callPreParse=False + ) + errorStop = False + for e in self.exprs[1:]: + # if isinstance(e, And._ErrorStop): + if type(e) is And._ErrorStop: + errorStop = True + continue + if errorStop: + try: + loc, exprtokens = e._parse(instring, loc, do_actions) + except ParseSyntaxException: + raise + except ParseBaseException as pe: + pe.__traceback__ = None + raise ParseSyntaxException._from_exception(pe) + except IndexError: + raise ParseSyntaxException( + instring, len(instring), self.errmsg, self + ) + else: + loc, exprtokens = e._parse(instring, loc, do_actions) + resultlist += exprtokens + return loc, resultlist + + def __iadd__(self, other): + if isinstance(other, str_type): + other = self._literalStringClass(other) + if not isinstance(other, ParserElement): + return NotImplemented + return self.append(other) # And([self, other]) + + def _checkRecursion(self, parseElementList): + subRecCheckList = parseElementList[:] + [self] + for e in self.exprs: + e._checkRecursion(subRecCheckList) + if not e.mayReturnEmpty: + break + + def _generateDefaultName(self) -> str: + inner = " ".join(str(e) for e in self.exprs) + # strip off redundant inner {}'s + while len(inner) > 1 and inner[0 :: len(inner) - 1] == "{}": + inner = inner[1:-1] + return f"{{{inner}}}" + + +class Or(ParseExpression): + """Requires that at least one :class:`ParserElement` is found. If + two expressions match, the expression that matches the longest + string will be used. May be constructed using the ``'^'`` + operator. + + Example: + + .. testcode:: + + # construct Or using '^' operator + + number = Word(nums) ^ Combine(Word(nums) + '.' + Word(nums)) + print(number.search_string("123 3.1416 789")) + + prints: + + .. testoutput:: + + [['123'], ['3.1416'], ['789']] + """ + + def __init__( + self, exprs: typing.Iterable[ParserElement], savelist: bool = False + ) -> None: + super().__init__(exprs, savelist) + if self.exprs: + self._may_return_empty = any(e.mayReturnEmpty for e in self.exprs) + self.skipWhitespace = all(e.skipWhitespace for e in self.exprs) + else: + self._may_return_empty = True + + def streamline(self) -> ParserElement: + super().streamline() + if self.exprs: + self._may_return_empty = any(e.mayReturnEmpty for e in self.exprs) + self.saveAsList = any(e.saveAsList for e in self.exprs) + self.skipWhitespace = all( + e.skipWhitespace and not isinstance(e, White) for e in self.exprs + ) + else: + self.saveAsList = False + return self + + def parseImpl(self, instring, loc, do_actions=True) -> ParseImplReturnType: + maxExcLoc = -1 + maxException = None + matches: list[tuple[int, ParserElement]] = [] + fatals: list[ParseFatalException] = [] + if all(e.callPreparse for e in self.exprs): + loc = self.preParse(instring, loc) + for e in self.exprs: + try: + loc2 = e.try_parse(instring, loc, raise_fatal=True) + except ParseFatalException as pfe: + pfe.__traceback__ = None + pfe.parser_element = e + fatals.append(pfe) + maxException = None + maxExcLoc = -1 + except ParseException as err: + if not fatals: + err.__traceback__ = None + if err.loc > maxExcLoc: + maxException = err + maxExcLoc = err.loc + except IndexError: + if len(instring) > maxExcLoc: + maxException = ParseException( + instring, len(instring), e.errmsg, self + ) + maxExcLoc = len(instring) + else: + # save match among all matches, to retry longest to shortest + matches.append((loc2, e)) + + if matches: + # re-evaluate all matches in descending order of length of match, in case attached actions + # might change whether or how much they match of the input. + matches.sort(key=itemgetter(0), reverse=True) + + if not do_actions: + # no further conditions or parse actions to change the selection of + # alternative, so the first match will be the best match + best_expr = matches[0][1] + return best_expr._parse(instring, loc, do_actions) + + longest: tuple[int, typing.Optional[ParseResults]] = -1, None + for loc1, expr1 in matches: + if loc1 <= longest[0]: + # already have a longer match than this one will deliver, we are done + return longest + + try: + loc2, toks = expr1._parse(instring, loc, do_actions) + except ParseException as err: + err.__traceback__ = None + if err.loc > maxExcLoc: + maxException = err + maxExcLoc = err.loc + else: + if loc2 >= loc1: + return loc2, toks + # didn't match as much as before + elif loc2 > longest[0]: + longest = loc2, toks + + if longest != (-1, None): + return longest + + if fatals: + if len(fatals) > 1: + fatals.sort(key=lambda e: -e.loc) + if fatals[0].loc == fatals[1].loc: + fatals.sort(key=lambda e: (-e.loc, -len(str(e.parser_element)))) + max_fatal = fatals[0] + raise max_fatal + + if maxException is not None: + # infer from this check that all alternatives failed at the current position + # so emit this collective error message instead of any single error message + parse_start_loc = self.preParse(instring, loc) + if maxExcLoc == parse_start_loc: + maxException.msg = self.errmsg or "" + raise maxException + + raise ParseException(instring, loc, "no defined alternatives to match", self) + + def __ixor__(self, other): + if isinstance(other, str_type): + other = self._literalStringClass(other) + if not isinstance(other, ParserElement): + return NotImplemented + return self.append(other) # Or([self, other]) + + def _generateDefaultName(self) -> str: + return f"{{{' ^ '.join(str(e) for e in self.exprs)}}}" + + def _setResultsName(self, name, list_all_matches=False) -> ParserElement: + if ( + __diag__.warn_multiple_tokens_in_named_alternation + and Diagnostics.warn_multiple_tokens_in_named_alternation + not in self.suppress_warnings_ + ): + if any( + isinstance(e, And) + and Diagnostics.warn_multiple_tokens_in_named_alternation + not in e.suppress_warnings_ + for e in self.exprs + ): + warning = ( + "warn_multiple_tokens_in_named_alternation:" + f" setting results name {name!r} on {type(self).__name__} expression" + " will return a list of all parsed tokens in an And alternative," + " in prior versions only the first token was returned; enclose" + " contained argument in Group" + ) + warnings.warn(warning, PyparsingDiagnosticWarning, stacklevel=3) + + return super()._setResultsName(name, list_all_matches) + + +class MatchFirst(ParseExpression): + """Requires that at least one :class:`ParserElement` is found. If + more than one expression matches, the first one listed is the one that will + match. May be constructed using the ``'|'`` operator. + + Example: Construct MatchFirst using '|' operator + + .. doctest:: + + # watch the order of expressions to match + >>> number = Word(nums) | Combine(Word(nums) + '.' + Word(nums)) + >>> print(number.search_string("123 3.1416 789")) # Fail! + [['123'], ['3'], ['1416'], ['789']] + + # put more selective expression first + >>> number = Combine(Word(nums) + '.' + Word(nums)) | Word(nums) + >>> print(number.search_string("123 3.1416 789")) # Better + [['123'], ['3.1416'], ['789']] + """ + + def __init__( + self, exprs: typing.Iterable[ParserElement], savelist: bool = False + ) -> None: + super().__init__(exprs, savelist) + if self.exprs: + self._may_return_empty = any(e.mayReturnEmpty for e in self.exprs) + self.skipWhitespace = all(e.skipWhitespace for e in self.exprs) + else: + self._may_return_empty = True + + def streamline(self) -> ParserElement: + if self.streamlined: + return self + + super().streamline() + if self.exprs: + self.saveAsList = any(e.saveAsList for e in self.exprs) + self._may_return_empty = any(e.mayReturnEmpty for e in self.exprs) + self.skipWhitespace = all( + e.skipWhitespace and not isinstance(e, White) for e in self.exprs + ) + else: + self.saveAsList = False + self._may_return_empty = True + return self + + def parseImpl(self, instring, loc, do_actions=True) -> ParseImplReturnType: + maxExcLoc = -1 + maxException = None + + for e in self.exprs: + try: + return e._parse(instring, loc, do_actions) + except ParseFatalException as pfe: + pfe.__traceback__ = None + pfe.parser_element = e + raise + except ParseException as err: + if err.loc > maxExcLoc: + maxException = err + maxExcLoc = err.loc + except IndexError: + if len(instring) > maxExcLoc: + maxException = ParseException( + instring, len(instring), e.errmsg, self + ) + maxExcLoc = len(instring) + + if maxException is not None: + # infer from this check that all alternatives failed at the current position + # so emit this collective error message instead of any individual error message + parse_start_loc = self.preParse(instring, loc) + if maxExcLoc == parse_start_loc: + maxException.msg = self.errmsg or "" + raise maxException + + raise ParseException(instring, loc, "no defined alternatives to match", self) + + def __ior__(self, other): + if isinstance(other, str_type): + other = self._literalStringClass(other) + if not isinstance(other, ParserElement): + return NotImplemented + return self.append(other) # MatchFirst([self, other]) + + def _generateDefaultName(self) -> str: + return f"{{{' | '.join(str(e) for e in self.exprs)}}}" + + def _setResultsName(self, name, list_all_matches=False) -> ParserElement: + if ( + __diag__.warn_multiple_tokens_in_named_alternation + and Diagnostics.warn_multiple_tokens_in_named_alternation + not in self.suppress_warnings_ + ): + if any( + isinstance(e, And) + and Diagnostics.warn_multiple_tokens_in_named_alternation + not in e.suppress_warnings_ + for e in self.exprs + ): + warning = ( + "warn_multiple_tokens_in_named_alternation:" + f" setting results name {name!r} on {type(self).__name__} expression" + " will return a list of all parsed tokens in an And alternative," + " in prior versions only the first token was returned; enclose" + " contained argument in Group" + ) + warnings.warn(warning, PyparsingDiagnosticWarning, stacklevel=3) + + return super()._setResultsName(name, list_all_matches) + + +class Each(ParseExpression): + """Requires all given :class:`ParserElement` s to be found, but in + any order. Expressions may be separated by whitespace. + + May be constructed using the ``'&'`` operator. + + Example: + + .. testcode:: + + color = one_of("RED ORANGE YELLOW GREEN BLUE PURPLE BLACK WHITE BROWN") + shape_type = one_of("SQUARE CIRCLE TRIANGLE STAR HEXAGON OCTAGON") + integer = Word(nums) + shape_attr = "shape:" + shape_type("shape") + posn_attr = "posn:" + Group(integer("x") + ',' + integer("y"))("posn") + color_attr = "color:" + color("color") + size_attr = "size:" + integer("size") + + # use Each (using operator '&') to accept attributes in any order + # (shape and posn are required, color and size are optional) + shape_spec = shape_attr & posn_attr & Opt(color_attr) & Opt(size_attr) + + shape_spec.run_tests(''' + shape: SQUARE color: BLACK posn: 100, 120 + shape: CIRCLE size: 50 color: BLUE posn: 50,80 + color:GREEN size:20 shape:TRIANGLE posn:20,40 + ''' + ) + + prints: + + .. testoutput:: + :options: +NORMALIZE_WHITESPACE + + + shape: SQUARE color: BLACK posn: 100, 120 + ['shape:', 'SQUARE', 'color:', 'BLACK', 'posn:', ['100', ',', '120']] + - color: 'BLACK' + - posn: ['100', ',', '120'] + - x: '100' + - y: '120' + - shape: 'SQUARE' + ... + + shape: CIRCLE size: 50 color: BLUE posn: 50,80 + ['shape:', 'CIRCLE', 'size:', '50', 'color:', 'BLUE', + 'posn:', ['50', ',', '80']] + - color: 'BLUE' + - posn: ['50', ',', '80'] + - x: '50' + - y: '80' + - shape: 'CIRCLE' + - size: '50' + ... + + color:GREEN size:20 shape:TRIANGLE posn:20,40 + ['color:', 'GREEN', 'size:', '20', 'shape:', 'TRIANGLE', + 'posn:', ['20', ',', '40']] + - color: 'GREEN' + - posn: ['20', ',', '40'] + - x: '20' + - y: '40' + - shape: 'TRIANGLE' + - size: '20' + ... + """ + + def __init__( + self, exprs: typing.Iterable[ParserElement], savelist: bool = True + ) -> None: + super().__init__(exprs, savelist) + if self.exprs: + self._may_return_empty = all(e.mayReturnEmpty for e in self.exprs) + else: + self._may_return_empty = True + self.skipWhitespace = True + self.initExprGroups = True + self.saveAsList = True + + def __iand__(self, other): + if isinstance(other, str_type): + other = self._literalStringClass(other) + if not isinstance(other, ParserElement): + return NotImplemented + return self.append(other) # Each([self, other]) + + def streamline(self) -> ParserElement: + super().streamline() + if self.exprs: + self._may_return_empty = all(e.mayReturnEmpty for e in self.exprs) + else: + self._may_return_empty = True + return self + + def parseImpl(self, instring, loc, do_actions=True) -> ParseImplReturnType: + if self.initExprGroups: + self.opt1map = dict( + (id(e.expr), e) for e in self.exprs if isinstance(e, Opt) + ) + opt1 = [e.expr for e in self.exprs if isinstance(e, Opt)] + opt2 = [ + e + for e in self.exprs + if e.mayReturnEmpty and not isinstance(e, (Opt, Regex, ZeroOrMore)) + ] + self.optionals = opt1 + opt2 + self.multioptionals = [ + e.expr.set_results_name(e.resultsName, list_all_matches=True) + for e in self.exprs + if isinstance(e, _MultipleMatch) + ] + self.multirequired = [ + e.expr.set_results_name(e.resultsName, list_all_matches=True) + for e in self.exprs + if isinstance(e, OneOrMore) + ] + self.required = [ + e for e in self.exprs if not isinstance(e, (Opt, ZeroOrMore, OneOrMore)) + ] + self.required += self.multirequired + self.initExprGroups = False + + tmpLoc = loc + tmpReqd = self.required[:] + tmpOpt = self.optionals[:] + multis = self.multioptionals[:] + matchOrder: list[ParserElement] = [] + + keepMatching = True + failed: list[ParserElement] = [] + fatals: list[ParseFatalException] = [] + while keepMatching: + tmpExprs = tmpReqd + tmpOpt + multis + failed.clear() + fatals.clear() + for e in tmpExprs: + try: + tmpLoc = e.try_parse(instring, tmpLoc, raise_fatal=True) + except ParseFatalException as pfe: + pfe.__traceback__ = None + pfe.parser_element = e + fatals.append(pfe) + failed.append(e) + except ParseException: + failed.append(e) + else: + matchOrder.append(self.opt1map.get(id(e), e)) + if e in tmpReqd: + tmpReqd.remove(e) + elif e in tmpOpt: + tmpOpt.remove(e) + if len(failed) == len(tmpExprs): + keepMatching = False + + # look for any ParseFatalExceptions + if fatals: + if len(fatals) > 1: + fatals.sort(key=lambda e: -e.loc) + if fatals[0].loc == fatals[1].loc: + fatals.sort(key=lambda e: (-e.loc, -len(str(e.parser_element)))) + max_fatal = fatals[0] + raise max_fatal + + if tmpReqd: + missing = ", ".join([str(e) for e in tmpReqd]) + raise ParseException( + instring, + loc, + f"Missing one or more required elements ({missing})", + ) + + # add any unmatched Opts, in case they have default values defined + matchOrder += [e for e in self.exprs if isinstance(e, Opt) and e.expr in tmpOpt] + + total_results = ParseResults([]) + for e in matchOrder: + loc, results = e._parse(instring, loc, do_actions) + total_results += results + + return loc, total_results + + def _generateDefaultName(self) -> str: + return f"{{{' & '.join(str(e) for e in self.exprs)}}}" + + +class ParseElementEnhance(ParserElement): + """Abstract subclass of :class:`ParserElement`, for combining and + post-processing parsed tokens. + """ + + def __init__(self, expr: Union[ParserElement, str], savelist: bool = False) -> None: + super().__init__(savelist) + if isinstance(expr, str_type): + expr_str = typing.cast(str, expr) + if issubclass(self._literalStringClass, Token): + expr = self._literalStringClass(expr_str) # type: ignore[call-arg] + elif issubclass(type(self), self._literalStringClass): + expr = Literal(expr_str) + else: + expr = self._literalStringClass(Literal(expr_str)) # type: ignore[assignment, call-arg] + expr = typing.cast(ParserElement, expr) + self.expr = expr + if expr is not None: + self.mayIndexError = expr.mayIndexError + self._may_return_empty = expr.mayReturnEmpty + self.set_whitespace_chars( + expr.whiteChars, copy_defaults=expr.copyDefaultWhiteChars + ) + self.skipWhitespace = expr.skipWhitespace + self.saveAsList = expr.saveAsList + self.callPreparse = expr.callPreparse + self.ignoreExprs.extend(expr.ignoreExprs) + + def recurse(self) -> list[ParserElement]: + return [self.expr] if self.expr is not None else [] + + def parseImpl(self, instring, loc, do_actions=True): + if self.expr is None: + raise ParseException(instring, loc, "No expression defined", self) + + try: + return self.expr._parse(instring, loc, do_actions, callPreParse=False) + except ParseSyntaxException: + raise + except ParseBaseException as pbe: + pbe.pstr = pbe.pstr or instring + pbe.loc = pbe.loc or loc + pbe.parser_element = pbe.parser_element or self + if not isinstance(self, Forward) and self.customName is not None: + if self.errmsg: + pbe.msg = self.errmsg + raise + + def leave_whitespace(self, recursive: bool = True) -> ParserElement: + """ + Extends ``leave_whitespace`` defined in base class, and also invokes ``leave_whitespace`` on + the contained expression. + """ + super().leave_whitespace(recursive) + + if recursive: + if self.expr is not None: + self.expr = self.expr.copy() + self.expr.leave_whitespace(recursive) + return self + + def ignore_whitespace(self, recursive: bool = True) -> ParserElement: + """ + Extends ``ignore_whitespace`` defined in base class, and also invokes ``ignore_whitespace`` on + the contained expression. + """ + super().ignore_whitespace(recursive) + + if recursive: + if self.expr is not None: + self.expr = self.expr.copy() + self.expr.ignore_whitespace(recursive) + return self + + def ignore(self, other) -> ParserElement: + """ + Define expression to be ignored (e.g., comments) while doing pattern + matching; may be called repeatedly, to define multiple comment or other + ignorable patterns. + """ + if not isinstance(other, Suppress) or other not in self.ignoreExprs: + super().ignore(other) + if self.expr is not None: + self.expr.ignore(self.ignoreExprs[-1]) + + return self + + def streamline(self) -> ParserElement: + super().streamline() + if self.expr is not None: + self.expr.streamline() + return self + + def _checkRecursion(self, parseElementList): + if self in parseElementList: + raise RecursiveGrammarException(parseElementList + [self]) + subRecCheckList = parseElementList[:] + [self] + if self.expr is not None: + self.expr._checkRecursion(subRecCheckList) + + def validate(self, validateTrace=None) -> None: + warnings.warn( + "ParserElement.validate() is deprecated, and should not be used to check for left recursion", + PyparsingDeprecationWarning, + stacklevel=2, + ) + if validateTrace is None: + validateTrace = [] + tmp = validateTrace[:] + [self] + if self.expr is not None: + self.expr.validate(tmp) + self._checkRecursion([]) + + def _generateDefaultName(self) -> str: + return f"{type(self).__name__}:({self.expr})" + + # Compatibility synonyms + # fmt: off + leaveWhitespace = replaced_by_pep8("leaveWhitespace", leave_whitespace) + ignoreWhitespace = replaced_by_pep8("ignoreWhitespace", ignore_whitespace) + # fmt: on + + +class IndentedBlock(ParseElementEnhance): + """ + Expression to match one or more expressions at a given indentation level. + Useful for parsing text where structure is implied by indentation (like Python source code). + + Example: + + .. testcode:: + + ''' + BNF: + statement ::= assignment_stmt | if_stmt + assignment_stmt ::= identifier '=' rvalue + rvalue ::= identifier | integer + if_stmt ::= 'if' bool_condition block + block ::= ([indent] statement)... + identifier ::= [A..Za..z] + integer ::= [0..9]... + bool_condition ::= 'TRUE' | 'FALSE' + ''' + + IF, TRUE, FALSE = Keyword.using_each("IF TRUE FALSE".split()) + + statement = Forward() + identifier = Char(alphas) + integer = Word(nums).add_parse_action(lambda t: int(t[0])) + rvalue = identifier | integer + assignment_stmt = identifier + "=" + rvalue + + if_stmt = IF + (TRUE | FALSE) + IndentedBlock(statement) + + statement <<= Group(assignment_stmt | if_stmt) + + result = if_stmt.parse_string(''' + IF TRUE + a = 1000 + b = 2000 + IF FALSE + z = 100 + ''') + print(result.dump()) + + .. testoutput:: + + ['IF', 'TRUE', [['a', '=', 1000], ['b', '=', 2000], ['IF', 'FALSE', [['z', '=', 100]]]]] + [0]: + IF + [1]: + TRUE + [2]: + [['a', '=', 1000], ['b', '=', 2000], ['IF', 'FALSE', [['z', '=', 100]]]] + [0]: + ['a', '=', 1000] + [1]: + ['b', '=', 2000] + [2]: + ['IF', 'FALSE', [['z', '=', 100]]] + [0]: + IF + [1]: + FALSE + [2]: + [['z', '=', 100]] + [0]: + ['z', '=', 100] + """ + + class _Indent(Empty): + def __init__(self, ref_col: int) -> None: + super().__init__() + self.errmsg = f"expected indent at column {ref_col}" + self.add_condition(lambda s, l, t: col(l, s) == ref_col) + + class _IndentGreater(Empty): + def __init__(self, ref_col: int) -> None: + super().__init__() + self.errmsg = f"expected indent at column greater than {ref_col}" + self.add_condition(lambda s, l, t: col(l, s) > ref_col) + + def __init__( + self, expr: ParserElement, *, recursive: bool = False, grouped: bool = True + ) -> None: + super().__init__(expr, savelist=True) + # if recursive: + # raise NotImplementedError("IndentedBlock with recursive is not implemented") + self._recursive = recursive + self._grouped = grouped + self.parent_anchor = 1 + + def parseImpl(self, instring, loc, do_actions=True) -> ParseImplReturnType: + # advance parse position to non-whitespace by using an Empty() + # this should be the column to be used for all subsequent indented lines + anchor_loc = Empty().preParse(instring, loc) + + # see if self.expr matches at the current location - if not it will raise an exception + # and no further work is necessary + self.expr.try_parse(instring, anchor_loc, do_actions=do_actions) + + indent_col = col(anchor_loc, instring) + peer_detect_expr = self._Indent(indent_col) + + inner_expr = Empty() + peer_detect_expr + self.expr + if self._recursive: + sub_indent = self._IndentGreater(indent_col) + nested_block = IndentedBlock( + self.expr, recursive=self._recursive, grouped=self._grouped + ) + nested_block.set_debug(self.debug) + nested_block.parent_anchor = indent_col + inner_expr += Opt(sub_indent + nested_block) + + inner_expr.set_name(f"inner {hex(id(inner_expr))[-4:].upper()}@{indent_col}") + block = OneOrMore(inner_expr) + + trailing_undent = self._Indent(self.parent_anchor) | StringEnd() + + if self._grouped: + wrapper = Group + else: + wrapper = lambda expr: expr # type: ignore[misc, assignment] + return (wrapper(block) + Optional(trailing_undent)).parseImpl( + instring, anchor_loc, do_actions + ) + + +class AtStringStart(ParseElementEnhance): + """Matches if expression matches at the beginning of the parse + string:: + + AtStringStart(Word(nums)).parse_string("123") + # prints ["123"] + + AtStringStart(Word(nums)).parse_string(" 123") + # raises ParseException + """ + + def __init__(self, expr: Union[ParserElement, str]) -> None: + super().__init__(expr) + self.callPreparse = False + + def parseImpl(self, instring, loc, do_actions=True) -> ParseImplReturnType: + if loc != 0: + raise ParseException(instring, loc, "not found at string start") + return super().parseImpl(instring, loc, do_actions) + + +class AtLineStart(ParseElementEnhance): + r"""Matches if an expression matches at the beginning of a line within + the parse string + + Example: + + .. testcode:: + + test = '''\ + BBB this line + BBB and this line + BBB but not this one + A BBB and definitely not this one + ''' + + for t in (AtLineStart('BBB') + rest_of_line).search_string(test): + print(t) + + prints: + + .. testoutput:: + + ['BBB', ' this line'] + ['BBB', ' and this line'] + """ + + def __init__(self, expr: Union[ParserElement, str]) -> None: + super().__init__(expr) + self.callPreparse = False + + def parseImpl(self, instring, loc, do_actions=True) -> ParseImplReturnType: + if col(loc, instring) != 1: + raise ParseException(instring, loc, "not found at line start") + return super().parseImpl(instring, loc, do_actions) + + +class FollowedBy(ParseElementEnhance): + """Lookahead matching of the given parse expression. + ``FollowedBy`` does *not* advance the parsing position within + the input string, it only verifies that the specified parse + expression matches at the current position. ``FollowedBy`` + always returns a null token list. If any results names are defined + in the lookahead expression, those *will* be returned for access by + name. + + Example: + + .. testcode:: + + # use FollowedBy to match a label only if it is followed by a ':' + data_word = Word(alphas) + label = data_word + FollowedBy(':') + attr_expr = Group( + label + Suppress(':') + + OneOrMore(data_word, stop_on=label).set_parse_action(' '.join) + ) + + attr_expr[1, ...].parse_string( + "shape: SQUARE color: BLACK posn: upper left").pprint() + + prints: + + .. testoutput:: + + [['shape', 'SQUARE'], ['color', 'BLACK'], ['posn', 'upper left']] + """ + + def __init__(self, expr: Union[ParserElement, str]) -> None: + super().__init__(expr) + self._may_return_empty = True + + def parseImpl(self, instring, loc, do_actions=True) -> ParseImplReturnType: + # by using self._expr.parse and deleting the contents of the returned ParseResults list + # we keep any named results that were defined in the FollowedBy expression + _, ret = self.expr._parse(instring, loc, do_actions=do_actions) + del ret[:] + + return loc, ret + + +class PrecededBy(ParseElementEnhance): + """Lookbehind matching of the given parse expression. + ``PrecededBy`` does not advance the parsing position within the + input string, it only verifies that the specified parse expression + matches prior to the current position. ``PrecededBy`` always + returns a null token list, but if a results name is defined on the + given expression, it is returned. + + Parameters: + + - ``expr`` - expression that must match prior to the current parse + location + - ``retreat`` - (default= ``None``) - (int) maximum number of characters + to lookbehind prior to the current parse location + + If the lookbehind expression is a string, :class:`Literal`, + :class:`Keyword`, or a :class:`Word` or :class:`CharsNotIn` + with a specified exact or maximum length, then the retreat + parameter is not required. Otherwise, retreat must be specified to + give a maximum number of characters to look back from + the current parse position for a lookbehind match. + + Example: + + .. testcode:: + + # VB-style variable names with type prefixes + int_var = PrecededBy("#") + pyparsing_common.identifier + str_var = PrecededBy("$") + pyparsing_common.identifier + """ + + def __init__(self, expr: Union[ParserElement, str], retreat: int = 0) -> None: + super().__init__(expr) + self.expr = self.expr().leave_whitespace() + self._may_return_empty = True + self.mayIndexError = False + self.exact = False + if isinstance(expr, str_type): + expr = typing.cast(str, expr) + retreat = len(expr) + self.exact = True + elif isinstance(expr, (Literal, Keyword)): + retreat = expr.matchLen + self.exact = True + elif isinstance(expr, (Word, CharsNotIn)) and expr.maxLen != _MAX_INT: + retreat = expr.maxLen + self.exact = True + elif isinstance(expr, PositionToken): + retreat = 0 + self.exact = True + self.retreat = retreat + self.errmsg = f"not preceded by {expr}" + self.skipWhitespace = False + self.parseAction.append(lambda s, l, t: t.__delitem__(slice(None, None))) + + def parseImpl(self, instring, loc=0, do_actions=True) -> ParseImplReturnType: + if self.exact: + if loc < self.retreat: + raise ParseException(instring, loc, self.errmsg, self) + start = loc - self.retreat + _, ret = self.expr._parse(instring, start) + return loc, ret + + # retreat specified a maximum lookbehind window, iterate + test_expr = self.expr + StringEnd() + instring_slice = instring[max(0, loc - self.retreat) : loc] + last_expr: ParseBaseException = ParseException(instring, loc, self.errmsg, self) + + for offset in range(1, min(loc, self.retreat + 1) + 1): + try: + # print('trying', offset, instring_slice, repr(instring_slice[loc - offset:])) + _, ret = test_expr._parse(instring_slice, len(instring_slice) - offset) + except ParseBaseException as pbe: + last_expr = pbe + else: + break + else: + raise last_expr + + return loc, ret + + +class Located(ParseElementEnhance): + """ + Decorates a returned token with its starting and ending + locations in the input string. + + This helper adds the following results names: + + - ``locn_start`` - location where matched expression begins + - ``locn_end`` - location where matched expression ends + - ``value`` - the actual parsed results + + Be careful if the input text contains ```` characters, you + may want to call :class:`ParserElement.parse_with_tabs` + + Example: + + .. testcode:: + + wd = Word(alphas) + for match in Located(wd).search_string("ljsdf123lksdjjf123lkkjj1222"): + print(match) + + prints: + + .. testoutput:: + + [0, ['ljsdf'], 5] + [8, ['lksdjjf'], 15] + [18, ['lkkjj'], 23] + """ + + def parseImpl(self, instring, loc, do_actions=True) -> ParseImplReturnType: + start = loc + loc, tokens = self.expr._parse(instring, start, do_actions, callPreParse=False) + ret_tokens = ParseResults([start, tokens, loc]) + ret_tokens["locn_start"] = start + ret_tokens["value"] = tokens + ret_tokens["locn_end"] = loc + if self.resultsName: + # must return as a list, so that the name will be attached to the complete group + return loc, [ret_tokens] + else: + return loc, ret_tokens + + +class NotAny(ParseElementEnhance): + """ + Lookahead to disallow matching with the given parse expression. + ``NotAny`` does *not* advance the parsing position within the + input string, it only verifies that the specified parse expression + does *not* match at the current position. Also, ``NotAny`` does + *not* skip over leading whitespace. ``NotAny`` always returns + a null token list. May be constructed using the ``'~'`` operator. + + Example: + + .. testcode:: + + AND, OR, NOT = map(CaselessKeyword, "AND OR NOT".split()) + + # take care not to mistake keywords for identifiers + ident = ~(AND | OR | NOT) + Word(alphas) + boolean_term = Opt(NOT) + ident + + # very crude boolean expression - to support parenthesis groups and + # operation hierarchy, use infix_notation + boolean_expr = boolean_term + ((AND | OR) + boolean_term)[...] + + # integers that are followed by "." are actually floats + integer = Word(nums) + ~Char(".") + """ + + def __init__(self, expr: Union[ParserElement, str]) -> None: + super().__init__(expr) + # do NOT use self.leave_whitespace(), don't want to propagate to exprs + # self.leave_whitespace() + self.skipWhitespace = False + + self._may_return_empty = True + self.errmsg = f"Found unwanted token, {self.expr}" + + def parseImpl(self, instring, loc, do_actions=True) -> ParseImplReturnType: + if self.expr.can_parse_next(instring, loc, do_actions=do_actions): + raise ParseException(instring, loc, self.errmsg, self) + return loc, [] + + def _generateDefaultName(self) -> str: + return f"~{{{self.expr}}}" + + +class _MultipleMatch(ParseElementEnhance): + def __init__( + self, + expr: Union[str, ParserElement], + stop_on: typing.Optional[Union[ParserElement, str]] = None, + max: typing.Optional[int] = None, + **kwargs, + ) -> None: + stopOn: typing.Optional[Union[ParserElement, str]] = deprecate_argument( + kwargs, "stopOn", None + ) + + super().__init__(expr) + if max is not None and max <= 0: + raise ValueError("max must be greater than 0") + stopOn = stopOn or stop_on + self.saveAsList = True + self.max_count = max + ender = stopOn + if isinstance(ender, str_type): + ender = self._literalStringClass(ender) + self.stopOn(ender) + + def stop_on(self, ender) -> ParserElement: + if isinstance(ender, str_type): + ender = self._literalStringClass(ender) + self.not_ender = ~ender if ender is not None else None + return self + + stopOn = stop_on + + def parseImpl(self, instring, loc, do_actions=True) -> ParseImplReturnType: + self_expr_parse = self.expr._parse + self_skip_ignorables = self._skipIgnorables + check_ender = False + if self.not_ender is not None: + try_not_ender = self.not_ender.try_parse + check_ender = True + + # must be at least one (but first see if we are the stopOn sentinel; + # if so, fail) + if check_ender: + try_not_ender(instring, loc) + loc, tokens = self_expr_parse(instring, loc, do_actions) + match_count = 1 + try: + hasIgnoreExprs = not not self.ignoreExprs + while self.max_count is None or match_count < self.max_count: + if check_ender: + try_not_ender(instring, loc) + if hasIgnoreExprs: + preloc = self_skip_ignorables(instring, loc) + else: + preloc = loc + loc, tmptokens = self_expr_parse(instring, preloc, do_actions) + tokens += tmptokens + match_count += 1 + except (ParseException, IndexError): + pass + + return loc, tokens + + def _setResultsName(self, name, list_all_matches=False) -> ParserElement: + if ( + __diag__.warn_ungrouped_named_tokens_in_collection + and Diagnostics.warn_ungrouped_named_tokens_in_collection + not in self.suppress_warnings_ + ): + for e in [self.expr] + self.expr.recurse(): + if ( + isinstance(e, ParserElement) + and e.resultsName + and ( + Diagnostics.warn_ungrouped_named_tokens_in_collection + not in e.suppress_warnings_ + ) + ): + warning = ( + "warn_ungrouped_named_tokens_in_collection:" + f" setting results name {name!r} on {type(self).__name__} expression" + f" collides with {e.resultsName!r} on contained expression" + ) + warnings.warn(warning, PyparsingDiagnosticWarning, stacklevel=3) + break + + return super()._setResultsName(name, list_all_matches) + + +class OneOrMore(_MultipleMatch): + """ + Repetition of one or more of the given expression. + + Parameters: + + - ``expr`` - expression that must match one or more times + - ``stop_on`` - (default= ``None``) - expression for a terminating sentinel + (only required if the sentinel would ordinarily match the repetition + expression) + - ``max`` - (default= ``None``) - maximum number times to match ``expr`` + (does not raise an exception if the expression occurs more than ``max`` + times, simply limits the number of matches to make) + + Example: + + .. doctest:: + + >>> data_word = Word(alphas) + >>> label = data_word + FollowedBy(':') + >>> attr_expr = Group( + ... label + Suppress(':') + ... + OneOrMore(data_word).set_parse_action(' '.join)) + + >>> text = "shape: SQUARE posn: upper left color: BLACK" + + # Fail! read 'posn' as data instead of next label + >>> attr_expr[1, ...].parse_string(text).pprint() + [['shape', 'SQUARE posn']] + + # use stop_on attribute for OneOrMore + # to avoid reading label string as part of the data + >>> attr_expr = Group( + ... label + Suppress(':') + ... + OneOrMore( + ... data_word, stop_on=label).set_parse_action(' '.join)) + >>> OneOrMore(attr_expr).parse_string(text).pprint() # Better + [['shape', 'SQUARE'], ['posn', 'upper left'], ['color', 'BLACK']] + + # could also be written as + >>> (attr_expr * (1,)).parse_string(text).pprint() + [['shape', 'SQUARE'], ['posn', 'upper left'], ['color', 'BLACK']] + """ + + def _generateDefaultName(self) -> str: + return f"{{{self.expr}}}..." + + +class ZeroOrMore(_MultipleMatch): + """ + Optional repetition of zero or more of the given expression. + + Parameters: + + - ``expr`` - expression that must match zero or more times + - ``stop_on`` - expression for a terminating sentinel + (only required if the sentinel would ordinarily match the repetition + expression) - (default= ``None``) + + Example: similar to :class:`OneOrMore` + """ + + def __init__( + self, + expr: Union[str, ParserElement], + stop_on: typing.Optional[Union[ParserElement, str]] = None, + max: typing.Optional[int] = None, + **kwargs, + ) -> None: + stopOn: Union[ParserElement, str] = deprecate_argument(kwargs, "stopOn", None) + + super().__init__(expr, stop_on=stopOn or stop_on, max=max) + self._may_return_empty = True + + def parseImpl(self, instring, loc, do_actions=True) -> ParseImplReturnType: + try: + return super().parseImpl(instring, loc, do_actions) + except (ParseException, IndexError): + return loc, ParseResults([], name=self.resultsName) + + def _generateDefaultName(self) -> str: + return f"[{self.expr}]..." + + +class DelimitedList(ParseElementEnhance): + """Helper to define a delimited list of expressions - the delimiter + defaults to ','. By default, the list elements and delimiters can + have intervening whitespace, and comments, but this can be + overridden by passing ``combine=True`` in the constructor. If + ``combine`` is set to ``True``, the matching tokens are + returned as a single token string, with the delimiters included; + otherwise, the matching tokens are returned as a list of tokens, + with the delimiters suppressed. + + If ``allow_trailing_delim`` is set to True, then the list may end with + a delimiter. + + Example: + + .. doctest:: + + >>> DelimitedList(Word(alphas)).parse_string("aa,bb,cc") + ParseResults(['aa', 'bb', 'cc'], {}) + >>> DelimitedList(Word(hexnums), delim=':', combine=True + ... ).parse_string("AA:BB:CC:DD:EE") + ParseResults(['AA:BB:CC:DD:EE'], {}) + + .. versionadded:: 3.1.0 + """ + + def __init__( + self, + expr: Union[str, ParserElement], + delim: Union[str, ParserElement] = ",", + combine: bool = False, + min: typing.Optional[int] = None, + max: typing.Optional[int] = None, + *, + allow_trailing_delim: bool = False, + ) -> None: + if isinstance(expr, str_type): + expr = ParserElement._literalStringClass(expr) + expr = typing.cast(ParserElement, expr) + + if min is not None and min < 1: + raise ValueError("min must be greater than 0") + + if max is not None and min is not None and max < min: + raise ValueError("max must be greater than, or equal to min") + + self.content = expr + self.raw_delim = str(delim) + self.delim = delim + self.combine = combine + if not combine: + self.delim = Suppress(delim) if not isinstance(delim, Suppress) else delim + self.min = min or 1 + self.max = max + self.allow_trailing_delim = allow_trailing_delim + + delim_list_expr = self.content + (self.delim + self.content) * ( + self.min - 1, + None if self.max is None else self.max - 1, + ) + if self.allow_trailing_delim: + delim_list_expr += Opt(self.delim) + + if self.combine: + delim_list_expr = Combine(delim_list_expr) + + super().__init__(delim_list_expr, savelist=True) + + def _generateDefaultName(self) -> str: + content_expr = self.content.streamline() + return f"{content_expr} [{self.raw_delim} {content_expr}]..." + + +class _NullToken: + def __bool__(self): + return False + + def __str__(self): + return "" + + +class Opt(ParseElementEnhance): + """ + Optional matching of the given expression. + + :param expr: expression that must match zero or more times + :param default: (optional) - value to be returned + if the optional expression is not found. + + Example: + + .. testcode:: + + # US postal code can be a 5-digit zip, plus optional 4-digit qualifier + zip = Combine(Word(nums, exact=5) + Opt('-' + Word(nums, exact=4))) + zip.run_tests(''' + # traditional ZIP code + 12345 + + # ZIP+4 form + 12101-0001 + + # invalid ZIP + 98765- + ''') + + prints: + + .. testoutput:: + :options: +NORMALIZE_WHITESPACE + + + # traditional ZIP code + 12345 + ['12345'] + + # ZIP+4 form + 12101-0001 + ['12101-0001'] + + # invalid ZIP + 98765- + 98765- + ^ + ParseException: Expected end of text, found '-' (at char 5), (line:1, col:6) + FAIL: Expected end of text, found '-' (at char 5), (line:1, col:6) + """ + + __optionalNotMatched = _NullToken() + + def __init__( + self, expr: Union[ParserElement, str], default: Any = __optionalNotMatched + ) -> None: + super().__init__(expr, savelist=False) + self.saveAsList = self.expr.saveAsList + self.defaultValue = default + self._may_return_empty = True + + def parseImpl(self, instring, loc, do_actions=True) -> ParseImplReturnType: + self_expr = self.expr + try: + loc, tokens = self_expr._parse( + instring, loc, do_actions, callPreParse=False + ) + except (ParseException, IndexError): + default_value = self.defaultValue + if default_value is not self.__optionalNotMatched: + if self_expr.resultsName: + tokens = ParseResults([default_value]) + tokens[self_expr.resultsName] = default_value + else: + tokens = [default_value] # type: ignore[assignment] + else: + tokens = [] # type: ignore[assignment] + return loc, tokens + + def _generateDefaultName(self) -> str: + inner = str(self.expr) + # strip off redundant inner {}'s + while len(inner) > 1 and inner[0 :: len(inner) - 1] == "{}": + inner = inner[1:-1] + return f"[{inner}]" + + +Optional = Opt + + +class SkipTo(ParseElementEnhance): + """ + Token for skipping over all undefined text until the matched + expression is found. + + :param expr: target expression marking the end of the data to be skipped + :param include: if ``True``, the target expression is also parsed + (the skipped text and target expression are returned + as a 2-element list) (default= ``False``). + + :param ignore: (default= ``None``) used to define grammars + (typically quoted strings and comments) + that might contain false matches to the target expression + + :param fail_on: (default= ``None``) define expressions that + are not allowed to be included in the skipped test; + if found before the target expression is found, + the :class:`SkipTo` is not a match + + Example: + + .. testcode:: + + report = ''' + Outstanding Issues Report - 1 Jan 2000 + + # | Severity | Description | Days Open + -----+----------+-------------------------------------------+----------- + 101 | Critical | Intermittent system crash | 6 + 94 | Cosmetic | Spelling error on Login ('log|n') | 14 + 79 | Minor | System slow when running too many reports | 47 + ''' + integer = Word(nums) + SEP = Suppress('|') + # use SkipTo to simply match everything up until the next SEP + # - ignore quoted strings, so that a '|' character inside a quoted string does not match + # - parse action will call token.strip() for each matched token, i.e., the description body + string_data = SkipTo(SEP, ignore=quoted_string) + string_data.set_parse_action(token_map(str.strip)) + ticket_expr = (integer("issue_num") + SEP + + string_data("sev") + SEP + + string_data("desc") + SEP + + integer("days_open")) + + for tkt in ticket_expr.search_string(report): + print(tkt.dump()) + + prints: + + .. testoutput:: + + ['101', 'Critical', 'Intermittent system crash', '6'] + - days_open: '6' + - desc: 'Intermittent system crash' + - issue_num: '101' + - sev: 'Critical' + ['94', 'Cosmetic', "Spelling error on Login ('log|n')", '14'] + - days_open: '14' + - desc: "Spelling error on Login ('log|n')" + - issue_num: '94' + - sev: 'Cosmetic' + ['79', 'Minor', 'System slow when running too many reports', '47'] + - days_open: '47' + - desc: 'System slow when running too many reports' + - issue_num: '79' + - sev: 'Minor' + """ + + def __init__( + self, + other: Union[ParserElement, str], + include: bool = False, + ignore: typing.Optional[Union[ParserElement, str]] = None, + fail_on: typing.Optional[Union[ParserElement, str]] = None, + **kwargs, + ) -> None: + failOn: typing.Optional[Union[ParserElement, str]] = deprecate_argument( + kwargs, "failOn", None + ) + + super().__init__(other) + failOn = failOn or fail_on + self.ignoreExpr = ignore + self._may_return_empty = True + self.mayIndexError = False + self.includeMatch = include + self.saveAsList = False + if isinstance(failOn, str_type): + self.failOn = self._literalStringClass(failOn) + else: + self.failOn = failOn + self.errmsg = f"No match found for {self.expr}" + self.ignorer = Empty().leave_whitespace() + self._update_ignorer() + + def _update_ignorer(self): + # rebuild internal ignore expr from current ignore exprs and assigned ignoreExpr + self.ignorer.ignoreExprs.clear() + for e in self.expr.ignoreExprs: + self.ignorer.ignore(e) + if self.ignoreExpr: + self.ignorer.ignore(self.ignoreExpr) + + def ignore(self, expr): + """ + Define expression to be ignored (e.g., comments) while doing pattern + matching; may be called repeatedly, to define multiple comment or other + ignorable patterns. + """ + super().ignore(expr) + self._update_ignorer() + + def parseImpl(self, instring, loc, do_actions=True): + startloc = loc + instrlen = len(instring) + self_expr_parse = self.expr._parse + self_failOn_canParseNext = ( + self.failOn.can_parse_next if self.failOn is not None else None + ) + ignorer_try_parse = self.ignorer.try_parse if self.ignorer.ignoreExprs else None + + tmploc = loc + while tmploc <= instrlen: + if self_failOn_canParseNext is not None: + # break if failOn expression matches + if self_failOn_canParseNext(instring, tmploc): + break + + if ignorer_try_parse is not None: + # advance past ignore expressions + prev_tmploc = tmploc + while 1: + try: + tmploc = ignorer_try_parse(instring, tmploc) + except ParseBaseException: + break + # see if all ignorers matched, but didn't actually ignore anything + if tmploc == prev_tmploc: + break + prev_tmploc = tmploc + + try: + self_expr_parse(instring, tmploc, do_actions=False, callPreParse=False) + except (ParseException, IndexError): + # no match, advance loc in string + tmploc += 1 + else: + # matched skipto expr, done + break + + else: + # ran off the end of the input string without matching skipto expr, fail + raise ParseException(instring, loc, self.errmsg, self) + + # build up return values + loc = tmploc + skiptext = instring[startloc:loc] + skipresult = ParseResults(skiptext) + + if self.includeMatch: + loc, mat = self_expr_parse(instring, loc, do_actions, callPreParse=False) + skipresult += mat + + return loc, skipresult + + +class Forward(ParseElementEnhance): + """ + Forward declaration of an expression to be defined later - + used for recursive grammars, such as algebraic infix notation. + When the expression is known, it is assigned to the ``Forward`` + instance using the ``'<<'`` operator. + + .. Note:: + + Take care when assigning to ``Forward`` not to overlook + precedence of operators. + + Specifically, ``'|'`` has a lower precedence than ``'<<'``, so that:: + + fwd_expr << a | b | c + + will actually be evaluated as:: + + (fwd_expr << a) | b | c + + thereby leaving b and c out as parseable alternatives. + It is recommended that you explicitly group the values + inserted into the :class:`Forward`:: + + fwd_expr << (a | b | c) + + Converting to use the ``'<<='`` operator instead will avoid this problem. + + See :meth:`ParseResults.pprint` for an example of a recursive + parser created using :class:`Forward`. + """ + + def __init__( + self, other: typing.Optional[Union[ParserElement, str]] = None + ) -> None: + self.caller_frame = traceback.extract_stack(limit=2)[0] + super().__init__(other, savelist=False) # type: ignore[arg-type] + self.lshift_line = None + + def __lshift__(self, other) -> Forward: + """ + ``'<<'`` operator overload to "inject" an expression into a :class:`Forward`. + """ + if hasattr(self, "caller_frame"): + del self.caller_frame + if isinstance(other, str_type): + other = self._literalStringClass(other) + + if not isinstance(other, ParserElement): + return NotImplemented + + self.expr = other + self.streamlined = other.streamlined + self.mayIndexError = self.expr.mayIndexError + self._may_return_empty = self.expr.mayReturnEmpty + self.set_whitespace_chars( + self.expr.whiteChars, copy_defaults=self.expr.copyDefaultWhiteChars + ) + self.skipWhitespace = self.expr.skipWhitespace + self.saveAsList = self.expr.saveAsList + self.ignoreExprs.extend(self.expr.ignoreExprs) + self.lshift_line = traceback.extract_stack(limit=2)[-2] # type: ignore[assignment] + return self + + def __ilshift__(self, other) -> Forward: + """ + ``'<<='`` operator overload to "inject" an expression into a :class:`Forward`. + """ + if not isinstance(other, ParserElement): + return NotImplemented + + return self << other + + def __or__(self, other) -> ParserElement: + caller_line = traceback.extract_stack(limit=2)[-2] + if ( + __diag__.warn_on_match_first_with_lshift_operator + and caller_line == self.lshift_line + and Diagnostics.warn_on_match_first_with_lshift_operator + not in self.suppress_warnings_ + ): + warnings.warn( + "warn_on_match_first_with_lshift_operator:" + " using '<<' operator with '|' is probably an error, use '<<='", + PyparsingDiagnosticWarning, + stacklevel=2, + ) + ret = super().__or__(other) + return ret + + def __del__(self): + # see if we are getting dropped because of '=' reassignment of var instead of '<<=' or '<<' + if ( + self.expr is None + and __diag__.warn_on_assignment_to_Forward + and Diagnostics.warn_on_assignment_to_Forward not in self.suppress_warnings_ + ): + warnings.warn_explicit( + "warn_on_assignment_to_Forward:" + " Forward defined here but no expression attached later using '<<=' or '<<'", + UserWarning, + filename=self.caller_frame.filename, + lineno=self.caller_frame.lineno, + ) + + def parseImpl(self, instring, loc, do_actions=True) -> ParseImplReturnType: + if ( + self.expr is None + and __diag__.warn_on_parse_using_empty_Forward + and Diagnostics.warn_on_parse_using_empty_Forward + not in self.suppress_warnings_ + ): + # walk stack until parse_string, scan_string, search_string, or transform_string is found + parse_fns = ( + "parse_string", + "scan_string", + "search_string", + "transform_string", + ) + tb = traceback.extract_stack(limit=200) + for i, frm in enumerate(reversed(tb), start=1): + if frm.name in parse_fns: + stacklevel = i + 1 + break + else: + stacklevel = 2 + warnings.warn( + "warn_on_parse_using_empty_Forward:" + " Forward expression was never assigned a value, will not parse any input", + PyparsingDiagnosticWarning, + stacklevel=stacklevel, + ) + if not ParserElement._left_recursion_enabled: + return super().parseImpl(instring, loc, do_actions) + + # ## Bounded Recursion algorithm ## + # Recursion only needs to be processed at ``Forward`` elements, since they are + # the only ones that can actually refer to themselves. The general idea is + # to handle recursion stepwise: We start at no recursion, then recurse once, + # recurse twice, ..., until more recursion offers no benefit (we hit the bound). + # + # The "trick" here is that each ``Forward`` gets evaluated in two contexts + # - to *match* a specific recursion level, and + # - to *search* the bounded recursion level + # and the two run concurrently. The *search* must *match* each recursion level + # to find the best possible match. This is handled by a memo table, which + # provides the previous match to the next level match attempt. + # + # See also "Left Recursion in Parsing Expression Grammars", Medeiros et al. + # + # There is a complication since we not only *parse* but also *transform* via + # actions: We do not want to run the actions too often while expanding. Thus, + # we expand using `do_actions=False` and only run `do_actions=True` if the next + # recursion level is acceptable. + with ParserElement.recursion_lock: + memo = ParserElement.recursion_memos + try: + # we are parsing at a specific recursion expansion - use it as-is + prev_loc, prev_result = memo[loc, self, do_actions] + if isinstance(prev_result, Exception): + raise prev_result + return prev_loc, prev_result.copy() + except KeyError: + act_key = (loc, self, True) + peek_key = (loc, self, False) + # we are searching for the best recursion expansion - keep on improving + # both `do_actions` cases must be tracked separately here! + prev_loc, prev_peek = memo[peek_key] = ( + loc - 1, + ParseException( + instring, loc, "Forward recursion without base case", self + ), + ) + if do_actions: + memo[act_key] = memo[peek_key] + while True: + try: + new_loc, new_peek = super().parseImpl(instring, loc, False) + except ParseException: + # we failed before getting any match - do not hide the error + if isinstance(prev_peek, Exception): + raise + new_loc, new_peek = prev_loc, prev_peek + # the match did not get better: we are done + if new_loc <= prev_loc: + if do_actions: + # replace the match for do_actions=False as well, + # in case the action did backtrack + prev_loc, prev_result = memo[peek_key] = memo[act_key] + del memo[peek_key], memo[act_key] + return prev_loc, copy.copy(prev_result) + del memo[peek_key] + return prev_loc, copy.copy(prev_peek) + # the match did get better: see if we can improve further + if do_actions: + try: + memo[act_key] = super().parseImpl(instring, loc, True) + except ParseException as e: + memo[peek_key] = memo[act_key] = (new_loc, e) + raise + prev_loc, prev_peek = memo[peek_key] = new_loc, new_peek + + def leave_whitespace(self, recursive: bool = True) -> ParserElement: + """ + Extends ``leave_whitespace`` defined in base class. + """ + self.skipWhitespace = False + return self + + def ignore_whitespace(self, recursive: bool = True) -> ParserElement: + """ + Extends ``ignore_whitespace`` defined in base class. + """ + self.skipWhitespace = True + return self + + def streamline(self) -> ParserElement: + if not self.streamlined: + self.streamlined = True + if self.expr is not None: + self.expr.streamline() + return self + + def validate(self, validateTrace=None) -> None: + warnings.warn( + "ParserElement.validate() is deprecated, and should not be used to check for left recursion", + PyparsingDeprecationWarning, + stacklevel=2, + ) + if validateTrace is None: + validateTrace = [] + + if self not in validateTrace: + tmp = validateTrace[:] + [self] + if self.expr is not None: + self.expr.validate(tmp) + self._checkRecursion([]) + + def _generateDefaultName(self) -> str: + # Avoid infinite recursion by setting a temporary _defaultName + save_default_name = self._defaultName + self._defaultName = ": ..." + + # Use the string representation of main expression. + try: + if self.expr is not None: + ret_string = str(self.expr)[:1000] + else: + ret_string = "None" + except Exception: + ret_string = "..." + + self._defaultName = save_default_name + return f"{type(self).__name__}: {ret_string}" + + def copy(self) -> ParserElement: + """ + Returns a copy of this expression. + + Generally only used internally by pyparsing. + """ + if self.expr is not None: + return super().copy() + else: + ret = Forward() + ret <<= self + return ret + + def _setResultsName(self, name, list_all_matches=False) -> ParserElement: + # fmt: off + if ( + __diag__.warn_name_set_on_empty_Forward + and Diagnostics.warn_name_set_on_empty_Forward not in self.suppress_warnings_ + and self.expr is None + ): + warning = ( + "warn_name_set_on_empty_Forward:" + f" setting results name {name!r} on {type(self).__name__} expression" + " that has no contained expression" + ) + warnings.warn(warning, PyparsingDiagnosticWarning, stacklevel=3) + # fmt: on + + return super()._setResultsName(name, list_all_matches) + + # Compatibility synonyms + # fmt: off + leaveWhitespace = replaced_by_pep8("leaveWhitespace", leave_whitespace) + ignoreWhitespace = replaced_by_pep8("ignoreWhitespace", ignore_whitespace) + # fmt: on + + +class TokenConverter(ParseElementEnhance): + """ + Abstract subclass of :class:`ParseElementEnhance`, for converting parsed results. + """ + + def __init__(self, expr: Union[ParserElement, str], savelist=False) -> None: + super().__init__(expr) # , savelist) + self.saveAsList = False + + +class Combine(TokenConverter): + """Converter to concatenate all matching tokens to a single string. + By default, the matching patterns must also be contiguous in the + input string; this can be disabled by specifying + ``'adjacent=False'`` in the constructor. + + Example: + + .. doctest:: + + >>> real = Word(nums) + '.' + Word(nums) + >>> print(real.parse_string('3.1416')) + ['3', '.', '1416'] + + >>> # will also erroneously match the following + >>> print(real.parse_string('3. 1416')) + ['3', '.', '1416'] + + >>> real = Combine(Word(nums) + '.' + Word(nums)) + >>> print(real.parse_string('3.1416')) + ['3.1416'] + + >>> # no match when there are internal spaces + >>> print(real.parse_string('3. 1416')) + Traceback (most recent call last): + ParseException: Expected W:(0123...) + """ + + def __init__( + self, + expr: ParserElement, + join_string: str = "", + adjacent: bool = True, + *, + joinString: typing.Optional[str] = None, + ) -> None: + super().__init__(expr) + joinString = joinString if joinString is not None else join_string + # suppress whitespace-stripping in contained parse expressions, but re-enable it on the Combine itself + if adjacent: + self.leave_whitespace() + self.adjacent = adjacent + self.skipWhitespace = True + self.joinString = joinString + self.callPreparse = True + + def ignore(self, other) -> ParserElement: + """ + Define expression to be ignored (e.g., comments) while doing pattern + matching; may be called repeatedly, to define multiple comment or other + ignorable patterns. + """ + if self.adjacent: + ParserElement.ignore(self, other) + else: + super().ignore(other) + return self + + def postParse(self, instring, loc, tokenlist): + retToks = tokenlist.copy() + del retToks[:] + retToks += ParseResults( + ["".join(tokenlist._asStringList(self.joinString))], modal=self.modalResults + ) + + if self.resultsName and retToks.haskeys(): + return [retToks] + else: + return retToks + + +class Group(TokenConverter): + """Converter to return the matched tokens as a list - useful for + returning tokens of :class:`ZeroOrMore` and :class:`OneOrMore` expressions. + + The optional ``aslist`` argument when set to True will return the + parsed tokens as a Python list instead of a pyparsing ParseResults. + + Example: + + .. doctest:: + + >>> ident = Word(alphas) + >>> num = Word(nums) + >>> term = ident | num + >>> func = ident + Opt(DelimitedList(term)) + >>> print(func.parse_string("fn a, b, 100")) + ['fn', 'a', 'b', '100'] + + >>> func = ident + Group(Opt(DelimitedList(term))) + >>> print(func.parse_string("fn a, b, 100")) + ['fn', ['a', 'b', '100']] + """ + + def __init__(self, expr: ParserElement, aslist: bool = False) -> None: + super().__init__(expr) + self.saveAsList = True + self._asPythonList = aslist + + def postParse(self, instring, loc, tokenlist): + if self._asPythonList: + return ParseResults.List( + tokenlist.as_list() + if isinstance(tokenlist, ParseResults) + else list(tokenlist) + ) + + return [tokenlist] + + +class Dict(TokenConverter): + """Converter to return a repetitive expression as a list, but also + as a dictionary. Each element can also be referenced using the first + token in the expression as its key. Useful for tabular report + scraping when the first column can be used as a item key. + + The optional ``asdict`` argument when set to True will return the + parsed tokens as a Python dict instead of a pyparsing ParseResults. + + Example: + + .. doctest:: + + >>> data_word = Word(alphas) + >>> label = data_word + FollowedBy(':') + + >>> attr_expr = ( + ... label + Suppress(':') + ... + OneOrMore(data_word, stop_on=label) + ... .set_parse_action(' '.join) + ... ) + + >>> text = "shape: SQUARE posn: upper left color: light blue texture: burlap" + + >>> # print attributes as plain groups + >>> print(attr_expr[1, ...].parse_string(text).dump()) + ['shape', 'SQUARE', 'posn', 'upper left', 'color', 'light blue', 'texture', 'burlap'] + + # instead of OneOrMore(expr), parse using Dict(Group(expr)[1, ...]) + # Dict will auto-assign names. + >>> result = Dict(Group(attr_expr)[1, ...]).parse_string(text) + >>> print(result.dump()) + [['shape', 'SQUARE'], ['posn', 'upper left'], ['color', 'light blue'], ['texture', 'burlap']] + - color: 'light blue' + - posn: 'upper left' + - shape: 'SQUARE' + - texture: 'burlap' + [0]: + ['shape', 'SQUARE'] + [1]: + ['posn', 'upper left'] + [2]: + ['color', 'light blue'] + [3]: + ['texture', 'burlap'] + + # access named fields as dict entries, or output as dict + >>> print(result['shape']) + SQUARE + >>> print(result.as_dict()) + {'shape': 'SQUARE', 'posn': 'upper left', 'color': 'light blue', 'texture': 'burlap'} + + See more examples at :class:`ParseResults` of accessing fields by results name. + """ + + def __init__(self, expr: ParserElement, asdict: bool = False) -> None: + super().__init__(expr) + self.saveAsList = True + self._asPythonDict = asdict + + def postParse(self, instring, loc, tokenlist): + for i, tok in enumerate(tokenlist): + if len(tok) == 0: + continue + + ikey = tok[0] + if isinstance(ikey, int): + ikey = str(ikey).strip() + + if len(tok) == 1: + tokenlist[ikey] = _ParseResultsWithOffset("", i) + + elif len(tok) == 2 and not isinstance(tok[1], ParseResults): + tokenlist[ikey] = _ParseResultsWithOffset(tok[1], i) + + else: + try: + dictvalue = tok.copy() # ParseResults(i) + except Exception: + exc = TypeError( + "could not extract dict values from parsed results" + " - Dict expression must contain Grouped expressions" + ) + raise exc from None + + del dictvalue[0] + + if len(dictvalue) != 1 or ( + isinstance(dictvalue, ParseResults) and dictvalue.haskeys() + ): + tokenlist[ikey] = _ParseResultsWithOffset(dictvalue, i) + else: + tokenlist[ikey] = _ParseResultsWithOffset(dictvalue[0], i) + + if self._asPythonDict: + return [tokenlist.as_dict()] if self.resultsName else tokenlist.as_dict() + + return [tokenlist] if self.resultsName else tokenlist + + +class Suppress(TokenConverter): + """Converter for ignoring the results of a parsed expression. + + Example: + + .. doctest:: + + >>> source = "a, b, c,d" + >>> wd = Word(alphas) + >>> wd_list1 = wd + (',' + wd)[...] + >>> print(wd_list1.parse_string(source)) + ['a', ',', 'b', ',', 'c', ',', 'd'] + + # often, delimiters that are useful during parsing are just in the + # way afterward - use Suppress to keep them out of the parsed output + >>> wd_list2 = wd + (Suppress(',') + wd)[...] + >>> print(wd_list2.parse_string(source)) + ['a', 'b', 'c', 'd'] + + # Skipped text (using '...') can be suppressed as well + >>> source = "lead in START relevant text END trailing text" + >>> start_marker = Keyword("START") + >>> end_marker = Keyword("END") + >>> find_body = Suppress(...) + start_marker + ... + end_marker + >>> print(find_body.parse_string(source)) + ['START', 'relevant text ', 'END'] + + (See also :class:`DelimitedList`.) + """ + + def __init__(self, expr: Union[ParserElement, str], savelist: bool = False) -> None: + if expr is ...: + expr = _PendingSkip(NoMatch()) + super().__init__(expr) + + def __add__(self, other) -> ParserElement: + if isinstance(self.expr, _PendingSkip): + return Suppress(SkipTo(other)) + other + + return super().__add__(other) + + def __sub__(self, other) -> ParserElement: + if isinstance(self.expr, _PendingSkip): + return Suppress(SkipTo(other)) - other + + return super().__sub__(other) + + def postParse(self, instring, loc, tokenlist): + return [] + + def suppress(self) -> ParserElement: + return self + + +# XXX: Example needs to be re-done for updated output +def trace_parse_action(f: ParseAction) -> ParseAction: + """Decorator for debugging parse actions. + + When the parse action is called, this decorator will print + ``">> entering method-name(line:, , )"``. + When the parse action completes, the decorator will print + ``"<<"`` followed by the returned value, or any exception that the parse action raised. + + Example: + + .. testsetup:: stderr + + import sys + sys.stderr = sys.stdout + + .. testcleanup:: stderr + + sys.stderr = sys.__stderr__ + + .. testcode:: stderr + + wd = Word(alphas) + + @trace_parse_action + def remove_duplicate_chars(tokens): + return ''.join(sorted(set(''.join(tokens)))) + + wds = wd[1, ...].set_parse_action(remove_duplicate_chars) + print(wds.parse_string("slkdjs sld sldd sdlf sdljf")) + + prints: + + .. testoutput:: stderr + :options: +NORMALIZE_WHITESPACE + + >>entering remove_duplicate_chars(line: 'slkdjs sld sldd sdlf sdljf', + 0, ParseResults(['slkdjs', 'sld', 'sldd', 'sdlf', 'sdljf'], {})) + < 3: + thisFunc = f"{type(paArgs[0]).__name__}.{thisFunc}" + sys.stderr.write(f">>entering {thisFunc}(line: {line(l, s)!r}, {l}, {t!r})\n") + try: + ret = f(*paArgs) + except Exception as exc: + sys.stderr.write( + f"< str: + r"""Helper to easily define string ranges for use in :class:`Word` + construction. Borrows syntax from regexp ``'[]'`` string range + definitions:: + + srange("[0-9]") -> "0123456789" + srange("[a-z]") -> "abcdefghijklmnopqrstuvwxyz" + srange("[a-z$_]") -> "abcdefghijklmnopqrstuvwxyz$_" + + The input string must be enclosed in []'s, and the returned string + is the expanded character set joined into a single string. The + values enclosed in the []'s may be: + + - a single character + - an escaped character with a leading backslash (such as ``\-`` + or ``\]``) + - an escaped hex character with a leading ``'\x'`` + (``\x21``, which is a ``'!'`` character) (``\0x##`` + is also supported for backwards compatibility) + - an escaped octal character with a leading ``'\0'`` + (``\041``, which is a ``'!'`` character) + - a range of any of the above, separated by a dash (``'a-z'``, + etc.) + - any combination of the above (``'aeiouy'``, + ``'a-zA-Z0-9_$'``, etc.) + """ + + def _expanded(p): + if isinstance(p, ParseResults): + yield from (chr(c) for c in range(ord(p[0]), ord(p[1]) + 1)) + else: + yield p + + try: + return "".join( + [c for part in _reBracketExpr.parse_string(s).body for c in _expanded(part)] + ) + except Exception as e: + return "" + + +def token_map(func, *args) -> ParseAction: + """Helper to define a parse action by mapping a function to all + elements of a :class:`ParseResults` list. If any additional args are passed, + they are forwarded to the given function as additional arguments + after the token, as in + ``hex_integer = Word(hexnums).set_parse_action(token_map(int, 16))``, + which will convert the parsed data to an integer using base 16. + + Example (compare the last to example in :class:`ParserElement.transform_string`:: + + hex_ints = Word(hexnums)[1, ...].set_parse_action(token_map(int, 16)) + hex_ints.run_tests(''' + 00 11 22 aa FF 0a 0d 1a + ''') + + upperword = Word(alphas).set_parse_action(token_map(str.upper)) + upperword[1, ...].run_tests(''' + my kingdom for a horse + ''') + + wd = Word(alphas).set_parse_action(token_map(str.title)) + wd[1, ...].set_parse_action(' '.join).run_tests(''' + now is the winter of our discontent made glorious summer by this sun of york + ''') + + prints:: + + 00 11 22 aa FF 0a 0d 1a + [0, 17, 34, 170, 255, 10, 13, 26] + + my kingdom for a horse + ['MY', 'KINGDOM', 'FOR', 'A', 'HORSE'] + + now is the winter of our discontent made glorious summer by this sun of york + ['Now Is The Winter Of Our Discontent Made Glorious Summer By This Sun Of York'] + """ + + def pa(s, l, t): + return [func(tokn, *args) for tokn in t] + + func_name = getattr(func, "__name__", getattr(func, "__class__").__name__) + pa.__name__ = func_name + + return pa + + +def autoname_elements() -> None: + """ + Utility to simplify mass-naming of parser elements, for + generating railroad diagram with named subdiagrams. + """ + + # guard against _getframe not being implemented in the current Python + getframe_fn = getattr(sys, "_getframe", lambda _: None) + calling_frame = getframe_fn(1) + if calling_frame is None: + return + + # find all locals in the calling frame that are ParserElements + calling_frame = typing.cast(types.FrameType, calling_frame) + for name, var in calling_frame.f_locals.items(): + # if no custom name defined, set the name to the var name + if isinstance(var, ParserElement) and not var.customName: + var.set_name(name) + + +dbl_quoted_string = Combine( + Regex(r'"(?:[^"\n\r\\]|(?:"")|(?:\\(?:[^x]|x[0-9a-fA-F]+)))*') + '"' +).set_name("string enclosed in double quotes") + +sgl_quoted_string = Combine( + Regex(r"'(?:[^'\n\r\\]|(?:'')|(?:\\(?:[^x]|x[0-9a-fA-F]+)))*") + "'" +).set_name("string enclosed in single quotes") + +quoted_string = Combine( + (Regex(r'"(?:[^"\n\r\\]|(?:"")|(?:\\(?:[^x]|x[0-9a-fA-F]+)))*') + '"').set_name( + "double quoted string" + ) + | (Regex(r"'(?:[^'\n\r\\]|(?:'')|(?:\\(?:[^x]|x[0-9a-fA-F]+)))*") + "'").set_name( + "single quoted string" + ) +).set_name("quoted string using single or double quotes") + +# XXX: Is there some way to make this show up in API docs? +# .. versionadded:: 3.1.0 +python_quoted_string = Combine( + (Regex(r'"""(?:[^"\\]|""(?!")|"(?!"")|\\.)*', flags=re.MULTILINE) + '"""').set_name( + "multiline double quoted string" + ) + ^ ( + Regex(r"'''(?:[^'\\]|''(?!')|'(?!'')|\\.)*", flags=re.MULTILINE) + "'''" + ).set_name("multiline single quoted string") + ^ (Regex(r'"(?:[^"\n\r\\]|(?:\\")|(?:\\(?:[^x]|x[0-9a-fA-F]+)))*') + '"').set_name( + "double quoted string" + ) + ^ (Regex(r"'(?:[^'\n\r\\]|(?:\\')|(?:\\(?:[^x]|x[0-9a-fA-F]+)))*") + "'").set_name( + "single quoted string" + ) +).set_name("Python quoted string") + +unicode_string = Combine("u" + quoted_string.copy()).set_name("unicode string literal") + + +alphas8bit = srange(r"[\0xc0-\0xd6\0xd8-\0xf6\0xf8-\0xff]") +punc8bit = srange(r"[\0xa1-\0xbf\0xd7\0xf7]") + +# build list of built-in expressions, for future reference if a global default value +# gets updated +_builtin_exprs: list[ParserElement] = [ + v for v in vars().values() if isinstance(v, ParserElement) +] + +# Compatibility synonyms +# fmt: off +sglQuotedString = sgl_quoted_string +dblQuotedString = dbl_quoted_string +quotedString = quoted_string +unicodeString = unicode_string +lineStart = line_start +lineEnd = line_end +stringStart = string_start +stringEnd = string_end +nullDebugAction = replaced_by_pep8("nullDebugAction", null_debug_action) +traceParseAction = replaced_by_pep8("traceParseAction", trace_parse_action) +conditionAsParseAction = replaced_by_pep8("conditionAsParseAction", condition_as_parse_action) +tokenMap = replaced_by_pep8("tokenMap", token_map) +# fmt: on diff --git a/.venv/lib/python3.12/site-packages/pyparsing/diagram/__init__.py b/.venv/lib/python3.12/site-packages/pyparsing/diagram/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..b8baa47d14751ee7954e380ef16b97707bce9e0d --- /dev/null +++ b/.venv/lib/python3.12/site-packages/pyparsing/diagram/__init__.py @@ -0,0 +1,761 @@ +# mypy: ignore-errors +from __future__ import annotations + +import itertools +import railroad +import pyparsing +import dataclasses +import typing +from typing import ( + Generic, + TypeVar, + Callable, + Iterable, +) +from jinja2 import Template +from io import StringIO +import inspect +import re + + +jinja2_template_source = """\ +{% if not embed %} + + + +{% endif %} + {% if not head %} + + {% else %} + {{ head | safe }} + {% endif %} +{% if not embed %} + + +{% endif %} + +{{ body | safe }} +{% for diagram in diagrams %} +
+

{{ diagram.title }}

+
{{ diagram.text }}
+
+ {{ diagram.svg }} +
+
+{% endfor %} +{% if not embed %} + + +{% endif %} +""" + +template = Template(jinja2_template_source) + + +_bookmark_lookup = {} +_bookmark_ids = itertools.count(start=1) + +def _make_bookmark(s: str) -> str: + """ + Converts a string into a valid HTML bookmark (ID or anchor name). + """ + if s in _bookmark_lookup: + return _bookmark_lookup[s] + + # Replace invalid characters with hyphens and ensure only valid characters + bookmark = re.sub(r'[^a-zA-Z0-9-]+', '-', s) + + # Ensure it starts with a letter by adding 'z' if necessary + if not bookmark[:1].isalpha(): + bookmark = f"z{bookmark}" + + # Convert to lowercase and strip hyphens + bookmark = bookmark.lower().strip('-') + + _bookmark_lookup[s] = bookmark = f"{bookmark}-{next(_bookmark_ids):04d}" + + return bookmark + + +def _collapse_verbose_regex(regex_str: str) -> str: + if "\n" not in regex_str: + return regex_str + collapsed = pyparsing.Regex(r"#.*$").suppress().transform_string(regex_str) + collapsed = re.sub(r"\s*\n\s*", "", collapsed) + return collapsed + + +@dataclasses.dataclass +class NamedDiagram: + """ + A simple structure for associating a name with a railroad diagram + """ + + name: str + index: int + diagram: railroad.DiagramItem = None + + @property + def bookmark(self): + bookmark = _make_bookmark(self.name) + return bookmark + + +T = TypeVar("T") + + +class EachItem(railroad.Group): + """ + Custom railroad item to compose a: + + - :class:`railroad.Group` containing a + + - :class:`railroad.OneOrMore` containing a + + - :class:`railroad.Choice` of the elements in the + :class:`railroad.Each` + + with the group label indicating that all must be matched + """ + + all_label = "[ALL]" + + def __init__(self, *items) -> None: + choice_item = railroad.Choice(len(items) - 1, *items) + one_or_more_item = railroad.OneOrMore(item=choice_item) + super().__init__(one_or_more_item, label=self.all_label) + + +class AnnotatedItem(railroad.Group): + """ + Simple subclass of Group that creates an annotation label + """ + + def __init__(self, label: str, item) -> None: + super().__init__(item=item, label=f"[{label}]" if label else "") + + +class EditablePartial(Generic[T]): + """ + Acts like a functools.partial, but can be edited. In other words, it represents a type that hasn't yet been + constructed. + """ + + # We need this here because the railroad constructors actually transform the data, so can't be called until the + # entire tree is assembled + + def __init__(self, func: Callable[..., T], args: list, kwargs: dict) -> None: + self.func = func + self.args = args + self.kwargs = kwargs + + @classmethod + def from_call(cls, func: Callable[..., T], *args, **kwargs) -> EditablePartial[T]: + """ + If you call this function in the same way that you would call the constructor, + it will store the arguments as you expect. For example + ``EditablePartial.from_call(Fraction, 1, 3)() == Fraction(1, 3)`` + """ + return EditablePartial(func=func, args=list(args), kwargs=kwargs) + + @property + def name(self): + return self.kwargs["name"] + + def __call__(self) -> T: + """ + Evaluate the partial and return the result + """ + args = self.args.copy() + kwargs = self.kwargs.copy() + + # This is a helpful hack to allow you to specify varargs parameters (e.g. *args) as keyword args (e.g. + # args=['list', 'of', 'things']) + arg_spec = inspect.getfullargspec(self.func) + if arg_spec.varargs in self.kwargs: + args += kwargs.pop(arg_spec.varargs) + + return self.func(*args, **kwargs) + + +def railroad_to_html(diagrams: list[NamedDiagram], embed=False, **kwargs) -> str: + """ + Given a list of :class:`NamedDiagram`, produce a single HTML string + that visualises those diagrams. + + :params kwargs: kwargs to be passed in to the template + """ + data = [] + for diagram in diagrams: + if diagram.diagram is None: + continue + io = StringIO() + try: + css = kwargs.get("css") + diagram.diagram.writeStandalone(io.write, css=css) + except AttributeError: + diagram.diagram.writeSvg(io.write) + title = diagram.name + if diagram.index == 0: + title += " (root)" + data.append( + { + "title": title, "text": "", "svg": io.getvalue(), "bookmark": diagram.bookmark + } + ) + + return template.render(diagrams=data, embed=embed, **kwargs) + + +def resolve_partial(partial: EditablePartial[T]) -> T: + """ + Recursively resolves a collection of Partials into whatever type they are + """ + if isinstance(partial, EditablePartial): + partial.args = resolve_partial(partial.args) + partial.kwargs = resolve_partial(partial.kwargs) + return partial() + elif isinstance(partial, list): + return [resolve_partial(x) for x in partial] + elif isinstance(partial, dict): + return {key: resolve_partial(x) for key, x in partial.items()} + else: + return partial + + +def to_railroad( + element: pyparsing.ParserElement, + diagram_kwargs: typing.Optional[dict] = None, + vertical: int = 3, + show_results_names: bool = False, + show_groups: bool = False, + show_hidden: bool = False, +) -> list[NamedDiagram]: + """ + Convert a pyparsing element tree into a list of diagrams. This is the recommended entrypoint to diagram + creation if you want to access the Railroad tree before it is converted to HTML + + :param element: base element of the parser being diagrammed + + :param diagram_kwargs: kwargs to pass to the :meth:`Diagram` constructor + + :param vertical: (optional) int - limit at which number of alternatives + should be shown vertically instead of horizontally + + :param show_results_names: bool to indicate whether results name + annotations should be included in the diagram + + :param show_groups: bool to indicate whether groups should be highlighted + with an unlabeled surrounding box + + :param show_hidden: bool to indicate whether internal elements that are + typically hidden should be shown + """ + # Convert the whole tree underneath the root + lookup = ConverterState(diagram_kwargs=diagram_kwargs or {}) + _to_diagram_element( + element, + lookup=lookup, + parent=None, + vertical=vertical, + show_results_names=show_results_names, + show_groups=show_groups, + show_hidden=show_hidden, + ) + + root_id = id(element) + # Convert the root if it hasn't been already + if root_id in lookup: + if not element.customName: + lookup[root_id].name = "" + lookup[root_id].mark_for_extraction(root_id, lookup, force=True) + + # Now that we're finished, we can convert from intermediate structures into Railroad elements + diags = list(lookup.diagrams.values()) + if len(diags) > 1: + # collapse out duplicate diags with the same name + seen = set() + deduped_diags = [] + for d in diags: + # don't extract SkipTo elements, they are uninformative as subdiagrams + if d.name == "...": + continue + if d.name is not None and d.name not in seen: + seen.add(d.name) + deduped_diags.append(d) + resolved = [resolve_partial(partial) for partial in deduped_diags] + else: + # special case - if just one diagram, always display it, even if + # it has no name + resolved = [resolve_partial(partial) for partial in diags] + return sorted(resolved, key=lambda diag: diag.index) + + +def _should_vertical( + specification: int, exprs: Iterable[pyparsing.ParserElement] +) -> bool: + """ + Returns true if we should return a vertical list of elements + """ + if specification is None: + return False + else: + return len(_visible_exprs(exprs)) >= specification + + +@dataclasses.dataclass +class ElementState: + """ + State recorded for an individual pyparsing Element + """ + + #: The pyparsing element that this represents + element: pyparsing.ParserElement + #: The output Railroad element in an unconverted state + converted: EditablePartial + #: The parent Railroad element, which we store so that we can extract this if it's duplicated + parent: EditablePartial + #: The order in which we found this element, used for sorting diagrams if this is extracted into a diagram + number: int + #: The name of the element + name: str = None + #: The index of this inside its parent + parent_index: typing.Optional[int] = None + #: If true, we should extract this out into a subdiagram + extract: bool = False + #: If true, all of this element's children have been filled out + complete: bool = False + + def mark_for_extraction( + self, el_id: int, state: ConverterState, name: str = None, force: bool = False + ): + """ + Called when this instance has been seen twice, and thus should eventually be extracted into a sub-diagram + :param el_id: id of the element + :param state: element/diagram state tracker + :param name: name to use for this element's text + :param force: If true, force extraction now, regardless of the state of this. Only useful for extracting the + root element when we know we're finished + """ + self.extract = True + + # Set the name + if not self.name: + if name: + # Allow forcing a custom name + self.name = name + elif self.element.customName: + self.name = self.element.customName + else: + self.name = "" + + # Just because this is marked for extraction doesn't mean we can do it yet. We may have to wait for children + # to be added + # Also, if this is just a string literal etc, don't bother extracting it + if force or (self.complete and _worth_extracting(self.element)): + state.extract_into_diagram(el_id) + + +class ConverterState: + """ + Stores some state that persists between recursions into the element tree + """ + index_generator = itertools.count(start=1) + + def __init__(self, diagram_kwargs: typing.Optional[dict] = None) -> None: + #: A dictionary mapping ParserElements to state relating to them + self._element_diagram_states: dict[int, ElementState] = {} + #: A dictionary mapping ParserElement IDs to subdiagrams generated from them + self.diagrams: dict[int, EditablePartial[NamedDiagram]] = {} + #: The index of the next element. This is used for sorting + self.index: int = 0 + #: Shared kwargs that are used to customize the construction of diagrams + self.diagram_kwargs: dict = diagram_kwargs or {} + self.extracted_diagram_names: set[str] = set() + + def __setitem__(self, key: int, value: ElementState): + self._element_diagram_states[key] = value + + def __getitem__(self, key: int) -> ElementState: + return self._element_diagram_states[key] + + def __delitem__(self, key: int): + del self._element_diagram_states[key] + + def __contains__(self, key: int): + return key in self._element_diagram_states + + def get(self, key, default=None): + try: + return self[key] + except KeyError: + return default + + def generate_index(self) -> int: + """ + Generate a number used to index a diagram + """ + return next(self.index_generator) + + def extract_into_diagram(self, el_id: int): + """ + Used when we encounter the same token twice in the same tree. When this + happens, we replace all instances of that token with a terminal, and + create a new subdiagram for the token + """ + position = self[el_id] + + # Replace the original definition of this element with a regular block + if position.parent: + href = f"#{_make_bookmark(position.name)}" + ret = EditablePartial.from_call(railroad.NonTerminal, text=position.name, href=href) + if "item" in position.parent.kwargs: + position.parent.kwargs["item"] = ret + elif "items" in position.parent.kwargs: + position.parent.kwargs["items"][position.parent_index] = ret + + # If the element we're extracting is a group, skip to its content but keep the title + if position.converted.func == railroad.Group: + content = position.converted.kwargs["item"] + else: + content = position.converted + + self.diagrams[el_id] = EditablePartial.from_call( + NamedDiagram, + name=position.name, + diagram=EditablePartial.from_call( + railroad.Diagram, content, **self.diagram_kwargs + ), + index=position.number, + ) + + del self[el_id] + + +def _worth_extracting(element: pyparsing.ParserElement) -> bool: + """ + Returns true if this element is worth having its own sub-diagram. Simply, if any of its children + themselves have children, then its complex enough to extract + """ + children = element.recurse() + return any(child.recurse() for child in children) + + +def _apply_diagram_item_enhancements(fn): + """ + decorator to ensure enhancements to a diagram item (such as results name annotations) + get applied on return from _to_diagram_element (we do this since there are several + returns in _to_diagram_element) + """ + + def _inner( + element: pyparsing.ParserElement, + parent: typing.Optional[EditablePartial], + lookup: ConverterState = None, + vertical: int = None, + index: int = 0, + name_hint: str = None, + show_results_names: bool = False, + show_groups: bool = False, + show_hidden: bool = False, + ) -> typing.Optional[EditablePartial]: + ret = fn( + element, + parent, + lookup, + vertical, + index, + name_hint, + show_results_names, + show_groups, + show_hidden, + ) + + # apply annotation for results name, if present + if show_results_names and ret is not None: + element_results_name = element.resultsName + if element_results_name: + # add "*" to indicate if this is a "list all results" name + modal_tag = "" if element.modalResults else "*" + ret = EditablePartial.from_call( + railroad.Group, + item=ret, + label=f"{repr(element_results_name)}{modal_tag}", + ) + + return ret + + return _inner + + +def _visible_exprs(exprs: Iterable[pyparsing.ParserElement]): + non_diagramming_exprs = ( + pyparsing.ParseElementEnhance, + pyparsing.PositionToken, + pyparsing.And._ErrorStop, + ) + return [ + e + for e in exprs + if not isinstance(e, non_diagramming_exprs) + ] + + +@_apply_diagram_item_enhancements +def _to_diagram_element( + element: pyparsing.ParserElement, + parent: typing.Optional[EditablePartial], + lookup: ConverterState = None, + vertical: int = None, + index: int = 0, + name_hint: str = None, + show_results_names: bool = False, + show_groups: bool = False, + show_hidden: bool = False, +) -> typing.Optional[EditablePartial]: + """ + Recursively converts a PyParsing Element to a railroad Element + :param lookup: The shared converter state that keeps track of useful things + :param index: The index of this element within the parent + :param parent: The parent of this element in the output tree + :param vertical: Controls at what point we make a list of elements vertical. If this is an integer (the default), + it sets the threshold of the number of items before we go vertical. If True, always go vertical, if False, never + do so + :param name_hint: If provided, this will override the generated name + :param show_results_names: bool flag indicating whether to add annotations for results names + :param show_groups: bool flag indicating whether to show groups using bounding box + :param show_hidden: bool flag indicating whether to show elements that are typically hidden + :returns: The converted version of the input element, but as a Partial that hasn't yet been constructed + """ + exprs = element.recurse() + name = name_hint or element.customName or type(element).__name__ + + # Python's id() is used to provide a unique identifier for elements + el_id = id(element) + + element_results_name = element.resultsName + + # Here we basically bypass processing certain wrapper elements if they contribute nothing to the diagram + if not element.customName: + if isinstance( + element, + ( + # pyparsing.TokenConverter, + pyparsing.Forward, + pyparsing.Located, + pyparsing.AtStringStart, + pyparsing.AtLineStart, + ), + ): + # However, if this element has a useful custom name, and its child does not, we can pass it on to the child + if exprs: + if not exprs[0].customName: + propagated_name = name + else: + propagated_name = None + + return _to_diagram_element( + element.expr, + parent=parent, + lookup=lookup, + vertical=vertical, + index=index, + name_hint=propagated_name, + show_results_names=show_results_names, + show_groups=show_groups, + show_hidden=show_hidden, + ) + + # If the element isn't worth extracting, we always treat it as the first time we say it + if _worth_extracting(element): + looked_up = lookup.get(el_id) + if looked_up and looked_up.name is not None: + # If we've seen this element exactly once before, we are only just now finding out that it's a duplicate, + # so we have to extract it into a new diagram. + looked_up.mark_for_extraction(el_id, lookup, name=name_hint) + href = f"#{_make_bookmark(looked_up.name)}" + ret = EditablePartial.from_call(railroad.NonTerminal, text=looked_up.name, href=href) + return ret + + elif el_id in lookup.diagrams: + # If we have seen the element at least twice before, and have already extracted it into a subdiagram, we + # just put in a marker element that refers to the sub-diagram + text = lookup.diagrams[el_id].kwargs["name"] + ret = EditablePartial.from_call( + railroad.NonTerminal, text=text, href=f"#{_make_bookmark(text)}" + ) + return ret + + # Recursively convert child elements + # Here we find the most relevant Railroad element for matching pyparsing Element + # We use ``items=[]`` here to hold the place for where the child elements will go once created + + # see if this element is normally hidden, and whether hidden elements are desired + # if not, just return None + if not element.show_in_diagram and not show_hidden: + return None + + if isinstance(element, pyparsing.And): + # detect And's created with ``expr*N`` notation - for these use a OneOrMore with a repeat + # (all will have the same name, and resultsName) + if not exprs: + return None + if len(set((e.name, e.resultsName) for e in exprs)) == 1 and len(exprs) > 2: + ret = EditablePartial.from_call( + railroad.OneOrMore, item="", repeat=str(len(exprs)) + ) + elif _should_vertical(vertical, exprs): + ret = EditablePartial.from_call(railroad.Stack, items=[]) + else: + ret = EditablePartial.from_call(railroad.Sequence, items=[]) + elif isinstance(element, (pyparsing.Or, pyparsing.MatchFirst)): + if not exprs: + return None + if _should_vertical(vertical, exprs): + ret = EditablePartial.from_call(railroad.Choice, 0, items=[]) + else: + ret = EditablePartial.from_call(railroad.HorizontalChoice, items=[]) + elif isinstance(element, pyparsing.Each): + if not exprs: + return None + ret = EditablePartial.from_call(EachItem, items=[]) + elif isinstance(element, pyparsing.NotAny): + ret = EditablePartial.from_call(AnnotatedItem, label="NOT", item="") + elif isinstance(element, pyparsing.FollowedBy): + ret = EditablePartial.from_call(AnnotatedItem, label="LOOKAHEAD", item="") + elif isinstance(element, pyparsing.PrecededBy): + ret = EditablePartial.from_call(AnnotatedItem, label="LOOKBEHIND", item="") + elif isinstance(element, pyparsing.Group): + if show_groups: + ret = EditablePartial.from_call(AnnotatedItem, label="", item="") + else: + ret = EditablePartial.from_call( + railroad.Group, item=None, label=element_results_name + ) + elif isinstance(element, pyparsing.TokenConverter): + label = type(element).__name__.lower() + if label == "tokenconverter": + ret = EditablePartial.from_call(railroad.Sequence, items=[]) + else: + ret = EditablePartial.from_call(AnnotatedItem, label=label, item="") + elif isinstance(element, pyparsing.Opt): + ret = EditablePartial.from_call(railroad.Optional, item="") + elif isinstance(element, pyparsing.OneOrMore): + if element.not_ender is not None: + args = [ + parent, + lookup, + vertical, + index, + name_hint, + show_results_names, + show_groups, + show_hidden, + ] + return _to_diagram_element( + (~element.not_ender.expr + element.expr)[1, ...].set_name(element.name), + *args, + ) + ret = EditablePartial.from_call(railroad.OneOrMore, item=None) + elif isinstance(element, pyparsing.ZeroOrMore): + if element.not_ender is not None: + args = [ + parent, + lookup, + vertical, + index, + name_hint, + show_results_names, + show_groups, + show_hidden, + ] + return _to_diagram_element( + (~element.not_ender.expr + element.expr)[...].set_name(element.name), + *args, + ) + ret = EditablePartial.from_call(railroad.ZeroOrMore, item="") + elif isinstance(element, pyparsing.Empty) and not element.customName: + # Skip unnamed "Empty" elements + ret = None + elif isinstance(element, pyparsing.ParseElementEnhance): + ret = EditablePartial.from_call(railroad.Sequence, items=[]) + elif len(exprs) > 0 and not element_results_name: + ret = EditablePartial.from_call(railroad.Group, item="", label=name) + elif isinstance(element, pyparsing.Regex): + collapsed_patt = _collapse_verbose_regex(element.pattern) + ret = EditablePartial.from_call(railroad.Terminal, collapsed_patt) + elif len(exprs) > 0: + ret = EditablePartial.from_call(railroad.Sequence, items=[]) + else: + terminal = EditablePartial.from_call(railroad.Terminal, element.defaultName) + ret = terminal + + if ret is None: + return + + # Indicate this element's position in the tree so we can extract it if necessary + lookup[el_id] = ElementState( + element=element, + converted=ret, + parent=parent, + parent_index=index, + number=lookup.generate_index(), + ) + if element.customName: + lookup[el_id].mark_for_extraction(el_id, lookup, element.customName) + + i = 0 + for expr in exprs: + # Add a placeholder index in case we have to extract the child before we even add it to the parent + if "items" in ret.kwargs: + ret.kwargs["items"].insert(i, None) + + item = _to_diagram_element( + expr, + parent=ret, + lookup=lookup, + vertical=vertical, + index=i, + show_results_names=show_results_names, + show_groups=show_groups, + show_hidden=show_hidden, + ) + + # Some elements don't need to be shown in the diagram + if item is not None: + if "item" in ret.kwargs: + ret.kwargs["item"] = item + elif "items" in ret.kwargs: + # If we've already extracted the child, don't touch this index, since it's occupied by a nonterminal + ret.kwargs["items"][i] = item + i += 1 + elif "items" in ret.kwargs: + # If we're supposed to skip this element, remove it from the parent + del ret.kwargs["items"][i] + + # If all this items children are none, skip this item + if ret and ( + ("items" in ret.kwargs and len(ret.kwargs["items"]) == 0) + or ("item" in ret.kwargs and ret.kwargs["item"] is None) + ): + ret = EditablePartial.from_call(railroad.Terminal, name) + + # Mark this element as "complete", ie it has all of its children + if el_id in lookup: + lookup[el_id].complete = True + + if el_id in lookup and lookup[el_id].extract and lookup[el_id].complete: + lookup.extract_into_diagram(el_id) + if ret is not None: + text = lookup.diagrams[el_id].kwargs["name"] + href = f"#{_make_bookmark(text)}" + ret = EditablePartial.from_call( + railroad.NonTerminal, text=text, href=href + ) + + return ret diff --git a/.venv/lib/python3.12/site-packages/pyparsing/diagram/__pycache__/__init__.cpython-312.pyc b/.venv/lib/python3.12/site-packages/pyparsing/diagram/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..bf1a1ba946d7f8d000929c9e2517ff837399ef58 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/pyparsing/diagram/__pycache__/__init__.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/pyparsing/exceptions.py b/.venv/lib/python3.12/site-packages/pyparsing/exceptions.py new file mode 100644 index 0000000000000000000000000000000000000000..237ca2ebf2b3798570ad8a1fce10544790f70f63 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/pyparsing/exceptions.py @@ -0,0 +1,353 @@ +# exceptions.py +from __future__ import annotations + +import copy +import re +import sys +import typing +import warnings +from functools import cached_property + +from .warnings import PyparsingDeprecationWarning +from .unicode import pyparsing_unicode as ppu +from .util import ( + _collapse_string_to_ranges, + col, + deprecate_argument, + line, + lineno, + replaced_by_pep8, +) + + +class _ExceptionWordUnicodeSet( + ppu.Latin1, ppu.LatinA, ppu.LatinB, ppu.Greek, ppu.Cyrillic +): + pass + + +_extract_alphanums = _collapse_string_to_ranges(_ExceptionWordUnicodeSet.alphanums) +_exception_word_extractor = re.compile(fr"([{_extract_alphanums}]{{1,16}})|.") + + +class ParseBaseException(Exception): + """base exception class for all parsing runtime exceptions""" + + loc: int + msg: str + pstr: str + parser_element: typing.Any # "ParserElement" + args: tuple[str, int, typing.Optional[str]] + + __slots__ = ( + "loc", + "msg", + "pstr", + "parser_element", + "args", + ) + + # Performance tuning: we construct a *lot* of these, so keep this + # constructor as small and fast as possible + def __init__( + self, + pstr: str, + loc: int = 0, + msg: typing.Optional[str] = None, + elem=None, + ) -> None: + if msg is None: + msg, pstr = pstr, "" + + self.loc = loc + self.msg = msg + self.pstr = pstr + self.parser_element = elem + self.args = (pstr, loc, msg) + + @staticmethod + def explain_exception(exc: Exception, depth: int = 16) -> str: + """ + Method to take an exception and translate the Python internal traceback into a list + of the pyparsing expressions that caused the exception to be raised. + + Parameters: + + - exc - exception raised during parsing (need not be a ParseException, in support + of Python exceptions that might be raised in a parse action) + - depth (default=16) - number of levels back in the stack trace to list expression + and function names; if None, the full stack trace names will be listed; if 0, only + the failing input line, marker, and exception string will be shown + + Returns a multi-line string listing the ParserElements and/or function names in the + exception's stack trace. + """ + import inspect + from .core import ParserElement + + if depth is None: + depth = sys.getrecursionlimit() + ret: list[str] = [] + if isinstance(exc, ParseBaseException): + ret.append(exc.line) + ret.append(f"{'^':>{exc.column}}") + ret.append(f"{type(exc).__name__}: {exc}") + + if depth <= 0 or exc.__traceback__ is None: + return "\n".join(ret) + + callers = inspect.getinnerframes(exc.__traceback__, context=depth) + seen: set[int] = set() + for ff in callers[-depth:]: + frm = ff[0] + + f_self = frm.f_locals.get("self", None) + if isinstance(f_self, ParserElement): + if not frm.f_code.co_name.startswith(("parseImpl", "_parseNoCache")): + continue + if id(f_self) in seen: + continue + seen.add(id(f_self)) + + self_type = type(f_self) + ret.append(f"{self_type.__module__}.{self_type.__name__} - {f_self}") + + elif f_self is not None: + self_type = type(f_self) + ret.append(f"{self_type.__module__}.{self_type.__name__}") + + else: + code = frm.f_code + if code.co_name in ("wrapper", ""): + continue + + ret.append(code.co_name) + + depth -= 1 + if not depth: + break + + return "\n".join(ret) + + @classmethod + def _from_exception(cls, pe) -> ParseBaseException: + """ + internal factory method to simplify creating one type of ParseException + from another - avoids having __init__ signature conflicts among subclasses + """ + return cls(pe.pstr, pe.loc, pe.msg, pe.parser_element) + + @cached_property + def line(self) -> str: + """ + Return the line of text where the exception occurred. + """ + return line(self.loc, self.pstr) + + @cached_property + def lineno(self) -> int: + """ + Return the 1-based line number of text where the exception occurred. + """ + return lineno(self.loc, self.pstr) + + @cached_property + def col(self) -> int: + """ + Return the 1-based column on the line of text where the exception occurred. + """ + return col(self.loc, self.pstr) + + @cached_property + def column(self) -> int: + """ + Return the 1-based column on the line of text where the exception occurred. + """ + return col(self.loc, self.pstr) + + @cached_property + def found(self) -> str: + if not self.pstr: + return "" + + if self.loc >= len(self.pstr): + return "end of text" + + # pull out next word at error location + found_match = _exception_word_extractor.match(self.pstr, self.loc) + if found_match is not None: + found_text = found_match[0] + else: + found_text = self.pstr[self.loc : self.loc + 1] + + return repr(found_text).replace(r"\\", "\\") + + # pre-PEP8 compatibility + @property + def parserElement(self): + warnings.warn( + "parserElement is deprecated, use parser_element", + PyparsingDeprecationWarning, + stacklevel=2, + ) + return self.parser_element + + @parserElement.setter + def parserElement(self, elem): + warnings.warn( + "parserElement is deprecated, use parser_element", + PyparsingDeprecationWarning, + stacklevel=2, + ) + self.parser_element = elem + + def copy(self): + return copy.copy(self) + + def formatted_message(self) -> str: + """ + Output the formatted exception message. + Can be overridden to customize the message formatting or contents. + + .. versionadded:: 3.2.0 + """ + found_phrase = f", found {self.found}" if self.found else "" + return f"{self.msg}{found_phrase} (at char {self.loc}), (line:{self.lineno}, col:{self.column})" + + def __str__(self) -> str: + """ + .. versionchanged:: 3.2.0 + Now uses :meth:`formatted_message` to format message. + """ + try: + return self.formatted_message() + except Exception as ex: + return ( + f"{type(self).__name__}: {self.msg}" + f" ({type(ex).__name__}: {ex} while formatting message)" + ) + + def __repr__(self): + return str(self) + + def mark_input_line( + self, marker_string: typing.Optional[str] = None, **kwargs + ) -> str: + """ + Extracts the exception line from the input string, and marks + the location of the exception with a special symbol. + """ + markerString: str = deprecate_argument(kwargs, "markerString", ">!<") + + markerString = marker_string if marker_string is not None else markerString + line_str = self.line + line_column = self.column - 1 + if markerString: + line_str = f"{line_str[:line_column]}{markerString}{line_str[line_column:]}" + return line_str.strip() + + def explain(self, depth: int = 16) -> str: + """ + Method to translate the Python internal traceback into a list + of the pyparsing expressions that caused the exception to be raised. + + Parameters: + + - depth (default=16) - number of levels back in the stack trace to list expression + and function names; if None, the full stack trace names will be listed; if 0, only + the failing input line, marker, and exception string will be shown + + Returns a multi-line string listing the ParserElements and/or function names in the + exception's stack trace. + + Example: + + .. testcode:: + + # an expression to parse 3 integers + expr = pp.Word(pp.nums) * 3 + try: + # a failing parse - the third integer is prefixed with "A" + expr.parse_string("123 456 A789") + except pp.ParseException as pe: + print(pe.explain(depth=0)) + + prints: + + .. testoutput:: + + 123 456 A789 + ^ + ParseException: Expected W:(0-9), found 'A789' (at char 8), (line:1, col:9) + + Note: the diagnostic output will include string representations of the expressions + that failed to parse. These representations will be more helpful if you use `set_name` to + give identifiable names to your expressions. Otherwise they will use the default string + forms, which may be cryptic to read. + + Note: pyparsing's default truncation of exception tracebacks may also truncate the + stack of expressions that are displayed in the ``explain`` output. To get the full listing + of parser expressions, you may have to set ``ParserElement.verbose_stacktrace = True`` + """ + return self.explain_exception(self, depth) + + # Compatibility synonyms + # fmt: off + markInputline = replaced_by_pep8("markInputline", mark_input_line) + # fmt: on + + +class ParseException(ParseBaseException): + """ + Exception thrown when a parse expression doesn't match the input string + + Example: + + .. testcode:: + + integer = Word(nums).set_name("integer") + try: + integer.parse_string("ABC") + except ParseException as pe: + print(pe, f"column: {pe.column}") + + prints: + + .. testoutput:: + + Expected integer, found 'ABC' (at char 0), (line:1, col:1) column: 1 + + """ + + +class ParseFatalException(ParseBaseException): + """ + User-throwable exception thrown when inconsistent parse content + is found; stops all parsing immediately + """ + + +class ParseSyntaxException(ParseFatalException): + """ + Just like :class:`ParseFatalException`, but thrown internally + when an :class:`ErrorStop` ('-' operator) indicates + that parsing is to stop immediately because an unbacktrackable + syntax error has been found. + """ + + +class RecursiveGrammarException(Exception): + """ + .. deprecated:: 3.0.0 + Only used by the deprecated :meth:`ParserElement.validate`. + + Exception thrown by :class:`ParserElement.validate` if the + grammar could be left-recursive; parser may need to enable + left recursion using :class:`ParserElement.enable_left_recursion` + """ + + def __init__(self, parseElementList) -> None: + self.parseElementTrace = parseElementList + + def __str__(self) -> str: + return f"RecursiveGrammarException: {self.parseElementTrace}" diff --git a/.venv/lib/python3.12/site-packages/pyparsing/helpers.py b/.venv/lib/python3.12/site-packages/pyparsing/helpers.py new file mode 100644 index 0000000000000000000000000000000000000000..59877dee76c31fae53a0ffe91c64947bf760c5c4 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/pyparsing/helpers.py @@ -0,0 +1,1769 @@ +# helpers.py +from enum import Enum, auto +import html.entities +import operator +import re +import sys +import typing + +from . import __diag__ +from .core import * +from .util import ( + _bslash, + _flatten, + _escape_regex_range_chars, + make_compressed_re, + replaced_by_pep8, +) + + +def _suppression(expr: Union[ParserElement, str]) -> ParserElement: + # internal helper to avoid wrapping Suppress inside another Suppress + if isinstance(expr, Suppress): + return expr + return Suppress(expr) + + +# +# global helpers +# +def counted_array( + expr: ParserElement, int_expr: typing.Optional[ParserElement] = None, **kwargs +) -> ParserElement: + """Helper to define a counted list of expressions. + + This helper defines a pattern of the form:: + + integer expr expr expr... + + where the leading integer tells how many expr expressions follow. + The matched tokens returns the array of expr tokens as a list - the + leading count token is suppressed. + + If ``int_expr`` is specified, it should be a pyparsing expression + that produces an integer value. + + Examples: + + .. doctest:: + + >>> counted_array(Word(alphas)).parse_string('2 ab cd ef') + ParseResults(['ab', 'cd'], {}) + + - In this parser, the leading integer value is given in binary, + '10' indicating that 2 values are in the array: + + .. doctest:: + + >>> binary_constant = Word('01').set_parse_action(lambda t: int(t[0], 2)) + >>> counted_array(Word(alphas), int_expr=binary_constant + ... ).parse_string('10 ab cd ef') + ParseResults(['ab', 'cd'], {}) + + - If other fields must be parsed after the count but before the + list items, give the fields results names and they will + be preserved in the returned ParseResults: + + .. doctest:: + + >>> ppc = pyparsing.common + >>> count_with_metadata = ppc.integer + Word(alphas)("type") + >>> typed_array = counted_array(Word(alphanums), + ... int_expr=count_with_metadata)("items") + >>> result = typed_array.parse_string("3 bool True True False") + >>> print(result.dump()) + ['True', 'True', 'False'] + - items: ['True', 'True', 'False'] + - type: 'bool' + """ + intExpr: typing.Optional[ParserElement] = deprecate_argument( + kwargs, "intExpr", None + ) + + intExpr = intExpr or int_expr + array_expr = Forward() + + def count_field_parse_action(s, l, t): + nonlocal array_expr + n = t[0] + array_expr <<= (expr * n) if n else Empty() + # clear list contents, but keep any named results + del t[:] + + if intExpr is None: + intExpr = Word(nums).set_parse_action(lambda t: int(t[0])) + else: + intExpr = intExpr.copy() + intExpr.set_name("arrayLen") + intExpr.add_parse_action(count_field_parse_action, call_during_try=True) + return (intExpr + array_expr).set_name(f"(len) {expr}...") + + +def match_previous_literal(expr: ParserElement) -> ParserElement: + """Helper to define an expression that is indirectly defined from + the tokens matched in a previous expression, that is, it looks for + a 'repeat' of a previous expression. For example:: + + .. testcode:: + + first = Word(nums) + second = match_previous_literal(first) + match_expr = first + ":" + second + + will match ``"1:1"``, but not ``"1:2"``. Because this + matches a previous literal, will also match the leading + ``"1:1"`` in ``"1:10"``. If this is not desired, use + :class:`match_previous_expr`. Do *not* use with packrat parsing + enabled. + """ + rep = Forward() + + def copy_token_to_repeater(s, l, t): + if not t: + rep << Empty() + return + + if len(t) == 1: + rep << t[0] + return + + # flatten t tokens + tflat = _flatten(t.as_list()) + rep << And(Literal(tt) for tt in tflat) + + expr.add_parse_action(copy_token_to_repeater, call_during_try=True) + rep.set_name(f"(prev) {expr}") + return rep + + +def match_previous_expr(expr: ParserElement) -> ParserElement: + """Helper to define an expression that is indirectly defined from + the tokens matched in a previous expression, that is, it looks for + a 'repeat' of a previous expression. For example: + + .. testcode:: + + first = Word(nums) + second = match_previous_expr(first) + match_expr = first + ":" + second + + will match ``"1:1"``, but not ``"1:2"``. Because this + matches by expressions, will *not* match the leading ``"1:1"`` + in ``"1:10"``; the expressions are evaluated first, and then + compared, so ``"1"`` is compared with ``"10"``. Do *not* use + with packrat parsing enabled. + """ + rep = Forward() + e2 = expr.copy() + rep <<= e2 + + def copy_token_to_repeater(s, l, t): + matchTokens = _flatten(t.as_list()) + + def must_match_these_tokens(s, l, t): + theseTokens = _flatten(t.as_list()) + if theseTokens != matchTokens: + raise ParseException( + s, l, f"Expected {matchTokens}, found{theseTokens}" + ) + + rep.set_parse_action(must_match_these_tokens, call_during_try=True) + + expr.add_parse_action(copy_token_to_repeater, call_during_try=True) + rep.set_name(f"(prev) {expr}") + return rep + + +def one_of( + strs: Union[typing.Iterable[str], str], + caseless: bool = False, + use_regex: bool = True, + as_keyword: bool = False, + **kwargs, +) -> ParserElement: + """Helper to quickly define a set of alternative :class:`Literal` s, + and makes sure to do longest-first testing when there is a conflict, + regardless of the input order, but returns + a :class:`MatchFirst` for best performance. + + :param strs: a string of space-delimited literals, or a collection of + string literals + :param caseless: treat all literals as caseless + :param use_regex: bool - as an optimization, will + generate a :class:`Regex` object; otherwise, will generate + a :class:`MatchFirst` object (if ``caseless=True`` or + ``as_keyword=True``, or if creating a :class:`Regex` raises an exception) + :param as_keyword: bool - enforce :class:`Keyword`-style matching on the + generated expressions + + Parameters ``asKeyword`` and ``useRegex`` are retained for pre-PEP8 + compatibility, but will be removed in a future release. + + Example: + + .. testcode:: + + comp_oper = one_of("< = > <= >= !=") + var = Word(alphas) + number = Word(nums) + term = var | number + comparison_expr = term + comp_oper + term + print(comparison_expr.search_string("B = 12 AA=23 B<=AA AA>12")) + + prints: + + .. testoutput:: + + [['B', '=', '12'], ['AA', '=', '23'], ['B', '<=', 'AA'], ['AA', '>', '12']] + """ + useRegex: bool = deprecate_argument(kwargs, "useRegex", True) + asKeyword: bool = deprecate_argument(kwargs, "asKeyword", False) + + asKeyword = asKeyword or as_keyword + useRegex = useRegex and use_regex + + if ( + isinstance(caseless, str_type) + and __diag__.warn_on_multiple_string_args_to_oneof + ): + warnings.warn( + "warn_on_multiple_string_args_to_oneof:" + " More than one string argument passed to one_of, pass" + " choices as a list or space-delimited string", + PyparsingDiagnosticWarning, + stacklevel=2, + ) + + if caseless: + is_equal = lambda a, b: a.upper() == b.upper() + masks = lambda a, b: b.upper().startswith(a.upper()) + else: + is_equal = operator.eq + masks = lambda a, b: b.startswith(a) + + symbols: list[str] + if isinstance(strs, str_type): + strs = typing.cast(str, strs) + symbols = strs.split() + elif isinstance(strs, Iterable): + symbols = list(strs) + else: + raise TypeError("Invalid argument to one_of, expected string or iterable") + if not symbols: + return NoMatch() + + # reorder given symbols to take care to avoid masking longer choices with shorter ones + # (but only if the given symbols are not just single characters) + i = 0 + while i < len(symbols) - 1: + cur = symbols[i] + for j, other in enumerate(symbols[i + 1 :]): + if is_equal(other, cur): + del symbols[i + j + 1] + break + if len(other) > len(cur) and masks(cur, other): + del symbols[i + j + 1] + symbols.insert(i, other) + break + else: + i += 1 + + if useRegex: + re_flags: int = re.IGNORECASE if caseless else 0 + + try: + if all(len(sym) == 1 for sym in symbols): + # symbols are just single characters, create range regex pattern + patt = f"[{''.join(_escape_regex_range_chars(sym) for sym in symbols)}]" + else: + patt = "|".join(re.escape(sym) for sym in symbols) + + # wrap with \b word break markers if defining as keywords + if asKeyword: + patt = rf"\b(?:{patt})\b" + + ret = Regex(patt, flags=re_flags) + ret.set_name(" | ".join(repr(s) for s in symbols)) + + if caseless: + # add parse action to return symbols as specified, not in random + # casing as found in input string + symbol_map = {sym.lower(): sym for sym in symbols} + ret.add_parse_action(lambda s, l, t: symbol_map[t[0].lower()]) + + return ret + + except re.error: + warnings.warn( + "Exception creating Regex for one_of, building MatchFirst", + PyparsingDiagnosticWarning, + stacklevel=2, + ) + + # last resort, just use MatchFirst of Token class corresponding to caseless + # and asKeyword settings + CASELESS = KEYWORD = True + parse_element_class = { + (CASELESS, KEYWORD): CaselessKeyword, + (CASELESS, not KEYWORD): CaselessLiteral, + (not CASELESS, KEYWORD): Keyword, + (not CASELESS, not KEYWORD): Literal, + }[(caseless, asKeyword)] + return MatchFirst(parse_element_class(sym) for sym in symbols).set_name( + " | ".join(symbols) + ) + + +def dict_of(key: ParserElement, value: ParserElement) -> Dict: + """Helper to easily and clearly define a dictionary by specifying + the respective patterns for the key and value. Takes care of + defining the :class:`Dict`, :class:`ZeroOrMore`, and + :class:`Group` tokens in the proper order. The key pattern + can include delimiting markers or punctuation, as long as they are + suppressed, thereby leaving the significant key text. The value + pattern can include named results, so that the :class:`Dict` results + can include named token fields. + + Example: + + .. doctest:: + + >>> text = "shape: SQUARE posn: upper left color: light blue texture: burlap" + + >>> data_word = Word(alphas) + >>> label = data_word + FollowedBy(':') + >>> attr_expr = ( + ... label + ... + Suppress(':') + ... + OneOrMore(data_word, stop_on=label) + ... .set_parse_action(' '.join)) + >>> print(attr_expr[1, ...].parse_string(text).dump()) + ['shape', 'SQUARE', 'posn', 'upper left', 'color', 'light blue', 'texture', 'burlap'] + + >>> attr_label = label + >>> attr_value = Suppress(':') + OneOrMore(data_word, stop_on=label + ... ).set_parse_action(' '.join) + + # similar to Dict, but simpler call format + >>> result = dict_of(attr_label, attr_value).parse_string(text) + >>> print(result.dump()) + [['shape', 'SQUARE'], ['posn', 'upper left'], ['color', 'light blue'], ['texture', 'burlap']] + - color: 'light blue' + - posn: 'upper left' + - shape: 'SQUARE' + - texture: 'burlap' + [0]: + ['shape', 'SQUARE'] + [1]: + ['posn', 'upper left'] + [2]: + ['color', 'light blue'] + [3]: + ['texture', 'burlap'] + + >>> print(result['shape']) + SQUARE + >>> print(result.shape) # object attribute access works too + SQUARE + >>> print(result.as_dict()) + {'shape': 'SQUARE', 'posn': 'upper left', 'color': 'light blue', 'texture': 'burlap'} + """ + return Dict(OneOrMore(Group(key + value))) + + +def original_text_for( + expr: ParserElement, as_string: bool = True, **kwargs +) -> ParserElement: + """Helper to return the original, untokenized text for a given + expression. Useful to restore the parsed fields of an HTML start + tag into the raw tag text itself, or to revert separate tokens with + intervening whitespace back to the original matching input text. By + default, returns a string containing the original parsed text. + + If the optional ``as_string`` argument is passed as + ``False``, then the return value is + a :class:`ParseResults` containing any results names that + were originally matched, and a single token containing the original + matched text from the input string. So if the expression passed to + :class:`original_text_for` contains expressions with defined + results names, you must set ``as_string`` to ``False`` if you + want to preserve those results name values. + + The ``asString`` pre-PEP8 argument is retained for compatibility, + but will be removed in a future release. + + Example: + + .. testcode:: + + src = "this is test bold text normal text " + for tag in ("b", "i"): + opener, closer = make_html_tags(tag) + patt = original_text_for(opener + ... + closer) + print(patt.search_string(src)[0]) + + prints: + + .. testoutput:: + + [' bold text '] + ['text'] + """ + asString: bool = deprecate_argument(kwargs, "asString", True) + + asString = asString and as_string + + locMarker = Empty().set_parse_action(lambda s, loc, t: loc) + endlocMarker = locMarker.copy() + endlocMarker.callPreparse = False + matchExpr = locMarker("_original_start") + expr + endlocMarker("_original_end") + if asString: + extractText = lambda s, l, t: s[t._original_start : t._original_end] + else: + + def extractText(s, l, t): + t[:] = [s[t.pop("_original_start") : t.pop("_original_end")]] + + matchExpr.set_parse_action(extractText) + matchExpr.ignoreExprs = expr.ignoreExprs + matchExpr.suppress_warning(Diagnostics.warn_ungrouped_named_tokens_in_collection) + return matchExpr + + +def ungroup(expr: ParserElement) -> ParserElement: + """Helper to undo pyparsing's default grouping of And expressions, + even if all but one are non-empty. + """ + return TokenConverter(expr).add_parse_action(lambda t: t[0]) + + +def locatedExpr(expr: ParserElement) -> ParserElement: + """ + .. deprecated:: 3.0.0 + Use the :class:`Located` class instead. Note that `Located` + returns results with one less grouping level. + + Helper to decorate a returned token with its starting and ending + locations in the input string. + + This helper adds the following results names: + + - ``locn_start`` - location where matched expression begins + - ``locn_end`` - location where matched expression ends + - ``value`` - the actual parsed results + + Be careful if the input text contains ```` characters, you + may want to call :meth:`ParserElement.parse_with_tabs` + """ + warnings.warn( + f"{'locatedExpr'!r} deprecated - use {'Located'!r}", + PyparsingDeprecationWarning, + stacklevel=2, + ) + + locator = Empty().set_parse_action(lambda ss, ll, tt: ll) + return Group( + locator("locn_start") + + expr("value") + + locator.copy().leave_whitespace()("locn_end") + ) + + +# define special default value to permit None as a significant value for +# ignore_expr +_NO_IGNORE_EXPR_GIVEN = NoMatch() + + +class _NestedExpr(ParseElementEnhance): + """Helper method for defining nested lists enclosed in opening and + closing delimiters (``"("`` and ``")"`` are the default). + + :param opener: str - opening character for a nested list + (default= ``"("``); can also be a pyparsing expression + + :param closer: str - closing character for a nested list + (default= ``")"``); can also be a pyparsing expression + + :param content: expression for items within the nested lists + + :param ignore_expr: expression for ignoring opening and closing delimiters + (default = :class:`quoted_string`) + + Parameter ``ignoreExpr`` is retained for compatibility + but will be removed in a future release. + + If an expression is not provided for the content argument, the + nested expression will capture all whitespace-delimited content + between delimiters as a list of separate values. + + Use the ``ignore_expr`` argument to define expressions that may + contain opening or closing characters that should not be treated as + opening or closing characters for nesting, such as quoted_string or + a comment expression. Specify multiple expressions using an + :class:`Or` or :class:`MatchFirst`. The default is + :class:`quoted_string`, but if no expressions are to be ignored, then + pass ``None`` for this argument. + + Example: + + .. testcode:: + + data_type = one_of("void int short long char float double") + decl_data_type = Combine(data_type + Opt(Word('*'))) + ident = Word(alphas+'_', alphanums+'_') + number = pyparsing_common.number + arg = Group(decl_data_type + ident) + LPAR, RPAR = map(Suppress, "()") + + code_body = nested_expr('{', '}', ignore_expr=(quoted_string | c_style_comment)) + + c_function = (decl_data_type("type") + + ident("name") + + LPAR + Opt(DelimitedList(arg), [])("args") + RPAR + + code_body("body")) + c_function.ignore(c_style_comment) + + source_code = ''' + int is_odd(int x) { + return (x%2); + } + + int dec_to_hex(char hchar) { + if (hchar >= '0' && hchar <= '9') { + return (ord(hchar)-ord('0')); + } else { + return (10+ord(hchar)-ord('A')); + } + } + ''' + for func in c_function.search_string(source_code): + print(f"{func.name} ({func.type}) args: {func.args}") + + + prints: + + .. testoutput:: + + is_odd (int) args: [['int', 'x']] + dec_to_hex (int) args: [['char', 'hchar']] + """ + + def __init__( + self, + opener: Union[str, ParserElement] = "(", + closer: Union[str, ParserElement] = ")", + content: typing.Optional[ParserElement] = None, + ignore_expr: typing.Optional[ParserElement] = _NO_IGNORE_EXPR_GIVEN, + **kwargs, + ): + ignoreExpr = deprecate_argument(kwargs, "ignoreExpr", _NO_IGNORE_EXPR_GIVEN) + if ignoreExpr != ignore_expr: + ignoreExpr = ( + ignore_expr if ignoreExpr is _NO_IGNORE_EXPR_GIVEN else ignoreExpr + ) + if ignoreExpr is _NO_IGNORE_EXPR_GIVEN: + ignoreExpr = quoted_string() + + if opener == closer: + raise ValueError("opening and closing strings cannot be the same") + + original_content = content + if content is None: + if isinstance(opener, str_type) and isinstance(closer, str_type): + opener_str = str(opener) + closer_str = str(closer) + if len(opener_str) == 1 and len(closer_str) == 1: + if ignoreExpr is not None: + content = Combine( + OneOrMore( + ~ignoreExpr + + CharsNotIn( + opener_str + + closer_str + + ParserElement.DEFAULT_WHITE_CHARS, + exact=1, + ) + ) + ) + else: + content = Combine( + Empty() + + CharsNotIn( + opener_str + + closer_str + + ParserElement.DEFAULT_WHITE_CHARS + ) + ) + else: + if ignoreExpr is not None: + content = Combine( + OneOrMore( + ~ignoreExpr + + ~Literal(opener_str) + + ~Literal(closer_str) + + CharsNotIn(ParserElement.DEFAULT_WHITE_CHARS, exact=1) + ) + ) + else: + content = Combine( + OneOrMore( + ~Literal(opener_str) + + ~Literal(closer_str) + + CharsNotIn(ParserElement.DEFAULT_WHITE_CHARS, exact=1) + ) + ) + else: + raise ValueError( + "opening and closing arguments must be strings if no content expression is given" + ) + + if ParserElement.DEFAULT_WHITE_CHARS: + content.set_parse_action( + lambda t: t[0].strip(ParserElement.DEFAULT_WHITE_CHARS) + ) + + super().__init__(content, savelist=True) + self.opener = _suppression(opener) + self.closer = _suppression(closer) + self.opener_raw = opener + self.closer_raw = closer + self.content = content + self.ignore_expr = ignoreExpr + self.saveAsList = True + self.errmsg = None + self.original_content = original_content + + def _generateDefaultName(self) -> str: + if self.original_content is None: + return f"nested {self.opener_raw}{self.closer_raw} expression" + else: + return f"nested {self.opener_raw}{self.original_content}{self.closer_raw} expression" + + def parseImpl(self, instring, loc, do_actions=True): + loc, _ = self.opener._parse(instring, loc, do_actions=do_actions) + stack = [[]] + while stack: + # 1. try ignore_expr + if self.ignore_expr is not None: + try: + loc, toks = self.ignore_expr._parse( + instring, loc, do_actions=do_actions + ) + stack[-1].extend(toks) + continue + except ParseException: + pass + # 2. try opener + try: + loc, _ = self.opener._parse(instring, loc, do_actions=do_actions) + stack.append([]) + continue + except ParseException: + pass + # 3. try content + try: + next_loc, toks = self.content._parse( + instring, loc, do_actions=do_actions + ) + if next_loc > loc: + loc = next_loc + stack[-1].extend(toks) + continue + except ParseException: + pass + # 4. try closer + try: + loc, _ = self.closer._parse(instring, loc, do_actions=do_actions) + top = ParseResults(stack.pop()) + if stack: + stack[-1].append(top) + else: + return loc, ParseResults([top]) + continue + except ParseException: + pass + + raise ParseException(instring, loc, f"Expected {self.closer_raw!r}") + + +def nested_expr( + opener: Union[str, ParserElement] = "(", + closer: Union[str, ParserElement] = ")", + content: typing.Optional[ParserElement] = None, + ignore_expr: typing.Optional[ParserElement] = _NO_IGNORE_EXPR_GIVEN, + **kwargs, +) -> ParserElement: + """Helper method for defining nested lists enclosed in opening and + closing delimiters (``"("`` and ``")"`` are the default). + + :param opener: str - opening character for a nested list + (default= ``"("``); can also be a pyparsing expression + + :param closer: str - closing character for a nested list + (default= ``")"``); can also be a pyparsing expression + + :param content: expression for items within the nested lists + + :param ignore_expr: expression for ignoring opening and closing delimiters + (default = :class:`quoted_string`) + + Parameter ``ignoreExpr`` is retained for compatibility + but will be removed in a future release. + + If an expression is not provided for the content argument, the + nested expression will capture all whitespace-delimited content + between delimiters as a list of separate values. + + Use the ``ignore_expr`` argument to define expressions that may + contain opening or closing characters that should not be treated as + opening or closing characters for nesting, such as quoted_string or + a comment expression. Specify multiple expressions using an + :class:`Or` or :class:`MatchFirst`. The default is + :class:`quoted_string`, but if no expressions are to be ignored, then + pass ``None`` for this argument. + + Example: + + .. testcode:: + + data_type = one_of("void int short long char float double") + decl_data_type = Combine(data_type + Opt(Word('*'))) + ident = Word(alphas+'_', alphanums+'_') + number = pyparsing_common.number + arg = Group(decl_data_type + ident) + LPAR, RPAR = map(Suppress, "()") + + code_body = nested_expr('{', '}', ignore_expr=(quoted_string | c_style_comment)) + + c_function = (decl_data_type("type") + + ident("name") + + LPAR + Opt(DelimitedList(arg), [])("args") + RPAR + + code_body("body")) + c_function.ignore(c_style_comment) + + source_code = ''' + int is_odd(int x) { + return (x%2); + } + + int dec_to_hex(char hchar) { + if (hchar >= '0' && hchar <= '9') { + return (ord(hchar)-ord('0')); + } else { + return (10+ord(hchar)-ord('A')); + } + } + ''' + for func in c_function.search_string(source_code): + print(f"{func.name} ({func.type}) args: {func.args}") + + + prints: + + .. testoutput:: + + is_odd (int) args: [['int', 'x']] + dec_to_hex (int) args: [['char', 'hchar']] + """ + return _NestedExpr( + opener, closer, content=content, ignore_expr=ignore_expr, **kwargs + ) + + +def _makeTags(tagStr, xml, suppress_LT=Suppress("<"), suppress_GT=Suppress(">")): + """Internal helper to construct opening and closing tag expressions, + given a tag name""" + if isinstance(tagStr, str_type): + resname = tagStr + tagStr = Keyword(tagStr, caseless=not xml) + else: + resname = tagStr.name + + tagAttrName = Word(alphas, alphanums + "_-:") + if xml: + tagAttrValue = dbl_quoted_string.copy().set_parse_action(remove_quotes) + openTag = ( + suppress_LT + + tagStr("tag") + + Dict(ZeroOrMore(Group(tagAttrName + Suppress("=") + tagAttrValue))) + + Opt("/", default=[False])("empty").set_parse_action( + lambda s, l, t: t[0] == "/" + ) + + suppress_GT + ) + else: + tagAttrValue = quoted_string.copy().set_parse_action(remove_quotes) | Word( + printables, exclude_chars=">" + ) + openTag = ( + suppress_LT + + tagStr("tag") + + Dict( + ZeroOrMore( + Group( + tagAttrName.set_parse_action(lambda t: t[0].lower()) + + Opt(Suppress("=") + tagAttrValue) + ) + ) + ) + + Opt("/", default=[False])("empty").set_parse_action( + lambda s, l, t: t[0] == "/" + ) + + suppress_GT + ) + closeTag = Combine(Literal("", adjacent=False) + + openTag.set_name(f"<{resname}>") + # add start results name in parse action now that ungrouped names are not reported at two levels + openTag.add_parse_action( + lambda t: t.__setitem__( + "start" + "".join(resname.replace(":", " ").title().split()), t.copy() + ) + ) + closeTag = closeTag( + "end" + "".join(resname.replace(":", " ").title().split()) + ).set_name(f"") + openTag.tag = resname + closeTag.tag = resname + openTag.tag_body = SkipTo(closeTag()) + return openTag, closeTag + + +def make_html_tags( + tag_str: Union[str, ParserElement], +) -> tuple[ParserElement, ParserElement]: + """Helper to construct opening and closing tag expressions for HTML, + given a tag name. Matches tags in either upper or lower case, + attributes with namespaces and with quoted or unquoted values. + + Example: + + .. testcode:: + + text = 'More info at the pyparsing wiki page' + # make_html_tags returns pyparsing expressions for the opening and + # closing tags as a 2-tuple + a, a_end = make_html_tags("A") + link_expr = a + SkipTo(a_end)("link_text") + a_end + + for link in link_expr.search_string(text): + # attributes in the tag (like "href" shown here) are + # also accessible as named results + print(link.link_text, '->', link.href) + + prints: + + .. testoutput:: + + pyparsing -> https://github.com/pyparsing/pyparsing/wiki + """ + return _makeTags(tag_str, False) + + +def make_xml_tags( + tag_str: Union[str, ParserElement], +) -> tuple[ParserElement, ParserElement]: + """Helper to construct opening and closing tag expressions for XML, + given a tag name. Matches tags only in the given upper/lower case. + + Example: similar to :class:`make_html_tags` + """ + return _makeTags(tag_str, True) + + +any_open_tag: ParserElement +any_close_tag: ParserElement +any_open_tag, any_close_tag = make_html_tags( + Word(alphas, alphanums + "_:").set_name("any tag") +) + +_htmlEntityMap = {k.rstrip(";"): v for k, v in html.entities.html5.items()} +_most_common_entities = "nbsp lt gt amp quot apos cent pound euro copy".replace( + " ", "|" +) +common_html_entity = Regex( + lambda: f"&(?P{_most_common_entities}|{make_compressed_re(_htmlEntityMap)});" +).set_name("common HTML entity") + + +def replace_html_entity(s, l, t): + """Helper parser action to replace common HTML entities with their special characters""" + return _htmlEntityMap.get(t.entity) + + +class OpAssoc(Enum): + """Enumeration of operator associativity + - used in constructing InfixNotationOperatorSpec for :class:`infix_notation`""" + + LEFT = 1 + RIGHT = 2 + + +InfixNotationOperatorArgType = Union[ + ParserElement, str, tuple[Union[ParserElement, str], Union[ParserElement, str]] +] +InfixNotationOperatorSpec = Union[ + tuple[ + InfixNotationOperatorArgType, + int, + OpAssoc, + typing.Optional[ParseAction], + ], + tuple[ + InfixNotationOperatorArgType, + int, + OpAssoc, + ], +] + + +class _ParserState(Enum): + EXPECT_OPERAND = auto() + EXPECT_OPERATOR = auto() + + +class _OpType(Enum): + PREFIX = auto() + POSTFIX = auto() + INFIX2 = auto() + INFIX2_RIGHT = auto() + TERNARY_LEFT_STAGE1 = auto() + TERNARY_LEFT_STAGE2 = auto() + TERNARY_RIGHT_STAGE1 = auto() + TERNARY_RIGHT_STAGE2 = auto() + LPAR = auto() + + +class _InfixNotationOperatorSpec(NamedTuple): + op: InfixNotationOperatorArgType + arity: int + op_type: _OpType + parse_action: typing.Optional[list[Callable]] + + +class _InfixNotation(ParseElementEnhance): + """ + An iterative / stack-based implementation of infix_notation (using operator-precedence / + shunting-yard style evaluation with an explicit stack). + Prevents Python recursion limits from being exceeded on deeply nested expressions or long chains. + """ + def __init__( + self, + base_expr: ParserElement, + op_list: list[_InfixNotationOperatorSpec], + lpar: Union[str, ParserElement] = Suppress("("), + rpar: Union[str, ParserElement] = Suppress(")"), + ): + from .core import _trim_arity + + while isinstance(base_expr, _InfixNotation): + op_list[:0] = base_expr.op_list[:] # type: ignore[has-type] + base_expr = base_expr.base_expr # type: ignore[has-type] + + super().__init__(base_expr, savelist=True) + self.base_expr = base_expr + self.op_list = op_list + self.lpar = Suppress(lpar) if isinstance(lpar, str) else lpar + self.rpar = Suppress(rpar) if isinstance(rpar, str) else rpar + self.keep_parens = not (isinstance(self.lpar, Suppress) and isinstance(self.rpar, Suppress)) + self.errmsg = None + + # Classify operators by arity and associativity + # Precedence is defined by order in op_list (higher index in op_list = lower precedence) + # We assign higher numeric precedence to earlier entries in op_list + self.prefix_ops: list[_InfixNotationOperatorSpec] = [] # (expr, prec, assoc, pa_list) + self.postfix_ops: list[_InfixNotationOperatorSpec] = [] # (expr, prec, assoc, pa_list) + self.infix_ops = [] # type: ignore[var-annotated] + + total_ops = len(op_list) + for idx, oper_def in enumerate(op_list): + op_expr, arity, assoc, *pa_opt = (oper_def + (None,))[:4] + pa = pa_opt[0] if pa_opt else None + pa_list = ( + [_trim_arity(f) for f in pa] + if isinstance(pa, (tuple, list)) + else ([_trim_arity(pa)] if pa is not None else []) + ) + + if not 1 <= arity <= 3: + raise ValueError("operator must be unary (1), binary (2), or ternary (3)") + + if assoc not in (OpAssoc.LEFT, OpAssoc.RIGHT): + raise ValueError("operator must indicate right or left associativity") + + # Precedence: top of list has highest precedence + prec = (total_ops - idx) * 10 + + if arity == 1: + if isinstance(op_expr, str_type): + op_expr = Literal(op_expr) + if assoc is OpAssoc.RIGHT: + self.prefix_ops.append((op_expr, prec, assoc, pa_list)) + else: + self.postfix_ops.append((op_expr, prec, assoc, pa_list)) + elif arity == 2: + if op_expr is not None and isinstance(op_expr, str_type): + op_expr = Literal(op_expr) + self.infix_ops.append((op_expr, prec, assoc, pa_list, 2, None)) + elif arity == 3: + if not isinstance(op_expr, (tuple, list)) or len(op_expr) != 2: + raise ValueError( + "if numterms=3, opExpr must be a tuple or list of two expressions" + ) + op1, op2 = op_expr + if isinstance(op1, str_type): + op1 = Literal(op1) + if isinstance(op2, str_type): + op2 = Literal(op2) + self.infix_ops.append((op1, prec, assoc, pa_list, 3, op2)) + + def _generateDefaultName(self) -> str: + return f"{self.base_expr} infix expression" + + def _run_parse_actions(self, pa_list, instring, loc, tokens): + ret_tokens = tokens + for fn in pa_list: + res = fn(instring, loc, ret_tokens) + if res is not None and res is not ret_tokens: + if isinstance(res, (ParseResults, list, tuple)): + ret_tokens = ParseResults(res, aslist=True) + else: + return res + return ret_tokens + + def _apply_operator(self, op_info, operand_stack, instring): + op_type = op_info["type"] + pa_list = op_info.get("pa", []) + start_loc = op_info.get("loc", 0) + + if op_type is _OpType.PREFIX: + op_tok = op_info["op"] + arg = operand_stack.pop() + tokens = [] + if isinstance(op_tok, (list, ParseResults)): + tokens.extend(op_tok) + elif op_tok is not None: + tokens.append(op_tok) + tokens.append(arg) + tokens_pr = ParseResults(tokens) + if pa_list: + res = self._run_parse_actions(pa_list, instring, start_loc, ParseResults([tokens_pr])) + else: + res = tokens_pr + operand_stack.append(res) + + elif op_type is _OpType.POSTFIX: + arg = operand_stack.pop() + if isinstance(arg, ParseResults): + res_pr = arg.copy() + elif isinstance(arg, list): + res_pr = ParseResults(arg) + else: + res_pr = ParseResults([arg]) + for op_tok in op_info["ops"]: + if isinstance(op_tok, ParseResults): + res_pr += op_tok + elif isinstance(op_tok, list): + res_pr.extend(op_tok) + elif op_tok is not None: + res_pr.append(op_tok) + if pa_list: + res = self._run_parse_actions(pa_list, instring, start_loc, ParseResults([res_pr])) + else: + res = res_pr + operand_stack.append(res) + + elif op_type is _OpType.INFIX2: + ops = op_info["ops"] + num_ops = len(ops) + args = [operand_stack.pop() for _ in range(num_ops + 1)] + args.reverse() + tokens = [args[0]] + for i in range(num_ops): + op_tok = ops[i] + if isinstance(op_tok, (list, ParseResults)): + tokens.extend(op_tok) + elif op_tok is not None: + tokens.append(op_tok) + tokens.append(args[i + 1]) + tokens_pr = ParseResults(tokens) + if pa_list: + res = self._run_parse_actions(pa_list, instring, start_loc, ParseResults([tokens_pr])) + else: + res = tokens_pr + operand_stack.append(res) + + elif op_type is _OpType.INFIX2_RIGHT: + op_tok = op_info["op"] + right = operand_stack.pop() + left = operand_stack.pop() + tokens = [left] + if isinstance(op_tok, (list, ParseResults)): + tokens.extend(op_tok) + elif op_tok is not None: + tokens.append(op_tok) + tokens.append(right) + tokens_pr = ParseResults(tokens) + if pa_list: + res = self._run_parse_actions(pa_list, instring, start_loc, ParseResults([tokens_pr])) + else: + res = tokens_pr + operand_stack.append(res) + + elif op_type is _OpType.TERNARY_LEFT_STAGE2: + ops_list = op_info["ops"] + num_ops = len(ops_list) + num_operands = 2 * num_ops + 1 + args = [operand_stack.pop() for _ in range(num_operands)] + args.reverse() + tokens = [args[0]] + for i in range(num_ops): + op1_tok, op2_tok = ops_list[i] + if isinstance(op1_tok, (list, ParseResults)): + tokens.extend(op1_tok) + elif op1_tok is not None: + tokens.append(op1_tok) + tokens.append(args[2 * i + 1]) + if isinstance(op2_tok, (list, ParseResults)): + tokens.extend(op2_tok) + elif op2_tok is not None: + tokens.append(op2_tok) + tokens.append(args[2 * i + 2]) + tokens_pr = ParseResults(tokens) + if pa_list: + res = self._run_parse_actions(pa_list, instring, start_loc, ParseResults([tokens_pr])) + else: + res = tokens_pr + operand_stack.append(res) + + elif op_type is _OpType.TERNARY_RIGHT_STAGE2: + op1_tok = op_info["op1"] + op2_tok = op_info["op2"] + arg3 = operand_stack.pop() + arg2 = operand_stack.pop() + arg1 = operand_stack.pop() + tokens = [arg1] + if isinstance(op1_tok, (list, ParseResults)): + tokens.extend(op1_tok) + elif op1_tok is not None: + tokens.append(op1_tok) + tokens.append(arg2) + if isinstance(op2_tok, (list, ParseResults)): + tokens.extend(op2_tok) + elif op2_tok is not None: + tokens.append(op2_tok) + tokens.append(arg3) + tokens_pr = ParseResults(tokens) + if pa_list: + res = self._run_parse_actions(pa_list, instring, start_loc, ParseResults([tokens_pr])) + else: + res = tokens_pr + operand_stack.append(res) + + return bool(pa_list) + + def parseImpl(self, instring, loc, do_actions=True): + operand_stack = [] + operator_stack = [] + last_pa_applied = [False] + + def reduce_operators(min_prec): + while operator_stack: + top = operator_stack[-1] + if top["type"] in (_OpType.LPAR, _OpType.TERNARY_LEFT_STAGE1, _OpType.TERNARY_RIGHT_STAGE1): + break + if top["prec"] > min_prec: + op_info = operator_stack.pop() + last_pa_applied[0] = self._apply_operator(op_info, operand_stack, instring) + else: + break + + state = _ParserState.EXPECT_OPERAND + paren_depth = 0 + + while True: + try: + loc = self.preParse(instring, loc) + except ParseException: + pass + + if state is _ParserState.EXPECT_OPERAND: + # 1. Try prefix operators + matched_prefix = False + for op_expr, prec, assoc, pa_list in self.prefix_ops: + try: + next_loc, toks = op_expr._parse(instring, loc, do_actions=do_actions) + op_tok = toks.as_list()[0] if len(toks) == 1 else toks.as_list() + operator_stack.append({ + "type": _OpType.PREFIX, + "op": op_tok, + "prec": prec, + "assoc": assoc, + "pa": pa_list if do_actions else [], + "loc": loc, + }) + loc = next_loc + matched_prefix = True + break + except ParseException: + pass + if matched_prefix: + continue + + # 2. Try base_expr + try: + next_loc, base_toks = self.base_expr._parse(instring, loc, do_actions=do_actions) + if not base_toks and not base_toks._tokdict: + loc = next_loc + continue + operand = base_toks[0] if len(base_toks) == 1 else base_toks + operand_stack.append(operand) + loc = next_loc + state = _ParserState.EXPECT_OPERATOR + continue + except ParseException: + pass + + # 3. Try lpar + try: + next_loc, lpar_toks = self.lpar._parse(instring, loc, do_actions=do_actions) + operator_stack.append({ + "type": _OpType.LPAR, + "paren_toks": lpar_toks.as_list(), + "loc": loc, + }) + paren_depth += 1 + loc = next_loc + continue + except ParseException: + raise ParseException(instring, loc, f"Expected {self.base_expr}") + + elif state is _ParserState.EXPECT_OPERATOR: + # 1. Try postfix operators + matched_postfix = False + for op_expr, prec, assoc, pa_list in self.postfix_ops: + try: + next_loc, toks = op_expr._parse(instring, loc, do_actions=do_actions) + op_tok = toks + if ( + operator_stack + and operator_stack[-1]["type"] is _OpType.POSTFIX + and operator_stack[-1]["prec"] == prec + and operator_stack[-1]["assoc"] is OpAssoc.LEFT + ): + operator_stack[-1]["ops"].append(op_tok) + else: + reduce_operators(prec) + operator_stack.append({ + "type": _OpType.POSTFIX, + "ops": [op_tok], + "prec": prec, + "assoc": assoc, + "pa": pa_list if do_actions else [], + "loc": loc, + }) + loc = next_loc + matched_postfix = True + break + except ParseException: + pass + if matched_postfix: + continue + + # 2. Try rpar if inside parens + if paren_depth > 0: + try: + next_loc, rpar_toks = self.rpar._parse(instring, loc, do_actions=do_actions) + reduce_operators(-1) # reduce all operators inside this paren + if operator_stack and operator_stack[-1]["type"] is _OpType.LPAR: + lpar_info = operator_stack.pop() + if self.keep_parens: + top_val = operand_stack.pop() + operand_stack.append(ParseResults([*lpar_info["paren_toks"], top_val, *rpar_toks.as_list()])) + paren_depth -= 1 + loc = next_loc + continue + except ParseException: + pass + + # 3. Try matching op2 for an open ternary operator (STAGE1) + matched_op2 = False + for i in range(len(operator_stack) - 1, -1, -1): + item = operator_stack[i] + if item["type"] is _OpType.LPAR: + break + if item["type"] in (_OpType.TERNARY_LEFT_STAGE1, _OpType.TERNARY_RIGHT_STAGE1): + try: + next_loc, toks = item["op2_expr"]._parse(instring, loc, do_actions=do_actions) + op2_tok = toks.as_list()[0] if len(toks) == 1 else toks.as_list() + while operator_stack and operator_stack[-1] is not item: + op_info = operator_stack.pop() + self._apply_operator(op_info, operand_stack, instring) + if item["type"] is _OpType.TERNARY_LEFT_STAGE1: + item["type"] = _OpType.TERNARY_LEFT_STAGE2 + item["ops"][-1].append(op2_tok) + else: + item["type"] = _OpType.TERNARY_RIGHT_STAGE2 + item["op2"] = op2_tok + loc = next_loc + matched_op2 = True + state = _ParserState.EXPECT_OPERAND + break + except ParseException: + pass + if matched_op2: + continue + + def _check_operand_follows(check_loc): + for p_op, _, _, _ in self.prefix_ops: + try: + p_op._parse(instring, check_loc, do_actions=False) + return True + except ParseException: + pass + try: + self.base_expr._parse(instring, check_loc, do_actions=False) + return True + except ParseException: + pass + try: + self.lpar._parse(instring, check_loc, do_actions=False) + return True + except ParseException: + pass + return False + + # 4. Try infix binary and ternary operators + matched_infix = False + for op_expr, prec, assoc, pa_list, arity, op2_expr in self.infix_ops: + if arity == 2: + if op_expr is None: + if not _check_operand_follows(loc): + continue + next_loc = loc + op_tok = None + else: + try: + next_loc, toks = op_expr._parse(instring, loc, do_actions=do_actions) + except ParseException: + continue + if next_loc == loc: + if not _check_operand_follows(loc): + continue + op_tok = (toks.as_list()[0] if len(toks) == 1 else toks.as_list()) if toks else None + else: + op_tok = toks.as_list()[0] if len(toks) == 1 else toks.as_list() + + if assoc is OpAssoc.LEFT: + reduce_operators(prec) + if ( + operator_stack + and operator_stack[-1]["type"] is _OpType.INFIX2 + and operator_stack[-1]["prec"] == prec + ): + operator_stack[-1]["ops"].append(op_tok) + else: + operator_stack.append({ + "type": _OpType.INFIX2, + "ops": [op_tok], + "prec": prec, + "assoc": assoc, + "pa": pa_list if do_actions else [], + "loc": loc, + }) + else: + reduce_operators(prec) + operator_stack.append({ + "type": _OpType.INFIX2_RIGHT, + "op": op_tok, + "prec": prec, + "assoc": assoc, + "pa": pa_list if do_actions else [], + "loc": loc, + }) + loc = next_loc + matched_infix = True + state = _ParserState.EXPECT_OPERAND + break + elif arity == 3: + try: + next_loc, toks = op_expr._parse(instring, loc, do_actions=do_actions) + if next_loc == loc and not _check_operand_follows(loc): + continue + op_tok = toks.as_list()[0] if len(toks) == 1 else toks.as_list() + if assoc is OpAssoc.LEFT: + if ( + operator_stack + and operator_stack[-1]["type"] is _OpType.TERNARY_LEFT_STAGE2 + and operator_stack[-1]["prec"] == prec + ): + operator_stack[-1]["type"] = _OpType.TERNARY_LEFT_STAGE1 + operator_stack[-1]["ops"].append([op_tok]) + else: + reduce_operators(prec) + operator_stack.append({ + "type": _OpType.TERNARY_LEFT_STAGE1, + "ops": [[op_tok]], + "op2_expr": op2_expr, + "prec": prec, + "assoc": assoc, + "pa": pa_list if do_actions else [], + "loc": loc, + }) + else: + reduce_operators(prec) + operator_stack.append({ + "type": _OpType.TERNARY_RIGHT_STAGE1, + "op1": op_tok, + "op2_expr": op2_expr, + "prec": prec, + "assoc": assoc, + "pa": pa_list if do_actions else [], + "loc": loc, + }) + loc = next_loc + matched_infix = True + state = _ParserState.EXPECT_OPERAND + break + except ParseException: + pass + if matched_infix: + continue + + # No more operators can be consumed at this level + break + + # Reduce remaining operators + reduce_operators(-1) + + if paren_depth != 0 or len(operand_stack) != 1 or operator_stack: + raise ParseException(instring, loc, "Unbalanced parentheses or expression syntax error") + + final_result = operand_stack.pop() + if last_pa_applied[0] and isinstance(final_result, ParseResults): + return loc, final_result + else: + return loc, ParseResults([final_result]) + + +def infix_notation(base_expr, op_list, lpar="(", rpar=")"): + """Helper method for constructing grammars of expressions made up of + operators working in a precedence hierarchy. Operators may be unary + or binary, left- or right-associative. Parse actions can also be + attached to operator expressions. The generated parser will also + recognize the use of parentheses to override operator precedences + (see example below). + + Note: if you define a deep operator list, you may see performance + issues when using infix_notation. See + :class:`ParserElement.enable_packrat` for a mechanism to potentially + improve your parser performance. + + Parameters: + + :param base_expr: expression representing the most basic operand to + be used in the expression + :param op_list: list of tuples, one for each operator precedence level + in the expression grammar; each tuple is of the form ``(op_expr, + num_operands, right_left_assoc, (optional)parse_action)``, where: + + - ``op_expr`` is the pyparsing expression for the operator; may also + be a string, which will be converted to a Literal; if ``num_operands`` + is 3, ``op_expr`` is a tuple of two expressions, for the two + operators separating the 3 terms + - ``num_operands`` is the number of terms for this operator (must be 1, + 2, or 3) + - ``right_left_assoc`` is the indicator whether the operator is right + or left associative, using the pyparsing-defined constants + ``OpAssoc.RIGHT`` and ``OpAssoc.LEFT``. + - ``parse_action`` is the parse action to be associated with + expressions matching this operator expression (the parse action + tuple member may be omitted); if the parse action is passed + a tuple or list of functions, this is equivalent to calling + ``set_parse_action(*fn)`` + (:class:`ParserElement.set_parse_action`) + + :param lpar: expression for matching left-parentheses; if passed as a + str, then will be parsed as ``Suppress(lpar)``. If lpar is passed as + an expression (such as ``Literal('(')``), then it will be kept in + the parsed results, and grouped with them. (default= ``Suppress('(')``) + :param rpar: expression for matching right-parentheses; if passed as a + str, then will be parsed as ``Suppress(rpar)``. If rpar is passed as + an expression (such as ``Literal(')')``), then it will be kept in + the parsed results, and grouped with them. (default= ``Suppress(')')``) + + Example: + + .. testcode:: + + # simple example of four-function arithmetic with ints and + # variable names + integer = pyparsing_common.signed_integer + varname = pyparsing_common.identifier + + arith_expr = infix_notation(integer | varname, + [ + ('-', 1, OpAssoc.RIGHT), + (one_of('* /'), 2, OpAssoc.LEFT), + (one_of('+ -'), 2, OpAssoc.LEFT), + ]) + + arith_expr.run_tests(''' + 5+3*6 + (5+3)*6 + (5+x)*y + -2--11 + ''', full_dump=False) + + prints: + + .. testoutput:: + :options: +NORMALIZE_WHITESPACE + + + 5+3*6 + [[5, '+', [3, '*', 6]]] + + (5+3)*6 + [[[5, '+', 3], '*', 6]] + + (5+x)*y + [[[5, '+', 'x'], '*', 'y']] + + -2--11 + [[['-', 2], '-', ['-', 11]]] + """ + return _InfixNotation(base_expr, op_list, lpar=lpar, rpar=rpar) + + +def indentedBlock(blockStatementExpr, indentStack, indent=True, backup_stacks=[]): + """ + .. deprecated:: 3.0.0 + Use the :class:`IndentedBlock` class instead. Note that `IndentedBlock` + has a difference method signature. + + Helper method for defining space-delimited indentation blocks, + such as those used to define block statements in Python source code. + + :param blockStatementExpr: expression defining syntax of statement that + is repeated within the indented block + + :param indentStack: list created by caller to manage indentation stack + (multiple ``statementWithIndentedBlock`` expressions within a single + grammar should share a common ``indentStack``) + + :param indent: boolean indicating whether block must be indented beyond + the current level; set to ``False`` for block of left-most statements + + A valid block must contain at least one ``blockStatement``. + + (Note that indentedBlock uses internal parse actions which make it + incompatible with packrat parsing.) + + Example: + + .. testcode:: + + data = ''' + def A(z): + A1 + B = 100 + G = A2 + A2 + A3 + B + def BB(a,b,c): + BB1 + def BBA(): + bba1 + bba2 + bba3 + C + D + def spam(x,y): + def eggs(z): + pass + ''' + + indentStack = [1] + stmt = Forward() + + identifier = Word(alphas, alphanums) + funcDecl = ("def" + identifier + Group("(" + Opt(delimitedList(identifier)) + ")") + ":") + func_body = indentedBlock(stmt, indentStack) + funcDef = Group(funcDecl + func_body) + + rvalue = Forward() + funcCall = Group(identifier + "(" + Opt(delimitedList(rvalue)) + ")") + rvalue << (funcCall | identifier | Word(nums)) + assignment = Group(identifier + "=" + rvalue) + stmt << (funcDef | assignment | identifier) + + module_body = stmt[1, ...] + + parseTree = module_body.parseString(data) + parseTree.pprint() + + prints: + + .. testoutput:: + + [['def', + 'A', + ['(', 'z', ')'], + ':', + [['A1'], [['B', '=', '100']], [['G', '=', 'A2']], ['A2'], ['A3']]], + 'B', + ['def', + 'BB', + ['(', 'a', 'b', 'c', ')'], + ':', + [['BB1'], [['def', 'BBA', ['(', ')'], ':', [['bba1'], ['bba2'], ['bba3']]]]]], + 'C', + 'D', + ['def', + 'spam', + ['(', 'x', 'y', ')'], + ':', + [[['def', 'eggs', ['(', 'z', ')'], ':', [['pass']]]]]]] + """ + warnings.warn( + f"{'indentedBlock'!r} deprecated - use {'IndentedBlock'!r}", + PyparsingDeprecationWarning, + stacklevel=2, + ) + + backup_stacks.append(indentStack[:]) + + def reset_stack(): + indentStack[:] = backup_stacks[-1] + + def checkPeerIndent(s, l, t): + if l >= len(s): + return + curCol = col(l, s) + if curCol != indentStack[-1]: + if curCol > indentStack[-1]: + raise ParseException(s, l, "illegal nesting") + raise ParseException(s, l, "not a peer entry") + + def checkSubIndent(s, l, t): + curCol = col(l, s) + if curCol > indentStack[-1]: + indentStack.append(curCol) + else: + raise ParseException(s, l, "not a subentry") + + def checkUnindent(s, l, t): + if l >= len(s): + return + curCol = col(l, s) + if not (indentStack and curCol in indentStack): + raise ParseException(s, l, "not an unindent") + if curCol < indentStack[-1]: + indentStack.pop() + + NL = OneOrMore(LineEnd().set_whitespace_chars("\t ").suppress()) + INDENT = (Empty() + Empty().set_parse_action(checkSubIndent)).set_name("INDENT") + PEER = Empty().set_parse_action(checkPeerIndent).set_name("") + UNDENT = Empty().set_parse_action(checkUnindent).set_name("UNINDENT") + if indent: + smExpr = Group( + Opt(NL) + + INDENT + + OneOrMore(PEER + Group(blockStatementExpr) + Opt(NL)) + + UNDENT + ) + else: + smExpr = Group( + Opt(NL) + + OneOrMore(PEER + Group(blockStatementExpr) + Opt(NL)) + + Opt(UNDENT) + ) + + # add a parse action to remove backup_stack from list of backups + smExpr.add_parse_action( + lambda: backup_stacks.pop(-1) and None if backup_stacks else None + ) + smExpr.set_fail_action(lambda a, b, c, d: reset_stack()) + blockStatementExpr.ignore(_bslash + LineEnd()) + return smExpr.set_name("indented block") + + +# it's easy to get these comment structures wrong - they're very common, +# so may as well make them available +c_style_comment = Regex(r"/\*(?:[^*]|\*(?!/))*\*\/").set_name("C style comment") +"Comment of the form ``/* ... */``" + +html_comment = Regex(r"").set_name("HTML comment") +"Comment of the form ````" + +rest_of_line = Regex(r".*").leave_whitespace().set_name("rest of line") +dbl_slash_comment = Regex(r"//(?:\\\n|[^\n])*").set_name("// comment") +"Comment of the form ``// ... (to end of line)``" + +cpp_style_comment = Regex( + r"(?:/\*(?:[^*]|\*(?!/))*\*\/)|(?://(?:\\\n|[^\n])*)" +).set_name("C++ style comment") +"Comment of either form :class:`c_style_comment` or :class:`dbl_slash_comment`" + +java_style_comment = cpp_style_comment +"Same as :class:`cpp_style_comment`" + +python_style_comment = Regex(r"#.*").set_name("Python style comment") +"Comment of the form ``# ... (to end of line)``" + + +# build list of built-in expressions, for future reference if a global default value +# gets updated +_builtin_exprs: list[ParserElement] = [ + v for v in vars().values() if isinstance(v, ParserElement) +] + + +# compatibility function, superseded by DelimitedList class +def delimited_list( + expr: Union[str, ParserElement], + delim: Union[str, ParserElement] = ",", + combine: bool = False, + min: typing.Optional[int] = None, + max: typing.Optional[int] = None, + *, + allow_trailing_delim: bool = False, +) -> ParserElement: + """ + .. deprecated:: 3.1.0 + Use the :class:`DelimitedList` class instead. + """ + return DelimitedList( + expr, delim, combine, min, max, allow_trailing_delim=allow_trailing_delim + ) + + +# Compatibility synonyms +# fmt: off +opAssoc = OpAssoc +anyOpenTag = any_open_tag +anyCloseTag = any_close_tag +commonHTMLEntity = common_html_entity +cStyleComment = c_style_comment +htmlComment = html_comment +restOfLine = rest_of_line +dblSlashComment = dbl_slash_comment +cppStyleComment = cpp_style_comment +javaStyleComment = java_style_comment +pythonStyleComment = python_style_comment +delimitedList = replaced_by_pep8("delimitedList", DelimitedList) +delimited_list = replaced_by_pep8("delimited_list", DelimitedList) +countedArray = replaced_by_pep8("countedArray", counted_array) +matchPreviousLiteral = replaced_by_pep8("matchPreviousLiteral", match_previous_literal) +matchPreviousExpr = replaced_by_pep8("matchPreviousExpr", match_previous_expr) +oneOf = replaced_by_pep8("oneOf", one_of) +dictOf = replaced_by_pep8("dictOf", dict_of) +originalTextFor = replaced_by_pep8("originalTextFor", original_text_for) +nestedExpr = replaced_by_pep8("nestedExpr", nested_expr) +makeHTMLTags = replaced_by_pep8("makeHTMLTags", make_html_tags) +makeXMLTags = replaced_by_pep8("makeXMLTags", make_xml_tags) +replaceHTMLEntity = replaced_by_pep8("replaceHTMLEntity", replace_html_entity) +infixNotation = replaced_by_pep8("infixNotation", infix_notation) +# fmt: on diff --git a/.venv/lib/python3.12/site-packages/pyparsing/py.typed b/.venv/lib/python3.12/site-packages/pyparsing/py.typed new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/.venv/lib/python3.12/site-packages/pyparsing/results.py b/.venv/lib/python3.12/site-packages/pyparsing/results.py new file mode 100644 index 0000000000000000000000000000000000000000..f7d674f180b6721187da8945cfad64a2a8ac67a5 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/pyparsing/results.py @@ -0,0 +1,928 @@ +# results.py + +from __future__ import annotations + +import collections +from collections.abc import ( + MutableMapping, + Mapping, + MutableSequence, + Iterator, + Iterable, +) +import pprint +from typing import Any + +from .util import deprecate_argument, _is_iterable, _flatten + + +str_type: tuple[type, ...] = (str, bytes) +_generator_type = type((_ for _ in ())) +NULL_SLICE: slice = slice(None) + + +class _ParseResultsWithOffset: + tup: tuple[ParseResults, int] + __slots__ = ["tup"] + + def __init__(self, p1: ParseResults, p2: int) -> None: + self.tup: tuple[ParseResults, int] = (p1, p2) + + def __getitem__(self, i): + return self.tup[i] + + def __getstate__(self): + return self.tup + + def __setstate__(self, *args): + self.tup = args[0] + + +class ParseResults: + """Structured parse results, to provide multiple means of access to + the parsed data: + + - as a list (``len(results)``) + - by list index (``results[0], results[1]``, etc.) + - by attribute (``results.`` - see :class:`ParserElement.set_results_name`) + + Example: + + .. testcode:: + + integer = Word(nums) + date_str = (integer.set_results_name("year") + '/' + + integer.set_results_name("month") + '/' + + integer.set_results_name("day")) + # equivalent form: + # date_str = (integer("year") + '/' + # + integer("month") + '/' + # + integer("day")) + + # parse_string returns a ParseResults object + result = date_str.parse_string("1999/12/31") + + def test(s, fn=repr): + print(f"{s} -> {fn(eval(s))}") + + test("list(result)") + test("result[0]") + test("result['month']") + test("result.day") + test("'month' in result") + test("'minutes' in result") + test("result.dump()", str) + + prints: + + .. testoutput:: + + list(result) -> ['1999', '/', '12', '/', '31'] + result[0] -> '1999' + result['month'] -> '12' + result.day -> '31' + 'month' in result -> True + 'minutes' in result -> False + result.dump() -> ['1999', '/', '12', '/', '31'] + - day: '31' + - month: '12' + - year: '1999' + + """ + + _null_values: tuple[Any, ...] = (None, [], ()) + + _name: str + _parent: ParseResults + _all_names: set[str] + _modal: bool + _toklist: list[Any] + _tokdict: dict[str, Any] + + __slots__ = ( + "_name", + "_parent", + "_all_names", + "_modal", + "_toklist", + "_tokdict", + ) + + class List(list): + """ + Simple wrapper class to distinguish parsed list results that should be preserved + as actual Python lists, instead of being converted to :class:`ParseResults`: + + .. testcode:: + + import pyparsing as pp + ppc = pp.common + + LBRACK, RBRACK, LPAR, RPAR = pp.Suppress.using_each("[]()") + element = pp.Forward() + item = ppc.integer + item_list = pp.DelimitedList(element) + element_list = LBRACK + item_list + RBRACK | LPAR + item_list + RPAR + element <<= item | element_list + + # add parse action to convert from ParseResults + # to actual Python collection types + @element_list.add_parse_action + def as_python_list(t): + return pp.ParseResults.List(t.as_list()) + + element.run_tests(''' + 100 + [2,3,4] + [[2, 1],3,4] + [(2, 1),3,4] + (2,3,4) + ([2, 3], 4) + ''', post_parse=lambda s, r: (r[0], type(r[0])) + ) + + prints: + + .. testoutput:: + :options: +NORMALIZE_WHITESPACE + + + 100 + (100, ) + + [2,3,4] + ([2, 3, 4], ) + + [[2, 1],3,4] + ([[2, 1], 3, 4], ) + + [(2, 1),3,4] + ([[2, 1], 3, 4], ) + + (2,3,4) + ([2, 3, 4], ) + + ([2, 3], 4) + ([[2, 3], 4], ) + + (Used internally by :class:`Group` when `aslist=True`.) + """ + + def __new__(cls, contained=None): + if contained is None: + contained = [] + + if not isinstance(contained, list): + raise TypeError( + f"{cls.__name__} may only be constructed with a list, not {type(contained).__name__}" + ) + + return list.__new__(cls) + + def __new__(cls, toklist=None, name=None, **kwargs): + if isinstance(toklist, ParseResults): + return toklist + self = object.__new__(cls) + self._name = None + self._parent = None + self._all_names = set() + + if toklist is None: + self._toklist = [] + elif isinstance(toklist, (list, _generator_type)): + self._toklist = ( + [toklist[:]] + if isinstance(toklist, ParseResults.List) + else list(toklist) + ) + else: + self._toklist = [toklist] + self._tokdict = dict() + return self + + # Performance tuning: we construct a *lot* of these, so keep this + # constructor as small and fast as possible + def __init__( + self, + toklist=None, + name=None, + aslist=True, + modal=True, + isinstance=isinstance, + **kwargs, + ) -> None: + asList = deprecate_argument(kwargs, "asList", True, new_name="aslist") + + asList = asList and aslist + self._tokdict: dict[str, _ParseResultsWithOffset] + self._modal = modal + + if name is None or name == "": + return + + if isinstance(name, int): + name = str(name) + + if not modal: + self._all_names = {name} + + self._name = name + + if toklist in self._null_values: + return + + if isinstance(toklist, (str_type, type)): + toklist = [toklist] + + if asList: + if isinstance(toklist, ParseResults): + self[name] = _ParseResultsWithOffset(ParseResults(toklist._toklist), 0) + else: + self[name] = _ParseResultsWithOffset(ParseResults(toklist[0]), 0) + self[name]._name = name + return + + try: + self[name] = toklist[0] + except (KeyError, TypeError, IndexError): + if toklist is not self: + self[name] = toklist + else: + self._name = name + + def __getitem__(self, i): + if isinstance(i, (int, slice)): + return self._toklist[i] + + if i not in self._all_names: + return self._tokdict[i][-1][0] + + return ParseResults([v[0] for v in self._tokdict[i]]) + + def __setitem__(self, k, v, isinstance=isinstance): + if isinstance(v, _ParseResultsWithOffset): + self._tokdict[k] = self._tokdict.get(k, list()) + [v] + sub = v[0] + elif isinstance(k, (int, slice)): + self._toklist[k] = v + sub = v + else: + self._tokdict[k] = self._tokdict.get(k, []) + [ + _ParseResultsWithOffset(v, 0) + ] + sub = v + if isinstance(sub, ParseResults): + sub._parent = self + + def __delitem__(self, i): + if not isinstance(i, (int, slice)): + del self._tokdict[i] + return + + # slight optimization if del results[:] + if i == NULL_SLICE: + self._toklist.clear() + return + + mylen = len(self._toklist) + del self._toklist[i] + + # convert int to slice + if isinstance(i, int): + if i < 0: + i += mylen + i = slice(i, i + 1) + # get removed indices + removed = list(range(*i.indices(mylen))) + removed.reverse() + # fixup indices in token dictionary + for occurrences in self._tokdict.values(): + for j in removed: + for k, (value, position) in enumerate(occurrences): + occurrences[k] = _ParseResultsWithOffset( + value, position - (position > j) + ) + + def __contains__(self, k) -> bool: + return k in self._tokdict + + def __len__(self) -> int: + return len(self._toklist) + + def __bool__(self) -> bool: + return not not (self._toklist or self._tokdict) + + def __iter__(self) -> Iterator: + return iter(self._toklist) + + def __reversed__(self) -> Iterator: + return iter(self._toklist[::-1]) + + def keys(self): + return iter(self._tokdict) + + def values(self): + return (self[k] for k in self.keys()) + + def items(self): + return ((k, self[k]) for k in self.keys()) + + def haskeys(self) -> bool: + """ + Since ``keys()`` returns an iterator, this method is helpful in bypassing + code that looks for the existence of any defined results names.""" + return not not self._tokdict + + def pop(self, *args, **kwargs): + """ + Removes and returns item at specified index (default= ``last``). + Supports both ``list`` and ``dict`` semantics for ``pop()``. If + passed no argument or an integer argument, it will use ``list`` + semantics and pop tokens from the list of parsed tokens. If passed + a non-integer argument (most likely a string), it will use ``dict`` + semantics and pop the corresponding value from any defined results + names. A second default return value argument is supported, just as in + ``dict.pop()``. + + Example: + + .. doctest:: + + >>> numlist = Word(nums)[...] + >>> print(numlist.parse_string("0 123 321")) + ['0', '123', '321'] + + >>> def remove_first(tokens): + ... tokens.pop(0) + ... + >>> numlist.add_parse_action(remove_first) + [W:(0-9)]... + >>> print(numlist.parse_string("0 123 321")) + ['123', '321'] + + >>> label = Word(alphas) + >>> patt = label("LABEL") + Word(nums)[1, ...] + >>> print(patt.parse_string("AAB 123 321").dump()) + ['AAB', '123', '321'] + - LABEL: 'AAB' + + >>> # Use pop() in a parse action to remove named result + >>> # (note that corresponding value is not + >>> # removed from list form of results) + >>> def remove_LABEL(tokens): + ... tokens.pop("LABEL") + ... return tokens + ... + >>> patt.add_parse_action(remove_LABEL) + {W:(A-Za-z) {W:(0-9)}...} + >>> print(patt.parse_string("AAB 123 321").dump()) + ['AAB', '123', '321'] + + """ + if not args: + args = [-1] + for k, v in kwargs.items(): + if k == "default": + args = (args[0], v) + else: + raise TypeError(f"pop() got an unexpected keyword argument {k!r}") + if isinstance(args[0], int) or len(args) == 1 or args[0] in self: + index = args[0] + ret = self[index] + del self[index] + return ret + else: + defaultvalue = args[1] + return defaultvalue + + def get(self, key, default_value=None): + """ + Returns named result matching the given key, or if there is no + such name, then returns the given ``default_value`` or ``None`` if no + ``default_value`` is specified. + + Similar to ``dict.get()``. + + Example: + + .. doctest:: + + >>> integer = Word(nums) + >>> date_str = integer("year") + '/' + integer("month") + '/' + integer("day") + + >>> result = date_str.parse_string("1999/12/31") + >>> result.get("year") + '1999' + >>> result.get("hour", "not specified") + 'not specified' + >>> result.get("hour") + + """ + if key in self: + return self[key] + else: + return default_value + + def insert(self, index, ins_string): + """ + Inserts new element at location index in the list of parsed tokens. + + Similar to ``list.insert()``. + + Example: + + .. doctest:: + + >>> numlist = Word(nums)[...] + >>> print(numlist.parse_string("0 123 321")) + ['0', '123', '321'] + + >>> # use a parse action to insert the parse location + >>> # in the front of the parsed results + >>> def insert_locn(locn, tokens): + ... tokens.insert(0, locn) + ... + >>> numlist.add_parse_action(insert_locn) + [W:(0-9)]... + >>> print(numlist.parse_string("0 123 321")) + [0, '0', '123', '321'] + + """ + self._toklist.insert(index, ins_string) + # fixup indices in token dictionary + for occurrences in self._tokdict.values(): + for k, (value, position) in enumerate(occurrences): + occurrences[k] = _ParseResultsWithOffset( + value, position + (position > index) + ) + + def append(self, item): + """ + Add single element to end of ``ParseResults`` list of elements. + + Example: + + .. doctest:: + + >>> numlist = Word(nums)[...] + >>> print(numlist.parse_string("0 123 321")) + ['0', '123', '321'] + + >>> # use a parse action to compute the sum of the parsed integers, + >>> # and add it to the end + >>> def append_sum(tokens): + ... tokens.append(sum(map(int, tokens))) + ... + >>> numlist.add_parse_action(append_sum) + [W:(0-9)]... + >>> print(numlist.parse_string("0 123 321")) + ['0', '123', '321', 444] + """ + self._toklist.append(item) + + def extend(self, itemseq): + """ + Add sequence of elements to end of :class:`ParseResults` list of elements. + + Example: + + .. testcode:: + + patt = Word(alphas)[1, ...] + + # use a parse action to append the reverse of the matched strings, + # to make a palindrome + def make_palindrome(tokens): + tokens.extend(reversed([t[::-1] for t in tokens])) + return ''.join(tokens) + + patt.add_parse_action(make_palindrome) + print(patt.parse_string("lskdj sdlkjf lksd")) + + prints: + + .. testoutput:: + + ['lskdjsdlkjflksddsklfjkldsjdksl'] + """ + if isinstance(itemseq, ParseResults): + self.__iadd__(itemseq) + else: + self._toklist.extend(itemseq) + + def clear(self): + """ + Clear all elements and results names. + """ + del self._toklist[:] + self._tokdict.clear() + + def __getattr__(self, name): + try: + return self[name] + except KeyError: + if name.startswith("__"): + raise AttributeError(name) + return "" + + def __add__(self, other: ParseResults) -> ParseResults: + ret = self.copy() + ret += other + return ret + + def __iadd__(self, other: ParseResults) -> ParseResults: + if not other: + return self + + if other._tokdict: + offset = len(self._toklist) + addoffset = lambda a: offset if a < 0 else a + offset + otheritems = other._tokdict.items() + otherdictitems = [ + (k, _ParseResultsWithOffset(v[0], addoffset(v[1]))) + for k, vlist in otheritems + for v in vlist + ] + for k, v in otherdictitems: + self[k] = v + if isinstance(v[0], ParseResults): + v[0]._parent = self + + self._toklist += other._toklist + self._all_names |= other._all_names + return self + + def __radd__(self, other) -> ParseResults: + if isinstance(other, int) and other == 0: + # useful for merging many ParseResults using sum() builtin + return self.copy() + else: + # this may raise a TypeError - so be it + return other + self + + def __repr__(self) -> str: + return f"{type(self).__name__}({self._toklist!r}, {self.as_dict()})" + + def __str__(self) -> str: + return ( + "[" + + ", ".join( + [ + str(i) if isinstance(i, ParseResults) else repr(i) + for i in self._toklist + ] + ) + + "]" + ) + + def _asStringList(self, sep=""): + out = [] + for item in self._toklist: + if out and sep: + out.append(sep) + if isinstance(item, ParseResults): + out += item._asStringList() + else: + out.append(str(item)) + return out + + def as_list(self, *, flatten: bool = False) -> list: + """ + Returns the parse results as a nested list of matching tokens, all converted to strings. + If ``flatten`` is True, all the nesting levels in the returned list are collapsed. + + Example: + + .. doctest:: + + >>> patt = Word(alphas)[1, ...] + >>> result = patt.parse_string("sldkj lsdkj sldkj") + >>> # even though the result prints in string-like form, + >>> # it is actually a pyparsing ParseResults + >>> type(result) + + >>> print(result) + ['sldkj', 'lsdkj', 'sldkj'] + + .. doctest:: + + >>> # Use as_list() to create an actual list + >>> result_list = result.as_list() + >>> type(result_list) + + >>> print(result_list) + ['sldkj', 'lsdkj', 'sldkj'] + + .. versionchanged:: 3.2.0 + New ``flatten`` argument. + """ + + if flatten: + return [*_flatten(self)] + else: + return [ + res.as_list() if isinstance(res, ParseResults) else res + for res in self._toklist + ] + + def as_dict(self) -> dict: + """ + Returns the named parse results as a nested dictionary. + + Example: + + .. doctest:: + + >>> integer = pp.Word(pp.nums) + >>> date_str = integer("year") + '/' + integer("month") + '/' + integer("day") + + >>> result = date_str.parse_string('1999/12/31') + >>> type(result) + + >>> result + ParseResults(['1999', '/', '12', '/', '31'], {'year': '1999', 'month': '12', 'day': '31'}) + + >>> result_dict = result.as_dict() + >>> type(result_dict) + + >>> result_dict + {'year': '1999', 'month': '12', 'day': '31'} + + >>> # even though a ParseResults supports dict-like access, + >>> # sometime you just need to have a dict + >>> import json + >>> print(json.dumps(result)) + Traceback (most recent call last): + TypeError: Object of type ParseResults is not JSON serializable + >>> print(json.dumps(result.as_dict())) + {"year": "1999", "month": "12", "day": "31"} + """ + + def to_item(obj): + if isinstance(obj, ParseResults): + return obj.as_dict() if obj.haskeys() else [to_item(v) for v in obj] + else: + return obj + + return dict((k, to_item(v)) for k, v in self.items()) + + def copy(self) -> ParseResults: + """ + Returns a new shallow copy of a :class:`ParseResults` object. + :class:`ParseResults` items contained within the source are + shared with the copy. Use :meth:`ParseResults.deepcopy` to + create a copy with its own separate content values. + """ + ret = ParseResults(self._toklist) + ret._tokdict = self._tokdict.copy() + ret._parent = self._parent + ret._all_names |= self._all_names + ret._name = self._name + return ret + + def deepcopy(self) -> ParseResults: + """ + Returns a new deep copy of a :class:`ParseResults` object. + + .. versionadded:: 3.1.0 + """ + ret = self.copy() + # replace values with copies if they are of known mutable types + for i, obj in enumerate(self._toklist): + if isinstance(obj, ParseResults): + ret._toklist[i] = obj.deepcopy() + elif isinstance(obj, (str, bytes)): + pass + elif isinstance(obj, MutableMapping): + ret._toklist[i] = dest = type(obj)() + for k, v in obj.items(): + dest[k] = v.deepcopy() if isinstance(v, ParseResults) else v + elif isinstance(obj, Iterable): + ret._toklist[i] = type(obj)( + v.deepcopy() if isinstance(v, ParseResults) else v for v in obj # type: ignore[call-arg] + ) + return ret + + def get_name(self) -> str | None: + r""" + Returns the results name for this token expression. + + Useful when several different expressions might match + at a particular location. + + Example: + + .. testcode:: + + integer = Word(nums) + ssn_expr = Regex(r"\d\d\d-\d\d-\d\d\d\d") + house_number_expr = Suppress('#') + Word(nums, alphanums) + user_data = (Group(house_number_expr)("house_number") + | Group(ssn_expr)("ssn") + | Group(integer)("age")) + user_info = user_data[1, ...] + + result = user_info.parse_string("22 111-22-3333 #221B") + for item in result: + print(item.get_name(), ':', item[0]) + + prints: + + .. testoutput:: + + age : 22 + ssn : 111-22-3333 + house_number : 221B + + """ + if self._name: + return self._name + elif self._parent: + par: ParseResults = self._parent + parent_tokdict_items = par._tokdict.items() + return next( + ( + k + for k, vlist in parent_tokdict_items + for v, loc in vlist + if v is self + ), + None, + ) + elif ( + len(self) == 1 + and len(self._tokdict) == 1 + and next(iter(self._tokdict.values()))[0][1] in (0, -1) + ): + return next(iter(self._tokdict.keys())) + else: + return None + + def dump(self, indent="", full=True, include_list=True, _depth=0) -> str: + """ + Diagnostic method for listing out the contents of + a :class:`ParseResults`. Accepts an optional ``indent`` argument so + that this string can be embedded in a nested display of other data. + + Example: + + .. testcode:: + + integer = Word(nums) + date_str = integer("year") + '/' + integer("month") + '/' + integer("day") + + result = date_str.parse_string('1999/12/31') + print(result.dump()) + + prints: + + .. testoutput:: + + ['1999', '/', '12', '/', '31'] + - day: '31' + - month: '12' + - year: '1999' + """ + out = [] + NL = "\n" + out.append(indent + str(self.as_list()) if include_list else "") + + if not full: + return "".join(out) + + if self.haskeys(): + items = sorted((str(k), v) for k, v in self.items()) + for k, v in items: + if out: + out.append(NL) + out.append(f"{indent}{(' ' * _depth)}- {k}: ") + if not isinstance(v, ParseResults): + out.append(repr(v)) + continue + + if not v: + out.append(str(v)) + continue + + out.append( + v.dump( + indent=indent, + full=full, + include_list=include_list, + _depth=_depth + 1, + ) + ) + if not any(isinstance(vv, ParseResults) for vv in self): + return "".join(out) + + v = self + incr = " " + nl = "\n" + for i, vv in enumerate(v): + if isinstance(vv, ParseResults): + vv_dump = vv.dump( + indent=indent, + full=full, + include_list=include_list, + _depth=_depth + 1, + ) + out.append( + f"{nl}{indent}{incr * _depth}[{i}]:{nl}{indent}{incr * (_depth + 1)}{vv_dump}" + ) + else: + out.append( + f"{nl}{indent}{incr * _depth}[{i}]:{nl}{indent}{incr * (_depth + 1)}{vv}" + ) + + return "".join(out) + + def pprint(self, *args, **kwargs): + """ + Pretty-printer for parsed results as a list, using the + `pprint `_ module. + Accepts additional positional or keyword args as defined for + `pprint.pprint `_ . + + Example: + + .. testcode:: + + ident = Word(alphas, alphanums) + num = Word(nums) + func = Forward() + term = ident | num | Group('(' + func + ')') + func <<= ident + Group(Optional(DelimitedList(term))) + result = func.parse_string("fna a,b,(fnb c,d,200),100") + result.pprint(width=40) + + prints: + + .. testoutput:: + + ['fna', + ['a', + 'b', + ['(', 'fnb', ['c', 'd', '200'], ')'], + '100']] + """ + pprint.pprint(self.as_list(), *args, **kwargs) + + # add support for pickle protocol + def __getstate__(self): + return ( + self._toklist, + ( + self._tokdict.copy(), + None, + self._all_names, + self._name, + ), + ) + + def __setstate__(self, state): + self._toklist, (self._tokdict, par, inAccumNames, self._name) = state + self._all_names = set(inAccumNames) + self._parent = None + + def __getnewargs__(self): + return self._toklist, self._name + + def __dir__(self): + return dir(type(self)) + list(self.keys()) + + @classmethod + def from_dict(cls, other, name=None) -> ParseResults: + """ + Helper classmethod to construct a :class:`ParseResults` from a ``dict``, preserving the + name-value relations as results names. If an optional ``name`` argument is + given, a nested :class:`ParseResults` will be returned. + """ + ret = cls([]) + for k, v in other.items(): + if isinstance(v, Mapping): + ret += cls.from_dict(v, name=k) + else: + ret += cls([v], name=k, aslist=_is_iterable(v)) + if name is not None: + ret = cls([ret], name=name) + return ret + + asList = as_list + """ + .. deprecated:: 3.0.0 + use :meth:`as_list` + """ + asDict = as_dict + """ + .. deprecated:: 3.0.0 + use :meth:`as_dict` + """ + getName = get_name + """ + .. deprecated:: 3.0.0 + use :meth:`get_name` + """ + + +MutableMapping.register(ParseResults) +MutableSequence.register(ParseResults) diff --git a/.venv/lib/python3.12/site-packages/pyparsing/testing.py b/.venv/lib/python3.12/site-packages/pyparsing/testing.py new file mode 100644 index 0000000000000000000000000000000000000000..d7b60b852bfae552aead2f254ba5b8d0e67f5216 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/pyparsing/testing.py @@ -0,0 +1,398 @@ +# testing.py + +from contextlib import contextmanager +import re +import typing +import unittest + + +from .core import ( + ParserElement, + ParseException, + Keyword, + __diag__, + __compat__, +) +from . import core_builtin_exprs + + +class pyparsing_test: + """ + namespace class for classes useful in writing unit tests + """ + + class reset_pyparsing_context: + """ + Context manager to be used when writing unit tests that modify pyparsing config values: + - packrat parsing + - bounded recursion parsing + - default whitespace characters + - default keyword characters + - literal string auto-conversion class + - ``__diag__`` settings + + Example: + + .. testcode:: + + ppt = pyparsing.pyparsing_test + + class MyTestClass(ppt.TestParseResultsAsserts): + def test_literal(self): + with ppt.reset_pyparsing_context(): + # test that literals used to construct + # a grammar are automatically suppressed + ParserElement.inline_literals_using(Suppress) + + term = Word(alphas) | Word(nums) + group = Group('(' + term[...] + ')') + + # assert that the '()' characters + # are not included in the parsed tokens + self.assertParseAndCheckList( + group, + "(abc 123 def)", + ['abc', '123', 'def'] + ) + + # after exiting context manager, literals + # are converted to Literal expressions again + """ + + def __init__(self): + self._save_context = {} + + def save(self): + self._save_context["default_whitespace"] = ParserElement.DEFAULT_WHITE_CHARS + self._save_context["default_keyword_chars"] = Keyword.DEFAULT_KEYWORD_CHARS + + self._save_context["literal_string_class"] = ( + ParserElement._literalStringClass + ) + + self._save_context["verbose_stacktrace"] = ParserElement.verbose_stacktrace + + self._save_context["packrat_enabled"] = ParserElement._packratEnabled + if ParserElement._packratEnabled: + self._save_context["packrat_cache_size"] = ( + ParserElement.packrat_cache.size + ) + else: + self._save_context["packrat_cache_size"] = None + self._save_context["packrat_parse"] = ParserElement._parse + self._save_context["recursion_enabled"] = ( + ParserElement._left_recursion_enabled + ) + + self._save_context["__diag__"] = { + name: getattr(__diag__, name) for name in __diag__._all_names + } + + self._save_context["__compat__"] = { + "collect_all_And_tokens": __compat__.collect_all_And_tokens + } + + return self + + def restore(self): + # reset pyparsing global state + if ( + ParserElement.DEFAULT_WHITE_CHARS + != self._save_context["default_whitespace"] + ): + ParserElement.set_default_whitespace_chars( + self._save_context["default_whitespace"] + ) + + ParserElement.verbose_stacktrace = self._save_context["verbose_stacktrace"] + + Keyword.DEFAULT_KEYWORD_CHARS = self._save_context["default_keyword_chars"] + ParserElement.inline_literals_using( + self._save_context["literal_string_class"] + ) + + for name, value in self._save_context["__diag__"].items(): + (__diag__.enable if value else __diag__.disable)(name) + + ParserElement._packratEnabled = False + if self._save_context["packrat_enabled"]: + ParserElement.enable_packrat(self._save_context["packrat_cache_size"]) + else: + ParserElement._parse = self._save_context["packrat_parse"] + ParserElement._left_recursion_enabled = self._save_context[ + "recursion_enabled" + ] + + # clear debug flags on all builtins + for expr in core_builtin_exprs: + expr.set_debug(False) + + __compat__.collect_all_And_tokens = self._save_context["__compat__"] + + return self + + def copy(self): + ret = type(self)() + ret._save_context.update(self._save_context) + return ret + + def __enter__(self): + return self.save() + + def __exit__(self, *args): + self.restore() + + class TestParseResultsAsserts(unittest.TestCase): + """ + A mixin class to add parse results assertion methods to normal unittest.TestCase classes. + """ + + def assertParseResultsEquals( + self, result, expected_list=None, expected_dict=None, msg=None + ): + """ + Unit test assertion to compare a :class:`ParseResults` object with an optional ``expected_list``, + and compare any defined results names with an optional ``expected_dict``. + """ + if expected_list is not None: + self.assertEqual(expected_list, result.as_list(), msg=msg) + if expected_dict is not None: + self.assertEqual(expected_dict, result.as_dict(), msg=msg) + + def assertParseAndCheckList( + self, expr, test_string, expected_list, msg=None, verbose=True + ): + """ + Convenience wrapper assert to test a parser element and input string, and assert that + the resulting :meth:`ParseResults.as_list` is equal to the ``expected_list``. + """ + result = expr.parse_string(test_string, parse_all=True) + if verbose: + print(result.dump()) + else: + print(result.as_list()) + self.assertParseResultsEquals(result, expected_list=expected_list, msg=msg) + + def assertParseAndCheckDict( + self, expr, test_string, expected_dict, msg=None, verbose=True + ): + """ + Convenience wrapper assert to test a parser element and input string, and assert that + the resulting :meth:`ParseResults.as_dict` is equal to the ``expected_dict``. + """ + result = expr.parse_string(test_string, parse_all=True) + if verbose: + print(result.dump()) + else: + print(result.as_list()) + self.assertParseResultsEquals(result, expected_dict=expected_dict, msg=msg) + + def assertRunTestResults( + self, run_tests_report, expected_parse_results=None, msg=None + ): + """ + Unit test assertion to evaluate output of + :meth:`~ParserElement.run_tests`. + + If a list of list-dict tuples is given as the + ``expected_parse_results`` argument, then these are zipped + with the report tuples returned by ``run_tests()`` + and evaluated using :meth:`assertParseResultsEquals`. + Finally, asserts that the overall + `:meth:~ParserElement.run_tests` success value is ``True``. + + :param run_tests_report: the return value from :meth:`ParserElement.run_tests` + :type run_tests_report: tuple[bool, list[tuple[str, ParseResults | Exception]]] + :param expected_parse_results: (optional) + :type expected_parse_results: list[tuple[str | list | dict | Exception, ...]] + """ + run_test_success, run_test_results = run_tests_report + + if expected_parse_results is None: + self.assertTrue( + run_test_success, msg=msg if msg is not None else "failed runTests" + ) + return + + merged = [ + (*rpt, expected) + for rpt, expected in zip(run_test_results, expected_parse_results) + ] + for test_string, result, expected in merged: + # expected should be a tuple containing a list and/or a dict or an exception, + # and optional failure message string + # an empty tuple will skip any result validation + fail_msg = next((exp for exp in expected if isinstance(exp, str)), None) + expected_exception = next( + ( + exp + for exp in expected + if isinstance(exp, type) and issubclass(exp, Exception) + ), + None, + ) + if expected_exception is not None: + with self.assertRaises( + expected_exception=expected_exception, msg=fail_msg or msg + ): + if isinstance(result, Exception): + raise result + else: + expected_list = next( + (exp for exp in expected if isinstance(exp, list)), None + ) + expected_dict = next( + (exp for exp in expected if isinstance(exp, dict)), None + ) + if (expected_list, expected_dict) != (None, None): + self.assertParseResultsEquals( + result, + expected_list=expected_list, + expected_dict=expected_dict, + msg=fail_msg or msg, + ) + else: + # warning here maybe? + print(f"no validation for {test_string!r}") + + # do this last, in case some specific test results can be reported instead + self.assertTrue( + run_test_success, msg=msg if msg is not None else "failed runTests" + ) + + @contextmanager + def assertRaisesParseException( + self, exc_type=ParseException, expected_msg=None, msg=None + ): + if expected_msg is not None: + if isinstance(expected_msg, str): + expected_msg = re.escape(expected_msg) + with self.assertRaisesRegex(exc_type, expected_msg, msg=msg) as ctx: + yield ctx + + else: + with self.assertRaises(exc_type, msg=msg) as ctx: + yield ctx + + @staticmethod + def with_line_numbers( + s: str, + start_line: typing.Optional[int] = None, + end_line: typing.Optional[int] = None, + expand_tabs: bool = True, + eol_mark: str = "|", + mark_spaces: typing.Optional[str] = None, + mark_control: typing.Optional[str] = None, + *, + indent: typing.Union[str, int] = "", + base_1: bool = True, + ) -> str: + """ + Helpful method for debugging a parser - prints a string with line and column numbers. + (Line and column numbers are 1-based by default - if debugging a parse action, + pass base_1=False, to correspond to the loc value passed to the parse action.) + + :param s: string to be printed with line and column numbers + :param start_line: starting line number in s to print (default=1) + :param end_line: ending line number in s to print (default=len(s)) + :param expand_tabs: expand tabs to spaces, to match the pyparsing default + :param eol_mark: string to mark the end of lines, helps visualize trailing spaces + :param mark_spaces: special character to display in place of spaces + :param mark_control: convert non-printing control characters to a placeholding + character; valid values: + + - ``"unicode"`` - replaces control chars with Unicode symbols, such as "␍" and "␊" + - any single character string - replace control characters with given string + - ``None`` (default) - string is displayed as-is + + + :param indent: string to indent with line and column numbers; if an int + is passed, converted to ``" " * indent`` + :param base_1: whether to label string using base 1; if False, string will be + labeled based at 0 + + :returns: input string with leading line numbers and column number headers + + .. versionchanged:: 3.2.0 + New ``indent`` and ``base_1`` arguments. + """ + if expand_tabs: + s = s.expandtabs() + if isinstance(indent, int): + indent = " " * indent + indent = indent.expandtabs() + if mark_control is not None: + mark_control = typing.cast(str, mark_control) + if mark_control == "unicode": + transtable_map = { + c: u for c, u in zip(range(0, 33), range(0x2400, 0x2433)) + } + transtable_map[127] = 0x2421 + tbl = str.maketrans(transtable_map) + eol_mark = "" + else: + ord_mark_control = ord(mark_control) + tbl = str.maketrans( + {c: ord_mark_control for c in list(range(0, 32)) + [127]} + ) + s = s.translate(tbl) + if mark_spaces is not None and mark_spaces != " ": + if mark_spaces == "unicode": + tbl = str.maketrans({9: 0x2409, 32: 0x2423}) + s = s.translate(tbl) + else: + s = s.replace(" ", mark_spaces) + if start_line is None: + start_line = 0 + if end_line is None: + end_line = len(s.splitlines()) + end_line = min(end_line, len(s.splitlines())) + start_line = min(max(0, start_line), end_line) + + if mark_control != "unicode": + s_lines = s.splitlines()[max(start_line - base_1, 0) : end_line] + else: + s_lines = [ + line + "␊" + for line in s.split("␊")[max(start_line - base_1, 0) : end_line] + ] + if not s_lines: + return "" + + lineno_width = len(str(end_line)) + max_line_len = max(len(line) for line in s_lines) + lead = f"{indent}{' ' * (lineno_width + 1)}" + + if max_line_len >= 99: + header0 = ( + lead + + ("" if base_1 else " ") + + "".join( + f"{' ' * 99}{(i + 1) % 100}" + for i in range(max(max_line_len // 100, 1)) + ) + + "\n" + ) + else: + header0 = "" + + header1 = ( + ("" if base_1 else " ") + + lead + + "".join(f" {(i + 1) % 10}" for i in range(-(-max_line_len // 10))) + + "\n" + ) + digits = "1234567890" + header2 = ( + lead + ("" if base_1 else "0") + digits * (-(-max_line_len // 10)) + "\n" + ) + return ( + header0 + + header1 + + header2 + + "\n".join( + f"{indent}{i:{lineno_width}d}:{line}{eol_mark}" + for i, line in enumerate(s_lines, start=start_line + base_1) + ) + + "\n" + ) diff --git a/.venv/lib/python3.12/site-packages/pyparsing/tools/__init__.py b/.venv/lib/python3.12/site-packages/pyparsing/tools/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/.venv/lib/python3.12/site-packages/pyparsing/tools/__pycache__/__init__.cpython-312.pyc b/.venv/lib/python3.12/site-packages/pyparsing/tools/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9d1df40fdb924b14bdd7afa78de749d0a5810105 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/pyparsing/tools/__pycache__/__init__.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/pyparsing/tools/__pycache__/cvt_pyparsing_pep8_names.cpython-312.pyc b/.venv/lib/python3.12/site-packages/pyparsing/tools/__pycache__/cvt_pyparsing_pep8_names.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d4db05119211b1d3d21f413335a65391a9c8aef1 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/pyparsing/tools/__pycache__/cvt_pyparsing_pep8_names.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/pyparsing/tools/cvt_pyparsing_pep8_names.py b/.venv/lib/python3.12/site-packages/pyparsing/tools/cvt_pyparsing_pep8_names.py new file mode 100644 index 0000000000000000000000000000000000000000..ecd2be7b4bc2eac78b4af9dd6829495bcf000338 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/pyparsing/tools/cvt_pyparsing_pep8_names.py @@ -0,0 +1,142 @@ +import warnings +from functools import lru_cache +import pyparsing as pp + + +@lru_cache(maxsize=None) +def camel_to_snake(s: str) -> str: + """ + Convert CamelCase to snake_case. + """ + return "".join(f"_{c.lower()}" if c.isupper() else c for c in s).lstrip("_") + + +pre_pep8_method_names = """ +addCondition addParseAction anyCloseTag anyOpenTag asDict asList cStyleComment canParseNext conditionAsParseAction +convertToDate convertToDatetime convertToFloat convertToInteger countedArray cppStyleComment dblQuotedString +dblSlashComment defaultName dictOf disableMemoization downcaseTokens enableLeftRecursion enablePackrat getName +htmlComment ignoreWhitespace infixNotation inlineLiteralsUsing javaStyleComment leaveWhitespace +lineEnd lineStart matchOnlyAtCol matchPreviousExpr matchPreviousLiteral nestedExpr nullDebugAction oneOf +originalTextFor parseFile parseString parseWithTabs pythonStyleComment quotedString removeQuotes replaceWith +resetCache restOfLine runTests scanString searchString setBreak setDebug setDebugActions setDefaultWhitespaceChars +setFailAction setName setParseAction setResultsName setWhitespaceChars sglQuotedString stringEnd stringStart tokenMap +traceParseAction transformString tryParse unicodeString upcaseTokens withAttribute withClass +""".split() + +special_changes = { + "opAssoc": "OpAssoc", + "delimitedList": "DelimitedList", + "delimited_list": "DelimitedList", + "replaceHTMLEntity": "replace_html_entity", + "makeHTMLTags": "make_html_tags", + "makeXMLTags": "make_xml_tags", + "commonHTMLEntity": "common_html_entity", + "stripHTMLTags": "strip_html_tags", + "indentedBlock": "IndentedBlock", + "locatedExpr": "Located", +} + +pre_pep8_arg_names = """parseAll maxMatches listAllMatches callDuringTry includeSeparators fullDump printResults +failureTests postParse matchString identChars maxMismatches initChars bodyChars asKeyword excludeChars asGroupList +asMatch quoteChar escChar escQuote unquoteResults endQuoteChar convertWhitespaceEscapes notChars wordChars stopOn +failOn joinString markerString intExpr useRegex asString ignoreExpr""".split() + +special_changes_arg_names = { + "asList": "aslist", +} + +pre_pep8_method_name = pp.one_of(pre_pep8_method_names, as_keyword=True) +pre_pep8_method_name.set_parse_action(lambda t: camel_to_snake(t[0])) +special_pre_pep8_name = pp.one_of(special_changes, as_keyword=True) +def update_special_changes(s, l, t): + if t[0] == "indentedBlock": + warnings.warn( + "Conversion of 'indentedBlock' to new 'IndentedBlock'" + " requires added code changes to remove 'indentStack' argument\n" + f" {pp.lineno(l, s)}: {pp.line(l, s)}", + stacklevel=2, + ) + elif t[0] == "locatedExpr": + warnings.warn( + "Conversion of 'locatedExpr' to new 'Located'" + " may require added code changes - Located does not automatically" + " group parsed elements\n" + f" {pp.lineno(l, s)}: {pp.line(l, s)}", + stacklevel=2, + ) + return special_changes[t[0]] +special_pre_pep8_name.set_parse_action(update_special_changes) +# only replace arg names if part of an arg list +pre_pep8_arg_name = pp.Regex( + rf"{pp.util.make_compressed_re(pre_pep8_arg_names)}" +) + pp.FollowedBy("=") +pre_pep8_arg_name.set_parse_action(lambda t: camel_to_snake(t[0])) +special_pre_pep8_arg_name = pp.one_of(special_changes_arg_names, as_keyword=True) + pp.FollowedBy("=") +special_pre_pep8_arg_name.set_parse_action(lambda t: special_changes_arg_names[t[0]]) + +pep8_converter = special_pre_pep8_arg_name | pre_pep8_method_name | special_pre_pep8_name | pre_pep8_arg_name + +if __name__ == "__main__": + import argparse + from pathlib import Path + import sys + + argparser = argparse.ArgumentParser( + description = ( + "Utility to convert Python pyparsing scripts using legacy" + " camelCase names to use PEP8 snake_case names." + "\nBy default, this script will only show whether this script would make any changes." + ) + ) + argparser.add_argument("--verbose", "-v", action="store_true", help="Show unified diff for each source file") + argparser.add_argument("-vv", action="store_true", dest="verbose2", help="Show unified diff for each source file, plus names of scanned files with no changes") + argparser.add_argument("--update", "-u", action="store_true", help="Update source files in-place") + argparser.add_argument("--encoding", type=str, default="utf-8", help="Encoding of source files (default: utf-8)") + argparser.add_argument("--exit-zero-even-if-changed", "-exit0", action="store_true", help="Exit with status code 0 even if changes were made") + argparser.add_argument("source_filename", nargs="+", help="Source filenames or filename patterns of Python files to be converted") + args = argparser.parse_args() + + + def show_diffs(original, modified): + import difflib + + diff = difflib.unified_diff( + original.splitlines(), modified.splitlines(), lineterm="" + ) + sys.stdout.writelines(f"{diff_line}\n" for diff_line in diff) + + exit_status = 0 + + for filename_pattern in args.source_filename: + + for filename in Path().glob(filename_pattern): + if not Path(filename).is_file(): + continue + + try: + original_contents = Path(filename).read_text(encoding=args.encoding) + modified_contents = pep8_converter.transform_string( + original_contents + ) + + if modified_contents != original_contents: + if args.update: + Path(filename).write_text(modified_contents, encoding=args.encoding) + print(f"Converted {filename}") + else: + print(f"Found required changes in {filename}") + + if args.verbose: + show_diffs(original_contents, modified_contents) + print() + + exit_status = 1 + + else: + if args.verbose2: + print(f"No required changes in {filename}") + + except Exception as e: + print(f"Failed to convert {filename}: {type(e).__name__}: {e}") + + sys.exit(exit_status if not args.exit_zero_even_if_changed else 0) diff --git a/.venv/lib/python3.12/site-packages/pyparsing/unicode.py b/.venv/lib/python3.12/site-packages/pyparsing/unicode.py new file mode 100644 index 0000000000000000000000000000000000000000..32bb94e4397a2dd4b66e2a725c1e119e3518de71 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/pyparsing/unicode.py @@ -0,0 +1,356 @@ +# unicode.py + +import sys +from itertools import filterfalse +from typing import Union + + +class _lazyclassproperty: + def __init__(self, fn): + self.fn = fn + self.__doc__ = fn.__doc__ + self.__name__ = fn.__name__ + + def __get__(self, obj, cls): + if cls is None: + cls = type(obj) + if not hasattr(cls, "_intern") or any( + cls._intern is getattr(superclass, "_intern", []) + for superclass in cls.__mro__[1:] + ): + cls._intern = {} + attrname = self.fn.__name__ + if attrname not in cls._intern: + cls._intern[attrname] = self.fn(cls) + return cls._intern[attrname] + + +UnicodeRangeList = list[Union[tuple[int, int], tuple[int]]] + + +class unicode_set: + """ + A set of Unicode characters, for language-specific strings for + ``alphas``, ``nums``, ``alphanums``, and ``printables``. + A unicode_set is defined by a list of ranges in the Unicode character + set, in a class attribute ``_ranges``. Ranges can be specified using + 2-tuples or a 1-tuple, such as:: + + _ranges = [ + (0x0020, 0x007e), + (0x00a0, 0x00ff), + (0x0100,), + ] + + Ranges are left- and right-inclusive. A 1-tuple of (x,) is treated as (x, x). + + A unicode set can also be defined using multiple inheritance of other unicode sets:: + + class CJK(Chinese, Japanese, Korean): + pass + """ + + _ranges: UnicodeRangeList = [] + + @_lazyclassproperty + def _chars_for_ranges(cls) -> list[str]: + ret: list[int] = [] + for cc in cls.__mro__: # type: ignore[attr-defined] + if cc is unicode_set: + break + for rr in getattr(cc, "_ranges", ()): + ret.extend(range(rr[0], rr[-1] + 1)) + return sorted(chr(c) for c in set(ret)) + + @_lazyclassproperty + def printables(cls) -> str: + """all non-whitespace characters in this range""" + return "".join(filterfalse(str.isspace, cls._chars_for_ranges)) + + @_lazyclassproperty + def alphas(cls) -> str: + """all alphabetic characters in this range""" + return "".join(filter(str.isalpha, cls._chars_for_ranges)) + + @_lazyclassproperty + def nums(cls) -> str: + """all numeric digit characters in this range""" + return "".join(filter(str.isdigit, cls._chars_for_ranges)) + + @_lazyclassproperty + def alphanums(cls) -> str: + """all alphanumeric characters in this range""" + return cls.alphas + cls.nums + + @_lazyclassproperty + def identchars(cls) -> str: + """all characters in this range that are valid identifier characters, plus underscore '_'""" + return "".join( + sorted( + set(filter(str.isidentifier, cls._chars_for_ranges)) + | set( + "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyzªµº" + "ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖØÙÚÛÜÝÞßàáâãäåæçèéêëìíîïðñòóôõöøùúûüýþÿ" + "_" + ) + ) + ) + + @_lazyclassproperty + def identbodychars(cls) -> str: + """ + all characters in this range that are valid identifier body characters, + plus the digits 0-9, and · (Unicode MIDDLE DOT) + """ + identifier_chars = set( + c for c in cls._chars_for_ranges if f"_{c}".isidentifier() + ) + return "".join( + sorted(identifier_chars | set(cls.identchars) | set("0123456789·")) + ) + + @_lazyclassproperty + def identifier(cls): + """ + a pyparsing Word expression for an identifier using this range's definitions for + identchars and identbodychars + """ + from pyparsing import Word + + return Word(cls.identchars, cls.identbodychars) + + +class pyparsing_unicode(unicode_set): + """ + A namespace class for defining common language unicode_sets. + """ + + # fmt: off + + # define ranges in language character sets + _ranges: UnicodeRangeList = [ + (0x0020, sys.maxunicode), + ] + + class BasicMultilingualPlane(unicode_set): + """Unicode set for the Basic Multilingual Plane""" + _ranges: UnicodeRangeList = [ + (0x0020, 0xFFFF), + ] + + class Latin1(unicode_set): + """Unicode set for Latin-1 Unicode Character Range""" + _ranges: UnicodeRangeList = [ + (0x0020, 0x007E), + (0x00A0, 0x00FF), + ] + + class LatinA(unicode_set): + """Unicode set for Latin-A Unicode Character Range""" + _ranges: UnicodeRangeList = [ + (0x0100, 0x017F), + ] + + class LatinB(unicode_set): + """Unicode set for Latin-B Unicode Character Range""" + _ranges: UnicodeRangeList = [ + (0x0180, 0x024F), + ] + + class Greek(unicode_set): + """Unicode set for Greek Unicode Character Ranges""" + _ranges: UnicodeRangeList = [ + (0x0342, 0x0345), + (0x0370, 0x0377), + (0x037A, 0x037F), + (0x0384, 0x038A), + (0x038C,), + (0x038E, 0x03A1), + (0x03A3, 0x03E1), + (0x03F0, 0x03FF), + (0x1D26, 0x1D2A), + (0x1D5E,), + (0x1D60,), + (0x1D66, 0x1D6A), + (0x1F00, 0x1F15), + (0x1F18, 0x1F1D), + (0x1F20, 0x1F45), + (0x1F48, 0x1F4D), + (0x1F50, 0x1F57), + (0x1F59,), + (0x1F5B,), + (0x1F5D,), + (0x1F5F, 0x1F7D), + (0x1F80, 0x1FB4), + (0x1FB6, 0x1FC4), + (0x1FC6, 0x1FD3), + (0x1FD6, 0x1FDB), + (0x1FDD, 0x1FEF), + (0x1FF2, 0x1FF4), + (0x1FF6, 0x1FFE), + (0x2129,), + (0x2719, 0x271A), + (0xAB65,), + (0x10140, 0x1018D), + (0x101A0,), + (0x1D200, 0x1D245), + (0x1F7A1, 0x1F7A7), + ] + + class Cyrillic(unicode_set): + """Unicode set for Cyrillic Unicode Character Range""" + _ranges: UnicodeRangeList = [ + (0x0400, 0x052F), + (0x1C80, 0x1C88), + (0x1D2B,), + (0x1D78,), + (0x2DE0, 0x2DFF), + (0xA640, 0xA672), + (0xA674, 0xA69F), + (0xFE2E, 0xFE2F), + ] + + class Chinese(unicode_set): + """Unicode set for Chinese Unicode Character Range""" + _ranges: UnicodeRangeList = [ + (0x2E80, 0x2E99), + (0x2E9B, 0x2EF3), + (0x31C0, 0x31E3), + (0x3400, 0x4DB5), + (0x4E00, 0x9FEF), + (0xA700, 0xA707), + (0xF900, 0xFA6D), + (0xFA70, 0xFAD9), + (0x16FE2, 0x16FE3), + (0x1F210, 0x1F212), + (0x1F214, 0x1F23B), + (0x1F240, 0x1F248), + (0x20000, 0x2A6D6), + (0x2A700, 0x2B734), + (0x2B740, 0x2B81D), + (0x2B820, 0x2CEA1), + (0x2CEB0, 0x2EBE0), + (0x2F800, 0x2FA1D), + ] + + class Japanese(unicode_set): + """Unicode set for Japanese Unicode Character Range, combining Kanji, Hiragana, and Katakana ranges""" + + class Kanji(unicode_set): + "Unicode set for Kanji Unicode Character Range" + _ranges: UnicodeRangeList = [ + (0x4E00, 0x9FBF), + (0x3000, 0x303F), + ] + + class Hiragana(unicode_set): + """Unicode set for Hiragana Unicode Character Range""" + _ranges: UnicodeRangeList = [ + (0x3041, 0x3096), + (0x3099, 0x30A0), + (0x30FC,), + (0xFF70,), + (0x1B001,), + (0x1B150, 0x1B152), + (0x1F200,), + ] + + class Katakana(unicode_set): + """Unicode set for Katakana Unicode Character Range""" + _ranges: UnicodeRangeList = [ + (0x3099, 0x309C), + (0x30A0, 0x30FF), + (0x31F0, 0x31FF), + (0x32D0, 0x32FE), + (0xFF65, 0xFF9F), + (0x1B000,), + (0x1B164, 0x1B167), + (0x1F201, 0x1F202), + (0x1F213,), + ] + + 漢字 = Kanji + カタカナ = Katakana + ひらがな = Hiragana + + _ranges = ( + Kanji._ranges + + Hiragana._ranges + + Katakana._ranges + ) + + class Hangul(unicode_set): + """Unicode set for Hangul (Korean) Unicode Character Range""" + _ranges: UnicodeRangeList = [ + (0x1100, 0x11FF), + (0x302E, 0x302F), + (0x3131, 0x318E), + (0x3200, 0x321C), + (0x3260, 0x327B), + (0x327E,), + (0xA960, 0xA97C), + (0xAC00, 0xD7A3), + (0xD7B0, 0xD7C6), + (0xD7CB, 0xD7FB), + (0xFFA0, 0xFFBE), + (0xFFC2, 0xFFC7), + (0xFFCA, 0xFFCF), + (0xFFD2, 0xFFD7), + (0xFFDA, 0xFFDC), + ] + + Korean = Hangul + + class CJK(Chinese, Japanese, Hangul): + """Unicode set for combined Chinese, Japanese, and Korean (CJK) Unicode Character Range""" + + class Thai(unicode_set): + """Unicode set for Thai Unicode Character Range""" + _ranges: UnicodeRangeList = [ + (0x0E01, 0x0E3A), + (0x0E3F, 0x0E5B) + ] + + class Arabic(unicode_set): + """Unicode set for Arabic Unicode Character Range""" + _ranges: UnicodeRangeList = [ + (0x0600, 0x061B), + (0x061E, 0x06FF), + (0x0700, 0x077F), + ] + + class Hebrew(unicode_set): + """Unicode set for Hebrew Unicode Character Range""" + _ranges: UnicodeRangeList = [ + (0x0591, 0x05C7), + (0x05D0, 0x05EA), + (0x05EF, 0x05F4), + (0xFB1D, 0xFB36), + (0xFB38, 0xFB3C), + (0xFB3E,), + (0xFB40, 0xFB41), + (0xFB43, 0xFB44), + (0xFB46, 0xFB4F), + ] + + class Devanagari(unicode_set): + """Unicode set for Devanagari Unicode Character Range""" + _ranges: UnicodeRangeList = [ + (0x0900, 0x097F), + (0xA8E0, 0xA8FF) + ] + + BMP = BasicMultilingualPlane + + # add language identifiers using language Unicode + العربية = Arabic + 中文 = Chinese + кириллица = Cyrillic + Ελληνικά = Greek + עִברִית = Hebrew + 日本語 = Japanese + 한국어 = Korean + ไทย = Thai + देवनागरी = Devanagari + + # fmt: on diff --git a/.venv/lib/python3.12/site-packages/pyparsing/util.py b/.venv/lib/python3.12/site-packages/pyparsing/util.py new file mode 100644 index 0000000000000000000000000000000000000000..62295915fa37da1831ce6839d5ec2d7f9add4779 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/pyparsing/util.py @@ -0,0 +1,514 @@ +# util.py +import contextlib +import re +from functools import lru_cache, wraps +import inspect +import itertools +import types +from typing import Callable, Union, Iterable, TypeVar, cast, Any +import warnings + +from .warnings import PyparsingDeprecationWarning, PyparsingDiagnosticWarning + +_bslash = chr(92) +C = TypeVar("C", bound=Callable) + + +class __config_flags: + """Internal class for defining compatibility and debugging flags""" + + _all_names: list[str] = [] + _fixed_names: list[str] = [] + _type_desc = "configuration" + + @classmethod + def _set(cls, dname, value): + if dname in cls._fixed_names: + warnings.warn( + f"{cls.__name__}.{dname} {cls._type_desc} is {str(getattr(cls, dname)).upper()}" + f" and cannot be overridden", + PyparsingDiagnosticWarning, + stacklevel=3, + ) + return + if dname in cls._all_names: + setattr(cls, dname, value) + else: + raise ValueError(f"no such {cls._type_desc} {dname!r}") + + enable = classmethod(lambda cls, name: cls._set(name, True)) + disable = classmethod(lambda cls, name: cls._set(name, False)) + + +@lru_cache(maxsize=128) +def col(loc: int, strg: str) -> int: + """ + Returns current column within a string, counting newlines as line separators. + The first column is number 1. + + Note: the default parsing behavior is to expand tabs in the input string + before starting the parsing process. See + :meth:`ParserElement.parse_string` for more + information on parsing strings containing ```` s, and suggested + methods to maintain a consistent view of the parsed string, the parse + location, and line and column positions within the parsed string. + """ + s = strg + return 1 if 0 < loc < len(s) and s[loc - 1] == "\n" else loc - s.rfind("\n", 0, loc) + + +@lru_cache(maxsize=128) +def lineno(loc: int, strg: str) -> int: + """Returns current line number within a string, counting newlines as line separators. + The first line is number 1. + + Note - the default parsing behavior is to expand tabs in the input string + before starting the parsing process. See :meth:`ParserElement.parse_string` + for more information on parsing strings containing ```` s, and + suggested methods to maintain a consistent view of the parsed string, the + parse location, and line and column positions within the parsed string. + """ + return strg.count("\n", 0, loc) + 1 + + +@lru_cache(maxsize=128) +def line(loc: int, strg: str) -> str: + """ + Returns the line of text containing loc within a string, counting newlines as line separators. + """ + last_cr = strg.rfind("\n", 0, loc) + next_cr = strg.find("\n", loc) + return strg[last_cr + 1 : next_cr] if next_cr >= 0 else strg[last_cr + 1 :] + + +class _UnboundedCache: + def __init__(self): + cache = {} + cache_get = cache.get + self.not_in_cache = not_in_cache = object() + + def get(_, key): + return cache_get(key, not_in_cache) + + def set_(_, key, value): + cache[key] = value + + def clear(_): + cache.clear() + + self.size = None + self.get = types.MethodType(get, self) + self.set = types.MethodType(set_, self) + self.clear = types.MethodType(clear, self) + + +class _FifoCache: + def __init__(self, size): + cache = {} + self.size = size + self.not_in_cache = not_in_cache = object() + cache_get = cache.get + cache_pop = cache.pop + + def get(_, key): + return cache_get(key, not_in_cache) + + def set_(_, key, value): + cache[key] = value + while len(cache) > size: + # pop oldest element in cache by getting the first key + cache_pop(next(iter(cache))) + + def clear(_): + cache.clear() + + self.get = types.MethodType(get, self) + self.set = types.MethodType(set_, self) + self.clear = types.MethodType(clear, self) + + +class LRUMemo: + """ + A memoizing mapping that retains `capacity` deleted items + + The memo tracks retained items by their access order; once `capacity` items + are retained, the least recently used item is discarded. + """ + + def __init__(self, capacity): + self._capacity = capacity + self._active = {} + self._memory = {} + + def __getitem__(self, key): + try: + return self._active[key] + except KeyError: + self._memory[key] = self._memory.pop(key) + return self._memory[key] + + def __setitem__(self, key, value): + self._memory.pop(key, None) + self._active[key] = value + + def __delitem__(self, key): + try: + value = self._active.pop(key) + except KeyError: + pass + else: + oldest_keys = list(self._memory)[: -(self._capacity + 1)] + for key_to_delete in oldest_keys: + self._memory.pop(key_to_delete) + self._memory[key] = value + + def clear(self): + self._active.clear() + self._memory.clear() + + +class UnboundedMemo(dict): + """ + A memoizing mapping that retains all deleted items + """ + + def __delitem__(self, key): + pass + + +def _escape_regex_range_chars(s: str) -> str: + # escape these chars: ^-[] + for c in r"\^-[]": + s = s.replace(c, _bslash + c) + s = s.replace("\n", r"\n") + s = s.replace("\t", r"\t") + return str(s) + + +class _GroupConsecutive: + """ + Used as a callable `key` for itertools.groupby to group + characters that are consecutive: + + .. testcode:: + + from itertools import groupby + from pyparsing.util import _GroupConsecutive + + grouped = groupby("abcdejkmpqrs", key=_GroupConsecutive()) + for index, group in grouped: + print(tuple([index, list(group)])) + + prints: + + .. testoutput:: + + (0, ['a', 'b', 'c', 'd', 'e']) + (1, ['j', 'k']) + (2, ['m']) + (3, ['p', 'q', 'r', 's']) + """ + + def __init__(self) -> None: + self.prev = 0 + self.counter = itertools.count() + self.value = -1 + + def __call__(self, char: str) -> int: + c_int = ord(char) + self.prev, prev = c_int, self.prev + if c_int - prev > 1: + self.value = next(self.counter) + return self.value + + +def _is_iterable(obj, _str_type=(str, bytes), _iter_exception=Exception): + # str's are iterable, but in pyparsing, we don't want to iterate over them + if isinstance(obj, _str_type): + return False + + try: + iter(obj) + except _iter_exception: # noqa + return False + else: + return True + + +def _escape_re_range_char(c: str) -> str: + return fr"\{c}" if c in r"\^-][" else c + + +def _collapse_string_to_ranges( + s: Union[str, Iterable[str]], re_escape: bool = True +) -> str: + r""" + Take a string or list of single-character strings, and return + a string of the consecutive characters in that string collapsed + into groups, as might be used in a regular expression '[a-z]' + character set:: + + 'a' -> 'a' -> '[a]' + 'bc' -> 'bc' -> '[bc]' + 'defgh' -> 'd-h' -> '[d-h]' + 'fdgeh' -> 'd-h' -> '[d-h]' + 'jklnpqrtu' -> 'j-lnp-rtu' -> '[j-lnp-rtu]' + + Duplicates get collapsed out:: + + 'aaa' -> 'a' -> '[a]' + 'bcbccb' -> 'bc' -> '[bc]' + 'defghhgf' -> 'd-h' -> '[d-h]' + 'jklnpqrjjjtu' -> 'j-lnp-rtu' -> '[j-lnp-rtu]' + + Spaces are preserved:: + + 'ab c' -> ' a-c' -> '[ a-c]' + + Characters that are significant when defining regex ranges + get escaped:: + + 'acde[]-' -> r'\-\[\]ac-e' -> r'[\-\[\]ac-e]' + """ + + # Developer notes: + # - Do not optimize this code assuming that the given input string + # or internal lists will be short (such as in loading generators into + # lists to make it easier to find the last element); this method is also + # used to generate regex ranges for character sets in the pyparsing.unicode + # classes, and these can be _very_ long lists of strings + + escape_re_range_char: Callable[[str], str] + if re_escape: + escape_re_range_char = _escape_re_range_char + else: + escape_re_range_char = lambda ss: ss + + ret = [] + + # reduce input string to remove duplicates, and put in sorted order + s_chars: list[str] = sorted(set(s)) + + if len(s_chars) > 2: + # find groups of characters that are consecutive (can be collapsed + # down to "-") + for _, chars in itertools.groupby(s_chars, key=_GroupConsecutive()): + # _ is unimportant, is just used to identify groups + # chars is an iterator of one or more consecutive characters + # that comprise the current group + first = last = next(chars) + with contextlib.suppress(ValueError): + *_, last = chars + + if first == last: + # there was only a single char in this group + ret.append(escape_re_range_char(first)) + + elif last == chr(ord(first) + 1): + # there were only 2 characters in this group + # 'a','b' -> 'ab' + ret.append(f"{escape_re_range_char(first)}{escape_re_range_char(last)}") + + else: + # there were > 2 characters in this group, make into a range + # 'c','d','e' -> 'c-e' + ret.append( + f"{escape_re_range_char(first)}-{escape_re_range_char(last)}" + ) + else: + # only 1 or 2 chars were given to form into groups + # 'a' -> ['a'] + # 'bc' -> ['b', 'c'] + # 'dg' -> ['d', 'g'] + # no need to list them with "-", just return as a list + # (after escaping) + ret = [escape_re_range_char(c) for c in s_chars] + + return "".join(ret) + + +def _flatten(ll: Iterable) -> list: + ret = [] + for i in ll: + # Developer notes: + # - do not collapse this section of code, isinstance checks are done + # in optimal order + if isinstance(i, str): + ret.append(i) + elif isinstance(i, Iterable): + ret.extend(_flatten(i)) + else: + ret.append(i) + return ret + + +def _convert_escaped_numerics_to_char(s: str) -> str: + if s == "0": + return "\0" + if s.isdigit() and len(s) == 3: + return chr(int(s, 8)) + elif s.startswith(("u", "x")): + return chr(int(s[1:], 16)) + return s + + +def make_compressed_re( + word_list: Iterable[str], + max_level: int = 2, + *, + non_capturing_groups: bool = True, + _level: int = 1, +) -> str: + """ + Create a regular expression string from a list of words, collapsing by common + prefixes and optional suffixes. + + Calls itself recursively to build nested sublists for each group of suffixes + that have a shared prefix. + """ + + def get_suffixes_from_common_prefixes(namelist: list[str]): + if len(namelist) > 1: + for prefix, suffixes in itertools.groupby(namelist, key=lambda s: s[:1]): + yield prefix, sorted([s[1:] for s in suffixes], key=len, reverse=True) + else: + yield namelist[0][0], [namelist[0][1:]] + + if _level == 1: + if not word_list: + raise ValueError("no words given to make_compressed_re()") + + if "" in word_list: + raise ValueError("word list cannot contain empty string") + else: + # internal recursive call, just return empty string if no words + if not word_list: + return "" + + # dedupe the word list + word_list = list({}.fromkeys(word_list)) + + if max_level == 0: + if any(len(wd) > 1 for wd in word_list): + return "|".join( + sorted([re.escape(wd) for wd in word_list], key=len, reverse=True) + ) + else: + return f"[{''.join(_escape_regex_range_chars(wd) for wd in word_list)}]" + + ret = [] + sep = "" + ncgroup = "?:" if non_capturing_groups else "" + + for initial, suffixes in get_suffixes_from_common_prefixes(sorted(word_list)): + ret.append(sep) + sep = "|" + + initial = re.escape(initial) + + trailing = "" + if "" in suffixes: + trailing = "?" + suffixes.remove("") + + if len(suffixes) > 1: + if all(len(s) == 1 for s in suffixes): + ret.append( + f"{initial}[{''.join(_escape_regex_range_chars(s) for s in suffixes)}]{trailing}" + ) + else: + if _level < max_level: + suffix_re = make_compressed_re( + sorted(suffixes), + max_level, + non_capturing_groups=non_capturing_groups, + _level=_level + 1, + ) + ret.append(f"{initial}({ncgroup}{suffix_re}){trailing}") + else: + if all(len(s) == 1 for s in suffixes): + ret.append( + f"{initial}[{''.join(_escape_regex_range_chars(s) for s in suffixes)}]{trailing}" + ) + else: + suffixes.sort(key=len, reverse=True) + ret.append( + f"{initial}({ncgroup}{'|'.join(re.escape(s) for s in suffixes)}){trailing}" + ) + else: + if suffixes: + suffix = re.escape(suffixes[0]) + if len(suffix) > 1 and trailing: + ret.append(f"{initial}({ncgroup}{suffix}){trailing}") + else: + ret.append(f"{initial}{suffix}{trailing}") + else: + ret.append(initial) + return "".join(ret) + + +def replaced_by_pep8(compat_name: str, fn: C) -> C: + + # Unwrap staticmethod/classmethod + fn = getattr(fn, "__func__", fn) + + # (Presence of 'self' arg in signature is used by explain_exception() methods, so we take + # some extra steps to add it if present in decorated function.) + if ["self"] == list(inspect.signature(fn).parameters)[:1]: + + @wraps(fn) + def _inner(self, *args, **kwargs): + warnings.warn( + f"{compat_name!r} deprecated - use {fn.__name__!r}", + PyparsingDeprecationWarning, + stacklevel=2, + ) + return fn(self, *args, **kwargs) + + else: + + @wraps(fn) + def _inner(*args, **kwargs): + warnings.warn( + f"{compat_name!r} deprecated - use {fn.__name__!r}", + PyparsingDeprecationWarning, + stacklevel=2, + ) + return fn(*args, **kwargs) + + _inner.__doc__ = f""" + .. deprecated:: 3.0.0 + Use :class:`{fn.__name__}` instead + """ + _inner.__name__ = compat_name + _inner.__annotations__ = fn.__annotations__ + if isinstance(fn, types.FunctionType): + _inner.__kwdefaults__ = fn.__kwdefaults__ # type: ignore [attr-defined] + elif isinstance(fn, type) and hasattr(fn, "__init__"): + _inner.__kwdefaults__ = fn.__init__.__kwdefaults__ # type: ignore [misc,attr-defined] + else: + _inner.__kwdefaults__ = None # type: ignore [attr-defined] + _inner.__qualname__ = fn.__qualname__ + return cast(C, _inner) + + +def _to_pep8_name(s: str, _re_sub_pattern=re.compile(r"([a-z])([A-Z])")) -> str: + s = _re_sub_pattern.sub(r"\1_\2", s) + return s.lower() + + +def deprecate_argument( + kwargs: dict[str, Any], arg_name: str, default_value=None, *, new_name: str = "" +) -> Any: + + if arg_name in kwargs: + new_name = new_name or _to_pep8_name(arg_name) + warnings.warn( + f"{arg_name!r} argument is deprecated, use {new_name!r}", + category=PyparsingDeprecationWarning, + stacklevel=3, + ) + else: + kwargs[arg_name] = default_value + + return kwargs[arg_name] diff --git a/.venv/lib/python3.12/site-packages/pyparsing/warnings.py b/.venv/lib/python3.12/site-packages/pyparsing/warnings.py new file mode 100644 index 0000000000000000000000000000000000000000..1e4e9425e62a62d1b70fe26d5b6fae12d3b9d5da --- /dev/null +++ b/.venv/lib/python3.12/site-packages/pyparsing/warnings.py @@ -0,0 +1,10 @@ +class PyparsingWarning(UserWarning): + """Base warning class for all pyparsing warnings""" + + +class PyparsingDeprecationWarning(PyparsingWarning, DeprecationWarning): + """Base warning class for all pyparsing deprecation warnings""" + + +class PyparsingDiagnosticWarning(PyparsingWarning): + """Base warning class for all pyparsing diagnostic warnings""" diff --git a/.venv/lib/python3.12/site-packages/pytest-9.1.1.dist-info/INSTALLER b/.venv/lib/python3.12/site-packages/pytest-9.1.1.dist-info/INSTALLER new file mode 100644 index 0000000000000000000000000000000000000000..a1b589e38a32041e49332e5e81c2d363dc418d68 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/pytest-9.1.1.dist-info/INSTALLER @@ -0,0 +1 @@ +pip diff --git a/.venv/lib/python3.12/site-packages/pytest-9.1.1.dist-info/METADATA b/.venv/lib/python3.12/site-packages/pytest-9.1.1.dist-info/METADATA new file mode 100644 index 0000000000000000000000000000000000000000..df8b1fee97e687917481b3c55459fedc523c9fd0 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/pytest-9.1.1.dist-info/METADATA @@ -0,0 +1,211 @@ +Metadata-Version: 2.4 +Name: pytest +Version: 9.1.1 +Summary: pytest: simple powerful testing with Python +Author: Brianna Laugher, Bruno Oliveira, Floris Bruynooghe, Freya Bruhin, Holger Krekel, Others (See AUTHORS), Ronny Pfannschmidt +License-Expression: MIT +Project-URL: Changelog, https://docs.pytest.org/en/stable/changelog.html +Project-URL: Contact, https://docs.pytest.org/en/stable/contact.html +Project-URL: Funding, https://docs.pytest.org/en/stable/sponsor.html +Project-URL: Homepage, https://docs.pytest.org/en/latest/ +Project-URL: Source, https://github.com/pytest-dev/pytest +Project-URL: Tracker, https://github.com/pytest-dev/pytest/issues +Keywords: test,unittest +Classifier: Development Status :: 6 - Mature +Classifier: Intended Audience :: Developers +Classifier: Operating System :: MacOS +Classifier: Operating System :: Microsoft :: Windows +Classifier: Operating System :: POSIX +Classifier: Operating System :: Unix +Classifier: Programming Language :: Python :: 3 :: Only +Classifier: Programming Language :: Python :: 3.10 +Classifier: Programming Language :: Python :: 3.11 +Classifier: Programming Language :: Python :: 3.12 +Classifier: Programming Language :: Python :: 3.13 +Classifier: Programming Language :: Python :: 3.14 +Classifier: Programming Language :: Python :: 3.15 +Classifier: Topic :: Software Development :: Libraries +Classifier: Topic :: Software Development :: Testing +Classifier: Topic :: Utilities +Requires-Python: >=3.10 +Description-Content-Type: text/x-rst +License-File: LICENSE +Requires-Dist: colorama>=0.4; sys_platform == "win32" +Requires-Dist: exceptiongroup>=1; python_version < "3.11" +Requires-Dist: iniconfig>=1.0.1 +Requires-Dist: packaging>=22 +Requires-Dist: pluggy<2,>=1.5 +Requires-Dist: pygments>=2.7.2 +Requires-Dist: tomli>=1; python_version < "3.11" +Provides-Extra: dev +Requires-Dist: argcomplete; extra == "dev" +Requires-Dist: attrs>=19.2; extra == "dev" +Requires-Dist: hypothesis>=3.56; extra == "dev" +Requires-Dist: mock; extra == "dev" +Requires-Dist: requests; extra == "dev" +Requires-Dist: setuptools; extra == "dev" +Requires-Dist: xmlschema; extra == "dev" +Dynamic: license-file + +.. image:: https://github.com/pytest-dev/pytest/raw/main/doc/en/img/pytest_logo_curves.svg + :target: https://docs.pytest.org/en/stable/ + :align: center + :height: 200 + :alt: pytest + + +------ + +.. image:: https://img.shields.io/pypi/v/pytest.svg + :target: https://pypi.org/project/pytest/ + +.. image:: https://img.shields.io/conda/vn/conda-forge/pytest.svg + :target: https://anaconda.org/conda-forge/pytest + +.. image:: https://img.shields.io/pypi/pyversions/pytest.svg + :target: https://pypi.org/project/pytest/ + +.. image:: https://codecov.io/gh/pytest-dev/pytest/branch/main/graph/badge.svg + :target: https://codecov.io/gh/pytest-dev/pytest + :alt: Code coverage Status + +.. image:: https://github.com/pytest-dev/pytest/actions/workflows/test.yml/badge.svg + :target: https://github.com/pytest-dev/pytest/actions?query=workflow%3Atest + +.. image:: https://results.pre-commit.ci/badge/github/pytest-dev/pytest/main.svg + :target: https://results.pre-commit.ci/latest/github/pytest-dev/pytest/main + :alt: pre-commit.ci status + +.. image:: https://www.codetriage.com/pytest-dev/pytest/badges/users.svg + :target: https://www.codetriage.com/pytest-dev/pytest + +.. image:: https://readthedocs.org/projects/pytest/badge/?version=latest + :target: https://pytest.readthedocs.io/en/latest/?badge=latest + :alt: Documentation Status + +.. image:: https://img.shields.io/badge/Discord-pytest--dev-blue + :target: https://discord.com/invite/pytest-dev + :alt: Discord + +.. image:: https://img.shields.io/badge/Libera%20chat-%23pytest-orange + :target: https://web.libera.chat/#pytest + :alt: Libera chat + + +The ``pytest`` framework makes it easy to write small tests, yet +scales to support complex functional testing for applications and libraries. + +An example of a simple test: + +.. code-block:: python + + # content of test_sample.py + def inc(x): + return x + 1 + + + def test_answer(): + assert inc(3) == 5 + + +To execute it:: + + $ pytest + ============================= test session starts ============================= + collected 1 items + + test_sample.py F + + ================================== FAILURES =================================== + _________________________________ test_answer _________________________________ + + def test_answer(): + > assert inc(3) == 5 + E assert 4 == 5 + E + where 4 = inc(3) + + test_sample.py:5: AssertionError + ========================== 1 failed in 0.04 seconds =========================== + + +Thanks to ``pytest``'s detailed assertion introspection, you can simply use plain ``assert`` statements. See `getting-started `_ for more examples. + + +Features +-------- + +- Detailed info on failing `assert statements `_ (no need to remember ``self.assert*`` names) + +- `Auto-discovery + `_ + of test modules and functions + +- `Modular fixtures `_ for + managing small or parametrized long-lived test resources + +- Can run `unittest `_ (or trial) + test suites out of the box + +- Python 3.10+ or PyPy3 + +- Rich plugin architecture, with over 1300+ `external plugins `_ and thriving community + + +Documentation +------------- + +For full documentation, including installation, tutorials and PDF documents, please see https://docs.pytest.org/en/stable/. + + +Bugs/Requests +------------- + +Please use the `GitHub issue tracker `_ to submit bugs or request features. + + +Changelog +--------- + +Consult the `Changelog `__ page for fixes and enhancements of each version. + + +Support pytest +-------------- + +`Open Collective`_ is an online funding platform for open and transparent communities. +It provides tools to raise money and share your finances in full transparency. + +It is the platform of choice for individuals and companies that want to make one-time or +monthly donations directly to the project. + +See more details in the `pytest collective`_. + +.. _Open Collective: https://opencollective.com +.. _pytest collective: https://opencollective.com/pytest + + +pytest for enterprise +--------------------- + +Available as part of the Tidelift Subscription. + +The maintainers of pytest and thousands of other packages are working with Tidelift to deliver commercial support and +maintenance for the open source dependencies you use to build your applications. +Save time, reduce risk, and improve code health, while paying the maintainers of the exact dependencies you use. + +`Learn more. `_ + +Security +^^^^^^^^ + +If you have found an issue that you believe is a security vulnerability, please do not create an issue -- instead, report it via a `new security advisory `__. + + +License +------- + +Copyright Holger Krekel and others, 2004. + +Distributed under the terms of the `MIT`_ license, pytest is free and open source software. + +.. _`MIT`: https://github.com/pytest-dev/pytest/blob/main/LICENSE diff --git a/.venv/lib/python3.12/site-packages/pytest-9.1.1.dist-info/RECORD b/.venv/lib/python3.12/site-packages/pytest-9.1.1.dist-info/RECORD new file mode 100644 index 0000000000000000000000000000000000000000..aa45181422a08b0b46d2de0b14bac1b32c809e03 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/pytest-9.1.1.dist-info/RECORD @@ -0,0 +1,174 @@ +../../../bin/py.test,sha256=yoygvjCsrrEp1WABBlfycwGlvdhEbXqWf6vvlHoF1j0,263 +../../../bin/pytest,sha256=yoygvjCsrrEp1WABBlfycwGlvdhEbXqWf6vvlHoF1j0,263 +__pycache__/py.cpython-312.pyc,, +_pytest/__init__.py,sha256=4IdRJhnW5XG2KlaJkOxn5_TC9WeQ5tXDSF7tbb4vEso,391 +_pytest/__pycache__/__init__.cpython-312.pyc,, +_pytest/__pycache__/_argcomplete.cpython-312.pyc,, +_pytest/__pycache__/_version.cpython-312.pyc,, +_pytest/__pycache__/cacheprovider.cpython-312.pyc,, +_pytest/__pycache__/capture.cpython-312.pyc,, +_pytest/__pycache__/compat.cpython-312.pyc,, +_pytest/__pycache__/debugging.cpython-312.pyc,, +_pytest/__pycache__/deprecated.cpython-312.pyc,, +_pytest/__pycache__/doctest.cpython-312.pyc,, +_pytest/__pycache__/faulthandler.cpython-312.pyc,, +_pytest/__pycache__/fixtures.cpython-312.pyc,, +_pytest/__pycache__/freeze_support.cpython-312.pyc,, +_pytest/__pycache__/helpconfig.cpython-312.pyc,, +_pytest/__pycache__/hookspec.cpython-312.pyc,, +_pytest/__pycache__/junitxml.cpython-312.pyc,, +_pytest/__pycache__/legacypath.cpython-312.pyc,, +_pytest/__pycache__/logging.cpython-312.pyc,, +_pytest/__pycache__/main.cpython-312.pyc,, +_pytest/__pycache__/monkeypatch.cpython-312.pyc,, +_pytest/__pycache__/nodes.cpython-312.pyc,, +_pytest/__pycache__/outcomes.cpython-312.pyc,, +_pytest/__pycache__/pastebin.cpython-312.pyc,, +_pytest/__pycache__/pathlib.cpython-312.pyc,, +_pytest/__pycache__/pytester.cpython-312.pyc,, +_pytest/__pycache__/pytester_assertions.cpython-312.pyc,, +_pytest/__pycache__/python.cpython-312.pyc,, +_pytest/__pycache__/python_api.cpython-312.pyc,, +_pytest/__pycache__/raises.cpython-312.pyc,, +_pytest/__pycache__/recwarn.cpython-312.pyc,, +_pytest/__pycache__/reports.cpython-312.pyc,, +_pytest/__pycache__/runner.cpython-312.pyc,, +_pytest/__pycache__/scope.cpython-312.pyc,, +_pytest/__pycache__/setuponly.cpython-312.pyc,, +_pytest/__pycache__/setupplan.cpython-312.pyc,, +_pytest/__pycache__/skipping.cpython-312.pyc,, +_pytest/__pycache__/stash.cpython-312.pyc,, +_pytest/__pycache__/stepwise.cpython-312.pyc,, +_pytest/__pycache__/subtests.cpython-312.pyc,, +_pytest/__pycache__/terminal.cpython-312.pyc,, +_pytest/__pycache__/terminalprogress.cpython-312.pyc,, +_pytest/__pycache__/threadexception.cpython-312.pyc,, +_pytest/__pycache__/timing.cpython-312.pyc,, +_pytest/__pycache__/tmpdir.cpython-312.pyc,, +_pytest/__pycache__/tracemalloc.cpython-312.pyc,, +_pytest/__pycache__/unittest.cpython-312.pyc,, +_pytest/__pycache__/unraisableexception.cpython-312.pyc,, +_pytest/__pycache__/warning_types.cpython-312.pyc,, +_pytest/__pycache__/warnings.cpython-312.pyc,, +_pytest/_argcomplete.py,sha256=gh0pna66p4LVb2D8ST4568WGxvdInGT43m6slYhqNqU,3776 +_pytest/_code/__init__.py,sha256=BKbowoYQADKjAJmTWdQ8SSQLbBBsh0-dZj3TGjtn6yM,521 +_pytest/_code/__pycache__/__init__.cpython-312.pyc,, +_pytest/_code/__pycache__/code.cpython-312.pyc,, +_pytest/_code/__pycache__/source.cpython-312.pyc,, +_pytest/_code/code.py,sha256=Y-wD0g5h06wqDplUvnGmGd10LQCcJAmx4xaOKm-tkJY,58426 +_pytest/_code/source.py,sha256=RvPQfzFE4-BdpapsUcsdL4msgeHnN-WnqGPkAyrPbAE,7859 +_pytest/_io/__init__.py,sha256=pkLF29VEFr6Dlr3eOtJL8sf47RLFt1Jf4X1DZBPlYmc,190 +_pytest/_io/__pycache__/__init__.cpython-312.pyc,, +_pytest/_io/__pycache__/pprint.cpython-312.pyc,, +_pytest/_io/__pycache__/saferepr.cpython-312.pyc,, +_pytest/_io/__pycache__/terminalwriter.cpython-312.pyc,, +_pytest/_io/__pycache__/wcwidth.cpython-312.pyc,, +_pytest/_io/pprint.py,sha256=h_y5zQmN2nLz1UWPhoJCvqYNU_HI2I4qtJmCfagL9OQ,19572 +_pytest/_io/saferepr.py,sha256=xGNORj4B62E_xS2Qn29E5KpoLgw60q09b-AobW8ceqg,4920 +_pytest/_io/terminalwriter.py,sha256=K0pB1pfAvrKBWFARKSobQ4wWi0pdmiBaGb3a_v_AAjQ,8994 +_pytest/_io/wcwidth.py,sha256=cUEJ74UhweICwbKvU2q6noZcNgD0QlBEB9CfakGYaqA,1289 +_pytest/_py/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +_pytest/_py/__pycache__/__init__.cpython-312.pyc,, +_pytest/_py/__pycache__/error.cpython-312.pyc,, +_pytest/_py/__pycache__/path.cpython-312.pyc,, +_pytest/_py/error.py,sha256=kGQ7F8_fZ6YVBhAx-u9mkTQBTx0qIxxnVMC0CgiOd70,3475 +_pytest/_py/path.py,sha256=cqCn0amzKhqSqiW1Wzt4KqvFI2ncKBzGnwERUsWpC_0,49229 +_pytest/_version.py,sha256=qSFl_XsOFH0OG4c_QuvofxCPHz1WsbU_5K01Kiet7Eo,520 +_pytest/assertion/__init__.py,sha256=KmkIcXT6uS3Yg1K2C1Rth5-5NBGmwJljhKD4SgcHGsc,8081 +_pytest/assertion/__pycache__/__init__.cpython-312.pyc,, +_pytest/assertion/__pycache__/_compare_any.cpython-312.pyc,, +_pytest/assertion/__pycache__/_compare_mapping.cpython-312.pyc,, +_pytest/assertion/__pycache__/_compare_sequence.cpython-312.pyc,, +_pytest/assertion/__pycache__/_compare_set.cpython-312.pyc,, +_pytest/assertion/__pycache__/_guards.cpython-312.pyc,, +_pytest/assertion/__pycache__/_typing.cpython-312.pyc,, +_pytest/assertion/__pycache__/compare_text.cpython-312.pyc,, +_pytest/assertion/__pycache__/highlight.cpython-312.pyc,, +_pytest/assertion/__pycache__/rewrite.cpython-312.pyc,, +_pytest/assertion/__pycache__/truncate.cpython-312.pyc,, +_pytest/assertion/__pycache__/util.cpython-312.pyc,, +_pytest/assertion/_compare_any.py,sha256=ltt0TiAj7LVVzz8D1-mm6vyM_iUPKO_1XNgjl5PYlMI,4959 +_pytest/assertion/_compare_mapping.py,sha256=dKM5hvqjZF-WM0iHwE7lHj6miVaLTt7u0eQprp2G9pA,1680 +_pytest/assertion/_compare_sequence.py,sha256=anxodI4FYyqMmnhKSgmc_AtK_obrHUoODBbBNyOlhoE,2947 +_pytest/assertion/_compare_set.py,sha256=JRpz19ET_bi6eE9Z_uWxS_BzrEIyItG2hyXQls6InJQ,2667 +_pytest/assertion/_guards.py,sha256=H6ahG_5JCwZhTg5lIk8D6vghUQdKfoOZGUwsT3OQCF4,1923 +_pytest/assertion/_typing.py,sha256=9iznoFsKp847gY1iqtdL_ThIUZrYBAPa8N72O3dNpWg,338 +_pytest/assertion/compare_text.py,sha256=4Q7bKW2N9d0u7kSA5ovamuG6LMvFX68ixMyORTpICMc,3385 +_pytest/assertion/highlight.py,sha256=AVqS4X64Pg1aekXnOYRoeJigIADWwAdbdtG_9bk_3-c,327 +_pytest/assertion/rewrite.py,sha256=F_Hu-9HC_lMmy3WS_zr5Knc1gs-dAXJ7CdOrhkkG7lA,47740 +_pytest/assertion/truncate.py,sha256=7ki8tB0rwj7Z7-YCAADQRuB3Ro19O83y7XV3eTjeL1w,5156 +_pytest/assertion/util.py,sha256=8u3kQ2jEBnTMmUODOlY0JTl0fpJCCUGRz-JLfurxPTM,7710 +_pytest/cacheprovider.py,sha256=vZv7BDdkXaXQQnkvMLo3nSj_TB__rGgG9VQzBaMHNXk,22627 +_pytest/capture.py,sha256=EgBNv_CrezQUH_U-M-YW2y6FfGlfZOZAYx9avjBhkUU,37228 +_pytest/compat.py,sha256=QfcD7kYGIy4fxuqiE282BwDJCCRQNJEiGkNYYcPyFh4,10628 +_pytest/config/__init__.py,sha256=mLBcLDfQnh1cBZde_C2a-Y1K_26kfeQQqOk5VkIIc8E,80947 +_pytest/config/__pycache__/__init__.cpython-312.pyc,, +_pytest/config/__pycache__/argparsing.cpython-312.pyc,, +_pytest/config/__pycache__/exceptions.cpython-312.pyc,, +_pytest/config/__pycache__/findpaths.cpython-312.pyc,, +_pytest/config/argparsing.py,sha256=owNzoRCsVo51K1zFxOtmz6hZXyweqhv5ULH8UHCg0Jg,17795 +_pytest/config/exceptions.py,sha256=6Vm9yzwUOxJGm17ZMGbw69v_i07mT1KmBwENM2scKhk,315 +_pytest/config/findpaths.py,sha256=U10Unm85YuRCYLZkW7NUl24ZUx9d0kjhTufX__YciEg,12890 +_pytest/debugging.py,sha256=_eJqifDKExFCOv4JhgFhBoDXYnswswHG1dcZICZTjg8,13853 +_pytest/deprecated.py,sha256=fyTwqU-ftooJ8Pu8iy24TLqWXViUpZQV1qSrJJDqTio,5443 +_pytest/doctest.py,sha256=BCYfWz3c4MNlhPK-QuKTjVoNvpFEFFAlM6k-jBQtrPk,25424 +_pytest/faulthandler.py,sha256=1c7DpRtP0_C3zpFUSw1BORpAG8GsiDtJ9zCuWdEiLc0,4250 +_pytest/fixtures.py,sha256=9dTT-EjZdBHkVtUEANOq7MGamwyQ3vkVHjle6JUgQrc,92893 +_pytest/freeze_support.py,sha256=X94IxipqebeA_HgzJh8dbjqGnrtEQFuMIC5hK7SGWXw,1300 +_pytest/helpconfig.py,sha256=ZKTM752i6PGvKK_EL2BaodnEwSVQia3G5KE2-8gaUHQ,10019 +_pytest/hookspec.py,sha256=EgmFcQRGccJO0AEeK7fZSXY4AmXlc0ww-FZHlILm-I0,41840 +_pytest/junitxml.py,sha256=VXuJeMZrgBD6_FCtpL9WMz-ZJ_MbK1kJ_kwanfGjwPA,25961 +_pytest/legacypath.py,sha256=_l6v8akNMfTc5TAjvbc6M-_t157p9QE6-118WM0DRt8,16588 +_pytest/logging.py,sha256=mtTD5YPCBal8NyZL9HlQPnTgJ89ouoGJlukjBiOAysI,36104 +_pytest/main.py,sha256=juJyUFf_GBHirp698b77dRgZX48zP5-MoCTXakuAeA4,42771 +_pytest/mark/__init__.py,sha256=GmScnssk8ecJLWLIa21bOGSNxL9D2smS8GH2h2rN4FE,9857 +_pytest/mark/__pycache__/__init__.cpython-312.pyc,, +_pytest/mark/__pycache__/expression.cpython-312.pyc,, +_pytest/mark/__pycache__/structures.cpython-312.pyc,, +_pytest/mark/expression.py,sha256=7a5DoL-0T2rgl0dVH2wTnNvZhbimbirzM1LExXrB8n0,11250 +_pytest/mark/structures.py,sha256=WY_ytEGT8emIaCV_9V9P_zknb8XVroQn_k3nF26hvJY,24633 +_pytest/monkeypatch.py,sha256=tcQF7Vfb1Yrft_D65E-E1iQCmTxQBY4H8DOHKFwD3zM,15510 +_pytest/nodes.py,sha256=RwHy-nTikrJVGueQ0m_kIbsl5eRZAiAmEHvQJBd80Sk,26286 +_pytest/outcomes.py,sha256=qgLb81HNEQGnleP-9oOrL9eiwE65YYholmP1Hs6AwIE,8799 +_pytest/pastebin.py,sha256=JtD5Q0Ub3EpIKQFEyoq27SU18KCTSMTO6aKtEcf0Z9Q,4281 +_pytest/pathlib.py,sha256=yf533Mv1KvoRlv-Shw7ZGeCfJUwIJxCobtQX_TypAyk,37454 +_pytest/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +_pytest/pytester.py,sha256=nnkdCjRGsEMk5wu5OXEvjUkABa0T60arMklZK6oI_xc,62905 +_pytest/pytester_assertions.py,sha256=1IT16XrLbUoifFeEtOnPStiHZuIog0Dl3ECkpwmzo2Q,2253 +_pytest/python.py,sha256=sESI9eRr8f_i6DRPgXVuELlw2_ry9_L00xK-zWQE33Y,67758 +_pytest/python_api.py,sha256=y6ItF7Xe3Ms5vnHKlGt2W5mMTDBVrhra1FP--9hDSX0,35984 +_pytest/raises.py,sha256=3CiAXx4cLbg18aUpAhjv7l1RDRkK0zPWFmPVm9bRNiw,59770 +_pytest/recwarn.py,sha256=Djqyf2tzE9ie_xE2xM1gkT5ZH-WzKWHIfncRd48tyQY,13875 +_pytest/reports.py,sha256=LpJypnzeOLkl66JKKIsu9390HA2qItpvvOU-5uWPpB0,23230 +_pytest/runner.py,sha256=yNf9VTwFFveIRQLuDnlU61pbFULyH8tcQ1dQDtL-FXA,20346 +_pytest/scope.py,sha256=eEmRJvR0ujeH_RypUk3PhYOytQX1Yyr0keocRYpyrio,2736 +_pytest/setuponly.py,sha256=BsRrC4ERDVr42-2G_L0AxhNU4XVwbMsy5S0lOvKr8wA,3167 +_pytest/setupplan.py,sha256=l-ycFNxDZPyY52wh4f7yaqhzZ7SW1ijSKnQLmqzDZWA,1184 +_pytest/skipping.py,sha256=zCEC9fjRlHj5HOdxF8EJNIuHZq4E68S4wz5fmSPlCu4,10788 +_pytest/stash.py,sha256=5pE3kDx4q855TW9aVvYTdrkkKlMDU6-xiX4luKpJEgI,3090 +_pytest/stepwise.py,sha256=kD81DrnhnclKBmMfauwQmbeMbYUvuw07w5WnNkmIdEQ,7689 +_pytest/subtests.py,sha256=9RSIO60GqEzsDX3cHdjOjBblaAWX-fxam9iDa4ePkqQ,13507 +_pytest/terminal.py,sha256=KMSp68oCQzhbFU9H7Lg7GKHfQV4LkS69lwecXqADZFk,65489 +_pytest/terminalprogress.py,sha256=_IO3vRGVATz3RkkacqIAaCUC4-Rq2pTEANUAY66dEwQ,1153 +_pytest/threadexception.py,sha256=hTccpzZUrrQkDROVFAqHgXwAU481ca4Mq4CA4YB7my4,4953 +_pytest/timing.py,sha256=Yt4oVx5SljUGJLwY_iCW8v6wZKVfM-HMjR4iPAR9udQ,3196 +_pytest/tmpdir.py,sha256=UJn3HYlBMZHJ51FcnU_p_HCDu3Mwbyzx9zqfichi7ZA,13271 +_pytest/tracemalloc.py,sha256=lCUB_YUAb6R1vqq_b-LSYSXy-Tidbn2m7tfzmWAUrjk,778 +_pytest/unittest.py,sha256=JGV7bEl-rL9QqXhxNZizuu1MBcKfHAGJFWPP7-0RkiQ,25176 +_pytest/unraisableexception.py,sha256=6J8X5Yy00cnsTDLcrbTjN3Fmuar9f48MXRlBCieYezI,6545 +_pytest/warning_types.py,sha256=jie-Um8DCyeYFk_YUREyovRHtvXvaVg2Mii_l4mY7bU,4241 +_pytest/warnings.py,sha256=gkpvnw9CM8XkdBvDfvNmYMY7tO8geqkQZMCAtppNrp8,5239 +py.py,sha256=txZ1tdmEW6CBTp6Idn-I2sOzzA0xKNoCi9Re27Uj6HE,329 +pytest-9.1.1.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4 +pytest-9.1.1.dist-info/METADATA,sha256=xdAyUYASeJyryHDUZYmso67aNs-fpDme6IvaPRBDhFE,7586 +pytest-9.1.1.dist-info/RECORD,, +pytest-9.1.1.dist-info/REQUESTED,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +pytest-9.1.1.dist-info/WHEEL,sha256=aeYiig01lYGDzBgS8HxWXOg3uV61G9ijOsup-k9o1sk,91 +pytest-9.1.1.dist-info/entry_points.txt,sha256=shtd5aQM5jcu_2UNh_5M4Wa2YlkKMHU14Xm_xsjSpNY,95 +pytest-9.1.1.dist-info/licenses/LICENSE,sha256=yoNqX57Mo7LzUCMPqiCkj7ixRWU7VWjXhIYt-GRwa5s,1091 +pytest-9.1.1.dist-info/top_level.txt,sha256=yyhjvmXH7-JOaoQIdmNQHPuoBCxOyXS3jIths_6C8A4,18 +pytest/__init__.py,sha256=7jeIXJWD-EM5BoTftJaQf4egkFEo56PPStIn9J_zTC0,5644 +pytest/__main__.py,sha256=N_i2o98a73Eza86F42bblo7eFT3XKtTmC-v_eeJ53EA,175 +pytest/__pycache__/__init__.cpython-312.pyc,, +pytest/__pycache__/__main__.cpython-312.pyc,, +pytest/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 diff --git a/.venv/lib/python3.12/site-packages/pytest-9.1.1.dist-info/REQUESTED b/.venv/lib/python3.12/site-packages/pytest-9.1.1.dist-info/REQUESTED new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/.venv/lib/python3.12/site-packages/pytest-9.1.1.dist-info/WHEEL b/.venv/lib/python3.12/site-packages/pytest-9.1.1.dist-info/WHEEL new file mode 100644 index 0000000000000000000000000000000000000000..14a883f292bc96b20c2b76a3081991f2676523a9 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/pytest-9.1.1.dist-info/WHEEL @@ -0,0 +1,5 @@ +Wheel-Version: 1.0 +Generator: setuptools (82.0.1) +Root-Is-Purelib: true +Tag: py3-none-any + diff --git a/.venv/lib/python3.12/site-packages/pytest-9.1.1.dist-info/entry_points.txt b/.venv/lib/python3.12/site-packages/pytest-9.1.1.dist-info/entry_points.txt new file mode 100644 index 0000000000000000000000000000000000000000..a18cb53f1ef84d46dbd286ae9a52873069114cbd --- /dev/null +++ b/.venv/lib/python3.12/site-packages/pytest-9.1.1.dist-info/entry_points.txt @@ -0,0 +1,3 @@ +[console_scripts] +py.test = _pytest.config:_console_main +pytest = _pytest.config:_console_main diff --git a/.venv/lib/python3.12/site-packages/pytest-9.1.1.dist-info/licenses/LICENSE b/.venv/lib/python3.12/site-packages/pytest-9.1.1.dist-info/licenses/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..c3f1657fce94589bd1ec7cead810639047f3d359 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/pytest-9.1.1.dist-info/licenses/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2004 Holger Krekel and others + +Permission is hereby granted, free of charge, to any person obtaining a copy of +this software and associated documentation files (the "Software"), to deal in +the Software without restriction, including without limitation the rights to +use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies +of the Software, and to permit persons to whom the Software is furnished to do +so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/.venv/lib/python3.12/site-packages/pytest-9.1.1.dist-info/top_level.txt b/.venv/lib/python3.12/site-packages/pytest-9.1.1.dist-info/top_level.txt new file mode 100644 index 0000000000000000000000000000000000000000..3084ae51ecc94b5979ae9075ebb0e08fbda8bdbd --- /dev/null +++ b/.venv/lib/python3.12/site-packages/pytest-9.1.1.dist-info/top_level.txt @@ -0,0 +1,3 @@ +_pytest +py +pytest diff --git a/.venv/lib/python3.12/site-packages/pytest/__init__.py b/.venv/lib/python3.12/site-packages/pytest/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..7bce1d55ae30fdf4f83e09febd6195cfa5298f53 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/pytest/__init__.py @@ -0,0 +1,188 @@ +# PYTHON_ARGCOMPLETE_OK +"""pytest: unit and functional testing with Python.""" + +from __future__ import annotations + +from _pytest import __version__ +from _pytest import version_tuple +from _pytest._code import ExceptionInfo +from _pytest.assertion import register_assert_rewrite +from _pytest.cacheprovider import Cache +from _pytest.capture import CaptureFixture +from _pytest.config import cmdline +from _pytest.config import Config +from _pytest.config import console_main +from _pytest.config import ExitCode +from _pytest.config import hookimpl +from _pytest.config import hookspec +from _pytest.config import main +from _pytest.config import PytestPluginManager +from _pytest.config import UsageError +from _pytest.config.argparsing import OptionGroup +from _pytest.config.argparsing import Parser +from _pytest.debugging import pytestPDB as __pytestPDB +from _pytest.doctest import DoctestItem +from _pytest.fixtures import fixture +from _pytest.fixtures import FixtureDef +from _pytest.fixtures import FixtureLookupError +from _pytest.fixtures import FixtureRequest +from _pytest.fixtures import register_fixture +from _pytest.fixtures import yield_fixture # type: ignore[deprecated] +from _pytest.freeze_support import freeze_includes +from _pytest.legacypath import TempdirFactory +from _pytest.legacypath import Testdir +from _pytest.logging import LogCaptureFixture +from _pytest.main import Dir +from _pytest.main import Session +from _pytest.mark import HIDDEN_PARAM +from _pytest.mark import Mark +from _pytest.mark import MARK_GEN as mark +from _pytest.mark import MarkDecorator +from _pytest.mark import MarkGenerator +from _pytest.mark import param +from _pytest.monkeypatch import MonkeyPatch +from _pytest.nodes import Collector +from _pytest.nodes import Directory +from _pytest.nodes import File +from _pytest.nodes import Item +from _pytest.outcomes import exit +from _pytest.outcomes import fail +from _pytest.outcomes import importorskip +from _pytest.outcomes import skip +from _pytest.outcomes import xfail +from _pytest.pytester import HookRecorder +from _pytest.pytester import LineMatcher +from _pytest.pytester import Pytester +from _pytest.pytester import RecordedHookCall +from _pytest.pytester import RunResult +from _pytest.python import Class +from _pytest.python import Function +from _pytest.python import Metafunc +from _pytest.python import Module +from _pytest.python import Package +from _pytest.python_api import approx +from _pytest.raises import raises +from _pytest.raises import RaisesExc +from _pytest.raises import RaisesGroup +from _pytest.recwarn import deprecated_call +from _pytest.recwarn import WarningsRecorder +from _pytest.recwarn import warns +from _pytest.reports import CollectReport +from _pytest.reports import TestReport +from _pytest.runner import CallInfo +from _pytest.scope import ScopeName +from _pytest.stash import Stash +from _pytest.stash import StashKey +from _pytest.subtests import SubtestReport +from _pytest.subtests import Subtests +from _pytest.terminal import TerminalReporter +from _pytest.terminal import TestShortLogReport +from _pytest.tmpdir import TempPathFactory +from _pytest.warning_types import PytestAssertRewriteWarning +from _pytest.warning_types import PytestCacheWarning +from _pytest.warning_types import PytestCollectionWarning +from _pytest.warning_types import PytestConfigWarning +from _pytest.warning_types import PytestDeprecationWarning +from _pytest.warning_types import PytestExperimentalApiWarning +from _pytest.warning_types import PytestFDWarning +from _pytest.warning_types import PytestRemovedIn10Warning +from _pytest.warning_types import PytestReturnNotNoneWarning +from _pytest.warning_types import PytestUnhandledThreadExceptionWarning +from _pytest.warning_types import PytestUnknownMarkWarning +from _pytest.warning_types import PytestUnraisableExceptionWarning +from _pytest.warning_types import PytestWarning + + +set_trace = __pytestPDB.set_trace + + +__all__ = [ + "HIDDEN_PARAM", + "Cache", + "CallInfo", + "CaptureFixture", + "Class", + "CollectReport", + "Collector", + "Config", + "Dir", + "Directory", + "DoctestItem", + "ExceptionInfo", + "ExitCode", + "File", + "FixtureDef", + "FixtureLookupError", + "FixtureRequest", + "Function", + "HookRecorder", + "Item", + "LineMatcher", + "LogCaptureFixture", + "Mark", + "MarkDecorator", + "MarkGenerator", + "Metafunc", + "Module", + "MonkeyPatch", + "OptionGroup", + "Package", + "Parser", + "PytestAssertRewriteWarning", + "PytestCacheWarning", + "PytestCollectionWarning", + "PytestConfigWarning", + "PytestDeprecationWarning", + "PytestExperimentalApiWarning", + "PytestFDWarning", + "PytestPluginManager", + "PytestRemovedIn10Warning", + "PytestReturnNotNoneWarning", + "PytestUnhandledThreadExceptionWarning", + "PytestUnknownMarkWarning", + "PytestUnraisableExceptionWarning", + "PytestWarning", + "Pytester", + "RaisesExc", + "RaisesGroup", + "RecordedHookCall", + "RunResult", + "ScopeName", + "Session", + "Stash", + "StashKey", + "SubtestReport", + "Subtests", + "TempPathFactory", + "TempdirFactory", + "TerminalReporter", + "TestReport", + "TestShortLogReport", + "Testdir", + "UsageError", + "WarningsRecorder", + "__version__", + "approx", + "cmdline", + "console_main", + "deprecated_call", + "exit", + "fail", + "fixture", + "freeze_includes", + "hookimpl", + "hookspec", + "importorskip", + "main", + "mark", + "param", + "raises", + "register_assert_rewrite", + "register_fixture", + "set_trace", + "skip", + "version_tuple", + "warns", + "xfail", + "yield_fixture", +] diff --git a/.venv/lib/python3.12/site-packages/pytest/__main__.py b/.venv/lib/python3.12/site-packages/pytest/__main__.py new file mode 100644 index 0000000000000000000000000000000000000000..9912fa0b5aca86b16fab3e0bd447e3b4d5075a4a --- /dev/null +++ b/.venv/lib/python3.12/site-packages/pytest/__main__.py @@ -0,0 +1,9 @@ +"""The pytest entry point.""" + +from __future__ import annotations + +from _pytest.config import _console_main + + +if __name__ == "__main__": + raise SystemExit(_console_main()) diff --git a/.venv/lib/python3.12/site-packages/pytest/__pycache__/__init__.cpython-312.pyc b/.venv/lib/python3.12/site-packages/pytest/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3a1b65af403c6f3110855b30b1caa3fbb86b9f35 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/pytest/__pycache__/__init__.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/pytest/__pycache__/__main__.cpython-312.pyc b/.venv/lib/python3.12/site-packages/pytest/__pycache__/__main__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7922e67e1349d08fd264d8676bac38550c4be2fa Binary files /dev/null and b/.venv/lib/python3.12/site-packages/pytest/__pycache__/__main__.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/pytest/py.typed b/.venv/lib/python3.12/site-packages/pytest/py.typed new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/.venv/lib/python3.12/site-packages/python_dateutil-2.9.0.post0.dist-info/INSTALLER b/.venv/lib/python3.12/site-packages/python_dateutil-2.9.0.post0.dist-info/INSTALLER new file mode 100644 index 0000000000000000000000000000000000000000..a1b589e38a32041e49332e5e81c2d363dc418d68 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/python_dateutil-2.9.0.post0.dist-info/INSTALLER @@ -0,0 +1 @@ +pip diff --git a/.venv/lib/python3.12/site-packages/python_dateutil-2.9.0.post0.dist-info/LICENSE b/.venv/lib/python3.12/site-packages/python_dateutil-2.9.0.post0.dist-info/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..1e65815cf0b3132689485874a93034ede7206bf4 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/python_dateutil-2.9.0.post0.dist-info/LICENSE @@ -0,0 +1,54 @@ +Copyright 2017- Paul Ganssle +Copyright 2017- dateutil contributors (see AUTHORS file) + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + +The above license applies to all contributions after 2017-12-01, as well as +all contributions that have been re-licensed (see AUTHORS file for the list of +contributors who have re-licensed their code). +-------------------------------------------------------------------------------- +dateutil - Extensions to the standard Python datetime module. + +Copyright (c) 2003-2011 - Gustavo Niemeyer +Copyright (c) 2012-2014 - Tomi Pieviläinen +Copyright (c) 2014-2016 - Yaron de Leeuw +Copyright (c) 2015- - Paul Ganssle +Copyright (c) 2015- - dateutil contributors (see AUTHORS file) + +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + + * Redistributions of source code must retain the above copyright notice, + this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation + and/or other materials provided with the distribution. + * Neither the name of the copyright holder nor the names of its + contributors may be used to endorse or promote products derived from + this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 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. + +The above BSD License Applies to all code, even that also covered by Apache 2.0. \ No newline at end of file diff --git a/.venv/lib/python3.12/site-packages/python_dateutil-2.9.0.post0.dist-info/METADATA b/.venv/lib/python3.12/site-packages/python_dateutil-2.9.0.post0.dist-info/METADATA new file mode 100644 index 0000000000000000000000000000000000000000..577f2bf2b7749e1b123b8225d610b1b257e430cc --- /dev/null +++ b/.venv/lib/python3.12/site-packages/python_dateutil-2.9.0.post0.dist-info/METADATA @@ -0,0 +1,204 @@ +Metadata-Version: 2.1 +Name: python-dateutil +Version: 2.9.0.post0 +Summary: Extensions to the standard Python datetime module +Home-page: https://github.com/dateutil/dateutil +Author: Gustavo Niemeyer +Author-email: gustavo@niemeyer.net +Maintainer: Paul Ganssle +Maintainer-email: dateutil@python.org +License: Dual License +Project-URL: Documentation, https://dateutil.readthedocs.io/en/stable/ +Project-URL: Source, https://github.com/dateutil/dateutil +Classifier: Development Status :: 5 - Production/Stable +Classifier: Intended Audience :: Developers +Classifier: License :: OSI Approved :: BSD License +Classifier: License :: OSI Approved :: Apache Software License +Classifier: Programming Language :: Python +Classifier: Programming Language :: Python :: 2 +Classifier: Programming Language :: Python :: 2.7 +Classifier: Programming Language :: Python :: 3 +Classifier: Programming Language :: Python :: 3.3 +Classifier: Programming Language :: Python :: 3.4 +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.12 +Classifier: Topic :: Software Development :: Libraries +Requires-Python: !=3.0.*,!=3.1.*,!=3.2.*,>=2.7 +Description-Content-Type: text/x-rst +License-File: LICENSE +Requires-Dist: six >=1.5 + +dateutil - powerful extensions to datetime +========================================== + +|pypi| |support| |licence| + +|gitter| |readthedocs| + +|travis| |appveyor| |pipelines| |coverage| + +.. |pypi| image:: https://img.shields.io/pypi/v/python-dateutil.svg?style=flat-square + :target: https://pypi.org/project/python-dateutil/ + :alt: pypi version + +.. |support| image:: https://img.shields.io/pypi/pyversions/python-dateutil.svg?style=flat-square + :target: https://pypi.org/project/python-dateutil/ + :alt: supported Python version + +.. |travis| image:: https://img.shields.io/travis/dateutil/dateutil/master.svg?style=flat-square&label=Travis%20Build + :target: https://travis-ci.org/dateutil/dateutil + :alt: travis build status + +.. |appveyor| image:: https://img.shields.io/appveyor/ci/dateutil/dateutil/master.svg?style=flat-square&logo=appveyor + :target: https://ci.appveyor.com/project/dateutil/dateutil + :alt: appveyor build status + +.. |pipelines| image:: https://dev.azure.com/pythondateutilazure/dateutil/_apis/build/status/dateutil.dateutil?branchName=master + :target: https://dev.azure.com/pythondateutilazure/dateutil/_build/latest?definitionId=1&branchName=master + :alt: azure pipelines build status + +.. |coverage| image:: https://codecov.io/gh/dateutil/dateutil/branch/master/graphs/badge.svg?branch=master + :target: https://codecov.io/gh/dateutil/dateutil?branch=master + :alt: Code coverage + +.. |gitter| image:: https://badges.gitter.im/dateutil/dateutil.svg + :alt: Join the chat at https://gitter.im/dateutil/dateutil + :target: https://gitter.im/dateutil/dateutil + +.. |licence| image:: https://img.shields.io/pypi/l/python-dateutil.svg?style=flat-square + :target: https://pypi.org/project/python-dateutil/ + :alt: licence + +.. |readthedocs| image:: https://img.shields.io/readthedocs/dateutil/latest.svg?style=flat-square&label=Read%20the%20Docs + :alt: Read the documentation at https://dateutil.readthedocs.io/en/latest/ + :target: https://dateutil.readthedocs.io/en/latest/ + +The `dateutil` module provides powerful extensions to +the standard `datetime` module, available in Python. + +Installation +============ +`dateutil` can be installed from PyPI using `pip` (note that the package name is +different from the importable name):: + + pip install python-dateutil + +Download +======== +dateutil is available on PyPI +https://pypi.org/project/python-dateutil/ + +The documentation is hosted at: +https://dateutil.readthedocs.io/en/stable/ + +Code +==== +The code and issue tracker are hosted on GitHub: +https://github.com/dateutil/dateutil/ + +Features +======== + +* Computing of relative deltas (next month, next year, + next Monday, last week of month, etc); +* Computing of relative deltas between two given + date and/or datetime objects; +* Computing of dates based on very flexible recurrence rules, + using a superset of the `iCalendar `_ + specification. Parsing of RFC strings is supported as well. +* Generic parsing of dates in almost any string format; +* Timezone (tzinfo) implementations for tzfile(5) format + files (/etc/localtime, /usr/share/zoneinfo, etc), TZ + environment string (in all known formats), iCalendar + format files, given ranges (with help from relative deltas), + local machine timezone, fixed offset timezone, UTC timezone, + and Windows registry-based time zones. +* Internal up-to-date world timezone information based on + Olson's database. +* Computing of Easter Sunday dates for any given year, + using Western, Orthodox or Julian algorithms; +* A comprehensive test suite. + +Quick example +============= +Here's a snapshot, just to give an idea about the power of the +package. For more examples, look at the documentation. + +Suppose you want to know how much time is left, in +years/months/days/etc, before the next easter happening on a +year with a Friday 13th in August, and you want to get today's +date out of the "date" unix system command. Here is the code: + +.. code-block:: python3 + + >>> from dateutil.relativedelta import * + >>> from dateutil.easter import * + >>> from dateutil.rrule import * + >>> from dateutil.parser import * + >>> from datetime import * + >>> now = parse("Sat Oct 11 17:13:46 UTC 2003") + >>> today = now.date() + >>> year = rrule(YEARLY,dtstart=now,bymonth=8,bymonthday=13,byweekday=FR)[0].year + >>> rdelta = relativedelta(easter(year), today) + >>> print("Today is: %s" % today) + Today is: 2003-10-11 + >>> print("Year with next Aug 13th on a Friday is: %s" % year) + Year with next Aug 13th on a Friday is: 2004 + >>> print("How far is the Easter of that year: %s" % rdelta) + How far is the Easter of that year: relativedelta(months=+6) + >>> print("And the Easter of that year is: %s" % (today+rdelta)) + And the Easter of that year is: 2004-04-11 + +Being exactly 6 months ahead was **really** a coincidence :) + +Contributing +============ + +We welcome many types of contributions - bug reports, pull requests (code, infrastructure or documentation fixes). For more information about how to contribute to the project, see the ``CONTRIBUTING.md`` file in the repository. + + +Author +====== +The dateutil module was written by Gustavo Niemeyer +in 2003. + +It is maintained by: + +* Gustavo Niemeyer 2003-2011 +* Tomi Pieviläinen 2012-2014 +* Yaron de Leeuw 2014-2016 +* Paul Ganssle 2015- + +Starting with version 2.4.1 and running until 2.8.2, all source and binary +distributions will be signed by a PGP key that has, at the very least, been +signed by the key which made the previous release. A table of release signing +keys can be found below: + +=========== ============================ +Releases Signing key fingerprint +=========== ============================ +2.4.1-2.8.2 `6B49 ACBA DCF6 BD1C A206 67AB CD54 FCE3 D964 BEFB`_ +=========== ============================ + +New releases *may* have signed tags, but binary and source distributions +uploaded to PyPI will no longer have GPG signatures attached. + +Contact +======= +Our mailing list is available at `dateutil@python.org `_. As it is hosted by the PSF, it is subject to the `PSF code of +conduct `_. + +License +======= + +All contributions after December 1, 2017 released under dual license - either `Apache 2.0 License `_ or the `BSD 3-Clause License `_. Contributions before December 1, 2017 - except those those explicitly relicensed - are released only under the BSD 3-Clause License. + + +.. _6B49 ACBA DCF6 BD1C A206 67AB CD54 FCE3 D964 BEFB: + https://pgp.mit.edu/pks/lookup?op=vindex&search=0xCD54FCE3D964BEFB diff --git a/.venv/lib/python3.12/site-packages/python_dateutil-2.9.0.post0.dist-info/RECORD b/.venv/lib/python3.12/site-packages/python_dateutil-2.9.0.post0.dist-info/RECORD new file mode 100644 index 0000000000000000000000000000000000000000..8abf769beb56ed307111268106e19c87137b23df --- /dev/null +++ b/.venv/lib/python3.12/site-packages/python_dateutil-2.9.0.post0.dist-info/RECORD @@ -0,0 +1,44 @@ +dateutil/__init__.py,sha256=Mqam67WO9IkTmUFyI66vS6IoSXTp9G388DadH2LCMLY,620 +dateutil/__pycache__/__init__.cpython-312.pyc,, +dateutil/__pycache__/_common.cpython-312.pyc,, +dateutil/__pycache__/_version.cpython-312.pyc,, +dateutil/__pycache__/easter.cpython-312.pyc,, +dateutil/__pycache__/relativedelta.cpython-312.pyc,, +dateutil/__pycache__/rrule.cpython-312.pyc,, +dateutil/__pycache__/tzwin.cpython-312.pyc,, +dateutil/__pycache__/utils.cpython-312.pyc,, +dateutil/_common.py,sha256=77w0yytkrxlYbSn--lDVPUMabUXRR9I3lBv_vQRUqUY,932 +dateutil/_version.py,sha256=BV031OxDDAmy58neUg5yyqLkLaqIw7ibK9As3jiMib0,166 +dateutil/easter.py,sha256=dyBi-lKvimH1u_k6p7Z0JJK72QhqVtVBsqByvpEPKvc,2678 +dateutil/parser/__init__.py,sha256=wWk6GFuxTpjoggCGtgkceJoti4pVjl4_fHQXpNOaSYg,1766 +dateutil/parser/__pycache__/__init__.cpython-312.pyc,, +dateutil/parser/__pycache__/_parser.cpython-312.pyc,, +dateutil/parser/__pycache__/isoparser.cpython-312.pyc,, +dateutil/parser/_parser.py,sha256=7klDdyicksQB_Xgl-3UAmBwzCYor1AIZqklIcT6dH_8,58796 +dateutil/parser/isoparser.py,sha256=8Fy999bnCd1frSdOYuOraWfJTtd5W7qQ51NwNuH_hXM,13233 +dateutil/relativedelta.py,sha256=IY_mglMjoZbYfrvloTY2ce02aiVjPIkiZfqgNTZRfuA,24903 +dateutil/rrule.py,sha256=KJzKlaCd1jEbu4A38ZltslaoAUh9nSbdbOFdjp70Kew,66557 +dateutil/tz/__init__.py,sha256=F-Mz13v6jYseklQf9Te9J6nzcLDmq47gORa61K35_FA,444 +dateutil/tz/__pycache__/__init__.cpython-312.pyc,, +dateutil/tz/__pycache__/_common.cpython-312.pyc,, +dateutil/tz/__pycache__/_factories.cpython-312.pyc,, +dateutil/tz/__pycache__/tz.cpython-312.pyc,, +dateutil/tz/__pycache__/win.cpython-312.pyc,, +dateutil/tz/_common.py,sha256=cgzDTANsOXvEc86cYF77EsliuSab8Puwpsl5-bX3_S4,12977 +dateutil/tz/_factories.py,sha256=unb6XQNXrPMveksTCU-Ag8jmVZs4SojoPUcAHpWnrvU,2569 +dateutil/tz/tz.py,sha256=EUnEdMfeThXiY6l4sh9yBabZ63_POzy01zSsh9thn1o,62855 +dateutil/tz/win.py,sha256=xJszWgSwE1xPx_HJj4ZkepyukC_hNy016WMcXhbRaB8,12935 +dateutil/tzwin.py,sha256=7Ar4vdQCnnM0mKR3MUjbIKsZrBVfHgdwsJZc_mGYRew,59 +dateutil/utils.py,sha256=dKCchEw8eObi0loGTx91unBxm_7UGlU3v_FjFMdqwYM,1965 +dateutil/zoneinfo/__init__.py,sha256=KYg0pthCMjcp5MXSEiBJn3nMjZeNZav7rlJw5-tz1S4,5889 +dateutil/zoneinfo/__pycache__/__init__.cpython-312.pyc,, +dateutil/zoneinfo/__pycache__/rebuild.cpython-312.pyc,, +dateutil/zoneinfo/dateutil-zoneinfo.tar.gz,sha256=0-pS57bpaN4NiE3xKIGTWW-pW4A9tPkqGCeac5gARHU,156400 +dateutil/zoneinfo/rebuild.py,sha256=MiqYzCIHvNbMH-LdRYLv-4T0EIA7hDKt5GLR0IRTLdI,2392 +python_dateutil-2.9.0.post0.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4 +python_dateutil-2.9.0.post0.dist-info/LICENSE,sha256=ugD1Gg2SgjtaHN4n2LW50jIeZ-2NqbwWPv-W1eF-V34,2889 +python_dateutil-2.9.0.post0.dist-info/METADATA,sha256=qdQ22jIr6AgzL5jYgyWZjofLaTpniplp_rTPrXKabpM,8354 +python_dateutil-2.9.0.post0.dist-info/RECORD,, +python_dateutil-2.9.0.post0.dist-info/WHEEL,sha256=-G_t0oGuE7UD0DrSpVZnq1hHMBV9DD2XkS5v7XpmTnk,110 +python_dateutil-2.9.0.post0.dist-info/top_level.txt,sha256=4tjdWkhRZvF7LA_BYe_L9gB2w_p2a-z5y6ArjaRkot8,9 +python_dateutil-2.9.0.post0.dist-info/zip-safe,sha256=AbpHGcgLb-kRsJGnwFEktk7uzpZOCcBY74-YBdrKVGs,1 diff --git a/.venv/lib/python3.12/site-packages/python_dateutil-2.9.0.post0.dist-info/WHEEL b/.venv/lib/python3.12/site-packages/python_dateutil-2.9.0.post0.dist-info/WHEEL new file mode 100644 index 0000000000000000000000000000000000000000..4724c45738f6ac125bb3a21787855562e6870440 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/python_dateutil-2.9.0.post0.dist-info/WHEEL @@ -0,0 +1,6 @@ +Wheel-Version: 1.0 +Generator: bdist_wheel (0.42.0) +Root-Is-Purelib: true +Tag: py2-none-any +Tag: py3-none-any + diff --git a/.venv/lib/python3.12/site-packages/python_dateutil-2.9.0.post0.dist-info/top_level.txt b/.venv/lib/python3.12/site-packages/python_dateutil-2.9.0.post0.dist-info/top_level.txt new file mode 100644 index 0000000000000000000000000000000000000000..66501480ba5b63f98ee9a59c1f99e5e6917da6d9 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/python_dateutil-2.9.0.post0.dist-info/top_level.txt @@ -0,0 +1 @@ +dateutil diff --git a/.venv/lib/python3.12/site-packages/python_dateutil-2.9.0.post0.dist-info/zip-safe b/.venv/lib/python3.12/site-packages/python_dateutil-2.9.0.post0.dist-info/zip-safe new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/.venv/lib/python3.12/site-packages/python_dateutil-2.9.0.post0.dist-info/zip-safe @@ -0,0 +1 @@ + diff --git a/.venv/lib/python3.12/site-packages/pywavelets-1.10.0.dist-info/INSTALLER b/.venv/lib/python3.12/site-packages/pywavelets-1.10.0.dist-info/INSTALLER new file mode 100644 index 0000000000000000000000000000000000000000..a1b589e38a32041e49332e5e81c2d363dc418d68 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/pywavelets-1.10.0.dist-info/INSTALLER @@ -0,0 +1 @@ +pip diff --git a/.venv/lib/python3.12/site-packages/pywavelets-1.10.0.dist-info/METADATA b/.venv/lib/python3.12/site-packages/pywavelets-1.10.0.dist-info/METADATA new file mode 100644 index 0000000000000000000000000000000000000000..d28a0a775dc278ae9eef19fbf85fbbab890524e6 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/pywavelets-1.10.0.dist-info/METADATA @@ -0,0 +1,191 @@ +Metadata-Version: 2.4 +Name: PyWavelets +Version: 1.10.0 +Summary: PyWavelets, wavelet transform module +Maintainer-Email: The PyWavelets Developers +License-Expression: MIT AND BSD-3-Clause +License-File: LICENSE +License-File: licenses_bundled/LICENSE_numpy.txt +License-File: licenses_bundled/LICENSE_scipy.txt +Classifier: Development Status :: 5 - Production/Stable +Classifier: Intended Audience :: Developers +Classifier: Intended Audience :: Education +Classifier: Intended Audience :: Science/Research +Classifier: Operating System :: OS Independent +Classifier: Programming Language :: C +Classifier: Programming Language :: Python +Classifier: Programming Language :: Python :: 3 +Classifier: Programming Language :: Python :: 3.12 +Classifier: Programming Language :: Python :: 3.13 +Classifier: Programming Language :: Python :: 3.14 +Classifier: Programming Language :: Python :: 3.15 +Classifier: Programming Language :: Python :: Free Threading :: 2 - Beta +Classifier: Topic :: Software Development :: Libraries :: Python Modules +Project-URL: homepage, https://github.com/PyWavelets/pywt +Project-URL: source, https://github.com/PyWavelets/pywt +Project-URL: documentation, https://pywavelets.readthedocs.io/ +Requires-Python: >=3.12 +Requires-Dist: numpy<3,>=1.26.4 +Description-Content-Type: text/x-rst + ++---------------+-----------------+ +| Service | Master branch | ++===============+=================+ +| GitHub | |ghactions_ci| | ++---------------+-----------------+ +| Appveyor | |appveyor_ci| | ++---------------+-----------------+ +| Read the Docs | |read_the_docs| | ++---------------+-----------------+ + + +.. |ghactions_ci| image:: https://github.com/PyWavelets/pywt/actions/workflows/tests.yml/badge.svg?branch=main + :alt: Build Status + :target: https://github.com/PyWavelets/pywt/actions/workflows/tests.yml?query=branch%3Amain + +.. |appveyor_ci| image:: https://ci.appveyor.com/api/projects/status/github/PyWavelets/pywt + :align: middle + :target: https://ci.appveyor.com/project/PyWavelets/pywt + :alt: Appveyor Status + +.. |read_the_docs| image:: https://readthedocs.org/projects/pywavelets/badge/?version=latest + :align: middle + :target: https://pywavelets.readthedocs.io/en/latest/?badge=latest + :alt: Documentation Status + + +PyWavelets +========== + +.. contents:: + +What is PyWavelets +------------------ + +PyWavelets is a free Open Source library for wavelet transforms in Python. +Wavelets are mathematical basis functions that are localized in both time and +frequency. Wavelet transforms are time-frequency transforms employing +wavelets. They are similar to Fourier transforms, the difference being that +Fourier transforms are localized only in frequency instead of in time and +frequency. + +The main features of PyWavelets are: + + * 1D, 2D and nD Forward and Inverse Discrete Wavelet Transform (DWT and IDWT) + * 1D, 2D and nD Multilevel DWT and IDWT + * 1D and 2D Stationary Wavelet Transform (Undecimated Wavelet Transform) + * 1D and 2D Wavelet Packet decomposition and reconstruction + * 1D Continuous Wavelet Transform + * Computing Approximations of wavelet and scaling functions + * Over 100 `built-in wavelet filters`_ and support for custom wavelets + * Single and double precision calculations + * Real and complex calculations + * Results compatible with Matlab Wavelet Toolbox (TM) + + +Documentation +------------- + +Documentation with detailed examples and links to more resources is available +online at http://pywavelets.readthedocs.org. + +For more usage examples see the `demo`_ directory in the source package. + + +Installation +------------ + +PyWavelets supports `Python`_ >=3.10, and is only dependent on `NumPy`_ +(supported versions are currently ``>= 1.23.0``). To pass all of the tests, +`Matplotlib`_ is also required. + +There are binary wheels for Intel Linux, Windows and macOS / OSX on PyPi. If +you are on one of these platforms, you should get a binary (precompiled) +installation with:: + + pip install PyWavelets + +Users of the Anaconda_ Python distribution may wish to obtain pre-built +Windows, Intel Linux or macOS / OSX binaries from the conda-forge channel. +This can be done via:: + + conda install -c conda-forge pywavelets + +Several Linux distributions have their own packages for PyWavelets, but these +tend to be moderately out of date. Query your Linux package manager tool for +``python-pywavelets``, ``python-wavelets``, ``python-pywt`` or a similar +package name. + +If you want or need to install from source, you will need a working C compiler +(any common one will work) and a recent version of `Cython`_. Navigate to the +PyWavelets source code directory (containing ``pyproject.toml``) and type:: + + pip install . + +The most recent *development* version can be found on GitHub at +https://github.com/PyWavelets/pywt. + +The latest release, including source and binary packages for Intel Linux, +macOS and Windows, is available for download from the `Python Package Index`_. +You can find source releases at the `Releases Page`_. + +State of development & Contributing +----------------------------------- + +PyWavelets started in 2006 as an academic project for a master thesis +on `Analysis and Classification of Medical Signals using Wavelet Transforms` +and was maintained until 2012 by its `original developer`_. In 2013 +maintenance was taken over in a `new repo `_) +by a larger development team - a move supported by the original developer. +The repo move doesn't mean that this is a fork - the package continues to be +developed under the name "PyWavelets", and released on PyPi and Github (see +`this issue `_ for the discussion +where that was decided). + +All contributions including bug reports, bug fixes, new feature implementations +and documentation improvements are welcome. Moreover, developers with an +interest in PyWavelets are very welcome to join the development team! + +As of 2019, PyWavelets development is supported in part by Tidelift. +`Help support PyWavelets with the Tidelift Subscription `_ + + +Contact +------- + +Use `GitHub Issues`_ or the `mailing list`_ to post your comments or questions. + +**Report a security vulnerability:** https://tidelift.com/security + +License +------- + +PyWavelets is a free Open Source software released under the MIT license. + +If you wish to cite PyWavelets in a publication, please use the following +JOSS publication. + +.. image:: http://joss.theoj.org/papers/10.21105/joss.01237/status.svg + :target: https://doi.org/10.21105/joss.01237 + +Specific releases can also be cited via Zenodo. The DOI below will correspond +to the most recent release. DOIs for past versions can be found by following +the link in the badge below to Zenodo: + +.. image:: https://zenodo.org/badge/DOI/10.5281/zenodo.1407171.svg + :target: https://doi.org/10.5281/zenodo.1407171 + +.. _built-in wavelet filters: http://wavelets.pybytes.com/ +.. _Cython: http://cython.org/ +.. _demo: https://github.com/PyWavelets/pywt/tree/main/demo +.. _Anaconda: https://www.continuum.io +.. _GitHub: https://github.com/PyWavelets/pywt +.. _GitHub Issues: https://github.com/PyWavelets/pywt/issues +.. _NumPy: https://www.numpy.org +.. _SciPy: https://www.scipy.org +.. _original developer: http://en.ig.ma +.. _Python: http://python.org/ +.. _Python Package Index: http://pypi.python.org/pypi/PyWavelets/ +.. _mailing list: http://groups.google.com/group/pywavelets +.. _Releases Page: https://github.com/PyWavelets/pywt/releases +.. _Matplotlib: http://matplotlib.org diff --git a/.venv/lib/python3.12/site-packages/pywavelets-1.10.0.dist-info/RECORD b/.venv/lib/python3.12/site-packages/pywavelets-1.10.0.dist-info/RECORD new file mode 100644 index 0000000000000000000000000000000000000000..e1dadb745e21a817263ad9e2a90862b62a760223 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/pywavelets-1.10.0.dist-info/RECORD @@ -0,0 +1,100 @@ +pywavelets-1.10.0.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4 +pywavelets-1.10.0.dist-info/METADATA,sha256=_VIHN5S8zvSMF7-yCE9XTvH55FuTTWq5HQndwrO00yc,7641 +pywavelets-1.10.0.dist-info/RECORD,, +pywavelets-1.10.0.dist-info/WHEEL,sha256=rJCplGeGFjRoUvxJWhVONRgyGYGZoOkhyej0s3KyjoI,138 +pywavelets-1.10.0.dist-info/licenses/LICENSE,sha256=DBLorjtU3WEHLFuX-XyrYnVbiTr7kejli_m5u-Ki7Ig,1171 +pywavelets-1.10.0.dist-info/licenses/licenses_bundled/LICENSE_numpy.txt,sha256=AfsBaEmqQn7bG7u9VfkcJspsrbMqWyDn8ABlXdBbB2A,1543 +pywavelets-1.10.0.dist-info/licenses/licenses_bundled/LICENSE_scipy.txt,sha256=wp-45ZNvMyN6ixUla0xukwN_Bbv1jD17V1Wu3kwgAXM,1536 +pywt/__init__.py,sha256=VF5PCSYm-sDiLVRQ0H-fufg_bac4ONFbP82tANegBIo,1027 +pywt/__pycache__/__init__.cpython-312.pyc,, +pywt/__pycache__/_cwt.cpython-312.pyc,, +pywt/__pycache__/_doc_utils.cpython-312.pyc,, +pywt/__pycache__/_dwt.cpython-312.pyc,, +pywt/__pycache__/_functions.cpython-312.pyc,, +pywt/__pycache__/_mra.cpython-312.pyc,, +pywt/__pycache__/_multidim.cpython-312.pyc,, +pywt/__pycache__/_multilevel.cpython-312.pyc,, +pywt/__pycache__/_pytest.cpython-312.pyc,, +pywt/__pycache__/_pytesttester.cpython-312.pyc,, +pywt/__pycache__/_swt.cpython-312.pyc,, +pywt/__pycache__/_thresholding.cpython-312.pyc,, +pywt/__pycache__/_utils.cpython-312.pyc,, +pywt/__pycache__/_wavelet_packets.cpython-312.pyc,, +pywt/__pycache__/conftest.cpython-312.pyc,, +pywt/__pycache__/version.cpython-312.pyc,, +pywt/_cwt.py,sha256=c5H1cFFweS2fAacm7ZMvsPPG0gWHIFNkDIYLaC5YbGE,9084 +pywt/_doc_utils.py,sha256=48RF4fcXkArsfptuCW_T4uiFoJkhYYl1XQm3ZMTSa9A,5820 +pywt/_dwt.py,sha256=kZIDnrYtz9hIrwR3UG39FEQjNdxGshP-c6KwJS5oQf8,16978 +pywt/_extensions/_cwt.cpython-312-x86_64-linux-gnu.so,sha256=XyZsSND5iZw4Ij2DdcPFrMc5yAqWNIGAvqktUojgk-o,306944 +pywt/_extensions/_dwt.cpython-312-x86_64-linux-gnu.so,sha256=muAQ2VttdjkFlSOM3U51BpTrh-HEMaQstdjAuN8A-iE,546280 +pywt/_extensions/_pywt.cpython-312-x86_64-linux-gnu.so,sha256=nn-4OOn8wyzUsi4jr-e3snr-l2_s366N-uo2XVomAy0,536848 +pywt/_extensions/_swt.cpython-312-x86_64-linux-gnu.so,sha256=yT4bycZJgVVYT89K35JXeSqG1-3gAj-XfV34h_iAmz0,479792 +pywt/_functions.py,sha256=Xe8MEKYTjq7eatBQqvcePbT9HZA_S_4UT61BLOqvzsI,7899 +pywt/_mra.py,sha256=D2280E6lt0cDlC9OuOvZ8Fmr6lZ6cfkbIZVsMwY4g6w,14375 +pywt/_multidim.py,sha256=cx_myX60xPDWnQLnP4nYFM7Q1dupcCASOY5SFFLOwjs,10695 +pywt/_multilevel.py,sha256=DXiDjIPN59oC4CIcVYZZjsGRPHjwAGny57z2hjqRXp8,56969 +pywt/_pytest.py,sha256=x_za6_7b8213vlof7OUZDRqLKTyQynpJ7Iqa_o3eEgk,2823 +pywt/_pytesttester.py,sha256=Te-lvHE8wKkX_J54ciTAshkt9VmALzkdv6KotHtVSkQ,4632 +pywt/_swt.py,sha256=SCRGm9PYKQqW5s9M5bSFJYF9HWEB5miz030ZnefFo9g,28862 +pywt/_thresholding.py,sha256=KNvgoQdAYEHbk48z2daiWn8XN0T_0N0OxhQa8nzT-00,8718 +pywt/_utils.py,sha256=3iXQzwvwJWV8-XQte7qT50e0tPANfNMLDiX05bf89W0,3441 +pywt/_wavelet_packets.py,sha256=FYlsgLfxBaAySBKcDAFfm7SCRcHchYvl-SxeKSzjC4c,36554 +pywt/conftest.py,sha256=cfdJT7ucDVr1E_2Zcl2wdjNQC-dyQW2IF6L21CCcN0E,143 +pywt/data/__init__.py,sha256=Hk9rGIBsbs4FQx7iO4fDnMLlzMhLw957HH70LzMhr6A,96 +pywt/data/__pycache__/__init__.cpython-312.pyc,, +pywt/data/__pycache__/_readers.cpython-312.pyc,, +pywt/data/__pycache__/_wavelab_signals.cpython-312.pyc,, +pywt/data/_readers.py,sha256=EdLN1VFgRbbD-O9mn-_m9gZ8YfDS1vIIzhBEhWMt0NE,4967 +pywt/data/_wavelab_signals.py,sha256=f9oJFBAux1e_4yon5akLqaEG8pcE0vC7L5TYL1a1sw0,9888 +pywt/data/aero.npz,sha256=34YmNXmLrJQia4ko8iTajO-LDQBJLB_fSPrG36-XqUs,227784 +pywt/data/ascent.npz,sha256=ptVryOllcdYSTzTO3rpJ8dNZlQf2yJCtm6U4VERU6Pc,170883 +pywt/data/camera.npz,sha256=K-gZXpaAzLPIBP7hnKC2mgl-rpybKrl0dMfxQ4Fx8HQ,169034 +pywt/data/ecg.npz,sha256=6nIEdhOTQeq-zz5EzGAs11V2r_HkFWscBp97M-hqnms,4358 +pywt/data/sst_nino3.npz,sha256=0e9wrxKCTYwIzvlsXhaEoi2BnYmtzZqzz5LRKl2dg2c,64262 +pywt/tests/__pycache__/test__pywt.cpython-312.pyc,, +pywt/tests/__pycache__/test_concurrent.cpython-312.pyc,, +pywt/tests/__pycache__/test_cwt_wavelets.cpython-312.pyc,, +pywt/tests/__pycache__/test_data.cpython-312.pyc,, +pywt/tests/__pycache__/test_deprecations.cpython-312.pyc,, +pywt/tests/__pycache__/test_doc.cpython-312.pyc,, +pywt/tests/__pycache__/test_dwt_idwt.cpython-312.pyc,, +pywt/tests/__pycache__/test_functions.cpython-312.pyc,, +pywt/tests/__pycache__/test_matlab_compatibility.cpython-312.pyc,, +pywt/tests/__pycache__/test_matlab_compatibility_cwt.cpython-312.pyc,, +pywt/tests/__pycache__/test_modes.cpython-312.pyc,, +pywt/tests/__pycache__/test_mra.cpython-312.pyc,, +pywt/tests/__pycache__/test_multidim.cpython-312.pyc,, +pywt/tests/__pycache__/test_multilevel.cpython-312.pyc,, +pywt/tests/__pycache__/test_perfect_reconstruction.cpython-312.pyc,, +pywt/tests/__pycache__/test_swt.cpython-312.pyc,, +pywt/tests/__pycache__/test_thresholding.cpython-312.pyc,, +pywt/tests/__pycache__/test_wavelet.cpython-312.pyc,, +pywt/tests/__pycache__/test_wp.cpython-312.pyc,, +pywt/tests/__pycache__/test_wp2d.cpython-312.pyc,, +pywt/tests/__pycache__/test_wpnd.cpython-312.pyc,, +pywt/tests/data/README.md,sha256=RzoMvLp22ekMmbglyb27w6USDYZSEn5p1TcJjcfCJfM,148 +pywt/tests/data/cwt_matlabR2015b_result.npz,sha256=MgyWON5UrhCsIhYswnnv6tpaAS30uXCDjYwmLjzH5Z4,1826646 +pywt/tests/data/dwt_matlabR2012a_result.npz,sha256=lhaHq4-ug_S2LtPUl1MVolUVxBanRDxgQ0EEPhHzziI,3740630 +pywt/tests/data/wavelab_test_signals.npz,sha256=-cx0ne9JdTcq6LiKBacjM_0_En72TAiKvvFUW1yiZYE,184818 +pywt/tests/test__pywt.py,sha256=zV9mqATwUVvC-7XiFhGMEl0xmup8qMEdyTZdPNlAuqw,5404 +pywt/tests/test_concurrent.py,sha256=_Ei1tai1dC2KlZfBXO1wJ9P4xAfWShwiJboeu-q6UD4,3937 +pywt/tests/test_cwt_wavelets.py,sha256=2L5YAxkhg0WigBv7z1LCT3nHEVr7pOox4GZm6M3i2vk,17389 +pywt/tests/test_data.py,sha256=v4wtM2Nh1fx8J15kVvuST5xcsvHcYy8tiReBTKGcveA,2267 +pywt/tests/test_deprecations.py,sha256=KxmrKVIWZp9uaucRDy-FJKlhJDl7BznDgpLj7z9Z9Fc,1859 +pywt/tests/test_doc.py,sha256=idmDvHyku0NgBD5M-76dfgxAvnJ2_05eIcLr87udWWw,603 +pywt/tests/test_dwt_idwt.py,sha256=Mj819cTbi_7W14SV0dXPJNQkeAl-R-Iykf3Za-M5Zgs,13076 +pywt/tests/test_functions.py,sha256=elVWSVvtTIRB0NHqiGCsnvlGhkISXrgYXlGPyvzbwoc,1301 +pywt/tests/test_matlab_compatibility.py,sha256=YWwHg9_kPkPcQLDHj6trMSHCg7Eg77DcCFK2hYu2zxU,5784 +pywt/tests/test_matlab_compatibility_cwt.py,sha256=QRUmzEf6f22_Qj1SHrdNTJonKujKhUS7-iLh8MtVzXk,6192 +pywt/tests/test_modes.py,sha256=UaNlce2uy-ZwsCLpvqaKQ9_5yZOz9HnCv4VtLqIpKVg,4783 +pywt/tests/test_mra.py,sha256=AjdWt99tlXqYjwhlbY_eqC88dJVAk4RoBjqWCwcl6hc,8967 +pywt/tests/test_multidim.py,sha256=w68h_nIwgABTYDWPYNwHeGXCTq4_8306bbOz3-4RdsU,14798 +pywt/tests/test_multilevel.py,sha256=_OJnhx4jIIPaJmMtjYnOKYKu4J7YpEXXitbCvkMr-Uc,39076 +pywt/tests/test_perfect_reconstruction.py,sha256=USDlQB_uDrVUSCGe7KA3lt4t5MtNlduH4E829udW4C4,1762 +pywt/tests/test_swt.py,sha256=GRn7-m2fhnuWAIOvgeRltCbWai0RgL6YTU-u6LahUR0,24860 +pywt/tests/test_thresholding.py,sha256=2NClToBrItkmji2mQntYjUMr-Myd_P9CjOjqX93BdkM,6467 +pywt/tests/test_wavelet.py,sha256=gL_45RgdlYXEvtsoMvHNN-irnBtIhR_1Lc0lWX_fKhs,11386 +pywt/tests/test_wp.py,sha256=7FTiiECq81JIfmBy6x7MPjnn8baHxnPZYybUng8KUqw,7987 +pywt/tests/test_wp2d.py,sha256=moquwbON3DGgdqaFSkhtwYgK23dZQEgBdCREoG8Y7uY,9366 +pywt/tests/test_wpnd.py,sha256=iseGXwMYrUHG7_MX8bVShDMJLdZuJ6rTYZ9bOtea4iE,8278 +pywt/version.py,sha256=kn_IX46WhnGH5PNKtylAaGdeyXj_Z6M_uKu5JbNH_fk,243 diff --git a/.venv/lib/python3.12/site-packages/pywavelets-1.10.0.dist-info/WHEEL b/.venv/lib/python3.12/site-packages/pywavelets-1.10.0.dist-info/WHEEL new file mode 100644 index 0000000000000000000000000000000000000000..227a38cf01899aeccdf106d40cea71a6c95d30af --- /dev/null +++ b/.venv/lib/python3.12/site-packages/pywavelets-1.10.0.dist-info/WHEEL @@ -0,0 +1,6 @@ +Wheel-Version: 1.0 +Generator: meson +Root-Is-Purelib: false +Tag: cp312-cp312-manylinux_2_27_x86_64 +Tag: cp312-cp312-manylinux_2_28_x86_64 + diff --git a/.venv/lib/python3.12/site-packages/pywavelets-1.10.0.dist-info/licenses/LICENSE b/.venv/lib/python3.12/site-packages/pywavelets-1.10.0.dist-info/licenses/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..d61b491ba658ec721148be8a5ce27d20f86239bf --- /dev/null +++ b/.venv/lib/python3.12/site-packages/pywavelets-1.10.0.dist-info/licenses/LICENSE @@ -0,0 +1,20 @@ +Copyright (c) 2006-2012 Filip Wasilewski +Copyright (c) 2012- The PyWavelets Developers + +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/.venv/lib/python3.12/site-packages/pywavelets-1.10.0.dist-info/licenses/licenses_bundled/LICENSE_numpy.txt b/.venv/lib/python3.12/site-packages/pywavelets-1.10.0.dist-info/licenses/licenses_bundled/LICENSE_numpy.txt new file mode 100644 index 0000000000000000000000000000000000000000..6ccec6824b651e67dc921c8a1bdb7e8ea3f0ae74 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/pywavelets-1.10.0.dist-info/licenses/licenses_bundled/LICENSE_numpy.txt @@ -0,0 +1,30 @@ +Copyright (c) 2005-2024, NumPy Developers. +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 NumPy Developers nor the names of any + contributors may be used to endorse or promote products derived + from this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/.venv/lib/python3.12/site-packages/pywavelets-1.10.0.dist-info/licenses/licenses_bundled/LICENSE_scipy.txt b/.venv/lib/python3.12/site-packages/pywavelets-1.10.0.dist-info/licenses/licenses_bundled/LICENSE_scipy.txt new file mode 100644 index 0000000000000000000000000000000000000000..117117616e806a9bb960b1f32a552c8c912b0497 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/pywavelets-1.10.0.dist-info/licenses/licenses_bundled/LICENSE_scipy.txt @@ -0,0 +1,30 @@ +Copyright (c) 2001-2002 Enthought, Inc. 2003-2024, SciPy Developers. +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions +are met: + +1. Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + +2. Redistributions in binary form must reproduce the above + copyright notice, this list of conditions and the following + disclaimer in the documentation and/or other materials provided + with the distribution. + +3. Neither the name of the copyright holder nor the names of its + contributors may be used to endorse or promote products derived + from this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/.venv/lib/python3.12/site-packages/pywt/__init__.py b/.venv/lib/python3.12/site-packages/pywt/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..669b06b62e975ce91777e694bcd871d54232e80a --- /dev/null +++ b/.venv/lib/python3.12/site-packages/pywt/__init__.py @@ -0,0 +1,38 @@ +# flake8: noqa + +# Copyright (c) 2006-2012 Filip Wasilewski +# Copyright (c) 2012- The PyWavelets Developers +# +# See LICENSE for more details. + +""" +Discrete forward and inverse wavelet transform, stationary wavelet transform, +wavelet packets signal decomposition and reconstruction module. +""" + +from ._extensions._pywt import * +from ._functions import * +from ._multilevel import * +from ._multidim import * +from ._thresholding import * +from ._wavelet_packets import * +from ._dwt import * +from ._swt import * +from ._cwt import * +from ._mra import * + +from . import data + +__all__ = [s for s in dir() if not s.startswith('_')] +try: + # In Python 2.x the name of the tempvar leaks out of the list + # comprehension. Delete it to not make it show up in the main namespace. + del s +except NameError: + pass + +from pywt.version import version as __version__ + +from ._pytesttester import PytestTester +test = PytestTester(__name__) +del PytestTester diff --git a/.venv/lib/python3.12/site-packages/pywt/_cwt.py b/.venv/lib/python3.12/site-packages/pywt/_cwt.py new file mode 100644 index 0000000000000000000000000000000000000000..2e52fea61934e96dba29ed856dde2702dbcb4c26 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/pywt/_cwt.py @@ -0,0 +1,231 @@ +from math import ceil, floor + +from ._extensions._pywt import ( + ContinuousWavelet, + DiscreteContinuousWavelet, + Wavelet, + _check_dtype, +) +from ._functions import integrate_wavelet, scale2frequency +from ._utils import AxisError + +__all__ = ["cwt"] + + +import numpy as np + + +def next_fast_len(n): + """Round up size to the nearest power of two. + + Given a number of samples `n`, returns the next power of two + following this number to take advantage of FFT speedup. + """ + return 2**ceil(np.log2(n)) + + +def cwt(data, scales, wavelet, sampling_period=1., method='conv', axis=-1, + *, precision=12): + """ + One dimensional Continuous Wavelet Transform. + + Parameters + ---------- + data : array_like + Input signal + scales : array_like + The wavelet scales to use. One can use + ``f = scale2frequency(wavelet, scale)/sampling_period`` to determine + what physical frequency, ``f``. Here, ``f`` is in hertz when the + ``sampling_period`` is given in seconds. + wavelet : Wavelet object or name + Wavelet to use + sampling_period : float + Sampling period for the frequencies output (optional). + The values computed for ``coefs`` are independent of the choice of + ``sampling_period`` (i.e. ``scales`` is not scaled by the sampling + period). + method : {'conv', 'fft'}, optional + The method used to compute the CWT. Can be any of: + - ``conv`` uses ``numpy.convolve``. + - ``fft`` uses frequency domain convolution. + - ``auto`` uses automatic selection based on an estimate of the + computational complexity at each scale. + + The ``conv`` method complexity is ``O(len(scale) * len(data))``. + The ``fft`` method is ``O(N * log2(N))`` with + ``N = len(scale) + len(data) - 1``. It is well suited for large size + signals but slightly slower than ``conv`` on small ones. + axis: int, optional + Axis over which to compute the CWT. If not given, the last axis is + used. + precision: int, optional + Length of wavelet (``2 ** precision``) used to compute the CWT. Greater + will increase resolution, especially for higher scales, but will + compute a bit slower. Too low will distort coefficients and their + norms, with a zipper-like effect. The default is 12, it's recommended + to use >=12. + + Returns + ------- + coefs : array_like + Continuous wavelet transform of the input signal for the given scales + and wavelet. The first axis of ``coefs`` corresponds to the scales. + The remaining axes match the shape of ``data``. + frequencies : array_like + If the unit of sampling period are seconds and given, then frequencies + are in hertz. Otherwise, a sampling period of 1 is assumed. + + Notes + ----- + Size of coefficients arrays depends on the length of the input array and + the length of given scales. + + The transform is computed entirely in units of samples. With the scale + ``a`` and the translation ``b`` both expressed in samples, the returned + coefficients are:: + + C[a, b] = 1/sqrt(a) * sum_n data[n] * conj(psi((n - b)/a)) + + No sampling interval enters this expression, which is why ``coefs`` does + not depend on ``sampling_period``. To express the coefficients in + physical-time units instead, multiply them by ``sqrt(dt)`` (equivalently, + divide by ``sqrt(fs)``); that factor comes from approximating the integral + of the continuous-time transform by a Riemann sum. See the + :ref:`CWT normalization` section of the documentation for details. + + Examples + -------- + >>> import pywt + >>> import numpy as np + >>> import matplotlib.pyplot as plt + >>> x = np.exp(np.linspace(0, 2, 512)) + >>> y = np.cos(2*np.pi*x) # exponential chirp + >>> scales = np.logspace(np.log10(1), np.log10(128), 128) + >>> coef, freqs = pywt.cwt(y, scales, 'gaus1') + >>> plt.matshow(coef) + >>> plt.show() + + >>> import pywt + >>> import numpy as np + >>> import matplotlib.pyplot as plt + >>> t = np.linspace(-1, 1, 200, endpoint=False) + >>> sig = np.cos(2 * np.pi * 7 * t) + np.real(np.exp(-7*(t-0.4)**2)*np.exp(1j*2*np.pi*2*(t-0.4))) + >>> widths = np.logspace(np.log10(1), np.log10(30), 30) + >>> cwtmatr, freqs = pywt.cwt(sig, widths, 'mexh') + >>> plt.imshow(cwtmatr, extent=[-1, 1, 1, 31], cmap='PRGn', aspect='auto', + ... vmax=abs(cwtmatr).max(), vmin=-abs(cwtmatr).max()) + >>> plt.show() + """ + + # accept array-like input; make a copy to ensure a contiguous array + dt = _check_dtype(data) + data = np.asarray(data, dtype=dt) + dt_cplx = np.result_type(dt, np.complex64) + if not isinstance(wavelet, (ContinuousWavelet, Wavelet)): + wavelet = DiscreteContinuousWavelet(wavelet) + if not isinstance(wavelet, ContinuousWavelet): + raise ValueError( + f"cwt() requires a continuous wavelet, but {wavelet.name!r} is a " + f"discrete wavelet. Use a continuous wavelet such as those returned " + f"by pywt.wavelist(kind='continuous') (e.g. 'morl', 'mexh', 'cmor')." + ) + + scales = np.atleast_1d(scales) + if np.any(scales <= 0): + raise ValueError("`scales` must only include positive values") + + if not np.isscalar(axis): + raise AxisError("axis must be a scalar.") + + dt_out = dt_cplx if wavelet.complex_cwt else dt + out = np.empty((np.size(scales),) + data.shape, dtype=dt_out) + + int_psi, x = integrate_wavelet(wavelet, precision=precision) + int_psi = np.conj(int_psi) if wavelet.complex_cwt else int_psi + + # convert int_psi, x to the same precision as the data + dt_psi = dt_cplx if int_psi.dtype.kind == 'c' else dt + int_psi = np.asarray(int_psi, dtype=dt_psi) + x = np.asarray(x, dtype=data.real.dtype) + + if method == 'fft': + size_scale0 = -1 + fft_data = None + use_real_fft = data.dtype.kind != 'c' and int_psi.dtype.kind != 'c' + elif method != "conv": + raise ValueError("method must be 'conv' or 'fft'") + + if data.ndim > 1: + # move axis to be transformed last (so it is contiguous) + data = data.swapaxes(-1, axis) + + # reshape to (n_batch, data.shape[-1]) + data_shape_pre = data.shape + data = data.reshape((-1, data.shape[-1])) + + for i, scale in enumerate(scales): + step = x[1] - x[0] + j = np.arange(scale * (x[-1] - x[0]) + 1) / (scale * step) + j = j.astype(int) # floor + if j[-1] >= int_psi.size: + j = np.extract(j < int_psi.size, j) + int_psi_scale = int_psi[j][::-1] + + if method == 'conv': + if data.ndim == 1: + conv = np.convolve(data, int_psi_scale) + else: + # batch convolution via loop + conv_shape = list(data.shape) + conv_shape[-1] += int_psi_scale.size - 1 + conv_shape = tuple(conv_shape) + conv = np.empty(conv_shape, dtype=dt_out) + for n in range(data.shape[0]): + conv[n, :] = np.convolve(data[n], int_psi_scale) + else: + # The padding is selected for: + # - optimal FFT complexity + # - to be larger than the two signals length to avoid circular + # convolution + size_scale = next_fast_len( + data.shape[-1] + int_psi_scale.size - 1 + ) + if size_scale != size_scale0: + # Must recompute fft_data when the padding size changes. + if use_real_fft: + fft_data = np.fft.rfft(data, size_scale, axis=-1) + else: + fft_data = np.fft.fft(data, size_scale, axis=-1) + size_scale0 = size_scale + if use_real_fft: + fft_wav = np.fft.rfft(int_psi_scale, size_scale, axis=-1) + conv = np.fft.irfft( + fft_wav * fft_data, n=size_scale, axis=-1 + ) + else: + fft_wav = np.fft.fft(int_psi_scale, size_scale, axis=-1) + conv = np.fft.ifft(fft_wav * fft_data, axis=-1) + conv = conv[..., :data.shape[-1] + int_psi_scale.size - 1] + + coef = - np.sqrt(scale) * np.diff(conv, axis=-1) + if out.dtype.kind != 'c': + coef = coef.real + # transform axis is always -1 due to the data reshape above + d = (coef.shape[-1] - data.shape[-1]) / 2. + if d > 0: + coef = coef[..., floor(d):-ceil(d)] + elif d < 0: + raise ValueError( + f"Selected scale of {scale} too small.") + if data.ndim > 1: + # restore original data shape and axis position + coef = coef.reshape(data_shape_pre) + coef = coef.swapaxes(axis, -1) + out[i, ...] = coef + + frequencies = scale2frequency(wavelet, scales, precision) + if np.isscalar(frequencies): + frequencies = np.array([frequencies]) + frequencies /= sampling_period + return out, frequencies diff --git a/.venv/lib/python3.12/site-packages/pywt/_doc_utils.py b/.venv/lib/python3.12/site-packages/pywt/_doc_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..827d12c99f1289c4f345319030ae9c9ec5bc5ecc --- /dev/null +++ b/.venv/lib/python3.12/site-packages/pywt/_doc_utils.py @@ -0,0 +1,187 @@ +"""Utilities used to generate various figures in the documentation.""" +from itertools import product + +import numpy as np +from matplotlib import pyplot as plt + +from ._dwt import pad + +__all__ = ['wavedec_keys', 'wavedec2_keys', 'draw_2d_wp_basis', + 'draw_2d_fswavedecn_basis', 'boundary_mode_subplot'] + + +def wavedec_keys(level): + """Subband keys corresponding to a wavedec decomposition.""" + approx = '' + coeffs = {} + for lev in range(level): + for k in ['a', 'd']: + coeffs[approx + k] = None + approx = 'a' * (lev + 1) + if lev < level - 1: + coeffs.pop(approx) + return list(coeffs.keys()) + + +def wavedec2_keys(level): + """Subband keys corresponding to a wavedec2 decomposition.""" + approx = '' + coeffs = {} + for lev in range(level): + for k in ['a', 'h', 'v', 'd']: + coeffs[approx + k] = None + approx = 'a' * (lev + 1) + if lev < level - 1: + coeffs.pop(approx) + return list(coeffs.keys()) + + +def _box(bl, ur): + """(x, y) coordinates for the 4 lines making up a rectangular box. + + Parameters + ========== + bl : float + The bottom left corner of the box + ur : float + The upper right corner of the box + + Returns + ======= + coords : 2-tuple + The first and second elements of the tuple are the x and y coordinates + of the box. + """ + xl, xr = bl[0], ur[0] + yb, yt = bl[1], ur[1] + box_x = [xl, xr, + xr, xr, + xr, xl, + xl, xl] + box_y = [yb, yb, + yb, yt, + yt, yt, + yt, yb] + return (box_x, box_y) + + +def _2d_wp_basis_coords(shape, keys): + # Coordinates of the lines to be drawn by draw_2d_wp_basis + coords = [] + centers = {} # retain center of boxes for use in labeling + for key in keys: + offset_x = offset_y = 0 + for n, char in enumerate(key): + if char in ['h', 'd']: + offset_x += shape[0] // 2**(n + 1) + if char in ['v', 'd']: + offset_y += shape[1] // 2**(n + 1) + sx = shape[0] // 2**(n + 1) + sy = shape[1] // 2**(n + 1) + xc, yc = _box((offset_x, -offset_y), + (offset_x + sx, -offset_y - sy)) + coords.append((xc, yc)) + centers[key] = (offset_x + sx // 2, -offset_y - sy // 2) + return coords, centers + + +def draw_2d_wp_basis(shape, keys, fmt='k', plot_kwargs={}, ax=None, + label_levels=0): + """Plot a 2D representation of a WaveletPacket2D basis.""" + coords, centers = _2d_wp_basis_coords(shape, keys) + if ax is None: + fig, ax = plt.subplots(1, 1) + else: + fig = ax.get_figure() + for coord in coords: + ax.plot(coord[0], coord[1], fmt) + ax.set_axis_off() + ax.axis('square') + if label_levels > 0: + for key, c in centers.items(): + if len(key) <= label_levels: + ax.text(c[0], c[1], key, + horizontalalignment='center', + verticalalignment='center') + return fig, ax + + +def _2d_fswavedecn_coords(shape, levels): + coords = [] + centers = {} # retain center of boxes for use in labeling + for key in product(wavedec_keys(levels), repeat=2): + (key0, key1) = key + offsets = [0, 0] + widths = list(shape) + for n0, char in enumerate(key0): + if char in ['d']: + offsets[0] += shape[0] // 2**(n0 + 1) + for n1, char in enumerate(key1): + if char in ['d']: + offsets[1] += shape[1] // 2**(n1 + 1) + widths[0] = shape[0] // 2**(n0 + 1) + widths[1] = shape[1] // 2**(n1 + 1) + xc, yc = _box((offsets[0], -offsets[1]), + (offsets[0] + widths[0], -offsets[1] - widths[1])) + coords.append((xc, yc)) + centers[(key0, key1)] = (offsets[0] + widths[0] / 2, + -offsets[1] - widths[1] / 2) + return coords, centers + + +def draw_2d_fswavedecn_basis(shape, levels, fmt='k', plot_kwargs={}, ax=None, + label_levels=0): + """Plot a 2D representation of a WaveletPacket2D basis.""" + coords, centers = _2d_fswavedecn_coords(shape, levels) + if ax is None: + fig, ax = plt.subplots(1, 1) + else: + fig = ax.get_figure() + for coord in coords: + ax.plot(coord[0], coord[1], fmt) + ax.set_axis_off() + ax.axis('square') + if label_levels > 0: + for key, c in centers.items(): + lev = np.max([len(k) for k in key]) + if lev <= label_levels: + ax.text(c[0], c[1], key, + horizontalalignment='center', + verticalalignment='center') + return fig, ax + + +def boundary_mode_subplot(x, mode, ax, symw=True): + """Plot an illustration of the boundary mode in a subplot axis.""" + + # if odd-length, periodization replicates the last sample to make it even + if mode == 'periodization' and len(x) % 2 == 1: + x = np.concatenate((x, (x[-1], ))) + + npad = 2 * len(x) + t = np.arange(len(x) + 2 * npad) + xp = pad(x, (npad, npad), mode=mode) + + ax.plot(t, xp, 'k.') + ax.set_title(mode) + + # plot the original signal in red + if mode == 'periodization': + ax.plot(t[npad:npad + len(x) - 1], x[:-1], 'r.') + else: + ax.plot(t[npad:npad + len(x)], x, 'r.') + + # add vertical bars indicating points of symmetry or boundary extension + o2 = np.ones(2) + left = npad + if symw: + step = len(x) - 1 + rng = range(-2, 4) + else: + left -= 0.5 + step = len(x) + rng = range(-2, 4) + if mode in ['smooth', 'constant', 'zero']: + rng = range(2) + for rep in rng: + ax.plot((left + rep * step) * o2, [xp.min() - .5, xp.max() + .5], 'k-') diff --git a/.venv/lib/python3.12/site-packages/pywt/_dwt.py b/.venv/lib/python3.12/site-packages/pywt/_dwt.py new file mode 100644 index 0000000000000000000000000000000000000000..151b8787643719951c3acc5197f08f4fdd8c3e56 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/pywt/_dwt.py @@ -0,0 +1,509 @@ +from numbers import Number + +import numpy as np + +from ._extensions._dwt import downcoef as _downcoef +from ._extensions._dwt import dwt_axis, dwt_single, idwt_axis, idwt_single +from ._extensions._dwt import dwt_coeff_len as _dwt_coeff_len +from ._extensions._dwt import dwt_max_level as _dwt_max_level +from ._extensions._dwt import upcoef as _upcoef +from ._extensions._pywt import Modes, Wavelet, _check_dtype, wavelist +from ._utils import AxisError, _as_wavelet + +__all__ = ["dwt", "idwt", "downcoef", "upcoef", "dwt_max_level", + "dwt_coeff_len", "pad"] + + +def dwt_max_level(data_len, filter_len): + r""" + dwt_max_level(data_len, filter_len) + + Compute the maximum useful level of decomposition. + + Parameters + ---------- + data_len : int + Input data length. + filter_len : int, str or Wavelet + The wavelet filter length. Alternatively, the name of a discrete + wavelet or a Wavelet object can be specified. + + Returns + ------- + max_level : int + Maximum level. + + Notes + ----- + The rational for the choice of levels is the maximum level where at least + one coefficient in the output is uncorrupted by edge effects caused by + signal extension. Put another way, decomposition stops when the signal + becomes shorter than the FIR filter length for a given wavelet. This + corresponds to: + + .. max_level = floor(log2(data_len/(filter_len - 1))) + + .. math:: + \mathtt{max\_level} = \left\lfloor\log_2\left(\mathtt{ + \frac{data\_len}{filter\_len - 1}}\right)\right\rfloor + + Examples + -------- + >>> import pywt + >>> w = pywt.Wavelet('sym5') + >>> pywt.dwt_max_level(data_len=1000, filter_len=w.dec_len) + 6 + >>> pywt.dwt_max_level(1000, w) + 6 + >>> pywt.dwt_max_level(1000, 'sym5') + 6 + """ + if isinstance(filter_len, Wavelet): + filter_len = filter_len.dec_len + elif isinstance(filter_len, str): + if filter_len in wavelist(kind='discrete'): + filter_len = Wavelet(filter_len).dec_len + else: + raise ValueError( + f"'{filter_len}', is not a recognized discrete wavelet. A list of " + "supported wavelet names can be obtained via " + "pywt.wavelist(kind='discrete')") + elif not (isinstance(filter_len, Number) and filter_len % 1 == 0): + raise ValueError( + "filter_len must be an integer, discrete Wavelet object, or the " + "name of a discrete wavelet.") + + if filter_len < 2: + raise ValueError("invalid wavelet filter length") + + return _dwt_max_level(data_len, filter_len) + + +def dwt_coeff_len(data_len, filter_len, mode): + """ + dwt_coeff_len(data_len, filter_len, mode='symmetric') + + Returns length of dwt output for given data length, filter length and mode + + Parameters + ---------- + data_len : int + Data length. + filter_len : int + Filter length. + mode : str, optional + Signal extension mode, see :ref:`Modes `. + + Returns + ------- + len : int + Length of dwt output. + + Notes + ----- + For all modes except periodization:: + + len(cA) == len(cD) == floor((len(data) + wavelet.dec_len - 1) / 2) + + for periodization mode ("per"):: + + len(cA) == len(cD) == ceil(len(data) / 2) + + """ + if isinstance(filter_len, Wavelet): + filter_len = filter_len.dec_len + + return _dwt_coeff_len(data_len, filter_len, Modes.from_object(mode)) + + +def dwt(data, wavelet, mode='symmetric', axis=-1): + """ + dwt(data, wavelet, mode='symmetric', axis=-1) + + Single level Discrete Wavelet Transform. + + Parameters + ---------- + data : array_like + Input signal + wavelet : Wavelet object or name + Wavelet to use + mode : str, optional + Signal extension mode, see :ref:`Modes `. + axis: int, optional + Axis over which to compute the DWT. If not given, the + last axis is used. + + Returns + ------- + (cA, cD) : tuple + Approximation and detail coefficients. + + Notes + ----- + Length of coefficients arrays depends on the selected mode. + For all modes except periodization: + + ``len(cA) == len(cD) == floor((len(data) + wavelet.dec_len - 1) / 2)`` + + For periodization mode ("per"): + + ``len(cA) == len(cD) == ceil(len(data) / 2)`` + + Examples + -------- + >>> import pywt + >>> (cA, cD) = pywt.dwt([1, 2, 3, 4, 5, 6], 'db1') + >>> cA + array([ 2.12132034, 4.94974747, 7.77817459]) + >>> cD + array([-0.70710678, -0.70710678, -0.70710678]) + + """ + # accept array_like input; make a copy to ensure a contiguous array + dt = _check_dtype(data) + data = np.asarray(data, dtype=dt, order='C') + mode = Modes.from_object(mode) + wavelet = _as_wavelet(wavelet) + + if axis < 0: + axis = axis + data.ndim + if not 0 <= axis < data.ndim: + raise AxisError("Axis greater than data dimensions") + + if data.ndim == 1: + cA, cD = dwt_single(data, wavelet, mode) + # TODO: Check whether this makes a copy + cA, cD = np.asarray(cA, dt), np.asarray(cD, dt) + else: + cA, cD = dwt_axis(data, wavelet, mode, axis=axis) + + return (cA, cD) + + +def idwt(cA, cD, wavelet, mode='symmetric', axis=-1): + """ + idwt(cA, cD, wavelet, mode='symmetric', axis=-1) + + Single level Inverse Discrete Wavelet Transform. + + Parameters + ---------- + cA : array_like or None + Approximation coefficients. If None, will be set to array of zeros + with same shape as ``cD``. + cD : array_like or None + Detail coefficients. If None, will be set to array of zeros + with same shape as ``cA``. + wavelet : Wavelet object or name + Wavelet to use + mode : str, optional (default: 'symmetric') + Signal extension mode, see :ref:`Modes `. + axis: int, optional + Axis over which to compute the inverse DWT. If not given, the + last axis is used. + + Returns + ------- + rec: array_like + Single level reconstruction of signal from given coefficients. + + Examples + -------- + >>> import pywt + >>> (cA, cD) = pywt.dwt([1,2,3,4,5,6], 'db2', 'smooth') + >>> pywt.idwt(cA, cD, 'db2', 'smooth') + array([ 1., 2., 3., 4., 5., 6.]) + + One of the neat features of ``idwt`` is that one of the ``cA`` and ``cD`` + arguments can be set to None. In that situation the reconstruction will be + performed using only the other one. Mathematically speaking, this is + equivalent to passing a zero-filled array as one of the arguments. + + >>> (cA, cD) = pywt.dwt([1,2,3,4,5,6], 'db2', 'smooth') + >>> A = pywt.idwt(cA, None, 'db2', 'smooth') + >>> D = pywt.idwt(None, cD, 'db2', 'smooth') + >>> A + D + array([ 1., 2., 3., 4., 5., 6.]) + + """ + # TODO: Lots of possible allocations to eliminate (zeros_like, asarray(rec)) + # accept array_like input; make a copy to ensure a contiguous array + + if cA is None and cD is None: + raise ValueError("At least one coefficient parameter must be " + "specified.") + + if cA is not None: + dt = _check_dtype(cA) + cA = np.asarray(cA, dtype=dt, order='C') + if cD is not None: + dt = _check_dtype(cD) + cD = np.asarray(cD, dtype=dt, order='C') + + if cA is not None and cD is not None: + if cA.dtype != cD.dtype: + # need to upcast to common type + if cA.dtype.kind == 'c' or cD.dtype.kind == 'c': + dtype = np.complex128 + else: + dtype = np.float64 + cA = cA.astype(dtype) + cD = cD.astype(dtype) + elif cA is None: + cA = np.zeros_like(cD) + elif cD is None: + cD = np.zeros_like(cA) + + # cA and cD should be same dimension by here + ndim = cA.ndim + + mode = Modes.from_object(mode) + wavelet = _as_wavelet(wavelet) + + if axis < 0: + axis = axis + ndim + if not 0 <= axis < ndim: + raise AxisError("Axis greater than coefficient dimensions") + + if ndim == 1: + rec = idwt_single(cA, cD, wavelet, mode) + else: + rec = idwt_axis(cA, cD, wavelet, mode, axis=axis) + + return rec + + +def downcoef(part, data, wavelet, mode='symmetric', level=1): + """ + downcoef(part, data, wavelet, mode='symmetric', level=1) + + Partial Discrete Wavelet Transform data decomposition. + + Similar to ``pywt.dwt``, but computes only one set of coefficients. + Useful when you need only approximation or only details at the given level. + + Parameters + ---------- + part : str + Coefficients type: + + * 'a' - approximations reconstruction is performed + * 'd' - details reconstruction is performed + + data : array_like + Input signal. + wavelet : Wavelet object or name + Wavelet to use + mode : str, optional + Signal extension mode, see :ref:`Modes `. + level : int, optional + Decomposition level. Default is 1. + + Returns + ------- + coeffs : ndarray + 1-D array of coefficients. + + See Also + -------- + upcoef + + """ + # accept array_like input; make a copy to ensure a contiguous array + dt = _check_dtype(data) + data = np.asarray(data, dtype=dt, order='C') + if data.ndim > 1: + raise ValueError("downcoef only supports 1d data.") + if part not in 'ad': + raise ValueError(f"Argument 1 must be 'a' or 'd', not '{part}'.") + mode = Modes.from_object(mode) + wavelet = _as_wavelet(wavelet) + return np.asarray(_downcoef(part == 'a', data, wavelet, mode, level)) + + +def upcoef(part, coeffs, wavelet, level=1, take=0): + """ + upcoef(part, coeffs, wavelet, level=1, take=0) + + Direct reconstruction from coefficients. + + Parameters + ---------- + part : str + Coefficients type: + * 'a' - approximations reconstruction is performed + * 'd' - details reconstruction is performed + coeffs : array_like + Coefficients array to reconstruct + wavelet : Wavelet object or name + Wavelet to use + level : int, optional + Multilevel reconstruction level. Default is 1. + take : int, optional + Take central part of length equal to 'take' from the result. + Default is 0. + + Returns + ------- + rec : ndarray + 1-D array with reconstructed data from coefficients. + + See Also + -------- + downcoef + + Examples + -------- + >>> import pywt + >>> data = [1,2,3,4,5,6] + >>> (cA, cD) = pywt.dwt(data, 'db2', 'smooth') + >>> pywt.upcoef('a', cA, 'db2') + pywt.upcoef('d', cD, 'db2') + array([-0.25 , -0.4330127 , 1. , 2. , 3. , + 4. , 5. , 6. , 1.78589838, -1.03108891]) + >>> n = len(data) + >>> pywt.upcoef('a', cA, 'db2', take=n) + pywt.upcoef('d', cD, 'db2', take=n) + array([ 1., 2., 3., 4., 5., 6.]) + + """ + # accept array_like input; make a copy to ensure a contiguous array + dt = _check_dtype(coeffs) + coeffs = np.asarray(coeffs, dtype=dt, order='C') + if coeffs.ndim > 1: + raise ValueError("upcoef only supports 1d coeffs.") + wavelet = _as_wavelet(wavelet) + if part not in 'ad': + raise ValueError(f"Argument 1 must be 'a' or 'd', not '{part}'.") + return np.asarray(_upcoef(part == 'a', coeffs, wavelet, level, take)) + + +def pad(x, pad_widths, mode): + """Extend a 1D signal using a given boundary mode. + + This function operates like :func:`numpy.pad` but supports all signal + extension modes that can be used by PyWavelets discrete wavelet transforms. + + Parameters + ---------- + x : ndarray + The array to pad + pad_widths : {sequence, array_like, int} + Number of values padded to the edges of each axis. + ``((before_1, after_1), … (before_N, after_N))`` unique pad widths for + each axis. ``((before, after),)`` yields same before and after pad for + each axis. ``(pad,)`` or int is a shortcut for + ``before = after = pad width`` for all axes. + mode : str, optional + Signal extension mode, see :ref:`Modes `. + + Returns + ------- + pad : ndarray + Padded array of rank equal to array with shape increased according to + ``pad_widths``. + + Notes + ----- + The performance of padding in dimensions > 1 may be substantially slower + for modes ``'smooth'`` and ``'antisymmetric'`` as these modes are not + supported efficiently by the underlying :func:`numpy.pad` function. + + Note that the behavior of the ``'constant'`` mode here follows the + PyWavelets convention which is different from NumPy (it is equivalent to + ``mode='edge'`` in :func:`numpy.pad`). + """ + x = np.asanyarray(x) + + # process pad_widths exactly as in numpy.pad + pad_widths = np.array(pad_widths) + pad_widths = np.round(pad_widths).astype(np.intp, copy=False) + if pad_widths.min() < 0: + raise ValueError("pad_widths must be >= 0") + pad_widths = np.broadcast_to(pad_widths, (x.ndim, 2)).tolist() + + if mode in ['symmetric', 'reflect']: + xp = np.pad(x, pad_widths, mode=mode) + elif mode in ['periodic', 'periodization']: + if mode == 'periodization': + # Promote odd-sized dimensions to even length by duplicating the + # last value. + edge_pad_widths = [(0, x.shape[ax] % 2) + for ax in range(x.ndim)] + x = np.pad(x, edge_pad_widths, mode='edge') + xp = np.pad(x, pad_widths, mode='wrap') + elif mode == 'zero': + xp = np.pad(x, pad_widths, mode='constant', constant_values=0) + elif mode == 'constant': + xp = np.pad(x, pad_widths, mode='edge') + elif mode == 'smooth': + def pad_smooth(vector, pad_width, iaxis, kwargs): + # Note: indices are measured from the start of the vector so that + # a pad width of 0 gives an empty slice rather than the full one. + iright = vector.size - pad_width[1] - 1 # last unpadded sample + vsize_nonpad = iright + 1 - pad_width[0] + if vsize_nonpad < 2: + # The slope is undefined for a signal shorter than two + # samples, so use constant edge extension instead. This is + # what the transforms do as well (see the MODE_SMOOTH case in + # convolution.template.c). + if vsize_nonpad == 1: + vector[:pad_width[0]] = vector[iright] + vector[iright + 1:] = vector[iright] + return vector + + # smooth extension to left + left = vector[pad_width[0]] + slope_left = (left - vector[pad_width[0] + 1]) + vector[:pad_width[0]] = \ + left + np.arange(pad_width[0], 0, -1) * slope_left + + # smooth extension to right + right = vector[iright] + slope_right = (right - vector[iright - 1]) + vector[iright + 1:] = \ + right + np.arange(1, pad_width[1] + 1) * slope_right + return vector + xp = np.pad(x, pad_widths, pad_smooth) + elif mode == 'antisymmetric': + def pad_antisymmetric(vector, pad_width, iaxis, kwargs): + # implement by flipping portions of symmetric padding + npad_l, npad_r = pad_width + vsize_nonpad = vector.size - npad_l - npad_r + if vsize_nonpad == 0: + # Nothing to reflect. The reflected segments below would have + # zero width, so the loops over them would never terminate. + return vector + # Note: must modify vector in-place + vector[:] = np.pad(vector[npad_l:vector.size - npad_r], + pad_width, mode='symmetric') + vp = vector + r_edge = npad_l + vsize_nonpad - 1 + l_edge = npad_l + # width of each reflected segment + seg_width = vsize_nonpad + # flip reflected segments on the right of the original signal + n = 1 + while r_edge <= vp.size: + segment_slice = slice(r_edge + 1, + min(r_edge + 1 + seg_width, vp.size)) + if n % 2: + vp[segment_slice] *= -1 + r_edge += seg_width + n += 1 + + # flip reflected segments on the left of the original signal + n = 1 + while l_edge >= 0: + segment_slice = slice(max(0, l_edge - seg_width), l_edge) + if n % 2: + vp[segment_slice] *= -1 + l_edge -= seg_width + n += 1 + return vector + xp = np.pad(x, pad_widths, pad_antisymmetric) + elif mode == 'antireflect': + xp = np.pad(x, pad_widths, mode='reflect', reflect_type='odd') + else: + raise ValueError( + f"unsupported mode: {mode}. The supported modes are {Modes.modes}") + return xp diff --git a/.venv/lib/python3.12/site-packages/pywt/_extensions/_cwt.cpython-312-x86_64-linux-gnu.so b/.venv/lib/python3.12/site-packages/pywt/_extensions/_cwt.cpython-312-x86_64-linux-gnu.so new file mode 100644 index 0000000000000000000000000000000000000000..e7255673c62bc375dfcd1507d97596daee3bd041 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/pywt/_extensions/_cwt.cpython-312-x86_64-linux-gnu.so @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:5f266c48d0f9899c38223d8375c3c5acc739c80a96348180bea92d5288e093ea +size 306944 diff --git a/.venv/lib/python3.12/site-packages/pywt/_extensions/_dwt.cpython-312-x86_64-linux-gnu.so b/.venv/lib/python3.12/site-packages/pywt/_extensions/_dwt.cpython-312-x86_64-linux-gnu.so new file mode 100644 index 0000000000000000000000000000000000000000..09e0989c7bff73c6450a42bb7ecef27380b73e37 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/pywt/_extensions/_dwt.cpython-312-x86_64-linux-gnu.so @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:9ae010d95b6d76390595238cdd4e750694eb87e1c431a42cb5d8c0b8df00fa21 +size 546280 diff --git a/.venv/lib/python3.12/site-packages/pywt/_extensions/_pywt.cpython-312-x86_64-linux-gnu.so b/.venv/lib/python3.12/site-packages/pywt/_extensions/_pywt.cpython-312-x86_64-linux-gnu.so new file mode 100644 index 0000000000000000000000000000000000000000..2619f2e1f2b40e7150ff0fad1e1bd1ae5e0cfa03 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/pywt/_extensions/_pywt.cpython-312-x86_64-linux-gnu.so @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:9e7fb838e9fcc32cd4b22e23afe7b7b27afe976fecdfae8dfaea365d5a26032d +size 536848 diff --git a/.venv/lib/python3.12/site-packages/pywt/_extensions/_swt.cpython-312-x86_64-linux-gnu.so b/.venv/lib/python3.12/site-packages/pywt/_extensions/_swt.cpython-312-x86_64-linux-gnu.so new file mode 100644 index 0000000000000000000000000000000000000000..46749fcafe779acbe11e141e88d4c2b46c77c868 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/pywt/_extensions/_swt.cpython-312-x86_64-linux-gnu.so @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:c93e1bc9c6498155584fcf4adf9257792a86d7ede0023f977d5df887f8809b3d +size 479792 diff --git a/.venv/lib/python3.12/site-packages/pywt/_functions.py b/.venv/lib/python3.12/site-packages/pywt/_functions.py new file mode 100644 index 0000000000000000000000000000000000000000..b2826d816d04fe5395b1625657ec45c502e12a20 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/pywt/_functions.py @@ -0,0 +1,263 @@ +# Copyright (c) 2006-2012 Filip Wasilewski +# Copyright (c) 2012-2016 The PyWavelets Developers +# +# See COPYING for license details. + +""" +Other wavelet related functions. +""" + + +import warnings + +import numpy as np +from numpy.fft import fft + +from ._extensions._pywt import ContinuousWavelet, DiscreteContinuousWavelet, Wavelet + +__all__ = ["integrate_wavelet", "central_frequency", + "scale2frequency", "frequency2scale", "qmf", + "orthogonal_filter_bank", + "intwave", "centrfrq", "scal2frq", "orthfilt"] + + +_DEPRECATION_MSG = ("`{old}` has been renamed to `{new}` and will " + "be removed in a future version of pywt.") + + +def _integrate(arr, step): + integral = np.cumsum(arr) + integral *= step + return integral + + +def intwave(*args, **kwargs): + msg = _DEPRECATION_MSG.format(old='intwave', new='integrate_wavelet') + warnings.warn(msg, DeprecationWarning) + return integrate_wavelet(*args, **kwargs) + + +def centrfrq(*args, **kwargs): + msg = _DEPRECATION_MSG.format(old='centrfrq', new='central_frequency') + warnings.warn(msg, DeprecationWarning) + return central_frequency(*args, **kwargs) + + +def scal2frq(*args, **kwargs): + msg = _DEPRECATION_MSG.format(old='scal2frq', new='scale2frequency') + warnings.warn(msg, DeprecationWarning) + return scale2frequency(*args, **kwargs) + + +def orthfilt(*args, **kwargs): + msg = _DEPRECATION_MSG.format(old='orthfilt', new='orthogonal_filter_bank') + warnings.warn(msg, DeprecationWarning) + return orthogonal_filter_bank(*args, **kwargs) + + +def integrate_wavelet(wavelet, precision=8): + """ + Integrate `psi` wavelet function from -Inf to x using the rectangle + integration method. + + Parameters + ---------- + wavelet : Wavelet instance or str + Wavelet to integrate. If a string, should be the name of a wavelet. + precision : int, optional + Precision that will be used for wavelet function + approximation computed with the wavefun(level=precision) + Wavelet's method (default: 8). + + Returns + ------- + [int_psi, x] : + for orthogonal wavelets + [int_psi_d, int_psi_r, x] : + for other wavelets + + + Examples + -------- + >>> from pywt import Wavelet, integrate_wavelet + >>> wavelet1 = Wavelet('db2') + >>> [int_psi, x] = integrate_wavelet(wavelet1, precision=5) + >>> wavelet2 = Wavelet('bior1.3') + >>> [int_psi_d, int_psi_r, x] = integrate_wavelet(wavelet2, precision=5) + + """ + # FIXME: this function should really use scipy.integrate.quad + + if type(wavelet) in (tuple, list): + msg = ("Integration of a general signal is deprecated " + "and will be removed in a future version of pywt.") + warnings.warn(msg, DeprecationWarning) + elif not isinstance(wavelet, (Wavelet, ContinuousWavelet)): + wavelet = DiscreteContinuousWavelet(wavelet) + + if type(wavelet) in (tuple, list): + psi, x = np.asarray(wavelet[0]), np.asarray(wavelet[1]) + step = x[1] - x[0] + return _integrate(psi, step), x + + functions_approximations = wavelet.wavefun(precision) + + if len(functions_approximations) == 2: # continuous wavelet + psi, x = functions_approximations + step = x[1] - x[0] + return _integrate(psi, step), x + + elif len(functions_approximations) == 3: # orthogonal wavelet + phi, psi, x = functions_approximations + step = x[1] - x[0] + return _integrate(psi, step), x + + else: # biorthogonal wavelet + phi_d, psi_d, phi_r, psi_r, x = functions_approximations + step = x[1] - x[0] + return _integrate(psi_d, step), _integrate(psi_r, step), x + + +def central_frequency(wavelet, precision=8): + """ + Computes the central frequency of the `psi` wavelet function. + + Parameters + ---------- + wavelet : Wavelet instance, str or tuple + Wavelet to integrate. If a string, should be the name of a wavelet. + precision : int, optional + Precision that will be used for wavelet function + approximation computed with the wavefun(level=precision) + Wavelet's method (default: 8). + + Returns + ------- + scalar + + """ + + if not isinstance(wavelet, (Wavelet, ContinuousWavelet)): + wavelet = DiscreteContinuousWavelet(wavelet) + + functions_approximations = wavelet.wavefun(precision) + + if len(functions_approximations) == 2: + psi, x = functions_approximations + else: + # (psi, x) for (phi, psi, x) + # (psi_d, x) for (phi_d, psi_d, phi_r, psi_r, x) + psi, x = functions_approximations[1], functions_approximations[-1] + + domain = float(x[-1] - x[0]) + assert domain > 0 + + index = np.argmax(abs(fft(psi)[1:])) + 2 + if index > len(psi) / 2: + index = len(psi) - index + 2 + + return 1.0 / (domain / (index - 1)) + + +def scale2frequency(wavelet, scale, precision=8): + """Convert from CWT "scale" to normalized frequency. + + Parameters + ---------- + wavelet : Wavelet instance or str + Wavelet to integrate. If a string, should be the name of a wavelet. + scale : scalar + The scale of the CWT. + precision : int, optional + Precision that will be used for wavelet function approximation computed + with ``wavelet.wavefun(level=precision)``. Default is 8. + + Returns + ------- + freq : scalar + Frequency normalized to the sampling frequency. In other words, for a + sampling interval of `dt` seconds, the normalized frequency of 1.0 + corresponds to (`1/dt` Hz). + + """ + return central_frequency(wavelet, precision=precision) / scale + +def frequency2scale(wavelet, freq, precision=8): + """Convert from to normalized frequency to CWT "scale". + + Parameters + ---------- + wavelet : Wavelet instance or str + Wavelet to integrate. If a string, should be the name of a wavelet. + freq : scalar + Frequency, normalized so that the sampling frequency corresponds to a + value of 1.0. + precision : int, optional + Precision that will be used for wavelet function approximation computed + with ``wavelet.wavefun(level=precision)``. Default is 8. + + Returns + ------- + scale : scalar + + """ + return central_frequency(wavelet, precision=precision) / freq + +def qmf(filt): + """ + Returns the Quadrature Mirror Filter(QMF). + + The magnitude response of QMF is mirror image about `pi/2` of that of the + input filter. + + Parameters + ---------- + filt : array_like + Input filter for which QMF needs to be computed. + + Returns + ------- + qm_filter : ndarray + Quadrature mirror of the input filter. + + """ + qm_filter = np.array(filt)[::-1] + qm_filter[1::2] = -qm_filter[1::2] + return qm_filter + + +def orthogonal_filter_bank(scaling_filter): + """ + Returns the orthogonal filter bank. + + The orthogonal filter bank consists of the HPFs and LPFs at + decomposition and reconstruction stage for the input scaling filter. + + Parameters + ---------- + scaling_filter : array_like + Input scaling filter (father wavelet). + + Returns + ------- + orth_filt_bank : tuple of 4 ndarrays + The orthogonal filter bank of the input scaling filter in the order : + 1] Decomposition LPF + 2] Decomposition HPF + 3] Reconstruction LPF + 4] Reconstruction HPF + + """ + if not (len(scaling_filter) % 2 == 0): + raise ValueError("`scaling_filter` length has to be even.") + + scaling_filter = np.asarray(scaling_filter, dtype=np.float64) + + rec_lo = np.sqrt(2) * scaling_filter / np.sum(scaling_filter) + dec_lo = rec_lo[::-1] + + rec_hi = qmf(rec_lo) + dec_hi = rec_hi[::-1] + + orth_filt_bank = (dec_lo, dec_hi, rec_lo, rec_hi) + return orth_filt_bank diff --git a/.venv/lib/python3.12/site-packages/pywt/_mra.py b/.venv/lib/python3.12/site-packages/pywt/_mra.py new file mode 100644 index 0000000000000000000000000000000000000000..a41431e349cc03862404c4b7f130c48638b3d5b0 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/pywt/_mra.py @@ -0,0 +1,434 @@ +from functools import partial, reduce + +import numpy as np + +from ._multilevel import ( + _prep_axes_wavedecn, + wavedec, + wavedec2, + wavedecn, + waverec, + waverec2, + waverecn, +) +from ._swt import iswt, iswt2, iswtn, swt, swt2, swt_max_level, swtn +from ._utils import _modes_per_axis, _wavelets_per_axis + +__all__ = ["mra", "mra2", "mran", "imra", "imra2", "imran"] + + +def mra(data, wavelet, level=None, axis=-1, transform='swt', + mode='periodization'): + """Forward 1D multiresolution analysis. + + It is a projection onto the wavelet subspaces. + + Parameters + ---------- + data: array_like + Input data + wavelet : Wavelet object or name string + Wavelet to use + level : int, optional + Decomposition level (must be >= 0). If level is None (default) then it + will be calculated using the `dwt_max_level` function. + axis: int, optional + Axis over which to compute the DWT. If not given, the last axis is + used. Currently only available when ``transform='dwt'``. + transform : {'dwt', 'swt'} + Whether to use the DWT or SWT for the transforms. + mode : str, optional + Signal extension mode, see `Modes` (default: 'symmetric'). This option + is only used when transform='dwt'. + + Returns + ------- + [cAn, {details_level_n}, ... {details_level_1}] : list + For more information, see the detailed description in `wavedec` + + See Also + -------- + imra, swt + + Notes + ----- + This is sometimes referred to as an additive decomposition because the + inverse transform (``imra``) is just the sum of the coefficient arrays + [1]_. The decomposition using ``transform='dwt'`` corresponds to section + 2.2 while that using an undecimated transform (``transform='swt'``) is + described in section 3.2 and appendix A. + + This transform does not share the variance partition property of ``swt`` + with `norm=True`. It does however, result in coefficients that are + temporally aligned regardless of the symmetry of the wavelet used. + + The redundancy of this transform is ``(level + 1)``. + + References + ---------- + .. [1] Donald B. Percival and Harold O. Mofjeld. Analysis of Subtidal + Coastal Sea Level Fluctuations Using Wavelets. Journal of the American + Statistical Association Vol. 92, No. 439 (Sep., 1997), pp. 868-880. + https://doi.org/10.2307/2965551 + + """ + if transform == 'swt': + if mode != 'periodization': + raise ValueError( + "transform swt only supports mode='periodization'") + kwargs = {"wavelet": wavelet, "axis": axis, "norm": True} + forward = partial(swt, level=level, trim_approx=True, **kwargs) + inverse = partial(iswt, **kwargs) + is_swt = True + elif transform == 'dwt': + kwargs = {"wavelet": wavelet, "mode": mode, "axis": axis} + forward = partial(wavedec, level=level, **kwargs) + inverse = partial(waverec, **kwargs) + is_swt = False + else: + raise ValueError(f"unrecognized transform: {transform}") + + wav_coeffs = forward(data) + + mra_coeffs = [] + nc = len(wav_coeffs) + + if is_swt: + # replicate same zeros array to save memory + z = np.zeros_like(wav_coeffs[0]) + tmp = [z, ] * nc + else: + # zero arrays have variable size in DWT case + tmp = [np.zeros_like(c) for c in wav_coeffs] + + for j in range(nc): + # tmp has arrays of zeros except for the jth entry + tmp[j] = wav_coeffs[j] + + # reconstruct + rec = inverse(tmp) + if rec.shape != data.shape: + # trim any excess coefficients + rec = rec[tuple([slice(sz) for sz in data.shape])] + mra_coeffs.append(rec) + + # restore zeros + if is_swt: + tmp[j] = z + else: + tmp[j] = np.zeros_like(tmp[j]) + return mra_coeffs + + +def imra(mra_coeffs): + """Inverse 1D multiresolution analysis via summation. + + Parameters + ---------- + mra_coeffs : list of ndarray + Multiresolution analysis coefficients as returned by `mra`. + + Returns + ------- + rec : ndarray + The reconstructed signal. + + See Also + -------- + mra + + References + ---------- + .. [1] Donald B. Percival and Harold O. Mofjeld. Analysis of Subtidal + Coastal Sea Level Fluctuations Using Wavelets. Journal of the American + Statistical Association Vol. 92, No. 439 (Sep., 1997), pp. 868-880. + https://doi.org/10.2307/2965551 + """ + return reduce(lambda x, y: x + y, mra_coeffs) + + +def mra2(data, wavelet, level=None, axes=(-2, -1), transform='swt2', + mode='periodization'): + """Forward 2D multiresolution analysis. + + It is a projection onto wavelet subspaces. + + Parameters + ---------- + data: array_like + Input data + wavelet : Wavelet object or name string, or 2-tuple of wavelets + Wavelet to use. This can also be a tuple containing a wavelet to + apply along each axis in `axes`. + level : int, optional + Decomposition level (must be >= 0). If level is None (default) then it + will be calculated using the `dwt_max_level` function. + axes : 2-tuple of ints, optional + Axes over which to compute the DWT. Repeated elements are not allowed. + Currently only available when ``transform='dwt2'``. + transform : {'dwt2', 'swt2'} + Whether to use the DWT or SWT for the transforms. + mode : str or 2-tuple of str, optional + Signal extension mode, see `Modes` (default: 'symmetric'). This option + is only used when transform='dwt2'. + + Returns + ------- + coeffs : list + For more information, see the detailed description in `wavedec2` + + Notes + ----- + This is sometimes referred to as an additive decomposition because the + inverse transform (``imra2``) is just the sum of the coefficient arrays + [1]_. The decomposition using ``transform='dwt'`` corresponds to section + 2.2 while that using an undecimated transform (``transform='swt'``) is + described in section 3.2 and appendix A. + + This transform does not share the variance partition property of ``swt2`` + with `norm=True`. It does however, result in coefficients that are + temporally aligned regardless of the symmetry of the wavelet used. + + The redundancy of this transform is ``3 * level + 1``. + + See Also + -------- + imra2, swt2 + + References + ---------- + .. [1] Donald B. Percival and Harold O. Mofjeld. Analysis of Subtidal + Coastal Sea Level Fluctuations Using Wavelets. Journal of the American + Statistical Association Vol. 92, No. 439 (Sep., 1997), pp. 868-880. + https://doi.org/10.2307/2965551 + """ + if transform == 'swt2': + if mode != 'periodization': + raise ValueError( + "transform swt only supports mode='periodization'") + if level is None: + level = min(swt_max_level(s) for s in data.shape) + kwargs = {"wavelet": wavelet, "axes": axes, "norm": True} + forward = partial(swt2, level=level, trim_approx=True, **kwargs) + inverse = partial(iswt2, **kwargs) + elif transform == 'dwt2': + kwargs = {"wavelet": wavelet, "mode": mode, "axes": axes} + forward = partial(wavedec2, level=level, **kwargs) + inverse = partial(waverec2, **kwargs) + else: + raise ValueError(f"unrecognized transform: {transform}") + + wav_coeffs = forward(data) + + mra_coeffs = [] + nc = len(wav_coeffs) + z = np.zeros_like(wav_coeffs[0]) + tmp = [z] + for j in range(1, nc): + tmp.append([np.zeros_like(c) for c in wav_coeffs[j]]) + + # tmp has arrays of zeros except for the jth entry + tmp[0] = wav_coeffs[0] + # reconstruct + rec = inverse(tmp) + if rec.shape != data.shape: + # trim any excess coefficients + rec = rec[tuple([slice(sz) for sz in data.shape])] + mra_coeffs.append(rec) + # restore zeros + tmp[0] = z + + for j in range(1, nc): + dcoeffs = [] + for n in range(3): + # tmp has arrays of zeros except for the jth entry + z = tmp[j][n] + tmp[j][n] = wav_coeffs[j][n] + # reconstruct + rec = inverse(tmp) + if rec.shape != data.shape: + # trim any excess coefficients + rec = rec[tuple([slice(sz) for sz in data.shape])] + dcoeffs.append(rec) + # restore zeros + tmp[j][n] = z + mra_coeffs.append(tuple(dcoeffs)) + return mra_coeffs + + +def imra2(mra_coeffs): + """Inverse 2D multiresolution analysis via summation. + + Parameters + ---------- + mra_coeffs : list + Multiresolution analysis coefficients as returned by `mra2`. + + Returns + ------- + rec : ndarray + The reconstructed signal. + + See Also + -------- + mra2 + + References + ---------- + .. [1] Donald B. Percival and Harold O. Mofjeld. Analysis of Subtidal + Coastal Sea Level Fluctuations Using Wavelets. Journal of the American + Statistical Association Vol. 92, No. 439 (Sep., 1997), pp. 868-880. + https://doi.org/10.2307/2965551 + """ + rec = mra_coeffs[0] + for j in range(1, len(mra_coeffs)): + for n in range(3): + rec += mra_coeffs[j][n] + return rec + + +def mran(data, wavelet, level=None, axes=None, transform='swtn', + mode='periodization'): + """Forward nD multiresolution analysis. + + It is a projection onto the wavelet subspaces. + + Parameters + ---------- + data: array_like + Input data + wavelet : Wavelet object or name string, or tuple of wavelets + Wavelet to use. This can also be a tuple containing a wavelet to + apply along each axis in `axes`. + level : int, optional + Decomposition level (must be >= 0). If level is None (default) then it + will be calculated using the `dwt_max_level` function. + axes : tuple of ints, optional + Axes over which to compute the DWT. Repeated elements are not allowed. + transform : {'dwtn', 'swtn'} + Whether to use the DWT or SWT for the transforms. + mode : str or tuple of str, optional + Signal extension mode, see `Modes` (default: 'symmetric'). This option + is only used when transform='dwtn'. + + Returns + ------- + coeffs : list + For more information, see the detailed description in `wavedecn`. + + See Also + -------- + imran, swtn + + Notes + ----- + This is sometimes referred to as an additive decomposition because the + inverse transform (``imran``) is just the sum of the coefficient arrays + [1]_. The decomposition using ``transform='dwt'`` corresponds to section + 2.2 while that using an undecimated transform (``transform='swt'``) is + described in section 3.2 and appendix A. + + This transform does not share the variance partition property of ``swtn`` + with `norm=True`. It does however, result in coefficients that are + temporally aligned regardless of the symmetry of the wavelet used. + + The redundancy of this transform is ``(2**n - 1) * level + 1`` where ``n`` + corresponds to the number of axes transformed. + + References + ---------- + .. [1] Donald B. Percival and Harold O. Mofjeld. Analysis of Subtidal + Coastal Sea Level Fluctuations Using Wavelets. Journal of the American + Statistical Association Vol. 92, No. 439 (Sep., 1997), pp. 868-880. + https://doi.org/10.2307/2965551 + """ + axes, axes_shapes, ndim_transform = _prep_axes_wavedecn(data.shape, axes) + wavelets = _wavelets_per_axis(wavelet, axes) + + if transform == 'swtn': + if mode != 'periodization': + raise ValueError( + "transform swt only supports mode='periodization'") + if level is None: + level = min(swt_max_level(s) for s in data.shape) + kwargs = {"wavelet": wavelets, "axes": axes, "norm": True} + forward = partial(swtn, level=level, trim_approx=True, **kwargs) + inverse = partial(iswtn, **kwargs) + elif transform == 'dwtn': + modes = _modes_per_axis(mode, axes) + kwargs = {"wavelet": wavelets, "mode": modes, "axes": axes} + forward = partial(wavedecn, level=level, **kwargs) + inverse = partial(waverecn, **kwargs) + else: + raise ValueError(f"unrecognized transform: {transform}") + + wav_coeffs = forward(data) + + mra_coeffs = [] + nc = len(wav_coeffs) + z = np.zeros_like(wav_coeffs[0]) + tmp = [z] + for j in range(1, nc): + tmp.append({k: np.zeros_like(v) for k, v in wav_coeffs[j].items()}) + + # tmp has arrays of zeros except for the jth entry + tmp[0] = wav_coeffs[0] + # reconstruct + rec = inverse(tmp) + if rec.shape != data.shape: + # trim any excess coefficients + rec = rec[tuple([slice(sz) for sz in data.shape])] + mra_coeffs.append(rec) + # restore zeros + tmp[0] = z + + for j in range(1, nc): + dcoeffs = {} + dkeys = list(wav_coeffs[j].keys()) + for k in dkeys: + # tmp has arrays of zeros except for the jth entry + z = tmp[j][k] + tmp[j][k] = wav_coeffs[j][k] + # tmp[j]['a' * len(k)] = z + # reconstruct + rec = inverse(tmp) + if rec.shape != data.shape: + # trim any excess coefficients + rec = rec[tuple([slice(sz) for sz in data.shape])] + dcoeffs[k] = rec + # restore zeros + tmp[j][k] = z + # tmp[j].pop('a' * len(k)) + mra_coeffs.append(dcoeffs) + return mra_coeffs + + +def imran(mra_coeffs): + """Inverse nD multiresolution analysis via summation. + + Parameters + ---------- + mra_coeffs : list + Multiresolution analysis coefficients as returned by `mra2`. + + Returns + ------- + rec : ndarray + The reconstructed signal. + + See Also + -------- + mran + + References + ---------- + .. [1] Donald B. Percival and Harold O. Mofjeld. Analysis of Subtidal + Coastal Sea Level Fluctuations Using Wavelets. Journal of the American + Statistical Association Vol. 92, No. 439 (Sep., 1997), pp. 868-880. + https://doi.org/10.2307/2965551 + """ + rec = mra_coeffs[0] + for j in range(1, len(mra_coeffs)): + for k, v in mra_coeffs[j].items(): + rec += v + return rec diff --git a/.venv/lib/python3.12/site-packages/pywt/_multidim.py b/.venv/lib/python3.12/site-packages/pywt/_multidim.py new file mode 100644 index 0000000000000000000000000000000000000000..361c2cf250bda2a19aa1e964446e0eb0fb582e3e --- /dev/null +++ b/.venv/lib/python3.12/site-packages/pywt/_multidim.py @@ -0,0 +1,300 @@ +# Copyright (c) 2006-2012 Filip Wasilewski +# Copyright (c) 2012-2016 The PyWavelets Developers +# +# See COPYING for license details. + +""" +2D and nD Discrete Wavelet Transforms and Inverse Discrete Wavelet Transforms. +""" + + +from itertools import product + +import numpy as np + +from ._extensions._dwt import dwt_axis, idwt_axis +from ._utils import AxisError, _modes_per_axis, _wavelets_per_axis + +__all__ = ['dwt2', 'idwt2', 'dwtn', 'idwtn'] + + +def dwt2(data, wavelet, mode='symmetric', axes=(-2, -1)): + """ + 2D Discrete Wavelet Transform. + + Parameters + ---------- + data : array_like + 2D array with input data + wavelet : Wavelet object or name string, or 2-tuple of wavelets + Wavelet to use. This can also be a tuple containing a wavelet to + apply along each axis in ``axes``. + mode : str or 2-tuple of strings, optional + Signal extension mode, see :ref:`Modes `. This can + also be a tuple of modes specifying the mode to use on each axis in + ``axes``. + axes : 2-tuple of ints, optional + Axes over which to compute the DWT. Repeated elements mean the DWT will + be performed multiple times along these axes. + + Returns + ------- + (cA, (cH, cV, cD)) : tuple + Approximation, horizontal detail, vertical detail and diagonal + detail coefficients respectively. Horizontal refers to array axis 0 + (or ``axes[0]`` for user-specified ``axes``). + + Examples + -------- + >>> import numpy as np + >>> import pywt + >>> data = np.ones((4,4), dtype=np.float64) + >>> coeffs = pywt.dwt2(data, 'haar') + >>> cA, (cH, cV, cD) = coeffs + >>> cA + array([[ 2., 2.], + [ 2., 2.]]) + >>> cV + array([[ 0., 0.], + [ 0., 0.]]) + + """ + axes = tuple(axes) + data = np.asarray(data) + if len(axes) != 2: + raise ValueError("Expected 2 axes") + if data.ndim < len(np.unique(axes)): + raise ValueError("Input array has fewer dimensions than the specified " + "axes") + + coefs = dwtn(data, wavelet, mode, axes) + return coefs['aa'], (coefs['da'], coefs['ad'], coefs['dd']) + + +def idwt2(coeffs, wavelet, mode='symmetric', axes=(-2, -1)): + """ + 2-D Inverse Discrete Wavelet Transform. + + Reconstructs data from coefficient arrays. + + Parameters + ---------- + coeffs : tuple + (cA, (cH, cV, cD)) A tuple with approximation coefficients and three + details coefficients 2D arrays like from ``dwt2``. If any of these + components are set to ``None``, it will be treated as zeros. + wavelet : Wavelet object or name string, or 2-tuple of wavelets + Wavelet to use. This can also be a tuple containing a wavelet to + apply along each axis in ``axes``. + mode : str or 2-tuple of strings, optional + Signal extension mode, see :ref:`Modes `. This can + also be a tuple of modes specifying the mode to use on each axis in + ``axes``. + axes : 2-tuple of ints, optional + Axes over which to compute the IDWT. Repeated elements mean the IDWT + will be performed multiple times along these axes. + + Examples + -------- + >>> import numpy as np + >>> import pywt + >>> data = np.array([[1,2], [3,4]], dtype=np.float64) + >>> coeffs = pywt.dwt2(data, 'haar') + >>> pywt.idwt2(coeffs, 'haar') + array([[ 1., 2.], + [ 3., 4.]]) + + """ + # L -low-pass data, H - high-pass data + LL, (HL, LH, HH) = coeffs + axes = tuple(axes) + if len(axes) != 2: + raise ValueError("Expected 2 axes") + + coeffs = {'aa': LL, 'da': HL, 'ad': LH, 'dd': HH} + return idwtn(coeffs, wavelet, mode, axes) + + +def dwtn(data, wavelet, mode='symmetric', axes=None): + """ + Single-level n-dimensional Discrete Wavelet Transform. + + Parameters + ---------- + data : array_like + n-dimensional array with input data. + wavelet : Wavelet object or name string, or tuple of wavelets + Wavelet to use. This can also be a tuple containing a wavelet to + apply along each axis in ``axes``. + mode : str or tuple of string, optional + Signal extension mode used in the decomposition, + see :ref:`Modes `. This can also be a tuple of modes + specifying the mode to use on each axis in ``axes``. + axes : sequence of ints, optional + Axes over which to compute the DWT. Repeated elements mean the DWT will + be performed multiple times along these axes. A value of ``None`` (the + default) selects all axes. + + Axes may be repeated, but information about the original size may be + lost if it is not divisible by ``2 ** nrepeats``. The reconstruction + will be larger, with additional values derived according to the + ``mode`` parameter. ``pywt.wavedecn`` should be used for multilevel + decomposition. + + Returns + ------- + coeffs : dict + Results are arranged in a dictionary, where key specifies + the transform type on each dimension and value is a n-dimensional + coefficients array. + + For example, for a 2D case the result will look something like this:: + + {'aa': # A(LL) - approx. on 1st dim, approx. on 2nd dim + 'ad': # V(LH) - approx. on 1st dim, det. on 2nd dim + 'da': # H(HL) - det. on 1st dim, approx. on 2nd dim + 'dd': # D(HH) - det. on 1st dim, det. on 2nd dim + } + + For user-specified ``axes``, the order of the characters in the + dictionary keys map to the specified ``axes``. + + """ + data = np.asarray(data) + + if data.dtype == np.dtype('object'): + raise TypeError("Input must be a numeric array-like") + if data.ndim < 1: + raise ValueError("Input data must be at least 1D") + + if axes is None: + axes = range(data.ndim) + axes = [a + data.ndim if a < 0 else a for a in axes] + + modes = _modes_per_axis(mode, axes) + wavelets = _wavelets_per_axis(wavelet, axes) + + coeffs = [('', data)] + for axis, wav, mode in zip(axes, wavelets, modes): + new_coeffs = [] + for subband, x in coeffs: + cA, cD = dwt_axis(x, wav, mode, axis) + new_coeffs.extend([(subband + 'a', cA), + (subband + 'd', cD)]) + coeffs = new_coeffs + return dict(coeffs) + + +def _fix_coeffs(coeffs): + missing_keys = [k for k, v in coeffs.items() if v is None] + if missing_keys: + raise ValueError( + "The following detail coefficients were set to None:\n" + f"{missing_keys}\n" + "For multilevel transforms, rather than setting\n" + "\tcoeffs[key] = None\n" + "use\n" + "\tcoeffs[key] = np.zeros_like(coeffs[key])\n") + + invalid_keys = [k for k, v in coeffs.items() if + not set(k) <= set('ad')] + if invalid_keys: + raise ValueError( + "The following invalid keys were found in the detail " + f"coefficient dictionary: {invalid_keys}.") + + key_lengths = [len(k) for k in coeffs] + if len(np.unique(key_lengths)) > 1: + raise ValueError( + "All detail coefficient names must have equal length.") + + return {k: np.asarray(v) for k, v in coeffs.items()} + + +def idwtn(coeffs, wavelet, mode='symmetric', axes=None): + """ + Single-level n-dimensional Inverse Discrete Wavelet Transform. + + Parameters + ---------- + coeffs: dict + Dictionary as in output of ``dwtn``. Missing or ``None`` items + will be treated as zeros. + wavelet : Wavelet object or name string, or tuple of wavelets + Wavelet to use. This can also be a tuple containing a wavelet to + apply along each axis in ``axes``. + mode : str or list of string, optional + Signal extension mode used in the decomposition, + see :ref:`Modes `. This can also be a tuple of modes + specifying the mode to use on each axis in ``axes``. + axes : sequence of ints, optional + Axes over which to compute the IDWT. Repeated elements mean the IDWT + will be performed multiple times along these axes. A value of ``None`` + (the default) selects all axes. + + For the most accurate reconstruction, the axes should be provided in + the same order as they were provided to ``dwtn``. + + Returns + ------- + data: ndarray + Original signal reconstructed from input data. + + """ + + # drop the keys corresponding to value = None + coeffs = {k: v for k, v in coeffs.items() if v is not None} + + # drop the keys corresponding to value = None + coeffs = {k: v for k, v in coeffs.items() if v is not None} + + # Raise error for invalid key combinations + coeffs = _fix_coeffs(coeffs) + + + # key length matches the number of axes transformed + ndim_transform = max(len(key) for key in coeffs) + + try: + coeff_shapes = (v.shape for k, v in coeffs.items() + if v is not None and len(k) == ndim_transform) + coeff_shape = next(coeff_shapes) + except StopIteration: + raise ValueError("`coeffs` must contain at least one non-null wavelet " + "band") + if any(s != coeff_shape for s in coeff_shapes): + raise ValueError("`coeffs` must all be of equal size (or None)") + + if axes is None: + axes = range(ndim_transform) + ndim = ndim_transform + else: + ndim = len(coeff_shape) + axes = [a + ndim if a < 0 else a for a in axes] + + modes = _modes_per_axis(mode, axes) + wavelets = _wavelets_per_axis(wavelet, axes) + for key_length, (axis, wav, mode) in reversed( + list(enumerate(zip(axes, wavelets, modes)))): + if axis < 0 or axis >= ndim: + raise AxisError("Axis greater than data dimensions") + + new_coeffs = {} + new_keys = [''.join(coef) for coef in product('ad', repeat=key_length)] + + for key in new_keys: + L = coeffs.get(key + 'a', None) + H = coeffs.get(key + 'd', None) + if L is not None and H is not None: + if L.dtype != H.dtype: + # upcast to a common dtype (float64 or complex128) + if L.dtype.kind == 'c' or H.dtype.kind == 'c': + dtype = np.complex128 + else: + dtype = np.float64 + L = np.asarray(L, dtype=dtype) + H = np.asarray(H, dtype=dtype) + new_coeffs[key] = idwt_axis(L, H, wav, mode, axis) + coeffs = new_coeffs + + return coeffs[''] diff --git a/.venv/lib/python3.12/site-packages/pywt/_multilevel.py b/.venv/lib/python3.12/site-packages/pywt/_multilevel.py new file mode 100644 index 0000000000000000000000000000000000000000..0e5ca9cf142b743a927fcf34c1e50b96852f7175 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/pywt/_multilevel.py @@ -0,0 +1,1562 @@ +# Copyright (c) 2006-2012 Filip Wasilewski +# Copyright (c) 2012-2018 The PyWavelets Developers +# +# See COPYING for license details. + +""" +Multilevel 1D and 2D Discrete Wavelet Transform +and Inverse Discrete Wavelet Transform. +""" + + +import numbers +import warnings +from copy import copy +from itertools import product + +import numpy as np + +from ._dwt import dwt, dwt_coeff_len, idwt +from ._extensions._dwt import dwt_max_level +from ._extensions._pywt import Modes, Wavelet +from ._multidim import _fix_coeffs, dwt2, dwtn, idwt2, idwtn +from ._utils import AxisError, _as_wavelet, _modes_per_axis, _wavelets_per_axis + +__all__ = ['wavedec', 'waverec', 'wavedec2', 'waverec2', 'wavedecn', + 'waverecn', 'coeffs_to_array', 'array_to_coeffs', 'ravel_coeffs', + 'unravel_coeffs', 'dwtn_max_level', 'wavedecn_size', + 'wavedecn_shapes', 'fswavedecn', 'fswaverecn', 'FswavedecnResult'] + + +def _check_level(sizes, dec_lens, level): + if np.isscalar(sizes): + sizes = (sizes, ) + if np.isscalar(dec_lens): + dec_lens = (dec_lens, ) + max_level = np.min([dwt_max_level(s, d) for s, d in zip(sizes, dec_lens)]) + if level is None: + level = max_level + elif level < 0: + raise ValueError( + "Level value of %d is too low . Minimum level is 0." % level) + elif level > max_level: + warnings.warn( + f"Level value of {level} is too high: all coefficients will experience " + "boundary effects.") + return level + + +def wavedec(data, wavelet, mode='symmetric', level=None, axis=-1): + """ + Multilevel 1D Discrete Wavelet Transform of data. + + Parameters + ---------- + data: array_like + Input data + wavelet : Wavelet object or name string + Wavelet to use + mode : str, optional + Signal extension mode, see :ref:`Modes `. + level : int, optional + Decomposition level (must be >= 0). If level is None (default) then it + will be calculated using the ``dwt_max_level`` function. + axis: int, optional + Axis over which to compute the DWT. If not given, the + last axis is used. + + Returns + ------- + [cA_n, cD_n, cD_n-1, ..., cD2, cD1] : list + Ordered list of coefficients arrays + where ``n`` denotes the level of decomposition. The first element + (``cA_n``) of the result is approximation coefficients array and the + following elements (``cD_n`` - ``cD_1``) are details coefficients + arrays. + + Examples + -------- + >>> from pywt import wavedec + >>> coeffs = wavedec([1,2,3,4,5,6,7,8], 'db1', level=2) + >>> cA2, cD2, cD1 = coeffs + >>> cD1 + array([-0.70710678, -0.70710678, -0.70710678, -0.70710678]) + >>> cD2 + array([-2., -2.]) + >>> cA2 + array([ 5., 13.]) + + """ + data = np.asarray(data) + + wavelet = _as_wavelet(wavelet) + try: + axes_shape = data.shape[axis] + except IndexError: + raise AxisError("Axis greater than data dimensions") + level = _check_level(axes_shape, wavelet.dec_len, level) + + coeffs_list = [] + + a = data + for i in range(level): + a, d = dwt(a, wavelet, mode, axis) + coeffs_list.append(d) + + coeffs_list.append(a) + coeffs_list.reverse() + + return coeffs_list + + +def waverec(coeffs, wavelet, mode='symmetric', axis=-1): + """ + Multilevel 1D Inverse Discrete Wavelet Transform. + + Parameters + ---------- + coeffs : array_like + Coefficients list [cAn, cDn, cDn-1, ..., cD2, cD1] + wavelet : Wavelet object or name string + Wavelet to use + mode : str, optional + Signal extension mode, see :ref:`Modes `. + axis: int, optional + Axis over which to compute the inverse DWT. If not given, the + last axis is used. + + Notes + ----- + It may sometimes be desired to run ``waverec`` with some sets of + coefficients omitted. This can best be done by setting the corresponding + arrays to zero arrays of matching shape and dtype. Explicitly removing + list entries or setting them to None is not supported. + + Specifically, to ignore detail coefficients at level 2, one could do:: + + coeffs[-2] = np.zeros_like(coeffs[-2]) + + Examples + -------- + >>> import pywt + >>> coeffs = pywt.wavedec([1,2,3,4,5,6,7,8], 'db1', level=2) + >>> pywt.waverec(coeffs, 'db1') + array([ 1., 2., 3., 4., 5., 6., 7., 8.]) + """ + + if not isinstance(coeffs, (list, tuple)): + raise ValueError("Expected sequence of coefficient arrays.") + + if len(coeffs) < 1: + raise ValueError( + "Coefficient list too short (minimum 1 arrays required).") + elif len(coeffs) == 1: + # level 0 transform (just returns the approximation coefficients) + return coeffs[0] + + a, ds = coeffs[0], coeffs[1:] + + for d in ds: + if d is not None and not isinstance(d, np.ndarray): + raise ValueError( + f"Unexpected detail coefficient type: {type(d)}. Detail coefficients " + "must be arrays as returned by wavedec. If you are using " + "pywt.array_to_coeffs or pywt.unravel_coeffs, please specify " + "output_format='wavedec'") + if (a is not None) and (d is not None): + try: + if a.shape[axis] == d.shape[axis] + 1: + a = a[tuple(slice(s) for s in d.shape)] + elif a.shape[axis] != d.shape[axis]: + raise ValueError("coefficient shape mismatch") + except IndexError: + raise AxisError("Axis greater than coefficient dimensions") + a = idwt(a, d, wavelet, mode, axis) + + return a + + +def wavedec2(data, wavelet, mode='symmetric', level=None, axes=(-2, -1)): + """ + Multilevel 2D Discrete Wavelet Transform. + + Parameters + ---------- + data : ndarray + 2D input data + wavelet : Wavelet object or name string, or 2-tuple of wavelets + Wavelet to use. This can also be a tuple containing a wavelet to + apply along each axis in ``axes``. + mode : str or 2-tuple of str, optional + Signal extension mode, see :ref:`Modes `. This can + also be a tuple containing a mode to apply along each axis in ``axes``. + level : int, optional + Decomposition level (must be >= 0). If level is None (default) then it + will be calculated using the ``dwt_max_level`` function. + axes : 2-tuple of ints, optional + Axes over which to compute the DWT. Repeated elements are not allowed. + + Returns + ------- + [cAn, (cHn, cVn, cDn), ... (cH1, cV1, cD1)] : list + Coefficients list. For user-specified ``axes``, ``cH*`` + corresponds to ``axes[0]`` while ``cV*`` corresponds to ``axes[1]``. + The first element returned is the approximation coefficients for the + nth level of decomposition. Remaining elements are tuples of detail + coefficients in descending order of decomposition level. + (i.e. ``cH1`` are the horizontal detail coefficients at the first + level) + + Examples + -------- + >>> import pywt + >>> import numpy as np + >>> coeffs = pywt.wavedec2(np.ones((4,4)), 'db1') + >>> # Levels: + >>> len(coeffs)-1 + 2 + >>> pywt.waverec2(coeffs, 'db1') + array([[ 1., 1., 1., 1.], + [ 1., 1., 1., 1.], + [ 1., 1., 1., 1.], + [ 1., 1., 1., 1.]]) + """ + data = np.asarray(data) + if data.ndim < 2: + raise ValueError("Expected input data to have at least 2 dimensions.") + + axes = tuple(axes) + if len(axes) != 2: + raise ValueError("Expected 2 axes") + if len(axes) != len(set(axes)): + raise ValueError("The axes passed to wavedec2 must be unique.") + try: + axes_sizes = [data.shape[ax] for ax in axes] + except IndexError: + raise AxisError("Axis greater than data dimensions") + + wavelets = _wavelets_per_axis(wavelet, axes) + dec_lengths = [w.dec_len for w in wavelets] + + level = _check_level(axes_sizes, dec_lengths, level) + + coeffs_list = [] + + a = data + for i in range(level): + a, ds = dwt2(a, wavelet, mode, axes) + coeffs_list.append(ds) + + coeffs_list.append(a) + coeffs_list.reverse() + + return coeffs_list + + +def waverec2(coeffs, wavelet, mode='symmetric', axes=(-2, -1)): + """ + Multilevel 2D Inverse Discrete Wavelet Transform. + + coeffs : list or tuple + Coefficients list [cAn, (cHn, cVn, cDn), ... (cH1, cV1, cD1)] + wavelet : Wavelet object or name string, or 2-tuple of wavelets + Wavelet to use. This can also be a tuple containing a wavelet to + apply along each axis in ``axes``. + mode : str or 2-tuple of str, optional + Signal extension mode, see :ref:`Modes `. This can + also be a tuple containing a mode to apply along each axis in ``axes``. + axes : 2-tuple of ints, optional + Axes over which to compute the IDWT. Repeated elements are not allowed. + + Returns + ------- + 2D array of reconstructed data. + + Notes + ----- + It may sometimes be desired to run ``waverec2`` with some sets of + coefficients omitted. This can best be done by setting the corresponding + arrays to zero arrays of matching shape and dtype. Explicitly removing + list or tuple entries or setting them to None is not supported. + + Specifically, to ignore all detail coefficients at level 2, one could do:: + + coeffs[-2] == tuple([np.zeros_like(v) for v in coeffs[-2]]) + + Examples + -------- + >>> import pywt + >>> import numpy as np + >>> coeffs = pywt.wavedec2(np.ones((4,4)), 'db1') + >>> # Levels: + >>> len(coeffs)-1 + 2 + >>> pywt.waverec2(coeffs, 'db1') + array([[ 1., 1., 1., 1.], + [ 1., 1., 1., 1.], + [ 1., 1., 1., 1.], + [ 1., 1., 1., 1.]]) + """ + if not isinstance(coeffs, (list, tuple)): + raise ValueError("Expected sequence of coefficient arrays.") + + if len(axes) != len(set(axes)): + raise ValueError("The axes passed to waverec2 must be unique.") + + if len(coeffs) < 1: + raise ValueError( + "Coefficient list too short (minimum 1 array required).") + elif len(coeffs) == 1: + # level 0 transform (just returns the approximation coefficients) + return coeffs[0] + + a, ds = coeffs[0], coeffs[1:] + a = np.asarray(a) + + for d in ds: + if not isinstance(d, (list, tuple)) or len(d) != 3: + raise ValueError( + f"Unexpected detail coefficient type: {type(d)}. Detail coefficients " + "must be a 3-tuple of arrays as returned by wavedec2. If you " + "are using pywt.array_to_coeffs or pywt.unravel_coeffs, " + "please specify output_format='wavedec2'") + d = tuple(np.asarray(coeff) if coeff is not None else None + for coeff in d) + d_shapes = (coeff.shape for coeff in d if coeff is not None) + try: + d_shape = next(d_shapes) + except StopIteration: + idxs = slice(None), slice(None) + else: + if not all(s == d_shape for s in d_shapes): + raise ValueError("All detail shapes must be the same length.") + idxs = tuple(slice(None, -1 if a_len == d_len + 1 else None) + for a_len, d_len in zip(a.shape, d_shape)) + a = idwt2((a[idxs], d), wavelet, mode, axes) + + return a + + +def _prep_axes_wavedecn(shape, axes): + if len(shape) < 1: + raise ValueError("Expected at least 1D input data.") + ndim = len(shape) + if np.isscalar(axes): + axes = (axes, ) + if axes is None: + axes = range(ndim) + else: + axes = tuple(axes) + if len(axes) != len(set(axes)): + raise ValueError("The axes passed to wavedecn must be unique.") + try: + axes_shapes = [shape[ax] for ax in axes] + except IndexError: + raise AxisError("Axis greater than data dimensions") + ndim_transform = len(axes) + return axes, axes_shapes, ndim_transform + + +def wavedecn(data, wavelet, mode='symmetric', level=None, axes=None): + """ + Multilevel nD Discrete Wavelet Transform. + + Parameters + ---------- + data : ndarray + nD input data + wavelet : Wavelet object or name string, or tuple of wavelets + Wavelet to use. This can also be a tuple containing a wavelet to + apply along each axis in ``axes``. + mode : str or tuple of str, optional + Signal extension mode, see :ref:`Modes `. This can + also be a tuple containing a mode to apply along each axis in ``axes``. + level : int, optional + Decomposition level (must be >= 0). If level is None (default) then it + will be calculated using the ``dwt_max_level`` function. + axes : sequence of ints, optional + Axes over which to compute the DWT. Axes may not be repeated. The + default is None, which means transform all axes + (``axes = range(data.ndim)``). + + Returns + ------- + [cAn, {details_level_n}, ... {details_level_1}] : list + Coefficients list. Coefficients are listed in descending order of + decomposition level. ``cAn`` are the approximation coefficients at + level ``n``. Each ``details_level_i`` element is a dictionary + containing detail coefficients at level ``i`` of the decomposition. As + a concrete example, a 3D decomposition would have the following set of + keys in each ``details_level_i`` dictionary:: + + {'aad', 'ada', 'daa', 'add', 'dad', 'dda', 'ddd'} + + where the order of the characters in each key map to the specified + ``axes``. + + Examples + -------- + >>> import numpy as np + >>> from pywt import wavedecn, waverecn + >>> coeffs = wavedecn(np.ones((4, 4, 4)), 'db1') + >>> # Levels: + >>> len(coeffs)-1 + 2 + >>> waverecn(coeffs, 'db1') + array([[[ 1., 1., 1., 1.], + [ 1., 1., 1., 1.], + [ 1., 1., 1., 1.], + [ 1., 1., 1., 1.]], + [[ 1., 1., 1., 1.], + [ 1., 1., 1., 1.], + [ 1., 1., 1., 1.], + [ 1., 1., 1., 1.]], + [[ 1., 1., 1., 1.], + [ 1., 1., 1., 1.], + [ 1., 1., 1., 1.], + [ 1., 1., 1., 1.]], + [[ 1., 1., 1., 1.], + [ 1., 1., 1., 1.], + [ 1., 1., 1., 1.], + [ 1., 1., 1., 1.]]]) + + """ + data = np.asarray(data) + axes, axes_shapes, ndim_transform = _prep_axes_wavedecn(data.shape, axes) + wavelets = _wavelets_per_axis(wavelet, axes) + dec_lengths = [w.dec_len for w in wavelets] + + level = _check_level(axes_shapes, dec_lengths, level) + + coeffs_list = [] + + a = data + for i in range(level): + coeffs = dwtn(a, wavelet, mode, axes) + a = coeffs.pop('a' * ndim_transform) + coeffs_list.append(coeffs) + + coeffs_list.append(a) + coeffs_list.reverse() + + return coeffs_list + + +def _match_coeff_dims(a_coeff, d_coeff_dict): + # For each axis, compare the approximation coeff shape to one of the + # stored detail coeffs and truncate the last element along the axis + # if necessary. + if a_coeff is None: + return None + if not d_coeff_dict: + return a_coeff + d_coeff = d_coeff_dict[next(iter(d_coeff_dict))] + size_diffs = np.subtract(a_coeff.shape, d_coeff.shape) + if np.any((size_diffs < 0) | (size_diffs > 1)): + print(size_diffs) + raise ValueError("incompatible coefficient array sizes") + return a_coeff[tuple(slice(s) for s in d_coeff.shape)] + + +def waverecn(coeffs, wavelet, mode='symmetric', axes=None): + """ + Multilevel nD Inverse Discrete Wavelet Transform. + + coeffs : array_like + Coefficients list [cAn, {details_level_n}, ... {details_level_1}] + wavelet : Wavelet object or name string, or tuple of wavelets + Wavelet to use. This can also be a tuple containing a wavelet to + apply along each axis in ``axes``. + mode : str or tuple of str, optional + Signal extension mode, see :ref:`Modes `. This can + also be a tuple containing a mode to apply along each axis in ``axes``. + axes : sequence of ints, optional + Axes over which to compute the IDWT. Axes may not be repeated. + + Returns + ------- + nD array of reconstructed data. + + Notes + ----- + It may sometimes be desired to run ``waverecn`` with some sets of + coefficients omitted. This can best be done by setting the corresponding + arrays to zero arrays of matching shape and dtype. Explicitly removing + list or dictionary entries or setting them to None is not supported. + + Specifically, to ignore all detail coefficients at level 2, one could do:: + + coeffs[-2] = {k: np.zeros_like(v) for k, v in coeffs[-2].items()} + + Examples + -------- + >>> import numpy as np + >>> from pywt import wavedecn, waverecn + >>> coeffs = wavedecn(np.ones((4, 4, 4)), 'db1') + >>> # Levels: + >>> len(coeffs)-1 + 2 + >>> waverecn(coeffs, 'db1') + array([[[ 1., 1., 1., 1.], + [ 1., 1., 1., 1.], + [ 1., 1., 1., 1.], + [ 1., 1., 1., 1.]], + [[ 1., 1., 1., 1.], + [ 1., 1., 1., 1.], + [ 1., 1., 1., 1.], + [ 1., 1., 1., 1.]], + [[ 1., 1., 1., 1.], + [ 1., 1., 1., 1.], + [ 1., 1., 1., 1.], + [ 1., 1., 1., 1.]], + [[ 1., 1., 1., 1.], + [ 1., 1., 1., 1.], + [ 1., 1., 1., 1.], + [ 1., 1., 1., 1.]]]) + + """ + if len(coeffs) < 1: + raise ValueError( + "Coefficient list too short (minimum 1 array required).") + + a, ds = coeffs[0], coeffs[1:] + + # this dictionary check must be prior to the call to _fix_coeffs + if len(ds) > 0 and not all(isinstance(d, dict) for d in ds): + raise ValueError( + f"Unexpected detail coefficient type: {type(ds[0])}. Detail coefficients " + "must be a dictionary of arrays as returned by wavedecn. If " + "you are using pywt.array_to_coeffs or pywt.unravel_coeffs, " + "please specify output_format='wavedecn'") + + # Raise error for invalid key combinations + ds = list(map(_fix_coeffs, ds)) + + if not ds: + # level 0 transform (just returns the approximation coefficients) + return coeffs[0] + if a is None and not any(ds): + raise ValueError( + "At least one coefficient must contain a valid value.") + + coeff_ndims = [] + if a is not None: + a = np.asarray(a) + coeff_ndims.append(a.ndim) + for d in ds: + coeff_ndims += [v.ndim for k, v in d.items()] + + # test that all coefficients have a matching number of dimensions + unique_coeff_ndims = np.unique(coeff_ndims) + if len(unique_coeff_ndims) == 1: + ndim = unique_coeff_ndims[0] + else: + raise ValueError( + "All coefficients must have a matching number of dimensions") + + if np.isscalar(axes): + axes = (axes, ) + if axes is None: + axes = range(ndim) + else: + axes = tuple(axes) + if len(axes) != len(set(axes)): + raise ValueError("The axes passed to waverecn must be unique.") + ndim_transform = len(axes) + + for idx, d in enumerate(ds): + if a is None and not d: + continue + # The following if statement handles the case where the approximation + # coefficient returned at the previous level may exceed the size of the + # stored detail coefficients by 1 on any given axis. + if idx > 0: + a = _match_coeff_dims(a, d) + d['a' * ndim_transform] = a + a = idwtn(d, wavelet, mode, axes) + + return a + + +def _coeffs_wavedec_to_wavedecn(coeffs): + """Convert wavedec coefficients to the wavedecn format.""" + if len(coeffs) == 0: + return coeffs + coeffs = copy(coeffs) + for n in range(1, len(coeffs)): + if coeffs[n] is None: + continue + if coeffs[n].ndim != 1: + raise ValueError("expected a 1D coefficient array") + coeffs[n] = {'d': coeffs[n]} + return coeffs + + +def _coeffs_wavedec2_to_wavedecn(coeffs): + """Convert wavedec2 coefficients to the wavedecn format.""" + if len(coeffs) == 0: + return coeffs + coeffs = copy(coeffs) + for n in range(1, len(coeffs)): + if not isinstance(coeffs[n], (tuple, list)) or len(coeffs[n]) != 3: + raise ValueError("expected a 3-tuple of detail coefficients") + (da, ad, dd) = coeffs[n] + if da is None or ad is None or dd is None: + raise ValueError( + "Expected numpy arrays of detail coefficients. Setting " + "coefficients to None is not supported.") + coeffs[n] = {'ad': ad, 'da': da, 'dd': dd} + return coeffs + + +def _determine_coeff_array_shape(coeffs, axes): + arr_shape = np.asarray(coeffs[0].shape) + axes = np.asarray(axes) # axes that were transformed + ndim_transform = len(axes) + ncoeffs = coeffs[0].size + for d in coeffs[1:]: + arr_shape[axes] += np.asarray(d['d'*ndim_transform].shape)[axes] + for k, v in d.items(): + ncoeffs += v.size + arr_shape = tuple(arr_shape.tolist()) + # if the total number of coefficients doesn't equal the size of the array + # then tight packing is not possible. + is_tight_packing = (np.prod(arr_shape) == ncoeffs) + return arr_shape, is_tight_packing + + +def _prepare_coeffs_axes(coeffs, axes): + """Helper function to check type of coeffs and axes. + + This code is used by both coeffs_to_array and ravel_coeffs. + """ + if not isinstance(coeffs, list) or len(coeffs) == 0: + raise ValueError("input must be a list of coefficients from wavedecn") + if coeffs[0] is None: + raise ValueError("coeffs_to_array does not support missing " + "coefficients.") + if not isinstance(coeffs[0], np.ndarray): + raise ValueError("first list element must be a numpy array") + ndim = coeffs[0].ndim + + if len(coeffs) > 1: + # convert wavedec or wavedec2 format coefficients to waverecn format + if isinstance(coeffs[1], dict): + pass + elif isinstance(coeffs[1], np.ndarray): + coeffs = _coeffs_wavedec_to_wavedecn(coeffs) + elif isinstance(coeffs[1], (tuple, list)): + coeffs = _coeffs_wavedec2_to_wavedecn(coeffs) + else: + raise ValueError("invalid coefficient list") + + if len(coeffs) == 1: + # no detail coefficients were found + return coeffs, axes, ndim, None + + # Determine the number of dimensions that were transformed via key length + ndim_transform = len(list(coeffs[1].keys())[0]) + if axes is None: + if ndim_transform < ndim: + raise ValueError( + "coeffs corresponds to a DWT performed over only a subset of " + "the axes. In this case, axes must be specified.") + axes = np.arange(ndim) + + if len(axes) != ndim_transform: + raise ValueError( + "The length of axes doesn't match the number of dimensions " + "transformed.") + + return coeffs, axes, ndim, ndim_transform + + +def coeffs_to_array(coeffs, padding=0, axes=None): + """ + Arrange a wavelet coefficient list from ``wavedecn`` into a single array. + + Parameters + ---------- + + coeffs : array-like + Dictionary of wavelet coefficients as returned by pywt.wavedecn + padding : float or None, optional + The value to use for the background if the coefficients cannot be + tightly packed. If None, raise an error if the coefficients cannot be + tightly packed. + axes : sequence of ints, optional + Axes over which the DWT that created ``coeffs`` was performed. The + default value of None corresponds to all axes. + + Returns + ------- + coeff_arr : array-like + Wavelet transform coefficient array. + coeff_slices : list + List of slices corresponding to each coefficient. As a 2D example, + ``coeff_arr[coeff_slices[1]['dd']]`` would extract the first level + detail coefficients from ``coeff_arr``. + + See Also + -------- + array_to_coeffs : the inverse of coeffs_to_array + + Notes + ----- + Assume a 2D coefficient dictionary, c, from a two-level transform. + + Then all 2D coefficients will be stacked into a single larger 2D array + as follows:: + + +---------------+---------------+-------------------------------+ + | | | | + | c[0] | c[1]['da'] | | + | | | | + +---------------+---------------+ c[2]['da'] | + | | | | + | c[1]['ad'] | c[1]['dd'] | | + | | | | + +---------------+---------------+ ------------------------------+ + | | | + | | | + | | | + | c[2]['ad'] | c[2]['dd'] | + | | | + | | | + | | | + +-------------------------------+-------------------------------+ + + If the transform was not performed with mode "periodization" or the signal + length was not a multiple of ``2**level``, coefficients at each subsequent + scale will not be exactly 1/2 the size of those at the previous level due + to additional coefficients retained to handle the boundary condition. In + these cases, the default setting of `padding=0` indicates to pad the + individual coefficient arrays with 0 as needed so that they can be stacked + into a single, contiguous array. + + Examples + -------- + >>> import pywt + >>> cam = pywt.data.camera() + >>> coeffs = pywt.wavedecn(cam, wavelet='db2', level=3) + >>> arr, coeff_slices = pywt.coeffs_to_array(coeffs) + + """ + + coeffs, axes, ndim, ndim_transform = _prepare_coeffs_axes(coeffs, axes) + + # initialize with the approximation coefficients. + a_coeffs = coeffs[0] + a_shape = a_coeffs.shape + + if len(coeffs) == 1: + # only a single approximation coefficient array was found + return a_coeffs, [tuple([slice(None)] * ndim)] + + # determine size of output and if tight packing is possible + arr_shape, is_tight_packing = _determine_coeff_array_shape(coeffs, axes) + + # preallocate output array + if padding is None: + if not is_tight_packing: + raise ValueError("array coefficients cannot be tightly packed") + coeff_arr = np.empty(arr_shape, dtype=a_coeffs.dtype) + else: + coeff_arr = np.full(arr_shape, padding, dtype=a_coeffs.dtype) + + a_slices = tuple([slice(s) for s in a_shape]) + coeff_arr[a_slices] = a_coeffs + + # initialize list of coefficient slices + coeff_slices = [] + coeff_slices.append(a_slices) + + # loop over the detail coefficients, adding them to coeff_arr + ds = coeffs[1:] + for coeff_dict in ds: + coeff_slices.append({}) # new dictionary for detail coefficients + if np.any([d is None for d in coeff_dict.values()]): + raise ValueError("coeffs_to_array does not support missing " + "coefficients.") + d_shape = coeff_dict['d' * ndim_transform].shape + for key in coeff_dict: + d = coeff_dict[key] + slice_array = [slice(None), ] * ndim + for i, let in enumerate(key): + ax_i = axes[i] # axis corresponding to this transform index + if let == 'a': + slice_array[ax_i] = slice(d.shape[ax_i]) + elif let == 'd': + slice_array[ax_i] = slice(a_shape[ax_i], + a_shape[ax_i] + d.shape[ax_i]) + else: + raise ValueError(f"unexpected letter: {let}") + slice_array = tuple(slice_array) + coeff_arr[slice_array] = d + coeff_slices[-1][key] = slice_array + a_shape = [a_shape[n] + d_shape[n] for n in range(ndim)] + return coeff_arr, coeff_slices + + +def array_to_coeffs(arr, coeff_slices, output_format='wavedecn'): + """ + Convert a combined array of coefficients back to a list compatible with + ``waverecn``. + + Parameters + ---------- + + arr : array-like + An array containing all wavelet coefficients. This should have been + generated via ``coeffs_to_array``. + coeff_slices : list of tuples + List of slices corresponding to each coefficient as obtained from + ``array_to_coeffs``. + output_format : {'wavedec', 'wavedec2', 'wavedecn'} + Make the form of the coefficients compatible with this type of + multilevel transform. + + Returns + ------- + coeffs: array-like + Wavelet transform coefficient array. + + See Also + -------- + coeffs_to_array : the inverse of array_to_coeffs + + Notes + ----- + A single large array containing all coefficients will have subsets stored, + into a ``waverecn`` list, c, as indicated below:: + + +---------------+---------------+-------------------------------+ + | | | | + | c[0] | c[1]['da'] | | + | | | | + +---------------+---------------+ c[2]['da'] | + | | | | + | c[1]['ad'] | c[1]['dd'] | | + | | | | + +---------------+---------------+ ------------------------------+ + | | | + | | | + | | | + | c[2]['ad'] | c[2]['dd'] | + | | | + | | | + | | | + +-------------------------------+-------------------------------+ + + Examples + -------- + >>> import pywt + >>> from numpy.testing import assert_array_almost_equal + >>> cam = pywt.data.camera() + >>> coeffs = pywt.wavedecn(cam, wavelet='db2', level=3) + >>> arr, coeff_slices = pywt.coeffs_to_array(coeffs) + >>> coeffs_from_arr = pywt.array_to_coeffs(arr, coeff_slices, + ... output_format='wavedecn') + >>> cam_recon = pywt.waverecn(coeffs_from_arr, wavelet='db2') + >>> assert_array_almost_equal(cam, cam_recon) + + """ + arr = np.asarray(arr) + coeffs = [] + if len(coeff_slices) == 0: + raise ValueError("empty list of coefficient slices") + else: + coeffs.append(arr[coeff_slices[0]]) + + # difference coefficients at each level + for n in range(1, len(coeff_slices)): + if output_format == 'wavedec': + d = arr[coeff_slices[n]['d']] + elif output_format == 'wavedec2': + d = (arr[coeff_slices[n]['da']], + arr[coeff_slices[n]['ad']], + arr[coeff_slices[n]['dd']]) + elif output_format == 'wavedecn': + d = {} + for k, v in coeff_slices[n].items(): + d[k] = arr[v] + else: + raise ValueError( + f"Unrecognized output format: {output_format}") + coeffs.append(d) + return coeffs + + +def wavedecn_shapes(shape, wavelet, mode='symmetric', level=None, axes=None): + """Subband shapes for a multilevel nD discrete wavelet transform. + + Parameters + ---------- + shape : sequence of ints + The shape of the data to be transformed. + wavelet : Wavelet object or name string, or tuple of wavelets + Wavelet to use. This can also be a tuple containing a wavelet to + apply along each axis in ``axes``. + mode : str or tuple of str, optional + Signal extension mode, see :ref:`Modes `. This can + also be a tuple containing a mode to apply along each axis in ``axes``. + level : int, optional + Decomposition level (must be >= 0). If level is None (default) then it + will be calculated using the ``dwt_max_level`` function. + axes : sequence of ints, optional + Axes over which to compute the DWT. Axes may not be repeated. The + default is None, which means transform all axes + (``axes = range(data.ndim)``). + + Returns + ------- + shapes : [cAn, {details_level_n}, ... {details_level_1}] : list + Coefficients shape list. Mirrors the output of ``wavedecn``, except + it contains only the shapes of the coefficient arrays rather than the + arrays themselves. + + Examples + -------- + >>> import pywt + >>> pywt.wavedecn_shapes((64, 32), wavelet='db2', level=3, axes=(0, )) + [(10, 32), {'d': (10, 32)}, {'d': (18, 32)}, {'d': (33, 32)}] + """ + axes, axes_shapes, ndim_transform = _prep_axes_wavedecn(shape, axes) + wavelets = _wavelets_per_axis(wavelet, axes) + modes = _modes_per_axis(mode, axes) + dec_lengths = [w.dec_len for w in wavelets] + + level = _check_level(min(axes_shapes), max(dec_lengths), level) + + shapes = [] + for i in range(level): + detail_keys = [''.join(c) for c in product('ad', repeat=len(axes))] + new_shapes = {k: list(shape) for k in detail_keys} + for axis, wav, mode in zip(axes, wavelets, modes): + s = dwt_coeff_len(shape[axis], filter_len=wav.dec_len, mode=mode) + for k in detail_keys: + new_shapes[k][axis] = s + for k, v in new_shapes.items(): + new_shapes[k] = tuple(v) + shapes.append(new_shapes) + shape = new_shapes.pop('a' * ndim_transform) + shapes.append(shape) + shapes.reverse() + return shapes + + +def wavedecn_size(shapes): + """Compute the total number of wavedecn coefficients. + + Parameters + ---------- + shapes : list of coefficient shapes + A set of coefficient shapes as returned by ``wavedecn_shapes``. + Alternatively, the user can specify a set of coefficients as returned + by ``wavedecn``. + + Returns + ------- + size : int + The total number of coefficients. + + Examples + -------- + >>> import numpy as np + >>> import pywt + >>> data_shape = (64, 32) + >>> shapes = pywt.wavedecn_shapes(data_shape, 'db2', mode='periodization') + >>> pywt.wavedecn_size(shapes) + 2048 + >>> coeffs = pywt.wavedecn(np.ones(data_shape), 'sym4', mode='symmetric') + >>> pywt.wavedecn_size(coeffs) + 3087 + """ + def _size(x): + """Size corresponding to ``x`` as either a shape tuple or ndarray.""" + if isinstance(x, np.ndarray): + return x.size + else: + return np.prod(x) + ncoeffs = _size(shapes[0]) + for d in shapes[1:]: + for k, v in d.items(): + if v is None: + raise ValueError( + "Setting coefficient arrays to None is not supported.") + ncoeffs += _size(v) + return ncoeffs + + +def dwtn_max_level(shape, wavelet, axes=None): + """Compute the maximum level of decomposition for n-dimensional data. + + This returns the maximum number of levels of decomposition suitable for use + with ``wavedec``, ``wavedec2`` or ``wavedecn``. + + Parameters + ---------- + shape : sequence of ints + Input data shape. + wavelet : Wavelet object or name string, or tuple of wavelets + Wavelet to use. This can also be a tuple containing a wavelet to + apply along each axis in ``axes``. + axes : sequence of ints, optional + Axes over which to compute the DWT. Axes may not be repeated. + + Returns + ------- + level : int + Maximum level. + + Notes + ----- + The level returned is the smallest ``dwt_max_level`` over all axes. + + Examples + -------- + >>> import pywt + >>> pywt.dwtn_max_level((64, 32), 'db2') + 3 + """ + # Determine the axes and shape for the transform + axes, axes_shapes, ndim_transform = _prep_axes_wavedecn(shape, axes) + + # initialize a Wavelet object per (transformed) axis + wavelets = _wavelets_per_axis(wavelet, axes) + + # maximum level of decomposition per axis + max_levels = [dwt_max_level(n, wav.dec_len) + for n, wav in zip(axes_shapes, wavelets)] + return min(max_levels) + + +def ravel_coeffs(coeffs, axes=None): + """Ravel a set of multilevel wavelet coefficients into a single 1D array. + + Parameters + ---------- + coeffs : array-like + A list of multilevel wavelet coefficients as returned by + ``wavedec``, ``wavedec2`` or ``wavedecn``. This function is also + compatible with the output of ``swt``, ``swt2`` and ``swtn`` if those + functions were called with ``trim_approx=True``. + axes : sequence of ints, optional + Axes over which the DWT that created ``coeffs`` was performed. The + default value of None corresponds to all axes. + + Returns + ------- + coeff_arr : array-like + Wavelet transform coefficient array. All coefficients have been + concatenated into a single array. + coeff_slices : list + List of slices corresponding to each coefficient. As a 2D example, + ``coeff_arr[coeff_slices[1]['dd']]`` would extract the first level + detail coefficients from ``coeff_arr``. + coeff_shapes : list + List of shapes corresponding to each coefficient. For example, in 2D, + ``coeff_shapes[1]['dd']`` would contain the original shape of the first + level detail coefficients array. + + See Also + -------- + unravel_coeffs : the inverse of ravel_coeffs + + Examples + -------- + >>> import pywt + >>> cam = pywt.data.camera() + >>> coeffs = pywt.wavedecn(cam, wavelet='db2', level=3) + >>> arr, coeff_slices, coeff_shapes = pywt.ravel_coeffs(coeffs) + + """ + coeffs, axes, ndim, ndim_transform = _prepare_coeffs_axes(coeffs, axes) + + # initialize with the approximation coefficients. + a_coeffs = coeffs[0] + a_size = a_coeffs.size + + if len(coeffs) == 1: + # only a single approximation coefficient array was found + return a_coeffs.ravel(), [slice(a_size), ], [a_coeffs.shape, ] + + # preallocate output array + arr_size = wavedecn_size(coeffs) + coeff_arr = np.empty((arr_size, ), dtype=a_coeffs.dtype) + + a_slice = slice(a_size) + coeff_arr[a_slice] = a_coeffs.ravel() + + # initialize list of coefficient slices + coeff_slices = [] + coeff_shapes = [] + coeff_slices.append(a_slice) + coeff_shapes.append(coeffs[0].shape) + + # loop over the detail coefficients, embedding them in coeff_arr + ds = coeffs[1:] + offset = a_size + for coeff_dict in ds: + # new dictionaries for detail coefficient slices and shapes + coeff_slices.append({}) + coeff_shapes.append({}) + if np.any([d is None for d in coeff_dict.values()]): + raise ValueError("coeffs_to_array does not support missing " + "coefficients.") + # sort to make sure key order is consistent across Python versions + keys = sorted(coeff_dict.keys()) + for key in keys: + d = coeff_dict[key] + sl = slice(offset, offset + d.size) + offset += d.size + coeff_arr[sl] = d.ravel() + coeff_slices[-1][key] = sl + coeff_shapes[-1][key] = d.shape + return coeff_arr, coeff_slices, coeff_shapes + + +def unravel_coeffs(arr, coeff_slices, coeff_shapes, output_format='wavedecn'): + """Unravel a raveled array of multilevel wavelet coefficients. + + Parameters + ---------- + arr : array-like + An array containing all wavelet coefficients. This should have been + generated by applying ``ravel_coeffs`` to the output of ``wavedec``, + ``wavedec2`` or ``wavedecn`` (or via ``swt``, ``swt2`` or ``swtn`` + with ``trim_approx=True``). + coeff_slices : list of tuples + List of slices corresponding to each coefficient as obtained from + ``ravel_coeffs``. + coeff_shapes : list of tuples + List of shapes corresponding to each coefficient as obtained from + ``ravel_coeffs``. + output_format : {'wavedec', 'wavedec2', 'wavedecn', 'swt', 'swt2', 'swtn'}, optional + Make the form of the unraveled coefficients compatible with this type + of multilevel transform. The default is ``'wavedecn'``. + + Returns + ------- + coeffs: list + List of wavelet transform coefficients. The specific format of the list + elements is determined by ``output_format``. + + See Also + -------- + ravel_coeffs : the inverse of unravel_coeffs + + Examples + -------- + >>> import pywt + >>> from numpy.testing import assert_array_almost_equal + >>> cam = pywt.data.camera() + >>> coeffs = pywt.wavedecn(cam, wavelet='db2', level=3) + >>> arr, coeff_slices, coeff_shapes = pywt.ravel_coeffs(coeffs) + >>> coeffs_from_arr = pywt.unravel_coeffs(arr, coeff_slices, coeff_shapes, + ... output_format='wavedecn') + >>> cam_recon = pywt.waverecn(coeffs_from_arr, wavelet='db2') + >>> assert_array_almost_equal(cam, cam_recon) + + """ + arr = np.asarray(arr) + coeffs = [] + if len(coeff_slices) == 0: + raise ValueError("empty list of coefficient slices") + elif len(coeff_shapes) == 0: + raise ValueError("empty list of coefficient shapes") + elif len(coeff_shapes) != len(coeff_slices): + raise ValueError("coeff_shapes and coeff_slices have unequal length") + else: + coeffs.append(arr[coeff_slices[0]].reshape(coeff_shapes[0])) + + # difference coefficients at each level + for n in range(1, len(coeff_slices)): + slice_dict = coeff_slices[n] + shape_dict = coeff_shapes[n] + if output_format in ['wavedec', 'swt']: + d = arr[slice_dict['d']].reshape(shape_dict['d']) + elif output_format in ['wavedec2', 'swt2']: + d = (arr[slice_dict['da']].reshape(shape_dict['da']), + arr[slice_dict['ad']].reshape(shape_dict['ad']), + arr[slice_dict['dd']].reshape(shape_dict['dd'])) + elif output_format in ['wavedecn', 'swtn']: + d = {} + for k, v in coeff_slices[n].items(): + d[k] = arr[v].reshape(shape_dict[k]) + else: + raise ValueError( + f"Unrecognized output format: {output_format}") + coeffs.append(d) + return coeffs + + +def _check_fswavedecn_axes(data, axes): + """Axes checks common to fswavedecn, fswaverecn.""" + if len(axes) != len(set(axes)): + raise AxisError("The axes passed to fswavedecn must be unique.") + try: + [data.shape[ax] for ax in axes] + except IndexError: + raise AxisError("Axis greater than data dimensions") + + +class FswavedecnResult: + """Object representing fully separable wavelet transform coefficients. + + Parameters + ---------- + coeffs : ndarray + The coefficient array. + coeff_slices : list + List of slices corresponding to each detail or approximation + coefficient array. + wavelets : list of pywt.DiscreteWavelet objects + The wavelets used. Will be a list with length equal to + ``len(axes)``. + mode_enums : list of int + The border modes used. Will be a list with length equal to + ``len(axes)``. + axes : tuple of int + The set of axes over which the transform was performed. + + """ + def __init__(self, coeffs, coeff_slices, wavelets, mode_enums, + axes): + self._coeffs = coeffs + self._coeff_slices = coeff_slices + self._axes = axes + if not np.all(isinstance(w, Wavelet) for w in wavelets): + raise ValueError( + "wavelets must contain pywt.Wavelet objects") + self._wavelets = wavelets + if not np.all(isinstance(m, int) for m in mode_enums): + raise ValueError( + "mode_enums must be integers") + self._mode_enums = mode_enums + + @property + def coeffs(self): + """ndarray: All coefficients stacked into a single array.""" + return self._coeffs + + @coeffs.setter + def coeffs(self, c): + if c.shape != self._coeffs.shape: + raise ValueError("new coefficient array must match the existing " + "coefficient shape") + self._coeffs = c + + @property + def coeff_slices(self): + """List: List of coefficient slices.""" + return self._coeff_slices + + @property + def ndim(self): + """int: Number of data dimensions.""" + return self.coeffs.ndim + + @property + def ndim_transform(self): + """int: Number of axes transformed.""" + return len(self.axes) + + @property + def axes(self): + """List of str: The axes the transform was performed along.""" + return self._axes + + @property + def levels(self): + """List of int: Levels of decomposition along each transformed axis.""" + return [len(s) - 1 for s in self.coeff_slices] + + @property + def wavelets(self): + """List of pywt.DiscreteWavelet: wavelet for each transformed axis.""" + return self._wavelets + + @property + def wavelet_names(self): + """List of pywt.DiscreteWavelet: wavelet for each transformed axis.""" + return [w.name for w in self._wavelets] + + @property + def modes(self): + """List of str: The border mode used along each transformed axis.""" + names_dict = {getattr(Modes, mode): mode + for mode in Modes.modes} + return [names_dict[m] for m in self._mode_enums] + + def _get_coef_sl(self, levels): + sl = [slice(None), ] * self.ndim + for n, (ax, lev) in enumerate(zip(self.axes, levels)): + sl[ax] = self.coeff_slices[n][lev] + return tuple(sl) + + @property + def approx(self): + """ndarray: The approximation coefficients.""" + sl = self._get_coef_sl((0, )*self.ndim) + return self._coeffs[sl] + + @approx.setter + def approx(self, a): + sl = self._get_coef_sl((0, )*self.ndim) + if self._coeffs[sl].shape != a.shape: + raise ValueError( + "x does not match the shape of the requested coefficient") + self._coeffs[sl] = a + + def _validate_index(self, levels): + levels = tuple(levels) + + if len(levels) != len(self.axes): + raise ValueError( + "levels must match the number of transformed axes") + + # check that all elements are non-negative integers + if (not np.all([isinstance(lev, numbers.Number) for lev in levels]) or + np.any(np.asarray(levels) % 1 > 0) or + np.any([lev < 0 for lev in levels])): + raise ValueError("Index must be a tuple of non-negative integers") + # convert integer-valued floats to int + levels = tuple([int(lev) for lev in levels]) + + # check for out of range levels + if np.any([lev > maxlev for lev, maxlev in zip(levels, self.levels)]): + raise ValueError( + "Specified indices exceed the number of transform levels.") + + def __getitem__(self, levels): + """Retrieve a coefficient subband. + + Parameters + ---------- + levels : tuple of int + The number of degrees of decomposition along each transformed + axis. + """ + self._validate_index(levels) + sl = self._get_coef_sl(levels) + return self._coeffs[sl] + + def __setitem__(self, levels, x): + """Assign values to a coefficient subband. + + Parameters + ---------- + levels : tuple of int + The number of degrees of decomposition along each transformed + axis. + x : ndarray + The data corresponding to assign. It must match the expected + shape and dtype of the specified subband. + """ + self._validate_index(levels) + sl = self._get_coef_sl(levels) + current_dtype = self._coeffs[sl].dtype + if self._coeffs[sl].shape != x.shape: + raise ValueError( + "x does not match the shape of the requested coefficient") + if x.dtype != current_dtype: + warnings.warn("dtype mismatch: converting the provided array to" + f"dtype {current_dtype}") + self._coeffs[sl] = x + + def detail_keys(self): + """Return a list of all detail coefficient keys. + + Returns + ------- + keys : list of str + List of all detail coefficient keys. + """ + keys = list(product(*(range(l+1) for l in self.levels))) + keys.remove((0, )*len(self.axes)) + return sorted(keys) + + +def fswavedecn(data, wavelet, mode='symmetric', levels=None, axes=None): + """Fully Separable Wavelet Decomposition. + + This is a variant of the multilevel discrete wavelet transform where all + levels of decomposition are performed along a single axis prior to moving + onto the next axis. Unlike in ``wavedecn``, the number of levels of + decomposition are not required to be the same along each axis which can be + a benefit for anisotropic data. + + Parameters + ---------- + data: array_like + Input data + wavelet : Wavelet object or name string, or tuple of wavelets + Wavelet to use. This can also be a tuple containing a wavelet to + apply along each axis in ``axes``. + mode : str or tuple of str, optional + Signal extension mode, see :ref:`Modes `. This can + also be a tuple containing a mode to apply along each axis in ``axes``. + levels : int or sequence of ints, optional + Decomposition levels along each axis (must be >= 0). If an integer is + provided, the same number of levels are used for all axes. If + ``levels`` is None (default), ``dwt_max_level`` will be used to compute + the maximum number of levels possible for each axis. + axes : sequence of ints, optional + Axes over which to compute the transform. Axes may not be repeated. The + default is to transform along all axes. + + Returns + ------- + fswavedecn_result : FswavedecnResult object + Contains the wavelet coefficients, slice objects to allow obtaining + the coefficients per detail or approximation level, and more. + See ``FswavedecnResult`` for details. + + Examples + -------- + >>> import numpy as np + >>> from pywt import fswavedecn + >>> fs_result = fswavedecn(np.ones((32, 32)), 'sym2', levels=(1, 3)) + >>> print(fs_result.detail_keys()) + [(0, 1), (0, 2), (0, 3), (1, 0), (1, 1), (1, 2), (1, 3)] + >>> approx_coeffs = fs_result.approx + >>> detail_1_2 = fs_result[(1, 2)] + + + Notes + ----- + This transformation has been variously referred to as the (fully) separable + wavelet transform (e.g. refs [1]_, [3]_), the tensor-product wavelet + ([2]_) or the hyperbolic wavelet transform ([4]_). It is well suited to + data with anisotropic smoothness. + + In [2]_ it was demonstrated that fully separable transform performs at + least as well as the DWT for image compression. Computation time is a + factor 2 larger than that for the DWT. + + See Also + -------- + fswaverecn : inverse of fswavedecn + + References + ---------- + .. [1] PH Westerink. Subband Coding of Images. Ph.D. dissertation, Dept. + Elect. Eng., Inf. Theory Group, Delft Univ. Technol., Delft, The + Netherlands, 1989. (see Section 2.3) + http://resolver.tudelft.nl/uuid:a4d195c3-1f89-4d66-913d-db9af0969509 + + .. [2] CP Rosiene and TQ Nguyen. Tensor-product wavelet vs. Mallat + decomposition: A comparative analysis, in Proc. IEEE Int. Symp. + Circuits and Systems, Orlando, FL, Jun. 1999, pp. 431-434. + + .. [3] V Velisavljevic, B Beferull-Lozano, M Vetterli and PL Dragotti. + Directionlets: Anisotropic Multidirectional Representation With + Separable Filtering. IEEE Transactions on Image Processing, Vol. 15, + No. 7, July 2006. + + .. [4] RA DeVore, SV Konyagin and VN Temlyakov. "Hyperbolic wavelet + approximation," Constr. Approx. 14 (1998), 1-26. + """ + data = np.asarray(data) + if axes is None: + axes = tuple(np.arange(data.ndim)) + _check_fswavedecn_axes(data, axes) + + if levels is None or np.isscalar(levels): + levels = [levels, ] * len(axes) + if len(levels) != len(axes): + raise ValueError("levels must match the length of the axes list") + + modes = _modes_per_axis(mode, axes) + wavelets = _wavelets_per_axis(wavelet, axes) + + coeff_slices = [slice(None), ] * len(axes) + coeffs_arr = data + for ax_count, (ax, lev, wav, mode) in enumerate( + zip(axes, levels, wavelets, modes)): + coeffs = wavedec(coeffs_arr, wav, mode=mode, level=lev, axis=ax) + + # Slice objects for accessing coefficient subsets. + # These can be used to access specific detail coefficient arrays + # (e.g. as needed for inverse transformation via fswaverecn). + c_shapes = [c.shape[ax] for c in coeffs] + c_offsets = np.cumsum([0, ] + c_shapes) + coeff_slices[ax_count] = [ + slice(c_offsets[d], c_offsets[d+1]) for d in range(len(c_shapes))] + + # stack the coefficients from all levels into a single array + coeffs_arr = np.concatenate(coeffs, axis=ax) + + return FswavedecnResult(coeffs_arr, coeff_slices, wavelets, modes, axes) + + +def fswaverecn(fswavedecn_result): + """Fully Separable Inverse Wavelet Reconstruction. + + Parameters + ---------- + fswavedecn_result : FswavedecnResult object + FswavedecnResult object from ``fswavedecn``. + + Returns + ------- + reconstructed : ndarray + Array of reconstructed data. + + Notes + ----- + This transformation has been variously referred to as the (fully) separable + wavelet transform (e.g. refs [1]_, [3]_), the tensor-product wavelet + ([2]_) or the hyperbolic wavelet transform ([4]_). It is well suited to + data with anisotropic smoothness. + + In [2]_ it was demonstrated that the fully separable transform performs at + least as well as the DWT for image compression. Computation time is a + factor 2 larger than that for the DWT. + + See Also + -------- + fswavedecn : inverse of fswaverecn + + References + ---------- + .. [1] PH Westerink. Subband Coding of Images. Ph.D. dissertation, Dept. + Elect. Eng., Inf. Theory Group, Delft Univ. Technol., Delft, The + Netherlands, 1989. (see Section 2.3) + http://resolver.tudelft.nl/uuid:a4d195c3-1f89-4d66-913d-db9af0969509 + + .. [2] CP Rosiene and TQ Nguyen. Tensor-product wavelet vs. Mallat + decomposition: A comparative analysis, in Proc. IEEE Int. Symp. + Circuits and Systems, Orlando, FL, Jun. 1999, pp. 431-434. + + .. [3] V Velisavljevic, B Beferull-Lozano, M Vetterli and PL Dragotti. + Directionlets: Anisotropic Multidirectional Representation With + Separable Filtering. IEEE Transactions on Image Processing, Vol. 15, + No. 7, July 2006. + + .. [4] RA DeVore, SV Konyagin and VN Temlyakov. "Hyperbolic wavelet + approximation," Constr. Approx. 14 (1998), 1-26. + """ + coeffs_arr = fswavedecn_result.coeffs + coeff_slices = fswavedecn_result.coeff_slices + axes = fswavedecn_result.axes + modes = fswavedecn_result.modes + wavelets = fswavedecn_result.wavelets + + _check_fswavedecn_axes(coeffs_arr, axes) + if len(axes) != len(coeff_slices): + raise ValueError("dimension mismatch") + + arr = coeffs_arr + csl = [slice(None), ] * arr.ndim + # for ax_count, (ax, wav, mode) in reversed( + # list(enumerate(zip(axes, wavelets, modes)))): + for ax_count, (ax, wav, mode) in enumerate(zip(axes, wavelets, modes)): + coeffs = [] + for sl in coeff_slices[ax_count]: + csl[ax] = sl + coeffs.append(arr[tuple(csl)]) + csl[ax] = slice(None) + arr = waverec(coeffs, wav, mode=mode, axis=ax) + return arr diff --git a/.venv/lib/python3.12/site-packages/pywt/_pytest.py b/.venv/lib/python3.12/site-packages/pywt/_pytest.py new file mode 100644 index 0000000000000000000000000000000000000000..ef6afd5450697d33a53d81a2f351da09ab4f3af6 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/pywt/_pytest.py @@ -0,0 +1,74 @@ +"""common test-related code.""" +import multiprocessing +import os +import platform +import sys + +import numpy as np +import pytest + +__all__ = ['uses_matlab', # skip if pymatbridge and Matlab unavailable + 'uses_futures', # skip if futures unavailable + 'uses_pymatbridge', # skip if no PYWT_XSLOW environment variable + 'uses_precomputed', # skip if PYWT_XSLOW environment variable found + 'matlab_result_dict_cwt', # dict with precomputed Matlab dwt data + 'matlab_result_dict_dwt', # dict with precomputed Matlab cwt data + 'futures', # the futures module or None + 'max_workers', # the number of workers available to futures + 'size_set', # the set of Matlab tests to run + ] + +try: + from concurrent import futures + max_workers = multiprocessing.cpu_count() + futures_available = True +except ImportError: + futures_available = False + futures = None + max_workers = 1 + +# Check if running on Emscripten/WASM, and skip tests that require concurrency. +# Relevant issue: https://github.com/pyodide/pyodide/issues/237 +IS_WASM = (sys.platform == "emscripten") or (platform.machine() in ["wasm32", "wasm64"]) + + +# check if pymatbridge + MATLAB tests should be run +matlab_result_dict_dwt = None +matlab_result_dict_cwt = None +matlab_missing = True +use_precomputed = True +size_set = 'reduced' +if 'PYWT_XSLOW' in os.environ: + try: + from pymatbridge import Matlab + mlab = Matlab() + matlab_missing = False + use_precomputed = False + size_set = 'full' + except ImportError: + print("To run Matlab compatibility tests you need to have MathWorks " + "MATLAB, MathWorks Wavelet Toolbox and the pymatbridge Python " + "package installed.") +if use_precomputed: + # load dictionaries of precomputed results + data_dir = os.path.join(os.path.dirname(__file__), 'tests', 'data') + matlab_data_file_cwt = os.path.join( + data_dir, 'cwt_matlabR2015b_result.npz') + matlab_result_dict_cwt = np.load(matlab_data_file_cwt) + + matlab_data_file_dwt = os.path.join( + data_dir, 'dwt_matlabR2012a_result.npz') + matlab_result_dict_dwt = np.load(matlab_data_file_dwt) + +uses_futures = pytest.mark.skipif( + not futures_available or IS_WASM, + reason='futures is not available, or running via Pyodide/WASM.') + # not futures_available, reason='futures not available') +uses_matlab = pytest.mark.skipif( + matlab_missing, reason='pymatbridge and/or Matlab not available') +uses_pymatbridge = pytest.mark.skipif( + use_precomputed, + reason='PYWT_XSLOW set: skipping tests against precomputed Matlab results') +uses_precomputed = pytest.mark.skipif( + not use_precomputed, + reason='PYWT_XSLOW not set: test against precomputed matlab tests') diff --git a/.venv/lib/python3.12/site-packages/pywt/_pytesttester.py b/.venv/lib/python3.12/site-packages/pywt/_pytesttester.py new file mode 100644 index 0000000000000000000000000000000000000000..298ea3a09f384cbbf21c57db87c435f333edb32d --- /dev/null +++ b/.venv/lib/python3.12/site-packages/pywt/_pytesttester.py @@ -0,0 +1,158 @@ +""" +Pytest test running. + +This module implements the ``test()`` function for NumPy modules. The usual +boiler plate for doing that is to put the following in the module +``__init__.py`` file:: + + from pywt._pytesttester import PytestTester + test = PytestTester(__name__).test + del PytestTester + + +Warnings filtering and other runtime settings should be dealt with in the +``pytest.ini`` file in the pywt repo root. The behavior of the test depends on +whether or not that file is found as follows: + +* ``pytest.ini`` is present (develop mode) + All warnings except those explicily filtered out are raised as error. +* ``pytest.ini`` is absent (release mode) + DeprecationWarnings and PendingDeprecationWarnings are ignored, other + warnings are passed through. + +In practice, tests run from the PyWavelets repo are run in develop mode. That +includes the standard ``python runtests.py`` invocation. + +""" + +import os +import sys + +__all__ = ['PytestTester'] + + +def _show_pywt_info(): + import pywt + print(f"PyWavelets version {pywt.__version__}") + + +class PytestTester: + """ + Pytest test runner. + + This class is made available in ``pywt.testing``, and a test function + is typically added to a package's __init__.py like so:: + + from pywt.testing import PytestTester + test = PytestTester(__name__).test + del PytestTester + + Calling this test function finds and runs all tests associated with the + module and all its sub-modules. + + Attributes + ---------- + module_name : str + Full path to the package to test. + + Parameters + ---------- + module_name : module name + The name of the module to test. + + """ + def __init__(self, module_name): + self.module_name = module_name + + def __call__(self, label='fast', verbose=1, extra_argv=None, + doctests=False, coverage=False, durations=-1, tests=None): + """ + Run tests for module using pytest. + + Parameters + ---------- + label : {'fast', 'full'}, optional + Identifies the tests to run. When set to 'fast', tests decorated + with `pytest.mark.slow` are skipped, when 'full', the slow marker + is ignored. + verbose : int, optional + Verbosity value for test outputs, in the range 1-3. Default is 1. + extra_argv : list, optional + List with any extra arguments to pass to pytests. + doctests : bool, optional + .. note:: Not supported + coverage : bool, optional + If True, report coverage of NumPy code. Default is False. + Requires installation of (pip) pytest-cov. + durations : int, optional + If < 0, do nothing, If 0, report time of all tests, if > 0, + report the time of the slowest `timer` tests. Default is -1. + tests : test or list of tests + Tests to be executed with pytest '--pyargs' + + Returns + ------- + result : bool + Return True on success, false otherwise. + + Examples + -------- + >>> result = np.lib.test() #doctest: +SKIP + ... + 1023 passed, 2 skipped, 6 deselected, 1 xfailed in 10.39 seconds + >>> result + True + + """ + import pytest + + module = sys.modules[self.module_name] + module_path = os.path.abspath(module.__path__[0]) + + # setup the pytest arguments + pytest_args = ["-l"] + + # offset verbosity. The "-q" cancels a "-v". + pytest_args += ["-q"] + + # Filter out annoying import messages. Want these in both develop and + # release mode. + pytest_args += [ + "-W ignore:Not importing directory", + "-W ignore:numpy.dtype size changed", + "-W ignore:numpy.ufunc size changed", ] + + if doctests: + raise ValueError("Doctests not supported") + + if extra_argv: + pytest_args += list(extra_argv) + + if verbose > 1: + pytest_args += ["-" + "v"*(verbose - 1)] + + if coverage: + pytest_args += ["--cov=" + module_path] + + if label == "fast": + pytest_args += ["-m", "not slow"] + elif label != "full": + pytest_args += ["-m", label] + + if durations >= 0: + pytest_args += [f"--durations={durations}"] + + if tests is None: + tests = [self.module_name] + + pytest_args += ["--pyargs"] + list(tests) + + # run tests. + _show_pywt_info() + + try: + code = pytest.main(pytest_args) + except SystemExit as exc: + code = exc.code + + return code == 0 diff --git a/.venv/lib/python3.12/site-packages/pywt/_swt.py b/.venv/lib/python3.12/site-packages/pywt/_swt.py new file mode 100644 index 0000000000000000000000000000000000000000..5588b8f7c01ba006e76907ab7281b99e08c52914 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/pywt/_swt.py @@ -0,0 +1,757 @@ +import warnings +from itertools import product + +import numpy as np + +from ._extensions._dwt import idwt_single +from ._extensions._pywt import Modes, Wavelet, _check_dtype +from ._extensions._swt import swt as _swt +from ._extensions._swt import swt_axis as _swt_axis +from ._extensions._swt import swt_max_level +from ._multidim import idwt2, idwtn +from ._utils import AxisError, _as_wavelet, _wavelets_per_axis + +__all__ = ["swt", "swt_max_level", 'iswt', 'swt2', 'iswt2', 'swtn', 'iswtn'] + + +def _rescale_wavelet_filterbank(wavelet, sf): + wav = Wavelet(wavelet.name + 'r', + [np.asarray(f) * sf for f in wavelet.filter_bank]) + + # copy attributes from the original wavelet + wav.orthogonal = wavelet.orthogonal + wav.biorthogonal = wavelet.biorthogonal + return wav + + +def swt(data, wavelet, level=None, start_level=0, axis=-1, + trim_approx=False, norm=False): + """ + Multilevel 1D stationary wavelet transform. + + Parameters + ---------- + data : + Input signal + wavelet : + Wavelet to use (Wavelet object or name) + level : int, optional + The number of decomposition steps to perform. + start_level : int, optional + The level at which the decomposition will begin (it allows one to + skip a given number of transform steps and compute + coefficients starting from start_level) (default: 0). The output + always contains exactly ``level`` sets of coefficients, corresponding + to decomposition levels ``start_level + 1`` through + ``start_level + level``. + axis: int, optional + Axis over which to compute the SWT. If not given, the + last axis is used. + trim_approx : bool, optional + If True, approximation coefficients at the final level are retained. + norm : bool, optional + If True, transform is normalized so that the energy of the coefficients + will be equal to the energy of ``data``. In other words, + ``np.linalg.norm(data.ravel())`` will equal the norm of the + concatenated transform coefficients when ``trim_approx`` is True. + + Returns + ------- + coeffs : list + List of approximation and details coefficients pairs in order + similar to wavedec function:: + + [(cAn, cDn), ..., (cA2, cD2), (cA1, cD1)] + + where n equals input parameter ``level``. + + If ``start_level = m`` is given, then the beginning m steps are + skipped:: + + [(cAm+n, cDm+n), ..., (cAm+1, cDm+1)] + + If ``trim_approx`` is ``True``, then the output list is exactly as in + ``pywt.wavedec``, where the first coefficient in the list is the + approximation coefficient at the final level and the rest are the + detail coefficients:: + + [cAn, cDn, ..., cD2, cD1] + + Notes + ----- + The implementation here follows the "algorithm a-trous" and requires that + the signal length along the transformed axis be a multiple of ``2**level``. + If this is not the case, the user should pad up to an appropriate size + using a function such as ``numpy.pad``. + + A primary benefit of this transform in comparison to its decimated + counterpart (``pywt.wavedecn``), is that it is shift-invariant. This comes + at cost of redundancy in the transform (the size of the output coefficients + is larger than the input). + + When the following three conditions are true: + + 1. The wavelet is orthogonal + 2. ``swt`` is called with ``norm=True`` + 3. ``swt`` is called with ``trim_approx=True`` + + the transform has the following additional properties that may be + desirable in applications: + + 1. energy is conserved + 2. variance is partitioned across scales + + When used with ``norm=True``, this transform is closely related to the + maximal-overlap DWT (MODWT) as popularized for time-series analysis, + although the underlying implementation is slightly different from the one + published in [1]_. Specifically, the implementation used here requires a + signal that is a multiple of ``2**level`` in length. + + References + ---------- + .. [1] DB Percival and AT Walden. Wavelet Methods for Time Series Analysis. + Cambridge University Press, 2000. + """ + + + # accept array_like input; make a copy to ensure a contiguous array + dt = _check_dtype(data) + data = np.array(data, dtype=dt) + + wavelet = _as_wavelet(wavelet) + if norm: + if not wavelet.orthogonal: + warnings.warn( + "norm=True, but the wavelet is not orthogonal: \n" + "\tThe conditions for energy preservation are not satisfied.") + wavelet = _rescale_wavelet_filterbank(wavelet, 1/np.sqrt(2)) + + if axis < 0: + axis = axis + data.ndim + if not 0 <= axis < data.ndim: + raise AxisError("Axis greater than data dimensions") + + if level is None: + level = swt_max_level(data.shape[axis]) + + if data.ndim == 1: + ret = _swt(data, wavelet, level, start_level, trim_approx) + else: + ret = _swt_axis(data, wavelet, level, start_level, axis, trim_approx) + return ret + + +def iswt(coeffs, wavelet, norm=False, axis=-1): + """ + Multilevel 1D inverse discrete stationary wavelet transform. + + Parameters + ---------- + coeffs : array_like + Coefficients list of tuples:: + + [(cAn, cDn), ..., (cA2, cD2), (cA1, cD1)] + + where cA is approximation, cD is details. Index 1 corresponds to + ``start_level + 1`` from ``pywt.swt``. + wavelet : Wavelet object or name string + Wavelet to use + norm : bool, optional + Controls the normalization used by the inverse transform. This must + be set equal to the value that was used by ``pywt.swt`` to preserve the + energy of a round-trip transform. + + Returns + ------- + 1D array of reconstructed data. + + Examples + -------- + >>> import pywt + >>> coeffs = pywt.swt([1,2,3,4,5,6,7,8], 'db2', level=2) + >>> pywt.iswt(coeffs, 'db2') + array([ 1., 2., 3., 4., 5., 6., 7., 8.]) + """ + # copy to avoid modification of input data + # If swt was called with trim_approx=False, first element is a tuple + trim_approx = not isinstance(coeffs[0], (tuple, list)) + cA = coeffs[0] if trim_approx else coeffs[0][0] + if cA.ndim > 1: + # convert to swtn coefficient format and call iswtn + if trim_approx: + coeffs_nd = [cA] + [{'d': d} for d in coeffs[1:]] + else: + coeffs_nd = [{'a': a, 'd': d} for a, d in coeffs] + return iswtn(coeffs_nd, wavelet, axes=(axis,), norm=norm) + elif axis != 0 and axis != -1: + raise AxisError("Axis greater than data dimensions") + + if trim_approx: + coeffs = coeffs[1:] + + if cA.ndim != 1: + raise ValueError("iswt only supports 1D data") + + dt = _check_dtype(cA) + output = np.array(cA, dtype=dt, copy=True) + + # num_levels, equivalent to the decomposition level, n + num_levels = len(coeffs) + wavelet = _as_wavelet(wavelet) + if norm: + wavelet = _rescale_wavelet_filterbank(wavelet, np.sqrt(2)) + mode = Modes.from_object('periodization') + for j in range(num_levels, 0, -1): + step_size = int(pow(2, j-1)) + last_index = step_size + if trim_approx: + cD = coeffs[-j] + else: + _, cD = coeffs[-j] + cD = np.asarray(cD, dtype=_check_dtype(cD)) + if cD.dtype != output.dtype: + # upcast to a common dtype (float64 or complex128) + if output.dtype.kind == 'c' or cD.dtype.kind == 'c': + dtype = np.complex128 + else: + dtype = np.float64 + output = np.asarray(output, dtype=dtype) + cD = np.asarray(cD, dtype=dtype) + for first in range(last_index): # 0 to last_index - 1 + + # Getting the indices that we will transform + indices = np.arange(first, len(cD), step_size) + + # select the even indices + even_indices = indices[0::2] + # select the odd indices + odd_indices = indices[1::2] + + # perform the inverse dwt on the selected indices, + # making sure to use periodic boundary conditions + # Note: indexing with an array of ints returns a contiguous + # copy as required by idwt_single. + x1 = idwt_single(output[even_indices], + cD[even_indices], + wavelet, mode) + x2 = idwt_single(output[odd_indices], + cD[odd_indices], + wavelet, mode) + + # perform a circular shift right + x2 = np.roll(x2, 1) + + # average and insert into the correct indices + output[indices] = (x1 + x2)/2. + + return output + + +def swt2(data, wavelet, level, start_level=0, axes=(-2, -1), + trim_approx=False, norm=False): + """ + Multilevel 2D stationary wavelet transform. + + Parameters + ---------- + data : array_like + 2D array with input data + wavelet : Wavelet object or name string, or 2-tuple of wavelets + Wavelet to use. This can also be a tuple of wavelets to apply per + axis in ``axes``. + level : int + The number of decomposition steps to perform. + start_level : int, optional + The level at which the decomposition will start (default: 0) + axes : 2-tuple of ints, optional + Axes over which to compute the SWT. Repeated elements are not allowed. + trim_approx : bool, optional + If True, approximation coefficients at the final level are retained. + norm : bool, optional + If True, transform is normalized so that the energy of the coefficients + will be equal to the energy of ``data``. In other words, + ``np.linalg.norm(data.ravel())`` will equal the norm of the + concatenated transform coefficients when ``trim_approx`` is True. + + Returns + ------- + coeffs : list + Approximation and details coefficients (for ``start_level = m``). + If ``trim_approx`` is ``False``, approximation coefficients are + retained for all levels:: + + [ + (cA_m+level, + (cH_m+level, cV_m+level, cD_m+level) + ), + ..., + (cA_m+1, + (cH_m+1, cV_m+1, cD_m+1) + ) + ] + + where cA is approximation, cH is horizontal details, cV is + vertical details, cD is diagonal details and m is ``start_level``. + + If ``trim_approx`` is ``True``, approximation coefficients are only + retained at the final level of decomposition. This matches the format + used by ``pywt.wavedec2``:: + + [ + cA_m+level, + (cH_m+level, cV_m+level, cD_m+level), + ..., + (cH_m+1, cV_m+1, cD_m+1), + ] + + Notes + ----- + The implementation here follows the "algorithm a-trous" and requires that + the signal length along the transformed axes be a multiple of ``2**level``. + If this is not the case, the user should pad up to an appropriate size + using a function such as ``numpy.pad``. + + A primary benefit of this transform in comparison to its decimated + counterpart (``pywt.wavedecn``), is that it is shift-invariant. This comes + at cost of redundancy in the transform (the size of the output coefficients + is larger than the input). + + When the following three conditions are true: + + 1. The wavelet is orthogonal + 2. ``swt2`` is called with ``norm=True`` + 3. ``swt2`` is called with ``trim_approx=True`` + + the transform has the following additional properties that may be + desirable in applications: + + 1. energy is conserved + 2. variance is partitioned across scales + + """ + axes = tuple(axes) + data = np.asarray(data) + if len(axes) != 2: + raise ValueError("Expected 2 axes") + if len(axes) != len(set(axes)): + raise ValueError("The axes passed to swt2 must be unique.") + if data.ndim < len(np.unique(axes)): + raise ValueError("Input array has fewer dimensions than the specified " + "axes") + + coefs = swtn(data, wavelet, level, start_level, axes, trim_approx, norm) + ret = [] + if trim_approx: + ret.append(coefs[0]) + coefs = coefs[1:] + for c in coefs: + if trim_approx: + ret.append((c['da'], c['ad'], c['dd'])) + else: + ret.append((c['aa'], (c['da'], c['ad'], c['dd']))) + return ret + + +def iswt2(coeffs, wavelet, norm=False, axes=(-2, -1)): + """ + Multilevel 2D inverse discrete stationary wavelet transform. + + Parameters + ---------- + coeffs : list + Approximation and details coefficients:: + + [ + (cA_n, + (cH_n, cV_n, cD_n) + ), + ..., + (cA_2, + (cH_2, cV_2, cD_2) + ), + (cA_1, + (cH_1, cV_1, cD_1) + ) + ] + + where cA is approximation, cH is horizontal details, cV is + vertical details, cD is diagonal details and n is the number of + levels. Index 1 corresponds to ``start_level + 1`` from ``pywt.swt2``. + wavelet : Wavelet object or name string, or 2-tuple of wavelets + Wavelet to use. This can also be a 2-tuple of wavelets to apply per + axis. + norm : bool, optional + Controls the normalization used by the inverse transform. This must + be set equal to the value that was used by ``pywt.swt2`` to preserve + the energy of a round-trip transform. + + Returns + ------- + 2D array of reconstructed data. + + Examples + -------- + >>> import pywt + >>> coeffs = pywt.swt2([[1,2,3,4],[5,6,7,8], + ... [9,10,11,12],[13,14,15,16]], + ... 'db1', level=2) + >>> pywt.iswt2(coeffs, 'db1') + array([[ 1., 2., 3., 4.], + [ 5., 6., 7., 8.], + [ 9., 10., 11., 12.], + [ 13., 14., 15., 16.]]) + + """ + + # If swt was called with trim_approx=False, first element is a tuple + trim_approx = not isinstance(coeffs[0], (tuple, list)) + cA = coeffs[0] if trim_approx else coeffs[0][0] + if cA.ndim != 2 or axes != (-2, -1): + # convert to swtn coefficient format and call iswtn instead + if trim_approx: + coeffs_nd = [cA] + [{'da': h, 'ad': v, 'dd': d} + for h, v, d in coeffs[1:]] + else: + coeffs_nd = [{'aa': a, 'da': h, 'ad': v, 'dd': d} + for a, (h, v, d) in coeffs] + return iswtn(coeffs_nd, wavelet, axes=axes, norm=norm) + + if trim_approx: + coeffs = coeffs[1:] + + # copy to avoid modification of input data + dt = _check_dtype(cA) + output = np.array(cA, dtype=dt, copy=True) + + if output.ndim != 2: + raise ValueError( + "iswt2 only supports 2D arrays. see iswtn for a general " + "n-dimensionsal ISWT") + # num_levels, equivalent to the decomposition level, n + num_levels = len(coeffs) + wavelets = _wavelets_per_axis(wavelet, axes=(0, 1)) + if norm: + wavelets = [_rescale_wavelet_filterbank(wav, np.sqrt(2)) + for wav in wavelets] + + for j in range(num_levels): + step_size = int(pow(2, num_levels-j-1)) + last_index = step_size + if trim_approx: + (cH, cV, cD) = coeffs[j] + else: + _, (cH, cV, cD) = coeffs[j] + # We are going to assume cH, cV, and cD are of equal size + if (cH.shape != cV.shape) or (cH.shape != cD.shape): + raise RuntimeError( + "Mismatch in shape of intermediate coefficient arrays") + + # make sure output shares the common dtype + # (conversion of dtype for individual coeffs is handled within idwt2 ) + common_dtype = np.result_type(*( + [dt, ] + [_check_dtype(c) for c in [cH, cV, cD]])) + if output.dtype != common_dtype: + output = output.astype(common_dtype) + + for first_h in range(last_index): # 0 to last_index - 1 + for first_w in range(last_index): # 0 to last_index - 1 + # Getting the indices that we will transform + indices_h = slice(first_h, cH.shape[0], step_size) + indices_w = slice(first_w, cH.shape[1], step_size) + + even_idx_h = slice(first_h, cH.shape[0], 2*step_size) + even_idx_w = slice(first_w, cH.shape[1], 2*step_size) + odd_idx_h = slice(first_h + step_size, cH.shape[0], 2*step_size) + odd_idx_w = slice(first_w + step_size, cH.shape[1], 2*step_size) + + # perform the inverse dwt on the selected indices, + # making sure to use periodic boundary conditions + x1 = idwt2((output[even_idx_h, even_idx_w], + (cH[even_idx_h, even_idx_w], + cV[even_idx_h, even_idx_w], + cD[even_idx_h, even_idx_w])), + wavelets, 'periodization') + x2 = idwt2((output[even_idx_h, odd_idx_w], + (cH[even_idx_h, odd_idx_w], + cV[even_idx_h, odd_idx_w], + cD[even_idx_h, odd_idx_w])), + wavelets, 'periodization') + x3 = idwt2((output[odd_idx_h, even_idx_w], + (cH[odd_idx_h, even_idx_w], + cV[odd_idx_h, even_idx_w], + cD[odd_idx_h, even_idx_w])), + wavelets, 'periodization') + x4 = idwt2((output[odd_idx_h, odd_idx_w], + (cH[odd_idx_h, odd_idx_w], + cV[odd_idx_h, odd_idx_w], + cD[odd_idx_h, odd_idx_w])), + wavelets, 'periodization') + + # perform a circular shifts + x2 = np.roll(x2, 1, axis=1) + x3 = np.roll(x3, 1, axis=0) + x4 = np.roll(x4, 1, axis=0) + x4 = np.roll(x4, 1, axis=1) + output[indices_h, indices_w] = (x1 + x2 + x3 + x4) / 4 + + return output + + +def swtn(data, wavelet, level, start_level=0, axes=None, trim_approx=False, + norm=False): + """ + n-dimensional stationary wavelet transform. + + Parameters + ---------- + data : array_like + n-dimensional array with input data. + wavelet : Wavelet object or name string, or tuple of wavelets + Wavelet to use. This can also be a tuple of wavelets to apply per + axis in ``axes``. + level : int + The number of decomposition steps to perform. + start_level : int, optional + The level at which the decomposition will start (default: 0) + axes : sequence of ints, optional + Axes over which to compute the SWT. A value of ``None`` (the + default) selects all axes. Axes may not be repeated. + trim_approx : bool, optional + If True, approximation coefficients at the final level are retained. + norm : bool, optional + If True, transform is normalized so that the energy of the coefficients + will be equal to the energy of ``data``. In other words, + ``np.linalg.norm(data.ravel())`` will equal the norm of the + concatenated transform coefficients when ``trim_approx`` is True. + + Returns + ------- + [{coeffs_level_n}, ..., {coeffs_level_1}]: list of dict + Results for each level are arranged in a dictionary, where the key + specifies the transform type on each dimension and value is a + n-dimensional coefficients array. + + For example, for a 2D case the result at a given level will look + something like this:: + + {'aa': # A(LL) - approx. on 1st dim, approx. on 2nd dim + 'ad': # V(LH) - approx. on 1st dim, det. on 2nd dim + 'da': # H(HL) - det. on 1st dim, approx. on 2nd dim + 'dd': # D(HH) - det. on 1st dim, det. on 2nd dim + } + + For user-specified ``axes``, the order of the characters in the + dictionary keys map to the specified ``axes``. + + If ``trim_approx`` is ``True``, the first element of the list contains + the array of approximation coefficients from the final level of + decomposition, while the remaining coefficient dictionaries contain + only detail coefficients. This matches the behavior of `pywt.wavedecn`. + + Notes + ----- + The implementation here follows the "algorithm a-trous" and requires that + the signal length along the transformed axes be a multiple of ``2**level``. + If this is not the case, the user should pad up to an appropriate size + using a function such as ``numpy.pad``. + + A primary benefit of this transform in comparison to its decimated + counterpart (``pywt.wavedecn``), is that it is shift-invariant. This comes + at cost of redundancy in the transform (the size of the output coefficients + is larger than the input). + + When the following three conditions are true: + + 1. The wavelet is orthogonal + 2. ``swtn`` is called with ``norm=True`` + 3. ``swtn`` is called with ``trim_approx=True`` + + the transform has the following additional properties that may be + desirable in applications: + + 1. energy is conserved + 2. variance is partitioned across scales + + """ + data = np.asarray(data) + + if data.dtype == np.dtype('object'): + raise TypeError("Input must be a numeric array-like") + if data.ndim < 1: + raise ValueError("Input data must be at least 1D") + + if axes is None: + axes = range(data.ndim) + axes = [a + data.ndim if a < 0 else a for a in axes] + if any(a < 0 or a >= data.ndim for a in axes): + raise AxisError("Axis greater than data dimensions") + if len(axes) != len(set(axes)): + raise ValueError("The axes passed to swtn must be unique.") + num_axes = len(axes) + + wavelets = _wavelets_per_axis(wavelet, axes) + if norm: + if not np.all([wav.orthogonal for wav in wavelets]): + warnings.warn( + "norm=True, but the wavelets used are not orthogonal: \n" + "\tThe conditions for energy preservation are not satisfied.") + wavelets = [_rescale_wavelet_filterbank(wav, 1/np.sqrt(2)) + for wav in wavelets] + ret = [] + for i in range(start_level, start_level + level): + coeffs = [('', data)] + for axis, wavelet in zip(axes, wavelets): + new_coeffs = [] + for subband, x in coeffs: + cA, cD = _swt_axis(x, wavelet, level=1, start_level=i, + axis=axis)[0] + new_coeffs.extend([(subband + 'a', cA), + (subband + 'd', cD)]) + coeffs = new_coeffs + + coeffs = dict(coeffs) + ret.append(coeffs) + + # data for the next level is the approximation coeffs from this level + data = coeffs['a' * num_axes] + if trim_approx: + coeffs.pop('a' * num_axes) + if trim_approx: + ret.append(data) + ret.reverse() + return ret + + +def iswtn(coeffs, wavelet, axes=None, norm=False): + """ + Multilevel nD inverse discrete stationary wavelet transform. + + Parameters + ---------- + coeffs : list + [{coeffs_level_n}, ..., {coeffs_level_1}]: list of dict + wavelet : Wavelet object or name string, or tuple of wavelets + Wavelet to use. This can also be a tuple of wavelets to apply per + axis in ``axes``. + axes : sequence of ints, optional + Axes over which to compute the inverse SWT. Axes may not be repeated. + The default is ``None``, which means transform all axes + (``axes = range(data.ndim)``). + norm : bool, optional + Controls the normalization used by the inverse transform. This must + be set equal to the value that was used by ``pywt.swtn`` to preserve + the energy of a round-trip transform. + + Returns + ------- + nD array of reconstructed data. + + Examples + -------- + >>> import pywt + >>> coeffs = pywt.swtn([[1,2,3,4],[5,6,7,8], + ... [9,10,11,12],[13,14,15,16]], + ... 'db1', level=2) + >>> pywt.iswtn(coeffs, 'db1') + array([[ 1., 2., 3., 4.], + [ 5., 6., 7., 8.], + [ 9., 10., 11., 12.], + [ 13., 14., 15., 16.]]) + + """ + + # key length matches the number of axes transformed + ndim_transform = max(len(key) for key in coeffs[-1]) + trim_approx = not isinstance(coeffs[0], dict) + cA = coeffs[0] if trim_approx else coeffs[0]['a'*ndim_transform] + + + if trim_approx: + coeffs = coeffs[1:] + + # copy to avoid modification of input data + dt = _check_dtype(cA) + output = np.array(cA, dtype=dt, copy=True) + ndim = output.ndim + + if axes is None: + axes = range(output.ndim) + axes = [a + ndim if a < 0 else a for a in axes] + if len(axes) != len(set(axes)): + raise ValueError("The axes passed to swtn must be unique.") + if ndim_transform != len(axes): + raise ValueError("The number of axes used in iswtn must match the " + "number of dimensions transformed in swtn.") + + # num_levels, equivalent to the decomposition level, n + num_levels = len(coeffs) + wavelets = _wavelets_per_axis(wavelet, axes) + if norm: + wavelets = [_rescale_wavelet_filterbank(wav, np.sqrt(2)) + for wav in wavelets] + + # initialize various slice objects used in the loops below + # these will remain slice(None) only on axes that aren't transformed + indices = [slice(None), ]*ndim + even_indices = [slice(None), ]*ndim + odd_indices = [slice(None), ]*ndim + odd_even_slices = [slice(None), ]*ndim + + for j in range(num_levels): + step_size = int(pow(2, num_levels-j-1)) + last_index = step_size + if not trim_approx: + a = coeffs[j].pop('a'*ndim_transform) # will restore later + details = coeffs[j] + # make sure dtype matches the coarsest level approximation coefficients + common_dtype = np.result_type(*( + [dt, ] + [v.dtype for v in details.values()])) + if output.dtype != common_dtype: + output = output.astype(common_dtype) + + # We assume all coefficient arrays are of equal size + shapes = [v.shape for k, v in details.items()] + if len(set(shapes)) != 1: + raise RuntimeError( + "Mismatch in shape of intermediate coefficient arrays") + + # shape of a single coefficient array, excluding non-transformed axes + coeff_trans_shape = tuple([shapes[0][ax] for ax in axes]) + + # nested loop over all combinations of axis offsets at this level + for firsts in product(*([range(last_index), ]*ndim_transform)): + for first, sh, ax in zip(firsts, coeff_trans_shape, axes): + indices[ax] = slice(first, sh, step_size) + even_indices[ax] = slice(first, sh, 2*step_size) + odd_indices[ax] = slice(first+step_size, sh, 2*step_size) + + # nested loop over all combinations of odd/even inidices + approx = output.copy() + output[tuple(indices)] = 0 + ntransforms = 0 + for odds in product(*([(0, 1), ]*ndim_transform)): + for o, ax in zip(odds, axes): + if o: + odd_even_slices[ax] = odd_indices[ax] + else: + odd_even_slices[ax] = even_indices[ax] + # extract the odd/even indices for all detail coefficients + details_slice = {} + for key, value in details.items(): + details_slice[key] = value[tuple(odd_even_slices)] + details_slice['a'*ndim_transform] = approx[ + tuple(odd_even_slices)] + + # perform the inverse dwt on the selected indices, + # making sure to use periodic boundary conditions + x = idwtn(details_slice, wavelets, 'periodization', axes=axes) + for o, ax in zip(odds, axes): + # circular shift along any odd indexed axis + if o: + x = np.roll(x, 1, axis=ax) + output[tuple(indices)] += x + ntransforms += 1 + output[tuple(indices)] /= ntransforms # normalize + if not trim_approx: + coeffs[j]['a'*ndim_transform] = a # restore approx coeffs to dict + return output diff --git a/.venv/lib/python3.12/site-packages/pywt/_thresholding.py b/.venv/lib/python3.12/site-packages/pywt/_thresholding.py new file mode 100644 index 0000000000000000000000000000000000000000..33af65b843b5b1a9988a562271a1701285bb4af9 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/pywt/_thresholding.py @@ -0,0 +1,249 @@ +# Copyright (c) 2006-2012 Filip Wasilewski +# Copyright (c) 2012-2016 The PyWavelets Developers +# +# See COPYING for license details. + +""" +The thresholding helper module implements the most popular signal thresholding +functions. +""" + +import numpy as np + +__all__ = ['threshold', 'threshold_firm'] + + +def soft(data, value, substitute=0): + data = np.asarray(data) + magnitude = np.absolute(data) + + with np.errstate(divide='ignore'): + # divide by zero okay as np.inf values get clipped, so ignore warning. + thresholded = (1 - value/magnitude) + thresholded.clip(min=0, max=None, out=thresholded) + thresholded = data * thresholded + + if substitute == 0: + return thresholded + else: + cond = np.less(magnitude, value) + return np.where(cond, substitute, thresholded) + + +def nn_garrote(data, value, substitute=0): + """Non-negative Garrote.""" + data = np.asarray(data) + magnitude = np.absolute(data) + + with np.errstate(divide='ignore'): + # divide by zero okay as np.inf values get clipped, so ignore warning. + thresholded = (1 - value**2/magnitude**2) + thresholded.clip(min=0, max=None, out=thresholded) + thresholded = data * thresholded + + if substitute == 0: + return thresholded + else: + cond = np.less(magnitude, value) + return np.where(cond, substitute, thresholded) + + +def hard(data, value, substitute=0): + data = np.asarray(data) + cond = np.less(np.absolute(data), value) + return np.where(cond, substitute, data) + + +def greater(data, value, substitute=0): + data = np.asarray(data) + if np.iscomplexobj(data): + raise ValueError("greater thresholding only supports real data") + return np.where(np.less(data, value), substitute, data) + + +def less(data, value, substitute=0): + data = np.asarray(data) + if np.iscomplexobj(data): + raise ValueError("less thresholding only supports real data") + return np.where(np.greater(data, value), substitute, data) + + +thresholding_options = {'soft': soft, + 'hard': hard, + 'greater': greater, + 'less': less, + 'garrote': nn_garrote, + # misspelled garrote for backwards compatibility + 'garotte': nn_garrote, + } + + +def threshold(data, value, mode='soft', substitute=0): + """ + Thresholds the input data depending on the mode argument. + + In ``soft`` thresholding [1]_, data values with absolute value less than + `param` are replaced with `substitute`. Data values with absolute value + greater or equal to the thresholding value are shrunk toward zero + by `value`. In other words, the new value is + ``data/np.abs(data) * np.maximum(np.abs(data) - value, 0)``. + + In ``hard`` thresholding, the data values where their absolute value is + less than the value param are replaced with `substitute`. Data values with + absolute value greater or equal to the thresholding value stay untouched. + + ``garrote`` corresponds to the Non-negative garrote threshold [2]_, [3]_. + It is intermediate between ``hard`` and ``soft`` thresholding. It behaves + like soft thresholding for small data values and approaches hard + thresholding for large data values. + + In ``greater`` thresholding, the data is replaced with `substitute` where + data is below the thresholding value. Greater data values pass untouched. + + In ``less`` thresholding, the data is replaced with `substitute` where data + is above the thresholding value. Lesser data values pass untouched. + + Both ``hard`` and ``soft`` thresholding also support complex-valued data. + + Parameters + ---------- + data : array_like + Numeric data. + value : scalar + Thresholding value. + mode : {'soft', 'hard', 'garrote', 'greater', 'less'} + Decides the type of thresholding to be applied on input data. Default + is 'soft'. + substitute : float, optional + Substitute value (default: 0). + + Returns + ------- + output : array + Thresholded array. + + See Also + -------- + threshold_firm + + References + ---------- + .. [1] D.L. Donoho and I.M. Johnstone. Ideal Spatial Adaptation via + Wavelet Shrinkage. Biometrika. Vol. 81, No. 3, pp.425-455, 1994. + DOI:10.1093/biomet/81.3.425 + .. [2] L. Breiman. Better Subset Regression Using the Nonnegative Garrote. + Technometrics, Vol. 37, pp. 373-384, 1995. + DOI:10.2307/1269730 + .. [3] H-Y. Gao. Wavelet Shrinkage Denoising Using the Non-Negative + Garrote. Journal of Computational and Graphical Statistics Vol. 7, + No. 4, pp.469-488. 1998. + DOI:10.1080/10618600.1998.10474789 + + Examples + -------- + >>> import numpy as np + >>> import pywt + >>> data = np.linspace(1, 4, 7) + >>> data + array([ 1. , 1.5, 2. , 2.5, 3. , 3.5, 4. ]) + >>> pywt.threshold(data, 2, 'soft') + array([ 0. , 0. , 0. , 0.5, 1. , 1.5, 2. ]) + >>> pywt.threshold(data, 2, 'hard') + array([ 0. , 0. , 2. , 2.5, 3. , 3.5, 4. ]) + >>> pywt.threshold(data, 2, 'garrote') + array([ 0. , 0. , 0. , 0.9 , 1.66666667, + 2.35714286, 3. ]) + >>> pywt.threshold(data, 2, 'greater') + array([ 0. , 0. , 2. , 2.5, 3. , 3.5, 4. ]) + >>> pywt.threshold(data, 2, 'less') + array([ 1. , 1.5, 2. , 0. , 0. , 0. , 0. ]) + + """ + + try: + return thresholding_options[mode](data, value, substitute) + except KeyError: + # Make sure error is always identical by sorting keys + keys = (f"'{key}'" for key in + sorted(thresholding_options.keys())) + raise ValueError("The mode parameter only takes values from: {}." + .format(', '.join(keys))) + + +def threshold_firm(data, value_low, value_high): + """Firm threshold. + + The approach is intermediate between soft and hard thresholding [1]_. It + behaves the same as soft-thresholding for values below `value_low` and + the same as hard-thresholding for values above `thresh_high`. For + intermediate values, the thresholded value is in between that corresponding + to soft or hard thresholding. + + Parameters + ---------- + data : array-like + The data to threshold. This can be either real or complex-valued. + value_low : float + Any values smaller then `value_low` will be set to zero. + value_high : float + Any values larger than `value_high` will not be modified. + + Notes + ----- + This thresholding technique is also known as semi-soft thresholding [2]_. + + For each value, `x`, in `data`. This function computes:: + + if np.abs(x) <= value_low: + return 0 + elif np.abs(x) > value_high: + return x + elif value_low < np.abs(x) and np.abs(x) <= value_high: + return x * value_high * (1 - value_low/x)/(value_high - value_low) + + ``firm`` is a continuous function (like soft thresholding), but is + unbiased for large values (like hard thresholding). + + If ``value_high == value_low`` this function becomes hard-thresholding. + If ``value_high`` is infinity, this function becomes soft-thresholding. + + Returns + ------- + val_new : array-like + The values after firm thresholding at the specified thresholds. + + See Also + -------- + threshold + + References + ---------- + .. [1] H.-Y. Gao and A.G. Bruce. Waveshrink with firm shrinkage. + Statistica Sinica, Vol. 7, pp. 855-874, 1997. + .. [2] A. Bruce and H-Y. Gao. WaveShrink: Shrinkage Functions and + Thresholds. Proc. SPIE 2569, Wavelet Applications in Signal and + Image Processing III, 1995. + DOI:10.1117/12.217582 + """ + + if value_low < 0: + raise ValueError("value_low must be non-negative.") + + if value_high < value_low: + raise ValueError( + "value_high must be greater than or equal to value_low.") + + data = np.asarray(data) + magnitude = np.absolute(data) + with np.errstate(divide='ignore'): + # divide by zero okay as np.inf values get clipped, so ignore warning. + vdiff = value_high - value_low + thresholded = value_high * (1 - value_low/magnitude) / vdiff + thresholded.clip(min=0, max=None, out=thresholded) + thresholded = data * thresholded + + # restore hard-thresholding behavior for values > value_high + large_vals = np.where(magnitude > value_high) + if np.any(large_vals[0]): + thresholded[large_vals] = data[large_vals] + return thresholded diff --git a/.venv/lib/python3.12/site-packages/pywt/_utils.py b/.venv/lib/python3.12/site-packages/pywt/_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..c7dfcb6de5f567fe7654b9ee306c6e5c6011be40 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/pywt/_utils.py @@ -0,0 +1,104 @@ +# Copyright (c) 2017 The PyWavelets Developers +# +# See COPYING for license details. +import inspect +from collections.abc import Iterable + +import numpy as np + +from ._extensions._pywt import ( + ContinuousWavelet, + DiscreteContinuousWavelet, + Modes, + Wavelet, +) + +AxisError: type[Exception] +if np.lib.NumpyVersion(np.__version__) >= '1.25.0': + from numpy.exceptions import AxisError +else: + from numpy import AxisError + + +def _as_wavelet(wavelet): + """Convert wavelet name to a Wavelet object.""" + if not isinstance(wavelet, (ContinuousWavelet, Wavelet)): + wavelet = DiscreteContinuousWavelet(wavelet) + if isinstance(wavelet, ContinuousWavelet): + raise ValueError( + "A ContinuousWavelet object was provided, but only discrete " + "Wavelet objects are supported by this function. A list of all " + "supported discrete wavelets can be obtained by running:\n" + "print(pywt.wavelist(kind='discrete'))") + return wavelet + + +def _wavelets_per_axis(wavelet, axes): + """Initialize Wavelets for each axis to be transformed. + + Parameters + ---------- + wavelet : Wavelet or tuple of Wavelets + If a single Wavelet is provided, it will used for all axes. Otherwise + one Wavelet per axis must be provided. + axes : list + The tuple of axes to be transformed. + + Returns + ------- + wavelets : list of Wavelet objects + A tuple of Wavelets equal in length to ``axes``. + + """ + axes = tuple(axes) + if isinstance(wavelet, (str, Wavelet)): + # same wavelet on all axes + wavelets = [_as_wavelet(wavelet), ] * len(axes) + elif isinstance(wavelet, Iterable): + # (potentially) unique wavelet per axis (e.g. for dual-tree DWT) + if len(wavelet) == 1: + wavelets = [_as_wavelet(wavelet[0]), ] * len(axes) + else: + if len(wavelet) != len(axes): + raise ValueError( + "The number of wavelets must match the number of axes " + "to be transformed.") + wavelets = [_as_wavelet(w) for w in wavelet] + else: + raise ValueError("wavelet must be a str, Wavelet or iterable") + return wavelets + + +def _modes_per_axis(modes, axes): + """Initialize mode for each axis to be transformed. + + Parameters + ---------- + modes : str or tuple of strings + If a single mode is provided, it will used for all axes. Otherwise + one mode per axis must be provided. + axes : tuple + The tuple of axes to be transformed. + + Returns + ------- + modes : tuple of int + A tuple of Modes equal in length to ``axes``. + + """ + axes = tuple(axes) + if isinstance(modes, (int, str)): + # same wavelet on all axes + modes = [Modes.from_object(modes), ] * len(axes) + elif isinstance(modes, Iterable): + if len(modes) == 1: + modes = [Modes.from_object(modes[0]), ] * len(axes) + else: + # (potentially) unique wavelet per axis (e.g. for dual-tree DWT) + if len(modes) != len(axes): + raise ValueError("The number of modes must match the number " + "of axes to be transformed.") + modes = [Modes.from_object(mode) for mode in modes] + else: + raise ValueError("modes must be a str, Mode enum or iterable") + return modes diff --git a/.venv/lib/python3.12/site-packages/pywt/_wavelet_packets.py b/.venv/lib/python3.12/site-packages/pywt/_wavelet_packets.py new file mode 100644 index 0000000000000000000000000000000000000000..787df4431e525340ac445cb2668a3302c4015f10 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/pywt/_wavelet_packets.py @@ -0,0 +1,1054 @@ +# Copyright (c) 2006-2012 Filip Wasilewski +# Copyright (c) 2012-2016 The PyWavelets Developers +# +# See COPYING for license details. + +"""1D and 2D Wavelet packet transform module.""" + + +__all__ = ["BaseNode", "Node", "WaveletPacket", "Node2D", "WaveletPacket2D", + "NodeND", "WaveletPacketND"] + +from collections import OrderedDict +from itertools import product + +import numpy as np + +from ._dwt import dwt, dwt_max_level, idwt +from ._extensions._pywt import Wavelet, _check_dtype +from ._multidim import dwt2, dwtn, idwt2, idwtn + + +def get_graycode_order(level, x='a', y='d'): + graycode_order = [x, y] + for i in range(level - 1): + graycode_order = [x + path for path in graycode_order] + \ + [y + path for path in graycode_order[::-1]] + return graycode_order + + +class BaseNode: + """ + BaseNode for wavelet packet 1D and 2D tree nodes. + + The BaseNode is a base class for `Node` and `Node2D`. + It should not be used directly unless creating a new transformation + type. It is included here to document the common interface of 1D + and 2D node and wavelet packet transform classes. + + Parameters + ---------- + parent : + Parent node. If parent is None then the node is considered detached + (ie root). + data : 1D or 2D array + Data associated with the node. 1D or 2D numeric array, depending on the + transform type. + node_name : + A name identifying the coefficients type. + See `Node.node_name` and `Node2D.node_name` + for information on the accepted subnodes names. + """ + + # PART_LEN and PARTS attributes that define path tokens for node[] lookup + # must be defined in subclasses. + PART_LEN = None + PARTS = None + + def __init__(self, parent, data, node_name): + self.parent = parent + if parent is not None: + self.wavelet = parent.wavelet + self.mode = parent.mode + self.level = parent.level + 1 + self._maxlevel = parent.maxlevel + self.path = parent.path + node_name + self.axes = parent.axes + else: + self.wavelet = None + self.mode = None + self.axes = None + self.path = "" + self.level = 0 + + # data - signal on level 0, coeffs on higher levels + self.data = data + # Need to retain original data size/shape so we can trim any excess + # boundary coefficients from the inverse transform. + if self.data is None: + self._data_shape = None + else: + self._data_shape = np.asarray(data).shape + + self._init_subnodes() + + def _init_subnodes(self): + for part in self.PARTS: + self._set_node(part, None) + + def _create_subnode(self, part, data=None, overwrite=True): + raise NotImplementedError() + + def _create_subnode_base(self, node_cls, part, data=None, overwrite=True, + **kwargs): + self._validate_node_name(part) + if not overwrite and self._get_node(part) is not None: + return self._get_node(part) + node = node_cls(self, data, part, **kwargs) + self._set_node(part, node) + return node + + def _get_node(self, part): + return getattr(self, part) + + def _set_node(self, part, node): + setattr(self, part, node) + + def _delete_node(self, part): + self._set_node(part, None) + + def _validate_node_name(self, part): + if part not in self.PARTS: + raise ValueError("Subnode name must be in [{}], not '{}'.".format(', '.join("'%s'" % p for p in self.PARTS), part)) + + @property + def path_tuple(self): + """The path to the current node in tuple form. + + The length of the tuple is equal to the number of decomposition levels. + """ + path = self.path + nlev = len(path)//self.PART_LEN + return tuple([path[(n-1)*self.PART_LEN:n*self.PART_LEN] + for n in range(1, nlev+1)]) + + def _evaluate_maxlevel(self, evaluate_from='parent'): + """ + Try to find the value of maximum decomposition level if it is not + specified explicitly. + + Parameters + ---------- + evaluate_from : {'parent', 'subnodes'} + """ + assert evaluate_from in ('parent', 'subnodes') + + if self._maxlevel is not None: + return self._maxlevel + elif self.data is not None: + return self.level + dwt_max_level( + min(self.data.shape), self.wavelet) + + if evaluate_from == 'parent': + if self.parent is not None: + return self.parent._evaluate_maxlevel(evaluate_from) + elif evaluate_from == 'subnodes': + for node_name in self.PARTS: + node = getattr(self, node_name, None) + if node is not None: + level = node._evaluate_maxlevel(evaluate_from) + if level is not None: + return level + return None + + @property + def maxlevel(self): + if self._maxlevel is not None: + return self._maxlevel + + # Try getting the maxlevel from parents first + self._maxlevel = self._evaluate_maxlevel(evaluate_from='parent') + + # If not found, check whether it can be evaluated from subnodes + if self._maxlevel is None: + self._maxlevel = self._evaluate_maxlevel(evaluate_from='subnodes') + return self._maxlevel + + @property + def node_name(self): + return self.path[-self.PART_LEN:] + + def decompose(self): + """ + Decompose node data creating DWT coefficients subnodes. + + Performs Discrete Wavelet Transform on the `~BaseNode.data` and + returns transform coefficients. + + Note + ---- + Descends to subnodes and recursively + calls `~BaseNode.reconstruct` on them. + + """ + if self.level < self.maxlevel: + return self._decompose() + else: + raise ValueError("Maximum decomposition level reached.") + + def _decompose(self): + raise NotImplementedError() + + def reconstruct(self, update=False): + """ + Reconstruct node from subnodes. + + Parameters + ---------- + update : bool, optional + If True, then reconstructed data replaces the current + node data (default: False). + + Returns: + - original node data if subnodes do not exist + - IDWT of subnodes otherwise. + """ + if not self.has_any_subnode: + return self.data + return self._reconstruct(update) + + def _reconstruct(self): + raise NotImplementedError() # override this in subclasses + + def get_subnode(self, part, decompose=True): + """ + Returns subnode or None (see `decomposition` flag description). + + Parameters + ---------- + part : + Subnode name + decompose : bool, optional + If the param is True and corresponding subnode does not + exist, the subnode will be created using coefficients + from the DWT decomposition of the current node. + (default: True) + """ + self._validate_node_name(part) + subnode = self._get_node(part) + if subnode is None and decompose and not self.is_empty: + self.decompose() + subnode = self._get_node(part) + return subnode + + def __getitem__(self, path): + """ + Find node represented by the given path. + + Similar to `~BaseNode.get_subnode` method with `decompose=True`, but + can access nodes on any level in the decomposition tree. + + Parameters + ---------- + path : str + String composed of node names. See `Node.node_name` and + `Node2D.node_name` for node naming convention. + + Notes + ----- + If node does not exist yet, it will be created by decomposition of its + parent node. + """ + errmsg = ("Invalid path parameter type - expected string or " + "tuple of strings but got %s." % type(path)) + if isinstance(path, tuple): + # concatenate tuple of strings into a single string + try: + path = ''.join(path) + except TypeError: + raise TypeError(errmsg) + if isinstance(path, str): + if (self.maxlevel is not None and + len(path) > self.maxlevel * self.PART_LEN): + raise IndexError("Path length is out of range.") + if path: + return self.get_subnode(path[0:self.PART_LEN], True)[ + path[self.PART_LEN:]] + else: + return self + else: + raise TypeError(errmsg) + + def __setitem__(self, path, data): + """ + Set node or node's data in the decomposition tree. Nodes are + identified by string `path`. + + Parameters + ---------- + path : str + String composed of node names. + data : array or BaseNode subclass. + """ + + if isinstance(path, str): + if ( + self.maxlevel is not None and + len(self.path) + len(path) > self.maxlevel * self.PART_LEN + ): + raise IndexError("Path length out of range.") + if path: + subnode = self.get_subnode(path[0:self.PART_LEN], False) + if subnode is None: + self._create_subnode(path[0:self.PART_LEN], None) + subnode = self.get_subnode(path[0:self.PART_LEN], False) + subnode[path[self.PART_LEN:]] = data + else: + if isinstance(data, BaseNode): + self.data = np.asarray(data.data) + else: + self.data = np.asarray(data) + # convert data to nearest supported dtype + dtype = _check_dtype(data) + if self.data.dtype != dtype: + self.data = self.data.astype(dtype) + else: + raise TypeError("Invalid path parameter type - expected string but" + " got %s." % type(path)) + + def __delitem__(self, path): + """ + Remove node from the tree. + + Parameters + ---------- + path : str + String composed of node names. + """ + node = self[path] + # don't clear node value and subnodes (node may still exist outside + # the tree) + # # node._init_subnodes() + # # node.data = None + parent = node.parent + node.parent = None # TODO + if parent and node.node_name: + parent._delete_node(node.node_name) + + @property + def is_empty(self): + return self.data is None + + @property + def has_any_subnode(self): + return any(self._get_node(part) is not None for part in self.PARTS) + + def get_leaf_nodes(self, decompose=False): + """ + Returns leaf nodes. + + Parameters + ---------- + decompose : bool, optional + (default: True) + """ + result = [] + + def collect(node): + if node.level == node.maxlevel and not node.is_empty: + result.append(node) + return False + if not decompose and not node.has_any_subnode: + result.append(node) + return False + return True + self.walk(collect, decompose=decompose) + return result + + def walk(self, func, args=(), kwargs=None, decompose=True): + """ + Traverses the decomposition tree and calls + ``func(node, *args, **kwargs)`` on every node. If `func` returns True, + descending to subnodes will continue. + + Parameters + ---------- + func : callable + Callable accepting `BaseNode` as the first param and + optional positional and keyword arguments + args : + func params + kwargs : + func keyword params + decompose : bool, optional + If True (default), the method will also try to decompose the tree + up to the `maximum level `. + """ + if kwargs is None: + kwargs = {} + if func(self, *args, **kwargs) and self.level < self.maxlevel: + for part in self.PARTS: + subnode = self.get_subnode(part, decompose) + if subnode is not None: + subnode.walk(func, args, kwargs, decompose) + + def walk_depth(self, func, args=(), kwargs=None, decompose=True): + """ + Walk tree and call func on every node starting from the bottom-most + nodes. + + Parameters + ---------- + func : callable + Callable accepting :class:`BaseNode` as the first param and + optional positional and keyword arguments + args : + func params + kwargs : + func keyword params + decompose : bool, optional + (default: False) + """ + if kwargs is None: + kwargs = {} + if self.level < self.maxlevel: + for part in self.PARTS: + subnode = self.get_subnode(part, decompose) + if subnode is not None: + subnode.walk_depth(func, args, kwargs, decompose) + func(self, *args, **kwargs) + + def __str__(self): + return self.path + ": " + str(self.data) + + +class Node(BaseNode): + """ + WaveletPacket tree node. + + Subnodes are called `a` and `d`, just like approximation + and detail coefficients in the Discrete Wavelet Transform. + """ + + A = 'a' + D = 'd' + PARTS = A, D + PART_LEN = 1 + + def _create_subnode(self, part, data=None, overwrite=True): + return self._create_subnode_base(node_cls=Node, part=part, data=data, + overwrite=overwrite) + + def _decompose(self): + """ + + See also + -------- + dwt : for 1D Discrete Wavelet Transform output coefficients. + """ + if self.is_empty: + data_a, data_d = None, None + if self._get_node(self.A) is None: + self._create_subnode(self.A, data_a) + if self._get_node(self.D) is None: + self._create_subnode(self.D, data_d) + else: + data_a, data_d = dwt(self.data, self.wavelet, self.mode, + axis=self.axes) + self._create_subnode(self.A, data_a) + self._create_subnode(self.D, data_d) + return self._get_node(self.A), self._get_node(self.D) + + def _reconstruct(self, update): + data_a, data_d = None, None + node_a, node_d = self._get_node(self.A), self._get_node(self.D) + + if node_a is not None: + data_a = node_a.reconstruct() # TODO: (update) ??? + if node_d is not None: + data_d = node_d.reconstruct() # TODO: (update) ??? + + if data_a is None and data_d is None: + raise ValueError("Node is a leaf node and cannot be reconstructed" + " from subnodes.") + else: + rec = idwt(data_a, data_d, self.wavelet, self.mode, axis=self.axes) + if self._data_shape is not None and ( + rec.shape != self._data_shape): + rec = rec[tuple([slice(sz) for sz in self._data_shape])] + if update: + self.data = rec + return rec + + +class Node2D(BaseNode): + """ + WaveletPacket tree node. + + Subnodes are called 'a' (LL), 'h' (HL), 'v' (LH) and 'd' (HH), like + approximation and detail coefficients in the 2D Discrete Wavelet Transform + """ + + LL = 'a' + HL = 'h' + LH = 'v' + HH = 'd' + + PARTS = LL, HL, LH, HH + PART_LEN = 1 + + def _create_subnode(self, part, data=None, overwrite=True): + return self._create_subnode_base(node_cls=Node2D, part=part, data=data, + overwrite=overwrite) + + def _decompose(self): + """ + See also + -------- + dwt2 : for 2D Discrete Wavelet Transform output coefficients. + """ + if self.is_empty: + data_ll, data_lh, data_hl, data_hh = None, None, None, None + else: + data_ll, (data_hl, data_lh, data_hh) =\ + dwt2(self.data, self.wavelet, self.mode, axes=self.axes) + self._create_subnode(self.LL, data_ll) + self._create_subnode(self.LH, data_lh) + self._create_subnode(self.HL, data_hl) + self._create_subnode(self.HH, data_hh) + return (self._get_node(self.LL), self._get_node(self.HL), + self._get_node(self.LH), self._get_node(self.HH)) + + def _reconstruct(self, update): + data_ll, data_lh, data_hl, data_hh = None, None, None, None + + node_ll, node_lh, node_hl, node_hh =\ + self._get_node(self.LL), self._get_node(self.LH),\ + self._get_node(self.HL), self._get_node(self.HH) + + if node_ll is not None: + data_ll = node_ll.reconstruct() + if node_lh is not None: + data_lh = node_lh.reconstruct() + if node_hl is not None: + data_hl = node_hl.reconstruct() + if node_hh is not None: + data_hh = node_hh.reconstruct() + + if (data_ll is None and data_lh is None and + data_hl is None and data_hh is None): + raise ValueError( + "Tree is missing data - all subnodes of `%s` node " + "are None. Cannot reconstruct node." % self.path + ) + else: + coeffs = data_ll, (data_hl, data_lh, data_hh) + rec = idwt2(coeffs, self.wavelet, self.mode, axes=self.axes) + if self._data_shape is not None and ( + rec.shape != self._data_shape): + rec = rec[tuple([slice(sz) for sz in self._data_shape])] + if update: + self.data = rec + return rec + + def expand_2d_path(self, path): + expanded_paths = { + self.HH: 'hh', + self.HL: 'hl', + self.LH: 'lh', + self.LL: 'll' + } + return (''.join([expanded_paths[p][0] for p in path]), + ''.join([expanded_paths[p][1] for p in path])) + + +class NodeND(BaseNode): + """ + WaveletPacket tree node. + + Unlike Node and Node2D self.PARTS is a dictionary. + For 1D: self.PARTS has keys 'a' and 'd' + For 2D: self.PARTS has keys 'aa', 'ad', 'da', 'dd' + For 3D: self.PARTS has keys 'aaa', 'aad', 'ada', 'daa', ..., 'ddd' + + Parameters + ---------- + parent : + Parent node. If parent is None then the node is considered detached + (ie root). + data : 1D or 2D array + Data associated with the node. 1D or 2D numeric array, depending on the + transform type. + node_name : string + A name identifying the coefficients type. + See `Node.node_name` and `Node2D.node_name` + for information on the accepted subnodes names. + ndim : int + The number of data dimensions. + ndim_transform : int + The number of dimensions that are to be transformed. + + """ + def __init__(self, parent, data, node_name, ndim, ndim_transform): + super().__init__(parent=parent, data=data, + node_name=node_name) + self.PART_LEN = ndim_transform + self.PARTS = OrderedDict() + for key in product(*(('ad', )*self.PART_LEN)): + self.PARTS[''.join(key)] = None + self.ndim = ndim + self.ndim_transform = ndim_transform + + def _init_subnodes(self): + # need this empty so BaseNode's _init_subnodes isn't called during + # __init__. We use a dictionary for PARTS instead for the nd case. + pass + + def _get_node(self, part): + return self.PARTS[part] + + def _set_node(self, part, node): + if part not in self.PARTS: + raise ValueError("invalid part") + self.PARTS[part] = node + + def _delete_node(self, part): + self._set_node(part, None) + + def _validate_node_name(self, part): + if part not in self.PARTS: + raise ValueError( + "Subnode name must be in [{}], not '{}'.".format(', '.join("'%s'" % p for p in list(self.PARTS.keys())), part)) + + def _create_subnode(self, part, data=None, overwrite=True): + return self._create_subnode_base(node_cls=NodeND, part=part, data=data, + overwrite=overwrite, ndim=self.ndim, + ndim_transform=self.ndim_transform) + + def _evaluate_maxlevel(self, evaluate_from='parent'): + """ + Try to find the value of maximum decomposition level if it is not + specified explicitly. + + Parameters + ---------- + evaluate_from : {'parent', 'subnodes'} + """ + assert evaluate_from in ('parent', 'subnodes') + + if self._maxlevel is not None: + return self._maxlevel + elif self.data is not None: + return self.level + dwt_max_level( + min(self.data.shape), self.wavelet) + + if evaluate_from == 'parent': + if self.parent is not None: + return self.parent._evaluate_maxlevel(evaluate_from) + elif evaluate_from == 'subnodes': + for node_name, node in self.PARTS.items(): + if node is not None: + level = node._evaluate_maxlevel(evaluate_from) + if level is not None: + return level + return None + + def _decompose(self): + """ + See also + -------- + dwt2 : for 2D Discrete Wavelet Transform output coefficients. + """ + if self.is_empty: + coefs = {key: None for key in self.PARTS} + else: + coefs = dwtn(self.data, self.wavelet, self.mode, axes=self.axes) + + for key, data in coefs.items(): + self._create_subnode(key, data) + return (self._get_node(key) for key in self.PARTS) + + def _reconstruct(self, update): + coeffs = {key: None for key in self.PARTS} + + nnodes = 0 + for key in self.PARTS: + node = self._get_node(key) + if node is not None: + nnodes += 1 + coeffs[key] = node.reconstruct() + + if nnodes == 0: + raise ValueError( + "Tree is missing data - all subnodes of `%s` node " + "are None. Cannot reconstruct node." % self.path + ) + else: + rec = idwtn(coeffs, self.wavelet, self.mode, axes=self.axes) + if self._data_shape is not None and ( + rec.shape != self._data_shape): + rec = rec[tuple([slice(sz) for sz in self._data_shape])] + if update: + self.data = rec + return rec + + +class WaveletPacket(Node): + """ + Data structure representing Wavelet Packet decomposition of signal. + + Parameters + ---------- + data : 1D ndarray + Original data (signal) + wavelet : Wavelet object or name string + Wavelet used in DWT decomposition and reconstruction + mode : str, optional + Signal extension mode for the `dwt` and `idwt` decomposition and + reconstruction functions. + maxlevel : int, optional + Maximum level of decomposition. + If None, it will be calculated based on the `wavelet` and `data` + length using `pywt.dwt_max_level`. + axis : int, optional + The axis to transform. + """ + def __init__(self, data, wavelet, mode='symmetric', maxlevel=None, + axis=-1): + super().__init__(None, data, "") + + if not isinstance(wavelet, Wavelet): + wavelet = Wavelet(wavelet) + self.wavelet = wavelet + self.mode = mode + self.axes = axis # self.axes is just an integer for 1D transforms + + if data is not None: + data = np.asarray(data) + if self.axes < 0: + self.axes = self.axes + data.ndim + if not 0 <= self.axes < data.ndim: + raise ValueError("Axis greater than data dimensions") + self.data_size = data.shape + if maxlevel is None: + maxlevel = dwt_max_level(data.shape[self.axes], self.wavelet) + else: + self.data_size = None + + self._maxlevel = maxlevel + + def __reduce__(self): + return (WaveletPacket, + (self.data, self.wavelet, self.mode, self.maxlevel)) + + def reconstruct(self, update=True): + """ + Reconstruct data value using coefficients from subnodes. + + Parameters + ---------- + update : bool, optional + If True (default), then data values will be replaced by + reconstruction values, also in subnodes. + """ + if self.has_any_subnode: + data = super().reconstruct(update) + if self.data_size is not None and (data.shape != self.data_size): + data = data[tuple(slice(sz) for sz in self.data_size)] + if update: + self.data = data + return data + return self.data # return original data + + def get_level(self, level, order="natural", decompose=True): + """ + Returns all nodes on the specified level. + + Parameters + ---------- + level : int + Specifies decomposition `level` from which the nodes will be + collected. + order : {'natural', 'freq'}, optional + - "natural" - left to right in tree (default) + - "freq" - band ordered + decompose : bool, optional + If set then the method will try to decompose the data up + to the specified `level` (default: True). + + Notes + ----- + If nodes at the given level are missing (i.e. the tree is partially + decomposed) and `decompose` is set to False, only existing nodes + will be returned. + + Frequency order (``order="freq"``) is also known as sequency order + and "natural" order is sometimes referred to as Paley order. A detailed + discussion of these orderings is also given in [1]_, [2]_. + + References + ---------- + ..[1] M.V. Wickerhauser. Adapted Wavelet Analysis from Theory to + Software. Wellesley. Massachusetts: A K Peters. 1994. + ..[2] D.B. Percival and A.T. Walden. Wavelet Methods for Time Series + Analysis. Cambridge University Press. 2000. + DOI:10.1017/CBO9780511841040 + """ + if order not in ["natural", "freq"]: + raise ValueError(f"Invalid order: {order}") + if level > self.maxlevel: + raise ValueError("The level cannot be greater than the maximum" + " decomposition level value (%d)" % self.maxlevel) + + result = [] + + def collect(node): + if node.level == level: + result.append(node) + return False + return True + + self.walk(collect, decompose=decompose) + if order == "natural": + return result + elif order == "freq": + result = {node.path: node for node in result} + graycode_order = get_graycode_order(level) + return [result[path] for path in graycode_order if path in result] + else: + raise ValueError(f"Invalid order name - {order}.") + + +class WaveletPacket2D(Node2D): + """ + Data structure representing 2D Wavelet Packet decomposition of signal. + + Parameters + ---------- + data : 2D ndarray + Data associated with the node. + wavelet : Wavelet object or name string + Wavelet used in DWT decomposition and reconstruction + mode : str, optional + Signal extension mode for the `dwt` and `idwt` decomposition and + reconstruction functions. + maxlevel : int + Maximum level of decomposition. + If None, it will be calculated based on the `wavelet` and `data` + length using `pywt.dwt_max_level`. + axes : 2-tuple of ints, optional + The axes that will be transformed. + """ + def __init__(self, data, wavelet, mode='smooth', maxlevel=None, + axes=(-2, -1)): + super().__init__(None, data, "") + + if not isinstance(wavelet, Wavelet): + wavelet = Wavelet(wavelet) + self.wavelet = wavelet + self.mode = mode + self.axes = tuple(axes) + if len(np.unique(self.axes)) != 2: + raise ValueError("Expected two unique axes.") + if data is not None: + data = np.asarray(data) + if data.ndim < 2: + raise ValueError( + "WaveletPacket2D requires data with 2 or more dimensions.") + self.data_size = data.shape + transform_size = [data.shape[ax] for ax in self.axes] + if maxlevel is None: + maxlevel = dwt_max_level(min(transform_size), self.wavelet) + else: + self.data_size = None + self._maxlevel = maxlevel + + def __reduce__(self): + return (WaveletPacket2D, + (self.data, self.wavelet, self.mode, self.maxlevel)) + + def reconstruct(self, update=True): + """ + Reconstruct data using coefficients from subnodes. + + Parameters + ---------- + update : bool, optional + If True (default) then the coefficients of the current node + and its subnodes will be replaced with values from reconstruction. + """ + if self.has_any_subnode: + data = super().reconstruct(update) + if self.data_size is not None and (data.shape != self.data_size): + data = data[tuple(slice(sz) for sz in self.data_size)] + if update: + self.data = data + return data + return self.data # return original data + + def get_level(self, level, order="natural", decompose=True): + """ + Returns all nodes from specified level. + + Parameters + ---------- + level : int + Decomposition `level` from which the nodes will be + collected. + order : {'natural', 'freq'}, optional + If `natural` (default) a flat list is returned. + If `freq`, a 2d structure with rows and cols + sorted by corresponding dimension frequency of 2d + coefficient array (adapted from 1d case). + decompose : bool, optional + If set then the method will try to decompose the data up + to the specified `level` (default: True). + + Notes + ----- + Frequency order (``order="freq"``) is also known as as sequency order + and "natural" order is sometimes referred to as Paley order. A detailed + discussion of these orderings is also given in [1]_, [2]_. + + References + ---------- + ..[1] M.V. Wickerhauser. Adapted Wavelet Analysis from Theory to + Software. Wellesley. Massachusetts: A K Peters. 1994. + ..[2] D.B. Percival and A.T. Walden. Wavelet Methods for Time Series + Analysis. Cambridge University Press. 2000. + DOI:10.1017/CBO9780511841040 + """ + if order not in ["natural", "freq"]: + raise ValueError(f"Invalid order: {order}") + if level > self.maxlevel: + raise ValueError("The level cannot be greater than the maximum" + " decomposition level value (%d)" % self.maxlevel) + + result = [] + + def collect(node): + if node.level == level: + result.append(node) + return False + return True + + self.walk(collect, decompose=decompose) + + if order == "freq": + nodes = {} + for (row_path, col_path), node in [ + (self.expand_2d_path(node.path), node) for node in result + ]: + nodes.setdefault(row_path, {})[col_path] = node + graycode_order = get_graycode_order(level, x='l', y='h') + nodes = [nodes[path] for path in graycode_order if path in nodes] + result = [] + for row in nodes: + result.append( + [row[path] for path in graycode_order if path in row] + ) + return result + + +class WaveletPacketND(NodeND): + """ + Data structure representing ND Wavelet Packet decomposition of signal. + + Parameters + ---------- + data : ND ndarray + Data associated with the node. + wavelet : Wavelet object or name string + Wavelet used in DWT decomposition and reconstruction + mode : str, optional + Signal extension mode for the `dwt` and `idwt` decomposition and + reconstruction functions. + maxlevel : int, optional + Maximum level of decomposition. + If None, it will be calculated based on the `wavelet` and `data` + length using `pywt.dwt_max_level`. + axes : tuple of int, optional + The axes to transform. The default value of `None` corresponds to all + axes. + """ + def __init__(self, data, wavelet, mode='smooth', maxlevel=None, + axes=None): + if (data is None) and (axes is None): + # ndim is required to create a NodeND object + raise ValueError("If data is None, axes must be specified") + + # axes determines the number of transform dimensions + if axes is None: + axes = range(data.ndim) + elif np.isscalar(axes): + axes = (axes, ) + axes = tuple(axes) + if len(np.unique(axes)) != len(axes): + raise ValueError("Expected a set of unique axes.") + ndim_transform = len(axes) + + if data is not None: + data = np.asarray(data) + if data.ndim == 0: + raise ValueError("data must be at least 1D") + ndim = data.ndim + else: + ndim = len(axes) + + super().__init__(None, data, "", ndim, + ndim_transform) + if not isinstance(wavelet, Wavelet): + wavelet = Wavelet(wavelet) + self.wavelet = wavelet + self.mode = mode + self.axes = axes + self.ndim_transform = ndim_transform + if data is not None: + if data.ndim < len(axes): + raise ValueError("The number of axes exceeds the number of " + "data dimensions.") + self.data_size = data.shape + transform_size = [data.shape[ax] for ax in self.axes] + if maxlevel is None: + maxlevel = dwt_max_level(min(transform_size), self.wavelet) + else: + self.data_size = None + self._maxlevel = maxlevel + + def reconstruct(self, update=True): + """ + Reconstruct data using coefficients from subnodes. + + Parameters + ---------- + update : bool, optional + If True (default) then the coefficients of the current node + and its subnodes will be replaced with values from reconstruction. + """ + if self.has_any_subnode: + data = super().reconstruct(update) + if self.data_size is not None and (data.shape != self.data_size): + data = data[tuple(slice(sz) for sz in self.data_size)] + if update: + self.data = data + return data + return self.data # return original data + + def get_level(self, level, decompose=True): + """ + Returns all nodes from specified level. + + Parameters + ---------- + level : int + Decomposition `level` from which the nodes will be + collected. + decompose : bool, optional + If set then the method will try to decompose the data up + to the specified `level` (default: True). + """ + if level > self.maxlevel: + raise ValueError("The level cannot be greater than the maximum" + " decomposition level value (%d)" % self.maxlevel) + + result = [] + + def collect(node): + if node.level == level: + result.append(node) + return False + return True + + self.walk(collect, decompose=decompose) + + return result diff --git a/.venv/lib/python3.12/site-packages/pywt/conftest.py b/.venv/lib/python3.12/site-packages/pywt/conftest.py new file mode 100644 index 0000000000000000000000000000000000000000..da8ae64553df5e9da320101ed2a82c1d1f31b409 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/pywt/conftest.py @@ -0,0 +1,6 @@ +import pytest + + +def pytest_configure(config): + config.addinivalue_line("markers", + "slow: Tests that are slow.") diff --git a/.venv/lib/python3.12/site-packages/pywt/data/__init__.py b/.venv/lib/python3.12/site-packages/pywt/data/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..052e784a559e72b16235f2aadf33309b358d985d --- /dev/null +++ b/.venv/lib/python3.12/site-packages/pywt/data/__init__.py @@ -0,0 +1,2 @@ +from ._readers import aero, ascent, camera, ecg, nino +from ._wavelab_signals import demo_signal diff --git a/.venv/lib/python3.12/site-packages/pywt/data/_readers.py b/.venv/lib/python3.12/site-packages/pywt/data/_readers.py new file mode 100644 index 0000000000000000000000000000000000000000..8c2e7889cc9f413ee8e8a9574848a2372bcaec59 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/pywt/data/_readers.py @@ -0,0 +1,212 @@ +import functools +import importlib.resources +import os + +import numpy as np + +_DATADIR = importlib.resources.files('pywt.data') + + +@functools.cache +def ascent(): + """ + Get an 8-bit grayscale bit-depth, 512 x 512 derived image for + easy use in demos + + The image is derived from accent-to-the-top.jpg at + http://www.public-domain-image.com/people-public-domain-images-pictures/ + + Parameters + ---------- + None + + Returns + ------- + ascent : ndarray + convenient image to use for testing and demonstration + + Examples + -------- + >>> import pywt.data + >>> ascent = pywt.data.ascent() + >>> ascent.shape == (512, 512) + True + >>> ascent.max() + 255 + + >>> import matplotlib.pyplot as plt + >>> plt.gray() + >>> plt.imshow(ascent) + + >>> plt.show() + + """ + with importlib.resources.as_file(_DATADIR.joinpath('ascent.npz')) as f: + ascent = np.load(f)['data'] + + return ascent + + +@functools.cache +def aero(): + """ + Get an 8-bit grayscale bit-depth, 512 x 512 derived image for + easy use in demos + + Parameters + ---------- + None + + Returns + ------- + aero : ndarray + convenient image to use for testing and demonstration + + Examples + -------- + >>> import pywt.data + >>> aero = pywt.data.ascent() + >>> aero.shape == (512, 512) + True + >>> aero.max() + 255 + + >>> import matplotlib.pyplot as plt + >>> plt.gray() + >>> plt.imshow(aero) + + >>> plt.show() + + """ + with importlib.resources.as_file(_DATADIR.joinpath('aero.npz')) as f: + aero = np.load(f)['data'] + + return aero + + +@functools.cache +def camera(): + """ + Get an 8-bit grayscale bit-depth, 512 x 512 derived image for + easy use in demos + + Parameters + ---------- + None + + Returns + ------- + camera : ndarray + convenient image to use for testing and demonstration + + Notes + ----- + No copyright restrictions. CC0 by the photographer (Lav Varshney). + + .. versionchanged:: 0.18 + This image was replaced due to copyright restrictions. For more + information, please see [1]_, where the same change was made in + scikit-image. + + References + ---------- + .. [1] https://github.com/scikit-image/scikit-image/issues/3927 + + Examples + -------- + >>> import pywt.data + >>> camera = pywt.data.ascent() + >>> camera.shape == (512, 512) + True + + >>> import matplotlib.pyplot as plt + >>> plt.gray() + >>> plt.imshow(camera) + + >>> plt.show() + + """ + with importlib.resources.as_file(_DATADIR.joinpath('camera.npz')) as f: + camera = np.load(f)['data'] + + return camera + + +@functools.cache +def ecg(): + """ + Get 1024 points of an ECG timeseries. + + Parameters + ---------- + None + + Returns + ------- + ecg : ndarray + convenient timeseries to use for testing and demonstration + + Examples + -------- + >>> import pywt.data + >>> ecg = pywt.data.ecg() + >>> ecg.shape == (1024,) + True + + >>> import matplotlib.pyplot as plt + >>> plt.plot(ecg) + [] + >>> plt.show() + """ + with importlib.resources.as_file(_DATADIR.joinpath('ecg.npz')) as f: + ecg = np.load(f)['data'] + + return ecg + + +@functools.cache +def nino(): + """ + This data contains the averaged monthly sea surface temperature in degrees + Celsius of the Pacific Ocean, between 0-10 degrees South and 90-80 degrees West, from 1950 to 2016. + This dataset is in the public domain and was obtained from NOAA. + National Oceanic and Atmospheric Administration's National Weather Service + ERSSTv4 dataset, nino 3, http://www.cpc.ncep.noaa.gov/data/indices/ + + Parameters + ---------- + None + + Returns + ------- + time : ndarray + convenient timeseries to use for testing and demonstration + sst : ndarray + convenient timeseries to use for testing and demonstration + + Examples + -------- + >>> import pywt.data + >>> time, sst = pywt.data.nino() + >>> sst.shape == (264,) + True + + >>> import matplotlib.pyplot as plt + >>> plt.plot(time,sst) + [] + >>> plt.show() + """ + with importlib.resources.as_file(_DATADIR.joinpath('sst_nino3.npz')) as f: + sst_csv = np.load(f)['data'] + + # sst_csv = pd.read_csv("http://www.cpc.ncep.noaa.gov/data/indices/ersst4.nino.mth.81-10.ascii", sep=' ', skipinitialspace=True) + # take only full years + n = int(np.floor(sst_csv.shape[0]/12.)*12.) + # Building the mean of three months + # the 4. column is nino 3 + sst = np.mean(np.reshape(np.array(sst_csv)[:n, 4], (n//3, -1)), axis=1) + sst = (sst - np.mean(sst)) / np.std(sst, ddof=1) + + dt = 0.25 + time = np.arange(len(sst)) * dt + 1950.0 # construct time array + return time, sst diff --git a/.venv/lib/python3.12/site-packages/pywt/data/_wavelab_signals.py b/.venv/lib/python3.12/site-packages/pywt/data/_wavelab_signals.py new file mode 100644 index 0000000000000000000000000000000000000000..bd91b4add52c23ec3b210820cf629f60fa53d9b6 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/pywt/data/_wavelab_signals.py @@ -0,0 +1,267 @@ + +import numpy as np + +__all__ = ['demo_signal'] + +_implemented_signals = [ + 'Blocks', + 'Bumps', + 'HeaviSine', + 'Doppler', + 'Ramp', + 'HiSine', + 'LoSine', + 'LinChirp', + 'TwoChirp', + 'QuadChirp', + 'MishMash', + 'WernerSorrows', + 'HypChirps', + 'LinChirps', + 'Chirps', + 'Gabor', + 'sineoneoverx', + 'Piece-Regular', + 'Piece-Polynomial', + 'Riemann'] + + +def demo_signal(name='Bumps', n=None): + """Simple 1D wavelet test functions. + + This function can generate a number of common 1D test signals used in + papers by David Donoho and colleagues (e.g. [1]_) as well as the wavelet + book by Stéphane Mallat [2]_. + + Parameters + ---------- + name : {'Blocks', 'Bumps', 'HeaviSine', 'Doppler', ...} + The type of test signal to generate (`name` is case-insensitive). If + `name` is set to `'list'`, a list of the available test functions is + returned. + n : int or None + The length of the test signal. This should be provided for all test + signals except `'Gabor'` and `'sineoneoverx'` which have a fixed + length. + + Returns + ------- + f : np.ndarray + Array of length ``n`` corresponding to the specified test signal type. + + References + ---------- + .. [1] D.L. Donoho and I.M. Johnstone. Ideal spatial adaptation by + wavelet shrinkage. Biometrika, vol. 81, pp. 425–455, 1994. + .. [2] S. Mallat. A Wavelet Tour of Signal Processing: The Sparse Way. + Academic Press. 2009. + + Notes + ----- + This function is a partial reimplementation of the `MakeSignal` function + from the [Wavelab](https://statweb.stanford.edu/~wavelab/) toolbox. These + test signals are provided with permission of Dr. Donoho to encourage + reproducible research. + + Examples + -------- + >>> import pywt + >>> camera = pywt.data.camera() + >>> doppler = pywt.data.demo_signal('doppler', 1024) + >>> available_signals = pywt.data.demo_signal('list') + >>> print(available_signals) + ['Blocks', 'Bumps', 'HeaviSine', 'Doppler', 'Ramp', 'HiSine', 'LoSine', 'LinChirp', + 'TwoChirp', 'QuadChirp', 'MishMash', 'WernerSorrows', 'HypChirps', 'LinChirps', + 'Chirps', 'Gabor', 'sineoneoverx', 'Piece-Regular', 'Piece-Polynomial', 'Riemann'] + + """ + if name.lower() == 'list': + return _implemented_signals + + if n is not None: + if n < 1 or (n % 1) != 0: + raise ValueError("n must be an integer >= 1") + t = np.arange(1/n, 1 + 1/n, 1/n) + + # The following function types don't allow user-specified `n`. + n_hard_coded = ['gabor', 'sineoneoverx'] + + name = name.lower() + if name in n_hard_coded and n is not None: + raise ValueError( + f"Parameter n must be set to None when name is {name}") + elif n is None and name not in n_hard_coded: + raise ValueError( + f"Parameter n must be provided when name is {name}") + + if name == 'blocks': + t0s = [.1, .13, .15, .23, .25, .4, .44, .65, .76, .78, .81] + hs = [4, -5, 3, -4, 5, -4.2, 2.1, 4.3, -3.1, 2.1, -4.2] + f = 0 + for (t0, h) in zip(t0s, hs): + f += h * (1 + np.sign(t - t0)) / 2 + elif name == 'bumps': + t0s = [.1, .13, .15, .23, .25, .4, .44, .65, .76, .78, .81] + hs = [4, 5, 3, 4, 5, 4.2, 2.1, 4.3, 3.1, 5.1, 4.2] + ws = [.005, .005, .006, .01, .01, .03, .01, .01, .005, .008, .005] + f = 0 + for (t0, h, w) in zip(t0s, hs, ws): + f += h / (1 + np.abs((t - t0) / w))**4 + elif name == 'heavisine': + f = 4 * np.sin(4 * np.pi * t) - np.sign(t - 0.3) - np.sign(0.72 - t) + elif name == 'doppler': + f = np.sqrt(t * (1 - t)) * np.sin(2 * np.pi * 1.05 / (t + 0.05)) + elif name == 'ramp': + f = t - (t >= .37) + elif name == 'hisine': + f = np.sin(np.pi * (n * .6902) * t) + elif name == 'losine': + f = np.sin(np.pi * (n * .3333) * t) + elif name == 'linchirp': + f = np.sin(np.pi * t * ((n * .500) * t)) + elif name == 'twochirp': + f = np.sin(np.pi * t * (n * t)) + np.sin((np.pi / 3) * t * (n * t)) + elif name == 'quadchirp': + f = np.sin((np.pi / 3) * t * (n * t**2)) + elif name == 'mishmash': # QuadChirp + LinChirp + HiSine + f = np.sin((np.pi / 3) * t * (n * t**2)) + f += np.sin(np.pi * (n * .6902) * t) + f += np.sin(np.pi * t * (n * .125 * t)) + elif name == 'wernersorrows': + f = np.sin(np.pi * t * (n / 2 * t**2)) + f = f + np.sin(np.pi * (n * .6902) * t) + f = f + np.sin(np.pi * t * (n * t)) + pos = [.1, .13, .15, .23, .25, .40, .44, .65, .76, .78, .81] + hgt = [4, 5, 3, 4, 5, 4.2, 2.1, 4.3, 3.1, 5.1, 4.2] + wth = [.005, .005, .006, .01, .01, .03, .01, .01, .005, .008, .005] + for p, h, w in zip(pos, hgt, wth): + f += h / (1 + np.abs((t - p) / w))**4 + elif name == 'hypchirps': # Hyperbolic Chirps of Mallat's book + alpha = 15 * n * np.pi / 1024 + beta = 5 * n * np.pi / 1024 + t = np.arange(1.001, n + .001 + 1) / n + f1 = np.zeros(n) + f2 = np.zeros(n) + f1 = np.sin(alpha / (.8 - t)) * (0.1 < t) * (t < 0.68) + f2 = np.sin(beta / (.8 - t)) * (0.1 < t) * (t < 0.75) + m = int(np.round(0.65 * n)) + p = m // 4 + envelope = np.ones(m) # the rinp.sing cutoff function + tmp = np.arange(1, p + 1)-np.ones(p) + envelope[:p] = (1 + np.sin(-np.pi / 2 + tmp / (p - 1) * np.pi)) / 2 + envelope[m-p:m] = envelope[:p][::-1] + env = np.zeros(n) + env[int(np.ceil(n / 10)) - 1:m + int(np.ceil(n / 10)) - 1] = \ + envelope[:m] + f = (f1 + f2) * env + elif name == 'linchirps': # Linear Chirps of Mallat's book + b = 100 * n * np.pi / 1024 + a = 250 * n * np.pi / 1024 + t = np.arange(1, n + 1) / n + A1 = np.sqrt((t - 1 / n) * (1 - t)) + f = A1 * (np.cos(a * t**2) + np.cos(b * t + a * t**2)) + elif name == 'chirps': # Mixture of Chirps of Mallat's book + t = np.arange(1, n + 1)/n * 10 * np.pi + f1 = np.cos(t**2 * n / 1024) + a = 30 * n / 1024 + t = np.arange(1, n + 1)/n * np.pi + f2 = np.cos(a * (t**3)) + f2 = f2[::-1] + ix = np.arange(-n, n + 1) / n * 20 + g = np.exp(-ix**2 * 4 * n / 1024) + i1 = slice(n // 2, n // 2 + n) + i2 = slice(n // 8, n // 8 + n) + j = np.arange(1, n + 1) / n + f3 = g[i1] * np.cos(50 * np.pi * j * n / 1024) + f4 = g[i2] * np.cos(350 * np.pi * j * n / 1024) + f = f1 + f2 + f3 + f4 + envelope = np.ones(n) # the rinp.sing cutoff function + tmp = np.arange(1, n // 8 + 1) - np.ones(n // 8) + envelope[:n // 8] = ( + 1 + np.sin(-np.pi / 2 + tmp / (n / 8 - 1) * np.pi)) / 2 + envelope[7 * n // 8:n] = envelope[:n // 8][::-1] + f = f*envelope + elif name == 'gabor': # two modulated Gabor functions in Mallat's book + n = 512 + t = np.arange(-n, n + 1)*5 / n + j = np.arange(1, n + 1) / n + g = np.exp(-t**2 * 20) + i1 = slice(2*n // 4, 2 * n // 4 + n) + i2 = slice(n // 4, n // 4 + n) + f1 = 3 * g[i1] * np.exp(1j * (n // 16) * np.pi * j) + f2 = 3 * g[i2] * np.exp(1j * (n // 4) * np.pi * j) + f = f1 + f2 + elif name == 'sineoneoverx': # np.sin(1/x) in Mallat's book + n = 1024 + i1 = np.arange(-n + 1, n + 1, dtype=float) + i1[i1 == 0] = 1 / 100 + i1 = i1 / (n - 1) + f = np.sin(1.5 / i1) + f = f[512:1536] + elif name == 'piece-regular': + f = np.zeros(n) + n_12 = int(np.trunc(n / 12)) + n_7 = int(np.trunc(n / 7)) + n_5 = int(np.trunc(n / 5)) + n_3 = int(np.trunc(n / 3)) + n_2 = int(np.trunc(n / 2)) + n_20 = int(np.trunc(n / 20)) + f1 = -15 * demo_signal('bumps', n) + t = np.arange(1, n_12 + 1) / n_12 + f2 = -np.exp(4 * t) + t = np.arange(1, n_7 + 1) / n_7 + f5 = np.exp(4 * t)-np.exp(4) + t = np.arange(1, n_3 + 1) / n_3 + fma = 6 / 40 + f6 = -70 * np.exp(-((t - 0.5) * (t - 0.5)) / (2 * fma**2)) + f[:n_7] = f6[:n_7] + f[n_7:n_5] = 0.5 * f6[n_7:n_5] + f[n_5:n_3] = f6[n_5:n_3] + f[n_3:n_2] = f1[n_3:n_2] + f[n_2:n_2 + n_12] = f2 + f[n_2 + 2 * n_12 - 1:n_2 + n_12 - 1:-1] = f2 + f[n_2 + 2 * n_12 + n_20:n_2 + 2 * n_12 + 3 * n_20] = -np.ones( + n_2 + 2*n_12 + 3*n_20 - n_2 - 2*n_12 - n_20) * 25 + k = n_2 + 2 * n_12 + 3 * n_20 + f[k:k + n_7] = f5 + diff = n - 5 * n_5 + f[5 * n_5:n] = f[diff - 1::-1] + # zero-mean + bias = np.sum(f) / n + f = bias - f + elif name == 'piece-polynomial': + f = np.zeros(n) + n_5 = int(np.trunc(n / 5)) + n_10 = int(np.trunc(n / 10)) + n_20 = int(np.trunc(n / 20)) + t = np.arange(1, n_5 + 1) / n_5 + f1 = 20 * (t**3 + t**2 + 4) + f3 = 40 * (2 * t**3 + t) + 100 + f2 = 10 * t**3 + 45 + f4 = 16 * t**2 + 8 * t + 16 + f5 = 20 * (t + 4) + f6 = np.ones(n_10) * 20 + f[:n_5] = f1 + f[2 * n_5 - 1:n_5 - 1:-1] = f2 + f[2 * n_5:3 * n_5] = f3 + f[3 * n_5:4 * n_5] = f4 + f[4 * n_5:5 * n_5] = f5[n_5::-1] + diff = n - 5*n_5 + f[5 * n_5:n] = f[diff - 1::-1] + f[n_20:n_20 + n_10] = np.ones(n_10) * 10 + f[n - n_10:n + n_20 - n_10] = np.ones(n_20) * 150 + # zero-mean + bias = np.sum(f) / n + f = f - bias + elif name == 'riemann': + # Riemann's Non-differentiable Function + sqn = int(np.round(np.sqrt(n))) + idx = np.arange(1, sqn + 1) + idx *= idx + f = np.zeros_like(t) + f[idx - 1] = 1. / np.arange(1, sqn + 1) + f = np.real(np.fft.ifft(f)) + else: + raise ValueError( + f"unknown name: {name}. name must be one of: {_implemented_signals}") + return f diff --git a/.venv/lib/python3.12/site-packages/pywt/data/aero.npz b/.venv/lib/python3.12/site-packages/pywt/data/aero.npz new file mode 100644 index 0000000000000000000000000000000000000000..b65051121d1689eb66b8ed0b76a5863e268289a9 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/pywt/data/aero.npz @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:df862635798bac94226b8928f224da8cef8b0d00492c1fdf48fac6dfaf97a94b +size 227784 diff --git a/.venv/lib/python3.12/site-packages/pywt/data/ascent.npz b/.venv/lib/python3.12/site-packages/pywt/data/ascent.npz new file mode 100644 index 0000000000000000000000000000000000000000..1b3ec70837d5bc1b8d5f112ec5c39204e870f3d5 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/pywt/data/ascent.npz @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:a6d56bc8e96571d6124f34cedeba49f1d3599507f6c890ad9ba538544454e8f7 +size 170883 diff --git a/.venv/lib/python3.12/site-packages/pywt/data/camera.npz b/.venv/lib/python3.12/site-packages/pywt/data/camera.npz new file mode 100644 index 0000000000000000000000000000000000000000..d9d0d5473dbb8b7022298a0d45541390d8394ecf --- /dev/null +++ b/.venv/lib/python3.12/site-packages/pywt/data/camera.npz @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:2be8195e9680ccb3c804fee19ca0b69a097eae9c9b2ab97474c7f1438171f074 +size 169034 diff --git a/.venv/lib/python3.12/site-packages/pywt/data/ecg.npz b/.venv/lib/python3.12/site-packages/pywt/data/ecg.npz new file mode 100644 index 0000000000000000000000000000000000000000..0f4fa556363e26e37768aa2efa82af00fab4b8c2 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/pywt/data/ecg.npz @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:ea720476139341eabecf3e44cc602cd75576aff1e4156b1c069f7b33e86a9e6b +size 4358 diff --git a/.venv/lib/python3.12/site-packages/pywt/data/sst_nino3.npz b/.venv/lib/python3.12/site-packages/pywt/data/sst_nino3.npz new file mode 100644 index 0000000000000000000000000000000000000000..c2df4556d27d4f611a9505c960515e501e09f50b --- /dev/null +++ b/.venv/lib/python3.12/site-packages/pywt/data/sst_nino3.npz @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:d1ef70af12824d8c08cef96c5e1684a22d819d89adcd9ab3cf92d12a5d9d8367 +size 64262 diff --git a/.venv/lib/python3.12/site-packages/pywt/tests/data/README.md b/.venv/lib/python3.12/site-packages/pywt/tests/data/README.md new file mode 100644 index 0000000000000000000000000000000000000000..8910e1caa4b966e693598e586c55f289584983ab --- /dev/null +++ b/.venv/lib/python3.12/site-packages/pywt/tests/data/README.md @@ -0,0 +1,3 @@ +The .npz files with Matlab reference data are generated by the +`generate_matlab*.py` scripts in the `util/` top-level directory +in this repository. diff --git a/.venv/lib/python3.12/site-packages/pywt/tests/data/cwt_matlabR2015b_result.npz b/.venv/lib/python3.12/site-packages/pywt/tests/data/cwt_matlabR2015b_result.npz new file mode 100644 index 0000000000000000000000000000000000000000..665a3793b60059611620320c30647d0564bb2be3 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/pywt/tests/data/cwt_matlabR2015b_result.npz @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:320c9638de54ae10ac22162cc279efeada5a012df4b970838d8c262e3cc7e59e +size 1826646 diff --git a/.venv/lib/python3.12/site-packages/pywt/tests/data/dwt_matlabR2012a_result.npz b/.venv/lib/python3.12/site-packages/pywt/tests/data/dwt_matlabR2012a_result.npz new file mode 100644 index 0000000000000000000000000000000000000000..b613b59b7a5a092580387c6a6556c9394809de0c --- /dev/null +++ b/.venv/lib/python3.12/site-packages/pywt/tests/data/dwt_matlabR2012a_result.npz @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:961687ab8fae83f4b62ed3d4975315a25515c416a7443c604341043e11f3ce22 +size 3740630 diff --git a/.venv/lib/python3.12/site-packages/pywt/tests/data/wavelab_test_signals.npz b/.venv/lib/python3.12/site-packages/pywt/tests/data/wavelab_test_signals.npz new file mode 100644 index 0000000000000000000000000000000000000000..4eb1ec8a3681110cc351e768743beb9d90643764 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/pywt/tests/data/wavelab_test_signals.npz @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:f9cc749def4975372ae8b88a05a72333fd3f127ef64c088abef1545b5ca26581 +size 184818 diff --git a/.venv/lib/python3.12/site-packages/pywt/tests/test__pywt.py b/.venv/lib/python3.12/site-packages/pywt/tests/test__pywt.py new file mode 100644 index 0000000000000000000000000000000000000000..7131084d4526dc7c80c7490aa154a44197fca439 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/pywt/tests/test__pywt.py @@ -0,0 +1,169 @@ +#!/usr/bin/env python + + +import numpy as np +from numpy.testing import assert_, assert_allclose, assert_raises + +import pywt + + +def test_upcoef_reconstruct(): + data = np.arange(3) + a = pywt.downcoef('a', data, 'haar') + d = pywt.downcoef('d', data, 'haar') + + rec = (pywt.upcoef('a', a, 'haar', take=3) + + pywt.upcoef('d', d, 'haar', take=3)) + assert_allclose(rec, data) + + +def test_downcoef_multilevel(): + rstate = np.random.RandomState(1234) + r = rstate.randn(16) + nlevels = 3 + # calling with level=1 nlevels times + a1 = r.copy() + for i in range(nlevels): + a1 = pywt.downcoef('a', a1, 'haar', level=1) + # call with level=nlevels once + a3 = pywt.downcoef('a', r, 'haar', level=nlevels) + assert_allclose(a1, a3) + + +def test_downcoef_complex(): + rstate = np.random.RandomState(1234) + r = rstate.randn(16) + 1j * rstate.randn(16) + nlevels = 3 + a = pywt.downcoef('a', r, 'haar', level=nlevels) + a_ref = pywt.downcoef('a', r.real, 'haar', level=nlevels) + a_ref = a_ref + 1j * pywt.downcoef('a', r.imag, 'haar', level=nlevels) + assert_allclose(a, a_ref) + + +def test_downcoef_errs(): + # invalid part string (not 'a' or 'd') + assert_raises(ValueError, pywt.downcoef, 'f', np.ones(16), 'haar') + + +def test_compare_downcoef_coeffs(): + rstate = np.random.RandomState(1234) + r = rstate.randn(16) + # compare downcoef against wavedec outputs + for nlevels in [1, 2, 3]: + for wavelet in pywt.wavelist(): + if wavelet in ['cmor', 'shan', 'fbsp']: + # skip these CWT families to avoid warnings + continue + wavelet = pywt.DiscreteContinuousWavelet(wavelet) + if isinstance(wavelet, pywt.Wavelet): + max_level = pywt.dwt_max_level(r.size, wavelet.dec_len) + if nlevels <= max_level: + a = pywt.downcoef('a', r, wavelet, level=nlevels) + d = pywt.downcoef('d', r, wavelet, level=nlevels) + coeffs = pywt.wavedec(r, wavelet, level=nlevels) + assert_allclose(a, coeffs[0]) + assert_allclose(d, coeffs[1]) + + +def test_upcoef_multilevel(): + rstate = np.random.RandomState(1234) + r = rstate.randn(4) + nlevels = 3 + # calling with level=1 nlevels times + a1 = r.copy() + for i in range(nlevels): + a1 = pywt.upcoef('a', a1, 'haar', level=1) + # call with level=nlevels once + a3 = pywt.upcoef('a', r, 'haar', level=nlevels) + assert_allclose(a1, a3) + + +def test_upcoef_complex(): + rstate = np.random.RandomState(1234) + r = rstate.randn(4) + 1j*rstate.randn(4) + nlevels = 3 + a = pywt.upcoef('a', r, 'haar', level=nlevels) + a_ref = pywt.upcoef('a', r.real, 'haar', level=nlevels) + a_ref = a_ref + 1j*pywt.upcoef('a', r.imag, 'haar', level=nlevels) + assert_allclose(a, a_ref) + + +def test_upcoef_errs(): + # invalid part string (not 'a' or 'd') + assert_raises(ValueError, pywt.upcoef, 'f', np.ones(4), 'haar') + + +def test_upcoef_and_downcoef_1d_only(): + # upcoef and downcoef raise a ValueError if data.ndim > 1d + for ndim in [2, 3]: + data = np.ones((8, )*ndim) + assert_raises(ValueError, pywt.downcoef, 'a', data, 'haar') + assert_raises(ValueError, pywt.upcoef, 'a', data, 'haar') + + +def test_wavelet_repr(): + from pywt._extensions import _pywt + wavelet = _pywt.Wavelet('sym8') + + repr_wavelet = eval(wavelet.__repr__()) + + assert_(wavelet.__repr__() == repr_wavelet.__repr__()) + + +def test_dwt_max_level(): + assert_(pywt.dwt_max_level(16, 2) == 4) + assert_(pywt.dwt_max_level(16, 8) == 1) + assert_(pywt.dwt_max_level(16, 9) == 1) + assert_(pywt.dwt_max_level(16, 10) == 0) + assert_(pywt.dwt_max_level(16, np.int8(10)) == 0) + assert_(pywt.dwt_max_level(16, 10.) == 0) + assert_(pywt.dwt_max_level(16, 18) == 0) + + # accepts discrete Wavelet object or string as well + assert_(pywt.dwt_max_level(32, pywt.Wavelet('sym5')) == 1) + assert_(pywt.dwt_max_level(32, 'sym5') == 1) + + # string input that is not a discrete wavelet + assert_raises(ValueError, pywt.dwt_max_level, 16, 'mexh') + + # filter_len must be an integer >= 2 + assert_raises(ValueError, pywt.dwt_max_level, 16, 1) + assert_raises(ValueError, pywt.dwt_max_level, 16, -1) + assert_raises(ValueError, pywt.dwt_max_level, 16, 3.3) + + +def test_ContinuousWavelet_errs(): + assert_raises(ValueError, pywt.ContinuousWavelet, 'qwertz') + + +def test_ContinuousWavelet_repr(): + from pywt._extensions import _pywt + wavelet = _pywt.ContinuousWavelet('gaus2') + + repr_wavelet = eval(wavelet.__repr__()) + + assert_(wavelet.__repr__() == repr_wavelet.__repr__()) + + +def test_wavelist(): + for name in pywt.wavelist(family='coif'): + assert_(name.startswith('coif')) + + assert_('cgau7' in pywt.wavelist(kind='continuous')) + assert_('sym20' in pywt.wavelist(kind='discrete')) + assert_(len(pywt.wavelist(kind='continuous')) + + len(pywt.wavelist(kind='discrete')) == + len(pywt.wavelist(kind='all'))) + + assert_raises(ValueError, pywt.wavelist, kind='foobar') + + +def test_wavelet_errormsgs(): + try: + pywt.Wavelet('gaus1') + except ValueError as e: + assert_(e.args[0].startswith('The `Wavelet` class')) + try: + pywt.Wavelet('cmord') + except ValueError as e: + assert_(e.args[0] == "Invalid wavelet name 'cmord'.") diff --git a/.venv/lib/python3.12/site-packages/pywt/tests/test_concurrent.py b/.venv/lib/python3.12/site-packages/pywt/tests/test_concurrent.py new file mode 100644 index 0000000000000000000000000000000000000000..e508b7b7e19fe24ffd083764e76114492529648b --- /dev/null +++ b/.venv/lib/python3.12/site-packages/pywt/tests/test_concurrent.py @@ -0,0 +1,106 @@ +""" +Tests used to verify running PyWavelets transforms in parallel via +concurrent.futures.ThreadPoolExecutor does not raise errors. +""" + + +import warnings +from functools import partial + +import numpy as np +import pytest +from numpy.testing import assert_allclose, assert_array_equal + +import pywt +from pywt._pytest import futures, max_workers, uses_futures + + +def _assert_all_coeffs_equal(coefs1, coefs2): + # return True only if all coefficients of SWT or DWT match over all levels + if len(coefs1) != len(coefs2): + return False + for (c1, c2) in zip(coefs1, coefs2): + if isinstance(c1, tuple): + # for swt, swt2, dwt, dwt2, wavedec, wavedec2 + for a1, a2 in zip(c1, c2): + assert_array_equal(a1, a2) + elif isinstance(c1, dict): + # for swtn, dwtn, wavedecn + for k, v in c1.items(): + assert_array_equal(v, c2[k]) + else: + return False + return True + + +@uses_futures +def test_concurrent_swt(): + # tests error-free concurrent operation (see gh-288) + # swt on 1D data calls the Cython swt + # other cases call swt_axes + with warnings.catch_warnings(): + # can remove catch_warnings once the swt2 FutureWarning is removed + warnings.simplefilter('ignore', FutureWarning) + for swt_func, x in zip([pywt.swt, pywt.swt2, pywt.swtn], + [np.ones(8), np.eye(16), np.eye(16)]): + transform = partial(swt_func, wavelet='haar', level=3) + for _ in range(10): + arrs = [x.copy() for _ in range(100)] + with futures.ThreadPoolExecutor(max_workers=max_workers) as ex: + results = list(ex.map(transform, arrs)) + + # validate result from one of the concurrent runs + expected_result = transform(x) + _assert_all_coeffs_equal(expected_result, results[-1]) + + +@uses_futures +def test_concurrent_wavedec(): + # wavedec on 1D data calls the Cython dwt_single + # other cases call dwt_axis + for wavedec_func, x in zip([pywt.wavedec, pywt.wavedec2, pywt.wavedecn], + [np.ones(8), np.eye(16), np.eye(16)]): + transform = partial(wavedec_func, wavelet='haar', level=1) + for _ in range(10): + arrs = [x.copy() for _ in range(100)] + with futures.ThreadPoolExecutor(max_workers=max_workers) as ex: + results = list(ex.map(transform, arrs)) + + # validate result from one of the concurrent runs + expected_result = transform(x) + _assert_all_coeffs_equal(expected_result, results[-1]) + + +@uses_futures +def test_concurrent_dwt(): + # dwt on 1D data calls the Cython dwt_single + # other cases call dwt_axis + for dwt_func, x in zip([pywt.dwt, pywt.dwt2, pywt.dwtn], + [np.ones(8), np.eye(16), np.eye(16)]): + transform = partial(dwt_func, wavelet='haar') + for _ in range(10): + arrs = [x.copy() for _ in range(100)] + with futures.ThreadPoolExecutor(max_workers=max_workers) as ex: + results = list(ex.map(transform, arrs)) + + # validate result from one of the concurrent runs + expected_result = transform(x) + _assert_all_coeffs_equal([expected_result, ], [results[-1], ]) + + +@uses_futures +def test_concurrent_cwt(): + atol = rtol = 1e-14 + time, sst = pywt.data.nino() + dt = time[1]-time[0] + transform = partial(pywt.cwt, scales=np.arange(1, 4), wavelet='cmor1.5-1', + sampling_period=dt) + for _ in range(10): + arrs = [sst.copy() for _ in range(50)] + with futures.ThreadPoolExecutor(max_workers=max_workers) as ex: + results = list(ex.map(transform, arrs)) + + # validate result from one of the concurrent runs + expected_result = transform(sst) + for a1, a2 in zip(expected_result, results[-1]): + assert_allclose(a1, a2, atol=atol, rtol=rtol) diff --git a/.venv/lib/python3.12/site-packages/pywt/tests/test_cwt_wavelets.py b/.venv/lib/python3.12/site-packages/pywt/tests/test_cwt_wavelets.py new file mode 100644 index 0000000000000000000000000000000000000000..62b468853072ce2d9bbfbc33e6a289e2364cc906 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/pywt/tests/test_cwt_wavelets.py @@ -0,0 +1,563 @@ +#!/usr/bin/env python +import os +import pickle +from itertools import product + +import numpy as np +import pytest +from numpy.testing import ( + assert_allclose, + assert_almost_equal, + assert_equal, + assert_raises, +) + +import pywt + + +def ref_gaus(LB, UB, N, num): + X = np.linspace(LB, UB, N) + F0 = (2./np.pi)**(1./4.)*np.exp(-(X**2)) + if (num == 1): + psi = -2.*X*F0 + elif (num == 2): + psi = -2/(3**(1/2))*(-1 + 2*X**2)*F0 + elif (num == 3): + psi = -4/(15**(1/2))*X*(3 - 2*X**2)*F0 + elif (num == 4): + psi = 4/(105**(1/2))*(3 - 12*X**2 + 4*X**4)*F0 + elif (num == 5): + psi = 8/(3*(105**(1/2)))*X*(-15 + 20*X**2 - 4*X**4)*F0 + elif (num == 6): + psi = -8/(3*(1155**(1/2)))*(-15 + 90*X**2 - 60*X**4 + 8*X**6)*F0 + elif (num == 7): + psi = -16/(3*(15015**(1/2)))*X*(105 - 210*X**2 + 84*X**4 - 8*X**6)*F0 + elif (num == 8): + psi = 16/(45*(1001**(1/2)))*(105 - 840*X**2 + 840*X**4 - + 224*X**6 + 16*X**8)*F0 + return (psi, X) + + +def ref_cgau(LB, UB, N, num): + X = np.linspace(LB, UB, N) + F0 = np.exp(-X**2) + F1 = np.exp(-1j*X) + F2 = (F1*F0)/(np.exp(-1/2)*2**(1/2)*np.pi**(1/2))**(1/2) + if (num == 1): + psi = F2*(-1j - 2*X)*2**(1/2) + elif (num == 2): + psi = 1/3*F2*(-3 + 4j*X + 4*X**2)*6**(1/2) + elif (num == 3): + psi = 1/15*F2*(7j + 18*X - 12j*X**2 - 8*X**3)*30**(1/2) + elif (num == 4): + psi = 1/105*F2*(25 - 56j*X - 72*X**2 + 32j*X**3 + 16*X**4)*210**(1/2) + elif (num == 5): + psi = 1/315*F2*(-81j - 250*X + 280j*X**2 + 240*X**3 - + 80j*X**4 - 32*X**5)*210**(1/2) + elif (num == 6): + psi = 1/3465*F2*(-331 + 972j*X + 1500*X**2 - 1120j*X**3 - 720*X**4 + + 192j*X**5 + 64*X**6)*2310**(1/2) + elif (num == 7): + psi = 1/45045*F2*( + 1303j + 4634*X - 6804j*X**2 - 7000*X**3 + 3920j*X**4 + 2016*X**5 - + 448j*X**6 - 128*X**7)*30030**(1/2) + elif (num == 8): + psi = 1/45045*F2*( + 5937 - 20848j*X - 37072*X**2 + 36288j*X**3 + 28000*X**4 - + 12544j*X**5 - 5376*X**6 + 1024j*X**7 + 256*X**8)*2002**(1/2) + + psi = psi/np.real(np.sqrt(np.real(np.sum(psi*np.conj(psi)))*(X[1] - X[0]))) + return (psi, X) + + +def sinc2(x): + y = np.ones_like(x) + k = np.where(x)[0] + y[k] = np.sin(np.pi*x[k])/(np.pi*x[k]) + return y + + +def ref_shan(LB, UB, N, Fb, Fc): + x = np.linspace(LB, UB, N) + psi = np.sqrt(Fb)*(sinc2(Fb*x)*np.exp(2j*np.pi*Fc*x)) + return (psi, x) + + +def ref_fbsp(LB, UB, N, m, Fb, Fc): + x = np.linspace(LB, UB, N) + psi = np.sqrt(Fb)*((sinc2(Fb*x/m)**m)*np.exp(2j*np.pi*Fc*x)) + return (psi, x) + + +def ref_cmor(LB, UB, N, Fb, Fc): + x = np.linspace(LB, UB, N) + psi = ((np.pi*Fb)**(-0.5))*np.exp(2j*np.pi*Fc*x)*np.exp(-(x**2)/Fb) + return (psi, x) + + +def ref_morl(LB, UB, N): + x = np.linspace(LB, UB, N) + psi = np.exp(-(x**2)/2)*np.cos(5*x) + return (psi, x) + + +def ref_mexh(LB, UB, N): + x = np.linspace(LB, UB, N) + psi = (2/(np.sqrt(3)*np.pi**0.25))*np.exp(-(x**2)/2)*(1 - (x**2)) + return (psi, x) + + +def test_gaus(): + LB = -5 + UB = 5 + N = 1000 + for num in np.arange(1, 9): + [psi, x] = ref_gaus(LB, UB, N, num) + w = pywt.ContinuousWavelet("gaus" + str(num)) + PSI, X = w.wavefun(length=N) + + assert_allclose(np.real(PSI), np.real(psi)) + assert_allclose(np.imag(PSI), np.imag(psi)) + assert_allclose(X, x) + + +@pytest.mark.parametrize('dtype', [np.float32, np.float64]) +def test_continuous_wavelet_dtype(dtype): + wavelet = pywt.ContinuousWavelet('cmor1.5-1.0', dtype) + int_psi, x = pywt.integrate_wavelet(wavelet) + assert int_psi.real.dtype == dtype + assert x.dtype == dtype + + +def test_continuous_wavelet_invalid_dtype(): + with pytest.raises(ValueError): + pywt.ContinuousWavelet('gaus5', np.complex64) + with pytest.raises(ValueError): + pywt.ContinuousWavelet('gaus5', np.int_) + + +def test_cgau(): + LB = -5 + UB = 5 + N = 1000 + for num in np.arange(1, 9): + [psi, x] = ref_cgau(LB, UB, N, num) + w = pywt.ContinuousWavelet("cgau" + str(num)) + PSI, X = w.wavefun(length=N) + + assert_allclose(np.real(PSI), np.real(psi)) + assert_allclose(np.imag(PSI), np.imag(psi)) + assert_allclose(X, x) + + +def test_shan(): + LB = -20 + UB = 20 + N = 1000 + Fb = 1 + Fc = 1.5 + + [psi, x] = ref_shan(LB, UB, N, Fb, Fc) + w = pywt.ContinuousWavelet(f"shan{Fb}-{Fc}") + assert_almost_equal(w.center_frequency, Fc) + assert_almost_equal(w.bandwidth_frequency, Fb) + w.upper_bound = UB + w.lower_bound = LB + PSI, X = w.wavefun(length=N) + + assert_allclose(np.real(PSI), np.real(psi), atol=1e-15) + assert_allclose(np.imag(PSI), np.imag(psi), atol=1e-15) + assert_allclose(X, x, atol=1e-15) + + LB = -20 + UB = 20 + N = 1000 + Fb = 1.5 + Fc = 1 + + [psi, x] = ref_shan(LB, UB, N, Fb, Fc) + w = pywt.ContinuousWavelet(f"shan{Fb}-{Fc}") + assert_almost_equal(w.center_frequency, Fc) + assert_almost_equal(w.bandwidth_frequency, Fb) + w.upper_bound = UB + w.lower_bound = LB + PSI, X = w.wavefun(length=N) + + assert_allclose(np.real(PSI), np.real(psi), atol=1e-15) + assert_allclose(np.imag(PSI), np.imag(psi), atol=1e-15) + assert_allclose(X, x, atol=1e-15) + + +def test_cmor(): + LB = -20 + UB = 20 + N = 1000 + Fb = 1 + Fc = 1.5 + + [psi, x] = ref_cmor(LB, UB, N, Fb, Fc) + w = pywt.ContinuousWavelet(f"cmor{Fb}-{Fc}") + assert_almost_equal(w.center_frequency, Fc) + assert_almost_equal(w.bandwidth_frequency, Fb) + w.upper_bound = UB + w.lower_bound = LB + PSI, X = w.wavefun(length=N) + + assert_allclose(np.real(PSI), np.real(psi), atol=1e-15) + assert_allclose(np.imag(PSI), np.imag(psi), atol=1e-15) + assert_allclose(X, x, atol=1e-15) + + LB = -20 + UB = 20 + N = 1000 + Fb = 1.5 + Fc = 1 + + [psi, x] = ref_cmor(LB, UB, N, Fb, Fc) + w = pywt.ContinuousWavelet(f"cmor{Fb}-{Fc}") + assert_almost_equal(w.center_frequency, Fc) + assert_almost_equal(w.bandwidth_frequency, Fb) + w.upper_bound = UB + w.lower_bound = LB + PSI, X = w.wavefun(length=N) + + assert_allclose(np.real(PSI), np.real(psi), atol=1e-15) + assert_allclose(np.imag(PSI), np.imag(psi), atol=1e-15) + assert_allclose(X, x, atol=1e-15) + + +def test_fbsp(): + LB = -20 + UB = 20 + N = 1000 + M = 2 + Fb = 1 + Fc = 1.5 + + [psi, x] = ref_fbsp(LB, UB, N, M, Fb, Fc) + + w = pywt.ContinuousWavelet(f"fbsp{M}-{Fb}-{Fc}") + assert_almost_equal(w.center_frequency, Fc) + assert_almost_equal(w.bandwidth_frequency, Fb) + w.fbsp_order = M + w.upper_bound = UB + w.lower_bound = LB + PSI, X = w.wavefun(length=N) + + assert_allclose(np.real(PSI), np.real(psi), atol=1e-15) + assert_allclose(np.imag(PSI), np.imag(psi), atol=1e-15) + assert_allclose(X, x, atol=1e-15) + + LB = -20 + UB = 20 + N = 1000 + M = 2 + Fb = 1.5 + Fc = 1 + + [psi, x] = ref_fbsp(LB, UB, N, M, Fb, Fc) + w = pywt.ContinuousWavelet(f"fbsp{M}-{Fb}-{Fc}") + assert_almost_equal(w.center_frequency, Fc) + assert_almost_equal(w.bandwidth_frequency, Fb) + w.fbsp_order = M + w.upper_bound = UB + w.lower_bound = LB + PSI, X = w.wavefun(length=N) + + assert_allclose(np.real(PSI), np.real(psi), atol=1e-15) + assert_allclose(np.imag(PSI), np.imag(psi), atol=1e-15) + assert_allclose(X, x, atol=1e-15) + + LB = -20 + UB = 20 + N = 1000 + M = 3 + Fb = 1.5 + Fc = 1.2 + + [psi, x] = ref_fbsp(LB, UB, N, M, Fb, Fc) + w = pywt.ContinuousWavelet(f"fbsp{M}-{Fb}-{Fc}") + assert_almost_equal(w.center_frequency, Fc) + assert_almost_equal(w.bandwidth_frequency, Fb) + w.fbsp_order = M + w.upper_bound = UB + w.lower_bound = LB + PSI, X = w.wavefun(length=N) + # TODO: investigate why atol = 1e-5 is necessary + assert_allclose(np.real(PSI), np.real(psi), atol=1e-5) + assert_allclose(np.imag(PSI), np.imag(psi), atol=1e-5) + assert_allclose(X, x, atol=1e-15) + + +def test_morl(): + LB = -5 + UB = 5 + N = 1000 + + [psi, x] = ref_morl(LB, UB, N) + w = pywt.ContinuousWavelet("morl") + w.upper_bound = UB + w.lower_bound = LB + PSI, X = w.wavefun(length=N) + + assert_allclose(np.real(PSI), np.real(psi)) + assert_allclose(np.imag(PSI), np.imag(psi)) + assert_allclose(X, x) + + +def test_mexh(): + LB = -5 + UB = 5 + N = 1000 + + [psi, x] = ref_mexh(LB, UB, N) + w = pywt.ContinuousWavelet("mexh") + w.upper_bound = UB + w.lower_bound = LB + PSI, X = w.wavefun(length=N) + + assert_allclose(np.real(PSI), np.real(psi)) + assert_allclose(np.imag(PSI), np.imag(psi)) + assert_allclose(X, x) + + LB = -5 + UB = 5 + N = 1001 + + [psi, x] = ref_mexh(LB, UB, N) + w = pywt.ContinuousWavelet("mexh") + w.upper_bound = UB + w.lower_bound = LB + PSI, X = w.wavefun(length=N) + + assert_allclose(np.real(PSI), np.real(psi)) + assert_allclose(np.imag(PSI), np.imag(psi)) + assert_allclose(X, x) + + +def test_cwt_parameters_in_names(): + + for func in [pywt.ContinuousWavelet, pywt.DiscreteContinuousWavelet]: + for name in ['fbsp', 'cmor', 'shan']: + # additional parameters should be specified within the name + with pytest.warns(FutureWarning): + func(name) + + for name in ['cmor', 'shan']: + # valid names + func(name + '1.5-1.0') + func(name + '1-4') + + # invalid names + assert_raises(ValueError, func, name + '1.0') + assert_raises(ValueError, func, name + 'B-C') + assert_raises(ValueError, func, name + '1.0-1.0-1.0') + + # valid names + func('fbsp1-1.5-1.0') + func('fbsp1.0-1.5-1') + func('fbsp2-5-1') + + # invalid name (non-integer order) + assert_raises(ValueError, func, 'fbsp1.5-1-1') + assert_raises(ValueError, func, 'fbspM-B-C') + + # invalid name (too few or too many params) + assert_raises(ValueError, func, 'fbsp1.0') + assert_raises(ValueError, func, 'fbsp1.0-0.4') + assert_raises(ValueError, func, 'fbsp1-1-1-1') + + +@pytest.mark.parametrize('dtype, tol, method', + [(np.float32, 1e-5, 'conv'), + (np.float32, 1e-5, 'fft'), + (np.float64, 1e-13, 'conv'), + (np.float64, 1e-13, 'fft')]) +def test_cwt_complex(dtype, tol, method): + time, sst = pywt.data.nino() + sst = np.asarray(sst, dtype=dtype) + dt = time[1] - time[0] + wavelet = 'cmor1.5-1.0' + scales = np.arange(1, 32) + + # real-valued tranfsorm as a reference + [cfs, f] = pywt.cwt(sst, scales, wavelet, dt, method=method) + + # verify same precision + assert_equal(cfs.real.dtype, sst.dtype) + + # complex-valued transform equals sum of the transforms of the real + # and imaginary components + sst_complex = sst + 1j*sst + [cfs_complex, f] = pywt.cwt(sst_complex, scales, wavelet, dt, + method=method) + assert_allclose(cfs + 1j*cfs, cfs_complex, atol=tol, rtol=tol) + # verify dtype is preserved + assert_equal(cfs_complex.dtype, sst_complex.dtype) + + +@pytest.mark.parametrize('axis, method', list(product([0, 1], ['conv', 'fft']))) +def test_cwt_batch(axis, method): + dtype = np.float64 + time, sst = pywt.data.nino() + n_batch = 8 + batch_axis = 1 - axis + sst1 = np.asarray(sst, dtype=dtype) + sst = np.stack((sst1, ) * n_batch, axis=batch_axis) + dt = time[1] - time[0] + wavelet = 'cmor1.5-1.0' + scales = np.arange(1, 32) + + # non-batch transform as reference + [cfs1, f] = pywt.cwt(sst1, scales, wavelet, dt, method=method, axis=axis) + + shape_in = sst.shape + [cfs, f] = pywt.cwt(sst, scales, wavelet, dt, method=method, axis=axis) + + # shape of input is not modified + assert_equal(shape_in, sst.shape) + + # verify same precision + assert_equal(cfs.real.dtype, sst.dtype) + + # verify expected shape + assert_equal(cfs.shape[0], len(scales)) + assert_equal(cfs.shape[1 + batch_axis], n_batch) + assert_equal(cfs.shape[1 + axis], sst.shape[axis]) + + # batch result on stacked input is the same as stacked 1d result + assert_almost_equal(cfs, np.stack((cfs1,) * n_batch, axis=batch_axis + 1), + decimal=12) + + +def test_cwt_small_scales(): + data = np.zeros(32) + + # A scale of 0.1 was chosen specifically to give a filter of length 2 for + # mexh. This corner case should not raise an error. + cfs, f = pywt.cwt(data, scales=0.1, wavelet='mexh') + assert_allclose(cfs, np.zeros_like(cfs)) + + # extremely short scale factors raise a ValueError + assert_raises(ValueError, pywt.cwt, data, scales=0.01, wavelet='mexh') + +def test_cwt_zero_scale(): + data = np.zeros(32) + scales = np.arange(0, 4) + + # scale that includes 0 throws ValueError to prevent IndexError + assert_raises(ValueError, pywt.cwt, data, scales=scales, wavelet='morl') + +def test_cwt_negative_scale(): + data = np.zeros(32) + scales = np.asarray([-1, -2, -3]) + + # scale that includes negative values throws ValueError to prevent IndexError + assert_raises(ValueError, pywt.cwt, data, scales=scales, wavelet='morl') + + +def test_cwt_method_fft(): + rstate = np.random.RandomState(1) + data = rstate.randn(50) + data[15] = 1. + scales = np.arange(1, 64) + wavelet = 'cmor1.5-1.0' + + # build a reference cwt with the legacy np.conv() method + cfs_conv, _ = pywt.cwt(data, scales, wavelet, method='conv') + + # compare with the fft based convolution + cfs_fft, _ = pywt.cwt(data, scales, wavelet, method='fft') + assert_allclose(cfs_conv, cfs_fft, rtol=0, atol=1e-13) + + +@pytest.mark.parametrize('dtype, tol', [(np.float32, 1e-5), + (np.float64, 1e-13)]) +@pytest.mark.parametrize('shape, axis', [((49,), -1), + ((3, 50), 1), + ((49, 3), 0)]) +def test_cwt_method_fft_real(dtype, tol, shape, axis): + rstate = np.random.RandomState(1) + data = rstate.randn(*shape).astype(dtype) + scales = np.r_[1.0625, np.arange(1, 64)] + + cfs_conv, _ = pywt.cwt( + data, scales, 'morl', method='conv', axis=axis + ) + cfs_fft, _ = pywt.cwt( + data, scales, 'morl', method='fft', axis=axis + ) + + assert_equal(cfs_fft.dtype, dtype) + assert_allclose(cfs_conv, cfs_fft, rtol=tol, atol=tol) + + +@pytest.mark.parametrize('dtype, tol', [(np.complex64, 1e-5), + (np.complex128, 1e-13)]) +def test_cwt_method_fft_complex_data_real_wavelet(dtype, tol): + rstate = np.random.RandomState(1) + data = (rstate.randn(49) + 1j * rstate.randn(49)).astype(dtype) + scales = np.r_[1.0625, np.arange(1, 16)] + + cfs_conv, _ = pywt.cwt(data, scales, 'morl', method='conv') + cfs_fft, _ = pywt.cwt(data, scales, 'morl', method='fft') + + assert_equal(cfs_fft.dtype, dtype) + assert_allclose(cfs_conv, cfs_fft, rtol=tol, atol=tol) + + +def test_cwt_normalization_convention(): + # cwt works in units of samples: with the scale a and the shift b both + # given in samples, coefs[a, b] == 1/sqrt(a) * sum_n x[n] conj(psi((n-b)/a)) + # and no sampling interval enters. + fs = 3000. + Fb, Fc = 14., 2. + wavelet = pywt.ContinuousWavelet(f'cmor{Fb:g}-{Fc:g}') + x = np.sin(2 * np.pi * 40 * np.arange(3000) / fs) + scale = pywt.frequency2scale(wavelet, 40 / fs) + + cfs, freqs = pywt.cwt(x, scale, wavelet, sampling_period=1 / fs) + assert_allclose(freqs, [40.], rtol=1e-12) + + # psi is sampled at bin midpoints because cwt convolves with the integral + # of psi and then differences it, which averages psi over each sample bin. + lb, ub = wavelet.lower_bound, wavelet.upper_bound + k = np.arange(int(scale * (ub - lb)) + 1) + psi, _ = ref_cmor(lb + 0.5 / scale, ub + 0.5 / scale, k.size, Fb, Fc) + # the filter is conjugated *and* reversed; convolving with conj(psi) alone + # gives the complex conjugate of the correct result, which an abs() + # comparison would not catch + conv = np.convolve(x, np.conj(psi)[::-1]) / np.sqrt(scale) + trim = (conv.size - x.size) // 2 + manual = conv[trim:trim + x.size] + + assert_allclose(manual, cfs[0], atol=1e-3 * np.max(np.abs(cfs[0]))) + + # the coefficients themselves are unaffected by sampling_period + cfs_unit, freqs_unit = pywt.cwt(x, scale, wavelet, sampling_period=1.) + assert_allclose(cfs_unit, cfs, rtol=0, atol=0) + assert_allclose(freqs_unit * fs, freqs, rtol=1e-12) + + +def test_continuous_wavelet_pickle(tmpdir): + wavelet = pywt.ContinuousWavelet('cmor1.5-1.0') + filename = os.path.join(tmpdir, 'cwav.pickle') + with open(filename, 'wb') as f: + pickle.dump(wavelet, f) + with open(filename, 'rb') as f: + wavelet2 = pickle.load(f) + assert isinstance(wavelet2, pywt.ContinuousWavelet) + assert wavelet2.name == wavelet.name + + +def test_cwt_discrete_wavelet_raises(): + # A discrete wavelet such as 'coif1' has no continuous form; cwt should + # raise a clear error rather than an opaque AttributeError (gh-776). + data = np.ones(100) + for bad in ['coif1', 'db2', pywt.Wavelet('coif1')]: + with pytest.raises(ValueError, match='continuous wavelet'): + pywt.cwt(data, [1, 2], bad) + + # a continuous wavelet still works + out, _ = pywt.cwt(data, [1, 2], 'morl') + assert out.shape == (2, 100) diff --git a/.venv/lib/python3.12/site-packages/pywt/tests/test_data.py b/.venv/lib/python3.12/site-packages/pywt/tests/test_data.py new file mode 100644 index 0000000000000000000000000000000000000000..e1cf68fbcf4e4bb1b000ca8f4202870015209ca8 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/pywt/tests/test_data.py @@ -0,0 +1,78 @@ +import os + +import numpy as np +from numpy.testing import assert_, assert_allclose, assert_raises + +import pywt.data + +data_dir = os.path.join(os.path.dirname(__file__), 'data') +wavelab_data_file = os.path.join(data_dir, 'wavelab_test_signals.npz') +wavelab_result_dict = np.load(wavelab_data_file) + + +def test_data_aero(): + aero = pywt.data.aero() + + ref = np.array([[178, 178, 179], + [170, 173, 171], + [185, 174, 171]]) + + assert_allclose(aero[:3, :3], ref) + + +def test_data_ascent(): + ascent = pywt.data.ascent() + + ref = np.array([[83, 83, 83], + [82, 82, 83], + [80, 81, 83]]) + + assert_allclose(ascent[:3, :3], ref) + + +def test_data_camera(): + camera = pywt.data.camera() + + ref = np.array([[200, 200, 200], + [200, 199, 199], + [199, 199, 199]]) + + assert_allclose(camera[:3, :3], ref) + + +def test_data_ecg(): + ecg = pywt.data.ecg() + + ref = np.array([-86, -87, -87]) + + assert_allclose(ecg[:3], ref) + + +def test_wavelab_signals(): + """Comparison with results generated using WaveLab""" + rtol = atol = 1e-12 + + # get a list of the available signals + available_signals = pywt.data.demo_signal('list') + assert_('Doppler' in available_signals) + + for signal in available_signals: + # reference dictionary has lowercase names for the keys + key = signal.replace('-', '_').lower() + val = wavelab_result_dict[key] + if key in ['gabor', 'sineoneoverx']: + # these functions do not allow a size to be provided + assert_allclose(val, pywt.data.demo_signal(signal), + rtol=rtol, atol=atol) + assert_raises(ValueError, pywt.data.demo_signal, key, val.size) + else: + assert_allclose(val, pywt.data.demo_signal(signal, val.size), + rtol=rtol, atol=atol) + # these functions require a size to be provided + assert_raises(ValueError, pywt.data.demo_signal, key) + + # ValueError on unrecognized signal type + assert_raises(ValueError, pywt.data.demo_signal, 'unknown_signal', 512) + + # ValueError on invalid length + assert_raises(ValueError, pywt.data.demo_signal, 'Doppler', 0) diff --git a/.venv/lib/python3.12/site-packages/pywt/tests/test_deprecations.py b/.venv/lib/python3.12/site-packages/pywt/tests/test_deprecations.py new file mode 100644 index 0000000000000000000000000000000000000000..c8f85fdebe1de8c876310b860e3b1542fca9b4d7 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/pywt/tests/test_deprecations.py @@ -0,0 +1,76 @@ +import warnings + +import numpy as np +import pytest +from numpy.testing import assert_array_equal + +import pywt + + +def test_intwave_deprecation(): + wavelet = pywt.Wavelet('db3') + with pytest.warns(DeprecationWarning): + pywt.intwave(wavelet) + + +def test_centrfrq_deprecation(): + wavelet = pywt.Wavelet('db3') + with pytest.warns(DeprecationWarning): + pywt.centrfrq(wavelet) + + +def test_scal2frq_deprecation(): + wavelet = pywt.Wavelet('db3') + with pytest.warns(DeprecationWarning): + pywt.scal2frq(wavelet, 1) + + +def test_orthfilt_deprecation(): + with pytest.warns(DeprecationWarning): + pywt.orthfilt(range(6)) + + +def test_integrate_wave_tuple(): + sig = [0, 1, 2, 3] + xgrid = [0, 1, 2, 3] + with pytest.warns(DeprecationWarning): + pywt.integrate_wavelet((sig, xgrid)) + + +old_modes = ['zpd', + 'cpd', + 'sym', + 'ppd', + 'sp1', + 'per', + ] + + +def test_MODES_from_object_deprecation(): + for mode in old_modes: + with pytest.warns(DeprecationWarning): + pywt.Modes.from_object(mode) + + +def test_MODES_attributes_deprecation(): + def get_mode(Modes, name): + return getattr(Modes, name) + + for mode in old_modes: + with pytest.warns(DeprecationWarning): + get_mode(pywt.Modes, mode) + + +def test_mode_equivalence(): + old_new = [('zpd', 'zero'), + ('cpd', 'constant'), + ('sym', 'symmetric'), + ('ppd', 'periodic'), + ('sp1', 'smooth'), + ('per', 'periodization')] + x = np.arange(8.) + with warnings.catch_warnings(): + warnings.simplefilter('ignore', DeprecationWarning) + for old, new in old_new: + assert_array_equal(pywt.dwt(x, 'db2', mode=old), + pywt.dwt(x, 'db2', mode=new)) diff --git a/.venv/lib/python3.12/site-packages/pywt/tests/test_doc.py b/.venv/lib/python3.12/site-packages/pywt/tests/test_doc.py new file mode 100644 index 0000000000000000000000000000000000000000..ea9bb3ee2579393508b81419e4ed137e5885d81d --- /dev/null +++ b/.venv/lib/python3.12/site-packages/pywt/tests/test_doc.py @@ -0,0 +1,25 @@ + +import doctest +import glob +import os +import sys +import unittest + +try: + import numpy as np + np.set_printoptions(legacy='1.13') +except TypeError: + pass + +pdir = os.path.pardir +docs_base = os.path.abspath(os.path.join(os.path.dirname(__file__), + pdir, pdir, "doc", "source")) + +files = glob.glob(os.path.join(docs_base, "*.rst")) + \ + glob.glob(os.path.join(docs_base, "*", "*.rst")) + +suite = doctest.DocFileSuite(*files, module_relative=False, encoding="utf-8") + + +if __name__ == "__main__": + sys.exit(int(not unittest.TextTestRunner().run(suite).wasSuccessful())) diff --git a/.venv/lib/python3.12/site-packages/pywt/tests/test_dwt_idwt.py b/.venv/lib/python3.12/site-packages/pywt/tests/test_dwt_idwt.py new file mode 100644 index 0000000000000000000000000000000000000000..411e4c8eb53d6b4bf5025cce5ad8e350e2e8cb5c --- /dev/null +++ b/.venv/lib/python3.12/site-packages/pywt/tests/test_dwt_idwt.py @@ -0,0 +1,375 @@ +#!/usr/bin/env python + +import numpy as np +from numpy.testing import assert_, assert_allclose, assert_array_equal, assert_raises + +import pywt + +# Check that float32, float64, complex64, complex128 are preserved. +# Other real types get converted to float64. +# complex256 gets converted to complex128 +dtypes_in = [np.int8, np.float16, np.float32, np.float64, np.complex64, + np.complex128] +dtypes_out = [np.float64, np.float32, np.float32, np.float64, np.complex64, + np.complex128] + +# test complex256 as well if it is available +try: + dtypes_in += [np.complex256, ] + dtypes_out += [np.complex128, ] +except AttributeError: + pass + + +def test_dwt_idwt_basic(): + x = [3, 7, 1, 1, -2, 5, 4, 6] + cA, cD = pywt.dwt(x, 'db2') + cA_expect = [5.65685425, 7.39923721, 0.22414387, 3.33677403, 7.77817459] + cD_expect = [-2.44948974, -1.60368225, -4.44140056, -0.41361256, + 1.22474487] + assert_allclose(cA, cA_expect) + assert_allclose(cD, cD_expect) + + x_roundtrip = pywt.idwt(cA, cD, 'db2') + assert_allclose(x_roundtrip, x, rtol=1e-10) + + # mismatched dtypes OK + x_roundtrip2 = pywt.idwt(cA.astype(np.float64), cD.astype(np.float32), + 'db2') + assert_allclose(x_roundtrip2, x, rtol=1e-7, atol=1e-7) + assert_(x_roundtrip2.dtype == np.float64) + + +def test_idwt_mixed_complex_dtype(): + x = np.arange(8).astype(float) + x = x + 1j*x[::-1] + cA, cD = pywt.dwt(x, 'db2') + + x_roundtrip = pywt.idwt(cA, cD, 'db2') + assert_allclose(x_roundtrip, x, rtol=1e-10) + + # mismatched dtypes OK + x_roundtrip2 = pywt.idwt(cA.astype(np.complex128), cD.astype(np.complex64), + 'db2') + assert_allclose(x_roundtrip2, x, rtol=1e-7, atol=1e-7) + assert_(x_roundtrip2.dtype == np.complex128) + + +def test_dwt_idwt_dtypes(): + wavelet = pywt.Wavelet('haar') + for dt_in, dt_out in zip(dtypes_in, dtypes_out): + x = np.ones(4, dtype=dt_in) + errmsg = f"wrong dtype returned for {dt_in} input" + + cA, cD = pywt.dwt(x, wavelet) + assert_(cA.dtype == cD.dtype == dt_out, "dwt: " + errmsg) + + x_roundtrip = pywt.idwt(cA, cD, wavelet) + assert_(x_roundtrip.dtype == dt_out, "idwt: " + errmsg) + + +def test_dwt_idwt_basic_complex(): + x = np.asarray([3, 7, 1, 1, -2, 5, 4, 6]) + x = x + 0.5j*x + cA, cD = pywt.dwt(x, 'db2') + cA_expect = np.asarray([5.65685425, 7.39923721, 0.22414387, 3.33677403, + 7.77817459]) + cA_expect = cA_expect + 0.5j*cA_expect + cD_expect = np.asarray([-2.44948974, -1.60368225, -4.44140056, -0.41361256, + 1.22474487]) + cD_expect = cD_expect + 0.5j*cD_expect + assert_allclose(cA, cA_expect) + assert_allclose(cD, cD_expect) + + x_roundtrip = pywt.idwt(cA, cD, 'db2') + assert_allclose(x_roundtrip, x, rtol=1e-10) + + +def test_dwt_idwt_partial_complex(): + x = np.asarray([3, 7, 1, 1, -2, 5, 4, 6]) + x = x + 0.5j*x + + cA, cD = pywt.dwt(x, 'haar') + cA_rec_expect = np.array([5.0+2.5j, 5.0+2.5j, 1.0+0.5j, 1.0+0.5j, + 1.5+0.75j, 1.5+0.75j, 5.0+2.5j, 5.0+2.5j]) + cA_rec = pywt.idwt(cA, None, 'haar') + assert_allclose(cA_rec, cA_rec_expect) + + cD_rec_expect = np.array([-2.0-1.0j, 2.0+1.0j, 0.0+0.0j, 0.0+0.0j, + -3.5-1.75j, 3.5+1.75j, -1.0-0.5j, 1.0+0.5j]) + cD_rec = pywt.idwt(None, cD, 'haar') + assert_allclose(cD_rec, cD_rec_expect) + + assert_allclose(cA_rec + cD_rec, x) + + +def test_dwt_wavelet_kwd(): + x = np.array([3, 7, 1, 1, -2, 5, 4, 6]) + w = pywt.Wavelet('sym3') + cA, cD = pywt.dwt(x, wavelet=w, mode='constant') + cA_expect = [4.38354585, 3.80302657, 7.31813271, -0.58565539, 4.09727044, + 7.81994027] + cD_expect = [-1.33068221, -2.78795192, -3.16825651, -0.67715519, + -0.09722957, -0.07045258] + assert_allclose(cA, cA_expect) + assert_allclose(cD, cD_expect) + + +def test_dwt_coeff_len(): + x = np.array([3, 7, 1, 1, -2, 5, 4, 6]) + w = pywt.Wavelet('sym3') + ln_modes = [pywt.dwt_coeff_len(len(x), w.dec_len, mode) for mode in + pywt.Modes.modes] + + expected_result = [6, ] * len(pywt.Modes.modes) + expected_result[pywt.Modes.modes.index('periodization')] = 4 + + assert_allclose(ln_modes, expected_result) + ln_modes = [pywt.dwt_coeff_len(len(x), w, mode) for mode in + pywt.Modes.modes] + assert_allclose(ln_modes, expected_result) + + +def test_idwt_none_input(): + # None input equals arrays of zeros of the right length + res1 = pywt.idwt([1, 2, 0, 1], None, 'db2', 'symmetric') + res2 = pywt.idwt([1, 2, 0, 1], [0, 0, 0, 0], 'db2', 'symmetric') + assert_allclose(res1, res2, rtol=1e-15, atol=1e-15) + + res1 = pywt.idwt(None, [1, 2, 0, 1], 'db2', 'symmetric') + res2 = pywt.idwt([0, 0, 0, 0], [1, 2, 0, 1], 'db2', 'symmetric') + assert_allclose(res1, res2, rtol=1e-15, atol=1e-15) + + # Only one argument at a time can be None + assert_raises(ValueError, pywt.idwt, None, None, 'db2', 'symmetric') + + +def test_idwt_invalid_input(): + # Too short, min length is 4 for 'db4': + assert_raises(ValueError, pywt.idwt, [1, 2, 4], [4, 1, 3], 'db4', 'symmetric') + + +def test_dwt_single_axis(): + x = [[3, 7, 1, 1], + [-2, 5, 4, 6]] + + cA, cD = pywt.dwt(x, 'db2', axis=-1) + + cA0, cD0 = pywt.dwt(x[0], 'db2') + cA1, cD1 = pywt.dwt(x[1], 'db2') + + assert_allclose(cA[0], cA0) + assert_allclose(cA[1], cA1) + + assert_allclose(cD[0], cD0) + assert_allclose(cD[1], cD1) + + +def test_idwt_single_axis(): + x = [[3, 7, 1, 1], + [-2, 5, 4, 6]] + + x = np.asarray(x) + x = x + 1j*x # test with complex data + cA, cD = pywt.dwt(x, 'db2', axis=-1) + + x0 = pywt.idwt(cA[0], cD[0], 'db2', axis=-1) + x1 = pywt.idwt(cA[1], cD[1], 'db2', axis=-1) + + assert_allclose(x[0], x0) + assert_allclose(x[1], x1) + +def test_dwt_invalid_input(): + x = np.arange(1) + assert_raises(ValueError, pywt.dwt, x, 'db2', 'reflect') + assert_raises(ValueError, pywt.dwt, x, 'haar', 'antireflect') + + +def test_dwt_axis_arg(): + x = [[3, 7, 1, 1], + [-2, 5, 4, 6]] + + cA_, cD_ = pywt.dwt(x, 'db2', axis=-1) + cA, cD = pywt.dwt(x, 'db2', axis=1) + + assert_allclose(cA_, cA) + assert_allclose(cD_, cD) + +def test_dwt_axis_invalid_input(): + x = np.ones((3,1)) + assert_raises(ValueError, pywt.dwt, x, 'db2', 'reflect') + +def test_idwt_axis_arg(): + x = [[3, 7, 1, 1], + [-2, 5, 4, 6]] + + cA, cD = pywt.dwt(x, 'db2', axis=1) + + x_ = pywt.idwt(cA, cD, 'db2', axis=-1) + x = pywt.idwt(cA, cD, 'db2', axis=1) + + assert_allclose(x_, x) + + +def test_dwt_idwt_axis_excess(): + x = [[3, 7, 1, 1], + [-2, 5, 4, 6]] + # can't transform over axes that aren't there + assert_raises(ValueError, + pywt.dwt, x, 'db2', 'symmetric', axis=2) + + assert_raises(ValueError, + pywt.idwt, [1, 2, 4], [4, 1, 3], 'db2', 'symmetric', axis=1) + + +def test_error_on_continuous_wavelet(): + # A ValueError is raised if a Continuous wavelet is selected + data = np.ones((32, )) + for cwave in ['morl', pywt.DiscreteContinuousWavelet('morl')]: + assert_raises(ValueError, pywt.dwt, data, cwave) + + cA, cD = pywt.dwt(data, 'db1') + assert_raises(ValueError, pywt.idwt, cA, cD, cwave) + + +def test_dwt_zero_size_axes(): + # raise on empty input array + assert_raises(ValueError, pywt.dwt, [], 'db2') + + # >1D case uses a different code path so check there as well + x = np.ones((1, 4))[0:0, :] # 2D with a size zero axis + assert_raises(ValueError, pywt.dwt, x, 'db2', axis=0) + + +def test_dwt_readonly_array(): + data = np.random.randn(1000).astype(np.float64) + data.setflags(write=False) + pywt.dwt(data, "db4") + + +def test_pad_1d(): + x = [1, 2, 3] + assert_array_equal(pywt.pad(x, (4, 6), 'periodization'), + [1, 2, 3, 3, 1, 2, 3, 3, 1, 2, 3, 3, 1, 2]) + assert_array_equal(pywt.pad(x, (4, 6), 'periodic'), + [3, 1, 2, 3, 1, 2, 3, 1, 2, 3, 1, 2, 3]) + assert_array_equal(pywt.pad(x, (4, 6), 'constant'), + [1, 1, 1, 1, 1, 2, 3, 3, 3, 3, 3, 3, 3]) + assert_array_equal(pywt.pad(x, (4, 6), 'zero'), + [0, 0, 0, 0, 1, 2, 3, 0, 0, 0, 0, 0, 0]) + assert_array_equal(pywt.pad(x, (4, 6), 'smooth'), + [-3, -2, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9]) + assert_array_equal(pywt.pad(x, (4, 6), 'symmetric'), + [3, 3, 2, 1, 1, 2, 3, 3, 2, 1, 1, 2, 3]) + assert_array_equal(pywt.pad(x, (4, 6), 'antisymmetric'), + [3, -3, -2, -1, 1, 2, 3, -3, -2, -1, 1, 2, 3]) + assert_array_equal(pywt.pad(x, (4, 6), 'reflect'), + [1, 2, 3, 2, 1, 2, 3, 2, 1, 2, 3, 2, 1]) + assert_array_equal(pywt.pad(x, (4, 6), 'antireflect'), + [-3, -2, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9]) + + # equivalence of various pad_width formats + assert_array_equal(pywt.pad(x, 4, 'periodic'), + pywt.pad(x, (4, 4), 'periodic')) + + assert_array_equal(pywt.pad(x, (4, ), 'periodic'), + pywt.pad(x, (4, 4), 'periodic')) + + assert_array_equal(pywt.pad(x, [(4, 4)], 'periodic'), + pywt.pad(x, (4, 4), 'periodic')) + + +def test_pad_zero_width(): + # zero pad width is a no-op for all modes except 'periodization', which + # also promotes odd-length axes to even length (gh-589) + for ndim in [1, 2, 3]: + x = np.arange(3.0**ndim).reshape((3, ) * ndim) + for mode in pywt.Modes.modes: + if mode == 'periodization': + continue + assert_array_equal(pywt.pad(x, 0, mode), x, + err_msg=f"mode={mode}, ndim={ndim}") + + assert_array_equal(pywt.pad([1, 2, 3], 0, 'periodization'), [1, 2, 3, 3]) + + +def test_pad_zero_size_axis(): + # a zero-size axis has nothing to extend from, so a zero pad width leaves + # it alone rather than raising or (for 'antisymmetric') hanging (gh-589) + x = np.ones((0, 4)) + for mode in pywt.Modes.modes: + assert_array_equal(pywt.pad(x, 0, mode), x, err_msg=f"mode={mode}") + + # padding along the other axis only + assert_(pywt.pad(x, ((0, 0), (2, 2)), 'antisymmetric').shape == (0, 8)) + + +def test_pad_one_sided(): + # a zero pad width on only one side of the axis (gh-589) + x = [1, 2, 3] + assert_array_equal(pywt.pad(x, (2, 0), 'smooth'), [-1, 0, 1, 2, 3]) + assert_array_equal(pywt.pad(x, (0, 2), 'smooth'), [1, 2, 3, 4, 5]) + assert_array_equal(pywt.pad(x, (2, 0), 'antisymmetric'), [-2, -1, 1, 2, 3]) + assert_array_equal(pywt.pad(x, (0, 2), 'antisymmetric'), [1, 2, 3, -3, -2]) + + # one-sided padding matches the corresponding slice of two-sided padding + for mode in pywt.Modes.modes: + if mode == 'periodization': + continue + two_sided = pywt.pad(x, (4, 6), mode) + assert_array_equal(pywt.pad(x, (4, 0), mode), two_sided[:-6], + err_msg=f"mode={mode}") + assert_array_equal(pywt.pad(x, (0, 6), mode), two_sided[4:], + err_msg=f"mode={mode}") + + +def test_pad_smooth_short_signal(): + # the slope used by 'smooth' is undefined for a signal shorter than two + # samples, so constant edge extension is used instead (gh-589) + assert_array_equal(pywt.pad([1.], 0, 'smooth'), [1.]) + assert_array_equal(pywt.pad([1.], (2, 3), 'smooth'), + pywt.pad([1.], (2, 3), 'constant')) + + # only the length 1 axis of an nd array falls back + x = np.arange(3.0).reshape(1, 3) + assert_array_equal(pywt.pad(x, ((0, 0), (2, 2)), 'smooth'), + [[-2, -1, 0, 1, 2, 3, 4]]) + assert_array_equal(pywt.pad(x, ((2, 2), (0, 0)), 'smooth'), + np.tile(x, (5, 1))) + + # matches the fallback used by the transforms + assert_allclose(pywt.dwt([1.], 'db2', 'smooth'), + pywt.dwt([1.], 'db2', 'constant')) + + +def test_pad_errors(): + # negative pad width + x = [1, 2, 3] + assert_raises(ValueError, pywt.pad, x, -2, 'periodic') + + # wrong length pad width + assert_raises(ValueError, pywt.pad, x, (1, 1, 1), 'periodic') + + # invalid mode name + assert_raises(ValueError, pywt.pad, x, 2, 'bad_mode') + + +def test_pad_nd(): + for ndim in [2, 3]: + x = np.arange(4**ndim).reshape((4, ) * ndim) + if ndim == 2: + pad_widths = [(2, 1), (2, 3)] + else: + pad_widths = [(2, 1), ] * ndim + for mode in pywt.Modes.modes: + xp = pywt.pad(x, pad_widths, mode) + + # expected result is the same as applying along axes separably + xp_expected = x.copy() + for ax in range(ndim): + xp_expected = np.apply_along_axis(pywt.pad, + ax, + xp_expected, + pad_widths=[pad_widths[ax]], + mode=mode) + assert_array_equal(xp, xp_expected) diff --git a/.venv/lib/python3.12/site-packages/pywt/tests/test_functions.py b/.venv/lib/python3.12/site-packages/pywt/tests/test_functions.py new file mode 100644 index 0000000000000000000000000000000000000000..03bc1ee4ef22904ebd3f1ec823138b70de3f443f --- /dev/null +++ b/.venv/lib/python3.12/site-packages/pywt/tests/test_functions.py @@ -0,0 +1,44 @@ +#!/usr/bin/env python + +from numpy.testing import assert_allclose, assert_almost_equal + +import pywt + + +def test_centrfreq(): + # db1 is Haar function, frequency=1 + w = pywt.Wavelet('db1') + expected = 1 + result = pywt.central_frequency(w, precision=12) + assert_almost_equal(result, expected, decimal=3) + # db2, frequency=2/3 + w = pywt.Wavelet('db2') + expected = 2/3. + result = pywt.central_frequency(w, precision=12) + assert_almost_equal(result, expected) + + +def test_scal2frq_scale(): + scale = 2 + w = pywt.Wavelet('db1') + expected = 1. / scale + result = pywt.scale2frequency(w, scale, precision=12) + assert_almost_equal(result, expected, decimal=3) + +def test_frq2scal_freq(): + freq = 2 + w = pywt.Wavelet('db1') + expected = 1. / freq + result = pywt.frequency2scale(w, freq, precision=12) + assert_almost_equal(result, expected, decimal=3) + + +def test_intwave_orthogonal(): + w = pywt.Wavelet('db1') + int_psi, x = pywt.integrate_wavelet(w, precision=12) + ix = x < 0.5 + # For x < 0.5, the integral is equal to x + assert_allclose(int_psi[ix], x[ix]) + # For x > 0.5, the integral is equal to (1 - x) + # Ignore last point here, there x > 1 and something goes wrong + assert_allclose(int_psi[~ix][:-1], 1 - x[~ix][:-1], atol=1e-10) diff --git a/.venv/lib/python3.12/site-packages/pywt/tests/test_matlab_compatibility.py b/.venv/lib/python3.12/site-packages/pywt/tests/test_matlab_compatibility.py new file mode 100644 index 0000000000000000000000000000000000000000..9a79e6e151b3a9066554281acc99926665289587 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/pywt/tests/test_matlab_compatibility.py @@ -0,0 +1,159 @@ +""" +Test used to verify PyWavelets Discrete Wavelet Transform computation +accuracy against MathWorks Wavelet Toolbox. +""" + + +import numpy as np +import pytest +from numpy.testing import assert_ + +import pywt +from pywt._pytest import matlab_result_dict_dwt as matlab_result_dict +from pywt._pytest import size_set, uses_precomputed, uses_pymatbridge + +# list of mode names in pywt and matlab +modes = [('zero', 'zpd'), + ('constant', 'sp0'), + ('symmetric', 'sym'), + ('reflect', 'symw'), + ('periodic', 'ppd'), + ('smooth', 'sp1'), + ('periodization', 'per'), + # TODO: Now have implemented asymmetric modes too. + # Would be nice to update the Matlab data to test these as well. + ('antisymmetric', 'asym'), + ('antireflect', 'asymw'), + ] + +families = ('db', 'sym', 'coif', 'bior', 'rbio') +wavelets = sum([pywt.wavelist(name) for name in families], []) + + +def _get_data_sizes(w): + """ Return the sizes to test for wavelet w. """ + if size_set == 'full': + data_sizes = list(range(w.dec_len, 40)) + \ + [100, 200, 500, 1000, 50000] + else: + data_sizes = (w.dec_len, w.dec_len + 1) + return data_sizes + + +@uses_pymatbridge +@pytest.mark.slow +def test_accuracy_pymatbridge(): + Matlab = pytest.importorskip("pymatbridge.Matlab") + mlab = Matlab() + + rstate = np.random.RandomState(1234) + # max RMSE (was 1.0e-10, is reduced to 5.0e-5 due to different coefficients) + epsilon = 5.0e-5 + epsilon_pywt_coeffs = 1.0e-10 + mlab.start() + try: + for wavelet in wavelets: + w = pywt.Wavelet(wavelet) + mlab.set_variable('wavelet', wavelet) + for N in _get_data_sizes(w): + data = rstate.randn(N) + mlab.set_variable('data', data) + for pmode, mmode in modes: + ma, md = _compute_matlab_result(data, wavelet, mmode, mlab) + _check_accuracy(data, w, pmode, ma, md, wavelet, epsilon) + ma, md = _load_matlab_result_pywt_coeffs(data, wavelet, mmode) + _check_accuracy(data, w, pmode, ma, md, wavelet, epsilon_pywt_coeffs) + + finally: + mlab.stop() + + +@uses_precomputed +@pytest.mark.slow +def test_accuracy_precomputed(): + # Keep this specific random seed to match the precomputed Matlab result. + rstate = np.random.RandomState(1234) + # max RMSE (was 1.0e-10, is reduced to 5.0e-5 due to different coefficients) + epsilon = 5.0e-5 + epsilon_pywt_coeffs = 1.0e-10 + for wavelet in wavelets: + w = pywt.Wavelet(wavelet) + for N in _get_data_sizes(w): + data = rstate.randn(N) + for pmode, mmode in modes: + ma, md = _load_matlab_result(data, wavelet, mmode) + _check_accuracy(data, w, pmode, ma, md, wavelet, epsilon) + ma, md = _load_matlab_result_pywt_coeffs(data, wavelet, mmode) + _check_accuracy(data, w, pmode, ma, md, wavelet, epsilon_pywt_coeffs) + + +def _compute_matlab_result(data, wavelet, mmode, mlab): + """ Compute the result using MATLAB. + + This function assumes that the Matlab variables `wavelet` and `data` have + already been set externally. + """ + if np.any((wavelet == np.array(['coif6', 'coif7', 'coif8', 'coif9', 'coif10', 'coif11', 'coif12', 'coif13', 'coif14', 'coif15', 'coif16', 'coif17'])),axis=0): + w = pywt.Wavelet(wavelet) + mlab.set_variable('Lo_D', w.dec_lo) + mlab.set_variable('Hi_D', w.dec_hi) + mlab_code = f"[ma, md] = dwt(data, Lo_D, Hi_D, 'mode', '{mmode}');" + else: + mlab_code = f"[ma, md] = dwt(data, wavelet, 'mode', '{mmode}');" + res = mlab.run_code(mlab_code) + if not res['success']: + raise RuntimeError("Matlab failed to execute the provided code. " + "Check that the wavelet toolbox is installed.") + # need np.asarray because sometimes the output is a single float64 + ma = np.asarray(mlab.get_variable('ma')) + md = np.asarray(mlab.get_variable('md')) + return ma, md + + +def _load_matlab_result(data, wavelet, mmode): + """ Load the precomputed result. + """ + N = len(data) + ma_key = '_'.join([mmode, wavelet, str(N), 'ma']) + md_key = '_'.join([mmode, wavelet, str(N), 'md']) + if (ma_key not in matlab_result_dict) or \ + (md_key not in matlab_result_dict): + raise KeyError( + "Precompted Matlab result not found for wavelet: " + f"{wavelet}, mode: {mmode}, size: {N}") + ma = matlab_result_dict[ma_key] + md = matlab_result_dict[md_key] + return ma, md + + +def _load_matlab_result_pywt_coeffs(data, wavelet, mmode): + """ Load the precomputed result. + """ + N = len(data) + ma_key = '_'.join([mmode, wavelet, str(N), 'ma_pywtCoeffs']) + md_key = '_'.join([mmode, wavelet, str(N), 'md_pywtCoeffs']) + if (ma_key not in matlab_result_dict) or \ + (md_key not in matlab_result_dict): + raise KeyError( + "Precompted Matlab result not found for wavelet: " + f"{wavelet}, mode: {mmode}, size: {N}") + ma = matlab_result_dict[ma_key] + md = matlab_result_dict[md_key] + return ma, md + + +def _check_accuracy(data, w, pmode, ma, md, wavelet, epsilon): + # PyWavelets result + pa, pd = pywt.dwt(data, w, pmode) + + # calculate error measures + rms_a = np.sqrt(np.mean((pa - ma) ** 2)) + rms_d = np.sqrt(np.mean((pd - md) ** 2)) + + msg = ('[RMS_A > EPSILON] for Mode: %s, Wavelet: %s, ' + 'Length: %d, rms=%.3g' % (pmode, wavelet, len(data), rms_a)) + assert_(rms_a < epsilon, msg=msg) + + msg = ('[RMS_D > EPSILON] for Mode: %s, Wavelet: %s, ' + 'Length: %d, rms=%.3g' % (pmode, wavelet, len(data), rms_d)) + assert_(rms_d < epsilon, msg=msg) diff --git a/.venv/lib/python3.12/site-packages/pywt/tests/test_matlab_compatibility_cwt.py b/.venv/lib/python3.12/site-packages/pywt/tests/test_matlab_compatibility_cwt.py new file mode 100644 index 0000000000000000000000000000000000000000..7819c50fbca83121d3ce92c5fce0cb3880ff8da4 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/pywt/tests/test_matlab_compatibility_cwt.py @@ -0,0 +1,177 @@ +""" +Test used to verify PyWavelets Continuous Wavelet Transform computation +accuracy against MathWorks Wavelet Toolbox. +""" + + +import warnings + +import numpy as np +import pytest +from numpy.testing import assert_ + +import pywt +from pywt._pytest import ( + matlab_result_dict_cwt, + size_set, + uses_precomputed, + uses_pymatbridge, +) + +families = ('gaus', 'mexh', 'morl', 'cgau', 'shan', 'fbsp', 'cmor') +wavelets = sum([pywt.wavelist(name) for name in families], []) + + +def _get_data_sizes(w): + """ Return the sizes to test for wavelet w. """ + if size_set == 'full': + data_sizes = list(range(100, 101)) + \ + [100, 200, 500, 1000, 50000] + else: + data_sizes = (1000, 1000 + 1) + return data_sizes + + +def _get_scales(w): + """ Return the scales to test for wavelet w. """ + if size_set == 'full': + scales = (1, np.arange(1, 3), np.arange(1, 4), np.arange(1, 5)) + else: + scales = (1, np.arange(1, 3)) + return scales + + +@uses_pymatbridge # skip this case if precomputed results are used instead +@pytest.mark.slow +def test_accuracy_pymatbridge_cwt(): + Matlab = pytest.importorskip("pymatbridge.Matlab") + mlab = Matlab() + rstate = np.random.RandomState(1234) + # max RMSE (was 1.0e-10, is reduced to 5.0e-5 due to different coefficients) + epsilon = 1e-15 + epsilon_psi = 1e-15 + mlab.start() + try: + for wavelet in wavelets: + with warnings.catch_warnings(): + warnings.simplefilter('ignore', FutureWarning) + w = pywt.ContinuousWavelet(wavelet) + if np.any((wavelet == np.array(['shan', 'cmor'])),axis=0): + mlab.set_variable('wavelet', wavelet+str(w.bandwidth_frequency)+'-'+str(w.center_frequency)) + elif wavelet == 'fbsp': + mlab.set_variable('wavelet', wavelet+str(w.fbsp_order)+'-'+str(w.bandwidth_frequency)+'-'+str(w.center_frequency)) + else: + mlab.set_variable('wavelet', wavelet) + mlab_code = ("psi = wavefun(wavelet,10)") + res = mlab.run_code(mlab_code) + psi = np.asarray(mlab.get_variable('psi')) + _check_accuracy_psi(w, psi, wavelet, epsilon_psi) + for N in _get_data_sizes(w): + data = rstate.randn(N) + mlab.set_variable('data', data) + for scales in _get_scales(w): + coefs = _compute_matlab_result(data, wavelet, scales, mlab) + _check_accuracy(data, w, scales, coefs, wavelet, epsilon) + + finally: + mlab.stop() + + +@uses_precomputed # skip this case if pymatbridge + Matlab are being used +@pytest.mark.slow +def test_accuracy_precomputed_cwt(): + # Keep this specific random seed to match the precomputed Matlab result. + rstate = np.random.RandomState(1234) + # has to be improved + epsilon = 2e-15 + epsilon32 = 1e-5 + epsilon_psi = 1e-15 + for wavelet in wavelets: + with warnings.catch_warnings(): + warnings.simplefilter('ignore', FutureWarning) + w = pywt.ContinuousWavelet(wavelet) + w32 = pywt.ContinuousWavelet(wavelet,dtype=np.float32) + psi = _load_matlab_result_psi(wavelet) + _check_accuracy_psi(w, psi, wavelet, epsilon_psi) + + for N in _get_data_sizes(w): + data = rstate.randn(N) + data32 = data.astype(np.float32) + scales_count = 0 + for scales in _get_scales(w): + scales_count += 1 + coefs = _load_matlab_result(data, wavelet, scales_count) + _check_accuracy(data, w, scales, coefs, wavelet, epsilon) + _check_accuracy(data32, w32, scales, coefs, wavelet, epsilon32) + + +def _compute_matlab_result(data, wavelet, scales, mlab): + """ Compute the result using MATLAB. + + This function assumes that the Matlab variables `wavelet` and `data` have + already been set externally. + """ + mlab.set_variable('scales', scales) + mlab_code = ("coefs = cwt(data, scales, wavelet)") + res = mlab.run_code(mlab_code) + if not res['success']: + raise RuntimeError("Matlab failed to execute the provided code. " + "Check that the wavelet toolbox is installed.") + # need np.asarray because sometimes the output is a single float64 + coefs = np.asarray(mlab.get_variable('coefs')) + return coefs + + +def _load_matlab_result(data, wavelet, scales): + """ Load the precomputed result. + """ + N = len(data) + coefs_key = '_'.join([str(scales), wavelet, str(N), 'coefs']) + if (coefs_key not in matlab_result_dict_cwt): + raise KeyError( + "Precompted Matlab result not found for wavelet: " + f"{wavelet}, mode: {scales}, size: {N}") + coefs = matlab_result_dict_cwt[coefs_key] + return coefs + + +def _load_matlab_result_psi(wavelet): + """ Load the precomputed result. + """ + psi_key = '_'.join([wavelet, 'psi']) + if (psi_key not in matlab_result_dict_cwt): + raise KeyError( + "Precompted Matlab psi result not found for wavelet: " + "{0}}".format(wavelet)) + psi = matlab_result_dict_cwt[psi_key] + return psi + + +def _check_accuracy(data, w, scales, coefs, wavelet, epsilon): + # PyWavelets result + coefs_pywt, freq = pywt.cwt(data, scales, w, precision=10) + + # coefs from Matlab are from R2012a which is missing the complex conjugate + # as shown in Eq. 2 of Torrence and Compo. We take the complex conjugate of + # the precomputed Matlab result to account for this. + coefs = np.conj(coefs) + + # calculate error measures + err = coefs_pywt - coefs + rms = np.real(np.sqrt(np.mean(np.conj(err) * err))) + + msg = ('[RMS > EPSILON] for Scale: %s, Wavelet: %s, ' + 'Length: %d, rms=%.3g' % (scales, wavelet, len(data), rms)) + assert_(rms < epsilon, msg=msg) + + +def _check_accuracy_psi(w, psi, wavelet, epsilon): + # PyWavelets result + psi_pywt, x = w.wavefun(length=1024) + + # calculate error measures + err = psi_pywt.flatten() - psi.flatten() + rms = np.real(np.sqrt(np.mean(np.conj(err) * err))) + + msg = f'[RMS > EPSILON] for Wavelet: {wavelet}, rms={rms:.3g}' + assert_(rms < epsilon, msg=msg) diff --git a/.venv/lib/python3.12/site-packages/pywt/tests/test_modes.py b/.venv/lib/python3.12/site-packages/pywt/tests/test_modes.py new file mode 100644 index 0000000000000000000000000000000000000000..0af215f840ccde428c2a05bdc7c7ece9ad7b0a3c --- /dev/null +++ b/.venv/lib/python3.12/site-packages/pywt/tests/test_modes.py @@ -0,0 +1,108 @@ +#!/usr/bin/env python + +import numpy as np +from numpy.testing import assert_allclose, assert_equal, assert_raises + +import pywt + + +def test_available_modes(): + modes = ['zero', 'constant', 'symmetric', 'periodic', 'smooth', + 'periodization', 'reflect', 'antisymmetric', 'antireflect'] + assert_equal(pywt.Modes.modes, modes) + assert_equal(pywt.Modes.from_object('constant'), 2) + + +def test_invalid_modes(): + x = np.arange(4) + assert_raises(ValueError, pywt.dwt, x, 'db2', 'unknown') + assert_raises(ValueError, pywt.dwt, x, 'db2', -1) + assert_raises(ValueError, pywt.dwt, x, 'db2', 9) + assert_raises(TypeError, pywt.dwt, x, 'db2', None) + + assert_raises(ValueError, pywt.Modes.from_object, 'unknown') + assert_raises(ValueError, pywt.Modes.from_object, -1) + assert_raises(ValueError, pywt.Modes.from_object, 9) + assert_raises(TypeError, pywt.Modes.from_object, None) + + +def test_dwt_idwt_allmodes(): + # Test that :func:`dwt` and :func:`idwt` can be performed using every mode + x = [1, 2, 1, 5, -1, 8, 4, 6] + dwt_results = { + 'zero': ([-0.03467518, 1.73309178, 3.40612438, 6.32928585, 6.95094948], + [-0.12940952, -2.15599552, -5.95034847, -1.21545369, + -1.8625013]), + 'constant': ([1.28480404, 1.73309178, 3.40612438, 6.32928585, + 7.51935555], + [-0.48296291, -2.15599552, -5.95034847, -1.21545369, + 0.25881905]), + 'symmetric': ([1.76776695, 1.73309178, 3.40612438, 6.32928585, + 7.77817459], + [-0.61237244, -2.15599552, -5.95034847, -1.21545369, + 1.22474487]), + 'reflect': ([2.12132034, 1.73309178, 3.40612438, 6.32928585, + 6.81224877], + [-0.70710678, -2.15599552, -5.95034847, -1.21545369, + -2.38013939]), + 'periodic': ([6.9162743, 1.73309178, 3.40612438, 6.32928585, + 6.9162743], + [-1.99191082, -2.15599552, -5.95034847, -1.21545369, + -1.99191082]), + 'smooth': ([-0.51763809, 1.73309178, 3.40612438, 6.32928585, + 7.45000519], + [0, -2.15599552, -5.95034847, -1.21545369, 0]), + 'periodization': ([4.053172, 3.05257099, 2.85381112, 8.42522221], + [0.18946869, 4.18258152, 4.33737503, 2.60428326]), + 'antisymmetric': ([-1.83711731, 1.73309178, 3.40612438, 6.32928585, + 6.12372436], + [0.353553391, -2.15599552, -5.95034847, -1.21545369, + -4.94974747]), + 'antireflect': ([0.44828774, 1.73309178, 3.40612438, 6.32928585, + 8.22646233], + [-0.25881905, -2.15599552, -5.95034847, -1.21545369, + 2.89777748]) + } + + for mode in pywt.Modes.modes: + cA, cD = pywt.dwt(x, 'db2', mode) + assert_allclose(cA, dwt_results[mode][0], rtol=1e-7, atol=1e-8) + assert_allclose(cD, dwt_results[mode][1], rtol=1e-7, atol=1e-8) + assert_allclose(pywt.idwt(cA, cD, 'db2', mode), x, rtol=1e-10) + + +def test_dwt_short_input_allmodes(): + # some test cases where the input is shorter than the DWT filter + x = [1, 3, 2] + wavelet = 'db2' + # manually pad each end by the filter size (4 for 'db2' used here) + padded_x = {'zero': [0, 0, 0, 0, 1, 3, 2, 0, 0, 0, 0], + 'constant': [1, 1, 1, 1, 1, 3, 2, 2, 2, 2, 2], + 'symmetric': [2, 2, 3, 1, 1, 3, 2, 2, 3, 1, 1], + 'reflect': [1, 3, 2, 3, 1, 3, 2, 3, 1, 3, 2], + 'periodic': [2, 1, 3, 2, 1, 3, 2, 1, 3, 2, 1], + 'smooth': [-7, -5, -3, -1, 1, 3, 2, 1, 0, -1, -2], + 'antisymmetric': [2, -2, -3, -1, 1, 3, 2, -2, -3, -1, 1], + 'antireflect': [1, -1, 0, -1, 1, 3, 2, 1, 3, 5, 4], + } + for mode, xpad in padded_x.items(): + # DWT of the manually padded array. will discard edges later so + # symmetric mode used here doesn't matter. + cApad, cDpad = pywt.dwt(xpad, wavelet, mode='symmetric') + + # central region of the padded output (unaffected by mode ) + expected_result = (cApad[2:-2], cDpad[2:-2]) + + cA, cD = pywt.dwt(x, wavelet, mode) + assert_allclose(cA, expected_result[0], rtol=1e-7, atol=1e-8) + assert_allclose(cD, expected_result[1], rtol=1e-7, atol=1e-8) + + +def test_default_mode(): + # The default mode should be 'symmetric' + x = [1, 2, 1, 5, -1, 8, 4, 6] + cA, cD = pywt.dwt(x, 'db2') + cA2, cD2 = pywt.dwt(x, 'db2', mode='symmetric') + assert_allclose(cA, cA2) + assert_allclose(cD, cD2) + assert_allclose(pywt.idwt(cA, cD, 'db2'), x) diff --git a/.venv/lib/python3.12/site-packages/pywt/tests/test_mra.py b/.venv/lib/python3.12/site-packages/pywt/tests/test_mra.py new file mode 100644 index 0000000000000000000000000000000000000000..078a0762a298db8303232056fe64c1de245cd984 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/pywt/tests/test_mra.py @@ -0,0 +1,257 @@ +#!/usr/bin/env python + +import numpy as np +import pytest +from numpy.testing import assert_allclose + +import pywt +from pywt import data +from pywt._utils import AxisError + +# tolerances used in accuracy comparisons +tol_single = 1e-6 +tol_double = 1e-13 +atol = 1e-7 + + +#### +# 1d mra tests +#### + +@pytest.mark.parametrize('wavelet', ['db2', 'sym4', 'coif5']) +@pytest.mark.parametrize('transform', ['dwt', 'swt']) +@pytest.mark.parametrize('mode', pywt.Modes.modes) +@pytest.mark.parametrize( + 'dtype', ['float32', 'float64', 'complex64', 'complex128'] +) +def test_mra_roundtrip(wavelet, transform, mode, dtype): + x = data.ecg()[:64].astype(dtype) + if x.dtype.kind == 'c': + # fill some data for the imaginary channel + x.imag = x[::-1].real + + if transform == 'swt': + # swt mode only supports periodization + if mode != 'periodization': + with pytest.raises(ValueError): + pywt.mra(x, wavelet, transform=transform, mode=mode) + return + + coeffs = pywt.mra(x, wavelet, transform=transform, mode=mode) + assert isinstance(coeffs, list) + assert isinstance(coeffs[0], np.ndarray) + # assert all(isinstance(coeffs[i], dict) for i in range(1, len(coeffs))) + + y = pywt.imra(coeffs) + rtol = tol_single if x.real.dtype.kind == 'f' else tol_double + assert_allclose(x, y, rtol=rtol, atol=rtol) + + +@pytest.mark.parametrize('wavelet', ['rbio1.3', 'bior2.4']) +@pytest.mark.parametrize('transform', ['dwt', 'swt']) +def test_mra_warns_on_non_orthogonal(wavelet, transform): + dtype = np.float64 + x = data.ecg()[:64].astype(dtype) + + assert not pywt.Wavelet(wavelet).orthogonal + + if transform == 'swt': + # bi-orthogonal wavelets raise a warning for SWT case + msg = 'norm=True, but the wavelet is not orthogonal' + with pytest.warns(UserWarning, match=msg): + coeffs = pywt.mra(x, wavelet, transform=transform) + else: + coeffs = pywt.mra(x, wavelet, transform=transform) + + y = pywt.imra(coeffs) + rtol = tol_single if x.real.dtype.kind == 'f' else tol_double + assert_allclose(x, y, rtol=rtol, atol=rtol) + + +@pytest.mark.parametrize('axis', [0, -1, 1, 2, -3]) +@pytest.mark.parametrize('ndim', [1, 2, 3]) +@pytest.mark.parametrize('transform', ['dwt', 'swt']) +@pytest.mark.parametrize('dtype', [np.float64, np.complex128]) +def test_mra_axis(transform, ndim, axis, dtype): + # Test transforms over a specific axis of 1D, 2D or 3D data + if ndim == 1: + x = data.ecg()[:64] + elif ndim == 2: + x = data.camera()[:64, :32] + elif ndim == 3: + x = data.camera()[:48, :8] + x = np.stack((x,) * 8, axis=-1) + x = x.astype(dtype, copy=False) + + # out of range axis + if axis < -x.ndim or axis >= x.ndim: + with pytest.raises(AxisError): + pywt.mra(x, 'db1', transform=transform, axis=axis) + return + + coeffs = pywt.mra(x, 'db1', transform=transform, axis=axis) + y = pywt.imra(coeffs) + rtol = tol_single if x.real.dtype.kind == 'f' else tol_double + assert_allclose(x, y, rtol=rtol, atol=rtol) + + +#### +# 2d mra tests +#### + +@pytest.mark.parametrize('wavelet', ['db2', 'sym4', 'coif5']) +@pytest.mark.parametrize('transform', ['dwt2', 'swt2']) +@pytest.mark.parametrize('mode', pywt.Modes.modes) +@pytest.mark.parametrize( + 'dtype', ['float32', 'float64', 'complex64', 'complex128'] +) +def test_mra2_roundtrip(wavelet, transform, mode, dtype): + x = data.camera()[:32, :16].astype(dtype, copy=False) + if x.dtype.kind == 'c': + # fill some data for the imaginary channel + x.imag = x[::-1, :].real + + if transform == 'swt2': + # swt mode only supports periodization + if mode != 'periodization': + with pytest.raises(ValueError): + pywt.mra2(x, wavelet, transform=transform, mode=mode) + return + + coeffs = pywt.mra2(x, wavelet, transform=transform, mode=mode) + assert isinstance(coeffs, list) + assert isinstance(coeffs[0], np.ndarray) + # assert all(isinstance(coeffs[i], dict) for i in range(1, len(coeffs))) + + y = pywt.imra2(coeffs) + rtol = tol_single if x.real.dtype.kind == 'f' else tol_double + assert_allclose(x, y, rtol=rtol, atol=rtol) + + +@pytest.mark.parametrize('wavelet', ['rbio1.3', 'bior2.4']) +@pytest.mark.parametrize('transform', ['dwt2', 'swt2']) +def test_mra2_warns_on_non_orthogonal(wavelet, transform): + dtype = np.float64 + x = data.camera()[:32, :8].astype(dtype, copy=False) + + assert not pywt.Wavelet(wavelet).orthogonal + + if transform == 'swt2': + # bi-orthogonal wavelets raise a warning for SWT case + msg = 'norm=True, but the wavelets used are not orthogonal' + with pytest.warns(UserWarning, match=msg): + coeffs = pywt.mra2(x, wavelet, transform=transform) + else: + coeffs = pywt.mra2(x, wavelet, transform=transform) + + y = pywt.imra2(coeffs) + rtol = tol_single if x.real.dtype.kind == 'f' else tol_double + assert_allclose(x, y, rtol=rtol, atol=rtol) + + +@pytest.mark.parametrize('transform', ['dwt2', 'swt2']) +@pytest.mark.parametrize('ndim', [2, 3]) +@pytest.mark.parametrize('axes', [(0, 1), (-2, -1), (0, 2), (-3, 1), (0, 4)]) +@pytest.mark.parametrize('dtype', [np.float64, np.complex128]) +def test_mra2_axes(transform, axes, ndim, dtype): + # Test transforms over various axes of 2D or 3D data. + x = data.camera()[:32, :16].astype(dtype, copy=False) + if ndim == 3: + x = np.stack((x,) * 8, axis=-1) + + # out of range axis + if any(axis < -x.ndim or axis >= x.ndim for axis in axes): + with pytest.raises(AxisError): + pywt.mra2(x, 'db1', transform=transform, axes=axes) + return + + coeffs = pywt.mra2(x, 'db1', transform=transform, axes=axes) + y = pywt.imra2(coeffs) + rtol = tol_single if x.real.dtype.kind == 'f' else tol_double + assert_allclose(x, y, rtol=rtol, atol=rtol) + + +#### +# nd mra tests +#### + +@pytest.mark.slow +@pytest.mark.parametrize('wavelet', ['sym2', ]) +@pytest.mark.parametrize('transform', ['dwtn', 'swtn']) +@pytest.mark.parametrize('mode', pywt.Modes.modes) +@pytest.mark.parametrize( + 'dtype', ['float32', 'float64', 'complex64', 'complex128'] +) +@pytest.mark.parametrize('ndim', [1, 2, 3]) +def test_mran_roundtrip(wavelet, transform, mode, dtype, ndim): + if ndim == 1: + x = data.ecg()[:48].astype(dtype, copy=False) + elif ndim == 2: + x = data.camera()[:16, :8].astype(dtype, copy=False) + elif ndim == 3: + x = data.camera()[:16, :8].astype(dtype, copy=False) + x = np.stack((x,) * 8, axis=-1) + + if x.dtype.kind == 'c': + # fill some data for the imaginary channel + x.imag = x[::-1, ...].real + + if transform == 'swtn': + # swt mode only supports periodization + if mode != 'periodization': + with pytest.raises(ValueError): + pywt.mran(x, wavelet, transform=transform, mode=mode) + return + + coeffs = pywt.mran(x, wavelet, transform=transform, mode=mode) + assert isinstance(coeffs, list) + assert isinstance(coeffs[0], np.ndarray) + # assert all(isinstance(coeffs[i], dict) for i in range(1, len(coeffs))) + + y = pywt.imran(coeffs) + rtol = tol_single if x.real.dtype.kind == 'f' else tol_double + assert_allclose(x, y, rtol=rtol, atol=rtol) + + +@pytest.mark.parametrize('wavelet', ['rbio1.3', 'bior2.4']) +@pytest.mark.parametrize('transform', ['dwtn', 'swtn']) +def test_mran_warns_on_non_orthogonal(wavelet, transform): + dtype = np.float64 + x = data.camera()[:32, :8].astype(dtype, copy=False) + + assert not pywt.Wavelet(wavelet).orthogonal + + if transform == 'swtn': + # bi-orthogonal wavelets raise a warning for SWT case + msg = 'norm=True, but the wavelets used are not orthogonal' + with pytest.warns(UserWarning, match=msg): + coeffs = pywt.mran(x, wavelet, transform=transform) + else: + coeffs = pywt.mran(x, wavelet, transform=transform) + + y = pywt.imran(coeffs) + rtol = tol_single if x.real.dtype.kind == 'f' else tol_double + assert_allclose(x, y, rtol=rtol, atol=rtol) + + +@pytest.mark.parametrize( + 'axes', [(0, 1), (-2, -1), (0, 2), (-3, 1), (0, 4), (-3, -2, -1), + (0, 2, 1), (0, 5, 1), (0,), (1,), (2,), (-2,), (-3,), (-4,)]) +@pytest.mark.parametrize('transform', ['dwtn', 'swtn']) +def test_mran_axes(axes, transform): + # Test with transforms over 1, 2 or 3 axes of 3d data. + # Cases with out of range axes are also tested + dtype = np.float64 + x = data.camera()[:32, :16].astype(dtype, copy=False) + x3d = np.stack((x,) * 8, axis=-1) + + # out of range axis + if any(axis < -x.ndim or axis >= x.ndim for axis in axes): + with pytest.raises(AxisError): + pywt.mran(x, 'db1', transform='dwtn', axes=axes) + return + + coeffs = pywt.mran(x3d, 'db1', transform='dwtn', axes=axes) + y = pywt.imran(coeffs) + rtol = tol_single if x3d.real.dtype.kind == 'f' else tol_double + assert_allclose(x3d, y, rtol=rtol, atol=rtol) diff --git a/.venv/lib/python3.12/site-packages/pywt/tests/test_multidim.py b/.venv/lib/python3.12/site-packages/pywt/tests/test_multidim.py new file mode 100644 index 0000000000000000000000000000000000000000..eeaa680c078becd05a54a27017f3b14cddedc61e --- /dev/null +++ b/.venv/lib/python3.12/site-packages/pywt/tests/test_multidim.py @@ -0,0 +1,444 @@ +#!/usr/bin/env python + + +from itertools import combinations + +import numpy as np +from numpy.testing import assert_, assert_allclose, assert_equal, assert_raises + +import pywt + +# Check that float32, float64, complex64, complex128 are preserved. +# Other real types get converted to float64. +# complex256 gets converted to complex128 +dtypes_in = [np.int8, np.float16, np.float32, np.float64, np.complex64, + np.complex128] +dtypes_out = [np.float64, np.float32, np.float32, np.float64, np.complex64, + np.complex128] + +# test complex256 as well if it is available +try: + dtypes_in += [np.complex256, ] + dtypes_out += [np.complex128, ] +except AttributeError: + pass + + +def test_dwtn_input(): + # Array-like must be accepted + pywt.dwtn([1, 2, 3, 4], 'haar') + # Others must not + data = {} + assert_raises(TypeError, pywt.dwtn, data, 'haar') + # Must be at least 1D + assert_raises(ValueError, pywt.dwtn, 2, 'haar') + + +def test_3D_reconstruct(): + data = np.array([ + [[0, 4, 1, 5, 1, 4], + [0, 5, 26, 3, 2, 1], + [5, 8, 2, 33, 4, 9], + [2, 5, 19, 4, 19, 1]], + [[1, 5, 1, 2, 3, 4], + [7, 12, 6, 52, 7, 8], + [2, 12, 3, 52, 6, 8], + [5, 2, 6, 78, 12, 2]]]) + + wavelet = pywt.Wavelet('haar') + for mode in pywt.Modes.modes: + d = pywt.dwtn(data, wavelet, mode=mode) + assert_allclose(data, pywt.idwtn(d, wavelet, mode=mode), + rtol=1e-13, atol=1e-13) + + +def test_dwdtn_idwtn_allwavelets(): + rstate = np.random.RandomState(1234) + r = rstate.randn(16, 16) + # test 2D case only for all wavelet types + wavelist = pywt.wavelist() + if 'dmey' in wavelist: + wavelist.remove('dmey') + for wavelet in wavelist: + if wavelet in ['cmor', 'shan', 'fbsp']: + # skip these CWT families to avoid warnings + continue + if isinstance(pywt.DiscreteContinuousWavelet(wavelet), pywt.Wavelet): + for mode in pywt.Modes.modes: + coeffs = pywt.dwtn(r, wavelet, mode=mode) + assert_allclose(pywt.idwtn(coeffs, wavelet, mode=mode), + r, rtol=1e-7, atol=1e-7) + + +def test_stride(): + wavelet = pywt.Wavelet('haar') + + for dtype in ('float32', 'float64'): + data = np.array([[0, 4, 1, 5, 1, 4], + [0, 5, 6, 3, 2, 1], + [2, 5, 19, 4, 19, 1]], + dtype=dtype) + + for mode in pywt.Modes.modes: + expected = pywt.dwtn(data, wavelet) + strided = np.ones((3, 12), dtype=data.dtype) + strided[::-1, ::2] = data + strided_dwtn = pywt.dwtn(strided[::-1, ::2], wavelet) + for key in expected: + assert_allclose(strided_dwtn[key], expected[key]) + + +def test_byte_offset(): + wavelet = pywt.Wavelet('haar') + for dtype in ('float32', 'float64'): + data = np.array([[0, 4, 1, 5, 1, 4], + [0, 5, 6, 3, 2, 1], + [2, 5, 19, 4, 19, 1]], + dtype=dtype) + + for mode in pywt.Modes.modes: + expected = pywt.dwtn(data, wavelet) + padded = np.ones((3, 6), dtype=np.dtype({'data': (data.dtype, 0), + 'pad': ('byte', data.dtype.itemsize)}, + align=True)) + padded[:] = data + padded_dwtn = pywt.dwtn(padded['data'], wavelet) + for key in expected: + assert_allclose(padded_dwtn[key], expected[key]) + + +def test_3D_reconstruct_complex(): + # All dimensions even length so `take` does not need to be specified + data = np.array([ + [[0, 4, 1, 5, 1, 4], + [0, 5, 26, 3, 2, 1], + [5, 8, 2, 33, 4, 9], + [2, 5, 19, 4, 19, 1]], + [[1, 5, 1, 2, 3, 4], + [7, 12, 6, 52, 7, 8], + [2, 12, 3, 52, 6, 8], + [5, 2, 6, 78, 12, 2]]]) + data = data + 1j + + wavelet = pywt.Wavelet('haar') + d = pywt.dwtn(data, wavelet) + # idwtn creates even-length shapes (2x dwtn size) + original_shape = tuple([slice(None, s) for s in data.shape]) + assert_allclose(data, pywt.idwtn(d, wavelet)[original_shape], + rtol=1e-13, atol=1e-13) + + +def test_idwtn_idwt2(): + data = np.array([ + [0, 4, 1, 5, 1, 4], + [0, 5, 6, 3, 2, 1], + [2, 5, 19, 4, 19, 1]]) + + wavelet = pywt.Wavelet('haar') + + LL, (HL, LH, HH) = pywt.dwt2(data, wavelet) + d = {'aa': LL, 'da': HL, 'ad': LH, 'dd': HH} + + for mode in pywt.Modes.modes: + assert_allclose(pywt.idwt2((LL, (HL, LH, HH)), wavelet, mode=mode), + pywt.idwtn(d, wavelet, mode=mode), + rtol=1e-14, atol=1e-14) + + +def test_idwtn_idwt2_complex(): + data = np.array([ + [0, 4, 1, 5, 1, 4], + [0, 5, 6, 3, 2, 1], + [2, 5, 19, 4, 19, 1]]) + data = data + 1j + wavelet = pywt.Wavelet('haar') + + LL, (HL, LH, HH) = pywt.dwt2(data, wavelet) + d = {'aa': LL, 'da': HL, 'ad': LH, 'dd': HH} + + for mode in pywt.Modes.modes: + assert_allclose(pywt.idwt2((LL, (HL, LH, HH)), wavelet, mode=mode), + pywt.idwtn(d, wavelet, mode=mode), + rtol=1e-14, atol=1e-14) + + +def test_idwtn_missing(): + # Test to confirm missing data behave as zeroes + data = np.array([ + [0, 4, 1, 5, 1, 4], + [0, 5, 6, 3, 2, 1], + [2, 5, 19, 4, 19, 1]]) + + wavelet = pywt.Wavelet('haar') + + coefs = pywt.dwtn(data, wavelet) + + # No point removing zero, or all + for num_missing in range(1, len(coefs)): + for missing in combinations(coefs.keys(), num_missing): + missing_coefs = coefs.copy() + for key in missing: + del missing_coefs[key] + LL = missing_coefs.get('aa', None) + HL = missing_coefs.get('da', None) + LH = missing_coefs.get('ad', None) + HH = missing_coefs.get('dd', None) + + assert_allclose(pywt.idwt2((LL, (HL, LH, HH)), wavelet), + pywt.idwtn(missing_coefs, 'haar'), atol=1e-15) + + +def test_idwtn_all_coeffs_None(): + coefs = {'aa': None, 'da': None, 'ad': None, 'dd': None} + assert_raises(ValueError, pywt.idwtn, coefs, 'haar') + + +def test_error_on_invalid_keys(): + data = np.array([ + [0, 4, 1, 5, 1, 4], + [0, 5, 6, 3, 2, 1], + [2, 5, 19, 4, 19, 1]]) + + wavelet = pywt.Wavelet('haar') + + LL, (HL, LH, HH) = pywt.dwt2(data, wavelet) + + # unexpected key + d = {'aa': LL, 'da': HL, 'ad': LH, 'dd': HH, 'ff': LH} + assert_raises(ValueError, pywt.idwtn, d, wavelet) + + # mismatched key lengths + d = {'a': LL, 'da': HL, 'ad': LH, 'dd': HH} + assert_raises(ValueError, pywt.idwtn, d, wavelet) + + +def test_error_mismatched_size(): + data = np.array([ + [0, 4, 1, 5, 1, 4], + [0, 5, 6, 3, 2, 1], + [2, 5, 19, 4, 19, 1]]) + + wavelet = pywt.Wavelet('haar') + + LL, (HL, LH, HH) = pywt.dwt2(data, wavelet) + + # Pass/fail depends on first element being shorter than remaining ones so + # set 3/4 to an incorrect size to maximize chances. Order of dict items + # is random so may not trigger on every test run. Dict is constructed + # inside idwtn function so no use using an OrderedDict here. + LL = LL[:, :-1] + LH = LH[:, :-1] + HH = HH[:, :-1] + d = {'aa': LL, 'da': HL, 'ad': LH, 'dd': HH} + + assert_raises(ValueError, pywt.idwtn, d, wavelet) + + +def test_dwt2_idwt2_dtypes(): + wavelet = pywt.Wavelet('haar') + for dt_in, dt_out in zip(dtypes_in, dtypes_out): + x = np.ones((4, 4), dtype=dt_in) + errmsg = f"wrong dtype returned for {dt_in} input" + + cA, (cH, cV, cD) = pywt.dwt2(x, wavelet) + assert_(cA.dtype == cH.dtype == cV.dtype == cD.dtype, + "dwt2: " + errmsg) + + x_roundtrip = pywt.idwt2((cA, (cH, cV, cD)), wavelet) + assert_(x_roundtrip.dtype == dt_out, "idwt2: " + errmsg) + + +def test_dwtn_axes(): + data = np.array([[0, 1, 2, 3], + [1, 1, 1, 1], + [1, 4, 2, 8]]) + data = data + 1j*data # test with complex data + coefs = pywt.dwtn(data, 'haar', axes=(1,)) + expected_a = [pywt.dwt(x, 'haar')[0] for x in data] + assert_equal(coefs['a'], expected_a) + expected_d = [pywt.dwt(x, 'haar')[1] for x in data] + assert_equal(coefs['d'], expected_d) + + coefs = pywt.dwtn(data, 'haar', axes=(1, 1)) + expected_aa = [pywt.dwt(x, 'haar')[0] for x in expected_a] + assert_equal(coefs['aa'], expected_aa) + expected_ad = [pywt.dwt(x, 'haar')[1] for x in expected_a] + assert_equal(coefs['ad'], expected_ad) + + +def test_idwtn_axes(): + data = np.array([[0, 1, 2, 3], + [1, 1, 1, 1], + [1, 4, 2, 8]]) + data = data + 1j*data # test with complex data + coefs = pywt.dwtn(data, 'haar', axes=(1, 1)) + assert_allclose(pywt.idwtn(coefs, 'haar', axes=(1, 1)), data, atol=1e-14) + + +def test_idwt2_none_coeffs(): + data = np.array([[0, 1, 2, 3], + [1, 1, 1, 1], + [1, 4, 2, 8]]) + data = data + 1j*data # test with complex data + cA, (cH, cV, cD) = pywt.dwt2(data, 'haar', axes=(1, 1)) + + # verify setting coefficients to None is the same as zeroing them + cD = np.zeros_like(cD) + result_zeros = pywt.idwt2((cA, (cH, cV, cD)), 'haar', axes=(1, 1)) + + cD = None + result_none = pywt.idwt2((cA, (cH, cV, cD)), 'haar', axes=(1, 1)) + + assert_equal(result_zeros, result_none) + + +def test_idwtn_none_coeffs(): + data = np.array([[0, 1, 2, 3], + [1, 1, 1, 1], + [1, 4, 2, 8]]) + data = data + 1j*data # test with complex data + coefs = pywt.dwtn(data, 'haar', axes=(1, 1)) + + # verify setting coefficients to None is the same as zeroing them + coefs['dd'] = np.zeros_like(coefs['dd']) + result_zeros = pywt.idwtn(coefs, 'haar', axes=(1, 1)) + + coefs['dd'] = None + result_none = pywt.idwtn(coefs, 'haar', axes=(1, 1)) + + assert_equal(result_zeros, result_none) + + +def test_idwt2_axes(): + data = np.array([[0, 1, 2, 3], + [1, 1, 1, 1], + [1, 4, 2, 8]]) + coefs = pywt.dwt2(data, 'haar', axes=(1, 1)) + assert_allclose(pywt.idwt2(coefs, 'haar', axes=(1, 1)), data, atol=1e-14) + + # too many axes + assert_raises(ValueError, pywt.idwt2, coefs, 'haar', axes=(0, 1, 1)) + + +def test_idwt2_axes_subsets(): + data = np.array(np.random.standard_normal((4, 4, 4))) + # test all combinations of 2 out of 3 axes transformed + for axes in combinations((0, 1, 2), 2): + coefs = pywt.dwt2(data, 'haar', axes=axes) + assert_allclose(pywt.idwt2(coefs, 'haar', axes=axes), data, atol=1e-14) + + +def test_idwtn_axes_subsets(): + data = np.array(np.random.standard_normal((4, 4, 4, 4))) + # test all combinations of 3 out of 4 axes transformed + for axes in combinations((0, 1, 2, 3), 3): + coefs = pywt.dwtn(data, 'haar', axes=axes) + assert_allclose(pywt.idwtn(coefs, 'haar', axes=axes), data, atol=1e-14) + + +def test_negative_axes(): + data = np.array([[0, 1, 2, 3], + [1, 1, 1, 1], + [1, 4, 2, 8]]) + coefs1 = pywt.dwtn(data, 'haar', axes=(1, 1)) + coefs2 = pywt.dwtn(data, 'haar', axes=(-1, -1)) + assert_equal(coefs1, coefs2) + + rec1 = pywt.idwtn(coefs1, 'haar', axes=(1, 1)) + rec2 = pywt.idwtn(coefs1, 'haar', axes=(-1, -1)) + assert_equal(rec1, rec2) + + +def test_dwtn_idwtn_dtypes(): + wavelet = pywt.Wavelet('haar') + for dt_in, dt_out in zip(dtypes_in, dtypes_out): + x = np.ones((4, 4), dtype=dt_in) + errmsg = f"wrong dtype returned for {dt_in} input" + + coeffs = pywt.dwtn(x, wavelet) + for k, v in coeffs.items(): + assert_(v.dtype == dt_out, "dwtn: " + errmsg) + + x_roundtrip = pywt.idwtn(coeffs, wavelet) + assert_(x_roundtrip.dtype == dt_out, "idwtn: " + errmsg) + + +def test_idwtn_mixed_complex_dtype(): + rstate = np.random.RandomState(0) + x = rstate.randn(8, 8, 8) + x = x + 1j*x + coeffs = pywt.dwtn(x, 'db2') + + x_roundtrip = pywt.idwtn(coeffs, 'db2') + assert_allclose(x_roundtrip, x, rtol=1e-10) + + # mismatched dtypes OK + coeffs['a' * x.ndim] = coeffs['a' * x.ndim].astype(np.complex64) + x_roundtrip2 = pywt.idwtn(coeffs, 'db2') + assert_allclose(x_roundtrip2, x, rtol=1e-7, atol=1e-7) + assert_(x_roundtrip2.dtype == np.complex128) + + +def test_idwt2_size_mismatch_error(): + LL = np.zeros((6, 6)) + LH = HL = HH = np.zeros((5, 5)) + + assert_raises(ValueError, pywt.idwt2, (LL, (LH, HL, HH)), wavelet='haar') + + +def test_dwt2_dimension_error(): + data = np.ones(16) + wavelet = pywt.Wavelet('haar') + + # wrong number of input dimensions + assert_raises(ValueError, pywt.dwt2, data, wavelet) + + # too many axes + data2 = np.ones((8, 8)) + assert_raises(ValueError, pywt.dwt2, data2, wavelet, axes=(0, 1, 1)) + + +def test_per_axis_wavelets_and_modes(): + # tests separate wavelet and edge mode for each axis. + rstate = np.random.RandomState(1234) + data = rstate.randn(16, 16, 16) + + # wavelet can be a string or wavelet object + wavelets = (pywt.Wavelet('haar'), 'sym2', 'db4') + + # mode can be a string or a Modes enum + modes = ('symmetric', 'periodization', + pywt._extensions._pywt.Modes.reflect) + + coefs = pywt.dwtn(data, wavelets, modes) + assert_allclose(pywt.idwtn(coefs, wavelets, modes), data, atol=1e-14) + + coefs = pywt.dwtn(data, wavelets[:1], modes) + assert_allclose(pywt.idwtn(coefs, wavelets[:1], modes), data, atol=1e-14) + + coefs = pywt.dwtn(data, wavelets, modes[:1]) + assert_allclose(pywt.idwtn(coefs, wavelets, modes[:1]), data, atol=1e-14) + + # length of wavelets or modes doesn't match the length of axes + assert_raises(ValueError, pywt.dwtn, data, wavelets[:2]) + assert_raises(ValueError, pywt.dwtn, data, wavelets, mode=modes[:2]) + assert_raises(ValueError, pywt.idwtn, coefs, wavelets[:2]) + assert_raises(ValueError, pywt.idwtn, coefs, wavelets, mode=modes[:2]) + + # dwt2/idwt2 also support per-axis wavelets/modes + data2 = data[..., 0] + coefs2 = pywt.dwt2(data2, wavelets[:2], modes[:2]) + assert_allclose(pywt.idwt2(coefs2, wavelets[:2], modes[:2]), data2, + atol=1e-14) + + +def test_error_on_continuous_wavelet(): + # A ValueError is raised if a Continuous wavelet is selected + data = np.ones((16, 16)) + for dec_fun, rec_fun in zip([pywt.dwt2, pywt.dwtn], + [pywt.idwt2, pywt.idwtn]): + for cwave in ['morl', pywt.DiscreteContinuousWavelet('morl')]: + assert_raises(ValueError, dec_fun, data, wavelet=cwave) + + c = dec_fun(data, 'db1') + assert_raises(ValueError, rec_fun, c, wavelet=cwave) diff --git a/.venv/lib/python3.12/site-packages/pywt/tests/test_multilevel.py b/.venv/lib/python3.12/site-packages/pywt/tests/test_multilevel.py new file mode 100644 index 0000000000000000000000000000000000000000..640a477584044b069752841c892a0bf4149fcb99 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/pywt/tests/test_multilevel.py @@ -0,0 +1,1048 @@ +#!/usr/bin/env python + + +import warnings +from itertools import combinations + +import numpy as np +import pytest +from numpy.testing import ( + assert_, + assert_allclose, + assert_almost_equal, + assert_array_equal, + assert_equal, + assert_raises, + assert_raises_regex, +) + +import pywt + +# Check that float32, float64, complex64, complex128 are preserved. +# Other real types get converted to float64. +# complex256 gets converted to complex128 +dtypes_in = [np.int8, np.float16, np.float32, np.float64, np.complex64, + np.complex128] +dtypes_out = [np.float64, np.float32, np.float32, np.float64, np.complex64, + np.complex128] + +# tolerances used in accuracy comparisons +tol_single = 1e-6 +tol_double = 1e-13 +dtypes_and_tolerances = [(np.float16, tol_single), (np.float32, tol_single), + (np.float64, tol_double), (np.int8, tol_double), + (np.complex64, tol_single), + (np.complex128, tol_double)] + +# test complex256 as well if it is available +try: + dtypes_in += [np.complex256, ] + dtypes_out += [np.complex128, ] + dtypes_and_tolerances += [(np.complex256, tol_double), ] +except AttributeError: + pass + + +# determine which wavelets to test +wavelist = pywt.wavelist() +if 'dmey' in wavelist: + # accuracy is very low for dmey, so omit it + wavelist.remove('dmey') + +# removing wavelets with dwt_possible == False +del_list = [] +for wavelet in wavelist: + with warnings.catch_warnings(): + warnings.simplefilter('ignore', FutureWarning) + if not isinstance(pywt.DiscreteContinuousWavelet(wavelet), + pywt.Wavelet): + del_list.append(wavelet) +for del_ind in del_list: + wavelist.remove(del_ind) + + +#### +# 1d multilevel dwt tests +#### + +def test_wavedec(): + x = [3, 7, 1, 1, -2, 5, 4, 6] + db1 = pywt.Wavelet('db1') + cA3, cD3, cD2, cD1 = pywt.wavedec(x, db1) + assert_almost_equal(cA3, [8.83883476]) + assert_almost_equal(cD3, [-0.35355339]) + assert_allclose(cD2, [4., -3.5]) + assert_allclose(cD1, [-2.82842712, 0, -4.94974747, -1.41421356]) + assert_(pywt.dwt_max_level(len(x), db1) == 3) + + +def test_wavedec_readonly_array(): + data = np.random.randn(1000).astype(np.float64) + data.setflags(write=False) + pywt.wavedec(data, "db4", level=2) + + +def test_waverec_invalid_inputs(): + # input must be list or tuple + assert_raises(ValueError, pywt.waverec, np.ones(8), 'haar') + + # input list cannot be empty + assert_raises(ValueError, pywt.waverec, [], 'haar') + + # 'array_to_coeffs must specify 'output_format' to perform waverec + x = [3, 7, 1, 1, -2, 5, 4, 6] + coeffs = pywt.wavedec(x, 'db1') + arr, coeff_slices = pywt.coeffs_to_array(coeffs) + coeffs_from_arr = pywt.array_to_coeffs(arr, coeff_slices) + message = "Unexpected detail coefficient type" + assert_raises_regex(ValueError, message, pywt.waverec, coeffs_from_arr, + 'haar') + + +def test_waverec_accuracies(): + rstate = np.random.RandomState(1234) + x0 = rstate.randn(8) + for dt, tol in dtypes_and_tolerances: + x = x0.astype(dt) + if np.iscomplexobj(x): + x += 1j*rstate.randn(8).astype(x.real.dtype) + coeffs = pywt.wavedec(x, 'db1') + assert_allclose(pywt.waverec(coeffs, 'db1'), x, atol=tol, rtol=tol) + + +def test_waverec_none(): + x = [3, 7, 1, 1, -2, 5, 4, 6] + coeffs = pywt.wavedec(x, 'db1') + + # set some coefficients to None + coeffs[2] = None + coeffs[0] = None + assert_(pywt.waverec(coeffs, 'db1').size, len(x)) + + +def test_waverec_odd_length(): + x = [3, 7, 1, 1, -2, 5] + coeffs = pywt.wavedec(x, 'db1') + assert_allclose(pywt.waverec(coeffs, 'db1'), x, rtol=1e-12) + + +def test_waverec_complex(): + x = np.array([3, 7, 1, 1, -2, 5, 4, 6]) + x = x + 1j + coeffs = pywt.wavedec(x, 'db1') + assert_allclose(pywt.waverec(coeffs, 'db1'), x, rtol=1e-12) + + +def test_multilevel_dtypes_1d(): + # only checks that the result is of the expected type + wavelet = pywt.Wavelet('haar') + for dt_in, dt_out in zip(dtypes_in, dtypes_out): + # wavedec, waverec + x = np.ones(8, dtype=dt_in) + errmsg = f"wrong dtype returned for {dt_in} input" + + coeffs = pywt.wavedec(x, wavelet, level=2) + for c in coeffs: + assert_(c.dtype == dt_out, "wavedec: " + errmsg) + x_roundtrip = pywt.waverec(coeffs, wavelet) + assert_(x_roundtrip.dtype == dt_out, "waverec: " + errmsg) + + +def test_waverec_all_wavelets_modes(): + # test 2D case using all wavelets and modes + rstate = np.random.RandomState(1234) + r = rstate.randn(80) + for wavelet in wavelist: + for mode in pywt.Modes.modes: + coeffs = pywt.wavedec(r, wavelet, mode=mode) + assert_allclose(pywt.waverec(coeffs, wavelet, mode=mode), + r, rtol=tol_single, atol=tol_single) + +#### +# 2d multilevel dwt function tests +#### + + +def test_waverec2_accuracies(): + rstate = np.random.RandomState(1234) + x0 = rstate.randn(4, 4) + for dt, tol in dtypes_and_tolerances: + x = x0.astype(dt) + if np.iscomplexobj(x): + x += 1j*rstate.randn(4, 4).astype(x.real.dtype) + coeffs = pywt.wavedec2(x, 'db1') + assert_(len(coeffs) == 3) + assert_allclose(pywt.waverec2(coeffs, 'db1'), x, atol=tol, rtol=tol) + + +def test_multilevel_dtypes_2d(): + wavelet = pywt.Wavelet('haar') + for dt_in, dt_out in zip(dtypes_in, dtypes_out): + # wavedec2, waverec2 + x = np.ones((8, 8), dtype=dt_in) + errmsg = f"wrong dtype returned for {dt_in} input" + cA, coeffsD2, coeffsD1 = pywt.wavedec2(x, wavelet, level=2) + assert_(cA.dtype == dt_out, "wavedec2: " + errmsg) + for c in coeffsD1: + assert_(c.dtype == dt_out, "wavedec2: " + errmsg) + for c in coeffsD2: + assert_(c.dtype == dt_out, "wavedec2: " + errmsg) + x_roundtrip = pywt.waverec2([cA, coeffsD2, coeffsD1], wavelet) + assert_(x_roundtrip.dtype == dt_out, "waverec2: " + errmsg) + + +@pytest.mark.slow +def test_waverec2_all_wavelets_modes(): + # test 2D case using all wavelets and modes + rstate = np.random.RandomState(1234) + r = rstate.randn(80, 96) + for wavelet in wavelist: + for mode in pywt.Modes.modes: + coeffs = pywt.wavedec2(r, wavelet, mode=mode) + assert_allclose(pywt.waverec2(coeffs, wavelet, mode=mode), + r, rtol=tol_single, atol=tol_single) + + +def test_wavedec2_complex(): + data = np.ones((4, 4)) + 1j + coeffs = pywt.wavedec2(data, 'db1') + assert_(len(coeffs) == 3) + assert_allclose(pywt.waverec2(coeffs, 'db1'), data, rtol=1e-12) + + +def test_wavedec2_invalid_inputs(): + # input array has too few dimensions + data = np.ones(4) + assert_raises(ValueError, pywt.wavedec2, data, 'haar') + + +def test_waverec2_invalid_inputs(): + # input must be list or tuple + assert_raises(ValueError, pywt.waverec2, np.ones((8, 8)), 'haar') + + # input list cannot be empty + assert_raises(ValueError, pywt.waverec2, [], 'haar') + + # coefficients from a difference decomposition used as input + for dec_func in [pywt.wavedec, pywt.wavedecn]: + coeffs = dec_func(np.ones((8, 8)), 'haar') + message = "Unexpected detail coefficient type" + assert_raises_regex(ValueError, message, pywt.waverec2, coeffs, + 'haar') + + +def test_waverec2_coeff_shape_mismatch(): + x = np.ones((8, 8)) + coeffs = pywt.wavedec2(x, 'db1') + + # introduce a shape mismatch in the coefficients + coeffs = list(coeffs) + coeffs[1] = list(coeffs[1]) + coeffs[1][1] = np.zeros((16, 1)) + assert_raises(ValueError, pywt.waverec2, coeffs, 'db1') + + +def test_waverec2_odd_length(): + x = np.ones((10, 6)) + coeffs = pywt.wavedec2(x, 'db1') + assert_allclose(pywt.waverec2(coeffs, 'db1'), x, rtol=1e-12) + + +def test_waverec2_none_coeffs(): + x = np.arange(24).reshape(6, 4) + coeffs = pywt.wavedec2(x, 'db1') + coeffs[1] = (None, None, None) + assert_(x.shape == pywt.waverec2(coeffs, 'db1').shape) + +#### +# nd multilevel dwt function tests +#### + + +def test_waverecn(): + rstate = np.random.RandomState(1234) + # test 1D through 4D cases + for nd in range(1, 5): + x = rstate.randn(*(4, )*nd) + coeffs = pywt.wavedecn(x, 'db1') + assert_(len(coeffs) == 3) + assert_allclose(pywt.waverecn(coeffs, 'db1'), x, rtol=tol_double) + + +def test_waverecn_empty_coeff(): + coeffs = [np.ones((2, 2, 2)), {}, {}] + assert_equal(pywt.waverecn(coeffs, 'db1').shape, (8, 8, 8)) + + assert_equal(pywt.waverecn(coeffs, 'db1').shape, (8, 8, 8)) + coeffs = [np.ones((2, 2, 2)), {}, {'daa': np.ones((4, 4, 4))}] + + coeffs = [np.ones((2, 2, 2)), {}, {}, {'daa': np.ones((8, 8, 8))}] + assert_equal(pywt.waverecn(coeffs, 'db1').shape, (16, 16, 16)) + + +def test_waverecn_invalid_coeffs(): + # approximation coeffs as None and no valid detail oeffs + coeffs = [None, {}] + assert_raises(ValueError, pywt.waverecn, coeffs, 'db1') + + # use of None for a coefficient value + coeffs = [np.ones((2, 2, 2)), {}, {'daa': None}, ] + assert_raises(ValueError, pywt.waverecn, coeffs, 'db1') + + # invalid key names in coefficient list + coeffs = [np.ones((4, 4, 4)), {'daa': np.ones((4, 4, 4)), + 'foo': np.ones((4, 4, 4))}] + assert_raises(ValueError, pywt.waverecn, coeffs, 'db1') + + # mismatched key name lengths + coeffs = [np.ones((4, 4, 4)), {'daa': np.ones((4, 4, 4)), + 'da': np.ones((4, 4, 4))}] + assert_raises(ValueError, pywt.waverecn, coeffs, 'db1') + + # key name lengths don't match the array dimensions + coeffs = [[[[1.0]]], {'ad': [[[0.0]]], 'da': [[[0.0]]], 'dd': [[[0.0]]]}] + assert_raises(ValueError, pywt.waverecn, coeffs, 'db1') + + # input list cannot be empty + assert_raises(ValueError, pywt.waverecn, [], 'haar') + + +def test_waverecn_invalid_inputs(): + + # coefficients from a difference decomposition used as input + for dec_func in [pywt.wavedec, pywt.wavedec2]: + coeffs = dec_func(np.ones((8, 8)), 'haar') + message = "Unexpected detail coefficient type" + assert_raises_regex(ValueError, message, pywt.waverecn, coeffs, + 'haar') + + +def test_waverecn_lists(): + # support coefficient arrays specified as lists instead of arrays + coeffs = [[[1.0]], {'ad': [[0.0]], 'da': [[0.0]], 'dd': [[0.0]]}] + assert_equal(pywt.waverecn(coeffs, 'db1').shape, (2, 2)) + + +def test_waverecn_invalid_coeffs2(): + # shape mismatch should raise an error + coeffs = [np.ones((4, 4, 4)), {'ada': np.ones((4, 4))}] + assert_raises(ValueError, pywt.waverecn, coeffs, 'db1') + + +def test_wavedecn_invalid_inputs(): + # input array has too few dimensions + data = np.array(0) + assert_raises(ValueError, pywt.wavedecn, data, 'haar') + + # invalid number of levels + data = np.ones(16) + assert_raises(ValueError, pywt.wavedecn, data, 'haar', level=-1) + + +def test_wavedecn_many_levels(): + # perfect reconstruction even when level > pywt.dwt_max_level + data = np.arange(64).reshape(8, 8) + tol = 1e-12 + dec_funcs = [pywt.wavedec, pywt.wavedec2, pywt.wavedecn] + rec_funcs = [pywt.waverec, pywt.waverec2, pywt.waverecn] + with warnings.catch_warnings(): + warnings.simplefilter('ignore', UserWarning) + for dec_func, rec_func in zip(dec_funcs, rec_funcs): + for mode in ['periodization', 'symmetric']: + coeffs = dec_func(data, 'haar', mode=mode, level=20) + r = rec_func(coeffs, 'haar', mode=mode) + assert_allclose(data, r, atol=tol, rtol=tol) + + +def test_waverecn_accuracies(): + # testing 3D only here + rstate = np.random.RandomState(1234) + x0 = rstate.randn(4, 4, 4) + for dt, tol in dtypes_and_tolerances: + x = x0.astype(dt) + if np.iscomplexobj(x): + x += 1j*rstate.randn(4, 4, 4).astype(x.real.dtype) + coeffs = pywt.wavedecn(x.astype(dt), 'db1') + assert_allclose(pywt.waverecn(coeffs, 'db1'), x, atol=tol, rtol=tol) + + +def test_multilevel_dtypes_nd(): + wavelet = pywt.Wavelet('haar') + for dt_in, dt_out in zip(dtypes_in, dtypes_out): + # wavedecn, waverecn + x = np.ones((8, 8), dtype=dt_in) + errmsg = f"wrong dtype returned for {dt_in} input" + cA, coeffsD2, coeffsD1 = pywt.wavedecn(x, wavelet, level=2) + assert_(cA.dtype == dt_out, "wavedecn: " + errmsg) + for key, c in coeffsD1.items(): + assert_(c.dtype == dt_out, "wavedecn: " + errmsg) + for key, c in coeffsD2.items(): + assert_(c.dtype == dt_out, "wavedecn: " + errmsg) + x_roundtrip = pywt.waverecn([cA, coeffsD2, coeffsD1], wavelet) + assert_(x_roundtrip.dtype == dt_out, "waverecn: " + errmsg) + + +def test_wavedecn_complex(): + data = np.ones((4, 4, 4)) + 1j + coeffs = pywt.wavedecn(data, 'db1') + assert_allclose(pywt.waverecn(coeffs, 'db1'), data, rtol=1e-12) + + +def test_waverecn_dtypes(): + x = np.ones((4, 4, 4)) + for dt, tol in dtypes_and_tolerances: + coeffs = pywt.wavedecn(x.astype(dt), 'db1') + assert_allclose(pywt.waverecn(coeffs, 'db1'), x, atol=tol, rtol=tol) + + +@pytest.mark.slow +def test_waverecn_all_wavelets_modes(): + # test 2D case using all wavelets and modes + rstate = np.random.RandomState(1234) + r = rstate.randn(80, 96) + for wavelet in wavelist: + for mode in pywt.Modes.modes: + coeffs = pywt.wavedecn(r, wavelet, mode=mode) + assert_allclose(pywt.waverecn(coeffs, wavelet, mode=mode), + r, rtol=tol_single, atol=tol_single) + + +def test_coeffs_to_array(): + # single element list returns the first element + a_coeffs = [np.arange(8).reshape(2, 4), ] + arr, arr_slices = pywt.coeffs_to_array(a_coeffs) + assert_allclose(arr, a_coeffs[0]) + assert_allclose(arr, arr[arr_slices[0]]) + + assert_raises(ValueError, pywt.coeffs_to_array, []) + # invalid second element: array as in wavedec, but not 1D + assert_raises(ValueError, pywt.coeffs_to_array, [a_coeffs[0], ] * 2) + # invalid second element: tuple as in wavedec2, but not a 3-tuple + assert_raises(ValueError, pywt.coeffs_to_array, [a_coeffs[0], + (a_coeffs[0], )]) + # coefficients as None is not supported + assert_raises(ValueError, pywt.coeffs_to_array, [None, ]) + assert_raises(ValueError, pywt.coeffs_to_array, [a_coeffs, + (None, None, None)]) + + # invalid type for second coefficient list element + assert_raises(ValueError, pywt.coeffs_to_array, [a_coeffs, None]) + + # use an invalid key name in the coef dictionary + coeffs = [np.array([0]), {'d': np.array([0]), 'c': np.array([0])}] + assert_raises(ValueError, pywt.coeffs_to_array, coeffs) + + +def test_wavedecn_coeff_reshape_even(): + # verify round trip is correct: + # wavedecn - >coeffs_to_array-> array_to_coeffs -> waverecn + # This is done for wavedec{1, 2, n} + rng = np.random.RandomState(1234) + params = {'wavedec': {'d': 1, 'dec': pywt.wavedec, 'rec': pywt.waverec}, + 'wavedec2': {'d': 2, 'dec': pywt.wavedec2, 'rec': pywt.waverec2}, + 'wavedecn': {'d': 3, 'dec': pywt.wavedecn, 'rec': pywt.waverecn}} + N = 28 + for f in params: + x1 = rng.randn(*([N] * params[f]['d'])) + for mode in pywt.Modes.modes: + for wave in wavelist: + w = pywt.Wavelet(wave) + maxlevel = pywt.dwt_max_level(np.min(x1.shape), w.dec_len) + if maxlevel == 0: + continue + + coeffs = params[f]['dec'](x1, w, mode=mode) + coeff_arr, coeff_slices = pywt.coeffs_to_array(coeffs) + coeffs2 = pywt.array_to_coeffs(coeff_arr, coeff_slices, + output_format=f) + x1r = params[f]['rec'](coeffs2, w, mode=mode) + + assert_allclose(x1, x1r, rtol=1e-4, atol=1e-4) + + +def test_wavedecn_coeff_reshape_axes_subset(): + # verify round trip is correct when only a subset of axes are transformed: + # wavedecn - >coeffs_to_array-> array_to_coeffs -> waverecn + # This is done for wavedec{1, 2, n} + rng = np.random.RandomState(1234) + mode = 'symmetric' + w = pywt.Wavelet('db2') + N = 16 + ndim = 3 + for axes in [(-1, ), (0, ), (1, ), (0, 1), (1, 2), (0, 2), None]: + x1 = rng.randn(*([N] * ndim)) + coeffs = pywt.wavedecn(x1, w, mode=mode, axes=axes) + coeff_arr, coeff_slices = pywt.coeffs_to_array(coeffs, axes=axes) + if axes is not None: + # if axes is not None, it must be provided to coeffs_to_array + assert_raises(ValueError, pywt.coeffs_to_array, coeffs) + + # mismatched axes size + assert_raises(ValueError, pywt.coeffs_to_array, coeffs, + axes=(0, 1, 2, 3)) + assert_raises(ValueError, pywt.coeffs_to_array, coeffs, + axes=()) + + coeffs2 = pywt.array_to_coeffs(coeff_arr, coeff_slices) + x1r = pywt.waverecn(coeffs2, w, mode=mode, axes=axes) + + assert_allclose(x1, x1r, rtol=1e-4, atol=1e-4) + + +def test_coeffs_to_array_padding(): + rng = np.random.RandomState(1234) + x1 = rng.randn(32, 32) + mode = 'symmetric' + coeffs = pywt.wavedecn(x1, 'db2', mode=mode) + + # padding=None raises a ValueError when tight packing is not possible + assert_raises(ValueError, pywt.coeffs_to_array, coeffs, padding=None) + + # set padded values to nan + coeff_arr, coeff_slices = pywt.coeffs_to_array(coeffs, padding=np.nan) + npad = np.sum(np.isnan(coeff_arr)) + assert_(npad > 0) + + # pad with zeros + coeff_arr, coeff_slices = pywt.coeffs_to_array(coeffs, padding=0) + assert_(np.sum(np.isnan(coeff_arr)) == 0) + assert_(np.sum(coeff_arr == 0) == npad) + + # Haar case with N as a power of 2 can be tightly packed + coeffs_haar = pywt.wavedecn(x1, 'haar', mode=mode) + coeff_arr, coeff_slices = pywt.coeffs_to_array(coeffs_haar, padding=None) + # shape of coeff_arr will match in this case, but not in general + assert_equal(coeff_arr.shape, x1.shape) + + +def test_waverecn_coeff_reshape_odd(): + # verify round trip is correct: + # wavedecn - >coeffs_to_array-> array_to_coeffs -> waverecn + rng = np.random.RandomState(1234) + x1 = rng.randn(35, 33) + for mode in pywt.Modes.modes: + for wave in ['haar', ]: + w = pywt.Wavelet(wave) + maxlevel = pywt.dwt_max_level(np.min(x1.shape), w.dec_len) + if maxlevel == 0: + continue + coeffs = pywt.wavedecn(x1, w, mode=mode) + coeff_arr, coeff_slices = pywt.coeffs_to_array(coeffs) + coeffs2 = pywt.array_to_coeffs(coeff_arr, coeff_slices) + x1r = pywt.waverecn(coeffs2, w, mode=mode) + # truncate reconstructed values to original shape + x1r = x1r[tuple([slice(s) for s in x1.shape])] + assert_allclose(x1, x1r, rtol=1e-4, atol=1e-4) + + +def test_array_to_coeffs_invalid_inputs(): + coeffs = pywt.wavedecn(np.ones(2), 'haar') + arr, arr_slices = pywt.coeffs_to_array(coeffs) + + # empty list of array slices + assert_raises(ValueError, pywt.array_to_coeffs, arr, []) + + # invalid format name + assert_raises(ValueError, pywt.array_to_coeffs, arr, arr_slices, 'foo') + + +def test_wavedecn_coeff_ravel(): + # verify round trip is correct: + # wavedecn - >ravel_coeffs-> unravel_coeffs -> waverecn + # This is done for wavedec{1, 2, n} + rng = np.random.RandomState(1234) + params = {'wavedec': {'d': 1, 'dec': pywt.wavedec, 'rec': pywt.waverec}, + 'wavedec2': {'d': 2, 'dec': pywt.wavedec2, 'rec': pywt.waverec2}, + 'wavedecn': {'d': 3, 'dec': pywt.wavedecn, 'rec': pywt.waverecn}} + N = 12 + for f in params: + x1 = rng.randn(*([N] * params[f]['d'])) + for mode in pywt.Modes.modes: + for wave in wavelist: + w = pywt.Wavelet(wave) + maxlevel = pywt.dwt_max_level(np.min(x1.shape), w.dec_len) + if maxlevel == 0: + continue + + coeffs = params[f]['dec'](x1, w, mode=mode) + coeff_arr, slices, shapes = pywt.ravel_coeffs(coeffs) + coeffs2 = pywt.unravel_coeffs(coeff_arr, slices, shapes, + output_format=f) + x1r = params[f]['rec'](coeffs2, w, mode=mode) + + assert_allclose(x1, x1r, rtol=1e-4, atol=1e-4) + + +def test_wavedecn_coeff_ravel_zero_level(): + # verify round trip is correct: + # wavedecn - >ravel_coeffs-> unravel_coeffs -> waverecn + # This is done for wavedec{1, 2, n} + rng = np.random.RandomState(1234) + params = {'wavedec': {'d': 1, 'dec': pywt.wavedec, 'rec': pywt.waverec}, + 'wavedec2': {'d': 2, 'dec': pywt.wavedec2, 'rec': pywt.waverec2}, + 'wavedecn': {'d': 3, 'dec': pywt.wavedecn, 'rec': pywt.waverecn}} + N = 16 + for f in params: + x1 = rng.randn(*([N] * params[f]['d'])) + for mode in pywt.Modes.modes: + w = pywt.Wavelet('db2') + + coeffs = params[f]['dec'](x1, w, mode=mode, level=0) + coeff_arr, slices, shapes = pywt.ravel_coeffs(coeffs) + coeffs2 = pywt.unravel_coeffs(coeff_arr, slices, shapes, + output_format=f) + x1r = params[f]['rec'](coeffs2, w, mode=mode) + + assert_allclose(x1, x1r, rtol=1e-4, atol=1e-4) + + +def test_waverecn_coeff_ravel_odd(): + # verify round trip is correct: + # wavedecn - >ravel_coeffs-> unravel_coeffs -> waverecn + rng = np.random.RandomState(1234) + x1 = rng.randn(35, 33) + for mode in pywt.Modes.modes: + for wave in ['haar', ]: + w = pywt.Wavelet(wave) + maxlevel = pywt.dwt_max_level(np.min(x1.shape), w.dec_len) + if maxlevel == 0: + continue + coeffs = pywt.wavedecn(x1, w, mode=mode) + coeff_arr, slices, shapes = pywt.ravel_coeffs(coeffs) + coeffs2 = pywt.unravel_coeffs(coeff_arr, slices, shapes) + x1r = pywt.waverecn(coeffs2, w, mode=mode) + # truncate reconstructed values to original shape + x1r = x1r[tuple([slice(s) for s in x1.shape])] + assert_allclose(x1, x1r, rtol=1e-4, atol=1e-4) + + +def test_ravel_wavedec2_with_lists(): + x1 = np.ones((8, 8)) + wav = pywt.Wavelet('haar') + coeffs = pywt.wavedec2(x1, wav) + + # list [cHn, cVn, cDn] instead of tuple is okay + coeffs[1:] = [list(c) for c in coeffs[1:]] + coeff_arr, slices, shapes = pywt.ravel_coeffs(coeffs) + coeffs2 = pywt.unravel_coeffs(coeff_arr, slices, shapes, + output_format='wavedec2') + x1r = pywt.waverec2(coeffs2, wav) + assert_allclose(x1, x1r, rtol=1e-4, atol=1e-4) + + # wrong length list will cause a ValueError + coeffs[1:] = [list(c[:-1]) for c in coeffs[1:]] # truncate diag coeffs + assert_raises(ValueError, pywt.ravel_coeffs, coeffs) + + +def test_ravel_invalid_input(): + # wavedec ravel does not support any coefficient arrays being set to None + coeffs = pywt.wavedec(np.ones(8), 'haar') + coeffs[1] = None + assert_raises(ValueError, pywt.ravel_coeffs, coeffs) + + # wavedec2 ravel cannot have None or a tuple/list of None + coeffs = pywt.wavedec2(np.ones((8, 8)), 'haar') + coeffs[1] = (None, None, None) + assert_raises(ValueError, pywt.ravel_coeffs, coeffs) + coeffs[1] = [None, None, None] + assert_raises(ValueError, pywt.ravel_coeffs, coeffs) + coeffs[1] = None + assert_raises(ValueError, pywt.ravel_coeffs, coeffs) + + # wavedecn ravel cannot have any dictionary elements as None + coeffs = pywt.wavedecn(np.ones((8, 8, 8)), 'haar') + coeffs[1]['ddd'] = None + assert_raises(ValueError, pywt.ravel_coeffs, coeffs) + + +def test_unravel_invalid_inputs(): + coeffs = pywt.wavedecn(np.ones(2), 'haar') + arr, slices, shapes = pywt.ravel_coeffs(coeffs) + + # empty list for slices or shapes + assert_raises(ValueError, pywt.unravel_coeffs, arr, slices, []) + assert_raises(ValueError, pywt.unravel_coeffs, arr, [], shapes) + + # unequal length for slices/shapes + assert_raises(ValueError, pywt.unravel_coeffs, arr, slices[:-1], shapes) + + # invalid format name + assert_raises(ValueError, pywt.unravel_coeffs, arr, slices, shapes, 'foo') + + +def test_wavedecn_shapes_and_size(): + wav = pywt.Wavelet('db2') + for data_shape in [(33, ), (64, 32), (1, 15, 30)]: + for axes in [None, 0, -1]: + for mode in pywt.Modes.modes: + coeffs = pywt.wavedecn(np.ones(data_shape), wav, + mode=mode, axes=axes) + + # verify that the shapes match the coefficient shapes + shapes = pywt.wavedecn_shapes(data_shape, wav, + mode=mode, axes=axes) + + assert_equal(coeffs[0].shape, shapes[0]) + expected_size = coeffs[0].size + for level in range(1, len(coeffs)): + for k, v in coeffs[level].items(): + expected_size += v.size + assert_equal(shapes[level][k], v.shape) + + # size can be determined from either the shapes or coeffs + size = pywt.wavedecn_size(shapes) + assert_equal(size, expected_size) + + size = pywt.wavedecn_size(coeffs) + assert_equal(size, expected_size) + + +def test_dwtn_max_level(): + # predicted and empirical dwtn_max_level match + for wav in [pywt.Wavelet('db2'), 'sym8']: + for data_shape in [(33, ), (64, 32), (1, 15, 30)]: + for axes in [None, 0, -1]: + for mode in pywt.Modes.modes: + coeffs = pywt.wavedecn(np.ones(data_shape), wav, + mode=mode, axes=axes) + max_lev = pywt.dwtn_max_level(data_shape, wav, axes) + assert_equal(len(coeffs[1:]), max_lev) + + +def test_waverec_axes_subsets(): + rstate = np.random.RandomState(0) + data = rstate.standard_normal((8, 8, 8)) + # test all combinations of 1 out of 3 axes transformed + for axis in [0, 1, 2]: + coefs = pywt.wavedec(data, 'haar', axis=axis) + rec = pywt.waverec(coefs, 'haar', axis=axis) + assert_allclose(rec, data, atol=1e-14) + + +def test_waverec_axis_db2(): + # test for fix to issue gh-293 + rstate = np.random.RandomState(0) + data = rstate.standard_normal((16, 16)) + for axis in [0, 1]: + coefs = pywt.wavedec(data, 'db2', axis=axis) + rec = pywt.waverec(coefs, 'db2', axis=axis) + assert_allclose(rec, data, atol=1e-14) + + +def test_waverec2_axes_subsets(): + rstate = np.random.RandomState(0) + data = rstate.standard_normal((8, 8, 8)) + # test all combinations of 2 out of 3 axes transformed + for axes in combinations((0, 1, 2), 2): + coefs = pywt.wavedec2(data, 'haar', axes=axes) + rec = pywt.waverec2(coefs, 'haar', axes=axes) + assert_allclose(rec, data, atol=1e-14) + + +def test_waverecn_axes_subsets(): + rstate = np.random.RandomState(0) + data = rstate.standard_normal((8, 8, 8, 8)) + # test all combinations of 3 out of 4 axes transformed + for axes in combinations((0, 1, 2, 3), 3): + coefs = pywt.wavedecn(data, 'haar', axes=axes) + rec = pywt.waverecn(coefs, 'haar', axes=axes) + assert_allclose(rec, data, atol=1e-14) + + +def test_waverecn_int_axis(): + # waverecn should also work for axes as an integer + rstate = np.random.RandomState(0) + data = rstate.standard_normal((8, 8)) + for axis in [0, 1]: + coefs = pywt.wavedecn(data, 'haar', axes=axis) + rec = pywt.waverecn(coefs, 'haar', axes=axis) + assert_allclose(rec, data, atol=1e-14) + + +def test_wavedec_axis_error(): + data = np.ones(4) + # out of range axis not allowed + assert_raises(ValueError, pywt.wavedec, data, 'haar', axis=1) + + +def test_waverec_axis_error(): + c = pywt.wavedec(np.ones(4), 'haar') + # out of range axis not allowed + assert_raises(ValueError, pywt.waverec, c, 'haar', axis=1) + + +def test_waverec_shape_mismatch_error(): + c = pywt.wavedec(np.ones(16), 'haar') + # truncate a detail coefficient to an incorrect shape + c[3] = c[3][:-1] + assert_raises(ValueError, pywt.waverec, c, 'haar', axis=1) + + +def test_wavedec2_axes_errors(): + data = np.ones((4, 4)) + # integer axes not allowed + assert_raises(TypeError, pywt.wavedec2, data, 'haar', axes=1) + # non-unique axes not allowed + assert_raises(ValueError, pywt.wavedec2, data, 'haar', axes=(0, 0)) + # out of range axis not allowed + assert_raises(ValueError, pywt.wavedec2, data, 'haar', axes=(0, 2)) + + +def test_waverec2_axes_errors(): + data = np.ones((4, 4)) + c = pywt.wavedec2(data, 'haar') + # integer axes not allowed + assert_raises(TypeError, pywt.waverec2, c, 'haar', axes=1) + # non-unique axes not allowed + assert_raises(ValueError, pywt.waverec2, c, 'haar', axes=(0, 0)) + # out of range axis not allowed + assert_raises(ValueError, pywt.waverec2, c, 'haar', axes=(0, 2)) + + +def test_wavedecn_axes_errors(): + data = np.ones((8, 8, 8)) + # repeated axes not allowed + assert_raises(ValueError, pywt.wavedecn, data, 'haar', axes=(1, 1)) + # out of range axis not allowed + assert_raises(ValueError, pywt.wavedecn, data, 'haar', axes=(0, 1, 3)) + + +def test_waverecn_axes_errors(): + data = np.ones((8, 8, 8)) + c = pywt.wavedecn(data, 'haar') + # repeated axes not allowed + assert_raises(ValueError, pywt.waverecn, c, 'haar', axes=(1, 1)) + # out of range axis not allowed + assert_raises(ValueError, pywt.waverecn, c, 'haar', axes=(0, 1, 3)) + + +def test_per_axis_wavelets_and_modes(): + # tests separate wavelet and edge mode for each axis. + rstate = np.random.RandomState(1234) + data = rstate.randn(24, 24, 16) + + # wavelet can be a string or wavelet object + wavelets = (pywt.Wavelet('haar'), 'sym2', 'db2') + + # The default number of levels should be the minimum over this list + max_levels = [pywt._dwt.dwt_max_level(nd, nf) for nd, nf in + zip(data.shape, wavelets)] + + # mode can be a string or a Modes enum + modes = ('symmetric', 'periodization', + pywt._extensions._pywt.Modes.reflect) + + coefs = pywt.wavedecn(data, wavelets, modes) + assert_allclose(pywt.waverecn(coefs, wavelets, modes), data, atol=1e-14) + assert_equal(min(max_levels), len(coefs[1:])) + + coefs = pywt.wavedecn(data, wavelets[:1], modes) + assert_allclose(pywt.waverecn(coefs, wavelets[:1], modes), data, + atol=1e-14) + + coefs = pywt.wavedecn(data, wavelets, modes[:1]) + assert_allclose(pywt.waverecn(coefs, wavelets, modes[:1]), data, + atol=1e-14) + + # length of wavelets or modes doesn't match the length of axes + assert_raises(ValueError, pywt.wavedecn, data, wavelets[:2]) + assert_raises(ValueError, pywt.wavedecn, data, wavelets, mode=modes[:2]) + assert_raises(ValueError, pywt.waverecn, coefs, wavelets[:2]) + assert_raises(ValueError, pywt.waverecn, coefs, wavelets, mode=modes[:2]) + + # dwt2/idwt2 also support per-axis wavelets/modes + data2 = data[..., 0] + coefs2 = pywt.wavedec2(data2, wavelets[:2], modes[:2]) + assert_allclose(pywt.waverec2(coefs2, wavelets[:2], modes[:2]), data2, + atol=1e-14) + assert_equal(min(max_levels[:2]), len(coefs2[1:])) + +# Tests for fully separable multi-level transforms + + +def test_fswavedecn_fswaverecn_roundtrip(): + # verify proper round trip result for 1D through 4D data + # same DWT as wavedecn/waverecn so don't need to test all modes/wavelets + rstate = np.random.RandomState(0) + for ndim in range(1, 5): + for dt_in, dt_out in zip(dtypes_in, dtypes_out): + for levels in (1, None): + data = rstate.standard_normal((8, )*ndim) + data = data.astype(dt_in) + T = pywt.fswavedecn(data, 'haar', levels=levels) + rec = pywt.fswaverecn(T) + if data.real.dtype in [np.float32, np.float16]: + assert_allclose(rec, data, rtol=1e-6, atol=1e-6) + else: + assert_allclose(rec, data, rtol=1e-14, atol=1e-14) + assert_(T.coeffs.dtype == dt_out) + assert_(rec.dtype == dt_out) + + +def test_fswavedecn_fswaverecn_zero_levels(): + # zero level transform gives coefs matching the original data + rstate = np.random.RandomState(0) + ndim = 2 + data = rstate.standard_normal((8, )*ndim) + T = pywt.fswavedecn(data, 'haar', levels=0) + assert_array_equal(T.coeffs, data) + rec = pywt.fswaverecn(T) + assert_array_equal(T.coeffs, rec) + + +def test_fswavedecn_fswaverecn_variable_levels(): + # test with differing number of transform levels per axis + rstate = np.random.RandomState(0) + ndim = 3 + data = rstate.standard_normal((16, )*ndim) + T = pywt.fswavedecn(data, 'haar', levels=(1, 2, 3)) + rec = pywt.fswaverecn(T) + assert_allclose(rec, data, atol=1e-14) + + # levels doesn't match number of axes + assert_raises(ValueError, pywt.fswavedecn, data, 'haar', levels=(1, 1)) + assert_raises(ValueError, pywt.fswavedecn, data, 'haar', levels=(1, 1, 1, 1)) + + # levels too large for array size + with pytest.warns(UserWarning): + pywt.fswavedecn(data, 'haar', + levels=int(np.log2(np.min(data.shape)))+1) + + +def test_fswavedecn_fswaverecn_variable_wavelets_and_modes(): + # test with differing number of transform levels per axis + rstate = np.random.RandomState(0) + ndim = 3 + data = rstate.standard_normal((16, )*ndim) + wavelets = ('haar', 'db2', 'sym3') + modes = ('periodic', 'symmetric', 'periodization') + T = pywt.fswavedecn(data, wavelet=wavelets, mode=modes) + for ax in range(ndim): + # expect approx + dwt_max_level detail coeffs along each axis + assert_equal(len(T.coeff_slices[ax]), + pywt.dwt_max_level(data.shape[ax], wavelets[ax])+1) + + rec = pywt.fswaverecn(T) + assert_allclose(rec, data, atol=1e-14) + + # number of wavelets doesn't match number of axes + assert_raises(ValueError, pywt.fswavedecn, data, wavelets[:2]) + + # number of modes doesn't match number of axes + assert_raises(ValueError, pywt.fswavedecn, data, wavelets[0], mode=modes[:2]) + + +def test_fswavedecn_fswaverecn_axes_subsets(): + """Fully separable DWT over only a subset of axes""" + rstate = np.random.RandomState(0) + # use anisotropic data to result in unique number of levels per axis + data = rstate.standard_normal((4, 8, 16, 32)) + # test all combinations of 3 out of 4 axes transformed + for axes in combinations((0, 1, 2, 3), 3): + T = pywt.fswavedecn(data, 'haar', axes=axes) + rec = pywt.fswaverecn(T) + assert_allclose(rec, data, atol=1e-14) + + # some axes exceed data dimensions + assert_raises(ValueError, pywt.fswavedecn, data, 'haar', axes=(1, 5)) + + +def test_fswavedecnresult(): + data = np.ones((32, 32)) + levels = (1, 2) + result = pywt.fswavedecn(data, 'sym2', levels=levels) + + # can access the lowpass band via .approx or via __getitem__ + approx_key = (0, ) * data.ndim + assert_array_equal(result[approx_key], result.approx) + + dkeys = result.detail_keys() + # the approximation key shouldn't be present in the detail_keys + assert_(approx_key not in dkeys) + + # can access all detail coefficients and they have matching ndim + for k in dkeys: + d = result[k] + assert_equal(d.ndim, data.ndim) + + # can assign modified coefficients + result[k] = np.zeros_like(d) + + # assigning a differently sized array raises a ValueError + assert_raises(ValueError, result.__setitem__, + k, np.zeros(tuple([s + 1 for s in d.shape]))) + + # warns on assigning with a non-matching dtype + with pytest.warns(UserWarning): + result.__setitem__(k, np.zeros_like(d).astype(np.float32)) + + # all coefficients are stacked into result.coeffs (same ndim) + assert_equal(result.coeffs.ndim, data.ndim) + + +def test_error_on_continuous_wavelet(): + # A ValueError is raised if a Continuous wavelet is selected + data = np.ones((16, 16)) + for dec_fun, rec_fun in zip([pywt.wavedec, pywt.wavedec2, pywt.wavedecn], + [pywt.waverec, pywt.waverec2, pywt.waverecn]): + for cwave in ['morl', pywt.DiscreteContinuousWavelet('morl')]: + assert_raises(ValueError, dec_fun, data, wavelet=cwave) + + c = dec_fun(data, 'db1') + assert_raises(ValueError, rec_fun, c, wavelet=cwave) + + +def test_default_level(): + # default level is the maximum permissible for the transformed axes + data = np.ones((128, 32, 4)) + wavelet = ('db8', 'db1') + for dec_func in [pywt.wavedec2, pywt.wavedecn]: + for axes in [(0, 1), (2, 1), (0, 2)]: + c = dec_func(data, wavelet, axes=axes) + max_lev = np.min([pywt.dwt_max_level(data.shape[ax], wav) + for ax, wav in zip(axes, wavelet)]) + assert_equal(len(c[1:]), max_lev) + + for ax in [0, 1]: + c = pywt.wavedecn(data, wavelet[ax], axes=(ax, )) + assert_equal(len(c[1:]), + pywt.dwt_max_level(data.shape[ax], wavelet[ax])) + + +def test_waverec_mixed_precision(): + rstate = np.random.RandomState(0) + for func, ifunc, shape in [(pywt.wavedec, pywt.waverec, (8, )), + (pywt.wavedec2, pywt.waverec2, (8, 8)), + (pywt.wavedecn, pywt.waverecn, (8, 8, 8))]: + x = rstate.randn(*shape) + coeffs_real = func(x, 'db1') + + # real: single precision approx, double precision details + coeffs_real[0] = coeffs_real[0].astype(np.float32) + r = ifunc(coeffs_real, 'db1') + assert_allclose(r, x, rtol=1e-7, atol=1e-7) + assert_equal(r.dtype, np.float64) + + x = x + 1j*x + coeffs = func(x, 'db1') + + # complex: single precision approx, double precision details + coeffs[0] = coeffs[0].astype(np.complex64) + r = ifunc(coeffs, 'db1') + assert_allclose(r, x, rtol=1e-7, atol=1e-7) + assert_equal(r.dtype, np.complex128) + + # complex: double precision approx, single precision details + if x.ndim == 1: + coeffs[0] = coeffs[0].astype(np.complex128) + coeffs[1] = coeffs[1].astype(np.complex64) + if x.ndim == 2: + coeffs[0] = coeffs[0].astype(np.complex128) + coeffs[1] = tuple([v.astype(np.complex64) for v in coeffs[1]]) + if x.ndim == 3: + coeffs[0] = coeffs[0].astype(np.complex128) + coeffs[1] = {k: v.astype(np.complex64) + for k, v in coeffs[1].items()} + r = ifunc(coeffs, 'db1') + assert_allclose(r, x, rtol=1e-7, atol=1e-7) + assert_equal(r.dtype, np.complex128) diff --git a/.venv/lib/python3.12/site-packages/pywt/tests/test_perfect_reconstruction.py b/.venv/lib/python3.12/site-packages/pywt/tests/test_perfect_reconstruction.py new file mode 100644 index 0000000000000000000000000000000000000000..b5e6f9375f93891692e415246d3539df230b76b6 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/pywt/tests/test_perfect_reconstruction.py @@ -0,0 +1,62 @@ +#!/usr/bin/env python + +""" +Verify DWT perfect reconstruction. +""" + + +import numpy as np +import pytest +from numpy.testing import assert_ + +import pywt + + +@pytest.mark.slow +def test_perfect_reconstruction(): + families = ('db', 'sym', 'coif', 'bior', 'rbio') + wavelets = sum([pywt.wavelist(name) for name in families], []) + # list of mode names in pywt and matlab + modes = [('zero', 'zpd'), + ('constant', 'sp0'), + ('symmetric', 'sym'), + ('periodic', 'ppd'), + ('smooth', 'sp1'), + ('periodization', 'per')] + + dtypes = (np.float32, np.float64) + + for wavelet in wavelets: + for pmode, mmode in modes: + for dt in dtypes: + check_reconstruction(pmode, mmode, wavelet, dt) + + +def check_reconstruction(pmode, mmode, wavelet, dtype): + data_size = list(range(2, 40)) + [100, 200, 500, 1000, 2000, 10000, + 50000, 100000] + np.random.seed(12345) + # TODO: smoke testing - more failures for different seeds + + if dtype == np.float32: + # was 3e-7 has to be lowered as db21, db29, db33, db35, coif14, coif16 were failing + epsilon = 6e-7 + else: + epsilon = 5e-11 + + for N in data_size: + data = np.asarray(np.random.random(N), dtype) + + # compute dwt coefficients + pa, pd = pywt.dwt(data, wavelet, pmode) + + # compute reconstruction + rec = pywt.idwt(pa, pd, wavelet, pmode) + + if len(data) % 2: + rec = rec[:len(data)] + + rms_rec = np.sqrt(np.mean((data-rec)**2)) + msg = ('[RMS_REC > EPSILON] for Mode: %s, Wavelet: %s, ' + 'Length: %d, rms=%.3g' % (pmode, wavelet, len(data), rms_rec)) + assert_(rms_rec < epsilon, msg=msg) diff --git a/.venv/lib/python3.12/site-packages/pywt/tests/test_swt.py b/.venv/lib/python3.12/site-packages/pywt/tests/test_swt.py new file mode 100644 index 0000000000000000000000000000000000000000..98e722ae24c390312d139274ef6946aae562941f --- /dev/null +++ b/.venv/lib/python3.12/site-packages/pywt/tests/test_swt.py @@ -0,0 +1,657 @@ +#!/usr/bin/env python + + +import warnings +from copy import deepcopy +from itertools import combinations, permutations + +import numpy as np +import pytest +from numpy.testing import ( + assert_, + assert_allclose, + assert_array_equal, + assert_equal, +) + +import pywt +from pywt._extensions._swt import swt_axis + +# Check that float32 and complex64 are preserved. Other real types get +# converted to float64. +dtypes_in = [np.int8, np.float16, np.float32, np.float64, np.complex64, + np.complex128] +dtypes_out = [np.float64, np.float32, np.float32, np.float64, np.complex64, + np.complex128] + +# tolerances used in accuracy comparisons +tol_single = 1e-6 +tol_double = 1e-13 + +#### +# 1d multilevel swt tests +#### + + +def test_swt_decomposition(): + x = [3, 7, 1, 3, -2, 6, 4, 6] + db1 = pywt.Wavelet('db1') + atol = tol_double + (cA3, cD3), (cA2, cD2), (cA1, cD1) = pywt.swt(x, db1, level=3) + expected_cA1 = [7.07106781, 5.65685425, 2.82842712, 0.70710678, + 2.82842712, 7.07106781, 7.07106781, 6.36396103] + assert_allclose(cA1, expected_cA1, rtol=1e-8, atol=atol) + expected_cD1 = [-2.82842712, 4.24264069, -1.41421356, 3.53553391, + -5.65685425, 1.41421356, -1.41421356, 2.12132034] + assert_allclose(cD1, expected_cD1, rtol=1e-8, atol=atol) + expected_cA2 = [7, 4.5, 4, 5.5, 7, 9.5, 10, 8.5] + assert_allclose(cA2, expected_cA2, rtol=tol_double, atol=atol) + expected_cD2 = [3, 3.5, 0, -4.5, -3, 0.5, 0, 0.5] + assert_allclose(cD2, expected_cD2, rtol=tol_double, atol=atol) + expected_cA3 = [9.89949494, ] * 8 + assert_allclose(cA3, expected_cA3, rtol=1e-8, atol=atol) + expected_cD3 = [0.00000000, -3.53553391, -4.24264069, -2.12132034, + 0.00000000, 3.53553391, 4.24264069, 2.12132034] + assert_allclose(cD3, expected_cD3, rtol=1e-8, atol=atol) + + # level=1, start_level=1 decomposition should match level=2 + res = pywt.swt(cA1, db1, level=1, start_level=1) + cA2, cD2 = res[0] + assert_allclose(cA2, expected_cA2, rtol=tol_double, atol=atol) + assert_allclose(cD2, expected_cD2, rtol=tol_double, atol=atol) + + coeffs = pywt.swt(x, db1) + assert_(len(coeffs) == 3) + assert_(pywt.swt_max_level(len(x)), 3) + + +def test_swt_max_level(): + # odd sized signal will warn about no levels of decomposition possible + with pytest.warns(UserWarning): + pywt.swt_max_level(11) + + with warnings.catch_warnings(): + warnings.simplefilter('ignore', UserWarning) + assert_equal(pywt.swt_max_level(11), 0) + + # no warnings when >= 1 level of decomposition possible + assert_equal(pywt.swt_max_level(2), 1) # divisible by 2**1 + assert_equal(pywt.swt_max_level(4*3), 2) # divisible by 2**2 + assert_equal(pywt.swt_max_level(16), 4) # divisible by 2**4 + assert_equal(pywt.swt_max_level(16*3), 4) # divisible by 2**4 + + +def test_swt_axis(): + x = [3, 7, 1, 3, -2, 6, 4, 6] + + db1 = pywt.Wavelet('db1') + (cA2, cD2), (cA1, cD1) = pywt.swt(x, db1, level=2) + + # test cases use 2D arrays based on tiling x along an axis and then + # calling swt along the other axis. + for order in ['C', 'F']: + # test SWT of 2D data along default axis (-1) + x_2d = np.asarray(x).reshape((1, -1)) + x_2d = np.concatenate((x_2d, )*5, axis=0) + if order == 'C': + x_2d = np.ascontiguousarray(x_2d) + elif order == 'F': + x_2d = np.asfortranarray(x_2d) + (cA2_2d, cD2_2d), (cA1_2d, cD1_2d) = pywt.swt(x_2d, db1, level=2) + + for c in [cA2_2d, cD2_2d, cA1_2d, cD1_2d]: + assert_(c.shape == x_2d.shape) + # each row should match the 1D result + for row in cA1_2d: + assert_array_equal(row, cA1) + for row in cA2_2d: + assert_array_equal(row, cA2) + for row in cD1_2d: + assert_array_equal(row, cD1) + for row in cD2_2d: + assert_array_equal(row, cD2) + + # test SWT of 2D data along other axis (0) + x_2d = np.asarray(x).reshape((-1, 1)) + x_2d = np.concatenate((x_2d, )*5, axis=1) + if order == 'C': + x_2d = np.ascontiguousarray(x_2d) + elif order == 'F': + x_2d = np.asfortranarray(x_2d) + (cA2_2d, cD2_2d), (cA1_2d, cD1_2d) = pywt.swt(x_2d, db1, level=2, + axis=0) + + for c in [cA2_2d, cD2_2d, cA1_2d, cD1_2d]: + assert_(c.shape == x_2d.shape) + # each column should match the 1D result + for row in cA1_2d.transpose((1, 0)): + assert_array_equal(row, cA1) + for row in cA2_2d.transpose((1, 0)): + assert_array_equal(row, cA2) + for row in cD1_2d.transpose((1, 0)): + assert_array_equal(row, cD1) + for row in cD2_2d.transpose((1, 0)): + assert_array_equal(row, cD2) + + # axis too large + with pytest.raises(ValueError): + pywt.swt(x, db1, level=2, axis=5) + + +def test_swt_iswt_integration(): + # This function performs a round-trip swt/iswt transform test on + # all available types of wavelets in PyWavelets - except the + # 'dmey' wavelet. The latter has been excluded because it does not + # produce very precise results. This is likely due to the fact + # that the 'dmey' wavelet is a discrete approximation of a + # continuous wavelet. All wavelets are tested up to 3 levels. The + # test validates neither swt or iswt as such, but it does ensure + # that they are each other's inverse. + + max_level = 3 + wavelets = pywt.wavelist(kind='discrete') + if 'dmey' in wavelets: + # The 'dmey' wavelet seems to be a bit special - disregard it for now + wavelets.remove('dmey') + for current_wavelet_str in wavelets: + current_wavelet = pywt.Wavelet(current_wavelet_str) + input_length_power = int(np.ceil(np.log2(max( + current_wavelet.dec_len, + current_wavelet.rec_len)))) + input_length = 2**(input_length_power + max_level - 1) + X = np.arange(input_length) + for norm in [True, False]: + if norm and not current_wavelet.orthogonal: + # non-orthogonal wavelets to avoid warnings when norm=True + continue + for trim_approx in [True, False]: + coeffs = pywt.swt(X, current_wavelet, max_level, + trim_approx=trim_approx, norm=norm) + Y = pywt.iswt(coeffs, current_wavelet, norm=norm) + assert_allclose(Y, X, rtol=1e-5, atol=1e-7) + + +def test_swt_dtypes(): + wavelet = pywt.Wavelet('haar') + for dt_in, dt_out in zip(dtypes_in, dtypes_out): + errmsg = f"wrong dtype returned for {dt_in} input" + + # swt + x = np.ones(8, dtype=dt_in) + (cA2, cD2), (cA1, cD1) = pywt.swt(x, wavelet, level=2) + assert_(cA2.dtype == cD2.dtype == cA1.dtype == cD1.dtype == dt_out, + "swt: " + errmsg) + + # swt2 + x = np.ones((8, 8), dtype=dt_in) + cA, (cH, cV, cD) = pywt.swt2(x, wavelet, level=1)[0] + assert_(cA.dtype == cH.dtype == cV.dtype == cD.dtype == dt_out, + "swt2: " + errmsg) + + +def test_swt_roundtrip_dtypes(): + # verify perfect reconstruction for all dtypes + rstate = np.random.RandomState(5) + wavelet = pywt.Wavelet('haar') + for dt_in, dt_out in zip(dtypes_in, dtypes_out): + # swt, iswt + x = rstate.standard_normal((8, )).astype(dt_in) + c = pywt.swt(x, wavelet, level=2) + xr = pywt.iswt(c, wavelet) + assert_allclose(x, xr, rtol=1e-6, atol=1e-7) + + # swt2, iswt2 + x = rstate.standard_normal((8, 8)).astype(dt_in) + c = pywt.swt2(x, wavelet, level=2) + xr = pywt.iswt2(c, wavelet) + assert_allclose(x, xr, rtol=1e-6, atol=1e-7) + + +def test_swt_default_level_by_axis(): + # make sure default number of levels matches the max level along the axis + wav = 'db2' + x = np.ones((2**3, 2**4, 2**5)) + for axis in (0, 1, 2): + sdec = pywt.swt(x, wav, level=None, start_level=0, axis=axis) + assert_equal(len(sdec), pywt.swt_max_level(x.shape[axis])) + + +def test_swt2_ndim_error(): + x = np.ones(8) + with pytest.raises(ValueError): + pywt.swt2(x, 'haar', level=1) + + +@pytest.mark.slow +def test_swt2_iswt2_integration(wavelets=None): + # This function performs a round-trip swt2/iswt2 transform test on + # all available types of wavelets in PyWavelets - except the + # 'dmey' wavelet. The latter has been excluded because it does not + # produce very precise results. This is likely due to the fact + # that the 'dmey' wavelet is a discrete approximation of a + # continuous wavelet. All wavelets are tested up to 3 levels. The + # test validates neither swt2 or iswt2 as such, but it does ensure + # that they are each other's inverse. + + max_level = 3 + if wavelets is None: + wavelets = pywt.wavelist(kind='discrete') + if 'dmey' in wavelets: + # The 'dmey' wavelet is a special case - disregard it for now + wavelets.remove('dmey') + for current_wavelet_str in wavelets: + current_wavelet = pywt.Wavelet(current_wavelet_str) + input_length_power = int(np.ceil(np.log2(max( + current_wavelet.dec_len, + current_wavelet.rec_len)))) + input_length = 2**(input_length_power + max_level - 1) + X = np.arange(input_length**2).reshape(input_length, input_length) + + for norm in [True, False]: + if norm and not current_wavelet.orthogonal: + # non-orthogonal wavelets to avoid warnings when norm=True + continue + for trim_approx in [True, False]: + coeffs = pywt.swt2(X, current_wavelet, max_level, + trim_approx=trim_approx, norm=norm) + Y = pywt.iswt2(coeffs, current_wavelet, norm=norm) + assert_allclose(Y, X, rtol=1e-5, atol=1e-5) + + +def test_swt2_iswt2_quick(): + test_swt2_iswt2_integration(wavelets=['db1', ]) + + +def test_swt2_iswt2_non_square(wavelets=None): + for nrows in [8, 16, 48]: + X = np.arange(nrows*32).reshape(nrows, 32) + current_wavelet = 'db1' + with warnings.catch_warnings(): + warnings.simplefilter('ignore', FutureWarning) + coeffs = pywt.swt2(X, current_wavelet, level=2) + Y = pywt.iswt2(coeffs, current_wavelet) + assert_allclose(Y, X, rtol=tol_single, atol=tol_single) + + +def test_swt2_axes(): + atol = 1e-14 + current_wavelet = pywt.Wavelet('db2') + input_length_power = int(np.ceil(np.log2(max( + current_wavelet.dec_len, + current_wavelet.rec_len)))) + input_length = 2**(input_length_power) + X = np.arange(input_length**2).reshape(input_length, input_length) + + (cA1, (cH1, cV1, cD1)) = pywt.swt2(X, current_wavelet, level=1)[0] + # opposite order + (cA2, (cH2, cV2, cD2)) = pywt.swt2(X, current_wavelet, level=1, + axes=(1, 0))[0] + assert_allclose(cA1, cA2, atol=atol) + assert_allclose(cH1, cV2, atol=atol) + assert_allclose(cV1, cH2, atol=atol) + assert_allclose(cD1, cD2, atol=atol) + + # reverify iswt2 restores the original data + r1 = pywt.iswt2([cA1, (cH1, cV1, cD1)], current_wavelet) + assert_allclose(X, r1, atol=atol) + r2 = pywt.iswt2([cA2, (cH2, cV2, cD2)], current_wavelet, axes=(1, 0)) + assert_allclose(X, r2, atol=atol) + + # duplicate axes not allowed + with pytest.raises(ValueError): + pywt.swt2(X, current_wavelet, 1, axes=(0, 0)) + + # too few axes + with pytest.raises(ValueError): + pywt.swt2(X, current_wavelet, 1, axes=(0, )) + + +def test_swtn_axes(): + atol = 1e-14 + current_wavelet = pywt.Wavelet('db2') + input_length_power = int(np.ceil(np.log2(max( + current_wavelet.dec_len, + current_wavelet.rec_len)))) + input_length = 2**(input_length_power) + X = np.arange(input_length**2).reshape(input_length, input_length) + coeffs = pywt.swtn(X, current_wavelet, level=1, axes=None)[0] + # opposite order + coeffs2 = pywt.swtn(X, current_wavelet, level=1, axes=(1, 0))[0] + assert_allclose(coeffs['aa'], coeffs2['aa'], atol=atol) + assert_allclose(coeffs['ad'], coeffs2['da'], atol=atol) + assert_allclose(coeffs['da'], coeffs2['ad'], atol=atol) + assert_allclose(coeffs['dd'], coeffs2['dd'], atol=atol) + + # 0-level transform + empty = pywt.swtn(X, current_wavelet, level=0) + assert_equal(empty, []) + + # duplicate axes not allowed + with pytest.raises(ValueError): + pywt.swtn(X, current_wavelet, 1, axes=(0, 0)) + + # data.ndim = 0 + with pytest.raises(ValueError): + pywt.swtn(np.asarray([]), current_wavelet, 1) + + # start_level too large + with pytest.raises(ValueError): + pywt.swtn(X, current_wavelet, level=1, start_level=2) + + # level < 1 in swt_axis call + with pytest.raises(ValueError): + swt_axis(X, current_wavelet, level=0, start_level=0) + + # odd-sized data not allowed + with pytest.raises(ValueError): + swt_axis( X[-1, :], current_wavelet, level=0, start_level=0, axis=0) + + +@pytest.mark.slow +def test_swtn_iswtn_integration(wavelets=None): + # This function performs a round-trip swtn/iswtn transform for various + # possible combinations of: + # 1.) 1 out of 2 axes of a 2D array + # 2.) 2 out of 3 axes of a 3D array + # + # To keep test time down, only wavelets of length <= 8 are run. + # + # This test does not validate swtn or iswtn individually, but only + # confirms that iswtn yields an (almost) perfect reconstruction of swtn. + max_level = 3 + if wavelets is None: + wavelets = pywt.wavelist(kind='discrete') + if 'dmey' in wavelets: + # The 'dmey' wavelet is a special case - disregard it for now + wavelets.remove('dmey') + for ndim_transform in range(1, 3): + ndim = ndim_transform + 1 + for axes in combinations(range(ndim), ndim_transform): + for current_wavelet_str in wavelets: + wav = pywt.Wavelet(current_wavelet_str) + if wav.dec_len > 8: + continue # avoid excessive test duration + input_length_power = int(np.ceil(np.log2(max( + wav.dec_len, + wav.rec_len)))) + N = 2**(input_length_power + max_level - 1) + X = np.arange(N**ndim).reshape((N, )*ndim) + + for norm in [True, False]: + if norm and not wav.orthogonal: + # non-orthogonal wavelets to avoid warnings + continue + for trim_approx in [True, False]: + coeffs = pywt.swtn(X, wav, max_level, axes=axes, + trim_approx=trim_approx, norm=norm) + coeffs_copy = deepcopy(coeffs) + Y = pywt.iswtn(coeffs, wav, axes=axes, norm=norm) + assert_allclose(Y, X, rtol=1e-5, atol=1e-5) + + # verify the inverse transform didn't modify any coeffs + for c, c2 in zip(coeffs, coeffs_copy): + for k, v in c.items(): + assert_array_equal(c2[k], v) + + +def test_swtn_iswtn_quick(): + test_swtn_iswtn_integration(wavelets=['db1', ]) + + +def test_iswtn_errors(): + x = np.arange(8**3).reshape(8, 8, 8) + max_level = 2 + axes = (0, 1) + w = pywt.Wavelet('db1') + coeffs = pywt.swtn(x, w, max_level, axes=axes) + + # more axes than dimensions transformed + with pytest.raises(ValueError): + pywt.iswtn(coeffs, w, axes=(0, 1, 2)) + + # duplicate axes not allowed + with pytest.raises(ValueError): + pywt.iswtn(coeffs, w, axes=(0, 0)) + + # mismatched coefficient size + coeffs[0]['da'] = coeffs[0]['da'][:-1, :] + with pytest.raises(RuntimeError): + pywt.iswtn(coeffs, w, axes=axes) + + +def test_swtn_iswtn_unique_shape_per_axis(): + # test case for gh-460 + _shape = (1, 48, 32) # unique shape per axis + wav = 'sym2' + max_level = 3 + rstate = np.random.RandomState(0) + for shape in permutations(_shape): + # transform only along the non-singleton axes + axes = [ax for ax, s in enumerate(shape) if s != 1] + x = rstate.standard_normal(shape) + c = pywt.swtn(x, wav, max_level, axes=axes) + r = pywt.iswtn(c, wav, axes=axes) + assert_allclose(x, r, rtol=1e-10, atol=1e-10) + + +def test_per_axis_wavelets(): + # tests separate wavelet for each axis. + rstate = np.random.RandomState(1234) + data = rstate.randn(16, 16, 16) + level = 3 + + # wavelet can be a string or wavelet object + wavelets = (pywt.Wavelet('haar'), 'sym2', 'db4') + + coefs = pywt.swtn(data, wavelets, level=level) + assert_allclose(pywt.iswtn(coefs, wavelets), data, atol=1e-14) + + # 1-tuple also okay + coefs = pywt.swtn(data, wavelets[:1], level=level) + assert_allclose(pywt.iswtn(coefs, wavelets[:1]), data, atol=1e-14) + + # length of wavelets doesn't match the length of axes + with pytest.raises(ValueError): + pywt.swtn(data, wavelets[:2], level) + + with pytest.raises(ValueError): + pywt.iswtn(coefs, wavelets[:2]) + + with warnings.catch_warnings(): + warnings.simplefilter('ignore', FutureWarning) + # swt2/iswt2 also support per-axis wavelets/modes + data2 = data[..., 0] + coefs2 = pywt.swt2(data2, wavelets[:2], level) + assert_allclose(pywt.iswt2(coefs2, wavelets[:2]), data2, atol=1e-14) + + +def test_error_on_continuous_wavelet(): + # A ValueError is raised if a Continuous wavelet is selected + data = np.ones((16, 16)) + for dec_func, rec_func in zip([pywt.swt, pywt.swt2, pywt.swtn], + [pywt.iswt, pywt.iswt2, pywt.iswtn]): + for cwave in ['morl', pywt.DiscreteContinuousWavelet('morl')]: + with pytest.raises(ValueError): + dec_func(data, wavelet=cwave, level=3) + + c = dec_func(data, 'db1', level=3) + with pytest.raises(ValueError): + rec_func(c, wavelet=cwave) + + +def test_iswt_mixed_dtypes(): + # Mixed precision inputs give double precision output + x_real = np.arange(16).astype(np.float64) + x_complex = x_real + 1j*x_real + wav = 'sym2' + for dtype1, dtype2 in [(np.float64, np.float32), + (np.float32, np.float64), + (np.float16, np.float64), + (np.complex128, np.complex64), + (np.complex64, np.complex128)]: + + if dtype1 in [np.complex64, np.complex128]: + x = x_complex + output_dtype = np.complex128 + else: + x = x_real + output_dtype = np.float64 + + coeffs = pywt.swt(x, wav, 2) + # different precision for the approximation coefficients + coeffs[0] = [coeffs[0][0].astype(dtype1), + coeffs[0][1].astype(dtype2)] + y = pywt.iswt(coeffs, wav) + assert_equal(output_dtype, y.dtype) + assert_allclose(y, x, rtol=1e-3, atol=1e-3) + + +def test_iswt2_mixed_dtypes(): + # Mixed precision inputs give double precision output + rstate = np.random.RandomState(0) + x_real = rstate.randn(8, 8) + x_complex = x_real + 1j*x_real + wav = 'sym2' + for dtype1, dtype2 in [(np.float64, np.float32), + (np.float32, np.float64), + (np.float16, np.float64), + (np.complex128, np.complex64), + (np.complex64, np.complex128)]: + + if dtype1 in [np.complex64, np.complex128]: + x = x_complex + output_dtype = np.complex128 + else: + x = x_real + output_dtype = np.float64 + + coeffs = pywt.swt2(x, wav, 2) + # different precision for the approximation coefficients + coeffs[0] = [coeffs[0][0].astype(dtype1), + tuple([c.astype(dtype2) for c in coeffs[0][1]])] + y = pywt.iswt2(coeffs, wav) + assert_equal(output_dtype, y.dtype) + assert_allclose(y, x, rtol=1e-3, atol=1e-3) + + +def test_iswtn_mixed_dtypes(): + # Mixed precision inputs give double precision output + rstate = np.random.RandomState(0) + x_real = rstate.randn(8, 8, 8) + x_complex = x_real + 1j*x_real + wav = 'sym2' + for dtype1, dtype2 in [(np.float64, np.float32), + (np.float32, np.float64), + (np.float16, np.float64), + (np.complex128, np.complex64), + (np.complex64, np.complex128)]: + + if dtype1 in [np.complex64, np.complex128]: + x = x_complex + output_dtype = np.complex128 + else: + x = x_real + output_dtype = np.float64 + + coeffs = pywt.swtn(x, wav, 2) + # different precision for the approximation coefficients + a = coeffs[0].pop('a' * x.ndim) + a = a.astype(dtype1) + coeffs[0] = {k: c.astype(dtype2) for k, c in coeffs[0].items()} + coeffs[0]['a' * x.ndim] = a + y = pywt.iswtn(coeffs, wav) + assert_equal(output_dtype, y.dtype) + assert_allclose(y, x, rtol=1e-3, atol=1e-3) + + +def test_swt_zero_size_axes(): + # raise on empty input array + with pytest.raises(ValueError): + pywt.swt([], 'db2') + + # >1D case uses a different code path so check there as well + x = np.ones((1, 4))[0:0, :] # 2D with a size zero axis + with pytest.raises(ValueError): + pywt.swtn(x, 'db2', level=1, axes=(0,)) + + +def test_swt_variance_and_energy_preservation(): + """Verify that the 1D SWT partitions variance among the coefficients.""" + # When norm is True and the wavelet is orthogonal, the sum of the + # variances of the coefficients should equal the variance of the signal. + wav = 'db2' + rstate = np.random.RandomState(5) + x = rstate.randn(256) + coeffs = pywt.swt(x, wav, trim_approx=True, norm=True) + variances = [np.var(c) for c in coeffs] + assert_allclose(np.sum(variances), np.var(x)) + + # also verify L2-norm energy preservation property + assert_allclose(np.linalg.norm(x), + np.linalg.norm(np.concatenate(coeffs))) + + # non-orthogonal wavelet with norm=True raises a warning + with pytest.warns(UserWarning): + pywt.swt(x, 'bior2.2', norm=True) + + +def test_swt2_variance_and_energy_preservation(): + """Verify that the 2D SWT partitions variance among the coefficients.""" + # When norm is True and the wavelet is orthogonal, the sum of the + # variances of the coefficients should equal the variance of the signal. + wav = 'db2' + rstate = np.random.RandomState(5) + x = rstate.randn(64, 64) + coeffs = pywt.swt2(x, wav, level=4, trim_approx=True, norm=True) + coeff_list = [coeffs[0].ravel()] + for d in coeffs[1:]: + for v in d: + coeff_list.append(v.ravel()) + variances = [np.var(v) for v in coeff_list] + assert_allclose(np.sum(variances), np.var(x)) + + # also verify L2-norm energy preservation property + assert_allclose(np.linalg.norm(x), + np.linalg.norm(np.concatenate(coeff_list))) + + # non-orthogonal wavelet with norm=True raises a warning + with pytest.warns(UserWarning): + pywt.swt2(x, 'bior2.2', level=4, norm=True) + + +def test_swtn_variance_and_energy_preservation(): + """Verify that the nD SWT partitions variance among the coefficients.""" + # When norm is True and the wavelet is orthogonal, the sum of the + # variances of the coefficients should equal the variance of the signal. + wav = 'db2' + rstate = np.random.RandomState(5) + x = rstate.randn(64, 64) + coeffs = pywt.swtn(x, wav, level=4, trim_approx=True, norm=True) + coeff_list = [coeffs[0].ravel()] + for d in coeffs[1:]: + for k, v in d.items(): + coeff_list.append(v.ravel()) + variances = [np.var(v) for v in coeff_list] + assert_allclose(np.sum(variances), np.var(x)) + + # also verify L2-norm energy preservation property + assert_allclose(np.linalg.norm(x), + np.linalg.norm(np.concatenate(coeff_list))) + + # non-orthogonal wavelet with norm=True raises a warning + with pytest.warns(UserWarning): + pywt.swtn(x, 'bior2.2', level=4, norm=True) + + +def test_swt_ravel_and_unravel(): + # When trim_approx=True, all swt functions can user pywt.ravel_coeffs + for ndim, _swt, _iswt, ravel_type in [ + (1, pywt.swt, pywt.iswt, 'swt'), + (2, pywt.swt2, pywt.iswt2, 'swt2'), + (3, pywt.swtn, pywt.iswtn, 'swtn')]: + x = np.ones((16, ) * ndim) + c = _swt(x, 'sym2', level=3, trim_approx=True) + arr, slices, shapes = pywt.ravel_coeffs(c) + c = pywt.unravel_coeffs(arr, slices, shapes, output_format=ravel_type) + r = _iswt(c, 'sym2') + assert_allclose(x, r) diff --git a/.venv/lib/python3.12/site-packages/pywt/tests/test_thresholding.py b/.venv/lib/python3.12/site-packages/pywt/tests/test_thresholding.py new file mode 100644 index 0000000000000000000000000000000000000000..8e1dc940659847d6f48212278d099cdeaa8b9f0b --- /dev/null +++ b/.venv/lib/python3.12/site-packages/pywt/tests/test_thresholding.py @@ -0,0 +1,167 @@ +import numpy as np +from numpy.testing import assert_, assert_allclose, assert_equal, assert_raises + +import pywt + +float_dtypes = [np.float32, np.float64, np.complex64, np.complex128] +real_dtypes = [np.float32, np.float64] + + +def _sign(x): + # Matlab-like sign function (numpy uses a different convention). + return x / np.abs(x) + + +def _soft(x, thresh): + """soft thresholding supporting complex values. + + Notes + ----- + This version is not robust to zeros in x. + """ + return _sign(x) * np.maximum(np.abs(x) - thresh, 0) + + +def test_threshold(): + data = np.linspace(1, 4, 7) + + # soft + soft_result = [0., 0., 0., 0.5, 1., 1.5, 2.] + assert_allclose(pywt.threshold(data, 2, 'soft'), + np.array(soft_result), rtol=1e-12) + assert_allclose(pywt.threshold(-data, 2, 'soft'), + -np.array(soft_result), rtol=1e-12) + assert_allclose(pywt.threshold([[1, 2]] * 2, 1, 'soft'), + [[0, 1]] * 2, rtol=1e-12) + assert_allclose(pywt.threshold([[1, 2]] * 2, 2, 'soft'), + [[0, 0]] * 2, rtol=1e-12) + + # soft thresholding complex values + assert_allclose(pywt.threshold([[1j, 2j]] * 2, 1, 'soft'), + [[0j, 1j]] * 2, rtol=1e-12) + assert_allclose(pywt.threshold([[1+1j, 2+2j]] * 2, 6, 'soft'), + [[0, 0]] * 2, rtol=1e-12) + complex_data = [[1+2j, 2+2j]]*2 + for thresh in [1, 2]: + assert_allclose(pywt.threshold(complex_data, thresh, 'soft'), + _soft(complex_data, thresh), rtol=1e-12) + + # test soft thresholding with non-default substitute argument + s = 5 + assert_allclose(pywt.threshold([[1j, 2]] * 2, 1.5, 'soft', substitute=s), + [[s, 0.5]] * 2, rtol=1e-12) + + # soft: no divide by zero warnings when input contains zeros + assert_allclose(pywt.threshold(np.zeros(16), 2, 'soft'), + np.zeros(16), rtol=1e-12) + + # hard + hard_result = [0., 0., 2., 2.5, 3., 3.5, 4.] + assert_allclose(pywt.threshold(data, 2, 'hard'), + np.array(hard_result), rtol=1e-12) + assert_allclose(pywt.threshold(-data, 2, 'hard'), + -np.array(hard_result), rtol=1e-12) + assert_allclose(pywt.threshold([[1, 2]] * 2, 1, 'hard'), + [[1, 2]] * 2, rtol=1e-12) + assert_allclose(pywt.threshold([[1, 2]] * 2, 2, 'hard'), + [[0, 2]] * 2, rtol=1e-12) + assert_allclose(pywt.threshold([[1, 2]] * 2, 2, 'hard', substitute=s), + [[s, 2]] * 2, rtol=1e-12) + assert_allclose(pywt.threshold([[1+1j, 2+2j]] * 2, 2, 'hard'), + [[0, 2+2j]] * 2, rtol=1e-12) + + # greater + greater_result = [0., 0., 2., 2.5, 3., 3.5, 4.] + assert_allclose(pywt.threshold(data, 2, 'greater'), + np.array(greater_result), rtol=1e-12) + assert_allclose(pywt.threshold([[1, 2]] * 2, 1, 'greater'), + [[1, 2]] * 2, rtol=1e-12) + assert_allclose(pywt.threshold([[1, 2]] * 2, 2, 'greater'), + [[0, 2]] * 2, rtol=1e-12) + assert_allclose(pywt.threshold([[1, 2]] * 2, 2, 'greater', substitute=s), + [[s, 2]] * 2, rtol=1e-12) + # greater doesn't allow complex-valued inputs + assert_raises(ValueError, pywt.threshold, [1j, 2j], 2, 'greater') + + # less + assert_allclose(pywt.threshold(data, 2, 'less'), + np.array([1., 1.5, 2., 0., 0., 0., 0.]), rtol=1e-12) + assert_allclose(pywt.threshold([[1, 2]] * 2, 1, 'less'), + [[1, 0]] * 2, rtol=1e-12) + assert_allclose(pywt.threshold([[1, 2]] * 2, 1, 'less', substitute=s), + [[1, s]] * 2, rtol=1e-12) + assert_allclose(pywt.threshold([[1, 2]] * 2, 2, 'less'), + [[1, 2]] * 2, rtol=1e-12) + + # less doesn't allow complex-valued inputs + assert_raises(ValueError, pywt.threshold, [1j, 2j], 2, 'less') + + # invalid + assert_raises(ValueError, pywt.threshold, data, 2, 'foo') + + +def test_nonnegative_garotte(): + thresh = 0.3 + data_real = np.linspace(-1, 1, 100) + for dtype in float_dtypes: + if dtype in real_dtypes: + data = np.asarray(data_real, dtype=dtype) + else: + data = np.asarray(data_real + 0.1j, dtype=dtype) + d_hard = pywt.threshold(data, thresh, 'hard') + d_soft = pywt.threshold(data, thresh, 'soft') + d_garotte = pywt.threshold(data, thresh, 'garotte') + + # check dtypes + assert_equal(d_hard.dtype, data.dtype) + assert_equal(d_soft.dtype, data.dtype) + assert_equal(d_garotte.dtype, data.dtype) + + # values < threshold are zero + lt = np.where(np.abs(data) < thresh) + assert_(np.all(d_garotte[lt] == 0)) + + # values > than the threshold are intermediate between soft and hard + gt = np.where(np.abs(data) > thresh) + gt_abs_garotte = np.abs(d_garotte[gt]) + assert_(np.all(gt_abs_garotte < np.abs(d_hard[gt]))) + assert_(np.all(gt_abs_garotte > np.abs(d_soft[gt]))) + + +def test_threshold_firm(): + thresh = 0.2 + thresh2 = 3 * thresh + data_real = np.linspace(-1, 1, 100) + for dtype in float_dtypes: + if dtype in real_dtypes: + data = np.asarray(data_real, dtype=dtype) + else: + data = np.asarray(data_real + 0.1j, dtype=dtype) + if data.real.dtype == np.float32: + rtol = atol = 1e-6 + else: + rtol = atol = 1e-14 + d_hard = pywt.threshold(data, thresh, 'hard') + d_soft = pywt.threshold(data, thresh, 'soft') + d_firm = pywt.threshold_firm(data, thresh, thresh2) + + # check dtypes + assert_equal(d_hard.dtype, data.dtype) + assert_equal(d_soft.dtype, data.dtype) + assert_equal(d_firm.dtype, data.dtype) + + # values < threshold are zero + lt = np.where(np.abs(data) < thresh) + assert_(np.all(d_firm[lt] == 0)) + + # values > than the threshold are equal to hard-thresholding + gt = np.where(np.abs(data) >= thresh2) + assert_allclose(np.abs(d_hard[gt]), np.abs(d_firm[gt]), + rtol=rtol, atol=atol) + + # other values are intermediate between soft and hard thresholding + mt = np.where(np.logical_and(np.abs(data) > thresh, + np.abs(data) < thresh2)) + mt_abs_firm = np.abs(d_firm[mt]) + assert_(np.all(mt_abs_firm < np.abs(d_hard[mt]))) + assert_(np.all(mt_abs_firm > np.abs(d_soft[mt]))) diff --git a/.venv/lib/python3.12/site-packages/pywt/tests/test_wavelet.py b/.venv/lib/python3.12/site-packages/pywt/tests/test_wavelet.py new file mode 100644 index 0000000000000000000000000000000000000000..8981d4a338ebac17e35e00f8cd1a74bda2603086 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/pywt/tests/test_wavelet.py @@ -0,0 +1,278 @@ +#!/usr/bin/env python +import os +import pickle + +import numpy as np +from numpy.testing import assert_, assert_allclose + +import pywt + + +def test_wavelet_properties(): + w = pywt.Wavelet('db3') + + # Name + assert_(w.name == 'db3') + assert_(w.short_family_name == 'db') + assert_(w.family_name, 'Daubechies') + + # String representation + fields = ('Family name', 'Short name', 'Filters length', 'Orthogonal', + 'Biorthogonal', 'Symmetry') + for field in fields: + assert_(field in str(w)) + + # Filter coefficients + dec_lo = [0.03522629188210, -0.08544127388224, -0.13501102001039, + 0.45987750211933, 0.80689150931334, 0.33267055295096] + dec_hi = [-0.33267055295096, 0.80689150931334, -0.45987750211933, + -0.13501102001039, 0.08544127388224, 0.03522629188210] + rec_lo = [0.33267055295096, 0.80689150931334, 0.45987750211933, + -0.13501102001039, -0.08544127388224, 0.03522629188210] + rec_hi = [0.03522629188210, 0.08544127388224, -0.13501102001039, + -0.45987750211933, 0.80689150931334, -0.33267055295096] + assert_allclose(w.dec_lo, dec_lo) + assert_allclose(w.dec_hi, dec_hi) + assert_allclose(w.rec_lo, rec_lo) + assert_allclose(w.rec_hi, rec_hi) + + assert_(len(w.filter_bank) == 4) + + # Orthogonality + assert_(w.orthogonal) + assert_(w.biorthogonal) + + # Symmetry + assert_(w.symmetry) + + # Vanishing moments + assert_(w.vanishing_moments_phi == 0) + assert_(w.vanishing_moments_psi == 3) + + +def test_wavelet_coefficients(): + families = ('db', 'sym', 'coif', 'bior', 'rbio') + wavelets = sum([pywt.wavelist(name) for name in families], []) + for wavelet in wavelets: + if (pywt.Wavelet(wavelet).orthogonal): + check_coefficients_orthogonal(wavelet) + elif(pywt.Wavelet(wavelet).biorthogonal): + check_coefficients_biorthogonal(wavelet) + else: + check_coefficients(wavelet) + + +def check_coefficients_orthogonal(wavelet): + + epsilon = 5e-11 + level = 5 + w = pywt.Wavelet(wavelet) + phi, psi, x = w.wavefun(level=level) + + # Lowpass filter coefficients sum to sqrt2 + res = np.sum(w.dec_lo)-np.sqrt(2) + msg = f'[RMS_REC > EPSILON] for Wavelet: {wavelet}, rms={res:.3g}' + assert_(res < epsilon, msg=msg) + # sum even coef = sum odd coef = 1 / sqrt(2) + res = np.sum(w.dec_lo[::2])-1./np.sqrt(2) + msg = f'[RMS_REC > EPSILON] for Wavelet: {wavelet}, rms={res:.3g}' + assert_(res < epsilon, msg=msg) + + res = np.sum(w.dec_lo[1::2])-1./np.sqrt(2) + msg = f'[RMS_REC > EPSILON] for Wavelet: {wavelet}, rms={res:.3g}' + assert_(res < epsilon, msg=msg) + # Highpass filter coefficients sum to zero + res = np.sum(w.dec_hi) + msg = f'[RMS_REC > EPSILON] for Wavelet: {wavelet}, rms={res:.3g}' + assert_(res < epsilon, msg=msg) + # Scaling function integrates to unity + + res = np.sum(phi) - 2**level + msg = f'[RMS_REC > EPSILON] for Wavelet: {wavelet}, rms={res:.3g}' + assert_(res < epsilon, msg=msg) + # Wavelet function is orthogonal to the scaling function at the same scale + res = np.sum(phi*psi) + msg = f'[RMS_REC > EPSILON] for Wavelet: {wavelet}, rms={res:.3g}' + assert_(res < epsilon, msg=msg) + # The lowpass and highpass filter coefficients are orthogonal + res = np.sum(np.array(w.dec_lo)*np.array(w.dec_hi)) + msg = f'[RMS_REC > EPSILON] for Wavelet: {wavelet}, rms={res:.3g}' + assert_(res < epsilon, msg=msg) + + +def check_coefficients_biorthogonal(wavelet): + + epsilon = 5e-11 + level = 5 + w = pywt.Wavelet(wavelet) + phi_d, psi_d, phi_r, psi_r, x = w.wavefun(level=level) + + # Lowpass filter coefficients sum to sqrt2 + res = np.sum(w.dec_lo)-np.sqrt(2) + msg = f'[RMS_REC > EPSILON] for Wavelet: {wavelet}, rms={res:.3g}' + assert_(res < epsilon, msg=msg) + # sum even coef = sum odd coef = 1 / sqrt(2) + res = np.sum(w.dec_lo[::2])-1./np.sqrt(2) + msg = f'[RMS_REC > EPSILON] for Wavelet: {wavelet}, rms={res:.3g}' + assert_(res < epsilon, msg=msg) + res = np.sum(w.dec_lo[1::2])-1./np.sqrt(2) + msg = f'[RMS_REC > EPSILON] for Wavelet: {wavelet}, rms={res:.3g}' + assert_(res < epsilon, msg=msg) + # Highpass filter coefficients sum to zero + res = np.sum(w.dec_hi) + msg = f'[RMS_REC > EPSILON] for Wavelet: {wavelet}, rms={res:.3g}' + assert_(res < epsilon, msg=msg) + # Scaling function integrates to unity + res = np.sum(phi_d) - 2**level + msg = f'[RMS_REC > EPSILON] for Wavelet: {wavelet}, rms={res:.3g}' + assert_(res < epsilon, msg=msg) + res = np.sum(phi_r) - 2**level + msg = f'[RMS_REC > EPSILON] for Wavelet: {wavelet}, rms={res:.3g}' + assert_(res < epsilon, msg=msg) + + +def check_coefficients(wavelet): + epsilon = 5e-11 + level = 10 + w = pywt.Wavelet(wavelet) + # Lowpass filter coefficients sum to sqrt2 + res = np.sum(w.dec_lo)-np.sqrt(2) + msg = f'[RMS_REC > EPSILON] for Wavelet: {wavelet}, rms={res:.3g}' + assert_(res < epsilon, msg=msg) + # sum even coef = sum odd coef = 1 / sqrt(2) + res = np.sum(w.dec_lo[::2])-1./np.sqrt(2) + msg = f'[RMS_REC > EPSILON] for Wavelet: {wavelet}, rms={res:.3g}' + assert_(res < epsilon, msg=msg) + + res = np.sum(w.dec_lo[1::2])-1./np.sqrt(2) + msg = f'[RMS_REC > EPSILON] for Wavelet: {wavelet}, rms={res:.3g}' + assert_(res < epsilon, msg=msg) + # Highpass filter coefficients sum to zero + res = np.sum(w.dec_hi) + msg = f'[RMS_REC > EPSILON] for Wavelet: {wavelet}, rms={res:.3g}' + assert_(res < epsilon, msg=msg) + + +class _CustomHaarFilterBank: + @property + def filter_bank(self): + val = np.sqrt(2) / 2 + return ([val]*2, [-val, val], [val]*2, [val, -val]) + + +def test_custom_wavelet(): + haar_custom1 = pywt.Wavelet('Custom Haar Wavelet', + filter_bank=_CustomHaarFilterBank()) + haar_custom1.orthogonal = True + haar_custom1.biorthogonal = True + + val = np.sqrt(2) / 2 + filter_bank = ([val]*2, [-val, val], [val]*2, [val, -val]) + haar_custom2 = pywt.Wavelet('Custom Haar Wavelet', + filter_bank=filter_bank) + + # check expected default wavelet properties + assert_(not haar_custom2.orthogonal) + assert_(not haar_custom2.biorthogonal) + assert_(haar_custom2.symmetry == 'unknown') + assert_(haar_custom2.family_name == '') + assert_(haar_custom2.short_family_name == '') + assert_(haar_custom2.vanishing_moments_phi == 0) + assert_(haar_custom2.vanishing_moments_psi == 0) + + # Some properties can be set by the user + haar_custom2.orthogonal = True + haar_custom2.biorthogonal = True + + +def test_wavefun_sym3(): + w = pywt.Wavelet('sym3') + # sym3 is an orthogonal wavelet, so 3 outputs from wavefun + phi, psi, x = w.wavefun(level=3) + assert_(phi.size == 41) + assert_(psi.size == 41) + assert_(x.size == 41) + + assert_allclose(x, np.linspace(0, 5, num=x.size)) + phi_expect = np.array([0.00000000e+00, 1.04132926e-01, 2.52574126e-01, + 3.96525521e-01, 5.70356539e-01, 7.18934305e-01, + 8.70293448e-01, 1.05363620e+00, 1.24921722e+00, + 1.15296888e+00, 9.41669683e-01, 7.55875887e-01, + 4.96118565e-01, 3.28293151e-01, 1.67624969e-01, + -7.33690312e-02, -3.35452855e-01, -3.31221131e-01, + -2.32061503e-01, -1.66854239e-01, -4.34091324e-02, + -2.86152390e-02, -3.63563035e-02, 2.06034491e-02, + 8.30280254e-02, 7.17779073e-02, 3.85914311e-02, + 1.47527100e-02, -2.31896077e-02, -1.86122172e-02, + -1.56211329e-03, -8.70615088e-04, 3.20760857e-03, + 2.34142153e-03, -7.73737194e-04, -2.99879354e-04, + 1.23636238e-04, 0.00000000e+00, 0.00000000e+00, + 0.00000000e+00, 0.00000000e+00]) + + psi_expect = np.array([0.00000000e+00, 1.10265752e-02, 2.67449277e-02, + 4.19878574e-02, 6.03947231e-02, 7.61275365e-02, + 9.21548684e-02, 1.11568926e-01, 1.32278887e-01, + 6.45829680e-02, -3.97635130e-02, -1.38929884e-01, + -2.62428322e-01, -3.62246804e-01, -4.62843343e-01, + -5.89607507e-01, -7.25363076e-01, -3.36865858e-01, + 2.67715108e-01, 8.40176767e-01, 1.55574430e+00, + 1.18688954e+00, 4.20276324e-01, -1.51697311e-01, + -9.42076108e-01, -7.93172332e-01, -3.26343710e-01, + -1.24552779e-01, 2.12909254e-01, 1.75770320e-01, + 1.47523075e-02, 8.22192707e-03, -3.02920592e-02, + -2.21119497e-02, 7.30703025e-03, 2.83200488e-03, + -1.16759765e-03, 0.00000000e+00, 0.00000000e+00, + 0.00000000e+00, 0.00000000e+00]) + + assert_allclose(phi, phi_expect) + assert_allclose(psi, psi_expect) + + +def test_wavefun_bior13(): + w = pywt.Wavelet('bior1.3') + # bior1.3 is not an orthogonal wavelet, so 5 outputs from wavefun + phi_d, psi_d, phi_r, psi_r, x = w.wavefun(level=3) + for arr in [phi_d, psi_d, phi_r, psi_r]: + assert_(arr.size == 40) + + phi_d_expect = np.array([0., -0.00195313, 0.00195313, 0.01757813, + 0.01367188, 0.00390625, -0.03515625, -0.12890625, + -0.15234375, -0.125, -0.09375, -0.0625, 0.03125, + 0.15234375, 0.37890625, 0.78515625, 0.99609375, + 1.08203125, 1.13671875, 1.13671875, 1.08203125, + 0.99609375, 0.78515625, 0.37890625, 0.15234375, + 0.03125, -0.0625, -0.09375, -0.125, -0.15234375, + -0.12890625, -0.03515625, 0.00390625, 0.01367188, + 0.01757813, 0.00195313, -0.00195313, 0., 0., 0.]) + phi_r_expect = np.zeros(x.size, dtype=np.float64) + phi_r_expect[15:23] = 1 + + psi_d_expect = np.array([0, 0, 0, 0, 0, 0, 0, 0, 0, + 0.015625, -0.015625, -0.140625, -0.109375, + -0.03125, 0.28125, 1.03125, 1.21875, 1.125, 0.625, + -0.625, -1.125, -1.21875, -1.03125, -0.28125, + 0.03125, 0.109375, 0.140625, 0.015625, -0.015625, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]) + + psi_r_expect = np.zeros(x.size, dtype=np.float64) + psi_r_expect[7:15] = -0.125 + psi_r_expect[15:19] = 1 + psi_r_expect[19:23] = -1 + psi_r_expect[23:31] = 0.125 + + assert_allclose(x, np.linspace(0, 5, x.size, endpoint=False)) + assert_allclose(phi_d, phi_d_expect, rtol=1e-5, atol=1e-9) + assert_allclose(phi_r, phi_r_expect, rtol=1e-10, atol=1e-12) + assert_allclose(psi_d, psi_d_expect, rtol=1e-10, atol=1e-12) + assert_allclose(psi_r, psi_r_expect, rtol=1e-10, atol=1e-12) + + +def test_wavelet_pickle(tmpdir): + wavelet = pywt.Wavelet('sym4') + filename = os.path.join(tmpdir, 'wav.pickle') + with open(filename, 'wb') as f: + pickle.dump(wavelet, f) + with open(filename, 'rb') as f: + wavelet2 = pickle.load(f) + assert isinstance(wavelet2, pywt.Wavelet) + assert wavelet2.name == wavelet.name diff --git a/.venv/lib/python3.12/site-packages/pywt/tests/test_wp.py b/.venv/lib/python3.12/site-packages/pywt/tests/test_wp.py new file mode 100644 index 0000000000000000000000000000000000000000..9bcd1230293609ef5a36d94db4f47b0e8d005fe9 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/pywt/tests/test_wp.py @@ -0,0 +1,243 @@ +#!/usr/bin/env python + +import os +import pickle + +import numpy as np +from numpy.testing import assert_, assert_allclose, assert_equal, assert_raises + +import pywt + + +def test_wavelet_packet_structure(): + x = [1, 2, 3, 4, 5, 6, 7, 8] + wp = pywt.WaveletPacket(data=x, wavelet='db1', mode='symmetric') + + assert_(wp.data == [1, 2, 3, 4, 5, 6, 7, 8]) + assert_(wp.path == '') + assert_(wp.level == 0) + assert_(wp['ad'].maxlevel == 3) + + +def test_traversing_wp_tree(): + x = [1, 2, 3, 4, 5, 6, 7, 8] + wp = pywt.WaveletPacket(data=x, wavelet='db1', mode='symmetric') + + assert_(wp.maxlevel == 3) + + # First level + assert_allclose(wp['a'].data, np.array([2.12132034356, 4.949747468306, + 7.778174593052, 10.606601717798]), + rtol=1e-12) + + # Second level + assert_allclose(wp['aa'].data, np.array([5., 13.]), rtol=1e-12) + + # Third level + assert_allclose(wp['aaa'].data, np.array([12.727922061358]), rtol=1e-12) + + +def test_acess_path(): + x = [1, 2, 3, 4, 5, 6, 7, 8] + wp = pywt.WaveletPacket(data=x, wavelet='db1', mode='symmetric') + + assert_(wp['a'].path == 'a') + assert_(wp['aa'].path == 'aa') + assert_(wp['aaa'].path == 'aaa') + + # Maximum level reached: + assert_raises(IndexError, lambda: wp['aaaa'].path) + + # Wrong path + assert_raises(ValueError, lambda: wp['ac'].path) + + +def test_access_node_attributes(): + x = [1, 2, 3, 4, 5, 6, 7, 8] + wp = pywt.WaveletPacket(data=x, wavelet='db1', mode='symmetric') + + assert_allclose(wp['ad'].data, np.array([-2., -2.]), rtol=1e-12) + assert_(wp['ad'].path == 'ad') + assert_(wp['ad'].node_name == 'd') + assert_(wp['ad'].parent.path == 'a') + assert_(wp['ad'].level == 2) + assert_(wp['ad'].maxlevel == 3) + assert_(wp['ad'].mode == 'symmetric') + + # tuple-based access is also supported + node = wp[('a', 'd')] + # can access a node's path as either a single string or in tuple form + assert_(node.path == 'ad') + assert_(node.path_tuple == ('a', 'd')) + + +def test_collecting_nodes(): + x = [1, 2, 3, 4, 5, 6, 7, 8] + wp = pywt.WaveletPacket(data=x, wavelet='db1', mode='symmetric') + + # All nodes in natural order + assert_([node.path for node in wp.get_level(3, 'natural')] == + ['aaa', 'aad', 'ada', 'add', 'daa', 'dad', 'dda', 'ddd']) + + # and in frequency order. + assert_([node.path for node in wp.get_level(3, 'freq')] == + ['aaa', 'aad', 'add', 'ada', 'dda', 'ddd', 'dad', 'daa']) + + assert_raises(ValueError, wp.get_level, 3, 'invalid_order') + + +def test_reconstructing_data(): + x = [1, 2, 3, 4, 5, 6, 7, 8] + wp = pywt.WaveletPacket(data=x, wavelet='db1', mode='symmetric') + + # Create another Wavelet Packet and feed it with some data. + new_wp = pywt.WaveletPacket(data=None, wavelet='db1', mode='symmetric') + new_wp['aa'] = wp['aa'].data + new_wp['ad'] = [-2., -2.] + + # For convenience, :attr:`Node.data` gets automatically extracted + # from the :class:`Node` object: + new_wp['d'] = wp['d'] + + # Reconstruct data from aa, ad, and d packets. + assert_allclose(new_wp.reconstruct(update=False), x, rtol=1e-12) + + # The node's :attr:`~Node.data` will not be updated + assert_(new_wp.data is None) + + # When `update` is True: + assert_allclose(new_wp.reconstruct(update=True), x, rtol=1e-12) + assert_allclose(new_wp.data, np.arange(1, 9), rtol=1e-12) + + assert_([n.path for n in new_wp.get_leaf_nodes(False)] == + ['aa', 'ad', 'd']) + assert_([n.path for n in new_wp.get_leaf_nodes(True)] == + ['aaa', 'aad', 'ada', 'add', 'daa', 'dad', 'dda', 'ddd']) + + +def test_removing_nodes(): + x = [1, 2, 3, 4, 5, 6, 7, 8] + wp = pywt.WaveletPacket(data=x, wavelet='db1', mode='symmetric') + wp.get_level(2) + + dataleafs = [n.data for n in wp.get_leaf_nodes(False)] + expected = np.array([[5., 13.], [-2, -2], [-1, -1], [0, 0]]) + + for i in range(4): + assert_allclose(dataleafs[i], expected[i, :], atol=1e-12) + + node = wp['ad'] + del(wp['ad']) + dataleafs = [n.data for n in wp.get_leaf_nodes(False)] + expected = np.array([[5., 13.], [-1, -1], [0, 0]]) + + for i in range(3): + assert_allclose(dataleafs[i], expected[i, :], atol=1e-12) + + wp.reconstruct() + # The reconstruction is: + assert_allclose(wp.reconstruct(), + np.array([2., 3., 2., 3., 6., 7., 6., 7.]), rtol=1e-12) + + # Restore the data + wp['ad'].data = node.data + + dataleafs = [n.data for n in wp.get_leaf_nodes(False)] + expected = np.array([[5., 13.], [-2, -2], [-1, -1], [0, 0]]) + + for i in range(4): + assert_allclose(dataleafs[i], expected[i, :], atol=1e-12) + + assert_allclose(wp.reconstruct(), np.arange(1, 9), rtol=1e-12) + + +def test_wavelet_packet_dtypes(): + rstate = np.random.RandomState(0) + N = 32 + for dtype in [np.float32, np.float64, np.complex64, np.complex128]: + x = rstate.randn(N).astype(dtype) + if np.iscomplexobj(x): + x = x + 1j*np.random.randn(N).astype(x.real.dtype) + wp = pywt.WaveletPacket(data=x, wavelet='db1', mode='symmetric') + # no unnecessary copy made + assert_(wp.data is x) + + # assigning to a node should not change supported dtypes + wp['d'] = wp['d'].data + assert_equal(wp['d'].data.dtype, x.dtype) + + # full decomposition + wp.get_level(wp.maxlevel) + + # reconstruction from coefficients should preserve dtype + r = wp.reconstruct(False) + assert_equal(r.dtype, x.dtype) + assert_allclose(r, x, atol=1e-5, rtol=1e-5) + + # first element of the tuple is the input dtype + # second element of the tuple is the transform dtype + dtype_pairs = [(np.uint8, np.float64), + (np.intp, np.float64), ] + if hasattr(np, "complex256"): + dtype_pairs += [(np.complex256, np.complex128), ] + if hasattr(np, "half"): + dtype_pairs += [(np.half, np.float32), ] + for (dtype, transform_dtype) in dtype_pairs: + x = np.arange(N, dtype=dtype) + wp = pywt.WaveletPacket(x, wavelet='db1', mode='symmetric') + + # no unnecessary copy made of top-level data + assert_(wp.data is x) + + # full decomposition + wp.get_level(wp.maxlevel) + + # reconstructed data will have modified dtype + r = wp.reconstruct(False) + assert_equal(r.dtype, transform_dtype) + assert_allclose(r, x.astype(transform_dtype), atol=1e-5, rtol=1e-5) + + +def test_db3_roundtrip(): + original = np.arange(512) + wp = pywt.WaveletPacket(data=original, wavelet='db3', mode='smooth', + maxlevel=3) + r = wp.reconstruct() + assert_allclose(original, r, atol=1e-12, rtol=1e-12) + + +def test_wavelet_packet_axis(): + rstate = np.random.RandomState(0) + shape = (32, 16) + x = rstate.standard_normal(shape) + for axis in [0, 1, -1]: + wp = pywt.WaveletPacket(data=x, wavelet='db1', mode='symmetric', + axis=axis) + + # partial decomposition + nodes = wp.get_level(2) + # size along the transformed axis has changed + for ax2 in range(x.ndim): + if ax2 == (axis % x.ndim): + nodes[0].data.shape[ax2] < x.shape[ax2] + else: + nodes[0].data.shape[ax2] == x.shape[ax2] + + # recontsruction from coefficients should preserve dtype + r = wp.reconstruct(False) + assert_equal(r.dtype, x.dtype) + assert_allclose(r, x, atol=1e-12, rtol=1e-12) + + # ValueError if axis is out of range + assert_raises(ValueError, pywt.WaveletPacket, data=x, wavelet='db1', + axis=x.ndim) + + +def test_wavelet_packet_pickle(tmpdir): + packet = pywt.WaveletPacket(np.arange(16), 'sym4') + filename = os.path.join(tmpdir, 'wp.pickle') + with open(filename, 'wb') as f: + pickle.dump(packet, f) + with open(filename, 'rb') as f: + packet2 = pickle.load(f) + assert isinstance(packet2, pywt.WaveletPacket) diff --git a/.venv/lib/python3.12/site-packages/pywt/tests/test_wp2d.py b/.venv/lib/python3.12/site-packages/pywt/tests/test_wp2d.py new file mode 100644 index 0000000000000000000000000000000000000000..b6f0b60d93d0cfc61ed92c2e074cc6d4422f063d --- /dev/null +++ b/.venv/lib/python3.12/site-packages/pywt/tests/test_wp2d.py @@ -0,0 +1,244 @@ +#!/usr/bin/env python + +import os +import pickle + +import numpy as np +from numpy.testing import assert_, assert_allclose, assert_equal, assert_raises + +import pywt + + +def test_traversing_tree_2d(): + x = np.array([[1, 2, 3, 4, 5, 6, 7, 8]] * 8, dtype=np.float64) + wp = pywt.WaveletPacket2D(data=x, wavelet='db1', mode='symmetric') + + assert_(np.all(wp.data == x)) + assert_(wp.path == '') + assert_(wp.level == 0) + assert_(wp.maxlevel == 3) + + assert_allclose(wp['a'].data, np.array([[3., 7., 11., 15.]] * 4), + rtol=1e-12) + assert_allclose(wp['h'].data, np.zeros((4, 4)), rtol=1e-12, atol=1e-14) + assert_allclose(wp['v'].data, -np.ones((4, 4)), rtol=1e-12, atol=1e-14) + assert_allclose(wp['d'].data, np.zeros((4, 4)), rtol=1e-12, atol=1e-14) + + assert_allclose(wp['aa'].data, np.array([[10., 26.]] * 2), rtol=1e-12) + + assert_(wp['a']['a'].data is wp['aa'].data) + assert_allclose(wp['aaa'].data, np.array([[36.]]), rtol=1e-12) + + assert_raises(IndexError, lambda: wp['aaaa']) + assert_raises(ValueError, lambda: wp['f']) + + +def test_accessing_node_attributes_2d(): + x = np.array([[1, 2, 3, 4, 5, 6, 7, 8]] * 8, dtype=np.float64) + wp = pywt.WaveletPacket2D(data=x, wavelet='db1', mode='symmetric') + + assert_allclose(wp['av'].data, np.zeros((2, 2)) - 4, rtol=1e-12) + assert_(wp['av'].path == 'av') + assert_(wp['av'].node_name == 'v') + assert_(wp['av'].parent.path == 'a') + + assert_allclose(wp['av'].parent.data, np.array([[3., 7., 11., 15.]] * 4), + rtol=1e-12) + # can also index via a tuple instead of concatenated strings + assert_(wp['av'].level == 2) + assert_(wp['av'].maxlevel == 3) + assert_(wp['av'].mode == 'symmetric') + + # tuple-based access is also supported + node = wp[('a', 'v')] + # can access a node's path as either a single string or in tuple form + assert_(node.path == 'av') + assert_(node.path_tuple == ('a', 'v')) + + +def test_collecting_nodes_2d(): + x = np.array([[1, 2, 3, 4, 5, 6, 7, 8]] * 8, dtype=np.float64) + wp = pywt.WaveletPacket2D(data=x, wavelet='db1', mode='symmetric') + + assert_(len(wp.get_level(0)) == 1) + assert_(wp.get_level(0)[0].path == '') + + # First level + assert_(len(wp.get_level(1)) == 4) + assert_([node.path for node in wp.get_level(1)] == ['a', 'h', 'v', 'd']) + + # Second level + assert_(len(wp.get_level(2)) == 16) + paths = [node.path for node in wp.get_level(2)] + expected_paths = ['aa', 'ah', 'av', 'ad', 'ha', 'hh', 'hv', 'hd', 'va', + 'vh', 'vv', 'vd', 'da', 'dh', 'dv', 'dd'] + assert_(paths == expected_paths) + + # Third level. + assert_(len(wp.get_level(3)) == 64) + paths = [node.path for node in wp.get_level(3)] + expected_paths = ['aaa', 'aah', 'aav', 'aad', 'aha', 'ahh', 'ahv', 'ahd', + 'ava', 'avh', 'avv', 'avd', 'ada', 'adh', 'adv', 'add', + 'haa', 'hah', 'hav', 'had', 'hha', 'hhh', 'hhv', 'hhd', + 'hva', 'hvh', 'hvv', 'hvd', 'hda', 'hdh', 'hdv', 'hdd', + 'vaa', 'vah', 'vav', 'vad', 'vha', 'vhh', 'vhv', 'vhd', + 'vva', 'vvh', 'vvv', 'vvd', 'vda', 'vdh', 'vdv', 'vdd', + 'daa', 'dah', 'dav', 'dad', 'dha', 'dhh', 'dhv', 'dhd', + 'dva', 'dvh', 'dvv', 'dvd', 'dda', 'ddh', 'ddv', 'ddd'] + + assert_(paths == expected_paths) + + # test 2D frequency ordering at the first level + fnodes = wp.get_level(1, order='freq') + assert_(fnodes[0][0].path == 'a') + assert_(fnodes[0][1].path == 'v') + assert_(fnodes[1][0].path == 'h') + assert_(fnodes[1][1].path == 'd') + + # test 2D frequency ordering at the second level + fnodes = wp.get_level(2, order='freq') + assert_([n.path for n in fnodes[0]] == ['aa', 'av', 'vv', 'va']) + assert_([n.path for n in fnodes[1]] == ['ah', 'ad', 'vd', 'vh']) + assert_([n.path for n in fnodes[2]] == ['hh', 'hd', 'dd', 'dh']) + assert_([n.path for n in fnodes[3]] == ['ha', 'hv', 'dv', 'da']) + + # invalid node collection order + assert_raises(ValueError, wp.get_level, 2, 'invalid_order') + + +def test_data_reconstruction_2d(): + x = np.array([[1, 2, 3, 4, 5, 6, 7, 8]] * 8, dtype=np.float64) + wp = pywt.WaveletPacket2D(data=x, wavelet='db1', mode='symmetric') + + new_wp = pywt.WaveletPacket2D(data=None, wavelet='db1', mode='symmetric') + new_wp['vh'] = wp['vh'].data + new_wp['vv'] = wp['vh'].data + new_wp['vd'] = np.zeros((2, 2), dtype=np.float64) + new_wp['a'] = [[3.0, 7.0, 11.0, 15.0]] * 4 + new_wp['d'] = np.zeros((4, 4), dtype=np.float64) + new_wp['h'] = wp['h'] # all zeros + + assert_allclose(new_wp.reconstruct(update=False), + np.array([[1.5, 1.5, 3.5, 3.5, 5.5, 5.5, 7.5, 7.5]] * 8), + rtol=1e-12) + assert_allclose(wp['va'].data, np.zeros((2, 2)) - 2, rtol=1e-12) + + new_wp['va'] = wp['va'].data + assert_allclose(new_wp.reconstruct(update=False), x, rtol=1e-12) + + +def test_data_reconstruction_delete_nodes_2d(): + x = np.array([[1, 2, 3, 4, 5, 6, 7, 8]] * 8, dtype=np.float64) + wp = pywt.WaveletPacket2D(data=x, wavelet='db1', mode='symmetric') + + new_wp = pywt.WaveletPacket2D(data=None, wavelet='db1', mode='symmetric') + new_wp['vh'] = wp['vh'].data + new_wp['vv'] = wp['vh'].data + new_wp['vd'] = np.zeros((2, 2), dtype=np.float64) + new_wp['a'] = [[3.0, 7.0, 11.0, 15.0]] * 4 + new_wp['d'] = np.zeros((4, 4), dtype=np.float64) + new_wp['h'] = wp['h'] # all zeros + + assert_allclose(new_wp.reconstruct(update=False), + np.array([[1.5, 1.5, 3.5, 3.5, 5.5, 5.5, 7.5, 7.5]] * 8), + rtol=1e-12) + + new_wp['va'] = wp['va'].data + assert_allclose(new_wp.reconstruct(update=False), x, rtol=1e-12) + + del(new_wp['va']) + # TypeError on accessing deleted node + assert_raises(TypeError, lambda: new_wp['va']) + new_wp['va'] = wp['va'].data + assert_(new_wp.data is None) + + assert_allclose(new_wp.reconstruct(update=True), x, rtol=1e-12) + assert_allclose(new_wp.data, x, rtol=1e-12) + + # TODO: decompose=True + + +def test_lazy_evaluation_2D(): + # Note: internal implementation detail not to be relied on. Testing for + # now for backwards compatibility, but this test may be broken in needed. + x = np.array([[1, 2, 3, 4, 5, 6, 7, 8]] * 8) + wp = pywt.WaveletPacket2D(data=x, wavelet='db1', mode='symmetric') + + assert_(wp.a is None) + assert_allclose(wp['a'].data, np.array([[3., 7., 11., 15.]] * 4), + rtol=1e-12) + assert_allclose(wp.a.data, np.array([[3., 7., 11., 15.]] * 4), rtol=1e-12) + assert_allclose(wp.d.data, np.zeros((4, 4)), rtol=1e-12, atol=1e-12) + + +def test_wavelet_packet_dtypes(): + shape = (16, 16) + for dtype in [np.float32, np.float64, np.complex64, np.complex128]: + x = np.random.randn(*shape).astype(dtype) + if np.iscomplexobj(x): + x = x + 1j*np.random.randn(*shape).astype(x.real.dtype) + wp = pywt.WaveletPacket2D(data=x, wavelet='db1', mode='symmetric') + # no unnecessary copy made + assert_(wp.data is x) + + # assigning to a node should not change supported dtypes + wp['d'] = wp['d'].data + assert_equal(wp['d'].data.dtype, x.dtype) + + # full decomposition + wp.get_level(wp.maxlevel) + + # reconstruction from coefficients should preserve dtype + r = wp.reconstruct(False) + assert_equal(r.dtype, x.dtype) + assert_allclose(r, x, atol=1e-5, rtol=1e-5) + + +def test_2d_roundtrip(): + # test case corresponding to PyWavelets issue 447 + original = pywt.data.camera() + wp = pywt.WaveletPacket2D(data=original, wavelet='db3', mode='smooth', + maxlevel=3) + r = wp.reconstruct() + assert_allclose(original, r, atol=1e-12, rtol=1e-12) + + +def test_wavelet_packet_axes(): + rstate = np.random.RandomState(0) + shape = (32, 16) + x = rstate.standard_normal(shape) + for axes in [(0, 1), (1, 0), (-2, 1)]: + wp = pywt.WaveletPacket2D(data=x, wavelet='db1', mode='symmetric', + axes=axes) + + # partial decomposition + nodes = wp.get_level(2) + # size along the transformed axes has changed + for ax2 in range(x.ndim): + if ax2 in tuple(np.asarray(axes) % x.ndim): + nodes[0].data.shape[ax2] < x.shape[ax2] + else: + nodes[0].data.shape[ax2] == x.shape[ax2] + + # recontsruction from coefficients should preserve dtype + r = wp.reconstruct(False) + assert_equal(r.dtype, x.dtype) + assert_allclose(r, x, atol=1e-12, rtol=1e-12) + + # must have two non-duplicate axes + assert_raises(ValueError, pywt.WaveletPacket2D, data=x, wavelet='db1', + axes=(0, 0)) + assert_raises(ValueError, pywt.WaveletPacket2D, data=x, wavelet='db1', + axes=(0, )) + assert_raises(ValueError, pywt.WaveletPacket2D, data=x, wavelet='db1', + axes=(0, 1, 2)) + + +def test_wavelet_packet2d_pickle(tmpdir): + packet = pywt.WaveletPacket2D(np.arange(256).reshape(16, 16), 'sym4') + filename = os.path.join(tmpdir, 'wp2d.pickle') + with open(filename, 'wb') as f: + pickle.dump(packet, f) + with open(filename, 'rb') as f: + packet2 = pickle.load(f) + assert isinstance(packet2, pywt.WaveletPacket2D) diff --git a/.venv/lib/python3.12/site-packages/pywt/tests/test_wpnd.py b/.venv/lib/python3.12/site-packages/pywt/tests/test_wpnd.py new file mode 100644 index 0000000000000000000000000000000000000000..d04d034165ce0d6bd911d299b5112b1d9bdc305b --- /dev/null +++ b/.venv/lib/python3.12/site-packages/pywt/tests/test_wpnd.py @@ -0,0 +1,223 @@ +#!/usr/bin/env python + + +import operator +from functools import reduce +from itertools import product + +import numpy as np +from numpy.testing import assert_, assert_allclose, assert_equal, assert_raises + +import pywt + + +def test_traversing_tree_nd(): + x = np.array([[1, 2, 3, 4, 5, 6, 7, 8]] * 8, dtype=np.float64) + wp = pywt.WaveletPacketND(data=x, wavelet='db1', mode='symmetric') + + assert_(np.all(wp.data == x)) + assert_(wp.path == '') + assert_(wp.level == 0) + assert_(wp.maxlevel == 3) + + assert_allclose(wp['aa'].data, np.array([[3., 7., 11., 15.]] * 4), + rtol=1e-12) + assert_allclose(wp['da'].data, np.zeros((4, 4)), rtol=1e-12, atol=1e-14) + assert_allclose(wp['ad'].data, -np.ones((4, 4)), rtol=1e-12, atol=1e-14) + assert_allclose(wp['dd'].data, np.zeros((4, 4)), rtol=1e-12, atol=1e-14) + + assert_allclose(wp['aa'*2].data, np.array([[10., 26.]] * 2), rtol=1e-12) + # __getitem__ using a tuple access instead + assert_allclose(wp[('aa', 'aa')].data, np.array([[10., 26.]] * 2), + rtol=1e-12) + + assert_(wp['aa']['aa'].data is wp['aa'*2].data) + assert_allclose(wp['aa'*3].data, np.array([[36.]]), rtol=1e-12) + + assert_raises(IndexError, lambda: wp['aa'*(wp.maxlevel+1)]) + assert_raises(ValueError, lambda: wp['f']) + + # getitem input must be a string or tuple of strings + assert_raises(TypeError, wp.__getitem__, (5, 3)) + assert_raises(TypeError, wp.__getitem__, 5) + + +def test_accessing_node_attributes_nd(): + x = np.array([[1, 2, 3, 4, 5, 6, 7, 8]] * 8, dtype=np.float64) + wp = pywt.WaveletPacketND(data=x, wavelet='db1', mode='symmetric') + + assert_allclose(wp['aa'+'ad'].data, np.zeros((2, 2)) - 4, rtol=1e-12) + assert_(wp['aa'+'ad'].path == 'aa'+'ad') + assert_(wp['aa'+'ad'].node_name == 'ad') + assert_(wp['aa'+'ad'].parent.path == 'aa') + + assert_allclose(wp['aa'+'ad'].parent.data, + np.array([[3., 7., 11., 15.]] * 4), rtol=1e-12) + # can also index via a tuple instead of concatenated strings + assert_(wp[('aa', 'ad')].level == 2) + assert_(wp[('aa', 'ad')].maxlevel == 3) + assert_(wp[('aa', 'ad')].mode == 'symmetric') + + # can access a node's path as either a single string or in tuple form + node = wp[('ad', 'dd')] + assert_(node.path == 'addd') + assert_(node.path_tuple == ('ad', 'dd')) + + +def test_collecting_nodes_nd(): + x = np.array([[1, 2, 3, 4, 5, 6, 7, 8]] * 8, dtype=np.float64) + wp = pywt.WaveletPacketND(data=x, wavelet='db1', mode='symmetric') + + assert_(len(wp.get_level(0)) == 1) + assert_(wp.get_level(0)[0].path == '') + + # First level + assert_(len(wp.get_level(1)) == 4) + assert_( + [node.path for node in wp.get_level(1)] == ['aa', 'ad', 'da', 'dd']) + + # Second and third levels + for lev in [2, 3]: + assert_(len(wp.get_level(lev)) == (2**x.ndim)**lev) + paths = [node.path for node in wp.get_level(lev)] + expected_paths = [ + reduce(operator.add, p) for + p in sorted(product(['aa', 'ad', 'da', 'dd'], repeat=lev))] + assert_(paths == expected_paths) + + +def test_data_reconstruction_delete_nodes_nd(): + x = np.array([[1, 2, 3, 4, 5, 6, 7, 8]] * 8, dtype=np.float64) + wp = pywt.WaveletPacketND(data=x, wavelet='db1', mode='symmetric') + + # The user must supply either data or axes + assert_raises(ValueError, pywt.WaveletPacketND, data=None, wavelet='db1', + axes=None) + + new_wp = pywt.WaveletPacketND(data=None, wavelet='db1', mode='symmetric', + axes=range(x.ndim)) + + new_wp['ad'+'da'] = wp['ad'+'da'].data + new_wp['ad'*2] = wp['ad'+'da'].data + new_wp['ad'+'dd'] = np.zeros((2, 2), dtype=np.float64) + new_wp['aa'] = [[3.0, 7.0, 11.0, 15.0]] * 4 + new_wp['dd'] = np.zeros((4, 4), dtype=np.float64) + new_wp['da'] = wp['da'] # all zeros + + assert_allclose(new_wp.reconstruct(update=False), + np.array([[1.5, 1.5, 3.5, 3.5, 5.5, 5.5, 7.5, 7.5]] * 8), + rtol=1e-12) + + new_wp['ad'+'aa'] = wp['ad'+'aa'].data + assert_allclose(new_wp.reconstruct(update=False), x, rtol=1e-12) + + del(new_wp['ad'+'aa']) + # TypeError on accessing deleted node + assert_raises(TypeError, lambda: new_wp['ad'+'aa']) + + new_wp['ad'+'aa'] = wp['ad'+'aa'].data + assert_(new_wp.data is None) + + assert_allclose(new_wp.reconstruct(update=True), x, rtol=1e-12) + assert_allclose(new_wp.data, x, rtol=1e-12) + + # TODO: decompose=True + + +def test_wavelet_packet_dtypes(): + shape = (16, 8, 8) + for dtype in [np.float32, np.float64, np.complex64, np.complex128]: + x = np.random.randn(*shape).astype(dtype) + if np.iscomplexobj(x): + x = x + 1j*np.random.randn(*shape).astype(x.real.dtype) + wp = pywt.WaveletPacketND(data=x, wavelet='db1', mode='symmetric') + # no unnecessary copy made + assert_(wp.data is x) + + # full decomposition + wp.get_level(wp.maxlevel) + + # reconstruction from coefficients should preserve dtype + r = wp.reconstruct(False) + assert_equal(r.dtype, x.dtype) + assert_allclose(r, x, atol=1e-6, rtol=1e-6) + + +def test_wavelet_packet_axes(): + rstate = np.random.RandomState(0) + shape = (32, 16, 8) + x = rstate.standard_normal(shape) + for axes in [(0, 1), 1, (-3, -2, -1), (0, 2), (1, )]: + wp = pywt.WaveletPacketND(data=x, wavelet='db1', mode='symmetric', + axes=axes) + + # partial decomposition + nodes = wp.get_level(1) + # size along the transformed axes has changed + for ax2 in range(x.ndim): + if ax2 in tuple(np.atleast_1d(axes) % x.ndim): + nodes[0].data.shape[ax2] < x.shape[ax2] + else: + nodes[0].data.shape[ax2] == x.shape[ax2] + + # recontsruction from coefficients should preserve dtype + r = wp.reconstruct(False) + assert_equal(r.dtype, x.dtype) + assert_allclose(r, x, atol=1e-12, rtol=1e-12) + + # must have non-duplicate axes + assert_raises(ValueError, pywt.WaveletPacketND, data=x, wavelet='db1', + axes=(0, 0)) + + +def test_wavelet_packet_odd_shape(): + # the reconstruction has to be trimmed back to the original shape when a + # transformed axis has an odd length + x = np.arange(2 * 2 * 3, dtype=np.float64).reshape(2, 2, 3) + wp = pywt.WaveletPacketND(data=x, wavelet='haar', mode='symmetric', + axes=(0, 1, 2)) + wp.get_level(1) + r = wp.reconstruct(update=False) + assert_equal(r.shape, x.shape) + assert_allclose(r, x, atol=1e-12, rtol=1e-12) + + rstate = np.random.RandomState(0) + y = rstate.standard_normal((9, 11)) + for level in [1, 2, 3]: + wp = pywt.WaveletPacketND(data=y, wavelet='haar', mode='symmetric') + wp.get_level(level) + r = wp.reconstruct(update=False) + assert_equal(r.shape, y.shape) + assert_allclose(r, y, rtol=1e-12) + + # only some of the axes transformed + z = rstate.standard_normal((3, 5, 7)) + wp = pywt.WaveletPacketND(data=z, wavelet='haar', mode='symmetric', + axes=(1, 2)) + wp.get_level(1) + assert_allclose(wp.reconstruct(update=False), z, rtol=1e-12) + + # reconstructing again after an update gives the same result + wp = pywt.WaveletPacketND(data=y, wavelet='haar', mode='symmetric') + wp.get_level(2) + assert_allclose(wp.reconstruct(update=True), y, rtol=1e-12) + assert_allclose(wp.reconstruct(update=True), y, rtol=1e-12) + + +def test_wavelet_packet_odd_shape_subnode(): + # a subnode reconstructs to the shape of its own coefficients, so an + # update does not grow the data stored in the node + rstate = np.random.RandomState(0) + y = rstate.standard_normal((9, 11)) + wp = pywt.WaveletPacketND(data=y, wavelet='haar', mode='symmetric') + wp.get_level(2) + + shape = wp['aa'].data.shape + assert_equal(wp['aa'].reconstruct(update=False).shape, shape) + wp['aa'].reconstruct(update=True) + assert_equal(wp['aa'].data.shape, shape) + + # WaveletPacket2D already behaves this way + wp2 = pywt.WaveletPacket2D(data=y, wavelet='haar', mode='symmetric') + wp2.get_level(2) + assert_equal(wp2['a'].reconstruct(update=False).shape, shape) diff --git a/.venv/lib/python3.12/site-packages/pywt/version.py b/.venv/lib/python3.12/site-packages/pywt/version.py new file mode 100644 index 0000000000000000000000000000000000000000..1499da51172c127194292626ccfb0da98d2efca7 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/pywt/version.py @@ -0,0 +1,11 @@ +# THIS FILE IS GENERATED DURING THE PYWAVELETS BUILD +# See util/version_utils.py for details + +short_version = '1.8.0' +version = '1.8.0' +full_version = '1.8.0' +git_revision = '4bd3a5f' +release = True + +if not release: + version = full_version diff --git a/.venv/lib/python3.12/site-packages/pyyaml-6.0.3.dist-info/INSTALLER b/.venv/lib/python3.12/site-packages/pyyaml-6.0.3.dist-info/INSTALLER new file mode 100644 index 0000000000000000000000000000000000000000..a1b589e38a32041e49332e5e81c2d363dc418d68 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/pyyaml-6.0.3.dist-info/INSTALLER @@ -0,0 +1 @@ +pip diff --git a/.venv/lib/python3.12/site-packages/pyyaml-6.0.3.dist-info/METADATA b/.venv/lib/python3.12/site-packages/pyyaml-6.0.3.dist-info/METADATA new file mode 100644 index 0000000000000000000000000000000000000000..702ee6da5865b50b297705b077ea7d5904fead58 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/pyyaml-6.0.3.dist-info/METADATA @@ -0,0 +1,59 @@ +Metadata-Version: 2.4 +Name: PyYAML +Version: 6.0.3 +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.8 +Classifier: Programming Language :: Python :: 3.9 +Classifier: Programming Language :: Python :: 3.10 +Classifier: Programming Language :: Python :: 3.11 +Classifier: Programming Language :: Python :: 3.12 +Classifier: Programming Language :: Python :: 3.13 +Classifier: Programming Language :: Python :: 3.14 +Classifier: Programming Language :: Python :: Implementation :: CPython +Classifier: Programming Language :: Python :: Implementation :: PyPy +Classifier: Topic :: Software Development :: Libraries :: Python Modules +Classifier: Topic :: Text Processing :: Markup +Requires-Python: >=3.8 +License-File: LICENSE +Dynamic: author +Dynamic: author-email +Dynamic: classifier +Dynamic: description +Dynamic: download-url +Dynamic: home-page +Dynamic: license +Dynamic: license-file +Dynamic: platform +Dynamic: project-url +Dynamic: requires-python +Dynamic: summary + +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/.venv/lib/python3.12/site-packages/pyyaml-6.0.3.dist-info/RECORD b/.venv/lib/python3.12/site-packages/pyyaml-6.0.3.dist-info/RECORD new file mode 100644 index 0000000000000000000000000000000000000000..5d439d0f672cd256aa260d236c9aeb30ae829d99 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/pyyaml-6.0.3.dist-info/RECORD @@ -0,0 +1,44 @@ +_yaml/__init__.py,sha256=04Ae_5osxahpJHa3XBZUAf4wi6XX32gR8D6X6p64GEA,1402 +_yaml/__pycache__/__init__.cpython-312.pyc,, +pyyaml-6.0.3.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4 +pyyaml-6.0.3.dist-info/METADATA,sha256=A8O0Fe040J-u3Ek2DpMHabQMWPaFhebeAOLkkWqFjTQ,2351 +pyyaml-6.0.3.dist-info/RECORD,, +pyyaml-6.0.3.dist-info/REQUESTED,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +pyyaml-6.0.3.dist-info/WHEEL,sha256=DxRnWQz-Kp9-4a4hdDHsSv0KUC3H7sN9Nbef3-8RjXU,190 +pyyaml-6.0.3.dist-info/licenses/LICENSE,sha256=jTko-dxEkP1jVwfLiOsmvXZBAqcoKVQwfT5RZ6V36KQ,1101 +pyyaml-6.0.3.dist-info/top_level.txt,sha256=rpj0IVMTisAjh_1vG3Ccf9v5jpCQwAz6cD1IVU5ZdhQ,11 +yaml/__init__.py,sha256=sZ38wzPWp139cwc5ARZFByUvJxtB07X32FUQAzoFR6c,12311 +yaml/__pycache__/__init__.cpython-312.pyc,, +yaml/__pycache__/composer.cpython-312.pyc,, +yaml/__pycache__/constructor.cpython-312.pyc,, +yaml/__pycache__/cyaml.cpython-312.pyc,, +yaml/__pycache__/dumper.cpython-312.pyc,, +yaml/__pycache__/emitter.cpython-312.pyc,, +yaml/__pycache__/error.cpython-312.pyc,, +yaml/__pycache__/events.cpython-312.pyc,, +yaml/__pycache__/loader.cpython-312.pyc,, +yaml/__pycache__/nodes.cpython-312.pyc,, +yaml/__pycache__/parser.cpython-312.pyc,, +yaml/__pycache__/reader.cpython-312.pyc,, +yaml/__pycache__/representer.cpython-312.pyc,, +yaml/__pycache__/resolver.cpython-312.pyc,, +yaml/__pycache__/scanner.cpython-312.pyc,, +yaml/__pycache__/serializer.cpython-312.pyc,, +yaml/__pycache__/tokens.cpython-312.pyc,, +yaml/_yaml.cpython-312-x86_64-linux-gnu.so,sha256=lXoJmkUhwfdmkwb7b3nKY_pLmgtMRj98rIM6ZaXFwMs,2679264 +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/.venv/lib/python3.12/site-packages/pyyaml-6.0.3.dist-info/REQUESTED b/.venv/lib/python3.12/site-packages/pyyaml-6.0.3.dist-info/REQUESTED new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/.venv/lib/python3.12/site-packages/pyyaml-6.0.3.dist-info/WHEEL b/.venv/lib/python3.12/site-packages/pyyaml-6.0.3.dist-info/WHEEL new file mode 100644 index 0000000000000000000000000000000000000000..f3e8a970f16adf4526f1722547053522d94bf860 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/pyyaml-6.0.3.dist-info/WHEEL @@ -0,0 +1,7 @@ +Wheel-Version: 1.0 +Generator: setuptools (80.9.0) +Root-Is-Purelib: false +Tag: cp312-cp312-manylinux_2_17_x86_64 +Tag: cp312-cp312-manylinux2014_x86_64 +Tag: cp312-cp312-manylinux_2_28_x86_64 + diff --git a/.venv/lib/python3.12/site-packages/pyyaml-6.0.3.dist-info/licenses/LICENSE b/.venv/lib/python3.12/site-packages/pyyaml-6.0.3.dist-info/licenses/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..2f1b8e15e5627d92f0521605c9870bc8e5505cb4 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/pyyaml-6.0.3.dist-info/licenses/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/.venv/lib/python3.12/site-packages/pyyaml-6.0.3.dist-info/top_level.txt b/.venv/lib/python3.12/site-packages/pyyaml-6.0.3.dist-info/top_level.txt new file mode 100644 index 0000000000000000000000000000000000000000..e6475e911f628412049bc4090d86f23ac403adde --- /dev/null +++ b/.venv/lib/python3.12/site-packages/pyyaml-6.0.3.dist-info/top_level.txt @@ -0,0 +1,2 @@ +_yaml +yaml diff --git a/.venv/lib/python3.12/site-packages/regex-2026.9.10.dist-info/INSTALLER b/.venv/lib/python3.12/site-packages/regex-2026.9.10.dist-info/INSTALLER new file mode 100644 index 0000000000000000000000000000000000000000..a1b589e38a32041e49332e5e81c2d363dc418d68 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/regex-2026.9.10.dist-info/INSTALLER @@ -0,0 +1 @@ +pip diff --git a/.venv/lib/python3.12/site-packages/regex-2026.9.10.dist-info/METADATA b/.venv/lib/python3.12/site-packages/regex-2026.9.10.dist-info/METADATA new file mode 100644 index 0000000000000000000000000000000000000000..789c8c25ac5d255f663283f3862c8361e12e4442 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/regex-2026.9.10.dist-info/METADATA @@ -0,0 +1,1061 @@ +Metadata-Version: 2.4 +Name: regex +Version: 2026.9.10 +Summary: Alternative regular expression module, to replace re. +Author-email: Matthew Barnett +License-Expression: Apache-2.0 AND CNRI-Python +Project-URL: Homepage, https://github.com/mrabarnett/mrab-regex +Classifier: Development Status :: 5 - Production/Stable +Classifier: Intended Audience :: Developers +Classifier: Operating System :: OS Independent +Classifier: Programming Language :: Python :: 3.10 +Classifier: Programming Language :: Python :: 3.11 +Classifier: Programming Language :: Python :: 3.12 +Classifier: Programming Language :: Python :: 3.13 +Classifier: Programming Language :: Python :: 3.14 +Classifier: Programming Language :: Python :: 3.15 +Classifier: Topic :: Scientific/Engineering :: Information Analysis +Classifier: Topic :: Software Development :: Libraries :: Python Modules +Classifier: Topic :: Text Processing +Classifier: Topic :: Text Processing :: General +Requires-Python: >=3.10 +Description-Content-Type: text/x-rst +License-File: LICENSE.txt +Dynamic: license-file + +Introduction +------------ + +This regex implementation is backwards-compatible with the standard 're' module, but offers additional functionality. + +Python 2 +-------- + +Python 2 is no longer supported. The last release that supported Python 2 was 2021.11.10. + +PyPy +---- + +This module is targeted at CPython. It expects that all codepoints are the same width, so it won't behave properly with PyPy outside U+0000..U+007F because PyPy stores strings as UTF-8. + +Multithreading +-------------- + +The regex module releases the GIL during matching on instances of the built-in (immutable) string classes, enabling other Python threads to run concurrently. It is also possible to force the regex module to release the GIL during matching by calling the matching methods with the keyword argument ``concurrent=True``. The behaviour is undefined if the string changes during matching, so use it *only* when it is guaranteed that that won't happen. + +Unicode +------- + +This module supports Unicode 17.0.0. Full Unicode case-folding is supported. + +Flags +----- + +There are 2 kinds of flag: scoped and global. Scoped flags can apply to only part of a pattern and can be turned on or off; global flags apply to the entire pattern and can only be turned on. + +The scoped flags are: ``ASCII (?a)``, ``FULLCASE (?f)``, ``IGNORECASE (?i)``, ``LOCALE (?L)``, ``MULTILINE (?m)``, ``DOTALL (?s)``, ``UNICODE (?u)``, ``VERBOSE (?x)``, ``WORD (?w)``. + +The global flags are: ``BESTMATCH (?b)``, ``ENHANCEMATCH (?e)``, ``POSIX (?p)``, ``REVERSE (?r)``, ``VERSION0 (?V0)``, ``VERSION1 (?V1)``. + +If neither the ``ASCII``, ``LOCALE`` nor ``UNICODE`` flag is specified, it will default to ``UNICODE`` if the regex pattern is a Unicode string and ``ASCII`` if it's a bytestring. + +The ``ENHANCEMATCH`` flag makes fuzzy matching attempt to improve the fit of the next match that it finds. + +The ``BESTMATCH`` flag makes fuzzy matching search for the best match instead of the next match. + +Old vs new behaviour +-------------------- + +In order to be compatible with the re module, this module has 2 behaviours: + +* **Version 0** behaviour (old behaviour, compatible with the re module): + + Please note that the re module's behaviour may change over time, and I'll endeavour to match that behaviour in version 0. + + * Indicated by the ``VERSION0`` flag. + + * Zero-width matches are not handled correctly in the re module before Python 3.7. The behaviour in those earlier versions is: + + * ``.split`` won't split a string at a zero-width match. + + * ``.sub`` will advance by one character after a zero-width match. + + * Inline flags apply to the entire pattern, and they can't be turned off. + + * Only simple sets are supported. + + * Case-insensitive matches in Unicode use simple case-folding by default. + +* **Version 1** behaviour (new behaviour, possibly different from the re module): + + * Indicated by the ``VERSION1`` flag. + + * Zero-width matches are handled correctly. + + * Inline flags apply to the end of the group or pattern, and they can be turned off. + + * Nested sets and set operations are supported. + + * Case-insensitive matches in Unicode use full case-folding by default. + +If no version is specified, the regex module will default to ``regex.DEFAULT_VERSION``. + +Case-insensitive matches in Unicode +----------------------------------- + +The regex module supports both simple and full case-folding for case-insensitive matches in Unicode. Use of full case-folding can be turned on using the ``FULLCASE`` flag. Please note that this flag affects how the ``IGNORECASE`` flag works; the ``FULLCASE`` flag itself does not turn on case-insensitive matching. + +Version 0 behaviour: the flag is off by default. + +Version 1 behaviour: the flag is on by default. + +Nested sets and set operations +------------------------------ + +It's not possible to support both simple sets, as used in the re module, and nested sets at the same time because of a difference in the meaning of an unescaped ``"["`` in a set. + +For example, the pattern ``[[a-z]--[aeiou]]`` is treated in the version 0 behaviour (simple sets, compatible with the re module) as: + +* Set containing "[" and the letters "a" to "z" + +* Literal "--" + +* Set containing letters "a", "e", "i", "o", "u" + +* Literal "]" + +but in the version 1 behaviour (nested sets, enhanced behaviour) as: + +* Set which is: + + * Set containing the letters "a" to "z" + +* but excluding: + + * Set containing the letters "a", "e", "i", "o", "u" + +Version 0 behaviour: only simple sets are supported. + +Version 1 behaviour: nested sets and set operations are supported. + +Notes on named groups +--------------------- + +All groups have a group number, starting from 1. + +Groups with the same group name will have the same group number, and groups with a different group name will have a different group number. + +The same name can be used by more than one group, with later captures 'overwriting' earlier captures. All the captures of the group will be available from the ``captures`` method of the match object. + +Group numbers will be reused across different branches of a branch reset, eg. ``(?|(first)|(second))`` has only group 1. If groups have different group names then they will, of course, have different group numbers, eg. ``(?|(?Pfirst)|(?Psecond))`` has group 1 ("foo") and group 2 ("bar"). + +In the regex ``(\s+)(?|(?P[A-Z]+)|(\w+) (?P[0-9]+)`` there are 2 groups: + +* ``(\s+)`` is group 1. + +* ``(?P[A-Z]+)`` is group 2, also called "foo". + +* ``(\w+)`` is group 2 because of the branch reset. + +* ``(?P[0-9]+)`` is group 2 because it's called "foo". + +If you want to prevent ``(\w+)`` from being group 2, you need to name it (different name, different group number). + +Additional features +------------------- + +The issue numbers relate to the Python bug tracker, except where listed otherwise. + +Added ``\p{Horiz_Space}`` and ``\p{Vert_Space}`` (`GitHub issue 477 `_) +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +``\p{Horiz_Space}`` or ``\p{H}`` matches horizontal whitespace and ``\p{Vert_Space}`` or ``\p{V}`` matches vertical whitespace. + +Added support for lookaround in conditional pattern (`Hg issue 163 `_) +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +The test of a conditional pattern can be a lookaround. + +.. sourcecode:: python + + >>> regex.match(r'(?(?=\d)\d+|\w+)', '123abc') + + >>> regex.match(r'(?(?=\d)\d+|\w+)', 'abc123') + + +This is not quite the same as putting a lookaround in the first branch of a pair of alternatives. + +.. sourcecode:: python + + >>> print(regex.match(r'(?:(?=\d)\d+\b|\w+)', '123abc')) + + >>> print(regex.match(r'(?(?=\d)\d+\b|\w+)', '123abc')) + None + +In the first example, the lookaround matched, but the remainder of the first branch failed to match, and so the second branch was attempted, whereas in the second example, the lookaround matched, and the first branch failed to match, but the second branch was **not** attempted. + +Added POSIX matching (leftmost longest) (`Hg issue 150 `_) +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +The POSIX standard for regex is to return the leftmost longest match. This can be turned on using the ``POSIX`` flag. + +It looks for the longest overall match. It doesn't look for the longest match for each group. + +.. sourcecode:: python + + >>> # Normal matching. + >>> regex.search(r'Mr|Mrs', 'Mrs') + + >>> regex.search(r'one(self)?(selfsufficient)?', 'oneselfsufficient') + + >>> # POSIX matching. + >>> regex.search(r'(?p)Mr|Mrs', 'Mrs') + + >>> regex.search(r'(?p)one(self)?(selfsufficient)?', 'oneselfsufficient') + + +Note that it will take longer to find matches because when it finds a match at a certain position, it won't return that immediately, but will keep looking to see if there's another longer match there. + +Added ``(?(DEFINE)...)`` (`Hg issue 152 `_) +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +If there's no group called "DEFINE", then ... will be ignored except that any groups defined within it can be called and that the normal rules for numbering groups still apply. + +.. sourcecode:: python + + >>> regex.search(r'(?(DEFINE)(?P\d+)(?P\w+))(?&quant) (?&item)', '5 elephants') + + +Added ``(*PRUNE)``, ``(*SKIP)`` and ``(*FAIL)`` (`Hg issue 153 `_) +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +``(*PRUNE)`` discards the backtracking info up to that point. When used in an atomic group or a lookaround, it won't affect the enclosing pattern. + +``(*SKIP)`` is similar to ``(*PRUNE)``, except that it also sets where in the text the next attempt to match will start. When used in an atomic group or a lookaround, it won't affect the enclosing pattern. + +``(*FAIL)`` causes immediate backtracking. ``(*F)`` is a permitted abbreviation. + +Added ``\K`` (`Hg issue 151 `_) +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +Keeps the part of the entire match after the position where ``\K`` occurred; the part before it is discarded. + +It does not affect what groups return. + +.. sourcecode:: python + + >>> m = regex.search(r'(\w\w\K\w\w\w)', 'abcdef') + >>> m[0] + 'cde' + >>> m[1] + 'abcde' + >>> + >>> m = regex.search(r'(?r)(\w\w\K\w\w\w)', 'abcdef') + >>> m[0] + 'bc' + >>> m[1] + 'bcdef' + +Added capture subscripting for ``expandf`` and ``subf``/``subfn`` (`Hg issue 133 `_) +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +You can use subscripting to get the captures of a repeated group. + +.. sourcecode:: python + + >>> m = regex.match(r"(\w)+", "abc") + >>> m.expandf("{1}") + 'c' + >>> m.expandf("{1[0]} {1[1]} {1[2]}") + 'a b c' + >>> m.expandf("{1[-1]} {1[-2]} {1[-3]}") + 'c b a' + >>> + >>> m = regex.match(r"(?P\w)+", "abc") + >>> m.expandf("{letter}") + 'c' + >>> m.expandf("{letter[0]} {letter[1]} {letter[2]}") + 'a b c' + >>> m.expandf("{letter[-1]} {letter[-2]} {letter[-3]}") + 'c b a' + +Added support for referring to a group by number using ``(?P=...)`` +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +This is in addition to the existing ``\g<...>``. + +Fixed the handling of locale-sensitive regexes +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +The ``LOCALE`` flag is intended for legacy code and has limited support. You're still recommended to use Unicode instead. + +Added partial matches (`Hg issue 102 `_) +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +A partial match is one that matches up to the end of string, but that string has been truncated and you want to know whether a complete match could be possible if the string had not been truncated. + +Partial matches are supported by ``match``, ``search``, ``fullmatch`` and ``finditer`` with the ``partial`` keyword argument. + +Match objects have a ``partial`` attribute, which is ``True`` if it's a partial match. + +For example, if you wanted a user to enter a 4-digit number and check it character by character as it was being entered: + +.. sourcecode:: python + + >>> pattern = regex.compile(r'\d{4}') + + >>> # Initially, nothing has been entered: + >>> print(pattern.fullmatch('', partial=True)) + + + >>> # An empty string is OK, but it's only a partial match. + >>> # The user enters a letter: + >>> print(pattern.fullmatch('a', partial=True)) + None + >>> # It'll never match. + + >>> # The user deletes that and enters a digit: + >>> print(pattern.fullmatch('1', partial=True)) + + >>> # It matches this far, but it's only a partial match. + + >>> # The user enters 2 more digits: + >>> print(pattern.fullmatch('123', partial=True)) + + >>> # It matches this far, but it's only a partial match. + + >>> # The user enters another digit: + >>> print(pattern.fullmatch('1234', partial=True)) + + >>> # It's a complete match. + + >>> # If the user enters another digit: + >>> print(pattern.fullmatch('12345', partial=True)) + None + >>> # It's no longer a match. + + >>> # This is a partial match: + >>> pattern.match('123', partial=True).partial + True + + >>> # This is a complete match: + >>> pattern.match('1233', partial=True).partial + False + +``*`` operator not working correctly with sub() (`Hg issue 106 `_) +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +Sometimes it's not clear how zero-width matches should be handled. For example, should ``.*`` match 0 characters directly after matching >0 characters? + +.. sourcecode:: python + + >>> regex.sub('.*', 'x', 'test') + 'xx' + >>> regex.sub('.*?', '|', 'test') + '|||||||||' + +Added ``capturesdict`` (`Hg issue 86 `_) +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +``capturesdict`` is a combination of ``groupdict`` and ``captures``: + +``groupdict`` returns a dict of the named groups and the last capture of those groups. + +``captures`` returns a list of all the captures of a group + +``capturesdict`` returns a dict of the named groups and lists of all the captures of those groups. + +.. sourcecode:: python + + >>> m = regex.match(r"(?:(?P\w+) (?P\d+)\n)+", "one 1\ntwo 2\nthree 3\n") + >>> m.groupdict() + {'word': 'three', 'digits': '3'} + >>> m.captures("word") + ['one', 'two', 'three'] + >>> m.captures("digits") + ['1', '2', '3'] + >>> m.capturesdict() + {'word': ['one', 'two', 'three'], 'digits': ['1', '2', '3']} + +Added ``allcaptures`` and ``allspans`` (`Git issue 474 `_) +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +``allcaptures`` returns a list of all the captures of all the groups. + +``allspans`` returns a list of all the spans of the all captures of all the groups. + +.. sourcecode:: python + + >>> m = regex.match(r"(?:(?P\w+) (?P\d+)\n)+", "one 1\ntwo 2\nthree 3\n") + >>> m.allcaptures() + (['one 1\ntwo 2\nthree 3\n'], ['one', 'two', 'three'], ['1', '2', '3']) + >>> m.allspans() + ([(0, 20)], [(0, 3), (6, 9), (12, 17)], [(4, 5), (10, 11), (18, 19)]) + +Allow duplicate names of groups (`Hg issue 87 `_) +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +Group names can be duplicated. + +.. sourcecode:: python + + >>> # With optional groups: + >>> + >>> # Both groups capture, the second capture 'overwriting' the first. + >>> m = regex.match(r"(?P\w+)? or (?P\w+)?", "first or second") + >>> m.group("item") + 'second' + >>> m.captures("item") + ['first', 'second'] + >>> # Only the second group captures. + >>> m = regex.match(r"(?P\w+)? or (?P\w+)?", " or second") + >>> m.group("item") + 'second' + >>> m.captures("item") + ['second'] + >>> # Only the first group captures. + >>> m = regex.match(r"(?P\w+)? or (?P\w+)?", "first or ") + >>> m.group("item") + 'first' + >>> m.captures("item") + ['first'] + >>> + >>> # With mandatory groups: + >>> + >>> # Both groups capture, the second capture 'overwriting' the first. + >>> m = regex.match(r"(?P\w*) or (?P\w*)?", "first or second") + >>> m.group("item") + 'second' + >>> m.captures("item") + ['first', 'second'] + >>> # Again, both groups capture, the second capture 'overwriting' the first. + >>> m = regex.match(r"(?P\w*) or (?P\w*)", " or second") + >>> m.group("item") + 'second' + >>> m.captures("item") + ['', 'second'] + >>> # And yet again, both groups capture, the second capture 'overwriting' the first. + >>> m = regex.match(r"(?P\w*) or (?P\w*)", "first or ") + >>> m.group("item") + '' + >>> m.captures("item") + ['first', ''] + +Added ``fullmatch`` (`issue #16203 `_) +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +``fullmatch`` behaves like ``match``, except that it must match all of the string. + +.. sourcecode:: python + + >>> print(regex.fullmatch(r"abc", "abc").span()) + (0, 3) + >>> print(regex.fullmatch(r"abc", "abcx")) + None + >>> print(regex.fullmatch(r"abc", "abcx", endpos=3).span()) + (0, 3) + >>> print(regex.fullmatch(r"abc", "xabcy", pos=1, endpos=4).span()) + (1, 4) + >>> + >>> regex.match(r"a.*?", "abcd").group(0) + 'a' + >>> regex.fullmatch(r"a.*?", "abcd").group(0) + 'abcd' + +Added ``subf`` and ``subfn`` +^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +``subf`` and ``subfn`` are alternatives to ``sub`` and ``subn`` respectively. When passed a replacement string, they treat it as a format string. + +.. sourcecode:: python + + >>> regex.subf(r"(\w+) (\w+)", "{0} => {2} {1}", "foo bar") + 'foo bar => bar foo' + >>> regex.subf(r"(?P\w+) (?P\w+)", "{word2} {word1}", "foo bar") + 'bar foo' + +Added ``expandf`` to match object +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +``expandf`` is an alternative to ``expand``. When passed a replacement string, it treats it as a format string. + +.. sourcecode:: python + + >>> m = regex.match(r"(\w+) (\w+)", "foo bar") + >>> m.expandf("{0} => {2} {1}") + 'foo bar => bar foo' + >>> + >>> m = regex.match(r"(?P\w+) (?P\w+)", "foo bar") + >>> m.expandf("{word2} {word1}") + 'bar foo' + +Detach searched string +^^^^^^^^^^^^^^^^^^^^^^ + +A match object contains a reference to the string that was searched, via its ``string`` attribute. The ``detach_string`` method will 'detach' that string, making it available for garbage collection, which might save valuable memory if that string is very large. + +.. sourcecode:: python + + >>> m = regex.search(r"\w+", "Hello world") + >>> print(m.group()) + Hello + >>> print(m.string) + Hello world + >>> m.detach_string() + >>> print(m.group()) + Hello + >>> print(m.string) + None + +Recursive patterns (`Hg issue 27 `_) +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +Recursive and repeated patterns are supported. + +``(?R)`` or ``(?0)`` tries to match the entire regex recursively. ``(?1)``, ``(?2)``, etc, try to match the relevant group. + +``(?&name)`` tries to match the named group. + +.. sourcecode:: python + + >>> regex.match(r"(Tarzan|Jane) loves (?1)", "Tarzan loves Jane").groups() + ('Tarzan',) + >>> regex.match(r"(Tarzan|Jane) loves (?1)", "Jane loves Tarzan").groups() + ('Jane',) + + >>> m = regex.search(r"(\w)(?:(?R)|(\w?))\1", "kayak") + >>> m.group(0, 1, 2) + ('kayak', 'k', None) + +The first two examples show how the subpattern within the group is reused, but is _not_ itself a group. In other words, ``"(Tarzan|Jane) loves (?1)"`` is equivalent to ``"(Tarzan|Jane) loves (?:Tarzan|Jane)"``. + +It's possible to backtrack into a recursed or repeated group. + +You can't call a group if there is more than one group with that group name or group number (``"ambiguous group reference"``). + +The alternative forms ``(?P>name)`` and ``(?P&name)`` are also supported. + +Full Unicode case-folding is supported +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +In version 1 behaviour, the regex module uses full case-folding when performing case-insensitive matches in Unicode. + +.. sourcecode:: python + + >>> regex.match(r"(?iV1)strasse", "stra\N{LATIN SMALL LETTER SHARP S}e").span() + (0, 6) + >>> regex.match(r"(?iV1)stra\N{LATIN SMALL LETTER SHARP S}e", "STRASSE").span() + (0, 7) + +In version 0 behaviour, it uses simple case-folding for backward compatibility with the re module. + +Approximate "fuzzy" matching (`Hg issue 12 `_, `Hg issue 41 `_, `Hg issue 109 `_) +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +Regex usually attempts an exact match, but sometimes an approximate, or "fuzzy", match is needed, for those cases where the text being searched may contain errors in the form of inserted, deleted or substituted characters. + +A fuzzy regex specifies which types of errors are permitted, and, optionally, either the minimum and maximum or only the maximum permitted number of each type. (You cannot specify only a minimum.) + +The 3 types of error are: + +* Insertion, indicated by "i" + +* Deletion, indicated by "d" + +* Substitution, indicated by "s" + +In addition, "e" indicates any type of error. + +The fuzziness of a regex item is specified between "{" and "}" after the item. + +Examples: + +* ``foo`` match "foo" exactly + +* ``(?:foo){i}`` match "foo", permitting insertions + +* ``(?:foo){d}`` match "foo", permitting deletions + +* ``(?:foo){s}`` match "foo", permitting substitutions + +* ``(?:foo){i,s}`` match "foo", permitting insertions and substitutions + +* ``(?:foo){e}`` match "foo", permitting errors + +If a certain type of error is specified, then any type not specified will **not** be permitted. + +In the following examples I'll omit the item and write only the fuzziness: + +* ``{d<=3}`` permit at most 3 deletions, but no other types + +* ``{i<=1,s<=2}`` permit at most 1 insertion and at most 2 substitutions, but no deletions + +* ``{1<=e<=3}`` permit at least 1 and at most 3 errors + +* ``{i<=2,d<=2,e<=3}`` permit at most 2 insertions, at most 2 deletions, at most 3 errors in total, but no substitutions + +It's also possible to state the costs of each type of error and the maximum permitted total cost. + +Examples: + +* ``{2i+2d+1s<=4}`` each insertion costs 2, each deletion costs 2, each substitution costs 1, the total cost must not exceed 4 + +* ``{i<=1,d<=1,s<=1,2i+2d+1s<=4}`` at most 1 insertion, at most 1 deletion, at most 1 substitution; each insertion costs 2, each deletion costs 2, each substitution costs 1, the total cost must not exceed 4 + +You can also use "<" instead of "<=" if you want an exclusive minimum or maximum. + +You can add a test to perform on a character that's substituted or inserted. + +Examples: + +* ``{s<=2:[a-z]}`` at most 2 substitutions, which must be in the character set ``[a-z]``. + +* ``{s<=2,i<=3:\d}`` at most 2 substitutions, at most 3 insertions, which must be digits. + +By default, fuzzy matching searches for the first match that meets the given constraints. The ``ENHANCEMATCH`` flag will cause it to attempt to improve the fit (i.e. reduce the number of errors) of the match that it has found. + +The ``BESTMATCH`` flag will make it search for the best match instead. + +Further examples to note: + +* ``regex.search("(dog){e}", "cat and dog")[1]`` returns ``"cat"`` because that matches ``"dog"`` with 3 errors (an unlimited number of errors is permitted). + +* ``regex.search("(dog){e<=1}", "cat and dog")[1]`` returns ``" dog"`` (with a leading space) because that matches ``"dog"`` with 1 error, which is within the limit. + +* ``regex.search("(?e)(dog){e<=1}", "cat and dog")[1]`` returns ``"dog"`` (without a leading space) because the fuzzy search matches ``" dog"`` with 1 error, which is within the limit, and the ``(?e)`` then it attempts a better fit. + +In the first two examples there are perfect matches later in the string, but in neither case is it the first possible match. + +The match object has an attribute ``fuzzy_counts`` which gives the total number of substitutions, insertions and deletions. + +.. sourcecode:: python + + >>> # A 'raw' fuzzy match: + >>> regex.fullmatch(r"(?:cats|cat){e<=1}", "cat").fuzzy_counts + (0, 0, 1) + >>> # 0 substitutions, 0 insertions, 1 deletion. + + >>> # A better match might be possible if the ENHANCEMATCH flag used: + >>> regex.fullmatch(r"(?e)(?:cats|cat){e<=1}", "cat").fuzzy_counts + (0, 0, 0) + >>> # 0 substitutions, 0 insertions, 0 deletions. + +The match object also has an attribute ``fuzzy_changes`` which gives a tuple of the positions of the substitutions, insertions and deletions. + +.. sourcecode:: python + + >>> m = regex.search('(fuu){i<=2,d<=2,e<=5}', 'anaconda foo bar') + >>> m + + >>> m.fuzzy_changes + ([], [7, 8], [10, 11]) + +What this means is that if the matched part of the string had been: + +.. sourcecode:: python + + 'anacondfuuoo bar' + +it would've been an exact match. + +However, there were insertions at positions 7 and 8: + +.. sourcecode:: python + + 'anaconda fuuoo bar' + ^^ + +and deletions at positions 10 and 11: + +.. sourcecode:: python + + 'anaconda f~~oo bar' + ^^ + +So the actual string was: + +.. sourcecode:: python + + 'anaconda foo bar' + +Named lists ``\L`` (`Hg issue 11 `_) +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +There are occasions where you may want to include a list (actually, a set) of options in a regex. + +One way is to build the pattern like this: + +.. sourcecode:: python + + >>> p = regex.compile(r"first|second|third|fourth|fifth") + +but if the list is large, parsing the resulting regex can take considerable time, and care must also be taken that the strings are properly escaped and properly ordered, for example, "cats" before "cat". + +The new alternative is to use a named list: + +.. sourcecode:: python + + >>> option_set = ["first", "second", "third", "fourth", "fifth"] + >>> p = regex.compile(r"\L", options=option_set) + +The order of the items is irrelevant, they are treated as a set. The named lists are available as the ``.named_lists`` attribute of the pattern object : + +.. sourcecode:: python + + >>> print(p.named_lists) + {'options': frozenset({'third', 'first', 'fifth', 'fourth', 'second'})} + +If there are any unused keyword arguments, ``ValueError`` will be raised unless you tell it otherwise: + +.. sourcecode:: python + + >>> option_set = ["first", "second", "third", "fourth", "fifth"] + >>> p = regex.compile(r"\L", options=option_set, other_options=[]) + Traceback (most recent call last): + File "", line 1, in + File "C:\Python310\lib\site-packages\regex\regex.py", line 353, in compile + return _compile(pattern, flags, ignore_unused, kwargs, cache_pattern) + File "C:\Python310\lib\site-packages\regex\regex.py", line 500, in _compile + complain_unused_args() + File "C:\Python310\lib\site-packages\regex\regex.py", line 483, in complain_unused_args + raise ValueError('unused keyword argument {!a}'.format(any_one)) + ValueError: unused keyword argument 'other_options' + >>> p = regex.compile(r"\L", options=option_set, other_options=[], ignore_unused=True) + >>> p = regex.compile(r"\L", options=option_set, other_options=[], ignore_unused=False) + Traceback (most recent call last): + File "", line 1, in + File "C:\Python310\lib\site-packages\regex\regex.py", line 353, in compile + return _compile(pattern, flags, ignore_unused, kwargs, cache_pattern) + File "C:\Python310\lib\site-packages\regex\regex.py", line 500, in _compile + complain_unused_args() + File "C:\Python310\lib\site-packages\regex\regex.py", line 483, in complain_unused_args + raise ValueError('unused keyword argument {!a}'.format(any_one)) + ValueError: unused keyword argument 'other_options' + >>> + +Start and end of word +^^^^^^^^^^^^^^^^^^^^^ + +``\m`` matches at the start of a word. + +``\M`` matches at the end of a word. + +Compare with ``\b``, which matches at the start or end of a word. + +Unicode line separators +^^^^^^^^^^^^^^^^^^^^^^^ + +Normally the only line separator is ``\n`` (``\x0A``), but if the ``WORD`` flag is turned on then the line separators are ``\x0D\x0A``, ``\x0A``, ``\x0B``, ``\x0C`` and ``\x0D``, plus ``\x85``, ``\u2028`` and ``\u2029`` when working with Unicode. + +This affects the regex dot ``"."``, which, with the ``DOTALL`` flag turned off, matches any character except a line separator. It also affects the line anchors ``^`` and ``$`` (in multiline mode). + +Set operators +^^^^^^^^^^^^^ + +**Version 1 behaviour only** + +Set operators have been added, and a set ``[...]`` can include nested sets. + +The operators, in order of increasing precedence, are: + +* ``||`` for union ("x||y" means "x or y") + +* ``~~`` (double tilde) for symmetric difference ("x~~y" means "x or y, but not both") + +* ``&&`` for intersection ("x&&y" means "x and y") + +* ``--`` (double dash) for difference ("x--y" means "x but not y") + +Implicit union, ie, simple juxtaposition like in ``[ab]``, has the highest precedence. Thus, ``[ab&&cd]`` is the same as ``[[a||b]&&[c||d]]``. + +Examples: + +* ``[ab]`` # Set containing 'a' and 'b' + +* ``[a-z]`` # Set containing 'a' .. 'z' + +* ``[[a-z]--[qw]]`` # Set containing 'a' .. 'z', but not 'q' or 'w' + +* ``[a-z--qw]`` # Same as above + +* ``[\p{L}--QW]`` # Set containing all letters except 'Q' and 'W' + +* ``[\p{N}--[0-9]]`` # Set containing all numbers except '0' .. '9' + +* ``[\p{ASCII}&&\p{Letter}]`` # Set containing all characters which are ASCII and letter + +regex.escape (`issue #2650 `_) +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +regex.escape has an additional keyword parameter ``special_only``. When True, only 'special' regex characters, such as '?', are escaped. + +.. sourcecode:: python + + >>> regex.escape("foo!?", special_only=False) + 'foo\\!\\?' + >>> regex.escape("foo!?", special_only=True) + 'foo!\\?' + +regex.escape (`Hg issue 249 `_) +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +regex.escape has an additional keyword parameter ``literal_spaces``. When True, spaces are not escaped. + +.. sourcecode:: python + + >>> regex.escape("foo bar!?", literal_spaces=False) + 'foo\\ bar!\\?' + >>> regex.escape("foo bar!?", literal_spaces=True) + 'foo bar!\\?' + +Repeated captures (`issue #7132 `_) +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +A match object has additional methods which return information on all the successful matches of a repeated group. These methods are: + +* ``matchobject.captures([group1, ...])`` + + * Returns a list of the strings matched in a group or groups. Compare with ``matchobject.group([group1, ...])``. + +* ``matchobject.starts([group])`` + + * Returns a list of the start positions. Compare with ``matchobject.start([group])``. + +* ``matchobject.ends([group])`` + + * Returns a list of the end positions. Compare with ``matchobject.end([group])``. + +* ``matchobject.spans([group])`` + + * Returns a list of the spans. Compare with ``matchobject.span([group])``. + +.. sourcecode:: python + + >>> m = regex.search(r"(\w{3})+", "123456789") + >>> m.group(1) + '789' + >>> m.captures(1) + ['123', '456', '789'] + >>> m.start(1) + 6 + >>> m.starts(1) + [0, 3, 6] + >>> m.end(1) + 9 + >>> m.ends(1) + [3, 6, 9] + >>> m.span(1) + (6, 9) + >>> m.spans(1) + [(0, 3), (3, 6), (6, 9)] + +Atomic grouping ``(?>...)`` (`issue #433030 `_) +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +If the following pattern subsequently fails, then the subpattern as a whole will fail. + +Possessive quantifiers +^^^^^^^^^^^^^^^^^^^^^^ + +``(?:...)?+`` ; ``(?:...)*+`` ; ``(?:...)++`` ; ``(?:...){min,max}+`` + +The subpattern is matched up to 'max' times. If the following pattern subsequently fails, then all the repeated subpatterns will fail as a whole. For example, ``(?:...)++`` is equivalent to ``(?>(?:...)+)``. + +Scoped flags (`issue #433028 `_) +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +``(?flags-flags:...)`` + +The flags will apply only to the subpattern. Flags can be turned on or off. + +Definition of 'word' character (`issue #1693050 `_) +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +The definition of a 'word' character has been expanded for Unicode. It conforms to the Unicode specification at ``http://www.unicode.org/reports/tr29/``. + +Variable-length lookbehind +^^^^^^^^^^^^^^^^^^^^^^^^^^ + +A lookbehind can match a variable-length string. + +Flags argument for regex.split, regex.sub and regex.subn (`issue #3482 `_) +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +``regex.split``, ``regex.sub`` and ``regex.subn`` support a 'flags' argument. + +Pos and endpos arguments for regex.sub and regex.subn +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +``regex.sub`` and ``regex.subn`` support 'pos' and 'endpos' arguments. + +'Overlapped' argument for regex.findall and regex.finditer +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +``regex.findall`` and ``regex.finditer`` support an 'overlapped' flag which permits overlapped matches. + +Splititer +^^^^^^^^^ + +``regex.splititer`` has been added. It's a generator equivalent of ``regex.split``. + +Subscripting match objects for groups +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +A match object accepts access to the groups via subscripting and slicing: + +.. sourcecode:: python + + >>> m = regex.search(r"(?P.*?)(?P\d+)(?P.*)", "pqr123stu") + >>> print(m["before"]) + pqr + >>> print(len(m)) + 4 + >>> print(m[:]) + ('pqr123stu', 'pqr', '123', 'stu') + +Named groups +^^^^^^^^^^^^ + +Groups can be named with ``(?...)`` as well as the existing ``(?P...)``. + +Group references +^^^^^^^^^^^^^^^^ + +Groups can be referenced within a pattern with ``\g``. This also allows there to be more than 99 groups. + +Named characters ``\N{name}`` +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +Named characters are supported. Note that only those known by Python's Unicode database will be recognised. + +Unicode codepoint properties, including scripts and blocks +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +``\p{property=value}``; ``\P{property=value}``; ``\p{value}`` ; ``\P{value}`` + +Many Unicode properties are supported, including blocks and scripts. ``\p{property=value}`` or ``\p{property:value}`` matches a character whose property ``property`` has value ``value``. The inverse of ``\p{property=value}`` is ``\P{property=value}`` or ``\p{^property=value}``. + +If the short form ``\p{value}`` is used, the properties are checked in the order: ``General_Category``, ``Script``, ``Block``, binary property: + +* ``Latin``, the 'Latin' script (``Script=Latin``). + +* ``BasicLatin``, the 'BasicLatin' block (``Block=BasicLatin``). + +* ``Alphabetic``, the 'Alphabetic' binary property (``Alphabetic=Yes``). + +A short form starting with ``Is`` indicates a script or binary property: + +* ``IsLatin``, the 'Latin' script (``Script=Latin``). + +* ``IsAlphabetic``, the 'Alphabetic' binary property (``Alphabetic=Yes``). + +A short form starting with ``In`` indicates a block property: + +* ``InBasicLatin``, the 'BasicLatin' block (``Block=BasicLatin``). + +POSIX character classes +^^^^^^^^^^^^^^^^^^^^^^^ + +``[[:alpha:]]``; ``[[:^alpha:]]`` + +POSIX character classes are supported. These are normally treated as an alternative form of ``\p{...}``. + +The exceptions are ``alnum``, ``digit``, ``punct`` and ``xdigit``, whose definitions are different from those of Unicode. + +``[[:alnum:]]`` is equivalent to ``\p{posix_alnum}``. + +``[[:digit:]]`` is equivalent to ``\p{posix_digit}``. + +``[[:punct:]]`` is equivalent to ``\p{posix_punct}``. + +``[[:xdigit:]]`` is equivalent to ``\p{posix_xdigit}``. + +Search anchor ``\G`` +^^^^^^^^^^^^^^^^^^^^ + +A search anchor has been added. It matches at the position where each search started/continued and can be used for contiguous matches or in negative variable-length lookbehinds to limit how far back the lookbehind goes: + +.. sourcecode:: python + + >>> regex.findall(r"\w{2}", "abcd ef") + ['ab', 'cd', 'ef'] + >>> regex.findall(r"\G\w{2}", "abcd ef") + ['ab', 'cd'] + +* The search starts at position 0 and matches 'ab'. + +* The search continues at position 2 and matches 'cd'. + +* The search continues at position 4 and fails to match any letters. + +* The anchor stops the search start position from being advanced, so there are no more results. + +Reverse searching +^^^^^^^^^^^^^^^^^ + +Searches can also work backwards: + +.. sourcecode:: python + + >>> regex.findall(r".", "abc") + ['a', 'b', 'c'] + >>> regex.findall(r"(?r).", "abc") + ['c', 'b', 'a'] + +Note that the result of a reverse search is not necessarily the reverse of a forward search: + +.. sourcecode:: python + + >>> regex.findall(r"..", "abcde") + ['ab', 'cd'] + >>> regex.findall(r"(?r)..", "abcde") + ['de', 'bc'] + +Matching a single grapheme ``\X`` +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +The grapheme matcher is supported. It conforms to the Unicode specification at ``http://www.unicode.org/reports/tr29/``. + +Branch reset ``(?|...|...)`` +^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +Group numbers will be reused across the alternatives, but groups with different names will have different group numbers. + +.. sourcecode:: python + + >>> regex.match(r"(?|(first)|(second))", "first").groups() + ('first',) + >>> regex.match(r"(?|(first)|(second))", "second").groups() + ('second',) + +Note that there is only one group. + +Default Unicode word boundary +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +The ``WORD`` flag changes the definition of a 'word boundary' to that of a default Unicode word boundary. This applies to ``\b`` and ``\B``. + +Timeout +^^^^^^^ + +The matching methods and functions support timeouts. The timeout (in seconds) applies to the entire operation: + +.. sourcecode:: python + + >>> from time import sleep + >>> + >>> def fast_replace(m): + ... return 'X' + ... + >>> def slow_replace(m): + ... sleep(0.5) + ... return 'X' + ... + >>> regex.sub(r'[a-z]', fast_replace, 'abcde', timeout=2) + 'XXXXX' + >>> regex.sub(r'[a-z]', slow_replace, 'abcde', timeout=2) + Traceback (most recent call last): + File "", line 1, in + File "C:\Python310\lib\site-packages\regex\regex.py", line 278, in sub + return pat.sub(repl, string, count, pos, endpos, concurrent, timeout) + TimeoutError: regex timed out diff --git a/.venv/lib/python3.12/site-packages/regex-2026.9.10.dist-info/RECORD b/.venv/lib/python3.12/site-packages/regex-2026.9.10.dist-info/RECORD new file mode 100644 index 0000000000000000000000000000000000000000..9a01d054c8d4139745ca3b6726e52f6fe8cfd790 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/regex-2026.9.10.dist-info/RECORD @@ -0,0 +1,15 @@ +regex-2026.9.10.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4 +regex-2026.9.10.dist-info/METADATA,sha256=DqL6ABtlA4Ko2WgSUjCGWVXVWfvxvT1AZKZlBTYghn8,40564 +regex-2026.9.10.dist-info/RECORD,, +regex-2026.9.10.dist-info/WHEEL,sha256=eXYxUg5Kx9lvtuQM0-Xy0y45yuuc8CT0Zrq-N3e3wpY,190 +regex-2026.9.10.dist-info/licenses/LICENSE.txt,sha256=v_Ve9M3MjBTOJZ-OirYOJkQYRA1jNfTcE4Jz-9UGFE0,11584 +regex-2026.9.10.dist-info/top_level.txt,sha256=aQmiDMhNTF26cCK4_7D-qaVvhbxClG0wyCTnEhkzYBs,6 +regex/__init__.py,sha256=A5k0rm8Ln7HKsfG-8sEWYehek8zCKEe6sQW5QGUAmSU,75 +regex/__pycache__/__init__.cpython-312.pyc,, +regex/__pycache__/_main.cpython-312.pyc,, +regex/__pycache__/_regex_core.cpython-312.pyc,, +regex/_main.py,sha256=L_S4jQuBudVqY2C6LrX1d670mGV4B5XVm2nYJXke76k,33410 +regex/_regex.cpython-312-x86_64-linux-gnu.so,sha256=OyVtiAToEruarWrtT_YDeQV8OBELrVdB7oxgvWMJK-M,2581432 +regex/_regex_core.py,sha256=YE60YlNAIzbGY2LzLEogrwldO9C1UFUBtE5gd-kpUaI,147335 +regex/tests/__pycache__/test_regex.cpython-312.pyc,, +regex/tests/test_regex.py,sha256=iE4XOfiEpWrGKDUZISDxlxNi-Y0rX8KPH8yAwpMTLbI,225809 diff --git a/.venv/lib/python3.12/site-packages/regex-2026.9.10.dist-info/WHEEL b/.venv/lib/python3.12/site-packages/regex-2026.9.10.dist-info/WHEEL new file mode 100644 index 0000000000000000000000000000000000000000..0a4d0300062879d2c7e8ebd316e2fc3ba674f619 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/regex-2026.9.10.dist-info/WHEEL @@ -0,0 +1,7 @@ +Wheel-Version: 1.0 +Generator: setuptools (84.0.0) +Root-Is-Purelib: false +Tag: cp312-cp312-manylinux_2_17_x86_64 +Tag: cp312-cp312-manylinux2014_x86_64 +Tag: cp312-cp312-manylinux_2_28_x86_64 + diff --git a/.venv/lib/python3.12/site-packages/regex-2026.9.10.dist-info/licenses/LICENSE.txt b/.venv/lib/python3.12/site-packages/regex-2026.9.10.dist-info/licenses/LICENSE.txt new file mode 100644 index 0000000000000000000000000000000000000000..99c19cf844141395a87c34325da3a537f1e95815 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/regex-2026.9.10.dist-info/licenses/LICENSE.txt @@ -0,0 +1,208 @@ +This work was derived from the 're' module of CPython 2.6 and CPython 3.1, +copyright (c) 1998-2001 by Secret Labs AB and licensed under CNRI's Python 1.6 +license. + +All additions and alterations are licensed under the Apache 2.0 License. + + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright 2020 Matthew Barnett + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/.venv/lib/python3.12/site-packages/regex-2026.9.10.dist-info/top_level.txt b/.venv/lib/python3.12/site-packages/regex-2026.9.10.dist-info/top_level.txt new file mode 100644 index 0000000000000000000000000000000000000000..4f9256d62325c75de027d1cd48f1ff520117413e --- /dev/null +++ b/.venv/lib/python3.12/site-packages/regex-2026.9.10.dist-info/top_level.txt @@ -0,0 +1 @@ +regex diff --git a/.venv/lib/python3.12/site-packages/regex/__init__.py b/.venv/lib/python3.12/site-packages/regex/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..5ce0ad5ba85933c3b4a42ee019cf306c08042ba7 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/regex/__init__.py @@ -0,0 +1,3 @@ +import regex._main +from regex._main import * +__all__ = regex._main.__all__ diff --git a/.venv/lib/python3.12/site-packages/regex/__pycache__/__init__.cpython-312.pyc b/.venv/lib/python3.12/site-packages/regex/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6419d41f61f6e01d08a398f72124ebfa781b55a7 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/regex/__pycache__/__init__.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/regex/__pycache__/_main.cpython-312.pyc b/.venv/lib/python3.12/site-packages/regex/__pycache__/_main.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7162381fbf094c038bb5d82e055d2d1594ea8ff2 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/regex/__pycache__/_main.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/regex/__pycache__/_regex_core.cpython-312.pyc b/.venv/lib/python3.12/site-packages/regex/__pycache__/_regex_core.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..67cf23e7ebb02c31e61282315332cfd2eff569d1 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/regex/__pycache__/_regex_core.cpython-312.pyc @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:994e1732818126b60fae123f4b9c6ad4defc80c3d86a0be294c9803c0e5a9c60 +size 203350 diff --git a/.venv/lib/python3.12/site-packages/regex/_main.py b/.venv/lib/python3.12/site-packages/regex/_main.py new file mode 100644 index 0000000000000000000000000000000000000000..4fdfdc050c445bb502558da25ef08d3f58eb14e1 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/regex/_main.py @@ -0,0 +1,759 @@ +# +# Secret Labs' Regular Expression Engine +# +# Copyright (c) 1998-2001 by Secret Labs AB. All rights reserved. +# +# This version of the SRE library can be redistributed under CNRI's +# Python 1.6 license. For any other use, please contact Secret Labs +# AB (info@pythonware.com). +# +# Portions of this engine have been developed in cooperation with +# CNRI. Hewlett-Packard provided funding for 1.6 integration and +# other compatibility work. +# +# 2010-01-16 mrab Python front-end re-written and extended + +r"""Support for regular expressions (RE). + +This module provides regular expression matching operations similar to those +found in Perl. It supports both 8-bit and Unicode strings; both the pattern and +the strings being processed can contain null bytes and characters outside the +US ASCII range. + +Regular expressions can contain both special and ordinary characters. Most +ordinary characters, like "A", "a", or "0", are the simplest regular +expressions; they simply match themselves. You can concatenate ordinary +characters, so last matches the string 'last'. + +There are a few differences between the old (legacy) behaviour and the new +(enhanced) behaviour, which are indicated by VERSION0 or VERSION1. + +The special characters are: + "." Matches any character except a newline. + "^" Matches the start of the string. + "$" Matches the end of the string or just before the + newline at the end of the string. + "*" Matches 0 or more (greedy) repetitions of the preceding + RE. Greedy means that it will match as many repetitions + as possible. + "+" Matches 1 or more (greedy) repetitions of the preceding + RE. + "?" Matches 0 or 1 (greedy) of the preceding RE. + *?,+?,?? Non-greedy versions of the previous three special + characters. + *+,++,?+ Possessive versions of the previous three special + characters. + {m,n} Matches from m to n repetitions of the preceding RE. + {m,n}? Non-greedy version of the above. + {m,n}+ Possessive version of the above. + {...} Fuzzy matching constraints. + "\\" Either escapes special characters or signals a special + sequence. + [...] Indicates a set of characters. A "^" as the first + character indicates a complementing set. + "|" A|B, creates an RE that will match either A or B. + (...) Matches the RE inside the parentheses. The contents are + captured and can be retrieved or matched later in the + string. + (?flags-flags) VERSION1: Sets/clears the flags for the remainder of + the group or pattern; VERSION0: Sets the flags for the + entire pattern. + (?:...) Non-capturing version of regular parentheses. + (?>...) Atomic non-capturing version of regular parentheses. + (?flags-flags:...) Non-capturing version of regular parentheses with local + flags. + (?P...) The substring matched by the group is accessible by + name. + (?...) The substring matched by the group is accessible by + name. + (?P=name) Matches the text matched earlier by the group named + name. + (?#...) A comment; ignored. + (?=...) Matches if ... matches next, but doesn't consume the + string. + (?!...) Matches if ... doesn't match next. + (?<=...) Matches if preceded by .... + (? Matches the text matched by the group named name. + \G Matches the empty string, but only at the position where + the search started. + \h Matches horizontal whitespace. + \K Keeps only what follows for the entire match. + \L Named list. The list is provided as a keyword argument. + \m Matches the empty string, but only at the start of a word. + \M Matches the empty string, but only at the end of a word. + \n Matches the newline character. + \N{name} Matches the named character. + \p{name=value} Matches the character if its property has the specified + value. + \P{name=value} Matches the character if its property hasn't the specified + value. + \r Matches the carriage-return character. + \s Matches any whitespace character; equivalent to + [ \t\n\r\f\v]. + \S Matches any non-whitespace character; equivalent to [^\s]. + \t Matches the tab character. + \uXXXX Matches the Unicode codepoint with 4-digit hex code XXXX. + \UXXXXXXXX Matches the Unicode codepoint with 8-digit hex code + XXXXXXXX. + \v Matches the vertical tab character. + \w Matches any alphanumeric character; equivalent to + [a-zA-Z0-9_] when matching a bytestring or a Unicode string + with the ASCII flag, or the whole range of Unicode + alphanumeric characters (letters plus digits plus + underscore) when matching a Unicode string. With LOCALE, it + will match the set [0-9_] plus characters defined as + letters for the current locale. + \W Matches the complement of \w; equivalent to [^\w]. + \xXX Matches the character with 2-digit hex code XX. + \X Matches a grapheme. + \Z Matches only at the end of the string. + \z Matches only at the end of the string. Alias of \Z. + \\ Matches a literal backslash. + +This module exports the following functions: + match Match a regular expression pattern at the beginning of a string. + prefixmatch Match a regular expression pattern at the beginning of a string. + Alias of match. + fullmatch Match a regular expression pattern against all of a string. + search Search a string for the presence of a pattern. + sub Substitute occurrences of a pattern found in a string using a + template string. + subf Substitute occurrences of a pattern found in a string using a + format string. + subn Same as sub, but also return the number of substitutions made. + subfn Same as subf, but also return the number of substitutions made. + split Split a string by the occurrences of a pattern. VERSION1: will + split at zero-width match; VERSION0: won't split at zero-width + match. + splititer Return an iterator yielding the parts of a split string. + findall Find all occurrences of a pattern in a string. + finditer Return an iterator yielding a match object for each match. + compile Compile a pattern into a Pattern object. + purge Clear the regular expression cache. + escape Backslash all non-alphanumerics or special characters in a + string. + +Most of the functions support a concurrent parameter: if True, the GIL will be +released during matching, allowing other Python threads to run concurrently. If +the string changes during matching, the behaviour is undefined. This parameter +is not needed when working on the builtin (immutable) string classes. + +Some of the functions in this module take flags as optional parameters. Most of +these flags can also be set within an RE: + A a ASCII Make \w, \W, \b, \B, \d, and \D match the + corresponding ASCII character categories. Default + when matching a bytestring. + B b BESTMATCH Find the best fuzzy match (default is first). + D DEBUG Print the parsed pattern. + E e ENHANCEMATCH Attempt to improve the fit after finding the first + fuzzy match. + F f FULLCASE Use full case-folding when performing + case-insensitive matching in Unicode. + I i IGNORECASE Perform case-insensitive matching. + L L LOCALE Make \w, \W, \b, \B, \d, and \D dependent on the + current locale. (One byte per character only.) + M m MULTILINE "^" matches the beginning of lines (after a newline) + as well as the string. "$" matches the end of lines + (before a newline) as well as the end of the string. + P p POSIX Perform POSIX-standard matching (leftmost longest). + R r REVERSE Searches backwards. + S s DOTALL "." matches any character at all, including the + newline. + U u UNICODE Make \w, \W, \b, \B, \d, and \D dependent on the + Unicode locale. Default when matching a Unicode + string. + V0 V0 VERSION0 Turn on the old legacy behaviour. + V1 V1 VERSION1 Turn on the new enhanced behaviour. This flag + includes the FULLCASE flag. + W w WORD Make \b and \B work with default Unicode word breaks + and make ".", "^" and "$" work with Unicode line + breaks. + X x VERBOSE Ignore whitespace and comments for nicer looking REs. + +This module also defines an exception 'error'. + +""" + +# Public symbols. +__all__ = ["cache_all", "compile", "DEFAULT_VERSION", "escape", "findall", + "finditer", "fullmatch", "match", "prefixmatch", "purge", "search", "split", "splititer", + "sub", "subf", "subfn", "subn", "template", "Scanner", "A", "ASCII", "B", + "BESTMATCH", "D", "DEBUG", "E", "ENHANCEMATCH", "S", "DOTALL", "F", + "FULLCASE", "I", "IGNORECASE", "L", "LOCALE", "M", "MULTILINE", "P", "POSIX", + "R", "REVERSE", "T", "TEMPLATE", "U", "UNICODE", "V0", "VERSION0", "V1", + "VERSION1", "X", "VERBOSE", "W", "WORD", "error", "Regex", "__version__", + "__doc__", "RegexFlag"] + +__version__ = "2026.9.10" + +# -------------------------------------------------------------------- +# Public interface. + +def match(pattern, string, flags=0, pos=None, endpos=None, partial=False, + concurrent=None, timeout=None, ignore_unused=False, **kwargs): + """Try to apply the pattern at the start of the string, returning a match + object, or None if no match was found.""" + pat = _compile(pattern, flags, ignore_unused, kwargs, True) + return pat.match(string, pos, endpos, concurrent, partial, timeout) + +def prefixmatch(pattern, string, flags=0, pos=None, endpos=None, partial=False, + concurrent=None, timeout=None, ignore_unused=False, **kwargs): + """Try to apply the pattern at the start of the string, returning a match + object, or None if no match was found. Alias of match().""" + pat = _compile(pattern, flags, ignore_unused, kwargs, True) + return pat.match(string, pos, endpos, concurrent, partial, timeout) + +def fullmatch(pattern, string, flags=0, pos=None, endpos=None, partial=False, + concurrent=None, timeout=None, ignore_unused=False, **kwargs): + """Try to apply the pattern against all of the string, returning a match + object, or None if no match was found.""" + pat = _compile(pattern, flags, ignore_unused, kwargs, True) + return pat.fullmatch(string, pos, endpos, concurrent, partial, timeout) + +def search(pattern, string, flags=0, pos=None, endpos=None, partial=False, + concurrent=None, timeout=None, ignore_unused=False, **kwargs): + """Search through string looking for a match to the pattern, returning a + match object, or None if no match was found.""" + pat = _compile(pattern, flags, ignore_unused, kwargs, True) + return pat.search(string, pos, endpos, concurrent, partial, timeout) + +def sub(pattern, repl, string, count=0, flags=0, pos=None, endpos=None, + concurrent=None, timeout=None, ignore_unused=False, **kwargs): + """Return the string obtained by replacing the leftmost (or rightmost with a + reverse pattern) non-overlapping occurrences of the pattern in string by the + replacement repl. repl can be either a string or a callable; if a string, + backslash escapes in it are processed; if a callable, it's passed the match + object and must return a replacement string to be used.""" + pat = _compile(pattern, flags, ignore_unused, kwargs, True) + return pat.sub(repl, string, count, pos, endpos, concurrent, timeout) + +def subf(pattern, format, string, count=0, flags=0, pos=None, endpos=None, + concurrent=None, timeout=None, ignore_unused=False, **kwargs): + """Return the string obtained by replacing the leftmost (or rightmost with a + reverse pattern) non-overlapping occurrences of the pattern in string by the + replacement format. format can be either a string or a callable; if a string, + it's treated as a format string; if a callable, it's passed the match object + and must return a replacement string to be used.""" + pat = _compile(pattern, flags, ignore_unused, kwargs, True) + return pat.subf(format, string, count, pos, endpos, concurrent, timeout) + +def subn(pattern, repl, string, count=0, flags=0, pos=None, endpos=None, + concurrent=None, timeout=None, ignore_unused=False, **kwargs): + """Return a 2-tuple containing (new_string, number). new_string is the string + obtained by replacing the leftmost (or rightmost with a reverse pattern) + non-overlapping occurrences of the pattern in the source string by the + replacement repl. number is the number of substitutions that were made. repl + can be either a string or a callable; if a string, backslash escapes in it + are processed; if a callable, it's passed the match object and must return a + replacement string to be used.""" + pat = _compile(pattern, flags, ignore_unused, kwargs, True) + return pat.subn(repl, string, count, pos, endpos, concurrent, timeout) + +def subfn(pattern, format, string, count=0, flags=0, pos=None, endpos=None, + concurrent=None, timeout=None, ignore_unused=False, **kwargs): + """Return a 2-tuple containing (new_string, number). new_string is the string + obtained by replacing the leftmost (or rightmost with a reverse pattern) + non-overlapping occurrences of the pattern in the source string by the + replacement format. number is the number of substitutions that were made. format + can be either a string or a callable; if a string, it's treated as a format + string; if a callable, it's passed the match object and must return a + replacement string to be used.""" + pat = _compile(pattern, flags, ignore_unused, kwargs, True) + return pat.subfn(format, string, count, pos, endpos, concurrent, timeout) + +def split(pattern, string, maxsplit=0, flags=0, concurrent=None, timeout=None, + ignore_unused=False, **kwargs): + """Split the source string by the occurrences of the pattern, returning a + list containing the resulting substrings. If capturing parentheses are used + in pattern, then the text of all groups in the pattern are also returned as + part of the resulting list. If maxsplit is nonzero, at most maxsplit splits + occur, and the remainder of the string is returned as the final element of + the list.""" + pat = _compile(pattern, flags, ignore_unused, kwargs, True) + return pat.split(string, maxsplit, concurrent, timeout) + +def splititer(pattern, string, maxsplit=0, flags=0, concurrent=None, + timeout=None, ignore_unused=False, **kwargs): + "Return an iterator yielding the parts of a split string." + pat = _compile(pattern, flags, ignore_unused, kwargs, True) + return pat.splititer(string, maxsplit, concurrent, timeout) + +def findall(pattern, string, flags=0, pos=None, endpos=None, overlapped=False, + concurrent=None, timeout=None, ignore_unused=False, **kwargs): + """Return a list of all matches in the string. The matches may be overlapped + if overlapped is True. If one or more groups are present in the pattern, + return a list of groups; this will be a list of tuples if the pattern has + more than one group. Empty matches are included in the result.""" + pat = _compile(pattern, flags, ignore_unused, kwargs, True) + return pat.findall(string, pos, endpos, overlapped, concurrent, timeout) + +def finditer(pattern, string, flags=0, pos=None, endpos=None, overlapped=False, + partial=False, concurrent=None, timeout=None, ignore_unused=False, **kwargs): + """Return an iterator over all matches in the string. The matches may be + overlapped if overlapped is True. For each match, the iterator returns a + match object. Empty matches are included in the result.""" + pat = _compile(pattern, flags, ignore_unused, kwargs, True) + return pat.finditer(string, pos, endpos, overlapped, concurrent, partial, + timeout) + +def compile(pattern, flags=0, ignore_unused=False, cache_pattern=None, **kwargs): + "Compile a regular expression pattern, returning a pattern object." + if cache_pattern is None: + cache_pattern = _cache_all + return _compile(pattern, flags, ignore_unused, kwargs, cache_pattern) + +def purge(): + "Clear the regular expression cache" + with _cache_lock: + _cache.clear() + _locale_sensitive.clear() + +# Whether to cache all patterns. +_cache_all = True + +def cache_all(value=True): + """Sets whether to cache all patterns, even those are compiled explicitly. + Passing None has no effect, but returns the current setting.""" + global _cache_all + + if value is None: + return _cache_all + + _cache_all = value + +def template(pattern, flags=0): + "Compile a template pattern, returning a pattern object." + return _compile(pattern, flags | TEMPLATE, False, {}, False) + +def escape(pattern, special_only=True, literal_spaces=False): + """Escape a string for use as a literal in a pattern. If special_only is + True, escape only special characters, else escape all non-alphanumeric + characters. If literal_spaces is True, don't escape spaces.""" + # Convert it to Unicode. + if isinstance(pattern, bytes): + p = pattern.decode("latin-1") + else: + p = pattern + + s = [] + if special_only: + for c in p: + if c == " " and literal_spaces: + s.append(c) + elif c in _METACHARS or c.isspace(): + s.append("\\") + s.append(c) + else: + s.append(c) + else: + for c in p: + if c == " " and literal_spaces: + s.append(c) + elif c in _ALNUM: + s.append(c) + else: + s.append("\\") + s.append(c) + + r = "".join(s) + # Convert it back to bytes if necessary. + if isinstance(pattern, bytes): + r = r.encode("latin-1") + + return r + +# -------------------------------------------------------------------- +# Internals. + +from regex import _regex_core +from regex import _regex +from threading import RLock as _RLock +from locale import getpreferredencoding as _getpreferredencoding +from regex._regex_core import * +from regex._regex_core import (_ALL_VERSIONS, _ALL_ENCODINGS, _FirstSetError, + _UnscopedFlagSet, _check_group_features, _compile_firstset, + _compile_replacement, _flatten_code, _fold_case, _get_required_string, + _parse_pattern, _shrink_cache) +from regex._regex_core import (ALNUM as _ALNUM, Info as _Info, OP as _OP, Source + as _Source, Fuzzy as _Fuzzy) + +# Version 0 is the old behaviour, compatible with the original 're' module. +# Version 1 is the new behaviour, which differs slightly. + +DEFAULT_VERSION = RegexFlag.VERSION0 + +_METACHARS = frozenset("()[]{}?*+|^$\\.-#&~") + +_regex_core.DEFAULT_VERSION = DEFAULT_VERSION + +# Caches for the patterns and replacements. +_cache = {} +_cache_lock = _RLock() +_named_args = {} +_replacement_cache = {} +_locale_sensitive = {} + +# Maximum size of the cache. +_MAXCACHE = 500 +_MAXREPCACHE = 500 + +def _compile(pattern, flags, ignore_unused, kwargs, cache_it): + "Compiles a regular expression to a PatternObject." + + global DEFAULT_VERSION + try: + from regex import DEFAULT_VERSION + except ImportError: + pass + + # We won't bother to cache the pattern if we're debugging. + if (flags & DEBUG) != 0: + cache_it = False + + # What locale is this pattern using? + locale_key = (type(pattern), pattern) + if _locale_sensitive.get(locale_key, True) or (flags & LOCALE) != 0: + # This pattern is, or might be, locale-sensitive. + pattern_locale = _getpreferredencoding(False) + else: + # This pattern is definitely not locale-sensitive. + pattern_locale = None + + def complain_unused_args(): + if ignore_unused: + return + + # Complain about any unused keyword arguments, possibly resulting from a typo. + unused_kwargs = set(kwargs) - {k for k, v in args_needed} + if unused_kwargs: + any_one = next(iter(unused_kwargs)) + raise ValueError('unused keyword argument {!a}'.format(any_one)) + + if cache_it: + try: + # Do we know what keyword arguments are needed? + args_key = pattern, type(pattern), flags + args_needed = _named_args[args_key] + + # Are we being provided with its required keyword arguments? + args_supplied = set() + if args_needed: + for k, v in args_needed: + try: + args_supplied.add((k, frozenset(kwargs[k]))) + except KeyError: + raise error("missing named list: {!r}".format(k)) + + complain_unused_args() + + args_supplied = frozenset(args_supplied) + + # Have we already seen this regular expression and named list? + pattern_key = (pattern, type(pattern), flags, args_supplied, + DEFAULT_VERSION, pattern_locale) + return _cache[pattern_key] + except KeyError: + # It's a new pattern, or new named list for a known pattern. + pass + + # Guess the encoding from the class of the pattern string. + if isinstance(pattern, str): + guess_encoding = UNICODE + elif isinstance(pattern, bytes): + guess_encoding = ASCII + elif isinstance(pattern, Pattern): + if flags: + raise ValueError("cannot process flags argument with a compiled pattern") + + return pattern + else: + raise TypeError("first argument must be a string or compiled pattern") + + # Set the default version in the core code in case it has been changed. + _regex_core.DEFAULT_VERSION = DEFAULT_VERSION + + global_flags = flags + + while True: + caught_exception = None + try: + source = _Source(pattern) + info = _Info(global_flags, source.char_type, kwargs) + info.guess_encoding = guess_encoding + source.ignore_space = bool(info.flags & VERBOSE) + parsed = _parse_pattern(source, info) + break + except _UnscopedFlagSet: + # Remember the global flags for the next attempt. + global_flags = info.global_flags + except error as e: + caught_exception = e + + if caught_exception: + raise error(caught_exception.msg, caught_exception.pattern, + caught_exception.pos) + + if not source.at_end(): + raise error("unbalanced parenthesis", pattern, source.pos) + + # Check the global flags for conflicts. + version = (info.flags & _ALL_VERSIONS) or DEFAULT_VERSION + if version not in (0, VERSION0, VERSION1): + raise ValueError("VERSION0 and VERSION1 flags are mutually incompatible") + + if (info.flags & _ALL_ENCODINGS) not in (0, ASCII, LOCALE, UNICODE): + raise ValueError("ASCII, LOCALE and UNICODE flags are mutually incompatible") + + if isinstance(pattern, bytes) and (info.flags & UNICODE): + raise ValueError("cannot use UNICODE flag with a bytes pattern") + + if not (info.flags & _ALL_ENCODINGS): + if isinstance(pattern, str): + info.flags |= UNICODE + else: + info.flags |= ASCII + + reverse = bool(info.flags & REVERSE) + fuzzy = isinstance(parsed, _Fuzzy) + + # Remember whether this pattern as an inline locale flag. + _locale_sensitive[locale_key] = info.inline_locale + + # Fix the group references. + caught_exception = None + try: + parsed.fix_groups(pattern, reverse, False) + except error as e: + caught_exception = e + + if caught_exception: + raise error(caught_exception.msg, caught_exception.pattern, + caught_exception.pos) + + # Should we print the parsed pattern? + if flags & DEBUG: + parsed.dump(indent=0, reverse=reverse) + + # Optimise the parsed pattern. + parsed = parsed.optimise(info, reverse) + parsed = parsed.pack_characters(info) + + # Get the required string. + req_offset, req_chars, req_flags = _get_required_string(parsed, info.flags) + + # Build the named lists. + named_lists = {} + named_list_indexes = [None] * len(info.named_lists_used) + args_needed = set() + for key, index in info.named_lists_used.items(): + name, case_flags = key + values = frozenset(kwargs[name]) + if case_flags: + items = frozenset(_fold_case(info, v) for v in values) + else: + items = values + named_lists[name] = values + named_list_indexes[index] = items + args_needed.add((name, values)) + + complain_unused_args() + + # Check the features of the groups. + _check_group_features(info, parsed) + + # Compile the parsed pattern. The result is a list of tuples. + code = parsed.compile(reverse) + + # Is there a group call to the pattern as a whole? + key = (0, reverse, fuzzy) + ref = info.call_refs.get(key) + if ref is not None: + code = [(_OP.CALL_REF, ref)] + code + [(_OP.END, )] + + # Add the final 'success' opcode. + code += [(_OP.SUCCESS, )] + + # Compile the additional copies of the groups that we need. + for group, rev, fuz in info.additional_groups: + code += group.compile(rev, fuz) + + # Flatten the code into a list of ints. + code = _flatten_code(code) + + if not parsed.has_simple_start(): + # Get the first set, if possible. + try: + fs_code = _compile_firstset(info, parsed.get_firstset(reverse)) + fs_code = _flatten_code(fs_code) + code = fs_code + code + except _FirstSetError: + pass + + # The named capture groups. + index_group = dict((v, n) for n, v in info.group_index.items()) + + # Create the PatternObject. + # + # Local flags like IGNORECASE affect the code generation, but aren't needed + # by the PatternObject itself. Conversely, global flags like LOCALE _don't_ + # affect the code generation but _are_ needed by the PatternObject. + compiled_pattern = _regex.compile(pattern, info.flags | version, code, + info.group_index, index_group, named_lists, named_list_indexes, + req_offset, req_chars, req_flags, info.group_count) + + # Do we need to reduce the size of the cache? + if len(_cache) >= _MAXCACHE: + with _cache_lock: + _shrink_cache(_cache, _named_args, _locale_sensitive, _MAXCACHE) + + if cache_it: + if (info.flags & LOCALE) == 0: + pattern_locale = None + + args_needed = frozenset(args_needed) + + # Store this regular expression and named list. + pattern_key = (pattern, type(pattern), flags, args_needed, + DEFAULT_VERSION, pattern_locale) + + with _cache_lock: + _cache[pattern_key] = compiled_pattern + + # Store what keyword arguments are needed. + _named_args[args_key] = args_needed + + return compiled_pattern + +def _compile_replacement_helper(pattern, template): + "Compiles a replacement template." + # This function is called by the _regex module. + + # Have we seen this before? + key = pattern.pattern, pattern.flags, template + compiled = _replacement_cache.get(key) + if compiled is not None: + return compiled + + if len(_replacement_cache) >= _MAXREPCACHE: + _replacement_cache.clear() + + is_unicode = isinstance(template, str) + source = _Source(template) + if is_unicode: + def make_string(char_codes): + return "".join(chr(c) for c in char_codes) + else: + def make_string(char_codes): + return bytes(char_codes) + + compiled = [] + literal = [] + while True: + ch = source.get() + if not ch: + break + if ch == "\\": + # '_compile_replacement' will return either an int group reference + # or a string literal. It returns items (plural) in order to handle + # a 2-character literal (an invalid escape sequence). + is_group, items = _compile_replacement(source, pattern, is_unicode) + if is_group: + # It's a group, so first flush the literal. + if literal: + compiled.append(make_string(literal)) + literal = [] + compiled.extend(items) + else: + literal.extend(items) + else: + literal.append(ord(ch)) + + # Flush the literal. + if literal: + compiled.append(make_string(literal)) + + _replacement_cache[key] = compiled + + return compiled + +# We define Pattern here after all the support objects have been defined. +_pat = _compile('', 0, False, {}, False) +Pattern = type(_pat) +Match = type(_pat.match('')) +del _pat + +# Make Pattern public for typing annotations. +__all__.append("Pattern") +__all__.append("Match") + +# We'll define an alias for the 'compile' function so that the repr of a +# pattern object is eval-able. +Regex = compile + +# Register myself for pickling. +import copyreg as _copy_reg + +def _pickle(pattern): + return _regex.compile, pattern._pickled_data + +_copy_reg.pickle(Pattern, _pickle) diff --git a/.venv/lib/python3.12/site-packages/regex/_regex.cpython-312-x86_64-linux-gnu.so b/.venv/lib/python3.12/site-packages/regex/_regex.cpython-312-x86_64-linux-gnu.so new file mode 100644 index 0000000000000000000000000000000000000000..48e306f76fb1bdcf38e21c41eec4f966f4c4a380 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/regex/_regex.cpython-312-x86_64-linux-gnu.so @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:3b256d8804e812bb9aad6aed4ff60379057c38110bad5741ee8c60bd63092be3 +size 2581432 diff --git a/.venv/lib/python3.12/site-packages/regex/_regex_core.py b/.venv/lib/python3.12/site-packages/regex/_regex_core.py new file mode 100644 index 0000000000000000000000000000000000000000..60678919c2a774a2a8a6d0701bfd79b17e4d4ac8 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/regex/_regex_core.py @@ -0,0 +1,4675 @@ +# +# Secret Labs' Regular Expression Engine core module +# +# Copyright (c) 1998-2001 by Secret Labs AB. All rights reserved. +# +# This version of the SRE library can be redistributed under CNRI's +# Python 1.6 license. For any other use, please contact Secret Labs +# AB (info@pythonware.com). +# +# Portions of this engine have been developed in cooperation with +# CNRI. Hewlett-Packard provided funding for 1.6 integration and +# other compatibility work. +# +# 2010-01-16 mrab Python front-end re-written and extended + +import enum +import string +import unicodedata +from collections import defaultdict + +from regex import _regex + +__all__ = ["A", "ASCII", "B", "BESTMATCH", "D", "DEBUG", "E", "ENHANCEMATCH", + "F", "FULLCASE", "I", "IGNORECASE", "L", "LOCALE", "M", "MULTILINE", "P", + "POSIX", "R", "REVERSE", "S", "DOTALL", "T", "TEMPLATE", "U", "UNICODE", + "V0", "VERSION0", "V1", "VERSION1", "W", "WORD", "X", "VERBOSE", "error", + "Scanner", "RegexFlag"] + +# The regex exception. +class error(Exception): + """Exception raised for invalid regular expressions. + + Attributes: + + msg: The unformatted error message + pattern: The regular expression pattern + pos: The position in the pattern where compilation failed, or None + lineno: The line number where compilation failed, unless pos is None + colno: The column number where compilation failed, unless pos is None + """ + + def __init__(self, message, pattern=None, pos=None): + newline = '\n' if isinstance(pattern, str) else b'\n' + self.msg = message + self.pattern = pattern + self.pos = pos + if pattern is not None and pos is not None: + self.lineno = pattern.count(newline, 0, pos) + 1 + self.colno = pos - pattern.rfind(newline, 0, pos) + + message = "{} at position {}".format(message, pos) + + if newline in pattern: + message += " (line {}, column {})".format(self.lineno, + self.colno) + + Exception.__init__(self, message) + +# The exception for when a positional flag has been turned on in the old +# behaviour. +class _UnscopedFlagSet(Exception): + pass + +# The exception for when parsing fails and we want to try something else. +class ParseError(Exception): + pass + +# The exception for when there isn't a valid first set. +class _FirstSetError(Exception): + pass + +# Flags. +class RegexFlag(enum.IntFlag): + A = ASCII = 0x80 # Assume ASCII locale. + B = BESTMATCH = 0x1000 # Best fuzzy match. + D = DEBUG = 0x200 # Print parsed pattern. + E = ENHANCEMATCH = 0x8000 # Attempt to improve the fit after finding the first + # fuzzy match. + F = FULLCASE = 0x4000 # Unicode full case-folding. + I = IGNORECASE = 0x2 # Ignore case. + L = LOCALE = 0x4 # Assume current 8-bit locale. + M = MULTILINE = 0x8 # Make anchors look for newline. + P = POSIX = 0x10000 # POSIX-style matching (leftmost longest). + R = REVERSE = 0x400 # Search backwards. + S = DOTALL = 0x10 # Make dot match newline. + U = UNICODE = 0x20 # Assume Unicode locale. + V0 = VERSION0 = 0x2000 # Old legacy behaviour. + V1 = VERSION1 = 0x100 # New enhanced behaviour. + W = WORD = 0x800 # Default Unicode word breaks. + X = VERBOSE = 0x40 # Ignore whitespace and comments. + T = TEMPLATE = 0x1 # Template (present because re module has it). + + def __repr__(self): + if self._name_ is not None: + return 'regex.%s' % self._name_ + + value = self._value_ + members = [] + negative = value < 0 + + if negative: + value = ~value + + for m in self.__class__: + if value & m._value_: + value &= ~m._value_ + members.append('regex.%s' % m._name_) + + if value: + members.append(hex(value)) + + res = '|'.join(members) + + if negative: + if len(members) > 1: + res = '~(%s)' % res + else: + res = '~%s' % res + + return res + + __str__ = object.__str__ + +# Put the flags into the module namespace. Being explicit here helps tools like +# linters and IDEs understand the code better. +ASCII = RegexFlag.ASCII +BESTMATCH = RegexFlag.BESTMATCH +DEBUG = RegexFlag.DEBUG +DOTALL = RegexFlag.DOTALL +ENHANCEMATCH = RegexFlag.ENHANCEMATCH +FULLCASE = RegexFlag.FULLCASE +IGNORECASE = RegexFlag.IGNORECASE +LOCALE = RegexFlag.LOCALE +MULTILINE = RegexFlag.MULTILINE +POSIX = RegexFlag.POSIX +REVERSE = RegexFlag.REVERSE +TEMPLATE = RegexFlag.TEMPLATE +UNICODE = RegexFlag.UNICODE +VERBOSE = RegexFlag.VERBOSE +VERSION0 = RegexFlag.VERSION0 +VERSION1 = RegexFlag.VERSION1 +WORD = RegexFlag.WORD +A = RegexFlag.A +B = RegexFlag.B +D = RegexFlag.D +E = RegexFlag.E +F = RegexFlag.F +I = RegexFlag.I +L = RegexFlag.L +M = RegexFlag.M +P = RegexFlag.P +R = RegexFlag.R +S = RegexFlag.S +U = RegexFlag.U +V0 = RegexFlag.V0 +V1 = RegexFlag.V1 +W = RegexFlag.W +X = RegexFlag.X +T = RegexFlag.T + +DEFAULT_VERSION = VERSION1 + +_ALL_VERSIONS = VERSION0 | VERSION1 +_ALL_ENCODINGS = ASCII | LOCALE | UNICODE + +# The default flags for the various versions. +DEFAULT_FLAGS = {VERSION0: 0, VERSION1: FULLCASE} + +# The mask for the flags. +GLOBAL_FLAGS = (_ALL_VERSIONS | BESTMATCH | DEBUG | ENHANCEMATCH | POSIX | + REVERSE) +SCOPED_FLAGS = (FULLCASE | IGNORECASE | MULTILINE | DOTALL | WORD | VERBOSE | + _ALL_ENCODINGS) + +ALPHA = frozenset(string.ascii_letters) +DIGITS = frozenset(string.digits) +ALNUM = ALPHA | DIGITS +OCT_DIGITS = frozenset(string.octdigits) +HEX_DIGITS = frozenset(string.hexdigits) +SPECIAL_CHARS = frozenset("()|?*+{^$.[\\#") | frozenset([""]) +NAMED_CHAR_PART = ALNUM | frozenset(" -") +PROPERTY_NAME_PART = ALNUM | frozenset(" &_-.") +SET_OPS = ("||", "~~", "&&", "--") + +# The width of the code words inside the regex engine. +BYTES_PER_CODE = _regex.get_code_size() +BITS_PER_CODE = BYTES_PER_CODE * 8 + +# The repeat count which represents infinity. +UNLIMITED = (1 << BITS_PER_CODE) - 1 + +# The regular expression flags. +REGEX_FLAGS = {"a": ASCII, "b": BESTMATCH, "e": ENHANCEMATCH, "f": FULLCASE, + "i": IGNORECASE, "L": LOCALE, "m": MULTILINE, "p": POSIX, "r": REVERSE, + "s": DOTALL, "u": UNICODE, "V0": VERSION0, "V1": VERSION1, "w": WORD, "x": + VERBOSE} + +# The case flags. +CASE_FLAGS = FULLCASE | IGNORECASE +NOCASE = 0 +FULLIGNORECASE = FULLCASE | IGNORECASE + +FULL_CASE_FOLDING = UNICODE | FULLIGNORECASE + +CASE_FLAGS_COMBINATIONS = {0: 0, FULLCASE: 0, IGNORECASE: IGNORECASE, + FULLIGNORECASE: FULLIGNORECASE} + +# The number of digits in hexadecimal escapes. +HEX_ESCAPES = {"x": 2, "u": 4, "U": 8} + +# The names of the opcodes. +OPCODES = """ +FAILURE +SUCCESS +ANY +ANY_ALL +ANY_ALL_REV +ANY_REV +ANY_U +ANY_U_REV +ATOMIC +BOUNDARY +BRANCH +CALL_REF +CHARACTER +CHARACTER_IGN +CHARACTER_IGN_REV +CHARACTER_REV +CONDITIONAL +DEFAULT_BOUNDARY +DEFAULT_END_OF_WORD +DEFAULT_START_OF_WORD +END +END_OF_LINE +END_OF_LINE_U +END_OF_STRING +END_OF_STRING_LINE +END_OF_STRING_LINE_U +END_OF_WORD +FUZZY +GRAPHEME_BOUNDARY +GREEDY_REPEAT +GROUP +GROUP_CALL +GROUP_EXISTS +KEEP +LAZY_REPEAT +LOOKAROUND +NEXT +PROPERTY +PROPERTY_IGN +PROPERTY_IGN_REV +PROPERTY_REV +PRUNE +RANGE +RANGE_IGN +RANGE_IGN_REV +RANGE_REV +REF_GROUP +REF_GROUP_FLD +REF_GROUP_FLD_REV +REF_GROUP_IGN +REF_GROUP_IGN_REV +REF_GROUP_REV +SEARCH_ANCHOR +SET_DIFF +SET_DIFF_IGN +SET_DIFF_IGN_REV +SET_DIFF_REV +SET_INTER +SET_INTER_IGN +SET_INTER_IGN_REV +SET_INTER_REV +SET_SYM_DIFF +SET_SYM_DIFF_IGN +SET_SYM_DIFF_IGN_REV +SET_SYM_DIFF_REV +SET_UNION +SET_UNION_IGN +SET_UNION_IGN_REV +SET_UNION_REV +SKIP +START_OF_LINE +START_OF_LINE_U +START_OF_STRING +START_OF_WORD +STRING +STRING_FLD +STRING_FLD_REV +STRING_IGN +STRING_IGN_REV +STRING_REV +FUZZY_EXT +""" + +# Define the opcodes in a namespace. +class Namespace: + pass + +OP = Namespace() +for i, op in enumerate(OPCODES.split()): + setattr(OP, op, i) + +def _shrink_cache(cache_dict, args_dict, locale_sensitive, max_length, divisor=5): + """Make room in the given cache. + + Args: + cache_dict: The cache dictionary to modify. + args_dict: The dictionary of named list args used by patterns. + max_length: Maximum # of entries in cache_dict before it is shrunk. + divisor: Cache will shrink to max_length - 1/divisor*max_length items. + """ + # Toss out a fraction of the entries at random to make room for new ones. + # A random algorithm was chosen as opposed to simply cache_dict.popitem() + # as popitem could penalize the same regular expression repeatedly based + # on its internal hash value. Being random should spread the cache miss + # love around. + cache_keys = tuple(cache_dict.keys()) + overage = len(cache_keys) - max_length + if overage < 0: + # Cache is already within limits. Normally this should not happen + # but it could due to multithreading. + return + + number_to_toss = max_length // divisor + overage + + # The import is done here to avoid a circular dependency. + import random + if not hasattr(random, 'sample'): + # Do nothing while resolving the circular dependency: + # re->random->warnings->tokenize->string->re + return + + for doomed_key in random.sample(cache_keys, number_to_toss): + try: + del cache_dict[doomed_key] + except KeyError: + # Ignore problems if the cache changed from another thread. + pass + + # Rebuild the arguments and locale-sensitivity dictionaries. + args_dict.clear() + sensitivity_dict = {} + for pattern, pattern_type, flags, args, default_version, locale in tuple(cache_dict): + args_dict[pattern, pattern_type, flags, default_version, locale] = args + try: + sensitivity_dict[pattern_type, pattern] = locale_sensitive[pattern_type, pattern] + except KeyError: + pass + + locale_sensitive.clear() + locale_sensitive.update(sensitivity_dict) + +def _fold_case(info, string): + "Folds the case of a string." + flags = info.flags + if (flags & _ALL_ENCODINGS) == 0: + flags |= info.guess_encoding + + return _regex.fold_case(flags, string) + +def is_cased_i(info, char): + "Checks whether a character is cased." + return len(_regex.get_all_cases(info.flags, char)) > 1 + +def is_cased_f(flags, char): + "Checks whether a character is cased." + return len(_regex.get_all_cases(flags, char)) > 1 + +def _compile_firstset(info, fs): + "Compiles the firstset for the pattern." + reverse = bool(info.flags & REVERSE) + fs = _check_firstset(info, reverse, fs) + if not fs or isinstance(fs, AnyAll): + return [] + + # Compile the firstset. + return fs.compile(reverse) + +def _check_firstset(info, reverse, fs): + "Checks the firstset for the pattern." + if not fs or None in fs: + return None + + # If we ignore the case, for simplicity we won't build a firstset. + members = set() + case_flags = NOCASE + for i in fs: + if isinstance(i, Character) and not i.positive: + return None + +# if i.case_flags: +# if isinstance(i, Character): +# if is_cased_i(info, i.value): +# return [] +# elif isinstance(i, SetBase): +# return [] + case_flags |= i.case_flags + members.add(i.with_flags(case_flags=NOCASE)) + + if case_flags == (FULLCASE | IGNORECASE): + return None + + # Build the firstset. + fs = SetUnion(info, list(members), case_flags=case_flags & ~FULLCASE, + zerowidth=True) + fs = fs.optimise(info, reverse, in_set=True) + + return fs + +def _flatten_code(code): + "Flattens the code from a list of tuples." + flat_code = [] + for c in code: + flat_code.extend(c) + + return flat_code + +def make_case_flags(info): + "Makes the case flags." + flags = info.flags & CASE_FLAGS + + # Turn off FULLCASE if ASCII is turned on. + if info.flags & ASCII: + flags &= ~FULLCASE + + return flags + +def make_character(info, value, in_set=False): + "Makes a character literal." + if in_set: + # A character set is built case-sensitively. + return Character(value) + + return Character(value, case_flags=make_case_flags(info)) + +def make_ref_group(info, name, position): + "Makes a group reference." + return RefGroup(info, name, position, case_flags=make_case_flags(info)) + +def make_string_set(info, name): + "Makes a string set." + return StringSet(info, name, case_flags=make_case_flags(info)) + +def make_property(info, prop, in_set): + "Makes a property." + if in_set: + return prop + + return prop.with_flags(case_flags=make_case_flags(info)) + +def _parse_pattern(source, info): + "Parses a pattern, eg. 'a|b|c'." + branches = [parse_sequence(source, info)] + while source.match("|"): + branches.append(parse_sequence(source, info)) + + if len(branches) == 1: + return branches[0] + return Branch(branches) + +def parse_sequence(source, info): + "Parses a sequence, eg. 'abc'." + sequence = [None] + case_flags = make_case_flags(info) + while True: + saved_pos = source.pos + ch = source.get() + if ch in SPECIAL_CHARS: + if ch in ")|": + # The end of a sequence. At the end of the pattern ch is "". + source.pos = saved_pos + break + elif ch == "\\": + # An escape sequence outside a set. + sequence.append(parse_escape(source, info, False)) + elif ch == "(": + # A parenthesised subpattern or a flag. + element = parse_paren(source, info) + if element is None: + case_flags = make_case_flags(info) + else: + sequence.append(element) + elif ch == ".": + # Any character. + if info.flags & DOTALL: + sequence.append(AnyAll()) + elif info.flags & WORD: + sequence.append(AnyU()) + else: + sequence.append(Any()) + elif ch == "[": + # A character set. + sequence.append(parse_set(source, info)) + elif ch == "^": + # The start of a line or the string. + if info.flags & MULTILINE: + if info.flags & WORD: + sequence.append(StartOfLineU()) + else: + sequence.append(StartOfLine()) + else: + sequence.append(StartOfString()) + elif ch == "$": + # The end of a line or the string. + if info.flags & MULTILINE: + if info.flags & WORD: + sequence.append(EndOfLineU()) + else: + sequence.append(EndOfLine()) + else: + if info.flags & WORD: + sequence.append(EndOfStringLineU()) + else: + sequence.append(EndOfStringLine()) + elif ch in "?*+{": + # Looks like a quantifier. + counts = parse_quantifier(source, info, ch) + if counts: + # It _is_ a quantifier. + apply_quantifier(source, info, counts, case_flags, ch, + saved_pos, sequence) + sequence.append(None) + else: + # It's not a quantifier. Maybe it's a fuzzy constraint. + constraints = parse_fuzzy(source, info, ch, case_flags) + + if constraints: + # It _is_ a fuzzy constraint. + if is_actually_fuzzy(constraints): + apply_constraint(source, info, constraints, case_flags, + saved_pos, sequence) + sequence.append(None) + else: + # The element was just a literal. + sequence.append(Character(ord(ch), + case_flags=case_flags)) + else: + # A literal. + sequence.append(Character(ord(ch), case_flags=case_flags)) + else: + # A literal. + sequence.append(Character(ord(ch), case_flags=case_flags)) + + sequence = [item for item in sequence if item is not None] + return Sequence(sequence) + +def is_actually_fuzzy(constraints): + "Checks whether a fuzzy constraint is actually fuzzy." + if constraints.get("e") == (0, 0): + return False + + if (constraints.get("s"), constraints.get("i"), constraints.get("d")) == ((0, 0), (0, 0), (0, 0)): + return False + + return True + +def apply_quantifier(source, info, counts, case_flags, ch, saved_pos, + sequence): + element = sequence.pop() + if element is None: + if sequence: + raise error("multiple repeat", source.string, saved_pos) + raise error("nothing to repeat", source.string, saved_pos) + + if isinstance(element, (GreedyRepeat, LazyRepeat, PossessiveRepeat)): + raise error("multiple repeat", source.string, saved_pos) + + min_count, max_count = counts + saved_pos = source.pos + ch = source.get() + if ch == "?": + # The "?" suffix that means it's a lazy repeat. + repeated = LazyRepeat + elif ch == "+": + # The "+" suffix that means it's a possessive repeat. + repeated = PossessiveRepeat + else: + # No suffix means that it's a greedy repeat. + source.pos = saved_pos + repeated = GreedyRepeat + + # Ignore the quantifier if it applies to a zero-width item or the number of + # repeats is fixed at 1. + if not element.is_empty() and (min_count != 1 or max_count != 1): + element = repeated(element, min_count, max_count) + + sequence.append(element) + +def apply_constraint(source, info, constraints, case_flags, saved_pos, + sequence): + element = sequence.pop() + if element is None: + raise error("nothing for fuzzy constraint", source.string, saved_pos) + + # If a group is marked as fuzzy then put all of the fuzzy part in the + # group. + if isinstance(element, Group): + element.subpattern = Fuzzy(element.subpattern, constraints) + sequence.append(element) + else: + sequence.append(Fuzzy(element, constraints)) + +_QUANTIFIERS = {"?": (0, 1), "*": (0, None), "+": (1, None)} + +def parse_quantifier(source, info, ch): + "Parses a quantifier." + q = _QUANTIFIERS.get(ch) + if q: + # It's a quantifier. + return q + + if ch == "{": + # Looks like a limited repeated element, eg. 'a{2,3}'. + counts = parse_limited_quantifier(source) + if counts: + return counts + + return None + +def is_above_limit(count): + "Checks whether a count is above the maximum." + return count is not None and count >= UNLIMITED + +def parse_limited_quantifier(source): + "Parses a limited quantifier." + saved_pos = source.pos + min_count = parse_count(source) + if source.match(","): + max_count = parse_count(source) + + # No minimum means 0 and no maximum means unlimited. + min_count = int(min_count or 0) + max_count = int(max_count) if max_count else None + else: + if not min_count: + source.pos = saved_pos + return None + + min_count = max_count = int(min_count) + + if not source.match ("}"): + source.pos = saved_pos + return None + + if is_above_limit(min_count) or is_above_limit(max_count): + raise error("repeat count too big", source.string, saved_pos) + + if max_count is not None and min_count > max_count: + raise error("min repeat greater than max repeat", source.string, + saved_pos) + + return min_count, max_count + +def parse_fuzzy(source, info, ch, case_flags): + "Parses a fuzzy setting, if present." + saved_pos = source.pos + + if ch != "{": + return None + + constraints = {} + try: + parse_fuzzy_item(source, constraints) + while source.match(","): + parse_fuzzy_item(source, constraints) + except ParseError: + source.pos = saved_pos + return None + + if source.match(":"): + constraints["test"] = parse_fuzzy_test(source, info, case_flags) + + if not source.match("}"): + raise error("expected }", source.string, source.pos) + + return constraints + +def parse_fuzzy_item(source, constraints): + "Parses a fuzzy setting item." + saved_pos = source.pos + try: + parse_cost_constraint(source, constraints) + except ParseError: + source.pos = saved_pos + + parse_cost_equation(source, constraints) + +def parse_cost_constraint(source, constraints): + "Parses a cost constraint." + saved_pos = source.pos + ch = source.get() + if ch in ALPHA: + # Syntax: constraint [("<=" | "<") cost] + constraint = parse_constraint(source, constraints, ch) + + max_inc = parse_fuzzy_compare(source) + + if max_inc is None: + # No maximum cost. + constraints[constraint] = 0, None + else: + # There's a maximum cost. + cost_pos = source.pos + max_cost = parse_cost_limit(source) + + # Inclusive or exclusive limit? + if not max_inc: + max_cost -= 1 + + if max_cost < 0: + raise error("bad fuzzy cost limit", source.string, cost_pos) + + constraints[constraint] = 0, max_cost + elif ch in DIGITS: + # Syntax: cost ("<=" | "<") constraint ("<=" | "<") cost + source.pos = saved_pos + + # Minimum cost. + cost_pos = source.pos + min_cost = parse_cost_limit(source) + + min_inc = parse_fuzzy_compare(source) + if min_inc is None: + raise ParseError() + + constraint = parse_constraint(source, constraints, source.get()) + + max_inc = parse_fuzzy_compare(source) + if max_inc is None: + raise ParseError() + + # Maximum cost. + cost_pos = source.pos + max_cost = parse_cost_limit(source) + + # Inclusive or exclusive limits? + if not min_inc: + min_cost += 1 + if not max_inc: + max_cost -= 1 + + if not 0 <= min_cost <= max_cost: + raise error("bad fuzzy cost limit", source.string, cost_pos) + + constraints[constraint] = min_cost, max_cost + else: + raise ParseError() + +def parse_cost_limit(source): + "Parses a cost limit." + cost_pos = source.pos + digits = parse_count(source) + + try: + return int(digits) + except ValueError: + pass + + raise error("bad fuzzy cost limit", source.string, cost_pos) + +def parse_constraint(source, constraints, ch): + "Parses a constraint." + if ch not in "deis": + raise ParseError() + + if ch in constraints: + raise ParseError() + + return ch + +def parse_fuzzy_compare(source): + "Parses a cost comparator." + if source.match("<="): + return True + elif source.match("<"): + return False + else: + return None + +def parse_cost_equation(source, constraints): + "Parses a cost equation." + if "cost" in constraints: + raise error("more than one cost equation", source.string, source.pos) + + cost = {} + + parse_cost_term(source, cost) + while source.match("+"): + parse_cost_term(source, cost) + + max_inc = parse_fuzzy_compare(source) + if max_inc is None: + raise ParseError() + + max_cost = int(parse_count(source)) + + if not max_inc: + max_cost -= 1 + + if max_cost < 0: + raise error("bad fuzzy cost limit", source.string, source.pos) + + cost["max"] = max_cost + + constraints["cost"] = cost + +def parse_cost_term(source, cost): + "Parses a cost equation term." + coeff = parse_count(source) + ch = source.get() + if ch not in "dis": + raise ParseError() + + if ch in cost: + raise error("repeated fuzzy cost", source.string, source.pos) + + cost[ch] = int(coeff or 1) + +def parse_fuzzy_test(source, info, case_flags): + saved_pos = source.pos + ch = source.get() + if ch in SPECIAL_CHARS: + if ch == "\\": + # An escape sequence outside a set. + return parse_escape(source, info, False) + elif ch == ".": + # Any character. + if info.flags & DOTALL: + return AnyAll() + elif info.flags & WORD: + return AnyU() + else: + return Any() + elif ch == "[": + # A character set. + return parse_set(source, info) + else: + raise error("expected character set", source.string, saved_pos) + elif ch: + # A literal. + return Character(ord(ch), case_flags=case_flags) + else: + raise error("expected character set", source.string, saved_pos) + +def parse_count(source): + "Parses a quantifier's count, which can be empty." + return source.get_while(DIGITS) + +def parse_paren(source, info): + """Parses a parenthesised subpattern or a flag. Returns FLAGS if it's an + inline flag. + """ + saved_pos = source.pos + ch = source.get(True) + if ch == "?": + # (?... + saved_pos_2 = source.pos + ch = source.get(True) + if ch == "<": + # (?<... + saved_pos_3 = source.pos + ch = source.get() + if ch in ("=", "!"): + # (?<=... or (?") + saved_flags = info.flags + try: + subpattern = _parse_pattern(source, info) + source.expect(")") + finally: + info.flags = saved_flags + source.ignore_space = bool(info.flags & VERBOSE) + + info.close_group() + return Group(info, group, subpattern) + if ch in ("=", "!"): + # (?=... or (?!...: lookahead. + return parse_lookaround(source, info, False, ch == "=") + if ch == "P": + # (?P...: a Python extension. + return parse_extension(source, info) + if ch == "#": + # (?#...: a comment. + return parse_comment(source) + if ch == "(": + # (?(...: a conditional subpattern. + return parse_conditional(source, info) + if ch == ">": + # (?>...: an atomic subpattern. + return parse_atomic(source, info) + if ch == "|": + # (?|...: a common/reset groups branch. + return parse_common(source, info) + if ch == "R" or "0" <= ch <= "9": + # (?R...: probably a call to a group. + return parse_call_group(source, info, ch, saved_pos_2) + if ch == "&": + # (?&...: a call to a named group. + return parse_call_named_group(source, info, saved_pos_2) + if (ch == "+" or ch == "-") and source.peek() in DIGITS: + return parse_rel_call_group(source, info, ch, saved_pos_2) + + # (?...: probably a flags subpattern. + source.pos = saved_pos_2 + return parse_flags_subpattern(source, info) + + if ch == "*": + # (*... + saved_pos_2 = source.pos + word = source.get_while(set(")>"), include=False) + if word[ : 1].isalpha(): + verb = VERBS.get(word) + if not verb: + raise error("unknown verb", source.string, saved_pos_2) + + source.expect(")") + + return verb + + # (...: an unnamed capture group. + source.pos = saved_pos + group = info.open_group() + saved_flags = info.flags + try: + subpattern = _parse_pattern(source, info) + source.expect(")") + finally: + info.flags = saved_flags + source.ignore_space = bool(info.flags & VERBOSE) + + info.close_group() + + return Group(info, group, subpattern) + +def parse_extension(source, info): + "Parses a Python extension." + saved_pos = source.pos + ch = source.get() + if ch == "<": + # (?P<...: a named capture group. + name = parse_name(source) + group = info.open_group(name) + source.expect(">") + saved_flags = info.flags + try: + subpattern = _parse_pattern(source, info) + source.expect(")") + finally: + info.flags = saved_flags + source.ignore_space = bool(info.flags & VERBOSE) + + info.close_group() + + return Group(info, group, subpattern) + if ch == "=": + # (?P=...: a named group reference. + name = parse_name(source, allow_numeric=True) + source.expect(")") + if info.is_open_group(name): + raise error("cannot refer to an open group", source.string, + saved_pos) + + return make_ref_group(info, name, saved_pos) + if ch == ">" or ch == "&": + # (?P>...: a call to a group. + return parse_call_named_group(source, info, saved_pos) + + source.pos = saved_pos + raise error("unknown extension", source.string, saved_pos) + +def parse_comment(source): + "Parses a comment." + while True: + saved_pos = source.pos + c = source.get(True) + + if not c or c == ")": + break + + if c == "\\": + c = source.get(True) + + source.pos = saved_pos + source.expect(")") + + return None + +def parse_lookaround(source, info, behind, positive): + "Parses a lookaround." + saved_flags = info.flags + try: + subpattern = _parse_pattern(source, info) + source.expect(")") + finally: + info.flags = saved_flags + source.ignore_space = bool(info.flags & VERBOSE) + + return LookAround(behind, positive, subpattern) + +def parse_conditional(source, info): + "Parses a conditional subpattern." + saved_flags = info.flags + saved_pos = source.pos + ch = source.get() + if ch == "?": + # (?(?... + ch = source.get() + if ch in ("=", "!"): + # (?(?=... or (?(?!...: lookahead conditional. + return parse_lookaround_conditional(source, info, False, ch == "=") + if ch == "<": + # (?(?<... + ch = source.get() + if ch in ("=", "!"): + # (?(?<=... or (?(?"), include=False) + + if not name: + raise error("missing group name", source.string, source.pos) + + if name.isdigit(): + min_group = 0 if allow_group_0 else 1 + if not allow_numeric or int(name) < min_group: + raise error("bad character in group name", source.string, + source.pos) + else: + if not name.isidentifier(): + raise error("bad character in group name", source.string, + source.pos) + + return name + +def is_octal(string): + "Checks whether a string is octal." + return all(ch in OCT_DIGITS for ch in string) + +def is_decimal(string): + "Checks whether a string is decimal." + return all(ch in DIGITS for ch in string) + +def is_hexadecimal(string): + "Checks whether a string is hexadecimal." + return all(ch in HEX_DIGITS for ch in string) + +def parse_escape(source, info, in_set): + "Parses an escape sequence." + saved_ignore = source.ignore_space + source.ignore_space = False + ch = source.get() + source.ignore_space = saved_ignore + if not ch: + # A backslash at the end of the pattern. + raise error("bad escape (end of pattern)", source.string, source.pos) + if ch in HEX_ESCAPES: + # A hexadecimal escape sequence. + return parse_hex_escape(source, info, ch, HEX_ESCAPES[ch], in_set, ch) + elif ch == "g" and not in_set: + # A group reference. + saved_pos = source.pos + try: + return parse_group_ref(source, info) + except error: + # Invalid as a group reference, so assume it's a literal. + source.pos = saved_pos + + return make_character(info, ord(ch), in_set) + elif ch == "G" and not in_set: + # A search anchor. + return SearchAnchor() + elif ch == "L" and not in_set: + # A string set. + return parse_string_set(source, info) + elif ch == "N": + # A named codepoint. + return parse_named_char(source, info, in_set) + elif ch in "pP": + # A Unicode property, positive or negative. + return parse_property(source, info, ch == "p", in_set) + elif ch == "R" and not in_set: + # A line ending. + charset = [0x0A, 0x0B, 0x0C, 0x0D] + if info.guess_encoding == UNICODE: + charset.extend([0x85, 0x2028, 0x2029]) + + return Atomic(Branch([String([0x0D, 0x0A]), SetUnion(info, [Character(c) + for c in charset])])) + elif ch == "X" and not in_set: + # A grapheme cluster. + return Grapheme() + elif ch in ALPHA: + # An alphabetic escape sequence. + # Positional escapes aren't allowed inside a character set. + if not in_set: + if info.flags & WORD: + value = WORD_POSITION_ESCAPES.get(ch) + elif info.flags & ASCII: + value = ASCII_POSITION_ESCAPES.get(ch) + elif info.flags & UNICODE: + value = UNICODE_POSITION_ESCAPES.get(ch) + else: + value = POSITION_ESCAPES.get(ch) + + if value: + return value + + if info.flags & ASCII: + value = ASCII_CHARSET_ESCAPES.get(ch) + elif info.flags & UNICODE: + value = UNICODE_CHARSET_ESCAPES.get(ch) + else: + value = CHARSET_ESCAPES.get(ch) + + if value: + return value + + value = CHARACTER_ESCAPES.get(ch) + if value: + return Character(ord(value)) + + raise error("bad escape \\%s" % ch, source.string, source.pos) + elif ch in DIGITS: + # A numeric escape sequence. + return parse_numeric_escape(source, info, ch, in_set) + else: + # A literal. + return make_character(info, ord(ch), in_set) + +def parse_numeric_escape(source, info, ch, in_set): + "Parses a numeric escape sequence." + if in_set or ch == "0": + # Octal escape sequence, max 3 digits. + return parse_octal_escape(source, info, [ch], in_set) + + # At least 1 digit, so either octal escape or group. + digits = ch + saved_pos = source.pos + ch = source.get() + if ch in DIGITS: + # At least 2 digits, so either octal escape or group. + digits += ch + saved_pos = source.pos + ch = source.get() + if is_octal(digits) and ch in OCT_DIGITS: + # 3 octal digits, so octal escape sequence. + encoding = info.flags & _ALL_ENCODINGS + if encoding == ASCII or encoding == LOCALE: + octal_mask = 0xFF + else: + octal_mask = 0x1FF + + value = int(digits + ch, 8) & octal_mask + return make_character(info, value) + + # Group reference. + source.pos = saved_pos + if info.is_open_group(digits): + raise error("cannot refer to an open group", source.string, source.pos) + + return make_ref_group(info, digits, source.pos) + +def parse_octal_escape(source, info, digits, in_set): + "Parses an octal escape sequence." + saved_pos = source.pos + ch = source.get() + while len(digits) < 3 and ch in OCT_DIGITS: + digits.append(ch) + saved_pos = source.pos + ch = source.get() + + source.pos = saved_pos + try: + value = int("".join(digits), 8) + return make_character(info, value, in_set) + except ValueError: + if digits[0] in OCT_DIGITS: + raise error("incomplete escape \\%s" % ''.join(digits), + source.string, source.pos) + else: + raise error("bad escape \\%s" % digits[0], source.string, + source.pos) + +def parse_hex_escape(source, info, esc, expected_len, in_set, type): + "Parses a hex escape sequence." + saved_pos = source.pos + digits = [] + for i in range(expected_len): + ch = source.get() + if ch not in HEX_DIGITS: + raise error("incomplete escape \\%s%s" % (type, ''.join(digits)), + source.string, saved_pos) + digits.append(ch) + + try: + value = int("".join(digits), 16) + except ValueError: + pass + else: + if value < 0x110000: + return make_character(info, value, in_set) + + # Bad hex escape. + raise error("bad hex escape \\%s%s" % (esc, ''.join(digits)), + source.string, saved_pos) + +def parse_group_ref(source, info): + "Parses a group reference." + source.expect("<") + saved_pos = source.pos + name = parse_name(source, True) + source.expect(">") + if info.is_open_group(name): + raise error("cannot refer to an open group", source.string, source.pos) + + return make_ref_group(info, name, saved_pos) + +def parse_string_set(source, info): + "Parses a string set reference." + source.expect("<") + name = parse_name(source, True) + source.expect(">") + if name is None or name not in info.kwargs: + raise error("undefined named list", source.string, source.pos) + + return make_string_set(info, name) + +def parse_named_char(source, info, in_set): + "Parses a named character." + saved_pos = source.pos + if source.match("{"): + name = source.get_while(NAMED_CHAR_PART, keep_spaces=True) + if source.match("}"): + try: + value = unicodedata.lookup(name) + return make_character(info, ord(value), in_set) + except KeyError: + raise error("undefined character name", source.string, + source.pos) + + source.pos = saved_pos + return make_character(info, ord("N"), in_set) + +def parse_property(source, info, positive, in_set): + "Parses a Unicode property." + saved_pos = source.pos + ch = source.get() + if ch == "{": + negate = source.match("^") + prop_name, name = parse_property_name(source) + if source.match("}"): + # It's correctly delimited. + if info.flags & ASCII: + encoding = ASCII_ENCODING + elif info.flags & UNICODE: + encoding = UNICODE_ENCODING + else: + encoding = 0 + + prop = lookup_property(prop_name, name, positive != negate, source, + encoding=encoding) + return make_property(info, prop, in_set) + elif ch and ch in "CLMNPSZ": + # An abbreviated property, eg \pL. + if info.flags & ASCII: + encoding = ASCII_ENCODING + elif info.flags & UNICODE: + encoding = UNICODE_ENCODING + else: + encoding = 0 + + prop = lookup_property(None, ch, positive, source, encoding=encoding) + return make_property(info, prop, in_set) + + # Not a property, so treat as a literal "p" or "P". + source.pos = saved_pos + ch = "p" if positive else "P" + return make_character(info, ord(ch), in_set) + +def parse_property_name(source): + "Parses a property name, which may be qualified." + name = source.get_while(PROPERTY_NAME_PART) + saved_pos = source.pos + + ch = source.get() + if ch and ch in ":=": + prop_name = name + name = source.get_while(ALNUM | set(" &_-./")).strip() + + if name: + # Name after the ":" or "=", so it's a qualified name. + saved_pos = source.pos + else: + # No name after the ":" or "=", so assume it's an unqualified name. + prop_name, name = None, prop_name + else: + prop_name = None + + source.pos = saved_pos + return prop_name, name + +def parse_set(source, info): + "Parses a character set." + version = (info.flags & _ALL_VERSIONS) or DEFAULT_VERSION + + saved_ignore = source.ignore_space + source.ignore_space = False + # Negative set? + negate = source.match("^") + try: + if version == VERSION0: + item = parse_set_imp_union(source, info) + else: + item = parse_set_union(source, info) + + if not source.match("]"): + raise error("missing ]", source.string, source.pos) + finally: + source.ignore_space = saved_ignore + + if negate: + item = item.with_flags(positive=not item.positive) + + item = item.with_flags(case_flags=make_case_flags(info)) + + return item + +def parse_set_union(source, info): + "Parses a set union ([x||y])." + items = [parse_set_symm_diff(source, info)] + while source.match("||"): + items.append(parse_set_symm_diff(source, info)) + + if len(items) == 1: + return items[0] + return SetUnion(info, items) + +def parse_set_symm_diff(source, info): + "Parses a set symmetric difference ([x~~y])." + items = [parse_set_inter(source, info)] + while source.match("~~"): + items.append(parse_set_inter(source, info)) + + if len(items) == 1: + return items[0] + return SetSymDiff(info, items) + +def parse_set_inter(source, info): + "Parses a set intersection ([x&&y])." + items = [parse_set_diff(source, info)] + while source.match("&&"): + items.append(parse_set_diff(source, info)) + + if len(items) == 1: + return items[0] + return SetInter(info, items) + +def parse_set_diff(source, info): + "Parses a set difference ([x--y])." + items = [parse_set_imp_union(source, info)] + while source.match("--"): + items.append(parse_set_imp_union(source, info)) + + if len(items) == 1: + return items[0] + return SetDiff(info, items) + +def parse_set_imp_union(source, info): + "Parses a set implicit union ([xy])." + version = (info.flags & _ALL_VERSIONS) or DEFAULT_VERSION + + items = [parse_set_member(source, info)] + while True: + saved_pos = source.pos + if source.match("]"): + # End of the set. + source.pos = saved_pos + break + + if version == VERSION1 and any(source.match(op) for op in SET_OPS): + # The new behaviour has set operators. + source.pos = saved_pos + break + + items.append(parse_set_member(source, info)) + + if len(items) == 1: + return items[0] + return SetUnion(info, items) + +def parse_set_member(source, info): + "Parses a member in a character set." + # Parse a set item. + start = parse_set_item(source, info) + saved_pos1 = source.pos + if (not isinstance(start, Character) or not start.positive or not + source.match("-")): + # It's not the start of a range. + return start + + version = (info.flags & _ALL_VERSIONS) or DEFAULT_VERSION + + # It looks like the start of a range of characters. + saved_pos2 = source.pos + if version == VERSION1 and source.match("-"): + # It's actually the set difference operator '--', so return the + # character. + source.pos = saved_pos1 + return start + + if source.match("]"): + # We've reached the end of the set, so return both the character and + # hyphen. + source.pos = saved_pos2 + return SetUnion(info, [start, Character(ord("-"))]) + + # Parse a set item. + end = parse_set_item(source, info) + if not isinstance(end, Character) or not end.positive: + # It's not a range, so return the character, hyphen and property. + return SetUnion(info, [start, Character(ord("-")), end]) + + # It _is_ a range. + if start.value > end.value: + raise error("bad character range", source.string, source.pos) + + if start.value == end.value: + return start + + return Range(start.value, end.value) + +def parse_set_item(source, info): + "Parses an item in a character set." + version = (info.flags & _ALL_VERSIONS) or DEFAULT_VERSION + + if source.match("\\"): + # An escape sequence in a set. + return parse_escape(source, info, True) + + saved_pos = source.pos + if source.match("[:"): + # Looks like a POSIX character class. + try: + return parse_posix_class(source, info) + except ParseError: + # Not a POSIX character class. + source.pos = saved_pos + + if version == VERSION1 and source.match("["): + # It's the start of a nested set. + + # Negative set? + negate = source.match("^") + item = parse_set_union(source, info) + + if not source.match("]"): + raise error("missing ]", source.string, source.pos) + + if negate: + item = item.with_flags(positive=not item.positive) + + return item + + ch = source.get() + if not ch: + raise error("unterminated character set", source.string, source.pos) + + return Character(ord(ch)) + +def parse_posix_class(source, info): + "Parses a POSIX character class." + negate = source.match("^") + prop_name, name = parse_property_name(source) + if not source.match(":]"): + raise ParseError() + + return lookup_property(prop_name, name, not negate, source, posix=True) + +def float_to_rational(flt): + "Converts a float to a rational pair." + int_part = int(flt) + error = flt - int_part + if abs(error) < 0.0001: + return int_part, 1 + + den, num = float_to_rational(1.0 / error) + + return int_part * den + num, den + +def numeric_to_rational(numeric): + "Converts a numeric string to a rational string, if possible." + if numeric[ : 1] == "-": + sign, numeric = numeric[0], numeric[1 : ] + else: + sign = "" + + parts = numeric.split("/") + if len(parts) == 2: + num, den = float_to_rational(float(parts[0]) / float(parts[1])) + elif len(parts) == 1: + num, den = float_to_rational(float(parts[0])) + else: + raise ValueError() + + result = "{}{}/{}".format(sign, num, den) + if result.endswith("/1"): + return result[ : -2] + + return result + +def standardise_name(name): + "Standardises a property or value name." + try: + return numeric_to_rational("".join(name)) + except (ValueError, ZeroDivisionError): + return "".join(ch for ch in name if ch not in "_- ").upper() + +_POSIX_CLASSES = set('ALNUM DIGIT PUNCT XDIGIT'.split()) + +_BINARY_VALUES = set('YES Y NO N TRUE T FALSE F'.split()) + +def lookup_property(property, value, positive, source=None, posix=False, encoding=0): + "Looks up a property." + # Normalise the names (which may still be lists). + property = standardise_name(property) if property else None + value = standardise_name(value) + + if (property, value) == ("GENERALCATEGORY", "ASSIGNED"): + property, value, positive = "GENERALCATEGORY", "UNASSIGNED", not positive + + if posix and not property and value.upper() in _POSIX_CLASSES: + value = 'POSIX' + value + + if property: + # Both the property and the value are provided. + prop = PROPERTIES.get(property) + if not prop: + if not source: + raise error("unknown property") + + raise error("unknown property", source.string, source.pos) + + prop_id, value_dict = prop + val_id = value_dict.get(value) + if val_id is None: + if not source: + raise error("unknown property value") + + raise error("unknown property value", source.string, source.pos) + + return Property((prop_id << 16) | val_id, positive, encoding=encoding) + + # Only the value is provided. + # It might be the name of a GC, script or block value. + for property in ("GC", "SCRIPT", "BLOCK"): + prop_id, value_dict = PROPERTIES.get(property) + val_id = value_dict.get(value) + if val_id is not None: + return Property((prop_id << 16) | val_id, positive, encoding=encoding) + + # It might be the name of a binary property. + prop = PROPERTIES.get(value) + if prop: + prop_id, value_dict = prop + if set(value_dict) == _BINARY_VALUES: + return Property((prop_id << 16) | 1, positive, encoding=encoding) + + return Property(prop_id << 16, not positive, encoding=encoding) + + # It might be the name of a binary property starting with a prefix. + if value.startswith("IS"): + prop = PROPERTIES.get(value[2 : ]) + if prop: + prop_id, value_dict = prop + if "YES" in value_dict: + return Property((prop_id << 16) | 1, positive, encoding=encoding) + + # It might be the name of a script or block starting with a prefix. + for prefix, property in (("IS", "SCRIPT"), ("IN", "BLOCK")): + if value.startswith(prefix): + prop_id, value_dict = PROPERTIES.get(property) + val_id = value_dict.get(value[2 : ]) + if val_id is not None: + return Property((prop_id << 16) | val_id, positive, encoding=encoding) + + # Unknown property. + if not source: + raise error("unknown property") + + raise error("unknown property", source.string, source.pos) + +def _compile_replacement(source, pattern, is_unicode): + "Compiles a replacement template escape sequence." + ch = source.get() + if ch in ALPHA: + # An alphabetic escape sequence. + value = CHARACTER_ESCAPES.get(ch) + if value: + return False, [ord(value)] + + if ch in HEX_ESCAPES and (ch == "x" or is_unicode): + # A hexadecimal escape sequence. + return False, [parse_repl_hex_escape(source, HEX_ESCAPES[ch], ch)] + + if ch == "g": + # A group preference. + return True, [compile_repl_group(source, pattern)] + + if ch == "N" and is_unicode: + # A named character. + value = parse_repl_named_char(source) + if value is not None: + return False, [value] + + raise error("bad escape \\%s" % ch, source.string, source.pos) + + if isinstance(source.sep, bytes): + octal_mask = 0xFF + else: + octal_mask = 0x1FF + + if ch == "0": + # An octal escape sequence. + digits = ch + while len(digits) < 3: + saved_pos = source.pos + ch = source.get() + if ch not in OCT_DIGITS: + source.pos = saved_pos + break + digits += ch + + return False, [int(digits, 8) & octal_mask] + + if ch in DIGITS: + # Either an octal escape sequence (3 digits) or a group reference (max + # 2 digits). + digits = ch + saved_pos = source.pos + ch = source.get() + if ch in DIGITS: + digits += ch + saved_pos = source.pos + ch = source.get() + if ch and is_octal(digits + ch): + # An octal escape sequence. + return False, [int(digits + ch, 8) & octal_mask] + + # A group reference. + source.pos = saved_pos + return True, [int(digits)] + + if ch == "\\": + # An escaped backslash is a backslash. + return False, [ord("\\")] + + if not ch: + # A trailing backslash. + raise error("bad escape (end of pattern)", source.string, source.pos) + + # An escaped non-backslash is a backslash followed by the literal. + return False, [ord("\\"), ord(ch)] + +def parse_repl_hex_escape(source, expected_len, type): + "Parses a hex escape sequence in a replacement string." + digits = [] + for i in range(expected_len): + ch = source.get() + if ch not in HEX_DIGITS: + raise error("incomplete escape \\%s%s" % (type, ''.join(digits)), + source.string, source.pos) + digits.append(ch) + + return int("".join(digits), 16) + +def parse_repl_named_char(source): + "Parses a named character in a replacement string." + saved_pos = source.pos + if source.match("{"): + name = source.get_while(ALPHA | set(" ")) + + if source.match("}"): + try: + value = unicodedata.lookup(name) + return ord(value) + except KeyError: + raise error("undefined character name", source.string, + source.pos) + + source.pos = saved_pos + return None + +def compile_repl_group(source, pattern): + "Compiles a replacement template group reference." + source.expect("<") + name = parse_name(source, True, True) + + source.expect(">") + if name.isdigit(): + index = int(name) + if not 0 <= index <= pattern.groups: + raise error("invalid group reference", source.string, source.pos) + + return index + + try: + return pattern.groupindex[name] + except KeyError: + raise IndexError("unknown group") + +# The regular expression is parsed into a syntax tree. The different types of +# node are defined below. + +INDENT = " " +POSITIVE_OP = 0x1 +ZEROWIDTH_OP = 0x2 +FUZZY_OP = 0x4 +REVERSE_OP = 0x8 +REQUIRED_OP = 0x10 +ENCODING_OP_SHIFT = 5 + +POS_TEXT = {False: "NON-MATCH", True: "MATCH"} +CASE_TEXT = {NOCASE: "", IGNORECASE: " SIMPLE_IGNORE_CASE", FULLCASE: "", + FULLIGNORECASE: " FULL_IGNORE_CASE"} + +def make_sequence(items): + if len(items) == 1: + return items[0] + return Sequence(items) + +# Common base class for all nodes. +class RegexBase: + def __init__(self): + self._key = self.__class__ + + def with_flags(self, positive=None, case_flags=None, zerowidth=None): + if positive is None: + positive = self.positive + else: + positive = bool(positive) + if case_flags is None: + case_flags = self.case_flags + else: + case_flags = CASE_FLAGS_COMBINATIONS[case_flags & CASE_FLAGS] + if zerowidth is None: + zerowidth = self.zerowidth + else: + zerowidth = bool(zerowidth) + + if (positive == self.positive and case_flags == self.case_flags and + zerowidth == self.zerowidth): + return self + + return self.rebuild(positive, case_flags, zerowidth) + + def fix_groups(self, pattern, reverse, fuzzy): + pass + + def optimise(self, info, reverse): + return self + + def pack_characters(self, info): + return self + + def remove_captures(self): + return self + + def is_atomic(self): + return True + + def can_be_affix(self): + return True + + def contains_group(self): + return False + + def get_firstset(self, reverse): + raise _FirstSetError() + + def has_simple_start(self): + return False + + def compile(self, reverse=False, fuzzy=False): + return self._compile(reverse, fuzzy) + + def is_empty(self): + return False + + def __hash__(self): + return hash(self._key) + + def __eq__(self, other): + return type(self) is type(other) and self._key == other._key + + def __ne__(self, other): + return not self.__eq__(other) + + def get_required_string(self, reverse): + return self.max_width(), None + +# Base class for zero-width nodes. +class ZeroWidthBase(RegexBase): + def __init__(self, positive=True, encoding=0): + RegexBase.__init__(self) + self.positive = bool(positive) + self.encoding = encoding + + self._key = self.__class__, self.positive + + def get_firstset(self, reverse): + return set([None]) + + def _compile(self, reverse, fuzzy): + flags = 0 + if self.positive: + flags |= POSITIVE_OP + if fuzzy: + flags |= FUZZY_OP + if reverse: + flags |= REVERSE_OP + flags |= self.encoding << ENCODING_OP_SHIFT + return [(self._opcode, flags)] + + def dump(self, indent, reverse): + print("{}{} {}{}".format(INDENT * indent, self._op_name, + POS_TEXT[self.positive], ["", " ASCII"][self.encoding])) + + def max_width(self): + return 0 + +class Any(RegexBase): + _opcode = {False: OP.ANY, True: OP.ANY_REV} + _op_name = "ANY" + + def has_simple_start(self): + return True + + def _compile(self, reverse, fuzzy): + flags = 0 + if fuzzy: + flags |= FUZZY_OP + return [(self._opcode[reverse], flags)] + + def dump(self, indent, reverse): + print("{}{}".format(INDENT * indent, self._op_name)) + + def max_width(self): + return 1 + +class AnyAll(Any): + _opcode = {False: OP.ANY_ALL, True: OP.ANY_ALL_REV} + _op_name = "ANY_ALL" + + def __init__(self): + self.positive = True + self.zerowidth = False + self.case_flags = 0 + + self._key = self.__class__, self.positive + +class AnyU(Any): + _opcode = {False: OP.ANY_U, True: OP.ANY_U_REV} + _op_name = "ANY_U" + +class Atomic(RegexBase): + def __init__(self, subpattern): + RegexBase.__init__(self) + self.subpattern = subpattern + + def fix_groups(self, pattern, reverse, fuzzy): + self.subpattern.fix_groups(pattern, reverse, fuzzy) + + def optimise(self, info, reverse): + self.subpattern = self.subpattern.optimise(info, reverse) + + if self.subpattern.is_empty(): + return self.subpattern + return self + + def pack_characters(self, info): + self.subpattern = self.subpattern.pack_characters(info) + return self + + def remove_captures(self): + self.subpattern = self.subpattern.remove_captures() + return self + + def can_be_affix(self): + return self.subpattern.can_be_affix() + + def contains_group(self): + return self.subpattern.contains_group() + + def get_firstset(self, reverse): + return self.subpattern.get_firstset(reverse) + + def has_simple_start(self): + return self.subpattern.has_simple_start() + + def _compile(self, reverse, fuzzy): + return ([(OP.ATOMIC, )] + self.subpattern.compile(reverse, fuzzy) + + [(OP.END, )]) + + def dump(self, indent, reverse): + print("{}ATOMIC".format(INDENT * indent)) + self.subpattern.dump(indent + 1, reverse) + + def is_empty(self): + return self.subpattern.is_empty() + + def __eq__(self, other): + return (type(self) is type(other) and self.subpattern == + other.subpattern) + + def max_width(self): + return self.subpattern.max_width() + + def get_required_string(self, reverse): + return self.subpattern.get_required_string(reverse) + +class Boundary(ZeroWidthBase): + _opcode = OP.BOUNDARY + _op_name = "BOUNDARY" + +class Branch(RegexBase): + def __init__(self, branches): + RegexBase.__init__(self) + self.branches = branches + + def fix_groups(self, pattern, reverse, fuzzy): + for b in self.branches: + b.fix_groups(pattern, reverse, fuzzy) + + def optimise(self, info, reverse): + if not self.branches: + return Sequence([]) + + # Flatten branches within branches. + branches = Branch._flatten_branches(info, reverse, self.branches) + + # Move any common prefix or suffix out of the branches. + if reverse: + suffix, branches = Branch._split_common_suffix(info, branches) + prefix = [] + else: + prefix, branches = Branch._split_common_prefix(info, branches) + suffix = [] + + # Try to reduce adjacent single-character branches to sets. + branches = Branch._reduce_to_set(info, reverse, branches) + + if len(branches) > 1: + sequence = [Branch(branches)] + + if not prefix or not suffix: + # We might be able to add a quick precheck before the branches. + firstset = self._add_precheck(info, reverse, branches) + + if firstset: + if reverse: + sequence.append(firstset) + else: + sequence.insert(0, firstset) + else: + sequence = branches + + return make_sequence(prefix + sequence + suffix) + + def _add_precheck(self, info, reverse, branches): + charset = set() + pos = -1 if reverse else 0 + + for branch in branches: + if type(branch) is Literal and branch.case_flags == NOCASE: + charset.add(branch.characters[pos]) + else: + return + + if not charset: + return None + + return _check_firstset(info, reverse, [Character(c) for c in charset]) + + def pack_characters(self, info): + self.branches = [b.pack_characters(info) for b in self.branches] + return self + + def remove_captures(self): + self.branches = [b.remove_captures() for b in self.branches] + return self + + def is_atomic(self): + return all(b.is_atomic() for b in self.branches) + + def can_be_affix(self): + return all(b.can_be_affix() for b in self.branches) + + def contains_group(self): + return any(b.contains_group() for b in self.branches) + + def get_firstset(self, reverse): + fs = set() + for b in self.branches: + fs |= b.get_firstset(reverse) + + return fs or set([None]) + + def _compile(self, reverse, fuzzy): + if not self.branches: + return [] + + code = [(OP.BRANCH, )] + for b in self.branches: + code.extend(b.compile(reverse, fuzzy)) + code.append((OP.NEXT, )) + + code[-1] = (OP.END, ) + + return code + + def dump(self, indent, reverse): + print("{}BRANCH".format(INDENT * indent)) + self.branches[0].dump(indent + 1, reverse) + for b in self.branches[1 : ]: + print("{}OR".format(INDENT * indent)) + b.dump(indent + 1, reverse) + + @staticmethod + def _flatten_branches(info, reverse, branches): + # Flatten the branches so that there aren't branches of branches. + new_branches = [] + for b in branches: + b = b.optimise(info, reverse) + if isinstance(b, Branch): + new_branches.extend(b.branches) + else: + new_branches.append(b) + + return new_branches + + @staticmethod + def _split_common_prefix(info, branches): + # Common leading items can be moved out of the branches. + # Get the items in the branches. + alternatives = [] + for b in branches: + if isinstance(b, Sequence): + alternatives.append(b.items) + else: + alternatives.append([b]) + + # What is the maximum possible length of the prefix? + max_count = min(len(a) for a in alternatives) + + # What is the longest common prefix? + prefix = alternatives[0] + pos = 0 + end_pos = max_count + while pos < end_pos and prefix[pos].can_be_affix() and all(a[pos] == + prefix[pos] for a in alternatives): + pos += 1 + count = pos + + if info.flags & UNICODE: + # We need to check that we're not splitting a sequence of + # characters which could form part of full case-folding. + count = pos + while count > 0 and not all(Branch._can_split(a, count) for a in + alternatives): + count -= 1 + + # No common prefix is possible. + if count == 0: + return [], branches + + # Rebuild the branches. + new_branches = [] + for a in alternatives: + new_branches.append(make_sequence(a[count : ])) + + return prefix[ : count], new_branches + + @staticmethod + def _split_common_suffix(info, branches): + # Common trailing items can be moved out of the branches. + # Get the items in the branches. + alternatives = [] + for b in branches: + if isinstance(b, Sequence): + alternatives.append(b.items) + else: + alternatives.append([b]) + + # What is the maximum possible length of the suffix? + max_count = min(len(a) for a in alternatives) + + # What is the longest common suffix? + suffix = alternatives[0] + pos = -1 + end_pos = -1 - max_count + while pos > end_pos and suffix[pos].can_be_affix() and all(a[pos] == + suffix[pos] for a in alternatives): + pos -= 1 + count = -1 - pos + + if info.flags & UNICODE: + # We need to check that we're not splitting a sequence of + # characters which could form part of full case-folding. + while count > 0 and not all(Branch._can_split_rev(a, count) for a + in alternatives): + count -= 1 + + # No common suffix is possible. + if count == 0: + return [], branches + + # Rebuild the branches. + new_branches = [] + for a in alternatives: + new_branches.append(make_sequence(a[ : -count])) + + return suffix[-count : ], new_branches + + @staticmethod + def _can_split(items, count): + # Check the characters either side of the proposed split. + if not Branch._is_full_case(items, count - 1): + return True + + if not Branch._is_full_case(items, count): + return True + + # Check whether a 1-1 split would be OK. + if Branch._is_folded(items[count - 1 : count + 1]): + return False + + # Check whether a 1-2 split would be OK. + if (Branch._is_full_case(items, count + 2) and + Branch._is_folded(items[count - 1 : count + 2])): + return False + + # Check whether a 2-1 split would be OK. + if (Branch._is_full_case(items, count - 2) and + Branch._is_folded(items[count - 2 : count + 1])): + return False + + return True + + @staticmethod + def _can_split_rev(items, count): + end = len(items) + + # Check the characters either side of the proposed split. + if not Branch._is_full_case(items, end - count): + return True + + if not Branch._is_full_case(items, end - count - 1): + return True + + # Check whether a 1-1 split would be OK. + if Branch._is_folded(items[end - count - 1 : end - count + 1]): + return False + + # Check whether a 1-2 split would be OK. + if (Branch._is_full_case(items, end - count + 2) and + Branch._is_folded(items[end - count - 1 : end - count + 2])): + return False + + # Check whether a 2-1 split would be OK. + if (Branch._is_full_case(items, end - count - 2) and + Branch._is_folded(items[end - count - 2 : end - count + 1])): + return False + + return True + + @staticmethod + def _merge_common_prefixes(info, reverse, branches): + # Branches with the same case-sensitive character prefix can be grouped + # together if they are separated only by other branches with a + # character prefix. + prefixed = defaultdict(list) + order = {} + new_branches = [] + for b in branches: + if Branch._is_simple_character(b): + # Branch starts with a simple character. + prefixed[b.value].append([b]) + order.setdefault(b.value, len(order)) + elif (isinstance(b, Sequence) and b.items and + Branch._is_simple_character(b.items[0])): + # Branch starts with a simple character. + prefixed[b.items[0].value].append(b.items) + order.setdefault(b.items[0].value, len(order)) + else: + Branch._flush_char_prefix(info, reverse, prefixed, order, + new_branches) + + new_branches.append(b) + + Branch._flush_char_prefix(info, prefixed, order, new_branches) + + return new_branches + + @staticmethod + def _is_simple_character(c): + return isinstance(c, Character) and c.positive and not c.case_flags + + @staticmethod + def _reduce_to_set(info, reverse, branches): + # Can the branches be reduced to a set? + new_branches = [] + items = set() + case_flags = NOCASE + for b in branches: + if isinstance(b, (Character, Property, SetBase)): + # Branch starts with a single character. + if b.case_flags != case_flags: + # Different case sensitivity, so flush. + Branch._flush_set_members(info, reverse, items, case_flags, + new_branches) + + case_flags = b.case_flags + + items.add(b.with_flags(case_flags=NOCASE)) + else: + Branch._flush_set_members(info, reverse, items, case_flags, + new_branches) + + new_branches.append(b) + + Branch._flush_set_members(info, reverse, items, case_flags, + new_branches) + + return new_branches + + @staticmethod + def _flush_char_prefix(info, reverse, prefixed, order, new_branches): + # Flush the prefixed branches. + if not prefixed: + return + + for value, branches in sorted(prefixed.items(), key=lambda pair: + order[pair[0]]): + if len(branches) == 1: + new_branches.append(make_sequence(branches[0])) + else: + subbranches = [] + optional = False + for b in branches: + if len(b) > 1: + subbranches.append(make_sequence(b[1 : ])) + elif not optional: + subbranches.append(Sequence()) + optional = True + + sequence = Sequence([Character(value), Branch(subbranches)]) + new_branches.append(sequence.optimise(info, reverse)) + + prefixed.clear() + order.clear() + + @staticmethod + def _flush_set_members(info, reverse, items, case_flags, new_branches): + # Flush the set members. + if not items: + return + + if len(items) == 1: + item = list(items)[0] + else: + item = SetUnion(info, list(items)).optimise(info, reverse) + + new_branches.append(item.with_flags(case_flags=case_flags)) + + items.clear() + + @staticmethod + def _is_full_case(items, i): + if not 0 <= i < len(items): + return False + + item = items[i] + return (isinstance(item, Character) and item.positive and + (item.case_flags & FULLIGNORECASE) == FULLIGNORECASE) + + @staticmethod + def _is_folded(items): + if len(items) < 2: + return False + + for i in items: + if (not isinstance(i, Character) or not i.positive or not + i.case_flags): + return False + + folded = "".join(chr(i.value) for i in items) + folded = _regex.fold_case(FULL_CASE_FOLDING, folded) + + # Get the characters which expand to multiple codepoints on folding. + expanding_chars = _regex.get_expand_on_folding() + + for c in expanding_chars: + if folded == _regex.fold_case(FULL_CASE_FOLDING, c): + return True + + return False + + def is_empty(self): + return all(b.is_empty() for b in self.branches) + + def __eq__(self, other): + return type(self) is type(other) and self.branches == other.branches + + def max_width(self): + return max(b.max_width() for b in self.branches) + +class CallGroup(RegexBase): + def __init__(self, info, group, position): + RegexBase.__init__(self) + self.info = info + self.group = group + self.position = position + + self._key = self.__class__, self.group + + def fix_groups(self, pattern, reverse, fuzzy): + try: + self.group = int(self.group) + except ValueError: + try: + self.group = self.info.group_index[self.group] + except KeyError: + raise error("invalid group reference", pattern, self.position) + + if not 0 <= self.group <= self.info.group_count: + raise error("unknown group", pattern, self.position) + + if self.group > 0 and self.info.open_group_count[self.group] > 1: + raise error("ambiguous group reference", pattern, self.position) + + self.info.group_calls.append((self, reverse, fuzzy)) + + self._key = self.__class__, self.group + + def remove_captures(self): + raise error("group reference not allowed", self.pattern, self.position) + + def _compile(self, reverse, fuzzy): + return [(OP.GROUP_CALL, self.call_ref)] + + def dump(self, indent, reverse): + print("{}GROUP_CALL {}".format(INDENT * indent, self.group)) + + def __eq__(self, other): + return type(self) is type(other) and self.group == other.group + + def max_width(self): + return UNLIMITED + + def __del__(self): + self.info = None + +class CallRef(RegexBase): + def __init__(self, ref, parsed): + self.ref = ref + self.parsed = parsed + + def _compile(self, reverse, fuzzy): + return ([(OP.CALL_REF, self.ref)] + self.parsed._compile(reverse, + fuzzy) + [(OP.END, )]) + +class Character(RegexBase): + _opcode = {(NOCASE, False): OP.CHARACTER, (IGNORECASE, False): + OP.CHARACTER_IGN, (FULLCASE, False): OP.CHARACTER, (FULLIGNORECASE, + False): OP.CHARACTER_IGN, (NOCASE, True): OP.CHARACTER_REV, (IGNORECASE, + True): OP.CHARACTER_IGN_REV, (FULLCASE, True): OP.CHARACTER_REV, + (FULLIGNORECASE, True): OP.CHARACTER_IGN_REV} + + def __init__(self, value, positive=True, case_flags=NOCASE, + zerowidth=False): + RegexBase.__init__(self) + self.value = value + self.positive = bool(positive) + self.case_flags = CASE_FLAGS_COMBINATIONS[case_flags] + self.zerowidth = bool(zerowidth) + + if (self.positive and (self.case_flags & FULLIGNORECASE) == + FULLIGNORECASE): + self.folded = _regex.fold_case(FULL_CASE_FOLDING, chr(self.value)) + else: + self.folded = chr(self.value) + + self._key = (self.__class__, self.value, self.positive, + self.case_flags, self.zerowidth) + + def rebuild(self, positive, case_flags, zerowidth): + return Character(self.value, positive, case_flags, zerowidth) + + def optimise(self, info, reverse, in_set=False): + return self + + def get_firstset(self, reverse): + return set([self]) + + def has_simple_start(self): + return True + + def _compile(self, reverse, fuzzy): + flags = 0 + if self.positive: + flags |= POSITIVE_OP + if self.zerowidth: + flags |= ZEROWIDTH_OP + if fuzzy: + flags |= FUZZY_OP + + code = PrecompiledCode([self._opcode[self.case_flags, reverse], flags, + self.value]) + + if len(self.folded) > 1: + # The character expands on full case-folding. + code = Branch([code, String([ord(c) for c in self.folded], + case_flags=self.case_flags)]) + + return code.compile(reverse, fuzzy) + + def dump(self, indent, reverse): + display = ascii(chr(self.value)).lstrip("bu") + print("{}CHARACTER {} {}{}".format(INDENT * indent, + POS_TEXT[self.positive], display, CASE_TEXT[self.case_flags])) + + def matches(self, ch): + return (ch == self.value) == self.positive + + def max_width(self): + return len(self.folded) + + def get_required_string(self, reverse): + if not self.positive: + return 1, None + + self.folded_characters = tuple(ord(c) for c in self.folded) + + return 0, self + +class Conditional(RegexBase): + def __init__(self, info, group, yes_item, no_item, position): + RegexBase.__init__(self) + self.info = info + self.group = group + self.yes_item = yes_item + self.no_item = no_item + self.position = position + + def fix_groups(self, pattern, reverse, fuzzy): + try: + self.group = int(self.group) + except ValueError: + try: + self.group = self.info.group_index[self.group] + except KeyError: + if self.group == 'DEFINE': + # 'DEFINE' is a special name unless there's a group with + # that name. + self.group = 0 + else: + raise error("unknown group", pattern, self.position) + + if not 0 <= self.group <= self.info.group_count: + raise error("invalid group reference", pattern, self.position) + + self.yes_item.fix_groups(pattern, reverse, fuzzy) + self.no_item.fix_groups(pattern, reverse, fuzzy) + + def optimise(self, info, reverse): + yes_item = self.yes_item.optimise(info, reverse) + no_item = self.no_item.optimise(info, reverse) + + return Conditional(info, self.group, yes_item, no_item, self.position) + + def pack_characters(self, info): + self.yes_item = self.yes_item.pack_characters(info) + self.no_item = self.no_item.pack_characters(info) + return self + + def remove_captures(self): + self.yes_item = self.yes_item.remove_captures() + self.no_item = self.no_item.remove_captures() + + def is_atomic(self): + return self.yes_item.is_atomic() and self.no_item.is_atomic() + + def can_be_affix(self): + return self.yes_item.can_be_affix() and self.no_item.can_be_affix() + + def contains_group(self): + return self.yes_item.contains_group() or self.no_item.contains_group() + + def get_firstset(self, reverse): + return (self.yes_item.get_firstset(reverse) | + self.no_item.get_firstset(reverse)) + + def _compile(self, reverse, fuzzy): + code = [(OP.GROUP_EXISTS, self.group)] + code.extend(self.yes_item.compile(reverse, fuzzy)) + add_code = self.no_item.compile(reverse, fuzzy) + if add_code: + code.append((OP.NEXT, )) + code.extend(add_code) + + code.append((OP.END, )) + + return code + + def dump(self, indent, reverse): + print("{}GROUP_EXISTS {}".format(INDENT * indent, self.group)) + self.yes_item.dump(indent + 1, reverse) + if not self.no_item.is_empty(): + print("{}OR".format(INDENT * indent)) + self.no_item.dump(indent + 1, reverse) + + def is_empty(self): + return self.yes_item.is_empty() and self.no_item.is_empty() + + def __eq__(self, other): + return type(self) is type(other) and (self.group, self.yes_item, + self.no_item) == (other.group, other.yes_item, other.no_item) + + def max_width(self): + return max(self.yes_item.max_width(), self.no_item.max_width()) + + def __del__(self): + self.info = None + +class DefaultBoundary(ZeroWidthBase): + _opcode = OP.DEFAULT_BOUNDARY + _op_name = "DEFAULT_BOUNDARY" + +class DefaultEndOfWord(ZeroWidthBase): + _opcode = OP.DEFAULT_END_OF_WORD + _op_name = "DEFAULT_END_OF_WORD" + +class DefaultStartOfWord(ZeroWidthBase): + _opcode = OP.DEFAULT_START_OF_WORD + _op_name = "DEFAULT_START_OF_WORD" + +class EndOfLine(ZeroWidthBase): + _opcode = OP.END_OF_LINE + _op_name = "END_OF_LINE" + +class EndOfLineU(EndOfLine): + _opcode = OP.END_OF_LINE_U + _op_name = "END_OF_LINE_U" + +class EndOfString(ZeroWidthBase): + _opcode = OP.END_OF_STRING + _op_name = "END_OF_STRING" + +class EndOfStringLine(ZeroWidthBase): + _opcode = OP.END_OF_STRING_LINE + _op_name = "END_OF_STRING_LINE" + +class EndOfStringLineU(EndOfStringLine): + _opcode = OP.END_OF_STRING_LINE_U + _op_name = "END_OF_STRING_LINE_U" + +class EndOfWord(ZeroWidthBase): + _opcode = OP.END_OF_WORD + _op_name = "END_OF_WORD" + +class Failure(ZeroWidthBase): + _op_name = "FAILURE" + + def _compile(self, reverse, fuzzy): + return [(OP.FAILURE, )] + +class Fuzzy(RegexBase): + def __init__(self, subpattern, constraints=None): + RegexBase.__init__(self) + if constraints is None: + constraints = {} + self.subpattern = subpattern + self.constraints = constraints + + # If an error type is mentioned in the cost equation, then its maximum + # defaults to unlimited. + if "cost" in constraints: + for e in "dis": + if e in constraints["cost"]: + constraints.setdefault(e, (0, None)) + + # If any error type is mentioned, then all the error maxima default to + # 0, otherwise they default to unlimited. + if set(constraints) & set("dis"): + for e in "dis": + constraints.setdefault(e, (0, 0)) + else: + for e in "dis": + constraints.setdefault(e, (0, None)) + + # The maximum of the generic error type defaults to unlimited. + constraints.setdefault("e", (0, None)) + + # The cost equation defaults to equal costs. Also, the cost of any + # error type not mentioned in the cost equation defaults to 0. + if "cost" in constraints: + for e in "dis": + constraints["cost"].setdefault(e, 0) + else: + constraints["cost"] = {"d": 1, "i": 1, "s": 1, "max": + constraints["e"][1]} + + def fix_groups(self, pattern, reverse, fuzzy): + self.subpattern.fix_groups(pattern, reverse, True) + + def pack_characters(self, info): + self.subpattern = self.subpattern.pack_characters(info) + return self + + def remove_captures(self): + self.subpattern = self.subpattern.remove_captures() + return self + + def is_atomic(self): + return self.subpattern.is_atomic() + + def contains_group(self): + return self.subpattern.contains_group() + + def _compile(self, reverse, fuzzy): + # The individual limits. + arguments = [] + for e in "dise": + v = self.constraints[e] + arguments.append(v[0]) + arguments.append(UNLIMITED if v[1] is None else v[1]) + + # The coeffs of the cost equation. + for e in "dis": + arguments.append(self.constraints["cost"][e]) + + # The maximum of the cost equation. + v = self.constraints["cost"]["max"] + arguments.append(UNLIMITED if v is None else v) + + flags = 0 + if reverse: + flags |= REVERSE_OP + + test = self.constraints.get("test") + + if test: + return ([(OP.FUZZY_EXT, flags) + tuple(arguments)] + + test.compile(reverse, True) + [(OP.NEXT,)] + + self.subpattern.compile(reverse, True) + [(OP.END,)]) + + return ([(OP.FUZZY, flags) + tuple(arguments)] + + self.subpattern.compile(reverse, True) + [(OP.END,)]) + + def dump(self, indent, reverse): + constraints = self._constraints_to_string() + if constraints: + constraints = " " + constraints + print("{}FUZZY{}".format(INDENT * indent, constraints)) + self.subpattern.dump(indent + 1, reverse) + + def is_empty(self): + return self.subpattern.is_empty() + + def __eq__(self, other): + return (type(self) is type(other) and self.subpattern == + other.subpattern and self.constraints == other.constraints) + + def max_width(self): + return UNLIMITED + + def _constraints_to_string(self): + constraints = [] + + for name in "ids": + min, max = self.constraints[name] + if max == 0: + continue + + con = "" + + if min > 0: + con = "{}<=".format(min) + + con += name + + if max is not None: + con += "<={}".format(max) + + constraints.append(con) + + cost = [] + for name in "ids": + coeff = self.constraints["cost"][name] + if coeff > 0: + cost.append("{}{}".format(coeff, name)) + + limit = self.constraints["cost"]["max"] + if limit is not None and limit > 0: + cost = "{}<={}".format("+".join(cost), limit) + constraints.append(cost) + + return ",".join(constraints) + +class Grapheme(RegexBase): + def _compile(self, reverse, fuzzy): + # Match at least 1 character until a grapheme boundary is reached. Note + # that this is the same whether matching forwards or backwards. + grapheme_matcher = Atomic(Sequence([LazyRepeat(AnyAll(), 1, None), + GraphemeBoundary()])) + + return grapheme_matcher.compile(reverse, fuzzy) + + def dump(self, indent, reverse): + print("{}GRAPHEME".format(INDENT * indent)) + + def max_width(self): + return UNLIMITED + +class GraphemeBoundary: + def compile(self, reverse, fuzzy): + return [(OP.GRAPHEME_BOUNDARY, 1)] + +class GreedyRepeat(RegexBase): + _opcode = OP.GREEDY_REPEAT + _op_name = "GREEDY_REPEAT" + + def __init__(self, subpattern, min_count, max_count): + RegexBase.__init__(self) + self.subpattern = subpattern + self.min_count = min_count + self.max_count = max_count + + def fix_groups(self, pattern, reverse, fuzzy): + self.subpattern.fix_groups(pattern, reverse, fuzzy) + + def optimise(self, info, reverse): + subpattern = self.subpattern.optimise(info, reverse) + + return type(self)(subpattern, self.min_count, self.max_count) + + def pack_characters(self, info): + self.subpattern = self.subpattern.pack_characters(info) + return self + + def remove_captures(self): + self.subpattern = self.subpattern.remove_captures() + return self + + def is_atomic(self): + return self.min_count == self.max_count and self.subpattern.is_atomic() + + def can_be_affix(self): + return False + + def contains_group(self): + return self.subpattern.contains_group() + + def get_firstset(self, reverse): + fs = self.subpattern.get_firstset(reverse) + if self.min_count == 0: + fs.add(None) + + return fs + + def _compile(self, reverse, fuzzy): + repeat = [self._opcode, self.min_count] + if self.max_count is None: + repeat.append(UNLIMITED) + else: + repeat.append(self.max_count) + + subpattern = self.subpattern.compile(reverse, fuzzy) + if not subpattern: + return [] + + return ([tuple(repeat)] + subpattern + [(OP.END, )]) + + def dump(self, indent, reverse): + if self.max_count is None: + limit = "INF" + else: + limit = self.max_count + print("{}{} {} {}".format(INDENT * indent, self._op_name, + self.min_count, limit)) + + self.subpattern.dump(indent + 1, reverse) + + def is_empty(self): + return self.subpattern.is_empty() + + def __eq__(self, other): + return type(self) is type(other) and (self.subpattern, self.min_count, + self.max_count) == (other.subpattern, other.min_count, + other.max_count) + + def max_width(self): + if self.max_count is None: + return UNLIMITED + + return self.subpattern.max_width() * self.max_count + + def get_required_string(self, reverse): + max_count = UNLIMITED if self.max_count is None else self.max_count + if self.min_count == 0: + w = self.subpattern.max_width() * max_count + return min(w, UNLIMITED), None + + ofs, req = self.subpattern.get_required_string(reverse) + if req: + return ofs, req + + w = self.subpattern.max_width() * max_count + return min(w, UNLIMITED), None + +class PossessiveRepeat(GreedyRepeat): + def is_atomic(self): + return True + + def _compile(self, reverse, fuzzy): + subpattern = self.subpattern.compile(reverse, fuzzy) + if not subpattern: + return [] + + repeat = [self._opcode, self.min_count] + if self.max_count is None: + repeat.append(UNLIMITED) + else: + repeat.append(self.max_count) + + return ([(OP.ATOMIC, ), tuple(repeat)] + subpattern + [(OP.END, ), + (OP.END, )]) + + def dump(self, indent, reverse): + print("{}ATOMIC".format(INDENT * indent)) + + if self.max_count is None: + limit = "INF" + else: + limit = self.max_count + print("{}{} {} {}".format(INDENT * (indent + 1), self._op_name, + self.min_count, limit)) + + self.subpattern.dump(indent + 2, reverse) + +class Group(RegexBase): + def __init__(self, info, group, subpattern): + RegexBase.__init__(self) + self.info = info + self.group = group + self.subpattern = subpattern + + self.call_ref = None + + def fix_groups(self, pattern, reverse, fuzzy): + self.info.defined_groups[self.group] = (self, reverse, fuzzy) + self.subpattern.fix_groups(pattern, reverse, fuzzy) + + def optimise(self, info, reverse): + subpattern = self.subpattern.optimise(info, reverse) + + return Group(self.info, self.group, subpattern) + + def pack_characters(self, info): + self.subpattern = self.subpattern.pack_characters(info) + return self + + def remove_captures(self): + return self.subpattern.remove_captures() + + def is_atomic(self): + return self.subpattern.is_atomic() + + def can_be_affix(self): + return False + + def contains_group(self): + return True + + def get_firstset(self, reverse): + return self.subpattern.get_firstset(reverse) + + def has_simple_start(self): + return self.subpattern.has_simple_start() + + def _compile(self, reverse, fuzzy): + code = [] + + public_group = private_group = self.group + if private_group < 0: + public_group = self.info.private_groups[private_group] + private_group = self.info.group_count - private_group + + key = self.group, reverse, fuzzy + ref = self.info.call_refs.get(key) + if ref is not None: + code += [(OP.CALL_REF, ref)] + + code += [(OP.GROUP, int(not reverse), private_group, public_group)] + code += self.subpattern.compile(reverse, fuzzy) + code += [(OP.END, )] + + if ref is not None: + code += [(OP.END, )] + + return code + + def dump(self, indent, reverse): + group = self.group + if group < 0: + group = self.info.private_groups[group] + print("{}GROUP {}".format(INDENT * indent, group)) + self.subpattern.dump(indent + 1, reverse) + + def __eq__(self, other): + return (type(self) is type(other) and (self.group, self.subpattern) == + (other.group, other.subpattern)) + + def max_width(self): + return self.subpattern.max_width() + + def get_required_string(self, reverse): + return self.subpattern.get_required_string(reverse) + + def __del__(self): + self.info = None + +class Keep(ZeroWidthBase): + _opcode = OP.KEEP + _op_name = "KEEP" + +class LazyRepeat(GreedyRepeat): + _opcode = OP.LAZY_REPEAT + _op_name = "LAZY_REPEAT" + +class LookAround(RegexBase): + _dir_text = {False: "AHEAD", True: "BEHIND"} + + def __init__(self, behind, positive, subpattern): + RegexBase.__init__(self) + self.behind = bool(behind) + self.positive = bool(positive) + self.subpattern = subpattern + + def fix_groups(self, pattern, reverse, fuzzy): + self.subpattern.fix_groups(pattern, self.behind, fuzzy) + + def optimise(self, info, reverse): + subpattern = self.subpattern.optimise(info, self.behind) + if self.positive and subpattern.is_empty(): + return subpattern + + return LookAround(self.behind, self.positive, subpattern) + + def pack_characters(self, info): + self.subpattern = self.subpattern.pack_characters(info) + return self + + def remove_captures(self): + return self.subpattern.remove_captures() + + def is_atomic(self): + return self.subpattern.is_atomic() + + def can_be_affix(self): + return self.subpattern.can_be_affix() + + def contains_group(self): + return self.subpattern.contains_group() + + def get_firstset(self, reverse): + if self.positive and self.behind == reverse: + return self.subpattern.get_firstset(reverse) + + return set([None]) + + def _compile(self, reverse, fuzzy): + flags = 0 + if self.positive: + flags |= POSITIVE_OP + if fuzzy: + flags |= FUZZY_OP + if reverse: + flags |= REVERSE_OP + + return ([(OP.LOOKAROUND, flags, int(not self.behind))] + + self.subpattern.compile(self.behind) + [(OP.END, )]) + + def dump(self, indent, reverse): + print("{}LOOK{} {}".format(INDENT * indent, + self._dir_text[self.behind], POS_TEXT[self.positive])) + self.subpattern.dump(indent + 1, self.behind) + + def is_empty(self): + return self.positive and self.subpattern.is_empty() + + def __eq__(self, other): + return type(self) is type(other) and (self.behind, self.positive, + self.subpattern) == (other.behind, other.positive, other.subpattern) + + def max_width(self): + return 0 + +class LookAroundConditional(RegexBase): + _dir_text = {False: "AHEAD", True: "BEHIND"} + + def __init__(self, behind, positive, subpattern, yes_item, no_item): + RegexBase.__init__(self) + self.behind = bool(behind) + self.positive = bool(positive) + self.subpattern = subpattern + self.yes_item = yes_item + self.no_item = no_item + + def fix_groups(self, pattern, reverse, fuzzy): + self.subpattern.fix_groups(pattern, reverse, fuzzy) + self.yes_item.fix_groups(pattern, reverse, fuzzy) + self.no_item.fix_groups(pattern, reverse, fuzzy) + + def optimise(self, info, reverse): + subpattern = self.subpattern.optimise(info, self.behind) + yes_item = self.yes_item.optimise(info, self.behind) + no_item = self.no_item.optimise(info, self.behind) + + return LookAroundConditional(self.behind, self.positive, subpattern, + yes_item, no_item) + + def pack_characters(self, info): + self.subpattern = self.subpattern.pack_characters(info) + self.yes_item = self.yes_item.pack_characters(info) + self.no_item = self.no_item.pack_characters(info) + return self + + def remove_captures(self): + self.subpattern = self.subpattern.remove_captures() + self.yes_item = self.yes_item.remove_captures() + self.no_item = self.no_item.remove_captures() + + def is_atomic(self): + return (self.subpattern.is_atomic() and self.yes_item.is_atomic() and + self.no_item.is_atomic()) + + def can_be_affix(self): + return (self.subpattern.can_be_affix() and self.yes_item.can_be_affix() + and self.no_item.can_be_affix()) + + def contains_group(self): + return (self.subpattern.contains_group() or + self.yes_item.contains_group() or self.no_item.contains_group()) + + def _compile(self, reverse, fuzzy): + code = [(OP.CONDITIONAL, int(self.positive), int(not self.behind))] + code.extend(self.subpattern.compile(self.behind, fuzzy)) + code.append((OP.NEXT, )) + code.extend(self.yes_item.compile(reverse, fuzzy)) + add_code = self.no_item.compile(reverse, fuzzy) + if add_code: + code.append((OP.NEXT, )) + code.extend(add_code) + + code.append((OP.END, )) + + return code + + def dump(self, indent, reverse): + print("{}CONDITIONAL {} {}".format(INDENT * indent, + self._dir_text[self.behind], POS_TEXT[self.positive])) + self.subpattern.dump(indent + 1, self.behind) + print("{}EITHER".format(INDENT * indent)) + self.yes_item.dump(indent + 1, reverse) + if not self.no_item.is_empty(): + print("{}OR".format(INDENT * indent)) + self.no_item.dump(indent + 1, reverse) + + def is_empty(self): + return self.subpattern.is_empty() and self.yes_item.is_empty() + + def __eq__(self, other): + return type(self) is type(other) and (self.subpattern, self.yes_item, + self.no_item) == (other.subpattern, other.yes_item, other.no_item) + + def max_width(self): + return max(self.yes_item.max_width(), self.no_item.max_width()) + + def get_required_string(self, reverse): + return self.max_width(), None + +class PrecompiledCode(RegexBase): + def __init__(self, code): + self.code = code + + def _compile(self, reverse, fuzzy): + return [tuple(self.code)] + +class Property(RegexBase): + _opcode = {(NOCASE, False): OP.PROPERTY, (IGNORECASE, False): + OP.PROPERTY_IGN, (FULLCASE, False): OP.PROPERTY, (FULLIGNORECASE, False): + OP.PROPERTY_IGN, (NOCASE, True): OP.PROPERTY_REV, (IGNORECASE, True): + OP.PROPERTY_IGN_REV, (FULLCASE, True): OP.PROPERTY_REV, (FULLIGNORECASE, + True): OP.PROPERTY_IGN_REV} + + def __init__(self, value, positive=True, case_flags=NOCASE, + zerowidth=False, encoding=0): + RegexBase.__init__(self) + self.value = value + self.positive = bool(positive) + self.case_flags = CASE_FLAGS_COMBINATIONS[case_flags] + self.zerowidth = bool(zerowidth) + self.encoding = encoding + + self._key = (self.__class__, self.value, self.positive, + self.case_flags, self.zerowidth) + + def rebuild(self, positive, case_flags, zerowidth): + return Property(self.value, positive, case_flags, zerowidth, + self.encoding) + + def optimise(self, info, reverse, in_set=False): + return self + + def get_firstset(self, reverse): + return set([self]) + + def has_simple_start(self): + return True + + def _compile(self, reverse, fuzzy): + flags = 0 + if self.positive: + flags |= POSITIVE_OP + if self.zerowidth: + flags |= ZEROWIDTH_OP + if fuzzy: + flags |= FUZZY_OP + flags |= self.encoding << ENCODING_OP_SHIFT + return [(self._opcode[self.case_flags, reverse], flags, self.value)] + + def dump(self, indent, reverse): + prop = PROPERTY_NAMES[self.value >> 16] + name, value = prop[0], prop[1][self.value & 0xFFFF] + print("{}PROPERTY {} {}:{}{}{}".format(INDENT * indent, + POS_TEXT[self.positive], name, value, CASE_TEXT[self.case_flags], + ["", " ASCII"][self.encoding])) + + def matches(self, ch): + return _regex.has_property_value(self.value, ch) == self.positive + + def max_width(self): + return 1 + +class Prune(ZeroWidthBase): + _op_name = "PRUNE" + + def _compile(self, reverse, fuzzy): + return [(OP.PRUNE, )] + +class Range(RegexBase): + _opcode = {(NOCASE, False): OP.RANGE, (IGNORECASE, False): OP.RANGE_IGN, + (FULLCASE, False): OP.RANGE, (FULLIGNORECASE, False): OP.RANGE_IGN, + (NOCASE, True): OP.RANGE_REV, (IGNORECASE, True): OP.RANGE_IGN_REV, + (FULLCASE, True): OP.RANGE_REV, (FULLIGNORECASE, True): OP.RANGE_IGN_REV} + _op_name = "RANGE" + + def __init__(self, lower, upper, positive=True, case_flags=NOCASE, + zerowidth=False): + RegexBase.__init__(self) + self.lower = lower + self.upper = upper + self.positive = bool(positive) + self.case_flags = CASE_FLAGS_COMBINATIONS[case_flags] + self.zerowidth = bool(zerowidth) + + self._key = (self.__class__, self.lower, self.upper, self.positive, + self.case_flags, self.zerowidth) + + def rebuild(self, positive, case_flags, zerowidth): + return Range(self.lower, self.upper, positive, case_flags, zerowidth) + + def optimise(self, info, reverse, in_set=False): + # Is the range case-sensitive? + if not self.positive or not (self.case_flags & IGNORECASE) or in_set: + return self + + # Is full case-folding possible? + if (not (info.flags & UNICODE) or (self.case_flags & FULLIGNORECASE) != + FULLIGNORECASE): + return self + + # Get the characters which expand to multiple codepoints on folding. + expanding_chars = _regex.get_expand_on_folding() + + # Get the folded characters in the range. + items = [] + for ch in expanding_chars: + if self.lower <= ord(ch) <= self.upper: + folded = _regex.fold_case(FULL_CASE_FOLDING, ch) + items.append(String([ord(c) for c in folded], + case_flags=self.case_flags)) + + if not items: + # We can fall back to simple case-folding. + return self + + if len(items) < self.upper - self.lower + 1: + # Not all the characters are covered by the full case-folding. + items.insert(0, self) + + return Branch(items) + + def _compile(self, reverse, fuzzy): + flags = 0 + if self.positive: + flags |= POSITIVE_OP + if self.zerowidth: + flags |= ZEROWIDTH_OP + if fuzzy: + flags |= FUZZY_OP + return [(self._opcode[self.case_flags, reverse], flags, self.lower, + self.upper)] + + def dump(self, indent, reverse): + display_lower = ascii(chr(self.lower)).lstrip("bu") + display_upper = ascii(chr(self.upper)).lstrip("bu") + print("{}RANGE {} {} {}{}".format(INDENT * indent, + POS_TEXT[self.positive], display_lower, display_upper, + CASE_TEXT[self.case_flags])) + + def matches(self, ch): + return (self.lower <= ch <= self.upper) == self.positive + + def max_width(self): + return 1 + +class RefGroup(RegexBase): + _opcode = {(NOCASE, False): OP.REF_GROUP, (IGNORECASE, False): + OP.REF_GROUP_IGN, (FULLCASE, False): OP.REF_GROUP, (FULLIGNORECASE, + False): OP.REF_GROUP_FLD, (NOCASE, True): OP.REF_GROUP_REV, (IGNORECASE, + True): OP.REF_GROUP_IGN_REV, (FULLCASE, True): OP.REF_GROUP_REV, + (FULLIGNORECASE, True): OP.REF_GROUP_FLD_REV} + + def __init__(self, info, group, position, case_flags=NOCASE): + RegexBase.__init__(self) + self.info = info + self.group = group + self.position = position + self.case_flags = CASE_FLAGS_COMBINATIONS[case_flags] + + self._key = self.__class__, self.group, self.case_flags + + def fix_groups(self, pattern, reverse, fuzzy): + try: + self.group = int(self.group) + except ValueError: + try: + self.group = self.info.group_index[self.group] + except KeyError: + raise error("unknown group", pattern, self.position) + + if not 1 <= self.group <= self.info.group_count: + raise error("invalid group reference", pattern, self.position) + + self._key = self.__class__, self.group, self.case_flags + + def remove_captures(self): + raise error("group reference not allowed", self.pattern, self.position) + + def _compile(self, reverse, fuzzy): + flags = 0 + if fuzzy: + flags |= FUZZY_OP + return [(self._opcode[self.case_flags, reverse], flags, self.group)] + + def dump(self, indent, reverse): + print("{}REF_GROUP {}{}".format(INDENT * indent, self.group, + CASE_TEXT[self.case_flags])) + + def max_width(self): + return UNLIMITED + + def __del__(self): + self.info = None + +class SearchAnchor(ZeroWidthBase): + _opcode = OP.SEARCH_ANCHOR + _op_name = "SEARCH_ANCHOR" + +class Sequence(RegexBase): + def __init__(self, items=None): + RegexBase.__init__(self) + if items is None: + items = [] + + self.items = items + + def fix_groups(self, pattern, reverse, fuzzy): + for s in self.items: + s.fix_groups(pattern, reverse, fuzzy) + + def optimise(self, info, reverse): + # Flatten the sequences. + items = [] + for s in self.items: + s = s.optimise(info, reverse) + if isinstance(s, Sequence): + items.extend(s.items) + else: + items.append(s) + + return make_sequence(items) + + def pack_characters(self, info): + "Packs sequences of characters into strings." + items = [] + characters = [] + case_flags = NOCASE + for s in self.items: + if type(s) is Character and s.positive and not s.zerowidth: + if s.case_flags != case_flags: + # Different case sensitivity, so flush, unless neither the + # previous nor the new character are cased. + if s.case_flags or is_cased_i(info, s.value): + Sequence._flush_characters(info, characters, + case_flags, items) + + case_flags = s.case_flags + + characters.append(s.value) + elif type(s) is String or type(s) is Literal: + if s.case_flags != case_flags: + # Different case sensitivity, so flush, unless the neither + # the previous nor the new string are cased. + if s.case_flags or any(is_cased_i(info, c) for c in + characters): + Sequence._flush_characters(info, characters, + case_flags, items) + + case_flags = s.case_flags + + characters.extend(s.characters) + else: + Sequence._flush_characters(info, characters, case_flags, items) + + items.append(s.pack_characters(info)) + + Sequence._flush_characters(info, characters, case_flags, items) + + return make_sequence(items) + + def remove_captures(self): + self.items = [s.remove_captures() for s in self.items] + return self + + def is_atomic(self): + return all(s.is_atomic() for s in self.items) + + def can_be_affix(self): + return False + + def contains_group(self): + return any(s.contains_group() for s in self.items) + + def get_firstset(self, reverse): + fs = set() + items = self.items + if reverse: + items.reverse() + for s in items: + fs |= s.get_firstset(reverse) + if None not in fs: + return fs + fs.discard(None) + + return fs | set([None]) + + def has_simple_start(self): + return bool(self.items) and self.items[0].has_simple_start() + + def _compile(self, reverse, fuzzy): + seq = self.items + if reverse: + seq = seq[::-1] + + code = [] + for s in seq: + code.extend(s.compile(reverse, fuzzy)) + + return code + + def dump(self, indent, reverse): + for s in self.items: + s.dump(indent, reverse) + + @staticmethod + def _flush_characters(info, characters, case_flags, items): + if not characters: + return + + # Disregard case_flags if all of the characters are case-less. + if case_flags & IGNORECASE: + if not any(is_cased_i(info, c) for c in characters): + case_flags = NOCASE + + if (case_flags & FULLIGNORECASE) == FULLIGNORECASE: + literals = Sequence._fix_full_casefold(characters) + + for item in literals: + chars = item.characters + + if len(chars) == 1: + items.append(Character(chars[0], case_flags=item.case_flags)) + else: + items.append(String(chars, case_flags=item.case_flags)) + else: + if len(characters) == 1: + items.append(Character(characters[0], case_flags=case_flags)) + else: + items.append(String(characters, case_flags=case_flags)) + + characters[:] = [] + + @staticmethod + def _fix_full_casefold(characters): + # Split a literal needing full case-folding into chunks that need it + # and chunks that can use simple case-folding, which is faster. + expanded = [_regex.fold_case(FULL_CASE_FOLDING, c) for c in + _regex.get_expand_on_folding()] + string = _regex.fold_case(FULL_CASE_FOLDING, ''.join(chr(c) + for c in characters)).lower() + chunks = [] + + for e in expanded: + found = string.find(e) + + while found >= 0: + chunks.append((found, found + len(e))) + found = string.find(e, found + 1) + + pos = 0 + literals = [] + + for start, end in Sequence._merge_chunks(chunks): + if pos < start: + literals.append(Literal(characters[pos : start], + case_flags=IGNORECASE)) + + literals.append(Literal(characters[start : end], + case_flags=FULLIGNORECASE)) + pos = end + + if pos < len(characters): + literals.append(Literal(characters[pos : ], case_flags=IGNORECASE)) + + return literals + + @staticmethod + def _merge_chunks(chunks): + if len(chunks) < 2: + return chunks + + chunks.sort() + + start, end = chunks[0] + new_chunks = [] + + for s, e in chunks[1 : ]: + if s <= end: + end = max(end, e) + else: + new_chunks.append((start, end)) + start, end = s, e + + new_chunks.append((start, end)) + + return new_chunks + + def is_empty(self): + return all(i.is_empty() for i in self.items) + + def __eq__(self, other): + return type(self) is type(other) and self.items == other.items + + def max_width(self): + return sum(s.max_width() for s in self.items) + + def get_required_string(self, reverse): + seq = self.items + if reverse: + seq = seq[::-1] + + offset = 0 + + for s in seq: + ofs, req = s.get_required_string(reverse) + offset += ofs + if req: + return offset, req + + return offset, None + +class SetBase(RegexBase): + def __init__(self, info, items, positive=True, case_flags=NOCASE, + zerowidth=False): + RegexBase.__init__(self) + self.info = info + self.items = tuple(items) + self.positive = bool(positive) + self.case_flags = CASE_FLAGS_COMBINATIONS[case_flags] + self.zerowidth = bool(zerowidth) + + self.char_width = 1 + + self._key = (self.__class__, self.items, self.positive, + self.case_flags, self.zerowidth) + + def rebuild(self, positive, case_flags, zerowidth): + return type(self)(self.info, self.items, positive, case_flags, + zerowidth).optimise(self.info, False) + + def get_firstset(self, reverse): + return set([self]) + + def has_simple_start(self): + return True + + def _compile(self, reverse, fuzzy): + flags = 0 + if self.positive: + flags |= POSITIVE_OP + if self.zerowidth: + flags |= ZEROWIDTH_OP + if fuzzy: + flags |= FUZZY_OP + code = [(self._opcode[self.case_flags, reverse], flags)] + for m in self.items: + code.extend(m.compile()) + + code.append((OP.END, )) + + return code + + def dump(self, indent, reverse): + print("{}{} {}{}".format(INDENT * indent, self._op_name, + POS_TEXT[self.positive], CASE_TEXT[self.case_flags])) + for i in self.items: + i.dump(indent + 1, reverse) + + def _handle_case_folding(self, info, in_set): + # Is the set case-sensitive? + if not self.positive or not (self.case_flags & IGNORECASE) or in_set: + return self + + # Is full case-folding possible? + if (not (self.info.flags & UNICODE) or (self.case_flags & + FULLIGNORECASE) != FULLIGNORECASE): + return self + + # Get the characters which expand to multiple codepoints on folding. + expanding_chars = _regex.get_expand_on_folding() + + # Get the folded characters in the set. + items = [] + seen = set() + for ch in expanding_chars: + if self.matches(ord(ch)): + folded = _regex.fold_case(FULL_CASE_FOLDING, ch) + if folded not in seen: + items.append(String([ord(c) for c in folded], + case_flags=self.case_flags)) + seen.add(folded) + + if not items: + # We can fall back to simple case-folding. + return self + + return Branch([self] + items) + + def max_width(self): + # Is the set case-sensitive? + if not self.positive or not (self.case_flags & IGNORECASE): + return 1 + + # Is full case-folding possible? + if (not (self.info.flags & UNICODE) or (self.case_flags & + FULLIGNORECASE) != FULLIGNORECASE): + return 1 + + # Get the characters which expand to multiple codepoints on folding. + expanding_chars = _regex.get_expand_on_folding() + + # Get the folded characters in the set. + seen = set() + for ch in expanding_chars: + if self.matches(ord(ch)): + folded = _regex.fold_case(FULL_CASE_FOLDING, ch) + seen.add(folded) + + if not seen: + return 1 + + return max(len(folded) for folded in seen) + + def __del__(self): + self.info = None + +class SetDiff(SetBase): + _opcode = {(NOCASE, False): OP.SET_DIFF, (IGNORECASE, False): + OP.SET_DIFF_IGN, (FULLCASE, False): OP.SET_DIFF, (FULLIGNORECASE, False): + OP.SET_DIFF_IGN, (NOCASE, True): OP.SET_DIFF_REV, (IGNORECASE, True): + OP.SET_DIFF_IGN_REV, (FULLCASE, True): OP.SET_DIFF_REV, (FULLIGNORECASE, + True): OP.SET_DIFF_IGN_REV} + _op_name = "SET_DIFF" + + def optimise(self, info, reverse, in_set=False): + items = self.items + if len(items) > 2: + items = [items[0], SetUnion(info, items[1 : ])] + + if len(items) == 1: + return items[0].with_flags(case_flags=self.case_flags, + zerowidth=self.zerowidth).optimise(info, reverse, in_set) + + self.items = tuple(m.optimise(info, reverse, in_set=True) for m in + items) + + return self._handle_case_folding(info, in_set) + + def matches(self, ch): + m = self.items[0].matches(ch) and not self.items[1].matches(ch) + return m == self.positive + +class SetInter(SetBase): + _opcode = {(NOCASE, False): OP.SET_INTER, (IGNORECASE, False): + OP.SET_INTER_IGN, (FULLCASE, False): OP.SET_INTER, (FULLIGNORECASE, + False): OP.SET_INTER_IGN, (NOCASE, True): OP.SET_INTER_REV, (IGNORECASE, + True): OP.SET_INTER_IGN_REV, (FULLCASE, True): OP.SET_INTER_REV, + (FULLIGNORECASE, True): OP.SET_INTER_IGN_REV} + _op_name = "SET_INTER" + + def optimise(self, info, reverse, in_set=False): + items = [] + for m in self.items: + m = m.optimise(info, reverse, in_set=True) + if isinstance(m, SetInter) and m.positive: + # Intersection in intersection. + items.extend(m.items) + else: + items.append(m) + + if len(items) == 1: + return items[0].with_flags(case_flags=self.case_flags, + zerowidth=self.zerowidth).optimise(info, reverse, in_set) + + self.items = tuple(items) + + return self._handle_case_folding(info, in_set) + + def matches(self, ch): + m = all(i.matches(ch) for i in self.items) + return m == self.positive + +class SetSymDiff(SetBase): + _opcode = {(NOCASE, False): OP.SET_SYM_DIFF, (IGNORECASE, False): + OP.SET_SYM_DIFF_IGN, (FULLCASE, False): OP.SET_SYM_DIFF, (FULLIGNORECASE, + False): OP.SET_SYM_DIFF_IGN, (NOCASE, True): OP.SET_SYM_DIFF_REV, + (IGNORECASE, True): OP.SET_SYM_DIFF_IGN_REV, (FULLCASE, True): + OP.SET_SYM_DIFF_REV, (FULLIGNORECASE, True): OP.SET_SYM_DIFF_IGN_REV} + _op_name = "SET_SYM_DIFF" + + def optimise(self, info, reverse, in_set=False): + items = [] + for m in self.items: + m = m.optimise(info, reverse, in_set=True) + if isinstance(m, SetSymDiff) and m.positive: + # Symmetric difference in symmetric difference. + items.extend(m.items) + else: + items.append(m) + + if len(items) == 1: + return items[0].with_flags(case_flags=self.case_flags, + zerowidth=self.zerowidth).optimise(info, reverse, in_set) + + self.items = tuple(items) + + return self._handle_case_folding(info, in_set) + + def matches(self, ch): + m = False + for i in self.items: + m = m != i.matches(ch) + + return m == self.positive + +class SetUnion(SetBase): + _opcode = {(NOCASE, False): OP.SET_UNION, (IGNORECASE, False): + OP.SET_UNION_IGN, (FULLCASE, False): OP.SET_UNION, (FULLIGNORECASE, + False): OP.SET_UNION_IGN, (NOCASE, True): OP.SET_UNION_REV, (IGNORECASE, + True): OP.SET_UNION_IGN_REV, (FULLCASE, True): OP.SET_UNION_REV, + (FULLIGNORECASE, True): OP.SET_UNION_IGN_REV} + _op_name = "SET_UNION" + + def optimise(self, info, reverse, in_set=False): + items = [] + for m in self.items: + m = m.optimise(info, reverse, in_set=True) + if isinstance(m, SetUnion) and m.positive: + # Union in union. + items.extend(m.items) + elif isinstance(m, AnyAll): + return AnyAll() + else: + items.append(m) + + # Are there complementary properties? + properties = (set(), set()) + + for m in items: + if isinstance(m, Property): + properties[m.positive].add((m.value, m.case_flags, m.zerowidth)) + + if properties[0] & properties[1]: + return AnyAll() + + if len(items) == 1: + i = items[0] + return i.with_flags(positive=i.positive == self.positive, + case_flags=self.case_flags, + zerowidth=self.zerowidth).optimise(info, reverse, in_set) + + self.items = tuple(items) + + return self._handle_case_folding(info, in_set) + + def _compile(self, reverse, fuzzy): + flags = 0 + if self.positive: + flags |= POSITIVE_OP + if self.zerowidth: + flags |= ZEROWIDTH_OP + if fuzzy: + flags |= FUZZY_OP + + characters, others = defaultdict(list), [] + for m in self.items: + if isinstance(m, Character): + characters[m.positive].append(m.value) + else: + others.append(m) + + code = [(self._opcode[self.case_flags, reverse], flags)] + + for positive, values in characters.items(): + flags = 0 + if positive: + flags |= POSITIVE_OP + if len(values) == 1: + code.append((OP.CHARACTER, flags, values[0])) + else: + code.append((OP.STRING, flags, len(values)) + tuple(values)) + + for m in others: + code.extend(m.compile()) + + code.append((OP.END, )) + + return code + + def matches(self, ch): + m = any(i.matches(ch) for i in self.items) + return m == self.positive + +class Skip(ZeroWidthBase): + _op_name = "SKIP" + _opcode = OP.SKIP + +class StartOfLine(ZeroWidthBase): + _opcode = OP.START_OF_LINE + _op_name = "START_OF_LINE" + +class StartOfLineU(StartOfLine): + _opcode = OP.START_OF_LINE_U + _op_name = "START_OF_LINE_U" + +class StartOfString(ZeroWidthBase): + _opcode = OP.START_OF_STRING + _op_name = "START_OF_STRING" + +class StartOfWord(ZeroWidthBase): + _opcode = OP.START_OF_WORD + _op_name = "START_OF_WORD" + +class String(RegexBase): + _opcode = {(NOCASE, False): OP.STRING, (IGNORECASE, False): OP.STRING_IGN, + (FULLCASE, False): OP.STRING, (FULLIGNORECASE, False): OP.STRING_FLD, + (NOCASE, True): OP.STRING_REV, (IGNORECASE, True): OP.STRING_IGN_REV, + (FULLCASE, True): OP.STRING_REV, (FULLIGNORECASE, True): + OP.STRING_FLD_REV} + + def __init__(self, characters, case_flags=NOCASE): + self.characters = tuple(characters) + self.case_flags = CASE_FLAGS_COMBINATIONS[case_flags] + + if (self.case_flags & FULLIGNORECASE) == FULLIGNORECASE: + folded_characters = [] + for char in self.characters: + folded = _regex.fold_case(FULL_CASE_FOLDING, chr(char)) + folded_characters.extend(ord(c) for c in folded) + else: + folded_characters = self.characters + + self.folded_characters = tuple(folded_characters) + self.required = False + + self._key = self.__class__, self.characters, self.case_flags + + def get_firstset(self, reverse): + if reverse: + pos = -1 + else: + pos = 0 + return set([Character(self.characters[pos], + case_flags=self.case_flags)]) + + def has_simple_start(self): + return True + + def _compile(self, reverse, fuzzy): + flags = 0 + if fuzzy: + flags |= FUZZY_OP + if self.required: + flags |= REQUIRED_OP + return [(self._opcode[self.case_flags, reverse], flags, + len(self.folded_characters)) + self.folded_characters] + + def dump(self, indent, reverse): + display = ascii("".join(chr(c) for c in self.characters)).lstrip("bu") + print("{}STRING {}{}".format(INDENT * indent, display, + CASE_TEXT[self.case_flags])) + + def max_width(self): + return len(self.folded_characters) + + def get_required_string(self, reverse): + return 0, self + +class Literal(String): + def dump(self, indent, reverse): + literal = ''.join(chr(c) for c in self.characters) + display = ascii(literal).lstrip("bu") + print("{}LITERAL MATCH {}{}".format(INDENT * indent, display, + CASE_TEXT[self.case_flags])) + +class StringSet(Branch): + def __init__(self, info, name, case_flags=NOCASE): + self.info = info + self.name = name + self.case_flags = CASE_FLAGS_COMBINATIONS[case_flags] + + self._key = self.__class__, self.name, self.case_flags + + self.set_key = (name, self.case_flags) + if self.set_key not in info.named_lists_used: + info.named_lists_used[self.set_key] = len(info.named_lists_used) + + index = self.info.named_lists_used[self.set_key] + items = self.info.kwargs[self.name] + + case_flags = self.case_flags + + encoding = self.info.flags & _ALL_ENCODINGS + fold_flags = encoding | case_flags + + choices = [] + + for string in items: + if isinstance(string, str): + string = [ord(c) for c in string] + + choices.append([Character(c, case_flags=case_flags) for c in + string]) + + # Sort from longest to shortest. + choices.sort(key=len, reverse=True) + + self.branches = [Sequence(choice) for choice in choices] + + def dump(self, indent, reverse): + print("{}STRING_SET {}{}".format(INDENT * indent, self.name, + CASE_TEXT[self.case_flags])) + + def __del__(self): + self.info = None + +class Source: + "Scanner for the regular expression source string." + def __init__(self, string): + if isinstance(string, str): + self.string = string + self.char_type = chr + else: + self.string = string.decode("latin-1") + self.char_type = lambda c: bytes([c]) + + self.pos = 0 + self.ignore_space = False + self.sep = string[ : 0] + + def peek(self, override_ignore=False): + string = self.string + pos = self.pos + + try: + if self.ignore_space and not override_ignore: + while True: + if string[pos].isspace(): + # Skip over the whitespace. + pos += 1 + elif string[pos] == "#": + # Skip over the comment to the end of the line. + pos = string.index("\n", pos) + else: + break + + return string[pos] + except IndexError: + # We've reached the end of the string. + return string[ : 0] + except ValueError: + # The comment extended to the end of the string. + return string[ : 0] + + def get(self, override_ignore=False): + string = self.string + pos = self.pos + + try: + if self.ignore_space and not override_ignore: + while True: + if string[pos].isspace(): + # Skip over the whitespace. + pos += 1 + elif string[pos] == "#": + # Skip over the comment to the end of the line. + pos = string.index("\n", pos) + else: + break + + ch = string[pos] + self.pos = pos + 1 + return ch + except IndexError: + # We've reached the end of the string. + self.pos = pos + return string[ : 0] + except ValueError: + # The comment extended to the end of the string. + self.pos = len(string) + return string[ : 0] + + def get_many(self, count=1): + string = self.string + pos = self.pos + + try: + if self.ignore_space: + substring = [] + + while len(substring) < count: + while True: + if string[pos].isspace(): + # Skip over the whitespace. + pos += 1 + elif string[pos] == "#": + # Skip over the comment to the end of the line. + pos = string.index("\n", pos) + else: + break + + substring.append(string[pos]) + pos += 1 + + substring = "".join(substring) + else: + substring = string[pos : pos + count] + pos += len(substring) + + self.pos = pos + return substring + except IndexError: + # We've reached the end of the string. + self.pos = len(string) + return "".join(substring) + except ValueError: + # The comment extended to the end of the string. + self.pos = len(string) + return "".join(substring) + + def get_while(self, test_set, include=True, keep_spaces=False): + string = self.string + pos = self.pos + + if self.ignore_space and not keep_spaces: + try: + substring = [] + + while True: + if string[pos].isspace(): + # Skip over the whitespace. + pos += 1 + elif string[pos] == "#": + # Skip over the comment to the end of the line. + pos = string.index("\n", pos) + elif (string[pos] in test_set) == include: + substring.append(string[pos]) + pos += 1 + else: + break + + self.pos = pos + except IndexError: + # We've reached the end of the string. + self.pos = len(string) + except ValueError: + # The comment extended to the end of the string. + self.pos = len(string) + + return "".join(substring) + else: + try: + while (string[pos] in test_set) == include: + pos += 1 + + substring = string[self.pos : pos] + + self.pos = pos + + return substring + except IndexError: + # We've reached the end of the string. + substring = string[self.pos : pos] + + self.pos = pos + + return substring + + def skip_while(self, test_set, include=True): + string = self.string + pos = self.pos + + try: + if self.ignore_space: + while True: + if string[pos].isspace(): + # Skip over the whitespace. + pos += 1 + elif string[pos] == "#": + # Skip over the comment to the end of the line. + pos = string.index("\n", pos) + elif (string[pos] in test_set) == include: + pos += 1 + else: + break + else: + while (string[pos] in test_set) == include: + pos += 1 + + self.pos = pos + except IndexError: + # We've reached the end of the string. + self.pos = len(string) + except ValueError: + # The comment extended to the end of the string. + self.pos = len(string) + + def match(self, substring): + string = self.string + pos = self.pos + + if self.ignore_space: + try: + for c in substring: + while True: + if string[pos].isspace(): + # Skip over the whitespace. + pos += 1 + elif string[pos] == "#": + # Skip over the comment to the end of the line. + pos = string.index("\n", pos) + else: + break + + if string[pos] != c: + return False + + pos += 1 + + self.pos = pos + + return True + except IndexError: + # We've reached the end of the string. + return False + except ValueError: + # The comment extended to the end of the string. + return False + else: + if not string.startswith(substring, pos): + return False + + self.pos = pos + len(substring) + + return True + + def expect(self, substring): + if not self.match(substring): + raise error("missing {}".format(substring), self.string, self.pos) + + def at_end(self): + string = self.string + pos = self.pos + + try: + if self.ignore_space: + while True: + if string[pos].isspace(): + pos += 1 + elif string[pos] == "#": + pos = string.index("\n", pos) + else: + break + + return pos >= len(string) + except IndexError: + # We've reached the end of the string. + return True + except ValueError: + # The comment extended to the end of the string. + return True + +class Info: + "Info about the regular expression." + + def __init__(self, flags=0, char_type=None, kwargs={}): + flags |= DEFAULT_FLAGS[(flags & _ALL_VERSIONS) or DEFAULT_VERSION] + self.flags = flags + self.global_flags = flags + self.inline_locale = False + + self.kwargs = kwargs + + self.group_count = 0 + self.group_index = {} + self.group_name = {} + self.char_type = char_type + self.named_lists_used = {} + self.open_groups = [] + self.open_group_count = {} + self.defined_groups = {} + self.group_calls = [] + self.private_groups = {} + + def open_group(self, name=None): + group = self.group_index.get(name) + if group is None: + while True: + self.group_count += 1 + if name is None or self.group_count not in self.group_name: + break + + group = self.group_count + if name: + self.group_index[name] = group + self.group_name[group] = name + + if group in self.open_groups: + # We have a nested named group. We'll assign it a private group + # number, initially negative until we can assign a proper + # (positive) number. + group_alias = -(len(self.private_groups) + 1) + self.private_groups[group_alias] = group + group = group_alias + + self.open_groups.append(group) + self.open_group_count[group] = self.open_group_count.get(group, 0) + 1 + + return group + + def close_group(self): + self.open_groups.pop() + + def is_open_group(self, name): + # In version 1, a group reference can refer to an open group. We'll + # just pretend the group isn't open. + version = (self.flags & _ALL_VERSIONS) or DEFAULT_VERSION + if version == VERSION1: + return False + + if name.isdigit(): + group = int(name) + else: + group = self.group_index.get(name) + + return group in self.open_groups + +def _check_group_features(info, parsed): + """Checks whether the reverse and fuzzy features of the group calls match + the groups which they call. + """ + call_refs = {} + additional_groups = [] + for call, reverse, fuzzy in info.group_calls: + # Look up the reference of this group call. + key = (call.group, reverse, fuzzy) + ref = call_refs.get(key) + if ref is None: + # This group doesn't have a reference yet, so look up its features. + if call.group == 0: + # Calling the pattern as a whole. + rev = bool(info.flags & REVERSE) + fuz = isinstance(parsed, Fuzzy) + if (rev, fuz) != (reverse, fuzzy): + # The pattern as a whole doesn't have the features we want, + # so we'll need to make a copy of it with the desired + # features. + additional_groups.append((CallRef(len(call_refs), parsed), + reverse, fuzzy)) + else: + # Calling a capture group. + def_info = info.defined_groups[call.group] + group = def_info[0] + if def_info[1 : ] != (reverse, fuzzy): + # The group doesn't have the features we want, so we'll + # need to make a copy of it with the desired features. + additional_groups.append((group, reverse, fuzzy)) + + ref = len(call_refs) + call_refs[key] = ref + + call.call_ref = ref + + info.call_refs = call_refs + info.additional_groups = additional_groups + +def _get_required_string(parsed, flags): + "Gets the required string and related info of a parsed pattern." + + req_offset, required = parsed.get_required_string(bool(flags & REVERSE)) + if required: + required.required = True + if req_offset >= UNLIMITED: + req_offset = -1 + + req_flags = required.case_flags + if not (flags & UNICODE): + req_flags &= ~UNICODE + + req_chars = required.folded_characters + else: + req_offset = 0 + req_chars = () + req_flags = 0 + + return req_offset, req_chars, req_flags + +class Scanner: + def __init__(self, lexicon, flags=0): + self.lexicon = lexicon + + # Combine phrases into a compound pattern. + patterns = [] + for phrase, action in lexicon: + # Parse the regular expression. + source = Source(phrase) + info = Info(flags, source.char_type) + source.ignore_space = bool(info.flags & VERBOSE) + parsed = _parse_pattern(source, info) + if not source.at_end(): + raise error("unbalanced parenthesis", source.string, + source.pos) + + # We want to forbid capture groups within each phrase. + patterns.append(parsed.remove_captures()) + + # Combine all the subpatterns into one pattern. + info = Info(flags) + patterns = [Group(info, g + 1, p) for g, p in enumerate(patterns)] + parsed = Branch(patterns) + + # Optimise the compound pattern. + reverse = bool(info.flags & REVERSE) + parsed = parsed.optimise(info, reverse) + parsed = parsed.pack_characters(info) + + # Get the required string. + req_offset, req_chars, req_flags = _get_required_string(parsed, + info.flags) + + # Check the features of the groups. + _check_group_features(info, parsed) + + # Complain if there are any group calls. They are not supported by the + # Scanner class. + if info.call_refs: + raise error("recursive regex not supported by Scanner", + source.string, source.pos) + + reverse = bool(info.flags & REVERSE) + + # Compile the compound pattern. The result is a list of tuples. + code = parsed.compile(reverse) + [(OP.SUCCESS, )] + + # Flatten the code into a list of ints. + code = _flatten_code(code) + + if not parsed.has_simple_start(): + # Get the first set, if possible. + try: + fs_code = _compile_firstset(info, parsed.get_firstset(reverse)) + fs_code = _flatten_code(fs_code) + code = fs_code + code + except _FirstSetError: + pass + + # Check the global flags for conflicts. + version = (info.flags & _ALL_VERSIONS) or DEFAULT_VERSION + if version not in (0, VERSION0, VERSION1): + raise ValueError("VERSION0 and VERSION1 flags are mutually incompatible") + + # Create the PatternObject. + # + # Local flags like IGNORECASE affect the code generation, but aren't + # needed by the PatternObject itself. Conversely, global flags like + # LOCALE _don't_ affect the code generation but _are_ needed by the + # PatternObject. + self.scanner = _regex.compile(None, (flags & GLOBAL_FLAGS) | version, + code, {}, {}, {}, [], req_offset, req_chars, req_flags, + len(patterns)) + + def scan(self, string): + result = [] + append = result.append + match = self.scanner.scanner(string).match + i = 0 + while True: + m = match() + if not m: + break + j = m.end() + if i == j: + break + action = self.lexicon[m.lastindex - 1][1] + if hasattr(action, '__call__'): + self.match = m + action = action(self, m.group()) + if action is not None: + append(action) + i = j + + return result, string[i : ] + +# Get the known properties dict. +PROPERTIES = _regex.get_properties() + +# Build the inverse of the properties dict. +PROPERTY_NAMES = {} +for prop_name, (prop_id, values) in PROPERTIES.items(): + name, prop_values = PROPERTY_NAMES.get(prop_id, ("", {})) + name = max(name, prop_name, key=len) + PROPERTY_NAMES[prop_id] = name, prop_values + + for val_name, val_id in values.items(): + prop_values[val_id] = max(prop_values.get(val_id, ""), val_name, + key=len) + +# Character escape sequences. +CHARACTER_ESCAPES = { + "a": "\a", + "b": "\b", + "f": "\f", + "n": "\n", + "r": "\r", + "t": "\t", + "v": "\v", +} + +ASCII_ENCODING = 1 +UNICODE_ENCODING = 2 + +# Predefined character set escape sequences. +CHARSET_ESCAPES = { + "d": lookup_property(None, "Digit", True), + "D": lookup_property(None, "Digit", False), + "h": lookup_property(None, "Blank", True), + "s": lookup_property(None, "Space", True), + "S": lookup_property(None, "Space", False), + "w": lookup_property(None, "Word", True), + "W": lookup_property(None, "Word", False), +} + +ASCII_CHARSET_ESCAPES = dict(CHARSET_ESCAPES) +ASCII_CHARSET_ESCAPES.update({ + "d": lookup_property(None, "Digit", True, encoding=ASCII_ENCODING), + "D": lookup_property(None, "Digit", False, encoding=ASCII_ENCODING), + "s": lookup_property(None, "Space", True, encoding=ASCII_ENCODING), + "S": lookup_property(None, "Space", False, encoding=ASCII_ENCODING), + "w": lookup_property(None, "Word", True, encoding=ASCII_ENCODING), + "W": lookup_property(None, "Word", False, encoding=ASCII_ENCODING), +}) +UNICODE_CHARSET_ESCAPES = dict(CHARSET_ESCAPES) +UNICODE_CHARSET_ESCAPES.update({ + "d": lookup_property(None, "Digit", True, encoding=UNICODE_ENCODING), + "D": lookup_property(None, "Digit", False, encoding=UNICODE_ENCODING), + "s": lookup_property(None, "Space", True, encoding=UNICODE_ENCODING), + "S": lookup_property(None, "Space", False, encoding=UNICODE_ENCODING), + "w": lookup_property(None, "Word", True, encoding=UNICODE_ENCODING), + "W": lookup_property(None, "Word", False, encoding=UNICODE_ENCODING), +}) + +# Positional escape sequences. +POSITION_ESCAPES = { + "A": StartOfString(), + "b": Boundary(), + "B": Boundary(False), + "K": Keep(), + "m": StartOfWord(), + "M": EndOfWord(), + "Z": EndOfString(), + "z": EndOfString(), +} +ASCII_POSITION_ESCAPES = dict(POSITION_ESCAPES) +ASCII_POSITION_ESCAPES.update({ + "b": Boundary(encoding=ASCII_ENCODING), + "B": Boundary(False, encoding=ASCII_ENCODING), + "m": StartOfWord(encoding=ASCII_ENCODING), + "M": EndOfWord(encoding=ASCII_ENCODING), +}) +UNICODE_POSITION_ESCAPES = dict(POSITION_ESCAPES) +UNICODE_POSITION_ESCAPES.update({ + "b": Boundary(encoding=UNICODE_ENCODING), + "B": Boundary(False, encoding=UNICODE_ENCODING), + "m": StartOfWord(encoding=UNICODE_ENCODING), + "M": EndOfWord(encoding=UNICODE_ENCODING), +}) + +# Positional escape sequences when WORD flag set. +WORD_POSITION_ESCAPES = dict(POSITION_ESCAPES) +WORD_POSITION_ESCAPES.update({ + "b": DefaultBoundary(), + "B": DefaultBoundary(False), + "m": DefaultStartOfWord(), + "M": DefaultEndOfWord(), +}) + +# Regex control verbs. +VERBS = { + "FAIL": Failure(), + "F": Failure(), + "PRUNE": Prune(), + "SKIP": Skip(), +} diff --git a/.venv/lib/python3.12/site-packages/regex/tests/__pycache__/test_regex.cpython-312.pyc b/.venv/lib/python3.12/site-packages/regex/tests/__pycache__/test_regex.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..cecfb005678a8fedc8fd8a37cb9e05597f33015c --- /dev/null +++ b/.venv/lib/python3.12/site-packages/regex/tests/__pycache__/test_regex.cpython-312.pyc @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:620cccb245faa4c6c5d69017543a48ae1b06dae739af42eb65b8d2b3db16c875 +size 334958 diff --git a/.venv/lib/python3.12/site-packages/regex/tests/test_regex.py b/.venv/lib/python3.12/site-packages/regex/tests/test_regex.py new file mode 100644 index 0000000000000000000000000000000000000000..b391472b5bb4ea94924376c448a3674b8c6ff8ad --- /dev/null +++ b/.venv/lib/python3.12/site-packages/regex/tests/test_regex.py @@ -0,0 +1,4540 @@ +from weakref import proxy +import copy +import pickle +import regex +import string +import sys +import unittest + +# String subclasses for issue 18468. +class StrSubclass(str): + def __getitem__(self, index): + return StrSubclass(super().__getitem__(index)) + +class BytesSubclass(bytes): + def __getitem__(self, index): + return BytesSubclass(super().__getitem__(index)) + +class RegexTests(unittest.TestCase): + PATTERN_CLASS = "" + FLAGS_WITH_COMPILED_PAT = "cannot process flags argument with a compiled pattern" + INVALID_GROUP_REF = "invalid group reference" + MISSING_GT = "missing >" + BAD_GROUP_NAME = "bad character in group name" + MISSING_GROUP_NAME = "missing group name" + MISSING_LT = "missing <" + UNKNOWN_GROUP_I = "unknown group" + UNKNOWN_GROUP = "unknown group" + BAD_ESCAPE = r"bad escape \(end of pattern\)" + BAD_OCTAL_ESCAPE = r"bad escape \\" + BAD_SET = "unterminated character set" + STR_PAT_ON_BYTES = "cannot use a string pattern on a bytes-like object" + BYTES_PAT_ON_STR = "cannot use a bytes pattern on a string-like object" + STR_PAT_BYTES_TEMPL = "expected str instance, bytes found" + BYTES_PAT_STR_TEMPL = "expected a bytes-like object, str found" + BYTES_PAT_UNI_FLAG = "cannot use UNICODE flag with a bytes pattern" + MIXED_FLAGS = "ASCII, LOCALE and UNICODE flags are mutually incompatible" + MISSING_RPAREN = "missing \\)" + TRAILING_CHARS = "unbalanced parenthesis" + BAD_CHAR_RANGE = "bad character range" + NOTHING_TO_REPEAT = "nothing to repeat" + MULTIPLE_REPEAT = "multiple repeat" + OPEN_GROUP = "cannot refer to an open group" + DUPLICATE_GROUP = "duplicate group" + CANT_TURN_OFF = "bad inline flags: cannot turn flags off" + UNDEF_CHAR_NAME = "undefined character name" + + def assertTypedEqual(self, actual, expect, msg=None): + self.assertEqual(actual, expect, msg) + + def recurse(actual, expect): + if isinstance(expect, (tuple, list)): + for x, y in zip(actual, expect): + recurse(x, y) + else: + self.assertIs(type(actual), type(expect), msg) + + recurse(actual, expect) + + def test_weakref(self): + s = 'QabbbcR' + x = regex.compile('ab+c') + y = proxy(x) + if x.findall('QabbbcR') != y.findall('QabbbcR'): + self.fail() + + def test_search_star_plus(self): + self.assertEqual(regex.search('a*', 'xxx').span(0), (0, 0)) + self.assertEqual(regex.search('x*', 'axx').span(), (0, 0)) + self.assertEqual(regex.search('x+', 'axx').span(0), (1, 3)) + self.assertEqual(regex.search('x+', 'axx').span(), (1, 3)) + self.assertEqual(regex.search('x', 'aaa'), None) + self.assertEqual(regex.match('a*', 'xxx').span(0), (0, 0)) + self.assertEqual(regex.match('a*', 'xxx').span(), (0, 0)) + self.assertEqual(regex.match('x*', 'xxxa').span(0), (0, 3)) + self.assertEqual(regex.match('x*', 'xxxa').span(), (0, 3)) + self.assertEqual(regex.match('a+', 'xxx'), None) + + def bump_num(self, matchobj): + int_value = int(matchobj[0]) + return str(int_value + 1) + + def test_basic_regex_sub(self): + self.assertEqual(regex.sub("(?i)b+", "x", "bbbb BBBB"), 'x x') + self.assertEqual(regex.sub(r'\d+', self.bump_num, '08.2 -2 23x99y'), + '9.3 -3 24x100y') + self.assertEqual(regex.sub(r'\d+', self.bump_num, '08.2 -2 23x99y', 3), + '9.3 -3 23x99y') + + self.assertEqual(regex.sub('.', lambda m: r"\n", 'x'), "\\n") + self.assertEqual(regex.sub('.', r"\n", 'x'), "\n") + + self.assertEqual(regex.sub('(?Px)', r'\g\g', 'xx'), 'xxxx') + self.assertEqual(regex.sub('(?Px)', r'\g\g<1>', 'xx'), 'xxxx') + self.assertEqual(regex.sub('(?Px)', r'\g\g', 'xx'), + 'xxxx') + self.assertEqual(regex.sub('(?Px)', r'\g<1>\g<1>', 'xx'), 'xxxx') + + self.assertEqual(regex.sub('a', r'\t\n\v\r\f\a\b', 'a'), "\t\n\v\r\f\a\b") + self.assertEqual(regex.sub('a', '\t\n\v\r\f\a', 'a'), "\t\n\v\r\f\a") + self.assertEqual(regex.sub('a', '\t\n\v\r\f\a', 'a'), chr(9) + chr(10) + + chr(11) + chr(13) + chr(12) + chr(7)) + + self.assertEqual(regex.sub(r'^\s*', 'X', 'test'), 'Xtest') + + self.assertEqual(regex.sub(r"x", r"\x0A", "x"), "\n") + self.assertEqual(regex.sub(r"x", r"\u000A", "x"), "\n") + self.assertEqual(regex.sub(r"x", r"\U0000000A", "x"), "\n") + self.assertEqual(regex.sub(r"x", r"\N{LATIN CAPITAL LETTER A}", + "x"), "A") + + self.assertEqual(regex.sub(br"x", br"\x0A", b"x"), b"\n") + + def test_bug_449964(self): + # Fails for group followed by other escape. + self.assertEqual(regex.sub(r'(?Px)', r'\g<1>\g<1>\b', 'xx'), + "xx\bxx\b") + + def test_bug_449000(self): + # Test for sub() on escaped characters. + self.assertEqual(regex.sub(r'\r\n', r'\n', 'abc\r\ndef\r\n'), + "abc\ndef\n") + self.assertEqual(regex.sub('\r\n', r'\n', 'abc\r\ndef\r\n'), + "abc\ndef\n") + self.assertEqual(regex.sub(r'\r\n', '\n', 'abc\r\ndef\r\n'), + "abc\ndef\n") + self.assertEqual(regex.sub('\r\n', '\n', 'abc\r\ndef\r\n'), + "abc\ndef\n") + + def test_bug_1661(self): + # Verify that flags do not get silently ignored with compiled patterns + pattern = regex.compile('.') + self.assertRaisesRegex(ValueError, self.FLAGS_WITH_COMPILED_PAT, + lambda: regex.match(pattern, 'A', regex.I)) + self.assertRaisesRegex(ValueError, self.FLAGS_WITH_COMPILED_PAT, + lambda: regex.search(pattern, 'A', regex.I)) + self.assertRaisesRegex(ValueError, self.FLAGS_WITH_COMPILED_PAT, + lambda: regex.findall(pattern, 'A', regex.I)) + self.assertRaisesRegex(ValueError, self.FLAGS_WITH_COMPILED_PAT, + lambda: regex.compile(pattern, regex.I)) + + def test_bug_3629(self): + # A regex that triggered a bug in the sre-code validator + self.assertEqual(repr(type(regex.compile("(?P)(?(quote))"))), + self.PATTERN_CLASS) + + def test_sub_template_numeric_escape(self): + # Bug 776311 and friends. + self.assertEqual(regex.sub('x', r'\0', 'x'), "\0") + self.assertEqual(regex.sub('x', r'\000', 'x'), "\000") + self.assertEqual(regex.sub('x', r'\001', 'x'), "\001") + self.assertEqual(regex.sub('x', r'\008', 'x'), "\0" + "8") + self.assertEqual(regex.sub('x', r'\009', 'x'), "\0" + "9") + self.assertEqual(regex.sub('x', r'\111', 'x'), "\111") + self.assertEqual(regex.sub('x', r'\117', 'x'), "\117") + + self.assertEqual(regex.sub('x', r'\1111', 'x'), "\1111") + self.assertEqual(regex.sub('x', r'\1111', 'x'), "\111" + "1") + + self.assertEqual(regex.sub('x', r'\00', 'x'), '\x00') + self.assertEqual(regex.sub('x', r'\07', 'x'), '\x07') + self.assertEqual(regex.sub('x', r'\08', 'x'), "\0" + "8") + self.assertEqual(regex.sub('x', r'\09', 'x'), "\0" + "9") + self.assertEqual(regex.sub('x', r'\0a', 'x'), "\0" + "a") + + self.assertEqual(regex.sub('x', r'\400', 'x'), "\u0100") + self.assertEqual(regex.sub('x', r'\777', 'x'), "\u01FF") + self.assertEqual(regex.sub(b'x', br'\400', b'x'), b"\x00") + self.assertEqual(regex.sub(b'x', br'\777', b'x'), b"\xFF") + + self.assertRaisesRegex(regex.error, self.INVALID_GROUP_REF, lambda: + regex.sub('x', r'\1', 'x')) + self.assertRaisesRegex(regex.error, self.INVALID_GROUP_REF, lambda: + regex.sub('x', r'\8', 'x')) + self.assertRaisesRegex(regex.error, self.INVALID_GROUP_REF, lambda: + regex.sub('x', r'\9', 'x')) + self.assertRaisesRegex(regex.error, self.INVALID_GROUP_REF, lambda: + regex.sub('x', r'\11', 'x')) + self.assertRaisesRegex(regex.error, self.INVALID_GROUP_REF, lambda: + regex.sub('x', r'\18', 'x')) + self.assertRaisesRegex(regex.error, self.INVALID_GROUP_REF, lambda: + regex.sub('x', r'\1a', 'x')) + self.assertRaisesRegex(regex.error, self.INVALID_GROUP_REF, lambda: + regex.sub('x', r'\90', 'x')) + self.assertRaisesRegex(regex.error, self.INVALID_GROUP_REF, lambda: + regex.sub('x', r'\99', 'x')) + self.assertRaisesRegex(regex.error, self.INVALID_GROUP_REF, lambda: + regex.sub('x', r'\118', 'x')) # r'\11' + '8' + self.assertRaisesRegex(regex.error, self.INVALID_GROUP_REF, lambda: + regex.sub('x', r'\11a', 'x')) + self.assertRaisesRegex(regex.error, self.INVALID_GROUP_REF, lambda: + regex.sub('x', r'\181', 'x')) # r'\18' + '1' + self.assertRaisesRegex(regex.error, self.INVALID_GROUP_REF, lambda: + regex.sub('x', r'\800', 'x')) # r'\80' + '0' + + # In Python 2.3 (etc), these loop endlessly in sre_parser.py. + self.assertEqual(regex.sub('(((((((((((x)))))))))))', r'\11', 'x'), + 'x') + self.assertEqual(regex.sub('((((((((((y))))))))))(.)', r'\118', 'xyz'), + 'xz8') + self.assertEqual(regex.sub('((((((((((y))))))))))(.)', r'\11a', 'xyz'), + 'xza') + + def test_qualified_re_sub(self): + self.assertEqual(regex.sub('a', 'b', 'aaaaa'), 'bbbbb') + self.assertEqual(regex.sub('a', 'b', 'aaaaa', 1), 'baaaa') + + def test_bug_114660(self): + self.assertEqual(regex.sub(r'(\S)\s+(\S)', r'\1 \2', 'hello there'), + 'hello there') + + def test_bug_462270(self): + # Test for empty sub() behaviour, see SF bug #462270 + if sys.version_info >= (3, 7, 0): + self.assertEqual(regex.sub('(?V0)x*', '-', 'abxd'), '-a-b--d-') + else: + self.assertEqual(regex.sub('(?V0)x*', '-', 'abxd'), '-a-b-d-') + self.assertEqual(regex.sub('(?V1)x*', '-', 'abxd'), '-a-b--d-') + self.assertEqual(regex.sub('x+', '-', 'abxd'), 'ab-d') + + def test_bug_14462(self): + # chr(255) is a valid identifier in Python 3. + group_name = '\xFF' + self.assertEqual(regex.search(r'(?P<' + group_name + '>a)', + 'abc').group(group_name), 'a') + + def test_symbolic_refs(self): + self.assertRaisesRegex(regex.error, self.MISSING_GT, lambda: + regex.sub('(?Px)', r'\gx)', r'\g<', 'xx')) + self.assertRaisesRegex(regex.error, self.MISSING_LT, lambda: + regex.sub('(?Px)', r'\g', 'xx')) + self.assertRaisesRegex(regex.error, self.BAD_GROUP_NAME, lambda: + regex.sub('(?Px)', r'\g', 'xx')) + self.assertRaisesRegex(regex.error, self.BAD_GROUP_NAME, lambda: + regex.sub('(?Px)', r'\g<1a1>', 'xx')) + self.assertRaisesRegex(IndexError, self.UNKNOWN_GROUP_I, lambda: + regex.sub('(?Px)', r'\g', 'xx')) + + # The new behaviour of unmatched but valid groups is to treat them like + # empty matches in the replacement template, like in Perl. + self.assertEqual(regex.sub('(?Px)|(?Py)', r'\g', 'xx'), '') + self.assertEqual(regex.sub('(?Px)|(?Py)', r'\2', 'xx'), '') + + # The old behaviour was to raise it as an IndexError. + self.assertRaisesRegex(regex.error, self.BAD_GROUP_NAME, lambda: + regex.sub('(?Px)', r'\g<-1>', 'xx')) + + def test_re_subn(self): + self.assertEqual(regex.subn("(?i)b+", "x", "bbbb BBBB"), ('x x', 2)) + self.assertEqual(regex.subn("b+", "x", "bbbb BBBB"), ('x BBBB', 1)) + self.assertEqual(regex.subn("b+", "x", "xyz"), ('xyz', 0)) + self.assertEqual(regex.subn("b*", "x", "xyz"), ('xxxyxzx', 4)) + self.assertEqual(regex.subn("b*", "x", "xyz", 2), ('xxxyz', 2)) + + def test_re_split(self): + self.assertEqual(regex.split(":", ":a:b::c"), ['', 'a', 'b', '', 'c']) + if sys.version_info >= (3, 7, 0): + self.assertEqual(regex.split(":*", ":a:b::c"), ['', '', 'a', '', + 'b', '', 'c', '']) + self.assertEqual(regex.split("(:*)", ":a:b::c"), ['', ':', '', '', + 'a', ':', '', '', 'b', '::', '', '', 'c', '', '']) + self.assertEqual(regex.split("(?::*)", ":a:b::c"), ['', '', 'a', + '', 'b', '', 'c', '']) + self.assertEqual(regex.split("(:)*", ":a:b::c"), ['', ':', '', + None, 'a', ':', '', None, 'b', ':', '', None, 'c', None, '']) + else: + self.assertEqual(regex.split(":*", ":a:b::c"), ['', 'a', 'b', 'c']) + self.assertEqual(regex.split("(:*)", ":a:b::c"), ['', ':', 'a', + ':', 'b', '::', 'c']) + self.assertEqual(regex.split("(?::*)", ":a:b::c"), ['', 'a', 'b', + 'c']) + self.assertEqual(regex.split("(:)*", ":a:b::c"), ['', ':', 'a', + ':', 'b', ':', 'c']) + self.assertEqual(regex.split("([b:]+)", ":a:b::c"), ['', ':', 'a', + ':b::', 'c']) + self.assertEqual(regex.split("(b)|(:+)", ":a:b::c"), ['', None, ':', + 'a', None, ':', '', 'b', None, '', None, '::', 'c']) + self.assertEqual(regex.split("(?:b)|(?::+)", ":a:b::c"), ['', 'a', '', + '', 'c']) + + self.assertEqual(regex.split("x", "xaxbxc"), ['', 'a', 'b', 'c']) + self.assertEqual([m for m in regex.splititer("x", "xaxbxc")], ['', 'a', + 'b', 'c']) + + self.assertEqual(regex.split("(?r)x", "xaxbxc"), ['c', 'b', 'a', '']) + self.assertEqual([m for m in regex.splititer("(?r)x", "xaxbxc")], ['c', + 'b', 'a', '']) + + self.assertEqual(regex.split("(x)|(y)", "xaxbxc"), ['', 'x', None, 'a', + 'x', None, 'b', 'x', None, 'c']) + self.assertEqual([m for m in regex.splititer("(x)|(y)", "xaxbxc")], + ['', 'x', None, 'a', 'x', None, 'b', 'x', None, 'c']) + + self.assertEqual(regex.split("(?r)(x)|(y)", "xaxbxc"), ['c', 'x', None, + 'b', 'x', None, 'a', 'x', None, '']) + self.assertEqual([m for m in regex.splititer("(?r)(x)|(y)", "xaxbxc")], + ['c', 'x', None, 'b', 'x', None, 'a', 'x', None, '']) + + self.assertEqual(regex.split(r"(?V1)\b", "a b c"), ['', 'a', ' ', 'b', + ' ', 'c', '']) + self.assertEqual(regex.split(r"(?V1)\m", "a b c"), ['', 'a ', 'b ', + 'c']) + self.assertEqual(regex.split(r"(?V1)\M", "a b c"), ['a', ' b', ' c', + '']) + + def test_qualified_re_split(self): + self.assertEqual(regex.split(":", ":a:b::c", 2), ['', 'a', 'b::c']) + self.assertEqual(regex.split(':', 'a:b:c:d', 2), ['a', 'b', 'c:d']) + self.assertEqual(regex.split("(:)", ":a:b::c", 2), ['', ':', 'a', ':', + 'b::c']) + + if sys.version_info >= (3, 7, 0): + self.assertEqual(regex.split("(:*)", ":a:b::c", 2), ['', ':', '', + '', 'a:b::c']) + else: + self.assertEqual(regex.split("(:*)", ":a:b::c", 2), ['', ':', 'a', + ':', 'b::c']) + + def test_re_findall(self): + self.assertEqual(regex.findall(":+", "abc"), []) + self.assertEqual(regex.findall(":+", "a:b::c:::d"), [':', '::', ':::']) + self.assertEqual(regex.findall("(:+)", "a:b::c:::d"), [':', '::', + ':::']) + self.assertEqual(regex.findall("(:)(:*)", "a:b::c:::d"), [(':', ''), + (':', ':'), (':', '::')]) + + self.assertEqual(regex.findall(r"\((?P.{0,5}?TEST)\)", + "(MY TEST)"), ["MY TEST"]) + self.assertEqual(regex.findall(r"\((?P.{0,3}?TEST)\)", + "(MY TEST)"), ["MY TEST"]) + self.assertEqual(regex.findall(r"\((?P.{0,3}?T)\)", "(MY T)"), + ["MY T"]) + + self.assertEqual(regex.findall(r"[^a]{2}[A-Z]", "\n S"), [' S']) + self.assertEqual(regex.findall(r"[^a]{2,3}[A-Z]", "\n S"), ['\n S']) + self.assertEqual(regex.findall(r"[^a]{2,3}[A-Z]", "\n S"), [' S']) + + self.assertEqual(regex.findall(r"X(Y[^Y]+?){1,2}( |Q)+DEF", + "XYABCYPPQ\nQ DEF"), [('YPPQ\n', ' ')]) + + self.assertEqual(regex.findall(r"(\nTest(\n+.+?){0,2}?)?\n+End", + "\nTest\nxyz\nxyz\nEnd"), [('\nTest\nxyz\nxyz', '\nxyz')]) + + def test_bug_117612(self): + self.assertEqual(regex.findall(r"(a|(b))", "aba"), [('a', ''), ('b', + 'b'), ('a', '')]) + + def test_re_match(self): + self.assertEqual(regex.match('a', 'a')[:], ('a',)) + self.assertEqual(regex.match('(a)', 'a')[:], ('a', 'a')) + self.assertEqual(regex.match(r'(a)', 'a')[0], 'a') + self.assertEqual(regex.match(r'(a)', 'a')[1], 'a') + self.assertEqual(regex.match(r'(a)', 'a').group(1, 1), ('a', 'a')) + + pat = regex.compile('((a)|(b))(c)?') + self.assertEqual(pat.match('a')[:], ('a', 'a', 'a', None, None)) + self.assertEqual(pat.match('b')[:], ('b', 'b', None, 'b', None)) + self.assertEqual(pat.match('ac')[:], ('ac', 'a', 'a', None, 'c')) + self.assertEqual(pat.match('bc')[:], ('bc', 'b', None, 'b', 'c')) + self.assertEqual(pat.match('bc')[:], ('bc', 'b', None, 'b', 'c')) + + # A single group. + m = regex.match('(a)', 'a') + self.assertEqual(m.group(), 'a') + self.assertEqual(m.group(0), 'a') + self.assertEqual(m.group(1), 'a') + self.assertEqual(m.group(1, 1), ('a', 'a')) + + pat = regex.compile('(?:(?Pa)|(?Pb))(?Pc)?') + self.assertEqual(pat.match('a').group(1, 2, 3), ('a', None, None)) + self.assertEqual(pat.match('b').group('a1', 'b2', 'c3'), (None, 'b', + None)) + self.assertEqual(pat.match('ac').group(1, 'b2', 3), ('a', None, 'c')) + + def test_re_groupref_exists(self): + self.assertEqual(regex.match(r'^(\()?([^()]+)(?(1)\))$', '(a)')[:], + ('(a)', '(', 'a')) + self.assertEqual(regex.match(r'^(\()?([^()]+)(?(1)\))$', 'a')[:], ('a', + None, 'a')) + self.assertEqual(regex.match(r'^(\()?([^()]+)(?(1)\))$', 'a)'), None) + self.assertEqual(regex.match(r'^(\()?([^()]+)(?(1)\))$', '(a'), None) + self.assertEqual(regex.match('^(?:(a)|c)((?(1)b|d))$', 'ab')[:], ('ab', + 'a', 'b')) + self.assertEqual(regex.match('^(?:(a)|c)((?(1)b|d))$', 'cd')[:], ('cd', + None, 'd')) + self.assertEqual(regex.match('^(?:(a)|c)((?(1)|d))$', 'cd')[:], ('cd', + None, 'd')) + self.assertEqual(regex.match('^(?:(a)|c)((?(1)|d))$', 'a')[:], ('a', + 'a', '')) + + # Tests for bug #1177831: exercise groups other than the first group. + p = regex.compile('(?Pa)(?Pb)?((?(g2)c|d))') + self.assertEqual(p.match('abc')[:], ('abc', 'a', 'b', 'c')) + self.assertEqual(p.match('ad')[:], ('ad', 'a', None, 'd')) + self.assertEqual(p.match('abd'), None) + self.assertEqual(p.match('ac'), None) + + def test_re_groupref(self): + self.assertEqual(regex.match(r'^(\|)?([^()]+)\1$', '|a|')[:], ('|a|', + '|', 'a')) + self.assertEqual(regex.match(r'^(\|)?([^()]+)\1?$', 'a')[:], ('a', + None, 'a')) + self.assertEqual(regex.match(r'^(\|)?([^()]+)\1$', 'a|'), None) + self.assertEqual(regex.match(r'^(\|)?([^()]+)\1$', '|a'), None) + self.assertEqual(regex.match(r'^(?:(a)|c)(\1)$', 'aa')[:], ('aa', 'a', + 'a')) + self.assertEqual(regex.match(r'^(?:(a)|c)(\1)?$', 'c')[:], ('c', None, + None)) + + self.assertEqual(regex.findall(r"(?i)(.{1,40}?),(.{1,40}?)(?:;)+(.{1,80}).{1,40}?\3(\ |;)+(.{1,80}?)\1", + "TEST, BEST; LEST ; Lest 123 Test, Best"), [('TEST', ' BEST', + ' LEST', ' ', '123 ')]) + + def test_groupdict(self): + self.assertEqual(regex.match('(?Pfirst) (?Psecond)', + 'first second').groupdict(), {'first': 'first', 'second': 'second'}) + + def test_expand(self): + self.assertEqual(regex.match("(?Pfirst) (?Psecond)", + "first second").expand(r"\2 \1 \g \g"), + 'second first second first') + + def test_repeat_minmax(self): + self.assertEqual(regex.match(r"^(\w){1}$", "abc"), None) + self.assertEqual(regex.match(r"^(\w){1}?$", "abc"), None) + self.assertEqual(regex.match(r"^(\w){1,2}$", "abc"), None) + self.assertEqual(regex.match(r"^(\w){1,2}?$", "abc"), None) + + self.assertEqual(regex.match(r"^(\w){3}$", "abc")[1], 'c') + self.assertEqual(regex.match(r"^(\w){1,3}$", "abc")[1], 'c') + self.assertEqual(regex.match(r"^(\w){1,4}$", "abc")[1], 'c') + self.assertEqual(regex.match(r"^(\w){3,4}?$", "abc")[1], 'c') + self.assertEqual(regex.match(r"^(\w){3}?$", "abc")[1], 'c') + self.assertEqual(regex.match(r"^(\w){1,3}?$", "abc")[1], 'c') + self.assertEqual(regex.match(r"^(\w){1,4}?$", "abc")[1], 'c') + self.assertEqual(regex.match(r"^(\w){3,4}?$", "abc")[1], 'c') + + self.assertEqual(regex.match("^x{1}$", "xxx"), None) + self.assertEqual(regex.match("^x{1}?$", "xxx"), None) + self.assertEqual(regex.match("^x{1,2}$", "xxx"), None) + self.assertEqual(regex.match("^x{1,2}?$", "xxx"), None) + + self.assertEqual(regex.match("^x{1}", "xxx")[0], 'x') + self.assertEqual(regex.match("^x{1}?", "xxx")[0], 'x') + self.assertEqual(regex.match("^x{0,1}", "xxx")[0], 'x') + self.assertEqual(regex.match("^x{0,1}?", "xxx")[0], '') + + self.assertEqual(bool(regex.match("^x{3}$", "xxx")), True) + self.assertEqual(bool(regex.match("^x{1,3}$", "xxx")), True) + self.assertEqual(bool(regex.match("^x{1,4}$", "xxx")), True) + self.assertEqual(bool(regex.match("^x{3,4}?$", "xxx")), True) + self.assertEqual(bool(regex.match("^x{3}?$", "xxx")), True) + self.assertEqual(bool(regex.match("^x{1,3}?$", "xxx")), True) + self.assertEqual(bool(regex.match("^x{1,4}?$", "xxx")), True) + self.assertEqual(bool(regex.match("^x{3,4}?$", "xxx")), True) + + self.assertEqual(regex.match("^x{}$", "xxx"), None) + self.assertEqual(bool(regex.match("^x{}$", "x{}")), True) + + def test_getattr(self): + self.assertEqual(regex.compile("(?i)(a)(b)").pattern, '(?i)(a)(b)') + self.assertEqual(regex.compile("(?i)(a)(b)").flags, regex.I | regex.U | + regex.DEFAULT_VERSION) + self.assertEqual(regex.compile(b"(?i)(a)(b)").flags, regex.A | regex.I + | regex.DEFAULT_VERSION) + self.assertEqual(regex.compile("(?i)(a)(b)").groups, 2) + self.assertEqual(regex.compile("(?i)(a)(b)").groupindex, {}) + + self.assertEqual(regex.compile("(?i)(?Pa)(?Pb)").groupindex, + {'first': 1, 'other': 2}) + + self.assertEqual(regex.match("(a)", "a").pos, 0) + self.assertEqual(regex.match("(a)", "a").endpos, 1) + + self.assertEqual(regex.search("b(c)", "abcdef").pos, 0) + self.assertEqual(regex.search("b(c)", "abcdef").endpos, 6) + self.assertEqual(regex.search("b(c)", "abcdef").span(), (1, 3)) + self.assertEqual(regex.search("b(c)", "abcdef").span(1), (2, 3)) + + self.assertEqual(regex.match("(a)", "a").string, 'a') + self.assertEqual(regex.match("(a)", "a").regs, ((0, 1), (0, 1))) + self.assertEqual(repr(type(regex.match("(a)", "a").re)), + self.PATTERN_CLASS) + + # Issue 14260. + p = regex.compile(r'abc(?Pdef)') + p.groupindex["n"] = 0 + self.assertEqual(p.groupindex["n"], 1) + + def test_special_escapes(self): + self.assertEqual(regex.search(r"\b(b.)\b", "abcd abc bcd bx")[1], 'bx') + self.assertEqual(regex.search(r"\B(b.)\B", "abc bcd bc abxd")[1], 'bx') + self.assertEqual(regex.search(br"\b(b.)\b", b"abcd abc bcd bx", + regex.LOCALE)[1], b'bx') + self.assertEqual(regex.search(br"\B(b.)\B", b"abc bcd bc abxd", + regex.LOCALE)[1], b'bx') + self.assertEqual(regex.search(r"\b(b.)\b", "abcd abc bcd bx", + regex.UNICODE)[1], 'bx') + self.assertEqual(regex.search(r"\B(b.)\B", "abc bcd bc abxd", + regex.UNICODE)[1], 'bx') + + self.assertEqual(regex.search(r"^abc$", "\nabc\n", regex.M)[0], 'abc') + self.assertEqual(regex.search(r"^\Aabc\Z$", "abc", regex.M)[0], 'abc') + self.assertEqual(regex.search(r"^\Aabc\Z$", "\nabc\n", regex.M), None) + + self.assertEqual(regex.search(br"\b(b.)\b", b"abcd abc bcd bx")[1], + b'bx') + self.assertEqual(regex.search(br"\B(b.)\B", b"abc bcd bc abxd")[1], + b'bx') + self.assertEqual(regex.search(br"^abc$", b"\nabc\n", regex.M)[0], + b'abc') + self.assertEqual(regex.search(br"^\Aabc\Z$", b"abc", regex.M)[0], + b'abc') + self.assertEqual(regex.search(br"^\Aabc\Z$", b"\nabc\n", regex.M), + None) + + self.assertEqual(regex.search(r"\d\D\w\W\s\S", "1aa! a")[0], '1aa! a') + self.assertEqual(regex.search(br"\d\D\w\W\s\S", b"1aa! a", + regex.LOCALE)[0], b'1aa! a') + self.assertEqual(regex.search(r"\d\D\w\W\s\S", "1aa! a", + regex.UNICODE)[0], '1aa! a') + + def test_bigcharset(self): + self.assertEqual(regex.match(r"([\u2222\u2223])", "\u2222")[1], + '\u2222') + self.assertEqual(regex.match(r"([\u2222\u2223])", "\u2222", + regex.UNICODE)[1], '\u2222') + self.assertEqual("".join(regex.findall(".", + "e\xe8\xe9\xea\xeb\u0113\u011b\u0117", flags=regex.UNICODE)), + 'e\xe8\xe9\xea\xeb\u0113\u011b\u0117') + self.assertEqual("".join(regex.findall(r"[e\xe8\xe9\xea\xeb\u0113\u011b\u0117]", + "e\xe8\xe9\xea\xeb\u0113\u011b\u0117", flags=regex.UNICODE)), + 'e\xe8\xe9\xea\xeb\u0113\u011b\u0117') + self.assertEqual("".join(regex.findall(r"e|\xe8|\xe9|\xea|\xeb|\u0113|\u011b|\u0117", + "e\xe8\xe9\xea\xeb\u0113\u011b\u0117", flags=regex.UNICODE)), + 'e\xe8\xe9\xea\xeb\u0113\u011b\u0117') + + def test_anyall(self): + self.assertEqual(regex.match("a.b", "a\nb", regex.DOTALL)[0], "a\nb") + self.assertEqual(regex.match("a.*b", "a\n\nb", regex.DOTALL)[0], + "a\n\nb") + + def test_non_consuming(self): + self.assertEqual(regex.match(r"(a(?=\s[^a]))", "a b")[1], 'a') + self.assertEqual(regex.match(r"(a(?=\s[^a]*))", "a b")[1], 'a') + self.assertEqual(regex.match(r"(a(?=\s[abc]))", "a b")[1], 'a') + self.assertEqual(regex.match(r"(a(?=\s[abc]*))", "a bc")[1], 'a') + self.assertEqual(regex.match(r"(a)(?=\s\1)", "a a")[1], 'a') + self.assertEqual(regex.match(r"(a)(?=\s\1*)", "a aa")[1], 'a') + self.assertEqual(regex.match(r"(a)(?=\s(abc|a))", "a a")[1], 'a') + + self.assertEqual(regex.match(r"(a(?!\s[^a]))", "a a")[1], 'a') + self.assertEqual(regex.match(r"(a(?!\s[abc]))", "a d")[1], 'a') + self.assertEqual(regex.match(r"(a)(?!\s\1)", "a b")[1], 'a') + self.assertEqual(regex.match(r"(a)(?!\s(abc|a))", "a b")[1], 'a') + + def test_ignore_case(self): + self.assertEqual(regex.match("abc", "ABC", regex.I)[0], 'ABC') + self.assertEqual(regex.match(b"abc", b"ABC", regex.I)[0], b'ABC') + + self.assertEqual(regex.match(r"(a\s[^a]*)", "a bb", regex.I)[1], + 'a bb') + self.assertEqual(regex.match(r"(a\s[abc])", "a b", regex.I)[1], 'a b') + self.assertEqual(regex.match(r"(a\s[abc]*)", "a bb", regex.I)[1], + 'a bb') + self.assertEqual(regex.match(r"((a)\s\2)", "a a", regex.I)[1], 'a a') + self.assertEqual(regex.match(r"((a)\s\2*)", "a aa", regex.I)[1], + 'a aa') + self.assertEqual(regex.match(r"((a)\s(abc|a))", "a a", regex.I)[1], + 'a a') + self.assertEqual(regex.match(r"((a)\s(abc|a)*)", "a aa", regex.I)[1], + 'a aa') + + # Issue 3511. + self.assertEqual(regex.match(r"[Z-a]", "_").span(), (0, 1)) + self.assertEqual(regex.match(r"(?i)[Z-a]", "_").span(), (0, 1)) + + self.assertEqual(bool(regex.match(r"(?i)nao", "nAo")), True) + self.assertEqual(bool(regex.match(r"(?i)n\xE3o", "n\xC3o")), True) + self.assertEqual(bool(regex.match(r"(?i)n\xE3o", "N\xC3O")), True) + self.assertEqual(bool(regex.match(r"(?i)s", "\u017F")), True) + + def test_case_folding(self): + self.assertEqual(regex.search(r"(?fi)ss", "SS").span(), (0, 2)) + self.assertEqual(regex.search(r"(?fi)SS", "ss").span(), (0, 2)) + self.assertEqual(regex.search(r"(?fi)SS", + "\N{LATIN SMALL LETTER SHARP S}").span(), (0, 1)) + self.assertEqual(regex.search(r"(?fi)\N{LATIN SMALL LETTER SHARP S}", + "SS").span(), (0, 2)) + + self.assertEqual(regex.search(r"(?fi)\N{LATIN SMALL LIGATURE ST}", + "ST").span(), (0, 2)) + self.assertEqual(regex.search(r"(?fi)ST", + "\N{LATIN SMALL LIGATURE ST}").span(), (0, 1)) + self.assertEqual(regex.search(r"(?fi)ST", + "\N{LATIN SMALL LIGATURE LONG S T}").span(), (0, 1)) + + self.assertEqual(regex.search(r"(?fi)SST", + "\N{LATIN SMALL LETTER SHARP S}t").span(), (0, 2)) + self.assertEqual(regex.search(r"(?fi)SST", + "s\N{LATIN SMALL LIGATURE LONG S T}").span(), (0, 2)) + self.assertEqual(regex.search(r"(?fi)SST", + "s\N{LATIN SMALL LIGATURE ST}").span(), (0, 2)) + self.assertEqual(regex.search(r"(?fi)\N{LATIN SMALL LIGATURE ST}", + "SST").span(), (1, 3)) + self.assertEqual(regex.search(r"(?fi)SST", + "s\N{LATIN SMALL LIGATURE ST}").span(), (0, 2)) + + self.assertEqual(regex.search(r"(?fi)FFI", + "\N{LATIN SMALL LIGATURE FFI}").span(), (0, 1)) + self.assertEqual(regex.search(r"(?fi)FFI", + "\N{LATIN SMALL LIGATURE FF}i").span(), (0, 2)) + self.assertEqual(regex.search(r"(?fi)FFI", + "f\N{LATIN SMALL LIGATURE FI}").span(), (0, 2)) + self.assertEqual(regex.search(r"(?fi)\N{LATIN SMALL LIGATURE FFI}", + "FFI").span(), (0, 3)) + self.assertEqual(regex.search(r"(?fi)\N{LATIN SMALL LIGATURE FF}i", + "FFI").span(), (0, 3)) + self.assertEqual(regex.search(r"(?fi)f\N{LATIN SMALL LIGATURE FI}", + "FFI").span(), (0, 3)) + + sigma = "\u03A3\u03C3\u03C2" + for ch1 in sigma: + for ch2 in sigma: + if not regex.match(r"(?fi)" + ch1, ch2): + self.fail() + + self.assertEqual(bool(regex.search(r"(?iV1)ff", "\uFB00\uFB01")), + True) + self.assertEqual(bool(regex.search(r"(?iV1)ff", "\uFB01\uFB00")), + True) + self.assertEqual(bool(regex.search(r"(?iV1)fi", "\uFB00\uFB01")), + True) + self.assertEqual(bool(regex.search(r"(?iV1)fi", "\uFB01\uFB00")), + True) + self.assertEqual(bool(regex.search(r"(?iV1)fffi", "\uFB00\uFB01")), + True) + self.assertEqual(bool(regex.search(r"(?iV1)f\uFB03", + "\uFB00\uFB01")), True) + self.assertEqual(bool(regex.search(r"(?iV1)ff", "\uFB00\uFB01")), + True) + self.assertEqual(bool(regex.search(r"(?iV1)fi", "\uFB00\uFB01")), + True) + self.assertEqual(bool(regex.search(r"(?iV1)fffi", "\uFB00\uFB01")), + True) + self.assertEqual(bool(regex.search(r"(?iV1)f\uFB03", + "\uFB00\uFB01")), True) + self.assertEqual(bool(regex.search(r"(?iV1)f\uFB01", "\uFB00i")), + True) + self.assertEqual(bool(regex.search(r"(?iV1)f\uFB01", "\uFB00i")), + True) + + self.assertEqual(regex.findall(r"(?iV0)\m(?:word){e<=3}\M(?ne", "affine", + options=["\N{LATIN SMALL LIGATURE FFI}"]).span(), (0, 6)) + self.assertEqual(regex.search(r"(?fi)a\Lne", + "a\N{LATIN SMALL LIGATURE FFI}ne", options=["ffi"]).span(), (0, 4)) + + def test_category(self): + self.assertEqual(regex.match(r"(\s)", " ")[1], ' ') + + def test_not_literal(self): + self.assertEqual(regex.search(r"\s([^a])", " b")[1], 'b') + self.assertEqual(regex.search(r"\s([^a]*)", " bb")[1], 'bb') + + def test_search_coverage(self): + self.assertEqual(regex.search(r"\s(b)", " b")[1], 'b') + self.assertEqual(regex.search(r"a\s", "a ")[0], 'a ') + + def test_re_escape(self): + p = "" + self.assertEqual(regex.escape(p), p) + for i in range(0, 256): + p += chr(i) + self.assertEqual(bool(regex.match(regex.escape(chr(i)), chr(i))), + True) + self.assertEqual(regex.match(regex.escape(chr(i)), chr(i)).span(), + (0, 1)) + + pat = regex.compile(regex.escape(p)) + self.assertEqual(pat.match(p).span(), (0, 256)) + + def test_re_escape_byte(self): + p = b"" + self.assertEqual(regex.escape(p), p) + for i in range(0, 256): + b = bytes([i]) + p += b + self.assertEqual(bool(regex.match(regex.escape(b), b)), True) + self.assertEqual(regex.match(regex.escape(b), b).span(), (0, 1)) + + pat = regex.compile(regex.escape(p)) + self.assertEqual(pat.match(p).span(), (0, 256)) + + def test_constants(self): + if regex.I != regex.IGNORECASE: + self.fail() + if regex.L != regex.LOCALE: + self.fail() + if regex.M != regex.MULTILINE: + self.fail() + if regex.S != regex.DOTALL: + self.fail() + if regex.X != regex.VERBOSE: + self.fail() + + def test_flags(self): + for flag in [regex.I, regex.M, regex.X, regex.S, regex.L]: + self.assertEqual(repr(type(regex.compile('^pattern$', flag))), + self.PATTERN_CLASS) + + def test_sre_character_literals(self): + for i in [0, 8, 16, 32, 64, 127, 128, 255]: + self.assertEqual(bool(regex.match(r"\%03o" % i, chr(i))), True) + self.assertEqual(bool(regex.match(r"\%03o0" % i, chr(i) + "0")), + True) + self.assertEqual(bool(regex.match(r"\%03o8" % i, chr(i) + "8")), + True) + self.assertEqual(bool(regex.match(r"\x%02x" % i, chr(i))), True) + self.assertEqual(bool(regex.match(r"\x%02x0" % i, chr(i) + "0")), + True) + self.assertEqual(bool(regex.match(r"\x%02xz" % i, chr(i) + "z")), + True) + + self.assertRaisesRegex(regex.error, self.INVALID_GROUP_REF, lambda: + regex.match(r"\911", "")) + + def test_sre_character_class_literals(self): + for i in [0, 8, 16, 32, 64, 127, 128, 255]: + self.assertEqual(bool(regex.match(r"[\%03o]" % i, chr(i))), True) + self.assertEqual(bool(regex.match(r"[\%03o0]" % i, chr(i))), True) + self.assertEqual(bool(regex.match(r"[\%03o8]" % i, chr(i))), True) + self.assertEqual(bool(regex.match(r"[\x%02x]" % i, chr(i))), True) + self.assertEqual(bool(regex.match(r"[\x%02x0]" % i, chr(i))), True) + self.assertEqual(bool(regex.match(r"[\x%02xz]" % i, chr(i))), True) + + self.assertRaisesRegex(regex.error, self.BAD_OCTAL_ESCAPE, lambda: + regex.match(r"[\911]", "")) + + def test_bug_113254(self): + self.assertEqual(regex.match(r'(a)|(b)', 'b').start(1), -1) + self.assertEqual(regex.match(r'(a)|(b)', 'b').end(1), -1) + self.assertEqual(regex.match(r'(a)|(b)', 'b').span(1), (-1, -1)) + + def test_bug_527371(self): + # Bug described in patches 527371/672491. + self.assertEqual(regex.match(r'(a)?a','a').lastindex, None) + self.assertEqual(regex.match(r'(a)(b)?b','ab').lastindex, 1) + self.assertEqual(regex.match(r'(?Pa)(?Pb)?b','ab').lastgroup, + 'a') + self.assertEqual(regex.match("(?Pa(b))", "ab").lastgroup, 'a') + self.assertEqual(regex.match("((a))", "a").lastindex, 1) + + def test_bug_545855(self): + # Bug 545855 -- This pattern failed to cause a compile error as it + # should, instead provoking a TypeError. + self.assertRaisesRegex(regex.error, self.BAD_SET, lambda: + regex.compile('foo[a-')) + + def test_bug_418626(self): + # Bugs 418626 at al. -- Testing Greg Chapman's addition of op code + # SRE_OP_MIN_REPEAT_ONE for eliminating recursion on simple uses of + # pattern '*?' on a long string. + self.assertEqual(regex.match('.*?c', 10000 * 'ab' + 'cd').end(0), + 20001) + self.assertEqual(regex.match('.*?cd', 5000 * 'ab' + 'c' + 5000 * 'ab' + + 'cde').end(0), 20003) + self.assertEqual(regex.match('.*?cd', 20000 * 'abc' + 'de').end(0), + 60001) + # Non-simple '*?' still used to hit the recursion limit, before the + # non-recursive scheme was implemented. + self.assertEqual(regex.search('(a|b)*?c', 10000 * 'ab' + 'cd').end(0), + 20001) + + def test_bug_612074(self): + pat = "[" + regex.escape("\u2039") + "]" + self.assertEqual(regex.compile(pat) and 1, 1) + + def test_stack_overflow(self): + # Nasty cases that used to overflow the straightforward recursive + # implementation of repeated groups. + self.assertEqual(regex.match('(x)*', 50000 * 'x')[1], 'x') + self.assertEqual(regex.match('(x)*y', 50000 * 'x' + 'y')[1], 'x') + self.assertEqual(regex.match('(x)*?y', 50000 * 'x' + 'y')[1], 'x') + + def test_scanner(self): + def s_ident(scanner, token): return token + def s_operator(scanner, token): return "op%s" % token + def s_float(scanner, token): return float(token) + def s_int(scanner, token): return int(token) + + scanner = regex.Scanner([(r"[a-zA-Z_]\w*", s_ident), (r"\d+\.\d*", + s_float), (r"\d+", s_int), (r"=|\+|-|\*|/", s_operator), (r"\s+", + None), ]) + + self.assertEqual(repr(type(scanner.scanner.scanner("").pattern)), + self.PATTERN_CLASS) + + self.assertEqual(scanner.scan("sum = 3*foo + 312.50 + bar"), (['sum', + 'op=', 3, 'op*', 'foo', 'op+', 312.5, 'op+', 'bar'], '')) + + def test_bug_448951(self): + # Bug 448951 (similar to 429357, but with single char match). + # (Also test greedy matches.) + for op in '', '?', '*': + self.assertEqual(regex.match(r'((.%s):)?z' % op, 'z')[:], ('z', + None, None)) + self.assertEqual(regex.match(r'((.%s):)?z' % op, 'a:z')[:], ('a:z', + 'a:', 'a')) + + def test_bug_725106(self): + # Capturing groups in alternatives in repeats. + self.assertEqual(regex.match('^((a)|b)*', 'abc')[:], ('ab', 'b', 'a')) + self.assertEqual(regex.match('^(([ab])|c)*', 'abc')[:], ('abc', 'c', + 'b')) + self.assertEqual(regex.match('^((d)|[ab])*', 'abc')[:], ('ab', 'b', + None)) + self.assertEqual(regex.match('^((a)c|[ab])*', 'abc')[:], ('ab', 'b', + None)) + self.assertEqual(regex.match('^((a)|b)*?c', 'abc')[:], ('abc', 'b', + 'a')) + self.assertEqual(regex.match('^(([ab])|c)*?d', 'abcd')[:], ('abcd', + 'c', 'b')) + self.assertEqual(regex.match('^((d)|[ab])*?c', 'abc')[:], ('abc', 'b', + None)) + self.assertEqual(regex.match('^((a)c|[ab])*?c', 'abc')[:], ('abc', 'b', + None)) + + def test_bug_725149(self): + # Mark_stack_base restoring before restoring marks. + self.assertEqual(regex.match('(a)(?:(?=(b)*)c)*', 'abb')[:], ('a', 'a', + None)) + self.assertEqual(regex.match('(a)((?!(b)*))*', 'abb')[:], ('a', 'a', + None, None)) + + def test_bug_764548(self): + # Bug 764548, regex.compile() barfs on str/unicode subclasses. + class my_unicode(str): pass + pat = regex.compile(my_unicode("abc")) + self.assertEqual(pat.match("xyz"), None) + + def test_finditer(self): + it = regex.finditer(r":+", "a:b::c:::d") + self.assertEqual([item[0] for item in it], [':', '::', ':::']) + + def test_bug_926075(self): + if regex.compile('bug_926075') is regex.compile(b'bug_926075'): + self.fail() + + def test_bug_931848(self): + pattern = "[\u002E\u3002\uFF0E\uFF61]" + self.assertEqual(regex.compile(pattern).split("a.b.c"), ['a', 'b', + 'c']) + + def test_bug_581080(self): + it = regex.finditer(r"\s", "a b") + self.assertEqual(next(it).span(), (1, 2)) + self.assertRaises(StopIteration, lambda: next(it)) + + scanner = regex.compile(r"\s").scanner("a b") + self.assertEqual(scanner.search().span(), (1, 2)) + self.assertEqual(scanner.search(), None) + + def test_bug_817234(self): + it = regex.finditer(r".*", "asdf") + self.assertEqual(next(it).span(), (0, 4)) + self.assertEqual(next(it).span(), (4, 4)) + self.assertRaises(StopIteration, lambda: next(it)) + + def test_empty_array(self): + # SF buf 1647541. + import array + for typecode in 'bBhHiIlLfd': + a = array.array(typecode) + self.assertEqual(regex.compile(b"bla").match(a), None) + self.assertEqual(regex.compile(b"").match(a)[1 : ], ()) + + def test_inline_flags(self): + # Bug #1700. + upper_char = chr(0x1ea0) # Latin Capital Letter A with Dot Below + lower_char = chr(0x1ea1) # Latin Small Letter A with Dot Below + + p = regex.compile(upper_char, regex.I | regex.U) + self.assertEqual(bool(p.match(lower_char)), True) + + p = regex.compile(lower_char, regex.I | regex.U) + self.assertEqual(bool(p.match(upper_char)), True) + + p = regex.compile('(?i)' + upper_char, regex.U) + self.assertEqual(bool(p.match(lower_char)), True) + + p = regex.compile('(?i)' + lower_char, regex.U) + self.assertEqual(bool(p.match(upper_char)), True) + + p = regex.compile('(?iu)' + upper_char) + self.assertEqual(bool(p.match(lower_char)), True) + + p = regex.compile('(?iu)' + lower_char) + self.assertEqual(bool(p.match(upper_char)), True) + + # Changed to positional flags in regex 2023.12.23. + self.assertEqual(bool(regex.match(r"(?i)a", "A")), True) + self.assertEqual(regex.match(r"a(?i)", "A"), None) + + def test_dollar_matches_twice(self): + # $ matches the end of string, and just before the terminating \n. + pattern = regex.compile('$') + self.assertEqual(pattern.sub('#', 'a\nb\n'), 'a\nb#\n#') + self.assertEqual(pattern.sub('#', 'a\nb\nc'), 'a\nb\nc#') + self.assertEqual(pattern.sub('#', '\n'), '#\n#') + + pattern = regex.compile('$', regex.MULTILINE) + self.assertEqual(pattern.sub('#', 'a\nb\n' ), 'a#\nb#\n#') + self.assertEqual(pattern.sub('#', 'a\nb\nc'), 'a#\nb#\nc#') + self.assertEqual(pattern.sub('#', '\n'), '#\n#') + + def test_bytes_str_mixing(self): + # Mixing str and bytes is disallowed. + pat = regex.compile('.') + bpat = regex.compile(b'.') + self.assertRaisesRegex(TypeError, self.STR_PAT_ON_BYTES, lambda: + pat.match(b'b')) + self.assertRaisesRegex(TypeError, self.BYTES_PAT_ON_STR, lambda: + bpat.match('b')) + self.assertRaisesRegex(TypeError, self.STR_PAT_BYTES_TEMPL, lambda: + pat.sub(b'b', 'c')) + self.assertRaisesRegex(TypeError, self.STR_PAT_ON_BYTES, lambda: + pat.sub('b', b'c')) + self.assertRaisesRegex(TypeError, self.STR_PAT_ON_BYTES, lambda: + pat.sub(b'b', b'c')) + self.assertRaisesRegex(TypeError, self.BYTES_PAT_ON_STR, lambda: + bpat.sub(b'b', 'c')) + self.assertRaisesRegex(TypeError, self.BYTES_PAT_STR_TEMPL, lambda: + bpat.sub('b', b'c')) + self.assertRaisesRegex(TypeError, self.BYTES_PAT_ON_STR, lambda: + bpat.sub('b', 'c')) + + self.assertRaisesRegex(ValueError, self.BYTES_PAT_UNI_FLAG, lambda: + regex.compile(br'\w', regex.UNICODE)) + self.assertRaisesRegex(ValueError, self.BYTES_PAT_UNI_FLAG, lambda: + regex.compile(br'(?u)\w')) + self.assertRaisesRegex(ValueError, self.MIXED_FLAGS, lambda: + regex.compile(r'\w', regex.UNICODE | regex.ASCII)) + self.assertRaisesRegex(ValueError, self.MIXED_FLAGS, lambda: + regex.compile(r'(?u)\w', regex.ASCII)) + self.assertRaisesRegex(ValueError, self.MIXED_FLAGS, lambda: + regex.compile(r'(?a)\w', regex.UNICODE)) + self.assertRaisesRegex(ValueError, self.MIXED_FLAGS, lambda: + regex.compile(r'(?au)\w')) + + def test_ascii_and_unicode_flag(self): + # String patterns. + for flags in (0, regex.UNICODE): + pat = regex.compile('\xc0', flags | regex.IGNORECASE) + self.assertEqual(bool(pat.match('\xe0')), True) + pat = regex.compile(r'\w', flags) + self.assertEqual(bool(pat.match('\xe0')), True) + + pat = regex.compile('\xc0', regex.ASCII | regex.IGNORECASE) + self.assertEqual(pat.match('\xe0'), None) + pat = regex.compile('(?a)\xc0', regex.IGNORECASE) + self.assertEqual(pat.match('\xe0'), None) + pat = regex.compile(r'\w', regex.ASCII) + self.assertEqual(pat.match('\xe0'), None) + pat = regex.compile(r'(?a)\w') + self.assertEqual(pat.match('\xe0'), None) + + # Bytes patterns. + for flags in (0, regex.ASCII): + pat = regex.compile(b'\xc0', flags | regex.IGNORECASE) + self.assertEqual(pat.match(b'\xe0'), None) + pat = regex.compile(br'\w') + self.assertEqual(pat.match(b'\xe0'), None) + + self.assertRaisesRegex(ValueError, self.MIXED_FLAGS, lambda: + regex.compile(r'(?au)\w')) + + def test_subscripting_match(self): + m = regex.match(r'(?\w)', 'xy') + if not m: + self.fail("Failed: expected match but returned None") + elif not m or m[0] != m.group(0) or m[1] != m.group(1): + self.fail("Failed") + if not m: + self.fail("Failed: expected match but returned None") + elif m[:] != ('x', 'x'): + self.fail("Failed: expected \"('x', 'x')\" but got {} instead".format(ascii(m[:]))) + + def test_new_named_groups(self): + m0 = regex.match(r'(?P\w)', 'x') + m1 = regex.match(r'(?\w)', 'x') + if not (m0 and m1 and m0[:] == m1[:]): + self.fail("Failed") + + def test_properties(self): + self.assertEqual(regex.match(b'(?ai)\xC0', b'\xE0'), None) + self.assertEqual(regex.match(br'(?ai)\xC0', b'\xE0'), None) + self.assertEqual(regex.match(br'(?a)\w', b'\xE0'), None) + self.assertEqual(bool(regex.match(r'\w', '\xE0')), True) + + # Dropped the following test. It's not possible to determine what the + # correct result should be in the general case. +# self.assertEqual(bool(regex.match(br'(?L)\w', b'\xE0')), +# b'\xE0'.isalnum()) + + self.assertEqual(bool(regex.match(br'(?L)\d', b'0')), True) + self.assertEqual(bool(regex.match(br'(?L)\s', b' ')), True) + self.assertEqual(bool(regex.match(br'(?L)\w', b'a')), True) + self.assertEqual(regex.match(br'(?L)\d', b'?'), None) + self.assertEqual(regex.match(br'(?L)\s', b'?'), None) + self.assertEqual(regex.match(br'(?L)\w', b'?'), None) + + self.assertEqual(regex.match(br'(?L)\D', b'0'), None) + self.assertEqual(regex.match(br'(?L)\S', b' '), None) + self.assertEqual(regex.match(br'(?L)\W', b'a'), None) + self.assertEqual(bool(regex.match(br'(?L)\D', b'?')), True) + self.assertEqual(bool(regex.match(br'(?L)\S', b'?')), True) + self.assertEqual(bool(regex.match(br'(?L)\W', b'?')), True) + + self.assertEqual(bool(regex.match(r'\p{Cyrillic}', + '\N{CYRILLIC CAPITAL LETTER A}')), True) + self.assertEqual(bool(regex.match(r'(?i)\p{Cyrillic}', + '\N{CYRILLIC CAPITAL LETTER A}')), True) + self.assertEqual(bool(regex.match(r'\p{IsCyrillic}', + '\N{CYRILLIC CAPITAL LETTER A}')), True) + self.assertEqual(bool(regex.match(r'\p{Script=Cyrillic}', + '\N{CYRILLIC CAPITAL LETTER A}')), True) + self.assertEqual(bool(regex.match(r'\p{InCyrillic}', + '\N{CYRILLIC CAPITAL LETTER A}')), True) + self.assertEqual(bool(regex.match(r'\p{Block=Cyrillic}', + '\N{CYRILLIC CAPITAL LETTER A}')), True) + self.assertEqual(bool(regex.match(r'[[:Cyrillic:]]', + '\N{CYRILLIC CAPITAL LETTER A}')), True) + self.assertEqual(bool(regex.match(r'[[:IsCyrillic:]]', + '\N{CYRILLIC CAPITAL LETTER A}')), True) + self.assertEqual(bool(regex.match(r'[[:Script=Cyrillic:]]', + '\N{CYRILLIC CAPITAL LETTER A}')), True) + self.assertEqual(bool(regex.match(r'[[:InCyrillic:]]', + '\N{CYRILLIC CAPITAL LETTER A}')), True) + self.assertEqual(bool(regex.match(r'[[:Block=Cyrillic:]]', + '\N{CYRILLIC CAPITAL LETTER A}')), True) + + self.assertEqual(bool(regex.match(r'\P{Cyrillic}', + '\N{LATIN CAPITAL LETTER A}')), True) + self.assertEqual(bool(regex.match(r'\P{IsCyrillic}', + '\N{LATIN CAPITAL LETTER A}')), True) + self.assertEqual(bool(regex.match(r'\P{Script=Cyrillic}', + '\N{LATIN CAPITAL LETTER A}')), True) + self.assertEqual(bool(regex.match(r'\P{InCyrillic}', + '\N{LATIN CAPITAL LETTER A}')), True) + self.assertEqual(bool(regex.match(r'\P{Block=Cyrillic}', + '\N{LATIN CAPITAL LETTER A}')), True) + self.assertEqual(bool(regex.match(r'\p{^Cyrillic}', + '\N{LATIN CAPITAL LETTER A}')), True) + self.assertEqual(bool(regex.match(r'\p{^IsCyrillic}', + '\N{LATIN CAPITAL LETTER A}')), True) + self.assertEqual(bool(regex.match(r'\p{^Script=Cyrillic}', + '\N{LATIN CAPITAL LETTER A}')), True) + self.assertEqual(bool(regex.match(r'\p{^InCyrillic}', + '\N{LATIN CAPITAL LETTER A}')), True) + self.assertEqual(bool(regex.match(r'\p{^Block=Cyrillic}', + '\N{LATIN CAPITAL LETTER A}')), True) + self.assertEqual(bool(regex.match(r'[[:^Cyrillic:]]', + '\N{LATIN CAPITAL LETTER A}')), True) + self.assertEqual(bool(regex.match(r'[[:^IsCyrillic:]]', + '\N{LATIN CAPITAL LETTER A}')), True) + self.assertEqual(bool(regex.match(r'[[:^Script=Cyrillic:]]', + '\N{LATIN CAPITAL LETTER A}')), True) + self.assertEqual(bool(regex.match(r'[[:^InCyrillic:]]', + '\N{LATIN CAPITAL LETTER A}')), True) + self.assertEqual(bool(regex.match(r'[[:^Block=Cyrillic:]]', + '\N{LATIN CAPITAL LETTER A}')), True) + + self.assertEqual(bool(regex.match(r'\d', '0')), True) + self.assertEqual(bool(regex.match(r'\s', ' ')), True) + self.assertEqual(bool(regex.match(r'\w', 'A')), True) + self.assertEqual(regex.match(r"\d", "?"), None) + self.assertEqual(regex.match(r"\s", "?"), None) + self.assertEqual(regex.match(r"\w", "?"), None) + self.assertEqual(regex.match(r"\D", "0"), None) + self.assertEqual(regex.match(r"\S", " "), None) + self.assertEqual(regex.match(r"\W", "A"), None) + self.assertEqual(bool(regex.match(r'\D', '?')), True) + self.assertEqual(bool(regex.match(r'\S', '?')), True) + self.assertEqual(bool(regex.match(r'\W', '?')), True) + + self.assertEqual(bool(regex.match(r'\p{L}', 'A')), True) + self.assertEqual(bool(regex.match(r'\p{L}', 'a')), True) + self.assertEqual(bool(regex.match(r'\p{Lu}', 'A')), True) + self.assertEqual(bool(regex.match(r'\p{Ll}', 'a')), True) + + self.assertEqual(bool(regex.match(r'(?i)a', 'a')), True) + self.assertEqual(bool(regex.match(r'(?i)a', 'A')), True) + + self.assertEqual(bool(regex.match(r'\w', '0')), True) + self.assertEqual(bool(regex.match(r'\w', 'a')), True) + self.assertEqual(bool(regex.match(r'\w', '_')), True) + + self.assertEqual(regex.match(r"\X", "\xE0").span(), (0, 1)) + self.assertEqual(regex.match(r"\X", "a\u0300").span(), (0, 2)) + self.assertEqual(regex.findall(r"\X", + "a\xE0a\u0300e\xE9e\u0301"), ['a', '\xe0', 'a\u0300', 'e', + '\xe9', 'e\u0301']) + self.assertEqual(regex.findall(r"\X{3}", + "a\xE0a\u0300e\xE9e\u0301"), ['a\xe0a\u0300', 'e\xe9e\u0301']) + self.assertEqual(regex.findall(r"\X", "\r\r\n\u0301A\u0301"), + ['\r', '\r\n', '\u0301', 'A\u0301']) + + self.assertEqual(bool(regex.match(r'\p{Ll}', 'a')), True) + + chars_u = "-09AZaz_\u0393\u03b3" + chars_b = b"-09AZaz_" + word_set = set("Ll Lm Lo Lt Lu Mc Me Mn Nd Nl No Pc".split()) + + tests = [ + (r"\w", chars_u, "09AZaz_\u0393\u03b3"), + (r"[[:word:]]", chars_u, "09AZaz_\u0393\u03b3"), + (r"\W", chars_u, "-"), + (r"[[:^word:]]", chars_u, "-"), + (r"\d", chars_u, "09"), + (r"[[:digit:]]", chars_u, "09"), + (r"\D", chars_u, "-AZaz_\u0393\u03b3"), + (r"[[:^digit:]]", chars_u, "-AZaz_\u0393\u03b3"), + (r"[[:alpha:]]", chars_u, "AZaz\u0393\u03b3"), + (r"[[:^alpha:]]", chars_u, "-09_"), + (r"[[:alnum:]]", chars_u, "09AZaz\u0393\u03b3"), + (r"[[:^alnum:]]", chars_u, "-_"), + (r"[[:xdigit:]]", chars_u, "09Aa"), + (r"[[:^xdigit:]]", chars_u, "-Zz_\u0393\u03b3"), + (r"\p{InBasicLatin}", "a\xE1", "a"), + (r"\P{InBasicLatin}", "a\xE1", "\xE1"), + (r"(?i)\p{InBasicLatin}", "a\xE1", "a"), + (r"(?i)\P{InBasicLatin}", "a\xE1", "\xE1"), + + (br"(?L)\w", chars_b, b"09AZaz_"), + (br"(?L)[[:word:]]", chars_b, b"09AZaz_"), + (br"(?L)\W", chars_b, b"-"), + (br"(?L)[[:^word:]]", chars_b, b"-"), + (br"(?L)\d", chars_b, b"09"), + (br"(?L)[[:digit:]]", chars_b, b"09"), + (br"(?L)\D", chars_b, b"-AZaz_"), + (br"(?L)[[:^digit:]]", chars_b, b"-AZaz_"), + (br"(?L)[[:alpha:]]", chars_b, b"AZaz"), + (br"(?L)[[:^alpha:]]", chars_b, b"-09_"), + (br"(?L)[[:alnum:]]", chars_b, b"09AZaz"), + (br"(?L)[[:^alnum:]]", chars_b, b"-_"), + (br"(?L)[[:xdigit:]]", chars_b, b"09Aa"), + (br"(?L)[[:^xdigit:]]", chars_b, b"-Zz_"), + + (br"(?a)\w", chars_b, b"09AZaz_"), + (br"(?a)[[:word:]]", chars_b, b"09AZaz_"), + (br"(?a)\W", chars_b, b"-"), + (br"(?a)[[:^word:]]", chars_b, b"-"), + (br"(?a)\d", chars_b, b"09"), + (br"(?a)[[:digit:]]", chars_b, b"09"), + (br"(?a)\D", chars_b, b"-AZaz_"), + (br"(?a)[[:^digit:]]", chars_b, b"-AZaz_"), + (br"(?a)[[:alpha:]]", chars_b, b"AZaz"), + (br"(?a)[[:^alpha:]]", chars_b, b"-09_"), + (br"(?a)[[:alnum:]]", chars_b, b"09AZaz"), + (br"(?a)[[:^alnum:]]", chars_b, b"-_"), + (br"(?a)[[:xdigit:]]", chars_b, b"09Aa"), + (br"(?a)[[:^xdigit:]]", chars_b, b"-Zz_"), + ] + for pattern, chars, expected in tests: + try: + if chars[ : 0].join(regex.findall(pattern, chars)) != expected: + self.fail("Failed: {}".format(pattern)) + except Exception as e: + self.fail("Failed: {} raised {}".format(pattern, ascii(e))) + + self.assertEqual(bool(regex.match(r"\p{NumericValue=0}", "0")), + True) + self.assertEqual(bool(regex.match(r"\p{NumericValue=1/2}", + "\N{VULGAR FRACTION ONE HALF}")), True) + self.assertEqual(bool(regex.match(r"\p{NumericValue=0.5}", + "\N{VULGAR FRACTION ONE HALF}")), True) + + def test_word_class(self): + self.assertEqual(regex.findall(r"\w+", + " \u0939\u093f\u0928\u094d\u0926\u0940,"), + ['\u0939\u093f\u0928\u094d\u0926\u0940']) + self.assertEqual(regex.findall(r"\W+", + " \u0939\u093f\u0928\u094d\u0926\u0940,"), [' ', ',']) + self.assertEqual(regex.split(r"(?V1)\b", + " \u0939\u093f\u0928\u094d\u0926\u0940,"), [' ', + '\u0939\u093f\u0928\u094d\u0926\u0940', ',']) + self.assertEqual(regex.split(r"(?V1)\B", + " \u0939\u093f\u0928\u094d\u0926\u0940,"), ['', ' \u0939', + '\u093f', '\u0928', '\u094d', '\u0926', '\u0940,', '']) + + def test_search_anchor(self): + self.assertEqual(regex.findall(r"\G\w{2}", "abcd ef"), ['ab', 'cd']) + + def test_search_reverse(self): + self.assertEqual(regex.findall(r"(?r).", "abc"), ['c', 'b', 'a']) + self.assertEqual(regex.findall(r"(?r).", "abc", overlapped=True), ['c', + 'b', 'a']) + self.assertEqual(regex.findall(r"(?r)..", "abcde"), ['de', 'bc']) + self.assertEqual(regex.findall(r"(?r)..", "abcde", overlapped=True), + ['de', 'cd', 'bc', 'ab']) + self.assertEqual(regex.findall(r"(?r)(.)(-)(.)", "a-b-c", + overlapped=True), [("b", "-", "c"), ("a", "-", "b")]) + + self.assertEqual([m[0] for m in regex.finditer(r"(?r).", "abc")], ['c', + 'b', 'a']) + self.assertEqual([m[0] for m in regex.finditer(r"(?r)..", "abcde", + overlapped=True)], ['de', 'cd', 'bc', 'ab']) + self.assertEqual([m[0] for m in regex.finditer(r"(?r).", "abc")], ['c', + 'b', 'a']) + self.assertEqual([m[0] for m in regex.finditer(r"(?r)..", "abcde", + overlapped=True)], ['de', 'cd', 'bc', 'ab']) + + self.assertEqual(regex.findall(r"^|\w+", "foo bar"), ['', 'foo', + 'bar']) + self.assertEqual(regex.findall(r"(?V1)^|\w+", "foo bar"), ['', 'foo', + 'bar']) + self.assertEqual(regex.findall(r"(?r)^|\w+", "foo bar"), ['bar', 'foo', + '']) + self.assertEqual(regex.findall(r"(?rV1)^|\w+", "foo bar"), ['bar', + 'foo', '']) + + self.assertEqual([m[0] for m in regex.finditer(r"^|\w+", "foo bar")], + ['', 'foo', 'bar']) + self.assertEqual([m[0] for m in regex.finditer(r"(?V1)^|\w+", + "foo bar")], ['', 'foo', 'bar']) + self.assertEqual([m[0] for m in regex.finditer(r"(?r)^|\w+", + "foo bar")], ['bar', 'foo', '']) + self.assertEqual([m[0] for m in regex.finditer(r"(?rV1)^|\w+", + "foo bar")], ['bar', 'foo', '']) + + self.assertEqual(regex.findall(r"\G\w{2}", "abcd ef"), ['ab', 'cd']) + self.assertEqual(regex.findall(r".{2}(?<=\G.*)", "abcd"), ['ab', 'cd']) + self.assertEqual(regex.findall(r"(?r)\G\w{2}", "abcd ef"), []) + self.assertEqual(regex.findall(r"(?r)\w{2}\G", "abcd ef"), ['ef']) + + self.assertEqual(regex.findall(r"q*", "qqwe"), ['qq', '', '', '']) + self.assertEqual(regex.findall(r"(?V1)q*", "qqwe"), ['qq', '', '', '']) + self.assertEqual(regex.findall(r"(?r)q*", "qqwe"), ['', '', 'qq', '']) + self.assertEqual(regex.findall(r"(?rV1)q*", "qqwe"), ['', '', 'qq', + '']) + + self.assertEqual(regex.findall(".", "abcd", pos=1, endpos=3), ['b', + 'c']) + self.assertEqual(regex.findall(".", "abcd", pos=1, endpos=-1), ['b', + 'c']) + self.assertEqual([m[0] for m in regex.finditer(".", "abcd", pos=1, + endpos=3)], ['b', 'c']) + self.assertEqual([m[0] for m in regex.finditer(".", "abcd", pos=1, + endpos=-1)], ['b', 'c']) + + self.assertEqual([m[0] for m in regex.finditer("(?r).", "abcd", pos=1, + endpos=3)], ['c', 'b']) + self.assertEqual([m[0] for m in regex.finditer("(?r).", "abcd", pos=1, + endpos=-1)], ['c', 'b']) + self.assertEqual(regex.findall("(?r).", "abcd", pos=1, endpos=3), ['c', + 'b']) + self.assertEqual(regex.findall("(?r).", "abcd", pos=1, endpos=-1), + ['c', 'b']) + + self.assertEqual(regex.findall(r"[ab]", "aB", regex.I), ['a', 'B']) + self.assertEqual(regex.findall(r"(?r)[ab]", "aB", regex.I), ['B', 'a']) + + self.assertEqual(regex.findall(r"(?r).{2}", "abc"), ['bc']) + self.assertEqual(regex.findall(r"(?r).{2}", "abc", overlapped=True), + ['bc', 'ab']) + self.assertEqual(regex.findall(r"(\w+) (\w+)", + "first second third fourth fifth"), [('first', 'second'), ('third', + 'fourth')]) + self.assertEqual(regex.findall(r"(?r)(\w+) (\w+)", + "first second third fourth fifth"), [('fourth', 'fifth'), ('second', + 'third')]) + + self.assertEqual([m[0] for m in regex.finditer(r"(?r).{2}", "abc")], + ['bc']) + self.assertEqual([m[0] for m in regex.finditer(r"(?r).{2}", "abc", + overlapped=True)], ['bc', 'ab']) + self.assertEqual([m[0] for m in regex.finditer(r"(\w+) (\w+)", + "first second third fourth fifth")], ['first second', + 'third fourth']) + self.assertEqual([m[0] for m in regex.finditer(r"(?r)(\w+) (\w+)", + "first second third fourth fifth")], ['fourth fifth', + 'second third']) + + self.assertEqual(regex.search("abcdef", "abcdef").span(), (0, 6)) + self.assertEqual(regex.search("(?r)abcdef", "abcdef").span(), (0, 6)) + self.assertEqual(regex.search("(?i)abcdef", "ABCDEF").span(), (0, 6)) + self.assertEqual(regex.search("(?ir)abcdef", "ABCDEF").span(), (0, 6)) + + self.assertEqual(regex.sub(r"(.)", r"\1", "abc"), 'abc') + self.assertEqual(regex.sub(r"(?r)(.)", r"\1", "abc"), 'abc') + + def test_atomic(self): + # Issue 433030. + self.assertEqual(regex.search(r"(?>a*)a", "aa"), None) + + def test_possessive(self): + # Single-character non-possessive. + self.assertEqual(regex.search(r"a?a", "a").span(), (0, 1)) + self.assertEqual(regex.search(r"a*a", "aaa").span(), (0, 3)) + self.assertEqual(regex.search(r"a+a", "aaa").span(), (0, 3)) + self.assertEqual(regex.search(r"a{1,3}a", "aaa").span(), (0, 3)) + + # Multiple-character non-possessive. + self.assertEqual(regex.search(r"(?:ab)?ab", "ab").span(), (0, 2)) + self.assertEqual(regex.search(r"(?:ab)*ab", "ababab").span(), (0, 6)) + self.assertEqual(regex.search(r"(?:ab)+ab", "ababab").span(), (0, 6)) + self.assertEqual(regex.search(r"(?:ab){1,3}ab", "ababab").span(), (0, + 6)) + + # Single-character possessive. + self.assertEqual(regex.search(r"a?+a", "a"), None) + self.assertEqual(regex.search(r"a*+a", "aaa"), None) + self.assertEqual(regex.search(r"a++a", "aaa"), None) + self.assertEqual(regex.search(r"a{1,3}+a", "aaa"), None) + + # Multiple-character possessive. + self.assertEqual(regex.search(r"(?:ab)?+ab", "ab"), None) + self.assertEqual(regex.search(r"(?:ab)*+ab", "ababab"), None) + self.assertEqual(regex.search(r"(?:ab)++ab", "ababab"), None) + self.assertEqual(regex.search(r"(?:ab){1,3}+ab", "ababab"), None) + + def test_zerowidth(self): + # Issue 3262. + if sys.version_info >= (3, 7, 0): + self.assertEqual(regex.split(r"\b", "a b"), ['', 'a', ' ', 'b', + '']) + else: + self.assertEqual(regex.split(r"\b", "a b"), ['a b']) + self.assertEqual(regex.split(r"(?V1)\b", "a b"), ['', 'a', ' ', 'b', + '']) + + # Issue 1647489. + self.assertEqual(regex.findall(r"^|\w+", "foo bar"), ['', 'foo', + 'bar']) + self.assertEqual([m[0] for m in regex.finditer(r"^|\w+", "foo bar")], + ['', 'foo', 'bar']) + self.assertEqual(regex.findall(r"(?r)^|\w+", "foo bar"), ['bar', + 'foo', '']) + self.assertEqual([m[0] for m in regex.finditer(r"(?r)^|\w+", + "foo bar")], ['bar', 'foo', '']) + self.assertEqual(regex.findall(r"(?V1)^|\w+", "foo bar"), ['', 'foo', + 'bar']) + self.assertEqual([m[0] for m in regex.finditer(r"(?V1)^|\w+", + "foo bar")], ['', 'foo', 'bar']) + self.assertEqual(regex.findall(r"(?rV1)^|\w+", "foo bar"), ['bar', + 'foo', '']) + self.assertEqual([m[0] for m in regex.finditer(r"(?rV1)^|\w+", + "foo bar")], ['bar', 'foo', '']) + + if sys.version_info >= (3, 7, 0): + self.assertEqual(regex.split("", "xaxbxc"), ['', 'x', 'a', 'x', + 'b', 'x', 'c', '']) + self.assertEqual([m for m in regex.splititer("", "xaxbxc")], ['', + 'x', 'a', 'x', 'b', 'x', 'c', '']) + else: + self.assertEqual(regex.split("", "xaxbxc"), ['xaxbxc']) + self.assertEqual([m for m in regex.splititer("", "xaxbxc")], + ['xaxbxc']) + + if sys.version_info >= (3, 7, 0): + self.assertEqual(regex.split("(?r)", "xaxbxc"), ['', 'c', 'x', 'b', + 'x', 'a', 'x', '']) + self.assertEqual([m for m in regex.splititer("(?r)", "xaxbxc")], + ['', 'c', 'x', 'b', 'x', 'a', 'x', '']) + else: + self.assertEqual(regex.split("(?r)", "xaxbxc"), ['xaxbxc']) + self.assertEqual([m for m in regex.splititer("(?r)", "xaxbxc")], + ['xaxbxc']) + + self.assertEqual(regex.split("(?V1)", "xaxbxc"), ['', 'x', 'a', 'x', + 'b', 'x', 'c', '']) + self.assertEqual([m for m in regex.splititer("(?V1)", "xaxbxc")], ['', + 'x', 'a', 'x', 'b', 'x', 'c', '']) + + self.assertEqual(regex.split("(?rV1)", "xaxbxc"), ['', 'c', 'x', 'b', + 'x', 'a', 'x', '']) + self.assertEqual([m for m in regex.splititer("(?rV1)", "xaxbxc")], ['', + 'c', 'x', 'b', 'x', 'a', 'x', '']) + + def test_scoped_and_inline_flags(self): + # Issues 433028, 433024, 433027. + self.assertEqual(regex.search(r"(?i)Ab", "ab").span(), (0, 2)) + self.assertEqual(regex.search(r"(?i:A)b", "ab").span(), (0, 2)) + # Changed to positional flags in regex 2023.12.23. + self.assertEqual(regex.search(r"A(?i)b", "ab"), None) + + self.assertEqual(regex.search(r"(?V0)Ab", "ab"), None) + self.assertEqual(regex.search(r"(?V1)Ab", "ab"), None) + self.assertEqual(regex.search(r"(?-i)Ab", "ab", flags=regex.I), None) + self.assertEqual(regex.search(r"(?-i:A)b", "ab", flags=regex.I), None) + self.assertEqual(regex.search(r"A(?-i)b", "ab", flags=regex.I).span(), + (0, 2)) + + def test_repeated_repeats(self): + # Issue 2537. + self.assertEqual(regex.search(r"(?:a+)+", "aaa").span(), (0, 3)) + self.assertEqual(regex.search(r"(?:(?:ab)+c)+", "abcabc").span(), (0, + 6)) + + # Hg issue 286. + self.assertEqual(regex.search(r"(?:a+){2,}", "aaa").span(), (0, 3)) + + def test_lookbehind(self): + self.assertEqual(regex.search(r"123(?<=a\d+)", "a123").span(), (1, 4)) + self.assertEqual(regex.search(r"123(?<=a\d+)", "b123"), None) + self.assertEqual(regex.search(r"123(?= (3, 7, 0): + self.assertEqual(regex.sub(r"(?V0)(x)?(y)?", r"\2-\1", "xy"), + 'y-x-') + else: + self.assertEqual(regex.sub(r"(?V0)(x)?(y)?", r"\2-\1", "xy"), + 'y-x') + self.assertEqual(regex.sub(r"(?V1)(x)?(y)?", r"\2-\1", "xy"), 'y-x-') + if sys.version_info >= (3, 7, 0): + self.assertEqual(regex.sub(r"(?V0)(x)?(y)?", r"\2-\1", "x"), '-x-') + else: + self.assertEqual(regex.sub(r"(?V0)(x)?(y)?", r"\2-\1", "x"), '-x') + self.assertEqual(regex.sub(r"(?V1)(x)?(y)?", r"\2-\1", "x"), '-x-') + if sys.version_info >= (3, 7, 0): + self.assertEqual(regex.sub(r"(?V0)(x)?(y)?", r"\2-\1", "y"), 'y--') + else: + self.assertEqual(regex.sub(r"(?V0)(x)?(y)?", r"\2-\1", "y"), 'y-') + self.assertEqual(regex.sub(r"(?V1)(x)?(y)?", r"\2-\1", "y"), 'y--') + + def test_bug_10328 (self): + # Issue 10328. + pat = regex.compile(r'(?mV0)(?P[ \t]+\r*$)|(?P(?<=[^\n])\Z)') + if sys.version_info >= (3, 7, 0): + self.assertEqual(pat.subn(lambda m: '<' + m.lastgroup + '>', + 'foobar '), ('foobar', 2)) + else: + self.assertEqual(pat.subn(lambda m: '<' + m.lastgroup + '>', + 'foobar '), ('foobar', 1)) + self.assertEqual([m.group() for m in pat.finditer('foobar ')], [' ', + '']) + pat = regex.compile(r'(?mV1)(?P[ \t]+\r*$)|(?P(?<=[^\n])\Z)') + self.assertEqual(pat.subn(lambda m: '<' + m.lastgroup + '>', + 'foobar '), ('foobar', 2)) + self.assertEqual([m.group() for m in pat.finditer('foobar ')], [' ', + '']) + + def test_overlapped(self): + self.assertEqual(regex.findall(r"..", "abcde"), ['ab', 'cd']) + self.assertEqual(regex.findall(r"..", "abcde", overlapped=True), ['ab', + 'bc', 'cd', 'de']) + self.assertEqual(regex.findall(r"(?r)..", "abcde"), ['de', 'bc']) + self.assertEqual(regex.findall(r"(?r)..", "abcde", overlapped=True), + ['de', 'cd', 'bc', 'ab']) + self.assertEqual(regex.findall(r"(.)(-)(.)", "a-b-c", overlapped=True), + [("a", "-", "b"), ("b", "-", "c")]) + + self.assertEqual([m[0] for m in regex.finditer(r"..", "abcde")], ['ab', + 'cd']) + self.assertEqual([m[0] for m in regex.finditer(r"..", "abcde", + overlapped=True)], ['ab', 'bc', 'cd', 'de']) + self.assertEqual([m[0] for m in regex.finditer(r"(?r)..", "abcde")], + ['de', 'bc']) + self.assertEqual([m[0] for m in regex.finditer(r"(?r)..", "abcde", + overlapped=True)], ['de', 'cd', 'bc', 'ab']) + + self.assertEqual([m.groups() for m in regex.finditer(r"(.)(-)(.)", + "a-b-c", overlapped=True)], [("a", "-", "b"), ("b", "-", "c")]) + self.assertEqual([m.groups() for m in regex.finditer(r"(?r)(.)(-)(.)", + "a-b-c", overlapped=True)], [("b", "-", "c"), ("a", "-", "b")]) + + def test_splititer(self): + self.assertEqual(regex.split(r",", "a,b,,c,"), ['a', 'b', '', 'c', '']) + self.assertEqual([m for m in regex.splititer(r",", "a,b,,c,")], ['a', + 'b', '', 'c', '']) + + def test_grapheme(self): + self.assertEqual(regex.match(r"\X", "\xE0").span(), (0, 1)) + self.assertEqual(regex.match(r"\X", "a\u0300").span(), (0, 2)) + + self.assertEqual(regex.findall(r"\X", + "a\xE0a\u0300e\xE9e\u0301"), ['a', '\xe0', 'a\u0300', 'e', + '\xe9', 'e\u0301']) + self.assertEqual(regex.findall(r"\X{3}", + "a\xE0a\u0300e\xE9e\u0301"), ['a\xe0a\u0300', 'e\xe9e\u0301']) + self.assertEqual(regex.findall(r"\X", "\r\r\n\u0301A\u0301"), + ['\r', '\r\n', '\u0301', 'A\u0301']) + + def test_word_boundary(self): + text = 'The quick ("brown") fox can\'t jump 32.3 feet, right?' + self.assertEqual(regex.split(r'(?V1)\b', text), ['', 'The', ' ', + 'quick', ' ("', 'brown', '") ', 'fox', ' ', 'can', "'", 't', + ' ', 'jump', ' ', '32', '.', '3', ' ', 'feet', ', ', + 'right', '?']) + self.assertEqual(regex.split(r'(?V1w)\b', text), ['', 'The', ' ', + 'quick', ' ', '(', '"', 'brown', '"', ')', ' ', 'fox', ' ', + "can't", ' ', 'jump', ' ', '32.3', ' ', 'feet', ',', ' ', + 'right', '?', '']) + + text = "The fox" + self.assertEqual(regex.split(r'(?V1)\b', text), ['', 'The', ' ', + 'fox', '']) + self.assertEqual(regex.split(r'(?V1w)\b', text), ['', 'The', ' ', + 'fox', '']) + + text = "can't aujourd'hui l'objectif" + self.assertEqual(regex.split(r'(?V1)\b', text), ['', 'can', "'", + 't', ' ', 'aujourd', "'", 'hui', ' ', 'l', "'", 'objectif', + '']) + self.assertEqual(regex.split(r'(?V1w)\b', text), ['', "can't", ' ', + "aujourd'hui", ' ', "l'objectif", '']) + + def test_line_boundary(self): + self.assertEqual(regex.findall(r".+", "Line 1\nLine 2\n"), ["Line 1", + "Line 2"]) + self.assertEqual(regex.findall(r".+", "Line 1\rLine 2\r"), + ["Line 1\rLine 2\r"]) + self.assertEqual(regex.findall(r".+", "Line 1\r\nLine 2\r\n"), + ["Line 1\r", "Line 2\r"]) + self.assertEqual(regex.findall(r"(?w).+", "Line 1\nLine 2\n"), + ["Line 1", "Line 2"]) + self.assertEqual(regex.findall(r"(?w).+", "Line 1\rLine 2\r"), + ["Line 1", "Line 2"]) + self.assertEqual(regex.findall(r"(?w).+", "Line 1\r\nLine 2\r\n"), + ["Line 1", "Line 2"]) + + self.assertEqual(regex.search(r"^abc", "abc").start(), 0) + self.assertEqual(regex.search(r"^abc", "\nabc"), None) + self.assertEqual(regex.search(r"^abc", "\rabc"), None) + self.assertEqual(regex.search(r"(?w)^abc", "abc").start(), 0) + self.assertEqual(regex.search(r"(?w)^abc", "\nabc"), None) + self.assertEqual(regex.search(r"(?w)^abc", "\rabc"), None) + + self.assertEqual(regex.search(r"abc$", "abc").start(), 0) + self.assertEqual(regex.search(r"abc$", "abc\n").start(), 0) + self.assertEqual(regex.search(r"abc$", "abc\r"), None) + self.assertEqual(regex.search(r"(?w)abc$", "abc").start(), 0) + self.assertEqual(regex.search(r"(?w)abc$", "abc\n").start(), 0) + self.assertEqual(regex.search(r"(?w)abc$", "abc\r").start(), 0) + + self.assertEqual(regex.search(r"(?m)^abc", "abc").start(), 0) + self.assertEqual(regex.search(r"(?m)^abc", "\nabc").start(), 1) + self.assertEqual(regex.search(r"(?m)^abc", "\rabc"), None) + self.assertEqual(regex.search(r"(?mw)^abc", "abc").start(), 0) + self.assertEqual(regex.search(r"(?mw)^abc", "\nabc").start(), 1) + self.assertEqual(regex.search(r"(?mw)^abc", "\rabc").start(), 1) + + self.assertEqual(regex.search(r"(?m)abc$", "abc").start(), 0) + self.assertEqual(regex.search(r"(?m)abc$", "abc\n").start(), 0) + self.assertEqual(regex.search(r"(?m)abc$", "abc\r"), None) + self.assertEqual(regex.search(r"(?mw)abc$", "abc").start(), 0) + self.assertEqual(regex.search(r"(?mw)abc$", "abc\n").start(), 0) + self.assertEqual(regex.search(r"(?mw)abc$", "abc\r").start(), 0) + + def test_branch_reset(self): + self.assertEqual(regex.match(r"(?:(a)|(b))(c)", "ac").groups(), ('a', + None, 'c')) + self.assertEqual(regex.match(r"(?:(a)|(b))(c)", "bc").groups(), (None, + 'b', 'c')) + self.assertEqual(regex.match(r"(?:(?a)|(?b))(?c)", + "ac").groups(), ('a', None, 'c')) + self.assertEqual(regex.match(r"(?:(?a)|(?b))(?c)", + "bc").groups(), (None, 'b', 'c')) + + self.assertEqual(regex.match(r"(?a)(?:(?b)|(?c))(?d)", + "abd").groups(), ('a', 'b', None, 'd')) + self.assertEqual(regex.match(r"(?a)(?:(?b)|(?c))(?d)", + "acd").groups(), ('a', None, 'c', 'd')) + self.assertEqual(regex.match(r"(a)(?:(b)|(c))(d)", "abd").groups(), + ('a', 'b', None, 'd')) + + self.assertEqual(regex.match(r"(a)(?:(b)|(c))(d)", "acd").groups(), + ('a', None, 'c', 'd')) + self.assertEqual(regex.match(r"(a)(?|(b)|(b))(d)", "abd").groups(), + ('a', 'b', 'd')) + self.assertEqual(regex.match(r"(?|(?a)|(?b))(c)", "ac").groups(), + ('a', None, 'c')) + self.assertEqual(regex.match(r"(?|(?a)|(?b))(c)", "bc").groups(), + (None, 'b', 'c')) + self.assertEqual(regex.match(r"(?|(?a)|(?b))(c)", "ac").groups(), + ('a', 'c')) + + self.assertEqual(regex.match(r"(?|(?a)|(?b))(c)", "bc").groups(), + ('b', 'c')) + + self.assertEqual(regex.match(r"(?|(?a)(?b)|(?c)(?d))(e)", + "abe").groups(), ('a', 'b', 'e')) + self.assertEqual(regex.match(r"(?|(?a)(?b)|(?c)(?d))(e)", + "cde").groups(), ('d', 'c', 'e')) + self.assertEqual(regex.match(r"(?|(?a)(?b)|(?c)(d))(e)", + "abe").groups(), ('a', 'b', 'e')) + self.assertEqual(regex.match(r"(?|(?a)(?b)|(?c)(d))(e)", + "cde").groups(), ('d', 'c', 'e')) + self.assertEqual(regex.match(r"(?|(?a)(?b)|(c)(d))(e)", + "abe").groups(), ('a', 'b', 'e')) + self.assertEqual(regex.match(r"(?|(?a)(?b)|(c)(d))(e)", + "cde").groups(), ('c', 'd', 'e')) + + # Hg issue 87: Allow duplicate names of groups + self.assertEqual(regex.match(r"(?|(?a)(?b)|(c)(?d))(e)", + "abe").groups(), ("a", "b", "e")) + self.assertEqual(regex.match(r"(?|(?a)(?b)|(c)(?d))(e)", + "abe").capturesdict(), {"a": ["a"], "b": ["b"]}) + self.assertEqual(regex.match(r"(?|(?a)(?b)|(c)(?d))(e)", + "cde").groups(), ("d", None, "e")) + self.assertEqual(regex.match(r"(?|(?a)(?b)|(c)(?d))(e)", + "cde").capturesdict(), {"a": ["c", "d"], "b": []}) + + def test_set(self): + self.assertEqual(regex.match(r"[a]", "a").span(), (0, 1)) + self.assertEqual(regex.match(r"(?i)[a]", "A").span(), (0, 1)) + self.assertEqual(regex.match(r"[a-b]", r"a").span(), (0, 1)) + self.assertEqual(regex.match(r"(?i)[a-b]", r"A").span(), (0, 1)) + + self.assertEqual(regex.sub(r"(?V0)([][])", r"-", "a[b]c"), "a-b-c") + + self.assertEqual(regex.findall(r"[\p{Alpha}]", "a0"), ["a"]) + self.assertEqual(regex.findall(r"(?i)[\p{Alpha}]", "A0"), ["A"]) + + self.assertEqual(regex.findall(r"[a\p{Alpha}]", "ab0"), ["a", "b"]) + self.assertEqual(regex.findall(r"[a\P{Alpha}]", "ab0"), ["a", "0"]) + self.assertEqual(regex.findall(r"(?i)[a\p{Alpha}]", "ab0"), ["a", + "b"]) + self.assertEqual(regex.findall(r"(?i)[a\P{Alpha}]", "ab0"), ["a", + "0"]) + + self.assertEqual(regex.findall(r"[a-b\p{Alpha}]", "abC0"), ["a", + "b", "C"]) + self.assertEqual(regex.findall(r"(?i)[a-b\p{Alpha}]", "AbC0"), ["A", + "b", "C"]) + + self.assertEqual(regex.findall(r"[\p{Alpha}]", "a0"), ["a"]) + self.assertEqual(regex.findall(r"[\P{Alpha}]", "a0"), ["0"]) + self.assertEqual(regex.findall(r"[^\p{Alpha}]", "a0"), ["0"]) + self.assertEqual(regex.findall(r"[^\P{Alpha}]", "a0"), ["a"]) + + self.assertEqual("".join(regex.findall(r"[^\d-h]", "a^b12c-h")), + 'a^bc') + self.assertEqual("".join(regex.findall(r"[^\dh]", "a^b12c-h")), + 'a^bc-') + self.assertEqual("".join(regex.findall(r"[^h\s\db]", "a^b 12c-h")), + 'a^c-') + self.assertEqual("".join(regex.findall(r"[^b\w]", "a b")), ' ') + self.assertEqual("".join(regex.findall(r"[^b\S]", "a b")), ' ') + self.assertEqual("".join(regex.findall(r"[^8\d]", "a 1b2")), 'a b') + + all_chars = "".join(chr(c) for c in range(0x100)) + self.assertEqual(len(regex.findall(r"\p{ASCII}", all_chars)), 128) + self.assertEqual(len(regex.findall(r"\p{Letter}", all_chars)), + 117) + self.assertEqual(len(regex.findall(r"\p{Digit}", all_chars)), 10) + + # Set operators + self.assertEqual(len(regex.findall(r"(?V1)[\p{ASCII}&&\p{Letter}]", + all_chars)), 52) + self.assertEqual(len(regex.findall(r"(?V1)[\p{ASCII}&&\p{Alnum}&&\p{Letter}]", + all_chars)), 52) + self.assertEqual(len(regex.findall(r"(?V1)[\p{ASCII}&&\p{Alnum}&&\p{Digit}]", + all_chars)), 10) + self.assertEqual(len(regex.findall(r"(?V1)[\p{ASCII}&&\p{Cc}]", + all_chars)), 33) + self.assertEqual(len(regex.findall(r"(?V1)[\p{ASCII}&&\p{Graph}]", + all_chars)), 94) + self.assertEqual(len(regex.findall(r"(?V1)[\p{ASCII}--\p{Cc}]", + all_chars)), 95) + self.assertEqual(len(regex.findall(r"[\p{Letter}\p{Digit}]", + all_chars)), 127) + self.assertEqual(len(regex.findall(r"(?V1)[\p{Letter}||\p{Digit}]", + all_chars)), 127) + self.assertEqual(len(regex.findall(r"\p{HexDigit}", all_chars)), + 22) + self.assertEqual(len(regex.findall(r"(?V1)[\p{HexDigit}~~\p{Digit}]", + all_chars)), 12) + self.assertEqual(len(regex.findall(r"(?V1)[\p{Digit}~~\p{HexDigit}]", + all_chars)), 12) + + self.assertEqual(repr(type(regex.compile(r"(?V0)([][-])"))), + self.PATTERN_CLASS) + self.assertEqual(regex.findall(r"(?V1)[[a-z]--[aei]]", "abc"), ["b", + "c"]) + self.assertEqual(regex.findall(r"(?iV1)[[a-z]--[aei]]", "abc"), ["b", + "c"]) + self.assertEqual(regex.findall(r"(?V1)[\w--a]","abc"), ["b", "c"]) + self.assertEqual(regex.findall(r"(?iV1)[\w--a]","abc"), ["b", "c"]) + + def test_various(self): + tests = [ + # Test ?P< and ?P= extensions. + ('(?Pa)', '', '', regex.error, self.BAD_GROUP_NAME), # Begins with a digit. + ('(?Pa)', '', '', regex.error, self.BAD_GROUP_NAME), # Begins with an illegal char. + ('(?Pa)', '', '', regex.error, self.BAD_GROUP_NAME), # Begins with an illegal char. + + # Same tests, for the ?P= form. + ('(?Pa)(?P=foo_123', 'aa', '', regex.error, + self.MISSING_RPAREN), + ('(?Pa)(?P=1)', 'aa', '1', ascii('a')), + ('(?Pa)(?P=0)', 'aa', '', regex.error, + self.BAD_GROUP_NAME), + ('(?Pa)(?P=-1)', 'aa', '', regex.error, + self.BAD_GROUP_NAME), + ('(?Pa)(?P=!)', 'aa', '', regex.error, + self.BAD_GROUP_NAME), + ('(?Pa)(?P=foo_124)', 'aa', '', regex.error, + self.UNKNOWN_GROUP), # Backref to undefined group. + + ('(?Pa)', 'a', '1', ascii('a')), + ('(?Pa)(?P=foo_123)', 'aa', '1', ascii('a')), + + # Mal-formed \g in pattern treated as literal for compatibility. + (r'(?a)\ga)\g<1>', 'aa', '1', ascii('a')), + (r'(?a)\g', 'aa', '', ascii(None)), + (r'(?a)\g', 'aa', '', regex.error, + self.UNKNOWN_GROUP), # Backref to undefined group. + + ('(?a)', 'a', '1', ascii('a')), + (r'(?a)\g', 'aa', '1', ascii('a')), + + # Test octal escapes. + ('\\1', 'a', '', regex.error, self.INVALID_GROUP_REF), # Backreference. + ('[\\1]', '\1', '0', "'\\x01'"), # Character. + ('\\09', chr(0) + '9', '0', ascii(chr(0) + '9')), + ('\\141', 'a', '0', ascii('a')), + ('(a)(b)(c)(d)(e)(f)(g)(h)(i)(j)(k)(l)\\119', 'abcdefghijklk9', + '0,11', ascii(('abcdefghijklk9', 'k'))), + + # Test \0 is handled everywhere. + (r'\0', '\0', '0', ascii('\0')), + (r'[\0a]', '\0', '0', ascii('\0')), + (r'[a\0]', '\0', '0', ascii('\0')), + (r'[^a\0]', '\0', '', ascii(None)), + + # Test various letter escapes. + (r'\a[\b]\f\n\r\t\v', '\a\b\f\n\r\t\v', '0', + ascii('\a\b\f\n\r\t\v')), + (r'[\a][\b][\f][\n][\r][\t][\v]', '\a\b\f\n\r\t\v', '0', + ascii('\a\b\f\n\r\t\v')), + (r'\xff', '\377', '0', ascii(chr(255))), + + # New \x semantics. + (r'\x00ffffffffffffff', '\377', '', ascii(None)), + (r'\x00f', '\017', '', ascii(None)), + (r'\x00fe', '\376', '', ascii(None)), + + (r'\x00ff', '\377', '', ascii(None)), + (r'\t\n\v\r\f\a\g', '\t\n\v\r\f\ag', '0', ascii('\t\n\v\r\f\ag')), + ('\t\n\v\r\f\a\\g', '\t\n\v\r\f\ag', '0', ascii('\t\n\v\r\f\ag')), + (r'\t\n\v\r\f\a', '\t\n\v\r\f\a', '0', ascii(chr(9) + chr(10) + + chr(11) + chr(13) + chr(12) + chr(7))), + (r'[\t][\n][\v][\r][\f][\b]', '\t\n\v\r\f\b', '0', + ascii('\t\n\v\r\f\b')), + + (r"^\w+=(\\[\000-\277]|[^\n\\])*", + "SRC=eval.c g.c blah blah blah \\\\\n\tapes.c", '0', + ascii("SRC=eval.c g.c blah blah blah \\\\")), + + # Test that . only matches \n in DOTALL mode. + ('a.b', 'acb', '0', ascii('acb')), + ('a.b', 'a\nb', '', ascii(None)), + ('a.*b', 'acc\nccb', '', ascii(None)), + ('a.{4,5}b', 'acc\nccb', '', ascii(None)), + ('a.b', 'a\rb', '0', ascii('a\rb')), + # Changed to positional flags in regex 2023.12.23. + ('a.b(?s)', 'a\nb', '', ascii(None)), + ('(?s)a.b', 'a\nb', '0', ascii('a\nb')), + ('a.*(?s)b', 'acc\nccb', '', ascii(None)), + ('(?s)a.*b', 'acc\nccb', '0', ascii('acc\nccb')), + ('(?s)a.{4,5}b', 'acc\nccb', '0', ascii('acc\nccb')), + + (')', '', '', regex.error, self.TRAILING_CHARS), # Unmatched right bracket. + ('', '', '0', "''"), # Empty pattern. + ('abc', 'abc', '0', ascii('abc')), + ('abc', 'xbc', '', ascii(None)), + ('abc', 'axc', '', ascii(None)), + ('abc', 'abx', '', ascii(None)), + ('abc', 'xabcy', '0', ascii('abc')), + ('abc', 'ababc', '0', ascii('abc')), + ('ab*c', 'abc', '0', ascii('abc')), + ('ab*bc', 'abc', '0', ascii('abc')), + + ('ab*bc', 'abbc', '0', ascii('abbc')), + ('ab*bc', 'abbbbc', '0', ascii('abbbbc')), + ('ab+bc', 'abbc', '0', ascii('abbc')), + ('ab+bc', 'abc', '', ascii(None)), + ('ab+bc', 'abq', '', ascii(None)), + ('ab+bc', 'abbbbc', '0', ascii('abbbbc')), + ('ab?bc', 'abbc', '0', ascii('abbc')), + ('ab?bc', 'abc', '0', ascii('abc')), + ('ab?bc', 'abbbbc', '', ascii(None)), + ('ab?c', 'abc', '0', ascii('abc')), + + ('^abc$', 'abc', '0', ascii('abc')), + ('^abc$', 'abcc', '', ascii(None)), + ('^abc', 'abcc', '0', ascii('abc')), + ('^abc$', 'aabc', '', ascii(None)), + ('abc$', 'aabc', '0', ascii('abc')), + ('^', 'abc', '0', ascii('')), + ('$', 'abc', '0', ascii('')), + ('a.c', 'abc', '0', ascii('abc')), + ('a.c', 'axc', '0', ascii('axc')), + ('a.*c', 'axyzc', '0', ascii('axyzc')), + + ('a.*c', 'axyzd', '', ascii(None)), + ('a[bc]d', 'abc', '', ascii(None)), + ('a[bc]d', 'abd', '0', ascii('abd')), + ('a[b-d]e', 'abd', '', ascii(None)), + ('a[b-d]e', 'ace', '0', ascii('ace')), + ('a[b-d]', 'aac', '0', ascii('ac')), + ('a[-b]', 'a-', '0', ascii('a-')), + ('a[\\-b]', 'a-', '0', ascii('a-')), + ('a[b-]', 'a-', '0', ascii('a-')), + ('a[]b', '-', '', regex.error, self.BAD_SET), + + ('a[', '-', '', regex.error, self.BAD_SET), + ('a\\', '-', '', regex.error, self.BAD_ESCAPE), + ('abc)', '-', '', regex.error, self.TRAILING_CHARS), + ('(abc', '-', '', regex.error, self.MISSING_RPAREN), + ('a]', 'a]', '0', ascii('a]')), + ('a[]]b', 'a]b', '0', ascii('a]b')), + ('a[]]b', 'a]b', '0', ascii('a]b')), + ('a[^bc]d', 'aed', '0', ascii('aed')), + ('a[^bc]d', 'abd', '', ascii(None)), + ('a[^-b]c', 'adc', '0', ascii('adc')), + + ('a[^-b]c', 'a-c', '', ascii(None)), + ('a[^]b]c', 'a]c', '', ascii(None)), + ('a[^]b]c', 'adc', '0', ascii('adc')), + ('\\ba\\b', 'a-', '0', ascii('a')), + ('\\ba\\b', '-a', '0', ascii('a')), + ('\\ba\\b', '-a-', '0', ascii('a')), + ('\\by\\b', 'xy', '', ascii(None)), + ('\\by\\b', 'yz', '', ascii(None)), + ('\\by\\b', 'xyz', '', ascii(None)), + ('x\\b', 'xyz', '', ascii(None)), + + ('x\\B', 'xyz', '0', ascii('x')), + ('\\Bz', 'xyz', '0', ascii('z')), + ('z\\B', 'xyz', '', ascii(None)), + ('\\Bx', 'xyz', '', ascii(None)), + ('\\Ba\\B', 'a-', '', ascii(None)), + ('\\Ba\\B', '-a', '', ascii(None)), + ('\\Ba\\B', '-a-', '', ascii(None)), + ('\\By\\B', 'xy', '', ascii(None)), + ('\\By\\B', 'yz', '', ascii(None)), + ('\\By\\b', 'xy', '0', ascii('y')), + + ('\\by\\B', 'yz', '0', ascii('y')), + ('\\By\\B', 'xyz', '0', ascii('y')), + ('ab|cd', 'abc', '0', ascii('ab')), + ('ab|cd', 'abcd', '0', ascii('ab')), + ('()ef', 'def', '0,1', ascii(('ef', ''))), + ('$b', 'b', '', ascii(None)), + ('a\\(b', 'a(b', '', ascii(('a(b',))), + ('a\\(*b', 'ab', '0', ascii('ab')), + ('a\\(*b', 'a((b', '0', ascii('a((b')), + ('a\\\\b', 'a\\b', '0', ascii('a\\b')), + + ('((a))', 'abc', '0,1,2', ascii(('a', 'a', 'a'))), + ('(a)b(c)', 'abc', '0,1,2', ascii(('abc', 'a', 'c'))), + ('a+b+c', 'aabbabc', '0', ascii('abc')), + ('(a+|b)*', 'ab', '0,1', ascii(('ab', 'b'))), + ('(a+|b)+', 'ab', '0,1', ascii(('ab', 'b'))), + ('(a+|b)?', 'ab', '0,1', ascii(('a', 'a'))), + (')(', '-', '', regex.error, self.TRAILING_CHARS), + ('[^ab]*', 'cde', '0', ascii('cde')), + ('abc', '', '', ascii(None)), + ('a*', '', '0', ascii('')), + + ('a|b|c|d|e', 'e', '0', ascii('e')), + ('(a|b|c|d|e)f', 'ef', '0,1', ascii(('ef', 'e'))), + ('abcd*efg', 'abcdefg', '0', ascii('abcdefg')), + ('ab*', 'xabyabbbz', '0', ascii('ab')), + ('ab*', 'xayabbbz', '0', ascii('a')), + ('(ab|cd)e', 'abcde', '0,1', ascii(('cde', 'cd'))), + ('[abhgefdc]ij', 'hij', '0', ascii('hij')), + ('^(ab|cd)e', 'abcde', '', ascii(None)), + ('(abc|)ef', 'abcdef', '0,1', ascii(('ef', ''))), + ('(a|b)c*d', 'abcd', '0,1', ascii(('bcd', 'b'))), + + ('(ab|ab*)bc', 'abc', '0,1', ascii(('abc', 'a'))), + ('a([bc]*)c*', 'abc', '0,1', ascii(('abc', 'bc'))), + ('a([bc]*)(c*d)', 'abcd', '0,1,2', ascii(('abcd', 'bc', 'd'))), + ('a([bc]+)(c*d)', 'abcd', '0,1,2', ascii(('abcd', 'bc', 'd'))), + ('a([bc]*)(c+d)', 'abcd', '0,1,2', ascii(('abcd', 'b', 'cd'))), + ('a[bcd]*dcdcde', 'adcdcde', '0', ascii('adcdcde')), + ('a[bcd]+dcdcde', 'adcdcde', '', ascii(None)), + ('(ab|a)b*c', 'abc', '0,1', ascii(('abc', 'ab'))), + ('((a)(b)c)(d)', 'abcd', '1,2,3,4', ascii(('abc', 'a', 'b', 'd'))), + ('[a-zA-Z_][a-zA-Z0-9_]*', 'alpha', '0', ascii('alpha')), + + ('^a(bc+|b[eh])g|.h$', 'abh', '0,1', ascii(('bh', None))), + ('(bc+d$|ef*g.|h?i(j|k))', 'effgz', '0,1,2', ascii(('effgz', + 'effgz', None))), + ('(bc+d$|ef*g.|h?i(j|k))', 'ij', '0,1,2', ascii(('ij', 'ij', + 'j'))), + ('(bc+d$|ef*g.|h?i(j|k))', 'effg', '', ascii(None)), + ('(bc+d$|ef*g.|h?i(j|k))', 'bcdd', '', ascii(None)), + ('(bc+d$|ef*g.|h?i(j|k))', 'reffgz', '0,1,2', ascii(('effgz', + 'effgz', None))), + ('(((((((((a)))))))))', 'a', '0', ascii('a')), + ('multiple words of text', 'uh-uh', '', ascii(None)), + ('multiple words', 'multiple words, yeah', '0', + ascii('multiple words')), + ('(.*)c(.*)', 'abcde', '0,1,2', ascii(('abcde', 'ab', 'de'))), + + ('\\((.*), (.*)\\)', '(a, b)', '2,1', ascii(('b', 'a'))), + ('[k]', 'ab', '', ascii(None)), + ('a[-]?c', 'ac', '0', ascii('ac')), + ('(abc)\\1', 'abcabc', '1', ascii('abc')), + ('([a-c]*)\\1', 'abcabc', '1', ascii('abc')), + ('^(.+)?B', 'AB', '1', ascii('A')), + ('(a+).\\1$', 'aaaaa', '0,1', ascii(('aaaaa', 'aa'))), + ('^(a+).\\1$', 'aaaa', '', ascii(None)), + ('(abc)\\1', 'abcabc', '0,1', ascii(('abcabc', 'abc'))), + ('([a-c]+)\\1', 'abcabc', '0,1', ascii(('abcabc', 'abc'))), + + ('(a)\\1', 'aa', '0,1', ascii(('aa', 'a'))), + ('(a+)\\1', 'aa', '0,1', ascii(('aa', 'a'))), + ('(a+)+\\1', 'aa', '0,1', ascii(('aa', 'a'))), + ('(a).+\\1', 'aba', '0,1', ascii(('aba', 'a'))), + ('(a)ba*\\1', 'aba', '0,1', ascii(('aba', 'a'))), + ('(aa|a)a\\1$', 'aaa', '0,1', ascii(('aaa', 'a'))), + ('(a|aa)a\\1$', 'aaa', '0,1', ascii(('aaa', 'a'))), + ('(a+)a\\1$', 'aaa', '0,1', ascii(('aaa', 'a'))), + ('([abc]*)\\1', 'abcabc', '0,1', ascii(('abcabc', 'abc'))), + ('(a)(b)c|ab', 'ab', '0,1,2', ascii(('ab', None, None))), + + ('(a)+x', 'aaax', '0,1', ascii(('aaax', 'a'))), + ('([ac])+x', 'aacx', '0,1', ascii(('aacx', 'c'))), + ('([^/]*/)*sub1/', 'd:msgs/tdir/sub1/trial/away.cpp', '0,1', + ascii(('d:msgs/tdir/sub1/', 'tdir/'))), + ('([^.]*)\\.([^:]*):[T ]+(.*)', 'track1.title:TBlah blah blah', + '0,1,2,3', ascii(('track1.title:TBlah blah blah', 'track1', + 'title', 'Blah blah blah'))), + ('([^N]*N)+', 'abNNxyzN', '0,1', ascii(('abNNxyzN', 'xyzN'))), + ('([^N]*N)+', 'abNNxyz', '0,1', ascii(('abNN', 'N'))), + ('([abc]*)x', 'abcx', '0,1', ascii(('abcx', 'abc'))), + ('([abc]*)x', 'abc', '', ascii(None)), + ('([xyz]*)x', 'abcx', '0,1', ascii(('x', ''))), + ('(a)+b|aac', 'aac', '0,1', ascii(('aac', None))), + + # Test symbolic groups. + ('(?Paaa)a', 'aaaa', '', regex.error, self.BAD_GROUP_NAME), + ('(?Paaa)a', 'aaaa', '0,id', ascii(('aaaa', 'aaa'))), + ('(?Paa)(?P=id)', 'aaaa', '0,id', ascii(('aaaa', 'aa'))), + ('(?Paa)(?P=xd)', 'aaaa', '', regex.error, self.UNKNOWN_GROUP), + + # Character properties. + (r"\g", "g", '0', ascii('g')), + (r"\g<1>", "g", '', regex.error, self.INVALID_GROUP_REF), + (r"(.)\g<1>", "gg", '0', ascii('gg')), + (r"(.)\g<1>", "gg", '', ascii(('gg', 'g'))), + (r"\N", "N", '0', ascii('N')), + (r"\N{LATIN SMALL LETTER A}", "a", '0', ascii('a')), + (r"\p", "p", '0', ascii('p')), + (r"\p{Ll}", "a", '0', ascii('a')), + (r"\P", "P", '0', ascii('P')), + (r"\P{Lu}", "p", '0', ascii('p')), + + # All tests from Perl. + ('abc', 'abc', '0', ascii('abc')), + ('abc', 'xbc', '', ascii(None)), + ('abc', 'axc', '', ascii(None)), + ('abc', 'abx', '', ascii(None)), + ('abc', 'xabcy', '0', ascii('abc')), + ('abc', 'ababc', '0', ascii('abc')), + + ('ab*c', 'abc', '0', ascii('abc')), + ('ab*bc', 'abc', '0', ascii('abc')), + ('ab*bc', 'abbc', '0', ascii('abbc')), + ('ab*bc', 'abbbbc', '0', ascii('abbbbc')), + ('ab{0,}bc', 'abbbbc', '0', ascii('abbbbc')), + ('ab+bc', 'abbc', '0', ascii('abbc')), + ('ab+bc', 'abc', '', ascii(None)), + ('ab+bc', 'abq', '', ascii(None)), + ('ab{1,}bc', 'abq', '', ascii(None)), + ('ab+bc', 'abbbbc', '0', ascii('abbbbc')), + + ('ab{1,}bc', 'abbbbc', '0', ascii('abbbbc')), + ('ab{1,3}bc', 'abbbbc', '0', ascii('abbbbc')), + ('ab{3,4}bc', 'abbbbc', '0', ascii('abbbbc')), + ('ab{4,5}bc', 'abbbbc', '', ascii(None)), + ('ab?bc', 'abbc', '0', ascii('abbc')), + ('ab?bc', 'abc', '0', ascii('abc')), + ('ab{0,1}bc', 'abc', '0', ascii('abc')), + ('ab?bc', 'abbbbc', '', ascii(None)), + ('ab?c', 'abc', '0', ascii('abc')), + ('ab{0,1}c', 'abc', '0', ascii('abc')), + + ('^abc$', 'abc', '0', ascii('abc')), + ('^abc$', 'abcc', '', ascii(None)), + ('^abc', 'abcc', '0', ascii('abc')), + ('^abc$', 'aabc', '', ascii(None)), + ('abc$', 'aabc', '0', ascii('abc')), + ('^', 'abc', '0', ascii('')), + ('$', 'abc', '0', ascii('')), + ('a.c', 'abc', '0', ascii('abc')), + ('a.c', 'axc', '0', ascii('axc')), + ('a.*c', 'axyzc', '0', ascii('axyzc')), + + ('a.*c', 'axyzd', '', ascii(None)), + ('a[bc]d', 'abc', '', ascii(None)), + ('a[bc]d', 'abd', '0', ascii('abd')), + ('a[b-d]e', 'abd', '', ascii(None)), + ('a[b-d]e', 'ace', '0', ascii('ace')), + ('a[b-d]', 'aac', '0', ascii('ac')), + ('a[-b]', 'a-', '0', ascii('a-')), + ('a[b-]', 'a-', '0', ascii('a-')), + ('a[b-a]', '-', '', regex.error, self.BAD_CHAR_RANGE), + ('a[]b', '-', '', regex.error, self.BAD_SET), + + ('a[', '-', '', regex.error, self.BAD_SET), + ('a]', 'a]', '0', ascii('a]')), + ('a[]]b', 'a]b', '0', ascii('a]b')), + ('a[^bc]d', 'aed', '0', ascii('aed')), + ('a[^bc]d', 'abd', '', ascii(None)), + ('a[^-b]c', 'adc', '0', ascii('adc')), + ('a[^-b]c', 'a-c', '', ascii(None)), + ('a[^]b]c', 'a]c', '', ascii(None)), + ('a[^]b]c', 'adc', '0', ascii('adc')), + ('ab|cd', 'abc', '0', ascii('ab')), + + ('ab|cd', 'abcd', '0', ascii('ab')), + ('()ef', 'def', '0,1', ascii(('ef', ''))), + ('*a', '-', '', regex.error, self.NOTHING_TO_REPEAT), + ('(*)b', '-', '', regex.error, self.NOTHING_TO_REPEAT), + ('$b', 'b', '', ascii(None)), + ('a\\', '-', '', regex.error, self.BAD_ESCAPE), + ('a\\(b', 'a(b', '', ascii(('a(b',))), + ('a\\(*b', 'ab', '0', ascii('ab')), + ('a\\(*b', 'a((b', '0', ascii('a((b')), + ('a\\\\b', 'a\\b', '0', ascii('a\\b')), + + ('abc)', '-', '', regex.error, self.TRAILING_CHARS), + ('(abc', '-', '', regex.error, self.MISSING_RPAREN), + ('((a))', 'abc', '0,1,2', ascii(('a', 'a', 'a'))), + ('(a)b(c)', 'abc', '0,1,2', ascii(('abc', 'a', 'c'))), + ('a+b+c', 'aabbabc', '0', ascii('abc')), + ('a{1,}b{1,}c', 'aabbabc', '0', ascii('abc')), + ('a**', '-', '', regex.error, self.MULTIPLE_REPEAT), + ('a.+?c', 'abcabc', '0', ascii('abc')), + ('(a+|b)*', 'ab', '0,1', ascii(('ab', 'b'))), + ('(a+|b){0,}', 'ab', '0,1', ascii(('ab', 'b'))), + + ('(a+|b)+', 'ab', '0,1', ascii(('ab', 'b'))), + ('(a+|b){1,}', 'ab', '0,1', ascii(('ab', 'b'))), + ('(a+|b)?', 'ab', '0,1', ascii(('a', 'a'))), + ('(a+|b){0,1}', 'ab', '0,1', ascii(('a', 'a'))), + (')(', '-', '', regex.error, self.TRAILING_CHARS), + ('[^ab]*', 'cde', '0', ascii('cde')), + ('abc', '', '', ascii(None)), + ('a*', '', '0', ascii('')), + ('([abc])*d', 'abbbcd', '0,1', ascii(('abbbcd', 'c'))), + ('([abc])*bcd', 'abcd', '0,1', ascii(('abcd', 'a'))), + + ('a|b|c|d|e', 'e', '0', ascii('e')), + ('(a|b|c|d|e)f', 'ef', '0,1', ascii(('ef', 'e'))), + ('abcd*efg', 'abcdefg', '0', ascii('abcdefg')), + ('ab*', 'xabyabbbz', '0', ascii('ab')), + ('ab*', 'xayabbbz', '0', ascii('a')), + ('(ab|cd)e', 'abcde', '0,1', ascii(('cde', 'cd'))), + ('[abhgefdc]ij', 'hij', '0', ascii('hij')), + ('^(ab|cd)e', 'abcde', '', ascii(None)), + ('(abc|)ef', 'abcdef', '0,1', ascii(('ef', ''))), + ('(a|b)c*d', 'abcd', '0,1', ascii(('bcd', 'b'))), + + ('(ab|ab*)bc', 'abc', '0,1', ascii(('abc', 'a'))), + ('a([bc]*)c*', 'abc', '0,1', ascii(('abc', 'bc'))), + ('a([bc]*)(c*d)', 'abcd', '0,1,2', ascii(('abcd', 'bc', 'd'))), + ('a([bc]+)(c*d)', 'abcd', '0,1,2', ascii(('abcd', 'bc', 'd'))), + ('a([bc]*)(c+d)', 'abcd', '0,1,2', ascii(('abcd', 'b', 'cd'))), + ('a[bcd]*dcdcde', 'adcdcde', '0', ascii('adcdcde')), + ('a[bcd]+dcdcde', 'adcdcde', '', ascii(None)), + ('(ab|a)b*c', 'abc', '0,1', ascii(('abc', 'ab'))), + ('((a)(b)c)(d)', 'abcd', '1,2,3,4', ascii(('abc', 'a', 'b', 'd'))), + ('[a-zA-Z_][a-zA-Z0-9_]*', 'alpha', '0', ascii('alpha')), + + ('^a(bc+|b[eh])g|.h$', 'abh', '0,1', ascii(('bh', None))), + ('(bc+d$|ef*g.|h?i(j|k))', 'effgz', '0,1,2', ascii(('effgz', + 'effgz', None))), + ('(bc+d$|ef*g.|h?i(j|k))', 'ij', '0,1,2', ascii(('ij', 'ij', + 'j'))), + ('(bc+d$|ef*g.|h?i(j|k))', 'effg', '', ascii(None)), + ('(bc+d$|ef*g.|h?i(j|k))', 'bcdd', '', ascii(None)), + ('(bc+d$|ef*g.|h?i(j|k))', 'reffgz', '0,1,2', ascii(('effgz', + 'effgz', None))), + ('((((((((((a))))))))))', 'a', '10', ascii('a')), + ('((((((((((a))))))))))\\10', 'aa', '0', ascii('aa')), + + # Python does not have the same rules for \\41 so this is a syntax error + # ('((((((((((a))))))))))\\41', 'aa', '', ascii(None)), + # ('((((((((((a))))))))))\\41', 'a!', '0', ascii('a!')), + ('((((((((((a))))))))))\\41', '', '', regex.error, + self.INVALID_GROUP_REF), + ('(?i)((((((((((a))))))))))\\41', '', '', regex.error, + self.INVALID_GROUP_REF), + + ('(((((((((a)))))))))', 'a', '0', ascii('a')), + ('multiple words of text', 'uh-uh', '', ascii(None)), + ('multiple words', 'multiple words, yeah', '0', + ascii('multiple words')), + ('(.*)c(.*)', 'abcde', '0,1,2', ascii(('abcde', 'ab', 'de'))), + ('\\((.*), (.*)\\)', '(a, b)', '2,1', ascii(('b', 'a'))), + ('[k]', 'ab', '', ascii(None)), + ('a[-]?c', 'ac', '0', ascii('ac')), + ('(abc)\\1', 'abcabc', '1', ascii('abc')), + ('([a-c]*)\\1', 'abcabc', '1', ascii('abc')), + ('(?i)abc', 'ABC', '0', ascii('ABC')), + + ('(?i)abc', 'XBC', '', ascii(None)), + ('(?i)abc', 'AXC', '', ascii(None)), + ('(?i)abc', 'ABX', '', ascii(None)), + ('(?i)abc', 'XABCY', '0', ascii('ABC')), + ('(?i)abc', 'ABABC', '0', ascii('ABC')), + ('(?i)ab*c', 'ABC', '0', ascii('ABC')), + ('(?i)ab*bc', 'ABC', '0', ascii('ABC')), + ('(?i)ab*bc', 'ABBC', '0', ascii('ABBC')), + ('(?i)ab*?bc', 'ABBBBC', '0', ascii('ABBBBC')), + ('(?i)ab{0,}?bc', 'ABBBBC', '0', ascii('ABBBBC')), + + ('(?i)ab+?bc', 'ABBC', '0', ascii('ABBC')), + ('(?i)ab+bc', 'ABC', '', ascii(None)), + ('(?i)ab+bc', 'ABQ', '', ascii(None)), + ('(?i)ab{1,}bc', 'ABQ', '', ascii(None)), + ('(?i)ab+bc', 'ABBBBC', '0', ascii('ABBBBC')), + ('(?i)ab{1,}?bc', 'ABBBBC', '0', ascii('ABBBBC')), + ('(?i)ab{1,3}?bc', 'ABBBBC', '0', ascii('ABBBBC')), + ('(?i)ab{3,4}?bc', 'ABBBBC', '0', ascii('ABBBBC')), + ('(?i)ab{4,5}?bc', 'ABBBBC', '', ascii(None)), + ('(?i)ab??bc', 'ABBC', '0', ascii('ABBC')), + + ('(?i)ab??bc', 'ABC', '0', ascii('ABC')), + ('(?i)ab{0,1}?bc', 'ABC', '0', ascii('ABC')), + ('(?i)ab??bc', 'ABBBBC', '', ascii(None)), + ('(?i)ab??c', 'ABC', '0', ascii('ABC')), + ('(?i)ab{0,1}?c', 'ABC', '0', ascii('ABC')), + ('(?i)^abc$', 'ABC', '0', ascii('ABC')), + ('(?i)^abc$', 'ABCC', '', ascii(None)), + ('(?i)^abc', 'ABCC', '0', ascii('ABC')), + ('(?i)^abc$', 'AABC', '', ascii(None)), + ('(?i)abc$', 'AABC', '0', ascii('ABC')), + + ('(?i)^', 'ABC', '0', ascii('')), + ('(?i)$', 'ABC', '0', ascii('')), + ('(?i)a.c', 'ABC', '0', ascii('ABC')), + ('(?i)a.c', 'AXC', '0', ascii('AXC')), + ('(?i)a.*?c', 'AXYZC', '0', ascii('AXYZC')), + ('(?i)a.*c', 'AXYZD', '', ascii(None)), + ('(?i)a[bc]d', 'ABC', '', ascii(None)), + ('(?i)a[bc]d', 'ABD', '0', ascii('ABD')), + ('(?i)a[b-d]e', 'ABD', '', ascii(None)), + ('(?i)a[b-d]e', 'ACE', '0', ascii('ACE')), + + ('(?i)a[b-d]', 'AAC', '0', ascii('AC')), + ('(?i)a[-b]', 'A-', '0', ascii('A-')), + ('(?i)a[b-]', 'A-', '0', ascii('A-')), + ('(?i)a[b-a]', '-', '', regex.error, self.BAD_CHAR_RANGE), + ('(?i)a[]b', '-', '', regex.error, self.BAD_SET), + ('(?i)a[', '-', '', regex.error, self.BAD_SET), + ('(?i)a]', 'A]', '0', ascii('A]')), + ('(?i)a[]]b', 'A]B', '0', ascii('A]B')), + ('(?i)a[^bc]d', 'AED', '0', ascii('AED')), + ('(?i)a[^bc]d', 'ABD', '', ascii(None)), + + ('(?i)a[^-b]c', 'ADC', '0', ascii('ADC')), + ('(?i)a[^-b]c', 'A-C', '', ascii(None)), + ('(?i)a[^]b]c', 'A]C', '', ascii(None)), + ('(?i)a[^]b]c', 'ADC', '0', ascii('ADC')), + ('(?i)ab|cd', 'ABC', '0', ascii('AB')), + ('(?i)ab|cd', 'ABCD', '0', ascii('AB')), + ('(?i)()ef', 'DEF', '0,1', ascii(('EF', ''))), + ('(?i)*a', '-', '', regex.error, self.NOTHING_TO_REPEAT), + ('(?i)(*)b', '-', '', regex.error, self.NOTHING_TO_REPEAT), + ('(?i)$b', 'B', '', ascii(None)), + + ('(?i)a\\', '-', '', regex.error, self.BAD_ESCAPE), + ('(?i)a\\(b', 'A(B', '', ascii(('A(B',))), + ('(?i)a\\(*b', 'AB', '0', ascii('AB')), + ('(?i)a\\(*b', 'A((B', '0', ascii('A((B')), + ('(?i)a\\\\b', 'A\\B', '0', ascii('A\\B')), + ('(?i)abc)', '-', '', regex.error, self.TRAILING_CHARS), + ('(?i)(abc', '-', '', regex.error, self.MISSING_RPAREN), + ('(?i)((a))', 'ABC', '0,1,2', ascii(('A', 'A', 'A'))), + ('(?i)(a)b(c)', 'ABC', '0,1,2', ascii(('ABC', 'A', 'C'))), + ('(?i)a+b+c', 'AABBABC', '0', ascii('ABC')), + + ('(?i)a{1,}b{1,}c', 'AABBABC', '0', ascii('ABC')), + ('(?i)a**', '-', '', regex.error, self.MULTIPLE_REPEAT), + ('(?i)a.+?c', 'ABCABC', '0', ascii('ABC')), + ('(?i)a.*?c', 'ABCABC', '0', ascii('ABC')), + ('(?i)a.{0,5}?c', 'ABCABC', '0', ascii('ABC')), + ('(?i)(a+|b)*', 'AB', '0,1', ascii(('AB', 'B'))), + ('(?i)(a+|b){0,}', 'AB', '0,1', ascii(('AB', 'B'))), + ('(?i)(a+|b)+', 'AB', '0,1', ascii(('AB', 'B'))), + ('(?i)(a+|b){1,}', 'AB', '0,1', ascii(('AB', 'B'))), + ('(?i)(a+|b)?', 'AB', '0,1', ascii(('A', 'A'))), + + ('(?i)(a+|b){0,1}', 'AB', '0,1', ascii(('A', 'A'))), + ('(?i)(a+|b){0,1}?', 'AB', '0,1', ascii(('', None))), + ('(?i))(', '-', '', regex.error, self.TRAILING_CHARS), + ('(?i)[^ab]*', 'CDE', '0', ascii('CDE')), + ('(?i)abc', '', '', ascii(None)), + ('(?i)a*', '', '0', ascii('')), + ('(?i)([abc])*d', 'ABBBCD', '0,1', ascii(('ABBBCD', 'C'))), + ('(?i)([abc])*bcd', 'ABCD', '0,1', ascii(('ABCD', 'A'))), + ('(?i)a|b|c|d|e', 'E', '0', ascii('E')), + ('(?i)(a|b|c|d|e)f', 'EF', '0,1', ascii(('EF', 'E'))), + + ('(?i)abcd*efg', 'ABCDEFG', '0', ascii('ABCDEFG')), + ('(?i)ab*', 'XABYABBBZ', '0', ascii('AB')), + ('(?i)ab*', 'XAYABBBZ', '0', ascii('A')), + ('(?i)(ab|cd)e', 'ABCDE', '0,1', ascii(('CDE', 'CD'))), + ('(?i)[abhgefdc]ij', 'HIJ', '0', ascii('HIJ')), + ('(?i)^(ab|cd)e', 'ABCDE', '', ascii(None)), + ('(?i)(abc|)ef', 'ABCDEF', '0,1', ascii(('EF', ''))), + ('(?i)(a|b)c*d', 'ABCD', '0,1', ascii(('BCD', 'B'))), + ('(?i)(ab|ab*)bc', 'ABC', '0,1', ascii(('ABC', 'A'))), + ('(?i)a([bc]*)c*', 'ABC', '0,1', ascii(('ABC', 'BC'))), + + ('(?i)a([bc]*)(c*d)', 'ABCD', '0,1,2', ascii(('ABCD', 'BC', 'D'))), + ('(?i)a([bc]+)(c*d)', 'ABCD', '0,1,2', ascii(('ABCD', 'BC', 'D'))), + ('(?i)a([bc]*)(c+d)', 'ABCD', '0,1,2', ascii(('ABCD', 'B', 'CD'))), + ('(?i)a[bcd]*dcdcde', 'ADCDCDE', '0', ascii('ADCDCDE')), + ('(?i)a[bcd]+dcdcde', 'ADCDCDE', '', ascii(None)), + ('(?i)(ab|a)b*c', 'ABC', '0,1', ascii(('ABC', 'AB'))), + ('(?i)((a)(b)c)(d)', 'ABCD', '1,2,3,4', ascii(('ABC', 'A', 'B', + 'D'))), + ('(?i)[a-zA-Z_][a-zA-Z0-9_]*', 'ALPHA', '0', ascii('ALPHA')), + ('(?i)^a(bc+|b[eh])g|.h$', 'ABH', '0,1', ascii(('BH', None))), + ('(?i)(bc+d$|ef*g.|h?i(j|k))', 'EFFGZ', '0,1,2', ascii(('EFFGZ', + 'EFFGZ', None))), + + ('(?i)(bc+d$|ef*g.|h?i(j|k))', 'IJ', '0,1,2', ascii(('IJ', 'IJ', + 'J'))), + ('(?i)(bc+d$|ef*g.|h?i(j|k))', 'EFFG', '', ascii(None)), + ('(?i)(bc+d$|ef*g.|h?i(j|k))', 'BCDD', '', ascii(None)), + ('(?i)(bc+d$|ef*g.|h?i(j|k))', 'REFFGZ', '0,1,2', ascii(('EFFGZ', + 'EFFGZ', None))), + ('(?i)((((((((((a))))))))))', 'A', '10', ascii('A')), + ('(?i)((((((((((a))))))))))\\10', 'AA', '0', ascii('AA')), + #('(?i)((((((((((a))))))))))\\41', 'AA', '', ascii(None)), + #('(?i)((((((((((a))))))))))\\41', 'A!', '0', ascii('A!')), + ('(?i)(((((((((a)))))))))', 'A', '0', ascii('A')), + ('(?i)(?:(?:(?:(?:(?:(?:(?:(?:(?:(a))))))))))', 'A', '1', + ascii('A')), + ('(?i)(?:(?:(?:(?:(?:(?:(?:(?:(?:(a|b|c))))))))))', 'C', '1', + ascii('C')), + ('(?i)multiple words of text', 'UH-UH', '', ascii(None)), + + ('(?i)multiple words', 'MULTIPLE WORDS, YEAH', '0', + ascii('MULTIPLE WORDS')), + ('(?i)(.*)c(.*)', 'ABCDE', '0,1,2', ascii(('ABCDE', 'AB', 'DE'))), + ('(?i)\\((.*), (.*)\\)', '(A, B)', '2,1', ascii(('B', 'A'))), + ('(?i)[k]', 'AB', '', ascii(None)), + # ('(?i)abcd', 'ABCD', SUCCEED, 'found+"-"+\\found+"-"+\\\\found', ascii(ABCD-$&-\\ABCD)), + # ('(?i)a(bc)d', 'ABCD', SUCCEED, 'g1+"-"+\\g1+"-"+\\\\g1', ascii(BC-$1-\\BC)), + ('(?i)a[-]?c', 'AC', '0', ascii('AC')), + ('(?i)(abc)\\1', 'ABCABC', '1', ascii('ABC')), + ('(?i)([a-c]*)\\1', 'ABCABC', '1', ascii('ABC')), + ('a(?!b).', 'abad', '0', ascii('ad')), + ('a(?=d).', 'abad', '0', ascii('ad')), + ('a(?=c|d).', 'abad', '0', ascii('ad')), + + ('a(?:b|c|d)(.)', 'ace', '1', ascii('e')), + ('a(?:b|c|d)*(.)', 'ace', '1', ascii('e')), + ('a(?:b|c|d)+?(.)', 'ace', '1', ascii('e')), + ('a(?:b|(c|e){1,2}?|d)+?(.)', 'ace', '1,2', ascii(('c', 'e'))), + + # Lookbehind: split by : but not if it is escaped by -. + ('(?]*?b', 'a>b', '', ascii(None)), + # Bug 490573: minimizing repeat problem. + (r'^a*?$', 'foo', '', ascii(None)), + # Bug 470582: nested groups problem. + (r'^((a)c)?(ab)$', 'ab', '1,2,3', ascii((None, None, 'ab'))), + # Another minimizing repeat problem (capturing groups in assertions). + ('^([ab]*?)(?=(b)?)c', 'abc', '1,2', ascii(('ab', None))), + ('^([ab]*?)(?!(b))c', 'abc', '1,2', ascii(('ab', None))), + ('^([ab]*?)(?(.){0,2})d", "abcd").captures(1), + ['b', 'c']) + self.assertEqual(regex.search(r"(.)+", "a").captures(1), ['a']) + + def test_guards(self): + m = regex.search(r"(X.*?Y\s*){3}(X\s*)+AB:", + "XY\nX Y\nX Y\nXY\nXX AB:") + self.assertEqual(m.span(0, 1, 2), ((3, 21), (12, 15), (16, 18))) + + m = regex.search(r"(X.*?Y\s*){3,}(X\s*)+AB:", + "XY\nX Y\nX Y\nXY\nXX AB:") + self.assertEqual(m.span(0, 1, 2), ((0, 21), (12, 15), (16, 18))) + + m = regex.search(r'\d{4}(\s*\w)?\W*((?!\d)\w){2}', "9999XX") + self.assertEqual(m.span(0, 1, 2), ((0, 6), (-1, -1), (5, 6))) + + m = regex.search(r'A\s*?.*?(\n+.*?\s*?){0,2}\(X', 'A\n1\nS\n1 (X') + self.assertEqual(m.span(0, 1), ((0, 10), (5, 8))) + + m = regex.search(r'Derde\s*:', 'aaaaaa:\nDerde:') + self.assertEqual(m.span(), (8, 14)) + m = regex.search(r'Derde\s*:', 'aaaaa:\nDerde:') + self.assertEqual(m.span(), (7, 13)) + + def test_turkic(self): + # Turkish has dotted and dotless I/i. + pairs = "I=i;I=\u0131;i=\u0130" + + all_chars = set() + matching = set() + for pair in pairs.split(";"): + ch1, ch2 = pair.split("=") + all_chars.update((ch1, ch2)) + matching.add((ch1, ch1)) + matching.add((ch1, ch2)) + matching.add((ch2, ch1)) + matching.add((ch2, ch2)) + + for ch1 in all_chars: + for ch2 in all_chars: + m = regex.match(r"(?i)\A" + ch1 + r"\Z", ch2) + if m: + if (ch1, ch2) not in matching: + self.fail("{} matching {}".format(ascii(ch1), + ascii(ch2))) + else: + if (ch1, ch2) in matching: + self.fail("{} not matching {}".format(ascii(ch1), + ascii(ch2))) + + def test_named_lists(self): + options = ["one", "two", "three"] + self.assertEqual(regex.match(r"333\L444", "333one444", + bar=options).group(), "333one444") + self.assertEqual(regex.match(r"(?i)333\L444", "333TWO444", + bar=options).group(), "333TWO444") + self.assertEqual(regex.match(r"333\L444", "333four444", + bar=options), None) + + options = [b"one", b"two", b"three"] + self.assertEqual(regex.match(br"333\L444", b"333one444", + bar=options).group(), b"333one444") + self.assertEqual(regex.match(br"(?i)333\L444", b"333TWO444", + bar=options).group(), b"333TWO444") + self.assertEqual(regex.match(br"333\L444", b"333four444", + bar=options), None) + + self.assertEqual(repr(type(regex.compile(r"3\L4\L+5", + bar=["one", "two", "three"]))), self.PATTERN_CLASS) + + self.assertEqual(regex.findall(r"^\L", "solid QWERT", + options=set(['good', 'brilliant', '+s\\ol[i}d'])), []) + self.assertEqual(regex.findall(r"^\L", "+solid QWERT", + options=set(['good', 'brilliant', '+solid'])), ['+solid']) + + options = ["STRASSE"] + self.assertEqual(regex.match(r"(?fi)\L", + "stra\N{LATIN SMALL LETTER SHARP S}e", words=options).span(), (0, + 6)) + + options = ["STRASSE", "stress"] + self.assertEqual(regex.match(r"(?fi)\L", + "stra\N{LATIN SMALL LETTER SHARP S}e", words=options).span(), (0, + 6)) + + options = ["stra\N{LATIN SMALL LETTER SHARP S}e"] + self.assertEqual(regex.match(r"(?fi)\L", "STRASSE", + words=options).span(), (0, 7)) + + options = ["kit"] + self.assertEqual(regex.search(r"(?i)\L", "SKITS", + words=options).span(), (1, 4)) + self.assertEqual(regex.search(r"(?i)\L", + "SK\N{LATIN CAPITAL LETTER I WITH DOT ABOVE}TS", + words=options).span(), (1, 4)) + + self.assertEqual(regex.search(r"(?fi)\b(\w+) +\1\b", + " stra\N{LATIN SMALL LETTER SHARP S}e STRASSE ").span(), (1, 15)) + self.assertEqual(regex.search(r"(?fi)\b(\w+) +\1\b", + " STRASSE stra\N{LATIN SMALL LETTER SHARP S}e ").span(), (1, 15)) + + self.assertEqual(regex.search(r"^\L$", "", options=[]).span(), + (0, 0)) + + def test_fuzzy(self): + # Some tests borrowed from TRE library tests. + self.assertEqual(repr(type(regex.compile('(fou){s,e<=1}'))), + self.PATTERN_CLASS) + self.assertEqual(repr(type(regex.compile('(fuu){s}'))), + self.PATTERN_CLASS) + self.assertEqual(repr(type(regex.compile('(fuu){s,e}'))), + self.PATTERN_CLASS) + self.assertEqual(repr(type(regex.compile('(anaconda){1i+1d<1,s<=1}'))), + self.PATTERN_CLASS) + self.assertEqual(repr(type(regex.compile('(anaconda){1i+1d<1,s<=1,e<=10}'))), + self.PATTERN_CLASS) + self.assertEqual(repr(type(regex.compile('(anaconda){s<=1,e<=1,1i+1d<1}'))), + self.PATTERN_CLASS) + + text = 'molasses anaconda foo bar baz smith anderson ' + self.assertEqual(regex.search('(znacnda){s<=1,e<=3,1i+1d<1}', text), + None) + self.assertEqual(regex.search('(znacnda){s<=1,e<=3,1i+1d<2}', + text).span(0, 1), ((9, 17), (9, 17))) + self.assertEqual(regex.search('(ananda){1i+1d<2}', text), None) + self.assertEqual(regex.search(r"(?:\bznacnda){e<=2}", text)[0], + "anaconda") + self.assertEqual(regex.search(r"(?:\bnacnda){e<=2}", text)[0], + "anaconda") + + text = 'anaconda foo bar baz smith anderson' + self.assertEqual(regex.search('(fuu){i<=3,d<=3,e<=5}', text).span(0, + 1), ((0, 0), (0, 0))) + self.assertEqual(regex.search('(?b)(fuu){i<=3,d<=3,e<=5}', + text).span(0, 1), ((9, 10), (9, 10))) + self.assertEqual(regex.search('(fuu){i<=2,d<=2,e<=5}', text).span(0, + 1), ((7, 10), (7, 10))) + self.assertEqual(regex.search('(?e)(fuu){i<=2,d<=2,e<=5}', + text).span(0, 1), ((9, 10), (9, 10))) + self.assertEqual(regex.search('(fuu){i<=3,d<=3,e}', text).span(0, 1), + ((0, 0), (0, 0))) + self.assertEqual(regex.search('(?b)(fuu){i<=3,d<=3,e}', text).span(0, + 1), ((9, 10), (9, 10))) + + self.assertEqual(repr(type(regex.compile('(approximate){s<=3,1i+1d<3}'))), + self.PATTERN_CLASS) + + # No cost limit. + self.assertEqual(regex.search('(foobar){e}', + 'xirefoabralfobarxie').span(0, 1), ((0, 6), (0, 6))) + self.assertEqual(regex.search('(?e)(foobar){e}', + 'xirefoabralfobarxie').span(0, 1), ((0, 3), (0, 3))) + self.assertEqual(regex.search('(?b)(foobar){e}', + 'xirefoabralfobarxie').span(0, 1), ((11, 16), (11, 16))) + + # At most two errors. + self.assertEqual(regex.search('(foobar){e<=2}', + 'xirefoabrzlfd').span(0, 1), ((4, 9), (4, 9))) + self.assertEqual(regex.search('(foobar){e<=2}', 'xirefoabzlfd'), None) + + # At most two inserts or substitutions and max two errors total. + self.assertEqual(regex.search('(foobar){i<=2,s<=2,e<=2}', + 'oobargoobaploowap').span(0, 1), ((5, 11), (5, 11))) + + # Find best whole word match for "foobar". + self.assertEqual(regex.search('\\b(foobar){e}\\b', 'zfoobarz').span(0, + 1), ((0, 8), (0, 8))) + self.assertEqual(regex.search('\\b(foobar){e}\\b', + 'boing zfoobarz goobar woop').span(0, 1), ((0, 6), (0, 6))) + self.assertEqual(regex.search('(?b)\\b(foobar){e}\\b', + 'boing zfoobarz goobar woop').span(0, 1), ((15, 21), (15, 21))) + + # Match whole string, allow only 1 error. + self.assertEqual(regex.search('^(foobar){e<=1}$', 'foobar').span(0, 1), + ((0, 6), (0, 6))) + self.assertEqual(regex.search('^(foobar){e<=1}$', 'xfoobar').span(0, + 1), ((0, 7), (0, 7))) + self.assertEqual(regex.search('^(foobar){e<=1}$', 'foobarx').span(0, + 1), ((0, 7), (0, 7))) + self.assertEqual(regex.search('^(foobar){e<=1}$', 'fooxbar').span(0, + 1), ((0, 7), (0, 7))) + self.assertEqual(regex.search('^(foobar){e<=1}$', 'foxbar').span(0, 1), + ((0, 6), (0, 6))) + self.assertEqual(regex.search('^(foobar){e<=1}$', 'xoobar').span(0, 1), + ((0, 6), (0, 6))) + self.assertEqual(regex.search('^(foobar){e<=1}$', 'foobax').span(0, 1), + ((0, 6), (0, 6))) + self.assertEqual(regex.search('^(foobar){e<=1}$', 'oobar').span(0, 1), + ((0, 5), (0, 5))) + self.assertEqual(regex.search('^(foobar){e<=1}$', 'fobar').span(0, 1), + ((0, 5), (0, 5))) + self.assertEqual(regex.search('^(foobar){e<=1}$', 'fooba').span(0, 1), + ((0, 5), (0, 5))) + self.assertEqual(regex.search('^(foobar){e<=1}$', 'xfoobarx'), None) + self.assertEqual(regex.search('^(foobar){e<=1}$', 'foobarxx'), None) + self.assertEqual(regex.search('^(foobar){e<=1}$', 'xxfoobar'), None) + self.assertEqual(regex.search('^(foobar){e<=1}$', 'xfoxbar'), None) + self.assertEqual(regex.search('^(foobar){e<=1}$', 'foxbarx'), None) + + # At most one insert, two deletes, and three substitutions. + # Additionally, deletes cost two and substitutes one, and total + # cost must be less than 4. + self.assertEqual(regex.search('(foobar){i<=1,d<=2,s<=3,2d+1s<4}', + '3oifaowefbaoraofuiebofasebfaobfaorfeoaro').span(0, 1), ((6, 13), (6, + 13))) + self.assertEqual(regex.search('(?b)(foobar){i<=1,d<=2,s<=3,2d+1s<4}', + '3oifaowefbaoraofuiebofasebfaobfaorfeoaro').span(0, 1), ((34, 39), + (34, 39))) + + # Partially fuzzy matches. + self.assertEqual(regex.search('foo(bar){e<=1}zap', 'foobarzap').span(0, + 1), ((0, 9), (3, 6))) + self.assertEqual(regex.search('foo(bar){e<=1}zap', 'fobarzap'), None) + self.assertEqual(regex.search('foo(bar){e<=1}zap', 'foobrzap').span(0, + 1), ((0, 8), (3, 5))) + + text = ('www.cnn.com 64.236.16.20\nwww.slashdot.org 66.35.250.150\n' + 'For useful information, use www.slashdot.org\nthis is demo data!\n') + self.assertEqual(regex.search(r'(?s)^.*(dot.org){e}.*$', text).span(0, + 1), ((0, 120), (120, 120))) + self.assertEqual(regex.search(r'(?es)^.*(dot.org){e}.*$', text).span(0, + 1), ((0, 120), (93, 100))) + self.assertEqual(regex.search(r'^.*(dot.org){e}.*$', text).span(0, 1), + ((0, 119), (24, 101))) + + # Behaviour is unexpected, but arguably not wrong. It first finds the + # best match, then the best in what follows, etc. + self.assertEqual(regex.findall(r"\b\L{e<=1}\b", + " book cot dog desk ", words="cat dog".split()), ["cot", "dog"]) + self.assertEqual(regex.findall(r"\b\L{e<=1}\b", + " book dog cot desk ", words="cat dog".split()), [" dog", "cot"]) + self.assertEqual(regex.findall(r"(?e)\b\L{e<=1}\b", + " book dog cot desk ", words="cat dog".split()), ["dog", "cot"]) + self.assertEqual(regex.findall(r"(?r)\b\L{e<=1}\b", + " book cot dog desk ", words="cat dog".split()), ["dog ", "cot"]) + self.assertEqual(regex.findall(r"(?er)\b\L{e<=1}\b", + " book cot dog desk ", words="cat dog".split()), ["dog", "cot"]) + self.assertEqual(regex.findall(r"(?r)\b\L{e<=1}\b", + " book dog cot desk ", words="cat dog".split()), ["cot", "dog"]) + self.assertEqual(regex.findall(br"\b\L{e<=1}\b", + b" book cot dog desk ", words=b"cat dog".split()), [b"cot", b"dog"]) + self.assertEqual(regex.findall(br"\b\L{e<=1}\b", + b" book dog cot desk ", words=b"cat dog".split()), [b" dog", b"cot"]) + self.assertEqual(regex.findall(br"(?e)\b\L{e<=1}\b", + b" book dog cot desk ", words=b"cat dog".split()), [b"dog", b"cot"]) + self.assertEqual(regex.findall(br"(?r)\b\L{e<=1}\b", + b" book cot dog desk ", words=b"cat dog".split()), [b"dog ", b"cot"]) + self.assertEqual(regex.findall(br"(?er)\b\L{e<=1}\b", + b" book cot dog desk ", words=b"cat dog".split()), [b"dog", b"cot"]) + self.assertEqual(regex.findall(br"(?r)\b\L{e<=1}\b", + b" book dog cot desk ", words=b"cat dog".split()), [b"cot", b"dog"]) + + self.assertEqual(regex.search(r"(\w+) (\1{e<=1})", "foo fou").groups(), + ("foo", "fou")) + self.assertEqual(regex.search(r"(?r)(\2{e<=1}) (\w+)", + "foo fou").groups(), ("foo", "fou")) + self.assertEqual(regex.search(br"(\w+) (\1{e<=1})", + b"foo fou").groups(), (b"foo", b"fou")) + + self.assertEqual(regex.findall(r"(?:(?:QR)+){e}", "abcde"), ["abcde", + ""]) + self.assertEqual(regex.findall(r"(?:Q+){e}", "abc"), ["abc", ""]) + + # Hg issue 41: = for fuzzy matches + self.assertEqual(regex.match(r"(?:service detection){0[^()]+)|(?R))*\)", "(ab(cd)ef)")[ + : ], ("(ab(cd)ef)", "ef")) + self.assertEqual(regex.search(r"\(((?>[^()]+)|(?R))*\)", + "(ab(cd)ef)").captures(1), ["ab", "cd", "(cd)", "ef"]) + + self.assertEqual(regex.search(r"(?r)\(((?R)|(?>[^()]+))*\)", + "(ab(cd)ef)")[ : ], ("(ab(cd)ef)", "ab")) + self.assertEqual(regex.search(r"(?r)\(((?R)|(?>[^()]+))*\)", + "(ab(cd)ef)").captures(1), ["ef", "cd", "(cd)", "ab"]) + + self.assertEqual(regex.search(r"\(([^()]+|(?R))*\)", + "some text (a(b(c)d)e) more text")[ : ], ("(a(b(c)d)e)", "e")) + + self.assertEqual(regex.search(r"(?r)\(((?R)|[^()]+)*\)", + "some text (a(b(c)d)e) more text")[ : ], ("(a(b(c)d)e)", "a")) + + self.assertEqual(regex.search(r"(foo(\(((?:(?>[^()]+)|(?2))*)\)))", + "foo(bar(baz)+baz(bop))")[ : ], ("foo(bar(baz)+baz(bop))", + "foo(bar(baz)+baz(bop))", "(bar(baz)+baz(bop))", + "bar(baz)+baz(bop)")) + + self.assertEqual(regex.search(r"(?r)(foo(\(((?:(?2)|(?>[^()]+))*)\)))", + "foo(bar(baz)+baz(bop))")[ : ], ("foo(bar(baz)+baz(bop))", + "foo(bar(baz)+baz(bop))", "(bar(baz)+baz(bop))", + "bar(baz)+baz(bop)")) + + rgx = regex.compile(r"""^\s*(<\s*([a-zA-Z:]+)(?:\s*[a-zA-Z:]*\s*=\s*(?:'[^']*'|"[^"]*"))*\s*(/\s*)?>(?:[^<>]*|(?1))*(?(3)|<\s*/\s*\2\s*>))\s*$""") + self.assertEqual(bool(rgx.search('')), True) + self.assertEqual(bool(rgx.search('')), False) + self.assertEqual(bool(rgx.search('')), True) + self.assertEqual(bool(rgx.search('')), False) + self.assertEqual(bool(rgx.search('')), False) + + self.assertEqual(bool(rgx.search('')), False) + self.assertEqual(bool(rgx.search('')), True) + self.assertEqual(bool(rgx.search('< fooo / >')), True) + # The next regex should and does match. Perl 5.14 agrees. + #self.assertEqual(bool(rgx.search('foo')), False) + self.assertEqual(bool(rgx.search('foo')), False) + + self.assertEqual(bool(rgx.search('foo')), True) + self.assertEqual(bool(rgx.search('foo')), True) + self.assertEqual(bool(rgx.search('')), True) + + def test_copy(self): + # PatternObjects are immutable, therefore there's no need to clone them. + r = regex.compile("a") + self.assertTrue(copy.copy(r) is r) + self.assertTrue(copy.deepcopy(r) is r) + + # MatchObjects are normally mutable because the target string can be + # detached. However, after the target string has been detached, a + # MatchObject becomes immutable, so there's no need to clone it. + m = r.match("a") + self.assertTrue(copy.copy(m) is not m) + self.assertTrue(copy.deepcopy(m) is not m) + + self.assertTrue(m.string is not None) + m2 = copy.copy(m) + m2.detach_string() + self.assertTrue(m.string is not None) + self.assertTrue(m2.string is None) + + # The following behaviour matches that of the re module. + it = regex.finditer(".", "ab") + it2 = copy.copy(it) + self.assertEqual(next(it).group(), "a") + self.assertEqual(next(it2).group(), "b") + + # The following behaviour matches that of the re module. + it = regex.finditer(".", "ab") + it2 = copy.deepcopy(it) + self.assertEqual(next(it).group(), "a") + self.assertEqual(next(it2).group(), "b") + + # The following behaviour is designed to match that of copying 'finditer'. + it = regex.splititer(" ", "a b") + it2 = copy.copy(it) + self.assertEqual(next(it), "a") + self.assertEqual(next(it2), "b") + + # The following behaviour is designed to match that of copying 'finditer'. + it = regex.splititer(" ", "a b") + it2 = copy.deepcopy(it) + self.assertEqual(next(it), "a") + self.assertEqual(next(it2), "b") + + def test_format(self): + self.assertEqual(regex.subf(r"(\w+) (\w+)", "{0} => {2} {1}", + "foo bar"), "foo bar => bar foo") + self.assertEqual(regex.subf(r"(?\w+) (?\w+)", + "{word2} {word1}", "foo bar"), "bar foo") + + self.assertEqual(regex.subfn(r"(\w+) (\w+)", "{0} => {2} {1}", + "foo bar"), ("foo bar => bar foo", 1)) + self.assertEqual(regex.subfn(r"(?\w+) (?\w+)", + "{word2} {word1}", "foo bar"), ("bar foo", 1)) + + self.assertEqual(regex.match(r"(\w+) (\w+)", + "foo bar").expandf("{0} => {2} {1}"), "foo bar => bar foo") + + def test_fullmatch(self): + self.assertEqual(bool(regex.fullmatch(r"abc", "abc")), True) + self.assertEqual(bool(regex.fullmatch(r"abc", "abcx")), False) + self.assertEqual(bool(regex.fullmatch(r"abc", "abcx", endpos=3)), True) + + self.assertEqual(bool(regex.fullmatch(r"abc", "xabc", pos=1)), True) + self.assertEqual(bool(regex.fullmatch(r"abc", "xabcy", pos=1)), False) + self.assertEqual(bool(regex.fullmatch(r"abc", "xabcy", pos=1, + endpos=4)), True) + + self.assertEqual(bool(regex.fullmatch(r"(?r)abc", "abc")), True) + self.assertEqual(bool(regex.fullmatch(r"(?r)abc", "abcx")), False) + self.assertEqual(bool(regex.fullmatch(r"(?r)abc", "abcx", endpos=3)), + True) + + self.assertEqual(bool(regex.fullmatch(r"(?r)abc", "xabc", pos=1)), + True) + self.assertEqual(bool(regex.fullmatch(r"(?r)abc", "xabcy", pos=1)), + False) + self.assertEqual(bool(regex.fullmatch(r"(?r)abc", "xabcy", pos=1, + endpos=4)), True) + + def test_issue_18468(self): + self.assertTypedEqual(regex.sub('y', 'a', 'xyz'), 'xaz') + self.assertTypedEqual(regex.sub('y', StrSubclass('a'), + StrSubclass('xyz')), 'xaz') + self.assertTypedEqual(regex.sub(b'y', b'a', b'xyz'), b'xaz') + self.assertTypedEqual(regex.sub(b'y', BytesSubclass(b'a'), + BytesSubclass(b'xyz')), b'xaz') + self.assertTypedEqual(regex.sub(b'y', bytearray(b'a'), + bytearray(b'xyz')), b'xaz') + self.assertTypedEqual(regex.sub(b'y', memoryview(b'a'), + memoryview(b'xyz')), b'xaz') + + for string in ":a:b::c", StrSubclass(":a:b::c"): + self.assertTypedEqual(regex.split(":", string), ['', 'a', 'b', '', + 'c']) + if sys.version_info >= (3, 7, 0): + self.assertTypedEqual(regex.split(":*", string), ['', '', 'a', + '', 'b', '', 'c', '']) + self.assertTypedEqual(regex.split("(:*)", string), ['', ':', + '', '', 'a', ':', '', '', 'b', '::', '', '', 'c', '', '']) + else: + self.assertTypedEqual(regex.split(":*", string), ['', 'a', 'b', + 'c']) + self.assertTypedEqual(regex.split("(:*)", string), ['', ':', + 'a', ':', 'b', '::', 'c']) + + for string in (b":a:b::c", BytesSubclass(b":a:b::c"), + bytearray(b":a:b::c"), memoryview(b":a:b::c")): + self.assertTypedEqual(regex.split(b":", string), [b'', b'a', b'b', + b'', b'c']) + if sys.version_info >= (3, 7, 0): + self.assertTypedEqual(regex.split(b":*", string), [b'', b'', + b'a', b'', b'b', b'', b'c', b'']) + self.assertTypedEqual(regex.split(b"(:*)", string), [b'', b':', + b'', b'', b'a', b':', b'', b'', b'b', b'::', b'', b'', b'c', + b'', b'']) + else: + self.assertTypedEqual(regex.split(b":*", string), [b'', b'a', + b'b', b'c']) + self.assertTypedEqual(regex.split(b"(:*)", string), [b'', b':', + b'a', b':', b'b', b'::', b'c']) + + for string in "a:b::c:::d", StrSubclass("a:b::c:::d"): + self.assertTypedEqual(regex.findall(":+", string), [":", "::", + ":::"]) + self.assertTypedEqual(regex.findall("(:+)", string), [":", "::", + ":::"]) + self.assertTypedEqual(regex.findall("(:)(:*)", string), [(":", ""), + (":", ":"), (":", "::")]) + + for string in (b"a:b::c:::d", BytesSubclass(b"a:b::c:::d"), + bytearray(b"a:b::c:::d"), memoryview(b"a:b::c:::d")): + self.assertTypedEqual(regex.findall(b":+", string), [b":", b"::", + b":::"]) + self.assertTypedEqual(regex.findall(b"(:+)", string), [b":", b"::", + b":::"]) + self.assertTypedEqual(regex.findall(b"(:)(:*)", string), [(b":", + b""), (b":", b":"), (b":", b"::")]) + + for string in 'a', StrSubclass('a'): + self.assertEqual(regex.match('a', string).groups(), ()) + self.assertEqual(regex.match('(a)', string).groups(), ('a',)) + self.assertEqual(regex.match('(a)', string).group(0), 'a') + self.assertEqual(regex.match('(a)', string).group(1), 'a') + self.assertEqual(regex.match('(a)', string).group(1, 1), ('a', + 'a')) + + for string in (b'a', BytesSubclass(b'a'), bytearray(b'a'), + memoryview(b'a')): + self.assertEqual(regex.match(b'a', string).groups(), ()) + self.assertEqual(regex.match(b'(a)', string).groups(), (b'a',)) + self.assertEqual(regex.match(b'(a)', string).group(0), b'a') + self.assertEqual(regex.match(b'(a)', string).group(1), b'a') + self.assertEqual(regex.match(b'(a)', string).group(1, 1), (b'a', + b'a')) + + def test_partial(self): + self.assertEqual(regex.match('ab', 'a', partial=True).partial, True) + self.assertEqual(regex.match('ab', 'a', partial=True).span(), (0, 1)) + self.assertEqual(regex.match(r'cats', 'cat', partial=True).partial, + True) + self.assertEqual(regex.match(r'cats', 'cat', partial=True).span(), (0, + 3)) + self.assertEqual(regex.match(r'cats', 'catch', partial=True), None) + self.assertEqual(regex.match(r'abc\w{3}', 'abcdef', + partial=True).partial, False) + self.assertEqual(regex.match(r'abc\w{3}', 'abcdef', + partial=True).span(), (0, 6)) + self.assertEqual(regex.match(r'abc\w{3}', 'abcde', + partial=True).partial, True) + self.assertEqual(regex.match(r'abc\w{3}', 'abcde', + partial=True).span(), (0, 5)) + + self.assertEqual(regex.match(r'\d{4}$', '1234', partial=True).partial, + False) + + self.assertEqual(regex.match(r'\L', 'post', partial=True, + words=['post']).partial, False) + self.assertEqual(regex.match(r'\L', 'post', partial=True, + words=['post']).span(), (0, 4)) + self.assertEqual(regex.match(r'\L', 'pos', partial=True, + words=['post']).partial, True) + self.assertEqual(regex.match(r'\L', 'pos', partial=True, + words=['post']).span(), (0, 3)) + + self.assertEqual(regex.match(r'(?fi)\L', 'POST', partial=True, + words=['po\uFB06']).partial, False) + self.assertEqual(regex.match(r'(?fi)\L', 'POST', partial=True, + words=['po\uFB06']).span(), (0, 4)) + self.assertEqual(regex.match(r'(?fi)\L', 'POS', partial=True, + words=['po\uFB06']).partial, True) + self.assertEqual(regex.match(r'(?fi)\L', 'POS', partial=True, + words=['po\uFB06']).span(), (0, 3)) + self.assertEqual(regex.match(r'(?fi)\L', 'po\uFB06', + partial=True, words=['POS']), None) + + self.assertEqual(regex.match(r'[a-z]*4R$', 'a', partial=True).span(), + (0, 1)) + self.assertEqual(regex.match(r'[a-z]*4R$', 'ab', partial=True).span(), + (0, 2)) + self.assertEqual(regex.match(r'[a-z]*4R$', 'ab4', partial=True).span(), + (0, 3)) + self.assertEqual(regex.match(r'[a-z]*4R$', 'a4', partial=True).span(), + (0, 2)) + self.assertEqual(regex.match(r'[a-z]*4R$', 'a4R', partial=True).span(), + (0, 3)) + self.assertEqual(regex.match(r'[a-z]*4R$', '4a', partial=True), None) + self.assertEqual(regex.match(r'[a-z]*4R$', 'a44', partial=True), None) + + def test_hg_bugs(self): + # Hg issue 28: regex.compile("(?>b)") causes "TypeError: 'Character' + # object is not subscriptable" + self.assertEqual(bool(regex.compile("(?>b)", flags=regex.V1)), True) + + # Hg issue 29: regex.compile("^((?>\w+)|(?>\s+))*$") causes + # "TypeError: 'GreedyRepeat' object is not iterable" + self.assertEqual(bool(regex.compile(r"^((?>\w+)|(?>\s+))*$", + flags=regex.V1)), True) + + # Hg issue 31: atomic and normal groups in recursive patterns + self.assertEqual(regex.findall(r"\((?:(?>[^()]+)|(?R))*\)", + "a(bcd(e)f)g(h)"), ['(bcd(e)f)', '(h)']) + self.assertEqual(regex.findall(r"\((?:(?:[^()]+)|(?R))*\)", + "a(bcd(e)f)g(h)"), ['(bcd(e)f)', '(h)']) + self.assertEqual(regex.findall(r"\((?:(?>[^()]+)|(?R))*\)", + "a(b(cd)e)f)g)h"), ['(b(cd)e)']) + self.assertEqual(regex.findall(r"\((?:(?>[^()]+)|(?R))*\)", + "a(bc(d(e)f)gh"), ['(d(e)f)']) + self.assertEqual(regex.findall(r"(?r)\((?:(?>[^()]+)|(?R))*\)", + "a(bc(d(e)f)gh"), ['(d(e)f)']) + self.assertEqual([m.group() for m in + regex.finditer(r"\((?:[^()]*+|(?0))*\)", "a(b(c(de)fg)h")], + ['(c(de)fg)']) + + # Hg issue 32: regex.search("a(bc)d", "abcd", regex.I|regex.V1) returns + # None + self.assertEqual(regex.search("a(bc)d", "abcd", regex.I | + regex.V1).group(0), "abcd") + + # Hg issue 33: regex.search("([\da-f:]+)$", "E", regex.I|regex.V1) + # returns None + self.assertEqual(regex.search(r"([\da-f:]+)$", "E", regex.I | + regex.V1).group(0), "E") + self.assertEqual(regex.search(r"([\da-f:]+)$", "e", regex.I | + regex.V1).group(0), "e") + + # Hg issue 34: regex.search("^(?=ab(de))(abd)(e)", "abde").groups() + # returns (None, 'abd', 'e') instead of ('de', 'abd', 'e') + self.assertEqual(regex.search("^(?=ab(de))(abd)(e)", "abde").groups(), + ('de', 'abd', 'e')) + + # Hg issue 35: regex.compile("\ ", regex.X) causes "_regex_core.error: + # bad escape" + self.assertEqual(bool(regex.match(r"\ ", " ", flags=regex.X)), True) + + # Hg issue 36: regex.search("^(a|)\1{2}b", "b") returns None + self.assertEqual(regex.search(r"^(a|)\1{2}b", "b").group(0, 1), ('b', + '')) + + # Hg issue 37: regex.search("^(a){0,0}", "abc").group(0,1) returns + # ('a', 'a') instead of ('', None) + self.assertEqual(regex.search("^(a){0,0}", "abc").group(0, 1), ('', + None)) + + # Hg issue 38: regex.search("(?>.*/)b", "a/b") returns None + self.assertEqual(regex.search("(?>.*/)b", "a/b").group(0), "a/b") + + # Hg issue 39: regex.search("((?i)blah)\\s+\\1", "blah BLAH") doesn't + # return None + # Changed to positional flags in regex 2023.12.23. + self.assertEqual(regex.search(r"((?i)blah)\s+\1", "blah BLAH"), None) + + # Hg issue 40: regex.search("(\()?[^()]+(?(1)\)|)", "(abcd").group(0) + # returns "bcd" instead of "abcd" + self.assertEqual(regex.search(r"(\()?[^()]+(?(1)\)|)", + "(abcd").group(0), "abcd") + + # Hg issue 42: regex.search("(a*)*", "a", flags=regex.V1).span(1) + # returns (0, 1) instead of (1, 1) + self.assertEqual(regex.search("(a*)*", "a").span(1), (1, 1)) + self.assertEqual(regex.search("(a*)*", "aa").span(1), (2, 2)) + self.assertEqual(regex.search("(a*)*", "aaa").span(1), (3, 3)) + + # Hg issue 43: regex.compile("a(?#xxx)*") causes "_regex_core.error: + # nothing to repeat" + self.assertEqual(regex.search("a(?#xxx)*", "aaa").group(), "aaa") + + # Hg issue 44: regex.compile("(?=abc){3}abc") causes + # "_regex_core.error: nothing to repeat" + self.assertEqual(regex.search("(?=abc){3}abc", "abcabcabc").span(), (0, + 3)) + + # Hg issue 45: regex.compile("^(?:a(?:(?:))+)+") causes + # "_regex_core.error: nothing to repeat" + self.assertEqual(regex.search("^(?:a(?:(?:))+)+", "a").span(), (0, 1)) + self.assertEqual(regex.search("^(?:a(?:(?:))+)+", "aa").span(), (0, 2)) + + # Hg issue 46: regex.compile("a(?x: b c )d") causes + # "_regex_core.error: missing )" + self.assertEqual(regex.search("a(?x: b c )d", "abcd").group(0), "abcd") + + # Hg issue 47: regex.compile("a#comment\n*", flags=regex.X) causes + # "_regex_core.error: nothing to repeat" + self.assertEqual(regex.search("a#comment\n*", "aaa", + flags=regex.X).group(0), "aaa") + + # Hg issue 48: regex.search("(a(?(1)\\1)){4}", "a"*10, + # flags=regex.V1).group(0,1) returns ('aaaaa', 'a') instead of ('aaaaaaaaaa', 'aaaa') + self.assertEqual(regex.search(r"(?V1)(a(?(1)\1)){1}", + "aaaaaaaaaa").span(0, 1), ((0, 1), (0, 1))) + self.assertEqual(regex.search(r"(?V1)(a(?(1)\1)){2}", + "aaaaaaaaaa").span(0, 1), ((0, 3), (1, 3))) + self.assertEqual(regex.search(r"(?V1)(a(?(1)\1)){3}", + "aaaaaaaaaa").span(0, 1), ((0, 6), (3, 6))) + self.assertEqual(regex.search(r"(?V1)(a(?(1)\1)){4}", + "aaaaaaaaaa").span(0, 1), ((0, 10), (6, 10))) + + # Hg issue 49: regex.search("(a)(?<=b(?1))", "baz", regex.V1) returns + # None incorrectly + self.assertEqual(regex.search("(?V1)(a)(?<=b(?1))", "baz").group(0), + "a") + + # Hg issue 50: not all keywords are found by named list with + # overlapping keywords when full Unicode casefolding is required + self.assertEqual(regex.findall(r'(?fi)\L', + 'POST, Post, post, po\u017Ft, po\uFB06, and po\uFB05', + keywords=['post','pos']), ['POST', 'Post', 'post', 'po\u017Ft', + 'po\uFB06', 'po\uFB05']) + self.assertEqual(regex.findall(r'(?fi)pos|post', + 'POST, Post, post, po\u017Ft, po\uFB06, and po\uFB05'), ['POS', + 'Pos', 'pos', 'po\u017F', 'po\uFB06', 'po\uFB05']) + self.assertEqual(regex.findall(r'(?fi)post|pos', + 'POST, Post, post, po\u017Ft, po\uFB06, and po\uFB05'), ['POST', + 'Post', 'post', 'po\u017Ft', 'po\uFB06', 'po\uFB05']) + self.assertEqual(regex.findall(r'(?fi)post|another', + 'POST, Post, post, po\u017Ft, po\uFB06, and po\uFB05'), ['POST', + 'Post', 'post', 'po\u017Ft', 'po\uFB06', 'po\uFB05']) + + # Hg issue 51: regex.search("((a)(?1)|(?2))", "a", flags=regex.V1) + # returns None incorrectly + self.assertEqual(regex.search("(?V1)((a)(?1)|(?2))", "a").group(0, 1, + 2), ('a', 'a', None)) + + # Hg issue 52: regex.search("(\\1xx|){6}", "xx", + # flags=regex.V1).span(0,1) returns incorrect value + self.assertEqual(regex.search(r"(?V1)(\1xx|){6}", "xx").span(0, 1), + ((0, 2), (2, 2))) + + # Hg issue 53: regex.search("(a|)+", "a") causes MemoryError + self.assertEqual(regex.search("(a|)+", "a").group(0, 1), ("a", "")) + + # Hg issue 54: regex.search("(a|)*\\d", "a"*80) causes MemoryError + self.assertEqual(regex.search(r"(a|)*\d", "a" * 80), None) + + # Hg issue 55: regex.search("^(?:a?b?)*$", "ac") take a very long time. + self.assertEqual(regex.search("^(?:a?b?)*$", "ac"), None) + + # Hg issue 58: bad named character escape sequences like "\\N{1}" + # treats as "N" + self.assertRaisesRegex(regex.error, self.UNDEF_CHAR_NAME, lambda: + regex.compile("\\N{1}")) + + # Hg issue 59: regex.search("\\Z", "a\na\n") returns None incorrectly + self.assertEqual(regex.search("\\Z", "a\na\n").span(0), (4, 4)) + + # Hg issue 60: regex.search("(q1|.)*(q2|.)*(x(a|bc)*y){2,}", "xayxay") + # returns None incorrectly + self.assertEqual(regex.search("(q1|.)*(q2|.)*(x(a|bc)*y){2,}", + "xayxay").group(0), "xayxay") + + # Hg issue 61: regex.search("[^a]", "A", regex.I).group(0) returns '' + # incorrectly + self.assertEqual(regex.search("(?i)[^a]", "A"), None) + + # Hg issue 63: regex.search("[[:ascii:]]", "\N{KELVIN SIGN}", + # flags=regex.I|regex.V1) doesn't return None + self.assertEqual(regex.search("(?i)[[:ascii:]]", "\N{KELVIN SIGN}"), + None) + + # Hg issue 66: regex.search("((a|b(?1)c){3,5})", "baaaaca", + # flags=regex.V1).groups() returns ('baaaac', 'baaaac') instead of ('aaaa', 'a') + self.assertEqual(regex.search("((a|b(?1)c){3,5})", "baaaaca").group(0, + 1, 2), ('aaaa', 'aaaa', 'a')) + + # Hg issue 71: non-greedy quantifier in lookbehind + self.assertEqual(regex.findall(r"(?<=:\S+ )\w+", ":9 abc :10 def"), + ['abc', 'def']) + self.assertEqual(regex.findall(r"(?<=:\S* )\w+", ":9 abc :10 def"), + ['abc', 'def']) + self.assertEqual(regex.findall(r"(?<=:\S+? )\w+", ":9 abc :10 def"), + ['abc', 'def']) + self.assertEqual(regex.findall(r"(?<=:\S*? )\w+", ":9 abc :10 def"), + ['abc', 'def']) + + # Hg issue 73: conditional patterns + self.assertEqual(regex.search(r"(?:fe)?male", "female").group(), + "female") + self.assertEqual([m.group() for m in + regex.finditer(r"(fe)?male: h(?(1)(er)|(is)) (\w+)", + "female: her dog; male: his cat. asdsasda")], ['female: her dog', + 'male: his cat']) + + # Hg issue 78: "Captures" doesn't work for recursive calls + self.assertEqual(regex.search(r'(?\((?:[^()]++|(?&rec))*\))', + 'aaa(((1+0)+1)+1)bbb').captures('rec'), ['(1+0)', '((1+0)+1)', + '(((1+0)+1)+1)']) + + # Hg issue 80: Escape characters throws an exception + self.assertRaisesRegex(regex.error, self.BAD_ESCAPE, lambda: + regex.sub('x', '\\', 'x'), ) + + # Hg issue 82: error range does not work + fz = "(CAGCCTCCCATTTCAGAATATACATCC){1a(?b))', "ab").spans("x"), [(1, + 2), (0, 2)]) + + # Hg issue 91: match.expand is extremely slow + # Check that the replacement cache works. + self.assertEqual(regex.sub(r'(-)', lambda m: m.expand(r'x'), 'a-b-c'), + 'axbxc') + + # Hg issue 94: Python crashes when executing regex updates + # pattern.findall + rx = regex.compile(r'\bt(est){i<2}', flags=regex.V1) + self.assertEqual(rx.search("Some text"), None) + self.assertEqual(rx.findall("Some text"), []) + + # Hg issue 95: 'pos' for regex.error + self.assertRaisesRegex(regex.error, self.MULTIPLE_REPEAT, lambda: + regex.compile(r'.???')) + + # Hg issue 97: behaviour of regex.escape's special_only is wrong + # + # Hg issue 244: Make `special_only=True` the default in + # `regex.escape()` + self.assertEqual(regex.escape('foo!?', special_only=False), 'foo\\!\\?') + self.assertEqual(regex.escape('foo!?', special_only=True), 'foo!\\?') + self.assertEqual(regex.escape('foo!?'), 'foo!\\?') + + self.assertEqual(regex.escape(b'foo!?', special_only=False), b'foo\\!\\?') + self.assertEqual(regex.escape(b'foo!?', special_only=True), + b'foo!\\?') + self.assertEqual(regex.escape(b'foo!?'), b'foo!\\?') + + # Hg issue 100: strange results from regex.search + self.assertEqual(regex.search('^([^z]*(?:WWWi|W))?$', + 'WWWi').groups(), ('WWWi', )) + self.assertEqual(regex.search('^([^z]*(?:WWWi|w))?$', + 'WWWi').groups(), ('WWWi', )) + self.assertEqual(regex.search('^([^z]*?(?:WWWi|W))?$', + 'WWWi').groups(), ('WWWi', )) + + # Hg issue 101: findall() broken (seems like memory corruption) + pat = regex.compile(r'xxx', flags=regex.FULLCASE | regex.UNICODE) + self.assertEqual([x.group() for x in pat.finditer('yxxx')], ['xxx']) + self.assertEqual(pat.findall('yxxx'), ['xxx']) + + raw = 'yxxx' + self.assertEqual([x.group() for x in pat.finditer(raw)], ['xxx']) + self.assertEqual(pat.findall(raw), ['xxx']) + + pat = regex.compile(r'xxx', flags=regex.FULLCASE | regex.IGNORECASE | + regex.UNICODE) + self.assertEqual([x.group() for x in pat.finditer('yxxx')], ['xxx']) + self.assertEqual(pat.findall('yxxx'), ['xxx']) + + raw = 'yxxx' + self.assertEqual([x.group() for x in pat.finditer(raw)], ['xxx']) + self.assertEqual(pat.findall(raw), ['xxx']) + + # Hg issue 106: * operator not working correctly with sub() + if sys.version_info >= (3, 7, 0): + self.assertEqual(regex.sub('(?V0).*', 'x', 'test'), 'xx') + else: + self.assertEqual(regex.sub('(?V0).*', 'x', 'test'), 'x') + self.assertEqual(regex.sub('(?V1).*', 'x', 'test'), 'xx') + + if sys.version_info >= (3, 7, 0): + self.assertEqual(regex.sub('(?V0).*?', '|', 'test'), '|||||||||') + else: + self.assertEqual(regex.sub('(?V0).*?', '|', 'test'), '|t|e|s|t|') + self.assertEqual(regex.sub('(?V1).*?', '|', 'test'), '|||||||||') + + # Hg issue 112: re: OK, but regex: SystemError + self.assertEqual(regex.sub(r'^(@)\n(?!.*?@)(.*)', + r'\1\n==========\n\2', '@\n', flags=regex.DOTALL), '@\n==========\n') + + # Hg issue 109: Edit distance of fuzzy match + self.assertEqual(regex.match(r'(?:cats|cat){e<=1}', + 'caz').fuzzy_counts, (1, 0, 0)) + self.assertEqual(regex.match(r'(?e)(?:cats|cat){e<=1}', + 'caz').fuzzy_counts, (1, 0, 0)) + self.assertEqual(regex.match(r'(?b)(?:cats|cat){e<=1}', + 'caz').fuzzy_counts, (1, 0, 0)) + + self.assertEqual(regex.match(r'(?:cat){e<=1}', 'caz').fuzzy_counts, + (1, 0, 0)) + self.assertEqual(regex.match(r'(?e)(?:cat){e<=1}', + 'caz').fuzzy_counts, (1, 0, 0)) + self.assertEqual(regex.match(r'(?b)(?:cat){e<=1}', + 'caz').fuzzy_counts, (1, 0, 0)) + + self.assertEqual(regex.match(r'(?:cats){e<=2}', 'c ats').fuzzy_counts, + (1, 1, 0)) + self.assertEqual(regex.match(r'(?e)(?:cats){e<=2}', + 'c ats').fuzzy_counts, (0, 1, 0)) + self.assertEqual(regex.match(r'(?b)(?:cats){e<=2}', + 'c ats').fuzzy_counts, (0, 1, 0)) + + self.assertEqual(regex.match(r'(?:cats){e<=2}', + 'c a ts').fuzzy_counts, (0, 2, 0)) + self.assertEqual(regex.match(r'(?e)(?:cats){e<=2}', + 'c a ts').fuzzy_counts, (0, 2, 0)) + self.assertEqual(regex.match(r'(?b)(?:cats){e<=2}', + 'c a ts').fuzzy_counts, (0, 2, 0)) + + self.assertEqual(regex.match(r'(?:cats){e<=1}', 'c ats').fuzzy_counts, + (0, 1, 0)) + self.assertEqual(regex.match(r'(?e)(?:cats){e<=1}', + 'c ats').fuzzy_counts, (0, 1, 0)) + self.assertEqual(regex.match(r'(?b)(?:cats){e<=1}', + 'c ats').fuzzy_counts, (0, 1, 0)) + + # Hg issue 115: Infinite loop when processing backreferences + self.assertEqual(regex.findall(r'\bof ([a-z]+) of \1\b', + 'To make use of one of these modules'), []) + + # Hg issue 125: Reference to entire match (\g<0>) in + # Pattern.sub() doesn't work as of 2014.09.22 release. + self.assertEqual(regex.sub(r'x', r'\g<0>', 'x'), 'x') + + # Unreported issue: no such builtin as 'ascii' in Python 2. + self.assertEqual(bool(regex.match(r'a', 'a', regex.DEBUG)), True) + + # Hg issue 131: nested sets behaviour + self.assertEqual(regex.findall(r'(?V1)[[b-e]--cd]', 'abcdef'), ['b', + 'e']) + self.assertEqual(regex.findall(r'(?V1)[b-e--cd]', 'abcdef'), ['b', + 'e']) + self.assertEqual(regex.findall(r'(?V1)[[bcde]--cd]', 'abcdef'), ['b', + 'e']) + self.assertEqual(regex.findall(r'(?V1)[bcde--cd]', 'abcdef'), ['b', + 'e']) + + # Hg issue 132: index out of range on null property \p{} + self.assertRaisesRegex(regex.error, '^unknown property at position 4$', + lambda: regex.compile(r'\p{}')) + + # Issue 23692. + self.assertEqual(regex.match('(?:()|(?(1)()|z)){2}(?(2)a|z)', + 'a').group(0, 1, 2), ('a', '', '')) + self.assertEqual(regex.match('(?:()|(?(1)()|z)){0,2}(?(2)a|z)', + 'a').group(0, 1, 2), ('a', '', '')) + + # Hg issue 137: Posix character class :punct: does not seem to be + # supported. + + # Posix compatibility as recommended here: + # http://www.unicode.org/reports/tr18/#Compatibility_Properties + + # Posix in Unicode. + chars = ''.join(chr(c) for c in range(0x10000)) + + self.assertEqual(ascii(''.join(regex.findall(r'''[[:alnum:]]+''', + chars))), ascii(''.join(regex.findall(r'''[\p{Alpha}\p{PosixDigit}]+''', + chars)))) + self.assertEqual(ascii(''.join(regex.findall(r'''[[:alpha:]]+''', + chars))), ascii(''.join(regex.findall(r'''\p{Alpha}+''', + chars)))) + self.assertEqual(ascii(''.join(regex.findall(r'''[[:ascii:]]+''', + chars))), ascii(''.join(regex.findall(r'''[\p{InBasicLatin}]+''', + chars)))) + self.assertEqual(ascii(''.join(regex.findall(r'''[[:blank:]]+''', + chars))), ascii(''.join(regex.findall(r'''[\p{gc=Space_Separator}\t]+''', + chars)))) + self.assertEqual(ascii(''.join(regex.findall(r'''[[:cntrl:]]+''', + chars))), ascii(''.join(regex.findall(r'''\p{gc=Control}+''', chars)))) + self.assertEqual(ascii(''.join(regex.findall(r'''[[:digit:]]+''', + chars))), ascii(''.join(regex.findall(r'''[0-9]+''', chars)))) + self.assertEqual(ascii(''.join(regex.findall(r'''[[:graph:]]+''', + chars))), ascii(''.join(regex.findall(r'''[^\p{Space}\p{gc=Control}\p{gc=Surrogate}\p{gc=Unassigned}]+''', + chars)))) + self.assertEqual(ascii(''.join(regex.findall(r'''[[:lower:]]+''', + chars))), ascii(''.join(regex.findall(r'''\p{Lower}+''', + chars)))) + self.assertEqual(ascii(''.join(regex.findall(r'''[[:print:]]+''', + chars))), ascii(''.join(regex.findall(r'''(?V1)[\p{Graph}\p{Blank}--\p{Cntrl}]+''', chars)))) + self.assertEqual(ascii(''.join(regex.findall(r'''[[:punct:]]+''', + chars))), + ascii(''.join(regex.findall(r'''(?V1)[\p{gc=Punctuation}\p{gc=Symbol}--\p{Alpha}]+''', + chars)))) + self.assertEqual(ascii(''.join(regex.findall(r'''[[:space:]]+''', + chars))), ascii(''.join(regex.findall(r'''\p{Whitespace}+''', + chars)))) + self.assertEqual(ascii(''.join(regex.findall(r'''[[:upper:]]+''', + chars))), ascii(''.join(regex.findall(r'''\p{Upper}+''', + chars)))) + self.assertEqual(ascii(''.join(regex.findall(r'''[[:word:]]+''', + chars))), ascii(''.join(regex.findall(r'''[\p{Alpha}\p{gc=Mark}\p{Digit}\p{gc=Connector_Punctuation}\p{Join_Control}]+''', + chars)))) + self.assertEqual(ascii(''.join(regex.findall(r'''[[:xdigit:]]+''', + chars))), ascii(''.join(regex.findall(r'''[0-9A-Fa-f]+''', + chars)))) + + # Posix in ASCII. + chars = bytes(range(0x100)) + + self.assertEqual(ascii(b''.join(regex.findall(br'''(?a)[[:alnum:]]+''', + chars))), ascii(b''.join(regex.findall(br'''(?a)[\p{Alpha}\p{PosixDigit}]+''', + chars)))) + self.assertEqual(ascii(b''.join(regex.findall(br'''(?a)[[:alpha:]]+''', + chars))), ascii(b''.join(regex.findall(br'''(?a)\p{Alpha}+''', chars)))) + self.assertEqual(ascii(b''.join(regex.findall(br'''(?a)[[:ascii:]]+''', + chars))), ascii(b''.join(regex.findall(br'''(?a)[\x00-\x7F]+''', chars)))) + self.assertEqual(ascii(b''.join(regex.findall(br'''(?a)[[:blank:]]+''', + chars))), ascii(b''.join(regex.findall(br'''(?a)[\p{gc=Space_Separator}\t]+''', + chars)))) + self.assertEqual(ascii(b''.join(regex.findall(br'''(?a)[[:cntrl:]]+''', + chars))), ascii(b''.join(regex.findall(br'''(?a)\p{gc=Control}+''', + chars)))) + self.assertEqual(ascii(b''.join(regex.findall(br'''(?a)[[:digit:]]+''', + chars))), ascii(b''.join(regex.findall(br'''(?a)[0-9]+''', chars)))) + self.assertEqual(ascii(b''.join(regex.findall(br'''(?a)[[:graph:]]+''', + chars))), ascii(b''.join(regex.findall(br'''(?a)[^\p{Space}\p{gc=Control}\p{gc=Surrogate}\p{gc=Unassigned}]+''', chars)))) + self.assertEqual(ascii(b''.join(regex.findall(br'''(?a)[[:lower:]]+''', + chars))), ascii(b''.join(regex.findall(br'''(?a)\p{Lower}+''', chars)))) + self.assertEqual(ascii(b''.join(regex.findall(br'''(?a)[[:print:]]+''', + chars))), ascii(b''.join(regex.findall(br'''(?aV1)[\p{Graph}\p{Blank}--\p{Cntrl}]+''', chars)))) + self.assertEqual(ascii(b''.join(regex.findall(br'''(?a)[[:punct:]]+''', + chars))), ascii(b''.join(regex.findall(br'''(?aV1)[\p{gc=Punctuation}\p{gc=Symbol}--\p{Alpha}]+''', + chars)))) + self.assertEqual(ascii(b''.join(regex.findall(br'''(?a)[[:space:]]+''', + chars))), ascii(b''.join(regex.findall(br'''(?a)\p{Whitespace}+''', chars)))) + self.assertEqual(ascii(b''.join(regex.findall(br'''(?a)[[:upper:]]+''', + chars))), ascii(b''.join(regex.findall(br'''(?a)\p{Upper}+''', chars)))) + self.assertEqual(ascii(b''.join(regex.findall(br'''(?a)[[:word:]]+''', + chars))), ascii(b''.join(regex.findall(br'''(?a)[\p{Alpha}\p{gc=Mark}\p{Digit}\p{gc=Connector_Punctuation}\p{Join_Control}]+''', chars)))) + self.assertEqual(ascii(b''.join(regex.findall(br'''(?a)[[:xdigit:]]+''', + chars))), ascii(b''.join(regex.findall(br'''(?a)[0-9A-Fa-f]+''', chars)))) + + # Hg issue 138: grapheme anchored search not working properly. + self.assertEqual(ascii(regex.search(r'\X$', 'ab\u2103').group()), + ascii('\u2103')) + + # Hg issue 139: Regular expression with multiple wildcards where first + # should match empty string does not always work. + self.assertEqual(regex.search("([^L]*)([^R]*R)", "LtR").groups(), ('', + 'LtR')) + + # Hg issue 140: Replace with REVERSE and groups has unexpected + # behavior. + self.assertEqual(regex.sub(r'(.)', r'x\1y', 'ab'), 'xayxby') + self.assertEqual(regex.sub(r'(?r)(.)', r'x\1y', 'ab'), 'xayxby') + self.assertEqual(regex.subf(r'(.)', 'x{1}y', 'ab'), 'xayxby') + self.assertEqual(regex.subf(r'(?r)(.)', 'x{1}y', 'ab'), 'xayxby') + + # Hg issue 141: Crash on a certain partial match. + self.assertEqual(regex.fullmatch('(a)*abc', 'ab', + partial=True).span(), (0, 2)) + self.assertEqual(regex.fullmatch('(a)*abc', 'ab', + partial=True).partial, True) + + # Hg issue 143: Partial matches have incorrect span if prefix is '.' + # wildcard. + self.assertEqual(regex.search('OXRG', 'OOGOX', partial=True).span(), + (3, 5)) + self.assertEqual(regex.search('.XRG', 'OOGOX', partial=True).span(), + (3, 5)) + self.assertEqual(regex.search('.{1,3}XRG', 'OOGOX', + partial=True).span(), (1, 5)) + + # Hg issue 144: Latest version problem with matching 'R|R'. + self.assertEqual(regex.match('R|R', 'R').span(), (0, 1)) + + # Hg issue 146: Forced-fail (?!) works improperly in conditional. + self.assertEqual(regex.match(r'(.)(?(1)(?!))', 'xy'), None) + + # Groups cleared after failure. + self.assertEqual(regex.findall(r'(y)?(\d)(?(1)\b\B)', 'ax1y2z3b'), + [('', '1'), ('', '2'), ('', '3')]) + self.assertEqual(regex.findall(r'(y)?+(\d)(?(1)\b\B)', 'ax1y2z3b'), + [('', '1'), ('', '2'), ('', '3')]) + + # Hg issue 147: Fuzzy match can return match points beyond buffer end. + self.assertEqual([m.span() for m in regex.finditer(r'(?i)(?:error){e}', + 'regex failure')], [(0, 5), (5, 10), (10, 13), (13, 13)]) + self.assertEqual([m.span() for m in + regex.finditer(r'(?fi)(?:error){e}', 'regex failure')], [(0, 5), (5, + 10), (10, 13), (13, 13)]) + + # Hg issue 150: Have an option for POSIX-compatible longest match of + # alternates. + self.assertEqual(regex.search(r'(?p)\d+(\w(\d*)?|[eE]([+-]\d+))', + '10b12')[0], '10b12') + self.assertEqual(regex.search(r'(?p)\d+(\w(\d*)?|[eE]([+-]\d+))', + '10E+12')[0], '10E+12') + + self.assertEqual(regex.search(r'(?p)(\w|ae|oe|ue|ss)', 'ae')[0], 'ae') + self.assertEqual(regex.search(r'(?p)one(self)?(selfsufficient)?', + 'oneselfsufficient')[0], 'oneselfsufficient') + + # Hg issue 151: Request: \K. + self.assertEqual(regex.search(r'(ab\Kcd)', 'abcd').group(0, 1), ('cd', + 'abcd')) + self.assertEqual(regex.findall(r'\w\w\K\w\w', 'abcdefgh'), ['cd', + 'gh']) + self.assertEqual(regex.findall(r'(\w\w\K\w\w)', 'abcdefgh'), ['abcd', + 'efgh']) + + self.assertEqual(regex.search(r'(?r)(ab\Kcd)', 'abcd').group(0, 1), + ('ab', 'abcd')) + self.assertEqual(regex.findall(r'(?r)\w\w\K\w\w', 'abcdefgh'), ['ef', + 'ab']) + self.assertEqual(regex.findall(r'(?r)(\w\w\K\w\w)', 'abcdefgh'), + ['efgh', 'abcd']) + + # Hg issue 152: Request: Request: (?(DEFINE)...). + self.assertEqual(regex.search(r'(?(DEFINE)(?\d+)(?\w+))(?&quant) (?&item)', + '5 elephants')[0], '5 elephants') + + self.assertEqual(regex.search(r'(?&routine)(?(DEFINE)(?.))', 'a').group('routine'), None) + self.assertEqual(regex.search(r'(?&routine)(?(DEFINE)(?.))', 'a').captures('routine'), ['a']) + + # Hg issue 153: Request: (*SKIP). + self.assertEqual(regex.search(r'12(*FAIL)|3', '123')[0], '3') + self.assertEqual(regex.search(r'(?r)12(*FAIL)|3', '123')[0], '3') + + self.assertEqual(regex.search(r'\d+(*PRUNE)\d', '123'), None) + self.assertEqual(regex.search(r'\d+(?=(*PRUNE))\d', '123')[0], '123') + self.assertEqual(regex.search(r'\d+(*PRUNE)bcd|[3d]', '123bcd')[0], + '123bcd') + self.assertEqual(regex.search(r'\d+(*PRUNE)bcd|[3d]', '123zzd')[0], + 'd') + self.assertEqual(regex.search(r'\d+?(*PRUNE)bcd|[3d]', '123bcd')[0], + '3bcd') + self.assertEqual(regex.search(r'\d+?(*PRUNE)bcd|[3d]', '123zzd')[0], + 'd') + self.assertEqual(regex.search(r'\d++(?<=3(*PRUNE))zzd|[4d]$', + '123zzd')[0], '123zzd') + self.assertEqual(regex.search(r'\d++(?<=3(*PRUNE))zzd|[4d]$', + '124zzd')[0], 'd') + self.assertEqual(regex.search(r'\d++(?<=(*PRUNE)3)zzd|[4d]$', + '124zzd')[0], 'd') + self.assertEqual(regex.search(r'\d++(?<=2(*PRUNE)3)zzd|[3d]$', + '124zzd')[0], 'd') + + self.assertEqual(regex.search(r'(?r)\d(*PRUNE)\d+', '123'), None) + self.assertEqual(regex.search(r'(?r)\d(?<=(*PRUNE))\d+', '123')[0], + '123') + self.assertEqual(regex.search(r'(?r)\d+(*PRUNE)bcd|[3d]', + '123bcd')[0], '123bcd') + self.assertEqual(regex.search(r'(?r)\d+(*PRUNE)bcd|[3d]', + '123zzd')[0], 'd') + self.assertEqual(regex.search(r'(?r)\d++(?<=3(*PRUNE))zzd|[4d]$', + '123zzd')[0], '123zzd') + self.assertEqual(regex.search(r'(?r)\d++(?<=3(*PRUNE))zzd|[4d]$', + '124zzd')[0], 'd') + self.assertEqual(regex.search(r'(?r)\d++(?<=(*PRUNE)3)zzd|[4d]$', + '124zzd')[0], 'd') + self.assertEqual(regex.search(r'(?r)\d++(?<=2(*PRUNE)3)zzd|[3d]$', + '124zzd')[0], 'd') + + self.assertEqual(regex.search(r'\d+(*SKIP)bcd|[3d]', '123bcd')[0], + '123bcd') + self.assertEqual(regex.search(r'\d+(*SKIP)bcd|[3d]', '123zzd')[0], + 'd') + self.assertEqual(regex.search(r'\d+?(*SKIP)bcd|[3d]', '123bcd')[0], + '3bcd') + self.assertEqual(regex.search(r'\d+?(*SKIP)bcd|[3d]', '123zzd')[0], + 'd') + self.assertEqual(regex.search(r'\d++(?<=3(*SKIP))zzd|[4d]$', + '123zzd')[0], '123zzd') + self.assertEqual(regex.search(r'\d++(?<=3(*SKIP))zzd|[4d]$', + '124zzd')[0], 'd') + self.assertEqual(regex.search(r'\d++(?<=(*SKIP)3)zzd|[4d]$', + '124zzd')[0], 'd') + self.assertEqual(regex.search(r'\d++(?<=2(*SKIP)3)zzd|[3d]$', + '124zzd')[0], 'd') + + self.assertEqual(regex.search(r'(?r)\d+(*SKIP)bcd|[3d]', '123bcd')[0], + '123bcd') + self.assertEqual(regex.search(r'(?r)\d+(*SKIP)bcd|[3d]', '123zzd')[0], + 'd') + self.assertEqual(regex.search(r'(?r)\d++(?<=3(*SKIP))zzd|[4d]$', + '123zzd')[0], '123zzd') + self.assertEqual(regex.search(r'(?r)\d++(?<=3(*SKIP))zzd|[4d]$', + '124zzd')[0], 'd') + self.assertEqual(regex.search(r'(?r)\d++(?<=(*SKIP)3)zzd|[4d]$', + '124zzd')[0], 'd') + self.assertEqual(regex.search(r'(?r)\d++(?<=2(*SKIP)3)zzd|[3d]$', + '124zzd')[0], 'd') + + # Hg issue 154: Segmentation fault 11 when working with an atomic group + text = """June 30, December 31, 2013 2012 +some words follow: +more words and numbers 1,234,567 9,876,542 +more words and numbers 1,234,567 9,876,542""" + self.assertEqual(len(regex.findall(r'(?2014|2013 ?2012)', text)), 1) + + # Hg issue 156: regression on atomic grouping + self.assertEqual(regex.match('1(?>2)', '12').span(), (0, 2)) + + # Hg issue 157: regression: segfault on complex lookaround + self.assertEqual(regex.match(r'(?V1w)(?=(?=[^A-Z]*+[A-Z])(?=[^a-z]*+[a-z]))(?=\D*+\d)(?=\p{Alphanumeric}*+\P{Alphanumeric})\A(?s:.){8,255}+\Z', + 'AAaa11!!')[0], 'AAaa11!!') + + # Hg issue 158: Group issue with (?(DEFINE)...) + TEST_REGEX = regex.compile(r'''(?smx) +(?(DEFINE) + (? + ^,[^,]+, + ) +) + +# Group 2 is defined on this line +^,([^,]+), + +(?:(?!(?&subcat)[\r\n]+(?&subcat)).)+ +''') + + TEST_DATA = ''' +,Cat 1, +,Brand 1, +some +thing +,Brand 2, +other +things +,Cat 2, +,Brand, +Some +thing +''' + + self.assertEqual([m.span(1, 2) for m in + TEST_REGEX.finditer(TEST_DATA)], [((-1, -1), (2, 7)), ((-1, -1), (54, + 59))]) + + # Hg issue 161: Unexpected fuzzy match results + self.assertEqual(regex.search('(abcdefgh){e}', + '******abcdefghijklmnopqrtuvwxyz', regex.BESTMATCH).span(), (6, 14)) + self.assertEqual(regex.search('(abcdefghi){e}', + '******abcdefghijklmnopqrtuvwxyz', regex.BESTMATCH).span(), (6, 15)) + + # Hg issue 163: allow lookarounds in conditionals. + self.assertEqual(regex.match(r'(?:(?=\d)\d+\b|\w+)', '123abc').span(), + (0, 6)) + self.assertEqual(regex.match(r'(?(?=\d)\d+\b|\w+)', '123abc'), None) + self.assertEqual(regex.search(r'(?(?<=love\s)you|(?<=hate\s)her)', + "I love you").span(), (7, 10)) + self.assertEqual(regex.findall(r'(?(?<=love\s)you|(?<=hate\s)her)', + "I love you but I don't hate her either"), ['you', 'her']) + + # Hg issue 180: bug of POSIX matching. + self.assertEqual(regex.search(r'(?p)a*(.*?)', 'aaabbb').group(0, 1), + ('aaabbb', 'bbb')) + self.assertEqual(regex.search(r'(?p)a*(.*)', 'aaabbb').group(0, 1), + ('aaabbb', 'bbb')) + self.assertEqual(regex.sub(r'(?p)a*(.*?)', r'\1', 'aaabbb'), 'bbb') + self.assertEqual(regex.sub(r'(?p)a*(.*)', r'\1', 'aaabbb'), 'bbb') + + # Hg issue 192: Named lists reverse matching doesn't work with + # IGNORECASE and V1 + self.assertEqual(regex.match(r'(?irV0)\L', '21', kw=['1']).span(), + (1, 2)) + self.assertEqual(regex.match(r'(?irV1)\L', '21', kw=['1']).span(), + (1, 2)) + + # Hg issue 193: Alternation and .REVERSE flag. + self.assertEqual(regex.search('a|b', '111a222').span(), (3, 4)) + self.assertEqual(regex.search('(?r)a|b', '111a222').span(), (3, 4)) + + # Hg issue 194: .FULLCASE and Backreference + self.assertEqual(regex.search(r'(?if)<(CLI)><\1>', + '').span(), (0, 10)) + self.assertEqual(regex.search(r'(?if)<(CLI)><\1>', + '').span(), (0, 10)) + self.assertEqual(regex.search(r'(?ifr)<\1><(CLI)>', + '').span(), (0, 10)) + + # Hg issue 195: Pickle (or otherwise serial) the compiled regex + r = regex.compile(r'\L', options=['foo', 'bar']) + p = pickle.dumps(r) + r = pickle.loads(p) + self.assertEqual(r.match('foo').span(), (0, 3)) + + # Hg issue 196: Fuzzy matching on repeated regex not working as + # expected + self.assertEqual(regex.match('(x{6}){e<=1}', 'xxxxxx', + flags=regex.BESTMATCH).span(), (0, 6)) + self.assertEqual(regex.match('(x{6}){e<=1}', 'xxxxx', + flags=regex.BESTMATCH).span(), (0, 5)) + self.assertEqual(regex.match('(x{6}){e<=1}', 'x', + flags=regex.BESTMATCH), None) + self.assertEqual(regex.match('(?r)(x{6}){e<=1}', 'xxxxxx', + flags=regex.BESTMATCH).span(), (0, 6)) + self.assertEqual(regex.match('(?r)(x{6}){e<=1}', 'xxxxx', + flags=regex.BESTMATCH).span(), (0, 5)) + self.assertEqual(regex.match('(?r)(x{6}){e<=1}', 'x', + flags=regex.BESTMATCH), None) + + # Hg issue 197: ValueError in regex.compile + self.assertRaises(regex.error, lambda: + regex.compile(b'00000\\0\\00\\^\50\\00\\U05000000')) + + # Hg issue 198: ValueError in regex.compile + self.assertRaises(regex.error, lambda: regex.compile(b"{e', '22', aa=['121', + '22'])), True) + self.assertEqual(bool(regex.search(r'(?ri)\L', '22', aa=['121', + '22'])), True) + self.assertEqual(bool(regex.search(r'(?fi)\L', '22', aa=['121', + '22'])), True) + self.assertEqual(bool(regex.search(r'(?fri)\L', '22', aa=['121', + '22'])), True) + + # Hg issue 208: Named list, (?ri) flags, Backreference + self.assertEqual(regex.search(r'(?r)\1dog..(?<=(\L))$', 'ccdogcc', + aa=['bcb', 'cc']). span(), (0, 7)) + self.assertEqual(regex.search(r'(?ir)\1dog..(?<=(\L))$', + 'ccdogcc', aa=['bcb', 'cc']). span(), (0, 7)) + + # Hg issue 210: Fuzzy matching and Backreference + self.assertEqual(regex.search(r'(2)(?:\1{5}){e<=1}', + '3222212').span(), (1, 7)) + self.assertEqual(regex.search(r'(\d)(?:\1{5}){e<=1}', + '3222212').span(), (1, 7)) + + # Hg issue 211: Segmentation fault with recursive matches and atomic + # groups + self.assertEqual(regex.match(r'''\A(?P(?>\((?&whole)\)|[+\-]))\Z''', + '((-))').span(), (0, 5)) + self.assertEqual(regex.match(r'''\A(?P(?>\((?&whole)\)|[+\-]))\Z''', + '((-)+)'), None) + + # Hg issue 212: Unexpected matching difference with .*? between re and + # regex + self.assertEqual(regex.match(r"x.*? (.).*\1(.*)\1", + 'x |y| z|').span(), (0, 9)) + self.assertEqual(regex.match(r"\.sr (.*?) (.)(.*)\2(.*)\2(.*)", + r'.sr h |||').span(), (0, 35)) + + # Hg issue 213: Segmentation Fault + a = '"\\xF9\\x80\\xAEqdz\\x95L\\xA7\\x89[\\xFE \\x91)\\xF9]\\xDB\'\\x99\\x09=\\x00\\xFD\\x98\\x22\\xDD\\xF1\\xB6\\xC3 Z\\xB6gv\\xA5x\\x93P\\xE1r\\x14\\x8Cv\\x0C\\xC0w\\x15r\\xFFc%" ' + py_regex_pattern = r'''(?P((?>(?"(?>\\.|[^\\"]+)+"|""|(?>'(?>\\.|[^\\']+)+')|''|(?>`(?>\\.|[^\\`]+)+`)|``)))) (?P((?>(?"(?>\\.|[^\\"]+)+"|""|(?>'(?>\\.|[^\\']+)+')|''|(?>`(?>\\.|[^\\`]+)+`)|``))))''' + self.assertEqual(bool(regex.search(py_regex_pattern, a)), False) + + # Hg Issue 216: Invalid match when using negative lookbehind and pipe + self.assertEqual(bool(regex.match('foo(?<=foo)', 'foo')), True) + self.assertEqual(bool(regex.match('foo(?.*\!\w*\:.*)|(?P.*))', + '!')), False) + + # Hg issue 220: Misbehavior of group capture with OR operand + self.assertEqual(regex.match(r'\w*(ea)\w*|\w*e(?!a)\w*', + 'easier').groups(), ('ea', )) + + # Hg issue 225: BESTMATCH in fuzzy match not working + self.assertEqual(regex.search('(^1234$){i,d}', '12234', + regex.BESTMATCH).span(), (0, 5)) + self.assertEqual(regex.search('(^1234$){i,d}', '12234', + regex.BESTMATCH).fuzzy_counts, (0, 1, 0)) + + self.assertEqual(regex.search('(^1234$){s,i,d}', '12234', + regex.BESTMATCH).span(), (0, 5)) + self.assertEqual(regex.search('(^1234$){s,i,d}', '12234', + regex.BESTMATCH).fuzzy_counts, (0, 1, 0)) + + # Hg issue 226: Error matching at start of string + self.assertEqual(regex.search('(^123$){s,i,d}', 'xxxxxxxx123', + regex.BESTMATCH).span(), (0, 11)) + self.assertEqual(regex.search('(^123$){s,i,d}', 'xxxxxxxx123', + regex.BESTMATCH).fuzzy_counts, (0, 8, 0)) + + # Hg issue 227: Incorrect behavior for ? operator with UNICODE + + # IGNORECASE + self.assertEqual(regex.search(r'a?yz', 'xxxxyz', flags=regex.FULLCASE | + regex.IGNORECASE).span(), (4, 6)) + + # Hg issue 230: Is it a bug of (?(DEFINE)...) + self.assertEqual(regex.findall(r'(?:(?![a-d]).)+', 'abcdefgh'), + ['efgh']) + self.assertEqual(regex.findall(r'''(?(DEFINE)(?P(?:(?![a-d]).)))(?&mydef)+''', + 'abcdefgh'), ['efgh']) + + # Hg issue 238: Not fully re backward compatible + self.assertEqual(regex.findall(r'((\w{1,3})(\.{2,10})){1,3}', + '"Erm....yes. T..T...Thank you for that."'), [('Erm....', 'Erm', + '....'), ('T...', 'T', '...')]) + self.assertEqual(regex.findall(r'((\w{1,3})(\.{2,10})){3}', + '"Erm....yes. T..T...Thank you for that."'), []) + self.assertEqual(regex.findall(r'((\w{1,3})(\.{2,10})){2}', + '"Erm....yes. T..T...Thank you for that."'), [('T...', 'T', '...')]) + self.assertEqual(regex.findall(r'((\w{1,3})(\.{2,10})){1}', + '"Erm....yes. T..T...Thank you for that."'), [('Erm....', 'Erm', + '....'), ('T..', 'T', '..'), ('T...', 'T', '...')]) + + # Hg issue 247: Unexpected result with fuzzy matching and lookahead + # expression + self.assertEqual(regex.search(r'(?:ESTONIA(?!\w)){e<=1}', + 'ESTONIAN WORKERS').group(), 'ESTONIAN') + self.assertEqual(regex.search(r'(?:ESTONIA(?=\W)){e<=1}', + 'ESTONIAN WORKERS').group(), 'ESTONIAN') + + self.assertEqual(regex.search(r'(?:(?.))(?&func)', + 'abc').groups(), (None, )) + self.assertEqual(regex.search(r'(?(DEFINE)(?.))(?&func)', + 'abc').groupdict(), {'func': None}) + self.assertEqual(regex.search(r'(?(DEFINE)(?.))(?&func)', + 'abc').capturesdict(), {'func': ['a']}) + + self.assertEqual(regex.search(r'(?(DEFINE)(?.))(?=(?&func))', + 'abc').groups(), (None, )) + self.assertEqual(regex.search(r'(?(DEFINE)(?.))(?=(?&func))', + 'abc').groupdict(), {'func': None}) + self.assertEqual(regex.search(r'(?(DEFINE)(?.))(?=(?&func))', + 'abc').capturesdict(), {'func': ['a']}) + + self.assertEqual(regex.search(r'(?(DEFINE)(?.)).(?<=(?&func))', + 'abc').groups(), (None, )) + self.assertEqual(regex.search(r'(?(DEFINE)(?.)).(?<=(?&func))', + 'abc').groupdict(), {'func': None}) + self.assertEqual(regex.search(r'(?(DEFINE)(?.)).(?<=(?&func))', + 'abc').capturesdict(), {'func': ['a']}) + + # Hg issue 271: Comment logic different between Re and Regex + self.assertEqual(bool(regex.match(r'ab(?#comment\))cd', 'abcd')), True) + + # Hg issue 276: Partial Matches yield incorrect matches and bounds + self.assertEqual(regex.search(r'[a-z]+ [a-z]*?:', 'foo bar', + partial=True).span(), (0, 7)) + self.assertEqual(regex.search(r'(?r):[a-z]*? [a-z]+', 'foo bar', + partial=True).span(), (0, 7)) + + # Hg issue 291: Include Script Extensions as a supported Unicode property + self.assertEqual(bool(regex.match(r'(?u)\p{Script:Beng}', + '\u09EF')), True) + self.assertEqual(bool(regex.match(r'(?u)\p{Script:Bengali}', + '\u09EF')), True) + self.assertEqual(bool(regex.match(r'(?u)\p{Script_Extensions:Bengali}', + '\u09EF')), True) + self.assertEqual(bool(regex.match(r'(?u)\p{Script_Extensions:Beng}', + '\u09EF')), True) + self.assertEqual(bool(regex.match(r'(?u)\p{Script_Extensions:Cakm}', + '\u09EF')), True) + self.assertEqual(bool(regex.match(r'(?u)\p{Script_Extensions:Sylo}', + '\u09EF')), True) + + # Hg issue #293: scx (Script Extensions) property currently matches + # incorrectly + self.assertEqual(bool(regex.match(r'(?u)\p{scx:Latin}', 'P')), True) + self.assertEqual(bool(regex.match(r'(?u)\p{scx:Ahom}', 'P')), False) + self.assertEqual(bool(regex.match(r'(?u)\p{scx:Common}', '4')), True) + self.assertEqual(bool(regex.match(r'(?u)\p{scx:Caucasian_Albanian}', '4')), + False) + self.assertEqual(bool(regex.match(r'(?u)\p{scx:Arabic}', '\u062A')), True) + self.assertEqual(bool(regex.match(r'(?u)\p{scx:Balinese}', '\u062A')), + False) + self.assertEqual(bool(regex.match(r'(?u)\p{scx:Devanagari}', '\u091C')), + True) + self.assertEqual(bool(regex.match(r'(?u)\p{scx:Batak}', '\u091C')), False) + + # Hg issue 296: Group references are not taken into account when group is reporting the last match + self.assertEqual(regex.fullmatch('(?P.)*(?&x)', 'abc').captures('x'), + ['a', 'b', 'c']) + self.assertEqual(regex.fullmatch('(?P.)*(?&x)', 'abc').group('x'), + 'b') + + self.assertEqual(regex.fullmatch('(?P.)(?P.)(?P.)', + 'abc').captures('x'), ['a', 'b', 'c']) + self.assertEqual(regex.fullmatch('(?P.)(?P.)(?P.)', + 'abc').group('x'), 'c') + + # Hg issue 299: Partial gives misleading results with "open ended" regexp + self.assertEqual(regex.match('(?:ab)*', 'ab', partial=True).partial, + False) + self.assertEqual(regex.match('(?:ab)*', 'abab', partial=True).partial, + False) + self.assertEqual(regex.match('(?:ab)*?', '', partial=True).partial, + False) + self.assertEqual(regex.match('(?:ab)*+', 'ab', partial=True).partial, + False) + self.assertEqual(regex.match('(?:ab)*+', 'abab', partial=True).partial, + False) + self.assertEqual(regex.match('(?:ab)+', 'ab', partial=True).partial, + False) + self.assertEqual(regex.match('(?:ab)+', 'abab', partial=True).partial, + False) + self.assertEqual(regex.match('(?:ab)+?', 'ab', partial=True).partial, + False) + self.assertEqual(regex.match('(?:ab)++', 'ab', partial=True).partial, + False) + self.assertEqual(regex.match('(?:ab)++', 'abab', partial=True).partial, + False) + + self.assertEqual(regex.match('(?r)(?:ab)*', 'ab', partial=True).partial, + False) + self.assertEqual(regex.match('(?r)(?:ab)*', 'abab', partial=True).partial, + False) + self.assertEqual(regex.match('(?r)(?:ab)*?', '', partial=True).partial, + False) + self.assertEqual(regex.match('(?r)(?:ab)*+', 'ab', partial=True).partial, + False) + self.assertEqual(regex.match('(?r)(?:ab)*+', 'abab', partial=True).partial, + False) + self.assertEqual(regex.match('(?r)(?:ab)+', 'ab', partial=True).partial, + False) + self.assertEqual(regex.match('(?r)(?:ab)+', 'abab', partial=True).partial, + False) + self.assertEqual(regex.match('(?r)(?:ab)+?', 'ab', partial=True).partial, + False) + self.assertEqual(regex.match('(?r)(?:ab)++', 'ab', partial=True).partial, + False) + self.assertEqual(regex.match('(?r)(?:ab)++', 'abab', partial=True).partial, + False) + + self.assertEqual(regex.match('a*', '', partial=True).partial, False) + self.assertEqual(regex.match('a*?', '', partial=True).partial, False) + self.assertEqual(regex.match('a*+', '', partial=True).partial, False) + self.assertEqual(regex.match('a+', '', partial=True).partial, True) + self.assertEqual(regex.match('a+?', '', partial=True).partial, True) + self.assertEqual(regex.match('a++', '', partial=True).partial, True) + self.assertEqual(regex.match('a+', 'a', partial=True).partial, False) + self.assertEqual(regex.match('a+?', 'a', partial=True).partial, False) + self.assertEqual(regex.match('a++', 'a', partial=True).partial, False) + + self.assertEqual(regex.match('(?r)a*', '', partial=True).partial, False) + self.assertEqual(regex.match('(?r)a*?', '', partial=True).partial, False) + self.assertEqual(regex.match('(?r)a*+', '', partial=True).partial, False) + self.assertEqual(regex.match('(?r)a+', '', partial=True).partial, True) + self.assertEqual(regex.match('(?r)a+?', '', partial=True).partial, True) + self.assertEqual(regex.match('(?r)a++', '', partial=True).partial, True) + self.assertEqual(regex.match('(?r)a+', 'a', partial=True).partial, False) + self.assertEqual(regex.match('(?r)a+?', 'a', partial=True).partial, False) + self.assertEqual(regex.match('(?r)a++', 'a', partial=True).partial, False) + + self.assertEqual(regex.match(r"(?:\s*\w+'*)+", 'whatever', partial=True).partial, + False) + + # Hg issue 300: segmentation fault + pattern = ('(?PGGCGTCACACTTTGCTATGCCATAGCAT[AG]TTTATCCATAAGA' + 'TTAGCGGATCCTACCTGACGCTTTTTATCGCAACTCTCTACTGTTTCTCCATAACAGAACATATTGA' + 'CTATCCGGTATTACCCGGCATGACAGGAGTAAAA){e<=1}' + '(?P[ACGT]{1059}){e<=2}' + '(?PTAATCGTCTTGTTTGATACACAAGGGTCGCATCTGCGGCCCTTTTGCTTTTTTAAG' + 'TTGTAAGGATATGCCATTCTAGA){e<=0}' + '(?P[ACGT]{18}){e<=0}' + '(?PAGATCGG[CT]AGAGCGTCGTGTAGGGAAAGAGTGTGG){e<=1}') + + text = ('GCACGGCGTCACACTTTGCTATGCCATAGCATATTTATCCATAAGATTAGCGGATCCTACC' + 'TGACGCTTTTTATCGCAACTCTCTACTGTTTCTCCATAACAGAACATATTGACTATCCGGTATTACC' + 'CGGCATGACAGGAGTAAAAATGGCTATCGACGAAAACAAACAGAAAGCGTTGGCGGCAGCACTGGGC' + 'CAGATTGAGAAACAATTTGGTAAAGGCTCCATCATGCGCCTGGGTGAAGACCGTTCCATGGATGTGG' + 'AAACCATCTCTACCGGTTCGCTTTCACTGGATATCGCGCTTGGGGCAGGTGGTCTGCCGATGGGCCG' + 'TATCGTCGAAATCTACGGACCGGAATCTTCCGGTAAAACCACGCTGACGCTGCAGGTGATCGCCGCA' + 'GCGCAGCGTGAAGGTAAAACCTGTGCGTTTATCGATGCTGAACACGCGCTGGACCCAATCTACGCAC' + 'GTAAACTGGGCGTCGATATCGACAACCTGCTGTGCTCCCAGCCGGACACCGGCGAGCAGGCACTGGA' + 'AATCTGTGACGCCCTGGCGCGTTCTGGCGCAGTAGACGTTATCGTCGTTGACTCCGTGGCGGCACTG' + 'ACGCCGAAAGCGGAAATCGAAGGCGAAATCGGCGACTCTCATATGGGCCTTGCGGCACGTATGATGA' + 'GCCAGGCGATGCGTAAGCTGGCGGGTAACCTGAAGCAGTCCAACACGCTGCTGATCTTCATCAACCC' + 'CATCCGTATGAAAATTGGTGTGATGTTCGGCAACCCGGAAACCACTTACCGGTGGTAACGCGCTGAA' + 'ATTCTACGCCTCTGTTCGTCTCGACATCCGTTAAATCGGCGCGGTGAAAGAGGGCGAAAACGTGGTG' + 'GGTAGCGAAACCCGCGTGAAAGTGGTGAAGAACAAAATCGCTGCGCCGTTTAAACAGGCTGAATTCC' + 'AGATCCTCTACGGCGAAGGTATCAACTTCTACCCCGAACTGGTTGACCTGGGCGTAAAAGAGAAGCT' + 'GATCGAGAAAGCAGGCGCGTGGTACAGCTACAAAGGTGAGAAGATCGGTCAGGGTAAAGCGAATGCG' + 'ACTGCCTGGCTGAAATTTAACCCGGAAACCGCGAAAGAGATCGAGTGAAAAGTACGTGAGTTGCTGC' + 'TGAGCAACCCGAACTCAACGCCGGATTTCTCTGTAGATGATAGCGAAGGCGTAGCAGAAACTAACGA' + 'AGATTTTTAATCGTCTTGTTTGATACACAAGGGTCGCATCTGCGGCCCTTTTGCTTTTTTAAGTTGT' + 'AAGGATATGCCATTCTAGACAGTTAACACACCAACAAAGATCGGTAGAGCGTCGTGTAGGGAAAGAG' + 'TGTGGTACC') + + m = regex.search(pattern, text, flags=regex.BESTMATCH) + self.assertEqual(m.fuzzy_counts, (0, 1, 0)) + self.assertEqual(m.fuzzy_changes, ([], [1206], [])) + + # Hg issue 306: Fuzzy match parameters not respecting quantifier scope + self.assertEqual(regex.search(r'(?e)(dogf(((oo){e<1})|((00){e<1}))d){e<2}', + 'dogfood').fuzzy_counts, (0, 0, 0)) + self.assertEqual(regex.search(r'(?e)(dogf(((oo){e<1})|((00){e<1}))d){e<2}', + 'dogfoot').fuzzy_counts, (1, 0, 0)) + + # Hg issue 312: \X not matching graphemes with zero-width-joins + self.assertEqual(regex.findall(r'\X', + '\U0001F468\u200D\U0001F469\u200D\U0001F467\u200D\U0001F466'), + ['\U0001F468\u200D\U0001F469\u200D\U0001F467\u200D\U0001F466']) + + # Hg issue 320: Abnormal performance + self.assertEqual(bool(regex.search(r'(?=a)a', 'a')), True) + self.assertEqual(bool(regex.search(r'(?!b)a', 'a')), True) + + # Hg issue 327: .fullmatch() causes MemoryError + self.assertEqual(regex.fullmatch(r'((\d)*?)*?', '123').span(), (0, 3)) + + # Hg issue 329: Wrong group matches when question mark quantifier is used within a look behind + self.assertEqual(regex.search(r'''(?(DEFINE)(?(?THIS_SHOULD_NOT_MATCHx?)|(?right))).*(?<=(?&mydef).*)''', + 'x right').capturesdict(), {'mydef': ['right'], 'wrong': [], 'right': + ['right']}) + + # Hg issue 338: specifying allowed characters when fuzzy-matching + self.assertEqual(bool(regex.match(r'(?:cat){e<=1:[u]}', 'cut')), True) + self.assertEqual(bool(regex.match(r'(?:cat){e<=1:u}', 'cut')), True) + + # Hg issue 353: fuzzy changes negative indexes + self.assertEqual(regex.search(r'(?be)(AGTGTTCCCCGCGCCAGCGGGGATAAACCG){s<=5,i<=5,d<=5,s+i+d<=10}', + 'TTCCCCGCGCCAGCGGGGATAAACCG').fuzzy_changes, ([], [], [0, 1, 3, 5])) + + # Git issue 364: Contradictory values in fuzzy_counts and fuzzy_changes + self.assertEqual(regex.match(r'(?:bc){e}', 'c').fuzzy_counts, (1, 0, + 1)) + self.assertEqual(regex.match(r'(?:bc){e}', 'c').fuzzy_changes, ([0], + [], [1])) + self.assertEqual(regex.match(r'(?e)(?:bc){e}', 'c').fuzzy_counts, (0, + 0, 1)) + self.assertEqual(regex.match(r'(?e)(?:bc){e}', 'c').fuzzy_changes, + ([], [], [0])) + self.assertEqual(regex.match(r'(?b)(?:bc){e}', 'c').fuzzy_counts, (0, + 0, 1)) + self.assertEqual(regex.match(r'(?b)(?:bc){e}', 'c').fuzzy_changes, + ([], [], [0])) + + # Git issue 370: Confusions about Fuzzy matching behavior + self.assertEqual(regex.match('(?e)(?:^(\\$ )?\\d{1,3}(,\\d{3})*(\\.\\d{2})$){e}', + '$ 10,112.111.12').fuzzy_counts, (6, 0, 5)) + self.assertEqual(regex.match('(?e)(?:^(\\$ )?\\d{1,3}(,\\d{3})*(\\.\\d{2})$){s<=1}', + '$ 10,112.111.12').fuzzy_counts, (1, 0, 0)) + self.assertEqual(regex.match('(?e)(?:^(\\$ )?\\d{1,3}(,\\d{3})*(\\.\\d{2})$){s<=1,i<=1,d<=1}', + '$ 10,112.111.12').fuzzy_counts, (1, 0, 0)) + self.assertEqual(regex.match('(?e)(?:^(\\$ )?\\d{1,3}(,\\d{3})*(\\.\\d{2})$){s<=3}', + '$ 10,1a2.111.12').fuzzy_counts, (2, 0, 0)) + self.assertEqual(regex.match('(?e)(?:^(\\$ )?\\d{1,3}(,\\d{3})*(\\.\\d{2})$){s<=2}', + '$ 10,1a2.111.12').fuzzy_counts, (2, 0, 0)) + + self.assertEqual(regex.fullmatch(r'(?e)(?:0?,0(?:,0)?){s<=1,d<=1}', + ',0;0').fuzzy_counts, (1, 0, 0)) + self.assertEqual(regex.fullmatch(r'(?e)(?:0??,0(?:,0)?){s<=1,d<=1}', + ',0;0').fuzzy_counts, (1, 0, 0)) + + # Git issue 371: Specifying character set when fuzzy-matching allows characters not in the set + self.assertEqual(regex.search(r"\b(?e)(?:\d{6,20}){i<=5:[\-\\\/]}\b", + "cat dog starting at 00:01132.000. hello world"), None) + + # Git issue 385: Comments in expressions + self.assertEqual(bool(regex.compile('(?#)')), True) + self.assertEqual(bool(regex.compile('(?x)(?#)')), True) + + # Git issue 394: Unexpected behaviour in fuzzy matching with limited character set with IGNORECASE flag + self.assertEqual(regex.findall(r'(\d+){i<=2:[ab]}', '123X4Y5'), + ['123', '4', '5']) + self.assertEqual(regex.findall(r'(?i)(\d+){i<=2:[ab]}', '123X4Y5'), + ['123', '4', '5']) + + # Git issue 403: Fuzzy matching with wrong distance (unnecessary substitutions) + self.assertEqual(regex.match(r'^(test){e<=5}$', 'terstin', + flags=regex.B).fuzzy_counts, (0, 3, 0)) + + # Git issue 408: regex fails with a quantified backreference but succeeds with repeated backref + self.assertEqual(bool(regex.match(r"(?:(x*)\1\1\1)*x$", "x" * 5)), True) + self.assertEqual(bool(regex.match(r"(?:(x*)\1{3})*x$", "x" * 5)), True) + + # Git issue 415: Fuzzy character restrictions don't apply to insertions at "right edge" + self.assertEqual(regex.match(r't(?:es){s<=1:\d}t', 'te5t').group(), + 'te5t') + self.assertEqual(regex.match(r't(?:es){s<=1:\d}t', 'tezt'), None) + self.assertEqual(regex.match(r't(?:es){i<=1:\d}t', 'tes5t').group(), + 'tes5t') + self.assertEqual(regex.match(r't(?:es){i<=1:\d}t', 'teszt'), None) + self.assertEqual(regex.match(r't(?:es){i<=1:\d}t', + 'tes5t').fuzzy_changes, ([], [3], [])) + self.assertEqual(regex.match(r't(es){i<=1,0.*)(?PCTTCC){e<=1}(?P([ACGT]){4,6})(?PCAATACCGACTCCTCACTGTGT){e<=2}(?P([ACGT]){0,6}$)' + + m = regex.match(pattern, sequence, flags=regex.BESTMATCH) + self.assertEqual(m.span(), (0, 50)) + self.assertEqual(m.groupdict(), {'insert': 'TTCAGACGTGTGCT', 'anchor': 'CTTCC', 'umi': 'GATCT', 'sid': 'CAATACCGACTCCTCACTGTGT', 'end': 'GTCT'}) + + m = regex.match(pattern, sequence, flags=regex.ENHANCEMATCH) + self.assertEqual(m.span(), (0, 50)) + self.assertEqual(m.groupdict(), {'insert': 'TTCAGACGTGTGCT', 'anchor': 'CTTCC', 'umi': 'GATCT', 'sid': 'CAATACCGACTCCTCACTGTGT', 'end': 'GTCT'}) + + # Git issue 433: Disagreement between fuzzy_counts and fuzzy_changes + pattern = r'(?P.*)(?PAACACTGG){e<=1}(?P([AT][CG]){5}){e<=2}(?PGTAACCGAAG){e<=2}(?P([ACGT]){0,6}$)' + + sequence = 'GGAAAACACTGGTCTCAGTCTCGTAACCGAAGTGGTCG' + m = regex.match(pattern, sequence, flags=regex.BESTMATCH) + self.assertEqual(m.fuzzy_counts, (0, 0, 0)) + self.assertEqual(m.fuzzy_changes, ([], [], [])) + + sequence = 'GGAAAACACTGGTCTCAGTCTCGTCCCCGAAGTGGTCG' + m = regex.match(pattern, sequence, flags=regex.BESTMATCH) + self.assertEqual(m.fuzzy_counts, (2, 0, 0)) + self.assertEqual(m.fuzzy_changes, ([24, 25], [], [])) + + # Git issue 439: Unmatched groups: sub vs subf + self.assertEqual(regex.sub(r'(test1)|(test2)', r'matched: \1\2', 'test1'), 'matched: test1') + self.assertEqual(regex.subf(r'(test1)|(test2)', r'matched: {1}{2}', 'test1'), 'matched: test1') + self.assertEqual(regex.search(r'(test1)|(test2)', 'matched: test1').expand(r'matched: \1\2'), 'matched: test1'), + self.assertEqual(regex.search(r'(test1)|(test2)', 'matched: test1').expandf(r'matched: {1}{2}'), 'matched: test1') + + # Git issue 442: Fuzzy regex matching doesn't seem to test insertions correctly + self.assertEqual(regex.search(r"(?:\bha\b){i:[ ]}", "having"), None) + self.assertEqual(regex.search(r"(?:\bha\b){i:[ ]}", "having", flags=regex.I), None) + + # Git issue 467: Scoped inline flags 'a', 'u' and 'L' affect global flags + self.assertEqual(regex.match(r'(?a:\w)\w', 'd\N{CYRILLIC SMALL LETTER ZHE}').span(), (0, 2)) + self.assertEqual(regex.match(r'(?a:\w)(?u:\w)', 'd\N{CYRILLIC SMALL LETTER ZHE}').span(), (0, 2)) + + # Git issue 473: Emoji classified as letter + self.assertEqual(regex.match(r'^\p{LC}+$', '\N{SMILING CAT FACE WITH OPEN MOUTH}'), None) + self.assertEqual(regex.match(r'^\p{So}+$', '\N{SMILING CAT FACE WITH OPEN MOUTH}').span(), (0, 1)) + + # Git issue 474: regex has no equivalent to `re.Match.groups()` for captures + self.assertEqual(regex.match(r'(.)+', 'abc').allcaptures(), (['abc'], ['a', 'b', 'c'])) + self.assertEqual(regex.match(r'(.)+', 'abc').allspans(), ([(0, 3)], [(0, 1), (1, 2), (2, 3)])) + + # Git issue 477: \v for vertical spacing + self.assertEqual(bool(regex.fullmatch(r'\p{HorizSpace}+', '\t \xA0\u1680\u180E\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200A\u202F\u205F\u3000')), True) + self.assertEqual(bool(regex.fullmatch(r'\p{VertSpace}+', '\n\v\f\r\x85\u2028\u2029')), True) + + # Git issue 479: Segmentation fault when using conditional pattern + self.assertEqual(regex.match(r'(?(?<=A)|(?(?![^B])C|D))', 'A'), None) + self.assertEqual(regex.search(r'(?(?<=A)|(?(?![^B])C|D))', 'A').span(), (1, 1)) + + # Git issue 494: Backtracking failure matching regex ^a?(a?)b?c\1$ against string abca + self.assertEqual(regex.search(r"^a?(a?)b?c\1$", "abca").span(), (0, 4)) + + # Git issue 498: Conditional negative lookahead inside positive lookahead fails to match + self.assertEqual(regex.match(r'(?(?=a).|..)', 'ab').span(), (0, 1)) + self.assertEqual(regex.match(r'(?(?=b).|..)', 'ab').span(), (0, 2)) + self.assertEqual(regex.match(r'(?(?!a).|..)', 'ab').span(), (0, 2)) + self.assertEqual(regex.match(r'(?(?!b).|..)', 'ab').span(), (0, 1)) + + # Git issue 525: segfault when fuzzy matching empty list + self.assertEqual(regex.match(r"(\L){e<=5}", "blah", foo=[]).span(), (0, 0)) + + # Git issue 527: `VERBOSE`/`X` flag breaks `\N` escapes + self.assertEqual(regex.compile(r'\N{LATIN SMALL LETTER A}').match('a').span(), (0, 1)) + self.assertEqual(regex.compile(r'\N{LATIN SMALL LETTER A}', flags=regex.X).match('a').span(), (0, 1)) + + # Git issue 539: Bug: Partial matching fails on a simple example + self.assertEqual(regex.match(r"[^/]*b/ccc", "b/ccc", partial=True).span(), (0, 5)) + self.assertEqual(regex.match(r"[^/]*b/ccc", "b/ccb", partial=True), None) + self.assertEqual(regex.match(r"[^/]*b/ccc", "b/cc", partial=True).span(), (0, 4)) + self.assertEqual(regex.match(r"[^/]*b/xyz", "b/xy", partial=True).span(), (0, 4)) + self.assertEqual(regex.match(r"[^/]*b/xyz", "b/yz", partial=True), None) + + self.assertEqual(regex.match(r"(?i)[^/]*b/ccc", "b/ccc", partial=True).span(), (0, 5)) + self.assertEqual(regex.match(r"(?i)[^/]*b/ccc", "b/ccb", partial=True), None) + self.assertEqual(regex.match(r"(?i)[^/]*b/ccc", "b/cc", partial=True).span(), (0, 4)) + self.assertEqual(regex.match(r"(?i)[^/]*b/xyz", "b/xy", partial=True).span(), (0, 4)) + self.assertEqual(regex.match(r"(?i)[^/]*b/xyz", "b/yz", partial=True), None) + + # Git issue 546: Partial match not working in some instances with non-greedy capture + self.assertEqual(bool(regex.match(r'.*?', '<', partial=True)), True) + self.assertEqual(bool(regex.match(r'.*?', '.*?', '', partial=True)), True) + self.assertEqual(bool(regex.match(r'.*?', 'x', partial=True)), True) + self.assertEqual(bool(regex.match(r'.*?', 'xyz abc', partial=True)), True) + self.assertEqual(bool(regex.match(r'.*?', 'xyz abc foo', partial=True)), True) + self.assertEqual(bool(regex.match(r'.*?', 'xyz abc foo ', partial=True)), True) + self.assertEqual(bool(regex.match(r'.*?', 'xyz abc foo bar', partial=True)), True) + + # Git issue 551: + self.assertEqual(bool(regex.match(r'(?V1)[[\s\S]]', 'a')), True) + self.assertEqual(bool(regex.match(r'(?V1)[[\s\S]-a]', 'a')), True) + self.assertEqual(bool(regex.match(r'(?V1)[[\s\S]--a]', 'a')), False) + self.assertEqual(bool(regex.match(r'(?V1)[[a-z]--b]', 'a')), True) + self.assertEqual(bool(regex.match(r'(?V1)[[\s\S]--b]', 'a')), True) + self.assertEqual(bool(regex.match(r'(?V1)[a-[\s\S]]', 'a')), True) + self.assertEqual(bool(regex.match(r'(?V1)[a--[\s\S]]', 'a')), False) + + self.assertEqual(regex.search(r'(?ifu)(H\N{LATIN SMALL LETTER O WITH DIAERESIS}gskolan?)[\\s\\S]*p', + 'Yrkesh\N{LATIN SMALL LETTER O WITH DIAERESIS}gskola . Studie\N{LATIN SMALL LETTER A WITH DIAERESIS}mnen . Studie\N{LATIN SMALL LETTER A WITH DIAERESIS}mnen . Studie\N{LATIN SMALL LETTER A WITH DIAERESIS}mnen . Studie\N{LATIN SMALL LETTER A WITH DIAERESIS}mnen . Studie\N{LATIN SMALL LETTER A WITH DIAERESIS}mnen . Studie\N{LATIN SMALL LETTER A WITH DIAERESIS}mnen . Studie\N{LATIN SMALL LETTER A WITH DIAERESIS}mnen'), + None) + + # Git issue 572: Inline ASCII modifier doesn't seem to affect anything + self.assertEqual(bool(regex.match(r'\d', '\uFF19')), True) + self.assertEqual(bool(regex.match(r'(?a:\d)', '\uFF19')), False) + + # Git issue 575: Issues with ASCII/Unicode modifiers + self.assertEqual(regex.findall('\\d', '9\uFF19'), ['9', '\uff19']) + self.assertEqual(regex.findall('(?u:\\d)', '9\uFF19'), ['9', '\uff19']) + self.assertEqual(regex.findall('(?a:\\d)', '9\uFF19'), ['9']) + + self.assertEqual(regex.findall('\\d', '9\uFF19', flags=regex.U), ['9', '\uff19']) + self.assertEqual(regex.findall('(?u:\\d)', '9\uFF19', flags=regex.U), ['9', '\uff19']) + self.assertEqual(regex.findall('(?a:\\d)', '9\uFF19', flags=regex.U), ['9']) + + self.assertEqual(regex.findall('\\d', '9\uFF19', flags=regex.A), ['9']) + self.assertEqual(regex.findall('(?u:\\d)', '9\uFF19', flags=regex.A), ['9', '\uff19']) + self.assertEqual(regex.findall('(?a:\\d)', '9\uFF19', flags=regex.A), ['9']) + + self.assertEqual(len(regex.findall(r'\p{L}', ''.join(chr(c) for c in range(0x100)), flags=0)), 117) + self.assertEqual(len(regex.findall(r'\p{L}', ''.join(chr(c) for c in range(0x100)), flags=regex.A)), 52) + self.assertEqual(len(regex.findall(r'\p{L}', ''.join(chr(c) for c in range(0x100)), flags=regex.U)), 117) + + self.assertEqual(len(regex.findall(r'(?a:\p{L})', ''.join(chr(c) for c in range(0x100)), flags=0)), 52) + self.assertEqual(len(regex.findall(r'(?a:\p{L})', ''.join(chr(c) for c in range(0x100)), flags=regex.A)), 52) + self.assertEqual(len(regex.findall(r'(?a:\p{L})', ''.join(chr(c) for c in range(0x100)), flags=regex.U)), 52) + + self.assertEqual(len(regex.findall(r'(?u:\p{L})', ''.join(chr(c) for c in range(0x100)), flags=0)), 117) + self.assertEqual(len(regex.findall(r'(?u:\p{L})', ''.join(chr(c) for c in range(0x100)), flags=regex.A)), 117) + self.assertEqual(len(regex.findall(r'(?u:\p{L})', ''.join(chr(c) for c in range(0x100)), flags=regex.U)), 117) + + # Git issue 580: Regression in v2025.7.31: \P{L} no longer matches in simple patterns + self.assertEqual(bool(regex.match(r"\A\P{L}?\p{L}", "hello,")), True) + self.assertEqual(bool(regex.fullmatch(r"\A\P{L}*(?P\p{L}+)\P{L}*\Z", "hello,")), True) + + # Git issue 584: AttributeError: 'AnyAll' object has no attribute 'positive' + self.assertEqual(bool(regex.compile('(\\s|\\S)')), True) + + # Git PR 585: Fix AttributeError: 'AnyAll' object has no attribute '_key' + self.assertEqual(bool(regex.compile('(?:[\\S\\s]|[A-D][M-Z])')), True) + + def test_fuzzy_ext(self): + self.assertEqual(bool(regex.fullmatch(r'(?r)(?:a){e<=1:[a-z]}', 'e')), + True) + self.assertEqual(bool(regex.fullmatch(r'(?:a){e<=1:[a-z]}', 'e')), + True) + self.assertEqual(bool(regex.fullmatch(r'(?:a){e<=1:[a-z]}', '-')), + False) + self.assertEqual(bool(regex.fullmatch(r'(?r)(?:a){e<=1:[a-z]}', '-')), + False) + + self.assertEqual(bool(regex.fullmatch(r'(?:a){e<=1:[a-z]}', 'ae')), + True) + self.assertEqual(bool(regex.fullmatch(r'(?r)(?:a){e<=1:[a-z]}', + 'ae')), True) + self.assertEqual(bool(regex.fullmatch(r'(?:a){e<=1:[a-z]}', 'a-')), + False) + self.assertEqual(bool(regex.fullmatch(r'(?r)(?:a){e<=1:[a-z]}', + 'a-')), False) + + self.assertEqual(bool(regex.fullmatch(r'(?:ab){e<=1:[a-z]}', 'ae')), + True) + self.assertEqual(bool(regex.fullmatch(r'(?r)(?:ab){e<=1:[a-z]}', + 'ae')), True) + self.assertEqual(bool(regex.fullmatch(r'(?:ab){e<=1:[a-z]}', 'a-')), + False) + self.assertEqual(bool(regex.fullmatch(r'(?r)(?:ab){e<=1:[a-z]}', + 'a-')), False) + + self.assertEqual(bool(regex.fullmatch(r'(a)\1{e<=1:[a-z]}', 'ae')), + True) + self.assertEqual(bool(regex.fullmatch(r'(?r)\1{e<=1:[a-z]}(a)', + 'ea')), True) + self.assertEqual(bool(regex.fullmatch(r'(a)\1{e<=1:[a-z]}', 'a-')), + False) + self.assertEqual(bool(regex.fullmatch(r'(?r)\1{e<=1:[a-z]}(a)', + '-a')), False) + + self.assertEqual(bool(regex.fullmatch(r'(?fiu)(?:\N{LATIN SMALL LETTER SHARP S}){e<=1:[a-z]}', + 'ts')), True) + self.assertEqual(bool(regex.fullmatch(r'(?fiu)(?:\N{LATIN SMALL LETTER SHARP S}){e<=1:[a-z]}', + 'st')), True) + self.assertEqual(bool(regex.fullmatch(r'(?firu)(?:\N{LATIN SMALL LETTER SHARP S}){e<=1:[a-z]}', + 'st')), True) + self.assertEqual(bool(regex.fullmatch(r'(?firu)(?:\N{LATIN SMALL LETTER SHARP S}){e<=1:[a-z]}', + 'ts')), True) + self.assertEqual(bool(regex.fullmatch(r'(?fiu)(?:\N{LATIN SMALL LETTER SHARP S}){e<=1:[a-z]}', + '-s')), False) + self.assertEqual(bool(regex.fullmatch(r'(?fiu)(?:\N{LATIN SMALL LETTER SHARP S}){e<=1:[a-z]}', + 's-')), False) + self.assertEqual(bool(regex.fullmatch(r'(?firu)(?:\N{LATIN SMALL LETTER SHARP S}){e<=1:[a-z]}', + 's-')), False) + self.assertEqual(bool(regex.fullmatch(r'(?firu)(?:\N{LATIN SMALL LETTER SHARP S}){e<=1:[a-z]}', + '-s')), False) + + self.assertEqual(bool(regex.fullmatch(r'(?fiu)(\N{LATIN SMALL LETTER SHARP S})\1{e<=1:[a-z]}', + 'ssst')), True) + self.assertEqual(bool(regex.fullmatch(r'(?fiu)(\N{LATIN SMALL LETTER SHARP S})\1{e<=1:[a-z]}', + 'ssts')), True) + self.assertEqual(bool(regex.fullmatch(r'(?firu)\1{e<=1:[a-z]}(\N{LATIN SMALL LETTER SHARP S})', + 'stss')), True) + self.assertEqual(bool(regex.fullmatch(r'(?firu)\1{e<=1:[a-z]}(\N{LATIN SMALL LETTER SHARP S})', + 'tsss')), True) + self.assertEqual(bool(regex.fullmatch(r'(?fiu)(\N{LATIN SMALL LETTER SHARP S})\1{e<=1:[a-z]}', + 'ss-s')), False) + self.assertEqual(bool(regex.fullmatch(r'(?fiu)(\N{LATIN SMALL LETTER SHARP S})\1{e<=1:[a-z]}', + 'sss-')), False) + self.assertEqual(bool(regex.fullmatch(r'(?firu)(\N{LATIN SMALL LETTER SHARP S})\1{e<=1:[a-z]}', + '-s')), False) + self.assertEqual(bool(regex.fullmatch(r'(?firu)(\N{LATIN SMALL LETTER SHARP S})\1{e<=1:[a-z]}', + 's-')), False) + + self.assertEqual(bool(regex.fullmatch(r'(?fiu)(ss)\1{e<=1:[a-z]}', + '\N{LATIN SMALL LETTER SHARP S}ts')), True) + self.assertEqual(bool(regex.fullmatch(r'(?fiu)(ss)\1{e<=1:[a-z]}', + '\N{LATIN SMALL LETTER SHARP S}st')), True) + self.assertEqual(bool(regex.fullmatch(r'(?firu)\1{e<=1:[a-z]}(ss)', + 'st\N{LATIN SMALL LETTER SHARP S}')), True) + self.assertEqual(bool(regex.fullmatch(r'(?firu)\1{e<=1:[a-z]}(ss)', + 'ts\N{LATIN SMALL LETTER SHARP S}')), True) + self.assertEqual(bool(regex.fullmatch(r'(?fiu)(ss)\1{e<=1:[a-z]}', + '\N{LATIN SMALL LETTER SHARP S}-s')), False) + self.assertEqual(bool(regex.fullmatch(r'(?fiu)(ss)\1{e<=1:[a-z]}', + '\N{LATIN SMALL LETTER SHARP S}s-')), False) + self.assertEqual(bool(regex.fullmatch(r'(?firu)(ss)\1{e<=1:[a-z]}', + 's-\N{LATIN SMALL LETTER SHARP S}')), False) + self.assertEqual(bool(regex.fullmatch(r'(?firu)(ss)\1{e<=1:[a-z]}', + '-s\N{LATIN SMALL LETTER SHARP S}')), False) + + def test_subscripted_captures(self): + self.assertEqual(regex.match(r'(?P.)+', + 'abc').expandf('{0} {0[0]} {0[-1]}'), 'abc abc abc') + self.assertEqual(regex.match(r'(?P.)+', + 'abc').expandf('{1} {1[0]} {1[1]} {1[2]} {1[-1]} {1[-2]} {1[-3]}'), + 'c a b c c b a') + self.assertEqual(regex.match(r'(?P.)+', + 'abc').expandf('{x} {x[0]} {x[1]} {x[2]} {x[-1]} {x[-2]} {x[-3]}'), + 'c a b c c b a') + + self.assertEqual(regex.subf(r'(?P.)+', r'{0} {0[0]} {0[-1]}', + 'abc'), 'abc abc abc') + self.assertEqual(regex.subf(r'(?P.)+', + '{1} {1[0]} {1[1]} {1[2]} {1[-1]} {1[-2]} {1[-3]}', 'abc'), + 'c a b c c b a') + self.assertEqual(regex.subf(r'(?P.)+', + '{x} {x[0]} {x[1]} {x[2]} {x[-1]} {x[-2]} {x[-3]}', 'abc'), + 'c a b c c b a') + + def test_more_zerowidth(self): + if sys.version_info >= (3, 7, 0): + self.assertEqual(regex.split(r'\b|:+', 'a::bc'), ['', 'a', '', '', + 'bc', '']) + self.assertEqual(regex.sub(r'\b|:+', '-', 'a::bc'), '-a---bc-') + self.assertEqual(regex.findall(r'\b|:+', 'a::bc'), ['', '', '::', + '', '']) + self.assertEqual([m.span() for m in regex.finditer(r'\b|:+', + 'a::bc')], [(0, 0), (1, 1), (1, 3), (3, 3), (5, 5)]) + self.assertEqual([m.span() for m in regex.finditer(r'(?m)^\s*?$', + 'foo\n\n\nbar')], [(4, 4), (4, 5), (5, 5)]) + + def test_line_ending(self): + self.assertEqual(regex.findall(r'\R', '\r\n\n\x0B\f\r\x85\u2028\u2029'), + ['\r\n', '\n', '\x0B', '\f', '\r', '\x85', '\u2028', '\u2029']) + self.assertEqual(regex.findall(br'\R', b'\r\n\n\x0B\f\r\x85'), [b'\r\n', + b'\n', b'\x0B', b'\f', b'\r']) + +def test_main(): + unittest.main(verbosity=2) + +if __name__ == "__main__": + test_main() diff --git a/.venv/lib/python3.12/site-packages/requests-2.34.2.dist-info/INSTALLER b/.venv/lib/python3.12/site-packages/requests-2.34.2.dist-info/INSTALLER new file mode 100644 index 0000000000000000000000000000000000000000..a1b589e38a32041e49332e5e81c2d363dc418d68 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/requests-2.34.2.dist-info/INSTALLER @@ -0,0 +1 @@ +pip diff --git a/.venv/lib/python3.12/site-packages/requests-2.34.2.dist-info/METADATA b/.venv/lib/python3.12/site-packages/requests-2.34.2.dist-info/METADATA new file mode 100644 index 0000000000000000000000000000000000000000..cfc3f948ea8688876107fcd120e63e39df3e9664 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/requests-2.34.2.dist-info/METADATA @@ -0,0 +1,120 @@ +Metadata-Version: 2.4 +Name: requests +Version: 2.34.2 +Summary: Python HTTP for Humans. +Author-email: Kenneth Reitz +Maintainer-email: Ian Stapleton Cordasco , Nate Prewitt +License: Apache-2.0 +Project-URL: Documentation, https://requests.readthedocs.io +Project-URL: Source, https://github.com/psf/requests +Classifier: Development Status :: 5 - Production/Stable +Classifier: Environment :: Web Environment +Classifier: Intended Audience :: Developers +Classifier: License :: OSI Approved :: Apache Software License +Classifier: Natural Language :: English +Classifier: Operating System :: OS Independent +Classifier: Programming Language :: Python +Classifier: Programming Language :: Python :: 3 +Classifier: Programming Language :: Python :: 3.10 +Classifier: Programming Language :: Python :: 3.11 +Classifier: Programming Language :: Python :: 3.12 +Classifier: Programming Language :: Python :: 3.13 +Classifier: Programming Language :: Python :: 3.14 +Classifier: Programming Language :: Python :: 3.15 +Classifier: Programming Language :: Python :: 3 :: Only +Classifier: Programming Language :: Python :: Implementation :: CPython +Classifier: Programming Language :: Python :: Implementation :: PyPy +Classifier: Programming Language :: Python :: Free Threading :: 2 - Beta +Classifier: Topic :: Internet :: WWW/HTTP +Classifier: Topic :: Software Development :: Libraries +Requires-Python: >=3.10 +Description-Content-Type: text/markdown +License-File: LICENSE +License-File: NOTICE +Requires-Dist: charset_normalizer<4,>=2 +Requires-Dist: idna<4,>=2.5 +Requires-Dist: urllib3<3,>=1.26 +Requires-Dist: certifi>=2023.5.7 +Provides-Extra: security +Provides-Extra: socks +Requires-Dist: PySocks!=1.5.7,>=1.5.6; extra == "socks" +Provides-Extra: use-chardet-on-py3 +Requires-Dist: chardet<8,>=3.0.2; extra == "use-chardet-on-py3" +Dynamic: license-file + +# Requests + +[![Version](https://img.shields.io/pypi/v/requests.svg?maxAge=86400)](https://pypi.org/project/requests/) +[![Supported Versions](https://img.shields.io/pypi/pyversions/requests.svg)](https://pypi.org/project/requests) +[![Downloads](https://static.pepy.tech/badge/requests/month)](https://pepy.tech/project/requests) +[![Contributors](https://img.shields.io/github/contributors/psf/requests.svg)](https://github.com/psf/requests/graphs/contributors) +[![Documentation](https://readthedocs.org/projects/requests/badge/?version=latest)](https://requests.readthedocs.io) + +**Requests** is a simple, yet elegant, HTTP library. + +```python +>>> import requests +>>> r = requests.get('https://httpbin.org/basic-auth/user/pass', auth=('user', 'pass')) +>>> r.status_code +200 +>>> r.headers['content-type'] +'application/json; charset=utf8' +>>> r.encoding +'utf-8' +>>> r.text +'{"authenticated": true, ...' +>>> r.json() +{'authenticated': True, ...} +``` + +Requests allows you to send HTTP/1.1 requests extremely easily. There’s no need to manually add query strings to your URLs, or to form-encode your `PUT` & `POST` data — but nowadays, just use the `json` method! + +Requests is one of the most downloaded Python packages today, pulling in around `300M downloads / week` — according to GitHub, Requests is currently [depended upon](https://github.com/psf/requests/network/dependents?package_id=UGFja2FnZS01NzA4OTExNg%3D%3D) by `4,000,000+` repositories. + +## Installing Requests and Supported Versions + +Requests is available on PyPI: + +```console +$ python -m pip install requests +``` + +Requests officially supports Python 3.10+. + +## Supported Features & Best–Practices + +Requests is ready for the demands of building robust and reliable HTTP–speaking applications, for the needs of today. + +- Keep-Alive & Connection Pooling +- International Domains and URLs +- Sessions with Cookie Persistence +- Browser-style TLS/SSL Verification +- Basic & Digest Authentication +- Familiar `dict`–like Cookies +- Automatic Content Decompression and Decoding +- Multi-part File Uploads +- SOCKS Proxy Support +- Connection Timeouts +- Streaming Downloads +- Automatic honoring of `.netrc` +- Chunked HTTP Requests + +## Cloning the repository + +When cloning the Requests repository, you may need to add the `-c +fetch.fsck.badTimezone=ignore` flag to avoid an error about a bad commit timestamp (see +[this issue](https://github.com/psf/requests/issues/2690) for more background): + +```shell +git clone -c fetch.fsck.badTimezone=ignore https://github.com/psf/requests.git +``` + +You can also apply this setting to your global Git config: + +```shell +git config --global fetch.fsck.badTimezone ignore +``` + +--- + +[![Kenneth Reitz](https://raw.githubusercontent.com/psf/requests/main/ext/kr.png)](https://kennethreitz.org) [![Python Software Foundation](https://raw.githubusercontent.com/psf/requests/main/ext/psf.png)](https://www.python.org/psf) diff --git a/.venv/lib/python3.12/site-packages/requests-2.34.2.dist-info/RECORD b/.venv/lib/python3.12/site-packages/requests-2.34.2.dist-info/RECORD new file mode 100644 index 0000000000000000000000000000000000000000..6209d77b66a740ca6491283853a816966a278387 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/requests-2.34.2.dist-info/RECORD @@ -0,0 +1,46 @@ +requests-2.34.2.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4 +requests-2.34.2.dist-info/METADATA,sha256=jDhLo-l5SA-q4oWdPF5sEnbdLDYW4yLhJNUsjPxVbyc,4806 +requests-2.34.2.dist-info/RECORD,, +requests-2.34.2.dist-info/WHEEL,sha256=aeYiig01lYGDzBgS8HxWXOg3uV61G9ijOsup-k9o1sk,91 +requests-2.34.2.dist-info/licenses/LICENSE,sha256=CeipvOyAZxBGUsFoaFqwkx54aPnIKEtm9a5u2uXxEws,10142 +requests-2.34.2.dist-info/licenses/NOTICE,sha256=9REJct7a0rTp0xRRja87fXLW4C5Jms2AIYHeb3RXHcw,38 +requests-2.34.2.dist-info/top_level.txt,sha256=fMSVmHfb5rbGOo6xv-O_tUX6j-WyixssE-SnwcDRxNQ,9 +requests/__init__.py,sha256=MRFX5_pKqRZsgn1SN-b9aU7rXKVJ7kDi6Q-J8hq81W4,5922 +requests/__pycache__/__init__.cpython-312.pyc,, +requests/__pycache__/__version__.cpython-312.pyc,, +requests/__pycache__/_internal_utils.cpython-312.pyc,, +requests/__pycache__/_types.cpython-312.pyc,, +requests/__pycache__/adapters.cpython-312.pyc,, +requests/__pycache__/api.cpython-312.pyc,, +requests/__pycache__/auth.cpython-312.pyc,, +requests/__pycache__/certs.cpython-312.pyc,, +requests/__pycache__/compat.cpython-312.pyc,, +requests/__pycache__/cookies.cpython-312.pyc,, +requests/__pycache__/exceptions.cpython-312.pyc,, +requests/__pycache__/help.cpython-312.pyc,, +requests/__pycache__/hooks.cpython-312.pyc,, +requests/__pycache__/models.cpython-312.pyc,, +requests/__pycache__/packages.cpython-312.pyc,, +requests/__pycache__/sessions.cpython-312.pyc,, +requests/__pycache__/status_codes.cpython-312.pyc,, +requests/__pycache__/structures.cpython-312.pyc,, +requests/__pycache__/utils.cpython-312.pyc,, +requests/__version__.py,sha256=q7qQZwsDcKPcQNl8LepGo11L7JQf8Q18PPMJjvBKF_k,435 +requests/_internal_utils.py,sha256=TH2NEyyYmPx9cV5HPzrHR4XdxKuW0skkD4eDXcbZgf8,1542 +requests/_types.py,sha256=0G33n1SiecDMP67FlsRGJG1a0U7f1SnrMo3vvWKkSok,5838 +requests/adapters.py,sha256=ZH6r1EU94jKqQLVf8DPW8Zd4kQt-cGnFH99jB2_HdJM,28064 +requests/api.py,sha256=TRVICsBG8Ikgl5joZQR270oo6-b4G0AHWPjvQuxrVQk,7152 +requests/auth.py,sha256=6TlRpVLUw8X9m4Sl4dSbA8qrpHI8T_ES2mBTYA7IWmU,12233 +requests/certs.py,sha256=_ZxrgzWc75D_bE7uq43MI4jaOC68p9AKSZs8C0NKh-Q,430 +requests/compat.py,sha256=XXm6KJaQtQFQRDQaH3vH0kE0_BOi2z78-FJRW_mqGLQ,2465 +requests/cookies.py,sha256=ChzmFA8rlCBSLFCA41bmifp5bCUi9VyhCCb17Y4Kcjw,21549 +requests/exceptions.py,sha256=xeGPM1JFSWjjN7swVvCGffLzfAoNLBp33AXn4LPAQRs,4564 +requests/help.py,sha256=cjUZuxiE2hjYT2svt49-v3-1f3MgcLYCWuBx2sai0Xk,4210 +requests/hooks.py,sha256=69igJHXTGg5HOo9VPpUB_0NkW5VjiFrVKETnpj8Ndqs,1138 +requests/models.py,sha256=0bwNmQq_XV6-4F-JCRG0Nj-t8tUmS2hqlj30fFKbas4,41783 +requests/packages.py,sha256=_g0gZ681UyAlKHRjH6kanbaoxx2eAb6qzcXiODyTIoc,904 +requests/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +requests/sessions.py,sha256=lvuzC7vwalmlJo0TtXiFFJdWqj8xaVtcFeQd17svZ6Y,34248 +requests/status_codes.py,sha256=GVD0fInPGAGXh-B9jOSPZtazjmIvfZTXCpAkf-5sBA4,4351 +requests/structures.py,sha256=upRgw5B48l5vHSokrJQaxvjS7pcZf6jI0MJi2KHmegI,4134 +requests/utils.py,sha256=ZX_QI0OyWGu9E4pOwPA87rdhDCcS-WrFTyinCL99B5w,36322 diff --git a/.venv/lib/python3.12/site-packages/requests-2.34.2.dist-info/WHEEL b/.venv/lib/python3.12/site-packages/requests-2.34.2.dist-info/WHEEL new file mode 100644 index 0000000000000000000000000000000000000000..14a883f292bc96b20c2b76a3081991f2676523a9 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/requests-2.34.2.dist-info/WHEEL @@ -0,0 +1,5 @@ +Wheel-Version: 1.0 +Generator: setuptools (82.0.1) +Root-Is-Purelib: true +Tag: py3-none-any + diff --git a/.venv/lib/python3.12/site-packages/requests-2.34.2.dist-info/licenses/LICENSE b/.venv/lib/python3.12/site-packages/requests-2.34.2.dist-info/licenses/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..67db8588217f266eb561f75fae738656325deac9 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/requests-2.34.2.dist-info/licenses/LICENSE @@ -0,0 +1,175 @@ + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. diff --git a/.venv/lib/python3.12/site-packages/requests-2.34.2.dist-info/licenses/NOTICE b/.venv/lib/python3.12/site-packages/requests-2.34.2.dist-info/licenses/NOTICE new file mode 100644 index 0000000000000000000000000000000000000000..1ff62db688277b77c83c1766dac7f165364d3528 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/requests-2.34.2.dist-info/licenses/NOTICE @@ -0,0 +1,2 @@ +Requests +Copyright 2019 Kenneth Reitz diff --git a/.venv/lib/python3.12/site-packages/requests-2.34.2.dist-info/top_level.txt b/.venv/lib/python3.12/site-packages/requests-2.34.2.dist-info/top_level.txt new file mode 100644 index 0000000000000000000000000000000000000000..f2293605cf1b01dca72aad0a15c45b72ed5429a2 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/requests-2.34.2.dist-info/top_level.txt @@ -0,0 +1 @@ +requests diff --git a/.venv/lib/python3.12/site-packages/requests/__init__.py b/.venv/lib/python3.12/site-packages/requests/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..ad842400b99c65c91988579e76419cf48224a680 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/requests/__init__.py @@ -0,0 +1,219 @@ +# __ +# /__) _ _ _ _ _/ _ +# / ( (- (/ (/ (- _) / _) +# / + +""" +Requests HTTP Library +~~~~~~~~~~~~~~~~~~~~~ + +Requests is an HTTP library, written in Python, for human beings. +Basic GET usage: + + >>> import requests + >>> r = requests.get('https://www.python.org') + >>> r.status_code + 200 + >>> b'Python is a programming language' in r.content + True + +... or POST: + + >>> payload = dict(key1='value1', key2='value2') + >>> r = requests.post('https://httpbin.org/post', data=payload) + >>> print(r.text) + { + ... + "form": { + "key1": "value1", + "key2": "value2" + }, + ... + } + +The other HTTP methods are supported - see `requests.api`. Full documentation +is at . + +:copyright: (c) 2017 by Kenneth Reitz. +:license: Apache 2.0, see LICENSE for more details. +""" + +from __future__ import annotations + +import warnings + +import urllib3 + +from .exceptions import RequestsDependencyWarning + +try: + from charset_normalizer import __version__ as charset_normalizer_version +except ImportError: + charset_normalizer_version = None + +try: + from chardet import __version__ as chardet_version # type: ignore[import-not-found] +except ImportError: + chardet_version = None + + +def check_compatibility( + urllib3_version: str, + chardet_version: str | None, + charset_normalizer_version: str | None, +) -> None: + urllib3_version_list = urllib3_version.split(".")[:3] + assert urllib3_version_list != ["dev"] # Verify urllib3 isn't installed from git. + + # Sometimes, urllib3 only reports its version as 16.1. + if len(urllib3_version_list) == 2: + urllib3_version_list.append("0") + + # Check urllib3 for compatibility. + major, minor, patch = urllib3_version_list # noqa: F811 + major, minor, patch = int(major), int(minor), int(patch) + # urllib3 >= 1.21.1 + assert major >= 1 + if major == 1: + assert minor >= 21 + + # Check charset_normalizer for compatibility. + if chardet_version: + major, minor, patch = chardet_version.split(".")[:3] + major, minor, patch = int(major), int(minor), int(patch) + # chardet_version >= 3.0.2, < 8.0.0 + assert (3, 0, 2) <= (major, minor, patch) < (8, 0, 0) + elif charset_normalizer_version: + major, minor, patch = charset_normalizer_version.split(".")[:3] + major, minor, patch = int(major), int(minor), int(patch) + # charset_normalizer >= 2.0.0 < 4.0.0 + assert (2, 0, 0) <= (major, minor, patch) < (4, 0, 0) + else: + warnings.warn( + "Unable to find acceptable character detection dependency " + "(chardet or charset_normalizer).", + RequestsDependencyWarning, + ) + + +def _check_cryptography(cryptography_version: str) -> None: + # cryptography < 1.3.4 + try: + cryptography_version_list = list(map(int, cryptography_version.split("."))) + except ValueError: + return + + if cryptography_version_list < [1, 3, 4]: + warning = f"Old version of cryptography ({cryptography_version_list}) may cause slowdown." + warnings.warn(warning, RequestsDependencyWarning) + + +# Check imported dependencies for compatibility. +try: + check_compatibility( + urllib3.__version__, # type: ignore[reportPrivateImportUsage] + chardet_version, # type: ignore[reportUnknownArgumentType] + charset_normalizer_version, + ) +except (AssertionError, ValueError): + warnings.warn( + f"urllib3 ({urllib3.__version__}) or chardet " # type: ignore[reportPrivateImportUsage] + f"({chardet_version})/charset_normalizer ({charset_normalizer_version}) " + "doesn't match a supported version!", + RequestsDependencyWarning, + ) + +# Attempt to enable urllib3's fallback for SNI support +# if the standard library doesn't support SNI or the +# 'ssl' library isn't available. +try: + try: + import ssl + except ImportError: + ssl = None + + if not getattr(ssl, "HAS_SNI", False): + from urllib3.contrib import pyopenssl + + pyopenssl.inject_into_urllib3() + + # Check cryptography version + from cryptography import ( # type: ignore[reportMissingImports] + __version__ as cryptography_version, # type: ignore[reportUnknownVariableType] + ) + + _check_cryptography(cryptography_version) # type: ignore[reportUnknownArgumentType] +except ImportError: + pass + +# urllib3's DependencyWarnings should be silenced. +from urllib3.exceptions import DependencyWarning + +warnings.simplefilter("ignore", DependencyWarning) + +# Set default logging handler to avoid "No handler found" warnings. +import logging +from logging import NullHandler + +from . import packages, utils +from .__version__ import ( + __author__, + __author_email__, + __build__, + __cake__, + __copyright__, + __description__, + __license__, + __title__, + __url__, + __version__, +) +from .api import delete, get, head, options, patch, post, put, request +from .exceptions import ( + ConnectionError, + ConnectTimeout, + FileModeWarning, + HTTPError, + JSONDecodeError, + ReadTimeout, + RequestException, + Timeout, + TooManyRedirects, + URLRequired, +) +from .models import PreparedRequest, Request, Response +from .sessions import Session, session +from .status_codes import codes + +__all__ = ( + "ConnectionError", + "ConnectTimeout", + "HTTPError", + "JSONDecodeError", + "PreparedRequest", + "ReadTimeout", + "Request", + "RequestException", + "Response", + "Session", + "Timeout", + "TooManyRedirects", + "URLRequired", + "codes", + "delete", + "get", + "head", + "options", + "packages", + "patch", + "post", + "put", + "request", + "session", + "utils", +) + +logging.getLogger(__name__).addHandler(NullHandler()) + +# FileModeWarnings go off per the default. +warnings.simplefilter("default", FileModeWarning, append=True) diff --git a/.venv/lib/python3.12/site-packages/requests/__pycache__/__init__.cpython-312.pyc b/.venv/lib/python3.12/site-packages/requests/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b8a855745fbb4a7e92d0e122c280bc438ae19d24 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/requests/__pycache__/__init__.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/requests/__pycache__/__version__.cpython-312.pyc b/.venv/lib/python3.12/site-packages/requests/__pycache__/__version__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6b3fe6e7a3609cc8e65305cec5752a652d82acbc Binary files /dev/null and b/.venv/lib/python3.12/site-packages/requests/__pycache__/__version__.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/requests/__pycache__/_internal_utils.cpython-312.pyc b/.venv/lib/python3.12/site-packages/requests/__pycache__/_internal_utils.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c1919604cab4af279954255df44f363e8f57be26 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/requests/__pycache__/_internal_utils.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/requests/__pycache__/_types.cpython-312.pyc b/.venv/lib/python3.12/site-packages/requests/__pycache__/_types.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b12684a2bd2bd7f666aded3a7a42b96b2f4226c9 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/requests/__pycache__/_types.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/requests/__pycache__/adapters.cpython-312.pyc b/.venv/lib/python3.12/site-packages/requests/__pycache__/adapters.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3601d71dbed2ac9c0d25dee891085279da9274ca Binary files /dev/null and b/.venv/lib/python3.12/site-packages/requests/__pycache__/adapters.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/requests/__pycache__/api.cpython-312.pyc b/.venv/lib/python3.12/site-packages/requests/__pycache__/api.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..843537b4e88b439f542688a49592f172c3dbe0e1 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/requests/__pycache__/api.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/requests/__pycache__/auth.cpython-312.pyc b/.venv/lib/python3.12/site-packages/requests/__pycache__/auth.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5617f233f5b0971218de87f0aa4c602cad39d4ba Binary files /dev/null and b/.venv/lib/python3.12/site-packages/requests/__pycache__/auth.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/requests/__pycache__/certs.cpython-312.pyc b/.venv/lib/python3.12/site-packages/requests/__pycache__/certs.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..89cfa9f4cf424b8cf4f7bd52f39805d28a4c44e9 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/requests/__pycache__/certs.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/requests/__pycache__/compat.cpython-312.pyc b/.venv/lib/python3.12/site-packages/requests/__pycache__/compat.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..341e00d9ddcd33804b6ada6d279a6456e97bc9c3 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/requests/__pycache__/compat.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/requests/__pycache__/cookies.cpython-312.pyc b/.venv/lib/python3.12/site-packages/requests/__pycache__/cookies.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..90a71ad8baa909a7b7ce5e8b1fb73637e813c236 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/requests/__pycache__/cookies.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/requests/__pycache__/exceptions.cpython-312.pyc b/.venv/lib/python3.12/site-packages/requests/__pycache__/exceptions.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..984297c70d452631220943cf12f9e223849a6a63 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/requests/__pycache__/exceptions.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/requests/__pycache__/hooks.cpython-312.pyc b/.venv/lib/python3.12/site-packages/requests/__pycache__/hooks.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..836dc19a93cce669e36bca61892e5cd6079a5d2a Binary files /dev/null and b/.venv/lib/python3.12/site-packages/requests/__pycache__/hooks.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/requests/__pycache__/models.cpython-312.pyc b/.venv/lib/python3.12/site-packages/requests/__pycache__/models.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6881c9aba5eea8f3f2c594170a9469e92f6c3b0f Binary files /dev/null and b/.venv/lib/python3.12/site-packages/requests/__pycache__/models.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/requests/__pycache__/packages.cpython-312.pyc b/.venv/lib/python3.12/site-packages/requests/__pycache__/packages.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6d9c90001117a42788b56203379cbc71a57d8394 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/requests/__pycache__/packages.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/requests/__pycache__/sessions.cpython-312.pyc b/.venv/lib/python3.12/site-packages/requests/__pycache__/sessions.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..319d45ffce078f71cd2bb04bdd9699458c63a13c Binary files /dev/null and b/.venv/lib/python3.12/site-packages/requests/__pycache__/sessions.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/requests/__pycache__/status_codes.cpython-312.pyc b/.venv/lib/python3.12/site-packages/requests/__pycache__/status_codes.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d99129a8e73d54a35b89cefd875f1dc3cdea953a Binary files /dev/null and b/.venv/lib/python3.12/site-packages/requests/__pycache__/status_codes.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/requests/__pycache__/structures.cpython-312.pyc b/.venv/lib/python3.12/site-packages/requests/__pycache__/structures.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5f42d71bb48b87f92bb5f3346e33a73f4ea01e2a Binary files /dev/null and b/.venv/lib/python3.12/site-packages/requests/__pycache__/structures.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/requests/__pycache__/utils.cpython-312.pyc b/.venv/lib/python3.12/site-packages/requests/__pycache__/utils.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..32248d599bd51b580650c989eff8623ee65cf7ed Binary files /dev/null and b/.venv/lib/python3.12/site-packages/requests/__pycache__/utils.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/requests/__version__.py b/.venv/lib/python3.12/site-packages/requests/__version__.py new file mode 100644 index 0000000000000000000000000000000000000000..fea814e58271ecb7a1088ce9ac636791a2cc1289 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/requests/__version__.py @@ -0,0 +1,14 @@ +# .-. .-. .-. . . .-. .-. .-. .-. +# |( |- |.| | | |- `-. | `-. +# ' ' `-' `-`.`-' `-' `-' ' `-' + +__title__ = "requests" +__description__ = "Python HTTP for Humans." +__url__ = "https://requests.readthedocs.io" +__version__ = "2.34.2" +__build__ = 0x023402 +__author__ = "Kenneth Reitz" +__author_email__ = "me@kennethreitz.org" +__license__ = "Apache-2.0" +__copyright__ = "Copyright Kenneth Reitz" +__cake__ = "\u2728 \U0001f370 \u2728" diff --git a/.venv/lib/python3.12/site-packages/requests/_internal_utils.py b/.venv/lib/python3.12/site-packages/requests/_internal_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..0466a7d347db4ed34a37db51b75fc8e80bc06055 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/requests/_internal_utils.py @@ -0,0 +1,51 @@ +""" +requests._internal_utils +~~~~~~~~~~~~~~ + +Provides utility functions that are consumed internally by Requests +which depend on extremely few external helpers (such as compat) +""" + +import re + +from .compat import builtin_str + +_VALID_HEADER_NAME_RE_BYTE = re.compile(rb"^[^:\s][^:\r\n]*\Z") +_VALID_HEADER_NAME_RE_STR = re.compile(r"^[^:\s][^:\r\n]*\Z") +_VALID_HEADER_VALUE_RE_BYTE = re.compile(rb"^\S[^\r\n]*\Z|^\Z") +_VALID_HEADER_VALUE_RE_STR = re.compile(r"^\S[^\r\n]*\Z|^\Z") + +_HEADER_VALIDATORS_STR = (_VALID_HEADER_NAME_RE_STR, _VALID_HEADER_VALUE_RE_STR) +_HEADER_VALIDATORS_BYTE = (_VALID_HEADER_NAME_RE_BYTE, _VALID_HEADER_VALUE_RE_BYTE) +HEADER_VALIDATORS = { + bytes: _HEADER_VALIDATORS_BYTE, + str: _HEADER_VALIDATORS_STR, +} + + +def to_native_string(string: str | bytes, encoding: str = "ascii") -> str: + """Given a string object, regardless of type, returns a representation of + that string in the native string type, encoding and decoding where + necessary. This assumes ASCII unless told otherwise. + """ + if isinstance(string, builtin_str): + out = string + else: + out = string.decode(encoding) + + return out + + +def unicode_is_ascii(u_string: str) -> bool: + """Determine if unicode string only contains ASCII characters. + + :param str u_string: unicode string to check. Must be unicode + and not Python 2 `str`. + :rtype: bool + """ + assert isinstance(u_string, str) + try: + u_string.encode("ascii") + return True + except UnicodeEncodeError: + return False diff --git a/.venv/lib/python3.12/site-packages/requests/_types.py b/.venv/lib/python3.12/site-packages/requests/_types.py new file mode 100644 index 0000000000000000000000000000000000000000..b2273d612b17726609afb45a29058625b79eae60 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/requests/_types.py @@ -0,0 +1,183 @@ +""" +requests._types +~~~~~~~~~~~~~~~ + +This module contains type aliases used internally by the Requests library. +These types are not part of the public API and must not be relied upon +by external code. +""" + +from __future__ import annotations + +from collections.abc import Callable, Iterable, Mapping, MutableMapping, Sequence +from typing import ( + TYPE_CHECKING, + Any, + Protocol, + TypeAlias, + TypeVar, + runtime_checkable, +) + +_T_co = TypeVar("_T_co", covariant=True) +_KT_co = TypeVar("_KT_co", covariant=True) +_VT_co = TypeVar("_VT_co", covariant=True) + + +@runtime_checkable +class SupportsRead(Protocol[_T_co]): + def read(self, length: int = ..., /) -> _T_co: ... + + +@runtime_checkable +class SupportsItems(Protocol[_KT_co, _VT_co]): + def items(self) -> Iterable[tuple[_KT_co, _VT_co]]: ... + + +# These are needed at runtime for default_hooks() return type +HookType: TypeAlias = Callable[["Response"], Any] +HooksInputType: TypeAlias = Mapping[str, Iterable[HookType] | HookType] + + +def is_prepared(request: PreparedRequest) -> TypeIs[_ValidatedRequest]: + """Verify a PreparedRequest has been fully prepared.""" + if TYPE_CHECKING: + return request.url is not None and request.method is not None + # noop at runtime to avoid AssertionError + return True + + +if TYPE_CHECKING: + from http.cookiejar import CookieJar + from typing import TypeAlias, TypedDict + + from typing_extensions import ( + Buffer, # TODO: move to collections.abc when Python >= 3.12 + TypeIs, # TODO: move to typing when Python >= 3.13 + ) + + from .auth import AuthBase + from .cookies import RequestsCookieJar + from .models import PreparedRequest, Response + from .structures import CaseInsensitiveDict + + class _ValidatedRequest(PreparedRequest): + """Subtype asserting a PreparedRequest has been fully prepared before calling. + + The override suppression is required because mutable attribute types are + invariant (Liskov), but we only narrow after preparation is complete. This + is the explicit contract for Requests but Python's typing doesn't have a + better way to represent the requirement. + """ + + url: str # type: ignore[reportIncompatibleVariableOverride] + method: str # type: ignore[reportIncompatibleVariableOverride] + + # Type aliases for core API concepts (ordered by request() signature) + UriType: TypeAlias = str | bytes + + _ParamsMappingKeyType: TypeAlias = str | bytes | int | float + _ParamsMappingValueType: TypeAlias = ( + str | bytes | int | float | Iterable[str | bytes | int | float] | None + ) + ParamsType: TypeAlias = ( + SupportsItems[_ParamsMappingKeyType, _ParamsMappingValueType] + | tuple[tuple[_ParamsMappingKeyType, _ParamsMappingValueType], ...] + | Iterable[tuple[_ParamsMappingKeyType, _ParamsMappingValueType]] + | str + | bytes + | None + ) + + KVDataType: TypeAlias = Iterable[tuple[Any, Any]] | SupportsItems[Any, Any] + + RawDataType: TypeAlias = KVDataType | str | bytes + StreamDataType: TypeAlias = SupportsRead[str | bytes] + EncodableDataType: TypeAlias = RawDataType | StreamDataType + + DataType: TypeAlias = ( + KVDataType + | Iterable[bytes | str] + | str + | bytes + | Buffer + | SupportsRead[str | bytes] + | None + ) + + BodyType: TypeAlias = ( + bytes | str | Iterable[bytes | str] | SupportsRead[bytes | str] | None + ) + + HeadersType: TypeAlias = Mapping[str, str | bytes] | None + + CookiesType: TypeAlias = RequestsCookieJar | Mapping[str, str] + + # Building blocks for FilesType + _FileName: TypeAlias = str | None + _FileContent: TypeAlias = SupportsRead[str | bytes] | str | bytes + _FileSpecBasic: TypeAlias = tuple[_FileName, _FileContent] + _FileSpecWithContentType: TypeAlias = tuple[_FileName, _FileContent, str] + _FileSpecWithHeaders: TypeAlias = tuple[ + _FileName, _FileContent, str, CaseInsensitiveDict[str] | Mapping[str, str] + ] + _FileSpec: TypeAlias = ( + _FileContent | _FileSpecBasic | _FileSpecWithContentType | _FileSpecWithHeaders + ) + FilesType: TypeAlias = ( + Mapping[str, _FileSpec] | Iterable[tuple[str, _FileSpec]] | None + ) + + AuthType: TypeAlias = ( + tuple[str, str] | AuthBase | Callable[[PreparedRequest], PreparedRequest] | None + ) + + TimeoutType: TypeAlias = float | tuple[float | None, float | None] | None + ProxiesType: TypeAlias = MutableMapping[str, str] + HooksType: TypeAlias = dict[str, list[HookType]] | None + VerifyType: TypeAlias = bool | str + CertType: TypeAlias = str | tuple[str, str] | None + JsonType: TypeAlias = ( + None + | bool + | int + | float + | str + | Sequence["JsonType"] + | Mapping[str, "JsonType"] + ) + + # TypedDicts for Unpack kwargs (PEP 692) + + class BaseRequestKwargs(TypedDict, total=False): + headers: HeadersType + cookies: RequestsCookieJar | CookieJar | dict[str, str] | None + files: FilesType + auth: AuthType + timeout: TimeoutType + allow_redirects: bool + proxies: dict[str, str] | None + hooks: HooksInputType | None + stream: bool | None + verify: VerifyType | None + cert: CertType + + class RequestKwargs(BaseRequestKwargs, total=False): + """kwargs for request(), options(), head(), delete().""" + + params: ParamsType + data: DataType + json: JsonType + + class GetKwargs(BaseRequestKwargs, total=False): + data: DataType + json: JsonType + + class PostKwargs(BaseRequestKwargs, total=False): + params: ParamsType + + class DataKwargs(BaseRequestKwargs, total=False): + """kwargs for put(), patch().""" + + params: ParamsType + json: JsonType diff --git a/.venv/lib/python3.12/site-packages/requests/adapters.py b/.venv/lib/python3.12/site-packages/requests/adapters.py new file mode 100644 index 0000000000000000000000000000000000000000..40fe8a6d5a6168ba7303b91477af925db0aa3914 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/requests/adapters.py @@ -0,0 +1,748 @@ +""" +requests.adapters +~~~~~~~~~~~~~~~~~ + +This module contains the transport adapters that Requests uses to define +and maintain connections. +""" + +from __future__ import annotations + +import os.path +import socket # noqa: F401 # type: ignore[reportUnusedImport] +import typing +import warnings +from typing import Any + +from urllib3.exceptions import ( + ClosedPoolError, + ConnectTimeoutError, + LocationValueError, + MaxRetryError, + NewConnectionError, + ProtocolError, + ReadTimeoutError, + ResponseError, +) +from urllib3.exceptions import HTTPError as _HTTPError +from urllib3.exceptions import InvalidHeader as _InvalidHeader +from urllib3.exceptions import ProxyError as _ProxyError +from urllib3.exceptions import SSLError as _SSLError +from urllib3.poolmanager import PoolManager, proxy_from_url +from urllib3.util import Timeout as TimeoutSauce +from urllib3.util import parse_url +from urllib3.util.retry import Retry + +from .auth import _basic_auth_str # type: ignore[reportPrivateUsage] +from .compat import basestring, urlparse +from .cookies import extract_cookies_to_jar +from .exceptions import ( + ConnectionError, + ConnectTimeout, + InvalidHeader, + InvalidProxyURL, + InvalidSchema, + InvalidURL, + ProxyError, + ReadTimeout, + RetryError, + SSLError, +) +from .models import Response +from .structures import CaseInsensitiveDict +from .utils import ( + DEFAULT_CA_BUNDLE_PATH, + get_auth_from_url, + get_encoding_from_headers, + prepend_scheme_if_needed, + select_proxy, + urldefragauth, +) + +try: + from urllib3.contrib.socks import SOCKSProxyManager # type: ignore[assignment] +except ImportError: + + def SOCKSProxyManager(*args: Any, **kwargs: Any) -> None: + raise InvalidSchema("Missing dependencies for SOCKS support.") + + +if typing.TYPE_CHECKING: + from urllib3.connectionpool import HTTPConnectionPool + from urllib3.poolmanager import PoolManager as _PoolManager + + from . import _types as _t + from .models import PreparedRequest + +from ._types import is_prepared as _is_prepared + +DEFAULT_POOLBLOCK = False +DEFAULT_POOLSIZE = 10 +DEFAULT_RETRIES = 0 +DEFAULT_POOL_TIMEOUT = None + + +def _urllib3_request_context( + request: PreparedRequest, + verify: bool | str | None, + client_cert: tuple[str, str] | str | None, + poolmanager: PoolManager, +) -> tuple[dict[str, Any], dict[str, Any]]: + host_params: dict[str, Any] = {} + pool_kwargs: dict[str, Any] = {} + parsed_request_url = urlparse(request.url) + scheme = parsed_request_url.scheme.lower() + port = parsed_request_url.port + + cert_reqs = "CERT_REQUIRED" + if verify is False: + cert_reqs = "CERT_NONE" + elif isinstance(verify, str): + if not os.path.isdir(verify): + pool_kwargs["ca_certs"] = verify + else: + pool_kwargs["ca_cert_dir"] = verify + pool_kwargs["cert_reqs"] = cert_reqs + if client_cert is not None: + if isinstance(client_cert, tuple) and len(client_cert) == 2: + pool_kwargs["cert_file"] = client_cert[0] + pool_kwargs["key_file"] = client_cert[1] + else: + # According to our docs, we allow users to specify just the client + # cert path + pool_kwargs["cert_file"] = client_cert + host_params = { + "scheme": scheme, + "host": parsed_request_url.hostname, + "port": port, + } + return host_params, pool_kwargs + + +class BaseAdapter: + """The Base Transport Adapter""" + + def __init__(self) -> None: + super().__init__() + + def send( + self, + request: PreparedRequest, + stream: bool = False, + timeout: _t.TimeoutType = None, + verify: _t.VerifyType = True, + cert: _t.CertType = None, + proxies: dict[str, str] | None = None, + ) -> Response: + """Sends PreparedRequest object. Returns Response object. + + :param request: The :class:`PreparedRequest ` being sent. + :param stream: (optional) Whether to stream the request content. + :param timeout: (optional) How long to wait for the server to send + data before giving up, as a float, or a :ref:`(connect timeout, + read timeout) ` tuple. + :type timeout: float or tuple + :param verify: (optional) Either a boolean, in which case it controls whether we verify + the server's TLS certificate, or a string, in which case it must be a path + to a CA bundle to use + :param cert: (optional) Any user-provided SSL certificate to be trusted. + :param proxies: (optional) The proxies dictionary to apply to the request. + """ + raise NotImplementedError + + def close(self) -> None: + """Cleans up adapter specific items.""" + raise NotImplementedError + + +class HTTPAdapter(BaseAdapter): + """The built-in HTTP Adapter for urllib3. + + Provides a general-case interface for Requests sessions to contact HTTP and + HTTPS urls by implementing the Transport Adapter interface. This class will + usually be created by the :class:`Session ` class under the + covers. + + :param pool_connections: The number of urllib3 connection pools to cache. + :param pool_maxsize: The maximum number of connections to save in the pool. + :param max_retries: The maximum number of retries each connection + should attempt. Note, this applies only to failed DNS lookups, socket + connections and connection timeouts, never to requests where data has + made it to the server. By default, Requests does not retry failed + connections. If you need granular control over the conditions under + which we retry a request, import urllib3's ``Retry`` class and pass + that instead. + :param pool_block: Whether the connection pool should block for connections. + + Usage:: + + >>> import requests + >>> s = requests.Session() + >>> a = requests.adapters.HTTPAdapter(max_retries=3) + >>> s.mount('http://', a) + """ + + __attrs__: list[str] = [ + "max_retries", + "config", + "_pool_connections", + "_pool_maxsize", + "_pool_block", + ] + + max_retries: Retry + config: dict[str, Any] + proxy_manager: dict[str, Any] + _pool_connections: int + _pool_maxsize: int + _pool_block: bool + poolmanager: _PoolManager + + def __init__( + self, + pool_connections: int = DEFAULT_POOLSIZE, + pool_maxsize: int = DEFAULT_POOLSIZE, + max_retries: int | Retry = DEFAULT_RETRIES, + pool_block: bool = DEFAULT_POOLBLOCK, + ) -> None: + if max_retries == DEFAULT_RETRIES: + self.max_retries = Retry(0, read=False) + else: + self.max_retries = Retry.from_int(max_retries) + self.config = {} + self.proxy_manager = {} + + super().__init__() + + self._pool_connections = pool_connections + self._pool_maxsize = pool_maxsize + self._pool_block = pool_block + + self.init_poolmanager(pool_connections, pool_maxsize, block=pool_block) + + def __getstate__(self) -> dict[str, Any]: + return {attr: getattr(self, attr, None) for attr in self.__attrs__} + + def __setstate__(self, state: dict[str, Any]) -> None: + # Can't handle by adding 'proxy_manager' to self.__attrs__ because + # self.poolmanager uses a lambda function, which isn't pickleable. + self.proxy_manager = {} + self.config = {} + + for attr, value in state.items(): + setattr(self, attr, value) + + self.init_poolmanager( + self._pool_connections, self._pool_maxsize, block=self._pool_block + ) + + def init_poolmanager( + self, + connections: int, + maxsize: int, + block: bool = DEFAULT_POOLBLOCK, + **pool_kwargs: Any, + ) -> None: + """Initializes a urllib3 PoolManager. + + This method should not be called from user code, and is only + exposed for use when subclassing the + :class:`HTTPAdapter `. + + :param connections: The number of urllib3 connection pools to cache. + :param maxsize: The maximum number of connections to save in the pool. + :param block: Block when no free connections are available. + :param pool_kwargs: Extra keyword arguments used to initialize the Pool Manager. + """ + # save these values for pickling + self._pool_connections = connections + self._pool_maxsize = maxsize + self._pool_block = block + + self.poolmanager = PoolManager( + num_pools=connections, + maxsize=maxsize, + block=block, + **pool_kwargs, + ) + + def proxy_manager_for(self, proxy: str, **proxy_kwargs: Any) -> Any: + """Return urllib3 ProxyManager for the given proxy. + + This method should not be called from user code, and is only + exposed for use when subclassing the + :class:`HTTPAdapter `. + + :param proxy: The proxy to return a urllib3 ProxyManager for. + :param proxy_kwargs: Extra keyword arguments used to configure the Proxy Manager. + :returns: ProxyManager + :rtype: urllib3.ProxyManager + """ + if proxy in self.proxy_manager: + manager = self.proxy_manager[proxy] + elif proxy.lower().startswith("socks"): + username, password = get_auth_from_url(proxy) + manager = self.proxy_manager[proxy] = SOCKSProxyManager( + proxy, + username=username, + password=password, + num_pools=self._pool_connections, + maxsize=self._pool_maxsize, + block=self._pool_block, + **proxy_kwargs, + ) + else: + proxy_headers = self.proxy_headers(proxy) + manager = self.proxy_manager[proxy] = proxy_from_url( + proxy, + proxy_headers=proxy_headers, + num_pools=self._pool_connections, + maxsize=self._pool_maxsize, + block=self._pool_block, + **proxy_kwargs, + ) + + return manager + + def cert_verify( + self, conn: Any, url: str, verify: _t.VerifyType, cert: _t.CertType + ) -> None: + """Verify a SSL certificate. This method should not be called from user + code, and is only exposed for use when subclassing the + :class:`HTTPAdapter `. + + :param conn: The urllib3 connection object associated with the cert. + :param url: The requested URL. + :param verify: Either a boolean, in which case it controls whether we verify + the server's TLS certificate, or a string, in which case it must be a path + to a CA bundle to use + :param cert: The SSL certificate to verify. + """ + if url.lower().startswith("https") and verify: + cert_loc = None + + # Allow self-specified cert location. + if verify is not True: + cert_loc = verify + + if not cert_loc: + cert_loc = DEFAULT_CA_BUNDLE_PATH + + if not cert_loc or not os.path.exists(cert_loc): + raise OSError( + f"Could not find a suitable TLS CA certificate bundle, " + f"invalid path: {cert_loc}" + ) + + conn.cert_reqs = "CERT_REQUIRED" + + if not os.path.isdir(cert_loc): + conn.ca_certs = cert_loc + else: + conn.ca_cert_dir = cert_loc + else: + conn.cert_reqs = "CERT_NONE" + conn.ca_certs = None + conn.ca_cert_dir = None + + if cert: + if not isinstance(cert, basestring): + conn.cert_file = cert[0] + conn.key_file = cert[1] + else: + conn.cert_file = cert + conn.key_file = None + if conn.cert_file and not os.path.exists(conn.cert_file): + raise OSError( + f"Could not find the TLS certificate file, " + f"invalid path: {conn.cert_file}" + ) + if conn.key_file and not os.path.exists(conn.key_file): + raise OSError( + f"Could not find the TLS key file, invalid path: {conn.key_file}" + ) + + def build_response(self, req: PreparedRequest, resp: Any) -> Response: + """Builds a :class:`Response ` object from a urllib3 + response. This should not be called from user code, and is only exposed + for use when subclassing the + :class:`HTTPAdapter ` + + :param req: The :class:`PreparedRequest ` used to generate the response. + :param resp: The urllib3 response object. + :rtype: requests.Response + """ + assert _is_prepared(req) + response = Response() + + # Fallback to None if there's no status_code, for whatever reason. + response.status_code = getattr(resp, "status", None) # type: ignore[assignment] + + # Make headers case-insensitive. + response.headers = CaseInsensitiveDict(getattr(resp, "headers", {})) + + # Set encoding. + response.encoding = get_encoding_from_headers(response.headers) + response.raw = resp + response.reason = response.raw.reason + + if isinstance(req.url, bytes): + response.url = req.url.decode("utf-8") + else: + response.url = req.url + + # Add new cookies from the server. + extract_cookies_to_jar(response.cookies, req, resp) + + # Give the Response some context. + response.request = req + response.connection = self + + return response + + def build_connection_pool_key_attributes( + self, request: PreparedRequest, verify: _t.VerifyType, cert: _t.CertType = None + ) -> tuple[dict[str, Any], dict[str, Any]]: + """Build the PoolKey attributes used by urllib3 to return a connection. + + This looks at the PreparedRequest, the user-specified verify value, + and the value of the cert parameter to determine what PoolKey values + to use to select a connection from a given urllib3 Connection Pool. + + The SSL related pool key arguments are not consistently set. As of + this writing, use the following to determine what keys may be in that + dictionary: + + * If ``verify`` is ``True``, ``"ssl_context"`` will be set and will be the + default Requests SSL Context + * If ``verify`` is ``False``, ``"ssl_context"`` will not be set but + ``"cert_reqs"`` will be set + * If ``verify`` is a string, (i.e., it is a user-specified trust bundle) + ``"ca_certs"`` will be set if the string is not a directory recognized + by :py:func:`os.path.isdir`, otherwise ``"ca_cert_dir"`` will be + set. + * If ``"cert"`` is specified, ``"cert_file"`` will always be set. If + ``"cert"`` is a tuple with a second item, ``"key_file"`` will also + be present + + To override these settings, one may subclass this class, call this + method and use the above logic to change parameters as desired. For + example, if one wishes to use a custom :py:class:`ssl.SSLContext` one + must both set ``"ssl_context"`` and based on what else they require, + alter the other keys to ensure the desired behaviour. + + :param request: + The PreparedRequest being sent over the connection. + :type request: + :class:`~requests.models.PreparedRequest` + :param verify: + Either a boolean, in which case it controls whether + we verify the server's TLS certificate, or a string, in which case it + must be a path to a CA bundle to use. + :param cert: + (optional) Any user-provided SSL certificate for client + authentication (a.k.a., mTLS). This may be a string (i.e., just + the path to a file which holds both certificate and key) or a + tuple of length 2 with the certificate file path and key file + path. + :returns: + A tuple of two dictionaries. The first is the "host parameters" + portion of the Pool Key including scheme, hostname, and port. The + second is a dictionary of SSLContext related parameters. + """ + return _urllib3_request_context(request, verify, cert, self.poolmanager) + + def get_connection_with_tls_context( + self, + request: PreparedRequest, + verify: _t.VerifyType, + proxies: dict[str, str] | None = None, + cert: _t.CertType = None, + ) -> HTTPConnectionPool: + """Returns a urllib3 connection for the given request and TLS settings. + This should not be called from user code, and is only exposed for use + when subclassing the :class:`HTTPAdapter `. + + :param request: + The :class:`PreparedRequest ` object to be sent + over the connection. + :param verify: + Either a boolean, in which case it controls whether we verify the + server's TLS certificate, or a string, in which case it must be a + path to a CA bundle to use. + :param proxies: + (optional) The proxies dictionary to apply to the request. + :param cert: + (optional) Any user-provided SSL certificate to be used for client + authentication (a.k.a., mTLS). + :rtype: + urllib3.HTTPConnectionPool + """ + assert _is_prepared(request) + + proxy = select_proxy(request.url, proxies) + try: + host_params, pool_kwargs = self.build_connection_pool_key_attributes( + request, + verify, + cert, + ) + except ValueError as e: + raise InvalidURL(e, request=request) + if proxy: + proxy = prepend_scheme_if_needed(proxy, "http") + proxy_url = parse_url(proxy) + if not proxy_url.host: + raise InvalidProxyURL( + "Please check proxy URL. It is malformed " + "and could be missing the host." + ) + proxy_manager = self.proxy_manager_for(proxy) + conn = proxy_manager.connection_from_host( + **host_params, pool_kwargs=pool_kwargs + ) + else: + # Only scheme should be lower case + conn = self.poolmanager.connection_from_host( + **host_params, pool_kwargs=pool_kwargs + ) + + return conn + + def get_connection( + self, url: str, proxies: dict[str, str] | None = None + ) -> HTTPConnectionPool: + """DEPRECATED: Users should move to `get_connection_with_tls_context` + for all subclasses of HTTPAdapter using Requests>=2.32.2. + + Returns a urllib3 connection for the given URL. This should not be + called from user code, and is only exposed for use when subclassing the + :class:`HTTPAdapter `. + + :param url: The URL to connect to. + :param proxies: (optional) A Requests-style dictionary of proxies used on this request. + :rtype: urllib3.HTTPConnectionPool + """ + warnings.warn( + ( + "`get_connection` has been deprecated in favor of " + "`get_connection_with_tls_context`. Custom HTTPAdapter subclasses " + "will need to migrate for Requests>=2.32.2. Please see " + "https://github.com/psf/requests/pull/6710 for more details." + ), + DeprecationWarning, + ) + proxy = select_proxy(url, proxies) + + if proxy: + proxy = prepend_scheme_if_needed(proxy, "http") + proxy_url = parse_url(proxy) + if not proxy_url.host: + raise InvalidProxyURL( + "Please check proxy URL. It is malformed " + "and could be missing the host." + ) + proxy_manager = self.proxy_manager_for(proxy) + conn = proxy_manager.connection_from_url(url) + else: + # Only scheme should be lower case + parsed = urlparse(url) + url = parsed.geturl() + conn = self.poolmanager.connection_from_url(url) + + return conn + + def close(self) -> None: + """Disposes of any internal state. + + Currently, this closes the PoolManager and any active ProxyManager, + which closes any pooled connections. + """ + self.poolmanager.clear() + for proxy in self.proxy_manager.values(): + proxy.clear() + + def request_url( + self, request: PreparedRequest, proxies: dict[str, str] | None + ) -> str: + """Obtain the url to use when making the final request. + + If the message is being sent through a HTTP proxy, the full URL has to + be used. Otherwise, we should only use the path portion of the URL. + + This should not be called from user code, and is only exposed for use + when subclassing the + :class:`HTTPAdapter `. + + :param request: The :class:`PreparedRequest ` being sent. + :param proxies: A dictionary of schemes or schemes and hosts to proxy URLs. + :rtype: str + """ + assert _is_prepared(request) + + proxy = select_proxy(request.url, proxies) + scheme = urlparse(request.url).scheme + + is_proxied_http_request = proxy and scheme != "https" + using_socks_proxy = False + if proxy: + proxy_scheme = urlparse(proxy).scheme.lower() + using_socks_proxy = proxy_scheme.startswith("socks") + + url = request.path_url + + if is_proxied_http_request and not using_socks_proxy: + url = urldefragauth(request.url) + + return url + + def add_headers(self, request: PreparedRequest, **kwargs: Any) -> None: + """Add any headers needed by the connection. As of v2.0 this does + nothing by default, but is left for overriding by users that subclass + the :class:`HTTPAdapter `. + + This should not be called from user code, and is only exposed for use + when subclassing the + :class:`HTTPAdapter `. + + :param request: The :class:`PreparedRequest ` to add headers to. + :param kwargs: The keyword arguments from the call to send(). + """ + pass + + def proxy_headers(self, proxy: str) -> dict[str, str]: + """Returns a dictionary of the headers to add to any request sent + through a proxy. This works with urllib3 magic to ensure that they are + correctly sent to the proxy, rather than in a tunnelled request if + CONNECT is being used. + + This should not be called from user code, and is only exposed for use + when subclassing the + :class:`HTTPAdapter `. + + :param proxy: The url of the proxy being used for this request. + :rtype: dict + """ + headers: dict[str, str] = {} + username, password = get_auth_from_url(proxy) + + if username: + headers["Proxy-Authorization"] = _basic_auth_str(username, password) + + return headers + + def send( + self, + request: PreparedRequest, + stream: bool = False, + timeout: _t.TimeoutType = None, + verify: _t.VerifyType = True, + cert: _t.CertType = None, + proxies: dict[str, str] | None = None, + ) -> Response: + """Sends PreparedRequest object. Returns Response object. + + :param request: The :class:`PreparedRequest ` being sent. + :param stream: (optional) Whether to stream the request content. + :param timeout: (optional) How long to wait for the server to send + data before giving up, as a float, or a :ref:`(connect timeout, + read timeout) ` tuple. + :type timeout: float or tuple or urllib3 Timeout object + :param verify: (optional) Either a boolean, in which case it controls whether + we verify the server's TLS certificate, or a string, in which case it + must be a path to a CA bundle to use + :param cert: (optional) Any user-provided SSL certificate to be trusted. + :param proxies: (optional) The proxies dictionary to apply to the request. + :rtype: requests.Response + """ + + assert _is_prepared(request) + + try: + conn = self.get_connection_with_tls_context( + request, verify, proxies=proxies, cert=cert + ) + except LocationValueError as e: + raise InvalidURL(e, request=request) + + self.cert_verify(conn, request.url, verify, cert) + url = self.request_url(request, proxies) + self.add_headers( + request, + stream=stream, + timeout=timeout, + verify=verify, + cert=cert, + proxies=proxies, + ) + + chunked = not (request.body is None or "Content-Length" in request.headers) + + if isinstance(timeout, tuple): + try: + connect, read = timeout + resolved_timeout = TimeoutSauce(connect=connect, read=read) + except ValueError: + raise ValueError( + f"Invalid timeout {timeout}. Pass a (connect, read) timeout tuple, " + f"or a single float to set both timeouts to the same value." + ) + elif isinstance(timeout, TimeoutSauce): + resolved_timeout = timeout + else: + resolved_timeout = TimeoutSauce(connect=timeout, read=timeout) + + try: + resp = conn.urlopen( + method=request.method, + url=url, + body=request.body, # type: ignore[arg-type] # urllib3 stubs don't accept Iterable[bytes | str] + headers=request.headers, # type: ignore[arg-type] # urllib3#3072 + redirect=False, + assert_same_host=False, + preload_content=False, + decode_content=False, + retries=self.max_retries, + timeout=resolved_timeout, + chunked=chunked, + ) + + except (ProtocolError, OSError) as err: + raise ConnectionError(err, request=request) + + except MaxRetryError as e: + if isinstance(e.reason, ConnectTimeoutError): + # TODO: Remove this in 3.0.0: see #2811 + if not isinstance(e.reason, NewConnectionError): + raise ConnectTimeout(e, request=request) + + if isinstance(e.reason, ResponseError): + raise RetryError(e, request=request) + + if isinstance(e.reason, _ProxyError): + raise ProxyError(e, request=request) + + if isinstance(e.reason, _SSLError): + # This branch is for urllib3 v1.22 and later. + raise SSLError(e, request=request) + + raise ConnectionError(e, request=request) + + except ClosedPoolError as e: + raise ConnectionError(e, request=request) + + except _ProxyError as e: + raise ProxyError(e) + + except (_SSLError, _HTTPError) as e: + if isinstance(e, _SSLError): + # This branch is for urllib3 versions earlier than v1.22 + raise SSLError(e, request=request) + elif isinstance(e, ReadTimeoutError): + raise ReadTimeout(e, request=request) + elif isinstance(e, _InvalidHeader): + raise InvalidHeader(e, request=request) + else: + raise + + return self.build_response(request, resp) diff --git a/.venv/lib/python3.12/site-packages/requests/api.py b/.venv/lib/python3.12/site-packages/requests/api.py new file mode 100644 index 0000000000000000000000000000000000000000..eeb3b54d7f27e2c843080dfe81dfdb0d460c2b31 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/requests/api.py @@ -0,0 +1,180 @@ +""" +requests.api +~~~~~~~~~~~~ + +This module implements the Requests API. + +:copyright: (c) 2012 by Kenneth Reitz. +:license: Apache2, see LICENSE for more details. +""" + +from __future__ import annotations + +from typing import TYPE_CHECKING + +from . import sessions +from .models import Response + +if TYPE_CHECKING: + from typing_extensions import Unpack + + from . import _types as _t + + +def request( + method: str, url: _t.UriType, **kwargs: Unpack[_t.RequestKwargs] +) -> Response: + """Constructs and sends a :class:`Request `. + + :param method: method for the new :class:`Request` object: ``GET``, ``OPTIONS``, ``HEAD``, ``POST``, ``PUT``, ``PATCH``, or ``DELETE``. + :param url: URL for the new :class:`Request` object. + :param params: (optional) Dictionary, list of tuples or bytes to send + in the query string for the :class:`Request`. + :param data: (optional) Dictionary, list of tuples, bytes, or file-like + object to send in the body of the :class:`Request`. + :param json: (optional) A JSON serializable Python object to send in the body of the :class:`Request`. + :param headers: (optional) Dictionary of HTTP Headers to send with the :class:`Request`. + :param cookies: (optional) Dict or CookieJar object to send with the :class:`Request`. + :param files: (optional) Dictionary of ``'name': file-like-objects`` (or ``{'name': file-tuple}``) for multipart encoding upload. + ``file-tuple`` can be a 2-tuple ``('filename', fileobj)``, 3-tuple ``('filename', fileobj, 'content_type')`` + or a 4-tuple ``('filename', fileobj, 'content_type', custom_headers)``, where ``'content_type'`` is a string + defining the content type of the given file and ``custom_headers`` a dict-like object containing additional headers + to add for the file. + :param auth: (optional) Auth tuple to enable Basic/Digest/Custom HTTP Auth. + :param timeout: (optional) How many seconds to wait for the server to send data + before giving up, as a float, or a :ref:`(connect timeout, read + timeout) ` tuple. + :type timeout: float or tuple + :param allow_redirects: (optional) Boolean. Enable/disable GET/OPTIONS/POST/PUT/PATCH/DELETE/HEAD redirection. Defaults to ``True``. + :type allow_redirects: bool + :param proxies: (optional) Dictionary mapping protocol to the URL of the proxy. + :param verify: (optional) Either a boolean, in which case it controls whether we verify + the server's TLS certificate, or a string, in which case it must be a path + to a CA bundle to use. Defaults to ``True``. + :param stream: (optional) if ``False``, the response content will be immediately downloaded. + :param cert: (optional) if String, path to ssl client cert file (.pem). If Tuple, ('cert', 'key') pair. + :return: :class:`Response ` object + :rtype: requests.Response + + Usage:: + + >>> import requests + >>> req = requests.request('GET', 'https://httpbin.org/get') + >>> req + + """ + + # By using the 'with' statement we are sure the session is closed, thus we + # avoid leaving sockets open which can trigger a ResourceWarning in some + # cases, and look like a memory leak in others. + with sessions.Session() as session: + return session.request(method=method, url=url, **kwargs) + + +def get( + url: _t.UriType, params: _t.ParamsType = None, **kwargs: Unpack[_t.GetKwargs] +) -> Response: + r"""Sends a GET request. + + :param url: URL for the new :class:`Request` object. + :param params: (optional) Dictionary, list of tuples or bytes to send + in the query string for the :class:`Request`. + :param \*\*kwargs: Optional arguments that ``request`` takes. + :return: :class:`Response ` object + :rtype: requests.Response + """ + + return request("get", url, params=params, **kwargs) + + +def options(url: _t.UriType, **kwargs: Unpack[_t.RequestKwargs]) -> Response: + r"""Sends an OPTIONS request. + + :param url: URL for the new :class:`Request` object. + :param \*\*kwargs: Optional arguments that ``request`` takes. + :return: :class:`Response ` object + :rtype: requests.Response + """ + + return request("options", url, **kwargs) + + +def head(url: _t.UriType, **kwargs: Unpack[_t.RequestKwargs]) -> Response: + r"""Sends a HEAD request. + + :param url: URL for the new :class:`Request` object. + :param \*\*kwargs: Optional arguments that ``request`` takes. If + `allow_redirects` is not provided, it will be set to `False` (as + opposed to the default :meth:`request` behavior). + :return: :class:`Response ` object + :rtype: requests.Response + """ + + kwargs.setdefault("allow_redirects", False) + return request("head", url, **kwargs) + + +def post( + url: _t.UriType, + data: _t.DataType = None, + json: _t.JsonType = None, + **kwargs: Unpack[_t.PostKwargs], +) -> Response: + r"""Sends a POST request. + + :param url: URL for the new :class:`Request` object. + :param data: (optional) Dictionary, list of tuples, bytes, or file-like + object to send in the body of the :class:`Request`. + :param json: (optional) A JSON serializable Python object to send in the body of the :class:`Request`. + :param \*\*kwargs: Optional arguments that ``request`` takes. + :return: :class:`Response ` object + :rtype: requests.Response + """ + + return request("post", url, data=data, json=json, **kwargs) + + +def put( + url: _t.UriType, data: _t.DataType = None, **kwargs: Unpack[_t.DataKwargs] +) -> Response: + r"""Sends a PUT request. + + :param url: URL for the new :class:`Request` object. + :param data: (optional) Dictionary, list of tuples, bytes, or file-like + object to send in the body of the :class:`Request`. + :param json: (optional) A JSON serializable Python object to send in the body of the :class:`Request`. + :param \*\*kwargs: Optional arguments that ``request`` takes. + :return: :class:`Response ` object + :rtype: requests.Response + """ + + return request("put", url, data=data, **kwargs) + + +def patch( + url: _t.UriType, data: _t.DataType = None, **kwargs: Unpack[_t.DataKwargs] +) -> Response: + r"""Sends a PATCH request. + + :param url: URL for the new :class:`Request` object. + :param data: (optional) Dictionary, list of tuples, bytes, or file-like + object to send in the body of the :class:`Request`. + :param json: (optional) A JSON serializable Python object to send in the body of the :class:`Request`. + :param \*\*kwargs: Optional arguments that ``request`` takes. + :return: :class:`Response ` object + :rtype: requests.Response + """ + + return request("patch", url, data=data, **kwargs) + + +def delete(url: _t.UriType, **kwargs: Unpack[_t.RequestKwargs]) -> Response: + r"""Sends a DELETE request. + + :param url: URL for the new :class:`Request` object. + :param \*\*kwargs: Optional arguments that ``request`` takes. + :return: :class:`Response ` object + :rtype: requests.Response + """ + + return request("delete", url, **kwargs) diff --git a/.venv/lib/python3.12/site-packages/requests/auth.py b/.venv/lib/python3.12/site-packages/requests/auth.py new file mode 100644 index 0000000000000000000000000000000000000000..2af481dbf59e31965bde74c2e27d73517a39d7ac --- /dev/null +++ b/.venv/lib/python3.12/site-packages/requests/auth.py @@ -0,0 +1,354 @@ +""" +requests.auth +~~~~~~~~~~~~~ + +This module contains the authentication handlers for Requests. +""" + +from __future__ import annotations + +import hashlib +import os +import re +import threading +import time +import warnings +from base64 import b64encode +from typing import TYPE_CHECKING, Any, Final, cast, overload + +from ._internal_utils import to_native_string +from .compat import basestring, str, urlparse +from .cookies import extract_cookies_to_jar +from .utils import parse_dict_header + +if TYPE_CHECKING: + from http.cookiejar import CookieJar + from typing import Any + + from .models import PreparedRequest, Response + +CONTENT_TYPE_FORM_URLENCODED: Final = "application/x-www-form-urlencoded" +CONTENT_TYPE_MULTI_PART: Final = "multipart/form-data" + + +def _basic_auth_str(username: bytes | str, password: bytes | str) -> str: + """Returns a Basic Auth string.""" + + # "I want us to put a big-ol' comment on top of it that + # says that this behaviour is dumb but we need to preserve + # it because people are relying on it." + # - Lukasa + # + # These are here solely to maintain backwards compatibility + # for things like ints. This will be removed in 3.0.0. + if not isinstance(username, basestring): # type: ignore[reportUnnecessaryIsInstance] # runtime guard for non-str/bytes + warnings.warn( + "Non-string usernames will no longer be supported in Requests " + f"3.0.0. Please convert the object you've passed in ({username!r}) to " + "a string or bytes object in the near future to avoid " + "problems.", + category=DeprecationWarning, + ) + username = str(username) + + if not isinstance(password, basestring): # type: ignore[reportUnnecessaryIsInstance] # runtime guard for non-str/bytes + warnings.warn( + "Non-string passwords will no longer be supported in Requests " + f"3.0.0. Please convert the object you've passed in ({type(password)!r}) to " + "a string or bytes object in the near future to avoid " + "problems.", + category=DeprecationWarning, + ) + password = str(password) + # -- End Removal -- + + if isinstance(username, str): + username = username.encode("latin1") + + if isinstance(password, str): + password = password.encode("latin1") + + authstr = "Basic " + to_native_string( + b64encode(b":".join((username, password))).strip() + ) + + return authstr + + +class AuthBase: + """Base class that all auth implementations derive from""" + + def __call__(self, r: PreparedRequest) -> PreparedRequest: + raise NotImplementedError("Auth hooks must be callable.") + + +class HTTPBasicAuth(AuthBase): + """Attaches HTTP Basic Authentication to the given Request object.""" + + username: bytes | str + password: bytes | str + + @overload + def __init__(self, username: str, password: str) -> None: ... + @overload + def __init__(self, username: bytes, password: bytes) -> None: ... + + def __init__(self, username: bytes | str, password: bytes | str) -> None: + self.username = username + self.password = password + + def __eq__(self, other: object) -> bool: + return all( + [ + self.username == getattr(other, "username", None), + self.password == getattr(other, "password", None), + ] + ) + + def __ne__(self, other: Any) -> bool: + return not self == other + + def __call__(self, r: PreparedRequest) -> PreparedRequest: + r.headers["Authorization"] = _basic_auth_str(self.username, self.password) + return r + + +class HTTPProxyAuth(HTTPBasicAuth): + """Attaches HTTP Proxy Authentication to a given Request object.""" + + def __call__(self, r: PreparedRequest) -> PreparedRequest: + r.headers["Proxy-Authorization"] = _basic_auth_str(self.username, self.password) + return r + + +class HTTPDigestAuth(AuthBase): + """Attaches HTTP Digest Authentication to the given Request object.""" + + username: bytes | str + password: bytes | str + _thread_local: threading.local + last_nonce: str + nonce_count: int + chal: dict[str, str] + pos: int | None + num_401_calls: int | None + + @overload + def __init__(self, username: str, password: str) -> None: ... + @overload + def __init__(self, username: bytes, password: bytes) -> None: ... + + def __init__(self, username: bytes | str, password: bytes | str) -> None: + self.username = username + self.password = password + # Keep state in per-thread local storage + self._thread_local = threading.local() + + def init_per_thread_state(self) -> None: + # Ensure state is initialized just once per-thread + if not hasattr(self._thread_local, "init"): + self._thread_local.init = True + self._thread_local.last_nonce = "" + self._thread_local.nonce_count = 0 + self._thread_local.chal = {} + self._thread_local.pos = None + self._thread_local.num_401_calls = None + + def build_digest_header(self, method: str, url: str) -> str | None: + """ + :rtype: str + """ + + realm = self._thread_local.chal["realm"] + nonce = self._thread_local.chal["nonce"] + qop = self._thread_local.chal.get("qop") + algorithm = self._thread_local.chal.get("algorithm") + opaque = self._thread_local.chal.get("opaque") + hash_utf8 = None + + if algorithm is None: + _algorithm = "MD5" + else: + _algorithm = algorithm.upper() + # lambdas assume digest modules are imported at the top level + if _algorithm == "MD5" or _algorithm == "MD5-SESS": + + def md5_utf8(x: str | bytes) -> str: + if isinstance(x, str): + x = x.encode("utf-8") + return hashlib.md5(x, usedforsecurity=False).hexdigest() + + hash_utf8 = md5_utf8 + elif _algorithm == "SHA": + + def sha_utf8(x: str | bytes) -> str: + if isinstance(x, str): + x = x.encode("utf-8") + return hashlib.sha1(x, usedforsecurity=False).hexdigest() + + hash_utf8 = sha_utf8 + elif _algorithm == "SHA-256": + + def sha256_utf8(x: str | bytes) -> str: + if isinstance(x, str): + x = x.encode("utf-8") + return hashlib.sha256(x, usedforsecurity=False).hexdigest() + + hash_utf8 = sha256_utf8 + elif _algorithm == "SHA-512": + + def sha512_utf8(x: str | bytes) -> str: + if isinstance(x, str): + x = x.encode("utf-8") + return hashlib.sha512(x, usedforsecurity=False).hexdigest() + + hash_utf8 = sha512_utf8 + + if hash_utf8 is None: + return None + + def KD(s: str, d: str) -> str: + return hash_utf8(f"{s}:{d}") + + # XXX not implemented yet + entdig = None + p_parsed = urlparse(url) + #: path is request-uri defined in RFC 2616 which should not be empty + path = p_parsed.path or "/" + if p_parsed.query: + path += f"?{p_parsed.query}" + + A1 = f"{self.username}:{realm}:{self.password}" + A2 = f"{method}:{path}" + + HA1 = hash_utf8(A1) + HA2 = hash_utf8(A2) + + if nonce == self._thread_local.last_nonce: + self._thread_local.nonce_count += 1 + else: + self._thread_local.nonce_count = 1 + ncvalue = f"{self._thread_local.nonce_count:08x}" + s = str(self._thread_local.nonce_count).encode("utf-8") + s += nonce.encode("utf-8") + s += time.ctime().encode("utf-8") + s += os.urandom(8) + + cnonce = hashlib.sha1(s, usedforsecurity=False).hexdigest()[:16] + if _algorithm == "MD5-SESS": + HA1 = hash_utf8(f"{HA1}:{nonce}:{cnonce}") # type: ignore[reportConstantRedefinition] # RFC 2617 terminology + + if not qop: + respdig = KD(HA1, f"{nonce}:{HA2}") + elif qop == "auth" or "auth" in qop.split(","): + noncebit = f"{nonce}:{ncvalue}:{cnonce}:auth:{HA2}" + respdig = KD(HA1, noncebit) + else: + # XXX handle auth-int. + return None + + self._thread_local.last_nonce = nonce + + # XXX should the partial digests be encoded too? + base = ( + f'username="{self.username}", realm="{realm}", nonce="{nonce}", ' + f'uri="{path}", response="{respdig}"' + ) + if opaque: + base += f', opaque="{opaque}"' + if algorithm: + base += f', algorithm="{algorithm}"' + if entdig: + base += f', digest="{entdig}"' + if qop: + base += f', qop="auth", nc={ncvalue}, cnonce="{cnonce}"' + + return f"Digest {base}" + + def handle_redirect(self, r: Response, **kwargs: Any) -> None: + """Reset num_401_calls counter on redirects.""" + if r.is_redirect: + self._thread_local.num_401_calls = 1 + + def handle_401(self, r: Response, **kwargs: Any) -> Response: + """ + Takes the given response and tries digest-auth, if needed. + + :rtype: requests.Response + """ + + # If response is not 4xx, do not auth + # See https://github.com/psf/requests/issues/3772 + if not 400 <= r.status_code < 500: + self._thread_local.num_401_calls = 1 + return r + + if self._thread_local.pos is not None: + # Rewind the file position indicator of the body to where + # it was to resend the request. + if (seek := getattr(r.request.body, "seek", None)) is not None: + seek(self._thread_local.pos) + s_auth = r.headers.get("www-authenticate", "") + + if "digest" in s_auth.lower() and self._thread_local.num_401_calls < 2: + self._thread_local.num_401_calls += 1 + pat = re.compile(r"digest ", flags=re.IGNORECASE) + self._thread_local.chal = parse_dict_header(pat.sub("", s_auth, count=1)) + + # Consume content and release the original connection + # to allow our new request to reuse the same one. + r.content + r.close() + prep = r.request.copy() + cookie_jar = cast("CookieJar", prep._cookies) # type: ignore[reportPrivateUsage] + extract_cookies_to_jar(cookie_jar, r.request, r.raw) + prep.prepare_cookies(cookie_jar) + + _digest_auth = self.build_digest_header( + cast(str, prep.method), cast(str, prep.url) + ) + if _digest_auth: + prep.headers["Authorization"] = _digest_auth + _r = r.connection.send(prep, **kwargs) + _r.history.append(r) + _r.request = prep + + return _r + + self._thread_local.num_401_calls = 1 + return r + + def __call__(self, r: PreparedRequest) -> PreparedRequest: + # Initialize per-thread state, if needed + self.init_per_thread_state() + # If we have a saved nonce, skip the 401 + if self._thread_local.last_nonce: + _digest_auth = self.build_digest_header( + cast(str, r.method), cast(str, r.url) + ) + if _digest_auth: + r.headers["Authorization"] = _digest_auth + if (tell := getattr(r.body, "tell", None)) is not None: + self._thread_local.pos = tell() + else: + # In the case of HTTPDigestAuth being reused and the body of + # the previous request was a file-like object, pos has the + # file position of the previous body. Ensure it's set to + # None. + self._thread_local.pos = None + r.register_hook("response", self.handle_401) + r.register_hook("response", self.handle_redirect) + self._thread_local.num_401_calls = 1 + + return r + + def __eq__(self, other: object) -> bool: + return all( + [ + self.username == getattr(other, "username", None), + self.password == getattr(other, "password", None), + ] + ) + + def __ne__(self, other: Any) -> bool: + return not self == other diff --git a/.venv/lib/python3.12/site-packages/requests/certs.py b/.venv/lib/python3.12/site-packages/requests/certs.py new file mode 100644 index 0000000000000000000000000000000000000000..4f85ac070bc0230af8155bcadfaa96165268cede --- /dev/null +++ b/.venv/lib/python3.12/site-packages/requests/certs.py @@ -0,0 +1,18 @@ +#!/usr/bin/env python + +""" +requests.certs +~~~~~~~~~~~~~~ + +This module returns the preferred default CA certificate bundle. There is +only one — the one from the certifi package. + +If you are packaging Requests, e.g., for a Linux distribution or a managed +environment, you can change the definition of where() to return a separately +packaged CA bundle. +""" + +from certifi import where + +if __name__ == "__main__": + print(where()) diff --git a/.venv/lib/python3.12/site-packages/requests/compat.py b/.venv/lib/python3.12/site-packages/requests/compat.py new file mode 100644 index 0000000000000000000000000000000000000000..deab3c091fed207315c5af60fb415d7407a08b48 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/requests/compat.py @@ -0,0 +1,113 @@ +""" +requests.compat +~~~~~~~~~~~~~~~ + +This module previously handled import compatibility issues +between Python 2 and Python 3. It remains for backwards +compatibility until the next major version. +""" + +# pyright: reportUnusedImport=false + +from __future__ import annotations + +import importlib +import sys +from types import ModuleType + +# ------- +# urllib3 +# ------- +from urllib3 import ( + __version__ as urllib3_version, # type: ignore[reportPrivateImportUsage] +) + +# Detect which major version of urllib3 is being used. +try: + is_urllib3_1 = int(urllib3_version.split(".")[0]) == 1 +except (TypeError, AttributeError): + # If we can't discern a version, prefer old functionality. + is_urllib3_1 = True + +# ------------------- +# Character Detection +# ------------------- + + +def _resolve_char_detection() -> ModuleType | None: + """Find supported character detection libraries.""" + chardet = None + for lib in ("chardet", "charset_normalizer"): + if chardet is None: + try: + chardet = importlib.import_module(lib) + except ImportError: + pass + return chardet + + +chardet = _resolve_char_detection() + +# ------- +# Pythons +# ------- + +# Syntax sugar. +_ver = sys.version_info + +#: Python 2.x? +is_py2 = _ver[0] == 2 + +#: Python 3.x? +is_py3 = _ver[0] == 3 + +# json/simplejson module import resolution +has_simplejson = False +try: + import simplejson as json # type: ignore[import-not-found] + + has_simplejson = True +except ImportError: + import json + +if has_simplejson: + from simplejson import JSONDecodeError # type: ignore[import-not-found] +else: + from json import JSONDecodeError + +# Keep OrderedDict for backwards compatibility. +from collections import OrderedDict +from collections.abc import Callable, Mapping, MutableMapping +from http import cookiejar as cookielib +from http.cookies import Morsel +from io import StringIO + +# -------------- +# Legacy Imports +# -------------- +from urllib.parse import ( + quote, + quote_plus, + unquote, + unquote_plus, + urldefrag, + urlencode, + urljoin, + urlparse, + urlsplit, + urlunparse, +) +from urllib.request import ( + getproxies, + getproxies_environment, + parse_http_list, + proxy_bypass, + proxy_bypass_environment, # type: ignore[attr-defined] # https://github.com/python/cpython/issues/145331 +) + +builtin_str = str +str = str +bytes = bytes +basestring = (str, bytes) +numeric_types = (int, float) +integer_types = (int,) diff --git a/.venv/lib/python3.12/site-packages/requests/cookies.py b/.venv/lib/python3.12/site-packages/requests/cookies.py new file mode 100644 index 0000000000000000000000000000000000000000..2e3fc215095fad13817562bbaee871cba57eec08 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/requests/cookies.py @@ -0,0 +1,625 @@ +""" +requests.cookies +~~~~~~~~~~~~~~~~ + +Compatibility code to be able to use `http.cookiejar.CookieJar` with requests. + +requests.utils imports from here, so be careful with imports. +""" + +from __future__ import annotations + +import calendar +import copy +import time +from collections.abc import Iterator, MutableMapping +from http.cookiejar import Cookie, CookieJar, CookiePolicy +from typing import TYPE_CHECKING, Any, TypeVar, overload + +from ._internal_utils import to_native_string +from ._types import is_prepared as _is_prepared +from .compat import Morsel, cookielib, urlparse, urlunparse + +if TYPE_CHECKING: + from _typeshed import SupportsKeysAndGetItem + + from .models import PreparedRequest + +import threading + + +class MockRequest: + """Wraps a `requests.PreparedRequest` to mimic a `urllib2.Request`. + + The code in `http.cookiejar.CookieJar` expects this interface in order to correctly + manage cookie policies, i.e., determine whether a cookie can be set, given the + domains of the request and the cookie. + + The original request object is read-only. The client is responsible for collecting + the new headers via `get_new_headers()` and interpreting them appropriately. You + probably want `get_cookie_header`, defined below. + """ + + type: str + + def __init__(self, request: PreparedRequest) -> None: + assert _is_prepared(request) + self._r = request + self._new_headers: dict[str, str] = {} + self.type = urlparse(self._r.url).scheme + + def get_type(self) -> str: + return self.type + + def get_host(self) -> str: + return urlparse(self._r.url).netloc + + def get_origin_req_host(self) -> str: + return self.get_host() + + def get_full_url(self) -> str: + # Only return the response's URL if the user hadn't set the Host + # header + if not self._r.headers.get("Host"): + return self._r.url + # If they did set it, retrieve it and reconstruct the expected domain + host = to_native_string(self._r.headers["Host"], encoding="utf-8") + parsed = urlparse(self._r.url) + # Reconstruct the URL as we expect it + return urlunparse( + [ + parsed.scheme, + host, + parsed.path, + parsed.params, + parsed.query, + parsed.fragment, + ] + ) + + def is_unverifiable(self) -> bool: + return True + + def has_header(self, name: str) -> bool: + return name in self._r.headers or name in self._new_headers + + def get_header(self, name: str, default: str | None = None) -> str | None: + return self._r.headers.get(name, self._new_headers.get(name, default)) # type: ignore[return-value] + + def add_header(self, key: str, val: str) -> None: + """cookiejar has no legitimate use for this method; add it back if you find one.""" + raise NotImplementedError( + "Cookie headers should be added with add_unredirected_header()" + ) + + def add_unredirected_header(self, name: str, value: str) -> None: + self._new_headers[name] = value + + def get_new_headers(self) -> dict[str, str]: + return self._new_headers + + @property + def unverifiable(self) -> bool: + return self.is_unverifiable() + + @property + def origin_req_host(self) -> str: + return self.get_origin_req_host() + + @property + def host(self) -> str: + return self.get_host() + + +class MockResponse: + """Wraps a `httplib.HTTPMessage` to mimic a `urllib.addinfourl`. + + ...what? Basically, expose the parsed HTTP headers from the server response + the way `http.cookiejar` expects to see them. + """ + + def __init__(self, headers: Any) -> None: + """Make a MockResponse for `cookiejar` to read. + + :param headers: a httplib.HTTPMessage or analogous carrying the headers + """ + self._headers = headers + + def info(self) -> Any: + return self._headers + + def getheaders(self, name: str) -> Any: + self._headers.getheaders(name) + + +def extract_cookies_to_jar( + jar: CookieJar, request: PreparedRequest, response: Any +) -> None: + """Extract the cookies from the response into a CookieJar. + + :param jar: http.cookiejar.CookieJar (not necessarily a RequestsCookieJar) + :param request: our own requests.Request object + :param response: urllib3.HTTPResponse object + """ + if not (hasattr(response, "_original_response") and response._original_response): + return + # the _original_response field is the wrapped httplib.HTTPResponse object, + req = MockRequest(request) + # pull out the HTTPMessage with the headers and put it in the mock: + res = MockResponse(response._original_response.msg) + jar.extract_cookies(res, req) # type: ignore[arg-type] + + +def get_cookie_header(jar: CookieJar, request: PreparedRequest) -> str | None: + """ + Produce an appropriate Cookie header string to be sent with `request`, or None. + + :rtype: str + """ + r = MockRequest(request) + jar.add_cookie_header(r) # type: ignore[arg-type] + return r.get_new_headers().get("Cookie") + + +def remove_cookie_by_name( + cookiejar: CookieJar, name: str, domain: str | None = None, path: str | None = None +) -> None: + """Unsets a cookie by name, by default over all domains and paths. + + Wraps CookieJar.clear(), is O(n). + """ + clearables: list[tuple[str, str, str]] = [] + for cookie in cookiejar: + if cookie.name != name: + continue + if domain is not None and domain != cookie.domain: + continue + if path is not None and path != cookie.path: + continue + clearables.append((cookie.domain, cookie.path, cookie.name)) + + for domain, path, name in clearables: + cookiejar.clear(domain, path, name) + + +class CookieConflictError(RuntimeError): + """There are two cookies that meet the criteria specified in the cookie jar. + Use .get and .set and include domain and path args in order to be more specific. + """ + + +class RequestsCookieJar(CookieJar, MutableMapping[str, str | None]): # type: ignore[misc] + """Compatibility class; is a http.cookiejar.CookieJar, but exposes a dict + interface. + + This is the CookieJar we create by default for requests and sessions that + don't specify one, since some clients may expect response.cookies and + session.cookies to support dict operations. + + Requests does not use the dict interface internally; it's just for + compatibility with external client code. All requests code should work + out of the box with externally provided instances of ``CookieJar``, e.g. + ``LWPCookieJar`` and ``FileCookieJar``. + + Unlike a regular CookieJar, this class is pickleable. + + .. warning:: dictionary operations that are normally O(1) may be O(n). + """ + + _policy: CookiePolicy + + def get( # type: ignore[override] + self, + name: str, + default: str | None = None, + domain: str | None = None, + path: str | None = None, + ) -> str | None: + """Dict-like get() that also supports optional domain and path args in + order to resolve naming collisions from using one cookie jar over + multiple domains. + + .. warning:: operation is O(n), not O(1). + """ + try: + return self._find_no_duplicates(name, domain, path) + except KeyError: + return default + + def set( + self, name: str, value: str | Morsel[dict[str, str]] | None, **kwargs: Any + ) -> Cookie | None: + """Dict-like set() that also supports optional domain and path args in + order to resolve naming collisions from using one cookie jar over + multiple domains. + """ + # support client code that unsets cookies by assignment of a None value: + if value is None: + remove_cookie_by_name( + self, name, domain=kwargs.get("domain"), path=kwargs.get("path") + ) + return + + if isinstance(value, Morsel): + c = morsel_to_cookie(value) + else: + c = create_cookie(name, value, **kwargs) + self.set_cookie(c) + return c + + def iterkeys(self) -> Iterator[str]: + """Dict-like iterkeys() that returns an iterator of names of cookies + from the jar. + + .. seealso:: itervalues() and iteritems(). + """ + for cookie in iter(self): + yield cookie.name + + def keys(self) -> list[str]: # type: ignore[override] + """Dict-like keys() that returns a list of names of cookies from the + jar. + + .. seealso:: values() and items(). + """ + return list(self.iterkeys()) + + def itervalues(self) -> Iterator[str | None]: + """Dict-like itervalues() that returns an iterator of values of cookies + from the jar. + + .. seealso:: iterkeys() and iteritems(). + """ + for cookie in iter(self): + yield cookie.value + + def values(self) -> list[str | None]: # type: ignore[override] + """Dict-like values() that returns a list of values of cookies from the + jar. + + .. seealso:: keys() and items(). + """ + return list(self.itervalues()) + + def iteritems(self) -> Iterator[tuple[str, str | None]]: + """Dict-like iteritems() that returns an iterator of name-value tuples + from the jar. + + .. seealso:: iterkeys() and itervalues(). + """ + for cookie in iter(self): + yield cookie.name, cookie.value + + def items(self) -> list[tuple[str, str | None]]: # type: ignore[override] + """Dict-like items() that returns a list of name-value tuples from the + jar. Allows client-code to call ``dict(RequestsCookieJar)`` and get a + vanilla python dict of key value pairs. + + .. seealso:: keys() and values(). + """ + return list(self.iteritems()) + + def list_domains(self) -> list[str]: + """Utility method to list all the domains in the jar.""" + domains: list[str] = [] + for cookie in iter(self): + if cookie.domain not in domains: + domains.append(cookie.domain) + return domains + + def list_paths(self) -> list[str]: + """Utility method to list all the paths in the jar.""" + paths: list[str] = [] + for cookie in iter(self): + if cookie.path not in paths: + paths.append(cookie.path) + return paths + + def multiple_domains(self) -> bool: + """Returns True if there are multiple domains in the jar. + Returns False otherwise. + + :rtype: bool + """ + domains: list[str] = [] + for cookie in iter(self): + if cookie.domain is not None and cookie.domain in domains: # type: ignore[reportUnnecessaryComparison] # defensive check + return True + domains.append(cookie.domain) + return False # there is only one domain in jar + + def get_dict( + self, domain: str | None = None, path: str | None = None + ) -> dict[str, str | None]: + """Takes as an argument an optional domain and path and returns a plain + old Python dict of name-value pairs of cookies that meet the + requirements. + + :rtype: dict + """ + dictionary: dict[str, str | None] = {} + for cookie in iter(self): + if (domain is None or cookie.domain == domain) and ( + path is None or cookie.path == path + ): + dictionary[cookie.name] = cookie.value + return dictionary + + def __iter__(self) -> Iterator[Cookie]: # type: ignore[override] + """RequestCookieJar's __iter__ comes from CookieJar not MutableMapping.""" + return super().__iter__() + + def __contains__(self, name: object) -> bool: + try: + return super().__contains__(name) + except CookieConflictError: + return True + + def __getitem__(self, name: str) -> str | None: + """Dict-like __getitem__() for compatibility with client code. Throws + exception if there are more than one cookie with name. In that case, + use the more explicit get() method instead. + + .. warning:: operation is O(n), not O(1). + """ + return self._find_no_duplicates(name) + + def __setitem__( + self, name: str, value: str | Morsel[dict[str, str]] | None + ) -> None: + """Dict-like __setitem__ for compatibility with client code. Throws + exception if there is already a cookie of that name in the jar. In that + case, use the more explicit set() method instead. + """ + self.set(name, value) + + def __delitem__(self, name: str) -> None: + """Deletes a cookie given a name. Wraps ``http.cookiejar.CookieJar``'s + ``remove_cookie_by_name()``. + """ + remove_cookie_by_name(self, name) + + def set_cookie(self, cookie: Cookie, *args: Any, **kwargs: Any) -> None: + if ( + (value := cookie.value) is not None + and value.startswith('"') + and value.endswith('"') + ): + cookie.value = value.replace('\\"', "") + return super().set_cookie(cookie, *args, **kwargs) + + def update( # type: ignore[override] + self, other: CookieJar | SupportsKeysAndGetItem[str, str] + ) -> None: + """Updates this jar with cookies from another CookieJar or dict-like""" + if isinstance(other, cookielib.CookieJar): + for cookie in other: + self.set_cookie(copy.copy(cookie)) + else: + super().update(other) + + def _find( + self, name: str, domain: str | None = None, path: str | None = None + ) -> str | None: + """Requests uses this method internally to get cookie values. + + If there are conflicting cookies, _find arbitrarily chooses one. + See _find_no_duplicates if you want an exception thrown if there are + conflicting cookies. + + :param name: a string containing name of cookie + :param domain: (optional) string containing domain of cookie + :param path: (optional) string containing path of cookie + :return: cookie.value + """ + for cookie in iter(self): + if cookie.name == name: + if domain is None or cookie.domain == domain: + if path is None or cookie.path == path: + return cookie.value + + raise KeyError(f"name={name!r}, domain={domain!r}, path={path!r}") + + def _find_no_duplicates( + self, name: str, domain: str | None = None, path: str | None = None + ) -> str: + """Both ``__get_item__`` and ``get`` call this function: it's never + used elsewhere in Requests. + + :param name: a string containing name of cookie + :param domain: (optional) string containing domain of cookie + :param path: (optional) string containing path of cookie + :raises KeyError: if cookie is not found + :raises CookieConflictError: if there are multiple cookies + that match name and optionally domain and path + :return: cookie.value + """ + toReturn = None + for cookie in iter(self): + if cookie.name == name: + if domain is None or cookie.domain == domain: + if path is None or cookie.path == path: + if toReturn is not None: + # if there are multiple cookies that meet passed in criteria + raise CookieConflictError( + f"There are multiple cookies with name, {name!r}" + ) + # we will eventually return this as long as no cookie conflict + toReturn = cookie.value + + if toReturn is not None: + return toReturn + raise KeyError(f"name={name!r}, domain={domain!r}, path={path!r}") + + def __getstate__(self) -> dict[str, Any]: + """Unlike a normal CookieJar, this class is pickleable.""" + state = self.__dict__.copy() + # remove the unpickleable RLock object + state.pop("_cookies_lock") + return state + + def __setstate__(self, state: dict[str, Any]) -> None: + """Unlike a normal CookieJar, this class is pickleable.""" + self.__dict__.update(state) + if "_cookies_lock" not in self.__dict__: + self._cookies_lock = threading.RLock() + + def copy(self) -> RequestsCookieJar: + """Return a copy of this RequestsCookieJar.""" + new_cj = RequestsCookieJar() + new_cj.set_policy(self.get_policy()) + new_cj.update(self) + return new_cj + + def get_policy(self) -> CookiePolicy: + """Return the CookiePolicy instance used.""" + return self._policy + + +def _copy_cookie_jar(jar: CookieJar | None) -> CookieJar | None: # type: ignore[reportUnusedFunction] # cross-module usage in models.py + if jar is None: + return None + + if copy_method := getattr(jar, "copy", None): + # We're dealing with an instance of RequestsCookieJar + return copy_method() + # We're dealing with a generic CookieJar instance + new_jar = copy.copy(jar) + new_jar.clear() + for cookie in jar: + new_jar.set_cookie(copy.copy(cookie)) + return new_jar + + +def create_cookie(name: str, value: str, **kwargs: Any) -> Cookie: + """Make a cookie from underspecified parameters. + + By default, the pair of `name` and `value` will be set for the domain '' + and sent on every request (this is sometimes called a "supercookie"). + """ + result: dict[str, Any] = { + "version": 0, + "name": name, + "value": value, + "port": None, + "domain": "", + "path": "/", + "secure": False, + "expires": None, + "discard": True, + "comment": None, + "comment_url": None, + "rest": {"HttpOnly": None}, + "rfc2109": False, + } + + badargs = set(kwargs) - set(result) + if badargs: + raise TypeError( + f"create_cookie() got unexpected keyword arguments: {list(badargs)}" + ) + + result.update(kwargs) + result["port_specified"] = bool(result["port"]) + result["domain_specified"] = bool(result["domain"]) + result["domain_initial_dot"] = result["domain"].startswith(".") + result["path_specified"] = bool(result["path"]) + + return cookielib.Cookie(**result) + + +def morsel_to_cookie(morsel: Morsel[Any]) -> Cookie: + """Convert a Morsel object into a Cookie containing the one k/v pair.""" + + expires: int | None = None + if morsel["max-age"]: + try: + expires = int(time.time() + int(morsel["max-age"])) + except ValueError: + raise TypeError(f"max-age: {morsel['max-age']} must be integer") + elif morsel["expires"]: + time_template = "%a, %d-%b-%Y %H:%M:%S GMT" + expires = calendar.timegm(time.strptime(morsel["expires"], time_template)) + return create_cookie( + comment=morsel["comment"], + comment_url=bool(morsel["comment"]), + discard=False, + domain=morsel["domain"], + expires=expires, + name=morsel.key, + path=morsel["path"], + port=None, + rest={"HttpOnly": morsel["httponly"]}, + rfc2109=False, + secure=bool(morsel["secure"]), + value=morsel.value, + version=morsel["version"] or 0, + ) + + +_CookieJarT = TypeVar("_CookieJarT", bound=CookieJar) + + +@overload +def cookiejar_from_dict( + cookie_dict: dict[str, str] | None, + cookiejar: None = None, + overwrite: bool = True, +) -> RequestsCookieJar: ... + + +@overload +def cookiejar_from_dict( + cookie_dict: dict[str, str] | None, + cookiejar: _CookieJarT, + overwrite: bool = True, +) -> _CookieJarT: ... + + +def cookiejar_from_dict( + cookie_dict: dict[str, str] | None, + cookiejar: CookieJar | None = None, + overwrite: bool = True, +) -> CookieJar: + """Returns a CookieJar from a key/value dictionary. + + :param cookie_dict: Dict of key/values to insert into CookieJar. + :param cookiejar: (optional) A cookiejar to add the cookies to. + :param overwrite: (optional) If False, will not replace cookies + already in the jar with new ones. + :rtype: CookieJar + """ + if cookiejar is None: + cookiejar = RequestsCookieJar() + + if cookie_dict is not None: + names_from_jar = [cookie.name for cookie in cookiejar] + for name in cookie_dict: + if overwrite or (name not in names_from_jar): + cookiejar.set_cookie(create_cookie(name, cookie_dict[name])) + + return cookiejar + + +def merge_cookies( + cookiejar: CookieJar, cookies: dict[str, str] | CookieJar | None +) -> CookieJar: + """Add cookies to cookiejar and returns a merged CookieJar. + + :param cookiejar: CookieJar object to add the cookies to. + :param cookies: Dictionary or CookieJar object to be added. + :rtype: CookieJar + """ + if not isinstance(cookiejar, cookielib.CookieJar): # type: ignore[reportUnnecessaryIsInstance] # runtime guard + raise ValueError("You can only merge into CookieJar") + + if isinstance(cookies, dict): + cookiejar = cookiejar_from_dict(cookies, cookiejar=cookiejar, overwrite=False) + elif isinstance(cookies, cookielib.CookieJar): + if update_method := getattr(cookiejar, "update", None): + update_method(cookies) + else: + for cookie_in_jar in cookies: + cookiejar.set_cookie(cookie_in_jar) + + return cookiejar diff --git a/.venv/lib/python3.12/site-packages/requests/exceptions.py b/.venv/lib/python3.12/site-packages/requests/exceptions.py new file mode 100644 index 0000000000000000000000000000000000000000..cb5e9510e3b1cf4804ac6091fd7fdb55e9f2745b --- /dev/null +++ b/.venv/lib/python3.12/site-packages/requests/exceptions.py @@ -0,0 +1,162 @@ +""" +requests.exceptions +~~~~~~~~~~~~~~~~~~~ + +This module contains the set of Requests' exceptions. +""" + +from __future__ import annotations + +from typing import TYPE_CHECKING, Any + +from urllib3.exceptions import HTTPError as BaseHTTPError + +from .compat import JSONDecodeError as CompatJSONDecodeError + +if TYPE_CHECKING: + from .models import PreparedRequest, Request, Response + + +class RequestException(IOError): + """There was an ambiguous exception that occurred while handling your + request. + """ + + response: Response | None + request: Request | PreparedRequest | None + + def __init__(self, *args: Any, **kwargs: Any) -> None: + """Initialize RequestException with `request` and `response` objects.""" + response: Response | None = kwargs.pop("response", None) + self.response = response + self.request = kwargs.pop("request", None) + if response is not None and not self.request and hasattr(response, "request"): + self.request = response.request + super().__init__(*args, **kwargs) + + +class InvalidJSONError(RequestException): + """A JSON error occurred.""" + + +class JSONDecodeError(InvalidJSONError, CompatJSONDecodeError): + """Couldn't decode the text into json""" + + def __init__(self, *args: Any, **kwargs: Any) -> None: + """ + Construct the JSONDecodeError instance first with all + args. Then use it's args to construct the IOError so that + the json specific args aren't used as IOError specific args + and the error message from JSONDecodeError is preserved. + """ + CompatJSONDecodeError.__init__(self, *args) + InvalidJSONError.__init__(self, *self.args, **kwargs) + + def __reduce__(self) -> tuple[Any, ...] | str: + """ + The __reduce__ method called when pickling the object must + be the one from the JSONDecodeError (be it json/simplejson) + as it expects all the arguments for instantiation, not just + one like the IOError, and the MRO would by default call the + __reduce__ method from the IOError due to the inheritance order. + """ + return CompatJSONDecodeError.__reduce__(self) + + +class HTTPError(RequestException): + """An HTTP error occurred.""" + + +class ConnectionError(RequestException): + """A Connection error occurred.""" + + +class ProxyError(ConnectionError): + """A proxy error occurred.""" + + +class SSLError(ConnectionError): + """An SSL error occurred.""" + + +class Timeout(RequestException): + """The request timed out. + + Catching this error will catch both + :exc:`~requests.exceptions.ConnectTimeout` and + :exc:`~requests.exceptions.ReadTimeout` errors. + """ + + +class ConnectTimeout(ConnectionError, Timeout): + """The request timed out while trying to connect to the remote server. + + Requests that produced this error are safe to retry. + """ + + +class ReadTimeout(Timeout): + """The server did not send any data in the allotted amount of time.""" + + +class URLRequired(RequestException): + """A valid URL is required to make a request.""" + + +class TooManyRedirects(RequestException): + """Too many redirects.""" + + +class MissingSchema(RequestException, ValueError): + """The URL scheme (e.g. http or https) is missing.""" + + +class InvalidSchema(RequestException, ValueError): + """The URL scheme provided is either invalid or unsupported.""" + + +class InvalidURL(RequestException, ValueError): + """The URL provided was somehow invalid.""" + + +class InvalidHeader(RequestException, ValueError): + """The header value provided was somehow invalid.""" + + +class InvalidProxyURL(InvalidURL): + """The proxy URL provided is invalid.""" + + +class ChunkedEncodingError(RequestException): + """The server declared chunked encoding but sent an invalid chunk.""" + + +class ContentDecodingError(RequestException, BaseHTTPError): + """Failed to decode response content.""" + + +class StreamConsumedError(RequestException, TypeError): + """The content for this response was already consumed.""" + + +class RetryError(RequestException): + """Custom retries logic failed""" + + +class UnrewindableBodyError(RequestException): + """Requests encountered an error when trying to rewind a body.""" + + +# Warnings + + +class RequestsWarning(Warning): + """Base warning for Requests.""" + + +class FileModeWarning(RequestsWarning, DeprecationWarning): + """A file was opened in text mode, but Requests determined its binary length.""" + + +class RequestsDependencyWarning(RequestsWarning): + """An imported dependency doesn't match the expected version range.""" diff --git a/.venv/lib/python3.12/site-packages/requests/help.py b/.venv/lib/python3.12/site-packages/requests/help.py new file mode 100644 index 0000000000000000000000000000000000000000..9269cc71263e3f5938a89a9d6c2fed5a4274cc14 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/requests/help.py @@ -0,0 +1,134 @@ +"""Module containing bug report helper(s).""" + +# pyright: reportUnknownMemberType=false + +import json +import platform +import ssl +import sys +from typing import Any + +import idna +import urllib3 + +from . import __version__ as requests_version + +try: + import charset_normalizer +except ImportError: + charset_normalizer = None + +try: + import chardet # type: ignore[import-not-found] +except ImportError: + chardet = None + +try: + from urllib3.contrib import pyopenssl +except ImportError: + pyopenssl = None + OpenSSL = None + cryptography = None +else: + import cryptography # type: ignore[import-not-found] + import OpenSSL # type: ignore[import-not-found] + + +def _implementation(): + """Return a dict with the Python implementation and version. + + Provide both the name and the version of the Python implementation + currently running. For example, on CPython 3.10.3 it will return + {'name': 'CPython', 'version': '3.10.3'}. + + This function works best on CPython and PyPy: in particular, it probably + doesn't work for Jython or IronPython. Future investigation should be done + to work out the correct shape of the code for those platforms. + """ + implementation = platform.python_implementation() + + if implementation == "CPython": + implementation_version = platform.python_version() + elif implementation == "PyPy": + pypy = sys.pypy_version_info # type: ignore[attr-defined] + implementation_version = f"{pypy.major}.{pypy.minor}.{pypy.micro}" + if sys.pypy_version_info.releaselevel != "final": # type: ignore[attr-defined] + implementation_version = "".join( + [implementation_version, sys.pypy_version_info.releaselevel] # type: ignore[attr-defined] + ) + elif implementation == "Jython": + implementation_version = platform.python_version() # Complete Guess + elif implementation == "IronPython": + implementation_version = platform.python_version() # Complete Guess + else: + implementation_version = "Unknown" + + return {"name": implementation, "version": implementation_version} + + +def info() -> dict[str, Any]: + """Generate information for a bug report.""" + try: + platform_info = { + "system": platform.system(), + "release": platform.release(), + } + except OSError: + platform_info = { + "system": "Unknown", + "release": "Unknown", + } + + implementation_info = _implementation() + urllib3_info = {"version": urllib3.__version__} # type: ignore[reportPrivateImportUsage] + charset_normalizer_info = {"version": None} + chardet_info: dict[str, str | None] = {"version": None} + if charset_normalizer: + charset_normalizer_info = {"version": charset_normalizer.__version__} + if chardet: + chardet_info = {"version": chardet.__version__} + + pyopenssl_info: dict[str, str | None] = { + "version": None, + "openssl_version": "", + } + if OpenSSL: + pyopenssl_info = { + "version": OpenSSL.__version__, + "openssl_version": f"{OpenSSL.SSL.OPENSSL_VERSION_NUMBER:x}", + } + cryptography_info = { + "version": getattr(cryptography, "__version__", ""), + } + idna_info = { + "version": getattr(idna, "__version__", ""), + } + + system_ssl = ssl.OPENSSL_VERSION_NUMBER + system_ssl_info = {"version": f"{system_ssl:x}" if system_ssl is not None else ""} # type: ignore[reportUnnecessaryComparison] + + return { + "platform": platform_info, + "implementation": implementation_info, + "system_ssl": system_ssl_info, + "using_pyopenssl": pyopenssl is not None, + "using_charset_normalizer": chardet is None, + "pyOpenSSL": pyopenssl_info, + "urllib3": urllib3_info, + "chardet": chardet_info, + "charset_normalizer": charset_normalizer_info, + "cryptography": cryptography_info, + "idna": idna_info, + "requests": { + "version": requests_version, + }, + } + + +def main(): + """Pretty-print the bug information as JSON.""" + print(json.dumps(info(), sort_keys=True, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/.venv/lib/python3.12/site-packages/requests/hooks.py b/.venv/lib/python3.12/site-packages/requests/hooks.py new file mode 100644 index 0000000000000000000000000000000000000000..11ff9e9f27e76f5ef6b9b609e88c2f418d655e16 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/requests/hooks.py @@ -0,0 +1,48 @@ +""" +requests.hooks +~~~~~~~~~~~~~~ + +This module provides the capabilities for the Requests hooks system. + +Available hooks: + +``response``: + The response generated from a Request. +""" + +from __future__ import annotations + +from collections.abc import Callable, Iterable +from typing import TYPE_CHECKING, Any + +if TYPE_CHECKING: + from . import _types as _t + from .models import Response + +HOOKS: list[str] = ["response"] + + +def default_hooks() -> dict[str, list[_t.HookType]]: + return {event: [] for event in HOOKS} + + +# TODO: response is the only one + + +def dispatch_hook( + key: str, + hooks: _t.HooksInputType | None, + hook_data: Response, + **kwargs: Any, +) -> Response: + """Dispatches a hook dictionary on a given piece of data.""" + hooks_dict = hooks or {} + hook_list: Iterable[_t.HookType] | _t.HookType | None = hooks_dict.get(key) + if hook_list: + if isinstance(hook_list, Callable): + hook_list = [hook_list] + for hook in hook_list: + _hook_data = hook(hook_data, **kwargs) + if _hook_data is not None: + hook_data = _hook_data + return hook_data diff --git a/.venv/lib/python3.12/site-packages/requests/models.py b/.venv/lib/python3.12/site-packages/requests/models.py new file mode 100644 index 0000000000000000000000000000000000000000..59b5615960d19849d2dd4a85de4fdc079969ddae --- /dev/null +++ b/.venv/lib/python3.12/site-packages/requests/models.py @@ -0,0 +1,1180 @@ +""" +requests.models +~~~~~~~~~~~~~~~ + +This module contains the primary objects that power Requests. +""" + +from __future__ import annotations + +import datetime + +# Import encoding now, to avoid implicit import later. +# Implicit import within threads may cause LookupError when standard library is in a ZIP, +# such as in Embedded Python. See https://github.com/psf/requests/issues/3578. +import encodings.idna # noqa: F401 # type: ignore[reportUnusedImport] +from collections.abc import Callable, Generator, Iterable, Iterator, Mapping +from io import UnsupportedOperation +from typing import ( + TYPE_CHECKING, + Any, + Final, + Literal, + cast, + overload, +) + +from urllib3.exceptions import ( + DecodeError, + LocationParseError, + ProtocolError, + ReadTimeoutError, + SSLError, +) +from urllib3.fields import RequestField +from urllib3.filepost import encode_multipart_formdata +from urllib3.util import parse_url + +from ._internal_utils import to_native_string, unicode_is_ascii +from ._types import SupportsRead as _SupportsRead +from .auth import HTTPBasicAuth +from .compat import ( + JSONDecodeError, + basestring, + builtin_str, + chardet, + cookielib, + urlencode, + urlsplit, + urlunparse, +) +from .compat import json as complexjson +from .cookies import ( + _copy_cookie_jar, # type: ignore[reportPrivateUsage] + cookiejar_from_dict, + get_cookie_header, +) +from .exceptions import ( + ChunkedEncodingError, + ConnectionError, + ContentDecodingError, + HTTPError, + InvalidJSONError, + InvalidURL, + MissingSchema, + StreamConsumedError, +) +from .exceptions import JSONDecodeError as RequestsJSONDecodeError +from .exceptions import SSLError as RequestsSSLError +from .hooks import default_hooks +from .status_codes import codes +from .structures import CaseInsensitiveDict +from .utils import ( + check_header_validity, + get_auth_from_url, + guess_filename, + guess_json_utf, + iter_slices, + parse_header_links, + requote_uri, + stream_decode_response_unicode, + super_len, + to_key_val_list, +) + +if TYPE_CHECKING: + from http.cookiejar import CookieJar + + from typing_extensions import Self + + from . import _types as _t + from .adapters import HTTPAdapter + from .cookies import RequestsCookieJar + +#: The set of HTTP status codes that indicate an automatically +#: processable redirect. +REDIRECT_STATI: Final[tuple[int, ...]] = ( # type: ignore[assignment] + codes.moved, # 301 + codes.found, # 302 + codes.other, # 303 + codes.temporary_redirect, # 307 + codes.permanent_redirect, # 308 +) + +DEFAULT_REDIRECT_LIMIT: int = 30 +CONTENT_CHUNK_SIZE: int = 10 * 1024 +ITER_CHUNK_SIZE: int = 512 + + +class RequestEncodingMixin: + url: str | None + + @property + def path_url(self) -> str: + """Build the path URL to use.""" + + url: list[str] = [] + + p = urlsplit(cast(str, self.url)) + + path = p.path + if not path: + path = "/" + + url.append(path) + + query = p.query + if query: + url.append("?") + url.append(query) + + return "".join(url) + + @overload + @staticmethod + def _encode_params(data: str) -> str: ... + + @overload + @staticmethod + def _encode_params(data: bytes) -> bytes: ... + + @overload + @staticmethod + def _encode_params( + data: _t.SupportsRead[str | bytes], + ) -> _t.SupportsRead[str | bytes]: ... + + @overload + @staticmethod + def _encode_params(data: _t.KVDataType) -> str: ... + + @staticmethod + def _encode_params( + data: _t.EncodableDataType, + ) -> str | bytes | _t.SupportsRead[str | bytes]: + """Encode parameters in a piece of data. + + Will successfully encode parameters when passed as a dict or a list of + 2-tuples. Order is retained if data is a list of 2-tuples but arbitrary + if parameters are supplied as a dict. + """ + + if isinstance(data, (str, bytes)): + return data + elif isinstance(data, _SupportsRead): + return data + elif hasattr(data, "__iter__"): + result: list[tuple[bytes, bytes]] = [] + for k, vs in to_key_val_list(data): + if isinstance(vs, basestring) or not hasattr(vs, "__iter__"): + vs = [vs] + for v in vs: + if v is not None: + result.append( + ( + k.encode("utf-8") if isinstance(k, str) else k, + v.encode("utf-8") if isinstance(v, str) else v, + ) + ) + return urlencode(result, doseq=True) + else: + return data # type: ignore[return-value] # unreachable for valid _t.DataType + + @staticmethod + def _encode_files( + files: _t.FilesType, data: _t.RawDataType | None + ) -> tuple[bytes, str]: + """Build the body for a multipart/form-data request. + + Will successfully encode files when passed as a dict or a list of + tuples. Order is retained if data is a list of tuples but arbitrary + if parameters are supplied as a dict. + The tuples may be 2-tuples (filename, fileobj), 3-tuples (filename, fileobj, contentype) + or 4-tuples (filename, fileobj, contentype, custom_headers). + """ + if not files: + raise ValueError("Files must be provided.") + elif isinstance(data, basestring): + raise ValueError("Data must not be a string.") + + new_fields: list[RequestField | tuple[str, bytes]] = [] + fields = to_key_val_list(data or {}) + files = to_key_val_list(files or {}) + + for field, val in fields: + if isinstance(val, basestring) or not hasattr(val, "__iter__"): + val = [val] + for v in val: + if v is not None: + # Don't call str() on bytestrings: in Py3 it all goes wrong. + if not isinstance(v, bytes): + v = str(v) + + new_fields.append( + ( + field.decode("utf-8") + if isinstance(field, bytes) + else field, + v.encode("utf-8") if isinstance(v, str) else v, + ) + ) + + for k, v in files: + # support for explicit filename + ft = None + fh = None + if isinstance(v, (tuple, list)): + if len(v) == 2: + fn, fp = v + elif len(v) == 3: + fn, fp, ft = v + else: + fn, fp, ft, fh = v + else: + fn = guess_filename(v) or k + fp = v + + if isinstance(fp, (str, bytes, bytearray)): + fdata = fp + elif isinstance(fp, _SupportsRead): # type: ignore[reportUnnecessaryIsInstance] # defensive check for untyped callers + fdata = fp.read() + elif fp is None: # type: ignore[reportUnnecessaryComparison] # defensive check for untyped callers + continue + else: + fdata = fp + + rf = RequestField(name=k, data=fdata, filename=fn, headers=fh) + rf.make_multipart(content_type=ft) + new_fields.append(rf) + + body, content_type = encode_multipart_formdata(new_fields) + + return body, content_type + + +class RequestHooksMixin: + hooks: dict[str, list[_t.HookType]] + + def register_hook( + self, event: str, hook: Iterable[_t.HookType] | _t.HookType + ) -> None: + """Properly register a hook.""" + + if event not in self.hooks: + raise ValueError(f'Unsupported event specified, with event name "{event}"') + + if isinstance(hook, Callable): + self.hooks[event].append(hook) + elif hasattr(hook, "__iter__"): + self.hooks[event].extend(h for h in hook if isinstance(h, Callable)) # type: ignore[reportUnnecessaryIsInstance] # defensive runtime filter + + def deregister_hook(self, event: str, hook: _t.HookType) -> bool: + """Deregister a previously registered hook. + Returns True if the hook existed, False if not. + """ + + try: + self.hooks[event].remove(hook) + return True + except ValueError: + return False + + +class Request(RequestHooksMixin): + """A user-created :class:`Request ` object. + + Used to prepare a :class:`PreparedRequest `, which is sent to the server. + + :param method: HTTP method to use. + :param url: URL to send. + :param headers: dictionary of headers to send. + :param files: dictionary of {filename: fileobject} files to multipart upload. + :param data: the body to attach to the request. If a dictionary or + list of tuples ``[(key, value)]`` is provided, form-encoding will + take place. + :param json: json for the body to attach to the request (if files or data is not specified). + :param params: URL parameters to append to the URL. If a dictionary or + list of tuples ``[(key, value)]`` is provided, form-encoding will + take place. + :param auth: Auth handler or (user, pass) tuple. + :param cookies: dictionary or CookieJar of cookies to attach to this request. + :param hooks: dictionary of callback hooks, for internal usage. + + Usage:: + + >>> import requests + >>> req = requests.Request('GET', 'https://httpbin.org/get') + >>> req.prepare() + + """ + + method: str | None + url: _t.UriType | None + headers: Mapping[str, str | bytes] + files: _t.FilesType + data: _t.DataType + json: _t.JsonType + params: _t.ParamsType + auth: _t.AuthType + cookies: RequestsCookieJar | CookieJar | dict[str, str] | None + + def __init__( + self, + method: str | None = None, + url: _t.UriType | None = None, + headers: _t.HeadersType = None, + files: _t.FilesType = None, + data: _t.DataType = None, + params: _t.ParamsType = None, + auth: _t.AuthType = None, + cookies: RequestsCookieJar | CookieJar | dict[str, str] | None = None, + hooks: _t.HooksInputType | None = None, + json: _t.JsonType = None, + ) -> None: + # Default empty dicts for dict params. + data = [] if data is None else data + files = [] if files is None else files + headers = {} if headers is None else headers + params = {} if params is None else params + hooks = {} if hooks is None else hooks + + self.hooks = default_hooks() + for k, v in list(hooks.items()): + self.register_hook(event=k, hook=v) + + self.method = method + self.url = url + self.headers = headers + self.files = files + self.data = data + self.json = json + self.params = params + self.auth = auth + self.cookies = cookies + + def __repr__(self) -> str: + return f"" + + def prepare(self) -> PreparedRequest: + """Constructs a :class:`PreparedRequest ` for transmission and returns it.""" + p = PreparedRequest() + p.prepare( + method=self.method, + url=self.url, + headers=self.headers, + files=self.files, + data=self.data, + json=self.json, + params=self.params, + auth=self.auth, + cookies=self.cookies, + hooks=self.hooks, + ) + return p + + +class PreparedRequest(RequestEncodingMixin, RequestHooksMixin): + """The fully mutable :class:`PreparedRequest ` object, + containing the exact bytes that will be sent to the server. + + Instances are generated from a :class:`Request ` object, and + should not be instantiated manually; doing so may produce undesirable + effects. + + Usage:: + + >>> import requests + >>> req = requests.Request('GET', 'https://httpbin.org/get') + >>> r = req.prepare() + >>> r + + + >>> s = requests.Session() + >>> s.send(r) + + """ + + method: str | None + url: str | None + headers: CaseInsensitiveDict[str | bytes] + _cookies: RequestsCookieJar | CookieJar | None + body: _t.BodyType + hooks: dict[str, list[_t.HookType]] + _body_position: int | object | None + + def __init__(self) -> None: + #: HTTP verb to send to the server. + self.method = None + #: HTTP URL to send the request to. + self.url = None + #: dictionary of HTTP headers. + self.headers = None # type: ignore[assignment] + # The `CookieJar` used to create the Cookie header will be stored here + # after prepare_cookies is called + self._cookies = None + #: request body to send to the server. + self.body = None + #: dictionary of callback hooks, for internal usage. + self.hooks = default_hooks() + #: integer denoting starting position of a readable file-like body. + self._body_position = None + + def prepare( + self, + method: str | None = None, + url: _t.UriType | None = None, + headers: Mapping[str, str | bytes] | None = None, + files: _t.FilesType = None, + data: _t.DataType = None, + params: _t.ParamsType = None, + auth: _t.AuthType = None, + cookies: RequestsCookieJar | CookieJar | dict[str, str] | None = None, + hooks: _t.HooksInputType | None = None, + json: _t.JsonType = None, + ) -> None: + """Prepares the entire request with the given parameters.""" + + url = cast("_t.UriType", url) + self.prepare_method(method) + self.prepare_url(url, params) + self.prepare_headers(headers) + self.prepare_cookies(cookies) + self.prepare_body(data, files, json) + self.prepare_auth(auth, url) + + # Note that prepare_auth must be last to enable authentication schemes + # such as OAuth to work on a fully prepared request. + + # This MUST go after prepare_auth. Authenticators could add a hook + self.prepare_hooks(hooks) + + def __repr__(self) -> str: + return f"" + + def copy(self) -> PreparedRequest: + p = PreparedRequest() + p.method = self.method + p.url = self.url + p.headers = self.headers.copy() if self.headers is not None else None # type: ignore[assignment] + p._cookies = _copy_cookie_jar(self._cookies) + p.body = self.body + p.hooks = self.hooks + p._body_position = self._body_position + return p + + def prepare_method(self, method: str | None) -> None: + """Prepares the given HTTP method.""" + self.method = method + if self.method is not None: + self.method = to_native_string(self.method.upper()) + + @staticmethod + def _get_idna_encoded_host(host: str) -> str: + import idna + + try: + host = idna.encode(host, uts46=True).decode("utf-8") + except idna.IDNAError: + raise UnicodeError + return host + + def prepare_url( + self, + url: _t.UriType, + params: _t.ParamsType, + ) -> None: + """Prepares the given HTTP URL.""" + #: Accept objects that have string representations. + #: We're unable to blindly call unicode/str functions + #: as this will include the bytestring indicator (b'') + #: on python 3.x. + #: https://github.com/psf/requests/pull/2238 + if isinstance(url, bytes): + url = url.decode("utf8") + else: + url = str(url) + + # Remove leading whitespaces from url + url = url.lstrip() + + # Don't do any URL preparation for non-HTTP schemes like `mailto`, + # `data` etc to work around exceptions from `url_parse`, which + # handles RFC 3986 only. + if ":" in url and not url.lower().startswith("http"): + self.url = url + return + + # Support for unicode domain names and paths. + try: + scheme, auth, host, port, path, query, fragment = parse_url(url) + except LocationParseError as e: + raise InvalidURL(*e.args) + + if not scheme: + raise MissingSchema( + f"Invalid URL {url!r}: No scheme supplied. " + f"Perhaps you meant https://{url}?" + ) + + if not host: + raise InvalidURL(f"Invalid URL {url!r}: No host supplied") + + # In general, we want to try IDNA encoding the hostname if the string contains + # non-ASCII characters. This allows users to automatically get the correct IDNA + # behaviour. For strings containing only ASCII characters, we need to also verify + # it doesn't start with a wildcard (*), before allowing the unencoded hostname. + if not unicode_is_ascii(host): + try: + host = self._get_idna_encoded_host(host) + except UnicodeError: + raise InvalidURL("URL has an invalid label.") + elif host.startswith(("*", ".")): + raise InvalidURL("URL has an invalid label.") + + # Carefully reconstruct the network location + netloc = auth or "" + if netloc: + netloc += "@" + netloc += host + if port: + netloc += f":{port}" + + # Bare domains aren't valid URLs. + if not path: + path = "/" + + if isinstance(params, (str, bytes)): + params = to_native_string(params) + + if params is not None: + enc_params = self._encode_params(params) + else: + enc_params = "" + + if enc_params: + if query: + query = f"{query}&{enc_params}" + else: + query = enc_params + + url = requote_uri(urlunparse((scheme, netloc, path, "", query, fragment))) + self.url = url + + def prepare_headers(self, headers: Mapping[str, str | bytes] | None) -> None: + """Prepares the given HTTP headers.""" + + self.headers = CaseInsensitiveDict() + if headers: + for header in headers.items(): + # Raise exception on invalid header value. + check_header_validity(header) + name, value = header + self.headers[to_native_string(name)] = value + + def prepare_body( + self, data: _t.DataType, files: _t.FilesType, json: _t.JsonType = None + ) -> None: + """Prepares the given HTTP body data.""" + + # Check if file, fo, generator, iterator. + # If not, run through normal process. + + # Nottin' on you. + body = None + content_type = None + + if not data and json is not None: + # urllib3 requires a bytes-like body. Python 2's json.dumps + # provides this natively, but Python 3 gives a Unicode string. + content_type = "application/json" + + try: + body = complexjson.dumps(json, allow_nan=False) + except ValueError as ve: + raise InvalidJSONError(ve, request=self) + + if not isinstance(body, bytes): + body = body.encode("utf-8") + + # data that proxies attributes to underlying objects needs hasattr + is_iterable = isinstance(data, Iterable) or hasattr(data, "__iter__") + if is_iterable and not isinstance(data, (str, bytes, list, tuple, Mapping)): + try: + length = super_len(data) + except (TypeError, AttributeError, UnsupportedOperation): + length = None + + body = data + + if getattr(body, "tell", None) is not None: + # Record the current file position before reading. + # This will allow us to rewind a file in the event + # of a redirect. + try: + self._body_position = body.tell() # type: ignore[union-attr] # guarded by getattr check + except OSError: + # This differentiates from None, allowing us to catch + # a failed `tell()` later when trying to rewind the body + self._body_position = object() + + if files: + raise NotImplementedError( + "Streamed bodies and files are mutually exclusive." + ) + + if length: + self.headers["Content-Length"] = builtin_str(length) + else: + self.headers["Transfer-Encoding"] = "chunked" + else: + # After is_stream filtering, remaining data is raw (not streamed) + raw_data = cast("_t.RawDataType | None", data) + + # Multi-part file uploads. + if files: + (body, content_type) = self._encode_files(files, raw_data) + else: + if raw_data: + body = self._encode_params(raw_data) + if isinstance(data, basestring) or isinstance(data, _SupportsRead): + content_type = None + else: + content_type = "application/x-www-form-urlencoded" + + self.prepare_content_length(body) + + # Add content-type if it wasn't explicitly provided. + if content_type and ("content-type" not in self.headers): + self.headers["Content-Type"] = content_type + + self.body = body # type: ignore[assignment] # body transforms from DataType to BodyType + + def prepare_content_length(self, body: _t.BodyType) -> None: + """Prepare Content-Length header based on request method and body""" + if body is not None: + length = super_len(body) + if length: + # If length exists, set it. Otherwise, we fallback + # to Transfer-Encoding: chunked. + self.headers["Content-Length"] = builtin_str(length) + elif ( + self.method not in ("GET", "HEAD") + and self.headers.get("Content-Length") is None + ): + # Set Content-Length to 0 for methods that can have a body + # but don't provide one. (i.e. not GET or HEAD) + self.headers["Content-Length"] = "0" + + def prepare_auth( + self, + auth: _t.AuthType, + url: _t.UriType = "", + ) -> None: + """Prepares the given HTTP auth data.""" + + # If no Auth is explicitly provided, extract it from the URL first. + if auth is None: + url_auth = get_auth_from_url(cast(str, self.url)) + auth = url_auth if any(url_auth) else None + + if auth: + if isinstance(auth, tuple) and len(auth) == 2: # type: ignore[arg-type] # pyright widens tuple from Callable in AuthType + # special-case basic HTTP auth + auth_handler = HTTPBasicAuth(*auth) # type: ignore[arg-type] # pyright widens tuple from Callable in AuthType + else: + # TODO: can be fixed by flipping the conditionals + auth_handler = cast("Callable[..., PreparedRequest]", auth) + + # Allow auth to make its changes. + r = auth_handler(self) + + # Update self to reflect the auth changes. + self.__dict__.update(r.__dict__) + + # Recompute Content-Length + self.prepare_content_length(self.body) + + def prepare_cookies( + self, cookies: RequestsCookieJar | CookieJar | dict[str, str] | None + ) -> None: + """Prepares the given HTTP cookie data. + + This function eventually generates a ``Cookie`` header from the + given cookies using cookielib. Due to cookielib's design, the header + will not be regenerated if it already exists, meaning this function + can only be called once for the life of the + :class:`PreparedRequest ` object. Any subsequent calls + to ``prepare_cookies`` will have no actual effect, unless the "Cookie" + header is removed beforehand. + """ + if isinstance(cookies, cookielib.CookieJar): + self._cookies = cookies + else: + self._cookies = cookiejar_from_dict(cookies) + + cookies_jar = cast("CookieJar", self._cookies) + cookie_header = get_cookie_header(cookies_jar, self) + if cookie_header is not None: + self.headers["Cookie"] = cookie_header + + def prepare_hooks(self, hooks: _t.HooksInputType | None) -> None: + """Prepares the given hooks.""" + # hooks can be passed as None to the prepare method and to this + # method. To prevent iterating over None, simply use an empty list + # if hooks is False-y + hooks = hooks or {} + for event in hooks: + self.register_hook(event, hooks[event]) + + +class Response: + """The :class:`Response ` object, which contains a + server's response to an HTTP request. + """ + + _content: bytes | Literal[False] | None + _content_consumed: bool + _next: PreparedRequest | None + status_code: int + headers: CaseInsensitiveDict[str] + raw: Any + url: str + encoding: str | None + history: list[Response] + reason: str + cookies: RequestsCookieJar + elapsed: datetime.timedelta + request: PreparedRequest + connection: HTTPAdapter + + __attrs__: list[str] = [ + "_content", + "status_code", + "headers", + "url", + "history", + "encoding", + "reason", + "cookies", + "elapsed", + "request", + ] + + def __init__(self) -> None: + self._content = False + self._content_consumed = False + self._next = None + + #: Integer Code of responded HTTP Status, e.g. 404 or 200. + self.status_code = None # type: ignore[assignment] + + #: Case-insensitive Dictionary of Response Headers. + #: For example, ``headers['content-encoding']`` will return the + #: value of a ``'Content-Encoding'`` response header. + self.headers = CaseInsensitiveDict() + + #: File-like object representation of response (for advanced usage). + #: Use of ``raw`` requires that ``stream=True`` be set on the request. + #: This requirement does not apply for use internally to Requests. + self.raw = None + + #: Final URL location of Response. + self.url = None # type: ignore[assignment] + + #: Encoding to decode with when accessing r.text. + self.encoding = None + + #: A list of :class:`Response ` objects from + #: the history of the Request. Any redirect responses will end + #: up here. The list is sorted from the oldest to the most recent request. + self.history = [] + + #: Textual reason of responded HTTP Status, e.g. "Not Found" or "OK". + self.reason = None # type: ignore[assignment] + + #: A CookieJar of Cookies the server sent back. + self.cookies = cookiejar_from_dict({}) + + #: The amount of time elapsed between sending the request + #: and the arrival of the response (as a timedelta). + #: This property specifically measures the time taken between sending + #: the first byte of the request and finishing parsing the headers. It + #: is therefore unaffected by consuming the response content or the + #: value of the ``stream`` keyword argument. + self.elapsed = datetime.timedelta(0) + + #: The :class:`PreparedRequest ` object to which this + #: is a response. + self.request = None # type: ignore[assignment] + + def __enter__(self) -> Self: + return self + + def __exit__(self, *args: Any) -> None: + self.close() + + def __getstate__(self) -> dict[str, Any]: + # Consume everything; accessing the content attribute makes + # sure the content has been fully read. + if not self._content_consumed: + self.content + + return {attr: getattr(self, attr, None) for attr in self.__attrs__} + + def __setstate__(self, state: dict[str, Any]) -> None: + for name, value in state.items(): + setattr(self, name, value) + + # pickled objects do not have .raw + setattr(self, "_content_consumed", True) + setattr(self, "raw", None) + + def __repr__(self) -> str: + return f"" + + def __bool__(self) -> bool: + """Returns True if :attr:`status_code` is less than 400. + + This attribute checks if the status code of the response is between + 400 and 600 to see if there was a client error or a server error. If + the status code, is between 200 and 400, this will return True. This + is **not** a check to see if the response code is ``200 OK``. + """ + return self.ok + + def __nonzero__(self) -> bool: + """Returns True if :attr:`status_code` is less than 400. + + This attribute checks if the status code of the response is between + 400 and 600 to see if there was a client error or a server error. If + the status code, is between 200 and 400, this will return True. This + is **not** a check to see if the response code is ``200 OK``. + """ + return self.ok + + def __iter__(self) -> Iterator[bytes]: + """Allows you to use a response as an iterator.""" + return self.iter_content(128) + + @property + def ok(self) -> bool: + """Returns True if :attr:`status_code` is less than 400, False if not. + + This attribute checks if the status code of the response is between + 400 and 600 to see if there was a client error or a server error. If + the status code is between 200 and 400, this will return True. This + is **not** a check to see if the response code is ``200 OK``. + """ + try: + self.raise_for_status() + except HTTPError: + return False + return True + + @property + def is_redirect(self) -> bool: + """True if this Response is a well-formed HTTP redirect that could have + been processed automatically (by :meth:`Session.resolve_redirects`). + """ + return "location" in self.headers and self.status_code in REDIRECT_STATI + + @property + def is_permanent_redirect(self) -> bool: + """True if this Response one of the permanent versions of redirect.""" + return "location" in self.headers and self.status_code in ( + codes.moved_permanently, + codes.permanent_redirect, + ) + + @property + def next(self) -> PreparedRequest | None: + """Returns a PreparedRequest for the next request in a redirect chain, if there is one.""" + return self._next + + @property + def apparent_encoding(self) -> str | None: + """The apparent encoding, provided by the charset_normalizer or chardet libraries.""" + if chardet is not None: + return chardet.detect(self.content)["encoding"] + else: + # If no character detection library is available, we'll fall back + # to a standard Python utf-8 str. + return "utf-8" + + @overload + def iter_content( + self, chunk_size: int | None = 1, decode_unicode: Literal[False] = False + ) -> Iterator[bytes]: ... + @overload + def iter_content( + self, chunk_size: int | None = 1, *, decode_unicode: Literal[True] + ) -> Iterator[str | bytes]: ... + def iter_content( + self, chunk_size: int | None = 1, decode_unicode: bool = False + ) -> Iterator[str | bytes]: + """Iterates over the response data. When stream=True is set on the + request, this avoids reading the content at once into memory for + large responses. The chunk size is the number of bytes it should + read into memory. This is not necessarily the length of each item + returned as decoding can take place. + + chunk_size must be of type int or None. A value of None will + function differently depending on the value of `stream`. + stream=True will read data as it arrives in whatever size the + chunks are received. If stream=False, data is returned as + a single chunk. + + If decode_unicode is True, content will be decoded using encoding + information from the response. If no encoding information is available, + bytes will be returned. This can be bypassed by manually setting + `encoding` on the response. + """ + + def generate() -> Generator[bytes, None, None]: + # Special case for urllib3. + if hasattr(self.raw, "stream"): + try: + yield from self.raw.stream(chunk_size, decode_content=True) + except ProtocolError as e: + raise ChunkedEncodingError(e) + except DecodeError as e: + raise ContentDecodingError(e) + except ReadTimeoutError as e: + raise ConnectionError(e) + except SSLError as e: + raise RequestsSSLError(e) + else: + # Standard file-like object. + while True: + chunk = self.raw.read(chunk_size) + if not chunk: + break + yield chunk + + self._content_consumed = True + + if self._content_consumed and isinstance(self._content, bool): + raise StreamConsumedError() + elif chunk_size is not None and not isinstance(chunk_size, int): # type: ignore[reportUnnecessaryIsInstance] # runtime guard for untyped callers + raise TypeError( + f"chunk_size must be an int, it is instead a {type(chunk_size)}." + ) + + if self._content_consumed: + # simulate reading small chunks of the content + content = cast(bytes, self._content) + chunks = iter_slices(content, chunk_size) + else: + chunks = generate() + + if decode_unicode: + chunks = stream_decode_response_unicode(chunks, self) + + return chunks + + @overload + def iter_lines( + self, + chunk_size: int = ITER_CHUNK_SIZE, + decode_unicode: Literal[False] = False, + delimiter: bytes | None = None, + ) -> Iterator[bytes]: ... + @overload + def iter_lines( + self, + chunk_size: int = ITER_CHUNK_SIZE, + *, + decode_unicode: Literal[True], + delimiter: str | bytes | None = None, + ) -> Iterator[str | bytes]: ... + def iter_lines( + self, + chunk_size: int = ITER_CHUNK_SIZE, + decode_unicode: bool = False, + delimiter: str | bytes | None = None, + ) -> Iterator[str | bytes]: + """Iterates over the response data, one line at a time. When + stream=True is set on the request, this avoids reading the + content at once into memory for large responses. + + The decode_unicode param works the same as in `iter_content`, with the + same caveats. + + .. note:: This method is not reentrant safe. + """ + + pending: str | bytes | None = None + + for chunk in self.iter_content( + chunk_size=chunk_size, decode_unicode=decode_unicode + ): + if pending is not None: + # TODO: remove cast after iter_lines rewrite + chunk = cast("str | bytes", pending + chunk) # type: ignore[operator] + + if delimiter: + lines = chunk.split(delimiter) # type: ignore[arg-type] + else: + lines = chunk.splitlines() + + if lines and lines[-1] and chunk and lines[-1][-1] == chunk[-1]: + pending = lines.pop() + else: + pending = None + + yield from lines + + if pending is not None: + yield pending + + @property + def content(self) -> bytes: + """Content of the response, in bytes.""" + + if self._content is False: + # Read the contents. + if self._content_consumed: + raise RuntimeError("The content for this response was already consumed") + + if self.status_code == 0 or self.raw is None: + self._content = None + else: + self._content = b"".join(self.iter_content(CONTENT_CHUNK_SIZE)) or b"" + + self._content_consumed = True + # don't need to release the connection; that's been handled by urllib3 + # since we exhausted the data. + return self._content # type: ignore[return-value] + + @property + def text(self) -> str: + """Content of the response, in unicode. + + If Response.encoding is None, encoding will be guessed using + ``charset_normalizer`` or ``chardet``. + + The encoding of the response content is determined based solely on HTTP + headers, following RFC 2616 to the letter. If you can take advantage of + non-HTTP knowledge to make a better guess at the encoding, you should + set ``r.encoding`` appropriately before accessing this property. + """ + + # Try charset from content-type + content = None + encoding = self.encoding + + if not self.content: + return "" + + # Fallback to auto-detected encoding. + if self.encoding is None: + encoding = self.apparent_encoding + + # Decode unicode from given encoding. + try: + content = str(self.content, encoding or "utf-8", errors="replace") + except (LookupError, TypeError): + # A LookupError is raised if the encoding was not found which could + # indicate a misspelling or similar mistake. + # + # A TypeError can be raised if encoding is None + # + # So we try blindly encoding. + content = str(self.content, errors="replace") + + return content + + def json(self, **kwargs: Any) -> Any: + r"""Decodes the JSON response body (if any) as a Python object. + + This may return a dictionary, list, etc. depending on what is in the response. + + :param \*\*kwargs: Optional arguments that ``json.loads`` takes. + :raises requests.exceptions.JSONDecodeError: If the response body does not + contain valid json. + """ + + if not self.encoding and self.content and len(self.content) > 3: + # No encoding set. JSON RFC 4627 section 3 states we should expect + # UTF-8, -16 or -32. Detect which one to use; If the detection or + # decoding fails, fall back to `self.text` (using charset_normalizer to make + # a best guess). + encoding = guess_json_utf(self.content) + if encoding is not None: + try: + return complexjson.loads(self.content.decode(encoding), **kwargs) + except UnicodeDecodeError: + # Wrong UTF codec detected; usually because it's not UTF-8 + # but some other 8-bit codec. This is an RFC violation, + # and the server didn't bother to tell us what codec *was* + # used. + pass + except JSONDecodeError as e: + raise RequestsJSONDecodeError(e.msg, e.doc, e.pos) + + try: + return complexjson.loads(self.text, **kwargs) + except JSONDecodeError as e: + # Catch JSON-related errors and raise as requests.JSONDecodeError + # This aliases json.JSONDecodeError and simplejson.JSONDecodeError + raise RequestsJSONDecodeError(e.msg, e.doc, e.pos) + + @property + def links(self) -> dict[str, dict[str, str]]: + """Returns the parsed header links of the response, if any.""" + + header = self.headers.get("link") + + resolved_links: dict[str, dict[str, str]] = {} + + if header: + links = parse_header_links(header) + + for link in links: + key = link.get("rel") or link.get("url") + if key is not None: + resolved_links[key] = link + + return resolved_links + + def raise_for_status(self) -> None: + """Raises :class:`HTTPError`, if one occurred.""" + + http_error_msg = "" + if isinstance(self.reason, bytes): + # We attempt to decode utf-8 first because some servers + # choose to localize their reason strings. If the string + # isn't utf-8, we fall back to iso-8859-1 for all other + # encodings. (See PR #3538) + try: + reason = self.reason.decode("utf-8") + except UnicodeDecodeError: + reason = self.reason.decode("iso-8859-1") + else: + reason = self.reason + + if 400 <= self.status_code < 500: + http_error_msg = ( + f"{self.status_code} Client Error: {reason} for url: {self.url}" + ) + + elif 500 <= self.status_code < 600: + http_error_msg = ( + f"{self.status_code} Server Error: {reason} for url: {self.url}" + ) + + if http_error_msg: + raise HTTPError(http_error_msg, response=self) + + def close(self) -> None: + """Releases the connection back to the pool. Once this method has been + called the underlying ``raw`` object must not be accessed again. + + *Note: Should not normally need to be called explicitly.* + """ + if not self._content_consumed: + self.raw.close() + + release_conn = getattr(self.raw, "release_conn", None) + if release_conn is not None: + release_conn() diff --git a/.venv/lib/python3.12/site-packages/requests/packages.py b/.venv/lib/python3.12/site-packages/requests/packages.py new file mode 100644 index 0000000000000000000000000000000000000000..5ab3d8e250de8475cb22553f564e5444e02c7460 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/requests/packages.py @@ -0,0 +1,23 @@ +import sys + +from .compat import chardet + +# This code exists for backwards compatibility reasons. +# I don't like it either. Just look the other way. :) + +for package in ("urllib3", "idna"): + locals()[package] = __import__(package) + # This traversal is apparently necessary such that the identities are + # preserved (requests.packages.urllib3.* is urllib3.*) + for mod in list(sys.modules): + if mod == package or mod.startswith(f"{package}."): + sys.modules[f"requests.packages.{mod}"] = sys.modules[mod] + +if chardet is not None: + target = chardet.__name__ + for mod in list(sys.modules): + if mod == target or mod.startswith(f"{target}."): + imported_mod = sys.modules[mod] + sys.modules[f"requests.packages.{mod}"] = imported_mod + mod = mod.replace(target, "chardet") + sys.modules[f"requests.packages.{mod}"] = imported_mod diff --git a/.venv/lib/python3.12/site-packages/requests/py.typed b/.venv/lib/python3.12/site-packages/requests/py.typed new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/.venv/lib/python3.12/site-packages/requests/sessions.py b/.venv/lib/python3.12/site-packages/requests/sessions.py new file mode 100644 index 0000000000000000000000000000000000000000..feaf34053a911d4b9051069aeb57e595b4d00165 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/requests/sessions.py @@ -0,0 +1,920 @@ +""" +requests.sessions +~~~~~~~~~~~~~~~~~ + +This module provides a Session object to manage and persist settings across +requests (cookies, auth, proxies). +""" + +from __future__ import annotations + +import os +import sys +import time +from collections import OrderedDict +from collections.abc import Generator, Mapping, MutableMapping +from datetime import timedelta +from typing import TYPE_CHECKING, Any, cast + +from ._internal_utils import to_native_string +from ._types import is_prepared as _is_prepared +from .adapters import HTTPAdapter +from .auth import _basic_auth_str # type: ignore[reportPrivateUsage] +from .compat import cookielib, urljoin, urlparse +from .cookies import ( + RequestsCookieJar, + cookiejar_from_dict, + extract_cookies_to_jar, + merge_cookies, +) +from .exceptions import ( + ChunkedEncodingError, + ContentDecodingError, + InvalidSchema, + TooManyRedirects, +) +from .hooks import default_hooks, dispatch_hook + +# formerly defined here, reexposed here for backward compatibility +from .models import ( # noqa: F401 + DEFAULT_REDIRECT_LIMIT, + REDIRECT_STATI, # type: ignore[reportUnusedImport] + PreparedRequest, + Request, + Response, +) +from .status_codes import codes +from .structures import CaseInsensitiveDict +from .utils import ( # noqa: F401 + DEFAULT_PORTS, + default_headers, + get_auth_from_url, + get_environ_proxies, + get_netrc_auth, + requote_uri, + resolve_proxies, + rewind_body, + should_bypass_proxies, # type: ignore[reportUnusedImport] # re-export for external consumers + to_key_val_list, +) + +if TYPE_CHECKING: + from http.cookiejar import CookieJar + + from typing_extensions import Self, Unpack + + from . import _types as _t + from .adapters import BaseAdapter + +# Preferred clock, based on which one is more accurate on a given system. +if sys.platform == "win32": + preferred_clock = time.perf_counter +else: + preferred_clock = time.time + + +def merge_setting( + request_setting: Any, session_setting: Any, dict_class: type = OrderedDict +) -> Any: + """Determines appropriate setting for a given request, taking into account + the explicit setting on that request, and the setting in the session. If a + setting is a dictionary, they will be merged together using `dict_class` + """ + + if session_setting is None: + return request_setting + + if request_setting is None: + return session_setting + + # Bypass if not a dictionary (e.g. verify) + if not ( + isinstance(session_setting, Mapping) and isinstance(request_setting, Mapping) + ): + return request_setting + + merged_setting = dict_class(to_key_val_list(session_setting)) # type: ignore[arg-type] # isinstance narrows Any to Mapping[Unknown] + merged_setting.update(to_key_val_list(request_setting)) # type: ignore[arg-type] + + # Remove keys that are set to None. Extract keys first to avoid altering + # the dictionary during iteration. + none_keys = [k for (k, v) in merged_setting.items() if v is None] + for key in none_keys: + del merged_setting[key] + + return merged_setting + + +def merge_hooks( + request_hooks: _t.HooksType, + session_hooks: _t.HooksType, + dict_class: type = OrderedDict, +) -> _t.HooksType: + """Properly merges both requests and session hooks. + + This is necessary because when request_hooks == {'response': []}, the + merge breaks Session hooks entirely. + """ + if session_hooks is None or session_hooks.get("response") == []: + return request_hooks + + if request_hooks is None or request_hooks.get("response") == []: + return session_hooks + + return merge_setting(request_hooks, session_hooks, dict_class) + + +class SessionRedirectMixin: + max_redirects: int + trust_env: bool + cookies: RequestsCookieJar + + def send(self, request: PreparedRequest, **kwargs: Any) -> Response: ... + + def get_redirect_target(self, resp: Response) -> str | None: + """Receives a Response. Returns a redirect URI or ``None``""" + # Due to the nature of how requests processes redirects this method will + # be called at least once upon the original response and at least twice + # on each subsequent redirect response (if any). + # If a custom mixin is used to handle this logic, it may be advantageous + # to cache the redirect location onto the response object as a private + # attribute. + if resp.is_redirect: + location = resp.headers["location"] + # Currently the underlying http module on py3 decode headers + # in latin1, but empirical evidence suggests that latin1 is very + # rarely used with non-ASCII characters in HTTP headers. + # It is more likely to get UTF8 header rather than latin1. + # This causes incorrect handling of UTF8 encoded location headers. + # To solve this, we re-encode the location in latin1. + location = location.encode("latin1") + return to_native_string(location, "utf8") + return None + + def should_strip_auth(self, old_url: str, new_url: str) -> bool: + """Decide whether Authorization header should be removed when redirecting""" + old_parsed = urlparse(old_url) + new_parsed = urlparse(new_url) + if old_parsed.hostname != new_parsed.hostname: + return True + # Special case: allow http -> https redirect when using the standard + # ports. This isn't specified by RFC 7235, but is kept to avoid + # breaking backwards compatibility with older versions of requests + # that allowed any redirects on the same host. + if ( + old_parsed.scheme == "http" + and old_parsed.port in (80, None) + and new_parsed.scheme == "https" + and new_parsed.port in (443, None) + ): + return False + + # Handle default port usage corresponding to scheme. + changed_port = old_parsed.port != new_parsed.port + changed_scheme = old_parsed.scheme != new_parsed.scheme + default_port = (DEFAULT_PORTS.get(old_parsed.scheme, None), None) + if ( + not changed_scheme + and old_parsed.port in default_port + and new_parsed.port in default_port + ): + return False + + # Standard case: root URI must match + return changed_port or changed_scheme + + def resolve_redirects( + self, + resp: Response, + req: PreparedRequest, + stream: bool = False, + timeout: _t.TimeoutType = None, + verify: _t.VerifyType = True, + cert: _t.CertType = None, + proxies: dict[str, str] | None = None, + yield_requests: bool = False, + **adapter_kwargs: Any, + ) -> Generator[Response, None, None]: + """Receives a Response. Returns a generator of Responses or Requests.""" + + hist: list[Response] = [] # keep track of history + + url = self.get_redirect_target(resp) + previous_fragment = urlparse(req.url).fragment + while url: + prepared_request = req.copy() + + # Update history and keep track of redirects. + resp.history = hist[:] + hist.append(resp) + + try: + resp.content # Consume socket so it can be released + except (ChunkedEncodingError, ContentDecodingError, RuntimeError): + resp.raw.read(decode_content=False) + + if len(resp.history) >= self.max_redirects: + raise TooManyRedirects( + f"Exceeded {self.max_redirects} redirects.", response=resp + ) + + # Release the connection back into the pool. + resp.close() + + # Handle redirection without scheme (see: RFC 1808 Section 4) + if url.startswith("//"): + parsed_rurl = urlparse(resp.url) + url = ":".join([to_native_string(parsed_rurl.scheme), url]) + + # Normalize url case and attach previous fragment if needed (RFC 7231 7.1.2) + parsed = urlparse(url) + if parsed.fragment == "" and previous_fragment: + parsed = parsed._replace(fragment=previous_fragment) + elif parsed.fragment: + previous_fragment = parsed.fragment + url = parsed.geturl() + + # Facilitate relative 'location' headers, as allowed by RFC 7231. + # (e.g. '/path/to/resource' instead of 'http://domain.tld/path/to/resource') + # Compliant with RFC3986, we percent encode the url. + if not parsed.netloc: + url = urljoin(resp.url, requote_uri(url)) + else: + url = requote_uri(url) + + prepared_request.url = to_native_string(url) + + self.rebuild_method(prepared_request, resp) + + # https://github.com/psf/requests/issues/1084 + if resp.status_code not in ( + codes.temporary_redirect, + codes.permanent_redirect, + ): + # https://github.com/psf/requests/issues/3490 + purged_headers = ("Content-Length", "Content-Type", "Transfer-Encoding") + for header in purged_headers: + prepared_request.headers.pop(header, None) + prepared_request.body = None + + headers = prepared_request.headers + headers.pop("Cookie", None) + + # Extract any cookies sent on the response to the cookiejar + # in the new request. Because we've mutated our copied prepared + # request, use the old one that we haven't yet touched. + cookie_jar = cast("CookieJar", prepared_request._cookies) # type: ignore[reportPrivateUsage] + extract_cookies_to_jar(cookie_jar, req, resp.raw) + merge_cookies(cookie_jar, self.cookies) + prepared_request.prepare_cookies(cookie_jar) + + # Rebuild auth and proxy information. + proxies = self.rebuild_proxies(prepared_request, proxies) + self.rebuild_auth(prepared_request, resp) + + # A failed tell() sets `_body_position` to `object()`. This non-None + # value ensures `rewindable` will be True, allowing us to raise an + # UnrewindableBodyError, instead of hanging the connection. + rewindable = prepared_request._body_position is not None and ( # type: ignore[reportPrivateUsage] + "Content-Length" in headers or "Transfer-Encoding" in headers + ) + + # Attempt to rewind consumed file-like object. + if rewindable: + rewind_body(prepared_request) + + # Override the original request. + req = prepared_request + + if yield_requests: + yield req # type: ignore[misc] # Internal use only, returns PreparedRequest + else: + resp = self.send( + req, + stream=stream, + timeout=timeout, + verify=verify, + cert=cert, + proxies=proxies, + allow_redirects=False, + **adapter_kwargs, + ) + + extract_cookies_to_jar(self.cookies, prepared_request, resp.raw) + + # extract redirect url, if any, for the next loop + url = self.get_redirect_target(resp) + yield resp + + def rebuild_auth( + self, prepared_request: PreparedRequest, response: Response + ) -> None: + """When being redirected we may want to strip authentication from the + request to avoid leaking credentials. This method intelligently removes + and reapplies authentication where possible to avoid credential loss. + """ + original_request = response.request + assert _is_prepared(original_request) + assert _is_prepared(prepared_request) + + headers = prepared_request.headers + original_url = original_request.url + url = prepared_request.url + + if "Authorization" in headers and self.should_strip_auth(original_url, url): + # If we get redirected to a new host, we should strip out any + # authentication headers. + del headers["Authorization"] + + # .netrc might have more auth for us on our new host. + new_auth = get_netrc_auth(url) if self.trust_env else None + if new_auth is not None: + prepared_request.prepare_auth(new_auth) + + def rebuild_proxies( + self, + prepared_request: PreparedRequest, + proxies: dict[str, str] | None, + ) -> dict[str, str]: + """This method re-evaluates the proxy configuration by considering the + environment variables. If we are redirected to a URL covered by + NO_PROXY, we strip the proxy configuration. Otherwise, we set missing + proxy keys for this URL (in case they were stripped by a previous + redirect). + + This method also replaces the Proxy-Authorization header where + necessary. + + :rtype: dict + """ + assert _is_prepared(prepared_request) + headers = prepared_request.headers + scheme = urlparse(prepared_request.url).scheme + new_proxies = resolve_proxies(prepared_request, proxies, self.trust_env) + + if "Proxy-Authorization" in headers: + del headers["Proxy-Authorization"] + + try: + username, password = get_auth_from_url(new_proxies[scheme]) + except KeyError: + username, password = None, None + + # urllib3 handles proxy authorization for us in the standard adapter. + # Avoid appending this to TLS tunneled requests where it may be leaked. + if not scheme.startswith("https") and username and password: + headers["Proxy-Authorization"] = _basic_auth_str(username, password) + + return new_proxies + + def rebuild_method( + self, prepared_request: PreparedRequest, response: Response + ) -> None: + """When being redirected we may want to change the method of the request + based on certain specs or browser behavior. + """ + method = prepared_request.method + + # https://tools.ietf.org/html/rfc7231#section-6.4.4 + if response.status_code == codes.see_other and method != "HEAD": + method = "GET" + + # Do what the browsers do, despite standards... + # First, turn 302s into GETs. + if response.status_code == codes.found and method != "HEAD": + method = "GET" + + # Second, if a POST is responded to with a 301, turn it into a GET. + # This bizarre behaviour is explained in Issue 1704. + if response.status_code == codes.moved and method == "POST": + method = "GET" + + prepared_request.method = method + + +class Session(SessionRedirectMixin): + """A Requests session. + + Provides cookie persistence, connection-pooling, and configuration. + + Basic Usage:: + + >>> import requests + >>> s = requests.Session() + >>> s.get('https://httpbin.org/get') + + + Or as a context manager:: + + >>> with requests.Session() as s: + ... s.get('https://httpbin.org/get') + + """ + + headers: CaseInsensitiveDict[str] + auth: _t.AuthType + proxies: dict[str, str] + hooks: dict[str, list[_t.HookType]] + params: MutableMapping[str, Any] + stream: bool + verify: _t.VerifyType + cert: _t.CertType + max_redirects: int + trust_env: bool + cookies: RequestsCookieJar + adapters: MutableMapping[str, BaseAdapter] + + __attrs__: list[str] = [ + "headers", + "cookies", + "auth", + "proxies", + "hooks", + "params", + "verify", + "cert", + "adapters", + "stream", + "trust_env", + "max_redirects", + ] + + def __init__(self) -> None: + #: A case-insensitive dictionary of headers to be sent on each + #: :class:`Request ` sent from this + #: :class:`Session `. + self.headers = default_headers() + + #: Default Authentication tuple or object to attach to + #: :class:`Request `. + self.auth = None + + #: Dictionary mapping protocol or protocol and host to the URL of the proxy + #: (e.g. {'http': 'foo.bar:3128', 'http://host.name': 'foo.bar:4012'}) to + #: be used on each :class:`Request `. + self.proxies = {} + + #: Event-handling hooks. + self.hooks = default_hooks() + + #: Dictionary of querystring data to attach to each + #: :class:`Request `. The dictionary values may be lists for + #: representing multivalued query parameters. + self.params = {} + + #: Stream response content default. + self.stream = False + + #: SSL Verification default. + #: Defaults to `True`, requiring requests to verify the TLS certificate at the + #: remote end. + #: If verify is set to `False`, requests will accept any TLS certificate + #: presented by the server, and will ignore hostname mismatches and/or + #: expired certificates, which will make your application vulnerable to + #: man-in-the-middle (MitM) attacks. + #: Only set this to `False` for testing. + #: If verify is set to a string, it must be the path to a CA bundle file + #: that will be used to verify the TLS certificate. + self.verify = True + + #: SSL client certificate default, if String, path to ssl client + #: cert file (.pem). If Tuple, ('cert', 'key') pair. + self.cert = None + + #: Maximum number of redirects allowed. If the request exceeds this + #: limit, a :class:`TooManyRedirects` exception is raised. + #: This defaults to requests.models.DEFAULT_REDIRECT_LIMIT, which is + #: 30. + self.max_redirects = DEFAULT_REDIRECT_LIMIT + + #: Trust environment settings for proxy configuration, default + #: authentication and similar. + self.trust_env = True + + #: A CookieJar containing all currently outstanding cookies set on this + #: session. By default it is a + #: :class:`RequestsCookieJar `, but + #: may be any other ``cookielib.CookieJar`` compatible object. + self.cookies = cookiejar_from_dict({}) + + # Default connection adapters. + self.adapters = OrderedDict() + self.mount("https://", HTTPAdapter()) + self.mount("http://", HTTPAdapter()) + + def __enter__(self) -> Self: + return self + + def __exit__(self, *args: Any) -> None: + self.close() + + def prepare_request(self, request: Request) -> PreparedRequest: + """Constructs a :class:`PreparedRequest ` for + transmission and returns it. The :class:`PreparedRequest` has settings + merged from the :class:`Request ` instance and those of the + :class:`Session`. + + :param request: :class:`Request` instance to prepare with this + session's settings. + :rtype: requests.PreparedRequest + """ + url = cast("_t.UriType", request.url) + method = cast(str, request.method) + + cookies = request.cookies or {} + + # Bootstrap CookieJar. + if not isinstance(cookies, cookielib.CookieJar): + cookies = cookiejar_from_dict(cookies) + + # Merge with session cookies + merged_cookies = merge_cookies( + merge_cookies(RequestsCookieJar(), self.cookies), cookies + ) + + # Set environment's basic authentication if not explicitly set. + auth = request.auth + if self.trust_env and not auth and not self.auth: + auth = get_netrc_auth(url) + + p = PreparedRequest() + p.prepare( + method=method.upper(), + url=url, + files=request.files, + data=request.data, + json=request.json, + headers=merge_setting( + request.headers, self.headers, dict_class=CaseInsensitiveDict + ), + params=merge_setting(request.params, self.params), + auth=merge_setting(auth, self.auth), + cookies=merged_cookies, + hooks=merge_hooks(request.hooks, self.hooks), + ) + return p + + def request( + self, + method: str, + url: _t.UriType, + params: _t.ParamsType = None, + data: _t.DataType = None, + headers: _t.HeadersType = None, + cookies: RequestsCookieJar | CookieJar | dict[str, str] | None = None, + files: _t.FilesType = None, + auth: _t.AuthType = None, + timeout: _t.TimeoutType = None, + allow_redirects: bool = True, + proxies: dict[str, str] | None = None, + hooks: _t.HooksInputType | None = None, + stream: bool | None = None, + verify: _t.VerifyType | None = None, + cert: _t.CertType = None, + json: _t.JsonType = None, + ) -> Response: + """Constructs a :class:`Request `, prepares it and sends it. + Returns :class:`Response ` object. + + :param method: method for the new :class:`Request` object. + :param url: URL for the new :class:`Request` object. + :param params: (optional) Dictionary or bytes to be sent in the query + string for the :class:`Request`. + :param data: (optional) Dictionary, list of tuples, bytes, or file-like + object to send in the body of the :class:`Request`. + :param json: (optional) json to send in the body of the + :class:`Request`. + :param headers: (optional) Dictionary of HTTP Headers to send with the + :class:`Request`. + :param cookies: (optional) Dict or CookieJar object to send with the + :class:`Request`. + :param files: (optional) Dictionary of ``'filename': file-like-objects`` + for multipart encoding upload. + :param auth: (optional) Auth tuple or callable to enable + Basic/Digest/Custom HTTP Auth. + :param timeout: (optional) How many seconds to wait for the server to send + data before giving up, as a float, or a :ref:`(connect timeout, + read timeout) ` tuple. + :type timeout: float or tuple + :param allow_redirects: (optional) Set to True by default. + :type allow_redirects: bool + :param proxies: (optional) Dictionary mapping protocol or protocol and + hostname to the URL of the proxy. + :param hooks: (optional) Dictionary mapping hook name to one event or + list of events, event must be callable. + :param stream: (optional) whether to immediately download the response + content. Defaults to ``False``. + :param verify: (optional) Either a boolean, in which case it controls whether we verify + the server's TLS certificate, or a string, in which case it must be a path + to a CA bundle to use. Defaults to ``True``. When set to + ``False``, requests will accept any TLS certificate presented by + the server, and will ignore hostname mismatches and/or expired + certificates, which will make your application vulnerable to + man-in-the-middle (MitM) attacks. Setting verify to ``False`` + may be useful during local development or testing. + :param cert: (optional) if String, path to ssl client cert file (.pem). + If Tuple, ('cert', 'key') pair. + :rtype: requests.Response + """ + if isinstance(url, bytes): + url = url.decode("utf-8") + + # Create the Request. + req = Request( + method=method.upper(), + url=url, + headers=headers, + files=files, + data=data or {}, + json=json, + params=params or {}, + auth=auth, + cookies=cookies, + hooks=hooks, + ) + prep = self.prepare_request(req) + + assert _is_prepared(prep) + + proxies = proxies or {} + + settings = self.merge_environment_settings( + prep.url, proxies, stream, verify, cert + ) + + # Send the request. + send_kwargs = { + "timeout": timeout, + "allow_redirects": allow_redirects, + } + send_kwargs.update(settings) + resp = self.send(prep, **send_kwargs) + + return resp + + def get( + self, + url: _t.UriType, + params: _t.ParamsType = None, + **kwargs: Unpack[_t.GetKwargs], + ) -> Response: + r"""Sends a GET request. Returns :class:`Response` object. + + :param url: URL for the new :class:`Request` object. + :param params: (optional) Dictionary, list of tuples or bytes to send + in the query string for the :class:`Request`. + :param \*\*kwargs: Optional arguments that ``request`` takes. + :rtype: requests.Response + """ + + kwargs.setdefault("allow_redirects", True) + return self.request("GET", url, params=params, **kwargs) + + def options(self, url: _t.UriType, **kwargs: Unpack[_t.RequestKwargs]) -> Response: + r"""Sends a OPTIONS request. Returns :class:`Response` object. + + :param url: URL for the new :class:`Request` object. + :param \*\*kwargs: Optional arguments that ``request`` takes. + :rtype: requests.Response + """ + + kwargs.setdefault("allow_redirects", True) + return self.request("OPTIONS", url, **kwargs) + + def head(self, url: _t.UriType, **kwargs: Unpack[_t.RequestKwargs]) -> Response: + r"""Sends a HEAD request. Returns :class:`Response` object. + + :param url: URL for the new :class:`Request` object. + :param \*\*kwargs: Optional arguments that ``request`` takes. + :rtype: requests.Response + """ + + kwargs.setdefault("allow_redirects", False) + return self.request("HEAD", url, **kwargs) + + def post( + self, + url: _t.UriType, + data: _t.DataType = None, + json: _t.JsonType = None, + **kwargs: Unpack[_t.PostKwargs], + ) -> Response: + r"""Sends a POST request. Returns :class:`Response` object. + + :param url: URL for the new :class:`Request` object. + :param data: (optional) Dictionary, list of tuples, bytes, or file-like + object to send in the body of the :class:`Request`. + :param json: (optional) json to send in the body of the :class:`Request`. + :param \*\*kwargs: Optional arguments that ``request`` takes. + :rtype: requests.Response + """ + + return self.request("POST", url, data=data, json=json, **kwargs) + + def put( + self, url: _t.UriType, data: _t.DataType = None, **kwargs: Unpack[_t.DataKwargs] + ) -> Response: + r"""Sends a PUT request. Returns :class:`Response` object. + + :param url: URL for the new :class:`Request` object. + :param data: (optional) Dictionary, list of tuples, bytes, or file-like + object to send in the body of the :class:`Request`. + :param \*\*kwargs: Optional arguments that ``request`` takes. + :rtype: requests.Response + """ + + return self.request("PUT", url, data=data, **kwargs) + + def patch( + self, url: _t.UriType, data: _t.DataType = None, **kwargs: Unpack[_t.DataKwargs] + ) -> Response: + r"""Sends a PATCH request. Returns :class:`Response` object. + + :param url: URL for the new :class:`Request` object. + :param data: (optional) Dictionary, list of tuples, bytes, or file-like + object to send in the body of the :class:`Request`. + :param \*\*kwargs: Optional arguments that ``request`` takes. + :rtype: requests.Response + """ + + return self.request("PATCH", url, data=data, **kwargs) + + def delete(self, url: _t.UriType, **kwargs: Unpack[_t.RequestKwargs]) -> Response: + r"""Sends a DELETE request. Returns :class:`Response` object. + + :param url: URL for the new :class:`Request` object. + :param \*\*kwargs: Optional arguments that ``request`` takes. + :rtype: requests.Response + """ + + return self.request("DELETE", url, **kwargs) + + def send(self, request: PreparedRequest, **kwargs: Any) -> Response: + """Send a given PreparedRequest. + + :rtype: requests.Response + """ + # Set defaults that the hooks can utilize to ensure they always have + # the correct parameters to reproduce the previous request. + kwargs.setdefault("stream", self.stream) + kwargs.setdefault("verify", self.verify) + kwargs.setdefault("cert", self.cert) + if "proxies" not in kwargs: + kwargs["proxies"] = resolve_proxies(request, self.proxies, self.trust_env) + + # It's possible that users might accidentally send a Request object. + # Guard against that specific failure case. + if isinstance(request, Request): + raise ValueError("You can only send PreparedRequests.") + + assert _is_prepared(request) + + # Set up variables needed for resolve_redirects and dispatching of hooks + allow_redirects = kwargs.pop("allow_redirects", True) + stream = kwargs.get("stream") + hooks = request.hooks + + # Get the appropriate adapter to use + adapter = self.get_adapter(url=request.url) + + # Start time (approximately) of the request + start = preferred_clock() + + # Send the request + r = adapter.send(request, **kwargs) + + # Total elapsed time of the request (approximately) + elapsed = preferred_clock() - start + r.elapsed = timedelta(seconds=elapsed) + + # Response manipulation hooks + r = dispatch_hook("response", hooks, r, **kwargs) + + # Persist cookies + if r.history: + # If the hooks create history then we want those cookies too + for resp in r.history: + extract_cookies_to_jar(self.cookies, resp.request, resp.raw) + + extract_cookies_to_jar(self.cookies, request, r.raw) + + # Resolve redirects if allowed. + if allow_redirects: + # Redirect resolving generator. + gen = self.resolve_redirects(r, request, **kwargs) + history = [resp for resp in gen] + else: + history = [] + + # Shuffle things around if there's history. + if history: + # Insert the first (original) request at the start + history.insert(0, r) + # Get the last request made + r = history.pop() + r.history = history + + # If redirects aren't being followed, store the response on the Request for Response.next(). + if not allow_redirects: + try: + r._next = next( # type: ignore[assignment] # yield_requests=True returns PreparedRequest + self.resolve_redirects(r, request, yield_requests=True, **kwargs) + ) + except StopIteration: + pass + + if not stream: + r.content + + return r + + def merge_environment_settings( + self, + url: str, + proxies: dict[str, str] | None, + stream: bool | None, + verify: _t.VerifyType | None, + cert: _t.CertType, + ) -> dict[str, Any]: + """ + Check the environment and merge it with some settings. + + :rtype: dict + """ + # Gather clues from the surrounding environment. + if self.trust_env: + # Set environment's proxies. + no_proxy = proxies.get("no_proxy") if proxies is not None else None + env_proxies = get_environ_proxies(url, no_proxy=no_proxy) + if proxies is not None: + for k, v in env_proxies.items(): + proxies.setdefault(k, v) + + # Look for requests environment configuration + # and be compatible with cURL. + if verify is True or verify is None: + verify = ( + os.environ.get("REQUESTS_CA_BUNDLE") + or os.environ.get("CURL_CA_BUNDLE") + or verify + ) + + # Merge all the kwargs. + proxies = merge_setting(proxies, self.proxies) + stream = merge_setting(stream, self.stream) + verify = merge_setting(verify, self.verify) + cert = merge_setting(cert, self.cert) + + return {"proxies": proxies, "stream": stream, "verify": verify, "cert": cert} + + def get_adapter(self, url: str) -> BaseAdapter: + """ + Returns the appropriate connection adapter for the given URL. + + :rtype: requests.adapters.BaseAdapter + """ + for prefix, adapter in self.adapters.items(): + if url.lower().startswith(prefix.lower()): + return adapter + + # Nothing matches :-/ + raise InvalidSchema(f"No connection adapters were found for {url!r}") + + def close(self) -> None: + """Closes all adapters and as such the session""" + for v in self.adapters.values(): + v.close() + + def mount(self, prefix: str, adapter: BaseAdapter) -> None: + """Registers a connection adapter to a prefix. + + Adapters are sorted in descending order by prefix length. + """ + self.adapters[prefix] = adapter + keys_to_move = [k for k in self.adapters if len(k) < len(prefix)] + + for key in keys_to_move: + self.adapters[key] = self.adapters.pop(key) + + def __getstate__(self) -> dict[str, Any]: + state = {attr: getattr(self, attr, None) for attr in self.__attrs__} + return state + + def __setstate__(self, state: dict[str, Any]) -> None: + for attr, value in state.items(): + setattr(self, attr, value) + + +def session() -> Session: + """ + Returns a :class:`Session` for context-management. + + .. deprecated:: 1.0.0 + + This method has been deprecated since version 1.0.0 and is only kept for + backwards compatibility. New code should use :class:`~requests.sessions.Session` + to create a session. This may be removed at a future date. + + :rtype: Session + """ + return Session() diff --git a/.venv/lib/python3.12/site-packages/requests/status_codes.py b/.venv/lib/python3.12/site-packages/requests/status_codes.py new file mode 100644 index 0000000000000000000000000000000000000000..6c59d6baec83bd82055106a5d2cea08fa1195274 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/requests/status_codes.py @@ -0,0 +1,128 @@ +r""" +The ``codes`` object defines a mapping from common names for HTTP statuses +to their numerical codes, accessible either as attributes or as dictionary +items. + +Example:: + + >>> import requests + >>> requests.codes['temporary_redirect'] + 307 + >>> requests.codes.teapot + 418 + >>> requests.codes['\o/'] + 200 + +Some codes have multiple names, and both upper- and lower-case versions of +the names are allowed. For example, ``codes.ok``, ``codes.OK``, and +``codes.okay`` all correspond to the HTTP status code 200. +""" + +from .structures import LookupDict + +_codes = { + # Informational. + 100: ("continue",), + 101: ("switching_protocols",), + 102: ("processing", "early-hints"), + 103: ("checkpoint",), + 122: ("uri_too_long", "request_uri_too_long"), + 200: ("ok", "okay", "all_ok", "all_okay", "all_good", "\\o/", "✓"), + 201: ("created",), + 202: ("accepted",), + 203: ("non_authoritative_info", "non_authoritative_information"), + 204: ("no_content",), + 205: ("reset_content", "reset"), + 206: ("partial_content", "partial"), + 207: ("multi_status", "multiple_status", "multi_stati", "multiple_stati"), + 208: ("already_reported",), + 226: ("im_used",), + # Redirection. + 300: ("multiple_choices",), + 301: ("moved_permanently", "moved", "\\o-"), + 302: ("found",), + 303: ("see_other", "other"), + 304: ("not_modified",), + 305: ("use_proxy",), + 306: ("switch_proxy",), + 307: ("temporary_redirect", "temporary_moved", "temporary"), + 308: ( + "permanent_redirect", + "resume_incomplete", + "resume", + ), # "resume" and "resume_incomplete" to be removed in 3.0 + # Client Error. + 400: ("bad_request", "bad"), + 401: ("unauthorized",), + 402: ("payment_required", "payment"), + 403: ("forbidden",), + 404: ("not_found", "-o-"), + 405: ("method_not_allowed", "not_allowed"), + 406: ("not_acceptable",), + 407: ("proxy_authentication_required", "proxy_auth", "proxy_authentication"), + 408: ("request_timeout", "timeout"), + 409: ("conflict",), + 410: ("gone",), + 411: ("length_required",), + 412: ("precondition_failed", "precondition"), + 413: ("request_entity_too_large", "content_too_large"), + 414: ("request_uri_too_large", "uri_too_long"), + 415: ("unsupported_media_type", "unsupported_media", "media_type"), + 416: ( + "requested_range_not_satisfiable", + "requested_range", + "range_not_satisfiable", + ), + 417: ("expectation_failed",), + 418: ("im_a_teapot", "teapot", "i_am_a_teapot"), + 421: ("misdirected_request",), + 422: ("unprocessable_entity", "unprocessable", "unprocessable_content"), + 423: ("locked",), + 424: ("failed_dependency", "dependency"), + 425: ("unordered_collection", "unordered", "too_early"), + 426: ("upgrade_required", "upgrade"), + 428: ("precondition_required", "precondition"), + 429: ("too_many_requests", "too_many"), + 431: ("header_fields_too_large", "fields_too_large"), + 444: ("no_response", "none"), + 449: ("retry_with", "retry"), + 450: ("blocked_by_windows_parental_controls", "parental_controls"), + 451: ("unavailable_for_legal_reasons", "legal_reasons"), + 499: ("client_closed_request",), + # Server Error. + 500: ("internal_server_error", "server_error", "/o\\", "✗"), + 501: ("not_implemented",), + 502: ("bad_gateway",), + 503: ("service_unavailable", "unavailable"), + 504: ("gateway_timeout",), + 505: ("http_version_not_supported", "http_version"), + 506: ("variant_also_negotiates",), + 507: ("insufficient_storage",), + 509: ("bandwidth_limit_exceeded", "bandwidth"), + 510: ("not_extended",), + 511: ("network_authentication_required", "network_auth", "network_authentication"), +} + +codes: LookupDict[int] = LookupDict(name="status_codes") + + +def _init(): + for code, titles in _codes.items(): + for title in titles: + setattr(codes, title, code) + if not title.startswith(("\\", "/")): + setattr(codes, title.upper(), code) + + def doc(code: int) -> str: + names = ", ".join(f"``{n}``" for n in _codes[code]) + return "* %d: %s" % (code, names) + + global __doc__ + __doc__ = ( + __doc__ + "\n" + "\n".join(doc(code) for code in sorted(_codes)) + if __doc__ is not None + else None + ) + + +_init() diff --git a/.venv/lib/python3.12/site-packages/requests/structures.py b/.venv/lib/python3.12/site-packages/requests/structures.py new file mode 100644 index 0000000000000000000000000000000000000000..7675eaf15a181dada66c02bb0468dc00d6f523b3 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/requests/structures.py @@ -0,0 +1,130 @@ +""" +requests.structures +~~~~~~~~~~~~~~~~~~~ + +Data structures that power Requests. +""" + +from __future__ import annotations + +from collections import OrderedDict +from collections.abc import Iterable, Iterator, Mapping +from typing import Any, Generic, TypeVar, overload + +from .compat import MutableMapping + +_VT = TypeVar("_VT") +_D = TypeVar("_D") + + +class CaseInsensitiveDict(MutableMapping[str, _VT], Generic[_VT]): + """A case-insensitive ``dict``-like object. + + Implements all methods and operations of + ``MutableMapping`` as well as dict's ``copy``. Also + provides ``lower_items``. + + All keys are expected to be strings. The structure remembers the + case of the last key to be set, and ``iter(instance)``, + ``keys()``, ``items()``, ``iterkeys()``, and ``iteritems()`` + will contain case-sensitive keys. However, querying and contains + testing is case insensitive:: + + cid = CaseInsensitiveDict() + cid['Accept'] = 'application/json' + cid['aCCEPT'] == 'application/json' # True + list(cid) == ['Accept'] # True + + For example, ``headers['content-encoding']`` will return the + value of a ``'Content-Encoding'`` response header, regardless + of how the header name was originally stored. + + If the constructor, ``.update``, or equality comparison + operations are given keys that have equal ``.lower()``s, the + behavior is undefined. + """ + + _store: OrderedDict[str, tuple[str, _VT]] + + def __init__( + self, + data: Mapping[str, _VT] | Iterable[tuple[str, _VT]] | None = None, + **kwargs: _VT, + ) -> None: + self._store = OrderedDict() + if data is None: + data = {} + self.update(data, **kwargs) + + def __setitem__(self, key: str, value: _VT) -> None: + # Use the lowercased key for lookups, but store the actual + # key alongside the value. + self._store[key.lower()] = (key, value) + + def __getitem__(self, key: str) -> _VT: + return self._store[key.lower()][1] + + def __delitem__(self, key: str) -> None: + del self._store[key.lower()] + + def __iter__(self) -> Iterator[str]: + return (casedkey for casedkey, _ in self._store.values()) + + def __len__(self) -> int: + return len(self._store) + + def lower_items(self) -> Iterator[tuple[str, _VT]]: + """Like iteritems(), but with all lowercase keys.""" + return ((lowerkey, keyval[1]) for (lowerkey, keyval) in self._store.items()) + + def __eq__(self, other: object) -> bool: + if isinstance(other, Mapping): + other_dict: CaseInsensitiveDict[Any] = CaseInsensitiveDict(other) # type: ignore[reportUnknownArgumentType] + else: + return NotImplemented + # Compare insensitively + return dict(self.lower_items()) == dict(other_dict.lower_items()) + + # Copy is required + def copy(self) -> CaseInsensitiveDict[_VT]: + return CaseInsensitiveDict(self._store.values()) + + def __repr__(self) -> str: + return str(dict(self.items())) + + +class LookupDict(dict[str, _VT]): + """Dictionary lookup object.""" + + name: Any + + def __init__(self, name: Any = None) -> None: + self.name = name + super().__init__() + + def __repr__(self) -> str: + return f"" + + def __getattr__(self, key: str) -> _VT | None: + # We need this for type checkers to infer typing + # on attribute access with status_codes.py + if key in self.__dict__: + return self.__dict__[key] + else: + raise AttributeError( + f"'{type(self).__name__}' object has no attribute '{key}'" + ) + + def __getitem__(self, key: str) -> _VT | None: # type: ignore[override] + # We allow fall-through here, so values default to None + + return self.__dict__.get(key, None) + + @overload + def get(self, key: str, default: None = None) -> _VT | None: ... + + @overload + def get(self, key: str, default: _D | _VT) -> _D | _VT: ... + + def get(self, key: str, default: _D | None = None) -> _VT | _D | None: + return self.__dict__.get(key, default) diff --git a/.venv/lib/python3.12/site-packages/requests/utils.py b/.venv/lib/python3.12/site-packages/requests/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..120336ddc6ed5d802735685349c3c3cd42e0c597 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/requests/utils.py @@ -0,0 +1,1155 @@ +""" +requests.utils +~~~~~~~~~~~~~~ + +This module provides utility functions that are used within Requests +that are also useful for external consumption. +""" + +from __future__ import annotations + +import codecs +import contextlib +import io +import os +import re +import socket +import struct +import sys +import tempfile +import warnings +import zipfile +from collections import OrderedDict +from collections.abc import Generator, Iterable +from typing import ( + TYPE_CHECKING, + Any, + Final, + TypeVar, + cast, + overload, +) + +from urllib3.util import make_headers, parse_url + +from . import certs +from .__version__ import __version__ + +# to_native_string is unused here, but imported here for backwards compatibility +from ._internal_utils import ( # noqa: F401 + _HEADER_VALIDATORS_BYTE, # type: ignore[reportPrivateUsage] + _HEADER_VALIDATORS_STR, # type: ignore[reportPrivateUsage] + HEADER_VALIDATORS, # type: ignore[reportUnusedImport] + to_native_string, # type: ignore[reportUnusedImport] +) +from ._types import SupportsItems as _SupportsItems +from .compat import ( + Mapping, + bytes, + getproxies, + getproxies_environment, + integer_types, + is_urllib3_1, + proxy_bypass, + proxy_bypass_environment, # type: ignore[attr-defined] # https://github.com/python/cpython/issues/145331 + quote, + str, + unquote, + urlparse, + urlunparse, +) +from .compat import parse_http_list as _parse_list_header +from .cookies import cookiejar_from_dict +from .exceptions import ( + FileModeWarning, + InvalidHeader, + InvalidURL, + UnrewindableBodyError, +) +from .structures import CaseInsensitiveDict + +if TYPE_CHECKING: + from http.cookiejar import CookieJar + from io import BufferedWriter + + from . import _types as _t + from .models import PreparedRequest, Request, Response + +NETRC_FILES: Final = (".netrc", "_netrc") + + +# Certificate is extracted by certifi when needed. +DEFAULT_CA_BUNDLE_PATH: str = certs.where() + + +DEFAULT_PORTS: Final = {"http": 80, "https": 443} + +_KT = TypeVar("_KT") +_VT = TypeVar("_VT") + +# Ensure that ', ' is used to preserve previous delimiter behavior. +DEFAULT_ACCEPT_ENCODING: Final = ", ".join( + re.split(r",\s*", make_headers(accept_encoding=True)["accept-encoding"]) +) + + +if sys.platform == "win32": + # provide a proxy_bypass version on Windows without DNS lookups + + def proxy_bypass_registry(host: str) -> bool: + try: + import winreg + except ImportError: + return False + + try: + internetSettings = winreg.OpenKey( + winreg.HKEY_CURRENT_USER, + r"Software\Microsoft\Windows\CurrentVersion\Internet Settings", + ) + # ProxyEnable could be REG_SZ or REG_DWORD, normalizing it + proxyEnable = int(winreg.QueryValueEx(internetSettings, "ProxyEnable")[0]) + # ProxyOverride is almost always a string + proxyOverride = winreg.QueryValueEx(internetSettings, "ProxyOverride")[0] + except (OSError, ValueError): + return False + if not proxyEnable or not proxyOverride: + return False + + # make a check value list from the registry entry: replace the + # '' string by the localhost entry and the corresponding + # canonical entry. + proxyOverride = proxyOverride.split(";") + # filter out empty strings to avoid re.match return true in the following code. + proxyOverride = filter(None, proxyOverride) + # now check if we match one of the registry values. + for test in proxyOverride: + if test == "": + if "." not in host: + return True + test = test.replace(".", r"\.") # mask dots + test = test.replace("*", r".*") # change glob sequence + test = test.replace("?", r".") # change glob char + if re.match(test, host, re.I): + return True + return False + + def proxy_bypass(host: str) -> bool: # noqa + """Return True, if the host should be bypassed. + + Checks proxy settings gathered from the environment, if specified, + or the registry. + """ + if getproxies_environment(): + return proxy_bypass_environment(host) + else: + return proxy_bypass_registry(host) + + +def dict_to_sequence( + d: _t.SupportsItems[Any, Any] | Iterable[tuple[Any, Any]], +) -> Iterable[tuple[Any, Any]]: + """Returns an internal sequence dictionary update.""" + + if isinstance(d, _SupportsItems): + return d.items() + + return d + + +def super_len(o: Any) -> int: + total_length = None + current_position = 0 + + if not is_urllib3_1 and isinstance(o, str): + # urllib3 2.x+ treats all strings as utf-8 instead + # of latin-1 (iso-8859-1) like http.client. + o = o.encode("utf-8") + + if hasattr(o, "__len__"): + total_length = len(o) + + elif hasattr(o, "len"): + total_length = o.len + + elif hasattr(o, "fileno"): + try: + fileno = o.fileno() + except (io.UnsupportedOperation, AttributeError): + # AttributeError is a surprising exception, seeing as how we've just checked + # that `hasattr(o, 'fileno')`. It happens for objects obtained via + # `Tarfile.extractfile()`, per issue 5229. + pass + else: + total_length = os.fstat(fileno).st_size + + # Having used fstat to determine the file length, we need to + # confirm that this file was opened up in binary mode. + if "b" not in o.mode: + warnings.warn( + ( + "Requests has determined the content-length for this " + "request using the binary size of the file: however, the " + "file has been opened in text mode (i.e. without the 'b' " + "flag in the mode). This may lead to an incorrect " + "content-length. In Requests 3.0, support will be removed " + "for files in text mode." + ), + FileModeWarning, + ) + + if hasattr(o, "tell"): + try: + current_position = o.tell() + except OSError: + # This can happen in some weird situations, such as when the file + # is actually a special file descriptor like stdin. In this + # instance, we don't know what the length is, so set it to zero and + # let requests chunk it instead. + if total_length is not None: + current_position = total_length + else: + if hasattr(o, "seek") and total_length is None: + # StringIO and BytesIO have seek but no usable fileno + try: + # seek to end of file + o.seek(0, 2) + total_length = o.tell() + + # seek back to current position to support + # partially read file-like objects + o.seek(current_position or 0) + except OSError: + total_length = 0 + + if total_length is None: + total_length = 0 + + return max(0, total_length - current_position) + + +def get_netrc_auth( + url: _t.UriType, raise_errors: bool = False +) -> tuple[str, str] | None: + """Returns the Requests tuple auth for a given url from netrc.""" + + if isinstance(url, bytes): + url = url.decode("utf-8") + + netrc_file = os.environ.get("NETRC") + if netrc_file is not None: + netrc_locations = (netrc_file,) + else: + netrc_locations = (f"~/{f}" for f in NETRC_FILES) + + try: + from netrc import NetrcParseError, netrc + + netrc_path = None + + for f in netrc_locations: + loc = os.path.expanduser(f) + if os.path.exists(loc): + netrc_path = loc + break + + # Abort early if there isn't one. + if netrc_path is None: + return + + ri = urlparse(url) + host = ri.hostname + + if host is None: + return + + try: + _netrc = netrc(netrc_path).authenticators(host) + if _netrc and any(_netrc): + # Return with login / password + login_i = 0 if _netrc[0] else 1 + return (_netrc[login_i] or "", _netrc[2] or "") + except (NetrcParseError, OSError): + # If there was a parsing error or a permissions issue reading the file, + # we'll just skip netrc auth unless explicitly asked to raise errors. + if raise_errors: + raise + + # App Engine hackiness. + except (ImportError, AttributeError): + pass + + +def guess_filename(obj: Any) -> str | None: + """Tries to guess the filename of the given object.""" + name = getattr(obj, "name", None) + if name and isinstance(name, (str, bytes)) and name[0] != "<" and name[-1] != ">": + return os.path.basename(name) # type: ignore[return-value] # urllib3 accepts bytes but types str only + + +def extract_zipped_paths(path: str) -> str: + """Replace nonexistent paths that look like they refer to a member of a zip + archive with the location of an extracted copy of the target, or else + just return the provided path unchanged. + """ + if os.path.exists(path): + # this is already a valid path, no need to do anything further + return path + + # find the first valid part of the provided path and treat that as a zip archive + # assume the rest of the path is the name of a member in the archive + archive, member = os.path.split(path) + while archive and not os.path.exists(archive): + archive, prefix = os.path.split(archive) + if not prefix: + # If we don't check for an empty prefix after the split (in other words, archive remains unchanged after the split), + # we _can_ end up in an infinite loop on a rare corner case affecting a small number of users + break + member = "/".join([prefix, member]) + + if not zipfile.is_zipfile(archive): + return path + + zip_file = zipfile.ZipFile(archive) + if member not in zip_file.namelist(): + return path + + # we have a valid zip archive and a valid member of that archive + suffix = os.path.splitext(member.split("/")[-1])[-1] + fd, extracted_path = tempfile.mkstemp(suffix=suffix) + try: + os.write(fd, zip_file.read(member)) + finally: + os.close(fd) + + return extracted_path + + +@contextlib.contextmanager +def atomic_open(filename: str) -> Generator[BufferedWriter, None, None]: + """Write a file to the disk in an atomic fashion""" + tmp_descriptor, tmp_name = tempfile.mkstemp(dir=os.path.dirname(filename)) + try: + with os.fdopen(tmp_descriptor, "wb") as tmp_handler: + yield tmp_handler + os.replace(tmp_name, filename) + except BaseException: + os.remove(tmp_name) + raise + + +def from_key_val_list( + value: Mapping[Any, Any] | Iterable[tuple[Any, Any]] | None, +) -> dict[Any, Any] | None: + """Take an object and test to see if it can be represented as a + dictionary. Unless it can not be represented as such, return an + OrderedDict, e.g., + + :: + + >>> from_key_val_list([('key', 'val')]) + OrderedDict([('key', 'val')]) + >>> from_key_val_list('string') + Traceback (most recent call last): + ... + ValueError: cannot encode objects that are not 2-tuples + >>> from_key_val_list({'key': 'val'}) + OrderedDict([('key', 'val')]) + + :rtype: OrderedDict + """ + if value is None: + return None + + if isinstance(value, (str, bytes, bool, int)): + raise ValueError("cannot encode objects that are not 2-tuples") + + return OrderedDict(value) + + +@overload +def to_key_val_list(value: None) -> None: ... +@overload +def to_key_val_list( + value: _t.SupportsItems[_KT, _VT] | Iterable[tuple[_KT, _VT]], +) -> list[tuple[_KT, _VT]]: ... +def to_key_val_list( + value: _t.SupportsItems[_KT, _VT] | Iterable[tuple[_KT, _VT]] | None, +) -> list[tuple[_KT, _VT]] | None: + """Take an object and test to see if it can be represented as a + dictionary. If it can be, return a list of tuples, e.g., + + :: + + >>> to_key_val_list([('key', 'val')]) + [('key', 'val')] + >>> to_key_val_list({'key': 'val'}) + [('key', 'val')] + >>> to_key_val_list('string') + Traceback (most recent call last): + ... + ValueError: cannot encode objects that are not 2-tuples + + :rtype: list + """ + if value is None: + return None + + if isinstance(value, (str, bytes, bool, int)): + raise ValueError("cannot encode objects that are not 2-tuples") + + if isinstance(value, _SupportsItems): + return list(value.items()) + + return list(value) + + +# From mitsuhiko/werkzeug (used with permission). +def parse_list_header(value: str) -> list[str]: + """Parse lists as described by RFC 2068 Section 2. + + In particular, parse comma-separated lists where the elements of + the list may include quoted-strings. A quoted-string could + contain a comma. A non-quoted string could have quotes in the + middle. Quotes are removed automatically after parsing. + + It basically works like :func:`parse_set_header` just that items + may appear multiple times and case sensitivity is preserved. + + The return value is a standard :class:`list`: + + >>> parse_list_header('token, "quoted value"') + ['token', 'quoted value'] + + To create a header from the :class:`list` again, use the + :func:`dump_header` function. + + :param value: a string with a list header. + :return: :class:`list` + :rtype: list + """ + result: list[str] = [] + for item in _parse_list_header(value): + if item[:1] == item[-1:] == '"': + item = unquote_header_value(item[1:-1]) + result.append(item) + return result + + +# From mitsuhiko/werkzeug (used with permission). +def parse_dict_header(value: str) -> dict[str, str | None]: + """Parse lists of key, value pairs as described by RFC 2068 Section 2 and + convert them into a python dict: + + >>> d = parse_dict_header('foo="is a fish", bar="as well"') + >>> type(d) is dict + True + >>> sorted(d.items()) + [('bar', 'as well'), ('foo', 'is a fish')] + + If there is no value for a key it will be `None`: + + >>> parse_dict_header('key_without_value') + {'key_without_value': None} + + To create a header from the :class:`dict` again, use the + :func:`dump_header` function. + + :param value: a string with a dict header. + :return: :class:`dict` + :rtype: dict + """ + result: dict[str, str | None] = {} + for item in _parse_list_header(value): + if "=" not in item: + result[item] = None + continue + name, value = item.split("=", 1) + if value[:1] == value[-1:] == '"': + value = unquote_header_value(value[1:-1]) + result[name] = value + return result + + +# From mitsuhiko/werkzeug (used with permission). +def unquote_header_value(value: str, is_filename: bool = False) -> str: + r"""Unquotes a header value. (Reversal of :func:`quote_header_value`). + This does not use the real unquoting but what browsers are actually + using for quoting. + + :param value: the header value to unquote. + :rtype: str + """ + if value and value[0] == value[-1] == '"': + # this is not the real unquoting, but fixing this so that the + # RFC is met will result in bugs with internet explorer and + # probably some other browsers as well. IE for example is + # uploading files with "C:\foo\bar.txt" as filename + value = value[1:-1] + + # if this is a filename and the starting characters look like + # a UNC path, then just return the value without quotes. Using the + # replace sequence below on a UNC path has the effect of turning + # the leading double slash into a single slash and then + # _fix_ie_filename() doesn't work correctly. See #458. + if not is_filename or value[:2] != "\\\\": + return value.replace("\\\\", "\\").replace('\\"', '"') + return value + + +def dict_from_cookiejar(cj: CookieJar) -> dict[str, str | None]: + """Returns a key/value dictionary from a CookieJar. + + :param cj: CookieJar object to extract cookies from. + :rtype: dict + """ + + cookie_dict = {cookie.name: cookie.value for cookie in cj} + return cookie_dict + + +def add_dict_to_cookiejar(cj: CookieJar, cookie_dict: dict[str, str]) -> CookieJar: + """Returns a CookieJar from a key/value dictionary. + + :param cj: CookieJar to insert cookies into. + :param cookie_dict: Dict of key/values to insert into CookieJar. + :rtype: CookieJar + """ + + return cookiejar_from_dict(cookie_dict, cj) + + +def get_encodings_from_content(content: str) -> list[str]: + """Returns encodings from given content string. + + :param content: bytestring to extract encodings from. + """ + warnings.warn( + ( + "In requests 3.0, get_encodings_from_content will be removed. For " + "more information, please see the discussion on issue #2266. (This" + " warning should only appear once.)" + ), + DeprecationWarning, + ) + + charset_re = re.compile(r']', flags=re.I) + pragma_re = re.compile(r']', flags=re.I) + xml_re = re.compile(r'^<\?xml.*?encoding=["\']*(.+?)["\'>]') + + return ( + charset_re.findall(content) + + pragma_re.findall(content) + + xml_re.findall(content) + ) + + +def _parse_content_type_header(header: str) -> tuple[str, dict[str, Any]]: + """Returns content type and parameters from given header. + + :param header: string + :return: tuple containing content type and dictionary of + parameters. + """ + + tokens = header.split(";") + content_type, params = tokens[0].strip(), tokens[1:] + params_dict: dict[str, str | bool] = {} + strip_chars = "\"' " + + for param in params: + param = param.strip() + if param and (idx := param.find("=")) != -1: + key = param[:idx].strip(strip_chars) + value = param[idx + 1 :].strip(strip_chars) + params_dict[key.lower()] = value + return content_type, params_dict + + +def get_encoding_from_headers(headers: CaseInsensitiveDict[str]) -> str | None: + """Returns encodings from given HTTP Header Dict. + + :param headers: dictionary to extract encoding from. + :rtype: str + """ + + content_type = headers.get("content-type") + + if not content_type: + return None + + content_type, params = _parse_content_type_header(content_type) + + if "charset" in params: + return params["charset"].strip("'\"") + + if "text" in content_type: + return "ISO-8859-1" + + if "application/json" in content_type: + # Assume UTF-8 based on RFC 4627: https://www.ietf.org/rfc/rfc4627.txt since the charset was unset + return "utf-8" + + +def stream_decode_response_unicode( + iterator: Iterable[bytes], r: Response +) -> Generator[str | bytes, None, None]: + """Stream decodes an iterator.""" + + if r.encoding is None: + yield from iterator + return + + decoder = codecs.getincrementaldecoder(r.encoding)(errors="replace") + for chunk in iterator: + rv = decoder.decode(chunk) + if rv: + yield rv + rv = decoder.decode(b"", final=True) + if rv: + yield rv + + +@overload +def iter_slices( + string: bytes, slice_length: int | None +) -> Generator[bytes, None, None]: ... +@overload +def iter_slices( + string: str, slice_length: int | None +) -> Generator[str, None, None]: ... +def iter_slices( + string: bytes | str, slice_length: int | None +) -> Generator[bytes | str, None, None]: + """Iterate over slices of a string.""" + pos = 0 + if slice_length is None or slice_length <= 0: + slice_length = len(string) + while pos < len(string): + yield string[pos : pos + slice_length] + pos += slice_length + + +def get_unicode_from_response(r: Response) -> str | bytes | None: + """Returns the requested content back in unicode. + + :param r: Response object to get unicode content from. + + Tried: + + 1. charset from content-type + 2. fall back and replace all unicode characters + + :rtype: str + """ + warnings.warn( + ( + "In requests 3.0, get_unicode_from_response will be removed. For " + "more information, please see the discussion on issue #2266. (This" + " warning should only appear once.)" + ), + DeprecationWarning, + ) + if r.content is None: # type: ignore[reportUnnecessaryComparison] + return None + + tried_encodings: list[str] = [] + + # Try charset from content-type + encoding = get_encoding_from_headers(r.headers) + + if encoding: + try: + return str(r.content, encoding) + except UnicodeError: + tried_encodings.append(encoding) + + # Fall back: + try: + return str(r.content, encoding or "utf-8", errors="replace") + except TypeError: + return r.content + + +# The unreserved URI characters (RFC 3986) +UNRESERVED_SET: Final = frozenset( + "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz" + "0123456789-._~" +) + + +def unquote_unreserved(uri: str) -> str: + """Un-escape any percent-escape sequences in a URI that are unreserved + characters. This leaves all reserved, illegal and non-ASCII bytes encoded. + + :rtype: str + """ + parts = uri.split("%") + for i in range(1, len(parts)): + h = parts[i][0:2] + if len(h) == 2 and h.isalnum(): + try: + c = chr(int(h, 16)) + except ValueError: + raise InvalidURL(f"Invalid percent-escape sequence: '{h}'") + + if c in UNRESERVED_SET: + parts[i] = c + parts[i][2:] + else: + parts[i] = f"%{parts[i]}" + else: + parts[i] = f"%{parts[i]}" + return "".join(parts) + + +def requote_uri(uri: str) -> str: + """Re-quote the given URI. + + This function passes the given URI through an unquote/quote cycle to + ensure that it is fully and consistently quoted. + + :rtype: str + """ + safe_with_percent = "!#$%&'()*+,/:;=?@[]~" + safe_without_percent = "!#$&'()*+,/:;=?@[]~" + try: + # Unquote only the unreserved characters + # Then quote only illegal characters (do not quote reserved, + # unreserved, or '%') + return quote(unquote_unreserved(uri), safe=safe_with_percent) + except InvalidURL: + # We couldn't unquote the given URI, so let's try quoting it, but + # there may be unquoted '%'s in the URI. We need to make sure they're + # properly quoted so they do not cause issues elsewhere. + return quote(uri, safe=safe_without_percent) + + +def address_in_network(ip: str, net: str) -> bool: + """This function allows you to check if an IP belongs to a network subnet + + Example: returns True if ip = 192.168.1.1 and net = 192.168.1.0/24 + returns False if ip = 192.168.1.1 and net = 192.168.100.0/24 + + :rtype: bool + """ + ipaddr = struct.unpack("=L", socket.inet_aton(ip))[0] + netaddr, bits = net.split("/") + netmask = struct.unpack("=L", socket.inet_aton(dotted_netmask(int(bits))))[0] + network = struct.unpack("=L", socket.inet_aton(netaddr))[0] & netmask + return (ipaddr & netmask) == (network & netmask) + + +def dotted_netmask(mask: int) -> str: + """Converts mask from /xx format to xxx.xxx.xxx.xxx + + Example: if mask is 24 function returns 255.255.255.0 + + :rtype: str + """ + bits = 0xFFFFFFFF ^ (1 << 32 - mask) - 1 + return socket.inet_ntoa(struct.pack(">I", bits)) + + +def is_ipv4_address(string_ip: str) -> bool: + """ + :rtype: bool + """ + try: + socket.inet_aton(string_ip) + except OSError: + return False + return True + + +def is_valid_cidr(string_network: str) -> bool: + """ + Very simple check of the cidr format in no_proxy variable. + + :rtype: bool + """ + if string_network.count("/") == 1: + try: + mask = int(string_network.split("/")[1]) + except ValueError: + return False + + if mask < 1 or mask > 32: + return False + + try: + socket.inet_aton(string_network.split("/")[0]) + except OSError: + return False + else: + return False + return True + + +@contextlib.contextmanager +def set_environ(env_name: str, value: str | None) -> Generator[None, None, None]: + """Set the environment variable 'env_name' to 'value' + + Save previous value, yield, and then restore the previous value stored in + the environment variable 'env_name'. + + If 'value' is None, do nothing""" + value_changed = value is not None + old_value: str | None = None + if value_changed: + old_value = os.environ.get(env_name) + os.environ[env_name] = value + try: + yield + finally: + if value_changed: + if old_value is None: + del os.environ[env_name] + else: + os.environ[env_name] = old_value + + +def should_bypass_proxies(url: str, no_proxy: str | None) -> bool: + """ + Returns whether we should bypass proxies or not. + + :rtype: bool + """ + + # Prioritize lowercase environment variables over uppercase + # to keep a consistent behaviour with other http projects (curl, wget). + def get_proxy(key: str) -> str | None: + return os.environ.get(key) or os.environ.get(key.upper()) + + # First check whether no_proxy is defined. If it is, check that the URL + # we're getting isn't in the no_proxy list. + no_proxy_arg = no_proxy + if no_proxy is None: + no_proxy = get_proxy("no_proxy") + parsed = urlparse(url) + hostname = parsed.hostname + + if hostname is None: + # URLs don't always have hostnames, e.g. file:/// urls. + return True + + if no_proxy: + # We need to check whether we match here. We need to see if we match + # the end of the hostname, both with and without the port. + no_proxy_hosts = (host for host in no_proxy.replace(" ", "").split(",") if host) + + if is_ipv4_address(hostname): + for proxy_ip in no_proxy_hosts: + if is_valid_cidr(proxy_ip): + if address_in_network(hostname, proxy_ip): + return True + elif hostname == proxy_ip: + # If no_proxy ip was defined in plain IP notation instead of cidr notation & + # matches the IP of the index + return True + else: + host_with_port = hostname + if parsed.port: + host_with_port += f":{parsed.port}" + + for host in no_proxy_hosts: + host = host.lstrip(".") + if hostname == host or host_with_port == host: + return True + host = "." + host + if hostname.endswith(host) or host_with_port.endswith(host): + return True + + with set_environ("no_proxy", no_proxy_arg): + try: + bypass = proxy_bypass(hostname) + except (TypeError, socket.gaierror): + bypass = False + + if bypass: + return True + + return False + + +def get_environ_proxies(url: str, no_proxy: str | None = None) -> dict[str, str]: + """ + Return a dict of environment proxies. + + :rtype: dict + """ + if should_bypass_proxies(url, no_proxy=no_proxy): + return {} + else: + return getproxies() + + +def select_proxy(url: str, proxies: dict[str, str] | None) -> str | None: + """Select a proxy for the url, if applicable. + + :param url: The url being for the request + :param proxies: A dictionary of schemes or schemes and hosts to proxy URLs + """ + proxies = proxies or {} + urlparts = urlparse(url) + if urlparts.hostname is None: + return proxies.get(urlparts.scheme, proxies.get("all")) + + proxy_keys = [ + urlparts.scheme + "://" + urlparts.hostname, + urlparts.scheme, + "all://" + urlparts.hostname, + "all", + ] + proxy = None + for proxy_key in proxy_keys: + if proxy_key in proxies: + proxy = proxies[proxy_key] + break + + return proxy + + +def resolve_proxies( + request: Request | PreparedRequest, + proxies: dict[str, str] | None, + trust_env: bool = True, +) -> dict[str, str]: + """This method takes proxy information from a request and configuration + input to resolve a mapping of target proxies. This will consider settings + such as NO_PROXY to strip proxy configurations. + + :param request: Request or PreparedRequest + :param proxies: A dictionary of schemes or schemes and hosts to proxy URLs + :param trust_env: Boolean declaring whether to trust environment configs + + :rtype: dict + """ + proxies = proxies if proxies is not None else {} + url = cast(str, request.url) + scheme = urlparse(url).scheme + no_proxy = proxies.get("no_proxy") + new_proxies = proxies.copy() + + if trust_env and not should_bypass_proxies(url, no_proxy=no_proxy): + environ_proxies = get_environ_proxies(url, no_proxy=no_proxy) + + proxy = environ_proxies.get(scheme, environ_proxies.get("all")) + + if proxy: + new_proxies.setdefault(scheme, proxy) + return new_proxies + + +def default_user_agent(name: str = "python-requests") -> str: + """ + Return a string representing the default user agent. + + :rtype: str + """ + return f"{name}/{__version__}" + + +def default_headers() -> CaseInsensitiveDict[str]: + """ + :rtype: requests.structures.CaseInsensitiveDict + """ + return CaseInsensitiveDict( + { + "User-Agent": default_user_agent(), + "Accept-Encoding": DEFAULT_ACCEPT_ENCODING, + "Accept": "*/*", + "Connection": "keep-alive", + } + ) + + +def parse_header_links(value: str) -> list[dict[str, str]]: + """Return a list of parsed link headers proxies. + + i.e. Link: ; rel=front; type="image/jpeg",; rel=back;type="image/jpeg" + + :rtype: list + """ + + links: list[dict[str, str]] = [] + + replace_chars = " '\"" + + value = value.strip(replace_chars) + if not value: + return links + + for val in re.split(", *<", value): + try: + url, params = val.split(";", 1) + except ValueError: + url, params = val, "" + + link: dict[str, str] = {"url": url.strip("<> '\"")} + + for param in params.split(";"): + try: + key, value = param.split("=") + except ValueError: + break + + link[key.strip(replace_chars)] = value.strip(replace_chars) + + links.append(link) + + return links + + +# Null bytes; no need to recreate these on each call to guess_json_utf +_null = "\x00".encode("ascii") # encoding to ASCII for Python 3 +_null2 = _null * 2 +_null3 = _null * 3 + + +def guess_json_utf(data: bytes) -> str | None: + """ + :rtype: str + """ + # JSON always starts with two ASCII characters, so detection is as + # easy as counting the nulls and from their location and count + # determine the encoding. Also detect a BOM, if present. + sample = data[:4] + if sample in (codecs.BOM_UTF32_LE, codecs.BOM_UTF32_BE): + return "utf-32" # BOM included + if sample[:3] == codecs.BOM_UTF8: + return "utf-8-sig" # BOM included, MS style (discouraged) + if sample[:2] in (codecs.BOM_UTF16_LE, codecs.BOM_UTF16_BE): + return "utf-16" # BOM included + nullcount = sample.count(_null) + if nullcount == 0: + return "utf-8" + if nullcount == 2: + if sample[::2] == _null2: # 1st and 3rd are null + return "utf-16-be" + if sample[1::2] == _null2: # 2nd and 4th are null + return "utf-16-le" + # Did not detect 2 valid UTF-16 ascii-range characters + if nullcount == 3: + if sample[:3] == _null3: + return "utf-32-be" + if sample[1:] == _null3: + return "utf-32-le" + # Did not detect a valid UTF-32 ascii-range character + return None + + +def prepend_scheme_if_needed(url: str, new_scheme: str) -> str: + """Given a URL that may or may not have a scheme, prepend the given scheme. + Does not replace a present scheme with the one provided as an argument. + + :rtype: str + """ + parsed = parse_url(url) + scheme, auth, _host, _port, path, query, fragment = parsed + + # A defect in urlparse determines that there isn't a netloc present in some + # urls. We previously assumed parsing was overly cautious, and swapped the + # netloc and path. Due to a lack of tests on the original defect, this is + # maintained with parse_url for backwards compatibility. + netloc = parsed.netloc + if not netloc: + netloc, path = path, netloc + + if auth: + # parse_url doesn't provide the netloc with auth + # so we'll add it ourselves. + netloc = cast(str, netloc) + netloc = "@".join([auth, netloc]) + if scheme is None: + scheme = new_scheme + if path is None: + path = "" + + return urlunparse((scheme, netloc, path, "", query, fragment)) + + +def get_auth_from_url(url: str) -> tuple[str, str]: + """Given a url with authentication components, extract them into a tuple of + username,password. + + :rtype: (str,str) + """ + parsed = urlparse(url) + + try: + # except handles parsed.username/password being None + auth = (unquote(parsed.username), unquote(parsed.password)) # type: ignore[arg-type] + except (AttributeError, TypeError): + auth = ("", "") + + return auth + + +def check_header_validity(header: tuple[str | bytes, str | bytes]) -> None: + """Verifies that header parts don't contain leading whitespace + reserved characters, or return characters. + + :param header: tuple, in the format (name, value). + """ + name, value = header + _validate_header_part(header, name, 0) + _validate_header_part(header, value, 1) + + +def _validate_header_part( + header: tuple[str | bytes, str | bytes], + header_part: str | bytes, + header_validator_index: int, +) -> None: + if isinstance(header_part, str): + validator = _HEADER_VALIDATORS_STR[header_validator_index] + elif isinstance(header_part, bytes): # type: ignore[reportUnnecessaryIsInstance] + # runtime guard for non-str/bytes input + validator = _HEADER_VALIDATORS_BYTE[header_validator_index] + else: + raise InvalidHeader( + f"Header part ({header_part!r}) from {header} " + f"must be of type str or bytes, not {type(header_part)}" + ) + + if not validator.match(header_part): # type: ignore[arg-type] + header_kind = "name" if header_validator_index == 0 else "value" + raise InvalidHeader( + f"Invalid leading whitespace, reserved character(s), or return " + f"character(s) in header {header_kind}: {header_part!r}" + ) + + +def urldefragauth(url: str) -> str: + """ + Given a url remove the fragment and the authentication part. + + :rtype: str + """ + scheme, netloc, path, params, query, _fragment = urlparse(url) + + # see func:`prepend_scheme_if_needed` + if not netloc: + netloc, path = path, netloc + + netloc = netloc.rsplit("@", 1)[-1] + + return urlunparse((scheme, netloc, path, params, query, "")) + + +def rewind_body(prepared_request: PreparedRequest) -> None: + """Move file pointer back to its recorded starting position + so it can be read again on redirect. + """ + body_seek = getattr(prepared_request.body, "seek", None) + if body_seek is not None and isinstance( + prepared_request._body_position, # type: ignore[reportPrivateUsage] + integer_types, + ): + try: + body_seek(prepared_request._body_position) # type: ignore[reportPrivateUsage] + except OSError: + raise UnrewindableBodyError( + "An error occurred when rewinding request body for redirect." + ) + else: + raise UnrewindableBodyError("Unable to rewind request body for redirect.") diff --git a/.venv/lib/python3.12/site-packages/scipy/__config__.py b/.venv/lib/python3.12/site-packages/scipy/__config__.py new file mode 100644 index 0000000000000000000000000000000000000000..010caf545e2f8f4b5d7cf8a498f777af2f5371df --- /dev/null +++ b/.venv/lib/python3.12/site-packages/scipy/__config__.py @@ -0,0 +1,174 @@ +# This file is generated by SciPy's build process +# It contains system_info results at the time of building this package. +from enum import Enum + +__all__ = ["show"] +_built_with_meson = True + + +class DisplayModes(Enum): + stdout = "stdout" + dicts = "dicts" + + +def _cleanup(d): + """ + Removes empty values in a `dict` recursively + This ensures we remove values that Meson could not provide to CONFIG + """ + if isinstance(d, dict): + return { k: _cleanup(v) for k, v in d.items() if v != '' and _cleanup(v) != '' } + else: + return d + + +CONFIG = _cleanup( + { + "Compilers": { + "c": { + "name": "gcc", + "linker": r"ld.bfd", + "version": "14.2.1", + "commands": r"cc", + "args": r"", + "linker args": r"", + }, + "cython": { + "name": r"cython", + "linker": r"cython", + "version": r"3.2.9", + "commands": r"cython", + "args": r"", + "linker args": r"", + }, + "c++": { + "name": "gcc", + "linker": r"ld.bfd", + "version": "14.2.1", + "commands": r"c++", + "args": r"", + "linker args": r"", + }, + "fortran": { + "name": "gcc", + "linker": r"ld.bfd", + "version": "14.2.1", + "commands": r"gfortran", + "args": r"", + "linker args": r"", + }, + "pythran": { + "version": r"0.19.0", + "include directory": r"../../../tmp/build-env-3zxzwx9o/lib/python3.12/site-packages/pythran" + }, + }, + "Machine Information": { + "host": { + "cpu": r"x86_64", + "family": r"x86_64", + "endian": r"little", + "system": r"linux", + }, + "build": { + "cpu": r"x86_64", + "family": r"x86_64", + "endian": r"little", + "system": r"linux", + }, + "cross-compiled": bool("false".lower().replace('false', '')), + }, + "Build Dependencies": { + "blas": { + "name": "scipy-openblas", + "found": bool("true".lower().replace('false', '')), + "version": "0.3.31.dev", + "detection method": "pkgconfig", + "include directory": r"/opt/_internal/cpython-3.12.13/lib/python3.12/site-packages/scipy_openblas32/include", + "lib directory": r"/opt/_internal/cpython-3.12.13/lib/python3.12/site-packages/scipy_openblas32/lib", + "openblas configuration": r"OpenBLAS 0.3.31.dev DYNAMIC_ARCH NO_AFFINITY Haswell MAX_THREADS=64", + "pc file directory": r"/project/.openblas", + "has ilp64": bool(r"false".lower().replace('false', '')), + "cython blas ilp64": bool(r"false".lower().replace('false', '')), + }, + "lapack": { + "name": "scipy-openblas", + "found": bool("true".lower().replace('false', '')), + "version": "0.3.31.dev", + "detection method": "pkgconfig", + "include directory": r"/opt/_internal/cpython-3.12.13/lib/python3.12/site-packages/scipy_openblas32/include", + "lib directory": r"/opt/_internal/cpython-3.12.13/lib/python3.12/site-packages/scipy_openblas32/lib", + "openblas configuration": r"OpenBLAS 0.3.31.dev DYNAMIC_ARCH NO_AFFINITY Haswell MAX_THREADS=64", + "pc file directory": r"/project/.openblas", + "has ilp64": bool(r"false".lower().replace('false', '')), + }, + "pybind11": { + "name": "pybind11", + "version": "3.0.4", + "detection method": "config-tool", + "include directory": r"unknown", + }, + }, + "Python Information": { + "path": r"/tmp/build-env-3zxzwx9o/bin/python", + "version": "3.12", + }, + } +) + + +def _check_pyyaml(): + import yaml + + return yaml + + +def show(mode=DisplayModes.stdout.value): + """ + Show libraries and system information on which SciPy was built + and is being used + + Parameters + ---------- + mode : {`'stdout'`, `'dicts'`}, optional. + Indicates how to display the config information. + `'stdout'` prints to console, `'dicts'` returns a dictionary + of the configuration. + + Returns + ------- + out : {`dict`, `None`} + If mode is `'dicts'`, a dict is returned, else None + + Examples + -------- + >>> import scipy + >>> scipy.show_config() + ... # formatted output is printed to the console + + >>> config_dict = scipy.show_config(mode='dicts') + >>> list(config_dict.keys()) + ['Compilers', 'Machine Information', 'Build Dependencies', 'Python Information'] + + Notes + ----- + 1. The `'stdout'` mode will give more readable + output if ``pyyaml`` is installed + + """ + if mode == DisplayModes.stdout.value: + try: # Non-standard library, check import + yaml = _check_pyyaml() + + print(yaml.dump(CONFIG)) + except ModuleNotFoundError: + import warnings + import json + + warnings.warn("Install `pyyaml` for better output", stacklevel=1) + print(json.dumps(CONFIG, indent=2)) + elif mode == DisplayModes.dicts.value: + return CONFIG + else: + raise AttributeError( + f"Invalid `mode`, use one of: {', '.join([e.value for e in DisplayModes])}" + ) diff --git a/.venv/lib/python3.12/site-packages/scipy/__init__.py b/.venv/lib/python3.12/site-packages/scipy/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..95c288ab3a38cfcf476f6efb1d14eae8269c7d7a --- /dev/null +++ b/.venv/lib/python3.12/site-packages/scipy/__init__.py @@ -0,0 +1,144 @@ +""" +SciPy: A scientific computing package for Python +================================================ + +Documentation is available in the docstrings and +online at https://docs.scipy.org/doc/scipy/ + +Subpackages +----------- +:: + + cluster --- Vector Quantization / Kmeans + constants --- Physical and mathematical constants and units + datasets --- Dataset methods + differentiate --- Finite difference differentiation tools + fft --- Discrete Fourier transforms + fftpack --- Legacy discrete Fourier transforms + integrate --- Integration routines + interpolate --- Interpolation Tools + io --- Data input and output + linalg --- Linear algebra routines + ndimage --- N-D image package + odr --- Orthogonal Distance Regression + optimize --- Optimization Tools + signal --- Signal Processing Tools + sparse --- Sparse Matrices + spatial --- Spatial data structures and algorithms + special --- Special functions + stats --- Statistical Functions + +Public API in the main SciPy namespace +-------------------------------------- +:: + + __version__ --- SciPy version string + LowLevelCallable --- Low-level callback function + show_config --- Show scipy build configuration + test --- Run scipy unittests + +""" + +import importlib as _importlib + +from numpy import __version__ as __numpy_version__ + + +try: + from scipy.__config__ import show as show_config +except ImportError as e: + msg = """Error importing SciPy: you cannot import SciPy while + being in scipy source directory; please exit the SciPy source + tree first and relaunch your Python interpreter.""" + raise ImportError(msg) from e + + +from scipy.version import version as __version__ + + +# Allow distributors to run custom init code +from . import _distributor_init +del _distributor_init + + +from scipy._external.packaging_version.version import Version, parse +# In maintenance branch, change to np_maxversion N+3 if numpy is at N +np_minversion = '2.0.0' +np_maxversion = '2.8.0' +if (parse(__numpy_version__) < Version(np_minversion) or + parse(__numpy_version__) >= Version(np_maxversion)): + import warnings + warnings.warn(f"A NumPy version >={np_minversion} and <{np_maxversion}" + f" is required for this version of SciPy (detected " + f"version {__numpy_version__})", + UserWarning, stacklevel=2) +del Version, parse + + +# This is the first import of an extension module within SciPy. If there's +# a general issue with the install, such that extension modules are missing +# or cannot be imported, this is where we'll get a failure - so give an +# informative error message. +try: + from scipy._lib._ccallback import LowLevelCallable +except ImportError as e: + msg = "The `scipy` install you are using seems to be broken, " + \ + "(extension modules cannot be imported), " + \ + "please try reinstalling." + raise ImportError(msg) from e + + +from scipy._lib._testutils import PytestTester +test = PytestTester(__name__) +del PytestTester + + +submodules = [ + 'cluster', + 'constants', + 'datasets', + 'differentiate', + 'fft', + 'fftpack', + 'integrate', + 'interpolate', + 'io', + 'linalg', + 'ndimage', + 'odr', + 'optimize', + 'signal', + 'sparse', + 'spatial', + 'special', + 'stats' +] + +# Handle `_without-fortran` build option +import os +if not os.path.exists('odr'): + submodules.remove('odr') +del os + +__all__ = submodules + [ + 'LowLevelCallable', + 'test', + 'show_config', + '__version__', +] + + +def __dir__(): + return __all__ + + +def __getattr__(name): + if name in submodules: + return _importlib.import_module(f'scipy.{name}') + else: + try: + return globals()[name] + except KeyError: + raise AttributeError( + f"Module 'scipy' has no attribute '{name}'" + ) diff --git a/.venv/lib/python3.12/site-packages/scipy/__pycache__/__config__.cpython-312.pyc b/.venv/lib/python3.12/site-packages/scipy/__pycache__/__config__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e957233c5ae205c3e6b70e54f7ea13d4d66558b6 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/scipy/__pycache__/__config__.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/scipy/__pycache__/__init__.cpython-312.pyc b/.venv/lib/python3.12/site-packages/scipy/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..86b844fa593a1f24d6e6419f88df717cf0ce70ae Binary files /dev/null and b/.venv/lib/python3.12/site-packages/scipy/__pycache__/__init__.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/scipy/__pycache__/_distributor_init.cpython-312.pyc b/.venv/lib/python3.12/site-packages/scipy/__pycache__/_distributor_init.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..bab42c68c3099031a82bb99263a4354dfcf6d979 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/scipy/__pycache__/_distributor_init.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/scipy/__pycache__/version.cpython-312.pyc b/.venv/lib/python3.12/site-packages/scipy/__pycache__/version.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..00c887b6964fa21047c716cad9d4e24bc5998d03 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/scipy/__pycache__/version.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/scipy/_cyutility.cpython-312-x86_64-linux-gnu.so b/.venv/lib/python3.12/site-packages/scipy/_cyutility.cpython-312-x86_64-linux-gnu.so new file mode 100644 index 0000000000000000000000000000000000000000..868b18f32de5a7959fcabb4092cd68d7701f8591 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/scipy/_cyutility.cpython-312-x86_64-linux-gnu.so @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:3225d1b8f1ad1d6f1afb368438280f8cea6e92ebe1649a14ea75b08aae664a02 +size 210768 diff --git a/.venv/lib/python3.12/site-packages/scipy/_distributor_init.py b/.venv/lib/python3.12/site-packages/scipy/_distributor_init.py new file mode 100644 index 0000000000000000000000000000000000000000..5df134975aa27d31beaff74c3cbfd2d3fb0a55dd --- /dev/null +++ b/.venv/lib/python3.12/site-packages/scipy/_distributor_init.py @@ -0,0 +1,18 @@ +""" Distributor init file + +Distributors: you can replace the contents of this file with your own custom +code to support particular distributions of SciPy. + +For example, this is a good place to put any checks for hardware requirements +or BLAS/LAPACK library initialization. + +The SciPy standard source distribution will not put code in this file beyond +the try-except import of `_distributor_init_local` (which is not part of a +standard source distribution), so you can safely replace this file with your +own version. +""" + +try: + from . import _distributor_init_local # noqa: F401 +except ImportError: + pass diff --git a/.venv/lib/python3.12/site-packages/scipy/_external/__pycache__/_array_api_compat_vendor.cpython-312.pyc b/.venv/lib/python3.12/site-packages/scipy/_external/__pycache__/_array_api_compat_vendor.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..199c9946aeeb4ff030309f2f23fae11c07b2e799 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/scipy/_external/__pycache__/_array_api_compat_vendor.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/scipy/_external/_array_api_compat_vendor.py b/.venv/lib/python3.12/site-packages/scipy/_external/_array_api_compat_vendor.py new file mode 100644 index 0000000000000000000000000000000000000000..6093787c306a5a500f4ef6cfb83ae31231af9ef7 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/scipy/_external/_array_api_compat_vendor.py @@ -0,0 +1,9 @@ +# DO NOT RENAME THIS FILE +# This is a hook for array_api_extra/src/array_api_extra/_lib/_compat.py +# to override functions of array_api_compat. + +from .array_api_compat import * # noqa: F403 +from scipy._lib._array_api_override import array_namespace as scipy_array_namespace + +# overrides array_api_compat.array_namespace inside array-api-extra +array_namespace = scipy_array_namespace # type: ignore[assignment] diff --git a/.venv/lib/python3.12/site-packages/scipy/_external/array_api_compat/__init__.py b/.venv/lib/python3.12/site-packages/scipy/_external/array_api_compat/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..785659a0482e55831658871aca053a2ab0a4b1f2 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/scipy/_external/array_api_compat/__init__.py @@ -0,0 +1,22 @@ +""" +NumPy Array API compatibility library + +This is a small wrapper around NumPy, CuPy, JAX, sparse and others that are +compatible with the Array API standard https://data-apis.org/array-api/latest/. +See also NEP 47 https://numpy.org/neps/nep-0047-array-api-standard.html. + +Unlike array_api_strict, this is not a strict minimal implementation of the +Array API, but rather just an extension of the main NumPy namespace with +changes needed to be compliant with the Array API. See +https://numpy.org/doc/stable/reference/array_api.html for a full list of +changes. In particular, unlike array_api_strict, this package does not use a +separate Array object, but rather just uses numpy.ndarray directly. + +Library authors using the Array API may wish to test against array_api_strict +to ensure they are not using functionality outside of the standard, but prefer +this implementation for the default when working with NumPy arrays. + +""" +__version__ = '1.14.0' + +from .common import * # noqa: F401, F403 diff --git a/.venv/lib/python3.12/site-packages/scipy/_external/array_api_compat/__pycache__/__init__.cpython-312.pyc b/.venv/lib/python3.12/site-packages/scipy/_external/array_api_compat/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a1f178b20a5e82fe046f48a4634ec0071f818dc9 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/scipy/_external/array_api_compat/__pycache__/__init__.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/scipy/_external/array_api_compat/__pycache__/_internal.cpython-312.pyc b/.venv/lib/python3.12/site-packages/scipy/_external/array_api_compat/__pycache__/_internal.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..fc1e014cd95f1e24a3505cfbf6edcb504196e409 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/scipy/_external/array_api_compat/__pycache__/_internal.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/scipy/_external/array_api_compat/_internal.py b/.venv/lib/python3.12/site-packages/scipy/_external/array_api_compat/_internal.py new file mode 100644 index 0000000000000000000000000000000000000000..baa39ded8decf2837540837ebc7b49c7b6971b82 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/scipy/_external/array_api_compat/_internal.py @@ -0,0 +1,77 @@ +""" +Internal helpers +""" + +import importlib +from collections.abc import Callable +from functools import wraps +from inspect import signature +from types import ModuleType +from typing import TypeVar + +_T = TypeVar("_T") + + +def get_xp(xp: ModuleType) -> Callable[[Callable[..., _T]], Callable[..., _T]]: + """ + Decorator to automatically replace xp with the corresponding array module. + + Use like + + import numpy as np + + @get_xp(np) + def func(x, /, xp, kwarg=None): + return xp.func(x, kwarg=kwarg) + + Note that xp must be a keyword argument and come after all non-keyword + arguments. + + """ + + def inner(f: Callable[..., _T], /) -> Callable[..., _T]: + @wraps(f) + def wrapped_f(*args: object, **kwargs: object) -> object: + return f(*args, xp=xp, **kwargs) + + sig = signature(f) + new_sig = sig.replace( + parameters=[par for i, par in sig.parameters.items() if i != "xp"] + ) + + if wrapped_f.__doc__ is None: + wrapped_f.__doc__ = f"""\ +Array API compatibility wrapper for {f.__name__}. + +See the corresponding documentation in NumPy/CuPy and/or the array API +specification for more details. + +""" + wrapped_f.__signature__ = new_sig # type: ignore[attr-defined] # pyright: ignore[reportAttributeAccessIssue] + return wrapped_f # type: ignore[return-value] # pyright: ignore[reportReturnType] + + return inner + + +def clone_module(mod_name: str, globals_: dict[str, object]) -> list[str]: + """Import everything from module, updating globals(). + Returns __all__. + """ + mod = importlib.import_module(mod_name) + # Neither of these two methods is sufficient by itself, + # depending on various idiosyncrasies of the libraries we're wrapping. + objs = {} + exec(f"from {mod.__name__} import *", objs) + + for n in dir(mod): + if not n.startswith("_") and hasattr(mod, n): + objs[n] = getattr(mod, n) + + globals_.update(objs) + return list(objs) + + +__all__ = ["get_xp", "clone_module"] + +def __dir__() -> list[str]: + return __all__ diff --git a/.venv/lib/python3.12/site-packages/scipy/_external/array_api_compat/common/__init__.py b/.venv/lib/python3.12/site-packages/scipy/_external/array_api_compat/common/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..8236080738175f0fb7d1f47fcc52522306b43050 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/scipy/_external/array_api_compat/common/__init__.py @@ -0,0 +1 @@ +from ._helpers import * # noqa: F403 diff --git a/.venv/lib/python3.12/site-packages/scipy/_external/array_api_compat/common/__pycache__/__init__.cpython-312.pyc b/.venv/lib/python3.12/site-packages/scipy/_external/array_api_compat/common/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b88f8cbb0d0d655286c0d20c057b3caf0fe788a5 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/scipy/_external/array_api_compat/common/__pycache__/__init__.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/scipy/_external/array_api_compat/common/__pycache__/_aliases.cpython-312.pyc b/.venv/lib/python3.12/site-packages/scipy/_external/array_api_compat/common/__pycache__/_aliases.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5dd75d4b66362f0b6835632901701854c2ff59be Binary files /dev/null and b/.venv/lib/python3.12/site-packages/scipy/_external/array_api_compat/common/__pycache__/_aliases.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/scipy/_external/array_api_compat/common/__pycache__/_fft.cpython-312.pyc b/.venv/lib/python3.12/site-packages/scipy/_external/array_api_compat/common/__pycache__/_fft.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6c0524f679f936effe2beac3b01ccf1f6e3212c8 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/scipy/_external/array_api_compat/common/__pycache__/_fft.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/scipy/_external/array_api_compat/common/__pycache__/_helpers.cpython-312.pyc b/.venv/lib/python3.12/site-packages/scipy/_external/array_api_compat/common/__pycache__/_helpers.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1239c092011ed99f14e3cf5504426f17264ababa Binary files /dev/null and b/.venv/lib/python3.12/site-packages/scipy/_external/array_api_compat/common/__pycache__/_helpers.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/scipy/_external/array_api_compat/common/__pycache__/_linalg.cpython-312.pyc b/.venv/lib/python3.12/site-packages/scipy/_external/array_api_compat/common/__pycache__/_linalg.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3528899f6c51febb6cfd95c8e2baf053b9e0d312 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/scipy/_external/array_api_compat/common/__pycache__/_linalg.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/scipy/_external/array_api_compat/common/__pycache__/_typing.cpython-312.pyc b/.venv/lib/python3.12/site-packages/scipy/_external/array_api_compat/common/__pycache__/_typing.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b680310112907e6bc122d02d4a700c399184b689 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/scipy/_external/array_api_compat/common/__pycache__/_typing.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/scipy/_external/array_api_compat/common/_aliases.py b/.venv/lib/python3.12/site-packages/scipy/_external/array_api_compat/common/_aliases.py new file mode 100644 index 0000000000000000000000000000000000000000..3587ef16fa18b22081770ecbd13335a4fed5ac0c --- /dev/null +++ b/.venv/lib/python3.12/site-packages/scipy/_external/array_api_compat/common/_aliases.py @@ -0,0 +1,702 @@ +""" +These are functions that are just aliases of existing functions in NumPy. +""" + +from __future__ import annotations + +import inspect +from collections.abc import Sequence +from typing import TYPE_CHECKING, Any, NamedTuple, cast + +from ._helpers import _check_device, array_namespace +from ._helpers import device as _get_device +from ._helpers import is_cupy_namespace +from ._typing import Array, Device, DType, Namespace + +if TYPE_CHECKING: + # TODO: import from typing (requires Python >=3.13) + from typing_extensions import TypeIs + +# These functions are modified from the NumPy versions. + +# Creation functions add the device keyword (which does nothing for NumPy and Dask) + + +def arange( + start: float, + /, + stop: float | None = None, + step: float = 1, + *, + xp: Namespace, + dtype: DType | None = None, + device: Device | None = None, + **kwargs: object, +) -> Array: + _check_device(xp, device) + return xp.arange(start, stop=stop, step=step, dtype=dtype, **kwargs) + + +def empty( + shape: int | tuple[int, ...], + xp: Namespace, + *, + dtype: DType | None = None, + device: Device | None = None, + **kwargs: object, +) -> Array: + _check_device(xp, device) + return xp.empty(shape, dtype=dtype, **kwargs) + + +def empty_like( + x: Array, + /, + xp: Namespace, + *, + dtype: DType | None = None, + device: Device | None = None, + **kwargs: object, +) -> Array: + _check_device(xp, device) + return xp.empty_like(x, dtype=dtype, **kwargs) + + +def eye( + n_rows: int, + n_cols: int | None = None, + /, + *, + xp: Namespace, + k: int = 0, + dtype: DType | None = None, + device: Device | None = None, + **kwargs: object, +) -> Array: + _check_device(xp, device) + return xp.eye(n_rows, M=n_cols, k=k, dtype=dtype, **kwargs) + + +def full( + shape: int | tuple[int, ...], + fill_value: complex, + xp: Namespace, + *, + dtype: DType | None = None, + device: Device | None = None, + **kwargs: object, +) -> Array: + _check_device(xp, device) + return xp.full(shape, fill_value, dtype=dtype, **kwargs) + + +def full_like( + x: Array, + /, + fill_value: complex, + *, + xp: Namespace, + dtype: DType | None = None, + device: Device | None = None, + **kwargs: object, +) -> Array: + _check_device(xp, device) + return xp.full_like(x, fill_value, dtype=dtype, **kwargs) + + +def linspace( + start: float, + stop: float, + /, + num: int, + *, + xp: Namespace, + dtype: DType | None = None, + device: Device | None = None, + endpoint: bool = True, + **kwargs: object, +) -> Array: + _check_device(xp, device) + return xp.linspace(start, stop, num, dtype=dtype, endpoint=endpoint, **kwargs) + + +def ones( + shape: int | tuple[int, ...], + xp: Namespace, + *, + dtype: DType | None = None, + device: Device | None = None, + **kwargs: object, +) -> Array: + _check_device(xp, device) + return xp.ones(shape, dtype=dtype, **kwargs) + + +def ones_like( + x: Array, + /, + xp: Namespace, + *, + dtype: DType | None = None, + device: Device | None = None, + **kwargs: object, +) -> Array: + _check_device(xp, device) + return xp.ones_like(x, dtype=dtype, **kwargs) + + +def zeros( + shape: int | tuple[int, ...], + xp: Namespace, + *, + dtype: DType | None = None, + device: Device | None = None, + **kwargs: object, +) -> Array: + _check_device(xp, device) + return xp.zeros(shape, dtype=dtype, **kwargs) + + +def zeros_like( + x: Array, + /, + xp: Namespace, + *, + dtype: DType | None = None, + device: Device | None = None, + **kwargs: object, +) -> Array: + _check_device(xp, device) + return xp.zeros_like(x, dtype=dtype, **kwargs) + + +# np.unique() is split into four functions in the array API: +# unique_all, unique_counts, unique_inverse, and unique_values (this is done +# to remove polymorphic return types). + +# The functions here return namedtuples (np.unique() returns a normal +# tuple). + + +# Note that these named tuples aren't actually part of the standard namespace, +# but I don't see any issue with exporting the names here regardless. +class UniqueAllResult(NamedTuple): + values: Array + indices: Array + inverse_indices: Array + counts: Array + + +class UniqueCountsResult(NamedTuple): + values: Array + counts: Array + + +class UniqueInverseResult(NamedTuple): + values: Array + inverse_indices: Array + + +def _unique_kwargs(xp: Namespace) -> dict[str, bool]: + # Older versions of NumPy and CuPy do not have equal_nan. Rather than + # trying to parse version numbers, just check if equal_nan is in the + # signature. + s = inspect.signature(xp.unique) + if "equal_nan" in s.parameters: + return {"equal_nan": False} + return {} + + +def unique_all(x: Array, /, xp: Namespace) -> UniqueAllResult: + kwargs = _unique_kwargs(xp) + values, indices, inverse_indices, counts = xp.unique( + x, + return_counts=True, + return_index=True, + return_inverse=True, + **kwargs, + ) + # np.unique() flattens inverse indices, but they need to share x's shape + # See https://github.com/numpy/numpy/issues/20638 + inverse_indices = inverse_indices.reshape(x.shape) + return UniqueAllResult( + values, + indices, + inverse_indices, + counts, + ) + + +def unique_counts(x: Array, /, xp: Namespace) -> UniqueCountsResult: + kwargs = _unique_kwargs(xp) + res = xp.unique( + x, return_counts=True, return_index=False, return_inverse=False, **kwargs + ) + + return UniqueCountsResult(*res) + + +def unique_inverse(x: Array, /, xp: Namespace) -> UniqueInverseResult: + kwargs = _unique_kwargs(xp) + values, inverse_indices = xp.unique( + x, + return_counts=False, + return_index=False, + return_inverse=True, + **kwargs, + ) + # xp.unique() flattens inverse indices, but they need to share x's shape + # See https://github.com/numpy/numpy/issues/20638 + inverse_indices = inverse_indices.reshape(x.shape) + return UniqueInverseResult(values, inverse_indices) + + +def unique_values(x: Array, /, xp: Namespace) -> Array: + kwargs = _unique_kwargs(xp) + return xp.unique( + x, + return_counts=False, + return_index=False, + return_inverse=False, + **kwargs, + ) + + +# These functions have different keyword argument names + + +def std( + x: Array, + /, + xp: Namespace, + *, + axis: int | tuple[int, ...] | None = None, + correction: float = 0.0, # correction instead of ddof + keepdims: bool = False, + **kwargs: object, +) -> Array: + return xp.std(x, axis=axis, ddof=correction, keepdims=keepdims, **kwargs) + + +def var( + x: Array, + /, + xp: Namespace, + *, + axis: int | tuple[int, ...] | None = None, + correction: float = 0.0, # correction instead of ddof + keepdims: bool = False, + **kwargs: object, +) -> Array: + return xp.var(x, axis=axis, ddof=correction, keepdims=keepdims, **kwargs) + + +# cumulative_sum is renamed from cumsum, and adds the include_initial keyword +# argument + + +def cumulative_sum( + x: Array, + /, + xp: Namespace, + *, + axis: int | None = None, + dtype: DType | None = None, + include_initial: bool = False, + **kwargs: object, +) -> Array: + wrapped_xp = array_namespace(x) + + # TODO: The standard is not clear about what should happen when x.ndim == 0. + if axis is None: + if x.ndim > 1: + raise ValueError( + "axis must be specified in cumulative_sum for more than one dimension" + ) + axis = 0 + + res = xp.cumsum(x, axis=axis, dtype=dtype, **kwargs) + + # np.cumsum does not support include_initial + if include_initial: + initial_shape = list(x.shape) + initial_shape[axis] = 1 + res = xp.concatenate( + [ + wrapped_xp.zeros( + shape=initial_shape, dtype=res.dtype, device=_get_device(res) + ), + res, + ], + axis=axis, + ) + return res + + +def cumulative_prod( + x: Array, + /, + xp: Namespace, + *, + axis: int | None = None, + dtype: DType | None = None, + include_initial: bool = False, + **kwargs: object, +) -> Array: + wrapped_xp = array_namespace(x) + + if axis is None: + if x.ndim > 1: + raise ValueError( + "axis must be specified in cumulative_prod for more than one dimension" + ) + axis = 0 + + res = xp.cumprod(x, axis=axis, dtype=dtype, **kwargs) + + # np.cumprod does not support include_initial + if include_initial: + initial_shape = list(x.shape) + initial_shape[axis] = 1 + res = xp.concatenate( + [ + wrapped_xp.ones( + shape=initial_shape, dtype=res.dtype, device=_get_device(res) + ), + res, + ], + axis=axis, + ) + return res + + +# The min and max argument names in clip are different and not optional in numpy, and type +# promotion behavior is different. +def clip( + x: Array, + /, + min: float | Array | None = None, + max: float | Array | None = None, + *, + xp: Namespace, + # TODO: np.clip has other ufunc kwargs + out: Array | None = None, +) -> Array: + def _isscalar(a: object) -> TypeIs[float | None]: + return isinstance(a, int | float) or a is None + + min_shape = () if _isscalar(min) else min.shape + max_shape = () if _isscalar(max) else max.shape + + wrapped_xp = array_namespace(x) + + result_shape = xp.broadcast_shapes(x.shape, min_shape, max_shape) + + # np.clip does type promotion but the array API clip requires that the + # output have the same dtype as x. We do this instead of just downcasting + # the result of xp.clip() to handle some corner cases better (e.g., + # avoiding uint64 -> float64 promotion). + + # Note: cases where min or max overflow (integer) or round (float) in the + # wrong direction when downcasting to x.dtype are unspecified. This code + # just does whatever NumPy does when it downcasts in the assignment, but + # other behavior could be preferred, especially for integers. For example, + # this code produces: + + # >>> clip(asarray(0, dtype=int8), asarray(128, dtype=int16), None) + # -128 + + # but an answer of 0 might be preferred. See + # https://github.com/numpy/numpy/issues/24976 for more discussion on this issue. + + # At least handle the case of Python integers correctly (see + # https://github.com/numpy/numpy/pull/26892). + if wrapped_xp.isdtype(x.dtype, "integral"): + if type(min) is int and min <= wrapped_xp.iinfo(x.dtype).min: + min = None + if type(max) is int and max >= wrapped_xp.iinfo(x.dtype).max: + max = None + + dev = _get_device(x) + if out is None: + out = wrapped_xp.empty(result_shape, dtype=x.dtype, device=dev) + assert out is not None # workaround for a type-narrowing issue in pyright + out[()] = x + + if min is not None: + a = wrapped_xp.asarray(min, dtype=x.dtype, device=dev) + a = xp.broadcast_to(a, result_shape) + ia = (out < a) | xp.isnan(a) + out[ia] = a[ia] + + if max is not None: + b = wrapped_xp.asarray(max, dtype=x.dtype, device=dev) + b = xp.broadcast_to(b, result_shape) + ib = (out > b) | xp.isnan(b) + out[ib] = b[ib] + + # Return a scalar for 0-D + return out[()] + + +# Unlike transpose(), the axes argument to permute_dims() is required. +def permute_dims(x: Array, /, axes: tuple[int, ...], xp: Namespace) -> Array: + return xp.transpose(x, axes) + + +# np.reshape calls the keyword argument 'newshape' instead of 'shape' +def reshape( + x: Array, + /, + shape: tuple[int, ...], + xp: Namespace, + *, + copy: bool | None = None, + **kwargs: object, +) -> Array: + if copy is True: + x = x.copy() + elif copy is False: + y = x.view() + y.shape = shape + return y + return xp.reshape(x, shape, **kwargs) + + +# The descending keyword is new in sort and argsort, and 'kind' replaced with +# 'stable' +def argsort( + x: Array, + /, + xp: Namespace, + *, + axis: int = -1, + descending: bool = False, + stable: bool = True, + **kwargs: object, +) -> Array: + # Note: this keyword argument is different, and the default is different. + # We set it in kwargs like this because numpy.sort uses kind='quicksort' + # as the default whereas cupy.sort uses kind=None. + if stable: + kwargs["kind"] = "stable" + if not descending: + res = xp.argsort(x, axis=axis, **kwargs) + else: + # As NumPy has no native descending sort, we imitate it here. Note that + # simply flipping the results of xp.argsort(x, ...) would not + # respect the relative order like it would in native descending sorts. + res = xp.flip( + xp.argsort(xp.flip(x, axis=axis), axis=axis, **kwargs), + axis=axis, + ) + # Rely on flip()/argsort() to validate axis + normalised_axis = axis if axis >= 0 else x.ndim + axis + max_i = x.shape[normalised_axis] - 1 + res = max_i - res + return res + + +def sort( + x: Array, + /, + xp: Namespace, + *, + axis: int = -1, + descending: bool = False, + stable: bool = True, + **kwargs: object, +) -> Array: + # Note: this keyword argument is different, and the default is different. + # We set it in kwargs like this because numpy.sort uses kind='quicksort' + # as the default whereas cupy.sort uses kind=None. + if stable: + kwargs["kind"] = "stable" + res = xp.sort(x, axis=axis, **kwargs) + if descending: + res = xp.flip(res, axis=axis) + return res + + +# nonzero should error for zero-dimensional arrays +def nonzero(x: Array, /, xp: Namespace, **kwargs: object) -> tuple[Array, ...]: + if x.ndim == 0: + raise ValueError("nonzero() does not support zero-dimensional arrays") + return xp.nonzero(x, **kwargs) + + +# linear algebra functions + + +def matmul(x1: Array, x2: Array, /, xp: Namespace, **kwargs: object) -> Array: + return xp.matmul(x1, x2, **kwargs) + + +# Unlike transpose, matrix_transpose only transposes the last two axes. +def matrix_transpose(x: Array, /, xp: Namespace) -> Array: + if x.ndim < 2: + raise ValueError("x must be at least 2-dimensional for matrix_transpose") + return xp.swapaxes(x, -1, -2) + + +def tensordot( + x1: Array, + x2: Array, + /, + xp: Namespace, + *, + axes: int | tuple[Sequence[int], Sequence[int]] = 2, + **kwargs: object, +) -> Array: + return xp.tensordot(x1, x2, axes=axes, **kwargs) + + +def vecdot(x1: Array, x2: Array, /, xp: Namespace, *, axis: int = -1) -> Array: + if x1.shape[axis] != x2.shape[axis]: + raise ValueError("x1 and x2 must have the same size along the given axis") + + if hasattr(xp, "broadcast_tensors"): + _broadcast = xp.broadcast_tensors + else: + _broadcast = xp.broadcast_arrays + + x1_ = xp.moveaxis(x1, axis, -1) + x2_ = xp.moveaxis(x2, axis, -1) + x1_, x2_ = _broadcast(x1_, x2_) + + res = xp.conj(x1_[..., None, :]) @ x2_[..., None] + return res[..., 0, 0] + + +# isdtype is a new function in the 2022.12 array API specification. + + +def isdtype( + dtype: DType, + kind: DType | str | tuple[DType | str, ...], + xp: Namespace, + *, + _tuple: bool = True, # Disallow nested tuples +) -> bool: + """ + Returns a boolean indicating whether a provided dtype is of a specified data type ``kind``. + + Note that outside of this function, this compat library does not yet fully + support complex numbers. + + See + https://data-apis.org/array-api/latest/API_specification/generated/array_api.isdtype.html + for more details + """ + if isinstance(kind, tuple) and _tuple: + return any( + isdtype(dtype, k, xp, _tuple=False) + for k in cast("tuple[DType | str, ...]", kind) + ) + elif isinstance(kind, str): + if kind == "bool": + return dtype == xp.bool_ + elif kind == "signed integer": + return xp.issubdtype(dtype, xp.signedinteger) + elif kind == "unsigned integer": + return xp.issubdtype(dtype, xp.unsignedinteger) + elif kind == "integral": + return xp.issubdtype(dtype, xp.integer) + elif kind == "real floating": + return xp.issubdtype(dtype, xp.floating) + elif kind == "complex floating": + return xp.issubdtype(dtype, xp.complexfloating) + elif kind == "numeric": + return xp.issubdtype(dtype, xp.number) + else: + raise ValueError(f"Unrecognized data type kind: {kind!r}") + else: + # This will allow things that aren't required by the spec, like + # isdtype(np.float64, float) or isdtype(np.int64, 'l'). Should we be + # more strict here to match the type annotation? Note that the + # array_api_strict implementation will be very strict. + return dtype == kind + + +# unstack is a new function in the 2023.12 array API standard +def unstack(x: Array, /, xp: Namespace, *, axis: int = 0) -> tuple[Array, ...]: + if x.ndim == 0: + raise ValueError("Input array must be at least 1-d.") + return tuple(xp.moveaxis(x, axis, 0)) + + +# numpy 1.26 does not use the standard definition for sign on complex numbers + + +def sign(x: Array, /, xp: Namespace, **kwargs: object) -> Array: + if isdtype(x.dtype, "complex floating", xp=xp): + out = (x / xp.abs(x, **kwargs))[...] + # sign(0) = 0 but the above formula would give nan + out[x == 0j] = 0j + else: + out = xp.sign(x, **kwargs) + # CuPy sign() does not propagate nans. See + # https://github.com/data-apis/array-api-compat/issues/136 + if is_cupy_namespace(xp) and isdtype(x.dtype, "real floating", xp=xp): + out[xp.isnan(x)] = xp.nan + return out[()] + + +def finfo(type_: DType | Array, /, xp: Namespace) -> Any: + # It is surprisingly difficult to recognize a dtype apart from an array. + # np.int64 is not the same as np.asarray(1).dtype! + try: + return xp.finfo(type_) + except (ValueError, TypeError): + return xp.finfo(type_.dtype) + + +def iinfo(type_: DType | Array, /, xp: Namespace) -> Any: + try: + return xp.iinfo(type_) + except (ValueError, TypeError): + return xp.iinfo(type_.dtype) + + +__all__ = [ + "arange", + "empty", + "empty_like", + "eye", + "full", + "full_like", + "linspace", + "ones", + "ones_like", + "zeros", + "zeros_like", + "UniqueAllResult", + "UniqueCountsResult", + "UniqueInverseResult", + "unique_all", + "unique_counts", + "unique_inverse", + "unique_values", + "std", + "var", + "cumulative_sum", + "cumulative_prod", + "clip", + "permute_dims", + "reshape", + "argsort", + "sort", + "nonzero", + "matmul", + "matrix_transpose", + "tensordot", + "vecdot", + "isdtype", + "unstack", + "sign", + "finfo", + "iinfo", +] + +def __dir__() -> list[str]: + return __all__ diff --git a/.venv/lib/python3.12/site-packages/scipy/_external/array_api_compat/common/_fft.py b/.venv/lib/python3.12/site-packages/scipy/_external/array_api_compat/common/_fft.py new file mode 100644 index 0000000000000000000000000000000000000000..18839d37f84949ec2bf851b548c2e13b5179e04e --- /dev/null +++ b/.venv/lib/python3.12/site-packages/scipy/_external/array_api_compat/common/_fft.py @@ -0,0 +1,213 @@ +from __future__ import annotations + +from collections.abc import Sequence +from typing import Literal, TypeAlias + +from ._typing import Array, Device, DType, Namespace + +_Norm: TypeAlias = Literal["backward", "ortho", "forward"] + +# Note: NumPy fft functions improperly upcast float32 and complex64 to +# complex128, which is why we require wrapping them all here. + +def fft( + x: Array, + /, + xp: Namespace, + *, + n: int | None = None, + axis: int = -1, + norm: _Norm = "backward", +) -> Array: + res = xp.fft.fft(x, n=n, axis=axis, norm=norm) + if x.dtype in [xp.float32, xp.complex64]: + return res.astype(xp.complex64) + return res + +def ifft( + x: Array, + /, + xp: Namespace, + *, + n: int | None = None, + axis: int = -1, + norm: _Norm = "backward", +) -> Array: + res = xp.fft.ifft(x, n=n, axis=axis, norm=norm) + if x.dtype in [xp.float32, xp.complex64]: + return res.astype(xp.complex64) + return res + +def fftn( + x: Array, + /, + xp: Namespace, + *, + s: Sequence[int] | None = None, + axes: Sequence[int] | None = None, + norm: _Norm = "backward", +) -> Array: + res = xp.fft.fftn(x, s=s, axes=axes, norm=norm) + if x.dtype in [xp.float32, xp.complex64]: + return res.astype(xp.complex64) + return res + +def ifftn( + x: Array, + /, + xp: Namespace, + *, + s: Sequence[int] | None = None, + axes: Sequence[int] | None = None, + norm: _Norm = "backward", +) -> Array: + res = xp.fft.ifftn(x, s=s, axes=axes, norm=norm) + if x.dtype in [xp.float32, xp.complex64]: + return res.astype(xp.complex64) + return res + +def rfft( + x: Array, + /, + xp: Namespace, + *, + n: int | None = None, + axis: int = -1, + norm: _Norm = "backward", +) -> Array: + res = xp.fft.rfft(x, n=n, axis=axis, norm=norm) + if x.dtype == xp.float32: + return res.astype(xp.complex64) + return res + +def irfft( + x: Array, + /, + xp: Namespace, + *, + n: int | None = None, + axis: int = -1, + norm: _Norm = "backward", +) -> Array: + res = xp.fft.irfft(x, n=n, axis=axis, norm=norm) + if x.dtype == xp.complex64: + return res.astype(xp.float32) + return res + +def rfftn( + x: Array, + /, + xp: Namespace, + *, + s: Sequence[int] | None = None, + axes: Sequence[int] | None = None, + norm: _Norm = "backward", +) -> Array: + res = xp.fft.rfftn(x, s=s, axes=axes, norm=norm) + if x.dtype == xp.float32: + return res.astype(xp.complex64) + return res + +def irfftn( + x: Array, + /, + xp: Namespace, + *, + s: Sequence[int] | None = None, + axes: Sequence[int] | None = None, + norm: _Norm = "backward", +) -> Array: + res = xp.fft.irfftn(x, s=s, axes=axes, norm=norm) + if x.dtype == xp.complex64: + return res.astype(xp.float32) + return res + +def hfft( + x: Array, + /, + xp: Namespace, + *, + n: int | None = None, + axis: int = -1, + norm: _Norm = "backward", +) -> Array: + res = xp.fft.hfft(x, n=n, axis=axis, norm=norm) + if x.dtype in [xp.float32, xp.complex64]: + return res.astype(xp.float32) + return res + +def ihfft( + x: Array, + /, + xp: Namespace, + *, + n: int | None = None, + axis: int = -1, + norm: _Norm = "backward", +) -> Array: + res = xp.fft.ihfft(x, n=n, axis=axis, norm=norm) + if x.dtype in [xp.float32, xp.complex64]: + return res.astype(xp.complex64) + return res + +def fftfreq( + n: int, + /, + xp: Namespace, + *, + d: float = 1.0, + dtype: DType | None = None, + device: Device | None = None, +) -> Array: + if device not in ["cpu", None]: + raise ValueError(f"Unsupported device {device!r}") + res = xp.fft.fftfreq(n, d=d) + if dtype is not None: + return res.astype(dtype) + return res + +def rfftfreq( + n: int, + /, + xp: Namespace, + *, + d: float = 1.0, + dtype: DType | None = None, + device: Device | None = None, +) -> Array: + if device not in ["cpu", None]: + raise ValueError(f"Unsupported device {device!r}") + res = xp.fft.rfftfreq(n, d=d) + if dtype is not None: + return res.astype(dtype) + return res + +def fftshift( + x: Array, /, xp: Namespace, *, axes: int | Sequence[int] | None = None +) -> Array: + return xp.fft.fftshift(x, axes=axes) + +def ifftshift( + x: Array, /, xp: Namespace, *, axes: int | Sequence[int] | None = None +) -> Array: + return xp.fft.ifftshift(x, axes=axes) + +__all__ = [ + "fft", + "ifft", + "fftn", + "ifftn", + "rfft", + "irfft", + "rfftn", + "irfftn", + "hfft", + "ihfft", + "fftfreq", + "rfftfreq", + "fftshift", + "ifftshift", +] + +def __dir__() -> list[str]: + return __all__ diff --git a/.venv/lib/python3.12/site-packages/scipy/_external/array_api_compat/common/_helpers.py b/.venv/lib/python3.12/site-packages/scipy/_external/array_api_compat/common/_helpers.py new file mode 100644 index 0000000000000000000000000000000000000000..8a307f9ddb5b6678b82eb609ba83bfb92b726c74 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/scipy/_external/array_api_compat/common/_helpers.py @@ -0,0 +1,1079 @@ +""" +Various helper functions which are not part of the spec. + +Functions which start with an underscore are for internal use only but helpers +that are in __all__ are intended as additional helper functions for use by end +users of the compat library. +""" + +from __future__ import annotations + +import enum +import inspect +import math +import sys +import warnings +from collections.abc import Collection, Hashable +from functools import lru_cache +from typing import ( + TYPE_CHECKING, + Any, + Final, + Literal, + SupportsIndex, + TypeAlias, + TypeGuard, + cast, + overload, +) + +from ._typing import Array, Device, HasShape, Namespace, SupportsArrayNamespace + +if TYPE_CHECKING: + import cupy as cp + import dask.array as da + import jax + import ndonnx as ndx + import numpy as np + import numpy.typing as npt + import sparse + import torch + + # TODO: import from typing (requires Python >=3.13) + from typing_extensions import TypeIs + + _ZeroGradientArray: TypeAlias = npt.NDArray[np.void] + + _ArrayApiObj: TypeAlias = ( + npt.NDArray[Any] + | cp.ndarray + | da.Array + | jax.Array + | ndx.Array + | sparse.SparseArray + | torch.Tensor + | SupportsArrayNamespace[Any] + ) + +_API_VERSIONS_OLD: Final = frozenset({"2021.12", "2022.12", "2023.12", "2024.12"}) +_API_VERSIONS: Final = _API_VERSIONS_OLD | frozenset({"2025.12"}) + + +@lru_cache(100) +def _issubclass_fast(cls: type, modname: str, clsname: str) -> bool: + try: + mod = sys.modules[modname] + except KeyError: + return False + parent_cls = getattr(mod, clsname) + return issubclass(cls, parent_cls) + + +def _is_jax_zero_gradient_array(x: object) -> TypeGuard[_ZeroGradientArray]: + """Return True if `x` is a zero-gradient array. + + These arrays are a design quirk of Jax that may one day be removed. + See https://github.com/google/jax/issues/20620. + """ + # Fast exit + try: + dtype = x.dtype # type: ignore[attr-defined] + except AttributeError: + return False + cls = cast(Hashable, type(dtype)) + if not _issubclass_fast(cls, "numpy.dtypes", "VoidDType"): + return False + + if "jax" not in sys.modules: + return False + + import jax + # jax.float0 is a np.dtype([('float0', 'V')]) + return dtype == jax.float0 + + +def is_numpy_array(x: object) -> TypeIs[npt.NDArray[Any]]: + """ + Return True if `x` is a NumPy array. + + This function does not import NumPy if it has not already been imported + and is therefore cheap to use. + + This also returns True for `ndarray` subclasses and NumPy scalar objects. + + See Also + -------- + + array_namespace + is_array_api_obj + is_cupy_array + is_torch_array + is_ndonnx_array + is_dask_array + is_jax_array + is_pydata_sparse_array + """ + # TODO: Should we reject ndarray subclasses? + cls = cast(Hashable, type(x)) + return ( + _issubclass_fast(cls, "numpy", "ndarray") + or _issubclass_fast(cls, "numpy", "generic") + ) and not _is_jax_zero_gradient_array(x) + + +def is_cupy_array(x: object) -> bool: + """ + Return True if `x` is a CuPy array. + + This function does not import CuPy if it has not already been imported + and is therefore cheap to use. + + This also returns True for `cupy.ndarray` subclasses and CuPy scalar objects. + + See Also + -------- + + array_namespace + is_array_api_obj + is_numpy_array + is_torch_array + is_ndonnx_array + is_dask_array + is_jax_array + is_pydata_sparse_array + """ + cls = cast(Hashable, type(x)) + return _issubclass_fast(cls, "cupy", "ndarray") + + +def is_torch_array(x: object) -> TypeIs[torch.Tensor]: + """ + Return True if `x` is a PyTorch tensor. + + This function does not import PyTorch if it has not already been imported + and is therefore cheap to use. + + See Also + -------- + + array_namespace + is_array_api_obj + is_numpy_array + is_cupy_array + is_dask_array + is_jax_array + is_pydata_sparse_array + """ + cls = cast(Hashable, type(x)) + return _issubclass_fast(cls, "torch", "Tensor") + + +def is_ndonnx_array(x: object) -> TypeIs[ndx.Array]: + """ + Return True if `x` is a ndonnx Array. + + This function does not import ndonnx if it has not already been imported + and is therefore cheap to use. + + See Also + -------- + + array_namespace + is_array_api_obj + is_numpy_array + is_cupy_array + is_ndonnx_array + is_dask_array + is_jax_array + is_pydata_sparse_array + """ + cls = cast(Hashable, type(x)) + return _issubclass_fast(cls, "ndonnx", "Array") + + +def is_dask_array(x: object) -> TypeIs[da.Array]: + """ + Return True if `x` is a dask.array Array. + + This function does not import dask if it has not already been imported + and is therefore cheap to use. + + See Also + -------- + + array_namespace + is_array_api_obj + is_numpy_array + is_cupy_array + is_torch_array + is_ndonnx_array + is_jax_array + is_pydata_sparse_array + """ + cls = cast(Hashable, type(x)) + return _issubclass_fast(cls, "dask.array", "Array") + + +def is_jax_array(x: object) -> TypeIs[jax.Array]: + """ + Return True if `x` is a JAX array. + + This function does not import JAX if it has not already been imported + and is therefore cheap to use. + + + See Also + -------- + + array_namespace + is_array_api_obj + is_numpy_array + is_cupy_array + is_torch_array + is_ndonnx_array + is_dask_array + is_pydata_sparse_array + """ + cls = cast(Hashable, type(x)) + # We test for jax.core.Tracer here to identify jax arrays during jit tracing. From jax 0.8.2 on, + # tracers are not a subclass of jax.Array anymore. Note that tracers can also represent + # non-array values and a fully correct implementation would need to use isinstance checks. Since + # we use hash-based caching with type names as keys, we cannot use instance checks without + # losing performance here. For more information, see + # https://github.com/data-apis/array-api-compat/pull/369 and the corresponding issue. + return ( + _issubclass_fast(cls, "jax", "Array") + or _issubclass_fast(cls, "jax.core", "Tracer") + or _is_jax_zero_gradient_array(x) + ) + + +def is_pydata_sparse_array(x: object) -> TypeIs[sparse.SparseArray]: + """ + Return True if `x` is an array from the `sparse` package. + + This function does not import `sparse` if it has not already been imported + and is therefore cheap to use. + + + See Also + -------- + + array_namespace + is_array_api_obj + is_numpy_array + is_cupy_array + is_torch_array + is_ndonnx_array + is_dask_array + is_jax_array + """ + # TODO: Account for other backends. + cls = cast(Hashable, type(x)) + return _issubclass_fast(cls, "sparse", "SparseArray") + + +def is_array_api_obj(x: object) -> TypeGuard[_ArrayApiObj]: + """ + Return True if `x` is an array API compatible array object. + + See Also + -------- + + array_namespace + is_numpy_array + is_cupy_array + is_torch_array + is_ndonnx_array + is_dask_array + is_jax_array + """ + return ( + hasattr(x, '__array_namespace__') + or _is_array_api_cls(cast(Hashable, type(x))) + ) + + +@lru_cache(100) +def _is_array_api_cls(cls: type) -> bool: + return ( + # TODO: drop support for numpy<2 which didn't have __array_namespace__ + _issubclass_fast(cls, "numpy", "ndarray") + or _issubclass_fast(cls, "numpy", "generic") + or _issubclass_fast(cls, "cupy", "ndarray") + or _issubclass_fast(cls, "torch", "Tensor") + or _issubclass_fast(cls, "dask.array", "Array") + or _issubclass_fast(cls, "sparse", "SparseArray") + # TODO: drop support for jax<0.4.32 which didn't have __array_namespace__ + or _issubclass_fast(cls, "jax", "Array") + or _issubclass_fast(cls, "jax.core", "Tracer") # see is_jax_array for limitations + ) + + +def _compat_module_name() -> str: + assert __name__.endswith(".common._helpers") + return __name__.removesuffix(".common._helpers") + + +@lru_cache(100) +def is_numpy_namespace(xp: Namespace) -> bool: + """ + Returns True if `xp` is a NumPy namespace. + + This includes both NumPy itself and the version wrapped by array-api-compat. + + See Also + -------- + + array_namespace + is_cupy_namespace + is_torch_namespace + is_ndonnx_namespace + is_dask_namespace + is_jax_namespace + is_pydata_sparse_namespace + is_array_api_strict_namespace + """ + return xp.__name__ in {"numpy", _compat_module_name() + ".numpy"} + + +@lru_cache(100) +def is_cupy_namespace(xp: Namespace) -> bool: + """ + Returns True if `xp` is a CuPy namespace. + + This includes both CuPy itself and the version wrapped by array-api-compat. + + See Also + -------- + + array_namespace + is_numpy_namespace + is_torch_namespace + is_ndonnx_namespace + is_dask_namespace + is_jax_namespace + is_pydata_sparse_namespace + is_array_api_strict_namespace + """ + return xp.__name__ in {"cupy", _compat_module_name() + ".cupy"} + + +@lru_cache(100) +def is_torch_namespace(xp: Namespace) -> bool: + """ + Returns True if `xp` is a PyTorch namespace. + + This includes both PyTorch itself and the version wrapped by array-api-compat. + + See Also + -------- + + array_namespace + is_numpy_namespace + is_cupy_namespace + is_ndonnx_namespace + is_dask_namespace + is_jax_namespace + is_pydata_sparse_namespace + is_array_api_strict_namespace + """ + return xp.__name__ in {"torch", _compat_module_name() + ".torch"} + + +def is_ndonnx_namespace(xp: Namespace) -> bool: + """ + Returns True if `xp` is an NDONNX namespace. + + See Also + -------- + + array_namespace + is_numpy_namespace + is_cupy_namespace + is_torch_namespace + is_dask_namespace + is_jax_namespace + is_pydata_sparse_namespace + is_array_api_strict_namespace + """ + return xp.__name__ == "ndonnx" + + +@lru_cache(100) +def is_dask_namespace(xp: Namespace) -> bool: + """ + Returns True if `xp` is a Dask namespace. + + This includes both ``dask.array`` itself and the version wrapped by array-api-compat. + + See Also + -------- + + array_namespace + is_numpy_namespace + is_cupy_namespace + is_torch_namespace + is_ndonnx_namespace + is_jax_namespace + is_pydata_sparse_namespace + is_array_api_strict_namespace + """ + return xp.__name__ in {"dask.array", _compat_module_name() + ".dask.array"} + + +def is_jax_namespace(xp: Namespace) -> bool: + """ + Returns True if `xp` is a JAX namespace. + + This includes ``jax.numpy`` and ``jax.experimental.array_api`` which existed in + older versions of JAX. + + See Also + -------- + + array_namespace + is_numpy_namespace + is_cupy_namespace + is_torch_namespace + is_ndonnx_namespace + is_dask_namespace + is_pydata_sparse_namespace + is_array_api_strict_namespace + """ + return xp.__name__ in {"jax.numpy", "jax.experimental.array_api"} + + +def is_pydata_sparse_namespace(xp: Namespace) -> bool: + """ + Returns True if `xp` is a pydata/sparse namespace. + + See Also + -------- + + array_namespace + is_numpy_namespace + is_cupy_namespace + is_torch_namespace + is_ndonnx_namespace + is_dask_namespace + is_jax_namespace + is_array_api_strict_namespace + """ + return xp.__name__ == "sparse" + + +def is_array_api_strict_namespace(xp: Namespace) -> bool: + """ + Returns True if `xp` is an array-api-strict namespace. + + See Also + -------- + + array_namespace + is_numpy_namespace + is_cupy_namespace + is_torch_namespace + is_ndonnx_namespace + is_dask_namespace + is_jax_namespace + is_pydata_sparse_namespace + """ + return xp.__name__ == "array_api_strict" + + +def _check_api_version(api_version: str | None) -> None: + if api_version in _API_VERSIONS_OLD: + warnings.warn( + f"The {api_version} version of the array API specification was requested but the returned namespace is actually version 2025.12" + ) + elif api_version is not None and api_version not in _API_VERSIONS: + raise ValueError( + "Only the 2025.12 version of the array API specification is currently supported" + ) + + +class _ClsToXPInfo(enum.Enum): + SCALAR = 0 + MAYBE_JAX_ZERO_GRADIENT = 1 + + +@lru_cache(100) +def _cls_to_namespace( + cls: type, + api_version: str | None, + use_compat: bool | None, +) -> tuple[Namespace | None, _ClsToXPInfo | None]: + if use_compat not in (None, True, False): + raise ValueError("use_compat must be None, True, or False") + _use_compat = use_compat in (None, True) + cls_ = cast(Hashable, cls) # Make mypy happy + + if ( + _issubclass_fast(cls_, "numpy", "ndarray") + or _issubclass_fast(cls_, "numpy", "generic") + ): + if use_compat is True: + _check_api_version(api_version) + from .. import numpy as xp + elif use_compat is False: + import numpy as xp # type: ignore[no-redef] + else: + # NumPy 2.0+ have __array_namespace__; however they are not + # yet fully array API compatible. + from .. import numpy as xp # type: ignore[no-redef] + return xp, _ClsToXPInfo.MAYBE_JAX_ZERO_GRADIENT + + # Note: this must happen _after_ the test for np.generic, + # because np.float64 and np.complex128 are subclasses of float and complex. + if issubclass(cls, int | float | complex | type(None)): + return None, _ClsToXPInfo.SCALAR + + if _issubclass_fast(cls_, "cupy", "ndarray"): + if _use_compat: + _check_api_version(api_version) + from .. import cupy as xp # type: ignore[no-redef] + else: + import cupy as xp # type: ignore[no-redef] + return xp, None + + if _issubclass_fast(cls_, "torch", "Tensor"): + if _use_compat: + _check_api_version(api_version) + from .. import torch as xp # type: ignore[no-redef] + else: + import torch as xp # type: ignore[no-redef] + return xp, None + + if _issubclass_fast(cls_, "dask.array", "Array"): + if _use_compat: + _check_api_version(api_version) + from ..dask import array as xp # type: ignore[no-redef] + else: + import dask.array as xp # type: ignore[no-redef] + return xp, None + + # Backwards compatibility for jax<0.4.32 + if _issubclass_fast(cls_, "jax", "Array"): + return _jax_namespace(api_version, use_compat), None + + return None, None + + +def _jax_namespace(api_version: str | None, use_compat: bool | None) -> Namespace: + if use_compat: + raise ValueError("JAX does not have an array-api-compat wrapper") + import jax.numpy as jnp + if not hasattr(jnp, "__array_namespace_info__"): + # JAX v0.4.32 and newer implements the array API directly in jax.numpy. + # For older JAX versions, it is available via jax.experimental.array_api. + # jnp.Array objects gain the __array_namespace__ method. + import jax.experimental.array_api # noqa: F401 + # Test api_version + return jnp.empty(0).__array_namespace__(api_version=api_version) + + +def array_namespace( + *xs: Array | complex | None, + api_version: str | None = None, + use_compat: bool | None = None, +) -> Namespace: + """ + Get the array API compatible namespace for the arrays `xs`. + + Parameters + ---------- + xs: arrays + one or more arrays. xs can also be Python scalars (bool, int, float, + complex, or None), which are ignored. + + api_version: str + The newest version of the spec that you need support for (currently + the compat library wrapped APIs support v2025.12). + + use_compat: bool or None + If None (the default), the native namespace will be returned if it is + already array API compatible; otherwise, a compat wrapper is used. If + True, the compat library wrapped library will be returned. If False, + the native library namespace is returned. + + Returns + ------- + + out: namespace + The array API compatible namespace corresponding to the arrays in `xs`. + + Raises + ------ + TypeError + If `xs` contains arrays from different array libraries or contains a + non-array. + + + Typical usage is to pass the arguments of a function to + `array_namespace()` at the top of a function to get the corresponding + array API namespace: + + .. code:: python + + def your_function(x, y): + xp = array_api_compat.array_namespace(x, y) + # Now use xp as the array library namespace + return xp.mean(x, axis=0) + 2*xp.std(y, axis=0) + + + Wrapped array namespaces can also be imported directly. For example, + `array_namespace(np.array(...))` will return `array_api_compat.numpy`. + This function will also work for any array library not wrapped by + array-api-compat if it explicitly defines `__array_namespace__ + `__ + (the wrapped namespace is always preferred if it exists). + + See Also + -------- + + is_array_api_obj + is_numpy_array + is_cupy_array + is_torch_array + is_dask_array + is_jax_array + is_pydata_sparse_array + + """ + namespaces: set[Namespace] = set() + for x in xs: + xp, info = _cls_to_namespace(cast(Hashable, type(x)), api_version, use_compat) + if info is _ClsToXPInfo.SCALAR: + continue + + if ( + info is _ClsToXPInfo.MAYBE_JAX_ZERO_GRADIENT + and _is_jax_zero_gradient_array(x) + ): + xp = _jax_namespace(api_version, use_compat) + + if xp is None: + get_ns = getattr(x, "__array_namespace__", None) + if get_ns is None: + raise TypeError(f"{type(x).__name__} is not a supported array type") + if use_compat: + raise ValueError( + "The given array does not have an array-api-compat wrapper" + ) + xp = get_ns(api_version=api_version) + + namespaces.add(xp) + + try: + (xp,) = namespaces + return xp + except ValueError: + if not namespaces: + raise TypeError( + "array_namespace requires at least one non-scalar array input" + ) + raise TypeError(f"Multiple namespaces for array inputs: {namespaces}") + + +# backwards compatibility alias +get_namespace = array_namespace + + +def _check_device(bare_xp: Namespace, device: Device) -> None: # pyright: ignore[reportUnusedFunction] + """ + Validate dummy device on device-less array backends. + + Notes + ----- + This function is also invoked by CuPy, which does have multiple devices + if there are multiple GPUs available. + However, CuPy multi-device support is currently impossible + without using the global device or a context manager: + + https://github.com/data-apis/array-api-compat/pull/293 + """ + if bare_xp is sys.modules.get("numpy"): + if device not in ("cpu", None): + raise ValueError(f"Unsupported device for NumPy: {device!r}") + + elif bare_xp is sys.modules.get("dask.array"): + if device not in ("cpu", _DASK_DEVICE, None): + raise ValueError(f"Unsupported device for Dask: {device!r}") + + +# Placeholder object to represent the dask device +# when the array backend is not the CPU. +# (since it is not easy to tell which device a dask array is on) +class _dask_device: + def __repr__(self) -> Literal["DASK_DEVICE"]: + return "DASK_DEVICE" + + +_DASK_DEVICE = _dask_device() + + +# device() is not on numpy.ndarray or dask.array and to_device() is not on numpy.ndarray +# or cupy.ndarray. They are not included in array objects of this library +# because this library just reuses the respective ndarray classes without +# wrapping or subclassing them. These helper functions can be used instead of +# the wrapper functions for libraries that need to support both NumPy/CuPy and +# other libraries that use devices. +def device(x: _ArrayApiObj, /) -> Device: + """ + Hardware device the array data resides on. + + This is equivalent to `x.device` according to the `standard + `__. + This helper is included because some array libraries either do not have + the `device` attribute or include it with an incompatible API. + + Parameters + ---------- + x: array + array instance from an array API compatible library. + + Returns + ------- + out: device + a ``device`` object (see the `Device Support `__ + section of the array API specification). + + Notes + ----- + + For NumPy the device is always `"cpu"`. For Dask, the device is always a + special `DASK_DEVICE` object. + + See Also + -------- + + to_device : Move array data to a different device. + + """ + if is_numpy_array(x): + return "cpu" + elif is_dask_array(x): + # Peek at the metadata of the Dask array to determine type + if is_numpy_array(x._meta): + # Must be on CPU since backed by numpy + return "cpu" + return _DASK_DEVICE + elif is_jax_array(x): + # FIXME Jitted JAX arrays do not have a device attribute + # https://github.com/jax-ml/jax/issues/26000 + # Return None in this case. Note that this workaround breaks + # the standard and will result in new arrays being created on the + # default device instead of the same device as the input array(s). + x_device = getattr(x, "device", None) + # Older JAX releases had .device() as a method, which has been replaced + # with a property in accordance with the standard. + if inspect.ismethod(x_device): + return x_device() + else: + return x_device + elif is_pydata_sparse_array(x): + # `sparse` will gain `.device`, so check for this first. + x_device = getattr(x, "device", None) + if x_device is not None: + return x_device + # Everything but DOK has this attr. + try: + inner = x.data # pyright: ignore + except AttributeError: + return "cpu" + # Return the device of the constituent array + return device(inner) # pyright: ignore + return x.device # type: ignore # pyright: ignore + + +# Prevent shadowing, used below +_device = device + + +# Based on cupy.array_api.Array.to_device +def _cupy_to_device( + x: cp.ndarray, + device: Device, + /, + stream: int | Any | None = None, +) -> cp.ndarray: + import cupy as cp + + if device == "cpu": + # allowing us to use `to_device(x, "cpu")` + # is useful for portable test swapping between + # host and device backends + return x.get() + if not isinstance(device, cp.cuda.Device): + raise TypeError(f"Unsupported device type {device!r}") + + if stream is None: + with device: + return cp.asarray(x) + + # stream can be an int as specified in __dlpack__, or a CuPy stream + if isinstance(stream, int): + stream = cp.cuda.ExternalStream(stream) + elif not isinstance(stream, cp.cuda.Stream): + raise TypeError(f"Unsupported stream type {stream!r}") + + with device, stream: + return cp.asarray(x) + + +def _torch_to_device( + x: torch.Tensor, + device: torch.device | str | int, + /, + stream: int | Any | None = None, +) -> torch.Tensor: + if stream is not None: + raise NotImplementedError + return x.to(device) + + +def to_device(x: Array, device: Device, /, *, stream: int | Any | None = None) -> Array: + """ + Copy the array from the device on which it currently resides to the specified ``device``. + + This is equivalent to `x.to_device(device, stream=stream)` according to + the `standard + `__. + This helper is included because some array libraries do not have the + `to_device` method. + + Parameters + ---------- + + x: array + array instance from an array API compatible library. + + device: device + a ``device`` object (see the `Device Support `__ + section of the array API specification). + + stream: int | Any | None + stream object to use during copy. In addition to the types supported + in ``array.__dlpack__``, implementations may choose to support any + library-specific stream object with the caveat that any code using + such an object would not be portable. + + Returns + ------- + + out: array + an array with the same data and data type as ``x`` and located on the + specified ``device``. + + Notes + ----- + + For NumPy, this function effectively does nothing since the only supported + device is the CPU. For CuPy, this method supports CuPy CUDA + :external+cupy:class:`Device ` and + :external+cupy:class:`Stream ` objects. For PyTorch, + this is the same as :external+torch:meth:`x.to(device) ` + (the ``stream`` argument is not supported in PyTorch). + + See Also + -------- + + device : Hardware device the array data resides on. + + """ + if is_numpy_array(x): + if stream is not None: + raise ValueError("The stream argument to to_device() is not supported") + if device == "cpu": + return x + raise ValueError(f"Unsupported device {device!r}") + elif is_cupy_array(x): + # cupy does not yet have to_device + return _cupy_to_device(x, device, stream=stream) + elif is_torch_array(x): + return _torch_to_device(x, device, stream=stream) + elif is_dask_array(x): + if stream is not None: + raise ValueError("The stream argument to to_device() is not supported") + # TODO: What if our array is on the GPU already? + if device == "cpu": + return x + raise ValueError(f"Unsupported device {device!r}") + elif is_jax_array(x): + if not hasattr(x, "__array_namespace__"): + # In JAX v0.4.31 and older, this import adds to_device method to x... + import jax.experimental.array_api # noqa: F401 # pyright: ignore + + # ... but only on eager JAX. It won't work inside jax.jit. + if not hasattr(x, "to_device"): + return x + return x.to_device(device, stream=stream) + elif is_pydata_sparse_array(x) and device == _device(x): + # Perform trivial check to return the same array if + # device is same instead of err-ing. + return x + return x.to_device(device, stream=stream) # pyright: ignore + + +@overload +def size(x: HasShape[Collection[SupportsIndex]]) -> int: ... +@overload +def size(x: HasShape[Collection[SupportsIndex | None]]) -> int | None: ... +def size(x: HasShape[Collection[SupportsIndex | None]]) -> int | None: + """ + Return the total number of elements of x. + + This is equivalent to `x.size` according to the `standard + `__. + + This helper is included because PyTorch defines `size` in an + :external+torch:meth:`incompatible way `. + It also fixes dask.array's behaviour which returns nan for unknown sizes, whereas + the standard requires None. + """ + # Lazy API compliant arrays, such as ndonnx, can contain None in their shape + if None in x.shape: + return None + out = math.prod(cast("Collection[SupportsIndex]", x.shape)) + # dask.array.Array.shape can contain NaN + return None if math.isnan(out) else out + + +@lru_cache(100) +def _is_writeable_cls(cls: type) -> bool | None: + if ( + _issubclass_fast(cls, "numpy", "generic") + or _issubclass_fast(cls, "jax", "Array") + or _issubclass_fast(cls, "jax.core", "Tracer") # see is_jax_array for limitations + or _issubclass_fast(cls, "sparse", "SparseArray") + ): + return False + if _is_array_api_cls(cls): + return True + return None + + +def is_writeable_array(x: object) -> TypeGuard[_ArrayApiObj]: + """ + Return False if ``x.__setitem__`` is expected to raise; True otherwise. + Return False if `x` is not an array API compatible object. + + Warning + ------- + As there is no standard way to check if an array is writeable without actually + writing to it, this function blindly returns True for all unknown array types. + """ + cls = cast(Hashable, type(x)) + if _issubclass_fast(cls, "numpy", "ndarray"): + return cast("npt.NDArray", x).flags.writeable + res = _is_writeable_cls(cls) + if res is not None: + return res + return hasattr(x, '__array_namespace__') + + +@lru_cache(100) +def _is_lazy_cls(cls: type) -> bool | None: + if ( + _issubclass_fast(cls, "numpy", "ndarray") + or _issubclass_fast(cls, "numpy", "generic") + or _issubclass_fast(cls, "cupy", "ndarray") + or _issubclass_fast(cls, "torch", "Tensor") + or _issubclass_fast(cls, "sparse", "SparseArray") + ): + return False + if ( + _issubclass_fast(cls, "jax", "Array") + or _issubclass_fast(cls, "jax.core", "Tracer") # see is_jax_array for limitations + or _issubclass_fast(cls, "dask.array", "Array") + or _issubclass_fast(cls, "ndonnx", "Array") + ): + return True + return None + + +def is_lazy_array(x: object) -> TypeGuard[_ArrayApiObj]: + """Return True if x is potentially a future or it may be otherwise impossible or + expensive to eagerly read its contents, regardless of their size, e.g. by + calling ``bool(x)`` or ``float(x)``. + + Return False otherwise; e.g. ``bool(x)`` etc. is guaranteed to succeed and to be + cheap as long as the array has the right dtype and size. + + Note + ---- + This function errs on the side of caution for array types that may or may not be + lazy, e.g. JAX arrays, by always returning True for them. + """ + # **JAX note:** while it is possible to determine if you're inside or outside + # jax.jit by testing the subclass of a jax.Array object, as well as testing bool() + # as we do below for unknown arrays, this is not recommended by JAX best practices. + + # **Dask note:** Dask eagerly computes the graph on __bool__, __float__, and so on. + # This behaviour, while impossible to change without breaking backwards + # compatibility, is highly detrimental to performance as the whole graph will end + # up being computed multiple times. + + # Note: skipping reclassification of JAX zero gradient arrays, as one will + # exclusively get them once they leave a jax.grad JIT context. + cls = cast(Hashable, type(x)) + res = _is_lazy_cls(cls) + if res is not None: + return res + + if not hasattr(x, "__array_namespace__"): + return False + + # Unknown Array API compatible object. Note that this test may have dire consequences + # in terms of performance, e.g. for a lazy object that eagerly computes the graph + # on __bool__ (dask is one such example, which however is special-cased above). + + # Select a single point of the array + s = size(cast("HasShape[Collection[SupportsIndex | None]]", x)) + if s is None: + return True + xp = array_namespace(x) + if s > 1: + x = xp.reshape(x, (-1,))[0] + # Cast to dtype=bool and deal with size 0 arrays + x = xp.any(x) + + try: + bool(x) + return False + # The Array API standard dictactes that __bool__ should raise TypeError if the + # output cannot be defined. + # Here we allow for it to raise arbitrary exceptions, e.g. like Dask does. + except Exception: + return True + + +__all__ = [ + "array_namespace", + "device", + "get_namespace", + "is_array_api_obj", + "is_array_api_strict_namespace", + "is_cupy_array", + "is_cupy_namespace", + "is_dask_array", + "is_dask_namespace", + "is_jax_array", + "is_jax_namespace", + "is_numpy_array", + "is_numpy_namespace", + "is_torch_array", + "is_torch_namespace", + "is_ndonnx_array", + "is_ndonnx_namespace", + "is_pydata_sparse_array", + "is_pydata_sparse_namespace", + "is_writeable_array", + "is_lazy_array", + "size", + "to_device", +] + +def __dir__() -> list[str]: + return __all__ diff --git a/.venv/lib/python3.12/site-packages/scipy/_external/array_api_compat/common/_linalg.py b/.venv/lib/python3.12/site-packages/scipy/_external/array_api_compat/common/_linalg.py new file mode 100644 index 0000000000000000000000000000000000000000..14b560d13d3f29cce31b09cef0cf85770c784b90 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/scipy/_external/array_api_compat/common/_linalg.py @@ -0,0 +1,234 @@ +from __future__ import annotations + +import math +from typing import Literal, NamedTuple, cast + +import numpy as np + +if np.__version__[0] == "2": + from numpy.lib.array_utils import normalize_axis_tuple +else: + from numpy.core.numeric import normalize_axis_tuple # type: ignore[no-redef] + +from .._internal import get_xp +from ._aliases import isdtype, matmul, matrix_transpose, tensordot, vecdot +from ._typing import Array, DType, JustFloat, JustInt, Namespace + + +# These are in the main NumPy namespace but not in numpy.linalg +def cross( + x1: Array, + x2: Array, + /, + xp: Namespace, + *, + axis: int = -1, + **kwargs: object, +) -> Array: + return xp.cross(x1, x2, axis=axis, **kwargs) + +def outer(x1: Array, x2: Array, /, xp: Namespace, **kwargs: object) -> Array: + return xp.outer(x1, x2, **kwargs) + +class EighResult(NamedTuple): + eigenvalues: Array + eigenvectors: Array + +class EigResult(NamedTuple): + eigenvalues: Array + eigenvectors: Array + +class QRResult(NamedTuple): + Q: Array + R: Array + +class SlogdetResult(NamedTuple): + sign: Array + logabsdet: Array + +class SVDResult(NamedTuple): + U: Array + S: Array + Vh: Array + +# These functions are the same as their NumPy counterparts except they return +# a namedtuple. +def eigh(x: Array, /, xp: Namespace, **kwargs: object) -> EighResult: + return EighResult(*xp.linalg.eigh(x, **kwargs)) + +def qr( + x: Array, + /, + xp: Namespace, + *, + mode: Literal["reduced", "complete"] = "reduced", + **kwargs: object, +) -> QRResult: + return QRResult(*xp.linalg.qr(x, mode=mode, **kwargs)) + +def slogdet(x: Array, /, xp: Namespace, **kwargs: object) -> SlogdetResult: + return SlogdetResult(*xp.linalg.slogdet(x, **kwargs)) + +def svd( + x: Array, + /, + xp: Namespace, + *, + full_matrices: bool = True, + **kwargs: object, +) -> SVDResult: + return SVDResult(*xp.linalg.svd(x, full_matrices=full_matrices, **kwargs)) + +# These functions have additional keyword arguments + +# The upper keyword argument is new from NumPy +def cholesky( + x: Array, + /, + xp: Namespace, + *, + upper: bool = False, + **kwargs: object, +) -> Array: + L = xp.linalg.cholesky(x, **kwargs) + if upper: + U = get_xp(xp)(matrix_transpose)(L) + if get_xp(xp)(isdtype)(U.dtype, 'complex floating'): + U = xp.conj(U) # pyright: ignore[reportConstantRedefinition] + return U + return L + +# The rtol keyword argument of matrix_rank() and pinv() is new from NumPy. +# Note that it has a different semantic meaning from tol and rcond. +def matrix_rank( + x: Array, + /, + xp: Namespace, + *, + rtol: float | Array | None = None, + **kwargs: object, +) -> Array: + # this is different from xp.linalg.matrix_rank, which supports 1 + # dimensional arrays. + if x.ndim < 2: + raise xp.linalg.LinAlgError("1-dimensional array given. Array must be at least two-dimensional") + S: Array = get_xp(xp)(svdvals)(x, **kwargs) + if rtol is None: + tol = S.max(axis=-1, keepdims=True) * max(x.shape[-2:]) * xp.finfo(S.dtype).eps + else: + # this is different from xp.linalg.matrix_rank, which does not + # multiply the tolerance by the largest singular value. + tol = S.max(axis=-1, keepdims=True)*xp.asarray(rtol)[..., xp.newaxis] + return xp.count_nonzero(S > tol, axis=-1) + +def pinv( + x: Array, + /, + xp: Namespace, + *, + rtol: float | Array | None = None, + **kwargs: object, +) -> Array: + # this is different from xp.linalg.pinv, which does not multiply the + # default tolerance by max(M, N). + if rtol is None: + rtol = max(x.shape[-2:]) * xp.finfo(x.dtype).eps + return xp.linalg.pinv(x, rcond=rtol, **kwargs) + +# These functions are new in the array API spec + +def matrix_norm( + x: Array, + /, + xp: Namespace, + *, + keepdims: bool = False, + ord: Literal[1, 2, -1, -2] | JustFloat | Literal["fro", "nuc"] | None = "fro", +) -> Array: + return xp.linalg.norm(x, axis=(-2, -1), keepdims=keepdims, ord=ord) + +# svdvals is not in NumPy (but it is in SciPy). It is equivalent to +# xp.linalg.svd(compute_uv=False). +def svdvals(x: Array, /, xp: Namespace) -> Array | tuple[Array, ...]: + return xp.linalg.svd(x, compute_uv=False) + +def vector_norm( + x: Array, + /, + xp: Namespace, + *, + axis: int | tuple[int, ...] | None = None, + keepdims: bool = False, + ord: JustInt | JustFloat = 2, +) -> Array: + # xp.linalg.norm tries to do a matrix norm whenever axis is a 2-tuple or + # when axis=None and the input is 2-D, so to force a vector norm, we make + # it so the input is 1-D (for axis=None), or reshape so that norm is done + # on a single dimension. + if axis is None: + # Note: xp.linalg.norm() doesn't handle 0-D arrays + _x = x.ravel() + _axis = 0 + elif isinstance(axis, tuple): + # Note: The axis argument supports any number of axes, whereas + # xp.linalg.norm() only supports a single axis for vector norm. + normalized_axis = cast( + "tuple[int, ...]", + normalize_axis_tuple(axis, x.ndim), # pyright: ignore[reportCallIssue] + ) + rest = tuple(i for i in range(x.ndim) if i not in normalized_axis) + newshape = axis + rest + _x = xp.transpose(x, newshape).reshape( + (math.prod([x.shape[i] for i in axis]), *[x.shape[i] for i in rest])) + _axis = 0 + else: + _x = x + _axis = axis + + res = xp.linalg.norm(_x, axis=_axis, ord=ord) + + if keepdims: + # We can't reuse xp.linalg.norm(keepdims) because of the reshape hacks + # above to avoid matrix norm logic. + shape = list(x.shape) + axes = cast( + "tuple[int, ...]", + normalize_axis_tuple( # pyright: ignore[reportCallIssue] + range(x.ndim) if axis is None else axis, + x.ndim, + ), + ) + for i in axes: + shape[i] = 1 + res = xp.reshape(res, tuple(shape)) + + return res + +# xp.diagonal and xp.trace operate on the first two axes whereas these +# operates on the last two + +def diagonal(x: Array, /, xp: Namespace, *, offset: int = 0, **kwargs: object) -> Array: + return xp.diagonal(x, offset=offset, axis1=-2, axis2=-1, **kwargs) + +def trace( + x: Array, + /, + xp: Namespace, + *, + offset: int = 0, + dtype: DType | None = None, + **kwargs: object, +) -> Array: + return xp.asarray( + xp.trace(x, offset=offset, dtype=dtype, axis1=-2, axis2=-1, **kwargs) + ) + +__all__ = ['cross', 'matmul', 'outer', 'tensordot', 'EighResult', + 'QRResult', 'SlogdetResult', 'SVDResult', 'eigh', 'qr', 'slogdet', + 'svd', 'cholesky', 'matrix_rank', 'pinv', 'matrix_norm', + 'matrix_transpose', 'svdvals', 'vecdot', 'vector_norm', 'diagonal', + 'trace'] + + +def __dir__() -> list[str]: + return __all__ diff --git a/.venv/lib/python3.12/site-packages/scipy/_external/array_api_compat/common/_typing.py b/.venv/lib/python3.12/site-packages/scipy/_external/array_api_compat/common/_typing.py new file mode 100644 index 0000000000000000000000000000000000000000..11b00bd10395f43bf71e008d09aad5dffaf2f98a --- /dev/null +++ b/.venv/lib/python3.12/site-packages/scipy/_external/array_api_compat/common/_typing.py @@ -0,0 +1,189 @@ +from __future__ import annotations + +from collections.abc import Mapping +from types import ModuleType as Namespace +from typing import ( + TYPE_CHECKING, + Literal, + Protocol, + TypeAlias, + TypedDict, + TypeVar, + final, +) + +if TYPE_CHECKING: + from _typeshed import Incomplete + + SupportsBufferProtocol: TypeAlias = Incomplete + Array: TypeAlias = Incomplete + Device: TypeAlias = Incomplete + DType: TypeAlias = Incomplete +else: + SupportsBufferProtocol = object + Array = object + Device = object + DType = object + + +_T_co = TypeVar("_T_co", covariant=True) + + +# These "Just" types are equivalent to the `Just` type from the `optype` library, +# apart from them not being `@runtime_checkable`. +# - docs: https://github.com/jorenham/optype/blob/master/README.md#just +# - code: https://github.com/jorenham/optype/blob/master/optype/_core/_just.py +@final +class JustInt(Protocol): # type: ignore[misc] + @property # type: ignore[override] + def __class__(self, /) -> type[int]: ... + @__class__.setter + def __class__(self, value: type[int], /) -> None: ... # pyright: ignore[reportIncompatibleMethodOverride] + + +@final +class JustFloat(Protocol): # type: ignore[misc] + @property # type: ignore[override] + def __class__(self, /) -> type[float]: ... + @__class__.setter + def __class__(self, value: type[float], /) -> None: ... # pyright: ignore[reportIncompatibleMethodOverride] + + +@final +class JustComplex(Protocol): # type: ignore[misc] + @property # type: ignore[override] + def __class__(self, /) -> type[complex]: ... + @__class__.setter + def __class__(self, value: type[complex], /) -> None: ... # pyright: ignore[reportIncompatibleMethodOverride] + + +class NestedSequence(Protocol[_T_co]): + def __getitem__(self, key: int, /) -> _T_co | NestedSequence[_T_co]: ... + def __len__(self, /) -> int: ... + + +class SupportsArrayNamespace(Protocol[_T_co]): + def __array_namespace__(self, /, *, api_version: str | None) -> _T_co: ... + + +class HasShape(Protocol[_T_co]): + @property + def shape(self, /) -> _T_co: ... + + +# Return type of `__array_namespace_info__.default_dtypes` +Capabilities = TypedDict( + "Capabilities", + { + "boolean indexing": bool, + "data-dependent shapes": bool, + "max dimensions": int, + }, +) + +# Return type of `__array_namespace_info__.default_dtypes` +DefaultDTypes = TypedDict( + "DefaultDTypes", + { + "real floating": DType, + "complex floating": DType, + "integral": DType, + "indexing": DType, + }, +) + + +_DTypeKind: TypeAlias = Literal[ + "bool", + "signed integer", + "unsigned integer", + "integral", + "real floating", + "complex floating", + "numeric", +] +# Type of the `kind` parameter in `__array_namespace_info__.dtypes` +DTypeKind: TypeAlias = _DTypeKind | tuple[_DTypeKind, ...] + + +# `__array_namespace_info__.dtypes(kind="bool")` +class DTypesBool(TypedDict): + bool: DType + + +# `__array_namespace_info__.dtypes(kind="signed integer")` +class DTypesSigned(TypedDict): + int8: DType + int16: DType + int32: DType + int64: DType + + +# `__array_namespace_info__.dtypes(kind="unsigned integer")` +class DTypesUnsigned(TypedDict): + uint8: DType + uint16: DType + uint32: DType + uint64: DType + + +# `__array_namespace_info__.dtypes(kind="integral")` +class DTypesIntegral(DTypesSigned, DTypesUnsigned): + pass + + +# `__array_namespace_info__.dtypes(kind="real floating")` +class DTypesReal(TypedDict): + float32: DType + float64: DType + + +# `__array_namespace_info__.dtypes(kind="complex floating")` +class DTypesComplex(TypedDict): + complex64: DType + complex128: DType + + +# `__array_namespace_info__.dtypes(kind="numeric")` +class DTypesNumeric(DTypesIntegral, DTypesReal, DTypesComplex): + pass + + +# `__array_namespace_info__.dtypes(kind=None)` (default) +class DTypesAll(DTypesBool, DTypesNumeric): + pass + + +# `__array_namespace_info__.dtypes(kind=?)` (fallback) +DTypesAny: TypeAlias = Mapping[str, DType] + + +__all__ = [ + "Array", + "Capabilities", + "DType", + "DTypeKind", + "DTypesAny", + "DTypesAll", + "DTypesBool", + "DTypesNumeric", + "DTypesIntegral", + "DTypesSigned", + "DTypesUnsigned", + "DTypesReal", + "DTypesComplex", + "DefaultDTypes", + "Device", + "HasShape", + "Namespace", + "JustInt", + "JustFloat", + "JustComplex", + "NestedSequence", + "SupportsArrayNamespace", + "SupportsBufferProtocol", +] + + +def __dir__() -> list[str]: + return __all__ diff --git a/.venv/lib/python3.12/site-packages/scipy/_external/array_api_compat/cupy/__init__.py b/.venv/lib/python3.12/site-packages/scipy/_external/array_api_compat/cupy/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..558a83e1eff21462128595d2bb66a21c501c4aee --- /dev/null +++ b/.venv/lib/python3.12/site-packages/scipy/_external/array_api_compat/cupy/__init__.py @@ -0,0 +1,24 @@ +from typing import Final +from cupy import * # noqa: F403 + +# from cupy import * doesn't overwrite these builtin names +from cupy import abs, max, min, round # noqa: F401 + +# These imports may overwrite names from the import * above. +from ._aliases import * # noqa: F403 +from ._info import __array_namespace_info__ # noqa: F401 + +# See the comment in the numpy __init__.py +__import__(__package__ + '.linalg') +__import__(__package__ + '.fft') + +__array_api_version__: Final = '2025.12' + +__all__ = sorted( + {name for name in globals() if not name.startswith("__")} + - {"Final", "_aliases", "_info", "_typing"} + | {"__array_api_version__", "__array_namespace_info__", "linalg", "fft"} +) + +def __dir__() -> list[str]: + return __all__ diff --git a/.venv/lib/python3.12/site-packages/scipy/_external/array_api_compat/cupy/_aliases.py b/.venv/lib/python3.12/site-packages/scipy/_external/array_api_compat/cupy/_aliases.py new file mode 100644 index 0000000000000000000000000000000000000000..44808ec9a947104394c3e0ed152fd3dd2c5da166 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/scipy/_external/array_api_compat/cupy/_aliases.py @@ -0,0 +1,208 @@ +from __future__ import annotations + +from builtins import bool as py_bool +from typing import Literal + +import cupy as cp + +from ..common import _aliases, _helpers +from ..common._typing import NestedSequence, SupportsBufferProtocol +from .._internal import get_xp +from ._typing import Array, Device, DType + +bool = cp.bool_ + +# Basic renames +acos = cp.arccos +acosh = cp.arccosh +asin = cp.arcsin +asinh = cp.arcsinh +atan = cp.arctan +atan2 = cp.arctan2 +atanh = cp.arctanh +bitwise_left_shift = cp.left_shift +bitwise_invert = cp.invert +bitwise_right_shift = cp.right_shift +concat = cp.concatenate +pow = cp.power + +arange = get_xp(cp)(_aliases.arange) +empty = get_xp(cp)(_aliases.empty) +empty_like = get_xp(cp)(_aliases.empty_like) +eye = get_xp(cp)(_aliases.eye) +full = get_xp(cp)(_aliases.full) +full_like = get_xp(cp)(_aliases.full_like) +linspace = get_xp(cp)(_aliases.linspace) +ones = get_xp(cp)(_aliases.ones) +ones_like = get_xp(cp)(_aliases.ones_like) +zeros = get_xp(cp)(_aliases.zeros) +zeros_like = get_xp(cp)(_aliases.zeros_like) +UniqueAllResult = get_xp(cp)(_aliases.UniqueAllResult) +UniqueCountsResult = get_xp(cp)(_aliases.UniqueCountsResult) +UniqueInverseResult = get_xp(cp)(_aliases.UniqueInverseResult) +unique_all = get_xp(cp)(_aliases.unique_all) +unique_counts = get_xp(cp)(_aliases.unique_counts) +unique_inverse = get_xp(cp)(_aliases.unique_inverse) +unique_values = get_xp(cp)(_aliases.unique_values) +std = get_xp(cp)(_aliases.std) +var = get_xp(cp)(_aliases.var) +cumulative_sum = get_xp(cp)(_aliases.cumulative_sum) +cumulative_prod = get_xp(cp)(_aliases.cumulative_prod) +clip = get_xp(cp)(_aliases.clip) +permute_dims = get_xp(cp)(_aliases.permute_dims) +reshape = get_xp(cp)(_aliases.reshape) +argsort = get_xp(cp)(_aliases.argsort) +sort = get_xp(cp)(_aliases.sort) +nonzero = get_xp(cp)(_aliases.nonzero) +matmul = get_xp(cp)(_aliases.matmul) +matrix_transpose = get_xp(cp)(_aliases.matrix_transpose) +tensordot = get_xp(cp)(_aliases.tensordot) +sign = get_xp(cp)(_aliases.sign) +finfo = get_xp(cp)(_aliases.finfo) +iinfo = get_xp(cp)(_aliases.iinfo) + + +# asarray also adds the copy keyword, which is not present in numpy 1.0. +def asarray( + obj: Array | complex | NestedSequence[complex] | SupportsBufferProtocol, + /, + *, + dtype: DType | None = None, + device: Device | None = None, + copy: py_bool | None = None, + **kwargs: object, +) -> Array: + """ + Array API compatibility wrapper for asarray(). + + See the corresponding documentation in the array library and/or the array API + specification for more details. + """ + with cp.cuda.Device(device): + if copy is None: + return cp.asarray(obj, dtype=dtype, **kwargs) + else: + res = cp.array(obj, dtype=dtype, copy=copy, **kwargs) + if not copy and res is not obj: + raise ValueError("Unable to avoid copy while creating an array as requested") + return res + + +def astype( + x: Array, + dtype: DType, + /, + *, + copy: py_bool = True, + device: Device | None = None, +) -> Array: + if device is None: + return x.astype(dtype=dtype, copy=copy) + out = _helpers.to_device(x.astype(dtype=dtype, copy=False), device) + return out.copy() if copy and out is x else out + + +# cupy.count_nonzero does not have keepdims +def count_nonzero( + x: Array, + axis: int | tuple[int, ...] | None = None, + keepdims: py_bool = False, +) -> Array: + result = cp.count_nonzero(x, axis) + if keepdims: + if axis is None: + return cp.reshape(result, [1]*x.ndim) + return cp.expand_dims(result, axis) + return result + +# ceil, floor, and trunc return integers for integer inputs + +def ceil(x: Array, /) -> Array: + if cp.issubdtype(x.dtype, cp.integer): + return x.copy() + return cp.ceil(x) + + +def floor(x: Array, /) -> Array: + if cp.issubdtype(x.dtype, cp.integer): + return x.copy() + return cp.floor(x) + + +def trunc(x: Array, /) -> Array: + if cp.issubdtype(x.dtype, cp.integer): + return x.copy() + return cp.trunc(x) + + +# take_along_axis: axis defaults to -1 but in cupy (and numpy) axis is a required arg +def take_along_axis(x: Array, indices: Array, /, *, axis: int = -1) -> Array: + return cp.take_along_axis(x, indices, axis=axis) + + +# https://github.com/cupy/cupy/pull/9582 +def broadcast_arrays(*arrays: Array) -> tuple[Array, ...]: + return tuple(cp.broadcast_arrays(*arrays)) + + +def meshgrid(*arrays: Array, indexing: Literal['xy', 'ij'] = 'xy') -> tuple[Array, ...]: + return tuple(cp.meshgrid(*arrays, indexing=indexing)) + + +# Match https://github.com/cupy/cupy/pull/9512/ until cupy v14 is the minimum +# supported version +def searchsorted( + x1: Array, + x2: Array | int | float, + /, + *, + side: Literal['left', 'right'] = 'left', + sorter: Array | None = None +) -> Array: + if not isinstance(x2, cp.ndarray): + if not isinstance(x2, int | float | complex): + raise NotImplementedError( + 'Only python scalars or ndarrays are supported for x2') + x2 = cp.asarray(x2) + return cp.searchsorted(x1, x2, side, sorter) + + +# CuPy isin does not accept scalars +def isin(x1: Array | int, x2: Array | int, /, *, invert: bool = False, **kwds) -> Array: + if isinstance(x1, int): + x1 = cp.asarray(x1) + if isinstance(x2, int): + x2 = cp.asarray(x2) + return cp.isin(x1, x2, invert=invert, **kwds) + + +# These functions are completely new here. If the library already has them +# (i.e., numpy 2.0), use the library version instead of our wrapper. +if hasattr(cp, 'vecdot'): + vecdot = cp.vecdot +else: + vecdot = get_xp(cp)(_aliases.vecdot) + +if hasattr(cp, 'isdtype'): + isdtype = cp.isdtype +else: + isdtype = get_xp(cp)(_aliases.isdtype) + +if hasattr(cp, 'unstack'): + unstack = cp.unstack +else: + unstack = get_xp(cp)(_aliases.unstack) + +__all__ = _aliases.__all__ + ['asarray', 'astype', + 'acos', 'acosh', 'asin', 'asinh', 'atan', + 'atan2', 'atanh', 'bitwise_left_shift', + 'bitwise_invert', 'bitwise_right_shift', + 'bool', 'concat', 'count_nonzero', 'pow', 'sign', + 'ceil', 'floor', 'trunc', 'take_along_axis', + 'broadcast_arrays', 'meshgrid', + 'searchsorted', 'isin', +] + + +def __dir__() -> list[str]: + return __all__ diff --git a/.venv/lib/python3.12/site-packages/scipy/_external/array_api_compat/cupy/_info.py b/.venv/lib/python3.12/site-packages/scipy/_external/array_api_compat/cupy/_info.py new file mode 100644 index 0000000000000000000000000000000000000000..aef10e85f290cb29a4755e8f62019e47e4a22eb2 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/scipy/_external/array_api_compat/cupy/_info.py @@ -0,0 +1,336 @@ +""" +Array API Inspection namespace + +This is the namespace for inspection functions as defined by the array API +standard. See +https://data-apis.org/array-api/latest/API_specification/inspection.html for +more details. + +""" +from cupy import ( + dtype, + cuda, + bool_ as bool, + intp, + int8, + int16, + int32, + int64, + uint8, + uint16, + uint32, + uint64, + float32, + float64, + complex64, + complex128, +) + + +class __array_namespace_info__: + """ + Get the array API inspection namespace for CuPy. + + The array API inspection namespace defines the following functions: + + - capabilities() + - default_device() + - default_dtypes() + - dtypes() + - devices() + + See + https://data-apis.org/array-api/latest/API_specification/inspection.html + for more details. + + Returns + ------- + info : ModuleType + The array API inspection namespace for CuPy. + + Examples + -------- + >>> info = xp.__array_namespace_info__() + >>> info.default_dtypes() + {'real floating': cupy.float64, + 'complex floating': cupy.complex128, + 'integral': cupy.int64, + 'indexing': cupy.int64} + + """ + + __module__ = 'cupy' + + def capabilities(self): + """ + Return a dictionary of array API library capabilities. + + The resulting dictionary has the following keys: + + - **"boolean indexing"**: boolean indicating whether an array library + supports boolean indexing. Always ``True`` for CuPy. + + - **"data-dependent shapes"**: boolean indicating whether an array + library supports data-dependent output shapes. Always ``True`` for + CuPy. + + See + https://data-apis.org/array-api/latest/API_specification/generated/array_api.info.capabilities.html + for more details. + + See Also + -------- + __array_namespace_info__.default_device, + __array_namespace_info__.default_dtypes, + __array_namespace_info__.dtypes, + __array_namespace_info__.devices + + Returns + ------- + capabilities : dict + A dictionary of array API library capabilities. + + Examples + -------- + >>> info = xp.__array_namespace_info__() + >>> info.capabilities() + {'boolean indexing': True, + 'data-dependent shapes': True, + 'max dimensions': 64} + + """ + return { + "boolean indexing": True, + "data-dependent shapes": True, + "max dimensions": 64, + } + + def default_device(self): + """ + The default device used for new CuPy arrays. + + See Also + -------- + __array_namespace_info__.capabilities, + __array_namespace_info__.default_dtypes, + __array_namespace_info__.dtypes, + __array_namespace_info__.devices + + Returns + ------- + device : Device + The default device used for new CuPy arrays. + + Examples + -------- + >>> info = xp.__array_namespace_info__() + >>> info.default_device() + Device(0) + + Notes + ----- + This method returns the static default device when CuPy is initialized. + However, the *current* device used by creation functions (``empty`` etc.) + can be changed globally or with a context manager. + + See Also + -------- + https://github.com/data-apis/array-api/issues/835 + """ + return cuda.Device(0) + + def default_dtypes(self, *, device=None): + """ + The default data types used for new CuPy arrays. + + For CuPy, this always returns the following dictionary: + + - **"real floating"**: ``cupy.float64`` + - **"complex floating"**: ``cupy.complex128`` + - **"integral"**: ``cupy.intp`` + - **"indexing"**: ``cupy.intp`` + + Parameters + ---------- + device : str, optional + The device to get the default data types for. + + Returns + ------- + dtypes : dict + A dictionary describing the default data types used for new CuPy + arrays. + + See Also + -------- + __array_namespace_info__.capabilities, + __array_namespace_info__.default_device, + __array_namespace_info__.dtypes, + __array_namespace_info__.devices + + Examples + -------- + >>> info = xp.__array_namespace_info__() + >>> info.default_dtypes() + {'real floating': cupy.float64, + 'complex floating': cupy.complex128, + 'integral': cupy.int64, + 'indexing': cupy.int64} + + """ + # TODO: Does this depend on device? + return { + "real floating": dtype(float64), + "complex floating": dtype(complex128), + "integral": dtype(intp), + "indexing": dtype(intp), + } + + def dtypes(self, *, device=None, kind=None): + """ + The array API data types supported by CuPy. + + Note that this function only returns data types that are defined by + the array API. + + Parameters + ---------- + device : str, optional + The device to get the data types for. + kind : str or tuple of str, optional + The kind of data types to return. If ``None``, all data types are + returned. If a string, only data types of that kind are returned. + If a tuple, a dictionary containing the union of the given kinds + is returned. The following kinds are supported: + + - ``'bool'``: boolean data types (i.e., ``bool``). + - ``'signed integer'``: signed integer data types (i.e., ``int8``, + ``int16``, ``int32``, ``int64``). + - ``'unsigned integer'``: unsigned integer data types (i.e., + ``uint8``, ``uint16``, ``uint32``, ``uint64``). + - ``'integral'``: integer data types. Shorthand for ``('signed + integer', 'unsigned integer')``. + - ``'real floating'``: real-valued floating-point data types + (i.e., ``float32``, ``float64``). + - ``'complex floating'``: complex floating-point data types (i.e., + ``complex64``, ``complex128``). + - ``'numeric'``: numeric data types. Shorthand for ``('integral', + 'real floating', 'complex floating')``. + + Returns + ------- + dtypes : dict + A dictionary mapping the names of data types to the corresponding + CuPy data types. + + See Also + -------- + __array_namespace_info__.capabilities, + __array_namespace_info__.default_device, + __array_namespace_info__.default_dtypes, + __array_namespace_info__.devices + + Examples + -------- + >>> info = xp.__array_namespace_info__() + >>> info.dtypes(kind='signed integer') + {'int8': cupy.int8, + 'int16': cupy.int16, + 'int32': cupy.int32, + 'int64': cupy.int64} + + """ + # TODO: Does this depend on device? + if kind is None: + return { + "bool": dtype(bool), + "int8": dtype(int8), + "int16": dtype(int16), + "int32": dtype(int32), + "int64": dtype(int64), + "uint8": dtype(uint8), + "uint16": dtype(uint16), + "uint32": dtype(uint32), + "uint64": dtype(uint64), + "float32": dtype(float32), + "float64": dtype(float64), + "complex64": dtype(complex64), + "complex128": dtype(complex128), + } + if kind == "bool": + return {"bool": bool} + if kind == "signed integer": + return { + "int8": dtype(int8), + "int16": dtype(int16), + "int32": dtype(int32), + "int64": dtype(int64), + } + if kind == "unsigned integer": + return { + "uint8": dtype(uint8), + "uint16": dtype(uint16), + "uint32": dtype(uint32), + "uint64": dtype(uint64), + } + if kind == "integral": + return { + "int8": dtype(int8), + "int16": dtype(int16), + "int32": dtype(int32), + "int64": dtype(int64), + "uint8": dtype(uint8), + "uint16": dtype(uint16), + "uint32": dtype(uint32), + "uint64": dtype(uint64), + } + if kind == "real floating": + return { + "float32": dtype(float32), + "float64": dtype(float64), + } + if kind == "complex floating": + return { + "complex64": dtype(complex64), + "complex128": dtype(complex128), + } + if kind == "numeric": + return { + "int8": dtype(int8), + "int16": dtype(int16), + "int32": dtype(int32), + "int64": dtype(int64), + "uint8": dtype(uint8), + "uint16": dtype(uint16), + "uint32": dtype(uint32), + "uint64": dtype(uint64), + "float32": dtype(float32), + "float64": dtype(float64), + "complex64": dtype(complex64), + "complex128": dtype(complex128), + } + if isinstance(kind, tuple): + res = {} + for k in kind: + res.update(self.dtypes(kind=k)) + return res + raise ValueError(f"unsupported kind: {kind!r}") + + def devices(self): + """ + The devices supported by CuPy. + + Returns + ------- + devices : list[Device] + The devices supported by CuPy. + + See Also + -------- + __array_namespace_info__.capabilities, + __array_namespace_info__.default_device, + __array_namespace_info__.default_dtypes, + __array_namespace_info__.dtypes + + """ + return tuple(cuda.Device(i) for i in range(cuda.runtime.getDeviceCount())) diff --git a/.venv/lib/python3.12/site-packages/scipy/_external/array_api_compat/cupy/_typing.py b/.venv/lib/python3.12/site-packages/scipy/_external/array_api_compat/cupy/_typing.py new file mode 100644 index 0000000000000000000000000000000000000000..e5c202dc53e097936671115943072ad58dd8d389 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/scipy/_external/array_api_compat/cupy/_typing.py @@ -0,0 +1,30 @@ +from __future__ import annotations + +__all__ = ["Array", "DType", "Device"] + +from typing import TYPE_CHECKING + +import cupy as cp +from cupy import ndarray as Array +from cupy.cuda.device import Device + +if TYPE_CHECKING: + # NumPy 1.x on Python 3.10 fails to parse np.dtype[] + DType = cp.dtype[ + cp.intp + | cp.int8 + | cp.int16 + | cp.int32 + | cp.int64 + | cp.uint8 + | cp.uint16 + | cp.uint32 + | cp.uint64 + | cp.float32 + | cp.float64 + | cp.complex64 + | cp.complex128 + | cp.bool_ + ] +else: + DType = cp.dtype diff --git a/.venv/lib/python3.12/site-packages/scipy/_external/array_api_compat/cupy/fft.py b/.venv/lib/python3.12/site-packages/scipy/_external/array_api_compat/cupy/fft.py new file mode 100644 index 0000000000000000000000000000000000000000..53a9a45438651bc2adc7bc19884fe9361ef99580 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/scipy/_external/array_api_compat/cupy/fft.py @@ -0,0 +1,36 @@ +from cupy.fft import * # noqa: F403 + +# cupy.fft doesn't have __all__. If it is added, replace this with +# +# from cupy.fft import __all__ as linalg_all +_n: dict[str, object] = {} +exec("from cupy.fft import *", _n) +del _n["__builtins__"] +fft_all = list(_n) +del _n + +from ..common import _fft +from .._internal import get_xp + +import cupy as cp + +fft = get_xp(cp)(_fft.fft) +ifft = get_xp(cp)(_fft.ifft) +fftn = get_xp(cp)(_fft.fftn) +ifftn = get_xp(cp)(_fft.ifftn) +rfft = get_xp(cp)(_fft.rfft) +irfft = get_xp(cp)(_fft.irfft) +rfftn = get_xp(cp)(_fft.rfftn) +irfftn = get_xp(cp)(_fft.irfftn) +hfft = get_xp(cp)(_fft.hfft) +ihfft = get_xp(cp)(_fft.ihfft) +fftfreq = get_xp(cp)(_fft.fftfreq) +rfftfreq = get_xp(cp)(_fft.rfftfreq) +fftshift = get_xp(cp)(_fft.fftshift) +ifftshift = get_xp(cp)(_fft.ifftshift) + +__all__ = fft_all + _fft.__all__ + +def __dir__() -> list[str]: + return __all__ + diff --git a/.venv/lib/python3.12/site-packages/scipy/_external/array_api_compat/cupy/linalg.py b/.venv/lib/python3.12/site-packages/scipy/_external/array_api_compat/cupy/linalg.py new file mode 100644 index 0000000000000000000000000000000000000000..1943cb15e5cf9cb843c25d5193ac67c01ab6ebee --- /dev/null +++ b/.venv/lib/python3.12/site-packages/scipy/_external/array_api_compat/cupy/linalg.py @@ -0,0 +1,62 @@ +from cupy.linalg import * # noqa: F403 + +# https://github.com/cupy/cupy/issues/9749 +from cupy.linalg import lstsq # noqa: F401 + +# cupy.linalg doesn't have __all__ in cupy<14. If it is added, replace this with +# +# from cupy.linalg import __all__ as linalg_all +_n: dict[str, object] = {} +exec('from cupy.linalg import *', _n) +del _n['__builtins__'] +linalg_all = list(_n) + ['lstsq'] +del _n + +try: + # cupy 14 exports it, cupy 13 does not + from cupy.linalg import annotations # noqa: F401 + linalg_all += ['annotations'] +except ImportError: + pass + + +from ..common import _linalg +from .._internal import get_xp + +import cupy as cp + +# These functions are in both the main and linalg namespaces +from ._aliases import matmul, matrix_transpose, tensordot, vecdot # noqa: F401 + +cross = get_xp(cp)(_linalg.cross) +outer = get_xp(cp)(_linalg.outer) +EighResult = _linalg.EighResult +QRResult = _linalg.QRResult +SlogdetResult = _linalg.SlogdetResult +SVDResult = _linalg.SVDResult +eigh = get_xp(cp)(_linalg.eigh) +qr = get_xp(cp)(_linalg.qr) +slogdet = get_xp(cp)(_linalg.slogdet) +svd = get_xp(cp)(_linalg.svd) +cholesky = get_xp(cp)(_linalg.cholesky) +matrix_rank = get_xp(cp)(_linalg.matrix_rank) +pinv = get_xp(cp)(_linalg.pinv) +matrix_norm = get_xp(cp)(_linalg.matrix_norm) +svdvals = get_xp(cp)(_linalg.svdvals) +diagonal = get_xp(cp)(_linalg.diagonal) +trace = get_xp(cp)(_linalg.trace) + +# These functions are completely new here. If the library already has them +# (i.e., numpy 2.0), use the library version instead of our wrapper. +if hasattr(cp.linalg, 'vector_norm'): + vector_norm = cp.linalg.vector_norm +else: + vector_norm = get_xp(cp)(_linalg.vector_norm) + +__all__ = linalg_all + _linalg.__all__ + +# cupy 13 does not have __all__, cupy 14 has it: remove duplicates +__all__ = sorted(list(set(__all__))) + +def __dir__() -> list[str]: + return __all__ diff --git a/.venv/lib/python3.12/site-packages/scipy/_external/array_api_compat/dask/__init__.py b/.venv/lib/python3.12/site-packages/scipy/_external/array_api_compat/dask/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/.venv/lib/python3.12/site-packages/scipy/_external/array_api_compat/dask/array/__init__.py b/.venv/lib/python3.12/site-packages/scipy/_external/array_api_compat/dask/array/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..1905c671b05322d82c590d0d09dbbe90874be51a --- /dev/null +++ b/.venv/lib/python3.12/site-packages/scipy/_external/array_api_compat/dask/array/__init__.py @@ -0,0 +1,26 @@ +from typing import Final + +from ..._internal import clone_module + +__all__ = clone_module("dask.array", globals()) + +# These imports may overwrite names from the import * above. +from . import _aliases +from ._aliases import * # type: ignore[assignment] # noqa: F403 +from ._info import __array_namespace_info__ # noqa: F401 + +__array_api_version__: Final = "2025.12" +del Final + +# See the comment in the numpy __init__.py +__import__(__package__ + '.linalg') +__import__(__package__ + '.fft') + +__all__ = sorted( + set(__all__) + | set(_aliases.__all__) + | {"__array_api_version__", "__array_namespace_info__", "linalg", "fft"} +) + +def __dir__() -> list[str]: + return __all__ diff --git a/.venv/lib/python3.12/site-packages/scipy/_external/array_api_compat/dask/array/_aliases.py b/.venv/lib/python3.12/site-packages/scipy/_external/array_api_compat/dask/array/_aliases.py new file mode 100644 index 0000000000000000000000000000000000000000..54d323b2a5b6fd933ce8db39e584dff4877a2daa --- /dev/null +++ b/.venv/lib/python3.12/site-packages/scipy/_external/array_api_compat/dask/array/_aliases.py @@ -0,0 +1,369 @@ +# pyright: reportPrivateUsage=false +# pyright: reportUnknownArgumentType=false +# pyright: reportUnknownMemberType=false +# pyright: reportUnknownVariableType=false + +from __future__ import annotations + +from builtins import bool as py_bool +from collections.abc import Callable +from typing import TYPE_CHECKING, Any + +if TYPE_CHECKING: + from typing_extensions import TypeIs + +import dask.array as da +import numpy as np +from numpy import bool_ as bool +from numpy import ( + can_cast, + complex64, + complex128, + float32, + float64, + int8, + int16, + int32, + int64, + result_type, + uint8, + uint16, + uint32, + uint64, +) + +from ..._internal import get_xp +from ...common import _aliases, _helpers, array_namespace +from ...common._typing import ( + Array, + Device, + DType, + NestedSequence, + SupportsBufferProtocol, +) + +isdtype = get_xp(np)(_aliases.isdtype) +unstack = get_xp(da)(_aliases.unstack) + + +# da.astype doesn't respect copy=True +def astype( + x: Array, + dtype: DType, + /, + *, + copy: py_bool = True, + device: Device | None = None, +) -> Array: + """ + Array API compatibility wrapper for astype(). + + See the corresponding documentation in the array library and/or the array API + specification for more details. + """ + # TODO: respect device keyword? + _helpers._check_device(da, device) + + if not copy and dtype == x.dtype: + return x + x = x.astype(dtype) + return x.copy() if copy else x + + +# Common aliases + + +# This arange func is modified from the common one to +# not pass stop/step as keyword arguments, which will cause +# an error with dask +def arange( + start: float, + /, + stop: float | None = None, + step: float = 1, + *, + dtype: DType | None = None, + device: Device | None = None, + **kwargs: object, +) -> Array: + """ + Array API compatibility wrapper for arange(). + + See the corresponding documentation in the array library and/or the array API + specification for more details. + """ + # TODO: respect device keyword? + _helpers._check_device(da, device) + + args: list[Any] = [start] + if stop is not None: + args.append(stop) + else: + # stop is None, so start is actually stop + # prepend the default value for start which is 0 + args.insert(0, 0) + args.append(step) + + return da.arange(*args, dtype=dtype, **kwargs) + + +eye = get_xp(da)(_aliases.eye) +linspace = get_xp(da)(_aliases.linspace) +UniqueAllResult = get_xp(da)(_aliases.UniqueAllResult) +UniqueCountsResult = get_xp(da)(_aliases.UniqueCountsResult) +UniqueInverseResult = get_xp(da)(_aliases.UniqueInverseResult) +unique_all = get_xp(da)(_aliases.unique_all) +unique_counts = get_xp(da)(_aliases.unique_counts) +unique_inverse = get_xp(da)(_aliases.unique_inverse) +unique_values = get_xp(da)(_aliases.unique_values) +permute_dims = get_xp(da)(_aliases.permute_dims) +std = get_xp(da)(_aliases.std) +var = get_xp(da)(_aliases.var) +cumulative_sum = get_xp(da)(_aliases.cumulative_sum) +cumulative_prod = get_xp(da)(_aliases.cumulative_prod) +empty = get_xp(da)(_aliases.empty) +empty_like = get_xp(da)(_aliases.empty_like) +full = get_xp(da)(_aliases.full) +full_like = get_xp(da)(_aliases.full_like) +ones = get_xp(da)(_aliases.ones) +ones_like = get_xp(da)(_aliases.ones_like) +zeros = get_xp(da)(_aliases.zeros) +zeros_like = get_xp(da)(_aliases.zeros_like) +reshape = get_xp(da)(_aliases.reshape) +matrix_transpose = get_xp(da)(_aliases.matrix_transpose) +vecdot = get_xp(da)(_aliases.vecdot) +nonzero = get_xp(da)(_aliases.nonzero) +matmul = get_xp(np)(_aliases.matmul) +tensordot = get_xp(np)(_aliases.tensordot) +sign = get_xp(np)(_aliases.sign) +finfo = get_xp(np)(_aliases.finfo) +iinfo = get_xp(np)(_aliases.iinfo) + + +# asarray also adds the copy keyword, which is not present in numpy 1.0. +def asarray( + obj: Array | complex | NestedSequence[complex] | SupportsBufferProtocol, + /, + *, + dtype: DType | None = None, + device: Device | None = None, + copy: py_bool | None = None, + **kwargs: object, +) -> Array: + """ + Array API compatibility wrapper for asarray(). + + See the corresponding documentation in the array library and/or the array API + specification for more details. + """ + # TODO: respect device keyword? + _helpers._check_device(da, device) + + if isinstance(obj, da.Array): + if dtype is not None and dtype != obj.dtype: + if copy is False: + raise ValueError("Unable to avoid copy when changing dtype") + obj = obj.astype(dtype) + return obj.copy() if copy else obj # pyright: ignore[reportAttributeAccessIssue] + + if copy is False: + raise ValueError( + "Unable to avoid copy when converting a non-dask object to dask" + ) + + # copy=None to be uniform across dask < 2024.12 and >= 2024.12 + # see https://github.com/dask/dask/pull/11524/ + obj = np.array(obj, dtype=dtype, copy=True) + return da.from_array(obj) + + +# Element wise aliases +from dask.array import arccos as acos +from dask.array import arccosh as acosh +from dask.array import arcsin as asin +from dask.array import arcsinh as asinh +from dask.array import arctan as atan +from dask.array import arctan2 as atan2 +from dask.array import arctanh as atanh + +# Other +from dask.array import concatenate as concat +from dask.array import invert as bitwise_invert +from dask.array import left_shift as bitwise_left_shift +from dask.array import power as pow +from dask.array import right_shift as bitwise_right_shift + + +# dask.array.clip does not work unless all three arguments are provided. +# Furthermore, the masking workaround in common._aliases.clip cannot work with +# dask (meaning uint64 promoting to float64 is going to just be unfixed for +# now). +def clip( + x: Array, + /, + min: float | Array | None = None, + max: float | Array | None = None, +) -> Array: + """ + Array API compatibility wrapper for clip(). + + See the corresponding documentation in the array library and/or the array API + specification for more details. + """ + + def _isscalar(a: float | Array | None, /) -> TypeIs[float | None]: + return a is None or isinstance(a, (int, float)) + + min_shape = () if _isscalar(min) else min.shape + max_shape = () if _isscalar(max) else max.shape + + # TODO: This won't handle dask unknown shapes + result_shape = np.broadcast_shapes(x.shape, min_shape, max_shape) + + if min is not None: + min = da.broadcast_to(da.asarray(min), result_shape) + if max is not None: + max = da.broadcast_to(da.asarray(max), result_shape) + + if min is None and max is None: + return da.positive(x) + + if min is None: + return astype(da.minimum(x, max), x.dtype) + if max is None: + return astype(da.maximum(x, min), x.dtype) + + return astype(da.minimum(da.maximum(x, min), max), x.dtype) + + +def _ensure_single_chunk(x: Array, axis: int) -> tuple[Array, Callable[[Array], Array]]: + """ + Make sure that Array is not broken into multiple chunks along axis. + + Returns + ------- + x : Array + The input Array with a single chunk along axis. + restore : Callable[Array, Array] + function to apply to the output to rechunk it back into reasonable chunks + """ + if axis < 0: + axis += x.ndim + if x.numblocks[axis] < 2: + return x, lambda x: x + + # Break chunks on other axes in an attempt to keep chunk size low + x = x.rechunk({i: -1 if i == axis else "auto" for i in range(x.ndim)}) + + # Rather than reconstructing the original chunks, which can be a + # very expensive affair, just break down oversized chunks without + # incurring in any transfers over the network. + # This has the downside of a risk of overchunking if the array is + # then used in operations against other arrays that match the + # original chunking pattern. + return x, lambda x: x.rechunk() + + +def sort( + x: Array, + /, + *, + axis: int = -1, + descending: py_bool = False, + stable: py_bool = True, +) -> Array: + """ + Array API compatibility layer around the lack of sort() in Dask. + + Warnings + -------- + This function temporarily rechunks the array along `axis` to a single chunk. + This can be extremely inefficient and can lead to out-of-memory errors. + + See the corresponding documentation in the array library and/or the array API + specification for more details. + """ + x, restore = _ensure_single_chunk(x, axis) + + meta_xp = array_namespace(x._meta) + x = da.map_blocks( + meta_xp.sort, + x, + axis=axis, + meta=x._meta, + dtype=x.dtype, + descending=descending, + stable=stable, + ) + + return restore(x) + + +def argsort( + x: Array, + /, + *, + axis: int = -1, + descending: py_bool = False, + stable: py_bool = True, +) -> Array: + """ + Array API compatibility layer around the lack of argsort() in Dask. + + See the corresponding documentation in the array library and/or the array API + specification for more details. + + Warnings + -------- + This function temporarily rechunks the array along `axis` into a single chunk. + This can be extremely inefficient and can lead to out-of-memory errors. + """ + x, restore = _ensure_single_chunk(x, axis) + + meta_xp = array_namespace(x._meta) + dtype = meta_xp.argsort(x._meta).dtype + meta = meta_xp.astype(x._meta, dtype) + x = da.map_blocks( + meta_xp.argsort, + x, + axis=axis, + meta=meta, + dtype=dtype, + descending=descending, + stable=stable, + ) + + return restore(x) + + +# dask.array.count_nonzero does not have keepdims +def count_nonzero( + x: Array, + axis: int | None = None, + keepdims: py_bool = False, +) -> Array: + result = da.count_nonzero(x, axis) + if keepdims: + if axis is None: + return da.reshape(result, [1] * x.ndim) + return da.expand_dims(result, axis) + return result + + +__all__ = [ + "count_nonzero", + "bool", + "int8", "int16", "int32", "int64", + "uint8", "uint16", "uint32", "uint64", + "float32", "float64", + "complex64", "complex128", + "asarray", "astype", "can_cast", "result_type", + "pow", + "concat", + "acos", "acosh", "asin", "asinh", "atan", "atan2", "atanh", + "bitwise_left_shift", "bitwise_right_shift", "bitwise_invert", +] # fmt: skip +__all__ += _aliases.__all__ + +def __dir__() -> list[str]: + return __all__ diff --git a/.venv/lib/python3.12/site-packages/scipy/_external/array_api_compat/dask/array/_info.py b/.venv/lib/python3.12/site-packages/scipy/_external/array_api_compat/dask/array/_info.py new file mode 100644 index 0000000000000000000000000000000000000000..3a7285d594a25d3f4d270a12e2d8696e7ed3206e --- /dev/null +++ b/.venv/lib/python3.12/site-packages/scipy/_external/array_api_compat/dask/array/_info.py @@ -0,0 +1,407 @@ +""" +Array API Inspection namespace + +This is the namespace for inspection functions as defined by the array API +standard. See +https://data-apis.org/array-api/latest/API_specification/inspection.html for +more details. + +""" + +# pyright: reportPrivateUsage=false + +from __future__ import annotations + +from typing import Literal, TypeAlias, overload + +import dask.array as da +from numpy import bool_ as bool +from numpy import ( + complex64, + complex128, + dtype, + float32, + float64, + int8, + int16, + int32, + int64, + intp, + uint8, + uint16, + uint32, + uint64, +) + +from ...common._helpers import _DASK_DEVICE, _check_device, _dask_device +from ...common._typing import ( + Capabilities, + DefaultDTypes, + DType, + DTypeKind, + DTypesAll, + DTypesAny, + DTypesBool, + DTypesComplex, + DTypesIntegral, + DTypesNumeric, + DTypesReal, + DTypesSigned, + DTypesUnsigned, +) +Device: TypeAlias = Literal["cpu"] | _dask_device + + +class __array_namespace_info__: + """ + Get the array API inspection namespace for Dask. + + The array API inspection namespace defines the following functions: + + - capabilities() + - default_device() + - default_dtypes() + - dtypes() + - devices() + + See + https://data-apis.org/array-api/latest/API_specification/inspection.html + for more details. + + Returns + ------- + info : ModuleType + The array API inspection namespace for Dask. + + Examples + -------- + >>> info = xp.__array_namespace_info__() + >>> info.default_dtypes() + {'real floating': dask.float64, + 'complex floating': dask.complex128, + 'integral': dask.int64, + 'indexing': dask.int64} + + """ + + __module__ = "dask.array" + + def capabilities(self) -> Capabilities: + """ + Return a dictionary of array API library capabilities. + + The resulting dictionary has the following keys: + + - **"boolean indexing"**: boolean indicating whether an array library + supports boolean indexing. + + Dask support boolean indexing as long as both the index + and the indexed arrays have known shapes. + Note however that the output .shape and .size properties + will contain a non-compliant math.nan instead of None. + + - **"data-dependent shapes"**: boolean indicating whether an array + library supports data-dependent output shapes. + + Dask implements unique_values et.al. + Note however that the output .shape and .size properties + will contain a non-compliant math.nan instead of None. + + - **"max dimensions"**: integer indicating the maximum number of + dimensions supported by the array library. + + See + https://data-apis.org/array-api/latest/API_specification/generated/array_api.info.capabilities.html + for more details. + + See Also + -------- + __array_namespace_info__.default_device, + __array_namespace_info__.default_dtypes, + __array_namespace_info__.dtypes, + __array_namespace_info__.devices + + Returns + ------- + capabilities : dict + A dictionary of array API library capabilities. + + Examples + -------- + >>> info = xp.__array_namespace_info__() + >>> info.capabilities() + {'boolean indexing': True, + 'data-dependent shapes': True, + 'max dimensions': 64} + + """ + return { + "boolean indexing": True, + "data-dependent shapes": True, + "max dimensions": 64, + } + + def default_device(self) -> Device: + """ + The default device used for new Dask arrays. + + For Dask, this always returns ``'cpu'``. + + See Also + -------- + __array_namespace_info__.capabilities, + __array_namespace_info__.default_dtypes, + __array_namespace_info__.dtypes, + __array_namespace_info__.devices + + Returns + ------- + device : Device + The default device used for new Dask arrays. + + Examples + -------- + >>> info = xp.__array_namespace_info__() + >>> info.default_device() + 'cpu' + + """ + return "cpu" + + def default_dtypes(self, /, *, device: Device | None = None) -> DefaultDTypes: + """ + The default data types used for new Dask arrays. + + For Dask, this always returns the following dictionary: + + - **"real floating"**: ``numpy.float64`` + - **"complex floating"**: ``numpy.complex128`` + - **"integral"**: ``numpy.intp`` + - **"indexing"**: ``numpy.intp`` + + Parameters + ---------- + device : str, optional + The device to get the default data types for. + + Returns + ------- + dtypes : dict + A dictionary describing the default data types used for new Dask + arrays. + + See Also + -------- + __array_namespace_info__.capabilities, + __array_namespace_info__.default_device, + __array_namespace_info__.dtypes, + __array_namespace_info__.devices + + Examples + -------- + >>> info = xp.__array_namespace_info__() + >>> info.default_dtypes() + {'real floating': dask.float64, + 'complex floating': dask.complex128, + 'integral': dask.int64, + 'indexing': dask.int64} + + """ + _check_device(da, device) + return { + "real floating": dtype(float64), + "complex floating": dtype(complex128), + "integral": dtype(intp), + "indexing": dtype(intp), + } + + @overload + def dtypes( + self, /, *, device: Device | None = None, kind: None = None + ) -> DTypesAll: ... + @overload + def dtypes( + self, /, *, device: Device | None = None, kind: Literal["bool"] + ) -> DTypesBool: ... + @overload + def dtypes( + self, /, *, device: Device | None = None, kind: Literal["signed integer"] + ) -> DTypesSigned: ... + @overload + def dtypes( + self, /, *, device: Device | None = None, kind: Literal["unsigned integer"] + ) -> DTypesUnsigned: ... + @overload + def dtypes( + self, /, *, device: Device | None = None, kind: Literal["integral"] + ) -> DTypesIntegral: ... + @overload + def dtypes( + self, /, *, device: Device | None = None, kind: Literal["real floating"] + ) -> DTypesReal: ... + @overload + def dtypes( + self, /, *, device: Device | None = None, kind: Literal["complex floating"] + ) -> DTypesComplex: ... + @overload + def dtypes( + self, /, *, device: Device | None = None, kind: Literal["numeric"] + ) -> DTypesNumeric: ... + def dtypes( + self, /, *, device: Device | None = None, kind: DTypeKind | None = None + ) -> DTypesAny: + """ + The array API data types supported by Dask. + + Note that this function only returns data types that are defined by + the array API. + + Parameters + ---------- + device : str, optional + The device to get the data types for. + kind : str or tuple of str, optional + The kind of data types to return. If ``None``, all data types are + returned. If a string, only data types of that kind are returned. + If a tuple, a dictionary containing the union of the given kinds + is returned. The following kinds are supported: + + - ``'bool'``: boolean data types (i.e., ``bool``). + - ``'signed integer'``: signed integer data types (i.e., ``int8``, + ``int16``, ``int32``, ``int64``). + - ``'unsigned integer'``: unsigned integer data types (i.e., + ``uint8``, ``uint16``, ``uint32``, ``uint64``). + - ``'integral'``: integer data types. Shorthand for ``('signed + integer', 'unsigned integer')``. + - ``'real floating'``: real-valued floating-point data types + (i.e., ``float32``, ``float64``). + - ``'complex floating'``: complex floating-point data types (i.e., + ``complex64``, ``complex128``). + - ``'numeric'``: numeric data types. Shorthand for ``('integral', + 'real floating', 'complex floating')``. + + Returns + ------- + dtypes : dict + A dictionary mapping the names of data types to the corresponding + Dask data types. + + See Also + -------- + __array_namespace_info__.capabilities, + __array_namespace_info__.default_device, + __array_namespace_info__.default_dtypes, + __array_namespace_info__.devices + + Examples + -------- + >>> info = xp.__array_namespace_info__() + >>> info.dtypes(kind='signed integer') + {'int8': dask.int8, + 'int16': dask.int16, + 'int32': dask.int32, + 'int64': dask.int64} + + """ + _check_device(da, device) + if kind is None: + return { + "bool": dtype(bool), + "int8": dtype(int8), + "int16": dtype(int16), + "int32": dtype(int32), + "int64": dtype(int64), + "uint8": dtype(uint8), + "uint16": dtype(uint16), + "uint32": dtype(uint32), + "uint64": dtype(uint64), + "float32": dtype(float32), + "float64": dtype(float64), + "complex64": dtype(complex64), + "complex128": dtype(complex128), + } + if kind == "bool": + return {"bool": bool} + if kind == "signed integer": + return { + "int8": dtype(int8), + "int16": dtype(int16), + "int32": dtype(int32), + "int64": dtype(int64), + } + if kind == "unsigned integer": + return { + "uint8": dtype(uint8), + "uint16": dtype(uint16), + "uint32": dtype(uint32), + "uint64": dtype(uint64), + } + if kind == "integral": + return { + "int8": dtype(int8), + "int16": dtype(int16), + "int32": dtype(int32), + "int64": dtype(int64), + "uint8": dtype(uint8), + "uint16": dtype(uint16), + "uint32": dtype(uint32), + "uint64": dtype(uint64), + } + if kind == "real floating": + return { + "float32": dtype(float32), + "float64": dtype(float64), + } + if kind == "complex floating": + return { + "complex64": dtype(complex64), + "complex128": dtype(complex128), + } + if kind == "numeric": + return { + "int8": dtype(int8), + "int16": dtype(int16), + "int32": dtype(int32), + "int64": dtype(int64), + "uint8": dtype(uint8), + "uint16": dtype(uint16), + "uint32": dtype(uint32), + "uint64": dtype(uint64), + "float32": dtype(float32), + "float64": dtype(float64), + "complex64": dtype(complex64), + "complex128": dtype(complex128), + } + if isinstance(kind, tuple): + res: dict[str, DType] = {} + for k in kind: + res.update(self.dtypes(kind=k)) + return res + raise ValueError(f"unsupported kind: {kind!r}") + + def devices(self) -> tuple[Device]: + """ + The devices supported by Dask. + + For Dask, this always returns ``['cpu', DASK_DEVICE]``. + + Returns + ------- + devices : list[Device] + The devices supported by Dask. + + See Also + -------- + __array_namespace_info__.capabilities, + __array_namespace_info__.default_device, + __array_namespace_info__.default_dtypes, + __array_namespace_info__.dtypes + + Examples + -------- + >>> info = xp.__array_namespace_info__() + >>> info.devices() + ['cpu', DASK_DEVICE] + + """ + return ("cpu", _DASK_DEVICE) diff --git a/.venv/lib/python3.12/site-packages/scipy/_external/array_api_compat/dask/array/fft.py b/.venv/lib/python3.12/site-packages/scipy/_external/array_api_compat/dask/array/fft.py new file mode 100644 index 0000000000000000000000000000000000000000..44b68e733984f1f2da11cdd3b892e84b7bd5e797 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/scipy/_external/array_api_compat/dask/array/fft.py @@ -0,0 +1,16 @@ +from ..._internal import clone_module + +__all__ = clone_module("dask.array.fft", globals()) + +from ...common import _fft +from ..._internal import get_xp + +import dask.array as da + +fftfreq = get_xp(da)(_fft.fftfreq) +rfftfreq = get_xp(da)(_fft.rfftfreq) + +__all__ += ["fftfreq", "rfftfreq"] + +def __dir__() -> list[str]: + return __all__ diff --git a/.venv/lib/python3.12/site-packages/scipy/_external/array_api_compat/dask/array/linalg.py b/.venv/lib/python3.12/site-packages/scipy/_external/array_api_compat/dask/array/linalg.py new file mode 100644 index 0000000000000000000000000000000000000000..a9be5d5f52c913264bbb52c180dd97f9519acb0a --- /dev/null +++ b/.venv/lib/python3.12/site-packages/scipy/_external/array_api_compat/dask/array/linalg.py @@ -0,0 +1,64 @@ +from __future__ import annotations + +from typing import Literal + +import dask.array as da + +# The `matmul` and `tensordot` functions are in both the main and linalg namespaces +from dask.array import matmul, outer, tensordot + +# Exports +from ..._internal import clone_module, get_xp +from ...common import _linalg +from ...common._typing import Array + +__all__ = clone_module("dask.array.linalg", globals()) + +from ._aliases import matrix_transpose, vecdot + +EighResult = _linalg.EighResult +QRResult = _linalg.QRResult +SlogdetResult = _linalg.SlogdetResult +SVDResult = _linalg.SVDResult +# TODO: use the QR wrapper once dask +# supports the mode keyword on QR +# https://github.com/dask/dask/issues/10388 +#qr = get_xp(da)(_linalg.qr) +def qr( # type: ignore[no-redef] + x: Array, + mode: Literal["reduced", "complete"] = "reduced", + **kwargs: object, +) -> QRResult: + if mode != "reduced": + raise ValueError("dask arrays only support using mode='reduced'") + return QRResult(*da.linalg.qr(x, **kwargs)) +trace = get_xp(da)(_linalg.trace) +cholesky = get_xp(da)(_linalg.cholesky) +matrix_rank = get_xp(da)(_linalg.matrix_rank) +matrix_norm = get_xp(da)(_linalg.matrix_norm) + + +# Wrap the svd functions to not pass full_matrices to dask +# when full_matrices=False (as that is the default behavior for dask), +# and dask doesn't have the full_matrices keyword +def svd(x: Array, full_matrices: bool = True, **kwargs: object) -> SVDResult: # type: ignore[no-redef] + if full_matrices: + raise ValueError("full_matrices=True is not supported by dask.") + return da.linalg.svd(x, coerce_signs=False, **kwargs) + +def svdvals(x: Array) -> Array: + # TODO: can't avoid computing U or V for dask + _, s, _ = svd(x) + return s + +vector_norm = get_xp(da)(_linalg.vector_norm) +diagonal = get_xp(da)(_linalg.diagonal) + +__all__ += ["trace", "outer", "matmul", "tensordot", + "matrix_transpose", "vecdot", "EighResult", + "QRResult", "SlogdetResult", "SVDResult", "qr", + "cholesky", "matrix_rank", "matrix_norm", "svdvals", + "vector_norm", "diagonal"] + +def __dir__() -> list[str]: + return __all__ diff --git a/.venv/lib/python3.12/site-packages/scipy/_external/array_api_compat/numpy/__init__.py b/.venv/lib/python3.12/site-packages/scipy/_external/array_api_compat/numpy/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..81eaafefa9da6a149bf6fbd19cef5909afb01f3b --- /dev/null +++ b/.venv/lib/python3.12/site-packages/scipy/_external/array_api_compat/numpy/__init__.py @@ -0,0 +1,38 @@ +# ruff: noqa: PLC0414 +from typing import Final + +from .._internal import clone_module + +# This needs to be loaded explicitly before cloning +import numpy.typing # noqa: F401 + +__all__ = clone_module("numpy", globals()) + +# These imports may overwrite names from the import * above. +from . import _aliases +from ._aliases import * # type: ignore[assignment,no-redef] # noqa: F403 +from ._info import __array_namespace_info__ # noqa: F401 + +# Don't know why, but we have to do an absolute import to import linalg. If we +# instead do +# +# from . import linalg +# +# It doesn't overwrite np.linalg from above. The import is generated +# dynamically so that the library can be vendored. +__import__(__package__ + ".linalg") + +__import__(__package__ + ".fft") + +from .linalg import matrix_transpose, vecdot # type: ignore[no-redef] # noqa: F401 + +__array_api_version__: Final = "2025.12" + +__all__ = sorted( + set(__all__) + | set(_aliases.__all__) + | {"__array_api_version__", "__array_namespace_info__", "linalg", "fft"} +) + +def __dir__() -> list[str]: + return __all__ diff --git a/.venv/lib/python3.12/site-packages/scipy/_external/array_api_compat/numpy/__pycache__/__init__.cpython-312.pyc b/.venv/lib/python3.12/site-packages/scipy/_external/array_api_compat/numpy/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2bbb53607ea7cb45862d055caf55abd7360a9f05 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/scipy/_external/array_api_compat/numpy/__pycache__/__init__.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/scipy/_external/array_api_compat/numpy/__pycache__/_aliases.cpython-312.pyc b/.venv/lib/python3.12/site-packages/scipy/_external/array_api_compat/numpy/__pycache__/_aliases.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..704c7f71afba2968c463d82d6ee6666295bfd939 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/scipy/_external/array_api_compat/numpy/__pycache__/_aliases.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/scipy/_external/array_api_compat/numpy/__pycache__/_info.cpython-312.pyc b/.venv/lib/python3.12/site-packages/scipy/_external/array_api_compat/numpy/__pycache__/_info.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b678af25eea0458179d3c0f1097f3c51959020b1 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/scipy/_external/array_api_compat/numpy/__pycache__/_info.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/scipy/_external/array_api_compat/numpy/__pycache__/_typing.cpython-312.pyc b/.venv/lib/python3.12/site-packages/scipy/_external/array_api_compat/numpy/__pycache__/_typing.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b7b568018176bd0aa0f5bba1eba870f6ddb65aed Binary files /dev/null and b/.venv/lib/python3.12/site-packages/scipy/_external/array_api_compat/numpy/__pycache__/_typing.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/scipy/_external/array_api_compat/numpy/__pycache__/fft.cpython-312.pyc b/.venv/lib/python3.12/site-packages/scipy/_external/array_api_compat/numpy/__pycache__/fft.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8f0e637059ca9ccc841185d3cb49dbc2f6339b75 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/scipy/_external/array_api_compat/numpy/__pycache__/fft.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/scipy/_external/array_api_compat/numpy/__pycache__/linalg.cpython-312.pyc b/.venv/lib/python3.12/site-packages/scipy/_external/array_api_compat/numpy/__pycache__/linalg.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f6d56c20075eb643739e4e5ada376bd71e18722a Binary files /dev/null and b/.venv/lib/python3.12/site-packages/scipy/_external/array_api_compat/numpy/__pycache__/linalg.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/scipy/_external/array_api_compat/numpy/_aliases.py b/.venv/lib/python3.12/site-packages/scipy/_external/array_api_compat/numpy/_aliases.py new file mode 100644 index 0000000000000000000000000000000000000000..87b3c2f398af09fc8065aa05a1bfccd679e639d4 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/scipy/_external/array_api_compat/numpy/_aliases.py @@ -0,0 +1,191 @@ +# pyright: reportPrivateUsage=false +from __future__ import annotations + +from builtins import bool as py_bool +from typing import Any, cast + +import numpy as np + +from .._internal import get_xp +from ..common import _aliases, _helpers +from ..common._typing import NestedSequence, SupportsBufferProtocol +from ._typing import Array, Device, DType + +bool = np.bool_ + +# Basic renames +acos = np.arccos +acosh = np.arccosh +asin = np.arcsin +asinh = np.arcsinh +atan = np.arctan +atan2 = np.arctan2 +atanh = np.arctanh +bitwise_left_shift = np.left_shift +bitwise_invert = np.invert +bitwise_right_shift = np.right_shift +concat = np.concatenate +pow = np.power + +arange = get_xp(np)(_aliases.arange) +empty = get_xp(np)(_aliases.empty) +empty_like = get_xp(np)(_aliases.empty_like) +eye = get_xp(np)(_aliases.eye) +full = get_xp(np)(_aliases.full) +full_like = get_xp(np)(_aliases.full_like) +linspace = get_xp(np)(_aliases.linspace) +ones = get_xp(np)(_aliases.ones) +ones_like = get_xp(np)(_aliases.ones_like) +zeros = get_xp(np)(_aliases.zeros) +zeros_like = get_xp(np)(_aliases.zeros_like) +UniqueAllResult = get_xp(np)(_aliases.UniqueAllResult) +UniqueCountsResult = get_xp(np)(_aliases.UniqueCountsResult) +UniqueInverseResult = get_xp(np)(_aliases.UniqueInverseResult) +unique_all = get_xp(np)(_aliases.unique_all) +unique_counts = get_xp(np)(_aliases.unique_counts) +unique_inverse = get_xp(np)(_aliases.unique_inverse) +unique_values = get_xp(np)(_aliases.unique_values) +std = get_xp(np)(_aliases.std) +var = get_xp(np)(_aliases.var) +cumulative_sum = get_xp(np)(_aliases.cumulative_sum) +cumulative_prod = get_xp(np)(_aliases.cumulative_prod) +clip = get_xp(np)(_aliases.clip) +permute_dims = get_xp(np)(_aliases.permute_dims) +reshape = get_xp(np)(_aliases.reshape) +argsort = get_xp(np)(_aliases.argsort) +sort = get_xp(np)(_aliases.sort) +nonzero = get_xp(np)(_aliases.nonzero) +matmul = get_xp(np)(_aliases.matmul) +matrix_transpose = get_xp(np)(_aliases.matrix_transpose) +tensordot = get_xp(np)(_aliases.tensordot) +sign = get_xp(np)(_aliases.sign) +finfo = get_xp(np)(_aliases.finfo) +iinfo = get_xp(np)(_aliases.iinfo) + + +# asarray also adds the copy keyword, which is not present in numpy 1.0. +# asarray() is different enough between numpy, cupy, and dask, the logic +# complicated enough that it's easier to define it separately for each module +# rather than trying to combine everything into one function in common/ +def asarray( + obj: Array | complex | NestedSequence[complex] | SupportsBufferProtocol, + /, + *, + dtype: DType | None = None, + device: Device | None = None, + copy: py_bool | None = None, + **kwargs: Any, +) -> Array: + """ + Array API compatibility wrapper for asarray(). + + See the corresponding documentation in the array library and/or the array API + specification for more details. + """ + _helpers._check_device(np, device) + + # None is unsupported in NumPy 1.0, but we can use an internal enum + # False in NumPy 1.0 means None in NumPy 2.0 and in the Array API + if copy is None: + copy = np._CopyMode.IF_NEEDED # type: ignore[assignment,attr-defined] + elif copy is False: + copy = np._CopyMode.NEVER # type: ignore[assignment,attr-defined] + + return np.array(obj, copy=copy, dtype=dtype, **kwargs) + + +def astype( + x: Array, + dtype: DType, + /, + *, + copy: py_bool = True, + device: Device | None = None, +) -> Array: + _helpers._check_device(np, device) + return x.astype(dtype=dtype, copy=copy) + + +# count_nonzero returns a python int for axis=None and keepdims=False +# https://github.com/numpy/numpy/issues/17562 +def count_nonzero( + x: Array, + axis: int | tuple[int, ...] | None = None, + keepdims: py_bool = False, +) -> Array: + # NOTE: this is currently incorrectly typed in numpy, but will be fixed in + # numpy 2.2.5 and 2.3.0: https://github.com/numpy/numpy/pull/28750 + result = cast("Any", np.count_nonzero(x, axis=axis, keepdims=keepdims)) # pyright: ignore[reportArgumentType, reportCallIssue] + if axis is None and not keepdims: + return np.asarray(result) + return result + + +# take_along_axis: axis defaults to -1 but in numpy axis is a required arg +def take_along_axis(x: Array, indices: Array, /, *, axis: int = -1) -> Array: + return np.take_along_axis(x, indices, axis=axis) + + +# ceil, floor, and trunc return integers for integer inputs in NumPy < 2 + +def ceil(x: Array, /) -> Array: + if np.__version__ < '2' and np.issubdtype(x.dtype, np.integer): + return x.copy() + return np.ceil(x) + + +def floor(x: Array, /) -> Array: + if np.__version__ < '2' and np.issubdtype(x.dtype, np.integer): + return x.copy() + return np.floor(x) + + +def trunc(x: Array, /) -> Array: + if np.__version__ < '2' and np.issubdtype(x.dtype, np.integer): + return x.copy() + return np.trunc(x) + + +# These functions are completely new here. If the library already has them +# (i.e., numpy 2.0), use the library version instead of our wrapper. +if hasattr(np, "vecdot"): + vecdot = np.vecdot +else: + vecdot = get_xp(np)(_aliases.vecdot) # type: ignore[assignment] + +if hasattr(np, "isdtype"): + isdtype = np.isdtype +else: + isdtype = get_xp(np)(_aliases.isdtype) + +if hasattr(np, "unstack"): + unstack = np.unstack +else: + unstack = get_xp(np)(_aliases.unstack) + +__all__ = _aliases.__all__ + [ + "asarray", + "astype", + "acos", + "acosh", + "asin", + "asinh", + "atan", + "atan2", + "atanh", + "ceil", + "floor", + "trunc", + "bitwise_left_shift", + "bitwise_invert", + "bitwise_right_shift", + "bool", + "concat", + "count_nonzero", + "pow", + "take_along_axis" +] + + +def __dir__() -> list[str]: + return __all__ diff --git a/.venv/lib/python3.12/site-packages/scipy/_external/array_api_compat/numpy/_info.py b/.venv/lib/python3.12/site-packages/scipy/_external/array_api_compat/numpy/_info.py new file mode 100644 index 0000000000000000000000000000000000000000..9ba004da7cfe5e96435f543f89c2202b8bd1707d --- /dev/null +++ b/.venv/lib/python3.12/site-packages/scipy/_external/array_api_compat/numpy/_info.py @@ -0,0 +1,367 @@ +""" +Array API Inspection namespace + +This is the namespace for inspection functions as defined by the array API +standard. See +https://data-apis.org/array-api/latest/API_specification/inspection.html for +more details. + +""" +from __future__ import annotations + +from numpy import bool_ as bool +from numpy import ( + complex64, + complex128, + dtype, + float32, + float64, + int8, + int16, + int32, + int64, + intp, + uint8, + uint16, + uint32, + uint64, +) + +from ..common._typing import DefaultDTypes +from ._typing import Device, DType + + +class __array_namespace_info__: + """ + Get the array API inspection namespace for NumPy. + + The array API inspection namespace defines the following functions: + + - capabilities() + - default_device() + - default_dtypes() + - dtypes() + - devices() + + See + https://data-apis.org/array-api/latest/API_specification/inspection.html + for more details. + + Returns + ------- + info : ModuleType + The array API inspection namespace for NumPy. + + Examples + -------- + >>> info = np.__array_namespace_info__() + >>> info.default_dtypes() + {'real floating': numpy.float64, + 'complex floating': numpy.complex128, + 'integral': numpy.int64, + 'indexing': numpy.int64} + + """ + + __module__ = 'numpy' + + def capabilities(self): + """ + Return a dictionary of array API library capabilities. + + The resulting dictionary has the following keys: + + - **"boolean indexing"**: boolean indicating whether an array library + supports boolean indexing. Always ``True`` for NumPy. + + - **"data-dependent shapes"**: boolean indicating whether an array + library supports data-dependent output shapes. Always ``True`` for + NumPy. + + See + https://data-apis.org/array-api/latest/API_specification/generated/array_api.info.capabilities.html + for more details. + + See Also + -------- + __array_namespace_info__.default_device, + __array_namespace_info__.default_dtypes, + __array_namespace_info__.dtypes, + __array_namespace_info__.devices + + Returns + ------- + capabilities : dict + A dictionary of array API library capabilities. + + Examples + -------- + >>> info = np.__array_namespace_info__() + >>> info.capabilities() + {'boolean indexing': True, + 'data-dependent shapes': True, + 'max dimensions': 64} + + """ + return { + "boolean indexing": True, + "data-dependent shapes": True, + "max dimensions": 64, + } + + def default_device(self): + """ + The default device used for new NumPy arrays. + + For NumPy, this always returns ``'cpu'``. + + See Also + -------- + __array_namespace_info__.capabilities, + __array_namespace_info__.default_dtypes, + __array_namespace_info__.dtypes, + __array_namespace_info__.devices + + Returns + ------- + device : Device + The default device used for new NumPy arrays. + + Examples + -------- + >>> info = np.__array_namespace_info__() + >>> info.default_device() + 'cpu' + + """ + return "cpu" + + def default_dtypes( + self, + *, + device: Device | None = None, + ) -> DefaultDTypes: + """ + The default data types used for new NumPy arrays. + + For NumPy, this always returns the following dictionary: + + - **"real floating"**: ``numpy.float64`` + - **"complex floating"**: ``numpy.complex128`` + - **"integral"**: ``numpy.intp`` + - **"indexing"**: ``numpy.intp`` + + Parameters + ---------- + device : str, optional + The device to get the default data types for. For NumPy, only + ``'cpu'`` is allowed. + + Returns + ------- + dtypes : dict + A dictionary describing the default data types used for new NumPy + arrays. + + See Also + -------- + __array_namespace_info__.capabilities, + __array_namespace_info__.default_device, + __array_namespace_info__.dtypes, + __array_namespace_info__.devices + + Examples + -------- + >>> info = np.__array_namespace_info__() + >>> info.default_dtypes() + {'real floating': numpy.float64, + 'complex floating': numpy.complex128, + 'integral': numpy.int64, + 'indexing': numpy.int64} + + """ + if device not in ["cpu", None]: + raise ValueError( + 'Device not understood. Only "cpu" is allowed, but received:' + f' {device}' + ) + return { + "real floating": dtype(float64), + "complex floating": dtype(complex128), + "integral": dtype(intp), + "indexing": dtype(intp), + } + + def dtypes( + self, + *, + device: Device | None = None, + kind: str | tuple[str, ...] | None = None, + ) -> dict[str, DType]: + """ + The array API data types supported by NumPy. + + Note that this function only returns data types that are defined by + the array API. + + Parameters + ---------- + device : str, optional + The device to get the data types for. For NumPy, only ``'cpu'`` is + allowed. + kind : str or tuple of str, optional + The kind of data types to return. If ``None``, all data types are + returned. If a string, only data types of that kind are returned. + If a tuple, a dictionary containing the union of the given kinds + is returned. The following kinds are supported: + + - ``'bool'``: boolean data types (i.e., ``bool``). + - ``'signed integer'``: signed integer data types (i.e., ``int8``, + ``int16``, ``int32``, ``int64``). + - ``'unsigned integer'``: unsigned integer data types (i.e., + ``uint8``, ``uint16``, ``uint32``, ``uint64``). + - ``'integral'``: integer data types. Shorthand for ``('signed + integer', 'unsigned integer')``. + - ``'real floating'``: real-valued floating-point data types + (i.e., ``float32``, ``float64``). + - ``'complex floating'``: complex floating-point data types (i.e., + ``complex64``, ``complex128``). + - ``'numeric'``: numeric data types. Shorthand for ``('integral', + 'real floating', 'complex floating')``. + + Returns + ------- + dtypes : dict + A dictionary mapping the names of data types to the corresponding + NumPy data types. + + See Also + -------- + __array_namespace_info__.capabilities, + __array_namespace_info__.default_device, + __array_namespace_info__.default_dtypes, + __array_namespace_info__.devices + + Examples + -------- + >>> info = np.__array_namespace_info__() + >>> info.dtypes(kind='signed integer') + {'int8': numpy.int8, + 'int16': numpy.int16, + 'int32': numpy.int32, + 'int64': numpy.int64} + + """ + if device not in ["cpu", None]: + raise ValueError( + 'Device not understood. Only "cpu" is allowed, but received:' + f' {device}' + ) + if kind is None: + return { + "bool": dtype(bool), + "int8": dtype(int8), + "int16": dtype(int16), + "int32": dtype(int32), + "int64": dtype(int64), + "uint8": dtype(uint8), + "uint16": dtype(uint16), + "uint32": dtype(uint32), + "uint64": dtype(uint64), + "float32": dtype(float32), + "float64": dtype(float64), + "complex64": dtype(complex64), + "complex128": dtype(complex128), + } + if kind == "bool": + return {"bool": dtype(bool)} + if kind == "signed integer": + return { + "int8": dtype(int8), + "int16": dtype(int16), + "int32": dtype(int32), + "int64": dtype(int64), + } + if kind == "unsigned integer": + return { + "uint8": dtype(uint8), + "uint16": dtype(uint16), + "uint32": dtype(uint32), + "uint64": dtype(uint64), + } + if kind == "integral": + return { + "int8": dtype(int8), + "int16": dtype(int16), + "int32": dtype(int32), + "int64": dtype(int64), + "uint8": dtype(uint8), + "uint16": dtype(uint16), + "uint32": dtype(uint32), + "uint64": dtype(uint64), + } + if kind == "real floating": + return { + "float32": dtype(float32), + "float64": dtype(float64), + } + if kind == "complex floating": + return { + "complex64": dtype(complex64), + "complex128": dtype(complex128), + } + if kind == "numeric": + return { + "int8": dtype(int8), + "int16": dtype(int16), + "int32": dtype(int32), + "int64": dtype(int64), + "uint8": dtype(uint8), + "uint16": dtype(uint16), + "uint32": dtype(uint32), + "uint64": dtype(uint64), + "float32": dtype(float32), + "float64": dtype(float64), + "complex64": dtype(complex64), + "complex128": dtype(complex128), + } + if isinstance(kind, tuple): + res: dict[str, DType] = {} + for k in kind: + res.update(self.dtypes(kind=k)) + return res + raise ValueError(f"unsupported kind: {kind!r}") + + def devices(self) -> tuple[Device]: + """ + The devices supported by NumPy. + + For NumPy, this always returns ``['cpu']``. + + Returns + ------- + devices : list[Device] + The devices supported by NumPy. + + See Also + -------- + __array_namespace_info__.capabilities, + __array_namespace_info__.default_device, + __array_namespace_info__.default_dtypes, + __array_namespace_info__.dtypes + + Examples + -------- + >>> info = np.__array_namespace_info__() + >>> info.devices() + ['cpu'] + + """ + return ("cpu",) + + +__all__ = ["__array_namespace_info__"] + + +def __dir__() -> list[str]: + return __all__ diff --git a/.venv/lib/python3.12/site-packages/scipy/_external/array_api_compat/numpy/_typing.py b/.venv/lib/python3.12/site-packages/scipy/_external/array_api_compat/numpy/_typing.py new file mode 100644 index 0000000000000000000000000000000000000000..b5fa188c52b69c16a1fa088026720fee9390e640 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/scipy/_external/array_api_compat/numpy/_typing.py @@ -0,0 +1,29 @@ +from __future__ import annotations + +from typing import TYPE_CHECKING, Any, Literal, TypeAlias + +import numpy as np + +Device: TypeAlias = Literal["cpu"] + +if TYPE_CHECKING: + + # NumPy 1.x on Python 3.10 fails to parse np.dtype[] + DType: TypeAlias = np.dtype[ + np.bool_ + | np.integer[Any] + | np.float32 + | np.float64 + | np.complex64 + | np.complex128 + ] + Array: TypeAlias = np.ndarray[Any, DType] +else: + DType: TypeAlias = np.dtype + Array: TypeAlias = np.ndarray + +__all__ = ["Array", "DType", "Device"] + + +def __dir__() -> list[str]: + return __all__ diff --git a/.venv/lib/python3.12/site-packages/scipy/_external/array_api_compat/numpy/fft.py b/.venv/lib/python3.12/site-packages/scipy/_external/array_api_compat/numpy/fft.py new file mode 100644 index 0000000000000000000000000000000000000000..a492feb8cf69085a3a6617fbee13a8ac236701fa --- /dev/null +++ b/.venv/lib/python3.12/site-packages/scipy/_external/array_api_compat/numpy/fft.py @@ -0,0 +1,30 @@ +import numpy as np + +from .._internal import clone_module + +__all__ = clone_module("numpy.fft", globals()) + +from .._internal import get_xp +from ..common import _fft + +fft = get_xp(np)(_fft.fft) +ifft = get_xp(np)(_fft.ifft) +fftn = get_xp(np)(_fft.fftn) +ifftn = get_xp(np)(_fft.ifftn) +rfft = get_xp(np)(_fft.rfft) +irfft = get_xp(np)(_fft.irfft) +rfftn = get_xp(np)(_fft.rfftn) +irfftn = get_xp(np)(_fft.irfftn) +hfft = get_xp(np)(_fft.hfft) +ihfft = get_xp(np)(_fft.ihfft) +fftfreq = get_xp(np)(_fft.fftfreq) +rfftfreq = get_xp(np)(_fft.rfftfreq) +fftshift = get_xp(np)(_fft.fftshift) +ifftshift = get_xp(np)(_fft.ifftshift) + + +__all__ = sorted(set(__all__) | set(_fft.__all__)) + +def __dir__() -> list[str]: + return __all__ + diff --git a/.venv/lib/python3.12/site-packages/scipy/_external/array_api_compat/numpy/linalg.py b/.venv/lib/python3.12/site-packages/scipy/_external/array_api_compat/numpy/linalg.py new file mode 100644 index 0000000000000000000000000000000000000000..474efe50c8e77885101013ac79f728bd1bfcfcc2 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/scipy/_external/array_api_compat/numpy/linalg.py @@ -0,0 +1,208 @@ +# pyright: reportAttributeAccessIssue=false +# pyright: reportUnknownArgumentType=false +# pyright: reportUnknownMemberType=false +# pyright: reportUnknownVariableType=false + +from __future__ import annotations + +import numpy as np + +from .._internal import clone_module, get_xp +from ..common import _linalg + +__all__ = clone_module("numpy.linalg", globals()) + +# These functions are in both the main and linalg namespaces +from ._aliases import matmul, matrix_transpose, tensordot, vecdot # noqa: F401 +from ._typing import Array + +cross = get_xp(np)(_linalg.cross) +outer = get_xp(np)(_linalg.outer) +EighResult = _linalg.EighResult +EigResult = _linalg.EigResult +QRResult = _linalg.QRResult +SlogdetResult = _linalg.SlogdetResult +SVDResult = _linalg.SVDResult +eigh = get_xp(np)(_linalg.eigh) +qr = get_xp(np)(_linalg.qr) +slogdet = get_xp(np)(_linalg.slogdet) +svd = get_xp(np)(_linalg.svd) +cholesky = get_xp(np)(_linalg.cholesky) +matrix_rank = get_xp(np)(_linalg.matrix_rank) +pinv = get_xp(np)(_linalg.pinv) +matrix_norm = get_xp(np)(_linalg.matrix_norm) +svdvals = get_xp(np)(_linalg.svdvals) +diagonal = get_xp(np)(_linalg.diagonal) +trace = get_xp(np)(_linalg.trace) + +# Note: unlike np.linalg.solve, the array API solve() only accepts x2 as a +# vector when it is exactly 1-dimensional. All other cases treat x2 as a stack +# of matrices. The np.linalg.solve behavior of allowing stacks of both +# matrices and vectors is ambiguous c.f. +# https://github.com/numpy/numpy/issues/15349 and +# https://github.com/data-apis/array-api/issues/285. + +# To workaround this, the below is the code from np.linalg.solve except +# only calling solve1 in the exactly 1D case. + + +# This code is here instead of in common because it is numpy specific. Also +# note that CuPy's solve() does not currently support broadcasting (see +# https://github.com/cupy/cupy/blob/main/cupy/cublas.py#L43). +def solve(x1: Array, x2: Array, /) -> Array: + try: + from numpy.linalg._linalg import ( # type: ignore[attr-defined] + _assert_stacked_2d, + _assert_stacked_square, + _commonType, + _makearray, + _raise_linalgerror_singular, + isComplexType, + ) + except ImportError: + from numpy.linalg.linalg import ( # type: ignore[attr-defined] + _assert_stacked_2d, + _assert_stacked_square, + _commonType, + _makearray, + _raise_linalgerror_singular, + isComplexType, + ) + from numpy.linalg import _umath_linalg + + x1, _ = _makearray(x1) + _assert_stacked_2d(x1) + _assert_stacked_square(x1) + x2, wrap = _makearray(x2) + t, result_t = _commonType(x1, x2) + + # This part is different from np.linalg.solve + gufunc: np.ufunc + if x2.ndim == 1: + gufunc = _umath_linalg.solve1 + else: + gufunc = _umath_linalg.solve + + # This does nothing currently but is left in because it will be relevant + # when complex dtype support is added to the spec in 2022. + signature = "DD->D" if isComplexType(t) else "dd->d" + with np.errstate( + call=_raise_linalgerror_singular, + invalid="call", + over="ignore", + divide="ignore", + under="ignore", + ): + r: Array = gufunc(x1, x2, signature=signature) + + return wrap(r.astype(result_t, copy=False)) + + +# Unlike numpy.linalg.eig, Array API version always returns complex results + +def eig(x: Array, /) -> tuple[Array, Array]: + try: + from numpy.linalg._linalg import ( # type: ignore[attr-defined] + _assert_stacked_square, + _assert_finite, + _commonType, + _makearray, + _raise_linalgerror_eigenvalues_nonconvergence, + isComplexType, + _complexType, + ) + except ImportError: + from numpy.linalg.linalg import ( # type: ignore[attr-defined] + _assert_stacked_square, + _assert_finite, + _commonType, + _makearray, + _raise_linalgerror_eigenvalues_nonconvergence, + isComplexType, + _complexType, + ) + from numpy.linalg import _umath_linalg + + x, wrap = _makearray(x) + _assert_stacked_square(x) + _assert_finite(x) + t, result_t = _commonType(x) + + signature = 'D->DD' if isComplexType(t) else 'd->DD' + with np.errstate(call=_raise_linalgerror_eigenvalues_nonconvergence, + invalid='call', over='ignore', divide='ignore', + under='ignore'): + w, vt = _umath_linalg.eig(x, signature=signature) + + result_t = _complexType(result_t) + vt = vt.astype(result_t, copy=False) + return EigResult(w.astype(result_t, copy=False), wrap(vt)) + + +def eigvals(x: Array, /) -> Array: + try: + from numpy.linalg._linalg import ( # type: ignore[attr-defined] + _assert_stacked_square, + _assert_finite, + _commonType, + _makearray, + _raise_linalgerror_eigenvalues_nonconvergence, + isComplexType, + _complexType, + ) + except ImportError: + from numpy.linalg.linalg import ( # type: ignore[attr-defined] + _assert_stacked_square, + _assert_finite, + _commonType, + _makearray, + _raise_linalgerror_eigenvalues_nonconvergence, + isComplexType, + _complexType, + ) + from numpy.linalg import _umath_linalg + + x, wrap = _makearray(x) + _assert_stacked_square(x) + _assert_finite(x) + t, result_t = _commonType(x) + + signature = 'D->D' if isComplexType(t) else 'd->D' + with np.errstate(call=_raise_linalgerror_eigenvalues_nonconvergence, + invalid='call', over='ignore', divide='ignore', + under='ignore'): + w = _umath_linalg.eigvals(x, signature=signature) + + result_t = _complexType(result_t) + return w.astype(result_t, copy=False) + + +# These functions are completely new here. If the library already has them +# (i.e., numpy 2.0), use the library version instead of our wrapper. +if hasattr(np.linalg, "vector_norm"): + vector_norm = np.linalg.vector_norm +else: + vector_norm = get_xp(np)(_linalg.vector_norm) + + +_all = [ + "LinAlgError", + "cond", + "det", + "eig", + "eigvals", + "eigvalsh", + "inv", + "lstsq", + "matrix_power", + "multi_dot", + "norm", + "solve", + "tensorinv", + "tensorsolve", + "vector_norm", +] +__all__ = sorted(set(__all__) | set(_linalg.__all__) | set(_all)) + +def __dir__() -> list[str]: + return __all__ diff --git a/.venv/lib/python3.12/site-packages/scipy/_external/array_api_compat/torch/__init__.py b/.venv/lib/python3.12/site-packages/scipy/_external/array_api_compat/torch/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..8263faa693236d3c686ae12910661d79e1987c43 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/scipy/_external/array_api_compat/torch/__init__.py @@ -0,0 +1,25 @@ +from typing import Final + +from .._internal import clone_module + +__all__ = clone_module("torch", globals()) + +# These imports may overwrite names from the import * above. +from . import _aliases +from ._aliases import * # noqa: F403 +from ._info import __array_namespace_info__ # noqa: F401 + +# See the comment in the numpy __init__.py +__import__(__package__ + '.linalg') +__import__(__package__ + '.fft') + +__array_api_version__: Final = '2025.12' + +__all__ = sorted( + set(__all__) + | set(_aliases.__all__) + | {"__array_api_version__", "__array_namespace_info__", "linalg", "fft"} +) + +def __dir__() -> list[str]: + return __all__ diff --git a/.venv/lib/python3.12/site-packages/scipy/_external/array_api_compat/torch/_aliases.py b/.venv/lib/python3.12/site-packages/scipy/_external/array_api_compat/torch/_aliases.py new file mode 100644 index 0000000000000000000000000000000000000000..69bd37637c569d639182e041816c757595b154cb --- /dev/null +++ b/.venv/lib/python3.12/site-packages/scipy/_external/array_api_compat/torch/_aliases.py @@ -0,0 +1,938 @@ +from __future__ import annotations + +from collections.abc import Sequence +from functools import reduce as _reduce, wraps as _wraps +from builtins import all as _builtin_all, any as _builtin_any +from typing import Any, Literal +import math + +import torch + +from .._internal import get_xp +from ..common import _aliases +from ..common._typing import NestedSequence, SupportsBufferProtocol +from ._typing import Array, Device, DType + +_int_dtypes = { + torch.uint8, + torch.int8, + torch.int16, + torch.int32, + torch.int64, +} +try: + # torch >=2.3 + _int_dtypes |= {torch.uint16, torch.uint32, torch.uint64} +except AttributeError: + pass + + +_array_api_dtypes = { + torch.bool, + *_int_dtypes, + torch.float32, + torch.float64, + torch.complex64, + torch.complex128, +} + +_promotion_table = { + # ints + (torch.int8, torch.int16): torch.int16, + (torch.int8, torch.int32): torch.int32, + (torch.int8, torch.int64): torch.int64, + (torch.int16, torch.int32): torch.int32, + (torch.int16, torch.int64): torch.int64, + (torch.int32, torch.int64): torch.int64, + # ints and uints (mixed sign) + (torch.uint8, torch.int8): torch.int16, + (torch.uint8, torch.int16): torch.int16, + (torch.uint8, torch.int32): torch.int32, + (torch.uint8, torch.int64): torch.int64, + # floats + (torch.float32, torch.float64): torch.float64, + # complexes + (torch.complex64, torch.complex128): torch.complex128, + # Mixed float and complex + (torch.float32, torch.complex64): torch.complex64, + (torch.float32, torch.complex128): torch.complex128, + (torch.float64, torch.complex64): torch.complex128, + (torch.float64, torch.complex128): torch.complex128, +} + +_promotion_table.update({(b, a): c for (a, b), c in _promotion_table.items()}) +_promotion_table.update({(a, a): a for a in _array_api_dtypes}) + + +def _two_arg(f): + @_wraps(f) + def _f(x1, x2, /, **kwargs): + x1, x2 = _fix_promotion(x1, x2) + return f(x1, x2, **kwargs) + if _f.__doc__ is None: + _f.__doc__ = f"""\ +Array API compatibility wrapper for torch.{f.__name__}. + +See the corresponding PyTorch documentation and/or the array API specification +for more details. + +""" + return _f + +def _fix_promotion(x1, x2, only_scalar=True): + if not isinstance(x1, torch.Tensor) or not isinstance(x2, torch.Tensor): + return x1, x2 + if x1.dtype not in _array_api_dtypes or x2.dtype not in _array_api_dtypes: + return x1, x2 + # If an argument is 0-D pytorch downcasts the other argument + if not only_scalar or x1.shape == (): + dtype = result_type(x1, x2) + x2 = x2.to(dtype) + if not only_scalar or x2.shape == (): + dtype = result_type(x1, x2) + x1 = x1.to(dtype) + return x1, x2 + + +_py_scalars = (bool, int, float, complex) + + +def result_type(*arrays_and_dtypes: Array | DType | complex) -> DType: + num = len(arrays_and_dtypes) + + if num == 0: + raise ValueError("At least one array or dtype must be provided") + + elif num == 1: + x = arrays_and_dtypes[0] + if isinstance(x, torch.dtype): + return x + return x.dtype + + if num == 2: + x, y = arrays_and_dtypes + return _result_type(x, y) + + else: + # sort scalars so that they are treated last + scalars, others = [], [] + for x in arrays_and_dtypes: + if isinstance(x, _py_scalars): + scalars.append(x) + else: + others.append(x) + if not others: + raise ValueError("At least one array or dtype must be provided") + + # combine left-to-right + return _reduce(_result_type, others + scalars) + + +def _result_type(x: Array | DType | complex, y: Array | DType | complex) -> DType: + if not (isinstance(x, _py_scalars) or isinstance(y, _py_scalars)): + xdt = x if isinstance(x, torch.dtype) else x.dtype + ydt = y if isinstance(y, torch.dtype) else y.dtype + + try: + return _promotion_table[xdt, ydt] + except KeyError: + pass + + # This doesn't result_type(dtype, dtype) for non-array API dtypes + # because torch.result_type only accepts tensors. This does however, allow + # cross-kind promotion. + x = torch.tensor([], dtype=x) if isinstance(x, torch.dtype) else x + y = torch.tensor([], dtype=y) if isinstance(y, torch.dtype) else y + return torch.result_type(x, y) + + +def can_cast(from_: DType | Array, to: DType, /) -> bool: + if not isinstance(from_, torch.dtype): + from_ = from_.dtype + return torch.can_cast(from_, to) + +# Basic renames +bitwise_invert = torch.bitwise_not +newaxis = None +# torch.conj sets the conjugation bit, which breaks conversion to other +# libraries. See https://github.com/data-apis/array-api-compat/issues/173 +conj = torch.conj_physical + +# Two-arg elementwise functions +# These require a wrapper to do the correct type promotion on 0-D tensors +add = _two_arg(torch.add) +atan2 = _two_arg(torch.atan2) +bitwise_and = _two_arg(torch.bitwise_and) +bitwise_left_shift = _two_arg(torch.bitwise_left_shift) +bitwise_or = _two_arg(torch.bitwise_or) +bitwise_right_shift = _two_arg(torch.bitwise_right_shift) +bitwise_xor = _two_arg(torch.bitwise_xor) +copysign = _two_arg(torch.copysign) +divide = _two_arg(torch.divide) +# Also a rename. torch.equal does not broadcast +equal = _two_arg(torch.eq) +floor_divide = _two_arg(torch.floor_divide) +greater = _two_arg(torch.greater) +greater_equal = _two_arg(torch.greater_equal) +hypot = _two_arg(torch.hypot) +less = _two_arg(torch.less) +less_equal = _two_arg(torch.less_equal) +logaddexp = _two_arg(torch.logaddexp) +# logical functions are not included here because they only accept bool in the +# spec, so type promotion is irrelevant. +maximum = _two_arg(torch.maximum) +minimum = _two_arg(torch.minimum) +multiply = _two_arg(torch.multiply) +not_equal = _two_arg(torch.not_equal) +pow = _two_arg(torch.pow) +remainder = _two_arg(torch.remainder) +subtract = _two_arg(torch.subtract) + + +def asarray( + obj: Array | complex | NestedSequence[complex] | SupportsBufferProtocol, + /, + *, + dtype: DType | None = None, + device: Device | None = None, + copy: bool | None = None, + **kwargs: Any, +) -> Array: + # torch.asarray does not respect input->output device propagation + # https://github.com/pytorch/pytorch/issues/150199 + if device is None and isinstance(obj, torch.Tensor): + device = obj.device + return torch.asarray(obj, dtype=dtype, device=device, copy=copy, **kwargs) + + +# These wrappers are mostly based on the fact that pytorch uses 'dim' instead +# of 'axis'. + +# torch.min and torch.max return a tuple and don't support multiple axes https://github.com/pytorch/pytorch/issues/58745 +def max(x: Array, /, *, axis: int | tuple[int, ...] | None = None, keepdims: bool = False) -> Array: + # https://github.com/pytorch/pytorch/issues/29137 + if axis == (): + return torch.clone(x) + return torch.amax(x, axis, keepdims=keepdims) + +def min(x: Array, /, *, axis: int | tuple[int, ...] |None = None, keepdims: bool = False) -> Array: + # https://github.com/pytorch/pytorch/issues/29137 + if axis == (): + return torch.clone(x) + return torch.amin(x, axis, keepdims=keepdims) + +unstack = get_xp(torch)(_aliases.unstack) +cumulative_sum = get_xp(torch)(_aliases.cumulative_sum) +cumulative_prod = get_xp(torch)(_aliases.cumulative_prod) +finfo = get_xp(torch)(_aliases.finfo) +iinfo = get_xp(torch)(_aliases.iinfo) + + +# torch.sort also returns a tuple +# https://github.com/pytorch/pytorch/issues/70921 +def sort( + x: Array, + /, + *, + axis: int = -1, + descending: bool = False, + stable: bool = True, + **kwargs: object, +) -> Array: + return torch.sort(x, dim=axis, descending=descending, stable=stable, **kwargs).values + + +# Wrap torch.argsort to set stable=True by default +def argsort( + x: Array, + /, + *, + axis: int = -1, + descending: bool = False, + stable: bool = True, + **kwargs: object, +) -> Array: + return torch.argsort(x, dim=axis, descending=descending, stable=stable, **kwargs) + + +def _normalize_axes(axis, ndim): + axes = [] + if ndim == 0 and axis: + # Better error message in this case + raise IndexError(f"Dimension out of range: {axis[0]}") + lower, upper = -ndim, ndim - 1 + for a in axis: + if a < lower or a > upper: + # Match torch error message (e.g., from sum()) + raise IndexError(f"Dimension out of range (expected to be in range of [{lower}, {upper}], but got {a}") + if a < 0: + a = a + ndim + if a in axes: + # Use IndexError instead of RuntimeError, and "axis" instead of "dim" + raise IndexError(f"Axis {a} appears multiple times in the list of axes") + axes.append(a) + return sorted(axes) + +def _axis_none_keepdims(x, ndim, keepdims): + # Apply keepdims when axis=None + # (https://github.com/pytorch/pytorch/issues/71209) + # Note that this is only valid for the axis=None case. + if keepdims: + for i in range(ndim): + x = torch.unsqueeze(x, 0) + return x + +def _reduce_multiple_axes(f, x, axis, keepdims=False, **kwargs): + # Some reductions don't support multiple axes + # (https://github.com/pytorch/pytorch/issues/56586). + axes = _normalize_axes(axis, x.ndim) + for a in reversed(axes): + x = torch.movedim(x, a, -1) + x = torch.flatten(x, -len(axes)) + + out = f(x, -1, **kwargs) + + if keepdims: + for a in axes: + out = torch.unsqueeze(out, a) + return out + + +def _sum_prod_no_axis(x: Array, dtype: DType | None) -> Array: + """ + Implements `sum(..., axis=())` and `prod(..., axis=())`. + + Works around https://github.com/pytorch/pytorch/issues/29137 + """ + if dtype is not None: + return x.clone() if dtype == x.dtype else x.to(dtype) + + # We can't upcast uint8 according to the spec because there is no + # torch.uint64, so at least upcast to int64 which is what prod does + # when axis=None. + if x.dtype in (torch.uint8, torch.int8, torch.int16, torch.int32): + return x.to(torch.int64) + + return x.clone() + + +def prod(x: Array, + /, + *, + axis: int | tuple[int, ...] | None = None, + dtype: DType | None = None, + keepdims: bool = False, + **kwargs: object) -> Array: + + if axis == (): + return _sum_prod_no_axis(x, dtype) + # torch.prod doesn't support multiple axes + # (https://github.com/pytorch/pytorch/issues/56586). + if isinstance(axis, tuple): + return _reduce_multiple_axes(torch.prod, x, axis, keepdims=keepdims, dtype=dtype, **kwargs) + if axis is None: + # torch doesn't support keepdims with axis=None + # (https://github.com/pytorch/pytorch/issues/71209) + res = torch.prod(x, dtype=dtype, **kwargs) + res = _axis_none_keepdims(res, x.ndim, keepdims) + return res + + return torch.prod(x, axis, dtype=dtype, keepdims=keepdims, **kwargs) + + +def sum(x: Array, + /, + *, + axis: int | tuple[int, ...] | None = None, + dtype: DType | None = None, + keepdims: bool = False, + **kwargs: object) -> Array: + + if axis == (): + return _sum_prod_no_axis(x, dtype) + if axis is None: + # torch doesn't support keepdims with axis=None + # (https://github.com/pytorch/pytorch/issues/71209) + res = torch.sum(x, dtype=dtype, **kwargs) + res = _axis_none_keepdims(res, x.ndim, keepdims) + return res + + return torch.sum(x, axis, dtype=dtype, keepdims=keepdims, **kwargs) + +def any(x: Array, + /, + *, + axis: int | tuple[int, ...] | None = None, + keepdims: bool = False, + **kwargs: object) -> Array: + + if axis == (): + return x.to(torch.bool) + # torch.any doesn't support multiple axes + # (https://github.com/pytorch/pytorch/issues/56586). + if isinstance(axis, tuple): + res = _reduce_multiple_axes(torch.any, x, axis, keepdims=keepdims, **kwargs) + return res.to(torch.bool) + if axis is None: + # torch doesn't support keepdims with axis=None + # (https://github.com/pytorch/pytorch/issues/71209) + res = torch.any(x, **kwargs) + res = _axis_none_keepdims(res, x.ndim, keepdims) + return res.to(torch.bool) + + # torch.any doesn't return bool for uint8 + return torch.any(x, axis, keepdims=keepdims).to(torch.bool) + +def all(x: Array, + /, + *, + axis: int | tuple[int, ...] | None = None, + keepdims: bool = False, + **kwargs: object) -> Array: + + if axis == (): + return x.to(torch.bool) + # torch.all doesn't support multiple axes + # (https://github.com/pytorch/pytorch/issues/56586). + if isinstance(axis, tuple): + res = _reduce_multiple_axes(torch.all, x, axis, keepdims=keepdims, **kwargs) + return res.to(torch.bool) + if axis is None: + # torch doesn't support keepdims with axis=None + # (https://github.com/pytorch/pytorch/issues/71209) + res = torch.all(x, **kwargs) + res = _axis_none_keepdims(res, x.ndim, keepdims) + return res.to(torch.bool) + + # torch.all doesn't return bool for uint8 + return torch.all(x, axis, keepdims=keepdims).to(torch.bool) + +def mean(x: Array, + /, + *, + axis: int | tuple[int, ...] | None = None, + keepdims: bool = False, + **kwargs: object) -> Array: + # https://github.com/pytorch/pytorch/issues/29137 + if axis == (): + return torch.clone(x) + if axis is None: + # torch doesn't support keepdims with axis=None + # (https://github.com/pytorch/pytorch/issues/71209) + res = torch.mean(x, **kwargs) + res = _axis_none_keepdims(res, x.ndim, keepdims) + return res + return torch.mean(x, axis, keepdims=keepdims, **kwargs) + +def std(x: Array, + /, + *, + axis: int | tuple[int, ...] | None = None, + correction: float = 0.0, + keepdims: bool = False, + **kwargs: object) -> Array: + # Note, float correction is not supported + # https://github.com/pytorch/pytorch/issues/61492. We don't try to + # implement it here for now. + + if isinstance(correction, float): + _correction = int(correction) + if correction != _correction: + raise NotImplementedError("float correction in torch std() is not yet supported") + else: + _correction = correction + + # https://github.com/pytorch/pytorch/issues/29137 + if axis == (): + return torch.zeros_like(x) + if isinstance(axis, int): + axis = (axis,) + if axis is None: + # torch doesn't support keepdims with axis=None + # (https://github.com/pytorch/pytorch/issues/71209) + res = torch.std(x, tuple(range(x.ndim)), correction=_correction, **kwargs) + res = _axis_none_keepdims(res, x.ndim, keepdims) + return res + return torch.std(x, axis, correction=_correction, keepdims=keepdims, **kwargs) + +def var(x: Array, + /, + *, + axis: int | tuple[int, ...] | None = None, + correction: float = 0.0, + keepdims: bool = False, + **kwargs: object) -> Array: + # Note, float correction is not supported + # https://github.com/pytorch/pytorch/issues/61492. We don't try to + # implement it here for now. + + # if isinstance(correction, float): + # correction = int(correction) + + # https://github.com/pytorch/pytorch/issues/29137 + if axis == (): + return torch.zeros_like(x) + if isinstance(axis, int): + axis = (axis,) + if axis is None: + # torch doesn't support keepdims with axis=None + # (https://github.com/pytorch/pytorch/issues/71209) + res = torch.var(x, tuple(range(x.ndim)), correction=correction, **kwargs) + res = _axis_none_keepdims(res, x.ndim, keepdims) + return res + return torch.var(x, axis, correction=correction, keepdims=keepdims, **kwargs) + +# torch.concat doesn't support dim=None +# https://github.com/pytorch/pytorch/issues/70925 +def concat(arrays: tuple[Array, ...] | list[Array], + /, + *, + axis: int | None = 0, + **kwargs: object) -> Array: + if axis is None: + arrays = tuple(ar.flatten() for ar in arrays) + axis = 0 + return torch.concat(arrays, axis, **kwargs) + +# torch.squeeze only accepts int dim and doesn't require it +# https://github.com/pytorch/pytorch/issues/70924. Support for tuple dim was +# added at https://github.com/pytorch/pytorch/pull/89017. +def squeeze(x: Array, /, axis: int | tuple[int, ...]) -> Array: + if isinstance(axis, int): + axis = (axis,) + for a in axis: + if x.shape[a] != 1: + raise ValueError("squeezed dimensions must be equal to 1") + axes = _normalize_axes(axis, x.ndim) + # Remove this once pytorch 1.14 is released with the above PR #89017. + sequence = [a - i for i, a in enumerate(axes)] + for a in sequence: + x = torch.squeeze(x, a) + return x + +# torch.broadcast_to uses size instead of shape +def broadcast_to(x: Array, /, shape: tuple[int, ...], **kwargs: object) -> Array: + return torch.broadcast_to(x, shape, **kwargs) + +# torch.permute uses dims instead of axes +def permute_dims(x: Array, /, axes: tuple[int, ...]) -> Array: + return torch.permute(x, axes) + +# The axis parameter doesn't work for flip() and roll() +# https://github.com/pytorch/pytorch/issues/71210. Also torch.flip() doesn't +# accept axis=None +def flip(x: Array, /, *, axis: int | tuple[int, ...] | None = None, **kwargs: object) -> Array: + if axis is None: + axis = tuple(range(x.ndim)) + # torch.flip doesn't accept dim as an int but the method does + # https://github.com/pytorch/pytorch/issues/18095 + return x.flip(axis, **kwargs) + +def roll(x: Array, /, shift: int | tuple[int, ...], *, axis: int | tuple[int, ...] | None = None, **kwargs: object) -> Array: + return torch.roll(x, shift, axis, **kwargs) + +def nonzero(x: Array, /, **kwargs: object) -> tuple[Array, ...]: + if x.ndim == 0: + raise ValueError("nonzero() does not support zero-dimensional arrays") + return torch.nonzero(x, as_tuple=True, **kwargs) + + +# torch uses `dim` instead of `axis` +def diff( + x: Array, + /, + *, + axis: int = -1, + n: int = 1, + prepend: Array | None = None, + append: Array | None = None, +) -> Array: + return torch.diff(x, dim=axis, n=n, prepend=prepend, append=append) + + +# torch uses `dim` instead of `axis`, does not have keepdims +def count_nonzero( + x: Array, + /, + *, + axis: int | tuple[int, ...] | None = None, + keepdims: bool = False, +) -> Array: + result = torch.count_nonzero(x, dim=axis) + if keepdims: + if isinstance(axis, int): + return result.unsqueeze(axis) + elif isinstance(axis, tuple): + n_axis = [x.ndim + ax if ax < 0 else ax for ax in axis] + sh = [1 if i in n_axis else x.shape[i] for i in range(x.ndim)] + return torch.reshape(result, sh) + return _axis_none_keepdims(result, x.ndim, keepdims) + else: + return result + + +# "repeat" is torch.repeat_interleave; also the dim argument +def repeat(x: Array, repeats: int | Array, /, *, axis: int | None = None) -> Array: + if isinstance(repeats, torch.Tensor) and repeats.dtype in (torch.int8, torch.int16): + # torch rejects short integers for the `repeat` argument: + # https://github.com/pytorch/pytorch/issues/151311 + repeats = repeats.to(torch.int32) + return torch.repeat_interleave(x, repeats, axis) + + +def where(condition: Array, x1: Array | complex, x2: Array | complex, /) -> Array: + x1, x2 = _fix_promotion(x1, x2) + return torch.where(condition, x1, x2) + + +# torch.reshape doesn't have the copy keyword +def reshape(x: Array, + /, + shape: tuple[int, ...], + *, + copy: bool | None = None, + **kwargs: object) -> Array: + if copy is not None: + raise NotImplementedError("torch.reshape doesn't yet support the copy keyword") + return torch.reshape(x, shape, **kwargs) + +# torch.arange doesn't support returning empty arrays +# (https://github.com/pytorch/pytorch/issues/70915), and doesn't support some +# keyword argument combinations +# (https://github.com/pytorch/pytorch/issues/70914) +def arange(start: float, + /, + stop: float | None = None, + step: float = 1, + *, + dtype: DType | None = None, + device: Device | None = None, + **kwargs: object) -> Array: + if stop is None: + start, stop = 0, start + if step > 0 and stop <= start or step < 0 and stop >= start: + if dtype is None: + if _builtin_all(isinstance(i, int) for i in [start, stop, step]): + dtype = torch.int64 + else: + dtype = torch.float32 + return torch.empty(0, dtype=dtype, device=device, **kwargs) + return torch.arange(start, stop, step, dtype=dtype, device=device, **kwargs) + +# torch.eye does not accept None as a default for the second argument and +# doesn't support off-diagonals (https://github.com/pytorch/pytorch/issues/70910) +def eye(n_rows: int, + n_cols: int | None = None, + /, + *, + k: int = 0, + dtype: DType | None = None, + device: Device | None = None, + **kwargs: object) -> Array: + if n_cols is None: + n_cols = n_rows + z = torch.zeros(n_rows, n_cols, dtype=dtype, device=device, **kwargs) + if abs(k) <= n_rows + n_cols: + z.diagonal(k).fill_(1) + return z + +# torch.linspace doesn't have the endpoint parameter +def linspace(start: float, + stop: float, + /, + num: int, + *, + dtype: DType | None = None, + device: Device | None = None, + endpoint: bool = True, + **kwargs: object) -> Array: + if not endpoint: + return torch.linspace(start, stop, num+1, dtype=dtype, device=device, **kwargs)[:-1] + return torch.linspace(start, stop, num, dtype=dtype, device=device, **kwargs) + +# torch.full does not accept an int size +# https://github.com/pytorch/pytorch/issues/70906 +def full(shape: int | tuple[int, ...], + fill_value: complex, + *, + dtype: DType | None = None, + device: Device | None = None, + **kwargs: object) -> Array: + if isinstance(shape, int): + shape = (shape,) + + return torch.full(shape, fill_value, dtype=dtype, device=device, **kwargs) + +# ones, zeros, and empty do not accept shape as a keyword argument +def ones(shape: int | tuple[int, ...], + *, + dtype: DType | None = None, + device: Device | None = None, + **kwargs: object) -> Array: + return torch.ones(shape, dtype=dtype, device=device, **kwargs) + +def zeros(shape: int | tuple[int, ...], + *, + dtype: DType | None = None, + device: Device | None = None, + **kwargs: object) -> Array: + return torch.zeros(shape, dtype=dtype, device=device, **kwargs) + +def empty(shape: int | tuple[int, ...], + *, + dtype: DType | None = None, + device: Device | None = None, + **kwargs: object) -> Array: + return torch.empty(shape, dtype=dtype, device=device, **kwargs) + +# tril and triu do not call the keyword argument k + +def tril(x: Array, /, *, k: int = 0) -> Array: + return torch.tril(x, k) + +def triu(x: Array, /, *, k: int = 0) -> Array: + return torch.triu(x, k) + +# Functions that aren't in torch https://github.com/pytorch/pytorch/issues/58742 +def expand_dims(x: Array, /, axis: int | tuple[int, ...]) -> Array: + if isinstance(axis, int): + return torch.unsqueeze(x, axis) + else: + # follow https://github.com/numpy/numpy/blob/maintenance/2.4.x/numpy/lib/_shape_base_impl.py#L596-L602 + y_ndim = x.ndim + len(axis) + + # normalize + n_axis = tuple(ax + y_ndim if ax < 0 else ax for ax in axis) + if (len(n_axis) != len(set(n_axis)) or + _builtin_any(ax < 0 or ax >= y_ndim for ax in n_axis) + ): + raise ValueError(f"{axis=} not allowed for {x.shape = }") + + shape_it = iter(x.shape) + shape = [1 if ax in n_axis else next(shape_it) for ax in range(y_ndim)] + + return torch.reshape(x, shape) + +def astype( + x: Array, + dtype: DType, + /, + *, + copy: bool = True, + device: Device | None = None, +) -> Array: + if device is not None: + return x.to(device, dtype=dtype, copy=copy) + return x.to(dtype=dtype, copy=copy) + + +def broadcast_arrays(*arrays: Array) -> tuple[Array, ...]: + shape = torch.broadcast_shapes(*[a.shape for a in arrays]) + return tuple(torch.broadcast_to(a, shape) for a in arrays) + +# Note that these named tuples aren't actually part of the standard namespace, +# but I don't see any issue with exporting the names here regardless. +from ..common._aliases import (UniqueAllResult, UniqueCountsResult, + UniqueInverseResult) + +# https://github.com/pytorch/pytorch/issues/70920 +def unique_all(x: Array) -> UniqueAllResult: + # torch.unique doesn't support returning indices. + # https://github.com/pytorch/pytorch/issues/36748. The workaround + # suggested in that issue doesn't actually function correctly (it relies + # on non-deterministic behavior of scatter()). + raise NotImplementedError("unique_all() not yet implemented for pytorch (see https://github.com/pytorch/pytorch/issues/36748)") + + # values, inverse_indices, counts = torch.unique(x, return_counts=True, return_inverse=True) + # # torch.unique incorrectly gives a 0 count for nan values. + # # https://github.com/pytorch/pytorch/issues/94106 + # counts[torch.isnan(values)] = 1 + # return UniqueAllResult(values, indices, inverse_indices, counts) + +def unique_counts(x: Array) -> UniqueCountsResult: + values, counts = torch.unique(x, return_counts=True) + + # torch.unique incorrectly gives a 0 count for nan values. + # https://github.com/pytorch/pytorch/issues/94106 + counts[torch.isnan(values)] = 1 + return UniqueCountsResult(values, counts) + +def unique_inverse(x: Array) -> UniqueInverseResult: + values, inverse = torch.unique(x, return_inverse=True) + return UniqueInverseResult(values, inverse) + +def unique_values(x: Array) -> Array: + return torch.unique(x) + +def matmul(x1: Array, x2: Array, /, **kwargs: object) -> Array: + # torch.matmul doesn't type promote (but differently from _fix_promotion) + x1, x2 = _fix_promotion(x1, x2, only_scalar=False) + return torch.matmul(x1, x2, **kwargs) + +matrix_transpose = get_xp(torch)(_aliases.matrix_transpose) +_vecdot = get_xp(torch)(_aliases.vecdot) + +def vecdot(x1: Array, x2: Array, /, *, axis: int = -1) -> Array: + x1, x2 = _fix_promotion(x1, x2, only_scalar=False) + return _vecdot(x1, x2, axis=axis) + +# torch.tensordot uses dims instead of axes +def tensordot( + x1: Array, + x2: Array, + /, + *, + axes: int | tuple[Sequence[int], Sequence[int]] = 2, + **kwargs: object, +) -> Array: + # Note: torch.tensordot fails with integer dtypes when there is only 1 + # element in the axis (https://github.com/pytorch/pytorch/issues/84530). + x1, x2 = _fix_promotion(x1, x2, only_scalar=False) + return torch.tensordot(x1, x2, dims=axes, **kwargs) + + +def isdtype( + dtype: DType, + kind: DType | str | tuple[DType | str, ...], + *, + _tuple: bool = True, # Disallow nested tuples +) -> bool: + """ + Returns a boolean indicating whether a provided dtype is of a specified data type ``kind``. + + Note that outside of this function, this compat library does not yet fully + support complex numbers. + + See + https://data-apis.org/array-api/latest/API_specification/generated/array_api.isdtype.html + for more details + """ + if isinstance(kind, tuple) and _tuple: + return _builtin_any(isdtype(dtype, k, _tuple=False) for k in kind) + elif isinstance(kind, str): + if kind == 'bool': + return dtype == torch.bool + elif kind == 'signed integer': + return dtype in _int_dtypes and dtype.is_signed + elif kind == 'unsigned integer': + return dtype in _int_dtypes and not dtype.is_signed + elif kind == 'integral': + return dtype in _int_dtypes + elif kind == 'real floating': + return dtype.is_floating_point + elif kind == 'complex floating': + return dtype.is_complex + elif kind == 'numeric': + return isdtype(dtype, ('integral', 'real floating', 'complex floating')) + else: + raise ValueError(f"Unrecognized data type kind: {kind!r}") + else: + return dtype == kind + +def take(x: Array, indices: Array, /, *, axis: int | None = None, **kwargs: object) -> Array: + if axis is None: + if x.ndim != 1: + raise ValueError("axis must be specified when ndim > 1") + axis = 0 + # torch does not support negative indices, + # see https://github.com/pytorch/pytorch/issues/146211 + return torch.index_select( + x, + axis, + torch.where(indices < 0, indices + x.shape[axis], indices), + **kwargs + ) + + +def take_along_axis(x: Array, indices: Array, /, *, axis: int = -1) -> Array: + # torch does not support negative indices, + # see https://github.com/pytorch/pytorch/issues/146211 + return torch.take_along_dim( + x, + torch.where(indices < 0, indices + x.shape[axis], indices), + dim=axis + ) + + +def clip( + x: Array, + /, + min: int | float | Array | None = None, + max: int | float | Array | None = None, + **kwargs +) -> Array: + def _isscalar(a: object): + return isinstance(a, int | float) or a is None + + # cf clip in common/_aliases.py + if not x.is_floating_point(): + if type(min) is int and min <= torch.iinfo(x.dtype).min: + min = None + if type(max) is int and max >= torch.iinfo(x.dtype).max: + max = None + + if min is None and max is None: + return torch.clone(x) + + min_is_scalar = _isscalar(min) + max_is_scalar = _isscalar(max) + + if min_is_scalar and max_is_scalar: + if (min is not None and math.isnan(min)) or (max is not None and math.isnan(max)): + # edge case: torch.clamp(torch.zeros(1), float('nan')) -> tensor(0.) + # https://github.com/pytorch/pytorch/issues/172067 + return torch.full_like(x, fill_value=torch.nan) + return torch.clamp(x, min, max, **kwargs) + + # pytorch has (tensor, tensor, tensor) and (tensor, scalar, scalar) signatures, + # but does not accept (tensor, scalar, tensor) + a_min = min + if min is not None and min_is_scalar: + a_min = torch.as_tensor(min, dtype=x.dtype, device=x.device) + + a_max = max + if max is not None and max_is_scalar: + a_max = torch.as_tensor(max, dtype=x.dtype, device=x.device) + + return torch.clamp(x, a_min, a_max, **kwargs) + + +def sign(x: Array, /) -> Array: + # torch sign() does not support complex numbers and does not propagate + # nans. See https://github.com/data-apis/array-api-compat/issues/136 + if x.dtype.is_complex: + out = x/torch.abs(x) + # sign(0) = 0 but the above formula would give nan + out[x == 0+0j] = 0+0j + return out + else: + out = torch.sign(x) + if x.dtype.is_floating_point: + out[torch.isnan(x)] = torch.nan + return out + + +def meshgrid(*arrays: Array, indexing: Literal['xy', 'ij'] = 'xy') -> tuple[Array, ...]: + # torch <= 2.9 emits a UserWarning: "torch.meshgrid: in an upcoming release, it + # will be required to pass the indexing argument." + # Thus always pass it explicitly. + return torch.meshgrid(*arrays, indexing=indexing) + + +__all__ = ['asarray', 'result_type', 'can_cast', + 'permute_dims', 'bitwise_invert', 'newaxis', 'conj', 'add', + 'atan2', 'bitwise_and', 'bitwise_left_shift', 'bitwise_or', + 'bitwise_right_shift', 'bitwise_xor', 'copysign', 'count_nonzero', + 'diff', 'divide', + 'equal', 'floor_divide', 'greater', 'greater_equal', 'hypot', + 'less', 'less_equal', 'logaddexp', 'maximum', 'minimum', + 'multiply', 'not_equal', 'pow', 'remainder', 'subtract', 'max', + 'min', 'clip', 'unstack', 'cumulative_sum', 'cumulative_prod', 'sort', + 'argsort', 'prod', 'sum', 'any', 'all', 'mean', 'std', 'var', 'concat', + 'squeeze', 'broadcast_to', 'flip', 'roll', 'nonzero', 'where', 'reshape', + 'arange', 'eye', 'linspace', 'full', 'ones', 'zeros', 'empty', + 'tril', 'triu', 'expand_dims', 'astype', 'broadcast_arrays', + 'UniqueAllResult', 'UniqueCountsResult', 'UniqueInverseResult', + 'unique_all', 'unique_counts', 'unique_inverse', 'unique_values', + 'matmul', 'matrix_transpose', 'vecdot', 'tensordot', 'isdtype', + 'take', 'take_along_axis', 'sign', 'finfo', 'iinfo', 'repeat', 'meshgrid'] diff --git a/.venv/lib/python3.12/site-packages/scipy/_external/array_api_compat/torch/_info.py b/.venv/lib/python3.12/site-packages/scipy/_external/array_api_compat/torch/_info.py new file mode 100644 index 0000000000000000000000000000000000000000..050c7846f481e78b9835e52a93411cab30153fef --- /dev/null +++ b/.venv/lib/python3.12/site-packages/scipy/_external/array_api_compat/torch/_info.py @@ -0,0 +1,369 @@ +""" +Array API Inspection namespace + +This is the namespace for inspection functions as defined by the array API +standard. See +https://data-apis.org/array-api/latest/API_specification/inspection.html for +more details. + +""" +import torch + +from functools import cache + +class __array_namespace_info__: + """ + Get the array API inspection namespace for PyTorch. + + The array API inspection namespace defines the following functions: + + - capabilities() + - default_device() + - default_dtypes() + - dtypes() + - devices() + + See + https://data-apis.org/array-api/latest/API_specification/inspection.html + for more details. + + Returns + ------- + info : ModuleType + The array API inspection namespace for PyTorch. + + Examples + -------- + >>> info = xp.__array_namespace_info__() + >>> info.default_dtypes() + {'real floating': numpy.float64, + 'complex floating': numpy.complex128, + 'integral': numpy.int64, + 'indexing': numpy.int64} + + """ + + __module__ = 'torch' + + def capabilities(self): + """ + Return a dictionary of array API library capabilities. + + The resulting dictionary has the following keys: + + - **"boolean indexing"**: boolean indicating whether an array library + supports boolean indexing. Always ``True`` for PyTorch. + + - **"data-dependent shapes"**: boolean indicating whether an array + library supports data-dependent output shapes. Always ``True`` for + PyTorch. + + See + https://data-apis.org/array-api/latest/API_specification/generated/array_api.info.capabilities.html + for more details. + + See Also + -------- + __array_namespace_info__.default_device, + __array_namespace_info__.default_dtypes, + __array_namespace_info__.dtypes, + __array_namespace_info__.devices + + Returns + ------- + capabilities : dict + A dictionary of array API library capabilities. + + Examples + -------- + >>> info = xp.__array_namespace_info__() + >>> info.capabilities() + {'boolean indexing': True, + 'data-dependent shapes': True, + 'max dimensions': 64} + + """ + return { + "boolean indexing": True, + "data-dependent shapes": True, + "max dimensions": 64, + } + + def default_device(self): + """ + The default device used for new PyTorch arrays. + + See Also + -------- + __array_namespace_info__.capabilities, + __array_namespace_info__.default_dtypes, + __array_namespace_info__.dtypes, + __array_namespace_info__.devices + + Returns + ------- + device : Device + The default device used for new PyTorch arrays. + + Examples + -------- + >>> info = xp.__array_namespace_info__() + >>> info.default_device() + device(type='cpu') + + Notes + ----- + This method returns the static default device when PyTorch is initialized. + However, the *current* device used by creation functions (``empty`` etc.) + can be changed at runtime. + + See Also + -------- + https://github.com/data-apis/array-api/issues/835 + """ + return torch.device("cpu") + + def default_dtypes(self, *, device=None): + """ + The default data types used for new PyTorch arrays. + + Parameters + ---------- + device : Device, optional + The device to get the default data types for. + Unused for PyTorch, as all devices use the same default dtypes. + + Returns + ------- + dtypes : dict + A dictionary describing the default data types used for new PyTorch + arrays. + + See Also + -------- + __array_namespace_info__.capabilities, + __array_namespace_info__.default_device, + __array_namespace_info__.dtypes, + __array_namespace_info__.devices + + Examples + -------- + >>> info = xp.__array_namespace_info__() + >>> info.default_dtypes() + {'real floating': torch.float32, + 'complex floating': torch.complex64, + 'integral': torch.int64, + 'indexing': torch.int64} + + """ + # Note: if the default is set to float64, the devices like MPS that + # don't support float64 will error. We still return the default_dtype + # value here because this error doesn't represent a different default + # per-device. + default_floating = torch.get_default_dtype() + default_complex = torch.complex64 if default_floating == torch.float32 else torch.complex128 + default_integral = torch.int64 + return { + "real floating": default_floating, + "complex floating": default_complex, + "integral": default_integral, + "indexing": default_integral, + } + + + def _dtypes(self, kind): + bool = torch.bool + int8 = torch.int8 + int16 = torch.int16 + int32 = torch.int32 + int64 = torch.int64 + uint8 = torch.uint8 + # uint16, uint32, and uint64 are present in newer versions of pytorch, + # but they aren't generally supported by the array API functions, so + # we omit them from this function. + float32 = torch.float32 + float64 = torch.float64 + complex64 = torch.complex64 + complex128 = torch.complex128 + + if kind is None: + return { + "bool": bool, + "int8": int8, + "int16": int16, + "int32": int32, + "int64": int64, + "uint8": uint8, + "float32": float32, + "float64": float64, + "complex64": complex64, + "complex128": complex128, + } + if kind == "bool": + return {"bool": bool} + if kind == "signed integer": + return { + "int8": int8, + "int16": int16, + "int32": int32, + "int64": int64, + } + if kind == "unsigned integer": + return { + "uint8": uint8, + } + if kind == "integral": + return { + "int8": int8, + "int16": int16, + "int32": int32, + "int64": int64, + "uint8": uint8, + } + if kind == "real floating": + return { + "float32": float32, + "float64": float64, + } + if kind == "complex floating": + return { + "complex64": complex64, + "complex128": complex128, + } + if kind == "numeric": + return { + "int8": int8, + "int16": int16, + "int32": int32, + "int64": int64, + "uint8": uint8, + "float32": float32, + "float64": float64, + "complex64": complex64, + "complex128": complex128, + } + if isinstance(kind, tuple): + res = {} + for k in kind: + res.update(self.dtypes(kind=k)) + return res + raise ValueError(f"unsupported kind: {kind!r}") + + @cache + def dtypes(self, *, device=None, kind=None): + """ + The array API data types supported by PyTorch. + + Note that this function only returns data types that are defined by + the array API. + + Parameters + ---------- + device : Device, optional + The device to get the data types for. + Unused for PyTorch, as all devices use the same dtypes. + kind : str or tuple of str, optional + The kind of data types to return. If ``None``, all data types are + returned. If a string, only data types of that kind are returned. + If a tuple, a dictionary containing the union of the given kinds + is returned. The following kinds are supported: + + - ``'bool'``: boolean data types (i.e., ``bool``). + - ``'signed integer'``: signed integer data types (i.e., ``int8``, + ``int16``, ``int32``, ``int64``). + - ``'unsigned integer'``: unsigned integer data types (i.e., + ``uint8``, ``uint16``, ``uint32``, ``uint64``). + - ``'integral'``: integer data types. Shorthand for ``('signed + integer', 'unsigned integer')``. + - ``'real floating'``: real-valued floating-point data types + (i.e., ``float32``, ``float64``). + - ``'complex floating'``: complex floating-point data types (i.e., + ``complex64``, ``complex128``). + - ``'numeric'``: numeric data types. Shorthand for ``('integral', + 'real floating', 'complex floating')``. + + Returns + ------- + dtypes : dict + A dictionary mapping the names of data types to the corresponding + PyTorch data types. + + See Also + -------- + __array_namespace_info__.capabilities, + __array_namespace_info__.default_device, + __array_namespace_info__.default_dtypes, + __array_namespace_info__.devices + + Examples + -------- + >>> info = xp.__array_namespace_info__() + >>> info.dtypes(kind='signed integer') + {'int8': numpy.int8, + 'int16': numpy.int16, + 'int32': numpy.int32, + 'int64': numpy.int64} + + """ + res = self._dtypes(kind) + for k, v in res.copy().items(): + try: + torch.empty((0,), dtype=v, device=device) + except: + del res[k] + return res + + @cache + def devices(self): + """ + The devices supported by PyTorch. + + Returns + ------- + devices : list[Device] + The devices supported by PyTorch. + + See Also + -------- + __array_namespace_info__.capabilities, + __array_namespace_info__.default_device, + __array_namespace_info__.default_dtypes, + __array_namespace_info__.dtypes + + Examples + -------- + >>> info = xp.__array_namespace_info__() + >>> info.devices() + [device(type='cpu'), device(type='mps', index=0), device(type='meta')] + + """ + # Torch doesn't have a straightforward way to get the list of all + # currently supported devices. To do this, we first parse the error + # message of torch.device to get the list of all possible types of + # device: + try: + torch.device('notadevice') + raise AssertionError("unreachable") # pragma: nocover + except RuntimeError as e: + # The error message is something like: + # "Expected one of cpu, cuda, ipu, xpu, mkldnn, opengl, opencl, ideep, hip, ve, fpga, ort, xla, lazy, vulkan, mps, meta, hpu, mtia, privateuseone device type at start of device string: notadevice" + devices_names = e.args[0].split('Expected one of ')[1].split(' device type')[0].split(', ') + + # Next we need to check for different indices for different devices. + # device(device_name, index=index) doesn't actually check if the + # device name or index is valid. We have to try to create a tensor + # with it (which is why this function is cached). + devices = [] + for device_name in devices_names: + i = 0 + while True: + try: + a = torch.empty((0,), device=torch.device(device_name, index=i)) + if a.device in devices: + break + devices.append(a.device) + except: + break + i += 1 + + return tuple(devices) diff --git a/.venv/lib/python3.12/site-packages/scipy/_external/array_api_compat/torch/_typing.py b/.venv/lib/python3.12/site-packages/scipy/_external/array_api_compat/torch/_typing.py new file mode 100644 index 0000000000000000000000000000000000000000..52670871563710d326b0a114a7a517bf87098bf0 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/scipy/_external/array_api_compat/torch/_typing.py @@ -0,0 +1,3 @@ +__all__ = ["Array", "Device", "DType"] + +from torch import device as Device, dtype as DType, Tensor as Array diff --git a/.venv/lib/python3.12/site-packages/scipy/_external/array_api_compat/torch/fft.py b/.venv/lib/python3.12/site-packages/scipy/_external/array_api_compat/torch/fft.py new file mode 100644 index 0000000000000000000000000000000000000000..f11b3eb5975639150c6add018c7ac36e1205b9e8 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/scipy/_external/array_api_compat/torch/fft.py @@ -0,0 +1,82 @@ +from __future__ import annotations + +from collections.abc import Sequence +from typing import Literal + +import torch # noqa: F401 +import torch.fft + +from ._typing import Array +from .._internal import clone_module + +__all__ = clone_module("torch.fft", globals()) + +# Several torch fft functions do not map axes to dim + +def fftn( + x: Array, + /, + *, + s: Sequence[int] = None, + axes: Sequence[int] = None, + norm: Literal["backward", "ortho", "forward"] = "backward", + **kwargs: object, +) -> Array: + return torch.fft.fftn(x, s=s, dim=axes, norm=norm, **kwargs) + +def ifftn( + x: Array, + /, + *, + s: Sequence[int] = None, + axes: Sequence[int] = None, + norm: Literal["backward", "ortho", "forward"] = "backward", + **kwargs: object, +) -> Array: + return torch.fft.ifftn(x, s=s, dim=axes, norm=norm, **kwargs) + +def rfftn( + x: Array, + /, + *, + s: Sequence[int] = None, + axes: Sequence[int] = None, + norm: Literal["backward", "ortho", "forward"] = "backward", + **kwargs: object, +) -> Array: + return torch.fft.rfftn(x, s=s, dim=axes, norm=norm, **kwargs) + +def irfftn( + x: Array, + /, + *, + s: Sequence[int] = None, + axes: Sequence[int] = None, + norm: Literal["backward", "ortho", "forward"] = "backward", + **kwargs: object, +) -> Array: + return torch.fft.irfftn(x, s=s, dim=axes, norm=norm, **kwargs) + +def fftshift( + x: Array, + /, + *, + axes: int | Sequence[int] = None, + **kwargs: object, +) -> Array: + return torch.fft.fftshift(x, dim=axes, **kwargs) + +def ifftshift( + x: Array, + /, + *, + axes: int | Sequence[int] = None, + **kwargs: object, +) -> Array: + return torch.fft.ifftshift(x, dim=axes, **kwargs) + + +__all__ += ["fftn", "ifftn", "rfftn", "irfftn", "fftshift", "ifftshift"] + +def __dir__() -> list[str]: + return __all__ diff --git a/.venv/lib/python3.12/site-packages/scipy/_external/array_api_compat/torch/linalg.py b/.venv/lib/python3.12/site-packages/scipy/_external/array_api_compat/torch/linalg.py new file mode 100644 index 0000000000000000000000000000000000000000..08271d226734b64212a8cd687617f9ecb3197b41 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/scipy/_external/array_api_compat/torch/linalg.py @@ -0,0 +1,114 @@ +from __future__ import annotations + +import torch +import torch.linalg + +from .._internal import clone_module + +__all__ = clone_module("torch.linalg", globals()) + +# outer is implemented in torch but aren't in the linalg namespace +from torch import outer +from ._aliases import _fix_promotion, sum +# These functions are in both the main and linalg namespaces +from ._aliases import matmul, matrix_transpose, tensordot +from ._typing import Array, DType +from ..common._typing import JustInt, JustFloat + +# Note: torch.linalg.cross does not default to axis=-1 (it defaults to the +# first axis with size 3), see https://github.com/pytorch/pytorch/issues/58743 + +# torch.cross also does not support broadcasting when it would add new +# dimensions https://github.com/pytorch/pytorch/issues/39656 +def cross(x1: Array, x2: Array, /, *, axis: int = -1) -> Array: + x1, x2 = _fix_promotion(x1, x2, only_scalar=False) + if not (-min(x1.ndim, x2.ndim) <= axis < max(x1.ndim, x2.ndim)): + raise ValueError(f"axis {axis} out of bounds for cross product of arrays with shapes {x1.shape} and {x2.shape}") + if not (x1.shape[axis] == x2.shape[axis] == 3): + raise ValueError(f"cross product axis must have size 3, got {x1.shape[axis]} and {x2.shape[axis]}") + x1, x2 = torch.broadcast_tensors(x1, x2) + return torch.linalg.cross(x1, x2, dim=axis) + +def vecdot(x1: Array, x2: Array, /, *, axis: int = -1, **kwargs: object) -> Array: + from ._aliases import isdtype + + x1, x2 = _fix_promotion(x1, x2, only_scalar=False) + + # torch.linalg.vecdot incorrectly allows broadcasting along the contracted dimension + if x1.shape[axis] != x2.shape[axis]: + raise ValueError("x1 and x2 must have the same size along the given axis") + + # torch.linalg.vecdot doesn't support integer dtypes + if isdtype(x1.dtype, 'integral') or isdtype(x2.dtype, 'integral'): + if kwargs: + raise RuntimeError("vecdot kwargs not supported for integral dtypes") + + x1_ = torch.moveaxis(x1, axis, -1) + x2_ = torch.moveaxis(x2, axis, -1) + x1_, x2_ = torch.broadcast_tensors(x1_, x2_) + + res = x1_[..., None, :] @ x2_[..., None] + return res[..., 0, 0] + return torch.linalg.vecdot(x1, x2, dim=axis, **kwargs) + +def solve(x1: Array, x2: Array, /, **kwargs: object) -> Array: + x1, x2 = _fix_promotion(x1, x2, only_scalar=False) + # Torch tries to emulate NumPy 1 solve behavior by using batched 1-D solve + # whenever + # 1. x1.ndim - 1 == x2.ndim + # 2. x1.shape[:-1] == x2.shape + # + # See linalg_solve_is_vector_rhs in + # aten/src/ATen/native/LinearAlgebraUtils.h and + # TORCH_META_FUNC(_linalg_solve_ex) in + # aten/src/ATen/native/BatchLinearAlgebra.cpp in the PyTorch source code. + # + # The easiest way to work around this is to prepend a size 1 dimension to + # x2, since x2 is already one dimension less than x1. + # + # See https://github.com/pytorch/pytorch/issues/52915 + if x2.ndim != 1 and x1.ndim - 1 == x2.ndim and x1.shape[:-1] == x2.shape: + x2 = x2[None] + return torch.linalg.solve(x1, x2, **kwargs) + +# torch.trace doesn't support the offset argument and doesn't support stacking +def trace(x: Array, /, *, offset: int = 0, dtype: DType | None = None) -> Array: + # Use our wrapped sum to make sure it does upcasting correctly + return sum(torch.diagonal(x, offset=offset, dim1=-2, dim2=-1), axis=-1, dtype=dtype) + +def vector_norm( + x: Array, + /, + *, + axis: int | tuple[int, ...] | None = None, + keepdims: bool = False, + # JustFloat stands for inf | -inf, which are not valid for Literal + ord: JustInt | JustFloat = 2, + **kwargs: object, +) -> Array: + # torch.vector_norm incorrectly treats axis=() the same as axis=None + if axis == (): + out = kwargs.get('out') + if out is None: + dtype = None + if x.dtype == torch.complex64: + dtype = torch.float32 + elif x.dtype == torch.complex128: + dtype = torch.float64 + + out = torch.zeros_like(x, dtype=dtype) + + # The norm of a single scalar works out to abs(x) in every case except + # for ord=0, which is x != 0. + if ord == 0: + out[:] = (x != 0) + else: + out[:] = torch.abs(x) + return out + return torch.linalg.vector_norm(x, ord=ord, axis=axis, keepdim=keepdims, **kwargs) + +__all__ += ['outer', 'matmul', 'matrix_transpose', 'tensordot', + 'cross', 'vecdot', 'solve', 'trace', 'vector_norm'] + +def __dir__() -> list[str]: + return __all__ diff --git a/.venv/lib/python3.12/site-packages/scipy/_external/array_api_extra/__init__.py b/.venv/lib/python3.12/site-packages/scipy/_external/array_api_extra/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..7c35443e4f1957f3ea478ee76f71a86d6aef913f --- /dev/null +++ b/.venv/lib/python3.12/site-packages/scipy/_external/array_api_extra/__init__.py @@ -0,0 +1,57 @@ +"""Extra array functions built on top of the array API standard.""" + +from ._delegation import ( + argpartition, + atleast_nd, + cov, + create_diagonal, + expand_dims, + isclose, + isin, + nan_to_num, + one_hot, + pad, + partition, + searchsorted, + setdiff1d, + sinc, + union1d, +) +from ._lib._at import at +from ._lib._funcs import ( + apply_where, + broadcast_shapes, + default_dtype, + kron, + nunique, +) +from ._lib._lazy import lazy_apply + +__version__ = "0.10.1" + +# pylint: disable=duplicate-code +__all__ = [ + "__version__", + "apply_where", + "argpartition", + "at", + "atleast_nd", + "broadcast_shapes", + "cov", + "create_diagonal", + "default_dtype", + "expand_dims", + "isclose", + "isin", + "kron", + "lazy_apply", + "nan_to_num", + "nunique", + "one_hot", + "pad", + "partition", + "searchsorted", + "setdiff1d", + "sinc", + "union1d", +] diff --git a/.venv/lib/python3.12/site-packages/scipy/_external/array_api_extra/__pycache__/__init__.cpython-312.pyc b/.venv/lib/python3.12/site-packages/scipy/_external/array_api_extra/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..bf01b17012c294b649d7af0bdd25d81d9602d23a Binary files /dev/null and b/.venv/lib/python3.12/site-packages/scipy/_external/array_api_extra/__pycache__/__init__.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/scipy/_external/array_api_extra/__pycache__/_delegation.cpython-312.pyc b/.venv/lib/python3.12/site-packages/scipy/_external/array_api_extra/__pycache__/_delegation.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c3a238d39ad469b38f1bbbd4ce67aab42203f558 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/scipy/_external/array_api_extra/__pycache__/_delegation.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/scipy/_external/array_api_extra/__pycache__/testing.cpython-312.pyc b/.venv/lib/python3.12/site-packages/scipy/_external/array_api_extra/__pycache__/testing.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..40f4fd8e6b17f84026280408697494e2993005fe Binary files /dev/null and b/.venv/lib/python3.12/site-packages/scipy/_external/array_api_extra/__pycache__/testing.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/scipy/_external/array_api_extra/_delegation.py b/.venv/lib/python3.12/site-packages/scipy/_external/array_api_extra/_delegation.py new file mode 100644 index 0000000000000000000000000000000000000000..46639559967833e8110e399f8cf3d61e7de22d0b --- /dev/null +++ b/.venv/lib/python3.12/site-packages/scipy/_external/array_api_extra/_delegation.py @@ -0,0 +1,1152 @@ +"""Delegation to existing implementations for Public API Functions.""" + +from collections.abc import Sequence +from types import ModuleType +from typing import Literal + +from ._lib import _funcs +from ._lib._utils._compat import ( + array_namespace, + is_cupy_namespace, + is_dask_namespace, + is_jax_namespace, + is_numpy_namespace, + is_pydata_sparse_namespace, + is_torch_namespace, +) +from ._lib._utils._compat import device as get_device +from ._lib._utils._helpers import asarrays, eager_shape +from ._lib._utils._typing import Array, DType + +__all__ = [ + "atleast_nd", + "cov", + "create_diagonal", + "expand_dims", + "isclose", + "nan_to_num", + "one_hot", + "pad", + "searchsorted", + "sinc", +] + + +def atleast_nd(x: Array, /, *, ndim: int, xp: ModuleType | None = None) -> Array: + """ + Recursively expand the dimension of an array to at least `ndim`. + + Parameters + ---------- + x : array + Input array. + ndim : int + The minimum number of dimensions for the result. + xp : array_namespace, optional + The standard-compatible namespace for `x`. Default: infer. + + Returns + ------- + array + An array with ``res.ndim`` >= `ndim`. + If ``x.ndim`` >= `ndim`, `x` is returned. + If ``x.ndim`` < `ndim`, `x` is expanded by prepending new axes + until ``res.ndim`` equals `ndim`. + + Examples + -------- + >>> import array_api_strict as xp + >>> import array_api_extra as xpx + >>> x = xp.asarray([1]) + >>> xpx.atleast_nd(x, ndim=3, xp=xp) + Array([[[1]]], dtype=array_api_strict.int64) + + >>> x = xp.asarray([[[1, 2], + ... [3, 4]]]) + >>> xpx.atleast_nd(x, ndim=1, xp=xp) is x + True + """ + if xp is None: + xp = array_namespace(x) + + if 1 <= ndim <= 2 and ( + is_numpy_namespace(xp) + or is_jax_namespace(xp) + or is_dask_namespace(xp) + or is_cupy_namespace(xp) + or is_torch_namespace(xp) + ): + return getattr(xp, f"atleast_{ndim}d")(x) + + return _funcs.atleast_nd(x, ndim=ndim, xp=xp) + + +def cov(m: Array, /, *, xp: ModuleType | None = None) -> Array: + """ + Estimate a covariance matrix (or a stack of covariance matrices). + + Covariance indicates the level to which two variables vary together. + If we examine *N*-dimensional samples, :math:`X = [x_1, x_2, ... x_N]^T`, + each with *M* observations, then element :math:`C_{ij}` of the + :math:`N \times N` covariance matrix is the covariance of + :math:`x_i` and :math:`x_j`. The element :math:`C_{ii}` is the variance + of :math:`x_i`. + + With the exception of supporting batch input, this provides a subset of + the functionality of ``numpy.cov``. + + Parameters + ---------- + m : array + An array of shape ``(..., N, M)`` whose innermost two dimensions + contain *M* observations of *N* variables. That is, + each row of `m` represents a variable, and each column a single + observation of all those variables. + xp : array_namespace, optional + The standard-compatible namespace for `m`. Default: infer. + + Returns + ------- + array + An array having shape (..., N, N) whose innermost two dimensions represent + the covariance matrix of the variables. + + Examples + -------- + >>> import array_api_strict as xp + >>> import array_api_extra as xpx + + Consider two variables, :math:`x_0` and :math:`x_1`, which + correlate perfectly, but in opposite directions: + + >>> x = xp.asarray([[0, 2], [1, 1], [2, 0]]).T + >>> x + Array([[0, 1, 2], + [2, 1, 0]], dtype=array_api_strict.int64) + + Note how :math:`x_0` increases while :math:`x_1` decreases. The covariance + matrix shows this clearly: + + >>> xpx.cov(x, xp=xp) + Array([[ 1., -1.], + [-1., 1.]], dtype=array_api_strict.float64) + + Note that element :math:`C_{0,1}`, which shows the correlation between + :math:`x_0` and :math:`x_1`, is negative. + + Further, note how `x` and `y` are combined: + + >>> x = xp.asarray([-2.1, -1, 4.3]) + >>> y = xp.asarray([3, 1.1, 0.12]) + >>> X = xp.stack((x, y), axis=0) + >>> xpx.cov(X, xp=xp) + Array([[11.71 , -4.286 ], + [-4.286 , 2.14413333]], dtype=array_api_strict.float64) + + >>> xpx.cov(x, xp=xp) + Array(11.71, dtype=array_api_strict.float64) + + >>> xpx.cov(y, xp=xp) + Array(2.14413333, dtype=array_api_strict.float64) + + Input with more than two dimensions is treated as a stack of + two-dimensional input. + + >>> stack = xp.stack((X, 2*X)) + >>> xpx.cov(stack) + Array([[[ 11.71 , -4.286 ], + [ -4.286 , 2.14413333]], + + [[ 46.84 , -17.144 ], + [-17.144 , 8.57653333]]], dtype=array_api_strict.float64) + """ + + if xp is None: + xp = array_namespace(m) + + if ( + is_numpy_namespace(xp) + or is_cupy_namespace(xp) + or is_torch_namespace(xp) + or is_dask_namespace(xp) + or is_jax_namespace(xp) + ) and m.ndim <= 2: + return xp.cov(m) + + return _funcs.cov(m, xp=xp) + + +def create_diagonal( + x: Array, /, *, offset: int = 0, xp: ModuleType | None = None +) -> Array: + """ + Construct a diagonal array. + + Parameters + ---------- + x : array + An array having shape ``(*batch_dims, k)``. + offset : int, optional + Offset from the leading diagonal (default is ``0``). + Use positive ints for diagonals above the leading diagonal, + and negative ints for diagonals below the leading diagonal. + xp : array_namespace, optional + The standard-compatible namespace for `x`. Default: infer. + + Returns + ------- + array + An array having shape ``(*batch_dims, k+abs(offset), k+abs(offset))`` with `x` + on the diagonal (offset by `offset`). + + Examples + -------- + >>> import array_api_strict as xp + >>> import array_api_extra as xpx + >>> x = xp.asarray([2, 4, 8]) + + >>> xpx.create_diagonal(x, xp=xp) + Array([[2, 0, 0], + [0, 4, 0], + [0, 0, 8]], dtype=array_api_strict.int64) + + >>> xpx.create_diagonal(x, offset=-2, xp=xp) + Array([[0, 0, 0, 0, 0], + [0, 0, 0, 0, 0], + [2, 0, 0, 0, 0], + [0, 4, 0, 0, 0], + [0, 0, 8, 0, 0]], dtype=array_api_strict.int64) + """ + if xp is None: + xp = array_namespace(x) + + if x.ndim == 0: + err_msg = "`x` must be at least 1-dimensional." + raise ValueError(err_msg) + + if is_torch_namespace(xp): + return xp.diag_embed(x, offset=offset, dim1=-2, dim2=-1) + + if ( + is_dask_namespace(xp) + or is_cupy_namespace(xp) + or is_numpy_namespace(xp) + or is_jax_namespace(xp) + ) and (x.ndim < 2): + return xp.diag(x, k=offset) + + return _funcs.create_diagonal(x, offset=offset, xp=xp) + + +def expand_dims( + a: Array, /, *, axis: int | tuple[int, ...] = (0,), xp: ModuleType | None = None +) -> Array: + """ + Expand the shape of an array. + + Insert (a) new axis/axes that will appear at the position(s) specified by + `axis` in the expanded array shape. + + This is ``xp.expand_dims`` for `axis` an int *or a tuple of ints*. + Roughly equivalent to ``numpy.expand_dims`` for NumPy arrays. + + Parameters + ---------- + a : array + Array to have its shape expanded. + axis : int or tuple of ints, optional + Position(s) in the expanded axes where the new axis (or axes) is/are placed. + If multiple positions are provided, they should be unique (note that a position + given by a positive index could also be referred to by a negative index - + that will also result in an error). + Default: ``(0,)``. + xp : array_namespace, optional + The standard-compatible namespace for `a`. Default: infer. + + Returns + ------- + array + `a` with an expanded shape. + + Examples + -------- + >>> import array_api_strict as xp + >>> import array_api_extra as xpx + >>> x = xp.asarray([1, 2]) + >>> x.shape + (2,) + + The following is equivalent to ``x[xp.newaxis, :]`` or ``x[xp.newaxis]``: + + >>> y = xpx.expand_dims(x, axis=0, xp=xp) + >>> y + Array([[1, 2]], dtype=array_api_strict.int64) + >>> y.shape + (1, 2) + + The following is equivalent to ``x[:, xp.newaxis]``: + + >>> y = xpx.expand_dims(x, axis=1, xp=xp) + >>> y + Array([[1], + [2]], dtype=array_api_strict.int64) + >>> y.shape + (2, 1) + + ``axis`` may also be a tuple: + + >>> y = xpx.expand_dims(x, axis=(0, 1), xp=xp) + >>> y + Array([[[1, 2]]], dtype=array_api_strict.int64) + + >>> y = xpx.expand_dims(x, axis=(2, 0), xp=xp) + >>> y + Array([[[1], + [2]]], dtype=array_api_strict.int64) + """ + if xp is None: + xp = array_namespace(a) + + if not isinstance(axis, tuple): + axis = (axis,) + ndim = a.ndim + len(axis) + if axis != () and (min(axis) < -ndim or max(axis) >= ndim): + err_msg = ( + f"a provided axis position is out of bounds for array of dimension {a.ndim}" + ) + raise IndexError(err_msg) + axis = tuple(dim % ndim for dim in axis) + if len(set(axis)) != len(axis): + err_msg = "Duplicate dimensions specified in `axis`." + raise ValueError(err_msg) + + if is_numpy_namespace(xp) or is_dask_namespace(xp) or is_jax_namespace(xp): + return xp.expand_dims(a, axis=axis) + + return _funcs.expand_dims(a, axis=axis, xp=xp) + + +def isclose( + a: Array | complex, + b: Array | complex, + *, + rtol: float = 1e-05, + atol: float = 1e-08, + equal_nan: bool = False, + xp: ModuleType | None = None, +) -> Array: + """ + Return a boolean array where two arrays are element-wise equal within a tolerance. + + The tolerance values are positive, typically very small numbers. The relative + difference ``(rtol * abs(b))`` and the absolute difference `atol` are added together + to compare against the absolute difference between `a` and `b`. + + NaNs are treated as equal if they are in the same place and if ``equal_nan=True``. + Infs are treated as equal if they are in the same place and of the same sign in both + arrays. + + Parameters + ---------- + a, b : Array | int | float | complex | bool + Input objects to compare. At least one must be an array. + rtol : array_like, optional + The relative tolerance parameter (see Notes). + atol : array_like, optional + The absolute tolerance parameter (see Notes). + equal_nan : bool, optional + Whether to compare NaN's as equal. If True, NaN's in `a` will be considered + equal to NaN's in `b` in the output array. + xp : array_namespace, optional + The standard-compatible namespace for `a` and `b`. Default: infer. + + Returns + ------- + Array + A boolean array of shape broadcasted from `a` and `b`, containing ``True`` where + `a` is close to `b`, and ``False`` otherwise. + + Warnings + -------- + The default `atol` is not appropriate for comparing numbers with magnitudes much + smaller than one (see notes). + + See Also + -------- + math.isclose : Similar function in stdlib for Python scalars. + + Notes + ----- + For finite values, `isclose` uses the following equation to test whether two + floating point values are equivalent:: + + absolute(a - b) <= (atol + rtol * absolute(b)) + + Unlike the built-in `math.isclose`, + the above equation is not symmetric in `a` and `b`, + so that ``isclose(a, b)`` might be different from ``isclose(b, a)`` in some rare + cases. + + The default value of `atol` is not appropriate when the reference value `b` has + magnitude smaller than one. For example, it is unlikely that ``a = 1e-9`` and + ``b = 2e-9`` should be considered "close", yet ``isclose(1e-9, 2e-9)`` is ``True`` + with default settings. Be sure to select `atol` for the use case at hand, especially + for defining the threshold below which a non-zero value in `a` will be considered + "close" to a very small or zero value in `b`. + + The comparison of `a` and `b` uses standard broadcasting, which means that `a` and + `b` need not have the same shape in order for ``isclose(a, b)`` to evaluate to + ``True``. + + `isclose` is not defined for non-numeric data types. + ``bool`` is considered a numeric data-type for this purpose. + """ + xp = array_namespace(a, b) if xp is None else xp + + if ( + is_numpy_namespace(xp) + or is_cupy_namespace(xp) + or is_dask_namespace(xp) + or is_jax_namespace(xp) + ): + return xp.isclose(a, b, rtol=rtol, atol=atol, equal_nan=equal_nan) + + if is_torch_namespace(xp): + a, b = asarrays(a, b, xp=xp) # Array API 2024.12 support + return xp.isclose(a, b, rtol=rtol, atol=atol, equal_nan=equal_nan) + + return _funcs.isclose(a, b, rtol=rtol, atol=atol, equal_nan=equal_nan, xp=xp) + + +def nan_to_num( + x: Array | float | complex, + /, + *, + fill_value: int | float = 0.0, + xp: ModuleType | None = None, +) -> Array: + """ + Replace NaN with zero and infinity with large finite numbers (default behaviour). + + If `x` is inexact, NaN is replaced by zero or by the user defined value in the + `fill_value` keyword, infinity is replaced by the largest finite floating + point value representable by ``x.dtype``, and -infinity is replaced by the + most negative finite floating point value representable by ``x.dtype``. + + For complex dtypes, the above is applied to each of the real and + imaginary components of `x` separately. + + Parameters + ---------- + x : array | float | complex + Input data. + fill_value : int | float, optional + Value to be used to fill NaN values. If no value is passed + then NaN values will be replaced with 0.0. + xp : array_namespace, optional + The standard-compatible namespace for `x`. Default: infer. + + Returns + ------- + array + `x`, with the non-finite values replaced. + + See Also + -------- + array_api.isnan : Shows which elements are Not a Number (NaN). + + Examples + -------- + >>> import array_api_extra as xpx + >>> import array_api_strict as xp + >>> xpx.nan_to_num(xp.inf) + 1.7976931348623157e+308 + >>> xpx.nan_to_num(-xp.inf) + -1.7976931348623157e+308 + >>> xpx.nan_to_num(xp.nan) + 0.0 + >>> x = xp.asarray([xp.inf, -xp.inf, xp.nan, -128, 128]) + >>> xpx.nan_to_num(x) + array([ 1.79769313e+308, -1.79769313e+308, 0.00000000e+000, # may vary + -1.28000000e+002, 1.28000000e+002]) + >>> y = xp.asarray([complex(xp.inf, xp.nan), xp.nan, complex(xp.nan, xp.inf)]) + array([ 1.79769313e+308, -1.79769313e+308, 0.00000000e+000, # may vary + -1.28000000e+002, 1.28000000e+002]) + >>> xpx.nan_to_num(y) + array([ 1.79769313e+308 +0.00000000e+000j, # may vary + 0.00000000e+000 +0.00000000e+000j, + 0.00000000e+000 +1.79769313e+308j]) + """ + if isinstance(fill_value, complex): + msg = "Complex fill values are not supported." + raise TypeError(msg) + + xp = array_namespace(x) if xp is None else xp + + # for scalars we want to output an array + y = xp.asarray(x) + + if ( + is_cupy_namespace(xp) + or is_jax_namespace(xp) + or is_numpy_namespace(xp) + or is_torch_namespace(xp) + ): + return xp.nan_to_num(y, nan=fill_value) + + return _funcs.nan_to_num(y, fill_value=fill_value, xp=xp) + + +def one_hot( + x: Array, + /, + num_classes: int, + *, + dtype: DType | None = None, + axis: int = -1, + xp: ModuleType | None = None, +) -> Array: + """ + One-hot encode the given indices. + + Each index in the input `x` is encoded as a vector of zeros of length `num_classes` + with the element at the given index set to one. + + Parameters + ---------- + x : array + An array with integral dtype whose values are between `0` and `num_classes - 1`. + num_classes : int + Number of classes in the one-hot dimension. + dtype : DType, optional + The dtype of the return value. Defaults to the default float dtype (usually + float64). + axis : int, optional + Position in the expanded axes where the new axis is placed. Default: -1. + xp : array_namespace, optional + The standard-compatible namespace for `x`. Default: infer. + + Returns + ------- + array + An array having the same shape as `x` except for a new axis at the position + given by `axis` having size `num_classes`. If `axis` is unspecified, it + defaults to -1, which appends a new axis. + + If ``x < 0`` or ``x >= num_classes``, then the result is undefined, may raise + an exception, or may even cause a bad state. `x` is not checked. + + Examples + -------- + >>> import array_api_extra as xpx + >>> import array_api_strict as xp + >>> xpx.one_hot(xp.asarray([1, 2, 0]), 3) + Array([[0., 1., 0.], + [0., 0., 1.], + [1., 0., 0.]], dtype=array_api_strict.float64) + """ + # Validate inputs. + if xp is None: + xp = array_namespace(x) + if not xp.isdtype(x.dtype, "integral"): + msg = "x must have an integral dtype." + raise TypeError(msg) + if dtype is None: + dtype = _funcs.default_dtype(xp, device=get_device(x)) + # Delegate where possible. + if is_jax_namespace(xp): + from jax.nn import one_hot as jax_one_hot + + return jax_one_hot(x, num_classes, dtype=dtype, axis=axis) + if is_torch_namespace(xp): + from torch.nn.functional import one_hot as torch_one_hot + + x = xp.astype(x, xp.int64) # PyTorch only supports int64 here. + try: + out = torch_one_hot(x, num_classes) + except RuntimeError as e: + raise IndexError from e + else: + out = _funcs.one_hot(x, num_classes, xp=xp) + out = xp.astype(out, dtype, copy=False) + if axis != -1: + out = xp.moveaxis(out, -1, axis) + return out + + +def pad( + x: Array, + pad_width: int | tuple[int, int] | Sequence[tuple[int, int]], + mode: Literal["constant"] = "constant", + *, + constant_values: complex = 0, + xp: ModuleType | None = None, +) -> Array: + """ + Pad the input array. + + Parameters + ---------- + x : array + Input array. + pad_width : int or tuple of ints or sequence of pairs of ints + Pad the input array with this many elements from each side. + If a sequence of tuples, ``[(before_0, after_0), ... (before_N, after_N)]``, + each pair applies to the corresponding axis of ``x``. + A single tuple, ``(before, after)``, is equivalent to a list of ``x.ndim`` + copies of this tuple. + mode : str, optional + Only "constant" mode is currently supported, which pads with + the value passed to `constant_values`. + constant_values : python scalar, optional + Use this value to pad the input. Default is zero. + xp : array_namespace, optional + The standard-compatible namespace for `x`. Default: infer. + + Returns + ------- + array + The input array, + padded with ``pad_width`` elements equal to ``constant_values``. + """ + xp = array_namespace(x) if xp is None else xp + + if mode != "constant": + msg = "Only `'constant'` mode is currently supported" + raise NotImplementedError(msg) + + if ( + is_numpy_namespace(xp) + or is_cupy_namespace(xp) + or is_jax_namespace(xp) + or is_pydata_sparse_namespace(xp) + ): + return xp.pad(x, pad_width, mode, constant_values=constant_values) + + # https://github.com/pytorch/pytorch/blob/cf76c05b4dc629ac989d1fb8e789d4fac04a095a/torch/_numpy/_funcs_impl.py#L2045-L2056 + if is_torch_namespace(xp): + pad_width = xp.asarray(pad_width) + pad_width = xp.broadcast_to(pad_width, (x.ndim, 2)) + pad_width = xp.flip(pad_width, axis=(0,)).flatten() + return xp.nn.functional.pad(x, tuple(pad_width), value=constant_values) # type: ignore[arg-type] # pyright: ignore[reportArgumentType] + + return _funcs.pad(x, pad_width, constant_values=constant_values, xp=xp) + + +def searchsorted( + x1: Array, + x2: Array, + /, + *, + side: Literal["left", "right"] = "left", + xp: ModuleType | None = None, +) -> Array: + """ + Find indices where elements should be inserted to maintain order. + + Find the indices into a sorted array ``x1`` such that if the elements in ``x2`` + were inserted before the indices, the resulting array would remain sorted. + + The behavior of this function is similar to that of `array_api.searchsorted`, + but it relaxes the requirement that `x1` must be one-dimensional. + This function is vectorized, treating slices along the last axis + as elements and preceding axes as batch (or "loop") dimensions. + + Parameters + ---------- + x1 : Array + Input array. Should have a real-valued data type. Must be sorted in ascending + order along the last axis. + x2 : Array + Array containing search values. Should have a real-valued data type. Must have + the same shape as ``x1`` except along the last axis. + side : {'left', 'right'}, optional + Argument controlling which index is returned if an element of ``x2`` is equal to + one or more elements of ``x1``: ``'left'`` returns the index of the first of + these elements; ``'right'`` returns the next index after the last of these + elements. Default: ``'left'``. + xp : array_namespace, optional + The standard-compatible namespace for the array arguments. Default: infer. + + Returns + ------- + Array: integer array + An array of indices with the same shape as ``x2``. + + Examples + -------- + >>> import array_api_strict as xp + >>> import array_api_extra as xpx + >>> x = xp.asarray([11, 12, 13, 13, 14, 15]) + >>> xpx.searchsorted(x, xp.asarray([10, 11.5, 14.5, 16]), xp=xp) + Array([0, 1, 5, 6], dtype=array_api_strict.int64) + >>> xpx.searchsorted(x, xp.asarray(13), xp=xp) + Array(2, dtype=array_api_strict.int64) + >>> xpx.searchsorted(x, xp.asarray(13), side='right', xp=xp) + Array(4, dtype=array_api_strict.int64) + + `searchsorted` is vectorized along the last axis. + + >>> x1 = xp.asarray([[1., 2., 3., 4.], [5., 6., 7., 8.]]) + >>> x2 = xp.asarray([[1.1, 3.3], [6.6, 8.8]]) + >>> xpx.searchsorted(x1, x2, xp=xp) + Array([[1, 3], + [2, 4]], dtype=array_api_strict.int64) + """ + if xp is None: + xp = array_namespace(x1, x2) + + if side not in {"left", "right"}: + message = "`side` must be either 'left' or 'right'." + raise ValueError(message) + + xp_default_int = _funcs.default_dtype(xp, kind="integral") + x2_0d = x2.ndim == 0 + x1_1d = x1.ndim <= 1 + + if x1_1d or is_torch_namespace(xp): + x2 = xp.reshape(x2, ()) if (x2_0d and x1_1d) else x2 + out = xp.searchsorted(x1, x2, side=side) + return xp.astype(out, xp_default_int, copy=False) + + return _funcs.searchsorted(x1, x2, side=side, xp=xp) + + +def setdiff1d( + x1: Array | complex, + x2: Array | complex, + /, + *, + assume_unique: bool = False, + xp: ModuleType | None = None, +) -> Array: + """ + Find the set difference of two arrays. + + Return the unique values in `x1` that are not in `x2`. + + Parameters + ---------- + x1 : array | int | float | complex | bool + Input array. + x2 : array + Input comparison array. + assume_unique : bool + If ``True``, the input arrays are both assumed to be unique, which + can speed up the calculation. Default is ``False``. + xp : array_namespace, optional + The standard-compatible namespace for `x1` and `x2`. Default: infer. + + Returns + ------- + array + 1D array of values in `x1` that are not in `x2`. The result + is sorted when `assume_unique` is ``False``, but otherwise only sorted + if the input is sorted. + + Examples + -------- + >>> import array_api_strict as xp + >>> import array_api_extra as xpx + + >>> x1 = xp.asarray([1, 2, 3, 2, 4, 1]) + >>> x2 = xp.asarray([3, 4, 5, 6]) + >>> xpx.setdiff1d(x1, x2, xp=xp) + Array([1, 2], dtype=array_api_strict.int64) + """ + + if xp is None: + xp = array_namespace(x1, x2) + + if is_numpy_namespace(xp) or is_cupy_namespace(xp) or is_jax_namespace(xp): + x1, x2 = asarrays(x1, x2, xp=xp) + return xp.setdiff1d(x1, x2, assume_unique=assume_unique) + + return _funcs.setdiff1d(x1, x2, assume_unique=assume_unique, xp=xp) + + +def sinc(x: Array, /, *, xp: ModuleType | None = None) -> Array: + r""" + Return the normalized sinc function. + + The sinc function is equal to :math:`\sin(\pi x)/(\pi x)` for any argument + :math:`x\ne 0`. ``sinc(0)`` takes the limit value 1, making ``sinc`` not + only everywhere continuous but also infinitely differentiable. + + .. note:: + + Note the normalization factor of ``pi`` used in the definition. + This is the most commonly used definition in signal processing. + Use ``sinc(x / xp.pi)`` to obtain the unnormalized sinc function + :math:`\sin(x)/x` that is more common in mathematics. + + Parameters + ---------- + x : array + Array (possibly multi-dimensional) of values for which to calculate + ``sinc(x)``. Must have a real floating point dtype. + xp : array_namespace, optional + The standard-compatible namespace for `x`. Default: infer. + + Returns + ------- + array + ``sinc(x)`` calculated elementwise, which has the same shape as the input. + + Notes + ----- + The name sinc is short for "sine cardinal" or "sinus cardinalis". + + The sinc function is used in various signal processing applications, + including in anti-aliasing, in the construction of a Lanczos resampling + filter, and in interpolation. + + For bandlimited interpolation of discrete-time signals, the ideal + interpolation kernel is proportional to the sinc function. + + References + ---------- + #. Weisstein, Eric W. "Sinc Function." From MathWorld--A Wolfram Web + Resource. https://mathworld.wolfram.com/SincFunction.html + #. Wikipedia, "Sinc function", + https://en.wikipedia.org/wiki/Sinc_function + + Examples + -------- + >>> import array_api_strict as xp + >>> import array_api_extra as xpx + >>> x = xp.linspace(-4, 4, 41) + >>> xpx.sinc(x, xp=xp) + Array([-3.89817183e-17, -4.92362781e-02, + -8.40918587e-02, -8.90384387e-02, + -5.84680802e-02, 3.89817183e-17, + 6.68206631e-02, 1.16434881e-01, + 1.26137788e-01, 8.50444803e-02, + -3.89817183e-17, -1.03943254e-01, + -1.89206682e-01, -2.16236208e-01, + -1.55914881e-01, 3.89817183e-17, + 2.33872321e-01, 5.04551152e-01, + 7.56826729e-01, 9.35489284e-01, + 1.00000000e+00, 9.35489284e-01, + 7.56826729e-01, 5.04551152e-01, + 2.33872321e-01, 3.89817183e-17, + -1.55914881e-01, -2.16236208e-01, + -1.89206682e-01, -1.03943254e-01, + -3.89817183e-17, 8.50444803e-02, + 1.26137788e-01, 1.16434881e-01, + 6.68206631e-02, 3.89817183e-17, + -5.84680802e-02, -8.90384387e-02, + -8.40918587e-02, -4.92362781e-02, + -3.89817183e-17], dtype=array_api_strict.float64) + """ + + if xp is None: + xp = array_namespace(x) + + if not xp.isdtype(x.dtype, "real floating"): + err_msg = "`x` must have a real floating data type." + raise ValueError(err_msg) + + if ( + is_numpy_namespace(xp) + or is_cupy_namespace(xp) + or is_jax_namespace(xp) + or is_torch_namespace(xp) + or is_dask_namespace(xp) + ): + return xp.sinc(x) + + return _funcs.sinc(x, xp=xp) + + +def partition( + a: Array, + kth: int, + /, + axis: int | None = -1, + *, + xp: ModuleType | None = None, +) -> Array: + """ + Return a partitioned copy of an array. + + Creates a copy of the array and partially sorts it in such a way that the value + of the element in k-th position is in the position it would be in a sorted array. + In the output array, all elements smaller than the k-th element are located to + the left of this element and all equal or greater are located to its right. + The ordering of the elements in the two partitions on the either side of + the k-th element in the output array is undefined. + + Parameters + ---------- + a : Array + Input array. + kth : int + Element index to partition by. + axis : int, optional + Axis along which to partition. The default is ``-1`` (the last axis). + If ``None``, the flattened array is used. + xp : array_namespace, optional + The standard-compatible namespace for `x`. Default: infer. + + Returns + ------- + partitioned_array + Array of the same type and shape as `a`. + + Notes + ----- + If `xp` implements ``partition`` or an equivalent function + (e.g. ``topk`` for torch), complexity will likely be O(n). + If not, this function simply calls ``xp.sort`` and complexity is O(n log n). + """ + # Validate inputs. + if xp is None: + xp = array_namespace(a) + if a.ndim < 1: + msg = "`a` must be at least 1-dimensional" + raise TypeError(msg) + if axis is None: + return partition(xp.reshape(a, (-1,)), kth, axis=0, xp=xp) + (size,) = eager_shape(a, axis) + if not (0 <= kth < size): + msg = f"kth(={kth}) out of bounds [0 {size})" + raise ValueError(msg) + + # Delegate where possible. + if is_numpy_namespace(xp) or is_cupy_namespace(xp) or is_jax_namespace(xp): + return xp.partition(a, kth, axis=axis) + + # Use top-k when possible: + if is_torch_namespace(xp): + if not (axis == -1 or axis == a.ndim - 1): + a = xp.transpose(a, axis, -1) + + out = xp.empty_like(a) + ranks = xp.arange(a.shape[-1]).expand_as(a) + + split_value, indices = xp.kthvalue(a, kth + 1, keepdim=True) + del indices # indices won't be used => del ASAP to reduce peak memory usage + + # fill the left-side of the partition + mask_src = a < split_value + n_left = mask_src.sum(dim=-1, keepdim=True) + mask_dest = ranks < n_left + out[mask_dest] = a[mask_src] + + # fill the middle of the partition + mask_src = a == split_value + n_left += mask_src.sum(dim=-1, keepdim=True) + mask_dest ^= ranks < n_left + out[mask_dest] = a[mask_src] + + # fill the right-side of the partition + mask_src = a > split_value + mask_dest = ranks >= n_left + out[mask_dest] = a[mask_src] + + if not (axis == -1 or axis == a.ndim - 1): + out = xp.transpose(out, axis, -1) + return out + + # Note: dask topk/argtopk sort the return values, so it's + # not much more efficient than sorting everything when + # kth is not small compared to x.size + + return _funcs.partition(a, kth, axis=axis, xp=xp) + + +def argpartition( + a: Array, + kth: int, + /, + axis: int | None = -1, + *, + xp: ModuleType | None = None, +) -> Array: + """ + Perform an indirect partition along the given axis. + + It returns an array of indices of the same shape as `a` that + index data along the given axis in partitioned order. + + Parameters + ---------- + a : Array + Input array. + kth : int + Element index to partition by. + axis : int, optional + Axis along which to partition. The default is ``-1`` (the last axis). + If ``None``, the flattened array is used. + xp : array_namespace, optional + The standard-compatible namespace for `x`. Default: infer. + + Returns + ------- + index_array + Array of indices that partition `a` along the specified axis. + + Notes + ----- + If `xp` implements ``argpartition`` or an equivalent function + e.g. ``topk`` for torch), complexity will likely be O(n). + If not, this function simply calls ``xp.argsort`` and complexity is O(n log n). + """ + # Validate inputs. + if xp is None: + xp = array_namespace(a) + if is_pydata_sparse_namespace(xp): + msg = "Not implemented for sparse backend: no argsort" + raise NotImplementedError(msg) + if a.ndim < 1: + msg = "`a` must be at least 1-dimensional" + raise TypeError(msg) + if axis is None: + return argpartition(xp.reshape(a, (-1,)), kth, axis=0, xp=xp) + (size,) = eager_shape(a, axis) + if not (0 <= kth < size): + msg = f"kth(={kth}) out of bounds [0 {size})" + raise ValueError(msg) + + # Delegate where possible. + if is_numpy_namespace(xp) or is_cupy_namespace(xp) or is_jax_namespace(xp): + return xp.argpartition(a, kth, axis=axis) + + # Use top-k when possible: + if is_torch_namespace(xp): + # see `partition` above for commented details of those steps: + if not (axis == -1 or axis == a.ndim - 1): + a = xp.transpose(a, axis, -1) + + ranks = xp.arange(a.shape[-1]).expand_as(a) + out = xp.empty_like(ranks) + + split_value, indices = xp.kthvalue(a, kth + 1, keepdim=True) + del indices # indices won't be used => del ASAP to reduce peak memory usage + + mask_src = a < split_value + n_left = mask_src.sum(dim=-1, keepdim=True) + mask_dest = ranks < n_left + out[mask_dest] = ranks[mask_src] + + mask_src = a == split_value + n_left += mask_src.sum(dim=-1, keepdim=True) + mask_dest ^= ranks < n_left + out[mask_dest] = ranks[mask_src] + + mask_src = a > split_value + mask_dest = ranks >= n_left + out[mask_dest] = ranks[mask_src] + + if not (axis == -1 or axis == a.ndim - 1): + out = xp.transpose(out, axis, -1) + return out + + # Note: dask topk/argtopk sort the return values, so it's + # not much more efficient than sorting everything when + # kth is not small compared to x.size + + return _funcs.argpartition(a, kth, axis=axis, xp=xp) + + +def isin( + a: Array, + b: Array, + /, + *, + assume_unique: bool = False, + invert: bool = False, + kind: str | None = None, + xp: ModuleType | None = None, +) -> Array: + """ + Determine whether each element in `a` is present in `b`. + + Return a boolean array of the same shape as `a` that is True for elements + that are in `b` and False otherwise. + + Parameters + ---------- + a : array + Input elements. + b : array + The elements against which to test each element of `a`. + assume_unique : bool, optional + If True, the input arrays are both assumed to be unique which can speed + up the calculation. Default: False. + invert : bool, optional + If True, the values in the returned array are inverted. Default: False. + kind : str | None, optional + The algorithm or method to use. This will not affect the final result, + but will affect the speed and memory use. + For NumPy the options are {None, "sort", "table"}. + For Jax the mapped parameter is instead `method` and the options are + {"compare_all", "binary_search", "sort", and "auto" (default)} + For CuPy, Dask, Torch and the default case this parameter is not present and + thus ignored. Default: None. + xp : array_namespace, optional + The standard-compatible namespace for `a` and `b`. Default: infer. + + Returns + ------- + array + An array having the same shape as that of `a` that is True for elements + that are in `b` and False otherwise. + """ + if xp is None: + xp = array_namespace(a, b) + + if is_numpy_namespace(xp): + return xp.isin(a, b, assume_unique=assume_unique, invert=invert, kind=kind) + if is_jax_namespace(xp): + if kind is None: + kind = "auto" + return xp.isin(a, b, assume_unique=assume_unique, invert=invert, method=kind) + if is_cupy_namespace(xp) or is_torch_namespace(xp) or is_dask_namespace(xp): + return xp.isin(a, b, assume_unique=assume_unique, invert=invert) + + return _funcs.isin(a, b, assume_unique=assume_unique, invert=invert, xp=xp) + + +def union1d(a: Array, b: Array, /, *, xp: ModuleType | None = None) -> Array: + """ + Find the union of two arrays. + + Return the unique, sorted array of values that are in either of the two + input arrays. + + Parameters + ---------- + a, b : Array + Input arrays. They are flattened internally if they are not already 1D. + + xp : array_namespace, optional + The standard-compatible namespace for `a` and `b`. Default: infer. + + Returns + ------- + Array + Unique, sorted union of the input arrays. + + See Also + -------- + jax.numpy.union1d : Corresponding function in JAX. + + Notes + ----- + This function is not compatible with `jax.jit`. + See the docstring of the corresponding JAX function for more information. + """ + if xp is None: + xp = array_namespace(a, b) + + if ( + is_numpy_namespace(xp) + or is_cupy_namespace(xp) + or is_dask_namespace(xp) + or is_jax_namespace(xp) + ): + return xp.union1d(a, b) + + return _funcs.union1d(a, b, xp=xp) diff --git a/.venv/lib/python3.12/site-packages/scipy/_external/array_api_extra/_lib/__init__.py b/.venv/lib/python3.12/site-packages/scipy/_external/array_api_extra/_lib/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..d7b3203346da0006f89216d15670be62452d8571 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/scipy/_external/array_api_extra/_lib/__init__.py @@ -0,0 +1 @@ +"""Internals of array-api-extra.""" diff --git a/.venv/lib/python3.12/site-packages/scipy/_external/array_api_extra/_lib/__pycache__/__init__.cpython-312.pyc b/.venv/lib/python3.12/site-packages/scipy/_external/array_api_extra/_lib/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..04b68ae9a573d6773b8e7f56641f7532dccb7a70 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/scipy/_external/array_api_extra/_lib/__pycache__/__init__.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/scipy/_external/array_api_extra/_lib/__pycache__/_at.cpython-312.pyc b/.venv/lib/python3.12/site-packages/scipy/_external/array_api_extra/_lib/__pycache__/_at.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..eed1f555089463d390586dd510ae04fd833120c7 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/scipy/_external/array_api_extra/_lib/__pycache__/_at.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/scipy/_external/array_api_extra/_lib/__pycache__/_funcs.cpython-312.pyc b/.venv/lib/python3.12/site-packages/scipy/_external/array_api_extra/_lib/__pycache__/_funcs.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..95b0a1bf1210c006bfef1521f9682a3fb9031ad6 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/scipy/_external/array_api_extra/_lib/__pycache__/_funcs.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/scipy/_external/array_api_extra/_lib/__pycache__/_lazy.cpython-312.pyc b/.venv/lib/python3.12/site-packages/scipy/_external/array_api_extra/_lib/__pycache__/_lazy.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8ec864aaf6b911ca6a1225654611793ffc3cadd9 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/scipy/_external/array_api_extra/_lib/__pycache__/_lazy.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/scipy/_external/array_api_extra/_lib/_at.py b/.venv/lib/python3.12/site-packages/scipy/_external/array_api_extra/_lib/_at.py new file mode 100644 index 0000000000000000000000000000000000000000..e654ba7ad5ee2fe962cfb2bf45e6ff02a654add0 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/scipy/_external/array_api_extra/_lib/_at.py @@ -0,0 +1,463 @@ +"""Update operations for read-only arrays.""" + +from __future__ import annotations + +import operator +from collections.abc import Callable +from enum import Enum +from types import ModuleType +from typing import TYPE_CHECKING, ClassVar, cast + +from ._utils import _compat +from ._utils._compat import ( + array_namespace, + is_dask_array, + is_jax_array, + is_torch_array, + is_writeable_array, +) +from ._utils._helpers import meta_namespace +from ._utils._typing import Array, SetIndex + +if TYPE_CHECKING: # pragma: no cover + # TODO import from typing (requires Python >=3.11) + from typing import Self + + +class _AtOp(Enum): + """Operations for use in `xpx.at`.""" + + SET = "set" + ADD = "add" + SUBTRACT = "subtract" + MULTIPLY = "multiply" + DIVIDE = "divide" + POWER = "power" + MIN = "min" + MAX = "max" + + # @override from Python 3.12 + def __str__(self) -> str: # pyright: ignore[reportImplicitOverride] + """ + Return string representation (useful for pytest logs). + + Returns + ------- + str + The operation's name. + """ + return self.value + + +class Undef(Enum): + """Sentinel for undefined values.""" + + UNDEF = 0 + + +_undef = Undef.UNDEF + + +class at: # pylint: disable=invalid-name # numpydoc ignore=PR02 + """ + Update operations for read-only arrays. + + This implements ``jax.numpy.ndarray.at`` for all writeable + backends (those that support ``__setitem__``) and routes + to the ``.at[]`` method for JAX arrays. + + Parameters + ---------- + x : array + Input array. + idx : index, optional + Only `array API standard compliant indices + `_ + are supported. + + You may use two alternate syntaxes:: + + >>> import array_api_extra as xpx + >>> xpx.at(x, idx).set(value) # or add(value), etc. + >>> xpx.at(x)[idx].set(value) + + copy : bool, optional + None (default) + The array parameter *may* be modified in place if it is + possible and beneficial for performance. + You should not reuse it after calling this function. + True + Ensure that the inputs are not modified. + False + Ensure that the update operation writes back to the input. + Raise ``ValueError`` if a copy cannot be avoided. + + xp : array_namespace, optional + The standard-compatible namespace for `x`. Default: infer. + + Returns + ------- + Updated input array. + + Warnings + -------- + (a) When you omit the ``copy`` parameter, you should never reuse the parameter + array later on; ideally, you should reassign it immediately:: + + >>> import array_api_extra as xpx + >>> x = xpx.at(x, 0).set(2) + + The above best practice pattern ensures that the behaviour won't change depending + on whether ``x`` is writeable or not, as the original ``x`` object is dereferenced + as soon as ``xpx.at`` returns; this way there is no risk to accidentally update it + twice. + + On the reverse, the anti-pattern below must be avoided, as it will result in + different behaviour on read-only versus writeable arrays:: + + >>> x = xp.asarray([0, 0, 0]) + >>> y = xpx.at(x, 0).set(2) + >>> z = xpx.at(x, 1).set(3) + + In the above example, both calls to ``xpx.at`` update ``x`` in place *if possible*. + This causes the behaviour to diverge depending on whether ``x`` is writeable or not: + + - If ``x`` is writeable, then after the snippet above you'll have + ``x == y == z == [2, 3, 0]`` + - If ``x`` is read-only, then you'll end up with + ``x == [0, 0, 0]``, ``y == [2, 0, 0]`` and ``z == [0, 3, 0]``. + + The correct pattern to use if you want diverging outputs from the same input is + to enforce copies:: + + >>> x = xp.asarray([0, 0, 0]) + >>> y = xpx.at(x, 0).set(2, copy=True) # Never updates x + >>> z = xpx.at(x, 1).set(3) # May or may not update x in place + >>> del x # avoid accidental reuse of x as we don't know its state anymore + + (b) The array API standard does not support integer array indices. + The behaviour of update methods when the index is an array of integers is + undefined and will vary between backends; this is particularly true when the + index contains multiple occurrences of the same index, e.g.:: + + >>> import numpy as np + >>> import jax.numpy as jnp + >>> import array_api_extra as xpx + >>> xpx.at(np.asarray([123]), np.asarray([0, 0])).add(1) + array([124]) + >>> xpx.at(jnp.asarray([123]), jnp.asarray([0, 0])).add(1) + Array([125], dtype=int32) + + See Also + -------- + jax.numpy.ndarray.at : Equivalent array method in JAX. + + Notes + ----- + `sparse `_, as well as read-only arrays from libraries + not explicitly covered by ``array-api-compat``, are not supported by update + methods. + + Boolean masks are supported on Dask and jitted JAX arrays exclusively + when `idx` has the same shape as `x` and `y` is 0-dimensional. + Note that this support is not available in JAX's native + ``x.at[mask].set(y)``. + + This pattern:: + + >>> mask = m(x) + >>> x[mask] = f(x[mask]) + + Can't be replaced by `at`, as it won't work on Dask and JAX inside jax.jit:: + + >>> mask = m(x) + >>> x = xpx.at(x, mask).set(f(x[mask]) # Crash on Dask and jax.jit + + You should instead use:: + + >>> x = xp.where(m(x), f(x), x) + + Examples + -------- + Given either of these equivalent expressions:: + + >>> import array_api_extra as xpx + >>> x = xpx.at(x)[1].add(2) + >>> x = xpx.at(x, 1).add(2) + + If x is a JAX array, they are the same as:: + + >>> x = x.at[1].add(2) + + If x is a read-only NumPy array, they are the same as:: + + >>> x = x.copy() + >>> x[1] += 2 + + For other known backends, they are the same as:: + + >>> x[1] += 2 + """ + + _x: Array + _idx: SetIndex | Undef + __slots__: ClassVar[tuple[str, ...]] = ("_idx", "_x") + + def __init__( + self, x: Array, idx: SetIndex | Undef = _undef, / + ) -> None: # numpydoc ignore=GL08 + self._x = x + self._idx = idx + + def __getitem__(self, idx: SetIndex, /) -> Self: # numpydoc ignore=PR01,RT01 + """ + Allow for the alternate syntax ``at(x)[start:stop:step]``. + + It looks prettier than ``at(x, slice(start, stop, step))`` + and feels more intuitive coming from the JAX documentation. + """ + if self._idx is not _undef: + msg = "Index has already been set" + raise ValueError(msg) + return type(self)(self._x, idx) + + def _op( + self, + at_op: _AtOp, + in_place_op: Callable[[Array, Array | complex], Array] | None, + out_of_place_op: Callable[[Array, Array], Array] | None, + y: Array | complex, + /, + copy: bool | None, + xp: ModuleType | None, + ) -> Array: + """ + Implement all update operations. + + Parameters + ---------- + at_op : _AtOp + Method of JAX's Array.at[]. + in_place_op : Callable[[Array, Array | complex], Array] | None + In-place operation to apply on mutable backends:: + + x[idx] = in_place_op(x[idx], y) + + If None:: + + x[idx] = y + + out_of_place_op : Callable[[Array, Array], Array] | None + Out-of-place operation to apply when idx is a boolean mask and the backend + doesn't support in-place updates:: + + x = xp.where(idx, out_of_place_op(x, y), x) + + If None:: + + x = xp.where(idx, y, x) + + y : array or complex + Right-hand side of the operation. + copy : bool or None + Whether to copy the input array. See the class docstring for details. + xp : array_namespace, optional + The array namespace for the input array. Default: infer. + + Returns + ------- + Array + Updated `x`. + """ + from ._funcs import apply_where # pylint: disable=cyclic-import + + x, idx = self._x, self._idx + xp = array_namespace(x, y) if xp is None else xp + + if isinstance(idx, Undef): + msg = ( + "Index has not been set.\n" + "Usage: either\n" + " at(x, idx).set(value)\n" + "or\n" + " at(x)[idx].set(value)\n" + "(same for all other methods)." + ) + raise ValueError(msg) + + if copy not in (True, False, None): + msg = f"copy must be True, False, or None; got {copy!r}" + raise ValueError(msg) + + writeable = None if copy else is_writeable_array(x) + + # JAX inside jax.jit doesn't support in-place updates with boolean + # masks; Dask exclusively supports __setitem__ but not iops. + # We can handle the common special case of 0-dimensional y + # with where(idx, y, x) instead. + if ( + (is_dask_array(idx) or is_jax_array(idx)) + and idx.dtype == xp.bool + and idx.shape == x.shape + ): + y_xp = xp.asarray(y, dtype=x.dtype, device=_compat.device(x)) + if y_xp.ndim == 0: + if out_of_place_op: # add(), subtract(), ... + # suppress inf warnings on Dask + out = apply_where( + idx, (x, y_xp), out_of_place_op, fill_value=x, xp=xp + ) + # Undo int->float promotion on JAX after _AtOp.DIVIDE + out = xp.astype(out, x.dtype, copy=False) + else: # set() + out = xp.where(idx, y_xp, x) + + if copy is False: + x[()] = out + return x + return out + + # else: this will work on eager JAX and crash on jax.jit and Dask + + if copy or (copy is None and not writeable): + if is_jax_array(x): + # Use JAX's at[] + func = cast( + Callable[[Array | complex], Array], + getattr(x.at[idx], at_op.value), # type: ignore[attr-defined] # pyright: ignore[reportAttributeAccessIssue,reportUnknownArgumentType] + ) + out = func(y) + # Undo int->float promotion on JAX after _AtOp.DIVIDE + return xp.astype(out, x.dtype, copy=False) + + # Emulate at[] behaviour for non-JAX arrays + # with a copy followed by an update + + x = xp.asarray(x, copy=True) + # A copy of a read-only numpy array is writeable + # Note: this assumes that a copy of a writeable array is writeable + assert not writeable + writeable = None + + if writeable is None: + writeable = is_writeable_array(x) + if not writeable: + # sparse crashes here + msg = f"Can't update read-only array {x}" + raise ValueError(msg) + + # Work around bug in PyTorch where __setitem__ doesn't + # always support mismatched dtypes + # https://github.com/pytorch/pytorch/issues/150017 + if is_torch_array(y): + y = xp.astype(y, x.dtype, copy=False) + + # Backends without boolean indexing (other than JAX) crash here + if in_place_op: # add(), subtract(), ... + x[idx] = in_place_op(x[idx], y) + else: # set() + x[idx] = y + return x + + def set( + self, + y: Array | complex, + /, + copy: bool | None = None, + xp: ModuleType | None = None, + ) -> Array: # numpydoc ignore=PR01,RT01 + """Apply ``x[idx] = y`` and return the update array.""" + return self._op(_AtOp.SET, None, None, y, copy=copy, xp=xp) + + def add( + self, + y: Array | complex, + /, + copy: bool | None = None, + xp: ModuleType | None = None, + ) -> Array: # numpydoc ignore=PR01,RT01 + """Apply ``x[idx] += y`` and return the updated array.""" + + # Note for this and all other methods based on _iop: + # operator.iadd and operator.add subtly differ in behaviour, as + # only iadd will trigger exceptions when y has an incompatible dtype. + return self._op(_AtOp.ADD, operator.iadd, operator.add, y, copy=copy, xp=xp) + + def subtract( + self, + y: Array | complex, + /, + copy: bool | None = None, + xp: ModuleType | None = None, + ) -> Array: # numpydoc ignore=PR01,RT01 + """Apply ``x[idx] -= y`` and return the updated array.""" + return self._op( + _AtOp.SUBTRACT, operator.isub, operator.sub, y, copy=copy, xp=xp + ) + + def multiply( + self, + y: Array | complex, + /, + copy: bool | None = None, + xp: ModuleType | None = None, + ) -> Array: # numpydoc ignore=PR01,RT01 + """Apply ``x[idx] *= y`` and return the updated array.""" + return self._op( + _AtOp.MULTIPLY, operator.imul, operator.mul, y, copy=copy, xp=xp + ) + + def divide( + self, + y: Array | complex, + /, + copy: bool | None = None, + xp: ModuleType | None = None, + ) -> Array: # numpydoc ignore=PR01,RT01 + """Apply ``x[idx] /= y`` and return the updated array.""" + return self._op( + _AtOp.DIVIDE, operator.itruediv, operator.truediv, y, copy=copy, xp=xp + ) + + def power( + self, + y: Array | complex, + /, + copy: bool | None = None, + xp: ModuleType | None = None, + ) -> Array: # numpydoc ignore=PR01,RT01 + """Apply ``x[idx] **= y`` and return the updated array.""" + return self._op(_AtOp.POWER, operator.ipow, operator.pow, y, copy=copy, xp=xp) + + def min( + self, + y: Array | complex, + /, + copy: bool | None = None, + xp: ModuleType | None = None, + ) -> Array: # numpydoc ignore=PR01,RT01 + """Apply ``x[idx] = minimum(x[idx], y)`` and return the updated array.""" + # On Dask, this function runs on the chunks, so we need to determine the + # namespace that Dask is wrapping. + # Note that da.minimum _incidentally_ works on NumPy, CuPy, and sparse + # thanks to all these meta-namespaces implementing the __array_ufunc__ + # interface, but there's no guarantee that it will work for other + # wrapped libraries in the future. + xp = array_namespace(self._x) if xp is None else xp + mxp = meta_namespace(self._x, xp=xp) + y = xp.asarray(y) + return self._op(_AtOp.MIN, mxp.minimum, mxp.minimum, y, copy=copy, xp=xp) + + def max( + self, + y: Array | complex, + /, + copy: bool | None = None, + xp: ModuleType | None = None, + ) -> Array: # numpydoc ignore=PR01,RT01 + """Apply ``x[idx] = maximum(x[idx], y)`` and return the updated array.""" + # See note on min() + xp = array_namespace(self._x) if xp is None else xp + mxp = meta_namespace(self._x, xp=xp) + y = xp.asarray(y) + return self._op(_AtOp.MAX, mxp.maximum, mxp.maximum, y, copy=copy, xp=xp) diff --git a/.venv/lib/python3.12/site-packages/scipy/_external/array_api_extra/_lib/_backends.py b/.venv/lib/python3.12/site-packages/scipy/_external/array_api_extra/_lib/_backends.py new file mode 100644 index 0000000000000000000000000000000000000000..b4fed5dfb28fd6e435a6705e24e5be0c083f2547 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/scipy/_external/array_api_extra/_lib/_backends.py @@ -0,0 +1,72 @@ +"""Backends against which array-api-extra runs its tests.""" + +from __future__ import annotations + +from enum import Enum +from typing import Any + +import numpy as np +import pytest + +__all__ = ["NUMPY_VERSION", "Backend"] + +NUMPY_VERSION = tuple(int(v) for v in np.__version__.split(".")[:3]) + + +class Backend(Enum): # numpydoc ignore=PR02 + """ + All array library backends explicitly tested by array-api-extra. + + Parameters + ---------- + value : str + Tag of the backend's module, in the format ``[:]``. + """ + + # Use : to prevent Enum from deduplicating items with the same value + ARRAY_API_STRICT = "array_api_strict" + ARRAY_API_STRICTEST = "array_api_strict:strictest" + NUMPY = "numpy" + NUMPY_READONLY = "numpy:readonly" + CUPY = "cupy" + TORCH = "torch" + TORCH_GPU = "torch:gpu" + DASK = "dask.array" + SPARSE = "sparse" + JAX = "jax.numpy" + JAX_GPU = "jax.numpy:gpu" + + @property + def modname(self) -> str: # numpydoc ignore=RT01 + """Module name to be imported.""" + return self.value.split(":")[0] + + def like(self, *others: Backend) -> bool: # numpydoc ignore=PR01,RT01 + """Check if this backend uses the same module as others.""" + return any(self.modname == other.modname for other in others) + + def pytest_param(self) -> Any: + """ + Backend as a pytest parameter + + Returns + ------- + pytest.mark.ParameterSet + """ + id_ = ( + self.name.lower().replace("_gpu", ":gpu").replace("_readonly", ":readonly") + ) + + marks = [] + if self.like(Backend.ARRAY_API_STRICT): + marks.append( + pytest.mark.skipif( + NUMPY_VERSION < (1, 26), + reason="array_api_strict is untested on NumPy <1.26", + ) + ) + if self.like(Backend.DASK, Backend.JAX): + # Monkey-patched by lazy_xp_function + marks.append(pytest.mark.thread_unsafe) + + return pytest.param(self, id=id_, marks=marks) # pyright: ignore[reportUnknownArgumentType] diff --git a/.venv/lib/python3.12/site-packages/scipy/_external/array_api_extra/_lib/_funcs.py b/.venv/lib/python3.12/site-packages/scipy/_external/array_api_extra/_lib/_funcs.py new file mode 100644 index 0000000000000000000000000000000000000000..aea44a0de4b0bfc0a9e6a7a416cac4355756d304 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/scipy/_external/array_api_extra/_lib/_funcs.py @@ -0,0 +1,820 @@ +"""Array-agnostic implementations for the public API.""" + +import math +import warnings +from collections.abc import Callable, Sequence +from types import ModuleType, NoneType +from typing import Literal, cast, overload + +from ._at import at +from ._utils import _compat, _helpers +from ._utils._compat import ( + array_namespace, + is_dask_namespace, + is_jax_array, +) +from ._utils._helpers import ( + asarrays, + capabilities, + eager_shape, + meta_namespace, + ndindex, +) +from ._utils._typing import Array, Device, DType + +__all__ = [ + "apply_where", + "atleast_nd", + "broadcast_shapes", + "cov", + "create_diagonal", + "expand_dims", + "kron", + "nunique", + "pad", + "searchsorted", + "setdiff1d", + "sinc", +] + + +@overload +def apply_where( # numpydoc ignore=GL08 + cond: Array, + args: Array | tuple[Array, ...], + f1: Callable[..., Array], + f2: Callable[..., Array], + /, + *, + kwargs: dict[str, Array] | None = None, + xp: ModuleType | None = None, +) -> Array: ... + + +@overload +def apply_where( # numpydoc ignore=GL08 + cond: Array, + args: Array | tuple[Array, ...], + f1: Callable[..., Array], + /, + *, + fill_value: Array | complex, + kwargs: dict[str, Array] | None = None, + xp: ModuleType | None = None, +) -> Array: ... + + +def apply_where( # numpydoc ignore=PR01,PR02 + cond: Array, + args: Array | tuple[Array, ...], + f1: Callable[..., Array], + f2: Callable[..., Array] | None = None, + /, + *, + fill_value: Array | complex | None = None, + kwargs: dict[str, Array] | None = None, + xp: ModuleType | None = None, +) -> Array: + """ + Run one of two elementwise functions depending on a condition. + + Equivalent to ``f1(*args) if cond else fill_value`` performed elementwise + when `fill_value` is defined, otherwise to ``f1(*args) if cond else f2(*args)``. + + Parameters + ---------- + cond : array + The condition, expressed as a boolean array. + args : Array or tuple of Arrays + Argument(s) to `f1` (and `f2`). Must be broadcastable with `cond`. + f1 : callable + Elementwise function of `args`, returning a single array. + Where `cond` is True, output will be ``f1(arg0[cond], arg1[cond], ...)``. + f2 : callable, optional + Elementwise function of `args`, returning a single array. + Where `cond` is False, output will be ``f2(arg0[cond], arg1[cond], ...)``. + Mutually exclusive with `fill_value`. + fill_value : Array or scalar, optional + If provided, value with which to fill output array where `cond` is False. + It does not need to be scalar; it needs however to be broadcastable with + `cond` and `args`. + Mutually exclusive with `f2`. You must provide one or the other. + kwargs : dict of str : Array pairs + Keyword argument(s) to `f1` (and `f2`). Values must be broadcastable with + `cond`. + xp : array_namespace, optional + The standard-compatible namespace for `cond` and `args`. Default: infer. + + Returns + ------- + Array + An array with elements from the output of `f1` where `cond` is True and either + the output of `f2` or `fill_value` where `cond` is False. The returned array has + data type determined by type promotion rules between the output of `f1` and + either `fill_value` or the output of `f2`. + + Notes + ----- + ``xp.where(cond, f1(*args), f2(*args))`` requires explicitly evaluating `f1` even + when `cond` is False, and `f2` when cond is True. This function evaluates each + function only for their matching condition, if the backend allows for it. + + On Dask, `f1` and `f2` are applied to the individual chunks and should use functions + from the namespace of the chunks. + + Examples + -------- + >>> import array_api_strict as xp + >>> import array_api_extra as xpx + >>> a = xp.asarray([5, 4, 3]) + >>> b = xp.asarray([0, 2, 2]) + >>> def f(a, b): + ... return a // b + >>> xpx.apply_where(b != 0, (a, b), f, fill_value=xp.nan) + array([ nan, 2., 1.]) + """ + # Parse and normalize arguments + if (f2 is None) == (fill_value is None): + msg = "Exactly one of `fill_value` or `f2` must be given." + raise TypeError(msg) + args_ = list(args) if isinstance(args, tuple) else [args] + del args + + kwargs_ = {} if kwargs is None else kwargs + kwkeys = list(kwargs_.keys()) + args_ = [*args_, *kwargs_.values()] + del kwargs + + xp = array_namespace(cond, fill_value, *args_) if xp is None else xp + + if isinstance(fill_value, int | float | complex | NoneType): + cond, *args_ = xp.broadcast_arrays(cond, *args_) + else: + cond, fill_value, *args_ = xp.broadcast_arrays(cond, fill_value, *args_) + + if is_dask_namespace(xp): + meta_xp = meta_namespace(cond, fill_value, *args_, xp=xp) + # map_blocks doesn't descend into tuples of Arrays + return xp.map_blocks( + _apply_where, cond, f1, f2, fill_value, *args_, kwkeys=kwkeys, xp=meta_xp + ) + + return _apply_where(cond, f1, f2, fill_value, *args_, kwkeys=kwkeys, xp=xp) + + +def _apply_where( # numpydoc ignore=PR01,RT01 + cond: Array, + f1: Callable[..., Array], + f2: Callable[..., Array] | None, + fill_value: Array | int | float | complex | bool | None, + *args: Array, + kwkeys: list[str], + xp: ModuleType, +) -> Array: + """Helper of `apply_where`. On Dask, this runs on a single chunk.""" + + nargs = len(args) - len(kwkeys) + kwargs = dict(zip(kwkeys, args[nargs:], strict=True)) + args = args[:nargs] + + if not capabilities(xp, device=_compat.device(cond))["boolean indexing"]: + # jax.jit does not support assignment by boolean mask + return xp.where( + cond, + f1(*args, **kwargs), + f2(*args, **kwargs) if f2 is not None else fill_value, + ) + + temp1 = f1( + *(arr[cond] for arr in args), **{key: val[cond] for key, val in kwargs.items()} + ) + + if f2 is None: + dtype = xp.result_type(temp1, fill_value) + if isinstance(fill_value, int | float | complex): + out = xp.full_like(cond, dtype=dtype, fill_value=fill_value) + else: + out = xp.astype(fill_value, dtype, copy=True) + else: + ncond = ~cond + temp2 = f2( + *(arr[ncond] for arr in args), + **{key: val[ncond] for key, val in kwargs.items()}, + ) + dtype = xp.result_type(temp1, temp2) + out = xp.empty_like(cond, dtype=dtype) + out = at(out, ncond).set(temp2) + + return at(out, cond).set(temp1) + + +def atleast_nd(x: Array, /, *, ndim: int, xp: ModuleType) -> Array: + # numpydoc ignore=PR01,RT01 + """See docstring in array_api_extra._delegation.""" + + if x.ndim < ndim: + x = xp.expand_dims(x, axis=0) + x = atleast_nd(x, ndim=ndim, xp=xp) + return x + + +# `float` in signature to accept `math.nan` for Dask. +# `int`s are still accepted as `float` is a superclass of `int` in typing +def broadcast_shapes(*shapes: tuple[float | None, ...]) -> tuple[int | None, ...]: + """ + Compute the shape of the broadcasted arrays. + + Duplicates :func:`numpy.broadcast_shapes`, with additional support for + None and NaN sizes. + + This is equivalent to ``xp.broadcast_arrays(arr1, arr2, ...)[0].shape`` + without needing to worry about the backend potentially deep copying + the arrays. + + Parameters + ---------- + *shapes : tuple[int | None, ...] + Shapes of the arrays to broadcast. + + Returns + ------- + tuple[int | None, ...] + The shape of the broadcasted arrays. + + See Also + -------- + numpy.broadcast_shapes : Equivalent NumPy function. + array_api.broadcast_arrays : Function to broadcast actual arrays. + + Notes + ----- + This function accepts the Array API's ``None`` for unknown sizes, + as well as Dask's non-standard ``math.nan``. + Regardless of input, the output always contains ``None`` for unknown sizes. + + Examples + -------- + >>> import array_api_extra as xpx + >>> xpx.broadcast_shapes((2, 3), (2, 1)) + (2, 3) + >>> xpx.broadcast_shapes((4, 2, 3), (2, 1), (1, 3)) + (4, 2, 3) + """ + if not shapes: + return () # Match NumPy output + + ndim = max(len(shape) for shape in shapes) + out: list[int | None] = [] + for axis in range(-ndim, 0): + sizes = {shape[axis] for shape in shapes if axis >= -len(shape)} + # Dask uses NaN for unknown shape, which predates the Array API spec for None + none_size = None in sizes or math.nan in sizes # noqa: PLW0177 + sizes -= {1, None, math.nan} + if len(sizes) > 1: + msg = ( + "shape mismatch: objects cannot be broadcast to a single shape: " + f"{shapes}." + ) + raise ValueError(msg) + out.append(None if none_size else cast(int, sizes.pop()) if sizes else 1) + + return tuple(out) + + +def cov(m: Array, /, *, xp: ModuleType) -> Array: # numpydoc ignore=PR01,RT01 + """See docstring in array_api_extra._delegation.""" + m = xp.asarray(m, copy=True) + dtype = ( + xp.float64 if xp.isdtype(m.dtype, "integral") else xp.result_type(m, xp.float64) + ) + + m = atleast_nd(m, ndim=2, xp=xp) + m = xp.astype(m, dtype) + + avg = _helpers.mean(m, axis=-1, keepdims=True, xp=xp) + + m_shape = eager_shape(m) + fact = m_shape[-1] - 1 + + if fact <= 0: + warnings.warn("Degrees of freedom <= 0 for slice", RuntimeWarning, stacklevel=2) + fact = 0 + + m -= avg + m_transpose = xp.matrix_transpose(m) + if xp.isdtype(m_transpose.dtype, "complex floating"): + m_transpose = xp.conj(m_transpose) + c = xp.matmul(m, m_transpose) + c /= fact + axes = tuple(axis for axis, length in enumerate(c.shape) if length == 1) + return xp.squeeze(c, axis=axes) + + +def one_hot( + x: Array, + /, + num_classes: int, + *, + xp: ModuleType, +) -> Array: # numpydoc ignore=PR01,RT01 + """See docstring in `array_api_extra._delegation.py`.""" + # TODO: Benchmark whether this is faster on the NumPy backend: + # if is_numpy_array(x): + # out = xp.zeros((x.size, num_classes), dtype=dtype) + # out[xp.arange(x.size), xp.reshape(x, (-1,))] = 1 + # return xp.reshape(out, (*x.shape, num_classes)) + range_num_classes = xp.arange(num_classes, dtype=x.dtype, device=_compat.device(x)) + return x[..., xp.newaxis] == range_num_classes + + +def create_diagonal( + x: Array, /, *, offset: int = 0, xp: ModuleType +) -> Array: # numpydoc ignore=PR01,RT01 + """See docstring in array_api_extra._delegation.""" + x_shape = eager_shape(x) + batch_dims = x_shape[:-1] + n = x_shape[-1] + abs(offset) + diag = xp.zeros((*batch_dims, n**2), dtype=x.dtype, device=_compat.device(x)) + + target_slice = slice( + offset if offset >= 0 else abs(offset) * n, + min(n * (n - offset), diag.shape[-1]), + n + 1, + ) + for index in ndindex(*batch_dims): + diag = at(diag)[(*index, target_slice)].set(x[(*index, slice(None))]) + return xp.reshape(diag, (*batch_dims, n, n)) + + +def default_dtype( + xp: ModuleType, + kind: Literal[ + "real floating", "complex floating", "integral", "indexing" + ] = "real floating", + *, + device: Device | None = None, +) -> DType: + """ + Return the default dtype for the given namespace and device. + + This is a convenience shorthand for + ``xp.__array_namespace_info__().default_dtypes(device=device)[kind]``. + + Parameters + ---------- + xp : array_namespace + The standard-compatible namespace for which to get the default dtype. + kind : {'real floating', 'complex floating', 'integral', 'indexing'}, optional + The kind of dtype to return. Default is 'real floating'. + device : Device, optional + The device for which to get the default dtype. Default: current device. + + Returns + ------- + dtype + The default dtype for the given namespace, kind, and device. + """ + dtypes = xp.__array_namespace_info__().default_dtypes(device=device) + try: + return dtypes[kind] + except KeyError as e: + domain = ("real floating", "complex floating", "integral", "indexing") + assert set(dtypes) == set(domain), f"Non-compliant namespace: {dtypes}" + msg = f"Unknown kind '{kind}'. Expected one of {domain}." + raise ValueError(msg) from e + + +def expand_dims(a: Array, /, *, axis: tuple[int, ...] = (0,), xp: ModuleType) -> Array: + # numpydoc ignore=PR01,RT01 + """See docstring in array_api_extra._delegation.""" + for i in sorted(axis): + a = xp.expand_dims(a, axis=i) + return a + + +def isclose( + a: Array | complex, + b: Array | complex, + *, + rtol: float = 1e-05, + atol: float = 1e-08, + equal_nan: bool = False, + xp: ModuleType, +) -> Array: # numpydoc ignore=PR01,RT01 + """See docstring in array_api_extra._delegation.""" + a, b = asarrays(a, b, xp=xp) + + a_inexact = xp.isdtype(a.dtype, ("real floating", "complex floating")) + b_inexact = xp.isdtype(b.dtype, ("real floating", "complex floating")) + if a_inexact or b_inexact: + # prevent warnings on NumPy and Dask on inf - inf + mxp = meta_namespace(a, b, xp=xp) + out = apply_where( + xp.isinf(a) | xp.isinf(b), + (a, b), + lambda a, b: mxp.isinf(a) & mxp.isinf(b) & (mxp.sign(a) == mxp.sign(b)), # pyright: ignore[reportUnknownArgumentType] + # Note: inf <= inf is True! + lambda a, b: mxp.abs(a - b) <= (atol + rtol * mxp.abs(b)), # pyright: ignore[reportUnknownArgumentType] + xp=xp, + ) + if equal_nan: + out = xp.where(xp.isnan(a) & xp.isnan(b), True, out) + return out + + if xp.isdtype(a.dtype, "bool") or xp.isdtype(b.dtype, "bool"): + if atol >= 1 or rtol >= 1: + return xp.ones_like(a == b) + return a == b + + # integer types + atol = int(atol) + if rtol == 0: + return xp.abs(a - b) <= atol + + # Don't rely on OverflowError, as it is not guaranteed by the Array API. + nrtol = int(1.0 / rtol) + if nrtol > xp.iinfo(b.dtype).max: + # rtol * max_int < 1, so it's inconsequential + return xp.abs(a - b) <= atol + return xp.abs(a - b) <= (atol + xp.abs(b) // nrtol) + + +def kron( + a: Array | complex, + b: Array | complex, + /, + *, + xp: ModuleType | None = None, +) -> Array: + """ + Kronecker product of two arrays. + + Computes the Kronecker product, a composite array made of blocks of the + second array scaled by the first. + + Equivalent to ``numpy.kron`` for NumPy arrays. + + Parameters + ---------- + a, b : Array | int | float | complex + Input arrays or scalars. At least one must be an array. + xp : array_namespace, optional + The standard-compatible namespace for `a` and `b`. Default: infer. + + Returns + ------- + array + The Kronecker product of `a` and `b`. + + Notes + ----- + The function assumes that the number of dimensions of `a` and `b` + are the same, if necessary prepending the smallest with ones. + If ``a.shape = (r0,r1,..,rN)`` and ``b.shape = (s0,s1,...,sN)``, + the Kronecker product has shape ``(r0*s0, r1*s1, ..., rN*SN)``. + The elements are products of elements from `a` and `b`, organized + explicitly by:: + + kron(a,b)[k0,k1,...,kN] = a[i0,i1,...,iN] * b[j0,j1,...,jN] + + where:: + + kt = it * st + jt, t = 0,...,N + + In the common 2-D case (N=1), the block structure can be visualized:: + + [[ a[0,0]*b, a[0,1]*b, ... , a[0,-1]*b ], + [ ... ... ], + [ a[-1,0]*b, a[-1,1]*b, ... , a[-1,-1]*b ]] + + Examples + -------- + >>> import array_api_strict as xp + >>> import array_api_extra as xpx + >>> xpx.kron(xp.asarray([1, 10, 100]), xp.asarray([5, 6, 7]), xp=xp) + Array([ 5, 6, 7, 50, 60, 70, 500, + 600, 700], dtype=array_api_strict.int64) + + >>> xpx.kron(xp.asarray([5, 6, 7]), xp.asarray([1, 10, 100]), xp=xp) + Array([ 5, 50, 500, 6, 60, 600, 7, + 70, 700], dtype=array_api_strict.int64) + + >>> xpx.kron(xp.eye(2), xp.ones((2, 2)), xp=xp) + Array([[1., 1., 0., 0.], + [1., 1., 0., 0.], + [0., 0., 1., 1.], + [0., 0., 1., 1.]], dtype=array_api_strict.float64) + + >>> a = xp.reshape(xp.arange(100), (2, 5, 2, 5)) + >>> b = xp.reshape(xp.arange(24), (2, 3, 4)) + >>> c = xpx.kron(a, b, xp=xp) + >>> c.shape + (2, 10, 6, 20) + >>> I = (1, 3, 0, 2) + >>> J = (0, 2, 1) + >>> J1 = (0,) + J # extend to ndim=4 + >>> S1 = (1,) + b.shape + >>> K = tuple(xp.asarray(I) * xp.asarray(S1) + xp.asarray(J1)) + >>> c[K] == a[I]*b[J] + Array(True, dtype=array_api_strict.bool) + """ + if xp is None: + xp = array_namespace(a, b) + a, b = asarrays(a, b, xp=xp) + + singletons = (1,) * (b.ndim - a.ndim) + a = cast(Array, xp.broadcast_to(a, singletons + a.shape)) + + nd_b, nd_a = b.ndim, a.ndim + nd_max = max(nd_b, nd_a) + if nd_a == 0 or nd_b == 0: + return xp.multiply(a, b) + + a_shape = eager_shape(a) + b_shape = eager_shape(b) + + # Equalise the shapes by prepending smaller one with 1s + a_shape = (1,) * max(0, nd_b - nd_a) + a_shape + b_shape = (1,) * max(0, nd_a - nd_b) + b_shape + + # Insert empty dimensions + a_arr = expand_dims(a, axis=tuple(range(nd_b - nd_a)), xp=xp) + b_arr = expand_dims(b, axis=tuple(range(nd_a - nd_b)), xp=xp) + + # Compute the product + a_arr = expand_dims(a_arr, axis=tuple(range(1, nd_max * 2, 2)), xp=xp) + b_arr = expand_dims(b_arr, axis=tuple(range(0, nd_max * 2, 2)), xp=xp) + result = xp.multiply(a_arr, b_arr) + + # Reshape back and return + res_shape = tuple(a_s * b_s for a_s, b_s in zip(a_shape, b_shape, strict=True)) + return xp.reshape(result, res_shape) + + +def nan_to_num( # numpydoc ignore=PR01,RT01 + x: Array, + /, + fill_value: int | float = 0.0, + *, + xp: ModuleType, +) -> Array: + """See docstring in `array_api_extra._delegation.py`.""" + + def perform_replacements( # numpydoc ignore=PR01,RT01 + x: Array, + fill_value: int | float, + xp: ModuleType, + ) -> Array: + """Internal function to perform the replacements.""" + x = xp.where(xp.isnan(x), fill_value, x) + + # convert infinities to finite values + finfo = xp.finfo(x.dtype) + idx_posinf = xp.isinf(x) & ~xp.signbit(x) + idx_neginf = xp.isinf(x) & xp.signbit(x) + x = xp.where(idx_posinf, finfo.max, x) + return xp.where(idx_neginf, finfo.min, x) + + if xp.isdtype(x.dtype, "complex floating"): + return perform_replacements( + xp.real(x), + fill_value, + xp, + ) + 1j * perform_replacements( + xp.imag(x), + fill_value, + xp, + ) + + if xp.isdtype(x.dtype, "numeric"): + return perform_replacements(x, fill_value, xp) + + return x + + +def nunique(x: Array, /, *, xp: ModuleType | None = None) -> Array: + """ + Count the number of unique elements in an array. + + Compatible with JAX and Dask, whose laziness would be otherwise + problematic. + + Parameters + ---------- + x : Array + Input array. + xp : array_namespace, optional + The standard-compatible namespace for `x`. Default: infer. + + Returns + ------- + array: 0-dimensional integer array + The number of unique elements in `x`. It can be lazy. + """ + if xp is None: + xp = array_namespace(x) + + if is_jax_array(x): + # size= is JAX-specific + # https://github.com/data-apis/array-api/issues/883 + _, counts = xp.unique_counts(x, size=_compat.size(x)) + return (counts > 0).sum() + + # There are 3 general use cases: + # 1. backend has unique_counts and it returns an array with known shape + # 2. backend has unique_counts and it returns a None-sized array; + # e.g. Dask, ndonnx + # 3. backend does not have unique_counts; e.g. wrapped JAX + if capabilities(xp, device=_compat.device(x))["data-dependent shapes"]: + # xp has unique_counts; O(n) complexity + _, counts = xp.unique_counts(x) + n = _compat.size(counts) + if n is None: + return xp.sum(xp.ones_like(counts)) + return xp.asarray(n, device=_compat.device(x)) + + # xp does not have unique_counts; O(n*logn) complexity + x = xp.reshape(x, (-1,)) + x = xp.sort(x, stable=False) + mask = x != xp.roll(x, -1) + default_int = default_dtype(xp, "integral", device=_compat.device(x)) + return xp.maximum( + # Special cases: + # - array is size 0 + # - array has all elements equal to each other + xp.astype(xp.any(~mask), default_int), + xp.sum(xp.astype(mask, default_int)), + ) + + +def pad( + x: Array, + pad_width: int | tuple[int, int] | Sequence[tuple[int, int]], + *, + constant_values: complex = 0, + xp: ModuleType, +) -> Array: # numpydoc ignore=PR01,RT01 + """See docstring in `array_api_extra._delegation.py`.""" + # make pad_width a list of length-2 tuples of ints + if isinstance(pad_width, int): + pad_width_seq = [(pad_width, pad_width)] * x.ndim + elif ( + isinstance(pad_width, tuple) + and len(pad_width) == 2 + and all(isinstance(i, int) for i in pad_width) + ): + pad_width_seq = [cast(tuple[int, int], pad_width)] * x.ndim + else: + pad_width_seq = cast(list[tuple[int, int]], list(pad_width)) + + slices: list[slice] = [] + newshape: list[int] = [] + for ax, w_tpl in enumerate(pad_width_seq): + if len(w_tpl) != 2: + msg = f"expect a 2-tuple (before, after), got {w_tpl}." + raise ValueError(msg) + + sh = eager_shape(x)[ax] + + if w_tpl[0] == 0 and w_tpl[1] == 0: + sl = slice(None, None, None) + else: + stop: int | None + start, stop = w_tpl + stop = None if stop == 0 else -stop + + sl = slice(start, stop, None) + sh += w_tpl[0] + w_tpl[1] + + newshape.append(sh) + slices.append(sl) + + padded = xp.full( + tuple(newshape), + fill_value=constant_values, + dtype=x.dtype, + device=_compat.device(x), + ) + return at(padded, tuple(slices)).set(x) + + +def searchsorted( + x1: Array, + x2: Array, + /, + *, + side: Literal["left", "right"] = "left", + xp: ModuleType, +) -> Array: + # numpydoc ignore=PR01,RT01 + """See docstring in `array_api_extra._delegation.py`.""" + a = xp.full(x2.shape, 0, device=_compat.device(x1)) + + if x1.shape[-1] == 0: + return a + + n = xp.count_nonzero(~xp.isnan(x1), axis=-1, keepdims=True) + b = xp.broadcast_to(n, x2.shape) + + compare = xp.less_equal if side == "left" else xp.less + + # while xp.any(b - a > 1): + # refactored to for loop with ~log2(n) iterations for JAX JIT + for _ in range(int(math.log2(x1.shape[-1])) + 1): # type: ignore[arg-type] # pyright: ignore[reportArgumentType] + c = (a + b) // 2 + x0 = xp.take_along_axis(x1, c, axis=-1) + j = compare(x2, x0) + b = xp.where(j, c, b) + a = xp.where(j, a, c) + + out = xp.where(compare(x2, xp.min(x1, axis=-1, keepdims=True)), 0, b) + out = xp.where(xp.isnan(x2), x1.shape[-1], out) if side == "right" else out + return xp.astype(out, default_dtype(xp, kind="integral"), copy=False) + + +def setdiff1d( + x1: Array | complex, + x2: Array | complex, + /, + *, + assume_unique: bool = False, + xp: ModuleType, +) -> Array: # numpydoc ignore=PR01,RT01 + """See docstring in `array_api_extra._delegation.py`.""" + + # https://github.com/microsoft/pyright/issues/10103 + x1_, x2_ = asarrays(x1, x2, xp=xp) + + if assume_unique: + x1_ = xp.reshape(x1_, (-1,)) + x2_ = xp.reshape(x2_, (-1,)) + else: + x1_ = xp.unique_values(x1_) + x2_ = xp.unique_values(x2_) + + return x1_[_helpers.in1d(x1_, x2_, assume_unique=True, invert=True, xp=xp)] + + +def sinc(x: Array, /, *, xp: ModuleType) -> Array: + # numpydoc ignore=PR01,RT01 + """See docstring in `array_api_extra._delegation.py`.""" + + # no scalars in `where` - array-api#807 + y = xp.pi * xp.where( + xp.astype(x, xp.bool), + x, + xp.asarray(xp.finfo(x.dtype).eps, dtype=x.dtype, device=_compat.device(x)), + ) + return xp.sin(y) / y + + +def partition( # numpydoc ignore=PR01,RT01 + x: Array, + kth: int, # noqa: ARG001 + /, + axis: int = -1, + *, + xp: ModuleType, +) -> Array: + """See docstring in `array_api_extra._delegation.py`.""" + return xp.sort(x, axis=axis, stable=False) + + +def argpartition( # numpydoc ignore=PR01,RT01 + x: Array, + kth: int, # noqa: ARG001 + /, + axis: int = -1, + *, + xp: ModuleType, +) -> Array: + """See docstring in `array_api_extra._delegation.py`.""" + return xp.argsort(x, axis=axis, stable=False) + + +def isin( # numpydoc ignore=PR01,RT01 + a: Array, + b: Array, + /, + *, + assume_unique: bool = False, + invert: bool = False, + xp: ModuleType, +) -> Array: + """See docstring in `array_api_extra._delegation.py`.""" + original_a_shape = a.shape + a = xp.reshape(a, (-1,)) + b = xp.reshape(b, (-1,)) + return xp.reshape( + _helpers.in1d(a, b, assume_unique=assume_unique, invert=invert, xp=xp), + original_a_shape, + ) + + +def union1d(a: Array, b: Array, /, *, xp: ModuleType) -> Array: + # numpydoc ignore=PR01,RT01 + """See docstring in `array_api_extra._delegation.py`.""" + a = xp.reshape(a, (-1,)) + b = xp.reshape(b, (-1,)) + # XXX: `sparse` returns NumPy arrays from `unique_values` + return xp.asarray(xp.unique_values(xp.concat([a, b]))) diff --git a/.venv/lib/python3.12/site-packages/scipy/_external/array_api_extra/_lib/_lazy.py b/.venv/lib/python3.12/site-packages/scipy/_external/array_api_extra/_lib/_lazy.py new file mode 100644 index 0000000000000000000000000000000000000000..d509500132a4b8886f5ccca93d7d6bd2aa25b4dc --- /dev/null +++ b/.venv/lib/python3.12/site-packages/scipy/_external/array_api_extra/_lib/_lazy.py @@ -0,0 +1,357 @@ +"""Public API Functions.""" + +from __future__ import annotations + +import math +from collections.abc import Callable, Sequence +from functools import partial, wraps +from types import ModuleType +from typing import TYPE_CHECKING, Any, ParamSpec, TypeAlias, cast, overload + +from ._funcs import broadcast_shapes +from ._utils import _compat +from ._utils._compat import ( + array_namespace, + is_dask_namespace, + is_jax_namespace, +) +from ._utils._helpers import is_python_scalar +from ._utils._typing import Array, DType + +if TYPE_CHECKING: # pragma: no cover + import numpy as np + from numpy.typing import ArrayLike + + NumPyObject: TypeAlias = np.ndarray[Any, Any] | np.generic +else: + # Sphinx hack + NumPyObject = Any + +P = ParamSpec("P") + + +@overload +def lazy_apply( # type: ignore[valid-type] + func: Callable[P, Array | ArrayLike], + *args: Array | complex | None, + shape: tuple[int | None, ...] | None = None, + dtype: DType | None = None, + as_numpy: bool = False, + xp: ModuleType | None = None, + **kwargs: P.kwargs, # pyright: ignore[reportGeneralTypeIssues] +) -> Array: ... # numpydoc ignore=GL08 + + +@overload +def lazy_apply( # type: ignore[valid-type] + func: Callable[P, Sequence[Array | ArrayLike]], + *args: Array | complex | None, + shape: Sequence[tuple[int | None, ...]], + dtype: Sequence[DType] | None = None, + as_numpy: bool = False, + xp: ModuleType | None = None, + **kwargs: P.kwargs, # pyright: ignore[reportGeneralTypeIssues] +) -> tuple[Array, ...]: ... # numpydoc ignore=GL08 + + +def lazy_apply( # type: ignore[valid-type] # numpydoc ignore=GL07,SA04 + func: Callable[P, Array | ArrayLike | Sequence[Array | ArrayLike]], + *args: Array | complex | None, + shape: tuple[int | None, ...] | Sequence[tuple[int | None, ...]] | None = None, + dtype: DType | Sequence[DType] | None = None, + as_numpy: bool = False, + xp: ModuleType | None = None, + **kwargs: P.kwargs, # pyright: ignore[reportGeneralTypeIssues] +) -> Array | tuple[Array, ...]: + """ + Lazily apply an eager function. + + If the backend of the input arrays is lazy, e.g. Dask or jitted JAX, the execution + of the function is delayed until the graph is materialized; if it's eager, the + function is executed immediately. + + Parameters + ---------- + func : callable + The function to apply. + + It must accept one or more array API compliant arrays as positional arguments. + If `as_numpy=True`, inputs are converted to NumPy before they are passed to + `func`. + It must return either a single array-like or a sequence of array-likes. + + `func` must be a pure function, i.e. without side effects, as depending on the + backend it may be executed more than once or never. + *args : Array | int | float | complex | bool | None + One or more Array API compliant arrays, Python scalars, or None's. + + If `as_numpy=True`, you need to be able to apply :func:`numpy.asarray` to + non-None args to convert them to NumPy; read notes below about specific + backends. + shape : tuple[int | None, ...] | Sequence[tuple[int | None, ...]], optional + Output shape or sequence of output shapes, one for each output of `func`. + Default: assume single output and broadcast shapes of the input arrays. + dtype : DType | Sequence[DType], optional + Output dtype or sequence of output dtypes, one for each output of `func`. + dtype(s) must belong to the same array namespace as the input arrays. + Default: infer the result type(s) from the input arrays. + as_numpy : bool, optional + If True, convert the input arrays to NumPy before passing them to `func`. + This is particularly useful to make NumPy-only functions, e.g. written in Cython + or Numba, work transparently with array API-compliant arrays. + Default: False. + xp : array_namespace, optional + The standard-compatible namespace for `args`. Default: infer. + **kwargs : Any, optional + Additional keyword arguments to pass verbatim to `func`. + They cannot contain Array objects. + + Returns + ------- + Array | tuple[Array, ...] + The result(s) of `func` applied to the input arrays, wrapped in the same + array namespace as the inputs. + If shape is omitted or a single `tuple[int | None, ...]`, return a single array. + Otherwise, return a tuple of arrays. + + Notes + ----- + JAX + This allows applying eager functions to jitted JAX arrays, which are lazy. + The function won't be applied until the JAX array is materialized. + When running inside ``jax.jit``, `shape` must be fully known, i.e. it cannot + contain any `None` elements. + + .. warning:: + + `func` must never raise inside ``jax.jit``, as the resulting behavior is + undefined. + + Using this with `as_numpy=False` is particularly useful to apply non-jittable + JAX functions to arrays on GPU devices. + If ``as_numpy=True``, the :doc:`jax:transfer_guard` may prevent arrays on a GPU + device from being transferred back to CPU. This is treated as an implicit + transfer. + + PyTorch, CuPy + If ``as_numpy=True``, these backends raise by default if you attempt to convert + arrays on a GPU device to NumPy. + + Sparse + If ``as_numpy=True``, by default sparse prevents implicit densification through + :func:`numpy.asarray`. `This safety mechanism can be disabled + `_. + + Dask + This allows applying eager functions to Dask arrays. + The Dask graph won't be computed until the user calls ``compute()`` or + ``persist()`` down the line. + + The function name will be prominently visible on the user-facing Dask + dashboard and on Prometheus metrics, so it is recommended for it to be + meaningful. + + `lazy_apply` doesn't know if `func` reduces along any axes; also, shape + changes are non-trivial in chunked Dask arrays. For these reasons, all inputs + will be rechunked into a single chunk. + + .. warning:: + + The whole operation needs to fit in memory all at once on a single worker. + + The outputs will also be returned as a single chunk and you should consider + rechunking them into smaller chunks afterwards. + + If you want to distribute the calculation across multiple workers, you + should use :func:`dask.array.map_blocks`, :func:`dask.array.map_overlap`, + :func:`dask.array.blockwise`, or a native Dask wrapper instead of + `lazy_apply`. + + Dask wrapping around other backends + If ``as_numpy=False``, `func` will receive in input eager arrays of the meta + namespace, as defined by the ``._meta`` attribute of the input Dask arrays. + The outputs of `func` will be wrapped by the meta namespace, and then wrapped + again by Dask. + + Raises + ------ + ValueError + When ``xp=jax.numpy``, the output `shape` is unknown (it contains ``None`` on + one or more axes) and this function was called inside ``jax.jit``. + RuntimeError + When ``xp=sparse`` and auto-densification is disabled. + Exception (backend-specific) + When the backend disallows implicit device to host transfers and the input + arrays are on a non-CPU device, e.g. on GPU. + + See Also + -------- + jax.transfer_guard + jax.pure_callback + dask.array.map_blocks + dask.array.map_overlap + dask.array.blockwise + """ + args_not_none = [arg for arg in args if arg is not None] + array_args = [arg for arg in args_not_none if not is_python_scalar(arg)] + if not array_args: + msg = "Must have at least one argument array" + raise ValueError(msg) + if xp is None: + xp = array_namespace(*args) + + # Normalize and validate shape and dtype + shapes: list[tuple[int | None, ...]] + dtypes: list[DType] + multi_output = False + + if shape is None: + shapes = [broadcast_shapes(*(arg.shape for arg in array_args))] + elif all(isinstance(s, int | None) for s in shape): + # Do not test for shape to be a tuple + # https://github.com/data-apis/array-api/issues/891#issuecomment-2637430522 + shapes = [cast(tuple[int | None, ...], shape)] + else: + shapes = list(shape) # type: ignore[arg-type] # pyright: ignore[reportAssignmentType] + multi_output = True + + if dtype is None: + dtypes = [xp.result_type(*args_not_none)] * len(shapes) + elif multi_output: + if not isinstance(dtype, Sequence): + msg = "Got multiple shapes but only one dtype" + raise ValueError(msg) + dtypes = list(dtype) # pyright: ignore[reportUnknownArgumentType] + else: + if isinstance(dtype, Sequence): + msg = "Got single shape but multiple dtypes" + raise ValueError(msg) + + dtypes = [dtype] + + if len(shapes) != len(dtypes): + msg = f"Got {len(shapes)} shapes and {len(dtypes)} dtypes" + raise ValueError(msg) + del shape + del dtype + # End of shape and dtype parsing + + # Backend-specific branches + if is_dask_namespace(xp): + import dask + + metas: list[Array] = [arg._meta for arg in array_args] # pylint: disable=protected-access # pyright: ignore[reportAttributeAccessIssue] + meta_xp = array_namespace(*metas) + + wrapped = dask.delayed( # type: ignore[attr-defined] # pyright: ignore[reportPrivateImportUsage] + _lazy_apply_wrapper(func, as_numpy, multi_output, meta_xp), + pure=True, + ) + # This finalizes each arg, which is the same as arg.rechunk(-1). + # Please read docstring above for why we're not using + # dask.array.map_blocks or dask.array.blockwise! + delayed_out = wrapped(*args, **kwargs) + + out = tuple( + xp.from_delayed( + delayed_out[i], # pyright: ignore[reportIndexIssue] + # Dask's unknown shapes diverge from the Array API specification + shape=tuple(math.nan if s is None else s for s in shape), + dtype=dtype, + meta=metas[0], + ) + for i, (shape, dtype) in enumerate(zip(shapes, dtypes, strict=True)) + ) + + elif is_jax_namespace(xp) and _is_jax_jit_enabled(xp): + # Delay calling func with jax.pure_callback, which will forward to func eager + # JAX arrays. Do not use jax.pure_callback when running outside of the JIT, + # as it does not support raising exceptions: + # https://github.com/jax-ml/jax/issues/26102 + import jax + + if any(None in shape for shape in shapes): + msg = "Output shape must be fully known when running inside jax.jit" + raise ValueError(msg) + + # Shield kwargs from being coerced into JAX arrays. + # jax.pure_callback calls jax.jit under the hood, but without the chance of + # passing static_argnames / static_argnums. + wrapped = _lazy_apply_wrapper( + partial(func, **kwargs), as_numpy, multi_output, xp + ) + + # suppress unused-ignore to run mypy in -e lint as well as -e dev + out = cast( # type: ignore[bad-cast,unused-ignore] + tuple[Array, ...], + jax.pure_callback( + wrapped, + tuple( + jax.ShapeDtypeStruct(shape, dtype) # pyright: ignore[reportUnknownArgumentType] + for shape, dtype in zip(shapes, dtypes, strict=True) + ), + *args, + ), + ) + + else: + # Eager backends, including non-jitted JAX + wrapped = _lazy_apply_wrapper(func, as_numpy, multi_output, xp) + out = wrapped(*args, **kwargs) + + return out if multi_output else out[0] + + +def _is_jax_jit_enabled(xp: ModuleType) -> bool: # numpydoc ignore=PR01,RT01 + """Return True if this function is being called inside ``jax.jit``.""" + import jax # pylint: disable=import-outside-toplevel + + x = xp.asarray(False) + try: + return bool(x) + except jax.errors.TracerBoolConversionError: + return True + + +def _lazy_apply_wrapper( # numpydoc ignore=PR01,RT01 + func: Callable[..., Array | ArrayLike | Sequence[Array | ArrayLike]], + as_numpy: bool, + multi_output: bool, + xp: ModuleType, +) -> Callable[..., tuple[Array, ...]]: + """ + Helper of `lazy_apply`. + + Given a function that accepts one or more arrays as positional arguments and returns + a single array-like or a sequence of array-likes, return a function that accepts the + same number of Array API arrays and always returns a tuple of Array API array. + + Any keyword arguments are passed through verbatim to the wrapped function. + """ + + # On Dask, @wraps causes the graph key to contain the wrapped function's name + @wraps(func) + def wrapper( + *args: Array | complex | None, **kwargs: Any + ) -> tuple[Array, ...]: # numpydoc ignore=GL08 + args_list = [] + device = None + for arg in args: + if arg is not None and not is_python_scalar(arg): + if device is None: + device = _compat.device(arg) + if as_numpy: + import numpy as np + + arg = cast(Array, np.asarray(arg)) # pyright: ignore[reportInvalidCast] # noqa: PLW2901 + args_list.append(arg) + assert device is not None + + out = func(*args_list, **kwargs) + + if multi_output: + assert isinstance(out, Sequence) + return tuple(xp.asarray(o, device=device) for o in out) + return (xp.asarray(out, device=device),) + + return wrapper diff --git a/.venv/lib/python3.12/site-packages/scipy/_external/array_api_extra/_lib/_testing.py b/.venv/lib/python3.12/site-packages/scipy/_external/array_api_extra/_lib/_testing.py new file mode 100644 index 0000000000000000000000000000000000000000..30e2f1efb7b0e017673c871acddd2bb6a74522cf --- /dev/null +++ b/.venv/lib/python3.12/site-packages/scipy/_external/array_api_extra/_lib/_testing.py @@ -0,0 +1,304 @@ +""" +Testing utilities. + +Note that this is private API; don't expect it to be stable. +See also ..testing for public testing utilities. +""" + +from __future__ import annotations + +import math +from types import ModuleType +from typing import Any, cast + +import numpy as np +import pytest + +from ._utils._compat import ( + array_namespace, + is_array_api_strict_namespace, + is_cupy_namespace, + is_dask_namespace, + is_jax_namespace, + is_numpy_namespace, + is_pydata_sparse_namespace, + is_torch_array, + is_torch_namespace, + to_device, +) +from ._utils._typing import Array, Device + +__all__ = ["as_numpy_array", "xp_assert_close", "xp_assert_equal", "xp_assert_less"] + + +def _check_ns_shape_dtype( + actual: Array, + desired: Array, + check_dtype: bool, + check_shape: bool, + check_scalar: bool, +) -> ModuleType: # numpydoc ignore=RT03 + """ + Assert that namespace, shape and dtype of the two arrays match. + + Parameters + ---------- + actual : Array + The array produced by the tested function. + desired : Array + The expected array (typically hardcoded). + check_dtype, check_shape : bool, default: True + Whether to check agreement between actual and desired dtypes and shapes + check_scalar : bool, default: False + NumPy only: whether to check agreement between actual and desired types - + 0d array vs scalar. + + Returns + ------- + Arrays namespace. + """ + actual_xp = array_namespace(actual) # Raises on scalars and lists + desired_xp = array_namespace(desired) + + msg = f"namespaces do not match: {actual_xp} != f{desired_xp}" + assert actual_xp == desired_xp, msg + + # Dask uses nan instead of None for unknown shapes + actual_shape = cast(tuple[float, ...], actual.shape) + desired_shape = cast(tuple[float, ...], desired.shape) + assert None not in actual_shape # Requires explicit support + assert None not in desired_shape + if is_dask_namespace(desired_xp): + if any(math.isnan(i) for i in actual_shape): + actual_shape = actual.compute().shape # type: ignore[attr-defined] # pyright: ignore[reportAttributeAccessIssue] + if any(math.isnan(i) for i in desired_shape): + desired_shape = desired.compute().shape # type: ignore[attr-defined] # pyright: ignore[reportAttributeAccessIssue] + + if check_shape: + msg = f"shapes do not match: {actual_shape} != f{desired_shape}" + assert actual_shape == desired_shape, msg + else: + # Ignore shape, but check flattened size. This is normally done by + # np.testing.assert_array_equal etc even when strict=False, but not for + # non-materializable arrays. + actual_size = math.prod(actual_shape) # pyright: ignore[reportUnknownArgumentType] + desired_size = math.prod(desired_shape) # pyright: ignore[reportUnknownArgumentType] + msg = f"sizes do not match: {actual_size} != f{desired_size}" + assert actual_size == desired_size, msg + + if check_dtype: + msg = f"dtypes do not match: {actual.dtype} != {desired.dtype}" + assert actual.dtype == desired.dtype, msg + + if is_numpy_namespace(actual_xp) and check_scalar: + # only NumPy distinguishes between scalars and arrays; we do if check_scalar. + _msg = ( + "array-ness does not match:\n Actual: " + f"{type(actual)}\n Desired: {type(desired)}" + ) + assert np.isscalar(actual) == np.isscalar(desired), _msg + + return desired_xp + + +def _is_materializable(x: Array) -> bool: + """ + Return True if you can call `as_numpy_array(x)`; False otherwise. + """ + # Important: here we assume that we're not tracing - + # e.g. we're not inside `jax.jit`` nor `cupy.cuda.Stream.begin_capture`. + return not is_torch_array(x) or x.device.type != "meta" # type: ignore[attr-defined] # pyright: ignore[reportAttributeAccessIssue] + + +def as_numpy_array(array: Array, *, xp: ModuleType) -> np.typing.NDArray[Any]: + """ + Convert array to NumPy, bypassing GPU-CPU transfer guards and densification guards. + """ + if is_cupy_namespace(xp): + return xp.asnumpy(array) + if is_pydata_sparse_namespace(xp): + return array.todense() # type: ignore[attr-defined] # pyright: ignore[reportAttributeAccessIssue] + + if is_torch_namespace(xp): + array = to_device(array, "cpu") + if is_array_api_strict_namespace(xp): + cpu: Device = xp.Device("CPU_DEVICE") + array = to_device(array, cpu) + if is_jax_namespace(xp): + import jax + + # Note: only needed if the transfer guard is enabled + cpu = cast(Device, jax.devices("cpu")[0]) + array = to_device(array, cpu) + + return np.asarray(array) + + +def xp_assert_equal( + actual: Array, + desired: Array, + *, + err_msg: str = "", + check_dtype: bool = True, + check_shape: bool = True, + check_scalar: bool = False, +) -> None: + """ + Array-API compatible version of `np.testing.assert_array_equal`. + + Parameters + ---------- + actual : Array + The array produced by the tested function. + desired : Array + The expected array (typically hardcoded). + err_msg : str, optional + Error message to display on failure. + check_dtype, check_shape : bool, default: True + Whether to check agreement between actual and desired dtypes and shapes + check_scalar : bool, default: False + NumPy only: whether to check agreement between actual and desired types - + 0d array vs scalar. + + See Also + -------- + xp_assert_close : Similar function for inexact equality checks. + numpy.testing.assert_array_equal : Similar function for NumPy arrays. + """ + xp = _check_ns_shape_dtype(actual, desired, check_dtype, check_shape, check_scalar) + if not _is_materializable(actual): + return + actual_np = as_numpy_array(actual, xp=xp) + desired_np = as_numpy_array(desired, xp=xp) + np.testing.assert_array_equal(actual_np, desired_np, err_msg=err_msg) + + +def xp_assert_less( + x: Array, + y: Array, + *, + err_msg: str = "", + check_dtype: bool = True, + check_shape: bool = True, + check_scalar: bool = False, +) -> None: + """ + Array-API compatible version of `np.testing.assert_array_less`. + + Parameters + ---------- + x, y : Array + The arrays to compare according to ``x < y`` (elementwise). + err_msg : str, optional + Error message to display on failure. + check_dtype, check_shape : bool, default: True + Whether to check agreement between actual and desired dtypes and shapes + check_scalar : bool, default: False + NumPy only: whether to check agreement between actual and desired types - + 0d array vs scalar. + + See Also + -------- + xp_assert_close : Similar function for inexact equality checks. + numpy.testing.assert_array_equal : Similar function for NumPy arrays. + """ + xp = _check_ns_shape_dtype(x, y, check_dtype, check_shape, check_scalar) + if not _is_materializable(x): + return + x_np = as_numpy_array(x, xp=xp) + y_np = as_numpy_array(y, xp=xp) + np.testing.assert_array_less(x_np, y_np, err_msg=err_msg) + + +def xp_assert_close( + actual: Array, + desired: Array, + *, + rtol: float | None = None, + atol: float = 0, + err_msg: str = "", + check_dtype: bool = True, + check_shape: bool = True, + check_scalar: bool = False, +) -> None: + """ + Array-API compatible version of `np.testing.assert_allclose`. + + Parameters + ---------- + actual : Array + The array produced by the tested function. + desired : Array + The expected array (typically hardcoded). + rtol : float, optional + Relative tolerance. Default: dtype-dependent. + atol : float, optional + Absolute tolerance. Default: 0. + err_msg : str, optional + Error message to display on failure. + check_dtype, check_shape : bool, default: True + Whether to check agreement between actual and desired dtypes and shapes + check_scalar : bool, default: False + NumPy only: whether to check agreement between actual and desired types - + 0d array vs scalar. + + See Also + -------- + xp_assert_equal : Similar function for exact equality checks. + isclose : Public function for checking closeness. + numpy.testing.assert_allclose : Similar function for NumPy arrays. + + Notes + ----- + The default `atol` and `rtol` differ from `xp.all(xpx.isclose(a, b))`. + """ + xp = _check_ns_shape_dtype(actual, desired, check_dtype, check_shape, check_scalar) + if not _is_materializable(actual): + return + + if rtol is None: + if xp.isdtype(actual.dtype, ("real floating", "complex floating")): + # multiplier of 4 is used as for `np.float64` this puts the default `rtol` + # roughly half way between sqrt(eps) and the default for + # `numpy.testing.assert_allclose`, 1e-7 + rtol = xp.finfo(actual.dtype).eps ** 0.5 * 4 + else: + rtol = 1e-7 + + actual_np = as_numpy_array(actual, xp=xp) + desired_np = as_numpy_array(desired, xp=xp) + np.testing.assert_allclose( # pyright: ignore[reportCallIssue] + actual_np, + desired_np, + rtol=rtol, # pyright: ignore[reportArgumentType] + atol=atol, + err_msg=err_msg, + ) + + +def xfail( + request: pytest.FixtureRequest, *, reason: str, strict: bool | None = None +) -> None: + """ + XFAIL the currently running test. + + Unlike ``pytest.xfail``, allow rest of test to execute instead of immediately + halting it, so that it may result in a XPASS. + xref https://github.com/pandas-dev/pandas/issues/38902 + + Parameters + ---------- + request : pytest.FixtureRequest + ``request`` argument of the test function. + reason : str + Reason for the expected failure. + strict: bool, optional + If True, the test will be marked as failed if it passes. + If False, the test will be marked as passed if it fails. + Default: ``xfail_strict`` value in ``pyproject.toml``, or False if absent. + """ + if strict is not None: + marker = pytest.mark.xfail(reason=reason, strict=strict) + else: + marker = pytest.mark.xfail(reason=reason) + request.node.add_marker(marker) diff --git a/.venv/lib/python3.12/site-packages/scipy/_external/array_api_extra/_lib/_utils/__init__.py b/.venv/lib/python3.12/site-packages/scipy/_external/array_api_extra/_lib/_utils/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..3628c45f0e0a48ba403abd0ba4a6bec76dc8a9f1 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/scipy/_external/array_api_extra/_lib/_utils/__init__.py @@ -0,0 +1 @@ +"""Modules housing private utility functions.""" diff --git a/.venv/lib/python3.12/site-packages/scipy/_external/array_api_extra/_lib/_utils/__pycache__/__init__.cpython-312.pyc b/.venv/lib/python3.12/site-packages/scipy/_external/array_api_extra/_lib/_utils/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..907cea97bf3741c804b1b17f480324fe9b19a0ef Binary files /dev/null and b/.venv/lib/python3.12/site-packages/scipy/_external/array_api_extra/_lib/_utils/__pycache__/__init__.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/scipy/_external/array_api_extra/_lib/_utils/__pycache__/_compat.cpython-312.pyc b/.venv/lib/python3.12/site-packages/scipy/_external/array_api_extra/_lib/_utils/__pycache__/_compat.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..51e5c41004eeee0b914b56b0b1a57cb8e3f5edf4 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/scipy/_external/array_api_extra/_lib/_utils/__pycache__/_compat.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/scipy/_external/array_api_extra/_lib/_utils/__pycache__/_helpers.cpython-312.pyc b/.venv/lib/python3.12/site-packages/scipy/_external/array_api_extra/_lib/_utils/__pycache__/_helpers.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..42dd41ac16c18f1890d75ae7cd08e1e3bdc9da3a Binary files /dev/null and b/.venv/lib/python3.12/site-packages/scipy/_external/array_api_extra/_lib/_utils/__pycache__/_helpers.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/scipy/_external/array_api_extra/_lib/_utils/__pycache__/_typing.cpython-312.pyc b/.venv/lib/python3.12/site-packages/scipy/_external/array_api_extra/_lib/_utils/__pycache__/_typing.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7a229247c84394c45d98ec7e744a44c4bebfda21 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/scipy/_external/array_api_extra/_lib/_utils/__pycache__/_typing.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/scipy/_external/array_api_extra/_lib/_utils/_compat.py b/.venv/lib/python3.12/site-packages/scipy/_external/array_api_extra/_lib/_utils/_compat.py new file mode 100644 index 0000000000000000000000000000000000000000..82ce76b8ecbcd506c639beb2c9b5b3934d94b67d --- /dev/null +++ b/.venv/lib/python3.12/site-packages/scipy/_external/array_api_extra/_lib/_utils/_compat.py @@ -0,0 +1,74 @@ +"""Acquire helpers from array-api-compat.""" +# Allow packages that vendor both `array-api-extra` and +# `array-api-compat` to override the import location + +# pylint: disable=duplicate-code +try: + from ...._array_api_compat_vendor import ( + array_namespace, + device, + is_array_api_obj, + is_array_api_strict_namespace, + is_cupy_array, + is_cupy_namespace, + is_dask_array, + is_dask_namespace, + is_jax_array, + is_jax_namespace, + is_lazy_array, + is_numpy_array, + is_numpy_namespace, + is_pydata_sparse_array, + is_pydata_sparse_namespace, + is_torch_array, + is_torch_namespace, + is_writeable_array, + size, + to_device, + ) +except ImportError: + from array_api_compat import ( + array_namespace, + device, + is_array_api_obj, + is_array_api_strict_namespace, + is_cupy_array, + is_cupy_namespace, + is_dask_array, + is_dask_namespace, + is_jax_array, + is_jax_namespace, + is_lazy_array, + is_numpy_array, + is_numpy_namespace, + is_pydata_sparse_array, + is_pydata_sparse_namespace, + is_torch_array, + is_torch_namespace, + is_writeable_array, + size, + to_device, + ) + +__all__ = [ + "array_namespace", + "device", + "is_array_api_obj", + "is_array_api_strict_namespace", + "is_cupy_array", + "is_cupy_namespace", + "is_dask_array", + "is_dask_namespace", + "is_jax_array", + "is_jax_namespace", + "is_lazy_array", + "is_numpy_array", + "is_numpy_namespace", + "is_pydata_sparse_array", + "is_pydata_sparse_namespace", + "is_torch_array", + "is_torch_namespace", + "is_writeable_array", + "size", + "to_device", +] diff --git a/.venv/lib/python3.12/site-packages/scipy/_external/array_api_extra/_lib/_utils/_compat.pyi b/.venv/lib/python3.12/site-packages/scipy/_external/array_api_extra/_lib/_utils/_compat.pyi new file mode 100644 index 0000000000000000000000000000000000000000..95c6bc8a1baed1f083d907994e5c939d6cc325f2 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/scipy/_external/array_api_extra/_lib/_utils/_compat.pyi @@ -0,0 +1,45 @@ +"""Static type stubs for `_compat.py`.""" + +# https://github.com/scikit-learn/scikit-learn/pull/27910#issuecomment-2568023972 +from __future__ import annotations + +from types import ModuleType +from typing import Any, TypeGuard + +# TODO import from typing (requires Python >=3.13) +from typing_extensions import TypeIs + +from ._typing import Array, Device + +# pylint: disable=missing-class-docstring,unused-argument + +def array_namespace( + *xs: Array | complex | None, + api_version: str | None = None, + use_compat: bool | None = None, +) -> ModuleType: ... +def device(x: Array, /) -> Device: ... +def is_array_api_obj(x: object, /) -> TypeIs[Array]: ... +def is_array_api_strict_namespace(xp: ModuleType, /) -> bool: ... +def is_cupy_namespace(xp: ModuleType, /) -> bool: ... +def is_dask_namespace(xp: ModuleType, /) -> bool: ... +def is_jax_namespace(xp: ModuleType, /) -> bool: ... +def is_numpy_namespace(xp: ModuleType, /) -> bool: ... +def is_pydata_sparse_namespace(xp: ModuleType, /) -> bool: ... +def is_torch_namespace(xp: ModuleType, /) -> bool: ... +def is_cupy_array(x: object, /) -> TypeGuard[Array]: ... +def is_dask_array(x: object, /) -> TypeGuard[Array]: ... +def is_jax_array(x: object, /) -> TypeGuard[Array]: ... +def is_numpy_array(x: object, /) -> TypeGuard[Array]: ... +def is_pydata_sparse_array(x: object, /) -> TypeGuard[Array]: ... +def is_torch_array(x: object, /) -> TypeGuard[Array]: ... +def is_lazy_array(x: object, /) -> TypeGuard[Array]: ... +def is_writeable_array(x: object, /) -> TypeGuard[Array]: ... +def size(x: Array, /) -> int | None: ... +def to_device( + x: Array, + device: Device, # pylint: disable=redefined-outer-name + /, + *, + stream: int | Any | None = None, +) -> Array: ... diff --git a/.venv/lib/python3.12/site-packages/scipy/_external/array_api_extra/_lib/_utils/_helpers.py b/.venv/lib/python3.12/site-packages/scipy/_external/array_api_extra/_lib/_utils/_helpers.py new file mode 100644 index 0000000000000000000000000000000000000000..4065c25ff1fb61bfd4f05f921760d4f4fecbbc6c --- /dev/null +++ b/.venv/lib/python3.12/site-packages/scipy/_external/array_api_extra/_lib/_utils/_helpers.py @@ -0,0 +1,619 @@ +"""Helper functions used by `array_api_extra/_funcs.py`.""" + +from __future__ import annotations + +import io +import math +import pickle +import types +from collections.abc import Callable, Generator, Iterable, Iterator +from functools import wraps +from types import ModuleType +from typing import ( + TYPE_CHECKING, + Any, + ClassVar, + Generic, + Literal, + ParamSpec, + TypeAlias, + TypeVar, + cast, +) + +from . import _compat +from ._compat import ( + array_namespace, + is_array_api_obj, + is_dask_namespace, + is_jax_namespace, + is_numpy_array, + is_pydata_sparse_namespace, + is_torch_namespace, +) +from ._typing import Array, Device + +if TYPE_CHECKING: # pragma: no cover + # TODO import from typing (requires Python >=3.12 and >=3.13) + from typing_extensions import TypeIs, override +else: + + def override(func): + return func + + +P = ParamSpec("P") +T = TypeVar("T") + + +__all__ = [ + "asarrays", + "capabilities", + "eager_shape", + "in1d", + "is_python_scalar", + "jax_autojit", + "mean", + "meta_namespace", + "pickle_flatten", + "pickle_unflatten", +] + + +def in1d( + x1: Array, + x2: Array, + /, + *, + assume_unique: bool = False, + invert: bool = False, + xp: ModuleType | None = None, +) -> Array: # numpydoc ignore=PR01,RT01 + """ + Check whether each element of an array is also present in a second array. + + Returns a boolean array the same length as `x1` that is True + where an element of `x1` is in `x2` and False otherwise. + + This function has been adapted using the original implementation + present in numpy: + https://github.com/numpy/numpy/blob/v1.26.0/numpy/lib/arraysetops.py#L524-L758 + """ + if xp is None: + xp = array_namespace(x1, x2) + + x1_shape = eager_shape(x1) + x2_shape = eager_shape(x2) + + # This code is run to make the code significantly faster + if x2_shape[0] < 10 * x1_shape[0] ** 0.145 and isinstance(x2, Iterable): + if invert: + mask = xp.ones(x1_shape[0], dtype=xp.bool, device=_compat.device(x1)) + for a in x2: + mask &= x1 != a + else: + mask = xp.zeros(x1_shape[0], dtype=xp.bool, device=_compat.device(x1)) + for a in x2: + mask |= x1 == a + return mask + + rev_idx = xp.empty(0) # placeholder + if not assume_unique: + x1, rev_idx = xp.unique_inverse(x1) + x2 = xp.unique_values(x2) + + ar = xp.concat((x1, x2)) + device_ = _compat.device(ar) + # We need this to be a stable sort. + order = xp.argsort(ar, stable=True) + reverse_order = xp.argsort(order, stable=True) + sar = xp.take(ar, order, axis=0) + ar_size = _compat.size(sar) + assert ar_size is not None, "xp.unique*() on lazy backends raises" + if ar_size >= 1: + bool_ar = sar[1:] != sar[:-1] if invert else sar[1:] == sar[:-1] + else: + bool_ar = xp.asarray([False]) if invert else xp.asarray([True]) + flag = xp.concat((bool_ar, xp.asarray([invert], device=device_))) + ret = xp.take(flag, reverse_order, axis=0) + + if assume_unique: + return ret[: x1.shape[0]] + return xp.take(ret, rev_idx, axis=0) + + +def mean( + x: Array, + /, + *, + axis: int | tuple[int, ...] | None = None, + keepdims: bool = False, + xp: ModuleType | None = None, +) -> Array: # numpydoc ignore=PR01,RT01 + """ + Complex mean, https://github.com/data-apis/array-api/issues/846. + """ + if xp is None: + xp = array_namespace(x) + + if xp.isdtype(x.dtype, "complex floating"): + x_real = xp.real(x) + x_imag = xp.imag(x) + mean_real = xp.mean(x_real, axis=axis, keepdims=keepdims) + mean_imag = xp.mean(x_imag, axis=axis, keepdims=keepdims) + return mean_real + (mean_imag * xp.asarray(1j)) + return xp.mean(x, axis=axis, keepdims=keepdims) + + +def is_python_scalar(x: object) -> TypeIs[complex]: # numpydoc ignore=PR01,RT01 + """Return True if `x` is a Python scalar, False otherwise.""" + # isinstance(x, float) returns True for np.float64 + # isinstance(x, complex) returns True for np.complex128 + # bool is a subclass of int + return isinstance(x, int | float | complex) and not is_numpy_array(x) + + +def asarrays( + a: Array | complex, + b: Array | complex, + xp: ModuleType, +) -> tuple[Array, Array]: + """ + Ensure both `a` and `b` are arrays. + + If `b` is a python scalar, it is converted to the same dtype as `a`, and vice versa. + + Behavior is not specified when mixing a Python ``float`` and an array with an + integer data type; this may give ``float32``, ``float64``, or raise an exception. + Behavior is implementation-specific. + + Similarly, behavior is not specified when mixing a Python ``complex`` and an array + with a real-valued data type; this may give ``complex64``, ``complex128``, or raise + an exception. Behavior is implementation-specific. + + Parameters + ---------- + a, b : Array | int | float | complex | bool + Input arrays or scalars. At least one must be an array. + xp : array_namespace, optional + The standard-compatible namespace for `x`. Default: infer. + + Returns + ------- + Array, Array + The input arrays, possibly converted to arrays if they were scalars. + + See Also + -------- + mixing-arrays-with-python-scalars : Array API specification for the behavior. + """ + a_scalar = is_python_scalar(a) + b_scalar = is_python_scalar(b) + if not a_scalar and not b_scalar: + # This includes misc. malformed input e.g. str + return a, b # type: ignore[return-value] + + swap = False + if a_scalar: + swap = True + b, a = a, b + + if is_array_api_obj(a): + # a is an Array API object + # b is a int | float | complex | bool + xa = a + + # https://data-apis.org/array-api/draft/API_specification/type_promotion.html#mixing-arrays-with-python-scalars + same_dtype = { + bool: "bool", + int: ("integral", "real floating", "complex floating"), + float: ("real floating", "complex floating"), + complex: "complex floating", + } + kind = same_dtype[type(cast(complex, b))] + if xp.isdtype(a.dtype, kind): + xb = xp.asarray(b, dtype=a.dtype, device=_compat.device(a)) + else: + # Undefined behaviour. Let the function deal with it, if it can. + xb = xp.asarray(b, device=_compat.device(a)) + + else: + # Neither a nor b are Array API objects. + # Note: we can only reach this point when one explicitly passes + # xp=xp to the calling function; otherwise we fail earlier on + # array_namespace(a, b). + xa, xb = xp.asarray(a), xp.asarray(b) + + return (xb, xa) if swap else (xa, xb) + + +def ndindex(*x: int) -> Generator[tuple[int, ...]]: + """ + Generate all N-dimensional indices for a given array shape. + + Given the shape of an array, an ndindex instance iterates over the N-dimensional + index of the array. At each iteration a tuple of indices is returned, the last + dimension is iterated over first. + + This has an identical API to numpy.ndindex. + + Parameters + ---------- + *x : int + The shape of the array. + """ + if not x: + yield () + return + for i in ndindex(*x[:-1]): + for j in range(x[-1]): + yield *i, j + + +def eager_shape(x: Array, /, axis: int | None = None) -> tuple[int, ...]: + """ + Return shape of an array. Raise if shape is not fully defined. + + Parameters + ---------- + x : Array + Input array. + axis : int, optional + If provided, only returns the tuple (shape[axis],). + + Returns + ------- + tuple[int, ...] + Shape of the array. + """ + shape = x.shape + if axis is not None: + s = shape[axis] + # Dask arrays uses non-standard NaN instead of None + if s is None or math.isnan(s): + msg = f"Unsupported lazy shape for axis {axis}" + raise TypeError(msg) + return (s,) + + if any(s is None or math.isnan(s) for s in shape): + msg = "Unsupported lazy shape" + raise TypeError(msg) + return cast(tuple[int, ...], shape) + + +def meta_namespace( + *arrays: Array | complex | None, xp: ModuleType | None = None +) -> ModuleType: + """ + Get the namespace of Dask chunks. + + On all other backends, just return the namespace of the arrays. + + Parameters + ---------- + *arrays : Array | int | float | complex | bool | None + Input arrays. + xp : array_namespace, optional + The standard-compatible namespace for the input arrays. Default: infer. + + Returns + ------- + array_namespace + If xp is Dask, the namespace of the Dask chunks; + otherwise, the namespace of the arrays. + """ + xp = array_namespace(*arrays) if xp is None else xp + if not is_dask_namespace(xp): + return xp + # Quietly skip scalars and None's + metas = [cast(Array | None, getattr(a, "_meta", None)) for a in arrays] + return array_namespace(*metas) + + +def capabilities( + xp: ModuleType, *, device: Device | None = None +) -> dict[str, int | None]: + """ + Return patched ``xp.__array_namespace_info__().capabilities()``. + + TODO this helper should be eventually removed once all the special cases + it handles are fixed in the respective backends. + + Parameters + ---------- + xp : array_namespace + The standard-compatible namespace. + device : Device, optional + The device to use. + + Returns + ------- + dict + Capabilities of the namespace. + """ + out = xp.__array_namespace_info__().capabilities() + if is_pydata_sparse_namespace(xp): + if out["boolean indexing"]: + # FIXME https://github.com/pydata/sparse/issues/876 + # boolean indexing is supported, but not when the index is a sparse array. + # boolean indexing by list or numpy array is not part of the Array API. + out = out.copy() + out["boolean indexing"] = False + elif is_jax_namespace(xp): + if out["boolean indexing"]: # pragma: no cover + # Backwards compatibility with jax <0.6.0 + # https://github.com/jax-ml/jax/issues/27418 + out = out.copy() + out["boolean indexing"] = False + elif is_torch_namespace(xp): + # FIXME https://github.com/data-apis/array-api/issues/945 + device = xp.get_default_device() if device is None else xp.device(device) + if device.type == "meta": # type: ignore[union-attr] # pyright: ignore[reportAttributeAccessIssue,reportOptionalMemberAccess] + out = out.copy() + out["boolean indexing"] = False + out["data-dependent shapes"] = False + + return out + + +_BASIC_PICKLED_TYPES = frozenset(( + bool, int, float, complex, str, bytes, bytearray, + list, tuple, dict, set, frozenset, range, slice, + types.NoneType, types.EllipsisType, +)) # fmt: skip +_BASIC_REST_TYPES = frozenset(( + type, types.BuiltinFunctionType, types.FunctionType, types.ModuleType +)) # fmt: skip + +FlattenRest: TypeAlias = tuple[object, ...] + + +def pickle_flatten( + obj: object, cls: type[T] | tuple[type[T], ...] +) -> tuple[list[T], FlattenRest]: + """ + Use the pickle machinery to extract objects out of an arbitrary container. + + Unlike regular ``pickle.dumps``, this function always succeeds. + + Parameters + ---------- + obj : object + The object to pickle. + cls : type | tuple[type, ...] + One or multiple classes to extract from the object. + The instances of these classes inside ``obj`` will not be pickled. + + Returns + ------- + instances : list[cls] + All instances of ``cls`` found inside ``obj`` (not pickled). + rest + Opaque object containing the pickled bytes plus all other objects where + ``__reduce__`` / ``__reduce_ex__`` is either not implemented or raised. + These are unpickleable objects, types, modules, and functions. + + This object is *typically* hashable save for fairly exotic objects + that are neither pickleable nor hashable. + + This object is pickleable if everything except ``instances`` was pickleable + in the input object. + + See Also + -------- + pickle_unflatten : Reverse function. + + Examples + -------- + >>> class A: + ... def __repr__(self): + ... return "" + >>> class NS: + ... def __repr__(self): + ... return "" + ... def __reduce__(self): + ... assert False, "not serializable" + >>> obj = {1: A(), 2: [A(), NS(), A()]} + >>> instances, rest = pickle_flatten(obj, A) + >>> instances + [, , ] + >>> pickle_unflatten(instances, rest) + {1: , 2: [, , ]} + + This can be also used to swap inner objects; the only constraint is that + the number of objects in and out must be the same: + + >>> pickle_unflatten(["foo", "bar", "baz"], rest) + {1: "foo", 2: ["bar", , "baz"]} + """ + instances: list[T] = [] + rest: list[object] = [] + + class Pickler(pickle.Pickler): # numpydoc ignore=GL08 + """ + Use the `pickle.Pickler.persistent_id` hook to extract objects. + """ + + @override + def persistent_id( + self, obj: object + ) -> Literal[0, 1, None]: # numpydoc ignore=GL08 + if isinstance(obj, cls): + instances.append(obj) # type: ignore[arg-type] + return 0 + + typ_ = type(obj) + if typ_ in _BASIC_PICKLED_TYPES: # No subclasses! + # If obj is a collection, recursively descend inside it + return None + if typ_ in _BASIC_REST_TYPES: + rest.append(obj) + return 1 + + try: + # Note: a class that defines __slots__ without defining __getstate__ + # cannot be pickled with __reduce__(), but can with __reduce_ex__(5) + _ = obj.__reduce_ex__(pickle.HIGHEST_PROTOCOL) + except Exception: # pylint: disable=broad-exception-caught + rest.append(obj) + return 1 + + # Object can be pickled. Let the Pickler recursively descend inside it. + return None + + f = io.BytesIO() + p = Pickler(f, protocol=pickle.HIGHEST_PROTOCOL) + p.dump(obj) + return instances, (f.getvalue(), *rest) + + +def pickle_unflatten(instances: Iterable[object], rest: FlattenRest) -> Any: + """ + Reverse of ``pickle_flatten``. + + Parameters + ---------- + instances : Iterable + Inner objects to be reinserted into the flattened container. + rest : FlattenRest + Extra bits, as returned by ``pickle_flatten``. + + Returns + ------- + object + The outer object originally passed to ``pickle_flatten`` after a + pickle->unpickle round-trip. + + See Also + -------- + pickle_flatten : Serializing function. + pickle.loads : Standard unpickle function. + + Notes + ----- + The `instances` iterable must yield at least the same number of elements as the ones + returned by ``pickle_flatten``, but the elements do not need to be the same objects + or even the same types of objects. Excess elements, if any, will be left untouched. + """ + iters = iter(instances), iter(rest) + pik = cast(bytes, next(iters[1])) + + class Unpickler(pickle.Unpickler): # numpydoc ignore=GL08 + """Mirror of the overridden Pickler in pickle_flatten.""" + + @override + def persistent_load(self, pid: Literal[0, 1]) -> object: # numpydoc ignore=GL08 + try: + return next(iters[pid]) + except StopIteration as e: + msg = "Not enough objects to unpickle" + raise ValueError(msg) from e + + f = io.BytesIO(pik) + return Unpickler(f).load() + + +class _AutoJITWrapper(Generic[T]): # numpydoc ignore=PR01 + """ + Helper of :func:`jax_autojit`. + + Wrap arbitrary inputs and outputs of the jitted function and + convert them to/from PyTrees. + """ + + _obj: Any + _is_iter: bool + _registered: ClassVar[bool] = False + __slots__: tuple[str, ...] = ("_is_iter", "_obj") + + def __init__(self, obj: T) -> None: # numpydoc ignore=GL08 + self._register() + if isinstance(obj, Iterator): + self._obj = list(obj) + self._is_iter = True + else: + self._obj = obj + self._is_iter = False + + @property + def obj(self) -> T: # numpydoc ignore=RT01 + """Return wrapped object.""" + return iter(self._obj) if self._is_iter else self._obj + + @classmethod + def _register(cls) -> None: # numpydoc ignore=SS06 + """ + Register upon first use instead of at import time, to avoid + globally importing JAX. + """ + if not cls._registered: + import jax + + jax.tree_util.register_pytree_node( + cls, + lambda instance: pickle_flatten(instance, jax.Array), # pyright: ignore[reportUnknownArgumentType] + lambda aux_data, children: pickle_unflatten(children, aux_data), # pyright: ignore[reportUnknownArgumentType] + ) + cls._registered = True + + +def jax_autojit( + func: Callable[P, T], +) -> Callable[P, T]: # numpydoc ignore=PR01,RT01,SS03 + """ + Wrap `func` with ``jax.jit``, with the following differences: + + - Python scalar arguments and return values are not automatically converted to + ``jax.Array`` objects. + - All non-array arguments are automatically treated as static. + Unlike ``jax.jit``, static arguments must be either hashable or serializable with + ``pickle``. + - Unlike ``jax.jit``, non-array arguments and return values are not limited to + tuple/list/dict, but can be any object serializable with ``pickle``. + - Automatically descend into non-array arguments and find ``jax.Array`` objects + inside them, then rebuild the arguments when entering `func`, swapping the JAX + concrete arrays with tracer objects. + - Automatically descend into non-array return values and find ``jax.Array`` objects + inside them, then rebuild them downstream of exiting the JIT, swapping the JAX + tracer objects with concrete arrays. + - Returned iterators are immediately completely consumed. + + See Also + -------- + jax.jit : JAX JIT compilation function. + + Notes + ----- + These are useful choices *for testing purposes only*, which is how this function is + intended to be used. The output of ``jax.jit`` is a C++ level callable, that + directly dispatches to the compiled kernel after the initial call. In comparison, + ``jax_autojit`` incurs a much higher dispatch time. + + Additionally, consider:: + + def f(x: Array, y: float, plus: bool) -> Array: + return x + y if plus else x - y + + j1 = jax.jit(f, static_argnames="plus") + j2 = jax_autojit(f) + + In the above example, ``j2`` requires a lot less setup to be tested effectively than + ``j1``, but on the flip side it means that it will be re-traced for every different + value of ``y``, which likely makes it not fit for purpose in production. + """ + import jax + + @jax.jit # type: ignore[untyped-decorator] # pyright: ignore[reportUntypedFunctionDecorator] + def inner( # numpydoc ignore=GL08 + wargs: _AutoJITWrapper[Any], + ) -> _AutoJITWrapper[T]: + args, kwargs = wargs.obj + res = func(*args, **kwargs) # pyright: ignore[reportCallIssue] + return _AutoJITWrapper(res) + + @wraps(func) + def outer(*args: P.args, **kwargs: P.kwargs) -> T: # numpydoc ignore=GL08 + wargs = _AutoJITWrapper((args, kwargs)) + return inner(wargs).obj + + return outer diff --git a/.venv/lib/python3.12/site-packages/scipy/_external/array_api_extra/_lib/_utils/_typing.py b/.venv/lib/python3.12/site-packages/scipy/_external/array_api_extra/_lib/_utils/_typing.py new file mode 100644 index 0000000000000000000000000000000000000000..8204be4759610b1ddb33b3579ccaa5f3a1f0866a --- /dev/null +++ b/.venv/lib/python3.12/site-packages/scipy/_external/array_api_extra/_lib/_utils/_typing.py @@ -0,0 +1,10 @@ +# numpydoc ignore=GL08 +# pylint: disable=missing-module-docstring,duplicate-code + +Array = object +DType = object +Device = object +GetIndex = object +SetIndex = object + +__all__ = ["Array", "DType", "Device", "GetIndex", "SetIndex"] diff --git a/.venv/lib/python3.12/site-packages/scipy/_external/array_api_extra/_lib/_utils/_typing.pyi b/.venv/lib/python3.12/site-packages/scipy/_external/array_api_extra/_lib/_utils/_typing.pyi new file mode 100644 index 0000000000000000000000000000000000000000..35c255fc9ad5c6c93e1b988dc9fe1fc6543ee0a6 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/scipy/_external/array_api_extra/_lib/_utils/_typing.pyi @@ -0,0 +1,105 @@ +"""Static typing helpers.""" + +from __future__ import annotations + +from types import EllipsisType +from typing import Protocol, TypeAlias + +# TODO import from typing (requires Python >=3.12) +from typing_extensions import override + +# TODO: use array-api-typing once it is available + +class Array(Protocol): # pylint: disable=missing-class-docstring + # Unary operations + def __abs__(self) -> Array: ... + def __pos__(self) -> Array: ... + def __neg__(self) -> Array: ... + def __invert__(self) -> Array: ... + # Binary operations + def __add__(self, other: Array | complex, /) -> Array: ... + def __sub__(self, other: Array | complex, /) -> Array: ... + def __mul__(self, other: Array | complex, /) -> Array: ... + def __truediv__(self, other: Array | complex, /) -> Array: ... + def __floordiv__(self, other: Array | complex, /) -> Array: ... + def __mod__(self, other: Array | complex, /) -> Array: ... + def __pow__(self, other: Array | complex, /) -> Array: ... + def __matmul__(self, other: Array, /) -> Array: ... + def __and__(self, other: Array | int, /) -> Array: ... + def __or__(self, other: Array | int, /) -> Array: ... + def __xor__(self, other: Array | int, /) -> Array: ... + def __lshift__(self, other: Array | int, /) -> Array: ... + def __rshift__(self, other: Array | int, /) -> Array: ... + def __lt__(self, other: Array | complex, /) -> Array: ... + def __le__(self, other: Array | complex, /) -> Array: ... + def __gt__(self, other: Array | complex, /) -> Array: ... + def __ge__(self, other: Array | complex, /) -> Array: ... + @override + def __eq__(self, other: Array | complex, /) -> Array: ... # type: ignore[override] # pyright: ignore[reportIncompatibleMethodOverride] + @override + def __ne__(self, other: Array | complex, /) -> Array: ... # type: ignore[override] # pyright: ignore[reportIncompatibleMethodOverride] + # Reflected operations + def __radd__(self, other: Array | complex, /) -> Array: ... + def __rsub__(self, other: Array | complex, /) -> Array: ... + def __rmul__(self, other: Array | complex, /) -> Array: ... + def __rtruediv__(self, other: Array | complex, /) -> Array: ... + def __rfloordiv__(self, other: Array | complex, /) -> Array: ... + def __rmod__(self, other: Array | complex, /) -> Array: ... + def __rpow__(self, other: Array | complex, /) -> Array: ... + def __rmatmul__(self, other: Array, /) -> Array: ... + def __rand__(self, other: Array | int, /) -> Array: ... + def __ror__(self, other: Array | int, /) -> Array: ... + def __rxor__(self, other: Array | int, /) -> Array: ... + def __rlshift__(self, other: Array | int, /) -> Array: ... + def __rrshift__(self, other: Array | int, /) -> Array: ... + # Attributes + @property + def dtype(self) -> DType: ... + @property + def device(self) -> Device: ... + @property + def mT(self) -> Array: ... # pylint: disable=invalid-name + @property + def ndim(self) -> int: ... + @property + def shape(self) -> tuple[int | None, ...]: ... + @property + def size(self) -> int | None: ... + @property + def T(self) -> Array: ... # pylint: disable=invalid-name + # Collection operations (note: an Array does not have to be Sized or Iterable) + def __getitem__(self, key: GetIndex, /) -> Array: ... + def __setitem__(self, key: SetIndex, value: Array | complex, /) -> None: ... + # Materialization methods (may raise on lazy arrays) + def __bool__(self) -> bool: ... + def __complex__(self) -> complex: ... + def __float__(self) -> float: ... + def __index__(self) -> int: ... + def __int__(self) -> int: ... + + # Misc methods (frequently not implemented in Arrays wrapped by array-api-compat) + # def __array_namespace__(*, api_version: str | None) -> ModuleType: ... + # def __dlpack__( + # *, + # stream: int | Any | None = None, + # max_version: tuple[int, int] | None = None, + # dl_device: tuple[int, int] | None = None, # tuple[Enum, int] + # copy: bool | None = None, + # ) -> Any: ... + # def __dlpack_device__() -> tuple[int, int]: ... # tuple[Enum, int] + # def to_device(device: Device, /, *, stream: int | Any | None = None) -> Array: ... + +class DType(Protocol): # pylint: disable=missing-class-docstring + pass + +class Device(Protocol): # pylint: disable=missing-class-docstring + pass + +SetIndex: TypeAlias = ( + int | slice | EllipsisType | Array | tuple[int | slice | EllipsisType | Array, ...] +) +GetIndex: TypeAlias = ( + SetIndex | None | tuple[int | slice | EllipsisType | None | Array, ...] +) + +__all__ = ["Array", "DType", "Device", "GetIndex", "SetIndex"] diff --git a/.venv/lib/python3.12/site-packages/scipy/_external/array_api_extra/testing.py b/.venv/lib/python3.12/site-packages/scipy/_external/array_api_extra/testing.py new file mode 100644 index 0000000000000000000000000000000000000000..9f2b0d385a79f067873edb35072352e37b8a3774 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/scipy/_external/array_api_extra/testing.py @@ -0,0 +1,516 @@ +""" +Public testing utilities. + +See also _lib._testing for additional private testing utilities. +""" + +from __future__ import annotations + +import contextlib +import enum +import warnings +from collections.abc import Callable, Generator, Iterator, Sequence +from functools import update_wrapper, wraps +from inspect import getattr_static +from types import FunctionType, ModuleType +from typing import TYPE_CHECKING, Any, ParamSpec, TypeVar, cast + +from ._lib._utils._compat import is_dask_namespace, is_jax_namespace +from ._lib._utils._helpers import jax_autojit, pickle_flatten, pickle_unflatten + +__all__ = ["lazy_xp_function", "patch_lazy_xp_functions"] + +if TYPE_CHECKING: # pragma: no cover + # TODO import override from typing (requires Python >=3.12) + import pytest + from dask.typing import Graph, Key, SchedulerGetCallable + from typing_extensions import override + +else: + # Sphinx hacks + SchedulerGetCallable = object + + def override(func): + return func + + +P = ParamSpec("P") +T = TypeVar("T") + +_ufuncs_tags: dict[object, dict[str, Any]] = {} + + +class Deprecated(enum.Enum): + """Unique type for deprecated parameters.""" + + DEPRECATED = 1 + + +DEPRECATED = Deprecated.DEPRECATED + + +def _clone_function(f: Callable[..., Any]) -> Callable[..., Any]: + """Returns a clone of an existing function.""" + f_new = FunctionType( + f.__code__, + f.__globals__, + name=f.__name__, + argdefs=f.__defaults__, + closure=f.__closure__, + ) + f_new.__kwdefaults__ = f.__kwdefaults__ + return update_wrapper(f_new, f) + + +def lazy_xp_function( + func: Callable[..., Any] | tuple[type, str], + *, + allow_dask_compute: bool | int = False, + jax_jit: bool = True, + static_argnums: Deprecated = DEPRECATED, + static_argnames: Deprecated = DEPRECATED, +) -> None: # numpydoc ignore=GL07 + """ + Tag a function to be tested on lazy backends. + + Tag a function so that when any tests are executed with ``xp=jax.numpy`` the + function is replaced with a jitted version of itself, and when it is executed with + ``xp=dask.array`` the function will raise if it attempts to materialize the graph. + This will be later expanded to provide test coverage for other lazy backends. + + In order for the tag to be effective, the test or a fixture must call + :func:`patch_lazy_xp_functions`. + + Parameters + ---------- + func : callable | tuple[type, str] + Function to be tested, or a tuple containing an (uninstantiated) class and a + method name to specify a class method to be tested. + allow_dask_compute : bool | int, optional + Whether `func` is allowed to internally materialize the Dask graph, or maximum + number of times it is allowed to do so. This is typically triggered by + ``bool()``, ``float()``, or ``np.asarray()``. + + Set to 1 if you are aware that `func` converts the input parameters to NumPy and + want to let it do so at least for the time being, knowing that it is going to be + extremely detrimental for performance. + + If a test needs values higher than 1 to pass, it is a canary that the conversion + to NumPy/bool/float is happening multiple times, which translates to multiple + computations of the whole graph. Short of making the function fully lazy, you + should at least add explicit calls to ``np.asarray()`` early in the function. + *Note:* the counter of `allow_dask_compute` resets after each call to `func`, so + a test function that invokes `func` multiple times should still work with this + parameter set to 1. + + Set to True to allow `func` to materialize the graph an unlimited number + of times. + + Default: False, meaning that `func` must be fully lazy and never materialize the + graph. + jax_jit : bool, optional + Set to True to replace `func` with a smart variant of ``jax.jit(func)`` after + calling the :func:`patch_lazy_xp_functions` test helper with ``xp=jax.numpy``. + This is the default behaviour. + Set to False if `func` is only compatible with eager (non-jitted) JAX. + + Unlike with vanilla ``jax.jit``, all arguments and return types that are not JAX + arrays are treated as static; the function can accept and return arbitrary + wrappers around JAX arrays. This difference is because, in real life, most users + won't wrap the function directly with ``jax.jit`` but rather they will use it + within their own code, which is itself then wrapped by ``jax.jit``, and + internally consume the function's outputs. + + In other words, the pattern that is being tested is:: + + >>> @jax.jit + ... def user_func(x): + ... y = user_prepares_inputs(x) + ... z = func(y, some_static_arg=True) + ... return user_consumes(z) + + Default: True. + static_argnums : + Deprecated; ignored + static_argnames : + Deprecated; ignored + + See Also + -------- + patch_lazy_xp_functions : Companion function to call from the test or fixture. + jax.jit : JAX function to compile a function for performance. + + Examples + -------- + In ``test_mymodule.py``:: + + from array_api_extra.testing import lazy_xp_function from mymodule import myfunc + + lazy_xp_function(myfunc) + + def test_myfunc(xp): + a = xp.asarray([1, 2]) + # When xp=jax.numpy, this is similar to `b = jax.jit(myfunc)(a)` + # When xp=dask.array, crash on compute() or persist() + b = myfunc(a) + + Notes + ----- + In order for this tag to be effective, the test function must be imported into the + test module globals without its namespace; alternatively its namespace must be + declared in a ``lazy_xp_modules`` list in the test module globals. + + Example 1:: + + from mymodule import myfunc + + lazy_xp_function(myfunc) + + def test_myfunc(xp): + x = myfunc(xp.asarray([1, 2])) + + Example 2:: + + import mymodule + + lazy_xp_modules = [mymodule] + lazy_xp_function(mymodule.myfunc) + + def test_myfunc(xp): + x = mymodule.myfunc(xp.asarray([1, 2])) + + A test function can circumvent this monkey-patching system by using a namespace + outside of the two above patterns. You need to sanitize your code to make sure this + only happens intentionally. + + Example 1:: + + import mymodule + from mymodule import myfunc + + lazy_xp_function(myfunc) + + def test_myfunc(xp): + a = xp.asarray([1, 2]) + b = myfunc(a) # This is wrapped when xp=jax.numpy or xp=dask.array + c = mymodule.myfunc(a) # This is not + + Example 2:: + + import mymodule + + class naked: + myfunc = mymodule.myfunc + + lazy_xp_modules = [mymodule] + lazy_xp_function(mymodule.myfunc) + + def test_myfunc(xp): + a = xp.asarray([1, 2]) + b = mymodule.myfunc(a) # This is wrapped when xp=jax.numpy or xp=dask.array + c = naked.myfunc(a) # This is not + """ + if static_argnums is not DEPRECATED or static_argnames is not DEPRECATED: + warnings.warn( + ( + "The `static_argnums` and `static_argnames` parameters are deprecated " + "and ignored. They will be removed in a future version." + ), + DeprecationWarning, + stacklevel=2, + ) + tags: dict[str, bool | int | type] = { + "allow_dask_compute": allow_dask_compute, + "jax_jit": jax_jit, + } + + if isinstance(func, tuple): + # Replace the method with a clone before adding tags + # to avoid adding unwanted tags to a parent method when + # the method was inherited from a parent class. + # Note: can't just accept an unbound method `cls.method_name` because in + # case of inheritance it would be impossible to attribute it to the child class. + # This also makes it so tagged methods will appear in their class's ``__dict__`` + # and thus findable by ``iter_tagged_modules`` below. + cls, method_name = func + # The method might be a staticmethod or classmethod so we need to do a dance + # to ensure that this is preserved. + raw_attr = getattr_static(cls, method_name) + method = getattr(cls, method_name) + if isinstance(raw_attr, classmethod): + method = method.__func__ + cloned_method = _clone_function(method) + + method_to_set: Any + if isinstance(raw_attr, staticmethod): + method_to_set = staticmethod(cloned_method) + elif isinstance(raw_attr, classmethod): + method_to_set = classmethod(cloned_method) + else: + method_to_set = cloned_method + + setattr(cls, method_name, method_to_set) + f = getattr(cls, method_name) + if isinstance(raw_attr, classmethod): + f = f.__func__ + # Annotate that cls owns this method so we can check that later. + tags["owner"] = cls + else: + f = func + + try: + f._lazy_xp_function = tags # pylint: disable=protected-access # pyright: ignore[reportFunctionMemberAccess] + except AttributeError: # @cython.vectorize + _ufuncs_tags[f] = tags + + +def patch_lazy_xp_functions( + request: pytest.FixtureRequest, + monkeypatch: pytest.MonkeyPatch | None = None, + *, + xp: ModuleType, +) -> contextlib.AbstractContextManager[None]: + """ + Test lazy execution of functions tagged with :func:`lazy_xp_function`. + + If ``xp==jax.numpy``, search for all functions and methods which have been tagged + with :func:`lazy_xp_function` in the globals of the module that defines the current + test, as well as in the ``lazy_xp_modules`` list in the globals of the same module, + and wrap them with :func:`jax.jit`. + Unwrap them at the end of the test. + + If ``xp==dask.array``, wrap the functions with a decorator that disables + ``compute()`` and ``persist()`` and ensures that exceptions and warnings are raised + eagerly. + + This function should be typically called by your library's `xp` fixture that runs + tests on multiple backends:: + + @pytest.fixture(params=[ + numpy, + array_api_strict, + pytest.param(jax.numpy, marks=pytest.mark.thread_unsafe), + pytest.param(dask.array, marks=pytest.mark.thread_unsafe), + ]) + def xp(request): + with patch_lazy_xp_functions(request, xp=request.param): + yield request.param + + but it can be otherwise be called by the test itself too. + + Parameters + ---------- + request : pytest.FixtureRequest + Pytest fixture, as acquired by the test itself or by one of its fixtures. + monkeypatch : pytest.MonkeyPatch + Deprecated + xp : array_namespace + Array namespace to be tested. + + See Also + -------- + lazy_xp_function : Tag a function to be tested on lazy backends. + pytest.FixtureRequest : `request` test function parameter. + + Notes + ----- + This context manager monkey-patches modules and as such is thread unsafe + on Dask and JAX. If you run your test suite with + `pytest-run-parallel `_, + you should mark these backends with ``@pytest.mark.thread_unsafe``, as shown in + the example above. + """ + mod = cast(ModuleType, request.module) + search_targets: list[ModuleType | type] = [ + mod, + *cast(list[ModuleType], getattr(mod, "lazy_xp_modules", [])), + ] + # Also search for classes within the above modules which have had lazy_xp_function + # applied to methods through ``lazy_xp_function((cls, method_name))`` syntax. + # We might end up adding classes incidentally imported into modules, so using a + # set here to cut down on potential redundancy. + classes: set[type] = set() + for target in search_targets: + for obj in target.__dict__.values(): + if isinstance(obj, type): + classes.add(obj) + search_targets.extend(classes) + + to_revert: list[tuple[ModuleType | type, str, object]] = [] + + def temp_setattr(target: ModuleType | type, name: str, func: object) -> None: + """ + Variant of monkeypatch.setattr, which allows monkey-patching only selected + parameters of a test so that pytest-run-parallel can run on the remainder. + """ + assert hasattr(target, name) + # Need getattr_static because the attr could be a staticmethod or other + # descriptor and we don't want that to be stripped away. + original = getattr_static(target, name) + to_revert.append((target, name, original)) + setattr(target, name, func) + + if monkeypatch is not None: + warnings.warn( + ( + "The `monkeypatch` parameter is deprecated and will be removed in a " + "future version. " + "Use `patch_lazy_xp_function` as a context manager instead." + ), + DeprecationWarning, + stacklevel=2, + ) + # Enable using patch_lazy_xp_function not as a context manager + temp_setattr = monkeypatch.setattr # type: ignore[assignment] # pyright: ignore[reportAssignmentType] + + def iter_tagged() -> Iterator[ + tuple[ModuleType | type, str, Any, Callable[..., Any], dict[str, Any]] + ]: + for target in search_targets: + for name, attr in target.__dict__.items(): + # attr might be a staticmethod or classmethod. If so we need + # to peel it back and wrap the underlying function and later + # make sure not to accidentally replace it with a regular + # method. + func: Any = ( + attr.__func__ + if isinstance(attr, (staticmethod, classmethod)) + else attr + ) + tags: dict[str, Any] | None = None + with contextlib.suppress(AttributeError): + tags = func._lazy_xp_function # pylint: disable=protected-access + if tags is None: + with contextlib.suppress(KeyError, TypeError): + tags = _ufuncs_tags[func] + if tags is not None: + if isinstance(target, type) and tags.get("owner") is not target: + # There's a common pattern to wrap functions in namespace + # classes to bypass lazy_xp_function like this: + # + # class naked: + # myfunc = mymodule.myfunc + # + # To ensure this still works when checking for tags in + # attributes of classes, ensure that target is the actual + # owning class where func was defined. + continue + # put attr, and func in the outputs so we can later tell + # if this was a staticmethod or classmethod. + yield target, name, attr, func, tags + + wrapped: Any + if is_dask_namespace(xp): + for target, name, attr, func, tags in iter_tagged(): + n = tags["allow_dask_compute"] + if n is True: + n = 1_000_000 + elif n is False: + n = 0 + wrapped = _dask_wrap(func, n) + # If we're dealing with a staticmethod or classmethod, make + # sure things stay that way. + if isinstance(attr, staticmethod): + wrapped = staticmethod(wrapped) + elif isinstance(attr, classmethod): + wrapped = classmethod(wrapped) + temp_setattr(target, name, wrapped) + + elif is_jax_namespace(xp): + for target, name, attr, func, tags in iter_tagged(): + if tags["jax_jit"]: + wrapped = jax_autojit(func) + # If we're dealing with a staticmethod or classmethod, make + # sure things stay that way. + if isinstance(attr, staticmethod): + wrapped = staticmethod(wrapped) + elif isinstance(attr, classmethod): + wrapped = classmethod(wrapped) + temp_setattr(target, name, wrapped) + + # We can't just decorate patch_lazy_xp_functions with + # @contextlib.contextmanager because it would not work with the + # deprecated monkeypatch when not used as a context manager. + @contextlib.contextmanager + def revert_on_exit() -> Generator[None]: + try: + yield + finally: + for target, name, orig_func in to_revert: + setattr(target, name, orig_func) + + return revert_on_exit() + + +class CountingDaskScheduler(SchedulerGetCallable): + """ + Dask scheduler that counts how many times `dask.compute` is called. + + If the number of times exceeds 'max_count', it raises an error. + This is a wrapper around Dask's own 'synchronous' scheduler. + + Parameters + ---------- + max_count : int + Maximum number of allowed calls to `dask.compute`. + msg : str + Assertion to raise when the count exceeds `max_count`. + """ + + count: int + max_count: int + msg: str + + def __init__(self, max_count: int, msg: str): # numpydoc ignore=GL08 + self.count = 0 + self.max_count = max_count + self.msg = msg + + @override + def __call__( + self, dsk: Graph, keys: Sequence[Key] | Key, **kwargs: Any + ) -> Any: # numpydoc ignore=GL08 + import dask + + self.count += 1 + # This should yield a nice traceback to the + # offending line in the user's code + assert self.count <= self.max_count, self.msg + + return dask.get(dsk, keys, **kwargs) # type: ignore[attr-defined] # pyright: ignore[reportPrivateImportUsage] + + +def _dask_wrap( + func: Callable[P, T], n: int +) -> Callable[P, T]: # numpydoc ignore=PR01,RT01 + """ + Wrap `func` to raise if it attempts to call `dask.compute` more than `n` times. + + After the function returns, materialize the graph in order to re-raise exceptions. + """ + import dask + import dask.array as da + + func_name = getattr(func, "__name__", str(func)) + n_str = f"only up to {n}" if n else "no" + msg = ( + f"Called `dask.compute()` or `dask.persist()` {n + 1} times, " + f"but {n_str} calls are allowed. Set " + f"`lazy_xp_function({func_name}, allow_dask_compute={n + 1})` " + "to allow for more (but note that this will harm performance). " + ) + + @wraps(func) + def wrapper(*args: P.args, **kwargs: P.kwargs) -> T: # numpydoc ignore=GL08 + scheduler = CountingDaskScheduler(n, msg) + with dask.config.set({"scheduler": scheduler}): # pyright: ignore[reportPrivateImportUsage] + out = func(*args, **kwargs) + + # Block until the graph materializes and reraise exceptions. This allows + # `pytest.raises` and `pytest.warns` to work as expected. Note that this would + # not work on scheduler='distributed', as it would not block. + arrays, rest = pickle_flatten(out, da.Array) + arrays = dask.persist(arrays, scheduler="threads")[0] # type: ignore[attr-defined,no-untyped-call] # pyright: ignore[reportPrivateImportUsage] + return pickle_unflatten(arrays, rest) # pyright: ignore[reportUnknownArgumentType] + + return wrapper diff --git a/.venv/lib/python3.12/site-packages/scipy/_external/cobyqa/__init__.py b/.venv/lib/python3.12/site-packages/scipy/_external/cobyqa/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..2654c8a3d21ed3db207f6204816d852e6b4c0efc --- /dev/null +++ b/.venv/lib/python3.12/site-packages/scipy/_external/cobyqa/__init__.py @@ -0,0 +1,20 @@ +from .main import minimize +from .utils import show_versions + +# PEP0440 compatible formatted version, see: +# https://www.python.org/dev/peps/pep-0440/ +# +# Final release markers: +# X.Y.0 # For first release after an increment in Y +# X.Y.Z # For bugfix releases +# +# Admissible pre-release markers: +# X.YaN # Alpha release +# X.YbN # Beta release +# X.YrcN # Release Candidate +# +# Dev branch marker is: 'X.Y.dev' or 'X.Y.devN' where N is an integer. +# 'X.Y.dev0' is the canonical version of 'X.Y.dev'. +__version__ = "1.1.3" + +__all__ = ["minimize", "show_versions"] diff --git a/.venv/lib/python3.12/site-packages/scipy/_external/cobyqa/framework.py b/.venv/lib/python3.12/site-packages/scipy/_external/cobyqa/framework.py new file mode 100644 index 0000000000000000000000000000000000000000..9afea66281067e27a486ff317a4bffa03ec3e68b --- /dev/null +++ b/.venv/lib/python3.12/site-packages/scipy/_external/cobyqa/framework.py @@ -0,0 +1,1240 @@ +import warnings + +import numpy as np +from scipy.optimize import lsq_linear + +from .models import Models, Quadratic +from .settings import Options, Constants +from .subsolvers import ( + cauchy_geometry, + spider_geometry, + normal_byrd_omojokun, + tangential_byrd_omojokun, + constrained_tangential_byrd_omojokun, +) +from .subsolvers.optim import qr_tangential_byrd_omojokun +from .utils import get_arrays_tol + + +TINY = np.finfo(float).tiny +EPS = np.finfo(float).eps + + +class TrustRegion: + """ + Trust-region framework. + """ + + def __init__(self, pb, options, constants): + """ + Initialize the trust-region framework. + + Parameters + ---------- + pb : `cobyqa.problem.Problem` + Problem to solve. + options : dict + Options of the solver. + constants : dict + Constants of the solver. + + Raises + ------ + `cobyqa.utils.MaxEvalError` + If the maximum number of evaluations is reached. + `cobyqa.utils.TargetSuccess` + If a nearly feasible point has been found with an objective + function value below the target. + `cobyqa.utils.FeasibleSuccess` + If a feasible point has been found for a feasibility problem. + `numpy.linalg.LinAlgError` + If the initial interpolation system is ill-defined. + """ + # Set the initial penalty parameter. + self._penalty = 0.0 + + # Initialize the models. + self._pb = pb + self._models = Models(self._pb, options, self.penalty) + self._constants = constants + + # Set the index of the best interpolation point. + self._best_index = 0 + self.set_best_index() + + # Set the initial Lagrange multipliers. + self._lm_linear_ub = np.zeros(self.m_linear_ub) + self._lm_linear_eq = np.zeros(self.m_linear_eq) + self._lm_nonlinear_ub = np.zeros(self.m_nonlinear_ub) + self._lm_nonlinear_eq = np.zeros(self.m_nonlinear_eq) + self.set_multipliers(self.x_best) + + # Set the initial trust-region radius and the resolution. + self._resolution = options[Options.RHOBEG] + self._radius = self.resolution + + @property + def n(self): + """ + Number of variables. + + Returns + ------- + int + Number of variables. + """ + return self._pb.n + + @property + def m_linear_ub(self): + """ + Number of linear inequality constraints. + + Returns + ------- + int + Number of linear inequality constraints. + """ + return self._pb.m_linear_ub + + @property + def m_linear_eq(self): + """ + Number of linear equality constraints. + + Returns + ------- + int + Number of linear equality constraints. + """ + return self._pb.m_linear_eq + + @property + def m_nonlinear_ub(self): + """ + Number of nonlinear inequality constraints. + + Returns + ------- + int + Number of nonlinear inequality constraints. + """ + return self._pb.m_nonlinear_ub + + @property + def m_nonlinear_eq(self): + """ + Number of nonlinear equality constraints. + + Returns + ------- + int + Number of nonlinear equality constraints. + """ + return self._pb.m_nonlinear_eq + + @property + def radius(self): + """ + Trust-region radius. + + Returns + ------- + float + Trust-region radius. + """ + return self._radius + + @radius.setter + def radius(self, radius): + """ + Set the trust-region radius. + + Parameters + ---------- + radius : float + New trust-region radius. + """ + self._radius = radius + if ( + self.radius + <= self._constants[Constants.DECREASE_RADIUS_THRESHOLD] + * self.resolution + ): + self._radius = self.resolution + + @property + def resolution(self): + """ + Resolution of the trust-region framework. + + The resolution is a lower bound on the trust-region radius. + + Returns + ------- + float + Resolution of the trust-region framework. + """ + return self._resolution + + @resolution.setter + def resolution(self, resolution): + """ + Set the resolution of the trust-region framework. + + Parameters + ---------- + resolution : float + New resolution of the trust-region framework. + """ + self._resolution = resolution + + @property + def penalty(self): + """ + Penalty parameter. + + Returns + ------- + float + Penalty parameter. + """ + return self._penalty + + @property + def models(self): + """ + Models of the objective function and constraints. + + Returns + ------- + `cobyqa.models.Models` + Models of the objective function and constraints. + """ + return self._models + + @property + def best_index(self): + """ + Index of the best interpolation point. + + Returns + ------- + int + Index of the best interpolation point. + """ + return self._best_index + + @property + def x_best(self): + """ + Best interpolation point. + + Its value is interpreted as relative to the origin, not the base point. + + Returns + ------- + `numpy.ndarray` + Best interpolation point. + """ + return self.models.interpolation.point(self.best_index) + + @property + def fun_best(self): + """ + Value of the objective function at `x_best`. + + Returns + ------- + float + Value of the objective function at `x_best`. + """ + return self.models.fun_val[self.best_index] + + @property + def cub_best(self): + """ + Values of the nonlinear inequality constraints at `x_best`. + + Returns + ------- + `numpy.ndarray`, shape (m_nonlinear_ub,) + Values of the nonlinear inequality constraints at `x_best`. + """ + return self.models.cub_val[self.best_index, :] + + @property + def ceq_best(self): + """ + Values of the nonlinear equality constraints at `x_best`. + + Returns + ------- + `numpy.ndarray`, shape (m_nonlinear_eq,) + Values of the nonlinear equality constraints at `x_best`. + """ + return self.models.ceq_val[self.best_index, :] + + def lag_model(self, x): + """ + Evaluate the Lagrangian model at a given point. + + Parameters + ---------- + x : `numpy.ndarray`, shape (n,) + Point at which the Lagrangian model is evaluated. + + Returns + ------- + float + Value of the Lagrangian model at `x`. + """ + return ( + self.models.fun(x) + + self._lm_linear_ub + @ (self._pb.linear.a_ub @ x - self._pb.linear.b_ub) + + self._lm_linear_eq + @ (self._pb.linear.a_eq @ x - self._pb.linear.b_eq) + + self._lm_nonlinear_ub @ self.models.cub(x) + + self._lm_nonlinear_eq @ self.models.ceq(x) + ) + + def lag_model_grad(self, x): + """ + Evaluate the gradient of the Lagrangian model at a given point. + + Parameters + ---------- + x : `numpy.ndarray`, shape (n,) + Point at which the gradient of the Lagrangian model is evaluated. + + Returns + ------- + `numpy.ndarray`, shape (n,) + Gradient of the Lagrangian model at `x`. + """ + return ( + self.models.fun_grad(x) + + self._lm_linear_ub @ self._pb.linear.a_ub + + self._lm_linear_eq @ self._pb.linear.a_eq + + self._lm_nonlinear_ub @ self.models.cub_grad(x) + + self._lm_nonlinear_eq @ self.models.ceq_grad(x) + ) + + def lag_model_hess(self): + """ + Evaluate the Hessian matrix of the Lagrangian model at a given point. + + Returns + ------- + `numpy.ndarray`, shape (n, n) + Hessian matrix of the Lagrangian model at `x`. + """ + hess = self.models.fun_hess() + if self.m_nonlinear_ub > 0: + hess += self._lm_nonlinear_ub @ self.models.cub_hess() + if self.m_nonlinear_eq > 0: + hess += self._lm_nonlinear_eq @ self.models.ceq_hess() + return hess + + def lag_model_hess_prod(self, v): + """ + Evaluate the right product of the Hessian matrix of the Lagrangian + model with a given vector. + + Parameters + ---------- + v : `numpy.ndarray`, shape (n,) + Vector with which the Hessian matrix of the Lagrangian model is + multiplied from the right. + + Returns + ------- + `numpy.ndarray`, shape (n,) + Right product of the Hessian matrix of the Lagrangian model with + `v`. + """ + return ( + self.models.fun_hess_prod(v) + + self._lm_nonlinear_ub @ self.models.cub_hess_prod(v) + + self._lm_nonlinear_eq @ self.models.ceq_hess_prod(v) + ) + + def lag_model_curv(self, v): + """ + Evaluate the curvature of the Lagrangian model along a given direction. + + Parameters + ---------- + v : `numpy.ndarray`, shape (n,) + Direction along which the curvature of the Lagrangian model is + evaluated. + + Returns + ------- + float + Curvature of the Lagrangian model along `v`. + """ + return ( + self.models.fun_curv(v) + + self._lm_nonlinear_ub @ self.models.cub_curv(v) + + self._lm_nonlinear_eq @ self.models.ceq_curv(v) + ) + + def sqp_fun(self, step): + """ + Evaluate the objective function of the SQP subproblem. + + Parameters + ---------- + step : `numpy.ndarray`, shape (n,) + Step along which the objective function of the SQP subproblem is + evaluated. + + Returns + ------- + float + Value of the objective function of the SQP subproblem along `step`. + """ + return step @ ( + self.models.fun_grad(self.x_best) + + 0.5 * self.lag_model_hess_prod(step) + ) + + def sqp_cub(self, step): + """ + Evaluate the linearization of the nonlinear inequality constraints. + + Parameters + ---------- + step : `numpy.ndarray`, shape (n,) + Step along which the linearization of the nonlinear inequality + constraints is evaluated. + + Returns + ------- + `numpy.ndarray`, shape (m_nonlinear_ub,) + Value of the linearization of the nonlinear inequality constraints + along `step`. + """ + return ( + self.models.cub(self.x_best) + + self.models.cub_grad(self.x_best) @ step + ) + + def sqp_ceq(self, step): + """ + Evaluate the linearization of the nonlinear equality constraints. + + Parameters + ---------- + step : `numpy.ndarray`, shape (n,) + Step along which the linearization of the nonlinear equality + constraints is evaluated. + + Returns + ------- + `numpy.ndarray`, shape (m_nonlinear_ub,) + Value of the linearization of the nonlinear equality constraints + along `step`. + """ + return ( + self.models.ceq(self.x_best) + + self.models.ceq_grad(self.x_best) @ step + ) + + def merit(self, x, fun_val=None, cub_val=None, ceq_val=None): + """ + Evaluate the merit function at a given point. + + Parameters + ---------- + x : `numpy.ndarray`, shape (n,) + Point at which the merit function is evaluated. + fun_val : float, optional + Value of the objective function at `x`. If not provided, the + objective function is evaluated at `x`. + cub_val : `numpy.ndarray`, shape (m_nonlinear_ub,), optional + Values of the nonlinear inequality constraints. If not provided, + the nonlinear inequality constraints are evaluated at `x`. + ceq_val : `numpy.ndarray`, shape (m_nonlinear_eq,), optional + Values of the nonlinear equality constraints. If not provided, + the nonlinear equality constraints are evaluated at `x`. + + Returns + ------- + float + Value of the merit function at `x`. + """ + if fun_val is None or cub_val is None or ceq_val is None: + fun_val, cub_val, ceq_val = self._pb(x, self.penalty) + m_val = fun_val + if self._penalty > 0.0: + c_val = self._pb.violation(x, cub_val=cub_val, ceq_val=ceq_val) + if np.count_nonzero(c_val): + m_val += self._penalty * np.linalg.norm(c_val) + return m_val + + def get_constraint_linearizations(self, x): + """ + Get the linearizations of the constraints at a given point. + + Parameters + ---------- + x : `numpy.ndarray`, shape (n,) + Point at which the linearizations of the constraints are evaluated. + + Returns + ------- + `numpy.ndarray`, shape (m_linear_ub + m_nonlinear_ub, n) + Left-hand side matrix of the linearized inequality constraints. + `numpy.ndarray`, shape (m_linear_ub + m_nonlinear_ub,) + Right-hand side vector of the linearized inequality constraints. + `numpy.ndarray`, shape (m_linear_eq + m_nonlinear_eq, n) + Left-hand side matrix of the linearized equality constraints. + `numpy.ndarray`, shape (m_linear_eq + m_nonlinear_eq,) + Right-hand side vector of the linearized equality constraints. + """ + aub = np.block( + [ + [self._pb.linear.a_ub], + [self.models.cub_grad(x)], + ] + ) + bub = np.block( + [ + self._pb.linear.b_ub - self._pb.linear.a_ub @ x, + -self.models.cub(x), + ] + ) + aeq = np.block( + [ + [self._pb.linear.a_eq], + [self.models.ceq_grad(x)], + ] + ) + beq = np.block( + [ + self._pb.linear.b_eq - self._pb.linear.a_eq @ x, + -self.models.ceq(x), + ] + ) + return aub, bub, aeq, beq + + def get_trust_region_step(self, options): + """ + Get the trust-region step. + + The trust-region step is computed by solving the derivative-free + trust-region SQP subproblem using a Byrd-Omojokun composite-step + approach. For more details, see Section 5.2.3 of [1]_. + + Parameters + ---------- + options : dict + Options of the solver. + + Returns + ------- + `numpy.ndarray`, shape (n,) + Normal step. + `numpy.ndarray`, shape (n,) + Tangential step. + + References + ---------- + .. [1] T. M. Ragonneau. *Model-Based Derivative-Free Optimization + Methods and Software*. PhD thesis, Department of Applied + Mathematics, The Hong Kong Polytechnic University, Hong Kong, China, + 2022. URL: https://theses.lib.polyu.edu.hk/handle/200/12294. + """ + # Evaluate the linearizations of the constraints. + aub, bub, aeq, beq = self.get_constraint_linearizations(self.x_best) + xl = self._pb.bounds.xl - self.x_best + xu = self._pb.bounds.xu - self.x_best + + # Evaluate the normal step. + radius = self._constants[Constants.BYRD_OMOJOKUN_FACTOR] * self.radius + normal_step = normal_byrd_omojokun( + aub, + bub, + aeq, + beq, + xl, + xu, + radius, + options[Options.DEBUG], + **self._constants, + ) + if options[Options.DEBUG]: + tol = get_arrays_tol(xl, xu) + if (np.any(normal_step + tol < xl) + or np.any(xu < normal_step - tol)): + warnings.warn( + "the normal step does not respect the bound constraint.", + RuntimeWarning, + 2, + ) + if np.linalg.norm(normal_step) > 1.1 * radius: + warnings.warn( + "the normal step does not respect the trust-region " + "constraint.", + RuntimeWarning, + 2, + ) + + # Evaluate the tangential step. + radius = np.sqrt(self.radius**2.0 - normal_step @ normal_step) + xl -= normal_step + xu -= normal_step + bub = np.maximum(bub - aub @ normal_step, 0.0) + g_best = self.models.fun_grad(self.x_best) + self.lag_model_hess_prod( + normal_step + ) + if self._pb.type in ["unconstrained", "bound-constrained"]: + tangential_step = tangential_byrd_omojokun( + g_best, + self.lag_model_hess_prod, + xl, + xu, + radius, + options[Options.DEBUG], + **self._constants, + ) + else: + tangential_step = constrained_tangential_byrd_omojokun( + g_best, + self.lag_model_hess_prod, + xl, + xu, + aub, + bub, + aeq, + radius, + options["debug"], + **self._constants, + ) + if options[Options.DEBUG]: + tol = get_arrays_tol(xl, xu) + if np.any(tangential_step + tol < xl) or np.any( + xu < tangential_step - tol + ): + warnings.warn( + "The tangential step does not respect the bound " + "constraints.", + RuntimeWarning, + 2, + ) + if ( + np.linalg.norm(normal_step + tangential_step) + > 1.1 * np.sqrt(2.0) * self.radius + ): + warnings.warn( + "The trial step does not respect the trust-region " + "constraint.", + RuntimeWarning, + 2, + ) + return normal_step, tangential_step + + def get_geometry_step(self, k_new, options): + """ + Get the geometry-improving step. + + Three different geometry-improving steps are computed and the best one + is returned. For more details, see Section 5.2.7 of [1]_. + + Parameters + ---------- + k_new : int + Index of the interpolation point to be modified. + options : dict + Options of the solver. + + Returns + ------- + `numpy.ndarray`, shape (n,) + Geometry-improving step. + + Raises + ------ + `numpy.linalg.LinAlgError` + If the computation of a determinant fails. + + References + ---------- + .. [1] T. M. Ragonneau. *Model-Based Derivative-Free Optimization + Methods and Software*. PhD thesis, Department of Applied + Mathematics, The Hong Kong Polytechnic University, Hong Kong, China, + 2022. URL: https://theses.lib.polyu.edu.hk/handle/200/12294. + """ + if options[Options.DEBUG]: + assert ( + k_new != self.best_index + ), "The index `k_new` must be different from the best index." + + # Build the k_new-th Lagrange polynomial. + coord_vec = np.squeeze(np.eye(1, self.models.npt, k_new)) + lag = Quadratic( + self.models.interpolation, + coord_vec, + options[Options.DEBUG], + ) + g_lag = lag.grad(self.x_best, self.models.interpolation) + + # Compute a simple constrained Cauchy step. + xl = self._pb.bounds.xl - self.x_best + xu = self._pb.bounds.xu - self.x_best + step = cauchy_geometry( + 0.0, + g_lag, + lambda v: lag.curv(v, self.models.interpolation), + xl, + xu, + self.radius, + options[Options.DEBUG], + ) + sigma = self.models.determinants(self.x_best + step, k_new) + + # Compute the solution on the straight lines joining the interpolation + # points to the k-th one, and choose it if it provides a larger value + # of the determinant of the interpolation system in absolute value. + xpt = ( + self.models.interpolation.xpt + - self.models.interpolation.xpt[:, self.best_index, np.newaxis] + ) + xpt[:, [0, self.best_index]] = xpt[:, [self.best_index, 0]] + step_alt = spider_geometry( + 0.0, + g_lag, + lambda v: lag.curv(v, self.models.interpolation), + xpt[:, 1:], + xl, + xu, + self.radius, + options[Options.DEBUG], + ) + sigma_alt = self.models.determinants(self.x_best + step_alt, k_new) + if abs(sigma_alt) > abs(sigma): + step = step_alt + sigma = sigma_alt + + # Compute a Cauchy step on the tangent space of the active constraints. + if self._pb.type in [ + "linearly constrained", + "nonlinearly constrained", + ]: + aub, bub, aeq, beq = ( + self.get_constraint_linearizations(self.x_best)) + tol_bd = get_arrays_tol(xl, xu) + tol_ub = get_arrays_tol(bub) + free_xl = xl <= -tol_bd + free_xu = xu >= tol_bd + free_ub = bub >= tol_ub + + # Compute the Cauchy step. + n_act, q = qr_tangential_byrd_omojokun( + aub, + aeq, + free_xl, + free_xu, + free_ub, + ) + g_lag_proj = q[:, n_act:] @ (q[:, n_act:].T @ g_lag) + norm_g_lag_proj = np.linalg.norm(g_lag_proj) + if 0 < n_act < self._pb.n and norm_g_lag_proj > TINY * self.radius: + step_alt = (self.radius / norm_g_lag_proj) * g_lag_proj + if lag.curv(step_alt, self.models.interpolation) < 0.0: + step_alt = -step_alt + + # Evaluate the constraint violation at the Cauchy step. + cbd = np.block([xl - step_alt, step_alt - xu]) + cub = aub @ step_alt - bub + ceq = aeq @ step_alt - beq + maxcv_val = max( + np.max(array, initial=0.0) + for array in [cbd, cub, np.abs(ceq)] + ) + + # Accept the new step if it is nearly feasible and do not + # drastically worsen the determinant of the interpolation + # system in absolute value. + tol = np.max(np.abs(step_alt[~free_xl]), initial=0.0) + tol = np.max(np.abs(step_alt[~free_xu]), initial=tol) + tol = np.max(np.abs(aub[~free_ub, :] @ step_alt), initial=tol) + tol = min(10.0 * tol, 1e-2 * np.linalg.norm(step_alt)) + if maxcv_val <= tol: + sigma_alt = self.models.determinants( + self.x_best + step_alt, k_new + ) + if abs(sigma_alt) >= 0.1 * abs(sigma): + step = np.clip(step_alt, xl, xu) + + if options[Options.DEBUG]: + tol = get_arrays_tol(xl, xu) + if np.any(step + tol < xl) or np.any(xu < step - tol): + warnings.warn( + "The geometry step does not respect the bound " + "constraints.", + RuntimeWarning, + 2, + ) + if np.linalg.norm(step) > 1.1 * self.radius: + warnings.warn( + "The geometry step does not respect the " + "trust-region constraint.", + RuntimeWarning, + 2, + ) + return step + + def get_second_order_correction_step(self, step, options): + """ + Get the second-order correction step. + + Parameters + ---------- + step : `numpy.ndarray`, shape (n,) + Trust-region step. + options : dict + Options of the solver. + + Returns + ------- + `numpy.ndarray`, shape (n,) + Second-order correction step. + """ + # Evaluate the linearizations of the constraints. + aub, bub, aeq, beq = self.get_constraint_linearizations(self.x_best) + xl = self._pb.bounds.xl - self.x_best + xu = self._pb.bounds.xu - self.x_best + radius = np.linalg.norm(step) + soc_step = normal_byrd_omojokun( + aub, + bub, + aeq, + beq, + xl, + xu, + radius, + options[Options.DEBUG], + **self._constants, + ) + if options[Options.DEBUG]: + tol = get_arrays_tol(xl, xu) + if np.any(soc_step + tol < xl) or np.any(xu < soc_step - tol): + warnings.warn( + "The second-order correction step does not " + "respect the bound constraints.", + RuntimeWarning, + 2, + ) + if np.linalg.norm(soc_step) > 1.1 * radius: + warnings.warn( + "The second-order correction step does not " + "respect the trust-region constraint.", + RuntimeWarning, + 2, + ) + return soc_step + + def get_reduction_ratio(self, step, fun_val, cub_val, ceq_val): + """ + Get the reduction ratio. + + Parameters + ---------- + step : `numpy.ndarray`, shape (n,) + Trust-region step. + fun_val : float + Objective function value at the trial point. + cub_val : `numpy.ndarray`, shape (m_nonlinear_ub,) + Nonlinear inequality constraint values at the trial point. + ceq_val : `numpy.ndarray`, shape (m_nonlinear_eq,) + Nonlinear equality constraint values at the trial point. + + Returns + ------- + float + Reduction ratio. + """ + merit_old = self.merit( + self.x_best, + self.fun_best, + self.cub_best, + self.ceq_best, + ) + merit_new = self.merit(self.x_best + step, fun_val, cub_val, ceq_val) + merit_model_old = self.merit( + self.x_best, + 0.0, + self.models.cub(self.x_best), + self.models.ceq(self.x_best), + ) + merit_model_new = self.merit( + self.x_best + step, + self.sqp_fun(step), + self.sqp_cub(step), + self.sqp_ceq(step), + ) + if abs(merit_model_old - merit_model_new) > TINY * abs( + merit_old - merit_new + ): + return (merit_old - merit_new) / abs( + merit_model_old - merit_model_new + ) + else: + return -1.0 + + def increase_penalty(self, step): + """ + Increase the penalty parameter. + + Parameters + ---------- + step : `numpy.ndarray`, shape (n,) + Trust-region step. + """ + aub, bub, aeq, beq = self.get_constraint_linearizations(self.x_best) + viol_diff = max( + np.linalg.norm( + np.block( + [ + np.maximum(0.0, -bub), + beq, + ] + ) + ) + - np.linalg.norm( + np.block( + [ + np.maximum(0.0, aub @ step - bub), + aeq @ step - beq, + ] + ) + ), + 0.0, + ) + sqp_val = self.sqp_fun(step) + + threshold = np.linalg.norm( + np.block( + [ + self._lm_linear_ub, + self._lm_linear_eq, + self._lm_nonlinear_ub, + self._lm_nonlinear_eq, + ] + ) + ) + if abs(viol_diff) > TINY * abs(sqp_val): + threshold = max(threshold, sqp_val / viol_diff) + best_index_save = self.best_index + if ( + self._penalty + <= self._constants[Constants.PENALTY_INCREASE_THRESHOLD] + * threshold + ): + self._penalty = max( + self._constants[Constants.PENALTY_INCREASE_FACTOR] * threshold, + 1.0, + ) + self.set_best_index() + return best_index_save == self.best_index + + def decrease_penalty(self): + """ + Decrease the penalty parameter. + """ + self._penalty = min(self._penalty, self._get_low_penalty()) + self.set_best_index() + + def set_best_index(self): + """ + Set the index of the best point. + """ + best_index = self.best_index + m_best = self.merit( + self.x_best, + self.models.fun_val[best_index], + self.models.cub_val[best_index, :], + self.models.ceq_val[best_index, :], + ) + r_best = self._pb.maxcv( + self.x_best, + self.models.cub_val[best_index, :], + self.models.ceq_val[best_index, :], + ) + tol = ( + 10.0 + * EPS + * max(self.models.n, self.models.npt) + * max(abs(m_best), 1.0) + ) + for k in range(self.models.npt): + if k != self.best_index: + x_val = self.models.interpolation.point(k) + m_val = self.merit( + x_val, + self.models.fun_val[k], + self.models.cub_val[k, :], + self.models.ceq_val[k, :], + ) + r_val = self._pb.maxcv( + x_val, + self.models.cub_val[k, :], + self.models.ceq_val[k, :], + ) + if m_val < m_best or (m_val < m_best + tol and r_val < r_best): + best_index = k + m_best = m_val + r_best = r_val + self._best_index = best_index + + def get_index_to_remove(self, x_new=None): + """ + Get the index of the interpolation point to remove. + + If `x_new` is not provided, the index returned should be used during + the geometry-improvement phase. Otherwise, the index returned is the + best index for included `x_new` in the interpolation set. + + Parameters + ---------- + x_new : `numpy.ndarray`, shape (n,), optional + New point to be included in the interpolation set. + + Returns + ------- + int + Index of the interpolation point to remove. + float + Distance between `x_best` and the removed point. + + Raises + ------ + `numpy.linalg.LinAlgError` + If the computation of a determinant fails. + """ + dist_sq = np.sum( + ( + self.models.interpolation.xpt + - self.models.interpolation.xpt[:, self.best_index, np.newaxis] + ) + ** 2.0, + axis=0, + ) + if x_new is None: + sigma = 1.0 + weights = dist_sq + else: + sigma = self.models.determinants(x_new) + weights = ( + np.maximum( + 1.0, + dist_sq + / max( + self._constants[Constants.LOW_RADIUS_FACTOR] + * self.radius, + self.resolution, + ) + ** 2.0, + ) + ** 3.0 + ) + weights[self.best_index] = -1.0 # do not remove the best point + k_max = np.argmax(weights * np.abs(sigma)) + return k_max, np.sqrt(dist_sq[k_max]) + + def update_radius(self, step, ratio): + """ + Update the trust-region radius. + + Parameters + ---------- + step : `numpy.ndarray`, shape (n,) + Trust-region step. + ratio : float + Reduction ratio. + """ + s_norm = np.linalg.norm(step) + if ratio <= self._constants[Constants.LOW_RATIO]: + self.radius *= self._constants[Constants.DECREASE_RADIUS_FACTOR] + elif ratio <= self._constants[Constants.HIGH_RATIO]: + self.radius = max( + self._constants[Constants.DECREASE_RADIUS_FACTOR] + * self.radius, + s_norm, + ) + else: + self.radius = min( + self._constants[Constants.INCREASE_RADIUS_FACTOR] + * self.radius, + max( + self._constants[Constants.DECREASE_RADIUS_FACTOR] + * self.radius, + self._constants[Constants.INCREASE_RADIUS_THRESHOLD] + * s_norm, + ), + ) + + def enhance_resolution(self, options): + """ + Enhance the resolution of the trust-region framework. + + Parameters + ---------- + options : dict + Options of the solver. + """ + if ( + self._constants[Constants.LARGE_RESOLUTION_THRESHOLD] + * options[Options.RHOEND] + < self.resolution + ): + self.resolution *= self._constants[ + Constants.DECREASE_RESOLUTION_FACTOR + ] + elif ( + self._constants[Constants.MODERATE_RESOLUTION_THRESHOLD] + * options[Options.RHOEND] + < self.resolution + ): + self.resolution = np.sqrt(self.resolution + * options[Options.RHOEND]) + else: + self.resolution = options[Options.RHOEND] + + # Reduce the trust-region radius. + self._radius = max( + self._constants[Constants.DECREASE_RADIUS_FACTOR] * self._radius, + self.resolution, + ) + + def shift_x_base(self, options): + """ + Shift the base point to `x_best`. + + Parameters + ---------- + options : dict + Options of the solver. + """ + self.models.shift_x_base(np.copy(self.x_best), options) + + def set_multipliers(self, x): + """ + Set the Lagrange multipliers. + + This method computes and set the Lagrange multipliers of the linear and + nonlinear constraints to be the QP multipliers. + + Parameters + ---------- + x : `numpy.ndarray`, shape (n,) + Point at which the Lagrange multipliers are computed. + """ + # Build the constraints of the least-squares problem. + incl_linear_ub = self._pb.linear.a_ub @ x >= self._pb.linear.b_ub + incl_nonlinear_ub = self.cub_best >= 0.0 + incl_xl = self._pb.bounds.xl >= x + incl_xu = self._pb.bounds.xu <= x + m_linear_ub = np.count_nonzero(incl_linear_ub) + m_nonlinear_ub = np.count_nonzero(incl_nonlinear_ub) + m_xl = np.count_nonzero(incl_xl) + m_xu = np.count_nonzero(incl_xu) + + if ( + m_linear_ub + m_nonlinear_ub + self.m_linear_eq + + self.m_nonlinear_eq > 0 + ): + identity = np.eye(self._pb.n) + c_jac = np.r_[ + -identity[incl_xl, :], + identity[incl_xu, :], + self._pb.linear.a_ub[incl_linear_ub, :], + self.models.cub_grad(x, incl_nonlinear_ub), + self._pb.linear.a_eq, + self.models.ceq_grad(x), + ] + + # Solve the least-squares problem. + g_best = self.models.fun_grad(x) + xl_lm = np.full(c_jac.shape[0], -np.inf) + xl_lm[: m_xl + m_xu + m_linear_ub + m_nonlinear_ub] = 0.0 + res = lsq_linear( + c_jac.T, + -g_best, + bounds=(xl_lm, np.inf), + method="bvls", + ) + + # Extract the Lagrange multipliers. + self._lm_linear_ub[incl_linear_ub] = res.x[ + m_xl + m_xu:m_xl + m_xu + m_linear_ub + ] + self._lm_linear_ub[~incl_linear_ub] = 0.0 + self._lm_nonlinear_ub[incl_nonlinear_ub] = res.x[ + m_xl + + m_xu + + m_linear_ub:m_xl + + m_xu + + m_linear_ub + + m_nonlinear_ub + ] + self._lm_nonlinear_ub[~incl_nonlinear_ub] = 0.0 + self._lm_linear_eq[:] = res.x[ + m_xl + + m_xu + + m_linear_ub + + m_nonlinear_ub:m_xl + + m_xu + + m_linear_ub + + m_nonlinear_ub + + self.m_linear_eq + ] + self._lm_nonlinear_eq[:] = res.x[ + m_xl + m_xu + m_linear_ub + m_nonlinear_ub + self.m_linear_eq: + ] + + def _get_low_penalty(self): + r_val_ub = np.c_[ + ( + self.models.interpolation.x_base[np.newaxis, :] + + self.models.interpolation.xpt.T + ) + @ self._pb.linear.a_ub.T + - self._pb.linear.b_ub[np.newaxis, :], + self.models.cub_val, + ] + r_val_eq = ( + self.models.interpolation.x_base[np.newaxis, :] + + self.models.interpolation.xpt.T + ) @ self._pb.linear.a_eq.T - self._pb.linear.b_eq[np.newaxis, :] + r_val_eq = np.block( + [ + r_val_eq, + -r_val_eq, + self.models.ceq_val, + -self.models.ceq_val, + ] + ) + r_val = np.block([r_val_ub, r_val_eq]) + c_min = np.nanmin(r_val, axis=0) + c_max = np.nanmax(r_val, axis=0) + indices = ( + c_min + < self._constants[Constants.THRESHOLD_RATIO_CONSTRAINTS] * c_max + ) + if np.any(indices): + f_min = np.nanmin(self.models.fun_val) + f_max = np.nanmax(self.models.fun_val) + c_min_neg = np.minimum(0.0, c_min[indices]) + c_diff = np.min(c_max[indices] - c_min_neg) + if c_diff > TINY * (f_max - f_min): + penalty = (f_max - f_min) / c_diff + else: + penalty = np.inf + else: + penalty = 0.0 + return penalty diff --git a/.venv/lib/python3.12/site-packages/scipy/_external/cobyqa/main.py b/.venv/lib/python3.12/site-packages/scipy/_external/cobyqa/main.py new file mode 100644 index 0000000000000000000000000000000000000000..01e5159e0dfebed9a78c6948cb99bfb1d744b6c7 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/scipy/_external/cobyqa/main.py @@ -0,0 +1,1506 @@ +import warnings + +import numpy as np +from scipy.optimize import ( + Bounds, + LinearConstraint, + NonlinearConstraint, + OptimizeResult, +) + +from .framework import TrustRegion +from .problem import ( + ObjectiveFunction, + BoundConstraints, + LinearConstraints, + NonlinearConstraints, + Problem, +) +from .utils import ( + MaxEvalError, + TargetSuccess, + CallbackSuccess, + FeasibleSuccess, + exact_1d_array, +) +from .settings import ( + ExitStatus, + Options, + Constants, + DEFAULT_OPTIONS, + DEFAULT_CONSTANTS, + PRINT_OPTIONS, +) + + +def minimize( + fun, + x0, + args=(), + bounds=None, + constraints=(), + callback=None, + options=None, + **kwargs, +): + r""" + Minimize a scalar function using the COBYQA method. + + The Constrained Optimization BY Quadratic Approximations (COBYQA) method is + a derivative-free optimization method designed to solve general nonlinear + optimization problems. A complete description of COBYQA is given in [3]_. + + Parameters + ---------- + fun : {callable, None} + Objective function to be minimized. + + ``fun(x, *args) -> float`` + + where ``x`` is an array with shape (n,) and `args` is a tuple. If `fun` + is ``None``, the objective function is assumed to be the zero function, + resulting in a feasibility problem. + x0 : array_like, shape (n,) + Initial guess. + args : tuple, optional + Extra arguments passed to the objective function. + bounds : {`scipy.optimize.Bounds`, array_like, shape (n, 2)}, optional + Bound constraints of the problem. It can be one of the cases below. + + #. An instance of `scipy.optimize.Bounds`. For the time being, the + argument ``keep_feasible`` is disregarded, and all the constraints + are considered unrelaxable and will be enforced. + #. An array with shape (n, 2). The bound constraints for ``x[i]`` are + ``bounds[i][0] <= x[i] <= bounds[i][1]``. Set ``bounds[i][0]`` to + :math:`-\infty` if there is no lower bound, and set ``bounds[i][1]`` + to :math:`\infty` if there is no upper bound. + + The COBYQA method always respect the bound constraints. + constraints : {Constraint, list}, optional + General constraints of the problem. It can be one of the cases below. + + #. An instance of `scipy.optimize.LinearConstraint`. The argument + ``keep_feasible`` is disregarded. + #. An instance of `scipy.optimize.NonlinearConstraint`. The arguments + ``jac``, ``hess``, ``keep_feasible``, ``finite_diff_rel_step``, and + ``finite_diff_jac_sparsity`` are disregarded. + + #. A list, each of whose elements are described in the cases above. + + callback : callable, optional + A callback executed at each objective function evaluation. The method + terminates if a ``StopIteration`` exception is raised by the callback + function. Its signature can be one of the following: + + ``callback(intermediate_result)`` + + where ``intermediate_result`` is a keyword parameter that contains an + instance of `scipy.optimize.OptimizeResult`, with attributes ``x`` + and ``fun``, being the point at which the objective function is + evaluated and the value of the objective function, respectively. The + name of the parameter must be ``intermediate_result`` for the callback + to be passed an instance of `scipy.optimize.OptimizeResult`. + + Alternatively, the callback function can have the signature: + + ``callback(xk)`` + + where ``xk`` is the point at which the objective function is evaluated. + Introspection is used to determine which of the signatures to invoke. + options : dict, optional + Options passed to the solver. Accepted keys are: + + disp : bool, optional + Whether to print information about the optimization procedure. + Default is ``False``. + maxfev : int, optional + Maximum number of function evaluations. Default is ``500 * n``. + maxiter : int, optional + Maximum number of iterations. Default is ``1000 * n``. + target : float, optional + Target on the objective function value. The optimization + procedure is terminated when the objective function value of a + feasible point is less than or equal to this target. Default is + ``-numpy.inf``. + feasibility_tol : float, optional + Tolerance on the constraint violation. If the maximum + constraint violation at a point is less than or equal to this + tolerance, the point is considered feasible. Default is + ``numpy.sqrt(numpy.finfo(float).eps)``. + radius_init : float, optional + Initial trust-region radius. Typically, this value should be in + the order of one tenth of the greatest expected change to `x0`. + Default is ``1.0``. + radius_final : float, optional + Final trust-region radius. It should indicate the accuracy + required in the final values of the variables. Default is + ``1e-6``. + nb_points : int, optional + Number of interpolation points used to build the quadratic + models of the objective and constraint functions. Default is + ``2 * n + 1``. + scale : bool, optional + Whether to scale the variables according to the bounds. Default + is ``False``. + filter_size : int, optional + Maximum number of points in the filter. The filter is used to + select the best point returned by the optimization procedure. + Default is ``sys.maxsize``. + store_history : bool, optional + Whether to store the history of the function evaluations. + Default is ``False``. + history_size : int, optional + Maximum number of function evaluations to store in the history. + Default is ``sys.maxsize``. + debug : bool, optional + Whether to perform additional checks during the optimization + procedure. This option should be used only for debugging + purposes and is highly discouraged to general users. Default is + ``False``. + + Other constants (from the keyword arguments) are described below. They + are not intended to be changed by general users. They should only be + changed by users with a deep understanding of the algorithm, who want + to experiment with different settings. + + Returns + ------- + `scipy.optimize.OptimizeResult` + Result of the optimization procedure, with the following fields: + + message : str + Description of the cause of the termination. + success : bool + Whether the optimization procedure terminated successfully. + status : int + Termination status of the optimization procedure. + x : `numpy.ndarray`, shape (n,) + Solution point. + fun : float + Objective function value at the solution point. + maxcv : float + Maximum constraint violation at the solution point. + nfev : int + Number of function evaluations. + nit : int + Number of iterations. + + If ``store_history`` is True, the result also has the following fields: + + fun_history : `numpy.ndarray`, shape (nfev,) + History of the objective function values. + maxcv_history : `numpy.ndarray`, shape (nfev,) + History of the maximum constraint violations. + + A description of the termination statuses is given below. + + .. list-table:: + :widths: 25 75 + :header-rows: 1 + + * - Exit status + - Description + * - 0 + - The lower bound for the trust-region radius has been reached. + * - 1 + - The target objective function value has been reached. + * - 2 + - All variables are fixed by the bound constraints. + * - 3 + - The callback requested to stop the optimization procedure. + * - 4 + - The feasibility problem received has been solved successfully. + * - 5 + - The maximum number of function evaluations has been exceeded. + * - 6 + - The maximum number of iterations has been exceeded. + * - -1 + - The bound constraints are infeasible. + * - -2 + - A linear algebra error occurred. + + Other Parameters + ---------------- + decrease_radius_factor : float, optional + Factor by which the trust-region radius is reduced when the reduction + ratio is low or negative. Default is ``0.5``. + increase_radius_factor : float, optional + Factor by which the trust-region radius is increased when the reduction + ratio is large. Default is ``numpy.sqrt(2.0)``. + increase_radius_threshold : float, optional + Threshold that controls the increase of the trust-region radius when + the reduction ratio is large. Default is ``2.0``. + decrease_radius_threshold : float, optional + Threshold used to determine whether the trust-region radius should be + reduced to the resolution. Default is ``1.4``. + decrease_resolution_factor : float, optional + Factor by which the resolution is reduced when the current value is far + from its final value. Default is ``0.1``. + large_resolution_threshold : float, optional + Threshold used to determine whether the resolution is far from its + final value. Default is ``250.0``. + moderate_resolution_threshold : float, optional + Threshold used to determine whether the resolution is close to its + final value. Default is ``16.0``. + low_ratio : float, optional + Threshold used to determine whether the reduction ratio is low. Default + is ``0.1``. + high_ratio : float, optional + Threshold used to determine whether the reduction ratio is high. + Default is ``0.7``. + very_low_ratio : float, optional + Threshold used to determine whether the reduction ratio is very low. + This is used to determine whether the models should be reset. Default + is ``0.01``. + penalty_increase_threshold : float, optional + Threshold used to determine whether the penalty parameter should be + increased. Default is ``1.5``. + penalty_increase_factor : float, optional + Factor by which the penalty parameter is increased. Default is ``2.0``. + short_step_threshold : float, optional + Factor used to determine whether the trial step is too short. Default + is ``0.5``. + low_radius_factor : float, optional + Factor used to determine which interpolation point should be removed + from the interpolation set at each iteration. Default is ``0.1``. + byrd_omojokun_factor : float, optional + Factor by which the trust-region radius is reduced for the computations + of the normal step in the Byrd-Omojokun composite-step approach. + Default is ``0.8``. + threshold_ratio_constraints : float, optional + Threshold used to determine which constraints should be taken into + account when decreasing the penalty parameter. Default is ``2.0``. + large_shift_factor : float, optional + Factor used to determine whether the point around which the quadratic + models are built should be updated. Default is ``10.0``. + large_gradient_factor : float, optional + Factor used to determine whether the models should be reset. Default is + ``10.0``. + resolution_factor : float, optional + Factor by which the resolution is decreased. Default is ``2.0``. + improve_tcg : bool, optional + Whether to improve the steps computed by the truncated conjugate + gradient method when the trust-region boundary is reached. Default is + ``True``. + + References + ---------- + .. [1] J. Nocedal and S. J. Wright. *Numerical Optimization*. Springer Ser. + Oper. Res. Financ. Eng. Springer, New York, NY, USA, second edition, + 2006. `doi:10.1007/978-0-387-40065-5 + `_. + .. [2] M. J. D. Powell. A direct search optimization method that models the + objective and constraint functions by linear interpolation. In S. Gomez + and J.-P. Hennart, editors, *Advances in Optimization and Numerical + Analysis*, volume 275 of Math. Appl., pages 51--67. Springer, Dordrecht, + Netherlands, 1994. `doi:10.1007/978-94-015-8330-5_4 + `_. + .. [3] T. M. Ragonneau. *Model-Based Derivative-Free Optimization Methods + and Software*. PhD thesis, Department of Applied Mathematics, The Hong + Kong Polytechnic University, Hong Kong, China, 2022. URL: + https://theses.lib.polyu.edu.hk/handle/200/12294. + + Examples + -------- + To demonstrate how to use `minimize`, we first minimize the Rosenbrock + function implemented in `scipy.optimize` in an unconstrained setting. + + .. testsetup:: + + import numpy as np + np.set_printoptions(precision=3, suppress=True) + + >>> from cobyqa import minimize + >>> from scipy.optimize import rosen + + To solve the problem using COBYQA, run: + + >>> x0 = [1.3, 0.7, 0.8, 1.9, 1.2] + >>> res = minimize(rosen, x0) + >>> res.x + array([1., 1., 1., 1., 1.]) + + To see how bound and constraints are handled using `minimize`, we solve + Example 16.4 of [1]_, defined as + + .. math:: + + \begin{aligned} + \min_{x \in \mathbb{R}^2} & \quad (x_1 - 1)^2 + (x_2 - 2.5)^2\\ + \text{s.t.} & \quad -x_1 + 2x_2 \le 2,\\ + & \quad x_1 + 2x_2 \le 6,\\ + & \quad x_1 - 2x_2 \le 2,\\ + & \quad x_1 \ge 0,\\ + & \quad x_2 \ge 0. + \end{aligned} + + >>> import numpy as np + >>> from scipy.optimize import Bounds, LinearConstraint + + Its objective function can be implemented as: + + >>> def fun(x): + ... return (x[0] - 1.0)**2 + (x[1] - 2.5)**2 + + This problem can be solved using `minimize` as: + + >>> x0 = [2.0, 0.0] + >>> bounds = Bounds([0.0, 0.0], np.inf) + >>> constraints = LinearConstraint([ + ... [-1.0, 2.0], + ... [1.0, 2.0], + ... [1.0, -2.0], + ... ], -np.inf, [2.0, 6.0, 2.0]) + >>> res = minimize(fun, x0, bounds=bounds, constraints=constraints) + >>> res.x + array([1.4, 1.7]) + + To see how nonlinear constraints are handled, we solve Problem (F) of [2]_, + defined as + + .. math:: + + \begin{aligned} + \min_{x \in \mathbb{R}^2} & \quad -x_1 - x_2\\ + \text{s.t.} & \quad x_1^2 - x_2 \le 0,\\ + & \quad x_1^2 + x_2^2 \le 1. + \end{aligned} + + >>> from scipy.optimize import NonlinearConstraint + + Its objective and constraint functions can be implemented as: + + >>> def fun(x): + ... return -x[0] - x[1] + >>> + >>> def cub(x): + ... return [x[0]**2 - x[1], x[0]**2 + x[1]**2] + + This problem can be solved using `minimize` as: + + >>> x0 = [1.0, 1.0] + >>> constraints = NonlinearConstraint(cub, -np.inf, [0.0, 1.0]) + >>> res = minimize(fun, x0, constraints=constraints) + >>> res.x + array([0.707, 0.707]) + + Finally, to see how to supply linear and nonlinear constraints + simultaneously, we solve Problem (G) of [2]_, defined as + + .. math:: + + \begin{aligned} + \min_{x \in \mathbb{R}^3} & \quad x_3\\ + \text{s.t.} & \quad 5x_1 - x_2 + x_3 \ge 0,\\ + & \quad -5x_1 - x_2 + x_3 \ge 0,\\ + & \quad x_1^2 + x_2^2 + 4x_2 \le x_3. + \end{aligned} + + Its objective and nonlinear constraint functions can be implemented as: + + >>> def fun(x): + ... return x[2] + >>> + >>> def cub(x): + ... return x[0]**2 + x[1]**2 + 4.0*x[1] - x[2] + + This problem can be solved using `minimize` as: + + >>> x0 = [1.0, 1.0, 1.0] + >>> constraints = [ + ... LinearConstraint( + ... [[5.0, -1.0, 1.0], [-5.0, -1.0, 1.0]], + ... [0.0, 0.0], + ... np.inf, + ... ), + ... NonlinearConstraint(cub, -np.inf, 0.0), + ... ] + >>> res = minimize(fun, x0, constraints=constraints) + >>> res.x + array([ 0., -3., -3.]) + """ + # Get basic options that are needed for the initialization. + if options is None: + options = {} + else: + options = dict(options) + verbose = options.get(Options.VERBOSE, DEFAULT_OPTIONS[Options.VERBOSE]) + verbose = bool(verbose) + feasibility_tol = options.get( + Options.FEASIBILITY_TOL, + DEFAULT_OPTIONS[Options.FEASIBILITY_TOL], + ) + feasibility_tol = float(feasibility_tol) + scale = options.get(Options.SCALE, DEFAULT_OPTIONS[Options.SCALE]) + scale = bool(scale) + store_history = options.get( + Options.STORE_HISTORY, + DEFAULT_OPTIONS[Options.STORE_HISTORY], + ) + store_history = bool(store_history) + if Options.HISTORY_SIZE in options and options[Options.HISTORY_SIZE] <= 0: + raise ValueError("The size of the history must be positive.") + history_size = options.get( + Options.HISTORY_SIZE, + DEFAULT_OPTIONS[Options.HISTORY_SIZE], + ) + history_size = int(history_size) + if Options.FILTER_SIZE in options and options[Options.FILTER_SIZE] <= 0: + raise ValueError("The size of the filter must be positive.") + filter_size = options.get( + Options.FILTER_SIZE, + DEFAULT_OPTIONS[Options.FILTER_SIZE], + ) + filter_size = int(filter_size) + debug = options.get(Options.DEBUG, DEFAULT_OPTIONS[Options.DEBUG]) + debug = bool(debug) + + # Initialize the objective function. + if not isinstance(args, tuple): + args = (args,) + obj = ObjectiveFunction(fun, verbose, debug, *args) + + # Initialize the bound constraints. + if not hasattr(x0, "__len__"): + x0 = [x0] + n_orig = len(x0) + bounds = BoundConstraints(_get_bounds(bounds, n_orig)) + + # Initialize the constraints. + linear_constraints, nonlinear_constraints = _get_constraints(constraints) + linear = LinearConstraints(linear_constraints, n_orig, debug) + nonlinear = NonlinearConstraints(nonlinear_constraints, verbose, debug) + + # Initialize the problem (and remove the fixed variables). + pb = Problem( + obj, + x0, + bounds, + linear, + nonlinear, + callback, + feasibility_tol, + scale, + store_history, + history_size, + filter_size, + debug, + ) + + # Set the default options. + _set_default_options(options, pb.n) + constants = _set_default_constants(**kwargs) + + # Initialize the models and skip the computations whenever possible. + if not pb.bounds.is_feasible: + # The bound constraints are infeasible. + return _build_result( + pb, + 0.0, + False, + ExitStatus.INFEASIBLE_ERROR, + 0, + options, + ) + elif pb.n == 0: + # All variables are fixed by the bound constraints. + return _build_result( + pb, + 0.0, + True, + ExitStatus.FIXED_SUCCESS, + 0, + options, + ) + if verbose: + print("Starting the optimization procedure.") + print(f"Initial trust-region radius: {options[Options.RHOBEG]}.") + print(f"Final trust-region radius: {options[Options.RHOEND]}.") + print( + f"Maximum number of function evaluations: " + f"{options[Options.MAX_EVAL]}." + ) + print(f"Maximum number of iterations: {options[Options.MAX_ITER]}.") + print() + try: + framework = TrustRegion(pb, options, constants) + except TargetSuccess: + # The target on the objective function value has been reached + return _build_result( + pb, + 0.0, + True, + ExitStatus.TARGET_SUCCESS, + 0, + options, + ) + except CallbackSuccess: + # The callback raised a StopIteration exception. + return _build_result( + pb, + 0.0, + True, + ExitStatus.CALLBACK_SUCCESS, + 0, + options, + ) + except FeasibleSuccess: + # The feasibility problem has been solved successfully. + return _build_result( + pb, + 0.0, + True, + ExitStatus.FEASIBLE_SUCCESS, + 0, + options, + ) + except MaxEvalError: + # The maximum number of function evaluations has been exceeded. + return _build_result( + pb, + 0.0, + False, + ExitStatus.MAX_ITER_WARNING, + 0, + options, + ) + except np.linalg.LinAlgError: + # The construction of the initial interpolation set failed. + return _build_result( + pb, + 0.0, + False, + ExitStatus.LINALG_ERROR, + 0, + options, + ) + + # Start the optimization procedure. + success = False + n_iter = 0 + k_new = None + n_short_steps = 0 + n_very_short_steps = 0 + n_alt_models = 0 + while True: + # Stop the optimization procedure if the maximum number of iterations + # has been exceeded. We do not write the main loop as a for loop + # because we want to access the number of iterations outside the loop. + if n_iter >= options[Options.MAX_ITER]: + status = ExitStatus.MAX_ITER_WARNING + break + n_iter += 1 + + # Update the point around which the quadratic models are built. + if ( + np.linalg.norm( + framework.x_best - framework.models.interpolation.x_base + ) + >= constants[Constants.LARGE_SHIFT_FACTOR] * framework.radius + ): + framework.shift_x_base(options) + + # Evaluate the trial step. + radius_save = framework.radius + normal_step, tangential_step = framework.get_trust_region_step(options) + step = normal_step + tangential_step + s_norm = np.linalg.norm(step) + + # If the trial step is too short, we do not attempt to evaluate the + # objective and constraint functions. Instead, we reduce the + # trust-region radius and check whether the resolution should be + # enhanced and whether the geometry of the interpolation set should be + # improved. Otherwise, we entertain a classical iteration. The + # criterion for performing an exceptional jump is taken from NEWUOA. + if ( + s_norm + <= constants[Constants.SHORT_STEP_THRESHOLD] * framework.resolution + ): + framework.radius *= constants[Constants.DECREASE_RESOLUTION_FACTOR] + if radius_save > framework.resolution: + n_short_steps = 0 + n_very_short_steps = 0 + else: + n_short_steps += 1 + n_very_short_steps += 1 + if s_norm > 0.1 * framework.resolution: + n_very_short_steps = 0 + enhance_resolution = n_short_steps >= 5 or n_very_short_steps >= 3 + if enhance_resolution: + n_short_steps = 0 + n_very_short_steps = 0 + improve_geometry = False + else: + try: + k_new, dist_new = framework.get_index_to_remove() + except np.linalg.LinAlgError: + status = ExitStatus.LINALG_ERROR + break + improve_geometry = dist_new > max( + framework.radius, + constants[Constants.RESOLUTION_FACTOR] + * framework.resolution, + ) + else: + # Increase the penalty parameter if necessary. + same_best_point = framework.increase_penalty(step) + if same_best_point: + # Evaluate the objective and constraint functions. + try: + fun_val, cub_val, ceq_val = _eval( + pb, + framework, + step, + options, + ) + except TargetSuccess: + status = ExitStatus.TARGET_SUCCESS + success = True + break + except FeasibleSuccess: + status = ExitStatus.FEASIBLE_SUCCESS + success = True + break + except CallbackSuccess: + status = ExitStatus.CALLBACK_SUCCESS + success = True + break + except MaxEvalError: + status = ExitStatus.MAX_EVAL_WARNING + break + + # Perform a second-order correction step if necessary. + merit_old = framework.merit( + framework.x_best, + framework.fun_best, + framework.cub_best, + framework.ceq_best, + ) + merit_new = framework.merit( + framework.x_best + step, fun_val, cub_val, ceq_val + ) + if ( + pb.type == "nonlinearly constrained" + and merit_new > merit_old + and np.linalg.norm(normal_step) + > constants[Constants.BYRD_OMOJOKUN_FACTOR] ** 2.0 + * framework.radius + ): + soc_step = framework.get_second_order_correction_step( + step, options + ) + if np.linalg.norm(soc_step) > 0.0: + step += soc_step + + # Evaluate the objective and constraint functions. + try: + fun_val, cub_val, ceq_val = _eval( + pb, + framework, + step, + options, + ) + except TargetSuccess: + status = ExitStatus.TARGET_SUCCESS + success = True + break + except FeasibleSuccess: + status = ExitStatus.FEASIBLE_SUCCESS + success = True + break + except CallbackSuccess: + status = ExitStatus.CALLBACK_SUCCESS + success = True + break + except MaxEvalError: + status = ExitStatus.MAX_EVAL_WARNING + break + + # Calculate the reduction ratio. + ratio = framework.get_reduction_ratio( + step, + fun_val, + cub_val, + ceq_val, + ) + + # Choose an interpolation point to remove. + try: + k_new = framework.get_index_to_remove( + framework.x_best + step + )[0] + except np.linalg.LinAlgError: + status = ExitStatus.LINALG_ERROR + break + + # Update the interpolation set. + try: + ill_conditioned = framework.models.update_interpolation( + k_new, framework.x_best + step, fun_val, cub_val, + ceq_val + ) + except np.linalg.LinAlgError: + status = ExitStatus.LINALG_ERROR + break + framework.set_best_index() + + # Update the trust-region radius. + framework.update_radius(step, ratio) + + # Attempt to replace the models by the alternative ones. + if framework.radius <= framework.resolution: + if ratio >= constants[Constants.VERY_LOW_RATIO]: + n_alt_models = 0 + else: + n_alt_models += 1 + grad = framework.models.fun_grad(framework.x_best) + try: + grad_alt = framework.models.fun_alt_grad( + framework.x_best + ) + except np.linalg.LinAlgError: + status = ExitStatus.LINALG_ERROR + break + if np.linalg.norm(grad) < constants[ + Constants.LARGE_GRADIENT_FACTOR + ] * np.linalg.norm(grad_alt): + n_alt_models = 0 + if n_alt_models >= 3: + try: + framework.models.reset_models() + except np.linalg.LinAlgError: + status = ExitStatus.LINALG_ERROR + break + n_alt_models = 0 + + # Update the Lagrange multipliers. + framework.set_multipliers(framework.x_best + step) + + # Check whether the resolution should be enhanced. + try: + k_new, dist_new = framework.get_index_to_remove() + except np.linalg.LinAlgError: + status = ExitStatus.LINALG_ERROR + break + improve_geometry = ( + ill_conditioned + or ratio <= constants[Constants.LOW_RATIO] + and dist_new + > max( + framework.radius, + constants[Constants.RESOLUTION_FACTOR] + * framework.resolution, + ) + ) + enhance_resolution = ( + radius_save <= framework.resolution + and ratio <= constants[Constants.LOW_RATIO] + and not improve_geometry + ) + else: + # When increasing the penalty parameter, the best point so far + # may change. In this case, we restart the iteration. + enhance_resolution = False + improve_geometry = False + + # Reduce the resolution if necessary. + if enhance_resolution: + if framework.resolution <= options[Options.RHOEND]: + success = True + status = ExitStatus.RADIUS_SUCCESS + break + framework.enhance_resolution(options) + framework.decrease_penalty() + + if verbose: + maxcv_val = pb.maxcv( + framework.x_best, framework.cub_best, framework.ceq_best + ) + _print_step( + f"New trust-region radius: {framework.resolution}", + pb, + pb.build_x(framework.x_best), + framework.fun_best, + maxcv_val, + pb.n_eval, + n_iter, + ) + print() + + # Improve the geometry of the interpolation set if necessary. + if improve_geometry: + try: + step = framework.get_geometry_step(k_new, options) + except np.linalg.LinAlgError: + status = ExitStatus.LINALG_ERROR + break + + # Evaluate the objective and constraint functions. + try: + fun_val, cub_val, ceq_val = _eval(pb, framework, step, options) + except TargetSuccess: + status = ExitStatus.TARGET_SUCCESS + success = True + break + except FeasibleSuccess: + status = ExitStatus.FEASIBLE_SUCCESS + success = True + break + except CallbackSuccess: + status = ExitStatus.CALLBACK_SUCCESS + success = True + break + except MaxEvalError: + status = ExitStatus.MAX_EVAL_WARNING + break + + # Update the interpolation set. + try: + framework.models.update_interpolation( + k_new, + framework.x_best + step, + fun_val, + cub_val, + ceq_val, + ) + except np.linalg.LinAlgError: + status = ExitStatus.LINALG_ERROR + break + framework.set_best_index() + + return _build_result( + pb, + framework.penalty, + success, + status, + n_iter, + options, + ) + + +def _get_bounds(bounds, n): + """ + Uniformize the bounds. + """ + if bounds is None: + return Bounds(np.full(n, -np.inf), np.full(n, np.inf)) + elif isinstance(bounds, Bounds): + if bounds.lb.shape != (n,) or bounds.ub.shape != (n,): + raise ValueError(f"The bounds must have {n} elements.") + return Bounds(bounds.lb, bounds.ub) + elif hasattr(bounds, "__len__"): + bounds = np.asarray(bounds) + if bounds.shape != (n, 2): + raise ValueError( + "The shape of the bounds is not compatible with " + "the number of variables." + ) + return Bounds(bounds[:, 0], bounds[:, 1]) + else: + raise TypeError( + "The bounds must be an instance of " + "scipy.optimize.Bounds or an array-like object." + ) + + +def _get_constraints(constraints): + """ + Extract the linear and nonlinear constraints. + """ + if isinstance(constraints, dict) or not hasattr(constraints, "__len__"): + constraints = (constraints,) + + # Extract the linear and nonlinear constraints. + linear_constraints = [] + nonlinear_constraints = [] + for constraint in constraints: + if isinstance(constraint, LinearConstraint): + lb = exact_1d_array( + constraint.lb, + "The lower bound of the linear constraints must be a vector.", + ) + ub = exact_1d_array( + constraint.ub, + "The upper bound of the linear constraints must be a vector.", + ) + linear_constraints.append( + LinearConstraint( + constraint.A, + *np.broadcast_arrays(lb, ub), + ) + ) + elif isinstance(constraint, NonlinearConstraint): + lb = exact_1d_array( + constraint.lb, + "The lower bound of the " + "nonlinear constraints must be a " + "vector.", + ) + ub = exact_1d_array( + constraint.ub, + "The upper bound of the " + "nonlinear constraints must be a " + "vector.", + ) + nonlinear_constraints.append( + NonlinearConstraint( + constraint.fun, + *np.broadcast_arrays(lb, ub), + ) + ) + elif isinstance(constraint, dict): + if "type" not in constraint or constraint["type"] not in ( + "eq", + "ineq", + ): + raise ValueError('The constraint type must be "eq" or "ineq".') + if "fun" not in constraint or not callable(constraint["fun"]): + raise ValueError("The constraint function must be callable.") + nonlinear_constraints.append( + { + "fun": constraint["fun"], + "type": constraint["type"], + "args": constraint.get("args", ()), + } + ) + else: + raise TypeError( + "The constraints must be instances of " + "scipy.optimize.LinearConstraint, " + "scipy.optimize.NonlinearConstraint, or dict." + ) + return linear_constraints, nonlinear_constraints + + +def _set_default_options(options, n): + """ + Set the default options. + """ + if Options.RHOBEG in options and options[Options.RHOBEG] <= 0.0: + raise ValueError("The initial trust-region radius must be positive.") + if Options.RHOEND in options and options[Options.RHOEND] < 0.0: + raise ValueError("The final trust-region radius must be nonnegative.") + if Options.RHOBEG in options and Options.RHOEND in options: + if options[Options.RHOBEG] < options[Options.RHOEND]: + raise ValueError( + "The initial trust-region radius must be greater " + "than or equal to the final trust-region radius." + ) + elif Options.RHOBEG in options: + options[Options.RHOEND.value] = np.min( + [ + DEFAULT_OPTIONS[Options.RHOEND], + options[Options.RHOBEG], + ] + ) + elif Options.RHOEND in options: + options[Options.RHOBEG.value] = np.max( + [ + DEFAULT_OPTIONS[Options.RHOBEG], + options[Options.RHOEND], + ] + ) + else: + options[Options.RHOBEG.value] = DEFAULT_OPTIONS[Options.RHOBEG] + options[Options.RHOEND.value] = DEFAULT_OPTIONS[Options.RHOEND] + options[Options.RHOBEG.value] = float(options[Options.RHOBEG]) + options[Options.RHOEND.value] = float(options[Options.RHOEND]) + if Options.NPT in options and options[Options.NPT] <= 0: + raise ValueError("The number of interpolation points must be " + "positive.") + if ( + Options.NPT in options + and options[Options.NPT] > ((n + 1) * (n + 2)) // 2 + ): + raise ValueError( + f"The number of interpolation points must be at most " + f"{((n + 1) * (n + 2)) // 2}." + ) + options.setdefault(Options.NPT.value, DEFAULT_OPTIONS[Options.NPT](n)) + options[Options.NPT.value] = int(options[Options.NPT]) + if Options.MAX_EVAL in options and options[Options.MAX_EVAL] <= 0: + raise ValueError( + "The maximum number of function evaluations must be positive." + ) + options.setdefault( + Options.MAX_EVAL.value, + np.max( + [ + DEFAULT_OPTIONS[Options.MAX_EVAL](n), + options[Options.NPT] + 1, + ] + ), + ) + options[Options.MAX_EVAL.value] = int(options[Options.MAX_EVAL]) + if Options.MAX_ITER in options and options[Options.MAX_ITER] <= 0: + raise ValueError("The maximum number of iterations must be positive.") + options.setdefault( + Options.MAX_ITER.value, + DEFAULT_OPTIONS[Options.MAX_ITER](n), + ) + options[Options.MAX_ITER.value] = int(options[Options.MAX_ITER]) + options.setdefault(Options.TARGET.value, DEFAULT_OPTIONS[Options.TARGET]) + options[Options.TARGET.value] = float(options[Options.TARGET]) + options.setdefault( + Options.FEASIBILITY_TOL.value, + DEFAULT_OPTIONS[Options.FEASIBILITY_TOL], + ) + options[Options.FEASIBILITY_TOL.value] = float( + options[Options.FEASIBILITY_TOL] + ) + options.setdefault(Options.VERBOSE.value, DEFAULT_OPTIONS[Options.VERBOSE]) + options[Options.VERBOSE.value] = bool(options[Options.VERBOSE]) + options.setdefault(Options.SCALE.value, DEFAULT_OPTIONS[Options.SCALE]) + options[Options.SCALE.value] = bool(options[Options.SCALE]) + options.setdefault( + Options.FILTER_SIZE.value, + DEFAULT_OPTIONS[Options.FILTER_SIZE], + ) + options[Options.FILTER_SIZE.value] = int(options[Options.FILTER_SIZE]) + options.setdefault( + Options.STORE_HISTORY.value, + DEFAULT_OPTIONS[Options.STORE_HISTORY], + ) + options[Options.STORE_HISTORY.value] = bool(options[Options.STORE_HISTORY]) + options.setdefault( + Options.HISTORY_SIZE.value, + DEFAULT_OPTIONS[Options.HISTORY_SIZE], + ) + options[Options.HISTORY_SIZE.value] = int(options[Options.HISTORY_SIZE]) + options.setdefault(Options.DEBUG.value, DEFAULT_OPTIONS[Options.DEBUG]) + options[Options.DEBUG.value] = bool(options[Options.DEBUG]) + + # Check whether they are any unknown options. + for key in options: + if key not in Options.__members__.values(): + warnings.warn(f"Unknown option: {key}.", RuntimeWarning, 3) + + +def _set_default_constants(**kwargs): + """ + Set the default constants. + """ + constants = dict(kwargs) + constants.setdefault( + Constants.DECREASE_RADIUS_FACTOR.value, + DEFAULT_CONSTANTS[Constants.DECREASE_RADIUS_FACTOR], + ) + constants[Constants.DECREASE_RADIUS_FACTOR.value] = float( + constants[Constants.DECREASE_RADIUS_FACTOR] + ) + if ( + constants[Constants.DECREASE_RADIUS_FACTOR] <= 0.0 + or constants[Constants.DECREASE_RADIUS_FACTOR] >= 1.0 + ): + raise ValueError( + "The constant decrease_radius_factor must be in the interval " + "(0, 1)." + ) + constants.setdefault( + Constants.INCREASE_RADIUS_THRESHOLD.value, + DEFAULT_CONSTANTS[Constants.INCREASE_RADIUS_THRESHOLD], + ) + constants[Constants.INCREASE_RADIUS_THRESHOLD.value] = float( + constants[Constants.INCREASE_RADIUS_THRESHOLD] + ) + if constants[Constants.INCREASE_RADIUS_THRESHOLD] <= 1.0: + raise ValueError( + "The constant increase_radius_threshold must be greater than 1." + ) + if ( + Constants.INCREASE_RADIUS_FACTOR in constants + and constants[Constants.INCREASE_RADIUS_FACTOR] <= 1.0 + ): + raise ValueError( + "The constant increase_radius_factor must be greater than 1." + ) + if ( + Constants.DECREASE_RADIUS_THRESHOLD in constants + and constants[Constants.DECREASE_RADIUS_THRESHOLD] <= 1.0 + ): + raise ValueError( + "The constant decrease_radius_threshold must be greater than 1." + ) + if ( + Constants.INCREASE_RADIUS_FACTOR in constants + and Constants.DECREASE_RADIUS_THRESHOLD in constants + ): + if ( + constants[Constants.DECREASE_RADIUS_THRESHOLD] + >= constants[Constants.INCREASE_RADIUS_FACTOR] + ): + raise ValueError( + "The constant decrease_radius_threshold must be " + "less than increase_radius_factor." + ) + elif Constants.INCREASE_RADIUS_FACTOR in constants: + constants[Constants.DECREASE_RADIUS_THRESHOLD.value] = np.min( + [ + DEFAULT_CONSTANTS[Constants.DECREASE_RADIUS_THRESHOLD], + 0.5 * (1.0 + constants[Constants.INCREASE_RADIUS_FACTOR]), + ] + ) + elif Constants.DECREASE_RADIUS_THRESHOLD in constants: + constants[Constants.INCREASE_RADIUS_FACTOR.value] = np.max( + [ + DEFAULT_CONSTANTS[Constants.INCREASE_RADIUS_FACTOR], + 2.0 * constants[Constants.DECREASE_RADIUS_THRESHOLD], + ] + ) + else: + constants[Constants.INCREASE_RADIUS_FACTOR.value] = DEFAULT_CONSTANTS[ + Constants.INCREASE_RADIUS_FACTOR + ] + constants[Constants.DECREASE_RADIUS_THRESHOLD.value] = ( + DEFAULT_CONSTANTS[Constants.DECREASE_RADIUS_THRESHOLD]) + constants.setdefault( + Constants.DECREASE_RESOLUTION_FACTOR.value, + DEFAULT_CONSTANTS[Constants.DECREASE_RESOLUTION_FACTOR], + ) + constants[Constants.DECREASE_RESOLUTION_FACTOR.value] = float( + constants[Constants.DECREASE_RESOLUTION_FACTOR] + ) + if ( + constants[Constants.DECREASE_RESOLUTION_FACTOR] <= 0.0 + or constants[Constants.DECREASE_RESOLUTION_FACTOR] >= 1.0 + ): + raise ValueError( + "The constant decrease_resolution_factor must be in the interval " + "(0, 1)." + ) + if ( + Constants.LARGE_RESOLUTION_THRESHOLD in constants + and constants[Constants.LARGE_RESOLUTION_THRESHOLD] <= 1.0 + ): + raise ValueError( + "The constant large_resolution_threshold must be greater than 1." + ) + if ( + Constants.MODERATE_RESOLUTION_THRESHOLD in constants + and constants[Constants.MODERATE_RESOLUTION_THRESHOLD] <= 1.0 + ): + raise ValueError( + "The constant moderate_resolution_threshold must be greater than " + "1." + ) + if ( + Constants.LARGE_RESOLUTION_THRESHOLD in constants + and Constants.MODERATE_RESOLUTION_THRESHOLD in constants + ): + if ( + constants[Constants.MODERATE_RESOLUTION_THRESHOLD] + > constants[Constants.LARGE_RESOLUTION_THRESHOLD] + ): + raise ValueError( + "The constant moderate_resolution_threshold " + "must be at most large_resolution_threshold." + ) + elif Constants.LARGE_RESOLUTION_THRESHOLD in constants: + constants[Constants.MODERATE_RESOLUTION_THRESHOLD.value] = np.min( + [ + DEFAULT_CONSTANTS[Constants.MODERATE_RESOLUTION_THRESHOLD], + constants[Constants.LARGE_RESOLUTION_THRESHOLD], + ] + ) + elif Constants.MODERATE_RESOLUTION_THRESHOLD in constants: + constants[Constants.LARGE_RESOLUTION_THRESHOLD.value] = np.max( + [ + DEFAULT_CONSTANTS[Constants.LARGE_RESOLUTION_THRESHOLD], + constants[Constants.MODERATE_RESOLUTION_THRESHOLD], + ] + ) + else: + constants[Constants.LARGE_RESOLUTION_THRESHOLD.value] = ( + DEFAULT_CONSTANTS[Constants.LARGE_RESOLUTION_THRESHOLD] + ) + constants[Constants.MODERATE_RESOLUTION_THRESHOLD.value] = ( + DEFAULT_CONSTANTS[Constants.MODERATE_RESOLUTION_THRESHOLD] + ) + if Constants.LOW_RATIO in constants and ( + constants[Constants.LOW_RATIO] <= 0.0 + or constants[Constants.LOW_RATIO] >= 1.0 + ): + raise ValueError( + "The constant low_ratio must be in the interval (0, 1)." + ) + if Constants.HIGH_RATIO in constants and ( + constants[Constants.HIGH_RATIO] <= 0.0 + or constants[Constants.HIGH_RATIO] >= 1.0 + ): + raise ValueError( + "The constant high_ratio must be in the interval (0, 1)." + ) + if Constants.LOW_RATIO in constants and Constants.HIGH_RATIO in constants: + if constants[Constants.LOW_RATIO] > constants[Constants.HIGH_RATIO]: + raise ValueError( + "The constant low_ratio must be at most high_ratio." + ) + elif Constants.LOW_RATIO in constants: + constants[Constants.HIGH_RATIO.value] = np.max( + [ + DEFAULT_CONSTANTS[Constants.HIGH_RATIO], + constants[Constants.LOW_RATIO], + ] + ) + elif Constants.HIGH_RATIO in constants: + constants[Constants.LOW_RATIO.value] = np.min( + [ + DEFAULT_CONSTANTS[Constants.LOW_RATIO], + constants[Constants.HIGH_RATIO], + ] + ) + else: + constants[Constants.LOW_RATIO.value] = DEFAULT_CONSTANTS[ + Constants.LOW_RATIO + ] + constants[Constants.HIGH_RATIO.value] = DEFAULT_CONSTANTS[ + Constants.HIGH_RATIO + ] + constants.setdefault( + Constants.VERY_LOW_RATIO.value, + DEFAULT_CONSTANTS[Constants.VERY_LOW_RATIO], + ) + constants[Constants.VERY_LOW_RATIO.value] = float( + constants[Constants.VERY_LOW_RATIO] + ) + if ( + constants[Constants.VERY_LOW_RATIO] <= 0.0 + or constants[Constants.VERY_LOW_RATIO] >= 1.0 + ): + raise ValueError( + "The constant very_low_ratio must be in the interval (0, 1)." + ) + if ( + Constants.PENALTY_INCREASE_THRESHOLD in constants + and constants[Constants.PENALTY_INCREASE_THRESHOLD] < 1.0 + ): + raise ValueError( + "The constant penalty_increase_threshold must be " + "greater than or equal to 1." + ) + if ( + Constants.PENALTY_INCREASE_FACTOR in constants + and constants[Constants.PENALTY_INCREASE_FACTOR] <= 1.0 + ): + raise ValueError( + "The constant penalty_increase_factor must be greater than 1." + ) + if ( + Constants.PENALTY_INCREASE_THRESHOLD in constants + and Constants.PENALTY_INCREASE_FACTOR in constants + ): + if ( + constants[Constants.PENALTY_INCREASE_FACTOR] + < constants[Constants.PENALTY_INCREASE_THRESHOLD] + ): + raise ValueError( + "The constant penalty_increase_factor must be " + "greater than or equal to " + "penalty_increase_threshold." + ) + elif Constants.PENALTY_INCREASE_THRESHOLD in constants: + constants[Constants.PENALTY_INCREASE_FACTOR.value] = np.max( + [ + DEFAULT_CONSTANTS[Constants.PENALTY_INCREASE_FACTOR], + constants[Constants.PENALTY_INCREASE_THRESHOLD], + ] + ) + elif Constants.PENALTY_INCREASE_FACTOR in constants: + constants[Constants.PENALTY_INCREASE_THRESHOLD.value] = np.min( + [ + DEFAULT_CONSTANTS[Constants.PENALTY_INCREASE_THRESHOLD], + constants[Constants.PENALTY_INCREASE_FACTOR], + ] + ) + else: + constants[Constants.PENALTY_INCREASE_THRESHOLD.value] = ( + DEFAULT_CONSTANTS[Constants.PENALTY_INCREASE_THRESHOLD] + ) + constants[Constants.PENALTY_INCREASE_FACTOR.value] = DEFAULT_CONSTANTS[ + Constants.PENALTY_INCREASE_FACTOR + ] + constants.setdefault( + Constants.SHORT_STEP_THRESHOLD.value, + DEFAULT_CONSTANTS[Constants.SHORT_STEP_THRESHOLD], + ) + constants[Constants.SHORT_STEP_THRESHOLD.value] = float( + constants[Constants.SHORT_STEP_THRESHOLD] + ) + if ( + constants[Constants.SHORT_STEP_THRESHOLD] <= 0.0 + or constants[Constants.SHORT_STEP_THRESHOLD] >= 1.0 + ): + raise ValueError( + "The constant short_step_threshold must be in the interval (0, 1)." + ) + constants.setdefault( + Constants.LOW_RADIUS_FACTOR.value, + DEFAULT_CONSTANTS[Constants.LOW_RADIUS_FACTOR], + ) + constants[Constants.LOW_RADIUS_FACTOR.value] = float( + constants[Constants.LOW_RADIUS_FACTOR] + ) + if ( + constants[Constants.LOW_RADIUS_FACTOR] <= 0.0 + or constants[Constants.LOW_RADIUS_FACTOR] >= 1.0 + ): + raise ValueError( + "The constant low_radius_factor must be in the interval (0, 1)." + ) + constants.setdefault( + Constants.BYRD_OMOJOKUN_FACTOR.value, + DEFAULT_CONSTANTS[Constants.BYRD_OMOJOKUN_FACTOR], + ) + constants[Constants.BYRD_OMOJOKUN_FACTOR.value] = float( + constants[Constants.BYRD_OMOJOKUN_FACTOR] + ) + if ( + constants[Constants.BYRD_OMOJOKUN_FACTOR] <= 0.0 + or constants[Constants.BYRD_OMOJOKUN_FACTOR] >= 1.0 + ): + raise ValueError( + "The constant byrd_omojokun_factor must be in the interval (0, 1)." + ) + constants.setdefault( + Constants.THRESHOLD_RATIO_CONSTRAINTS.value, + DEFAULT_CONSTANTS[Constants.THRESHOLD_RATIO_CONSTRAINTS], + ) + constants[Constants.THRESHOLD_RATIO_CONSTRAINTS.value] = float( + constants[Constants.THRESHOLD_RATIO_CONSTRAINTS] + ) + if constants[Constants.THRESHOLD_RATIO_CONSTRAINTS] <= 1.0: + raise ValueError( + "The constant threshold_ratio_constraints must be greater than 1." + ) + constants.setdefault( + Constants.LARGE_SHIFT_FACTOR.value, + DEFAULT_CONSTANTS[Constants.LARGE_SHIFT_FACTOR], + ) + constants[Constants.LARGE_SHIFT_FACTOR.value] = float( + constants[Constants.LARGE_SHIFT_FACTOR] + ) + if constants[Constants.LARGE_SHIFT_FACTOR] < 0.0: + raise ValueError("The constant large_shift_factor must be " + "nonnegative.") + constants.setdefault( + Constants.LARGE_GRADIENT_FACTOR.value, + DEFAULT_CONSTANTS[Constants.LARGE_GRADIENT_FACTOR], + ) + constants[Constants.LARGE_GRADIENT_FACTOR.value] = float( + constants[Constants.LARGE_GRADIENT_FACTOR] + ) + if constants[Constants.LARGE_GRADIENT_FACTOR] <= 1.0: + raise ValueError( + "The constant large_gradient_factor must be greater than 1." + ) + constants.setdefault( + Constants.RESOLUTION_FACTOR.value, + DEFAULT_CONSTANTS[Constants.RESOLUTION_FACTOR], + ) + constants[Constants.RESOLUTION_FACTOR.value] = float( + constants[Constants.RESOLUTION_FACTOR] + ) + if constants[Constants.RESOLUTION_FACTOR] <= 1.0: + raise ValueError( + "The constant resolution_factor must be greater than 1." + ) + constants.setdefault( + Constants.IMPROVE_TCG.value, + DEFAULT_CONSTANTS[Constants.IMPROVE_TCG], + ) + constants[Constants.IMPROVE_TCG.value] = bool( + constants[Constants.IMPROVE_TCG] + ) + + # Check whether they are any unknown options. + for key in kwargs: + if key not in Constants.__members__.values(): + warnings.warn(f"Unknown constant: {key}.", RuntimeWarning, 3) + return constants + + +def _eval(pb, framework, step, options): + """ + Evaluate the objective and constraint functions. + """ + if pb.n_eval >= options[Options.MAX_EVAL]: + raise MaxEvalError + x_eval = framework.x_best + step + fun_val, cub_val, ceq_val = pb(x_eval, framework.penalty) + r_val = pb.maxcv(x_eval, cub_val, ceq_val) + if ( + fun_val <= options[Options.TARGET] + and r_val <= options[Options.FEASIBILITY_TOL] + ): + raise TargetSuccess + if pb.is_feasibility and r_val <= options[Options.FEASIBILITY_TOL]: + raise FeasibleSuccess + return fun_val, cub_val, ceq_val + + +def _build_result(pb, penalty, success, status, n_iter, options): + """ + Build the result of the optimization process. + """ + # Build the result. + x, fun, maxcv = pb.best_eval(penalty) + success = success and np.isfinite(fun) and np.isfinite(maxcv) + if status not in [ExitStatus.TARGET_SUCCESS, ExitStatus.FEASIBLE_SUCCESS]: + success = success and maxcv <= options[Options.FEASIBILITY_TOL] + result = OptimizeResult() + result.message = { + ExitStatus.RADIUS_SUCCESS: "The lower bound for the trust-region " + "radius has been reached", + ExitStatus.TARGET_SUCCESS: "The target objective function value has " + "been reached", + ExitStatus.FIXED_SUCCESS: "All variables are fixed by the bound " + "constraints", + ExitStatus.CALLBACK_SUCCESS: "The callback requested to stop the " + "optimization procedure", + ExitStatus.FEASIBLE_SUCCESS: "The feasibility problem received has " + "been solved successfully", + ExitStatus.MAX_EVAL_WARNING: "The maximum number of function " + "evaluations has been exceeded", + ExitStatus.MAX_ITER_WARNING: "The maximum number of iterations has " + "been exceeded", + ExitStatus.INFEASIBLE_ERROR: "The bound constraints are infeasible", + ExitStatus.LINALG_ERROR: "A linear algebra error occurred", + }.get(status, "Unknown exit status") + result.success = success + result.status = status.value + result.x = pb.build_x(x) + result.fun = fun + result.maxcv = maxcv + result.nfev = pb.n_eval + result.nit = n_iter + if options[Options.STORE_HISTORY]: + result.fun_history = pb.fun_history + result.maxcv_history = pb.maxcv_history + + # Print the result if requested. + if options[Options.VERBOSE]: + _print_step( + result.message, + pb, + result.x, + result.fun, + result.maxcv, + result.nfev, + result.nit, + ) + return result + + +def _print_step(message, pb, x, fun_val, r_val, n_eval, n_iter): + """ + Print information about the current state of the optimization process. + """ + print() + print(f"{message}.") + print(f"Number of function evaluations: {n_eval}.") + print(f"Number of iterations: {n_iter}.") + if not pb.is_feasibility: + print(f"Least value of {pb.fun_name}: {fun_val}.") + print(f"Maximum constraint violation: {r_val}.") + with np.printoptions(**PRINT_OPTIONS): + print(f"Corresponding point: {x}.") diff --git a/.venv/lib/python3.12/site-packages/scipy/_external/cobyqa/models.py b/.venv/lib/python3.12/site-packages/scipy/_external/cobyqa/models.py new file mode 100644 index 0000000000000000000000000000000000000000..44da70bf03a77e63af9ee45974050d008eed0147 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/scipy/_external/cobyqa/models.py @@ -0,0 +1,1531 @@ +import warnings + +import numpy as np +from scipy.linalg import eigh + +from .settings import Options +from .utils import MaxEvalError, TargetSuccess, FeasibleSuccess + + +EPS = np.finfo(float).eps + + +class Interpolation: + """ + Interpolation set. + + This class stores a base point around which the models are expanded and the + interpolation points. The coordinates of the interpolation points are + relative to the base point. + """ + + def __init__(self, pb, options): + """ + Initialize the interpolation set. + + Parameters + ---------- + pb : `cobyqa.problem.Problem` + Problem to be solved. + options : dict + Options of the solver. + """ + # Reduce the initial trust-region radius if necessary. + self._debug = options[Options.DEBUG] + max_radius = 0.5 * np.min(pb.bounds.xu - pb.bounds.xl) + if options[Options.RHOBEG] > max_radius: + options[Options.RHOBEG.value] = max_radius + options[Options.RHOEND.value] = np.min( + [ + options[Options.RHOEND], + max_radius, + ] + ) + + # Set the initial point around which the models are expanded. + self._x_base = np.copy(pb.x0) + very_close_xl_idx = ( + self.x_base <= pb.bounds.xl + 0.5 * options[Options.RHOBEG] + ) + self.x_base[very_close_xl_idx] = pb.bounds.xl[very_close_xl_idx] + close_xl_idx = ( + pb.bounds.xl + 0.5 * options[Options.RHOBEG] < self.x_base + ) & (self.x_base <= pb.bounds.xl + options[Options.RHOBEG]) + self.x_base[close_xl_idx] = np.minimum( + pb.bounds.xl[close_xl_idx] + options[Options.RHOBEG], + pb.bounds.xu[close_xl_idx], + ) + very_close_xu_idx = ( + self.x_base >= pb.bounds.xu - 0.5 * options[Options.RHOBEG] + ) + self.x_base[very_close_xu_idx] = pb.bounds.xu[very_close_xu_idx] + close_xu_idx = ( + self.x_base < pb.bounds.xu - 0.5 * options[Options.RHOBEG] + ) & (pb.bounds.xu - options[Options.RHOBEG] <= self.x_base) + self.x_base[close_xu_idx] = np.maximum( + pb.bounds.xu[close_xu_idx] - options[Options.RHOBEG], + pb.bounds.xl[close_xu_idx], + ) + + # Set the initial interpolation set. + self._xpt = np.zeros((pb.n, options[Options.NPT])) + for k in range(1, options[Options.NPT]): + if k <= pb.n: + if very_close_xu_idx[k - 1]: + self.xpt[k - 1, k] = -options[Options.RHOBEG] + else: + self.xpt[k - 1, k] = options[Options.RHOBEG] + elif k <= 2 * pb.n: + if very_close_xl_idx[k - pb.n - 1]: + self.xpt[k - pb.n - 1, k] = 2.0 * options[Options.RHOBEG] + elif very_close_xu_idx[k - pb.n - 1]: + self.xpt[k - pb.n - 1, k] = -2.0 * options[Options.RHOBEG] + else: + self.xpt[k - pb.n - 1, k] = -options[Options.RHOBEG] + else: + spread = (k - pb.n - 1) // pb.n + k1 = k - (1 + spread) * pb.n - 1 + k2 = (k1 + spread) % pb.n + self.xpt[k1, k] = self.xpt[k1, k1 + 1] + self.xpt[k2, k] = self.xpt[k2, k2 + 1] + self._lhs_cache = None + + @property + def n(self): + """ + Number of variables. + + Returns + ------- + int + Number of variables. + """ + return self.xpt.shape[0] + + @property + def npt(self): + """ + Number of interpolation points. + + Returns + ------- + int + Number of interpolation points. + """ + return self.xpt.shape[1] + + @property + def xpt(self): + """ + Interpolation points. + + Returns + ------- + `numpy.ndarray`, shape (n, npt) + Interpolation points. + """ + return self._xpt + + @xpt.setter + def xpt(self, xpt): + """ + Set the interpolation points. + + Parameters + ---------- + xpt : `numpy.ndarray`, shape (n, npt) + New interpolation points. + """ + if self._debug: + assert xpt.shape == ( + self.n, + self.npt, + ), "The shape of `xpt` is not valid." + self._xpt = xpt + + @property + def x_base(self): + """ + Base point around which the models are expanded. + + Returns + ------- + `numpy.ndarray`, shape (n,) + Base point around which the models are expanded. + """ + return self._x_base + + @x_base.setter + def x_base(self, x_base): + """ + Set the base point around which the models are expanded. + + Parameters + ---------- + x_base : `numpy.ndarray`, shape (n,) + New base point around which the models are expanded. + """ + if self._debug: + assert x_base.shape == ( + self.n, + ), "The shape of `x_base` is not valid." + self._x_base = x_base + + def point(self, k): + """ + Get the `k`-th interpolation point. + + The return point is relative to the origin. + + Parameters + ---------- + k : int + Index of the interpolation point. + + Returns + ------- + `numpy.ndarray`, shape (n,) + `k`-th interpolation point. + """ + if self._debug: + assert 0 <= k < self.npt, "The index `k` is not valid." + return self.x_base + self.xpt[:, k] + + +def build_system(interpolation): + """ + Build the left-hand side matrix of the interpolation system. The + matrix below stores W * diag(right_scaling), + where W is the theoretical matrix of the interpolation system. The + right scaling matrices is chosen to keep the elements in + the matrix well-balanced. + + Parameters + ---------- + interpolation : `cobyqa.models.Interpolation` + Interpolation set. + """ + + _cache = interpolation._lhs_cache + # Compute the scaled directions from the base point to the + # interpolation points. We scale the directions to avoid numerical + # difficulties. + if _cache is not None and np.array_equal( + interpolation.xpt, _cache["xpt"] + ): + return _cache["a"], _cache["right_scaling"], _cache["eigh"] + + scale = np.max(np.linalg.norm(interpolation.xpt, axis=0), initial=EPS) + xpt_scale = interpolation.xpt / scale + + n, npt = xpt_scale.shape + a = np.zeros((npt + n + 1, npt + n + 1)) + a[:npt, :npt] = 0.5 * (xpt_scale.T @ xpt_scale) ** 2.0 + a[:npt, npt] = 1.0 + a[:npt, npt + 1:] = xpt_scale.T + a[npt, :npt] = 1.0 + a[npt + 1:, :npt] = xpt_scale + + # Build the left and right scaling diagonal matrices. + right_scaling = np.empty(npt + n + 1) + right_scaling[:npt] = 1.0 / scale**2.0 + right_scaling[npt] = scale**2.0 + right_scaling[npt + 1:] = scale + + eig_values, eig_vectors = eigh(a, check_finite=False) + + new_cache = { + "xpt": np.copy(interpolation.xpt), + "a": np.copy(a), + "right_scaling": np.copy(right_scaling), + "eigh": (eig_values, eig_vectors), + } + interpolation._lhs_cache = new_cache + + return a, right_scaling, (eig_values, eig_vectors) + + +class Quadratic: + """ + Quadratic model. + + This class stores the Hessian matrix of the quadratic model using the + implicit/explicit representation designed by Powell for NEWUOA [1]_. + + References + ---------- + .. [1] M. J. D. Powell. The NEWUOA software for unconstrained optimization + without derivatives. In G. Di Pillo and M. Roma, editors, *Large-Scale + Nonlinear Optimization*, volume 83 of Nonconvex Optim. Appl., pages + 255--297. Springer, Boston, MA, USA, 2006. `doi:10.1007/0-387-30065-1_16 + `_. + """ + + def __init__(self, interpolation, values, debug): + """ + Initialize the quadratic model. + + Parameters + ---------- + interpolation : `cobyqa.models.Interpolation` + Interpolation set. + values : `numpy.ndarray`, shape (npt,) + Values of the interpolated function at the interpolation points. + debug : bool + Whether to make debugging tests during the execution. + + Raises + ------ + `numpy.linalg.LinAlgError` + If the interpolation system is ill-defined. + """ + self._debug = debug + if self._debug: + assert values.shape == ( + interpolation.npt, + ), "The shape of `values` is not valid." + if interpolation.npt < interpolation.n + 1: + raise ValueError( + f"The number of interpolation points must be at least " + f"{interpolation.n + 1}." + ) + self._const, self._grad, self._i_hess, _ = self._get_model( + interpolation, + values, + ) + self._e_hess = np.zeros((self.n, self.n)) + + def __call__(self, x, interpolation): + """ + Evaluate the quadratic model at a given point. + + Parameters + ---------- + x : `numpy.ndarray`, shape (n,) + Point at which the quadratic model is evaluated. + interpolation : `cobyqa.models.Interpolation` + Interpolation set. + + Returns + ------- + float + Value of the quadratic model at `x`. + """ + if self._debug: + assert x.shape == (self.n,), "The shape of `x` is not valid." + x_diff = x - interpolation.x_base + return ( + self._const + + self._grad @ x_diff + + 0.5 + * ( + self._i_hess @ (interpolation.xpt.T @ x_diff) ** 2.0 + + x_diff @ self._e_hess @ x_diff + ) + ) + + @property + def n(self): + """ + Number of variables. + + Returns + ------- + int + Number of variables. + """ + return self._grad.size + + @property + def npt(self): + """ + Number of interpolation points used to define the quadratic model. + + Returns + ------- + int + Number of interpolation points used to define the quadratic model. + """ + return self._i_hess.size + + def grad(self, x, interpolation): + """ + Evaluate the gradient of the quadratic model at a given point. + + Parameters + ---------- + x : `numpy.ndarray`, shape (n,) + Point at which the gradient of the quadratic model is evaluated. + interpolation : `cobyqa.models.Interpolation` + Interpolation set. + + Returns + ------- + `numpy.ndarray`, shape (n,) + Gradient of the quadratic model at `x`. + """ + if self._debug: + assert x.shape == (self.n,), "The shape of `x` is not valid." + x_diff = x - interpolation.x_base + return self._grad + self.hess_prod(x_diff, interpolation) + + def hess(self, interpolation): + """ + Evaluate the Hessian matrix of the quadratic model. + + Parameters + ---------- + interpolation : `cobyqa.models.Interpolation` + Interpolation set. + + Returns + ------- + `numpy.ndarray`, shape (n, n) + Hessian matrix of the quadratic model. + """ + return self._e_hess + interpolation.xpt @ ( + self._i_hess[:, np.newaxis] * interpolation.xpt.T + ) + + def hess_prod(self, v, interpolation): + """ + Evaluate the right product of the Hessian matrix of the quadratic model + with a given vector. + + Parameters + ---------- + v : `numpy.ndarray`, shape (n,) + Vector with which the Hessian matrix of the quadratic model is + multiplied from the right. + interpolation : `cobyqa.models.Interpolation` + Interpolation set. + + Returns + ------- + `numpy.ndarray`, shape (n,) + Right product of the Hessian matrix of the quadratic model with + `v`. + """ + if self._debug: + assert v.shape == (self.n,), "The shape of `v` is not valid." + return self._e_hess @ v + interpolation.xpt @ ( + self._i_hess * (interpolation.xpt.T @ v) + ) + + def curv(self, v, interpolation): + """ + Evaluate the curvature of the quadratic model along a given direction. + + Parameters + ---------- + v : `numpy.ndarray`, shape (n,) + Direction along which the curvature of the quadratic model is + evaluated. + interpolation : `cobyqa.models.Interpolation` + Interpolation set. + + Returns + ------- + float + Curvature of the quadratic model along `v`. + """ + if self._debug: + assert v.shape == (self.n,), "The shape of `v` is not valid." + return ( + v @ self._e_hess @ v + + self._i_hess @ (interpolation.xpt.T @ v) ** 2.0 + ) + + def update(self, interpolation, k_new, dir_old, values_diff): + """ + Update the quadratic model. + + This method applies the derivative-free symmetric Broyden update to the + quadratic model. The `knew`-th interpolation point must be updated + before calling this method. + + Parameters + ---------- + interpolation : `cobyqa.models.Interpolation` + Updated interpolation set. + k_new : int + Index of the updated interpolation point. + dir_old : `numpy.ndarray`, shape (n,) + Value of ``interpolation.xpt[:, k_new]`` before the update. + values_diff : `numpy.ndarray`, shape (npt,) + Differences between the values of the interpolated nonlinear + function and the previous quadratic model at the updated + interpolation points. + + Raises + ------ + `numpy.linalg.LinAlgError` + If the interpolation system is ill-defined. + """ + if self._debug: + assert 0 <= k_new < self.npt, "The index `k_new` is not valid." + assert dir_old.shape == ( + self.n, + ), "The shape of `dir_old` is not valid." + assert values_diff.shape == ( + self.npt, + ), "The shape of `values_diff` is not valid." + + # Forward the k_new-th element of the implicit Hessian matrix to the + # explicit Hessian matrix. This must be done because the implicit + # Hessian matrix is related to the interpolation points, and the + # k_new-th interpolation point is modified. + self._e_hess += self._i_hess[k_new] * np.outer(dir_old, dir_old) + self._i_hess[k_new] = 0.0 + + # Update the quadratic model. + const, grad, i_hess, ill_conditioned = self._get_model( + interpolation, + values_diff, + ) + self._const += const + self._grad += grad + self._i_hess += i_hess + return ill_conditioned + + def shift_x_base(self, interpolation, new_x_base): + """ + Shift the point around which the quadratic model is defined. + + Parameters + ---------- + interpolation : `cobyqa.models.Interpolation` + Previous interpolation set. + new_x_base : `numpy.ndarray`, shape (n,) + Point that will replace ``interpolation.x_base``. + """ + if self._debug: + assert new_x_base.shape == ( + self.n, + ), "The shape of `new_x_base` is not valid." + self._const = self(new_x_base, interpolation) + self._grad = self.grad(new_x_base, interpolation) + shift = new_x_base - interpolation.x_base + update = np.outer( + shift, + (interpolation.xpt - 0.5 * shift[:, np.newaxis]) @ self._i_hess, + ) + self._e_hess += update + update.T + + @staticmethod + def solve_systems(interpolation, rhs): + """ + Solve the interpolation systems. + + Parameters + ---------- + interpolation : `cobyqa.models.Interpolation` + Interpolation set. + rhs : `numpy.ndarray`, shape (npt + n + 1, m) + Right-hand side vectors of the ``m`` interpolation systems. + + Returns + ------- + `numpy.ndarray`, shape (npt + n + 1, m) + Solutions of the interpolation systems. + `numpy.ndarray`, shape (m, ) + Whether the interpolation systems are ill-conditioned. + + Raises + ------ + `numpy.linalg.LinAlgError` + If the interpolation systems are ill-defined. + """ + n, npt = interpolation.xpt.shape + assert ( + rhs.ndim == 2 and rhs.shape[0] == npt + n + 1 + ), "The shape of `rhs` is not valid." + + # Build the left-hand side matrix of the interpolation system. The + # matrix below stores diag(left_scaling) * W * diag(right_scaling), + # where W is the theoretical matrix of the interpolation system. The + # left and right scaling matrices are chosen to keep the elements in + # the matrix well-balanced. + a, right_scaling, eig = build_system(interpolation) + + # Build the solution. After a discussion with Mike Saunders and Alexis + # Montoison during their visit to the Hong Kong Polytechnic University + # in 2024, we decided to use the eigendecomposition of the symmetric + # matrix a. This is more stable than the previously employed LBL + # decomposition, and allows us to directly detect ill-conditioning of + # the system and to build the least-squares solution if necessary. + # Numerical experiments have shown that this strategy improves the + # performance of the solver. + rhs_scaled = rhs * right_scaling[:, np.newaxis] + if not (np.all(np.isfinite(a)) and np.all(np.isfinite(rhs_scaled))): + raise np.linalg.LinAlgError( + "The interpolation system is ill-defined." + ) + + # calculated in build_system + eig_values, eig_vectors = eig + + large_eig_values = np.abs(eig_values) > EPS + eig_vectors = eig_vectors[:, large_eig_values] + inv_eig_values = 1.0 / eig_values[large_eig_values] + ill_conditioned = ~np.all(large_eig_values, 0) + left_scaled_solutions = eig_vectors @ ( + (eig_vectors.T @ rhs_scaled) * inv_eig_values[:, np.newaxis] + ) + return ( + left_scaled_solutions * right_scaling[:, np.newaxis], + ill_conditioned, + ) + + @staticmethod + def _get_model(interpolation, values): + """ + Solve the interpolation system. + + Parameters + ---------- + interpolation : `cobyqa.models.Interpolation` + Interpolation set. + values : `numpy.ndarray`, shape (npt,) + Values of the interpolated function at the interpolation points. + + Returns + ------- + float + Constant term of the quadratic model. + `numpy.ndarray`, shape (n,) + Gradient of the quadratic model at ``interpolation.x_base``. + `numpy.ndarray`, shape (npt,) + Implicit Hessian matrix of the quadratic model. + + Raises + ------ + `numpy.linalg.LinAlgError` + If the interpolation system is ill-defined. + """ + assert values.shape == ( + interpolation.npt, + ), "The shape of `values` is not valid." + n, npt = interpolation.xpt.shape + x, ill_conditioned = Quadratic.solve_systems( + interpolation, + np.block( + [ + [ + values, + np.zeros(n + 1), + ] + ] + ).T, + ) + return x[npt, 0], x[npt + 1:, 0], x[:npt, 0], ill_conditioned + + +class Models: + """ + Models for a nonlinear optimization problem. + """ + + def __init__(self, pb, options, penalty): + """ + Initialize the models. + + Parameters + ---------- + pb : `cobyqa.problem.Problem` + Problem to be solved. + options : dict + Options of the solver. + penalty : float + Penalty parameter used to select the point in the filter to forward + to the callback function. + + Raises + ------ + `cobyqa.utils.MaxEvalError` + If the maximum number of evaluations is reached. + `cobyqa.utils.TargetSuccess` + If a nearly feasible point has been found with an objective + function value below the target. + `cobyqa.utils.FeasibleSuccess` + If a feasible point has been found for a feasibility problem. + `numpy.linalg.LinAlgError` + If the interpolation system is ill-defined. + """ + # Set the initial interpolation set. + self._debug = options[Options.DEBUG] + self._interpolation = Interpolation(pb, options) + + # Evaluate the nonlinear functions at the initial interpolation points. + x_eval = self.interpolation.point(0) + fun_init, cub_init, ceq_init = pb(x_eval, penalty) + self._fun_val = np.full(options[Options.NPT], np.nan) + self._cub_val = np.full((options[Options.NPT], cub_init.size), np.nan) + self._ceq_val = np.full((options[Options.NPT], ceq_init.size), np.nan) + for k in range(options[Options.NPT]): + if k >= options[Options.MAX_EVAL]: + raise MaxEvalError + if k == 0: + self.fun_val[k] = fun_init + self.cub_val[k, :] = cub_init + self.ceq_val[k, :] = ceq_init + else: + x_eval = self.interpolation.point(k) + self.fun_val[k], self.cub_val[k, :], self.ceq_val[k, :] = pb( + x_eval, + penalty, + ) + + # Stop the iterations if the problem is a feasibility problem and + # the current interpolation point is feasible. + if ( + pb.is_feasibility + and pb.maxcv( + self.interpolation.point(k), + self.cub_val[k, :], + self.ceq_val[k, :], + ) + <= options[Options.FEASIBILITY_TOL] + ): + raise FeasibleSuccess + + # Stop the iterations if the current interpolation point is nearly + # feasible and has an objective function value below the target. + if ( + self._fun_val[k] <= options[Options.TARGET] + and pb.maxcv( + self.interpolation.point(k), + self.cub_val[k, :], + self.ceq_val[k, :], + ) + <= options[Options.FEASIBILITY_TOL] + ): + raise TargetSuccess + + # Build the initial quadratic models. + self._fun = Quadratic( + self.interpolation, + self._fun_val, + options[Options.DEBUG], + ) + self._cub = np.empty(self.m_nonlinear_ub, dtype=Quadratic) + self._ceq = np.empty(self.m_nonlinear_eq, dtype=Quadratic) + for i in range(self.m_nonlinear_ub): + self._cub[i] = Quadratic( + self.interpolation, + self.cub_val[:, i], + options[Options.DEBUG], + ) + for i in range(self.m_nonlinear_eq): + self._ceq[i] = Quadratic( + self.interpolation, + self.ceq_val[:, i], + options[Options.DEBUG], + ) + if self._debug: + self._check_interpolation_conditions() + + @property + def n(self): + """ + Dimension of the problem. + + Returns + ------- + int + Dimension of the problem. + """ + return self.interpolation.n + + @property + def npt(self): + """ + Number of interpolation points. + + Returns + ------- + int + Number of interpolation points. + """ + return self.interpolation.npt + + @property + def m_nonlinear_ub(self): + """ + Number of nonlinear inequality constraints. + + Returns + ------- + int + Number of nonlinear inequality constraints. + """ + return self.cub_val.shape[1] + + @property + def m_nonlinear_eq(self): + """ + Number of nonlinear equality constraints. + + Returns + ------- + int + Number of nonlinear equality constraints. + """ + return self.ceq_val.shape[1] + + @property + def interpolation(self): + """ + Interpolation set. + + Returns + ------- + `cobyqa.models.Interpolation` + Interpolation set. + """ + return self._interpolation + + @property + def fun_val(self): + """ + Values of the objective function at the interpolation points. + + Returns + ------- + `numpy.ndarray`, shape (npt,) + Values of the objective function at the interpolation points. + """ + return self._fun_val + + @property + def cub_val(self): + """ + Values of the nonlinear inequality constraint functions at the + interpolation points. + + Returns + ------- + `numpy.ndarray`, shape (npt, m_nonlinear_ub) + Values of the nonlinear inequality constraint functions at the + interpolation points. + """ + return self._cub_val + + @property + def ceq_val(self): + """ + Values of the nonlinear equality constraint functions at the + interpolation points. + + Returns + ------- + `numpy.ndarray`, shape (npt, m_nonlinear_eq) + Values of the nonlinear equality constraint functions at the + interpolation points. + """ + return self._ceq_val + + def fun(self, x): + """ + Evaluate the quadratic model of the objective function at a given + point. + + Parameters + ---------- + x : `numpy.ndarray`, shape (n,) + Point at which to evaluate the quadratic model of the objective + function. + + Returns + ------- + float + Value of the quadratic model of the objective function at `x`. + """ + if self._debug: + assert x.shape == (self.n,), "The shape of `x` is not valid." + return self._fun(x, self.interpolation) + + def fun_grad(self, x): + """ + Evaluate the gradient of the quadratic model of the objective function + at a given point. + + Parameters + ---------- + x : `numpy.ndarray`, shape (n,) + Point at which to evaluate the gradient of the quadratic model of + the objective function. + + Returns + ------- + `numpy.ndarray`, shape (n,) + Gradient of the quadratic model of the objective function at `x`. + """ + if self._debug: + assert x.shape == (self.n,), "The shape of `x` is not valid." + return self._fun.grad(x, self.interpolation) + + def fun_hess(self): + """ + Evaluate the Hessian matrix of the quadratic model of the objective + function. + + Returns + ------- + `numpy.ndarray`, shape (n, n) + Hessian matrix of the quadratic model of the objective function. + """ + return self._fun.hess(self.interpolation) + + def fun_hess_prod(self, v): + """ + Evaluate the right product of the Hessian matrix of the quadratic model + of the objective function with a given vector. + + Parameters + ---------- + v : `numpy.ndarray`, shape (n,) + Vector with which the Hessian matrix of the quadratic model of the + objective function is multiplied from the right. + + Returns + ------- + `numpy.ndarray`, shape (n,) + Right product of the Hessian matrix of the quadratic model of the + objective function with `v`. + """ + if self._debug: + assert v.shape == (self.n,), "The shape of `v` is not valid." + return self._fun.hess_prod(v, self.interpolation) + + def fun_curv(self, v): + """ + Evaluate the curvature of the quadratic model of the objective function + along a given direction. + + Parameters + ---------- + v : `numpy.ndarray`, shape (n,) + Direction along which the curvature of the quadratic model of the + objective function is evaluated. + + Returns + ------- + float + Curvature of the quadratic model of the objective function along + `v`. + """ + if self._debug: + assert v.shape == (self.n,), "The shape of `v` is not valid." + return self._fun.curv(v, self.interpolation) + + def fun_alt_grad(self, x): + """ + Evaluate the gradient of the alternative quadratic model of the + objective function at a given point. + + Parameters + ---------- + x : `numpy.ndarray`, shape (n,) + Point at which to evaluate the gradient of the alternative + quadratic model of the objective function. + + Returns + ------- + `numpy.ndarray`, shape (n,) + Gradient of the alternative quadratic model of the objective + function at `x`. + + Raises + ------ + `numpy.linalg.LinAlgError` + If the interpolation system is ill-defined. + """ + if self._debug: + assert x.shape == (self.n,), "The shape of `x` is not valid." + model = Quadratic(self.interpolation, self.fun_val, self._debug) + return model.grad(x, self.interpolation) + + def cub(self, x, mask=None): + """ + Evaluate the quadratic models of the nonlinear inequality functions at + a given point. + + Parameters + ---------- + x : `numpy.ndarray`, shape (n,) + Point at which to evaluate the quadratic models of the nonlinear + inequality functions. + mask : `numpy.ndarray`, shape (m_nonlinear_ub,), optional + Mask of the quadratic models to consider. + + Returns + ------- + `numpy.ndarray` + Values of the quadratic model of the nonlinear inequality + functions. + """ + if self._debug: + assert x.shape == (self.n,), "The shape of `x` is not valid." + assert mask is None or mask.shape == ( + self.m_nonlinear_ub, + ), "The shape of `mask` is not valid." + return np.array( + [model(x, self.interpolation) for model in self._get_cub(mask)] + ) + + def cub_grad(self, x, mask=None): + """ + Evaluate the gradients of the quadratic models of the nonlinear + inequality functions at a given point. + + Parameters + ---------- + x : `numpy.ndarray`, shape (n,) + Point at which to evaluate the gradients of the quadratic models of + the nonlinear inequality functions. + mask : `numpy.ndarray`, shape (m_nonlinear_eq,), optional + Mask of the quadratic models to consider. + + Returns + ------- + `numpy.ndarray` + Gradients of the quadratic model of the nonlinear inequality + functions. + """ + if self._debug: + assert x.shape == (self.n,), "The shape of `x` is not valid." + assert mask is None or mask.shape == ( + self.m_nonlinear_ub, + ), "The shape of `mask` is not valid." + return np.reshape( + [model.grad(x, self.interpolation) + for model in self._get_cub(mask)], + (-1, self.n), + ) + + def cub_hess(self, mask=None): + """ + Evaluate the Hessian matrices of the quadratic models of the nonlinear + inequality functions. + + Parameters + ---------- + mask : `numpy.ndarray`, shape (m_nonlinear_ub,), optional + Mask of the quadratic models to consider. + + Returns + ------- + `numpy.ndarray` + Hessian matrices of the quadratic models of the nonlinear + inequality functions. + """ + if self._debug: + assert mask is None or mask.shape == ( + self.m_nonlinear_ub, + ), "The shape of `mask` is not valid." + return np.reshape( + [model.hess(self.interpolation) for model in self._get_cub(mask)], + (-1, self.n, self.n), + ) + + def cub_hess_prod(self, v, mask=None): + """ + Evaluate the right product of the Hessian matrices of the quadratic + models of the nonlinear inequality functions with a given vector. + + Parameters + ---------- + v : `numpy.ndarray`, shape (n,) + Vector with which the Hessian matrices of the quadratic models of + the nonlinear inequality functions are multiplied from the right. + mask : `numpy.ndarray`, shape (m_nonlinear_ub,), optional + Mask of the quadratic models to consider. + + Returns + ------- + `numpy.ndarray` + Right products of the Hessian matrices of the quadratic models of + the nonlinear inequality functions with `v`. + """ + if self._debug: + assert v.shape == (self.n,), "The shape of `v` is not valid." + assert mask is None or mask.shape == ( + self.m_nonlinear_ub, + ), "The shape of `mask` is not valid." + return np.reshape( + [ + model.hess_prod(v, self.interpolation) + for model in self._get_cub(mask) + ], + (-1, self.n), + ) + + def cub_curv(self, v, mask=None): + """ + Evaluate the curvature of the quadratic models of the nonlinear + inequality functions along a given direction. + + Parameters + ---------- + v : `numpy.ndarray`, shape (n,) + Direction along which the curvature of the quadratic models of the + nonlinear inequality functions is evaluated. + mask : `numpy.ndarray`, shape (m_nonlinear_ub,), optional + Mask of the quadratic models to consider. + + Returns + ------- + `numpy.ndarray` + Curvature of the quadratic models of the nonlinear inequality + functions along `v`. + """ + if self._debug: + assert v.shape == (self.n,), "The shape of `v` is not valid." + assert mask is None or mask.shape == ( + self.m_nonlinear_ub, + ), "The shape of `mask` is not valid." + return np.array( + [model.curv(v, self.interpolation) + for model in self._get_cub(mask)] + ) + + def ceq(self, x, mask=None): + """ + Evaluate the quadratic models of the nonlinear equality functions at a + given point. + + Parameters + ---------- + x : `numpy.ndarray`, shape (n,) + Point at which to evaluate the quadratic models of the nonlinear + equality functions. + mask : `numpy.ndarray`, shape (m_nonlinear_eq,), optional + Mask of the quadratic models to consider. + + Returns + ------- + `numpy.ndarray` + Values of the quadratic model of the nonlinear equality functions. + """ + if self._debug: + assert x.shape == (self.n,), "The shape of `x` is not valid." + assert mask is None or mask.shape == ( + self.m_nonlinear_eq, + ), "The shape of `mask` is not valid." + return np.array( + [model(x, self.interpolation) for model in self._get_ceq(mask)] + ) + + def ceq_grad(self, x, mask=None): + """ + Evaluate the gradients of the quadratic models of the nonlinear + equality functions at a given point. + + Parameters + ---------- + x : `numpy.ndarray`, shape (n,) + Point at which to evaluate the gradients of the quadratic models of + the nonlinear equality functions. + mask : `numpy.ndarray`, shape (m_nonlinear_eq,), optional + Mask of the quadratic models to consider. + + Returns + ------- + `numpy.ndarray` + Gradients of the quadratic model of the nonlinear equality + functions. + """ + if self._debug: + assert x.shape == (self.n,), "The shape of `x` is not valid." + assert mask is None or mask.shape == ( + self.m_nonlinear_eq, + ), "The shape of `mask` is not valid." + return np.reshape( + [model.grad(x, self.interpolation) + for model in self._get_ceq(mask)], + (-1, self.n), + ) + + def ceq_hess(self, mask=None): + """ + Evaluate the Hessian matrices of the quadratic models of the nonlinear + equality functions. + + Parameters + ---------- + mask : `numpy.ndarray`, shape (m_nonlinear_eq,), optional + Mask of the quadratic models to consider. + + Returns + ------- + `numpy.ndarray` + Hessian matrices of the quadratic models of the nonlinear equality + functions. + """ + if self._debug: + assert mask is None or mask.shape == ( + self.m_nonlinear_eq, + ), "The shape of `mask` is not valid." + return np.reshape( + [model.hess(self.interpolation) for model in self._get_ceq(mask)], + (-1, self.n, self.n), + ) + + def ceq_hess_prod(self, v, mask=None): + """ + Evaluate the right product of the Hessian matrices of the quadratic + models of the nonlinear equality functions with a given vector. + + Parameters + ---------- + v : `numpy.ndarray`, shape (n,) + Vector with which the Hessian matrices of the quadratic models of + the nonlinear equality functions are multiplied from the right. + mask : `numpy.ndarray`, shape (m_nonlinear_eq,), optional + Mask of the quadratic models to consider. + + Returns + ------- + `numpy.ndarray` + Right products of the Hessian matrices of the quadratic models of + the nonlinear equality functions with `v`. + """ + if self._debug: + assert v.shape == (self.n,), "The shape of `v` is not valid." + assert mask is None or mask.shape == ( + self.m_nonlinear_eq, + ), "The shape of `mask` is not valid." + return np.reshape( + [ + model.hess_prod(v, self.interpolation) + for model in self._get_ceq(mask) + ], + (-1, self.n), + ) + + def ceq_curv(self, v, mask=None): + """ + Evaluate the curvature of the quadratic models of the nonlinear + equality functions along a given direction. + + Parameters + ---------- + v : `numpy.ndarray`, shape (n,) + Direction along which the curvature of the quadratic models of the + nonlinear equality functions is evaluated. + mask : `numpy.ndarray`, shape (m_nonlinear_eq,), optional + Mask of the quadratic models to consider. + + Returns + ------- + `numpy.ndarray` + Curvature of the quadratic models of the nonlinear equality + functions along `v`. + """ + if self._debug: + assert v.shape == (self.n,), "The shape of `v` is not valid." + assert mask is None or mask.shape == ( + self.m_nonlinear_eq, + ), "The shape of `mask` is not valid." + return np.array( + [model.curv(v, self.interpolation) + for model in self._get_ceq(mask)] + ) + + def reset_models(self): + """ + Set the quadratic models of the objective function, nonlinear + inequality constraints, and nonlinear equality constraints to the + alternative quadratic models. + + Raises + ------ + `numpy.linalg.LinAlgError` + If the interpolation system is ill-defined. + """ + self._fun = Quadratic(self.interpolation, self.fun_val, self._debug) + for i in range(self.m_nonlinear_ub): + self._cub[i] = Quadratic( + self.interpolation, + self.cub_val[:, i], + self._debug, + ) + for i in range(self.m_nonlinear_eq): + self._ceq[i] = Quadratic( + self.interpolation, + self.ceq_val[:, i], + self._debug, + ) + if self._debug: + self._check_interpolation_conditions() + + def update_interpolation(self, k_new, x_new, fun_val, cub_val, ceq_val): + """ + Update the interpolation set. + + This method updates the interpolation set by replacing the `knew`-th + interpolation point with `xnew`. It also updates the function values + and the quadratic models. + + Parameters + ---------- + k_new : int + Index of the updated interpolation point. + x_new : `numpy.ndarray`, shape (n,) + New interpolation point. Its value is interpreted as relative to + the origin, not the base point. + fun_val : float + Value of the objective function at `x_new`. + Objective function value at `x_new`. + cub_val : `numpy.ndarray`, shape (m_nonlinear_ub,) + Values of the nonlinear inequality constraints at `x_new`. + ceq_val : `numpy.ndarray`, shape (m_nonlinear_eq,) + Values of the nonlinear equality constraints at `x_new`. + + Raises + ------ + `numpy.linalg.LinAlgError` + If the interpolation system is ill-defined. + """ + if self._debug: + assert 0 <= k_new < self.npt, "The index `k_new` is not valid." + assert x_new.shape == (self.n,), \ + "The shape of `x_new` is not valid." + assert isinstance(fun_val, float), \ + "The function value is not valid." + assert cub_val.shape == ( + self.m_nonlinear_ub, + ), "The shape of `cub_val` is not valid." + assert ceq_val.shape == ( + self.m_nonlinear_eq, + ), "The shape of `ceq_val` is not valid." + + # Compute the updates in the interpolation conditions. + fun_diff = np.zeros(self.npt) + cub_diff = np.zeros(self.cub_val.shape) + ceq_diff = np.zeros(self.ceq_val.shape) + fun_diff[k_new] = fun_val - self.fun(x_new) + cub_diff[k_new, :] = cub_val - self.cub(x_new) + ceq_diff[k_new, :] = ceq_val - self.ceq(x_new) + + # Update the function values. + self.fun_val[k_new] = fun_val + self.cub_val[k_new, :] = cub_val + self.ceq_val[k_new, :] = ceq_val + + # Update the interpolation set. + dir_old = np.copy(self.interpolation.xpt[:, k_new]) + self.interpolation.xpt[:, k_new] = x_new - self.interpolation.x_base + + # Update the quadratic models. + ill_conditioned = self._fun.update( + self.interpolation, + k_new, + dir_old, + fun_diff, + ) + for i in range(self.m_nonlinear_ub): + ill_conditioned = ill_conditioned or self._cub[i].update( + self.interpolation, + k_new, + dir_old, + cub_diff[:, i], + ) + for i in range(self.m_nonlinear_eq): + ill_conditioned = ill_conditioned or self._ceq[i].update( + self.interpolation, + k_new, + dir_old, + ceq_diff[:, i], + ) + if self._debug: + self._check_interpolation_conditions() + return ill_conditioned + + def determinants(self, x_new, k_new=None): + """ + Compute the normalized determinants of the new interpolation systems. + + Parameters + ---------- + x_new : `numpy.ndarray`, shape (n,) + New interpolation point. Its value is interpreted as relative to + the origin, not the base point. + k_new : int, optional + Index of the updated interpolation point. If `k_new` is not + specified, all the possible determinants are computed. + + Returns + ------- + {float, `numpy.ndarray`, shape (npt,)} + Determinant(s) of the new interpolation system. + + Raises + ------ + `numpy.linalg.LinAlgError` + If the interpolation system is ill-defined. + + Notes + ----- + The determinants are normalized by the determinant of the current + interpolation system. For stability reasons, the calculations are done + using the formula (2.12) in [1]_. + + References + ---------- + .. [1] M. J. D. Powell. On updating the inverse of a KKT matrix. + Technical Report DAMTP 2004/NA01, Department of Applied Mathematics + and Theoretical Physics, University of Cambridge, Cambridge, UK, + 2004. + """ + if self._debug: + assert x_new.shape == (self.n,), \ + "The shape of `x_new` is not valid." + assert ( + k_new is None or 0 <= k_new < self.npt + ), "The index `k_new` is not valid." + + # Compute the values independent of k_new. + shift = x_new - self.interpolation.x_base + new_col = np.empty((self.npt + self.n + 1, 1)) + new_col[: self.npt, 0] = ( + 0.5 * (self.interpolation.xpt.T @ shift) ** 2.0) + new_col[self.npt, 0] = 1.0 + new_col[self.npt + 1:, 0] = shift + inv_new_col = Quadratic.solve_systems(self.interpolation, new_col)[0] + beta = 0.5 * (shift @ shift) ** 2.0 - new_col[:, 0] @ inv_new_col[:, 0] + + # Compute the values that depend on k. + if k_new is None: + coord_vec = np.eye(self.npt + self.n + 1, self.npt) + alpha = np.diag( + Quadratic.solve_systems( + self.interpolation, + coord_vec, + )[0] + ) + tau = inv_new_col[: self.npt, 0] + else: + coord_vec = np.eye(self.npt + self.n + 1, 1, -k_new) + alpha = Quadratic.solve_systems( + self.interpolation, + coord_vec, + )[ + 0 + ][k_new, 0] + tau = inv_new_col[k_new, 0] + return alpha * beta + tau**2.0 + + def shift_x_base(self, new_x_base, options): + """ + Shift the base point without changing the interpolation set. + + Parameters + ---------- + new_x_base : `numpy.ndarray`, shape (n,) + New base point. + options : dict + Options of the solver. + """ + if self._debug: + assert new_x_base.shape == ( + self.n, + ), "The shape of `new_x_base` is not valid." + + # Update the models. + self._fun.shift_x_base(self.interpolation, new_x_base) + for model in self._cub: + model.shift_x_base(self.interpolation, new_x_base) + for model in self._ceq: + model.shift_x_base(self.interpolation, new_x_base) + + # Update the base point and the interpolation points. + shift = new_x_base - self.interpolation.x_base + self.interpolation.x_base += shift + self.interpolation.xpt -= shift[:, np.newaxis] + if options[Options.DEBUG]: + self._check_interpolation_conditions() + + def _get_cub(self, mask=None): + """ + Get the quadratic models of the nonlinear inequality constraints. + + Parameters + ---------- + mask : `numpy.ndarray`, shape (m_nonlinear_ub,), optional + Mask of the quadratic models to return. + + Returns + ------- + `numpy.ndarray` + Quadratic models of the nonlinear inequality constraints. + """ + return self._cub if mask is None else self._cub[mask] + + def _get_ceq(self, mask=None): + """ + Get the quadratic models of the nonlinear equality constraints. + + Parameters + ---------- + mask : `numpy.ndarray`, shape (m_nonlinear_eq,), optional + Mask of the quadratic models to return. + + Returns + ------- + `numpy.ndarray` + Quadratic models of the nonlinear equality constraints. + """ + return self._ceq if mask is None else self._ceq[mask] + + def _check_interpolation_conditions(self): + """ + Check the interpolation conditions of all quadratic models. + """ + error_fun = 0.0 + error_cub = 0.0 + error_ceq = 0.0 + for k in range(self.npt): + error_fun = np.max( + [ + error_fun, + np.abs( + self.fun(self.interpolation.point(k)) - self.fun_val[k] + ), + ] + ) + error_cub = np.max( + np.abs( + self.cub(self.interpolation.point(k)) - self.cub_val[k, :] + ), + initial=error_cub, + ) + error_ceq = np.max( + np.abs( + self.ceq(self.interpolation.point(k)) - self.ceq_val[k, :] + ), + initial=error_ceq, + ) + tol = 10.0 * np.sqrt(EPS) * max(self.n, self.npt) + if error_fun > tol * np.max(np.abs(self.fun_val), initial=1.0): + warnings.warn( + "The interpolation conditions for the objective function are " + "not satisfied.", + RuntimeWarning, + 2, + ) + if error_cub > tol * np.max(np.abs(self.cub_val), initial=1.0): + warnings.warn( + "The interpolation conditions for the inequality constraint " + "function are not satisfied.", + RuntimeWarning, + 2, + ) + if error_ceq > tol * np.max(np.abs(self.ceq_val), initial=1.0): + warnings.warn( + "The interpolation conditions for the equality constraint " + "function are not satisfied.", + RuntimeWarning, + 2, + ) diff --git a/.venv/lib/python3.12/site-packages/scipy/_external/cobyqa/problem.py b/.venv/lib/python3.12/site-packages/scipy/_external/cobyqa/problem.py new file mode 100644 index 0000000000000000000000000000000000000000..2dbebce3a48067e97da2b75bd2cdd609e01029b2 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/scipy/_external/cobyqa/problem.py @@ -0,0 +1,1296 @@ +from contextlib import suppress +from inspect import signature +import copy + +import numpy as np +from scipy.optimize import ( + Bounds, + LinearConstraint, + NonlinearConstraint, + OptimizeResult, +) +from scipy.optimize._constraints import PreparedConstraint + + +from .settings import PRINT_OPTIONS, BARRIER +from .utils import CallbackSuccess, get_arrays_tol +from .utils import exact_1d_array + + +class ObjectiveFunction: + """ + Real-valued objective function. + """ + + def __init__(self, fun, verbose, debug, *args): + """ + Initialize the objective function. + + Parameters + ---------- + fun : {callable, None} + Function to evaluate, or None. + + ``fun(x, *args) -> float`` + + where ``x`` is an array with shape (n,) and `args` is a tuple. + verbose : bool + Whether to print the function evaluations. + debug : bool + Whether to make debugging tests during the execution. + *args : tuple + Additional arguments to be passed to the function. + """ + if debug: + assert fun is None or callable(fun) + assert isinstance(verbose, bool) + assert isinstance(debug, bool) + + self._fun = fun + self._verbose = verbose + self._args = args + self._n_eval = 0 + + def __call__(self, x): + """ + Evaluate the objective function. + + Parameters + ---------- + x : array_like, shape (n,) + Point at which the objective function is evaluated. + + Returns + ------- + float + Function value at `x`. + """ + x = np.array(x, dtype=float) + if self._fun is None: + f = 0.0 + else: + f = float(np.squeeze(self._fun(x, *self._args))) + self._n_eval += 1 + if self._verbose: + with np.printoptions(**PRINT_OPTIONS): + print(f"{self.name}({x}) = {f}") + return f + + @property + def n_eval(self): + """ + Number of function evaluations. + + Returns + ------- + int + Number of function evaluations. + """ + return self._n_eval + + @property + def name(self): + """ + Name of the objective function. + + Returns + ------- + str + Name of the objective function. + """ + name = "" + if self._fun is not None: + try: + name = self._fun.__name__ + except AttributeError: + name = "fun" + return name + + +class BoundConstraints: + """ + Bound constraints ``xl <= x <= xu``. + """ + + def __init__(self, bounds): + """ + Initialize the bound constraints. + + Parameters + ---------- + bounds : scipy.optimize.Bounds + Bound constraints. + """ + self._xl = np.array(bounds.lb, float) + self._xu = np.array(bounds.ub, float) + + # Remove the ill-defined bounds. + self.xl[np.isnan(self.xl)] = -np.inf + self.xu[np.isnan(self.xu)] = np.inf + + self.is_feasible = ( + np.all(self.xl <= self.xu) + and np.all(self.xl < np.inf) + and np.all(self.xu > -np.inf) + ) + self.m = np.count_nonzero(self.xl > -np.inf) + np.count_nonzero( + self.xu < np.inf + ) + self.pcs = PreparedConstraint(bounds, np.ones(bounds.lb.size)) + + @property + def xl(self): + """ + Lower bound. + + Returns + ------- + `numpy.ndarray`, shape (n,) + Lower bound. + """ + return self._xl + + @property + def xu(self): + """ + Upper bound. + + Returns + ------- + `numpy.ndarray`, shape (n,) + Upper bound. + """ + return self._xu + + def maxcv(self, x): + """ + Evaluate the maximum constraint violation. + + Parameters + ---------- + x : array_like, shape (n,) + Point at which the maximum constraint violation is evaluated. + + Returns + ------- + float + Maximum constraint violation at `x`. + """ + x = np.asarray(x, dtype=float) + return self.violation(x) + + def violation(self, x): + # shortcut for no bounds + if self.is_feasible: + return np.array([0]) + else: + return self.pcs.violation(x) + + def project(self, x): + """ + Project a point onto the feasible set. + + Parameters + ---------- + x : array_like, shape (n,) + Point to be projected. + + Returns + ------- + `numpy.ndarray`, shape (n,) + Projection of `x` onto the feasible set. + """ + return np.clip(x, self.xl, self.xu) if self.is_feasible else x + + +class LinearConstraints: + """ + Linear constraints ``a_ub @ x <= b_ub`` and ``a_eq @ x == b_eq``. + """ + + def __init__(self, constraints, n, debug): + """ + Initialize the linear constraints. + + Parameters + ---------- + constraints : list of LinearConstraint + Linear constraints. + n : int + Number of variables. + debug : bool + Whether to make debugging tests during the execution. + """ + if debug: + assert isinstance(constraints, list) + for constraint in constraints: + assert isinstance(constraint, LinearConstraint) + assert isinstance(debug, bool) + + self._a_ub = np.empty((0, n)) + self._b_ub = np.empty(0) + self._a_eq = np.empty((0, n)) + self._b_eq = np.empty(0) + for constraint in constraints: + is_equality = np.abs( + constraint.ub - constraint.lb + ) <= get_arrays_tol(constraint.lb, constraint.ub) + if np.any(is_equality): + self._a_eq = np.vstack((self.a_eq, constraint.A[is_equality])) + self._b_eq = np.concatenate( + ( + self.b_eq, + 0.5 + * ( + constraint.lb[is_equality] + + constraint.ub[is_equality] + ), + ) + ) + if not np.all(is_equality): + self._a_ub = np.vstack( + ( + self.a_ub, + constraint.A[~is_equality], + -constraint.A[~is_equality], + ) + ) + self._b_ub = np.concatenate( + ( + self.b_ub, + constraint.ub[~is_equality], + -constraint.lb[~is_equality], + ) + ) + + # Remove the ill-defined constraints. + self.a_ub[np.isnan(self.a_ub)] = 0.0 + self.a_eq[np.isnan(self.a_eq)] = 0.0 + undef_ub = np.isnan(self.b_ub) | np.isinf(self.b_ub) + undef_eq = np.isnan(self.b_eq) + self._a_ub = self.a_ub[~undef_ub, :] + self._b_ub = self.b_ub[~undef_ub] + self._a_eq = self.a_eq[~undef_eq, :] + self._b_eq = self.b_eq[~undef_eq] + self.pcs = [ + PreparedConstraint(c, np.ones(n)) for c in constraints if c.A.size + ] + + @property + def a_ub(self): + """ + Left-hand side matrix of the linear inequality constraints. + + Returns + ------- + `numpy.ndarray`, shape (m, n) + Left-hand side matrix of the linear inequality constraints. + """ + return self._a_ub + + @property + def b_ub(self): + """ + Right-hand side vector of the linear inequality constraints. + + Returns + ------- + `numpy.ndarray`, shape (m, n) + Right-hand side vector of the linear inequality constraints. + """ + return self._b_ub + + @property + def a_eq(self): + """ + Left-hand side matrix of the linear equality constraints. + + Returns + ------- + `numpy.ndarray`, shape (m, n) + Left-hand side matrix of the linear equality constraints. + """ + return self._a_eq + + @property + def b_eq(self): + """ + Right-hand side vector of the linear equality constraints. + + Returns + ------- + `numpy.ndarray`, shape (m, n) + Right-hand side vector of the linear equality constraints. + """ + return self._b_eq + + @property + def m_ub(self): + """ + Number of linear inequality constraints. + + Returns + ------- + int + Number of linear inequality constraints. + """ + return self.b_ub.size + + @property + def m_eq(self): + """ + Number of linear equality constraints. + + Returns + ------- + int + Number of linear equality constraints. + """ + return self.b_eq.size + + def maxcv(self, x): + """ + Evaluate the maximum constraint violation. + + Parameters + ---------- + x : array_like, shape (n,) + Point at which the maximum constraint violation is evaluated. + + Returns + ------- + float + Maximum constraint violation at `x`. + """ + return np.max(self.violation(x), initial=0.0) + + def violation(self, x): + if len(self.pcs): + return np.concatenate([pc.violation(x) for pc in self.pcs]) + return np.array([]) + + +class NonlinearConstraints: + """ + Nonlinear constraints ``c_ub(x) <= 0`` and ``c_eq(x) == b_eq``. + """ + + def __init__(self, constraints, verbose, debug): + """ + Initialize the nonlinear constraints. + + Parameters + ---------- + constraints : list + Nonlinear constraints. + verbose : bool + Whether to print the function evaluations. + debug : bool + Whether to make debugging tests during the execution. + """ + if debug: + assert isinstance(constraints, list) + for constraint in constraints: + assert isinstance(constraint, NonlinearConstraint) + assert isinstance(verbose, bool) + assert isinstance(debug, bool) + + self._constraints = constraints + self.pcs = [] + self._verbose = verbose + + # map of indexes for equality and inequality constraints + self._map_ub = None + self._map_eq = None + self._m_ub = self._m_eq = None + + def __call__(self, x): + """ + Calculates the residual (slack) for the constraints. + + Parameters + ---------- + x : array_like, shape (n,) + Point at which the constraints are evaluated. + + Returns + ------- + `numpy.ndarray`, shape (m_nonlinear_ub,) + Nonlinear inequality constraint slack values. + `numpy.ndarray`, shape (m_nonlinear_eq,) + Nonlinear equality constraint slack values. + """ + if not len(self._constraints): + self._m_eq = self._m_ub = 0 + return np.array([]), np.array([]) + + x = np.array(x, dtype=float) + # first time around the constraints haven't been prepared + if not len(self.pcs): + self._map_ub = [] + self._map_eq = [] + self._m_eq = 0 + self._m_ub = 0 + + for constraint in self._constraints: + if not callable(constraint.jac): + # having a callable constraint function prevents + # constraint.fun from being evaluated when preparing + # constraint + c = copy.copy(constraint) + c.jac = lambda x0: x0 + c.hess = lambda x0, v: 0.0 + pc = PreparedConstraint(c, x) + else: + pc = PreparedConstraint(constraint, x) + # we're going to be using the same x value again immediately + # after this initialisation + pc.fun.f_updated = True + + self.pcs.append(pc) + idx = np.arange(pc.fun.m) + + # figure out equality and inequality maps + lb, ub = pc.bounds[0], pc.bounds[1] + arr_tol = get_arrays_tol(lb, ub) + is_equality = np.abs(ub - lb) <= arr_tol + self._map_eq.append(idx[is_equality]) + self._map_ub.append(idx[~is_equality]) + + # these values will be corrected to their proper values later + self._m_eq += np.count_nonzero(is_equality) + self._m_ub += np.count_nonzero(~is_equality) + + c_ub = [] + c_eq = [] + for i, pc in enumerate(self.pcs): + val = pc.fun.fun(x) + if self._verbose: + with np.printoptions(**PRINT_OPTIONS): + with suppress(AttributeError): + fun_name = self._constraints[i].fun.__name__ + print(f"{fun_name}({x}) = {val}") + + # separate violations into c_eq and c_ub + eq_idx = self._map_eq[i] + ub_idx = self._map_ub[i] + + ub_val = val[ub_idx] + if len(ub_idx): + xl = pc.bounds[0][ub_idx] + xu = pc.bounds[1][ub_idx] + + # calculate slack within lower bound + finite_xl = xl > -np.inf + _v = xl[finite_xl] - ub_val[finite_xl] + c_ub.append(_v) + + # calculate slack within lower bound + finite_xu = xu < np.inf + _v = ub_val[finite_xu] - xu[finite_xu] + c_ub.append(_v) + + # equality constraints taken from midpoint between lb and ub + eq_val = val[eq_idx] + if len(eq_idx): + midpoint = 0.5 * (pc.bounds[1][eq_idx] + pc.bounds[0][eq_idx]) + eq_val -= midpoint + c_eq.append(eq_val) + + if self._m_eq: + c_eq = np.concatenate(c_eq) + else: + c_eq = np.array([]) + + if self._m_ub: + c_ub = np.concatenate(c_ub) + else: + c_ub = np.array([]) + + self._m_ub = c_ub.size + self._m_eq = c_eq.size + + return c_ub, c_eq + + @property + def m_ub(self): + """ + Number of nonlinear inequality constraints. + + Returns + ------- + int + Number of nonlinear inequality constraints. + + Raises + ------ + ValueError + If the number of nonlinear inequality constraints is unknown. + """ + if self._m_ub is None: + raise ValueError( + "The number of nonlinear inequality constraints is unknown." + ) + else: + return self._m_ub + + @property + def m_eq(self): + """ + Number of nonlinear equality constraints. + + Returns + ------- + int + Number of nonlinear equality constraints. + + Raises + ------ + ValueError + If the number of nonlinear equality constraints is unknown. + """ + if self._m_eq is None: + raise ValueError( + "The number of nonlinear equality constraints is unknown." + ) + else: + return self._m_eq + + @property + def n_eval(self): + """ + Number of function evaluations. + + Returns + ------- + int + Number of function evaluations. + """ + if len(self.pcs): + return self.pcs[0].fun.nfev + else: + return 0 + + def maxcv(self, x, cub_val=None, ceq_val=None): + """ + Evaluate the maximum constraint violation. + + Parameters + ---------- + x : array_like, shape (n,) + Point at which the maximum constraint violation is evaluated. + cub_val : array_like, shape (m_nonlinear_ub,), optional + Values of the nonlinear inequality constraints. If not provided, + the nonlinear inequality constraints are evaluated at `x`. + ceq_val : array_like, shape (m_nonlinear_eq,), optional + Values of the nonlinear equality constraints. If not provided, + the nonlinear equality constraints are evaluated at `x`. + + Returns + ------- + float + Maximum constraint violation at `x`. + """ + return np.max( + self.violation(x, cub_val=cub_val, ceq_val=ceq_val), initial=0.0 + ) + + def violation(self, x, cub_val=None, ceq_val=None): + return np.concatenate([pc.violation(x) for pc in self.pcs]) + + +class Problem: + """ + Optimization problem. + """ + + def __init__( + self, + obj, + x0, + bounds, + linear, + nonlinear, + callback, + feasibility_tol, + scale, + store_history, + history_size, + filter_size, + debug, + ): + """ + Initialize the nonlinear problem. + + The problem is preprocessed to remove all the variables that are fixed + by the bound constraints. + + Parameters + ---------- + obj : ObjectiveFunction + Objective function. + x0 : array_like, shape (n,) + Initial guess. + bounds : BoundConstraints + Bound constraints. + linear : LinearConstraints + Linear constraints. + nonlinear : NonlinearConstraints + Nonlinear constraints. + callback : {callable, None} + Callback function. + feasibility_tol : float + Tolerance on the constraint violation. + scale : bool + Whether to scale the problem according to the bounds. + store_history : bool + Whether to store the function evaluations. + history_size : int + Maximum number of function evaluations to store. + filter_size : int + Maximum number of points in the filter. + debug : bool + Whether to make debugging tests during the execution. + """ + if debug: + assert isinstance(obj, ObjectiveFunction) + assert isinstance(bounds, BoundConstraints) + assert isinstance(linear, LinearConstraints) + assert isinstance(nonlinear, NonlinearConstraints) + assert isinstance(feasibility_tol, float) + assert isinstance(scale, bool) + assert isinstance(store_history, bool) + assert isinstance(history_size, int) + if store_history: + assert history_size > 0 + assert isinstance(filter_size, int) + assert filter_size > 0 + assert isinstance(debug, bool) + + self._obj = obj + self._linear = linear + self._nonlinear = nonlinear + if callback is not None: + if not callable(callback): + raise TypeError("The callback must be a callable function.") + self._callback = callback + + # Check the consistency of the problem. + x0 = exact_1d_array(x0, "The initial guess must be a vector.") + n = x0.size + if bounds.xl.size != n: + raise ValueError(f"The bounds must have {n} elements.") + if linear.a_ub.shape[1] != n: + raise ValueError( + f"The left-hand side matrices of the linear constraints must " + f"have {n} columns." + ) + + # Check which variables are fixed. + tol = get_arrays_tol(bounds.xl, bounds.xu) + self._fixed_idx = (bounds.xl <= bounds.xu) & ( + np.abs(bounds.xl - bounds.xu) < tol + ) + self._fixed_val = 0.5 * ( + bounds.xl[self._fixed_idx] + bounds.xu[self._fixed_idx] + ) + self._fixed_val = np.clip( + self._fixed_val, + bounds.xl[self._fixed_idx], + bounds.xu[self._fixed_idx], + ) + + # Set the bound constraints. + self._orig_bounds = bounds + self._bounds = BoundConstraints( + Bounds(bounds.xl[~self._fixed_idx], bounds.xu[~self._fixed_idx]) + ) + + # Set the initial guess. + self._x0 = self._bounds.project(x0[~self._fixed_idx]) + + # Set the linear constraints. + b_eq = linear.b_eq - linear.a_eq[:, self._fixed_idx] @ self._fixed_val + self._linear = LinearConstraints( + [ + LinearConstraint( + linear.a_ub[:, ~self._fixed_idx], + -np.inf, + linear.b_ub + - linear.a_ub[:, self._fixed_idx] @ self._fixed_val, + ), + LinearConstraint(linear.a_eq[:, ~self._fixed_idx], b_eq, b_eq), + ], + self.n, + debug, + ) + + # Scale the problem if necessary. + scale = ( + scale + and self._bounds.is_feasible + and np.all(np.isfinite(self._bounds.xl)) + and np.all(np.isfinite(self._bounds.xu)) + ) + if scale: + self._scaling_factor = 0.5 * (self._bounds.xu - self._bounds.xl) + self._scaling_shift = 0.5 * (self._bounds.xu + self._bounds.xl) + self._bounds = BoundConstraints( + Bounds(-np.ones(self.n), np.ones(self.n)) + ) + b_eq = self._linear.b_eq - self._linear.a_eq @ self._scaling_shift + self._linear = LinearConstraints( + [ + LinearConstraint( + self._linear.a_ub @ np.diag(self._scaling_factor), + -np.inf, + self._linear.b_ub + - self._linear.a_ub @ self._scaling_shift, + ), + LinearConstraint( + self._linear.a_eq @ np.diag(self._scaling_factor), + b_eq, + b_eq, + ), + ], + self.n, + debug, + ) + self._x0 = (self._x0 - self._scaling_shift) / self._scaling_factor + else: + self._scaling_factor = np.ones(self.n) + self._scaling_shift = np.zeros(self.n) + + # Set the initial filter. + self._feasibility_tol = feasibility_tol + self._filter_size = filter_size + self._fun_filter = [] + self._maxcv_filter = [] + self._x_filter = [] + + # Set the initial history. + self._store_history = store_history + self._history_size = history_size + self._fun_history = [] + self._maxcv_history = [] + self._x_history = [] + + def __call__(self, x, penalty=0.0): + """ + Evaluate the objective and nonlinear constraint functions. + + Parameters + ---------- + x : array_like, shape (n,) + Point at which the functions are evaluated. + penalty : float, optional + Penalty parameter used to select the point in the filter to forward + to the callback function. + + Returns + ------- + float + Objective function value. + `numpy.ndarray`, shape (m_nonlinear_ub,) + Nonlinear inequality constraint function values. + `numpy.ndarray`, shape (m_nonlinear_eq,) + Nonlinear equality constraint function values. + + Raises + ------ + `cobyqa.utils.CallbackSuccess` + If the callback function raises a ``StopIteration``. + """ + # Evaluate the objective and nonlinear constraint functions. + x = np.asarray(x, dtype=float) + x_full = self.build_x(x) + fun_val = self._obj(x_full) + cub_val, ceq_val = self._nonlinear(x_full) + maxcv_val = self.maxcv(x, cub_val, ceq_val) + if self._store_history: + self._fun_history.append(fun_val) + self._maxcv_history.append(maxcv_val) + self._x_history.append(x) + if len(self._fun_history) > self._history_size: + self._fun_history.pop(0) + self._maxcv_history.pop(0) + self._x_history.pop(0) + + # Add the point to the filter if it is not dominated by any point. + if np.isnan(fun_val) and np.isnan(maxcv_val): + include_point = len(self._fun_filter) == 0 + elif np.isnan(fun_val): + include_point = all( + np.isnan(fun_filter) + and maxcv_val < maxcv_filter + or np.isnan(maxcv_filter) + for fun_filter, maxcv_filter in zip( + self._fun_filter, + self._maxcv_filter, + ) + ) + elif np.isnan(maxcv_val): + include_point = all( + np.isnan(maxcv_filter) + and fun_val < fun_filter + or np.isnan(fun_filter) + for fun_filter, maxcv_filter in zip( + self._fun_filter, + self._maxcv_filter, + ) + ) + else: + include_point = all( + fun_val < fun_filter or maxcv_val < maxcv_filter + for fun_filter, maxcv_filter in zip( + self._fun_filter, + self._maxcv_filter, + ) + ) + if include_point: + self._fun_filter.append(fun_val) + self._maxcv_filter.append(maxcv_val) + self._x_filter.append(x) + + # Remove the points in the filter that are dominated by the new + # point. We must iterate in reverse order to avoid problems when + # removing elements from the list. + for k in range(len(self._fun_filter) - 2, -1, -1): + if np.isnan(fun_val): + remove_point = np.isnan(self._fun_filter[k]) + elif np.isnan(maxcv_val): + remove_point = np.isnan(self._maxcv_filter[k]) + else: + remove_point = ( + np.isnan(self._fun_filter[k]) + or np.isnan(self._maxcv_filter[k]) + or fun_val <= self._fun_filter[k] + and maxcv_val <= self._maxcv_filter[k] + ) + if remove_point: + self._fun_filter.pop(k) + self._maxcv_filter.pop(k) + self._x_filter.pop(k) + + # Keep only the most recent points in the filter. + if len(self._fun_filter) > self._filter_size: + self._fun_filter.pop(0) + self._maxcv_filter.pop(0) + self._x_filter.pop(0) + + # Evaluate the callback function after updating the filter to ensure + # that the current point can be returned by the method. + if self._callback is not None: + sig = signature(self._callback) + try: + x_best, fun_best, _ = self.best_eval(penalty) + x_best = self.build_x(x_best) + if set(sig.parameters) == {"intermediate_result"}: + intermediate_result = OptimizeResult( + x=x_best, + fun=fun_best, + # maxcv=maxcv_best, + ) + self._callback(intermediate_result=intermediate_result) + else: + self._callback(x_best) + except StopIteration as exc: + raise CallbackSuccess from exc + + # Apply the extreme barriers and return. + if np.isnan(fun_val): + fun_val = BARRIER + cub_val[np.isnan(cub_val)] = BARRIER + ceq_val[np.isnan(ceq_val)] = BARRIER + fun_val = max(min(fun_val, BARRIER), -BARRIER) + cub_val = np.maximum(np.minimum(cub_val, BARRIER), -BARRIER) + ceq_val = np.maximum(np.minimum(ceq_val, BARRIER), -BARRIER) + return fun_val, cub_val, ceq_val + + @property + def n(self): + """ + Number of variables. + + Returns + ------- + int + Number of variables. + """ + return self.x0.size + + @property + def n_orig(self): + """ + Number of variables in the original problem (with fixed variables). + + Returns + ------- + int + Number of variables in the original problem (with fixed variables). + """ + return self._fixed_idx.size + + @property + def x0(self): + """ + Initial guess. + + Returns + ------- + `numpy.ndarray`, shape (n,) + Initial guess. + """ + return self._x0 + + @property + def n_eval(self): + """ + Number of function evaluations. + + Returns + ------- + int + Number of function evaluations. + """ + return self._obj.n_eval + + @property + def fun_name(self): + """ + Name of the objective function. + + Returns + ------- + str + Name of the objective function. + """ + return self._obj.name + + @property + def bounds(self): + """ + Bound constraints. + + Returns + ------- + BoundConstraints + Bound constraints. + """ + return self._bounds + + @property + def linear(self): + """ + Linear constraints. + + Returns + ------- + LinearConstraints + Linear constraints. + """ + return self._linear + + @property + def m_bounds(self): + """ + Number of bound constraints. + + Returns + ------- + int + Number of bound constraints. + """ + return self.bounds.m + + @property + def m_linear_ub(self): + """ + Number of linear inequality constraints. + + Returns + ------- + int + Number of linear inequality constraints. + """ + return self.linear.m_ub + + @property + def m_linear_eq(self): + """ + Number of linear equality constraints. + + Returns + ------- + int + Number of linear equality constraints. + """ + return self.linear.m_eq + + @property + def m_nonlinear_ub(self): + """ + Number of nonlinear inequality constraints. + + Returns + ------- + int + Number of nonlinear inequality constraints. + + Raises + ------ + ValueError + If the number of nonlinear inequality constraints is not known. + """ + return self._nonlinear.m_ub + + @property + def m_nonlinear_eq(self): + """ + Number of nonlinear equality constraints. + + Returns + ------- + int + Number of nonlinear equality constraints. + + Raises + ------ + ValueError + If the number of nonlinear equality constraints is not known. + """ + return self._nonlinear.m_eq + + @property + def fun_history(self): + """ + History of objective function evaluations. + + Returns + ------- + `numpy.ndarray`, shape (n_eval,) + History of objective function evaluations. + """ + return np.array(self._fun_history, dtype=float) + + @property + def maxcv_history(self): + """ + History of maximum constraint violations. + + Returns + ------- + `numpy.ndarray`, shape (n_eval,) + History of maximum constraint violations. + """ + return np.array(self._maxcv_history, dtype=float) + + @property + def type(self): + """ + Type of the problem. + + The problem can be either 'unconstrained', 'bound-constrained', + 'linearly constrained', or 'nonlinearly constrained'. + + Returns + ------- + str + Type of the problem. + """ + try: + if self.m_nonlinear_ub > 0 or self.m_nonlinear_eq > 0: + return "nonlinearly constrained" + elif self.m_linear_ub > 0 or self.m_linear_eq > 0: + return "linearly constrained" + elif self.m_bounds > 0: + return "bound-constrained" + else: + return "unconstrained" + except ValueError: + # The number of nonlinear constraints is not known. It may be zero + # if the user provided a nonlinear inequality and/or equality + # constraint function that returns an empty array. However, as this + # is not known before the first call to the function, we assume + # that the problem is nonlinearly constrained. + return "nonlinearly constrained" + + @property + def is_feasibility(self): + """ + Whether the problem is a feasibility problem. + + Returns + ------- + bool + Whether the problem is a feasibility problem. + """ + return self.fun_name == "" + + def build_x(self, x): + """ + Build the full vector of variables from the reduced vector. + + Parameters + ---------- + x : array_like, shape (n,) + Reduced vector of variables. + + Returns + ------- + `numpy.ndarray`, shape (n_orig,) + Full vector of variables. + """ + x_full = np.empty(self.n_orig) + x_full[self._fixed_idx] = self._fixed_val + x_full[~self._fixed_idx] = (x * self._scaling_factor + + self._scaling_shift) + return self._orig_bounds.project(x_full) + + def maxcv(self, x, cub_val=None, ceq_val=None): + """ + Evaluate the maximum constraint violation. + + Parameters + ---------- + x : array_like, shape (n,) + Point at which the maximum constraint violation is evaluated. + cub_val : array_like, shape (m_nonlinear_ub,), optional + Values of the nonlinear inequality constraints. If not provided, + the nonlinear inequality constraints are evaluated at `x`. + ceq_val : array_like, shape (m_nonlinear_eq,), optional + Values of the nonlinear equality constraints. If not provided, + the nonlinear equality constraints are evaluated at `x`. + + Returns + ------- + float + Maximum constraint violation at `x`. + """ + violation = self.violation(x, cub_val=cub_val, ceq_val=ceq_val) + if np.count_nonzero(violation): + return np.max(violation, initial=0.0) + else: + return 0.0 + + def violation(self, x, cub_val=None, ceq_val=None): + violation = [] + if not self.bounds.is_feasible: + b = self.bounds.violation(x) + violation.append(b) + + if len(self.linear.pcs): + lc = self.linear.violation(x) + violation.append(lc) + if len(self._nonlinear.pcs): + nlc = self._nonlinear.violation(x, cub_val, ceq_val) + violation.append(nlc) + + if len(violation): + return np.concatenate(violation) + + def best_eval(self, penalty): + """ + Return the best point in the filter and the corresponding objective and + nonlinear constraint function evaluations. + + Parameters + ---------- + penalty : float + Penalty parameter + + Returns + ------- + `numpy.ndarray`, shape (n,) + Best point. + float + Corresponding objective function value. + float + Corresponding maximum constraint violation. + """ + # If the filter is empty, i.e., if no function evaluation has been + # performed, we evaluate the objective and nonlinear constraint + # functions at the initial guess. + if len(self._fun_filter) == 0: + self(self.x0) + + # Find the best point in the filter. + fun_filter = np.array(self._fun_filter) + maxcv_filter = np.array(self._maxcv_filter) + x_filter = np.array(self._x_filter) + finite_idx = np.isfinite(maxcv_filter) + if np.any(finite_idx): + # At least one point has a finite maximum constraint violation. + feasible_idx = maxcv_filter <= self._feasibility_tol + if np.any(feasible_idx) and not np.all( + np.isnan(fun_filter[feasible_idx]) + ): + # At least one point is feasible and has a well-defined + # objective function value. We select the point with the least + # objective function value. If there is a tie, we select the + # point with the least maximum constraint violation. If there + # is still a tie, we select the most recent point. + fun_min_idx = feasible_idx & ( + fun_filter <= np.nanmin(fun_filter[feasible_idx]) + ) + if np.count_nonzero(fun_min_idx) > 1: + fun_min_idx &= maxcv_filter <= np.min( + maxcv_filter[fun_min_idx] + ) + i = np.flatnonzero(fun_min_idx)[-1] + elif np.any(feasible_idx): + # At least one point is feasible but no feasible point has a + # well-defined objective function value. We select the most + # recent feasible point. + i = np.flatnonzero(feasible_idx)[-1] + else: + # No point is feasible. We first compute the merit function + # value for each point. + merit_filter = np.full_like(fun_filter, np.nan) + merit_filter[finite_idx] = ( + fun_filter[finite_idx] + penalty * maxcv_filter[finite_idx] + ) + if np.all(np.isnan(merit_filter)): + # No point has a well-defined merit function value. In + # other words, among the points with a well-defined maximum + # constraint violation, none has a well-defined objective + # function value. We select the point with the least + # maximum constraint violation. If there is a tie, we + # select the most recent point. + min_maxcv_idx = maxcv_filter <= np.nanmin(maxcv_filter) + i = np.flatnonzero(min_maxcv_idx)[-1] + else: + # At least one point has a well-defined merit function + # value. We select the point with the least merit function + # value. If there is a tie, we select the point with the + # least maximum constraint violation. If there is still a + # tie, we select the point with the least objective + # function value. If there is still a tie, we select the + # most recent point. + merit_min_idx = merit_filter <= np.nanmin(merit_filter) + if np.count_nonzero(merit_min_idx) > 1: + merit_min_idx &= maxcv_filter <= np.min( + maxcv_filter[merit_min_idx] + ) + + if np.count_nonzero(merit_min_idx) > 1: + merit_min_idx &= fun_filter <= np.min( + fun_filter[merit_min_idx] + ) + i = np.flatnonzero(merit_min_idx)[-1] + elif not np.all(np.isnan(fun_filter)): + # No maximum constraint violation is well-defined but at least one + # point has a well-defined objective function value. We select the + # point with the least objective function value. If there is a tie, + # we select the most recent point. + fun_min_idx = fun_filter <= np.nanmin(fun_filter) + i = np.flatnonzero(fun_min_idx)[-1] + else: + # No point has a well-defined maximum constraint violation or + # objective function value. We select the most recent point. + i = len(fun_filter) - 1 + return ( + self.bounds.project(x_filter[i, :]), + fun_filter[i], + maxcv_filter[i], + ) diff --git a/.venv/lib/python3.12/site-packages/scipy/_external/cobyqa/settings.py b/.venv/lib/python3.12/site-packages/scipy/_external/cobyqa/settings.py new file mode 100644 index 0000000000000000000000000000000000000000..6394822826e094a803a485556a298e342bf260ac --- /dev/null +++ b/.venv/lib/python3.12/site-packages/scipy/_external/cobyqa/settings.py @@ -0,0 +1,132 @@ +import sys +from enum import Enum + +import numpy as np + + +# Exit status. +class ExitStatus(Enum): + """ + Exit statuses. + """ + + RADIUS_SUCCESS = 0 + TARGET_SUCCESS = 1 + FIXED_SUCCESS = 2 + CALLBACK_SUCCESS = 3 + FEASIBLE_SUCCESS = 4 + MAX_EVAL_WARNING = 5 + MAX_ITER_WARNING = 6 + INFEASIBLE_ERROR = -1 + LINALG_ERROR = -2 + + +class Options(str, Enum): + """ + Options. + """ + + DEBUG = "debug" + FEASIBILITY_TOL = "feasibility_tol" + FILTER_SIZE = "filter_size" + HISTORY_SIZE = "history_size" + MAX_EVAL = "maxfev" + MAX_ITER = "maxiter" + NPT = "nb_points" + RHOBEG = "radius_init" + RHOEND = "radius_final" + SCALE = "scale" + STORE_HISTORY = "store_history" + TARGET = "target" + VERBOSE = "disp" + + +class Constants(str, Enum): + """ + Constants. + """ + + DECREASE_RADIUS_FACTOR = "decrease_radius_factor" + INCREASE_RADIUS_FACTOR = "increase_radius_factor" + INCREASE_RADIUS_THRESHOLD = "increase_radius_threshold" + DECREASE_RADIUS_THRESHOLD = "decrease_radius_threshold" + DECREASE_RESOLUTION_FACTOR = "decrease_resolution_factor" + LARGE_RESOLUTION_THRESHOLD = "large_resolution_threshold" + MODERATE_RESOLUTION_THRESHOLD = "moderate_resolution_threshold" + LOW_RATIO = "low_ratio" + HIGH_RATIO = "high_ratio" + VERY_LOW_RATIO = "very_low_ratio" + PENALTY_INCREASE_THRESHOLD = "penalty_increase_threshold" + PENALTY_INCREASE_FACTOR = "penalty_increase_factor" + SHORT_STEP_THRESHOLD = "short_step_threshold" + LOW_RADIUS_FACTOR = "low_radius_factor" + BYRD_OMOJOKUN_FACTOR = "byrd_omojokun_factor" + THRESHOLD_RATIO_CONSTRAINTS = "threshold_ratio_constraints" + LARGE_SHIFT_FACTOR = "large_shift_factor" + LARGE_GRADIENT_FACTOR = "large_gradient_factor" + RESOLUTION_FACTOR = "resolution_factor" + IMPROVE_TCG = "improve_tcg" + + +# Default options. +DEFAULT_OPTIONS = { + Options.DEBUG.value: False, + Options.FEASIBILITY_TOL.value: np.sqrt(np.finfo(float).eps), + Options.FILTER_SIZE.value: sys.maxsize, + Options.HISTORY_SIZE.value: sys.maxsize, + Options.MAX_EVAL.value: lambda n: 500 * n, + Options.MAX_ITER.value: lambda n: 1000 * n, + Options.NPT.value: lambda n: 2 * n + 1, + Options.RHOBEG.value: 1.0, + Options.RHOEND.value: 1e-6, + Options.SCALE.value: False, + Options.STORE_HISTORY.value: False, + Options.TARGET.value: -np.inf, + Options.VERBOSE.value: False, +} + +# Default constants. +DEFAULT_CONSTANTS = { + Constants.DECREASE_RADIUS_FACTOR.value: 0.5, + Constants.INCREASE_RADIUS_FACTOR.value: np.sqrt(2.0), + Constants.INCREASE_RADIUS_THRESHOLD.value: 2.0, + Constants.DECREASE_RADIUS_THRESHOLD.value: 1.4, + Constants.DECREASE_RESOLUTION_FACTOR.value: 0.1, + Constants.LARGE_RESOLUTION_THRESHOLD.value: 250.0, + Constants.MODERATE_RESOLUTION_THRESHOLD.value: 16.0, + Constants.LOW_RATIO.value: 0.1, + Constants.HIGH_RATIO.value: 0.7, + Constants.VERY_LOW_RATIO.value: 0.01, + Constants.PENALTY_INCREASE_THRESHOLD.value: 1.5, + Constants.PENALTY_INCREASE_FACTOR.value: 2.0, + Constants.SHORT_STEP_THRESHOLD.value: 0.5, + Constants.LOW_RADIUS_FACTOR.value: 0.1, + Constants.BYRD_OMOJOKUN_FACTOR.value: 0.8, + Constants.THRESHOLD_RATIO_CONSTRAINTS.value: 2.0, + Constants.LARGE_SHIFT_FACTOR.value: 10.0, + Constants.LARGE_GRADIENT_FACTOR.value: 10.0, + Constants.RESOLUTION_FACTOR.value: 2.0, + Constants.IMPROVE_TCG.value: True, +} + +# Printing options. +PRINT_OPTIONS = { + "threshold": 6, + "edgeitems": 2, + "linewidth": sys.maxsize, + "formatter": { + "float_kind": lambda x: np.format_float_scientific( + x, + precision=3, + unique=False, + pad_left=2, + ) + }, +} + +# Constants. +BARRIER = 2.0 ** min( + 100, + np.finfo(float).maxexp // 2, + -np.finfo(float).minexp // 2, +) diff --git a/.venv/lib/python3.12/site-packages/scipy/_external/cobyqa/subsolvers/__init__.py b/.venv/lib/python3.12/site-packages/scipy/_external/cobyqa/subsolvers/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..01a1ad3c6f4cb5c0c9b99d1ce35fea92e7618ff5 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/scipy/_external/cobyqa/subsolvers/__init__.py @@ -0,0 +1,14 @@ +from .geometry import cauchy_geometry, spider_geometry +from .optim import ( + tangential_byrd_omojokun, + constrained_tangential_byrd_omojokun, + normal_byrd_omojokun, +) + +__all__ = [ + "cauchy_geometry", + "spider_geometry", + "tangential_byrd_omojokun", + "constrained_tangential_byrd_omojokun", + "normal_byrd_omojokun", +] diff --git a/.venv/lib/python3.12/site-packages/scipy/_external/cobyqa/subsolvers/geometry.py b/.venv/lib/python3.12/site-packages/scipy/_external/cobyqa/subsolvers/geometry.py new file mode 100644 index 0000000000000000000000000000000000000000..7b67fd7c813ee493b18720d1daf71324d72330b6 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/scipy/_external/cobyqa/subsolvers/geometry.py @@ -0,0 +1,387 @@ +import inspect + +import numpy as np + +from ..utils import get_arrays_tol + + +TINY = np.finfo(float).tiny + + +def cauchy_geometry(const, grad, curv, xl, xu, delta, debug): + r""" + Maximize approximately the absolute value of a quadratic function subject + to bound constraints in a trust region. + + This function solves approximately + + .. math:: + + \max_{s \in \mathbb{R}^n} \quad \bigg\lvert c + g^{\mathsf{T}} s + + \frac{1}{2} s^{\mathsf{T}} H s \bigg\rvert \quad \text{s.t.} \quad + \left\{ \begin{array}{l} + l \le s \le u,\\ + \lVert s \rVert \le \Delta, + \end{array} \right. + + by maximizing the objective function along the constrained Cauchy + direction. + + Parameters + ---------- + const : float + Constant :math:`c` as shown above. + grad : `numpy.ndarray`, shape (n,) + Gradient :math:`g` as shown above. + curv : callable + Curvature of :math:`H` along any vector. + + ``curv(s) -> float`` + + returns :math:`s^{\mathsf{T}} H s`. + xl : `numpy.ndarray`, shape (n,) + Lower bounds :math:`l` as shown above. + xu : `numpy.ndarray`, shape (n,) + Upper bounds :math:`u` as shown above. + delta : float + Trust-region radius :math:`\Delta` as shown above. + debug : bool + Whether to make debugging tests during the execution. + + Returns + ------- + `numpy.ndarray`, shape (n,) + Approximate solution :math:`s`. + + Notes + ----- + This function is described as the first alternative in Section 6.5 of [1]_. + It is assumed that the origin is feasible with respect to the bound + constraints and that `delta` is finite and positive. + + References + ---------- + .. [1] T. M. Ragonneau. *Model-Based Derivative-Free Optimization Methods + and Software*. PhD thesis, Department of Applied Mathematics, The Hong + Kong Polytechnic University, Hong Kong, China, 2022. URL: + https://theses.lib.polyu.edu.hk/handle/200/12294. + """ + if debug: + assert isinstance(const, float) + assert isinstance(grad, np.ndarray) and grad.ndim == 1 + assert inspect.signature(curv).bind(grad) + assert isinstance(xl, np.ndarray) and xl.shape == grad.shape + assert isinstance(xu, np.ndarray) and xu.shape == grad.shape + assert isinstance(delta, float) + assert isinstance(debug, bool) + tol = get_arrays_tol(xl, xu) + assert np.all(xl <= tol) + assert np.all(xu >= -tol) + assert np.isfinite(delta) and delta > 0.0 + xl = np.minimum(xl, 0.0) + xu = np.maximum(xu, 0.0) + + # To maximize the absolute value of a quadratic function, we maximize the + # function itself or its negative, and we choose the solution that provides + # the largest function value. + step1, q_val1 = _cauchy_geom(const, grad, curv, xl, xu, delta, debug) + step2, q_val2 = _cauchy_geom( + -const, + -grad, + lambda x: -curv(x), + xl, + xu, + delta, + debug, + ) + step = step1 if abs(q_val1) >= abs(q_val2) else step2 + + if debug: + assert np.all(xl <= step) + assert np.all(step <= xu) + assert np.linalg.norm(step) < 1.1 * delta + return step + + +def spider_geometry(const, grad, curv, xpt, xl, xu, delta, debug): + r""" + Maximize approximately the absolute value of a quadratic function subject + to bound constraints in a trust region. + + This function solves approximately + + .. math:: + + \max_{s \in \mathbb{R}^n} \quad \bigg\lvert c + g^{\mathsf{T}} s + + \frac{1}{2} s^{\mathsf{T}} H s \bigg\rvert \quad \text{s.t.} \quad + \left\{ \begin{array}{l} + l \le s \le u,\\ + \lVert s \rVert \le \Delta, + \end{array} \right. + + by maximizing the objective function along given straight lines. + + Parameters + ---------- + const : float + Constant :math:`c` as shown above. + grad : `numpy.ndarray`, shape (n,) + Gradient :math:`g` as shown above. + curv : callable + Curvature of :math:`H` along any vector. + + ``curv(s) -> float`` + + returns :math:`s^{\mathsf{T}} H s`. + xpt : `numpy.ndarray`, shape (n, npt) + Points defining the straight lines. The straight lines considered are + the ones passing through the origin and the points in `xpt`. + xl : `numpy.ndarray`, shape (n,) + Lower bounds :math:`l` as shown above. + xu : `numpy.ndarray`, shape (n,) + Upper bounds :math:`u` as shown above. + delta : float + Trust-region radius :math:`\Delta` as shown above. + debug : bool + Whether to make debugging tests during the execution. + + Returns + ------- + `numpy.ndarray`, shape (n,) + Approximate solution :math:`s`. + + Notes + ----- + This function is described as the second alternative in Section 6.5 of + [1]_. It is assumed that the origin is feasible with respect to the bound + constraints and that `delta` is finite and positive. + + References + ---------- + .. [1] T. M. Ragonneau. *Model-Based Derivative-Free Optimization Methods + and Software*. PhD thesis, Department of Applied Mathematics, The Hong + Kong Polytechnic University, Hong Kong, China, 2022. URL: + https://theses.lib.polyu.edu.hk/handle/200/12294. + """ + if debug: + assert isinstance(const, float) + assert isinstance(grad, np.ndarray) and grad.ndim == 1 + assert inspect.signature(curv).bind(grad) + assert ( + isinstance(xpt, np.ndarray) + and xpt.ndim == 2 + and xpt.shape[0] == grad.size + ) + assert isinstance(xl, np.ndarray) and xl.shape == grad.shape + assert isinstance(xu, np.ndarray) and xu.shape == grad.shape + assert isinstance(delta, float) + assert isinstance(debug, bool) + tol = get_arrays_tol(xl, xu) + assert np.all(xl <= tol) + assert np.all(xu >= -tol) + assert np.isfinite(delta) and delta > 0.0 + xl = np.minimum(xl, 0.0) + xu = np.maximum(xu, 0.0) + + # Iterate through the straight lines. + step = np.zeros_like(grad) + q_val = const + s_norm = np.linalg.norm(xpt, axis=0) + + # Set alpha_xl to the step size for the lower-bound constraint and + # alpha_xu to the step size for the upper-bound constraint. + + # xl.shape = (N,) + # xpt.shape = (N, M) + # i_xl_pos.shape = (M, N) + i_xl_pos = (xl > -np.inf) & (xpt.T > -TINY * xl) + i_xl_neg = (xl > -np.inf) & (xpt.T < TINY * xl) + i_xu_pos = (xu < np.inf) & (xpt.T > TINY * xu) + i_xu_neg = (xu < np.inf) & (xpt.T < -TINY * xu) + + # (M, N) + alpha_xl_pos = np.atleast_2d( + np.broadcast_to(xl, i_xl_pos.shape)[i_xl_pos] / xpt.T[i_xl_pos] + ) + # (M,) + alpha_xl_pos = np.max(alpha_xl_pos, axis=1, initial=-np.inf) + # make sure it's (M,) + alpha_xl_pos = np.broadcast_to(np.atleast_1d(alpha_xl_pos), xpt.shape[1]) + + alpha_xl_neg = np.atleast_2d( + np.broadcast_to(xl, i_xl_neg.shape)[i_xl_neg] / xpt.T[i_xl_neg] + ) + alpha_xl_neg = np.max(alpha_xl_neg, axis=1, initial=np.inf) + alpha_xl_neg = np.broadcast_to(np.atleast_1d(alpha_xl_neg), xpt.shape[1]) + + alpha_xu_neg = np.atleast_2d( + np.broadcast_to(xu, i_xu_neg.shape)[i_xu_neg] / xpt.T[i_xu_neg] + ) + alpha_xu_neg = np.max(alpha_xu_neg, axis=1, initial=-np.inf) + alpha_xu_neg = np.broadcast_to(np.atleast_1d(alpha_xu_neg), xpt.shape[1]) + + alpha_xu_pos = np.atleast_2d( + np.broadcast_to(xu, i_xu_pos.shape)[i_xu_pos] / xpt.T[i_xu_pos] + ) + alpha_xu_pos = np.max(alpha_xu_pos, axis=1, initial=np.inf) + alpha_xu_pos = np.broadcast_to(np.atleast_1d(alpha_xu_pos), xpt.shape[1]) + + for k in range(xpt.shape[1]): + # Set alpha_tr to the step size for the trust-region constraint. + if s_norm[k] > TINY * delta: + alpha_tr = max(delta / s_norm[k], 0.0) + else: + # The current straight line is basically zero. + continue + + alpha_bd_pos = max(min(alpha_xu_pos[k], alpha_xl_neg[k]), 0.0) + alpha_bd_neg = min(max(alpha_xl_pos[k], alpha_xu_neg[k]), 0.0) + + # Set alpha_quad_pos and alpha_quad_neg to the step size to the extrema + # of the quadratic function along the positive and negative directions. + grad_step = grad @ xpt[:, k] + curv_step = curv(xpt[:, k]) + if ( + grad_step >= 0.0 + and curv_step < -TINY * grad_step + or grad_step <= 0.0 + and curv_step > -TINY * grad_step + ): + alpha_quad_pos = max(-grad_step / curv_step, 0.0) + else: + alpha_quad_pos = np.inf + if ( + grad_step >= 0.0 + and curv_step > TINY * grad_step + or grad_step <= 0.0 + and curv_step < TINY * grad_step + ): + alpha_quad_neg = min(-grad_step / curv_step, 0.0) + else: + alpha_quad_neg = -np.inf + + # Select the step that provides the largest value of the objective + # function if it improves the current best. The best positive step is + # either the one that reaches the constraints or the one that reaches + # the extremum of the objective function along the current direction + # (only possible if the resulting step is feasible). We test both, and + # we perform similar calculations along the negative step. + # N.B.: we select the largest possible step among all the ones that + # maximize the objective function. This is to avoid returning the zero + # step in some extreme cases. + alpha_pos = min(alpha_tr, alpha_bd_pos) + alpha_neg = max(-alpha_tr, alpha_bd_neg) + q_val_pos = ( + const + alpha_pos * grad_step + 0.5 * alpha_pos**2.0 * curv_step + ) + q_val_neg = ( + const + alpha_neg * grad_step + 0.5 * alpha_neg**2.0 * curv_step + ) + if alpha_quad_pos < alpha_pos: + q_val_quad_pos = ( + const + + alpha_quad_pos * grad_step + + 0.5 * alpha_quad_pos**2.0 * curv_step + ) + if abs(q_val_quad_pos) > abs(q_val_pos): + alpha_pos = alpha_quad_pos + q_val_pos = q_val_quad_pos + if alpha_quad_neg > alpha_neg: + q_val_quad_neg = ( + const + + alpha_quad_neg * grad_step + + 0.5 * alpha_quad_neg**2.0 * curv_step + ) + if abs(q_val_quad_neg) > abs(q_val_neg): + alpha_neg = alpha_quad_neg + q_val_neg = q_val_quad_neg + if abs(q_val_pos) >= abs(q_val_neg) and abs(q_val_pos) > abs(q_val): + step = np.clip(alpha_pos * xpt[:, k], xl, xu) + q_val = q_val_pos + elif abs(q_val_neg) > abs(q_val_pos) and abs(q_val_neg) > abs(q_val): + step = np.clip(alpha_neg * xpt[:, k], xl, xu) + q_val = q_val_neg + + if debug: + assert np.all(xl <= step) + assert np.all(step <= xu) + assert np.linalg.norm(step) < 1.1 * delta + return step + + +def _cauchy_geom(const, grad, curv, xl, xu, delta, debug): + """ + Same as `bound_constrained_cauchy_step` without the absolute value. + """ + # Calculate the initial active set. + fixed_xl = (xl < 0.0) & (grad > 0.0) + fixed_xu = (xu > 0.0) & (grad < 0.0) + + # Calculate the Cauchy step. + cauchy_step = np.zeros_like(grad) + cauchy_step[fixed_xl] = xl[fixed_xl] + cauchy_step[fixed_xu] = xu[fixed_xu] + if np.linalg.norm(cauchy_step) > delta: + working = fixed_xl | fixed_xu + while True: + # Calculate the Cauchy step for the directions in the working set. + g_norm = np.linalg.norm(grad[working]) + delta_reduced = np.sqrt( + delta**2.0 - cauchy_step[~working] @ cauchy_step[~working] + ) + if g_norm > TINY * abs(delta_reduced): + mu = max(delta_reduced / g_norm, 0.0) + else: + break + cauchy_step[working] = mu * grad[working] + + # Update the working set. + fixed_xl = working & (cauchy_step < xl) + fixed_xu = working & (cauchy_step > xu) + if not np.any(fixed_xl) and not np.any(fixed_xu): + # Stop the calculations as the Cauchy step is now feasible. + break + cauchy_step[fixed_xl] = xl[fixed_xl] + cauchy_step[fixed_xu] = xu[fixed_xu] + working = working & ~(fixed_xl | fixed_xu) + + # Calculate the step that maximizes the quadratic along the Cauchy step. + grad_step = grad @ cauchy_step + if grad_step >= 0.0: + # Set alpha_tr to the step size for the trust-region constraint. + s_norm = np.linalg.norm(cauchy_step) + if s_norm > TINY * delta: + alpha_tr = max(delta / s_norm, 0.0) + else: + # The Cauchy step is basically zero. + alpha_tr = 0.0 + + # Set alpha_quad to the step size for the maximization problem. + curv_step = curv(cauchy_step) + if curv_step < -TINY * grad_step: + alpha_quad = max(-grad_step / curv_step, 0.0) + else: + alpha_quad = np.inf + + # Set alpha_bd to the step size for the bound constraints. + i_xl = (xl > -np.inf) & (cauchy_step < TINY * xl) + i_xu = (xu < np.inf) & (cauchy_step > TINY * xu) + alpha_xl = np.min(xl[i_xl] / cauchy_step[i_xl], initial=np.inf) + alpha_xu = np.min(xu[i_xu] / cauchy_step[i_xu], initial=np.inf) + alpha_bd = min(alpha_xl, alpha_xu) + + # Calculate the solution and the corresponding function value. + alpha = min(alpha_tr, alpha_quad, alpha_bd) + step = np.clip(alpha * cauchy_step, xl, xu) + q_val = const + alpha * grad_step + 0.5 * alpha**2.0 * curv_step + else: + # This case is never reached in exact arithmetic. It prevents this + # function to return a step that decreases the objective function. + step = np.zeros_like(grad) + q_val = const + + if debug: + assert np.all(xl <= step) + assert np.all(step <= xu) + assert np.linalg.norm(step) < 1.1 * delta + return step, q_val diff --git a/.venv/lib/python3.12/site-packages/scipy/_external/cobyqa/subsolvers/optim.py b/.venv/lib/python3.12/site-packages/scipy/_external/cobyqa/subsolvers/optim.py new file mode 100644 index 0000000000000000000000000000000000000000..c4a960396fb2e992cf76bac0baf171b5af9b7717 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/scipy/_external/cobyqa/subsolvers/optim.py @@ -0,0 +1,1203 @@ +import inspect + +import numpy as np +from scipy.linalg import qr + +from ..utils import get_arrays_tol + + +TINY = np.finfo(float).tiny +EPS = np.finfo(float).eps + + +def tangential_byrd_omojokun(grad, hess_prod, xl, xu, delta, debug, **kwargs): + r""" + Minimize approximately a quadratic function subject to bound constraints in + a trust region. + + This function solves approximately + + .. math:: + + \min_{s \in \mathbb{R}^n} \quad g^{\mathsf{T}} s + \frac{1}{2} + s^{\mathsf{T}} H s \quad \text{s.t.} \quad + \left\{ \begin{array}{l} + l \le s \le u\\ + \lVert s \rVert \le \Delta, + \end{array} \right. + + using an active-set variation of the truncated conjugate gradient method. + + Parameters + ---------- + grad : `numpy.ndarray`, shape (n,) + Gradient :math:`g` as shown above. + hess_prod : callable + Product of the Hessian matrix :math:`H` with any vector. + + ``hess_prod(s) -> `numpy.ndarray`, shape (n,)`` + + returns the product :math:`H s`. + xl : `numpy.ndarray`, shape (n,) + Lower bounds :math:`l` as shown above. + xu : `numpy.ndarray`, shape (n,) + Upper bounds :math:`u` as shown above. + delta : float + Trust-region radius :math:`\Delta` as shown above. + debug : bool + Whether to make debugging tests during the execution. + + Returns + ------- + `numpy.ndarray`, shape (n,) + Approximate solution :math:`s`. + + Other Parameters + ---------------- + improve_tcg : bool, optional + If True, a solution generated by the truncated conjugate gradient + method that is on the boundary of the trust region is improved by + moving around the trust-region boundary on the two-dimensional space + spanned by the solution and the gradient of the quadratic function at + the solution (default is True). + + Notes + ----- + This function implements Algorithm 6.2 of [1]_. It is assumed that the + origin is feasible with respect to the bound constraints and that `delta` + is finite and positive. + + References + ---------- + .. [1] T. M. Ragonneau. *Model-Based Derivative-Free Optimization Methods + and Software*. PhD thesis, Department of Applied Mathematics, The Hong + Kong Polytechnic University, Hong Kong, China, 2022. URL: + https://theses.lib.polyu.edu.hk/handle/200/12294. + """ + if debug: + assert isinstance(grad, np.ndarray) and grad.ndim == 1 + assert inspect.signature(hess_prod).bind(grad) + assert isinstance(xl, np.ndarray) and xl.shape == grad.shape + assert isinstance(xu, np.ndarray) and xu.shape == grad.shape + assert isinstance(delta, float) + assert isinstance(debug, bool) + tol = get_arrays_tol(xl, xu) + assert np.all(xl <= tol) + assert np.all(xu >= -tol) + assert np.isfinite(delta) and delta > 0.0 + xl = np.minimum(xl, 0.0) + xu = np.maximum(xu, 0.0) + + # Copy the arrays that may be modified by the code below. + n = grad.size + grad = np.copy(grad) + grad_orig = np.copy(grad) + + # Calculate the initial active set. + free_bd = ((xl < 0.0) | (grad < 0.0)) & ((xu > 0.0) | (grad > 0.0)) + + # Set the initial iterate and the initial search direction. + step = np.zeros_like(grad) + sd = np.zeros_like(step) + sd[free_bd] = -grad[free_bd] + + k = 0 + reduct = 0.0 + boundary_reached = False + while k < np.count_nonzero(free_bd): + # Stop the computations if sd is not a descent direction. + grad_sd = grad @ sd + if grad_sd >= -10.0 * EPS * n * max(1.0, np.linalg.norm(grad)): + break + + # Set alpha_tr to the step size for the trust-region constraint. + try: + alpha_tr = _alpha_tr(step, sd, delta) + except ZeroDivisionError: + break + + # Stop the computations if a step along sd is expected to give a + # relatively small reduction in the objective function. + if -alpha_tr * grad_sd <= 1e-8 * reduct: + break + + # Set alpha_quad to the step size for the minimization problem. + hess_sd = hess_prod(sd) + curv_sd = sd @ hess_sd + if curv_sd > TINY * abs(grad_sd): + alpha_quad = max(-grad_sd / curv_sd, 0.0) + else: + alpha_quad = np.inf + + # Stop the computations if the reduction in the objective function + # provided by an unconstrained step is small. + alpha = min(alpha_tr, alpha_quad) + if -alpha * (grad_sd + 0.5 * alpha * curv_sd) <= 1e-8 * reduct: + break + + # Set alpha_bd to the step size for the bound constraints. + i_xl = (xl > -np.inf) & (sd < -TINY * np.abs(xl - step)) + i_xu = (xu < np.inf) & (sd > TINY * np.abs(xu - step)) + all_alpha_xl = np.full_like(step, np.inf) + all_alpha_xu = np.full_like(step, np.inf) + all_alpha_xl[i_xl] = np.maximum( + (xl[i_xl] - step[i_xl]) / sd[i_xl], + 0.0, + ) + all_alpha_xu[i_xu] = np.maximum( + (xu[i_xu] - step[i_xu]) / sd[i_xu], + 0.0, + ) + alpha_xl = np.min(all_alpha_xl) + alpha_xu = np.min(all_alpha_xu) + alpha_bd = min(alpha_xl, alpha_xu) + + # Update the iterate. + alpha = min(alpha, alpha_bd) + if alpha > 0.0: + step[free_bd] = np.clip( + step[free_bd] + alpha * sd[free_bd], + xl[free_bd], + xu[free_bd], + ) + grad += alpha * hess_sd + reduct -= alpha * (grad_sd + 0.5 * alpha * curv_sd) + + if alpha < min(alpha_tr, alpha_bd): + # The current iteration is a conjugate gradient iteration. Update + # the search direction so that it is conjugate (with respect to H) + # to all the previous search directions. + beta = (grad[free_bd] @ hess_sd[free_bd]) / curv_sd + sd[free_bd] = beta * sd[free_bd] - grad[free_bd] + sd[~free_bd] = 0.0 + k += 1 + elif alpha < alpha_tr: + # The iterate is restricted by a bound constraint. Add this bound + # constraint to the active set, and restart the calculations. + if alpha_xl <= alpha: + i_new = np.argmin(all_alpha_xl) + step[i_new] = xl[i_new] + else: + i_new = np.argmin(all_alpha_xu) + step[i_new] = xu[i_new] + free_bd[i_new] = False + sd[free_bd] = -grad[free_bd] + sd[~free_bd] = 0.0 + k = 0 + else: + # The current iterate is on the trust-region boundary. Add all the + # active bounds to the working set to prepare for the improvement + # of the solution, and stop the iterations. + if alpha_xl <= alpha: + i_new = _argmin(all_alpha_xl) + step[i_new] = xl[i_new] + free_bd[i_new] = False + if alpha_xu <= alpha: + i_new = _argmin(all_alpha_xu) + step[i_new] = xu[i_new] + free_bd[i_new] = False + boundary_reached = True + break + + # Attempt to improve the solution on the trust-region boundary. + if kwargs.get("improve_tcg", True) and boundary_reached: + step_base = np.copy(step) + step_comparator = grad_orig @ step_base + 0.5 * step_base @ hess_prod( + step_base + ) + + while np.count_nonzero(free_bd) > 0: + # Check whether a substantial reduction in the objective function + # is possible, and set the search direction. + step_sq = step[free_bd] @ step[free_bd] + grad_sq = grad[free_bd] @ grad[free_bd] + grad_step = grad[free_bd] @ step[free_bd] + grad_sd = -np.sqrt(max(step_sq * grad_sq - grad_step**2.0, 0.0)) + sd[free_bd] = grad_step * step[free_bd] - step_sq * grad[free_bd] + sd[~free_bd] = 0.0 + if grad_sd >= -1e-8 * reduct or np.any( + grad_sd >= -TINY * np.abs(sd[free_bd]) + ): + break + sd[free_bd] /= -grad_sd + + # Calculate an upper bound for the tangent of half the angle theta + # of this alternative iteration. The step will be updated as: + # step = cos(theta) * step + sin(theta) * sd. + temp_xl = np.zeros(n) + temp_xu = np.zeros(n) + temp_xl[free_bd] = ( + step[free_bd] ** 2.0 + sd[free_bd] ** 2.0 - xl[free_bd] ** 2.0 + ) + temp_xu[free_bd] = ( + step[free_bd] ** 2.0 + sd[free_bd] ** 2.0 - xu[free_bd] ** 2.0 + ) + temp_xl[temp_xl > 0.0] = ( + np.sqrt(temp_xl[temp_xl > 0.0]) - sd[temp_xl > 0.0] + ) + temp_xu[temp_xu > 0.0] = ( + np.sqrt(temp_xu[temp_xu > 0.0]) + sd[temp_xu > 0.0] + ) + dist_xl = np.maximum(step - xl, 0.0) + dist_xu = np.maximum(xu - step, 0.0) + i_xl = temp_xl > TINY * dist_xl + i_xu = temp_xu > TINY * dist_xu + all_t_xl = np.ones(n) + all_t_xu = np.ones(n) + all_t_xl[i_xl] = np.minimum( + all_t_xl[i_xl], + dist_xl[i_xl] / temp_xl[i_xl], + ) + all_t_xu[i_xu] = np.minimum( + all_t_xu[i_xu], + dist_xu[i_xu] / temp_xu[i_xu], + ) + t_xl = np.min(all_t_xl) + t_xu = np.min(all_t_xu) + t_bd = min(t_xl, t_xu) + + # Calculate some curvature information. + hess_step = hess_prod(step) + hess_sd = hess_prod(sd) + curv_step = step @ hess_step + curv_sd = sd @ hess_sd + curv_step_sd = step @ hess_sd + + # For a range of equally spaced values of tan(0.5 * theta), + # calculate the reduction in the objective function that would be + # obtained by accepting the corresponding angle. + n_samples = 20 + n_samples = int((n_samples - 3) * t_bd + 3) + t_samples = np.linspace(t_bd / n_samples, t_bd, n_samples) + sin_values = 2.0 * t_samples / (1.0 + t_samples**2.0) + all_reduct = sin_values * ( + grad_step * t_samples + - grad_sd + - t_samples * curv_step + + sin_values + * (t_samples * curv_step_sd - 0.5 * (curv_sd - curv_step)) + ) + if np.all(all_reduct <= 0.0): + # No reduction in the objective function is obtained. + break + + # Accept the angle that provides the largest reduction in the + # objective function, and update the iterate. + i_max = np.argmax(all_reduct) + cos_value = (1.0 - t_samples[i_max] ** 2.0) / ( + 1.0 + t_samples[i_max] ** 2.0 + ) + step[free_bd] = ( + cos_value * step[free_bd] + sin_values[i_max] * sd[free_bd] + ) + grad += (cos_value - 1.0) * hess_step + sin_values[i_max] * hess_sd + reduct += all_reduct[i_max] + + # If the above angle is restricted by bound constraints, add them + # to the working set, and restart the alternative iteration. + # Otherwise, the calculations are terminated. + if t_bd < 1.0 and i_max == n_samples - 1: + if t_xl <= t_bd: + i_new = _argmin(all_t_xl) + step[i_new] = xl[i_new] + free_bd[i_new] = False + if t_xu <= t_bd: + i_new = _argmin(all_t_xu) + step[i_new] = xu[i_new] + free_bd[i_new] = False + else: + break + + # Ensure that the alternative iteration improves the objective + # function. + if grad_orig @ step + 0.5 * step @ hess_prod(step) > step_comparator: + step = step_base + + if debug: + assert np.all(xl <= step) + assert np.all(step <= xu) + assert np.linalg.norm(step) < 1.1 * delta + return step + + +def constrained_tangential_byrd_omojokun( + grad, + hess_prod, + xl, + xu, + aub, + bub, + aeq, + delta, + debug, + **kwargs, +): + r""" + Minimize approximately a quadratic function subject to bound and linear + constraints in a trust region. + + This function solves approximately + + .. math:: + + \min_{s \in \mathbb{R}^n} \quad g^{\mathsf{T}} s + \frac{1}{2} + s^{\mathsf{T}} H s \quad \text{s.t.} \quad + \left\{ \begin{array}{l} + l \le s \le u,\\ + A_{\scriptscriptstyle I} s \le b_{\scriptscriptstyle I},\\ + A_{\scriptscriptstyle E} s = 0,\\ + \lVert s \rVert \le \Delta, + \end{array} \right. + + using an active-set variation of the truncated conjugate gradient method. + + Parameters + ---------- + grad : `numpy.ndarray`, shape (n,) + Gradient :math:`g` as shown above. + hess_prod : callable + Product of the Hessian matrix :math:`H` with any vector. + + ``hess_prod(s) -> `numpy.ndarray`, shape (n,)`` + + returns the product :math:`H s`. + xl : `numpy.ndarray`, shape (n,) + Lower bounds :math:`l` as shown above. + xu : `numpy.ndarray`, shape (n,) + Upper bounds :math:`u` as shown above. + aub : `numpy.ndarray`, shape (m_linear_ub, n) + Coefficient matrix :math:`A_{\scriptscriptstyle I}` as shown above. + bub : `numpy.ndarray`, shape (m_linear_ub,) + Right-hand side :math:`b_{\scriptscriptstyle I}` as shown above. + aeq : `numpy.ndarray`, shape (m_linear_eq, n) + Coefficient matrix :math:`A_{\scriptscriptstyle E}` as shown above. + delta : float + Trust-region radius :math:`\Delta` as shown above. + debug : bool + Whether to make debugging tests during the execution. + + Returns + ------- + `numpy.ndarray`, shape (n,) + Approximate solution :math:`s`. + + Other Parameters + ---------------- + improve_tcg : bool, optional + If True, a solution generated by the truncated conjugate gradient + method that is on the boundary of the trust region is improved by + moving around the trust-region boundary on the two-dimensional space + spanned by the solution and the gradient of the quadratic function at + the solution (default is True). + + Notes + ----- + This function implements Algorithm 6.3 of [1]_. It is assumed that the + origin is feasible with respect to the bound and linear constraints, and + that `delta` is finite and positive. + + References + ---------- + .. [1] T. M. Ragonneau. *Model-Based Derivative-Free Optimization Methods + and Software*. PhD thesis, Department of Applied Mathematics, The Hong + Kong Polytechnic University, Hong Kong, China, 2022. URL: + https://theses.lib.polyu.edu.hk/handle/200/12294. + """ + if debug: + assert isinstance(grad, np.ndarray) and grad.ndim == 1 + assert inspect.signature(hess_prod).bind(grad) + assert isinstance(xl, np.ndarray) and xl.shape == grad.shape + assert isinstance(xu, np.ndarray) and xu.shape == grad.shape + assert ( + isinstance(aub, np.ndarray) + and aub.ndim == 2 + and aub.shape[1] == grad.size + ) + assert ( + isinstance(bub, np.ndarray) + and bub.ndim == 1 + and bub.size == aub.shape[0] + ) + assert ( + isinstance(aeq, np.ndarray) + and aeq.ndim == 2 + and aeq.shape[1] == grad.size + ) + assert isinstance(delta, float) + assert isinstance(debug, bool) + tol = get_arrays_tol(xl, xu) + assert np.all(xl <= tol) + assert np.all(xu >= -tol) + assert np.all(bub >= -tol) + assert np.isfinite(delta) and delta > 0.0 + xl = np.minimum(xl, 0.0) + xu = np.maximum(xu, 0.0) + bub = np.maximum(bub, 0.0) + + # Copy the arrays that may be modified by the code below. + n = grad.size + grad = np.copy(grad) + grad_orig = np.copy(grad) + + # Calculate the initial active set. + free_xl = (xl < 0.0) | (grad < 0.0) + free_xu = (xu > 0.0) | (grad > 0.0) + free_ub = (bub > 0.0) | (aub @ grad > 0.0) + n_act, q = qr_tangential_byrd_omojokun(aub, aeq, free_xl, free_xu, free_ub) + + # Set the initial iterate and the initial search direction. + step = np.zeros_like(grad) + sd = -q[:, n_act:] @ (q[:, n_act:].T @ grad) + resid = np.copy(bub) + + k = 0 + reduct = 0.0 + boundary_reached = False + while k < n - n_act: + # Stop the computations if sd is not a descent direction. + grad_sd = grad @ sd + if grad_sd >= -10.0 * EPS * n * max(1.0, np.linalg.norm(grad)): + break + + # Set alpha_tr to the step size for the trust-region constraint. + try: + alpha_tr = _alpha_tr(step, sd, delta) + except ZeroDivisionError: + break + + # Stop the computations if a step along sd is expected to give a + # relatively small reduction in the objective function. + if -alpha_tr * grad_sd <= 1e-8 * reduct: + break + + # Set alpha_quad to the step size for the minimization problem. + hess_sd = hess_prod(sd) + curv_sd = sd @ hess_sd + if curv_sd > TINY * abs(grad_sd): + alpha_quad = max(-grad_sd / curv_sd, 0.0) + else: + alpha_quad = np.inf + + # Stop the computations if the reduction in the objective function + # provided by an unconstrained step is small. + alpha = min(alpha_tr, alpha_quad) + if -alpha * (grad_sd + 0.5 * alpha * curv_sd) <= 1e-8 * reduct: + break + + # Set alpha_bd to the step size for the bound constraints. + i_xl = free_xl & (xl > -np.inf) & (sd < -TINY * np.abs(xl - step)) + i_xu = free_xu & (xu < np.inf) & (sd > TINY * np.abs(xu - step)) + all_alpha_xl = np.full_like(step, np.inf) + all_alpha_xu = np.full_like(step, np.inf) + all_alpha_xl[i_xl] = np.maximum( + (xl[i_xl] - step[i_xl]) / sd[i_xl], + 0.0, + ) + all_alpha_xu[i_xu] = np.maximum( + (xu[i_xu] - step[i_xu]) / sd[i_xu], + 0.0, + ) + alpha_xl = np.min(all_alpha_xl) + alpha_xu = np.min(all_alpha_xu) + alpha_bd = min(alpha_xl, alpha_xu) + + # Set alpha_ub to the step size for the linear constraints. + aub_sd = aub @ sd + i_ub = free_ub & (aub_sd > TINY * np.abs(resid)) + all_alpha_ub = np.full_like(bub, np.inf) + all_alpha_ub[i_ub] = resid[i_ub] / aub_sd[i_ub] + alpha_ub = np.min(all_alpha_ub, initial=np.inf) + + # Update the iterate. + alpha = min(alpha, alpha_bd, alpha_ub) + if alpha > 0.0: + step = np.clip(step + alpha * sd, xl, xu) + grad += alpha * hess_sd + resid = np.maximum(0.0, resid - alpha * aub_sd) + reduct -= alpha * (grad_sd + 0.5 * alpha * curv_sd) + + if alpha < min(alpha_tr, alpha_bd, alpha_ub): + # The current iteration is a conjugate gradient iteration. Update + # the search direction so that it is conjugate (with respect to H) + # to all the previous search directions. + grad_proj = q[:, n_act:] @ (q[:, n_act:].T @ grad) + beta = (grad_proj @ hess_sd) / curv_sd + sd = beta * sd - grad_proj + k += 1 + elif alpha < alpha_tr: + # The iterate is restricted by a bound/linear constraint. Add this + # constraint to the active set, and restart the calculations. + if alpha_xl <= alpha: + i_new = np.argmin(all_alpha_xl) + step[i_new] = xl[i_new] + free_xl[i_new] = False + elif alpha_xu <= alpha: + i_new = np.argmin(all_alpha_xu) + step[i_new] = xu[i_new] + free_xu[i_new] = False + else: + i_new = np.argmin(all_alpha_ub) + free_ub[i_new] = False + n_act, q = qr_tangential_byrd_omojokun( + aub, + aeq, + free_xl, + free_xu, + free_ub, + ) + sd = -q[:, n_act:] @ (q[:, n_act:].T @ grad) + k = 0 + else: + # The current iterate is on the trust-region boundary. Add all the + # active bound/linear constraints to the working set to prepare for + # the improvement of the solution, and stop the iterations. + if alpha_xl <= alpha: + i_new = _argmin(all_alpha_xl) + step[i_new] = xl[i_new] + free_xl[i_new] = False + if alpha_xu <= alpha: + i_new = _argmin(all_alpha_xu) + step[i_new] = xu[i_new] + free_xu[i_new] = False + if alpha_ub <= alpha: + i_new = _argmin(all_alpha_ub) + free_ub[i_new] = False + n_act, q = qr_tangential_byrd_omojokun( + aub, + aeq, + free_xl, + free_xu, + free_ub, + ) + boundary_reached = True + break + + # Attempt to improve the solution on the trust-region boundary. + if kwargs.get("improve_tcg", True) and boundary_reached and n_act < n: + step_base = np.copy(step) + while n_act < n: + # Check whether a substantial reduction in the objective function + # is possible, and set the search direction. + step_proj = q[:, n_act:] @ (q[:, n_act:].T @ step) + grad_proj = q[:, n_act:] @ (q[:, n_act:].T @ grad) + step_sq = step_proj @ step_proj + grad_sq = grad_proj @ grad_proj + grad_step = grad_proj @ step_proj + grad_sd = -np.sqrt(max(step_sq * grad_sq - grad_step**2.0, 0.0)) + sd = q[:, n_act:] @ ( + q[:, n_act:].T @ (grad_step * step - step_sq * grad) + ) + if grad_sd >= -1e-8 * reduct or np.any( + grad_sd >= -TINY * np.abs(sd) + ): + break + sd /= -grad_sd + + # Calculate an upper bound for the tangent of half the angle theta + # of this alternative iteration for the bound constraints. The step + # will be updated as: + # step += (cos(theta) - 1) * step_proj + sin(theta) * sd. + temp_xl = np.zeros(n) + temp_xu = np.zeros(n) + dist_xl = np.maximum(step - xl, 0.0) + dist_xu = np.maximum(xu - step, 0.0) + temp_xl[free_xl] = sd[free_xl] ** 2.0 - dist_xl[free_xl] * ( + dist_xl[free_xl] - 2.0 * step_proj[free_xl] + ) + temp_xu[free_xu] = sd[free_xu] ** 2.0 - dist_xu[free_xu] * ( + dist_xu[free_xu] + 2.0 * step_proj[free_xu] + ) + temp_xl[temp_xl > 0.0] = ( + np.sqrt(temp_xl[temp_xl > 0.0]) - sd[temp_xl > 0.0] + ) + temp_xu[temp_xu > 0.0] = ( + np.sqrt(temp_xu[temp_xu > 0.0]) + sd[temp_xu > 0.0] + ) + i_xl = temp_xl > TINY * dist_xl + i_xu = temp_xu > TINY * dist_xu + all_t_xl = np.ones(n) + all_t_xu = np.ones(n) + all_t_xl[i_xl] = np.minimum( + all_t_xl[i_xl], + dist_xl[i_xl] / temp_xl[i_xl], + ) + all_t_xu[i_xu] = np.minimum( + all_t_xu[i_xu], + dist_xu[i_xu] / temp_xu[i_xu], + ) + t_xl = np.min(all_t_xl) + t_xu = np.min(all_t_xu) + t_bd = min(t_xl, t_xu) + + # Calculate an upper bound for the tangent of half the angle theta + # of this alternative iteration for the linear constraints. + temp_ub = np.zeros_like(resid) + aub_step = aub @ step_proj + aub_sd = aub @ sd + temp_ub[free_ub] = aub_sd[free_ub] ** 2.0 - resid[free_ub] * ( + resid[free_ub] + 2.0 * aub_step[free_ub] + ) + temp_ub[temp_ub > 0.0] = ( + np.sqrt(temp_ub[temp_ub > 0.0]) + aub_sd[temp_ub > 0.0] + ) + i_ub = temp_ub > TINY * resid + all_t_ub = np.ones_like(resid) + all_t_ub[i_ub] = np.minimum( + all_t_ub[i_ub], + resid[i_ub] / temp_ub[i_ub], + ) + t_ub = np.min(all_t_ub, initial=1.0) + t_min = min(t_bd, t_ub) + + # Calculate some curvature information. + hess_step = hess_prod(step_proj) + hess_sd = hess_prod(sd) + curv_step = step_proj @ hess_step + curv_sd = sd @ hess_sd + curv_step_sd = step_proj @ hess_sd + + # For a range of equally spaced values of tan(0.5 * theta), + # calculate the reduction in the objective function that would be + # obtained by accepting the corresponding angle. + n_samples = 20 + n_samples = int((n_samples - 3) * t_min + 3) + t_samples = np.linspace(t_min / n_samples, t_min, n_samples) + sin_values = 2.0 * t_samples / (1.0 + t_samples**2.0) + all_reduct = sin_values * ( + grad_step * t_samples + - grad_sd + - sin_values + * ( + 0.5 * t_samples**2.0 * curv_step + - 2.0 * t_samples * curv_step_sd + + 0.5 * curv_sd + ) + ) + if np.all(all_reduct <= 0.0): + # No reduction in the objective function is obtained. + break + + # Accept the angle that provides the largest reduction in the + # objective function, and update the iterate. + i_max = np.argmax(all_reduct) + cos_value = (1.0 - t_samples[i_max] ** 2.0) / ( + 1.0 + t_samples[i_max] ** 2.0 + ) + step = np.clip( + step + (cos_value - 1.0) * step_proj + sin_values[i_max] * sd, + xl, + xu, + ) + grad += (cos_value - 1.0) * hess_step + sin_values[i_max] * hess_sd + resid = np.maximum( + 0.0, + resid + - (cos_value - 1.0) * aub_step + - sin_values[i_max] * aub_sd, + ) + reduct += all_reduct[i_max] + + # If the above angle is restricted by bound constraints, add them + # to the working set, and restart the alternative iteration. + # Otherwise, the calculations are terminated. + if t_min < 1.0 and i_max == n_samples - 1: + if t_xl <= t_min: + i_new = _argmin(all_t_xl) + step[i_new] = xl[i_new] + free_xl[i_new] = False + if t_xu <= t_min: + i_new = _argmin(all_t_xu) + step[i_new] = xu[i_new] + free_xl[i_new] = False + if t_ub <= t_min: + i_new = _argmin(all_t_ub) + free_ub[i_new] = False + n_act, q = qr_tangential_byrd_omojokun( + aub, + aeq, + free_xl, + free_xu, + free_ub, + ) + else: + break + + # Ensure that the alternative iteration improves the objective + # function. + if grad_orig @ step + 0.5 * step @ hess_prod( + step + ) > grad_orig @ step_base + 0.5 * step_base @ hess_prod(step_base): + step = step_base + + if debug: + tol = get_arrays_tol(xl, xu) + assert np.all(xl <= step) + assert np.all(step <= xu) + assert np.all(aub @ step <= bub + tol) + assert np.all(np.abs(aeq @ step) <= tol) + assert np.linalg.norm(step) < 1.1 * delta + return step + + +def normal_byrd_omojokun(aub, bub, aeq, beq, xl, xu, delta, debug, **kwargs): + r""" + Minimize approximately a linear constraint violation subject to bound + constraints in a trust region. + + This function solves approximately + + .. math:: + + \min_{s \in \mathbb{R}^n} \quad \frac{1}{2} \big( \lVert \max \{ + A_{\scriptscriptstyle I} s - b_{\scriptscriptstyle I}, 0 \} \rVert^2 + + \lVert A_{\scriptscriptstyle E} s - b_{\scriptscriptstyle E} \rVert^2 + \big) \quad \text{s.t.} + \quad + \left\{ \begin{array}{l} + l \le s \le u,\\ + \lVert s \rVert \le \Delta, + \end{array} \right. + + using a variation of the truncated conjugate gradient method. + + Parameters + ---------- + aub : `numpy.ndarray`, shape (m_linear_ub, n) + Matrix :math:`A_{\scriptscriptstyle I}` as shown above. + bub : `numpy.ndarray`, shape (m_linear_ub,) + Vector :math:`b_{\scriptscriptstyle I}` as shown above. + aeq : `numpy.ndarray`, shape (m_linear_eq, n) + Matrix :math:`A_{\scriptscriptstyle E}` as shown above. + beq : `numpy.ndarray`, shape (m_linear_eq,) + Vector :math:`b_{\scriptscriptstyle E}` as shown above. + xl : `numpy.ndarray`, shape (n,) + Lower bounds :math:`l` as shown above. + xu : `numpy.ndarray`, shape (n,) + Upper bounds :math:`u` as shown above. + delta : float + Trust-region radius :math:`\Delta` as shown above. + debug : bool + Whether to make debugging tests during the execution. + + Returns + ------- + `numpy.ndarray`, shape (n,) + Approximate solution :math:`s`. + + Other Parameters + ---------------- + improve_tcg : bool, optional + If True, a solution generated by the truncated conjugate gradient + method that is on the boundary of the trust region is improved by + moving around the trust-region boundary on the two-dimensional space + spanned by the solution and the gradient of the quadratic function at + the solution (default is True). + + Notes + ----- + This function implements Algorithm 6.4 of [1]_. It is assumed that the + origin is feasible with respect to the bound constraints and that `delta` + is finite and positive. + + References + ---------- + .. [1] T. M. Ragonneau. *Model-Based Derivative-Free Optimization Methods + and Software*. PhD thesis, Department of Applied Mathematics, The Hong + Kong Polytechnic University, Hong Kong, China, 2022. URL: + https://theses.lib.polyu.edu.hk/handle/200/12294. + """ + if debug: + assert isinstance(aub, np.ndarray) and aub.ndim == 2 + assert ( + isinstance(bub, np.ndarray) + and bub.ndim == 1 + and bub.size == aub.shape[0] + ) + assert ( + isinstance(aeq, np.ndarray) + and aeq.ndim == 2 + and aeq.shape[1] == aub.shape[1] + ) + assert ( + isinstance(beq, np.ndarray) + and beq.ndim == 1 + and beq.size == aeq.shape[0] + ) + assert isinstance(xl, np.ndarray) and xl.shape == (aub.shape[1],) + assert isinstance(xu, np.ndarray) and xu.shape == (aub.shape[1],) + assert isinstance(delta, float) + assert isinstance(debug, bool) + tol = get_arrays_tol(xl, xu) + assert np.all(xl <= tol) + assert np.all(xu >= -tol) + assert np.isfinite(delta) and delta > 0.0 + xl = np.minimum(xl, 0.0) + xu = np.maximum(xu, 0.0) + + # Calculate the initial active set. + m_linear_ub, n = aub.shape + grad = np.r_[aeq.T @ -beq, np.maximum(0.0, -bub)] + free_xl = (xl < 0.0) | (grad[:n] < 0.0) + free_xu = (xu > 0.0) | (grad[:n] > 0.0) + free_slack = bub < 0.0 + free_ub = (bub > 0.0) | (aub @ grad[:n] - grad[n:] > 0.0) + n_act, q = qr_normal_byrd_omojokun( + aub, + free_xl, + free_xu, + free_slack, + free_ub, + ) + + # Calculate an upper bound on the norm of the slack variables. It is not + # used in the original algorithm, but it may prevent undesired behaviors + # engendered by computer rounding errors. + delta_slack = np.sqrt(beq @ beq + grad[n:] @ grad[n:]) + + # Set the initial iterate and the initial search direction. + step = np.zeros(n) + sd = -q[:, n_act:] @ (q[:, n_act:].T @ grad) + resid = bub + grad[n:] + + k = 0 + reduct = 0.0 + boundary_reached = False + while k < n + m_linear_ub - n_act: + # Stop the computations if sd is not a descent direction. + grad_sd = grad @ sd + if grad_sd >= -10.0 * EPS * n * max(1.0, np.linalg.norm(grad)): + break + + # Set alpha_tr to the step size for the trust-region constraint. + try: + alpha_tr = _alpha_tr(step, sd[:n], delta) + except ZeroDivisionError: + alpha_tr = np.inf + + # Prevent undesired behaviors engendered by computer rounding errors by + # considering the trust-region constraint on the slack variables. + try: + alpha_tr = min(alpha_tr, _alpha_tr(grad[n:], sd[n:], delta_slack)) + except ZeroDivisionError: + pass + + # Stop the computations if a step along sd is expected to give a + # relatively small reduction in the objective function. + if -alpha_tr * grad_sd <= 1e-8 * reduct: + break + + # Set alpha_quad to the step size for the minimization problem. + hess_sd = np.r_[aeq.T @ (aeq @ sd[:n]), sd[n:]] + curv_sd = sd @ hess_sd + if curv_sd > TINY * abs(grad_sd): + alpha_quad = max(-grad_sd / curv_sd, 0.0) + else: + alpha_quad = np.inf + + # Stop the computations if the reduction in the objective function + # provided by an unconstrained step is small. + alpha = min(alpha_tr, alpha_quad) + if -alpha * (grad_sd + 0.5 * alpha * curv_sd) <= 1e-8 * reduct: + break + + # Set alpha_bd to the step size for the bound constraints. + i_xl = free_xl & (xl > -np.inf) & (sd[:n] < -TINY * np.abs(xl - step)) + i_xu = free_xu & (xu < np.inf) & (sd[:n] > TINY * np.abs(xu - step)) + i_slack = free_slack & (sd[n:] < -TINY * np.abs(grad[n:])) + all_alpha_xl = np.full_like(step, np.inf) + all_alpha_xu = np.full_like(step, np.inf) + all_alpha_slack = np.full_like(bub, np.inf) + all_alpha_xl[i_xl] = np.maximum( + (xl[i_xl] - step[i_xl]) / sd[:n][i_xl], + 0.0, + ) + all_alpha_xu[i_xu] = np.maximum( + (xu[i_xu] - step[i_xu]) / sd[:n][i_xu], + 0.0, + ) + all_alpha_slack[i_slack] = np.maximum( + -grad[n:][i_slack] / sd[n:][i_slack], + 0.0, + ) + alpha_xl = np.min(all_alpha_xl) + alpha_xu = np.min(all_alpha_xu) + alpha_slack = np.min(all_alpha_slack, initial=np.inf) + alpha_bd = min(alpha_xl, alpha_xu, alpha_slack) + + # Set alpha_ub to the step size for the linear constraints. + aub_sd = aub @ sd[:n] - sd[n:] + i_ub = free_ub & (aub_sd > TINY * np.abs(resid)) + all_alpha_ub = np.full_like(bub, np.inf) + all_alpha_ub[i_ub] = resid[i_ub] / aub_sd[i_ub] + alpha_ub = np.min(all_alpha_ub, initial=np.inf) + + # Update the iterate. + alpha = min(alpha, alpha_bd, alpha_ub) + if alpha > 0.0: + step = np.clip(step + alpha * sd[:n], xl, xu) + grad += alpha * hess_sd + resid = np.maximum(0.0, resid - alpha * aub_sd) + reduct -= alpha * (grad_sd + 0.5 * alpha * curv_sd) + + if alpha < min(alpha_tr, alpha_bd, alpha_ub): + # The current iteration is a conjugate gradient iteration. Update + # the search direction so that it is conjugate (with respect to H) + # to all the previous search directions. + grad_proj = q[:, n_act:] @ (q[:, n_act:].T @ grad) + beta = (grad_proj @ hess_sd) / curv_sd + sd = beta * sd - grad_proj + k += 1 + elif alpha < alpha_tr: + # The iterate is restricted by a bound/linear constraint. Add this + # constraint to the active set, and restart the calculations. + if alpha_xl <= alpha: + i_new = np.argmin(all_alpha_xl) + step[i_new] = xl[i_new] + free_xl[i_new] = False + elif alpha_xu <= alpha: + i_new = np.argmin(all_alpha_xu) + step[i_new] = xu[i_new] + free_xu[i_new] = False + elif alpha_slack <= alpha: + i_new = np.argmin(all_alpha_slack) + free_slack[i_new] = False + else: + i_new = np.argmin(all_alpha_ub) + free_ub[i_new] = False + n_act, q = qr_normal_byrd_omojokun( + aub, free_xl, free_xu, free_slack, free_ub + ) + sd = -q[:, n_act:] @ (q[:, n_act:].T @ grad) + k = 0 + else: + # The current iterate is on the trust-region boundary. Add all the + # active bound constraints to the working set to prepare for the + # improvement of the solution, and stop the iterations. + if alpha_xl <= alpha: + i_new = _argmin(all_alpha_xl) + step[i_new] = xl[i_new] + free_xl[i_new] = False + if alpha_xu <= alpha: + i_new = _argmin(all_alpha_xu) + step[i_new] = xu[i_new] + free_xu[i_new] = False + boundary_reached = True + break + + # Attempt to improve the solution on the trust-region boundary. + if kwargs.get("improve_tcg", True) and boundary_reached: + step_base = np.copy(step) + free_bd = free_xl & free_xu + grad = aub.T @ np.maximum(aub @ step - bub, 0.0) + aeq.T @ ( + aeq @ step - beq + ) + sd = np.zeros(n) + while np.count_nonzero(free_bd) > 0: + # Check whether a substantial reduction in the objective function + # is possible, and set the search direction. + step_sq = step[free_bd] @ step[free_bd] + grad_sq = grad[free_bd] @ grad[free_bd] + grad_step = grad[free_bd] @ step[free_bd] + grad_sd = -np.sqrt(max(step_sq * grad_sq - grad_step**2.0, 0.0)) + sd[free_bd] = grad_step * step[free_bd] - step_sq * grad[free_bd] + sd[~free_bd] = 0.0 + if grad_sd >= -1e-8 * reduct or np.any( + grad_sd >= -TINY * np.abs(sd[free_bd]) + ): + break + sd[free_bd] /= -grad_sd + + # Calculate an upper bound for the tangent of half the angle theta + # of this alternative iteration. The step will be updated as: + # step = cos(theta) * step + sin(theta) * sd. + temp_xl = np.zeros(n) + temp_xu = np.zeros(n) + temp_xl[free_bd] = ( + step[free_bd] ** 2.0 + sd[free_bd] ** 2.0 - xl[free_bd] ** 2.0 + ) + temp_xu[free_bd] = ( + step[free_bd] ** 2.0 + sd[free_bd] ** 2.0 - xu[free_bd] ** 2.0 + ) + temp_xl[temp_xl > 0.0] = ( + np.sqrt(temp_xl[temp_xl > 0.0]) - sd[temp_xl > 0.0] + ) + temp_xu[temp_xu > 0.0] = ( + np.sqrt(temp_xu[temp_xu > 0.0]) + sd[temp_xu > 0.0] + ) + dist_xl = np.maximum(step - xl, 0.0) + dist_xu = np.maximum(xu - step, 0.0) + i_xl = temp_xl > TINY * dist_xl + i_xu = temp_xu > TINY * dist_xu + all_t_xl = np.ones(n) + all_t_xu = np.ones(n) + all_t_xl[i_xl] = np.minimum( + all_t_xl[i_xl], + dist_xl[i_xl] / temp_xl[i_xl], + ) + all_t_xu[i_xu] = np.minimum( + all_t_xu[i_xu], + dist_xu[i_xu] / temp_xu[i_xu], + ) + t_xl = np.min(all_t_xl) + t_xu = np.min(all_t_xu) + t_bd = min(t_xl, t_xu) + + # For a range of equally spaced values of tan(0.5 * theta), + # calculate the reduction in the objective function that would be + # obtained by accepting the corresponding angle. + n_samples = 20 + n_samples = int((n_samples - 3) * t_bd + 3) + t_samples = np.linspace(t_bd / n_samples, t_bd, n_samples) + resid_ub = np.maximum(aub @ step - bub, 0.0) + resid_eq = aeq @ step - beq + step_proj = np.copy(step) + step_proj[~free_bd] = 0.0 + all_reduct = np.empty(n_samples) + for i in range(n_samples): + sin_value = 2.0 * t_samples[i] / (1.0 + t_samples[i] ** 2.0) + step_alt = np.clip( + step + sin_value * (sd - t_samples[i] * step_proj), + xl, + xu, + ) + resid_ub_alt = np.maximum(aub @ step_alt - bub, 0.0) + resid_eq_alt = aeq @ step_alt - beq + all_reduct[i] = 0.5 * ( + resid_ub @ resid_ub + + resid_eq @ resid_eq + - resid_ub_alt @ resid_ub_alt + - resid_eq_alt @ resid_eq_alt + ) + if np.all(all_reduct <= 0.0): + # No reduction in the objective function is obtained. + break + + # Accept the angle that provides the largest reduction in the + # objective function, and update the iterate. + i_max = np.argmax(all_reduct) + cos_value = (1.0 - t_samples[i_max] ** 2.0) / ( + 1.0 + t_samples[i_max] ** 2.0 + ) + sin_value = (2.0 * t_samples[i_max] + / (1.0 + t_samples[i_max] ** 2.0)) + step[free_bd] = cos_value * step[free_bd] + sin_value * sd[free_bd] + grad = aub.T @ np.maximum(aub @ step - bub, 0.0) + aeq.T @ ( + aeq @ step - beq + ) + reduct += all_reduct[i_max] + + # If the above angle is restricted by bound constraints, add them + # to the working set, and restart the alternative iteration. + # Otherwise, the calculations are terminated. + if t_bd < 1.0 and i_max == n_samples - 1: + if t_xl <= t_bd: + i_new = _argmin(all_t_xl) + step[i_new] = xl[i_new] + free_bd[i_new] = False + if t_xu <= t_bd: + i_new = _argmin(all_t_xu) + step[i_new] = xu[i_new] + free_bd[i_new] = False + else: + break + + # Ensure that the alternative iteration improves the objective + # function. + resid_ub = np.maximum(aub @ step - bub, 0.0) + resid_ub_base = np.maximum(aub @ step_base - bub, 0.0) + resid_eq = aeq @ step - beq + resid_eq_base = aeq @ step_base - beq + if ( + resid_ub @ resid_ub + resid_eq @ resid_eq + > resid_ub_base @ resid_ub_base + resid_eq_base @ resid_eq_base + ): + step = step_base + + if debug: + assert np.all(xl <= step) + assert np.all(step <= xu) + assert np.linalg.norm(step) < 1.1 * delta + return step + + +def qr_tangential_byrd_omojokun(aub, aeq, free_xl, free_xu, free_ub): + n = free_xl.size + identity = np.eye(n) + q, r, _ = qr( + np.block( + [ + [aeq], + [aub[~free_ub, :]], + [-identity[~free_xl, :]], + [identity[~free_xu, :]], + ] + ).T, + pivoting=True, + ) + n_act = np.count_nonzero( + np.abs(np.diag(r)) + >= 10.0 + * EPS + * n + * np.linalg.norm(r[: np.min(r.shape), : np.min(r.shape)], axis=0) + ) + return n_act, q + + +def qr_normal_byrd_omojokun(aub, free_xl, free_xu, free_slack, free_ub): + m_linear_ub, n = aub.shape + identity_n = np.eye(n) + identity_m = np.eye(m_linear_ub) + q, r, _ = qr( + np.block( + [ + [ + aub[~free_ub, :], + -identity_m[~free_ub, :], + ], + [ + np.zeros((m_linear_ub - np.count_nonzero(free_slack), n)), + -identity_m[~free_slack, :], + ], + [ + -identity_n[~free_xl, :], + np.zeros((n - np.count_nonzero(free_xl), m_linear_ub)), + ], + [ + identity_n[~free_xu, :], + np.zeros((n - np.count_nonzero(free_xu), m_linear_ub)), + ], + ] + ).T, + pivoting=True, + ) + n_act = np.count_nonzero( + np.abs(np.diag(r)) + >= 10.0 + * EPS + * (n + m_linear_ub) + * np.linalg.norm(r[: np.min(r.shape), : np.min(r.shape)], axis=0) + ) + return n_act, q + + +def _alpha_tr(step, sd, delta): + step_sd = step @ sd + sd_sq = sd @ sd + dist_tr_sq = delta**2.0 - step @ step + temp = np.sqrt(max(step_sd**2.0 + sd_sq * dist_tr_sq, 0.0)) + if step_sd <= 0.0 and sd_sq > TINY * abs(temp - step_sd): + alpha_tr = max((temp - step_sd) / sd_sq, 0.0) + elif abs(temp + step_sd) > TINY * dist_tr_sq: + alpha_tr = max(dist_tr_sq / (temp + step_sd), 0.0) + else: + raise ZeroDivisionError + return alpha_tr + + +def _argmax(x): + return np.flatnonzero(x >= np.max(x)) + + +def _argmin(x): + return np.flatnonzero(x <= np.min(x)) diff --git a/.venv/lib/python3.12/site-packages/scipy/_external/cobyqa/utils/__init__.py b/.venv/lib/python3.12/site-packages/scipy/_external/cobyqa/utils/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..fe6b4841ddff3a04bda5cbff744e30681b6963b9 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/scipy/_external/cobyqa/utils/__init__.py @@ -0,0 +1,18 @@ +from .exceptions import ( + MaxEvalError, + TargetSuccess, + CallbackSuccess, + FeasibleSuccess, +) +from .math import get_arrays_tol, exact_1d_array +from .versions import show_versions + +__all__ = [ + "MaxEvalError", + "TargetSuccess", + "CallbackSuccess", + "FeasibleSuccess", + "get_arrays_tol", + "exact_1d_array", + "show_versions", +] diff --git a/.venv/lib/python3.12/site-packages/scipy/_external/cobyqa/utils/exceptions.py b/.venv/lib/python3.12/site-packages/scipy/_external/cobyqa/utils/exceptions.py new file mode 100644 index 0000000000000000000000000000000000000000..c85094894f378a8e3934ad109ea6166e33e4366b --- /dev/null +++ b/.venv/lib/python3.12/site-packages/scipy/_external/cobyqa/utils/exceptions.py @@ -0,0 +1,22 @@ +class MaxEvalError(Exception): + """ + Exception raised when the maximum number of evaluations is reached. + """ + + +class TargetSuccess(Exception): + """ + Exception raised when the target value is reached. + """ + + +class CallbackSuccess(StopIteration): + """ + Exception raised when the callback function raises a ``StopIteration``. + """ + + +class FeasibleSuccess(Exception): + """ + Exception raised when a feasible point of a feasible problem is found. + """ diff --git a/.venv/lib/python3.12/site-packages/scipy/_external/cobyqa/utils/math.py b/.venv/lib/python3.12/site-packages/scipy/_external/cobyqa/utils/math.py new file mode 100644 index 0000000000000000000000000000000000000000..1b16ae98a0df38752815f5a69d56da20f856f9f9 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/scipy/_external/cobyqa/utils/math.py @@ -0,0 +1,77 @@ +import numpy as np + + +EPS = np.finfo(float).eps + + +def get_arrays_tol(*arrays): + """ + Get a relative tolerance for a set of arrays. + + Parameters + ---------- + *arrays: tuple + Set of `numpy.ndarray` to get the tolerance for. + + Returns + ------- + float + Relative tolerance for the set of arrays. + + Raises + ------ + ValueError + If no array is provided. + """ + if len(arrays) == 0: + raise ValueError("At least one array must be provided.") + size = max(array.size for array in arrays) + weight = max( + np.max(np.abs(array[np.isfinite(array)]), initial=1.0) + for array in arrays + ) + return 10.0 * EPS * max(size, 1.0) * weight + + +def exact_1d_array(x, message): + """ + Preprocess a 1-dimensional array. + + Parameters + ---------- + x : array_like + Array to be preprocessed. + message : str + Error message if `x` cannot be interpreter as a 1-dimensional array. + + Returns + ------- + `numpy.ndarray` + Preprocessed array. + """ + x = np.atleast_1d(np.squeeze(x)).astype(float) + if x.ndim != 1: + raise ValueError(message) + return x + + +def exact_2d_array(x, message): + """ + Preprocess a 2-dimensional array. + + Parameters + ---------- + x : array_like + Array to be preprocessed. + message : str + Error message if `x` cannot be interpreter as a 2-dimensional array. + + Returns + ------- + `numpy.ndarray` + Preprocessed array. + """ + x = np.atleast_2d(x).astype(float) + if x.ndim != 2: + raise ValueError(message) + return x diff --git a/.venv/lib/python3.12/site-packages/scipy/_external/cobyqa/utils/versions.py b/.venv/lib/python3.12/site-packages/scipy/_external/cobyqa/utils/versions.py new file mode 100644 index 0000000000000000000000000000000000000000..94a0f8f5cef626354f40901cbe06a84287291c1c --- /dev/null +++ b/.venv/lib/python3.12/site-packages/scipy/_external/cobyqa/utils/versions.py @@ -0,0 +1,67 @@ +import os +import platform +import sys +from importlib.metadata import PackageNotFoundError, version + + +def _get_sys_info(): + """ + Get useful system information. + + Returns + ------- + dict + Useful system information. + """ + return { + "python": sys.version.replace(os.linesep, " "), + "executable": sys.executable, + "machine": platform.platform(), + } + + +def _get_deps_info(): + """ + Get the versions of the dependencies. + + Returns + ------- + dict + Versions of the dependencies. + """ + deps = ["cobyqa", "numpy", "scipy", "setuptools", "pip"] + deps_info = {} + for module in deps: + try: + deps_info[module] = version(module) + except PackageNotFoundError: + deps_info[module] = None + return deps_info + + +def show_versions(): + """ + Display useful system and dependencies information. + + When reporting issues, please include this information. + """ + print("System settings") + print("---------------") + sys_info = _get_sys_info() + print( + "\n".join( + f"{k:>{max(map(len, sys_info.keys())) + 1}}: {v}" + for k, v in sys_info.items() + ) + ) + + print() + print("Python dependencies") + print("-------------------") + deps_info = _get_deps_info() + print( + "\n".join( + f"{k:>{max(map(len, deps_info.keys())) + 1}}: {v}" + for k, v in deps_info.items() + ) + ) diff --git a/.venv/lib/python3.12/site-packages/scipy/_external/packaging_version/__pycache__/_structures.cpython-312.pyc b/.venv/lib/python3.12/site-packages/scipy/_external/packaging_version/__pycache__/_structures.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3130e6391742ba5036e15012910badb9e25c24b6 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/scipy/_external/packaging_version/__pycache__/_structures.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/scipy/_external/packaging_version/__pycache__/version.cpython-312.pyc b/.venv/lib/python3.12/site-packages/scipy/_external/packaging_version/__pycache__/version.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e0e95d805a99669533536e8850f69aebd4950ba1 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/scipy/_external/packaging_version/__pycache__/version.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/scipy/_external/packaging_version/_structures.py b/.venv/lib/python3.12/site-packages/scipy/_external/packaging_version/_structures.py new file mode 100644 index 0000000000000000000000000000000000000000..90a6465f9682c886363eea5327dac64bf623a6ff --- /dev/null +++ b/.venv/lib/python3.12/site-packages/scipy/_external/packaging_version/_structures.py @@ -0,0 +1,61 @@ +# This file is dual licensed under the terms of the Apache License, Version +# 2.0, and the BSD License. See the LICENSE file in the root of this repository +# for complete details. + + +class InfinityType: + def __repr__(self) -> str: + return "Infinity" + + def __hash__(self) -> int: + return hash(repr(self)) + + def __lt__(self, other: object) -> bool: + return False + + def __le__(self, other: object) -> bool: + return False + + def __eq__(self, other: object) -> bool: + return isinstance(other, self.__class__) + + def __gt__(self, other: object) -> bool: + return True + + def __ge__(self, other: object) -> bool: + return True + + def __neg__(self: object) -> "NegativeInfinityType": + return NegativeInfinity + + +Infinity = InfinityType() + + +class NegativeInfinityType: + def __repr__(self) -> str: + return "-Infinity" + + def __hash__(self) -> int: + return hash(repr(self)) + + def __lt__(self, other: object) -> bool: + return True + + def __le__(self, other: object) -> bool: + return True + + def __eq__(self, other: object) -> bool: + return isinstance(other, self.__class__) + + def __gt__(self, other: object) -> bool: + return False + + def __ge__(self, other: object) -> bool: + return False + + def __neg__(self: object) -> InfinityType: + return Infinity + + +NegativeInfinity = NegativeInfinityType() diff --git a/.venv/lib/python3.12/site-packages/scipy/_external/packaging_version/version.py b/.venv/lib/python3.12/site-packages/scipy/_external/packaging_version/version.py new file mode 100644 index 0000000000000000000000000000000000000000..c9bbda20e463b8d9389ecd65f74af33810a02bdd --- /dev/null +++ b/.venv/lib/python3.12/site-packages/scipy/_external/packaging_version/version.py @@ -0,0 +1,582 @@ +# This file is dual licensed under the terms of the Apache License, Version +# 2.0, and the BSD License. See the LICENSE file in the root of this repository +# for complete details. +""" +.. testsetup:: + + from packaging.version import parse, Version +""" + +from __future__ import annotations + +import itertools +import re +from typing import Any, Callable, NamedTuple, SupportsInt, Tuple, Union + +from ._structures import Infinity, InfinityType, NegativeInfinity, NegativeInfinityType + +__all__ = ["VERSION_PATTERN", "InvalidVersion", "Version", "parse"] + +LocalType = Tuple[Union[int, str], ...] + +CmpPrePostDevType = Union[InfinityType, NegativeInfinityType, Tuple[str, int]] +CmpLocalType = Union[ + NegativeInfinityType, + Tuple[Union[Tuple[int, str], Tuple[NegativeInfinityType, Union[int, str]]], ...], +] +CmpKey = Tuple[ + int, + Tuple[int, ...], + CmpPrePostDevType, + CmpPrePostDevType, + CmpPrePostDevType, + CmpLocalType, +] +VersionComparisonMethod = Callable[[CmpKey, CmpKey], bool] + + +class _Version(NamedTuple): + epoch: int + release: tuple[int, ...] + dev: tuple[str, int] | None + pre: tuple[str, int] | None + post: tuple[str, int] | None + local: LocalType | None + + +def parse(version: str) -> Version: + """Parse the given version string. + + >>> parse('1.0.dev1') + + + :param version: The version string to parse. + :raises InvalidVersion: When the version string is not a valid version. + """ + return Version(version) + + +class InvalidVersion(ValueError): + """Raised when a version string is not a valid version. + + >>> Version("invalid") + Traceback (most recent call last): + ... + packaging.version.InvalidVersion: Invalid version: 'invalid' + """ + + +class _BaseVersion: + _key: tuple[Any, ...] + + def __hash__(self) -> int: + return hash(self._key) + + # Please keep the duplicated `isinstance` check + # in the six comparisons hereunder + # unless you find a way to avoid adding overhead function calls. + def __lt__(self, other: _BaseVersion) -> bool: + if not isinstance(other, _BaseVersion): + return NotImplemented + + return self._key < other._key + + def __le__(self, other: _BaseVersion) -> bool: + if not isinstance(other, _BaseVersion): + return NotImplemented + + return self._key <= other._key + + def __eq__(self, other: object) -> bool: + if not isinstance(other, _BaseVersion): + return NotImplemented + + return self._key == other._key + + def __ge__(self, other: _BaseVersion) -> bool: + if not isinstance(other, _BaseVersion): + return NotImplemented + + return self._key >= other._key + + def __gt__(self, other: _BaseVersion) -> bool: + if not isinstance(other, _BaseVersion): + return NotImplemented + + return self._key > other._key + + def __ne__(self, other: object) -> bool: + if not isinstance(other, _BaseVersion): + return NotImplemented + + return self._key != other._key + + +# Deliberately not anchored to the start and end of the string, to make it +# easier for 3rd party code to reuse +_VERSION_PATTERN = r""" + v? + (?: + (?:(?P[0-9]+)!)? # epoch + (?P[0-9]+(?:\.[0-9]+)*) # release segment + (?P
                                          # pre-release
+            [-_\.]?
+            (?Palpha|a|beta|b|preview|pre|c|rc)
+            [-_\.]?
+            (?P[0-9]+)?
+        )?
+        (?P                                         # post release
+            (?:-(?P[0-9]+))
+            |
+            (?:
+                [-_\.]?
+                (?Ppost|rev|r)
+                [-_\.]?
+                (?P[0-9]+)?
+            )
+        )?
+        (?P                                          # dev release
+            [-_\.]?
+            (?Pdev)
+            [-_\.]?
+            (?P[0-9]+)?
+        )?
+    )
+    (?:\+(?P[a-z0-9]+(?:[-_\.][a-z0-9]+)*))?       # local version
+"""
+
+VERSION_PATTERN = _VERSION_PATTERN
+"""
+A string containing the regular expression used to match a valid version.
+
+The pattern is not anchored at either end, and is intended for embedding in larger
+expressions (for example, matching a version number as part of a file name). The
+regular expression should be compiled with the ``re.VERBOSE`` and ``re.IGNORECASE``
+flags set.
+
+:meta hide-value:
+"""
+
+
+class Version(_BaseVersion):
+    """This class abstracts handling of a project's versions.
+
+    A :class:`Version` instance is comparison aware and can be compared and
+    sorted using the standard Python interfaces.
+
+    >>> v1 = Version("1.0a5")
+    >>> v2 = Version("1.0")
+    >>> v1
+    
+    >>> v2
+    
+    >>> v1 < v2
+    True
+    >>> v1 == v2
+    False
+    >>> v1 > v2
+    False
+    >>> v1 >= v2
+    False
+    >>> v1 <= v2
+    True
+    """
+
+    _regex = re.compile(r"^\s*" + VERSION_PATTERN + r"\s*$", re.VERBOSE | re.IGNORECASE)
+    _key: CmpKey
+
+    def __init__(self, version: str) -> None:
+        """Initialize a Version object.
+
+        :param version:
+            The string representation of a version which will be parsed and normalized
+            before use.
+        :raises InvalidVersion:
+            If the ``version`` does not conform to PEP 440 in any way then this
+            exception will be raised.
+        """
+
+        # Validate the version and parse it into pieces
+        match = self._regex.search(version)
+        if not match:
+            raise InvalidVersion(f"Invalid version: {version!r}")
+
+        # Store the parsed out pieces of the version
+        self._version = _Version(
+            epoch=int(match.group("epoch")) if match.group("epoch") else 0,
+            release=tuple(int(i) for i in match.group("release").split(".")),
+            pre=_parse_letter_version(match.group("pre_l"), match.group("pre_n")),
+            post=_parse_letter_version(
+                match.group("post_l"), match.group("post_n1") or match.group("post_n2")
+            ),
+            dev=_parse_letter_version(match.group("dev_l"), match.group("dev_n")),
+            local=_parse_local_version(match.group("local")),
+        )
+
+        # Generate a key which will be used for sorting
+        self._key = _cmpkey(
+            self._version.epoch,
+            self._version.release,
+            self._version.pre,
+            self._version.post,
+            self._version.dev,
+            self._version.local,
+        )
+
+    def __repr__(self) -> str:
+        """A representation of the Version that shows all internal state.
+
+        >>> Version('1.0.0')
+        
+        """
+        return f""
+
+    def __str__(self) -> str:
+        """A string representation of the version that can be round-tripped.
+
+        >>> str(Version("1.0a5"))
+        '1.0a5'
+        """
+        parts = []
+
+        # Epoch
+        if self.epoch != 0:
+            parts.append(f"{self.epoch}!")
+
+        # Release segment
+        parts.append(".".join(str(x) for x in self.release))
+
+        # Pre-release
+        if self.pre is not None:
+            parts.append("".join(str(x) for x in self.pre))
+
+        # Post-release
+        if self.post is not None:
+            parts.append(f".post{self.post}")
+
+        # Development release
+        if self.dev is not None:
+            parts.append(f".dev{self.dev}")
+
+        # Local version segment
+        if self.local is not None:
+            parts.append(f"+{self.local}")
+
+        return "".join(parts)
+
+    @property
+    def epoch(self) -> int:
+        """The epoch of the version.
+
+        >>> Version("2.0.0").epoch
+        0
+        >>> Version("1!2.0.0").epoch
+        1
+        """
+        return self._version.epoch
+
+    @property
+    def release(self) -> tuple[int, ...]:
+        """The components of the "release" segment of the version.
+
+        >>> Version("1.2.3").release
+        (1, 2, 3)
+        >>> Version("2.0.0").release
+        (2, 0, 0)
+        >>> Version("1!2.0.0.post0").release
+        (2, 0, 0)
+
+        Includes trailing zeroes but not the epoch or any pre-release / development /
+        post-release suffixes.
+        """
+        return self._version.release
+
+    @property
+    def pre(self) -> tuple[str, int] | None:
+        """The pre-release segment of the version.
+
+        >>> print(Version("1.2.3").pre)
+        None
+        >>> Version("1.2.3a1").pre
+        ('a', 1)
+        >>> Version("1.2.3b1").pre
+        ('b', 1)
+        >>> Version("1.2.3rc1").pre
+        ('rc', 1)
+        """
+        return self._version.pre
+
+    @property
+    def post(self) -> int | None:
+        """The post-release number of the version.
+
+        >>> print(Version("1.2.3").post)
+        None
+        >>> Version("1.2.3.post1").post
+        1
+        """
+        return self._version.post[1] if self._version.post else None
+
+    @property
+    def dev(self) -> int | None:
+        """The development number of the version.
+
+        >>> print(Version("1.2.3").dev)
+        None
+        >>> Version("1.2.3.dev1").dev
+        1
+        """
+        return self._version.dev[1] if self._version.dev else None
+
+    @property
+    def local(self) -> str | None:
+        """The local version segment of the version.
+
+        >>> print(Version("1.2.3").local)
+        None
+        >>> Version("1.2.3+abc").local
+        'abc'
+        """
+        if self._version.local:
+            return ".".join(str(x) for x in self._version.local)
+        else:
+            return None
+
+    @property
+    def public(self) -> str:
+        """The public portion of the version.
+
+        >>> Version("1.2.3").public
+        '1.2.3'
+        >>> Version("1.2.3+abc").public
+        '1.2.3'
+        >>> Version("1!1.2.3dev1+abc").public
+        '1!1.2.3.dev1'
+        """
+        return str(self).split("+", 1)[0]
+
+    @property
+    def base_version(self) -> str:
+        """The "base version" of the version.
+
+        >>> Version("1.2.3").base_version
+        '1.2.3'
+        >>> Version("1.2.3+abc").base_version
+        '1.2.3'
+        >>> Version("1!1.2.3dev1+abc").base_version
+        '1!1.2.3'
+
+        The "base version" is the public version of the project without any pre or post
+        release markers.
+        """
+        parts = []
+
+        # Epoch
+        if self.epoch != 0:
+            parts.append(f"{self.epoch}!")
+
+        # Release segment
+        parts.append(".".join(str(x) for x in self.release))
+
+        return "".join(parts)
+
+    @property
+    def is_prerelease(self) -> bool:
+        """Whether this version is a pre-release.
+
+        >>> Version("1.2.3").is_prerelease
+        False
+        >>> Version("1.2.3a1").is_prerelease
+        True
+        >>> Version("1.2.3b1").is_prerelease
+        True
+        >>> Version("1.2.3rc1").is_prerelease
+        True
+        >>> Version("1.2.3dev1").is_prerelease
+        True
+        """
+        return self.dev is not None or self.pre is not None
+
+    @property
+    def is_postrelease(self) -> bool:
+        """Whether this version is a post-release.
+
+        >>> Version("1.2.3").is_postrelease
+        False
+        >>> Version("1.2.3.post1").is_postrelease
+        True
+        """
+        return self.post is not None
+
+    @property
+    def is_devrelease(self) -> bool:
+        """Whether this version is a development release.
+
+        >>> Version("1.2.3").is_devrelease
+        False
+        >>> Version("1.2.3.dev1").is_devrelease
+        True
+        """
+        return self.dev is not None
+
+    @property
+    def major(self) -> int:
+        """The first item of :attr:`release` or ``0`` if unavailable.
+
+        >>> Version("1.2.3").major
+        1
+        """
+        return self.release[0] if len(self.release) >= 1 else 0
+
+    @property
+    def minor(self) -> int:
+        """The second item of :attr:`release` or ``0`` if unavailable.
+
+        >>> Version("1.2.3").minor
+        2
+        >>> Version("1").minor
+        0
+        """
+        return self.release[1] if len(self.release) >= 2 else 0
+
+    @property
+    def micro(self) -> int:
+        """The third item of :attr:`release` or ``0`` if unavailable.
+
+        >>> Version("1.2.3").micro
+        3
+        >>> Version("1").micro
+        0
+        """
+        return self.release[2] if len(self.release) >= 3 else 0
+
+
+class _TrimmedRelease(Version):
+    @property
+    def release(self) -> tuple[int, ...]:
+        """
+        Release segment without any trailing zeros.
+
+        >>> _TrimmedRelease('1.0.0').release
+        (1,)
+        >>> _TrimmedRelease('0.0').release
+        (0,)
+        """
+        rel = super().release
+        nonzeros = (index for index, val in enumerate(rel) if val)
+        last_nonzero = max(nonzeros, default=0)
+        return rel[: last_nonzero + 1]
+
+
+def _parse_letter_version(
+    letter: str | None, number: str | bytes | SupportsInt | None
+) -> tuple[str, int] | None:
+    if letter:
+        # We consider there to be an implicit 0 in a pre-release if there is
+        # not a numeral associated with it.
+        if number is None:
+            number = 0
+
+        # We normalize any letters to their lower case form
+        letter = letter.lower()
+
+        # We consider some words to be alternate spellings of other words and
+        # in those cases we want to normalize the spellings to our preferred
+        # spelling.
+        if letter == "alpha":
+            letter = "a"
+        elif letter == "beta":
+            letter = "b"
+        elif letter in ["c", "pre", "preview"]:
+            letter = "rc"
+        elif letter in ["rev", "r"]:
+            letter = "post"
+
+        return letter, int(number)
+
+    assert not letter
+    if number:
+        # We assume if we are given a number, but we are not given a letter
+        # then this is using the implicit post release syntax (e.g. 1.0-1)
+        letter = "post"
+
+        return letter, int(number)
+
+    return None
+
+
+_local_version_separators = re.compile(r"[\._-]")
+
+
+def _parse_local_version(local: str | None) -> LocalType | None:
+    """
+    Takes a string like abc.1.twelve and turns it into ("abc", 1, "twelve").
+    """
+    if local is not None:
+        return tuple(
+            part.lower() if not part.isdigit() else int(part)
+            for part in _local_version_separators.split(local)
+        )
+    return None
+
+
+def _cmpkey(
+    epoch: int,
+    release: tuple[int, ...],
+    pre: tuple[str, int] | None,
+    post: tuple[str, int] | None,
+    dev: tuple[str, int] | None,
+    local: LocalType | None,
+) -> CmpKey:
+    # When we compare a release version, we want to compare it with all of the
+    # trailing zeros removed. So we'll use a reverse the list, drop all the now
+    # leading zeros until we come to something non zero, then take the rest
+    # re-reverse it back into the correct order and make it a tuple and use
+    # that for our sorting key.
+    _release = tuple(
+        reversed(list(itertools.dropwhile(lambda x: x == 0, reversed(release))))
+    )
+
+    # We need to "trick" the sorting algorithm to put 1.0.dev0 before 1.0a0.
+    # We'll do this by abusing the pre segment, but we _only_ want to do this
+    # if there is not a pre or a post segment. If we have one of those then
+    # the normal sorting rules will handle this case correctly.
+    if pre is None and post is None and dev is not None:
+        _pre: CmpPrePostDevType = NegativeInfinity
+    # Versions without a pre-release (except as noted above) should sort after
+    # those with one.
+    elif pre is None:
+        _pre = Infinity
+    else:
+        _pre = pre
+
+    # Versions without a post segment should sort before those with one.
+    if post is None:
+        _post: CmpPrePostDevType = NegativeInfinity
+
+    else:
+        _post = post
+
+    # Versions without a development segment should sort after those with one.
+    if dev is None:
+        _dev: CmpPrePostDevType = Infinity
+
+    else:
+        _dev = dev
+
+    if local is None:
+        # Versions without a local segment should sort before those with one.
+        _local: CmpLocalType = NegativeInfinity
+    else:
+        # Versions with a local segment need that segment parsed to implement
+        # the sorting rules in PEP440.
+        # - Alpha numeric segments sort before numeric segments
+        # - Alpha numeric segments sort lexicographically
+        # - Numeric segments sort numerically
+        # - Shorter versions sort before longer versions when the prefixes
+        #   match exactly
+        _local = tuple(
+            (i, "") if isinstance(i, int) else (NegativeInfinity, i) for i in local
+        )
+
+    return epoch, _release, _pre, _post, _dev, _local
diff --git a/.venv/lib/python3.12/site-packages/scipy/_external/pyprima/__init__.py b/.venv/lib/python3.12/site-packages/scipy/_external/pyprima/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..577e1d266162d70023cdee4cc0bfe72ce0796712
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/_external/pyprima/__init__.py
@@ -0,0 +1,212 @@
+# Bounds may appear unused in this file but we need to import it to make it available to the user
+from scipy.optimize import NonlinearConstraint, LinearConstraint, Bounds
+from .common._nonlinear_constraints import process_nl_constraints
+from .common._linear_constraints import (
+    combine_multiple_linear_constraints,
+    separate_LC_into_eq_and_ineq,
+)
+from .common._bounds import process_bounds
+from enum import Enum
+from .common._project import _project
+from .common.linalg import get_arrays_tol
+from .cobyla.cobyla import cobyla
+import numpy as np
+from collections.abc import Iterable
+
+
+class ConstraintType(Enum):
+    LINEAR_OBJECT = 5
+    NONLINEAR_OBJECT = 10
+    LINEAR_DICT = 15
+    NONLINEAR_DICT = 20
+
+
+def get_constraint_type(constraint):
+    if isinstance(constraint, dict) and ("A" in constraint) and ("lb" in constraint) and ("ub" in constraint):
+        return ConstraintType.LINEAR_DICT
+    elif isinstance(constraint, dict) and ("fun" in constraint) and ("lb" in constraint) and ("ub" in constraint):
+        return ConstraintType.NONLINEAR_DICT
+    elif hasattr(constraint, "A") and hasattr(constraint, "lb") and hasattr(constraint, "ub"):
+        return ConstraintType.LINEAR_OBJECT
+    elif hasattr(constraint, "fun") and hasattr(constraint, "lb") and hasattr(constraint, "ub"):
+        return ConstraintType.NONLINEAR_OBJECT
+    else:
+        raise ValueError(f"Constraint type {type(constraint)} not recognized")
+
+
+def process_constraints(constraints):
+    # First throw it back if it's an empty tuple
+    if not constraints:
+        return None, None
+    # Next figure out if it's a list of constraints or a single constraint
+    # If it's a single constraint, make it a list, and then the remaining logic
+    # doesn't have to change
+    if not isinstance(constraints, Iterable):
+        constraints = [constraints]
+
+    # Separate out the linear and nonlinear constraints
+    linear_constraints = []
+    nonlinear_constraints = []
+    for constraint in constraints:
+        constraint_type = get_constraint_type(constraint)
+        if constraint_type is ConstraintType.LINEAR_OBJECT:
+            linear_constraints.append(constraint)
+        elif constraint_type is ConstraintType.NONLINEAR_OBJECT:
+            nonlinear_constraints.append(constraint)
+        elif constraint_type == ConstraintType.LINEAR_DICT:
+            linear_constraints.append(LinearConstraint(constraint["A"], constraint["lb"], constraint["ub"]))
+        elif constraint_type == ConstraintType.NONLINEAR_DICT:
+            nonlinear_constraints.append(NonlinearConstraint(constraint["fun"], constraint["lb"], constraint["ub"]))
+        else:
+            raise ValueError("Constraint type not recognized")
+
+    if len(nonlinear_constraints) > 0:
+        nonlinear_constraint_function = process_nl_constraints(nonlinear_constraints)
+    else:
+        nonlinear_constraint_function = None
+
+    # Determine if we have multiple linear constraints, just 1, or none, and process accordingly
+    if len(linear_constraints) > 1:
+        linear_constraint = combine_multiple_linear_constraints(linear_constraints)
+    elif len(linear_constraints) == 1:
+        linear_constraint = linear_constraints[0]
+    else:
+        linear_constraint = None
+
+    return linear_constraint, nonlinear_constraint_function
+
+
+def minimize(fun, x0, args=(), method=None, bounds=None, constraints=(), callback=None, options=None):
+
+    linear_constraint, nonlinear_constraint_function = process_constraints(constraints)
+
+    options = {'quiet': True} if options is None else options
+    quiet = options.get("quiet", True)
+
+    if method is None:
+        if nonlinear_constraint_function is not None:
+            if not quiet: print("Nonlinear constraints detected, applying COBYLA")
+            method = "cobyla"
+        elif linear_constraint is not None:
+            if not quiet: print("Linear constraints detected without nonlinear constraints, applying LINCOA")
+            method = "lincoa"
+        elif bounds is not None:
+            if not quiet: print("Bounds without linear or nonlinear constraints detected, applying BOBYQA")
+            method = "bobyqa"
+        else:
+            if not quiet: print("No bounds or constraints detected, applying NEWUOA")
+            method = "newuoa"
+    else:
+        # Raise some errors if methods were called with inappropriate options
+        method = method.lower()
+        if method not in ('newuoa', 'uobyqa', 'bobyqa', 'cobyla', 'lincoa'):
+            raise ValueError(f"Method must be one of NEWUOA, UOBYQA, BOBYQA, COBYLA, or LINCOA, not '{method}'")
+        if method != "cobyla" and nonlinear_constraint_function is not None:
+            raise ValueError("Nonlinear constraints were provided for an algorithm that cannot handle them")
+        if method not in ("cobyla", "lincoa") and linear_constraint is not None:
+            raise ValueError("Linear constraints were provided for an algorithm that cannot handle them")
+        if method not in ("cobyla", "bobyqa", "lincoa") and bounds is not None:
+            raise ValueError("Bounds were provided for an algorithm that cannot handle them")
+
+    # Try to get the length of x0. If we can't that likely means it's a scalar, and
+    # in that case we turn it into an array and wrap the original function so that it
+    # can accept an array and return a scalar.
+    try:
+        lenx0 = len(x0)
+    except TypeError:
+        x0 = np.array([x0])
+        original_scalar_fun = fun
+        def scalar_fun(x):
+            return original_scalar_fun(x[0], *args)
+        fun = scalar_fun
+        lenx0 = 1
+
+    lb, ub = process_bounds(bounds, lenx0)
+
+    # Check which variables are fixed and eliminate them from the problem.
+    # Save the indices and values so that we can call the original function with
+    # an array of the appropriate size, and so that we can add the fixed values to the
+    # result when COBYLA returns.
+    tol = get_arrays_tol(lb, ub)
+    _fixed_idx = (
+        (lb <= ub)
+        & (np.abs(lb - ub) < tol)
+    )
+    if any(_fixed_idx):
+        _fixed_values = 0.5 * (
+            lb[_fixed_idx] + ub[_fixed_idx]
+        )
+        _fixed_values = np.clip(
+            _fixed_values,
+            lb[_fixed_idx],
+            ub[_fixed_idx],
+        )
+        x0 = x0[~_fixed_idx]
+        lb = lb[~_fixed_idx]
+        ub = ub[~_fixed_idx]
+        original_fun = fun
+        def fixed_fun(x):
+            newx = np.zeros(lenx0)
+            newx[_fixed_idx] = _fixed_values
+            newx[~_fixed_idx] = x
+            return original_fun(newx, *args)
+        fun = fixed_fun
+
+
+    # Project x0 onto the feasible set
+    if nonlinear_constraint_function is None:
+        result = _project(x0, lb, ub, {"linear": linear_constraint, "nonlinear": None})
+        x0 = result.x
+    
+    if linear_constraint is not None:
+        A_eq, b_eq, A_ineq, b_ineq = separate_LC_into_eq_and_ineq(linear_constraint)
+    else:
+        A_eq, b_eq, A_ineq, b_ineq = None, None, None, None
+
+    if nonlinear_constraint_function is not None:
+        # If there is a nonlinear constraint function, we will call COBYLA, which needs the number of nonlinear
+        # constraints (m_nlcon). In order to get this number we need to evaluate the constraint function at x0.
+        # The constraint value at x0 (nlconstr0) is not discarded but passed down to the Fortran backend, as its
+        # evaluation is assumed to be expensive. We also evaluate the objective function at x0 and pass the result
+        # (f0) down to the Fortran backend, which expects nlconstr0 and f0 to be provided in sync.
+        def calcfc(x):
+            f = fun(x, *args)
+            nlconstr = nonlinear_constraint_function(x)
+            return f, nlconstr
+    else:
+        def calcfc(x):
+            f = fun(x, *args)
+            constr = np.zeros(0)
+            return f, constr
+
+    f0, nlconstr0 = calcfc(x0)
+
+    if 'quiet' in options:
+        del options['quiet']
+
+    if 'maxfev' in options:
+        options['maxfun'] = options['maxfev']
+        del options['maxfev']
+
+    result = cobyla(
+        calcfc,
+        len(nlconstr0),
+        x0,
+        A_ineq,
+        b_ineq,
+        A_eq,
+        b_eq,
+        lb,
+        ub,
+        f0=f0,
+        nlconstr0=nlconstr0,
+        callback=callback,
+        **options
+    )
+
+    if any(_fixed_idx):
+        newx = np.zeros(lenx0)
+        newx[_fixed_idx] = _fixed_values
+        newx[~_fixed_idx] = result.x
+        result.x = newx
+    return result
diff --git a/.venv/lib/python3.12/site-packages/scipy/_external/pyprima/cobyla/__init__.py b/.venv/lib/python3.12/site-packages/scipy/_external/pyprima/cobyla/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/.venv/lib/python3.12/site-packages/scipy/_external/pyprima/cobyla/cobyla.py b/.venv/lib/python3.12/site-packages/scipy/_external/pyprima/cobyla/cobyla.py
new file mode 100644
index 0000000000000000000000000000000000000000..11772a249e71ea23663b4d78479cd3792e1e7c43
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/_external/pyprima/cobyla/cobyla.py
@@ -0,0 +1,559 @@
+'''
+This module provides Powell's COBYLA algorithm.
+
+Translated from Zaikun Zhang's modern-Fortran reference implementation in PRIMA.
+
+Dedicated to late Professor M. J. D. Powell FRS (1936--2015).
+
+Python translation by Nickolai Belakovski.
+
+N.B.:
+
+1. The modern-Fortran reference implementation in PRIMA contains bug fixes and improvements over the
+original Fortran 77 implementation by Powell. Consequently, the PRIMA implementation behaves differently
+from the original Fortran 77 implementation by Powell. Therefore, it is important to point out that
+you are using PRIMA rather than the original solvers if you want your results to be reproducible.
+
+2. Compared to Powell's Fortran 77 implementation, the modern-Fortran implementation and hence any
+faithful translation like this one generally produce better solutions with fewer function evaluations,
+making them preferable for applications with expensive function evaluations. However, if function
+evaluations are not the dominant cost in your application, the Fortran 77 solvers are likely to be
+faster, as they are more efficient in terms of memory usage and flops thanks to the careful and
+ingenious (but unmaintained and unmaintainable) implementation by Powell.
+
+See the PRIMA documentation (www.libprima.net) for more information.
+'''
+
+from ..common.evaluate import evaluate, moderatex, moderatef, moderatec
+from ..common.consts import (EPS, RHOBEG_DEFAULT, RHOEND_DEFAULT, CTOL_DEFAULT,
+                                   CWEIGHT_DEFAULT, FTARGET_DEFAULT, IPRINT_DEFAULT,
+                                   MAXFUN_DIM_DEFAULT, DEBUGGING, BOUNDMAX,
+                                   ETA1_DEFAULT, ETA2_DEFAULT, GAMMA1_DEFAULT,
+                                   GAMMA2_DEFAULT)
+from ..common.preproc import preproc
+from ..common.present import present
+from ..common.linalg import matprod
+from .cobylb import cobylb
+import numpy as np
+from dataclasses import dataclass
+from copy import copy
+
+
+@dataclass
+class COBYLAResult:
+    x: np.ndarray
+    f: float
+    constr: np.ndarray
+    cstrv: float
+    nf: int
+    xhist: np.ndarray | None
+    fhist: np.ndarray | None
+    chist: np.ndarray | None
+    conhist: np.ndarray | None
+    info: int
+
+
+def cobyla(calcfc, m_nlcon, x, Aineq=None, bineq=None, Aeq=None, beq=None,
+           xl=None, xu=None, f0=None, nlconstr0=None, rhobeg=None, rhoend=None,
+           ftarget=FTARGET_DEFAULT, ctol=CTOL_DEFAULT, cweight=CWEIGHT_DEFAULT,
+           maxfun=None, iprint=IPRINT_DEFAULT, eta1=None, eta2=None,
+           gamma1=GAMMA1_DEFAULT, gamma2=GAMMA2_DEFAULT, maxhist=None, maxfilt=2000,
+           callback=None):
+    """
+    Among all the arguments, only CALCFC, M_NLCON, and X are obligatory. The others are
+    OPTIONAL and you can neglect them unless you are familiar with the algorithm. Any
+    unspecified optional input will take the default value detailed below. For
+    instance, we may invoke the solver as follows.
+
+    # First define CALCFC, M_NLCON, and X, and then do the following.
+    result = cobyla(calcfc, m_nlcon, x)
+
+    or
+
+    # First define CALCFC, M_NLCON, X, Aineq, and Bineq, and then do the following.
+    result = cobyla(calcfc, m_nlcon, x, Aineq=Aineq, bineq=bineq, rhobeg=1.0e0,
+        rhoend=1.0e-6)
+
+    ####################################################################################
+    # IMPORTANT NOTICE: The user must set M_NLCON correctly to the number of nonlinear
+    # constraints, namely the size of NLCONSTR introduced below. Set it to 0 if there
+    # is no nonlinear constraint.
+    ####################################################################################
+
+    See examples/cobyla/cobyla_example.py for a concrete example.
+
+    A detailed introduction to the arguments is as follows.
+
+    ####################################################################################
+    # INPUTS
+    ####################################################################################
+
+    CALCFC
+      Input, function.
+      f, nlconstr = CALCFC(X) should evaluate the objective function and nonlinear
+      constraints at the given vector X; it should return a tuple consisting of the
+      objective function value and the nonlinear constraint value. It must be provided
+      by the user, and its definition must conform to the following interface:
+      #-------------------------------------------------------------------------#
+       def calcfc(x):
+           f = 0.0
+           nlconstr = np.zeros(m_nlcon)
+           return f, nlconstr
+      #-------------------------------------------------------------------------#
+
+    M_NLCON
+      Input, scalar.
+      M_NLCON must be set to the number of nonlinear constraints, namely the size of
+      NLCONSTR(X).
+      N.B.:
+      1. Why don't we define M_NLCON as optional and default it to 0 when it is absent?
+      This is because we need to allocate memory for CONSTR_LOC using M_NLCON. To
+      ensure that the size of CONSTR_LOC is correct, we require the user to specify
+      M_NLCON explicitly.
+
+    X
+      Input, vector.
+      As an input, X should be an N-dimensional vector that contains the starting
+      point, N being the dimension of the problem.
+
+    Aineq, Bineq
+      Input, matrix of size [Mineq, N] and vector of size Mineq unless they are both
+      empty, default: None and None.
+      Aineq and Bineq represent the linear inequality constraints: Aineq*X <= Bineq.
+
+    Aeq, Beq
+      Input, matrix of size [Meq, N] and vector of size Meq unless they are both
+      empty, default: None and None.
+      Aeq and Beq represent the linear equality constraints: Aeq*X = Beq.
+
+    XL, XU
+      Input, vectors of size N unless they are both None, default: None and None.
+      XL is the lower bound for X. If XL is None, X has no
+      lower bound. Any entry of XL that is NaN or below -BOUNDMAX will be taken as
+      -BOUNDMAX, which effectively means there is no lower bound for the corresponding
+      entry of X. The value of BOUNDMAX is 0.25*HUGE(X), which is about 8.6E37 for
+      single precision and 4.5E307 for double precision. XU is similar.
+
+    F0
+      Input, scalar.
+      F0, if present, should be set to the objective function value of the starting X.
+
+    NLCONSTR0
+      Input, vector.
+      NLCONSTR0, if present, should be set to the nonlinear constraint value at the
+      starting X; in addition, SIZE(NLCONSTR0) must be M_NLCON, or the solver will
+      abort.
+
+    RHOBEG, RHOEND
+      Inputs, scalars, default: RHOBEG = 1, RHOEND = 10^-6. RHOBEG and RHOEND must be
+      set to the initial and final values of a trust-region radius, both being positive
+      and RHOEND <= RHOBEG. Typically RHOBEG should be about one tenth of the greatest
+      expected change to a variable, and RHOEND should indicate the accuracy that is
+      required in the final values of the variables.
+
+    FTARGET
+      Input, scalar, default: -Inf.
+      FTARGET is the target function value. The algorithm will terminate when a
+      feasible point with a function value <= FTARGET is found.
+
+    CTOL
+      Input, scalar, default: sqrt(machine epsilon).
+      CTOL is the tolerance of constraint violation. X is considered feasible if
+      CSTRV(X) <= CTOL.
+      N.B.:
+        1. CTOL is absolute, not relative.
+        2. CTOL is used only when selecting the returned X. It does not affect the
+           iterations of the algorithm.
+
+    CWEIGHT
+      Input, scalar, default: CWEIGHT_DFT defined in common/consts.py.
+      CWEIGHT is the weight that the constraint violation takes in the selection of the
+      returned X.
+
+    MAXFUN
+      Input, integer scalar, default: MAXFUN_DIM_DFT*N with MAXFUN_DIM_DFT defined in
+      common/consts.py. MAXFUN is the maximal number of calls of CALCFC.
+
+    IPRINT
+      Input, integer scalar, default: 0.
+      The value of IPRINT should be set to 0, 1, -1, 2, -2, 3, or -3, which controls
+      how much information will be printed during the computation:
+      0: there will be no printing;
+      1: a message will be printed to the screen at the return, showing the best vector
+         of variables found and its objective function value;
+      2: in addition to 1, each new value of RHO is printed to the screen, with the
+         best vector of variables so far and its objective function value; each new
+         value of CPEN is also printed;
+      3: in addition to 2, each function evaluation with its variables will be printed
+         to the screen; -1, -2, -3: the same information as 1, 2, 3 will be printed,
+         not to the screen but to a file named COBYLA_output.txt; the file will be
+         created if it does not exist; the new output will be appended to the end of
+         this file if it already exists.
+      Note that IPRINT = +/-3 can be costly in terms of time and/or space.
+
+    ETA1, ETA2, GAMMA1, GAMMA2
+      Input, scalars, default: ETA1 = 0.1, ETA2 = 0.7, GAMMA1 = 0.5, and GAMMA2 = 2.
+      ETA1, ETA2, GAMMA1, and GAMMA2 are parameters in the updating scheme of the
+      trust-region radius detailed in the subroutine TRRAD in trustregion.py. Roughly
+      speaking, the trust-region radius is contracted by a factor of GAMMA1 when the
+      reduction ratio is below ETA1, and enlarged by a factor of GAMMA2 when the
+      reduction ratio is above ETA2. It is required that 0 < ETA1 <= ETA2 < 1 and
+      0 < GAMMA1 < 1 < GAMMA2. Normally, ETA1 <= 0.25. It is NOT advised to set
+      ETA1 >= 0.5.
+
+    MAXFILT
+      Input, scalar.
+      MAXFILT is a nonnegative integer indicating the maximal length of the filter used
+      for selecting the returned solution; default: MAXFILT_DFT (a value lower than
+      MIN_MAXFILT is not recommended);
+      see common/consts.py for the definitions of MAXFILT_DFT and MIN_MAXFILT.
+
+    CALLBACK
+      Input, function to report progress and optionally request termination.
+
+
+    ####################################################################################
+    # OUTPUTS
+    ####################################################################################
+
+    The output is a single data structure, COBYLAResult, with the following fields:
+
+    X
+      Output, vector.
+      As an output, X will be set to an approximate minimizer.
+
+    F
+      Output, scalar.
+      F will be set to the objective function value of X at exit.
+
+    CONSTR
+      Output, vector.
+      CONSTR will be set to the constraint value of X at exit.
+
+    CSTRV
+      Output, scalar.
+      CSTRV will be set to the constraint violation of X at exit, i.e.,
+      max([0, XL - X, X - XU, Aineq*X - Bineq, ABS(Aeq*X -Beq), NLCONSTR(X)]).
+
+    NF
+      Output, scalar.
+      NF will be set to the number of calls of CALCFC at exit.
+
+    XHIST, FHIST, CHIST, CONHIST, MAXHIST
+      XHIST: Output, rank 2 array;
+      FHIST: Output, rank 1 array;
+      CHIST: Output, rank 1 array;
+      CONHIST: Output, rank 2 array;
+      MAXHIST: Input, scalar, default: MAXFUN
+      XHIST, if present, will output the history of iterates; FHIST, if present, will
+      output the history function values; CHIST, if present, will output the history of
+      constraint violations; CONHIST, if present, will output the history of constraint
+      values; MAXHIST should be a nonnegative integer, and XHIST/FHIST/CHIST/CONHIST
+      will output only the history of the last MAXHIST iterations.
+      Therefore, MAXHIST= 0 means XHIST/FHIST/CONHIST/CHIST will output
+      nothing, while setting MAXHIST = MAXFUN requests XHIST/FHIST/CHIST/CONHIST to
+      output all the history. If XHIST is present, its size at exit will be
+      (N, min(NF, MAXHIST)); if FHIST is present, its size at exit will be
+      min(NF, MAXHIST); if CHIST is present, its size at exit will be min(NF, MAXHIST);
+      if CONHIST is present, its size at exit will be (M, min(NF, MAXHIST)).
+
+      IMPORTANT NOTICE:
+      Setting MAXHIST to a large value can be costly in terms of memory for large
+      problems.
+      MAXHIST will be reset to a smaller value if the memory needed exceeds MAXHISTMEM
+      defined in common/consts.py
+      Use *HIST with caution!!! (N.B.: the algorithm is NOT designed for large
+      problems).
+
+    INFO
+      Output, scalar.
+      INFO is the exit flag. It will be set to one of the following values defined in
+      common/infos.py:
+      SMALL_TR_RADIUS: the lower bound for the trust region radius is reached;
+      FTARGET_ACHIEVED: the target function value is reached;
+      MAXFUN_REACHED: the objective function has been evaluated MAXFUN times;
+      MAXTR_REACHED: the trust region iteration has been performed MAXTR times (MAXTR = 2*MAXFUN);
+      NAN_INF_X: NaN or Inf occurs in X;
+      DAMAGING_ROUNDING: rounding errors are becoming damaging.
+      #--------------------------------------------------------------------------#
+      The following case(s) should NEVER occur unless there is a bug.
+      NAN_INF_F: the objective function returns NaN or +Inf;
+      NAN_INF_MODEL: NaN or Inf occurs in the model;
+      TRSUBP_FAILED: a trust region step failed to reduce the model
+      #--------------------------------------------------------------------------#
+    """
+
+    # Local variables
+    solver = "COBYLA"
+    srname = "COBYLA"
+
+    # Sizes
+    mineq = len(bineq) if present(bineq) else 0
+    meq = len(beq) if present(beq) else 0
+    mxl = sum(xl > -BOUNDMAX) if present(xl) else 0
+    mxu = sum(xu < BOUNDMAX) if present(xu) else 0
+    mmm = mxu + mxl + 2*meq + mineq + m_nlcon
+    num_vars = len(x)
+
+    # Preconditions
+    if DEBUGGING:
+        assert m_nlcon >= 0, f'{srname} M_NLCON >= 0'
+        assert num_vars >= 1, f'{srname} N >= 1'
+
+        assert present(Aineq) == present(bineq), \
+            f'{srname} Aineq and Bineq are both present or both absent'
+        if (present(Aineq)):
+            assert Aineq.shape == (mineq, num_vars), f'{srname} SIZE(Aineq) == [Mineq, N]'
+
+        assert present(Aeq) == present(beq), \
+            f'{srname} Aeq and Beq are both present or both absent'
+        if (present(Aeq)):
+            assert Aeq.shape == (meq, num_vars), f'{srname} SIZE(Aeq) == [Meq, N]'
+
+        if (present(xl)):
+            assert len(xl) == num_vars, f'{srname} SIZE(XL) == N'
+        if (present(xu)):
+            assert len(xu) == num_vars, f'{srname} SIZE(XU) == N'
+
+
+        # N.B.: If NLCONSTR0 is present, then F0 must be present, and we assume that
+        # F(X0) = F0 even if F0 is NaN; if NLCONSTR0 is absent, then F0 must be either
+        # absent or NaN, both of which will be interpreted as F(X0) is not provided.
+        if present(nlconstr0):
+            assert present(f0), f'{srname} If NLCONSTR0 is present, then F0 is present'
+        if present(f0):
+            assert np.isnan(f0) or present(nlconstr0), \
+                f'{srname} If F0 is present and not NaN, then NLCONSTR0 is present'
+
+
+
+    # Exit if the size of NLCONSTR0 is inconsistent with M_NLCON.
+    if present(nlconstr0):
+        assert np.size(nlconstr0) == m_nlcon
+
+    # Read the inputs.
+
+    if xl is not None:
+      xl = copy(xl)
+      xl[np.isnan(xl)] = -BOUNDMAX
+      xl[xl < -BOUNDMAX] = -BOUNDMAX
+
+    if xu is not None:
+      xu = copy(xu)
+      xu[np.isnan(xu)] = BOUNDMAX
+      xu[xu > BOUNDMAX] = BOUNDMAX
+
+    # Wrap the linear and bound constraints into a single constraint: AMAT@X <= BVEC.
+    amat, bvec = get_lincon(Aeq, Aineq, beq, bineq, xl, xu)
+
+    # Create constraint vector
+    constr = np.zeros(mmm)
+
+    # Set [F_LOC, CONSTR_LOC] to [F(X0), CONSTR(X0)] after evaluating the latter if
+    # needed. In this way, COBYLB only needs one interface.
+    # N.B.: Due to the preconditions above, there are two possibilities for F0 and
+    # NLCONSTR0.
+    # If NLCONSTR0 is present, then F0 must be present, and we assume that F(X0) = F0
+    # even if F0 is NaN.
+    # If NLCONSTR0 is absent, then F0 must be either absent or NaN, both of which will
+    # be interpreted as F(X0) is not provided and we have to evaluate F(X0) and
+    # NLCONSTR(X0) now.
+    if (present(f0) and present(nlconstr0) and all(np.isfinite(x))):
+        f = moderatef(f0)
+        if amat is not None:
+          constr[:mmm - m_nlcon] = moderatec(matprod(amat, x) - bvec)
+        constr[mmm - m_nlcon:] = moderatec(nlconstr0)
+    else:
+        x = moderatex(x)
+        f, constr = evaluate(calcfc, x, m_nlcon, amat, bvec)
+        constr[:mmm - m_nlcon] = moderatec(constr[:mmm - m_nlcon])
+        # N.B.: Do NOT call FMSG, SAVEHIST, or SAVEFILT for the function/constraint evaluation at X0.
+        # They will be called during the initialization, which will read the function/constraint at X0.
+    cstrv = max(np.append(0, constr))
+
+
+    # If RHOBEG is present, use it; otherwise, RHOBEG takes the default value for
+    # RHOBEG, taking the value of RHOEND into account. Note that RHOEND is considered
+    # only if it is present and it is VALID (i.e., finite and positive). The other
+    # inputs are read similarly.
+    if present(rhobeg):
+        rhobeg = rhobeg
+    elif present(rhoend) and np.isfinite(rhoend) and rhoend > 0:
+        rhobeg = max(10 * rhoend, RHOBEG_DEFAULT)
+    else:
+        rhobeg = RHOBEG_DEFAULT
+
+    if present(rhoend):
+        rhoend = rhoend
+    elif rhobeg > 0:
+        rhoend = max(EPS, min(RHOEND_DEFAULT/RHOBEG_DEFAULT * rhobeg, RHOEND_DEFAULT))
+    else:
+        rhoend = RHOEND_DEFAULT
+
+    maxfun = maxfun if present(maxfun) else MAXFUN_DIM_DEFAULT * num_vars
+
+    if present(eta1):
+        eta1 = eta1
+    elif present(eta2) and 0 < eta2 < 1:
+        eta1 = max(EPS, eta2 / 7)
+    else:
+        eta1 = ETA1_DEFAULT
+
+    if present(eta2):
+        eta2 = eta2
+    elif 0 < eta1 < 1:
+        eta2 = (eta1 + 2) / 3
+    else:
+        eta2 = ETA2_DEFAULT
+
+    maxhist = (
+        maxhist
+        if present(maxhist)
+        else max(maxfun, num_vars + 2, MAXFUN_DIM_DEFAULT * num_vars)
+    )
+
+    # Preprocess the inputs in case some of them are invalid. It does nothing if all
+    # inputs are valid.
+    (
+        iprint,
+        maxfun,
+        maxhist,
+        ftarget,
+        rhobeg,
+        rhoend,
+        npt,  # Unused in COBYLA
+        maxfilt,
+        ctol,
+        cweight,
+        eta1,
+        eta2,
+        gamma1,
+        gamma2,
+        _x0,  # Unused in COBYLA
+    ) = preproc(
+        solver,
+        num_vars,
+        iprint,
+        maxfun,
+        maxhist,
+        ftarget,
+        rhobeg,
+        rhoend,
+        num_constraints=mmm,
+        maxfilt=maxfilt,
+        ctol=ctol,
+        cweight=cweight,
+        eta1=eta1,
+        eta2=eta2,
+        gamma1=gamma1,
+        gamma2=gamma2,
+        is_constrained=(mmm > 0),
+    )
+
+    # Further revise MAXHIST according to MAXHISTMEM, and allocate memory for the history.
+    # In MATLAB/Python/Julia/R implementation, we should simply set MAXHIST = MAXFUN and initialize
+    # CHIST = NaN(1, MAXFUN), CONHIST = NaN(M, MAXFUN), FHIST = NaN(1, MAXFUN), XHIST = NaN(N, MAXFUN)
+    # if they are requested; replace MAXFUN with 0 for the history that is not requested.
+    # prehist(maxhist, num_vars, present(xhist), xhist_loc, present(fhist), fhist_loc, &
+    #     & present(chist), chist_loc, m, present(conhist), conhist_loc)
+
+    # call cobylb, which performs the real calculations
+    x, f, constr, cstrv, nf, xhist, fhist, chist, conhist, info = cobylb(
+        calcfc,
+        iprint,
+        maxfilt,
+        maxfun,
+        amat,
+        bvec,
+        ctol,
+        cweight,
+        eta1,
+        eta2,
+        ftarget,
+        gamma1,
+        gamma2,
+        rhobeg,
+        rhoend,
+        constr,
+        f,
+        x,
+        maxhist,
+        callback
+    )
+
+    return COBYLAResult(x, f, constr, cstrv, nf, xhist, fhist, chist, conhist, info)
+
+
+def get_lincon(Aeq=None, Aineq=None, beq=None, bineq=None, xl=None, xu=None):
+    """
+    This subroutine wraps the linear and bound constraints into a single constraint:
+        AMAT*X <= BVEC.
+
+    N.B.:
+
+    LINCOA normalizes the linear constraints so that each constraint has a gradient
+    of norm 1. However, COBYLA does not do this.
+    """
+
+    # Sizes
+    if Aeq is not None:
+        num_vars = Aeq.shape[1]
+    elif Aineq is not None:
+        num_vars = Aineq.shape[1]
+    elif xl is not None:
+        num_vars = len(xl)
+    elif xu is not None:
+        num_vars = len(xu)
+    else:
+        return None, None
+
+    # Preconditions
+    if DEBUGGING:
+        assert Aineq is None or Aineq.shape == (len(bineq), num_vars)
+        assert Aeq is None or Aeq.shape == (len(beq), num_vars)
+        assert (xl is None or xu is None) or len(xl) == len(xu) == num_vars
+
+    #====================#
+    # Calculation starts #
+    #====================#
+
+    # Define the indices of the nontrivial bound constraints.
+    ixl = np.where(xl > -BOUNDMAX)[0] if xl is not None else None
+    ixu = np.where(xu < BOUNDMAX)[0] if xu is not None else None
+
+    # Wrap the linear constraints.
+    # The bound constraint XL <= X <= XU is handled as two constraints:
+    # -X <= -XL, X <= XU.
+    # The equality constraint Aeq*X = Beq is handled as two constraints:
+    # -Aeq*X <= -Beq, Aeq*X <= Beq.
+    # N.B.:
+    # 1. The treatment of the equality constraints is naive. One may choose to
+    #    eliminate them instead.
+    idmat = np.eye(num_vars)
+    amat = np.vstack([
+        -idmat[ixl, :] if ixl is not None else np.empty((0, num_vars)),
+        idmat[ixu, :] if ixu is not None else np.empty((0, num_vars)),
+        -Aeq if Aeq is not None else np.empty((0, num_vars)),
+        Aeq if Aeq is not None else np.empty((0, num_vars)),
+        Aineq if Aineq is not None else np.empty((0, num_vars))
+    ])
+    bvec = np.hstack([
+        -xl[ixl] if ixl is not None else np.empty(0),
+        xu[ixu] if ixu is not None else np.empty(0),
+        -beq if beq is not None else np.empty(0),
+        beq if beq is not None else np.empty(0),
+        bineq if bineq is not None else np.empty(0)
+    ])
+
+    amat = amat if amat.shape[0] > 0 else None
+    bvec = bvec if bvec.shape[0] > 0 else None
+
+    #==================#
+    # Calculation ends #
+    #==================#
+
+    # Postconditions
+    if DEBUGGING:
+        assert (amat is None and bvec is None) or amat.shape == (len(bvec), num_vars)
+
+    return amat, bvec
diff --git a/.venv/lib/python3.12/site-packages/scipy/_external/pyprima/cobyla/cobylb.py b/.venv/lib/python3.12/site-packages/scipy/_external/pyprima/cobyla/cobylb.py
new file mode 100644
index 0000000000000000000000000000000000000000..91012c3b3b2bca1c8827db3c4e2b7245735d23c2
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/_external/pyprima/cobyla/cobylb.py
@@ -0,0 +1,714 @@
+'''
+This module performs the major calculations of COBYLA.
+
+Translated from Zaikun Zhang's modern-Fortran reference implementation in PRIMA.
+
+Dedicated to late Professor M. J. D. Powell FRS (1936--2015).
+
+Python translation by Nickolai Belakovski.
+'''
+
+import numpy as np
+from ..common.checkbreak import checkbreak_con
+from ..common.consts import REALMAX, EPS, DEBUGGING, MIN_MAXFILT
+from ..common.infos import INFO_DEFAULT, MAXTR_REACHED, DAMAGING_ROUNDING, \
+                    SMALL_TR_RADIUS, CALLBACK_TERMINATE
+from ..common.evaluate import evaluate
+from ..common.history import savehist
+from ..common.linalg import isinv, matprod, inprod, norm, primasum, primapow2
+from ..common.message import fmsg, retmsg, rhomsg
+from ..common.ratio import redrat
+from ..common.redrho import redrho
+from ..common.selectx import savefilt, selectx
+from .update import updatepole, findpole, updatexfc
+from .geometry import setdrop_tr, geostep
+from .trustregion import trstlp, trrad
+from .initialize import initxfc, initfilt
+
+
+def cobylb(calcfc, iprint, maxfilt, maxfun, amat, bvec, ctol, cweight, eta1, eta2,
+           ftarget, gamma1, gamma2, rhobeg, rhoend, constr, f, x, maxhist, callback):
+    '''
+    This subroutine performs the actual computations of COBYLA.
+    '''
+
+    # Outputs
+    xhist = []
+    fhist = []
+    chist = []
+    conhist = []
+
+    # Local variables
+    solver = 'COBYLA'
+    A = np.zeros((np.size(x), np.size(constr))) # A contains the approximate gradient for the constraints
+    distsq = np.zeros(np.size(x) + 1)
+    # CPENMIN is the minimum of the penalty parameter CPEN for the L-infinity
+    # constraint violation in the merit function. Note that CPENMIN = 0 in Powell's
+    # implementation, which allows CPEN to be 0. Here, we take CPENMIN > 0 so that CPEN
+    # is always positive. This avoids the situation where PREREM becomes 0 when
+    # PREREF = 0 = CPEN. It brings two advantages as follows.
+    # 1. If the trust-region subproblem solver works correctly and the trust-region
+    #    center is not optimal for the subproblem, then PREREM > 0 is guaranteed. This
+    #    is because, in theory, PREREC >= 0 and MAX(PREREC, PREREF) > 0, and the
+    #    definition of CPEN in GETCPEN ensures that PREREM > 0.
+    # 2. There is no need to revise ACTREM and PREREM when CPEN = 0 and F = FVAL(N+1)
+    #    as in lines 312--314 of Powell's cobylb.f code. Powell's code revises ACTREM
+    #    to CVAL(N + 1) - CSTRV and PREREM to PREREC in this case, which is crucial for
+    #    feasibility problems.
+    cpenmin = EPS
+
+    # Sizes
+    m_lcon = np.size(bvec) if bvec is not None else 0
+    num_constraints = np.size(constr)
+    m_nlcon = num_constraints - m_lcon
+    num_vars = np.size(x)
+
+    # Preconditions
+    if DEBUGGING:
+        assert abs(iprint) <= 3
+        assert num_constraints >= m_lcon and m_lcon >= 0
+        assert num_vars >= 1
+        assert maxfun >= num_vars + 2
+        assert rhobeg >= rhoend and rhoend > 0
+        assert all(np.isfinite(x))
+        assert 0 <= eta1 <= eta2 < 1
+        assert 0 < gamma1 < 1 < gamma2
+        assert 0 <= ctol
+        assert 0 <= cweight
+        assert 0 <= maxhist <= maxfun
+        assert amat is None or np.shape(amat) == (m_lcon, num_vars)
+        assert min(MIN_MAXFILT, maxfun) <= maxfilt <= maxfun
+
+    #====================#
+    # Calculation starts #
+    #====================#
+
+    # Initialize SIM, FVAL, CONMAT, and CVAL, together with the history.
+    # After the initialization, SIM[:, NUM_VARS] holds the vertex of the initial
+    # simplex with the smallest function value (regardless of the constraint
+    # violation), and SIM[:, :NUM_VARS] holds the displacements from the other vertices
+    # to SIM[:, NUM_VARS]. FVAL, CONMAT, and CVAL hold the function values, constraint
+    # values, and constraint violations on the vertices in the order corresponding to
+    # SIM.
+    evaluated, conmat, cval, sim, simi, fval, nf, subinfo = initxfc(calcfc, iprint,
+      maxfun, constr, amat, bvec, ctol, f, ftarget, rhobeg, x,
+      xhist, fhist, chist, conhist, maxhist)
+
+    # Initialize the filter, including xfilt, ffilt, confilt, cfilt, and nfilt.
+    # N.B.: The filter is used only when selecting which iterate to return. It does not
+    # interfere with the iterations. COBYLA is NOT a filter method but a trust-region
+    # method based on an L-infinity merit function. Powell's implementation does not
+    # use a filter to select the iterate, possibly returning a suboptimal iterate.
+    cfilt = np.zeros(np.minimum(np.maximum(maxfilt, 1), maxfun))
+    confilt = np.zeros((np.size(constr), np.size(cfilt)))
+    ffilt = np.zeros(np.size(cfilt))
+    xfilt = np.zeros((np.size(x), np.size(cfilt)))
+    nfilt = initfilt(conmat, ctol, cweight, cval, fval, sim, evaluated, cfilt, confilt,
+                     ffilt, xfilt)
+
+    # Check whether to return due to abnormal cases that may occur during the initialization.
+    if subinfo != INFO_DEFAULT:
+        info = subinfo
+        # Return the best calculated values of the variables
+        # N.B: Selectx and findpole choose X by different standards, one cannot replace the other
+        kopt = selectx(ffilt[:nfilt], cfilt[:nfilt], cweight, ctol)
+        x = xfilt[:, kopt]
+        f = ffilt[kopt]
+        constr = confilt[:, kopt]
+        cstrv = cfilt[kopt]
+        # print a return message according to IPRINT.
+        retmsg(solver, info, iprint, nf, f, x, cstrv, constr)
+        # Postconditions
+        if DEBUGGING:
+            assert nf <= maxfun
+            assert np.size(x) == num_vars and not any(np.isnan(x))
+            assert not (np.isnan(f) or np.isposinf(f))
+            # assert np.size(xhist, 0) == n and np.size(xhist, 1) == maxxhist
+            # assert not any(np.isnan(xhist(:, 1:min(nf, maxxhist))))
+            # The last calculated X can be Inf (finite + finite can be Inf numerically).
+            # assert np.size(fhist) == maxfhist
+            # assert not any(np.isnan(fhist(1:min(nf, maxfhist))) or np.isposinf(fhist(1:min(nf, maxfhist))))
+            # assert np.size(conhist, 0) == m and np.size(conhist, 1) == maxconhist
+            # assert not any(np.isnan(conhist(:, 1:min(nf, maxconhist))) or np.isneginf(conhist(:, 1:min(nf, maxconhist))))
+            # assert np.size(chist) == maxchist
+            # assert not any(chist(1:min(nf, maxchist)) < 0 or np.isnan(chist(1:min(nf, maxchist))) or np.isposinf(chist(1:min(nf, maxchist))))
+            # nhist = minval([nf, maxfhist, maxchist])
+            # assert not any(isbetter(fhist(1:nhist), chist(1:nhist), f, cstrv, ctol))
+        return x, f, constr, cstrv, nf, xhist, fhist, chist, conhist, info
+
+
+    # Set some more initial values.
+    # We must initialize shortd, ratio, and jdrop_tr because these get defined on
+    # branches that are not guaranteed to be executed, but their values are used later.
+    # Our initialization of CPEN differs from Powell's in two ways. First, we use the
+    # ratio defined in (13) of Powell's COBYLA paper to initialize CPEN. Second, we
+    # impose CPEN >= CPENMIN > 0. Powell's code simply initializes CPEN to 0.
+    rho = rhobeg
+    delta = rhobeg
+    cpen = np.maximum(cpenmin, np.minimum(1.0E3, fcratio(conmat, fval)))  # Powell's code: CPEN = ZERO
+    shortd = False
+    ratio = -1
+    jdrop_tr = 0
+
+    # If DELTA <= GAMMA3*RHO after an update, we set DELTA to RHO. GAMMA3 must be less
+    # than GAMMA2. The reason is as follows. Imagine a very successful step with
+    # DNORM = the un-updated DELTA = RHO. The TRRAD will update DELTA to GAMMA2*RHO.
+    # If GAMMA3 >= GAMMA2, then DELTA will be reset to RHO, which is not reasonable as
+    # D is very successful. See paragraph two of Sec 5.2.5 in T. M. Ragonneau's thesis:
+    # "Model-Based Derivative-Free Optimization Methods and Software." According to
+    # test on 20230613, for COBYLA, this Powellful updating scheme of DELTA works
+    # slightly better than setting directly DELTA = max(NEW_DELTA, RHO).
+    gamma3 = np.maximum(1, np.minimum(0.75 * gamma2, 1.5))
+
+    # MAXTR is the maximal number of trust region iterations. Each trust-region
+    # iteration takes 1 or 2 function evaluations unless the trust-region step is short
+    # or the trust-region subproblem solver fails but the geometry step is not invoked.
+    # Thus the following MAXTR is unlikely to be reached.
+    maxtr = 10 * maxfun
+    info = MAXTR_REACHED
+
+    # Begin the iterative procedure
+    # After solving a trust-region subproblem, we use three boolean variables to
+    # control the workflow.
+    # SHORTD - Is the trust-region trial step too short to invoke # a function
+    #          evaluation?
+    # IMPROVE_GEO - Will we improve the model after the trust-region iteration? If yes,
+    #               a geometry step will be taken, corresponding to the "Branch (Delta)"
+    #               in the COBYLA paper.
+    # REDUCE_RHO - Will we reduce rho after the trust-region iteration?
+    # COBYLA never sets IMPROVE_GEO and REDUCE_RHO to True simultaneously.
+    for tr in range(maxtr):
+        # Increase the penalty parameter CPEN, if needed, so that
+        # PREREM = PREREF + CPEN * PREREC > 0.
+        # This is the first (out of two) update of CPEN, where CPEN increases or
+        # remains the same.
+        # N.B.: CPEN and the merit function PHI = FVAL + CPEN*CVAL are used in three
+        # places only.
+        # 1. In FINDPOLE/UPDATEPOLE, deciding the optimal vertex of the current simplex.
+        # 2. After the trust-region trial step, calculating the reduction ratio.
+        # 3. In GEOSTEP, deciding the direction of the geometry step.
+        # They do not appear explicitly in the trust-region subproblem, though the
+        # trust-region center (i.e. the current optimal vertex) is defined by them.
+        cpen = getcpen(amat, bvec, conmat, cpen, cval, delta, fval, rho, sim, simi)
+
+        # Switch the best vertex of the current simplex to SIM[:, NUM_VARS].
+        conmat, cval, fval, sim, simi, subinfo = updatepole(cpen, conmat, cval, fval,
+                                                            sim, simi)
+        # Check whether to exit due to damaging rounding in UPDATEPOLE.
+        if subinfo == DAMAGING_ROUNDING:
+            info = subinfo
+            break  # Better action to take? Geometry step, or simply continue?
+
+        # Does the interpolation set have adequate geometry? It affects improve_geo and
+        # reduce_rho.
+        adequate_geo = all(primasum(primapow2(sim[:, :num_vars]), axis=0) <= 4 * primapow2(delta))
+
+        # Calculate the linear approximations to the objective and constraint functions.
+        # N.B.: TRSTLP accesses A mostly by columns, so it is more reasonable to save A
+        # instead of A^T.
+        # Zaikun 2023108: According to a test on 2023108, calculating G and
+        # A(:, M_LCON+1:M) by solving the linear systems SIM^T*G = FVAL(1:N)-FVAL(N+1)
+        # and SIM^T*A = CONMAT(:, 1:N)-CONMAT(:, N+1) does not seem to improve or worsen
+        # the performance of COBYLA in terms of the number of function evaluations. The
+        # system was solved by SOLVE in LINALG_MOD based on a QR factorization of SIM
+        # (not necessarily a good algorithm). No preconditioning or scaling was used.
+        g = matprod((fval[:num_vars] - fval[num_vars]), simi)
+        A[:, :m_lcon] = amat.T if amat is not None else amat
+        A[:, m_lcon:] = matprod((conmat[m_lcon:, :num_vars] -
+                          np.tile(conmat[m_lcon:, num_vars], (num_vars, 1)).T), simi).T
+
+        # Calculate the trust-region trial step d. Note that d does NOT depend on cpen.
+        d = trstlp(A, -conmat[:, num_vars], delta, g)
+        dnorm = min(delta, norm(d))
+
+        # Is the trust-region trial step short? N.B.: we compare DNORM with RHO, not
+        # DELTA. Powell's code especially defines SHORTD by SHORTD = (DNORM < 0.5 *
+        # RHO). In our tests 1/10 seems to work better than 1/2 or 1/4, especially for
+        # linearly constrained problems. Note that LINCOA has a slightly more
+        # sophisticated way of defining SHORTD, taking into account whether D causes a
+        # change to the active set. Should we try the same here?
+        shortd = (dnorm <= 0.1 * rho)
+
+        # Predict the change to F (PREREF) and to the constraint violation (PREREC) due
+        # to D. We have the following in precise arithmetic. They may fail to hold due
+        # to rounding errors.
+        # 1. B[:NUM_CONSTRAINTS] = -CONMAT[:, NUM_VARS] and hence
+        # np.max(np.append(B[:NUM_CONSTRAINTS] - D@A[:, :NUM_CONSTRAINTS], 0)) is the
+        # L-infinity violation of the linearized constraints corresponding to D. When
+        # D=0, the violation is np.max(np.append(B[:NUM_CONSTRAINTS], 0)) =
+        # CVAL[NUM_VARS]. PREREC is the reduction of this violation achieved by D,
+        # which is nonnegative in theory; PREREC = 0 iff B[:NUM_CONSTRAINTS] <= 0, i.e.
+        # the trust-region center satisfies the linearized constraints.
+        # 2. PREREF may be negative or 0, but it is positive when PREREC = 0 and shortd
+        # is False
+        # 3. Due to 2, in theory, max(PREREC, PREREF) > 0 if shortd is False.
+        preref = -inprod(d, g)  # Can be negative
+        prerec = cval[num_vars] - np.max(np.append(0, conmat[:, num_vars] + matprod(d, A)))
+
+        # Evaluate PREREM, which is the predicted reduction in the merit function.
+        # In theory, PREREM >= 0 and it is 0 iff CPEN = 0 = PREREF. This may not be true
+        # numerically.
+        prerem = preref + cpen * prerec
+        trfail = not (prerem > 1.0E-6 * min(cpen, 1) * rho)
+
+        if shortd or trfail:
+            # Reduce DELTA if D is short or if D fails to render PREREM > 0. The latter
+            # can only happen due to rounding errors. This seems quite important for
+            # performance
+            delta *= 0.1
+            if delta <= gamma3 * rho:
+                delta = rho  # set delta to rho when it is close to or below
+        else:
+            # Calculate the next value of the objective and constraint functions.
+            # If X is close to one of the points in the interpolation set, then we do
+            # not evaluate the objective and constraints at X, assuming them to have
+            # the values at the closest point.
+            # N.B.: If this happens, do NOT include X into the filter, as F and CONSTR
+            # are inaccurate.
+            x = sim[:, num_vars] + d
+            distsq[num_vars] = primasum(primapow2(x - sim[:, num_vars]))
+            distsq[:num_vars] = primasum(primapow2(x.reshape(num_vars, 1) -
+                (sim[:, num_vars].reshape(num_vars, 1) + sim[:, :num_vars])), axis=0)
+            j = np.argmin(distsq)
+            if distsq[j] <= primapow2(1e-4 * rhoend):
+                f = fval[j]
+                constr = conmat[:, j]
+                cstrv = cval[j]
+            else:
+                # Evaluate the objective and constraints at X, taking care of possible
+                # inf/nan values.
+                f, constr = evaluate(calcfc, x, m_nlcon, amat, bvec)
+                cstrv = np.max(np.append(0, constr))
+                nf += 1
+                # Save X, F, CONSTR, CSTRV into the history.
+                savehist(maxhist, x, xhist, f, fhist, cstrv, chist, constr, conhist)
+                # Save X, F, CONSTR, CSTRV into the filter.
+                nfilt, cfilt, ffilt, xfilt, confilt = savefilt(cstrv, ctol, cweight, f,
+                                                               x, nfilt, cfilt, ffilt,
+                                                               xfilt, constr, confilt)
+
+            # Print a message about the function/constraint evaluation according to
+            # iprint
+            fmsg(solver, 'Trust region', iprint, nf, delta, f, x, cstrv, constr)
+
+            # Evaluate ACTREM, which is the actual reduction in the merit function
+            actrem = (fval[num_vars] + cpen * cval[num_vars]) - (f + cpen * cstrv)
+
+            # Calculate the reduction  ratio by redrat, which hands inf/nan carefully
+            ratio = redrat(actrem, prerem, eta1)
+
+            # Update DELTA. After this, DELTA < DNORM may hold.
+            # N.B.:
+            # 1. Powell's code uses RHO as the trust-region radius and updates it as
+            #    follows.
+            #    Reduce RHO to GAMMA1*RHO if ADEQUATE_GEO is TRUE and either SHORTD is
+            #    TRUE or RATIO < ETA1, and then revise RHO to RHOEND if its new value is
+            #    not more than GAMMA3*RHOEND; RHO remains unchanged in all other cases;
+            #    in particular, RHO is never increased.
+            # 2. Our implementation uses DELTA as the trust-region radius, while using
+            #    RHO as a lower bound for DELTA. DELTA is updated in a way that is
+            #    typical for trust-region methods, and it is revised to RHO if its new
+            #    value is not more than GAMMA3*RHO. RHO reflects the current resolution
+            #    of the algorithm; its update is essentially the same as the update of
+            #    RHO in Powell's code (see the definition of REDUCE_RHO below). Our
+            #    implementation aligns with UOBYQA/NEWUOA/BOBYQA/LINCOA and improves the
+            #    performance of COBYLA.
+            # 3. The same as Powell's code, we do not reduce RHO unless ADEQUATE_GEO is
+            #    TRUE. This is also how Powell updated RHO in
+            #    UOBYQA/NEWUOA/BOBYQA/LINCOA. What about we also use ADEQUATE_GEO ==
+            #    TRUE as a prerequisite for reducing DELTA? The argument would be that
+            #    the bad (small) value of RATIO may be because of a bad geometry (and
+            #    hence a bad model) rather than an improperly large DELTA, and it might
+            #    be good to try improving the geometry first without reducing DELTA.
+            #    However, according to a test on 20230206, it does not improve the
+            #    performance if we skip the update of DELTA when ADEQUATE_GEO is FALSE
+            #    and RATIO < 0.1. Therefore, we choose to update DELTA without checking
+            #    ADEQUATE_GEO.
+
+            delta = trrad(delta, dnorm, eta1, eta2, gamma1, gamma2, ratio)
+            if delta <= gamma3*rho:
+                delta = rho  # Set delta to rho when it is close to or below.
+
+            # Is the newly generated X better than the current best point?
+            ximproved = actrem > 0  # If ACTREM is NaN, then XIMPROVED should and will be False
+
+            # Set JDROP_TR to the index of the vertex to be replaced with X. JDROP_TR = 0 means there
+            # is no good point to replace, and X will not be included into the simplex; in this case,
+            # the geometry of the simplex likely needs improvement, which will be handled below.
+            jdrop_tr = setdrop_tr(ximproved, d, delta, rho, sim, simi)
+
+            # Update SIM, SIMI, FVAL, CONMAT, and CVAL so that SIM[:, JDROP_TR] is replaced with D.
+            # UPDATEXFC does nothing if JDROP_TR is None, as the algorithm decides to discard X.
+            sim, simi, fval, conmat, cval, subinfo = updatexfc(jdrop_tr, constr, cpen, cstrv, d, f, conmat, cval, fval, sim, simi)
+            # Check whether to break due to damaging rounding in UPDATEXFC
+            if subinfo == DAMAGING_ROUNDING:
+                info = subinfo
+                break  # Better action to take? Geometry step, or a RESCUE as in BOBYQA?
+
+            # Check whether to break due to maxfun, ftarget, etc.
+            subinfo = checkbreak_con(maxfun, nf, cstrv, ctol, f, ftarget, x)
+            if subinfo != INFO_DEFAULT:
+                info = subinfo
+                break
+        # End of if SHORTD or TRFAIL. The normal trust-region calculation ends.
+
+        # Before the next trust-region iteration, we possibly improve the geometry of the simplex or
+        # reduce RHO according to IMPROVE_GEO and REDUCE_RHO. Now we decide these indicators.
+        # N.B.: We must ensure that the algorithm does not set IMPROVE_GEO = True at infinitely many
+        # consecutive iterations without moving SIM[:, NUM_VARS] or reducing RHO. Otherwise, the algorithm
+        # will get stuck in repetitive invocations of GEOSTEP. This is ensured by the following facts:
+        # 1. If an iteration sets IMPROVE_GEO to True, it must also reduce DELTA or set DELTA to RHO.
+        # 2. If SIM[:, NUM_VARS] and RHO remain unchanged, then ADEQUATE_GEO will become True after at
+        # most NUM_VARS invocations of GEOSTEP.
+
+        # BAD_TRSTEP: Is the last trust-region step bad?
+        bad_trstep = shortd or trfail or ratio <= 0 or jdrop_tr is None
+        # IMPROVE_GEO: Should we take a geometry step to improve the geometry of the interpolation set?
+        improve_geo = bad_trstep and not adequate_geo
+        # REDUCE_RHO: Should we enhance the resolution by reducing rho?
+        reduce_rho = bad_trstep and adequate_geo and max(delta, dnorm) <= rho
+
+        # COBYLA never sets IMPROVE_GEO and REDUCE_RHO to True simultaneously.
+        # assert not (IMPROVE_GEO and REDUCE_RHO), 'IMPROVE_GEO or REDUCE_RHO are not both TRUE, COBYLA'
+
+        # If SHORTD or TRFAIL is True, then either IMPROVE_GEO or REDUCE_RHO is True unless ADEQUATE_GEO
+        # is True and max(DELTA, DNORM) > RHO.
+        # assert not (shortd or trfail) or (improve_geo or reduce_rho or (adequate_geo and max(delta, dnorm) > rho)), \
+        #     'If SHORTD or TRFAIL is TRUE, then either IMPROVE_GEO or REDUCE_RHO is TRUE unless ADEQUATE_GEO is TRUE and MAX(DELTA, DNORM) > RHO'
+
+        # Comments on BAD_TRSTEP:
+        # 1. Powell's definition of BAD_TRSTEP is as follows. The one used above seems to work better,
+        # especially for linearly constrained problems due to the factor TENTH (= ETA1).
+        # !bad_trstep = (shortd .or. actrem <= 0 .or. actrem < TENTH * prerem .or. jdrop_tr == 0)
+        # Besides, Powell did not check PREREM > 0 in BAD_TRSTEP, which is reasonable to do but has
+        # little impact upon the performance.
+        # 2. NEWUOA/BOBYQA/LINCOA would define BAD_TRSTEP, IMPROVE_GEO, and REDUCE_RHO as follows. Two
+        # different thresholds are used in BAD_TRSTEP. It outperforms Powell's version.
+        # !bad_trstep = (shortd .or. trfail .or. ratio <= eta1 .or. jdrop_tr == 0)
+        # !improve_geo = bad_trstep .and. .not. adequate_geo
+        # !bad_trstep = (shortd .or. trfail .or. ratio <= 0 .or. jdrop_tr == 0)
+        # !reduce_rho = bad_trstep .and. adequate_geo .and. max(delta, dnorm) <= rho
+        # 3. Theoretically, JDROP_TR > 0 when ACTREM > 0 (guaranteed by RATIO > 0). However, in Powell's
+        # implementation, JDROP_TR may be 0 even RATIO > 0 due to NaN. The modernized code has rectified
+        # this in the function SETDROP_TR. After this rectification, we can indeed simplify the
+        # definition of BAD_TRSTEP by removing the condition JDROP_TR == 0. We retain it for robustness.
+
+        # Comments on REDUCE_RHO:
+        # When SHORTD is TRUE, UOBYQA/NEWUOA/BOBYQA/LINCOA all set REDUCE_RHO to TRUE if the recent
+        # models are sufficiently accurate according to certain criteria. See the paragraph around (37)
+        # in the UOBYQA paper and the discussions about Box 14 in the NEWUOA paper. This strategy is
+        # crucial for the performance of the solvers. However, as of 20221111, we have not managed to
+        # make it work in COBYLA. As in NEWUOA, we recorded the errors of the recent models, and set
+        # REDUCE_RHO to true if they are small (e.g., ALL(ABS(MODERR_REC) <= 0.1 * MAXVAL(ABS(A))*RHO) or
+        # ALL(ABS(MODERR_REC) <= RHO**2)) when SHORTD is TRUE. It made little impact on the performance.
+
+
+        # Since COBYLA never sets IMPROVE_GEO and REDUCE_RHO to TRUE simultaneously, the following
+        # two blocks are exchangeable: IF (IMPROVE_GEO) ... END IF and IF (REDUCE_RHO) ... END IF.
+
+        # Improve the geometry of the simplex by removing a point and adding a new one.
+        # If the current interpolation set has acceptable geometry, then we skip the geometry step.
+        # The code has a small difference from Powell's original code here: If the current geometry
+        # is acceptable, then we will continue with a new trust-region iteration; however, at the
+        # beginning of the iteration, CPEN may be updated, which may alter the pole point SIM(:, N+1)
+        # by UPDATEPOLE; the quality of the interpolation point depends on SIM(:, N + 1), meaning
+        # that the same interpolation set may have good or bad geometry with respect to different
+        # "poles"; if the geometry turns out bad with the new pole, the original COBYLA code will
+        # take a geometry step, but our code here will NOT do it but continue to take a trust-region
+        # step. The argument is this: even if the geometry step is not skipped in the first place, the
+        # geometry may turn out bad again after the pole is altered due to an update to CPEN; should
+        # we take another geometry step in that case? If no, why should we do it here? Indeed, this
+        # distinction makes no practical difference for CUTEst problems with at most 100 variables
+        # and 5000 constraints, while the algorithm framework is simplified.
+        if improve_geo and not all(primasum(primapow2(sim[:, :num_vars]), axis=0) <= 4 * primapow2(delta)):
+            # Before the geometry step, updatepole has been called either implicitly by UPDATEXFC or
+            # explicitly after CPEN is updated, so that SIM[:, :NUM_VARS] is the optimal vertex.
+
+            # Decide a vertex to drop from the simplex. It will be replaced with SIM[:, NUM_VARS] + D to
+            # improve the geometry of the simplex.
+            # N.B.:
+            # 1. COBYLA never sets JDROP_GEO = num_vars.
+            # 2. The following JDROP_GEO comes from UOBYQA/NEWUOA/BOBYQA/LINCOA.
+            # 3. In Powell's original algorithm, the geometry of the simplex is considered acceptable
+            # iff the distance between any vertex and the pole is at most 2.1*DELTA, and the distance
+            # between any vertex and the opposite face of the simplex is at least 0.25*DELTA, as
+            # specified in (14) of the COBYLA paper. Correspondingly, JDROP_GEO is set to the index of
+            # the vertex with the largest distance to the pole provided that the distance is larger than
+            # 2.1*DELTA, or the vertex with the smallest distance to the opposite face of the simplex,
+            # in which case the distance must be less than 0.25*DELTA, as the current simplex does not
+            # have acceptable geometry (see (15)--(16) of the COBYLA paper). Once JDROP_GEO is set, the
+            # algorithm replaces SIM(:, JDROP_GEO) with D specified in (17) of the COBYLA paper, which
+            # is orthogonal to the face opposite to SIM(:, JDROP_GEO) and has a length of 0.5*DELTA,
+            # intending to improve the geometry of the simplex as per (14).
+            # 4. Powell's geometry-improving procedure outlined above has an intrinsic flaw: it may lead
+            # to infinite cycling, as was observed in a test on 20240320. In this test, the geometry-
+            # improving point introduced in the previous iteration was replaced with the trust-region
+            # trial point in the current iteration, which was then replaced with the same geometry-
+            # improving point in the next iteration, and so on. In this process, the simplex alternated
+            # between two configurations, neither of which had acceptable geometry. Thus RHO was never
+            # reduced, leading to infinite cycling. (N.B.: Our implementation uses DELTA as the trust
+            # region radius, with RHO being its lower bound. When the infinite cycling occurred in this
+            # test, DELTA = RHO and it could not be reduced due to the requirement that DELTA >= RHO.)
+            jdrop_geo = np.argmax(primasum(primapow2(sim[:, :num_vars]), axis=0), axis=0)
+
+            # Calculate the geometry step D.
+            delbar = delta/2
+            d = geostep(jdrop_geo, amat, bvec, conmat, cpen, cval, delbar, fval, simi)
+
+            # Calculate the next value of the objective and constraint functions.
+            # If X is close to one of the points in the interpolation set, then we do not evaluate the
+            # objective and constraints at X, assuming them to have the values at the closest point.
+            # N.B.:
+            # 1. If this happens, do NOT include X into the filter, as F and CONSTR are inaccurate.
+            # 2. In precise arithmetic, the geometry improving step ensures that the distance between X
+            # and any interpolation point is at least DELBAR, yet X may be close to them due to
+            # rounding. In an experiment with single precision on 20240317, X = SIM(:, N+1) occurred.
+            x = sim[:, num_vars] + d
+            distsq[num_vars] = primasum(primapow2(x - sim[:, num_vars]))
+            distsq[:num_vars] = primasum(primapow2(x.reshape(num_vars, 1) -
+                (sim[:, num_vars].reshape(num_vars, 1) + sim[:, :num_vars])), axis=0)
+            j = np.argmin(distsq)
+            if distsq[j] <= primapow2(1e-4 * rhoend):
+                f = fval[j]
+                constr = conmat[:, j]
+                cstrv = cval[j]
+            else:
+                # Evaluate the objective and constraints at X, taking care of possible
+                # inf/nan values.
+                f, constr = evaluate(calcfc, x, m_nlcon, amat, bvec)
+                cstrv = np.max(np.append(0, constr))
+                nf += 1
+                # Save X, F, CONSTR, CSTRV into the history.
+                savehist(maxhist, x, xhist, f, fhist, cstrv, chist, constr, conhist)
+                # Save X, F, CONSTR, CSTRV into the filter.
+                nfilt, cfilt, ffilt, xfilt, confilt = savefilt(cstrv, ctol, cweight, f,
+                                                               x, nfilt, cfilt, ffilt,
+                                                               xfilt, constr, confilt)
+
+            # Print a message about the function/constraint evaluation according to iprint
+            fmsg(solver, 'Geometry', iprint, nf, delta, f, x, cstrv, constr)
+            # Update SIM, SIMI, FVAL, CONMAT, and CVAL so that SIM(:, JDROP_GEO) is replaced with D.
+            sim, simi, fval, conmat, cval, subinfo = updatexfc(jdrop_geo, constr, cpen, cstrv, d, f, conmat, cval, fval, sim, simi)
+            # Check whether to break due to damaging rounding in UPDATEXFC
+            if subinfo == DAMAGING_ROUNDING:
+                info = subinfo
+                break  # Better action to take? Geometry step, or simply continue?
+
+            # Check whether to break due to maxfun, ftarget, etc.
+            subinfo = checkbreak_con(maxfun, nf, cstrv, ctol, f, ftarget, x)
+            if subinfo != INFO_DEFAULT:
+                info = subinfo
+                break
+        # end of if improve_geo. The procedure of improving the geometry ends.
+
+        # The calculations with the current RHO are complete. Enhance the resolution of the algorithm
+        # by reducing RHO; update DELTA and CPEN at the same time.
+        if reduce_rho:
+            if rho <= rhoend:
+                info = SMALL_TR_RADIUS
+                break
+            delta = max(0.5 * rho, redrho(rho, rhoend))
+            rho = redrho(rho, rhoend)
+            # THe second (out of two) updates of CPEN, where CPEN decreases or remains the same.
+            # Powell's code: cpen = min(cpen, fcratio(fval, conmat)), which may set CPEN to 0.
+            cpen = np.maximum(cpenmin, np.minimum(cpen, fcratio(conmat, fval)))
+            # Print a message about the reduction of rho according to iprint
+            rhomsg(solver, iprint, nf, fval[num_vars], rho, sim[:, num_vars], cval[num_vars], conmat[:, num_vars], cpen)
+            conmat, cval, fval, sim, simi, subinfo = updatepole(cpen, conmat, cval, fval, sim, simi)
+            # Check whether to break due to damaging rounding detected in updatepole
+            if subinfo == DAMAGING_ROUNDING:
+                info = subinfo
+                break  # Better action to take? Geometry step, or simply continue?
+        # End of if reduce_rho. The procedure of reducing RHO ends.
+        # Report the current best value, and check if user asks for early termination.
+        if callback:
+            terminate = callback(sim[:, num_vars], fval[num_vars], nf, tr, cval[num_vars], conmat[:, num_vars])
+            if terminate:
+                info = CALLBACK_TERMINATE
+                break
+    # End of for loop. The iterative procedure ends
+
+    # Return from the calculation, after trying the last trust-region step if it has not been tried yet.
+    # Ensure that D has not been updated after SHORTD == TRUE occurred, or the code below is incorrect.
+    x = sim[:, num_vars] + d
+    if (info == SMALL_TR_RADIUS and
+            shortd and
+            norm(x - sim[:, num_vars]) > 1.0E-3 * rhoend and
+            nf < maxfun):
+        # Zaikun 20230615: UPDATEXFC or UPDATEPOLE is not called since the last trust-region step. Hence
+        # SIM[:, NUM_VARS] remains unchanged. Otherwise SIM[:, NUM_VARS] + D would not make sense.
+        f, constr = evaluate(calcfc, x, m_nlcon, amat, bvec)
+        cstrv = np.max(np.append(0, constr))
+        nf += 1
+        savehist(maxhist, x, xhist, f, fhist, cstrv, chist, constr, conhist)
+        nfilt, cfilt, ffilt, xfilt, confilt = savefilt(cstrv, ctol, cweight, f, x, nfilt, cfilt, ffilt, xfilt, constr, confilt)
+        # Zaikun 20230512: DELTA has been updated. RHO is only indicative here. TO BE IMPROVED.
+        fmsg(solver, 'Trust region', iprint, nf, rho, f, x, cstrv, constr)
+
+    # Return the best calculated values of the variables
+    # N.B.: SELECTX and FINDPOLE choose X by different standards, one cannot replace the other.
+    kopt = selectx(ffilt[:nfilt], cfilt[:nfilt], max(cpen, cweight), ctol)
+    x = xfilt[:, kopt]
+    f = ffilt[kopt]
+    constr = confilt[:, kopt]
+    cstrv = cfilt[kopt]
+
+    # Print a return message according to IPRINT.
+    retmsg(solver, info, iprint, nf, f, x, cstrv, constr)
+    return x, f, constr, cstrv, nf, xhist, fhist, chist, conhist, info
+
+
+
+def getcpen(amat, bvec, conmat, cpen, cval, delta, fval, rho, sim, simi):
+    '''
+    This function gets the penalty parameter CPEN so that PREREM = PREREF + CPEN * PREREC > 0.
+    See the discussions around equation (9) of the COBYLA paper.
+    '''
+
+    # Even after nearly all of the pycutest problems were showing nearly bit for bit
+    # identical results between Python and the Fortran bindings, HS102 was still off by
+    # more than machine epsilon. It turned out to be due to the fact that getcpen was
+    # modifying fval, among other. It just goes to show that even when you're nearly
+    # perfect, you can still have non trivial bugs.
+    conmat = conmat.copy()
+    cval = cval.copy()
+    fval = fval.copy()
+    sim = sim.copy()
+    simi = simi.copy()
+
+    # Intermediate variables
+    A = np.zeros((np.size(sim, 0), np.size(conmat, 0)))
+    itol = 1
+
+    # Sizes
+    m_lcon = np.size(bvec) if bvec is not None else 0
+    num_constraints = np.size(conmat, 0)
+    num_vars = np.size(sim, 0)
+
+    # Preconditions
+    if DEBUGGING:
+        assert num_constraints >= 0
+        assert num_vars >= 1
+        assert cpen > 0
+        assert np.size(conmat, 0) == num_constraints and np.size(conmat, 1) == num_vars + 1
+        assert not (np.isnan(conmat) | np.isneginf(conmat)).any()
+        assert np.size(cval) == num_vars + 1 and \
+            not any(cval < 0 | np.isnan(cval) | np.isposinf(cval))
+        assert np.size(fval) == num_vars + 1 and not any(np.isnan(fval) | np.isposinf(fval))
+        assert np.size(sim, 0) == num_vars and np.size(sim, 1) == num_vars + 1
+        assert np.isfinite(sim).all()
+        assert all(np.max(abs(sim[:, :num_vars]), axis=0) > 0)
+        assert np.size(simi, 0) == num_vars and np.size(simi, 1) == num_vars
+        assert np.isfinite(simi).all()
+        assert isinv(sim[:, :num_vars], simi, itol)
+        assert delta >= rho and rho > 0
+
+    #====================#
+    # Calculation starts #
+    #====================#
+
+    # Initialize INFO which is needed in the postconditions
+    info = INFO_DEFAULT
+
+    # Increase CPEN if necessary to ensure PREREM > 0. Branch back for the next loop
+    # if this change alters the optimal vertex of the current simplex.
+    # Note the following:
+    # 1. In each loop, CPEN is changed only if PREREC > 0 > PREREF, in which case
+    #    PREREM is guaranteed positive after the update. Note that PREREC >= 0 and
+    #    max(PREREC, PREREF) > 0 in theory. If this holds numerically as well then CPEN
+    #    is not changed only if PREREC = 0 or PREREF >= 0, in which case PREREM is
+    #    currently positive, explaining why CPEN needs no update.
+    # 2. Even without an upper bound for the loop counter, the loop can occur at most
+    #    NUM_VARS+1 times. This is because the update of CPEN does not decrease CPEN,
+    #    and hence it can make vertex J (J <= NUM_VARS) become the new optimal vertex
+    #    only if CVAL[J] is less than CVAL[NUM_VARS], which can happen at most NUM_VARS
+    #    times. See the paragraph below (9) in the COBYLA paper. After the "correct"
+    #    optimal vertex is found, one more loop is needed to calculate CPEN, and hence
+    #    the loop can occur at most NUM_VARS+1 times.
+    for iter in range(num_vars + 1):
+        # Switch the best vertex of the current simplex to SIM[:, NUM_VARS]
+        conmat, cval, fval, sim, simi, info = updatepole(cpen, conmat, cval, fval, sim,
+                                                         simi)
+        # Check whether to exit due to damaging rounding in UPDATEPOLE
+        if info == DAMAGING_ROUNDING:
+            break
+
+        # Calculate the linear approximations to the objective and constraint functions.
+        g = matprod(fval[:num_vars] - fval[num_vars], simi)
+        A[:, :m_lcon] = amat.T if amat is not None else amat
+        A[:, m_lcon:] = matprod((conmat[m_lcon:, :num_vars] -
+                          np.tile(conmat[m_lcon:, num_vars], (num_vars, 1)).T), simi).T
+
+        # Calculate the trust-region trial step D. Note that D does NOT depend on CPEN.
+        d = trstlp(A, -conmat[:, num_vars], delta, g)
+
+        # Predict the change to F (PREREF) and to the constraint violation (PREREC) due
+        # to D.
+        preref = -inprod(d, g)  # Can be negative
+        prerec = cval[num_vars] - np.max(np.append(0, conmat[:, num_vars] + matprod(d, A)))
+
+        # PREREC <= 0 or PREREF >=0 or either is NaN
+        if not (prerec > 0 and preref < 0):
+            break
+
+        # Powell's code defines BARMU = -PREREF / PREREC, and CPEN is increased to
+        # 2*BARMU if and only if it is currently less than 1.5*BARMU, a very
+        # "Powellful" scheme. In our implementation, however, we set CPEN directly to
+        # the maximum between its current value and 2*BARMU while handling possible
+        # overflow. The simplifies the scheme without worsening the performance of
+        # COBYLA.
+        cpen = max(cpen, min(-2 * preref / prerec, REALMAX))
+
+        if findpole(cpen, cval, fval) == num_vars:
+            break
+
+    #==================#
+    # Calculation ends #
+    #==================#
+
+    # Postconditions
+    if DEBUGGING:
+        assert cpen >= cpen and cpen > 0
+        assert preref + cpen * prerec > 0 or info == DAMAGING_ROUNDING or \
+            not (prerec >= 0 and np.maximum(prerec, preref) > 0) or not np.isfinite(preref)
+
+    return cpen
+
+
+def fcratio(conmat, fval):
+    '''
+    This function calculates the ratio between the "typical change" of F and that of CONSTR.
+    See equations (12)-(13) in Section 3 of the COBYLA paper for the definition of the ratio.
+    '''
+
+    # Preconditions
+    if DEBUGGING:
+        assert np.size(fval) >= 1
+        assert np.size(conmat, 1) == np.size(fval)
+
+    #====================#
+    # Calculation starts #
+    #====================#
+
+    cmin = np.min(-conmat, axis=1)
+    cmax = np.max(-conmat, axis=1)
+    fmin = min(fval)
+    fmax = max(fval)
+    if any(cmin < 0.5 * cmax) and fmin < fmax:
+        denom = np.min(np.maximum(cmax, 0) - cmin, where=cmin < 0.5 * cmax, initial=np.inf)
+        # Powell mentioned the following alternative in section 4 of his COBYLA paper. According to a test
+        # on 20230610, it does not make much difference to the performance.
+        # denom = np.max(max(*cmax, 0) - cmin, mask=(cmin < 0.5 * cmax))
+        r = (fmax - fmin) / denom
+    else:
+        r = 0
+
+    #==================#
+    # Calculation ends #
+    #==================#
+
+    # Postconditions
+    if DEBUGGING:
+        assert r >= 0
+
+    return r
diff --git a/.venv/lib/python3.12/site-packages/scipy/_external/pyprima/cobyla/geometry.py b/.venv/lib/python3.12/site-packages/scipy/_external/pyprima/cobyla/geometry.py
new file mode 100644
index 0000000000000000000000000000000000000000..c03e5626696f5a40939792b6448972d304b31d71
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/_external/pyprima/cobyla/geometry.py
@@ -0,0 +1,226 @@
+'''
+This module contains subroutines concerning the geometry-improving of the interpolation set.
+
+Translated from Zaikun Zhang's modern-Fortran reference implementation in PRIMA.
+
+Dedicated to late Professor M. J. D. Powell FRS (1936--2015).
+
+Python translation by Nickolai Belakovski.
+'''
+
+from ..common.consts import DEBUGGING
+from ..common.linalg import isinv, matprod, inprod, norm, primasum, primapow2
+import numpy as np
+
+
+def setdrop_tr(ximproved, d, delta, rho, sim, simi):
+    '''
+    This function finds (the index) of a current interpolation point to be replaced with
+    the trust-region trial point. See (19)-(22) of the COBYLA paper.
+    N.B.:
+    1. If XIMPROVED == True, then JDROP > 0 so that D is included into XPT. Otherwise,
+       it is a bug.
+    2. COBYLA never sets JDROP = NUM_VARS
+    TODO: Check whether it improves the performance if JDROP = NUM_VARS is allowed when
+    XIMPROVED is True. Note that UPDATEXFC should be revised accordingly.
+    '''
+
+    # Local variables
+    itol = 0.1
+
+    # Sizes
+    num_vars = np.size(sim, 0)
+
+    # Preconditions
+    if DEBUGGING:
+        assert num_vars >= 1
+        assert np.size(d) == num_vars and all(np.isfinite(d))
+        assert delta >= rho and rho > 0
+        assert np.size(sim, 0) == num_vars and np.size(sim, 1) == num_vars + 1
+        assert np.isfinite(sim).all()
+        assert all(np.max(abs(sim[:, :num_vars]), axis=0) > 0)
+        assert np.size(simi, 0) == num_vars and np.size(simi, 1) == num_vars
+        assert np.isfinite(simi).all()
+        assert isinv(sim[:, :num_vars], simi, itol)
+
+    #====================#
+    # Calculation starts #
+    #====================#
+
+    # -------------------------------------------------------------------------------------------------- #
+    #  The following code is Powell's scheme for defining JDROP.
+    # -------------------------------------------------------------------------------------------------- #
+    # ! JDROP = 0 by default. It cannot be removed, as JDROP may not be set below in some cases (e.g.,
+    # ! when XIMPROVED == FALSE, MAXVAL(ABS(SIMID)) <= 1, and MAXVAL(VETA) <= EDGMAX).
+    # jdrop = 0
+    #
+    # ! SIMID(J) is the value of the J-th Lagrange function at D. It is the counterpart of VLAG in UOBYQA
+    # ! and DEN in NEWUOA/BOBYQA/LINCOA, but it excludes the value of the (N+1)-th Lagrange function.
+    # simid = matprod(simi, d)
+    # if (any(abs(simid) > 1) .or. (ximproved .and. any(.not. is_nan(simid)))) then
+    #     jdrop = int(maxloc(abs(simid), mask=(.not. is_nan(simid)), dim=1), kind(jdrop))
+    #     !!MATLAB: [~, jdrop] = max(simid, [], 'omitnan');
+    # end if
+    #
+    # ! VETA(J) is the distance from the J-th vertex of the simplex to the best vertex, taking the trial
+    # ! point SIM(:, N+1) + D into account.
+    # if (ximproved) then
+    #     veta = sqrt(sum((sim(:, 1:n) - spread(d, dim=2, ncopies=n))**2, dim=1))
+    #     !!MATLAB: veta = sqrt(sum((sim(:, 1:n) - d).^2));  % d should be a column! Implicit expansion
+    # else
+    #     veta = sqrt(sum(sim(:, 1:n)**2, dim=1))
+    # end if
+    #
+    # ! VSIG(J) (J=1, .., N) is the Euclidean distance from vertex J to the opposite face of the simplex.
+    # vsig = ONE / sqrt(sum(simi**2, dim=2))
+    # sigbar = abs(simid) * vsig
+    #
+    # ! The following JDROP will overwrite the previous one if its premise holds.
+    # mask = (veta > factor_delta * delta .and. (sigbar >= factor_alpha * delta .or. sigbar >= vsig))
+    # if (any(mask)) then
+    #     jdrop = int(maxloc(veta, mask=mask, dim=1), kind(jdrop))
+    #     !!MATLAB: etamax = max(veta(mask)); jdrop = find(mask & ~(veta < etamax), 1, 'first');
+    # end if
+    #
+    # ! Powell's code does not include the following instructions. With Powell's code, if SIMID consists
+    # ! of only NaN, then JDROP can be 0 even when XIMPROVED == TRUE (i.e., D reduces the merit function).
+    # ! With the following code, JDROP cannot be 0 when XIMPROVED == TRUE, unless VETA is all NaN, which
+    # ! should not happen if X0 does not contain NaN, the trust-region/geometry steps never contain NaN,
+    # ! and we exit once encountering an iterate containing Inf (due to overflow).
+    # if (ximproved .and. jdrop <= 0) then  ! Write JDROP <= 0 instead of JDROP == 0 for robustness.
+    #     jdrop = int(maxloc(veta, mask=(.not. is_nan(veta)), dim=1), kind(jdrop))
+    #     !!MATLAB: [~, jdrop] = max(veta, [], 'omitnan');
+    # end if
+    # -------------------------------------------------------------------------------------------------- #
+    #  Powell's scheme ends here.
+    # -------------------------------------------------------------------------------------------------- #
+
+    # The following definition of JDROP is inspired by SETDROP_TR in UOBYQA/NEWUOA/BOBYQA/LINCOA.
+    # It is simpler and works better than Powell's scheme. Note that we allow JDROP to be NUM_VARS+1 if
+    # XIMPROVED is True, whereas Powell's code does not.
+    # See also (4.1) of Scheinberg-Toint-2010: Self-Correcting Geometry in Model-Based Algorithms for
+    # Derivative-Free Unconstrained Optimization, which refers to the strategy here as the "combined
+    # distance/poisedness criteria".
+
+    # DISTSQ[j] is the square of the distance from the jth vertex of the simplex to get "best" point so
+    # far, taking the trial point SIM[:, NUM_VARS] + D into account.
+    distsq = np.zeros(np.size(sim, 1))
+    if ximproved:
+        distsq[:num_vars] = primasum(primapow2(sim[:, :num_vars] - np.tile(d, (num_vars, 1)).T), axis=0)
+        distsq[num_vars] = primasum(d*d)
+    else:
+        distsq[:num_vars] = primasum(primapow2(sim[:, :num_vars]), axis=0)
+        distsq[num_vars] = 0
+
+    weight = np.maximum(1, distsq / primapow2(np.maximum(rho, delta/10)))  # Similar to Powell's NEWUOA code.
+
+    # Other possible definitions of weight. They work almost the same as the one above.
+    # weight = distsq  # Similar to Powell's LINCOA code, but WRONG. See comments in LINCOA/geometry.f90.
+    # weight = max(1, max(25 * distsq / delta**2))  # Similar to Powell's BOBYQA code, works well.
+    # weight = max(1, max(10 * distsq / delta**2))
+    # weight = max(1, max(1e2 * distsq / delta**2))
+    # weight = max(1, max(distsq / rho**2))  ! Similar to Powell's UOBYQA
+
+    # If 0 <= j < NUM_VARS, SIMID[j] is the value of the jth Lagrange function at D; the value of the
+    # (NUM_VARS+1)th Lagrange function is 1 - sum(SIMID). [SIMID, 1 - sum(SIMID)] is the counterpart of
+    # VLAG in UOBYQA and DEN in NEWUOA/BOBYQA/LINCOA.
+    simid = matprod(simi, d)
+    score = weight * abs(np.array([*simid, 1 - primasum(simid)]))
+
+    # If XIMPROVED = False (D does not render a better X), set SCORE[NUM_VARS] = -1 to avoid JDROP = NUM_VARS.
+    if not ximproved:
+        score[num_vars] = -1
+
+    # score[j] is NaN implies SIMID[j] is NaN, but we want abs(SIMID) to be big. So we
+    # exclude such j.
+    score[np.isnan(score)] = -1
+
+    jdrop = None
+    # The following if statement works a bit better than
+    # `if any(score > 1) or (any(score > 0) and ximproved)` from Powell's UOBYQA and
+    # NEWUOA code.
+    if any(score > 0):  # Powell's BOBYQA and LINCOA code.
+        jdrop = np.argmax(score)
+
+    if (ximproved and jdrop is None):
+        jdrop = np.argmax(distsq)
+
+    #==================#
+    # Calculation ends #
+    #==================#
+
+    # Postconditions
+    if DEBUGGING:
+        assert jdrop is None or (0 <= jdrop < num_vars + 1)
+        assert jdrop <= num_vars or ximproved
+        assert jdrop >= 0 or not ximproved
+        # JDROP >= 1 when XIMPROVED = TRUE unless NaN occurs in DISTSQ, which should not happen if the
+        # starting point does not contain NaN and the trust-region/geometry steps never contain NaN.
+
+    return jdrop
+
+
+
+
+def geostep(jdrop, amat, bvec, conmat, cpen, cval, delbar, fval, simi):
+    '''
+    This function calculates a geometry step so that the geometry of the interpolation set is improved
+    when SIM[: JDROP_GEO] is replaced with SIM[:, NUM_VARS] + D. See (15)--(17) of the COBYLA paper.
+    '''
+
+    # Sizes
+    m_lcon = np.size(bvec, 0) if bvec is not None else 0
+    num_constraints = np.size(conmat, 0)
+    num_vars = np.size(simi, 0)
+
+    # Preconditions
+    if DEBUGGING:
+        assert num_constraints >= m_lcon >= 0
+        assert num_vars >= 1
+        assert delbar > 0
+        assert cpen > 0
+        assert np.size(simi, 0) == num_vars and np.size(simi, 1) == num_vars
+        assert np.isfinite(simi).all()
+        assert np.size(fval) == num_vars + 1 and not any(np.isnan(fval) | np.isposinf(fval))
+        assert np.size(conmat, 0) == num_constraints and np.size(conmat, 1) == num_vars + 1
+        assert not np.any(np.isnan(conmat) | np.isposinf(conmat))
+        assert np.size(cval) == num_vars + 1 and not any(cval < 0 | np.isnan(cval) | np.isposinf(cval))
+        assert 0 <= jdrop < num_vars
+
+    #====================#
+    # Calculation starts #
+    #====================#
+
+    # SIMI[JDROP, :] is a vector perpendicular to the face of the simplex to the opposite of vertex
+    # JDROP. Set D to the vector in this direction and with length DELBAR.
+    d = simi[jdrop, :]
+    d = delbar * (d / norm(d))
+
+    # The code below chooses the direction of D according to an approximation of the merit function.
+    # See (17) of the COBYLA paper and  line 225 of Powell's cobylb.f.
+
+    # Calculate the coefficients of the linear approximations to the objective and constraint functions.
+    # N.B.: CONMAT and SIMI have been updated after the last trust-region step, but G and A have not.
+    # So we cannot pass G and A from outside.
+    g = matprod(fval[:num_vars] - fval[num_vars], simi)
+    A = np.zeros((num_vars, num_constraints))
+    A[:, :m_lcon] = amat.T if amat is not None else amat
+    A[:, m_lcon:] = matprod((conmat[m_lcon:, :num_vars] -
+                          np.tile(conmat[m_lcon:, num_vars], (num_vars, 1)).T), simi).T
+    # CVPD and CVND are the predicted constraint violation of D and -D by the linear models.
+    cvpd = np.max(np.append(0, conmat[:, num_vars] + matprod(d, A)))
+    cvnd = np.max(np.append(0, conmat[:, num_vars] - matprod(d, A)))
+    if -inprod(d, g) + cpen * cvnd < inprod(d, g) + cpen * cvpd:
+        d *= -1
+
+    #==================#
+    # Calculation ends #
+    #==================#
+
+    # Postconditions
+    if DEBUGGING:
+        assert np.size(d) == num_vars and all(np.isfinite(d))
+        # In theory, ||S|| == DELBAR, which may be false due to rounding, but not too far.
+        # It is crucial to ensure that the geometry step is nonzero, which holds in theory.
+        assert 0.9 * delbar < np.linalg.norm(d) <= 1.1 * delbar
+    return d
diff --git a/.venv/lib/python3.12/site-packages/scipy/_external/pyprima/cobyla/initialize.py b/.venv/lib/python3.12/site-packages/scipy/_external/pyprima/cobyla/initialize.py
new file mode 100644
index 0000000000000000000000000000000000000000..c8c3da8e2c7b0ec09bb30b7bf67ec55238022a94
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/_external/pyprima/cobyla/initialize.py
@@ -0,0 +1,215 @@
+'''
+This module contains subroutines for initialization.
+
+Translated from Zaikun Zhang's modern-Fortran reference implementation in PRIMA.
+
+Dedicated to late Professor M. J. D. Powell FRS (1936--2015).
+
+Python translation by Nickolai Belakovski.
+'''
+
+from ..common.checkbreak import checkbreak_con
+from ..common.consts import DEBUGGING, REALMAX
+from ..common.infos import INFO_DEFAULT
+from ..common.evaluate import evaluate
+from ..common.history import savehist
+from ..common.linalg import inv
+from ..common.message import fmsg
+from ..common.selectx import savefilt
+
+import numpy as np
+
+def initxfc(calcfc, iprint, maxfun, constr0, amat, bvec, ctol, f0, ftarget, rhobeg, x0,
+            xhist, fhist, chist, conhist, maxhist):
+    '''
+    This subroutine does the initialization concerning X, function values, and
+    constraints.
+    '''
+
+    # Local variables
+    solver = 'COBYLA'
+    srname = "INITIALIZE"
+
+    # Sizes
+    num_constraints = np.size(constr0)
+    m_lcon = np.size(bvec) if bvec is not None else 0
+    m_nlcon = num_constraints - m_lcon
+    num_vars = np.size(x0)
+
+    # Preconditions
+    if DEBUGGING:
+        assert num_constraints >= 0, f'M >= 0 {srname}'
+        assert num_vars >= 1, f'N >= 1 {srname}'
+        assert abs(iprint) <= 3, f'IPRINT is 0, 1, -1, 2, -2, 3, or -3 {srname}'
+        # assert conmat.shape == (num_constraints , num_vars + 1), f'CONMAT.shape = [M, N+1] {srname}'
+        # assert cval.size == num_vars + 1, f'CVAL.size == N+1 {srname}'
+        # assert maxchist * (maxchist - maxhist) == 0, f'CHIST.shape == 0 or MAXHIST {srname}'
+        # assert conhist.shape[0] == num_constraints and maxconhist * (maxconhist - maxhist) == 0, 'CONHIST.shape[0] == num_constraints, SIZE(CONHIST, 2) == 0 or MAXHIST {srname)}'
+        # assert maxfhist * (maxfhist - maxhist) == 0, f'FHIST.shape == 0 or MAXHIST {srname}'
+        # assert xhist.shape[0] == num_vars and maxxhist * (maxxhist - maxhist) == 0, 'XHIST.shape[0] == N, SIZE(XHIST, 2) == 0 or MAXHIST {srname)}'
+        assert all(np.isfinite(x0)), f'X0 is finite {srname}'
+        assert rhobeg > 0, f'RHOBEG > 0 {srname}'
+
+    #====================#
+    # Calculation starts #
+    #====================#
+
+    # Initialize info to the default value. At return, a value different from this
+    # value will indicate an abnormal return
+    info = INFO_DEFAULT
+
+    # Initialize the simplex. It will be revised during the initialization.
+    sim = np.eye(num_vars, num_vars+1) * rhobeg
+    sim[:, num_vars] = x0
+
+    # Initialize the matrix simi. In most cases simi is overwritten, but not always.
+    simi = np.eye(num_vars) / rhobeg
+
+    # evaluated[j] = True iff the function/constraint of SIM[:, j] has been evaluated.
+    evaluated = np.zeros(num_vars+1, dtype=bool)
+
+    # Initialize fval
+    fval = np.zeros(num_vars+1) + REALMAX
+    cval = np.zeros(num_vars+1) + REALMAX
+    conmat = np.zeros((num_constraints, num_vars+1)) + REALMAX
+
+
+    for k in range(num_vars + 1):
+        x = sim[:, num_vars].copy()
+        # We will evaluate F corresponding to SIM(:, J).
+        if k == 0:
+            j = num_vars
+            f = f0
+            constr = constr0
+        else:
+            j = k - 1
+            x[j] += rhobeg
+            f, constr = evaluate(calcfc, x, m_nlcon, amat, bvec)
+        cstrv = np.max(np.append(0, constr))
+
+        # Print a message about the function/constraint evaluation according to IPRINT.
+        fmsg(solver, 'Initialization', iprint, k, rhobeg, f, x, cstrv, constr)
+
+        # Save X, F, CONSTR, CSTRV into the history.
+        savehist(maxhist, x, xhist, f, fhist, cstrv, chist, constr, conhist)
+
+        # Save F, CONSTR, and CSTRV to FVAL, CONMAT, and CVAL respectively.
+        evaluated[j] = True
+        fval[j] = f
+        conmat[:, j] = constr
+        cval[j] = cstrv
+
+        # Check whether to exit.
+        subinfo = checkbreak_con(maxfun, k, cstrv, ctol, f, ftarget, x)
+        if subinfo != INFO_DEFAULT:
+            info = subinfo
+            break
+
+        # Exchange the new vertex of the initial simplex with the optimal vertex if necessary.
+        # This is the ONLY part that is essentially non-parallel.
+        if j < num_vars and fval[j] < fval[num_vars]:
+            fval[j], fval[num_vars] = fval[num_vars], fval[j]
+            cval[j], cval[num_vars] = cval[num_vars], cval[j]
+            conmat[:, [j, num_vars]] = conmat[:, [num_vars, j]]
+            sim[:, num_vars] = x
+            sim[j, :j+1] = -rhobeg  # SIM[:, :j+1] is lower triangular
+
+    nf = np.count_nonzero(evaluated)
+
+    if evaluated.all():
+        # Initialize SIMI to the inverse of SIM[:, :num_vars]
+        simi = inv(sim[:, :num_vars])
+
+    #==================#
+    # Calculation ends #
+    #==================#
+
+    # Postconditions
+    if DEBUGGING:
+        assert nf <= maxfun, f'NF <= MAXFUN {srname}'
+        assert evaluated.size == num_vars + 1, f'EVALUATED.size == Num_vars + 1 {srname}'
+        # assert chist.size == maxchist, f'CHIST.size == MAXCHIST {srname}'
+        # assert conhist.shape== (num_constraints, maxconhist), f'CONHIST.shape == [M, MAXCONHIST] {srname}'
+        assert conmat.shape == (num_constraints, num_vars + 1), f'CONMAT.shape = [M, N+1] {srname}'
+        assert not (np.isnan(conmat).any() or np.isneginf(conmat).any()), f'CONMAT does not contain NaN/-Inf {srname}'
+        assert cval.size == num_vars + 1 and not (any(cval < 0) or any(np.isnan(cval)) or any(np.isposinf(cval))), f'CVAL.shape == Num_vars+1 and CVAL does not contain negative values or NaN/+Inf {srname}'
+        # assert fhist.shape == maxfhist, f'FHIST.shape == MAXFHIST {srname}'
+        # assert maxfhist * (maxfhist - maxhist) == 0, f'FHIST.shape == 0 or MAXHIST {srname}'
+        assert fval.size == num_vars + 1 and not (any(np.isnan(fval)) or any(np.isposinf(fval))), f'FVAL.shape == Num_vars+1 and FVAL is not NaN/+Inf {srname}'
+        # assert xhist.shape == (num_vars, maxxhist), f'XHIST.shape == [N, MAXXHIST] {srname}'
+        assert sim.shape == (num_vars, num_vars + 1), f'SIM.shape == [N, N+1] {srname}'
+        assert np.isfinite(sim).all(), f'SIM is finite {srname}'
+        assert all(np.max(abs(sim[:, :num_vars]), axis=0) > 0), f'SIM(:, 1:N) has no zero column {srname}'
+        assert simi.shape == (num_vars, num_vars), f'SIMI.shape == [N, N] {srname}'
+        assert np.isfinite(simi).all(), f'SIMI is finite {srname}'
+        assert np.allclose(sim[:, :num_vars] @ simi, np.eye(num_vars), rtol=0.1, atol=0.1) or not all(evaluated), f'SIMI = SIM(:, 1:N)^{-1} {srname}'
+
+    return evaluated, conmat, cval, sim, simi, fval, nf, info
+
+
+def initfilt(conmat, ctol, cweight, cval, fval, sim, evaluated, cfilt, confilt, ffilt, xfilt):
+    '''
+    This function initializes the filter (XFILT, etc) that will be used when selecting
+    x at the end of the solver.
+    N.B.:
+    1. Why not initialize the filters using XHIST, etc? Because the history is empty if
+    the user chooses not to output it.
+    2. We decouple INITXFC and INITFILT so that it is easier to parallelize the former
+    if needed.
+    '''
+
+    # Sizes
+    num_constraints = conmat.shape[0]
+    num_vars = sim.shape[0]
+    maxfilt = len(ffilt)
+
+    # Preconditions
+    if DEBUGGING:
+        assert num_constraints >= 0
+        assert num_vars >= 1
+        assert maxfilt >= 1
+        assert np.size(confilt, 0) == num_constraints and np.size(confilt, 1) == maxfilt
+        assert np.size(cfilt) == maxfilt
+        assert np.size(xfilt, 0) == num_vars and np.size(xfilt, 1) == maxfilt
+        assert np.size(ffilt) == maxfilt
+        assert np.size(conmat, 0) == num_constraints and np.size(conmat, 1) == num_vars + 1
+        assert not (np.isnan(conmat) | np.isneginf(conmat)).any()
+        assert np.size(cval) == num_vars + 1 and not any(cval < 0 | np.isnan(cval) | np.isposinf(cval))
+        assert np.size(fval) == num_vars + 1 and not any(np.isnan(fval) | np.isposinf(fval))
+        assert np.size(sim, 0) == num_vars and np.size(sim, 1) == num_vars + 1
+        assert np.isfinite(sim).all()
+        assert all(np.max(abs(sim[:, :num_vars]), axis=0) > 0)
+        assert np.size(evaluated) == num_vars + 1
+
+    #====================#
+    # Calculation starts #
+    #====================#
+
+
+    nfilt = 0
+    for i in range(num_vars+1):
+        if evaluated[i]:
+            if i < num_vars:
+                x = sim[:, i] + sim[:, num_vars]
+            else:
+                x = sim[:, i]  # i == num_vars, i.e. the last column
+            nfilt, cfilt, ffilt, xfilt, confilt = savefilt(cval[i], ctol, cweight, fval[i], x, nfilt, cfilt, ffilt, xfilt, conmat[:, i], confilt)
+
+    #==================#
+    # Calculation ends #
+    #==================#
+
+    # Postconditions
+    if DEBUGGING:
+        assert nfilt <= maxfilt
+        assert np.size(confilt, 0) == num_constraints and np.size(confilt, 1) == maxfilt
+        assert not (np.isnan(confilt[:, :nfilt]) | np.isneginf(confilt[:, :nfilt])).any()
+        assert np.size(cfilt) == maxfilt
+        assert not any(cfilt[:nfilt] < 0 | np.isnan(cfilt[:nfilt]) | np.isposinf(cfilt[:nfilt]))
+        assert np.size(xfilt, 0) == num_vars and np.size(xfilt, 1) == maxfilt
+        assert not (np.isnan(xfilt[:, :nfilt])).any()
+        # The last calculated X can be Inf (finite + finite can be Inf numerically).
+        assert np.size(ffilt) == maxfilt
+        assert not any(np.isnan(ffilt[:nfilt]) | np.isposinf(ffilt[:nfilt]))
+
+    return nfilt
diff --git a/.venv/lib/python3.12/site-packages/scipy/_external/pyprima/cobyla/trustregion.py b/.venv/lib/python3.12/site-packages/scipy/_external/pyprima/cobyla/trustregion.py
new file mode 100644
index 0000000000000000000000000000000000000000..3e97d7c0b5066a94e96168bd2f42e72197f4b632
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/_external/pyprima/cobyla/trustregion.py
@@ -0,0 +1,492 @@
+'''
+This module provides subroutines concerning the trust-region calculations of COBYLA.
+
+Translated from Zaikun Zhang's modern-Fortran reference implementation in PRIMA.
+
+Dedicated to late Professor M. J. D. Powell FRS (1936--2015).
+
+Python translation by Nickolai Belakovski.
+'''
+
+import numpy as np
+import numpy.typing as npt
+from ..common.consts import DEBUGGING, REALMIN, REALMAX, EPS
+from ..common.powalg import qradd_Rdiag, qrexc_Rdiag
+from ..common.linalg import isminor, matprod, inprod, lsqr, primasum
+
+
+def trstlp(A, b, delta, g):
+    '''
+    This function calculated an n-component vector d by the following two stages. In the first
+    stage, d is set to the shortest vector that minimizes the greatest violation of the constraints
+        A.T @ D <= B,  K = 1, 2, 3, ..., M,
+    subject to the Euclidean length of d being at most delta. If its length is strictly less than
+    delta, then the second stage uses the resultant freedom in d to minimize the objective function
+        G.T @ D
+    subject to no increase in any greatest constraint violation.
+
+    It is possible but rare that a degeneracy may prevent d from attaining the target length delta.
+
+    cviol is the largest constraint violation of the current d: max(max(A.T@D - b), 0)
+    icon is the index of a most violated constraint if cviol is positive.
+
+    nact is the number of constraints in the active set and iact[0], ..., iact[nact-1] are their indices,
+    while the remainder of the iact contains a permutation of the remaining constraint indicies.
+    N.B.: nact <= min(num_constraints, num_vars). Obviously nact <= num_constraints. In addition, the constraints
+    in iact[0, ..., nact-1] have linearly independent gradients (see the comments above the instruction
+    that delete a constraint from the active set to make room for the new active constraint with index iact[icon]);
+    it can also be seen from the update of nact: starting from 0, nact is incremented only if nact < n.
+
+    Further, Z is an orthogonal matrix whose first nact columns can be regarded as the result of
+    Gram-Schmidt applied to the active constraint gradients. For j = 0, 1, ..., nact-1, the number
+    zdota[j] is the scalar product of the jth column of Z with the gradient of the jth active
+    constraint. d is the current vector of variables and here the residuals of the active constraints
+    should be zero. Further, the active constraints have nonnegative Lagrange multipliers that are
+    held at the beginning of vmultc. The remainder of this vector holds the residuals of the inactive
+    constraints at d, the ordering of the components of vmultc being in agreement with the permutation
+    of the indices of the constraints that is in iact. All these residuals are nonnegative, which is
+    achieved by the shift cviol that makes the least residual zero.
+
+    N.B.:
+    0. In Powell's implementation, the constraints are A.T @ D >= B. In other words, the A and B in
+    our implementation are the negative of those in Powell's implementation.
+    1. The algorithm was NOT documented in the COBYLA paper. A note should be written to introduce it!
+    2. As a major part of the algorithm (see trstlp_sub), the code maintains and updates the QR
+    factorization of A[iact[:nact]], i.e. the gradients of all the active (linear) constraints. The
+    matrix Z is indeed Q, and the vector zdota is the diagonal of R. The factorization is updated by
+    Givens rotations when an index is added in or removed from iact.
+    3. There are probably better algorithms available for the trust-region linear programming problem.
+    '''
+
+    # Sizes
+    num_constraints = A.shape[1]
+    num_vars = A.shape[0]
+
+    # Preconditions
+    if DEBUGGING:
+        assert num_vars >= 1
+        assert num_constraints >= 0
+        assert np.size(g) == num_vars
+        assert np.size(b) == num_constraints
+        assert delta > 0
+
+
+    vmultc = np.zeros(num_constraints + 1)
+    iact = np.zeros(num_constraints + 1, dtype=int)
+    nact = 0
+    d = np.zeros(num_vars)
+    z = np.zeros((num_vars, num_vars))
+
+    # ==================
+    # Calculation starts
+    # ==================
+
+    # Form A_aug and B_aug. This allows the gradient of the objective function to be regarded as the
+    # gradient of a constraint in the second stage.
+    A_aug = np.hstack([A, g.reshape((num_vars, 1))])
+    b_aug = np.hstack([b, 0])
+
+
+    # Scale the problem if A contains large values. Otherwise floating point exceptions may occur.
+    # Note that the trust-region step is scale invariant.
+    for i in range(num_constraints+1):  # Note that A_aug.shape[1] == num_constraints+1
+        if (maxval:=max(abs(A_aug[:, i]))) > 1e12:
+            modscal = max(2*REALMIN, 1/maxval)
+            A_aug[:, i] *= modscal
+            b_aug[i] *= modscal
+
+    # Stage 1: minimize the 1+infinity constraint violation of the linearized constraints.
+    iact[:num_constraints], nact, d, vmultc[:num_constraints], z = trstlp_sub(iact[:num_constraints], nact, 1, A_aug[:, :num_constraints], b_aug[:num_constraints], delta, d, vmultc[:num_constraints], z)
+
+    # Stage 2: minimize the linearized objective without increasing the 1_infinity constraint violation.
+    iact, nact, d, vmultc, z = trstlp_sub(iact, nact, 2, A_aug, b_aug, delta, d, vmultc, z)
+
+    # ================
+    # Calculation ends
+    # ================
+
+    # Postconditions
+    if DEBUGGING:
+        assert all(np.isfinite(d))
+        # Due to rounding, it may happen that ||D|| > DELTA, but ||D|| > 2*DELTA is highly improbable.
+        assert np.linalg.norm(d) <= 2 * delta
+
+    return d
+
+def trstlp_sub(iact: npt.NDArray, nact: int, stage, A, b, delta, d, vmultc, z):
+    '''
+    This subroutine does the real calculations for trstlp, both stage 1 and stage 2.
+    Major differences between stage 1 and stage 2:
+    1. Initialization. Stage 2 inherits the values of some variables from stage 1, so they are
+    initialized in stage 1 but not in stage 2.
+    2. cviol. cviol is updated after at iteration in stage 1, while it remains a constant in stage2.
+    3. sdirn. See the definition of sdirn in the code for details.
+    4. optnew. The two stages have different objectives, so optnew is updated differently.
+    5. step. step <= cviol in stage 1.
+    '''
+    zdasav = np.zeros(z.shape[1])
+    vmultd = np.zeros(np.size(vmultc))
+    zdota = np.zeros(np.size(z, 1))
+
+    # Sizes
+    mcon = np.size(A, 1)
+    num_vars = np.size(A, 0)
+
+    # Preconditions
+    if DEBUGGING:
+        assert num_vars >= 1
+        assert stage == 1 or stage == 2
+        assert (mcon >= 0 and stage == 1) or (mcon >= 1 and stage == 2)
+        assert np.size(b) == mcon
+        assert np.size(iact) == mcon
+        assert np.size(vmultc) == mcon
+        assert np.size(d) == num_vars
+        assert np.size(z, 0) == num_vars and np.size(z, 1) == num_vars
+        assert delta > 0
+        if stage == 2:
+            assert all(np.isfinite(d)) and np.linalg.norm(d) <= 2 * delta
+            assert nact >= 0 and nact <= np.minimum(mcon, num_vars)
+            assert all(vmultc[:mcon]) >= 0
+            # N.B.: Stage 1 defines only VMULTC(1:M); VMULTC(M+1) is undefined!
+
+
+    # Initialize according to stage
+    if stage == 1:
+        iact = np.linspace(0, mcon-1, mcon, dtype=int)
+        nact = 0
+        d = np.zeros(num_vars)
+        cviol = np.max(np.append(0, -b))
+        vmultc = cviol + b
+        z = np.eye(num_vars)
+        if mcon == 0 or cviol <= 0:
+            # Check whether a quick return is possible. Make sure the in-outputs have been initialized.
+            return iact, nact, d, vmultc, z
+
+        if all(np.isnan(b)):
+            return iact, nact, d, vmultc, z
+        else:
+            icon = np.nanargmax(-b)
+        num_constraints = mcon
+        sdirn = np.zeros(len(d))
+    else:
+        if inprod(d, d) >= delta*delta:
+            # Check whether a quick return is possible.
+            return iact, nact, d, vmultc, z
+
+        iact[mcon-1] = mcon-1
+        vmultc[mcon-1] = 0
+        num_constraints = mcon - 1
+        icon = mcon - 1
+
+        # In Powell's code, stage 2 uses the zdota and cviol calculated by stage1. Here we recalculate
+        # them so that they need not be passed from stage 1 to 2, and hence the coupling is reduced.
+        cviol = np.max(np.append(0, matprod(d, A[:, :num_constraints]) - b[:num_constraints]))
+    zdota[:nact] = [inprod(z[:, k], A[:, iact[k]]) for k in range(nact)]
+
+    # More initialization
+    optold = REALMAX
+    nactold = nact
+    nfail = 0
+
+    # Zaikun 20211011: vmultd is computed from scratch at each iteration, but vmultc is inherited
+
+    # Powell's code can encounter infinite cycling, which did happen when testing the following CUTEst
+    # problems: DANWOODLS, GAUSS1LS, GAUSS2LS, GAUSS3LS, KOEBHELB, TAX13322, TAXR13322. Indeed, in all
+    # these cases, Inf/NaN appear in d due to extremely large values in A (up to 10^219). To resolve
+    # this, we set the maximal number of iterations to maxiter, and terminate if Inf/NaN occurs in d.
+    maxiter = np.minimum(10000, 100*max(num_constraints, num_vars))
+    for iter in range(maxiter):
+        if DEBUGGING:
+            assert all(vmultc >= 0)
+        if stage == 1:
+            optnew = cviol
+        else:
+            optnew = inprod(d, A[:, mcon-1])
+
+        # End the current stage of the calculation if 3 consecutive iterations have either failed to
+        # reduce the best calculated value of the objective function or to increase the number of active
+        # constraints since the best value was calculated. This strategy prevents cycling, but there is
+        # a remote possibility that it will cause premature termination.
+        if optnew < optold or nact > nactold:
+            nactold = nact
+            nfail = 0
+        else:
+            nfail += 1
+        optold = np.minimum(optold, optnew)
+        if nfail == 3:
+            break
+
+        # If icon exceeds nact, then we add the constraint with index iact[icon] to the active set.
+        if icon >= nact:  # In Python this needs to be >= since Python is 0-indexed (in Fortran we have 1 > 0, in Python we need 0 >= 0)
+            zdasav[:nact] = zdota[:nact]
+            nactsav = nact
+            z, zdota, nact = qradd_Rdiag(A[:, iact[icon]], z, zdota, nact)  # May update nact to nact+1
+            # Indeed it suffices to pass zdota[:min(num_vars, nact+1)] to qradd as follows:
+            # qradd(A[:, iact[icon]], z, zdota[:min(num_vars, nact+1)], nact)
+
+            if nact == nactsav + 1:
+                # N.B.: It is possible to index arrays using [nact, icon] when nact == icon.
+                # Zaikun 20211012: Why should vmultc[nact] = 0?
+                if nact != (icon + 1):  # Need to add 1 to Python for 0 indexing
+                    vmultc[[icon, nact-1]] = vmultc[nact-1], 0
+                    iact[[icon, nact-1]] = iact[[nact-1, icon]]
+                else:
+                    vmultc[nact-1] = 0
+            else:
+                # Zaikun 20211011:
+                # 1. VMULTD is calculated from scratch for the first time (out of 2) in one iteration.
+                # 2. Note that IACT has not been updated to replace IACT[NACT] with IACT[ICON]. Thus
+                # A[:, IACT[:NACT]] is the UNUPDATED version before QRADD (note Z[:, :NACT] remains the
+                # same before and after QRADD). Therefore if we supply ZDOTA to LSQR (as Rdiag) as
+                # Powell did, we should use the UNUPDATED version, namely ZDASAV.
+                # vmultd[:nact] = lsqr(A[:, iact[:nact]], A[:, iact[icon]], z[:, :nact], zdasav[:nact])
+                vmultd[:nact] = lsqr(A[:, iact[:nact]], A[:, iact[icon]], z[:, :nact], zdasav[:nact])
+                if not any(np.logical_and(vmultd[:nact] > 0, iact[:nact] <= num_constraints)):
+                    # N.B.: This can be triggered by NACT == 0 (among other possibilities)! This is
+                    # important, because NACT will be used as an index in the sequel.
+                    break
+                # vmultd[NACT+1:mcon] is not used, but we have to initialize it in Fortran, or compilers
+                # complain about the where construct below (another solution: restrict where to 1:NACT).
+                vmultd[nact:mcon] = -1  # len(vmultd) == mcon
+
+                # Revise the Lagrange multipliers. The revision is not applicable to vmultc[nact:num_constraints].
+                fracmult = [vmultc[i]/vmultd[i] if vmultd[i] > 0 and iact[i] <= num_constraints else REALMAX for i in range(nact)]
+                # Only the places with vmultd > 0 and iact <= m is relevant below, if any.
+                frac = min(fracmult[:nact])  # fracmult[nact:mcon] may contain garbage
+                vmultc[:nact] = np.maximum(np.zeros(len(vmultc[:nact])), vmultc[:nact] - frac*vmultd[:nact])
+
+                # Reorder the active constraints so that the one to be replaced is at the end of the list.
+                # Exit if the new value of zdota[nact] is not acceptable. Powell's condition for the
+                # following If: not abs(zdota[nact]) > 0. Note that it is different from
+                # 'abs(zdota[nact]) <=0)' as zdota[nact] can be NaN.
+                # N.B.: We cannot arrive here with nact == 0, which should have triggered a break above
+                if np.isnan(zdota[nact - 1]) or abs(zdota[nact - 1]) <= EPS**2:
+                    break
+                vmultc[[icon, nact - 1]] = 0, frac  # vmultc[[icon, nact]] is valid as icon > nact
+                iact[[icon, nact - 1]] = iact[[nact - 1, icon]]
+            # end if nact == nactsav + 1
+
+            # In stage 2, ensure that the objective continues to be treated as the last active constraint.
+            # Zaikun 20211011, 20211111: Is it guaranteed for stage 2 that iact[nact-1] = mcon when
+            # iact[nact] != mcon??? If not, then how does the following procedure ensure that mcon is
+            # the last of iact[:nact]?
+            if stage == 2 and iact[nact - 1] != (mcon - 1):
+                if nact <= 1:
+                    # We must exit, as nact-2 is used as an index below. Powell's code does not have this.
+                    break
+                z, zdota[:nact] = qrexc_Rdiag(A[:, iact[:nact]], z, zdota[:nact], nact - 2)  # We pass nact-2 in Python instead of nact-1
+                # Indeed, it suffices to pass Z[:, :nact] to qrexc as follows:
+                # z[:, :nact], zdota[:nact] = qrexc(A[:, iact[:nact]], z[:, :nact], zdota[:nact], nact - 1)
+                iact[[nact-2, nact-1]] = iact[[nact-1, nact-2]]
+                vmultc[[nact-2, nact-1]] = vmultc[[nact-1, nact-2]]
+            # Zaikun 20211117: It turns out that the last few lines do not guarantee iact[nact] == num_vars in
+            # stage 2; the following test cannot be passed. IS THIS A BUG?!
+            # assert iact[nact] == mcon or stage == 1, 'iact[nact] must == mcon in stage 2'
+
+            # Powell's code does not have the following. It avoids subsequent floating points exceptions.
+            if np.isnan(zdota[nact-1]) or abs(zdota[nact-1]) <= EPS**2:
+                break
+
+            # Set sdirn to the direction of the next change to the current vector of variables
+            # Usually during stage 1 the vector sdirn gives a search direction that reduces all the
+            # active constraint violations by one simultaneously.
+            if stage == 1:
+                sdirn -= ((inprod(sdirn, A[:, iact[nact-1]]) + 1)/zdota[nact-1])*z[:, nact-1]
+            else:
+                sdirn = -1/zdota[nact-1]*z[:, nact-1]
+        else:  # icon < nact
+            # Delete the constraint with the index iact[icon] from the active set, which is done by
+            # reordering iact[icon:nact] into [iact[icon+1:nact], iact[icon]] and then reduce nact to
+            # nact - 1. In theory, icon > 0.
+            # assert icon > 0, "icon > 0 is required"  #  For Python I think this is irrelevant
+            z, zdota[:nact] = qrexc_Rdiag(A[:, iact[:nact]], z, zdota[:nact], icon)  # qrexc does nothing if icon == nact
+            # Indeed, it suffices to pass Z[:, :nact] to qrexc as follows:
+            # z[:, :nact], zdota[:nact] = qrexc(A[:, iact[:nact]], z[:, :nact], zdota[:nact], icon)
+            iact[icon:nact] = [*iact[icon+1:nact], iact[icon]]
+            vmultc[icon:nact] = [*vmultc[icon+1:nact], vmultc[icon]]
+            nact -= 1
+
+            # Powell's code does not have the following. It avoids subsequent exceptions.
+            # Zaikun 20221212: In theory, nact > 0 in stage 2, as the objective function should always
+            # be considered as an "active constraint" --- more precisely, iact[nact] = mcon. However,
+            # looking at the code, I cannot see why in stage 2 nact must be positive after the reduction
+            # above. It did happen in stage 1 that nact became 0 after the reduction --- this is
+            # extremely rare, and it was never observed until 20221212, after almost one year of
+            # random tests. Maybe nact is theoretically positive even in stage 1?
+            if stage == 2 and nact < 0:
+                break  # If this case ever occurs, we have to break, as nact is used as an index below.
+            if nact > 0:
+                if np.isnan(zdota[nact-1]) or abs(zdota[nact-1]) <= EPS**2:
+                    break
+
+            # Set sdirn to the direction of the next change to the current vector of variables.
+            if stage == 1:
+                sdirn -= inprod(sdirn, z[:, nact]) * z[:, nact]
+                # sdirn is orthogonal to z[:, nact+1]
+            else:
+                sdirn = -1/zdota[nact-1] * z[:, nact-1]
+        # end if icon > nact
+
+        # Calculate the step to the trust region boundary or take the step that reduces cviol to 0.
+        # ----------------------------------------------------------------------------------------- #
+        # The following calculation of step is adopted from NEWUOA/BOBYQA/LINCOA. It seems to improve
+        # the performance of COBYLA. We also found that removing the precaution about underflows is
+        # beneficial to the overall performance of COBYLA --- the underflows are harmless anyway.
+        dd = delta*delta - inprod(d, d)
+        ss = inprod(sdirn, sdirn)
+        sd = inprod(sdirn, d)
+        if dd <= 0 or ss <= EPS * delta*delta or np.isnan(sd):
+            break
+        # sqrtd: square root of a discriminant. The max avoids sqrtd < abs(sd) due to underflow
+        sqrtd = max(np.sqrt(ss*dd + sd*sd), abs(sd), np.sqrt(ss * dd))
+        if sd > 0:
+            step = dd / (sqrtd + sd)
+        else:
+            step = (sqrtd - sd) / ss
+        # step < 0 should not happen. Step can be 0 or NaN when, e.g., sd or ss becomes inf
+        if step <= 0 or not np.isfinite(step):
+            break
+
+        # Powell's approach and comments are as follows.
+        # -------------------------------------------------- #
+        # The two statements below that include the factor eps prevent
+        # some harmless underflows that occurred in a test calculation
+        # (Zaikun: here, eps is the machine epsilon; Powell's original
+        # code used 1.0e-6, and Powell's code was written in single
+        # precision). Further, we skip the step if it could be 0 within
+        # a reasonable tolerance for computer rounding errors.
+
+        #  !dd = delta*delta - sum(d**2, mask=(abs(d) >= EPS * delta))
+        #  !ss = inprod(sdirn, sdirn)
+        #  !if (dd  <= 0) then
+        #  !    exit
+        #  !end if
+        #  !sd = inprod(sdirn, d)
+        #  !if (abs(sd) >= EPS * sqrt(ss * dd)) then
+        #  !    step = dd / (sqrt(ss * dd + sd*sd) + sd)
+        #  !else
+        #  !    step = dd / (sqrt(ss * dd) + sd)
+        #  !end if
+        # -------------------------------------------------- #
+
+        if stage == 1:
+            if isminor(cviol, step):
+                break
+            step = min(step, cviol)
+
+        # Set dnew to the new variables if step is the steplength, and reduce cviol to the corresponding
+        # maximum residual if stage 1 is being done
+        dnew = d + step * sdirn
+        if stage == 1:
+            cviol = np.max(np.append(0, matprod(dnew, A[:, iact[:nact]]) - b[iact[:nact]]))
+            # N.B.: cviol will be used when calculating vmultd[nact+1:mcon].
+
+        # Zaikun 20211011:
+        # 1. vmultd is computed from scratch for the second (out of 2) time in one iteration.
+        # 2. vmultd[:nact] and vmultd[nact:mcon] are calculated separately with no coupling.
+        # 3. vmultd will be calculated from scratch again in the next iteration.
+        # Set vmultd to the vmultc vector that would occur if d became dnew. A device is included to
+        # force vmultd[k] = 0 if deviations from this value can be attributed to computer rounding
+        # errors. First calculate the new Lagrange multipliers.
+        vmultd[:nact] = -lsqr(A[:, iact[:nact]], dnew, z[:, :nact], zdota[:nact])
+        if stage == 2:
+            vmultd[nact-1] = max(0, vmultd[nact-1])  # This seems never activated.
+        # Complete vmultd by finding the new constraint residuals. (Powell wrote "Complete vmultc ...")
+        cvshift = cviol - (matprod(dnew, A[:, iact]) - b[iact])  # Only cvshift[nact+1:mcon] is needed
+        cvsabs = matprod(abs(dnew), abs(A[:, iact])) + abs(b[iact]) + cviol
+        cvshift[isminor(cvshift, cvsabs)] = 0
+        vmultd[nact:mcon] = cvshift[nact:mcon]
+
+        # Calculate the fraction of the step from d to dnew that will be taken
+        fracmult = [vmultc[i]/(vmultc[i] - vmultd[i]) if vmultd[i] < 0 else REALMAX for i in range(len(vmultd))]
+        # Only the places with vmultd < 0 are relevant below, if any.
+        icon = np.argmin(np.append(1, fracmult)) - 1
+        frac = min(np.append(1, fracmult))
+
+        # Update d, vmultc, and cviol
+        dold = d
+        d = (1 - frac)*d + frac * dnew
+        vmultc = np.maximum(0, (1 - frac)*vmultc + frac*vmultd)
+        # Break in the case of inf/nan in d or vmultc.
+        if not (np.isfinite(primasum(abs(d))) and np.isfinite(primasum(abs(vmultc)))):
+            d = dold  # Should we restore also iact, nact, vmultc, and z?
+            break
+
+        if stage == 1:
+            # cviol = (1 - frac) * cvold + frac * cviol  # Powell's version
+            # In theory, cviol = np.max(np.append(d@A - b, 0)), yet the
+            # cviol updated as above can be quite different from this value if A has huge entries (e.g., > 1e20)
+            cviol = np.max(np.append(0, matprod(d, A) - b))
+
+        if icon < 0 or icon >= mcon:
+            # In Powell's code, the condition is icon == 0. Indeed, icon < 0 cannot hold unless
+            # fracmult contains only nan, which should not happen; icon >= mcon should never occur.
+            break
+
+    #==================#
+    # Calculation ends #
+    #==================#
+
+    # Postconditions
+    if DEBUGGING:
+        assert np.size(iact) == mcon
+        assert np.size(vmultc) == mcon
+        assert all(vmultc >= 0)
+        assert np.size(d) == num_vars
+        assert all(np.isfinite(d))
+        assert np.linalg.norm(d) <= 2 * delta
+        assert np.size(z, 0) == num_vars and np.size(z, 1) == num_vars
+        assert nact >= 0 and nact <= np.minimum(mcon, num_vars)
+
+    return iact, nact, d, vmultc, z
+
+
+def trrad(delta_in, dnorm, eta1, eta2, gamma1, gamma2, ratio):
+    '''
+    This function updates the trust region radius according to RATIO and DNORM.
+    '''
+
+    # Preconditions
+    if DEBUGGING:
+        assert delta_in >= dnorm > 0
+        assert 0 <= eta1 <= eta2 < 1
+        assert 0 < gamma1 < 1 < gamma2
+        # By the definition of RATIO in ratio.f90, RATIO cannot be NaN unless the
+        # actual reduction is NaN, which should NOT happen due to the moderated extreme
+        # barrier.
+        assert not np.isnan(ratio)
+
+    #====================#
+    # Calculation starts #
+    #====================#
+
+    if ratio <= eta1:
+        delta = gamma1 * dnorm  # Powell's UOBYQA/NEWUOA
+        # delta = gamma1 * delta_in  # Powell's COBYLA/LINCOA
+        # delta = min(gamma1 * delta_in, dnorm)  # Powell's BOBYQA
+    elif ratio <= eta2:
+        delta = max(gamma1 * delta_in, dnorm)  # Powell's UOBYQA/NEWUOA/BOBYQA/LINCOA
+    else:
+        delta = max(gamma1 * delta_in, gamma2 * dnorm)  # Powell's NEWUOA/BOBYQA
+        # delta = max(delta_in, gamma2 * dnorm)  # Modified version. Works well for UOBYQA
+        # For noise-free CUTEst problems of <= 100 variables, Powell's version works slightly better
+        # than the modified one.
+        # delta = max(delta_in, 1.25*dnorm, dnorm + rho)  # Powell's UOBYQA
+        # delta = min(max(gamma1 * delta_in, gamma2 * dnorm), gamma3 * delta_in)  # Powell's LINCOA, gamma3 = np.sqrt(2)
+
+    # For noisy problems, the following may work better.
+    # if ratio <= eta1:
+    #     delta = gamma1 * dnorm
+    # elseif ratio <= eta2:  # Ensure DELTA >= DELTA_IN
+    #     delta = delta_in
+    # else:  # Ensure DELTA > DELTA_IN with a constant factor
+    #     delta = max(delta_in * (1 + gamma2) / 2, gamma2 * dnorm)
+
+    #==================#
+    # Calculation ends #
+    #==================#
+
+    # Postconditions
+    if DEBUGGING:
+        assert delta > 0
+    return delta
diff --git a/.venv/lib/python3.12/site-packages/scipy/_external/pyprima/cobyla/update.py b/.venv/lib/python3.12/site-packages/scipy/_external/pyprima/cobyla/update.py
new file mode 100644
index 0000000000000000000000000000000000000000..66a3fa3623f9373b27346ebe052ddbf6f3ba68a4
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/_external/pyprima/cobyla/update.py
@@ -0,0 +1,289 @@
+'''
+This module contains subroutines concerning the update of the interpolation set.
+
+Translated from Zaikun Zhang's modern-Fortran reference implementation in PRIMA.
+
+Dedicated to late Professor M. J. D. Powell FRS (1936--2015).
+
+Python translation by Nickolai Belakovski.
+'''
+
+from ..common.consts import DEBUGGING
+from ..common.infos import DAMAGING_ROUNDING, INFO_DEFAULT
+from ..common.linalg import isinv, matprod, outprod, inprod, inv, primasum
+import numpy as np
+
+
+def updatexfc(jdrop, constr, cpen, cstrv, d, f, conmat, cval, fval, sim, simi):
+    '''
+    This function revises the simplex by updating the elements of SIM, SIMI, FVAL, CONMAT, and CVAL
+    '''
+
+    # Local variables
+    itol = 1
+
+    # Sizes
+    num_constraints = np.size(constr)
+    num_vars = np.size(sim, 0)
+
+    # Preconditions
+    if DEBUGGING:
+        assert num_constraints >= 0
+        assert num_vars >= 1
+        assert jdrop >= 0 and jdrop <= num_vars + 1
+        assert not any(np.isnan(constr) | np.isneginf(constr))
+        assert not (np.isnan(cstrv) | np.isposinf(cstrv))
+        assert np.size(d) == num_vars and all(np.isfinite(d))
+        assert not (np.isnan(f) | np.isposinf(f))
+        assert np.size(conmat, 0) == num_constraints and np.size(conmat, 1) == num_vars + 1
+        assert not (np.isnan(conmat) | np.isneginf(conmat)).any()
+        assert np.size(cval) == num_vars + 1 and not any(cval < 0 | np.isnan(cval) | np.isposinf(cval))
+        assert np.size(fval) == num_vars + 1 and not any(np.isnan(fval) | np.isposinf(fval))
+        assert np.size(sim, 0) == num_vars and np.size(sim, 1) == num_vars + 1
+        assert np.isfinite(sim).all()
+        assert all(primasum(abs(sim[:, :num_vars]), axis=0) > 0)
+        assert np.size(simi, 0) == num_vars and np.size(simi, 1) == num_vars
+        assert np.isfinite(simi).all()
+        assert isinv(sim[:, :num_vars], simi, itol)
+
+    #====================#
+    # Calculation starts #
+    #====================#
+
+
+    # Do nothing when JDROP is None. This can only happen after a trust-region step.
+    if jdrop is None:  # JDROP is None is impossible if the input is correct.
+        return conmat, cval, fval, sim, simi, INFO_DEFAULT
+
+    sim_old = sim
+    simi_old = simi
+    if jdrop < num_vars:
+        sim[:, jdrop] = d
+        simi_jdrop = simi[jdrop, :] / inprod(simi[jdrop, :], d)
+        simi -= outprod(matprod(simi, d), simi_jdrop)
+        simi[jdrop, :] = simi_jdrop
+    else:  # jdrop == num_vars
+        sim[:, num_vars] += d
+        sim[:, :num_vars] -= np.tile(d, (num_vars, 1)).T
+        simid = matprod(simi, d)
+        sum_simi = primasum(simi, axis=0)
+        simi += outprod(simid, sum_simi / (1 - sum(simid)))
+
+    # Check whether SIMI is a poor approximation to the inverse of SIM[:, :NUM_VARS]
+    # Calculate SIMI from scratch if the current one is damaged by rounding errors.
+    itol = 1
+    erri = np.max(abs(matprod(simi, sim[:, :num_vars]) - np.eye(num_vars)))  # np.max returns NaN if any input is NaN
+    if erri > 0.1 * itol or np.isnan(erri):
+        simi_test = inv(sim[:, :num_vars])
+        erri_test = np.max(abs(matprod(simi_test, sim[:, :num_vars]) - np.eye(num_vars)))
+        if erri_test < erri or (np.isnan(erri) and not np.isnan(erri_test)):
+            simi = simi_test
+            erri = erri_test
+
+    # If SIMI is satisfactory, then update FVAL, CONMAT, CVAL, and the pole position. Otherwise restore
+    # SIM and SIMI, and return with INFO = DAMAGING_ROUNDING.
+    if erri <= itol:
+        fval[jdrop] = f
+        conmat[:, jdrop] = constr
+        cval[jdrop] = cstrv
+        # Switch the best vertex to the pole position SIM[:, NUM_VARS] if it is not there already
+        conmat, cval, fval, sim, simi, info = updatepole(cpen, conmat, cval, fval, sim, simi)
+    else:
+        info = DAMAGING_ROUNDING
+        sim = sim_old
+        simi = simi_old
+
+    #==================#
+    # Calculation ends #
+    #==================#
+
+    # Postconditions
+    if DEBUGGING:
+        assert np.size(conmat, 0) == num_constraints and np.size(conmat, 1) == num_vars + 1
+        assert not (np.isnan(conmat) | np.isneginf(conmat)).any()
+        assert np.size(cval) == num_vars + 1 and not any(cval < 0 | np.isnan(cval) | np.isposinf(cval))
+        assert np.size(fval) == num_vars + 1 and not any(np.isnan(fval) | np.isposinf(fval))
+        assert np.size(sim, 0) == num_vars and np.size(sim, 1) == num_vars + 1
+        assert np.isfinite(sim).all()
+        assert all(primasum(abs(sim[:, :num_vars]), axis=0) > 0)
+        assert np.size(simi, 0) == num_vars and np.size(simi, 1) == num_vars
+        assert np.isfinite(simi).all()
+        assert isinv(sim[:, :num_vars], simi, itol) or info == DAMAGING_ROUNDING
+
+    return sim, simi, fval, conmat, cval, info
+
+def findpole(cpen, cval, fval):
+    '''
+    This subroutine identifies the best vertex of the current simplex with respect to the merit
+    function PHI = F + CPEN * CSTRV.
+    '''
+
+    # Size
+    num_vars = np.size(fval) - 1
+
+    # Preconditions
+    if DEBUGGING:
+        assert cpen > 0
+        assert np.size(cval) == num_vars + 1 and not any(cval < 0 | np.isnan(cval) | np.isposinf(cval))
+        assert np.size(fval) == num_vars + 1 and not any(np.isnan(fval) | np.isposinf(fval))
+
+    #====================#
+    # Calculation starts #
+    #====================#
+
+    # Identify the optimal vertex of the current simplex
+    jopt = np.size(fval) - 1
+    phi = fval + cpen * cval
+    phimin = min(phi)
+    # Essentially jopt = np.argmin(phi). However, we keep jopt = num_vars unless there
+    # is a strictly better choice. When there are multiple choices, we choose the jopt
+    # with the smallest value of cval.
+    if phimin < phi[jopt] or any((cval < cval[jopt]) & (phi <= phi[jopt])):
+        # While we could use argmin(phi), there may be two places where phi achieves
+        # phimin, and in that case we should choose the one with the smallest cval.
+        jopt = np.ma.array(cval, mask=(phi > phimin)).argmin()
+
+    #==================#
+    # Calculation ends #
+    #==================#
+
+    # Postconditions
+    if DEBUGGING:
+        assert jopt >= 0 and jopt < num_vars + 1
+        assert jopt == num_vars or phi[jopt] < phi[num_vars] or (phi[jopt] <= phi[num_vars] and cval[jopt] < cval[num_vars])
+    return jopt
+
+
+def updatepole(cpen, conmat, cval, fval, sim, simi):
+    #--------------------------------------------------------------------------------------------------!
+    # This subroutine identifies the best vertex of the current simplex with respect to the merit
+    # function PHI = F + CPEN * CSTRV, and then switch this vertex to SIM[:, NUM_VARS], which Powell called
+    # the "pole position" in his comments. CONMAT, CVAL, FVAL, and SIMI are updated accordingly.
+    #
+    # N.B. 1: In precise arithmetic, the following two procedures produce the same results:
+    # 1) apply UPDATEPOLE to SIM twice, first with CPEN = CPEN1 and then with CPEN = CPEN2;
+    # 2) apply UPDATEPOLE to SIM with CPEN = CPEN2.
+    # In finite-precision arithmetic, however, they may produce different results unless CPEN1 = CPEN2.
+    #
+    # N.B. 2: When JOPT == N+1, the best vertex is already at the pole position, so there is nothing to
+    # switch. However, as in Powell's code, the code below will check whether SIMI is good enough to
+    # work as the inverse of SIM(:, 1:N) or not. If not, Powell's code would invoke an error return of
+    # COBYLB; our implementation, however, will try calculating SIMI from scratch; if the recalculated
+    # SIMI is still of poor quality, then UPDATEPOLE will return with INFO = DAMAGING_ROUNDING,
+    # informing COBYLB that SIMI is poor due to damaging rounding errors.
+    #
+    # N.B. 3: UPDATEPOLE should be called when and only when FINDPOLE can potentially returns a value
+    # other than N+1. The value of FINDPOLE is determined by CPEN, CVAL, and FVAL, the latter two being
+    # decided by SIM. Thus UPDATEPOLE should be called after CPEN or SIM changes. COBYLA updates CPEN at
+    # only two places: the beginning of each trust-region iteration, and when REDRHO is called;
+    # SIM is updated only by UPDATEXFC, which itself calls UPDATEPOLE internally. Therefore, we only
+    # need to call UPDATEPOLE after updating CPEN at the beginning of each trust-region iteration and
+    # after each invocation of REDRHO.
+
+    # Local variables
+    itol = 1
+
+    # Sizes
+    num_constraints = conmat.shape[0]
+    num_vars = sim.shape[0]
+
+    # Preconditions
+    if DEBUGGING:
+        assert num_constraints >= 0
+        assert num_vars >= 1
+        assert cpen > 0
+        assert np.size(conmat, 0) == num_constraints and np.size(conmat, 1) == num_vars + 1
+        assert not (np.isnan(conmat) | np.isneginf(conmat)).any()
+        assert np.size(cval) == num_vars + 1 and not any(cval < 0 | np.isnan(cval) | np.isposinf(cval))
+        assert np.size(fval) == num_vars + 1 and not any(np.isnan(fval) | np.isposinf(fval))
+        assert np.size(sim, 0) == num_vars and np.size(sim, 1) == num_vars + 1
+        assert np.isfinite(sim).all()
+        assert all(primasum(abs(sim[:, :num_vars]), axis=0) > 0)
+        assert np.size(simi, 0) == num_vars and np.size(simi, 1) == num_vars
+        assert np.isfinite(simi).all()
+        assert isinv(sim[:, :num_vars], simi, itol)
+
+    #====================#
+    # Calculation starts #
+    #====================#
+
+    # INFO must be set, as it is an output.
+    info = INFO_DEFAULT
+
+    # Identify the optimal vertex of the current simplex.
+    jopt = findpole(cpen, cval, fval)
+
+    # Switch the best vertex to the pole position SIM[:, NUM_VARS] if it is not there already and update
+    # SIMI. Before the update, save a copy of SIM and SIMI. If the update is unsuccessful due to
+    # damaging rounding errors, we restore them and return with INFO = DAMAGING_ROUNDING.
+    sim_old = sim.copy()
+    simi_old = simi.copy()
+    if 0 <= jopt < num_vars:
+        # Unless there is a bug in FINDPOLE it is guaranteed that JOPT >= 0
+        # When JOPT == NUM_VARS, there is nothing to switch; in addition SIMI[JOPT, :] will be illegal.
+        # fval[[jopt, -1]] = fval[[-1, jopt]]
+        # conmat[:, [jopt, -1]] = conmat[:, [-1, jopt]] # Exchange CONMAT[:, JOPT] AND CONMAT[:, -1]
+        # cval[[jopt, -1]] = cval[[-1, jopt]]
+        sim[:, num_vars] += sim[:, jopt]
+        sim_jopt = sim[:, jopt].copy()
+        sim[:, jopt] = 0  # np.zeros(num_constraints)?
+        sim[:, :num_vars] -= np.tile(sim_jopt, (num_vars, 1)).T
+        # The above update is equivalent to multiplying SIM[:, :NUM_VARS] from the right side by a matrix whose
+        # JOPT-th row is [-1, -1, ..., -1], while all the other rows are the same as those of the
+        # identity matrix. It is easy to check that the inverse of this matrix is itself. Therefore,
+        # SIMI should be updated by a multiplication with this matrix (i.e. its inverse) from the left
+        # side, as is done in the following line. The JOPT-th row of the updated SIMI is minus the sum
+        # of all rows of the original SIMI, whereas all the other rows remain unchanged.
+        # NDB 20250114: In testing the cutest problem 'SYNTHES2' between the Python implementation and
+        # the Fortran bindings, I saw a difference between the following for loop and the
+        # np.sum command. The differences were small, on the order of 1e-16, i.e. epsilon.
+        # According to numpy documentation, np.sum sometimes uses partial pairwise summation,
+        # depending on the memory layout of the array and the axis specified.
+        # for i in range(simi.shape[1]):
+        #     simi[jopt, i] = -sum(simi[:, i])
+        simi[jopt, :] = -primasum(simi, axis=0)
+
+    # Check whether SIMI is a poor approximation to the inverse of SIM[:, :NUM_VARS]
+    # Calculate SIMI from scratch if the current one is damaged by rounding errors.
+    erri = np.max(abs(matprod(simi, sim[:, :num_vars]) - np.eye(num_vars)))  # np.max returns NaN if any input is NaN
+    itol = 1
+    if erri > 0.1 * itol or np.isnan(erri):
+        simi_test = inv(sim[:, :num_vars])
+        erri_test = np.max(abs(matprod(simi_test, sim[:, :num_vars]) - np.eye(num_vars)))
+        if erri_test < erri or (np.isnan(erri) and not np.isnan(erri_test)):
+            simi = simi_test
+            erri = erri_test
+
+
+    # If SIMI is satisfactory, then update FVAL, CONMAT, and CVAL. Otherwise restore SIM and SIMI, and
+    # return with INFO = DAMAGING_ROUNDING.
+    if erri <= itol:
+        if 0 <= jopt < num_vars:
+            fval[[jopt, num_vars]] = fval[[num_vars, jopt]]
+            conmat[:, [jopt, num_vars]] = conmat[:, [num_vars, jopt]]
+            cval[[jopt, num_vars]] = cval[[num_vars, jopt]]
+    else:  # erri > itol or erri is NaN
+        info = DAMAGING_ROUNDING
+        sim = sim_old
+        simi = simi_old
+
+    #==================#
+    # Calculation ends #
+    #==================#
+
+    # Postconditions
+    if DEBUGGING:
+        assert findpole(cpen, cval, fval) == num_vars or info == DAMAGING_ROUNDING
+        assert np.size(conmat, 0) == num_constraints and np.size(conmat, 1) == num_vars + 1
+        assert not (np.isnan(conmat) | np.isneginf(conmat)).any()
+        assert np.size(cval) == num_vars + 1 and not any(cval < 0 | np.isnan(cval) | np.isposinf(cval))
+        assert np.size(fval) == num_vars + 1 and not any(np.isnan(fval) | np.isposinf(fval))
+        assert np.size(sim, 0) == num_vars and np.size(sim, 1) == num_vars + 1
+        assert np.isfinite(sim).all()
+        assert all(primasum(abs(sim[:, :num_vars]), axis=0) > 0)
+        assert np.size(simi, 0) == num_vars and np.size(simi, 1) == num_vars
+        assert np.isfinite(simi).all()
+        # Do not check SIMI = SIM[:, :num_vars]^{-1}, as it may not be true due to damaging rounding.
+        assert isinv(sim[:, :num_vars], simi, itol) or info == DAMAGING_ROUNDING
+
+    return conmat, cval, fval, sim, simi, info
diff --git a/.venv/lib/python3.12/site-packages/scipy/_external/pyprima/common/__init__.py b/.venv/lib/python3.12/site-packages/scipy/_external/pyprima/common/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/.venv/lib/python3.12/site-packages/scipy/_external/pyprima/common/_bounds.py b/.venv/lib/python3.12/site-packages/scipy/_external/pyprima/common/_bounds.py
new file mode 100644
index 0000000000000000000000000000000000000000..89afe9529f21235fc659d661df5f6037688bfdcf
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/_external/pyprima/common/_bounds.py
@@ -0,0 +1,34 @@
+import numpy as np
+from scipy.optimize import Bounds
+
+def process_bounds(bounds, lenx0):
+    '''
+    `bounds` can either be an object with the properties lb and ub, or a list of tuples
+    indicating a lower bound and an upper bound for each variable. If the list contains
+    fewer entries than the length of x0, the remaining entries will generated as -/+ infinity.
+    Some examples of valid lists of tuple, assuming len(x0) == 3:
+    [(0, 1), (2, 3), (4, 5)] -> returns [0, 2, 4], [1, 3, 5]
+    [(0, 1), (None, 3)]      -> returns [0, -inf, -inf], [1, 3, inf]
+    [(0, 1), (-np.inf, 3)]   -> returns [0, -inf, -inf], [1, 3, inf]
+    '''
+
+    if bounds is None:
+        lb = np.array([-np.inf]*lenx0, dtype=np.float64)
+        ub = np.array([np.inf]*lenx0, dtype=np.float64)
+        return lb, ub
+    
+    if isinstance(bounds, Bounds):
+        lb = np.array(bounds.lb, dtype=np.float64)
+        ub = np.array(bounds.ub, dtype=np.float64)
+        lb = np.concatenate((lb, -np.inf*np.ones(lenx0 - len(lb))))
+        ub = np.concatenate((ub, np.inf*np.ones(lenx0 - len(ub))))
+        return lb, ub
+    
+    # If neither of the above conditions are true, we assume that bounds is a list of tuples
+    lb = np.array([bound[0] if bound[0] is not None else -np.inf for bound in bounds], dtype=np.float64)
+    ub = np.array([bound[1] if bound[1] is not None else np.inf for bound in bounds], dtype=np.float64)
+    # If there were fewer bounds than variables, pad the rest with -/+ infinity
+    lb = np.concatenate((lb, -np.inf*np.ones(lenx0 - len(lb))))
+    ub = np.concatenate((ub, np.inf*np.ones(lenx0 - len(ub))))
+    
+    return lb, ub
diff --git a/.venv/lib/python3.12/site-packages/scipy/_external/pyprima/common/_linear_constraints.py b/.venv/lib/python3.12/site-packages/scipy/_external/pyprima/common/_linear_constraints.py
new file mode 100644
index 0000000000000000000000000000000000000000..be508dced7edd7cda998d840bf195411a140b2ad
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/_external/pyprima/common/_linear_constraints.py
@@ -0,0 +1,46 @@
+import numpy as np
+from scipy.optimize import LinearConstraint
+
+
+def combine_multiple_linear_constraints(constraints):
+    full_A = constraints[0].A
+    full_lb = constraints[0].lb
+    full_ub = constraints[0].ub
+    for constraint in constraints[1:]:
+        full_A = np.concatenate((full_A, constraint.A), axis=0)
+        full_lb = np.concatenate((full_lb, constraint.lb), axis=0)
+        full_ub = np.concatenate((full_ub, constraint.ub), axis=0)
+    return LinearConstraint(full_A, full_lb, full_ub)
+
+
+def separate_LC_into_eq_and_ineq(linear_constraint):
+    # The Python interface receives linear constraints lb <= A*x <= ub, but the
+    # Fortran backend of PRIMA expects that the linear constraints are specified
+    # as A_eq*x = b_eq, A_ineq*x <= b_ineq.
+    # As such, we must:
+    # 1. for constraints with lb == ub, rewrite them as A_eq*x = lb;
+    # 2. for constraints with lb < ub, rewrite them as A_ineq*x <= b_ineq.
+
+    # We suppose lb == ub if ub <= lb + 2*epsilon, assuming that the preprocessing
+    # ensures lb <= ub.
+    epsilon = np.finfo(np.float64).eps
+
+    eq_indices = (linear_constraint.ub <= (linear_constraint.lb + 2*epsilon))
+    A_eq = linear_constraint.A[eq_indices]
+    b_eq = (linear_constraint.lb[eq_indices] + linear_constraint.ub[eq_indices])/2.0
+
+    ineq_lb_indices = (linear_constraint.lb > -np.inf)
+    A_ineq_lb = -linear_constraint.A[~eq_indices & ineq_lb_indices]
+    b_ineq_lb = -linear_constraint.lb[~eq_indices & ineq_lb_indices]
+    ineq_ub_indices = (linear_constraint.ub < np.inf)
+    A_ineq_ub = linear_constraint.A[~eq_indices & ineq_ub_indices]
+    b_ineq_ub = linear_constraint.ub[~eq_indices & ineq_ub_indices]
+    A_ineq = np.concatenate((A_ineq_lb, A_ineq_ub))
+    b_ineq = np.concatenate((b_ineq_lb, b_ineq_ub))
+
+    # Ensure dtype is float64, or set to None if empty
+    A_eq = np.array(A_eq, dtype=np.float64) if len(A_eq) > 0 else None
+    b_eq = np.array(b_eq, dtype=np.float64) if len(b_eq) > 0 else None
+    A_ineq = np.array(A_ineq, dtype=np.float64) if len(A_ineq) > 0 else None
+    b_ineq = np.array(b_ineq, dtype=np.float64) if len(b_ineq) > 0 else None
+    return A_eq, b_eq, A_ineq, b_ineq
diff --git a/.venv/lib/python3.12/site-packages/scipy/_external/pyprima/common/_nonlinear_constraints.py b/.venv/lib/python3.12/site-packages/scipy/_external/pyprima/common/_nonlinear_constraints.py
new file mode 100644
index 0000000000000000000000000000000000000000..bfee3b7f2cf2e591b5d956cf3a1ae75cc79f1a19
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/_external/pyprima/common/_nonlinear_constraints.py
@@ -0,0 +1,54 @@
+import numpy as np
+        
+def transform_constraint_function(nlc):
+    '''
+    The Python interfaces receives the constraints as lb <= constraint(x) <= ub, 
+    but the Fortran backend expects the nonlinear constraints to be constraint(x) <= 0.
+    Thus a conversion is needed.
+    
+    In addition to the conversion, we add a check to ensure that the provided lower/upper bounds
+    have a shape consistent with the output of the constraint function.
+    '''
+
+    def newconstraint(x):
+        values = np.atleast_1d(np.array(nlc.fun(x), dtype=np.float64))
+        
+        # Upgrade the lower/upper bounds to vectors if necessary
+        lb = nlc.lb
+        try:
+            _ = len(lb)
+        except TypeError:
+            lb = np.array([nlc.lb]*len(values), dtype=np.float64)
+
+        ub = nlc.ub
+        try:
+            _ = len(ub)
+        except TypeError:
+            ub = np.array([nlc.ub]*len(values), dtype=np.float64)
+        
+        
+        # Check the shapes and raise an exception if they do not match
+        if len(values) != len(lb):
+            raise ValueError("The number of elements in the constraint function's output does not match the number of elements in the lower bound.")
+        if len(values) != len(ub):
+            raise ValueError("The number of elements in the constraint function's output does not match the number of elements in the upper bound.")
+        
+        # Combine the upper and lower bounds to transform the function into the form
+        # expected by the Fortran backend.
+        return np.concatenate(([lb_ii - vi for lb_ii, vi in zip(lb, values) if lb_ii > -np.inf],
+                               [vi - ub_ii for ub_ii, vi in zip(ub, values) if ub_ii < np.inf],
+                            ))
+    return newconstraint
+
+
+def process_nl_constraints(nlcs):
+    functions = []
+    for nlc in nlcs:
+        fun_i = transform_constraint_function(nlc)
+        functions.append(fun_i)
+    def constraint_function(x):
+        values = np.empty(0, dtype=np.float64)
+        for fun in functions:
+            values = np.concatenate((values, fun(x)))
+        return values
+    return constraint_function
diff --git a/.venv/lib/python3.12/site-packages/scipy/_external/pyprima/common/_project.py b/.venv/lib/python3.12/site-packages/scipy/_external/pyprima/common/_project.py
new file mode 100644
index 0000000000000000000000000000000000000000..233a4e32e905d9a4d3b91f3918de766f51a085fc
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/_external/pyprima/common/_project.py
@@ -0,0 +1,173 @@
+'''
+This module provides the _project function that attempts to project the initial guess
+onto the feasible set.
+
+Adapted from the corresponding function in the PDFO package (https://www.pdfo.net) by
+Tom M. Ragonneau (https://ragonneau.github.io) and Zaikun Zhang (https://www.zhangzk.net).
+'''
+
+import numpy as np
+from ._linear_constraints import LinearConstraint
+from scipy.optimize import OptimizeResult
+
+# All the accepted scalar types; np.generic correspond to all NumPy types.
+scalar_types = (int, float, np.generic)
+eps = np.finfo(np.float64).eps
+
+def _project(x0, lb, ub, constraints):
+    """Projection of the initial guess onto the feasible set.
+
+    Parameters
+    ----------
+    x0: ndarray, shape (n,)
+        The same as in prepdfo.
+    lb: ndarray, shape (n,)
+        The same as in prepdfo.
+    ub: ndarray, shape (n,)
+        The same as in prepdfo.
+    constraints: dict
+        The general constraints of the problem, defined as a dictionary with
+        fields:
+            linear: LinearConstraint
+                The linear constraints of the problem.
+            nonlinear: dict
+                The nonlinear constraints of the problem. When ``_project`` is called, the nonlinear constraints are
+                None.
+
+    Returns
+    -------
+    result: OptimizeResult
+        The result of the projection.
+
+    Authors
+    -------
+    Tom M. RAGONNEAU (ragonneau.github.io)
+    and Zaikun ZHANG (www.zhangzk.net)
+
+    Dedicated to the late Professor M. J. D. Powell FRS (1936--2015).
+    """
+    invoker = 'prima'
+
+    # Validate x0.
+    if isinstance(x0, scalar_types):
+        x0_c = [x0]
+    elif hasattr(x0, '__len__'):
+        x0_c = x0
+    else:
+        raise ValueError('{}: UNEXPECTED ERROR: x0 should be a vector.'.format(invoker))
+    try:
+        x0_c = np.asarray(x0_c, dtype=np.float64)
+    except ValueError:
+        raise ValueError('{}: UNEXPECTED ERROR: x0 should contain only scalars.'.format(invoker))
+    if len(x0_c.shape) != 1:
+        raise ValueError('{}: UNEXPECTED ERROR: x0 should be a vector.'.format(invoker))
+    lenx0 = x0_c.size
+
+    # Validate lb.
+    if isinstance(lb, scalar_types):
+        lb_c = [lb]
+    elif hasattr(lb, '__len__'):
+        lb_c = lb
+    else:
+        raise ValueError('{}: UNEXPECTED ERROR: lb should be a vector.'.format(invoker))
+    try:
+        lb_c = np.asarray(lb_c, dtype=np.float64)
+    except ValueError:
+        raise ValueError('{}: UNEXPECTED ERROR: lb should contain only scalars.'.format(invoker))
+    if len(lb_c.shape) != 1 or lb_c.size != lenx0:
+        raise ValueError('{}: UNEXPECTED ERROR: the size of lb is inconsistent with x0.'.format(invoker))
+
+    # Validate ub.
+    if isinstance(ub, scalar_types):
+        ub_c = [ub]
+    elif hasattr(ub, '__len__'):
+        ub_c = ub
+    else:
+        raise ValueError('{}: UNEXPECTED ERROR: ub should be a vector.'.format(invoker))
+    try:
+        ub_c = np.asarray(ub_c, dtype=np.float64)
+    except ValueError:
+        raise ValueError('{}: UNEXPECTED ERROR: ub should contain only scalars.'.format(invoker))
+    if len(ub_c.shape) != 1 or ub_c.size != lenx0:
+        raise ValueError('{}: UNEXPECTED ERROR: the size of ub is inconsistent with x0.'.format(invoker))
+
+    # Validate constraints.
+    if not isinstance(constraints, dict) or not ({'linear', 'nonlinear'} <= set(constraints.keys())) or \
+            not (isinstance(constraints['linear'], LinearConstraint) or constraints['linear'] is None):
+        # the nonlinear constraints will not be taken into account in this function and are, therefore, not validated
+        raise ValueError('{}: UNEXPECTED ERROR: The constraints are ill-defined.'.format(invoker))
+
+    max_con = 1e20  # Decide whether an inequality constraint can be ignored
+
+    # Project onto the feasible set.
+    if constraints['linear'] is None:
+        # Direct projection onto the bound constraints
+        x_proj = np.nanmin((np.nanmax((x0_c, lb_c), axis=0), ub_c), axis=0)
+        return OptimizeResult(x=x_proj)
+    elif all(np.less_equal(np.abs(constraints['linear'].ub - constraints['linear'].lb), eps)) and \
+            np.max(lb_c) <= -max_con and np.min(ub_c) >= max_con:
+        # The linear constraints are all equality constraints. The projection can therefore be done by solving the
+        # least-squares problem: min ||A*x - (b - A*x_0)||.
+        a = constraints['linear'].A
+        b = (constraints['linear'].lb + constraints['linear'].ub) / 2
+        xi, _, _, _ = np.linalg.lstsq(a, b - np.dot(a, x0_c), rcond=None)
+
+        # The problem is not bounded. However, if the least-square solver returned values bigger in absolute value
+        # than max_con, they will be reduced to this bound.
+        x_proj = np.nanmin((np.nanmax((x0_c + xi, lb_c), axis=0), ub_c), axis=0)
+
+        return OptimizeResult(x=x_proj)
+
+    if constraints['linear'] is not None:
+        try:
+            # Project the initial guess onto the linear constraints via SciPy.
+            from scipy.optimize import minimize
+            from scipy.optimize import Bounds as ScipyBounds
+            from scipy.optimize import LinearConstraint as ScipyLinearConstraint
+
+            linear = constraints['linear']
+
+            # To be more efficient, SciPy asks to separate the equality and the inequality constraints into two
+            # different LinearConstraint structures
+            pc_args_ineq, pc_args_eq = dict(), dict()
+            pc_args_ineq['A'], pc_args_eq['A'] = np.asarray([[]]), np.asarray([[]])
+            pc_args_ineq['A'] = pc_args_ineq['A'].reshape(0, linear.A.shape[1])
+            pc_args_eq['A'] = pc_args_eq['A'].reshape(0, linear.A.shape[1])
+            pc_args_ineq['lb'], pc_args_eq['lb'] = np.asarray([]), np.asarray([])
+            pc_args_ineq['ub'], pc_args_eq['ub'] = np.asarray([]), np.asarray([])
+
+            for i in range(linear.lb.size):
+                if linear.lb[i] != linear.ub[i]:
+                    pc_args_ineq['A'] = np.concatenate((pc_args_ineq['A'], linear.A[i:i+1, :]), axis=0)
+                    pc_args_ineq['lb'] = np.r_[pc_args_ineq['lb'], linear.lb[i]]
+                    pc_args_ineq['ub'] = np.r_[pc_args_ineq['ub'], linear.ub[i]]
+                else:
+                    pc_args_eq['A'] = np.concatenate((pc_args_eq['A'], linear.A[i:i+1, :]), axis=0)
+                    pc_args_eq['lb'] = np.r_[pc_args_eq['lb'], linear.lb[i]]
+                    pc_args_eq['ub'] = np.r_[pc_args_eq['ub'], linear.ub[i]]
+
+            if pc_args_ineq['A'].size > 0 and pc_args_ineq['lb'].size > 0 and pc_args_eq['lb'].size > 0:
+                project_constraints = [ScipyLinearConstraint(**pc_args_ineq), ScipyLinearConstraint(**pc_args_eq)]
+            elif pc_args_ineq['A'].size > 0 and pc_args_ineq['lb'].size > 0:
+                project_constraints = ScipyLinearConstraint(**pc_args_ineq)
+            elif pc_args_eq['A'].size > 0:
+                project_constraints = ScipyLinearConstraint(**pc_args_eq)
+            else:
+                project_constraints = ()
+
+            # Perform the actual projection.
+            ax_ineq = np.dot(pc_args_ineq['A'], x0_c)
+            ax_eq = np.dot(pc_args_eq['A'], x0_c)
+            if np.greater(ax_ineq, pc_args_ineq['ub']).any() or np.greater(pc_args_ineq['lb'], ax_ineq).any() or \
+                    np.not_equal(ax_eq, pc_args_eq['lb']).any() or \
+                    np.greater(x0_c, ub_c).any() or np.greater(lb_c, x0_c).any():
+                return minimize(lambda x: np.dot(x - x0_c, x - x0_c) / 2, x0_c, jac=lambda x: (x - x0_c),
+                                bounds=ScipyBounds(lb_c, ub_c), constraints=project_constraints)
+            else:
+                # Do not perform any projection if the initial guess is feasible.
+                return OptimizeResult(x=x0_c)
+
+        except ImportError:
+            return OptimizeResult(x=x0_c)
+
+    return OptimizeResult(x=x0_c)
diff --git a/.venv/lib/python3.12/site-packages/scipy/_external/pyprima/common/checkbreak.py b/.venv/lib/python3.12/site-packages/scipy/_external/pyprima/common/checkbreak.py
new file mode 100644
index 0000000000000000000000000000000000000000..95efd6c14b3dc6e572b3d83a7f47b419ac050c93
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/_external/pyprima/common/checkbreak.py
@@ -0,0 +1,93 @@
+'''
+This module checks whether to break out of the solver loop.
+
+Translated from Zaikun Zhang's modern-Fortran reference implementation in PRIMA.
+
+Dedicated to late Professor M. J. D. Powell FRS (1936--2015).
+
+Python translation by Nickolai Belakovski.
+'''
+
+from .infos import INFO_DEFAULT, NAN_INF_X, NAN_INF_F, FTARGET_ACHIEVED, MAXFUN_REACHED
+
+import numpy as np
+
+def checkbreak_unc(maxfun, nf, f, ftarget, x):
+    '''
+    This module checks whether to break out of the solver loop in the unconstrained case.
+    '''
+
+    # Outputs
+    info = INFO_DEFAULT
+
+    # Local variables
+    srname = "CHECKbreak_UNC"
+
+    # Preconditions
+    assert INFO_DEFAULT not in [NAN_INF_X, NAN_INF_F, FTARGET_ACHIEVED, MAXFUN_REACHED], f'NAN_INF_X, NAN_INF_F, FTARGET_ACHIEVED, and MAXFUN_REACHED differ from INFO_DFT {srname}'
+    # X does not contain NaN if the initial X does not contain NaN and the subroutines generating
+    # trust-region/geometry steps work properly so that they never produce a step containing NaN/Inf.
+    assert not any(np.isnan(x)), f'X does not contain NaN {srname}'
+    # With the moderated extreme barrier, F cannot be NaN/+Inf.
+    assert not (any(np.isnan(f)) or any(np.isposinf(f))), f'F is not NaN/+Inf {srname}'
+
+    #====================#
+    # Calculation starts #
+    #====================#
+
+    # Although X should not contain NaN unless there is a bug, we include the following for security.
+    # X can be Inf, as finite + finite can be Inf numerically.
+    if any(np.isnan(x)) or any(np.isinf(x)):
+        info = NAN_INF_X
+
+    # Although NAN_INF_F should not happen unless there is a bug, we include the following for security.
+    if any(np.isnan(f)) or any(np.isposinf(f)):
+        info = NAN_INF_F
+
+    if f <= ftarget:
+        info = FTARGET_ACHIEVED
+
+    if nf >= maxfun:
+        info = MAXFUN_REACHED
+
+    return info
+
+def checkbreak_con(maxfun, nf, cstrv, ctol, f, ftarget, x):
+    '''
+    This module checks whether to break out of the solver loop in the constrained case.
+    '''
+
+    # Outputs
+    info = INFO_DEFAULT
+
+    # Local variables
+    srname = "CHECKbreak_CON"
+
+    # Preconditions
+    assert INFO_DEFAULT not in [NAN_INF_X, NAN_INF_F, FTARGET_ACHIEVED, MAXFUN_REACHED], f'NAN_INF_X, NAN_INF_F, FTARGET_ACHIEVED, and MAXFUN_REACHED differ from INFO_DFT {srname}'
+    # X does not contain NaN if the initial X does not contain NaN and the subroutines generating
+    # trust-region/geometry steps work properly so that they never produce a step containing NaN/Inf.
+    assert not any(np.isnan(x)), f'X does not contain NaN {srname}'
+    # With the moderated extreme barrier, F or CSTRV cannot be NaN/+Inf.
+    assert not (np.isnan(f) or np.isposinf(f) or np.isnan(cstrv) or np.isposinf(cstrv)), f'F or CSTRV is not NaN/+Inf {srname}'
+
+    #====================#
+    # Calculation starts #
+    #====================#
+
+    # Although X should not contain NaN unless there is a bug, we include the following for security.
+    # X can be Inf, as finite + finite can be Inf numerically.
+    if any(np.isnan(x)) or any(np.isinf(x)):
+        info = NAN_INF_X
+
+    # Although NAN_INF_F should not happen unless there is a bug, we include the following for security.
+    if np.isnan(f) or np.isposinf(f) or np.isnan(cstrv) or np.isposinf(cstrv):
+        info = NAN_INF_F
+
+    if cstrv <= ctol and f <= ftarget:
+        info = FTARGET_ACHIEVED
+
+    if nf >= maxfun:
+        info = MAXFUN_REACHED
+
+    return info
diff --git a/.venv/lib/python3.12/site-packages/scipy/_external/pyprima/common/consts.py b/.venv/lib/python3.12/site-packages/scipy/_external/pyprima/common/consts.py
new file mode 100644
index 0000000000000000000000000000000000000000..1916bae39cf08a495af8008cd623eb45680914e8
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/_external/pyprima/common/consts.py
@@ -0,0 +1,47 @@
+'''
+This is a module defining some constants.
+
+Translated from Zaikun Zhang's modern-Fortran reference implementation in PRIMA.
+
+Dedicated to late Professor M. J. D. Powell FRS (1936--2015).
+
+Python translation by Nickolai Belakovski.
+'''
+
+import numpy as np
+import os
+
+DEBUGGING = bool(os.getenv('PRIMA_DEBUGGING'))
+
+REALMIN = np.finfo(float).tiny
+REALMAX = np.finfo(float).max
+FUNCMAX = 10.0**30
+CONSTRMAX = FUNCMAX
+EPS = np.finfo(float).eps
+
+# Any bound with an absolute value at least BOUNDMAX is considered as no bound.
+BOUNDMAX = REALMAX/4
+
+# Some default values
+RHOBEG_DEFAULT = 1
+RHOEND_DEFAULT = 1e-6
+FTARGET_DEFAULT = -REALMAX
+CTOL_DEFAULT = np.sqrt(EPS)
+CWEIGHT_DEFAULT = 1e8
+ETA1_DEFAULT = 0.1
+ETA2_DEFAULT = 0.7
+GAMMA1_DEFAULT = 0.5
+GAMMA2_DEFAULT = 2
+IPRINT_DEFAULT = 0
+MAXFUN_DIM_DEFAULT = 500
+
+PRIMA_MAX_HIST_MEM_MB = 300  # 1MB > 10^5*REAL64. 100 can be too small.
+
+# Maximal amount of memory (Byte) allowed for XHIST, FHIST, CONHIST, CHIST, and the filters.
+MHM = PRIMA_MAX_HIST_MEM_MB * 10**6
+# Make sure that MAXHISTMEM does not exceed HUGE(0) to avoid overflow and memory errors.
+MAXHISTMEM = min(MHM, np.iinfo(np.int32).max)
+
+# Maximal length of the filter used in constrained solvers.
+MIN_MAXFILT = 200  # Should be positive; < 200 is not recommended.
+MAXFILT_DEFAULT = 10 * MIN_MAXFILT
diff --git a/.venv/lib/python3.12/site-packages/scipy/_external/pyprima/common/evaluate.py b/.venv/lib/python3.12/site-packages/scipy/_external/pyprima/common/evaluate.py
new file mode 100644
index 0000000000000000000000000000000000000000..075e1d42fa30fcd0eaeb7b40a491f41623e27293
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/_external/pyprima/common/evaluate.py
@@ -0,0 +1,99 @@
+'''
+This is a module evaluating the objective/constraint function with Nan/Inf handling.
+
+Translated from Zaikun Zhang's modern-Fortran reference implementation in PRIMA.
+
+Dedicated to late Professor M. J. D. Powell FRS (1936--2015).
+
+Python translation by Nickolai Belakovski.
+'''
+
+import numpy as np
+from .consts import FUNCMAX, CONSTRMAX, REALMAX, DEBUGGING
+from .linalg import matprod, primasum
+
+# This is a module evaluating the objective/constraint function with Nan/Inf handling.
+
+
+def moderatex(x):
+    '''
+    This function moderates a decision variable. It replaces NaN by 0 and Inf/-Inf by
+    REALMAX/-REALMAX.
+    '''
+    x[np.isnan(x)] = 0
+    x = np.clip(x, -REALMAX, REALMAX)
+    return x
+
+def moderatef(f):
+    """
+    This function moderates the function value of a MINIMIZATION problem. It replaces
+    NaN and any value above FUNCMAX by FUNCMAX.
+    """
+    f = FUNCMAX if np.isnan(f) else f
+    f = np.clip(f, -REALMAX, FUNCMAX)
+    # We may moderate huge negative function values as follows, but we decide not to.
+    # f = np.clip(f, -FUNCMAX, FUNCMAX)
+    return f
+
+
+def moderatec(c):
+    """
+    This function moderates the constraint value, the constraint demanding this value
+    to be NONNEGATIVE. It replaces any value below -CONSTRMAX by -CONSTRMAX, and any
+    NaN or value above CONSTRMAX by CONSTRMAX.
+    """
+    np.nan_to_num(c, copy=False, nan=CONSTRMAX)
+    c = np.clip(c, -CONSTRMAX, CONSTRMAX)
+    return c
+
+
+def evaluate(calcfc, x, m_nlcon, amat, bvec):
+    """
+    This function evaluates CALCFC at X, returning the objective function value and the
+    constraint value. Nan/Inf are handled by a moderated extreme barrier.
+    """
+
+    # Sizes
+    m_lcon = len(bvec) if bvec is not None else 0
+
+    # Preconditions
+    if DEBUGGING:
+        # X should not contain NaN if the initial X does not contain NaN and the
+        # subroutines generating # trust-region/geometry steps work properly so that
+        # they never produce a step containing NaN/Inf.
+        assert not any(np.isnan(x))
+
+    #====================#
+    # Calculation starts #
+    #====================#
+
+    constr = np.zeros(m_lcon + m_nlcon)
+    if amat is not None:
+        constr[:m_lcon] = matprod(x, amat.T) - bvec
+
+    if any(np.isnan(x)):
+        # Although this should not happen unless there is a bug, we include this case
+        # for robustness.
+        f = primasum(x)
+        constr = np.ones(m_nlcon) * f
+    else:
+        f, constr[m_lcon:] = calcfc(moderatex(x))
+
+        # Moderated extreme barrier: replace NaN/huge objective or constraint values
+        # with a large but finite value. This is naive, and better approaches surely
+        # exist.
+        f = moderatef(f)
+        constr[m_lcon:] = moderatec(constr[m_lcon:])
+
+    #==================#
+    # Calculation ends #
+    #==================#
+
+    # Postconditions
+    if DEBUGGING:
+        # With X not containing NaN, and with the moderated extreme barrier, F cannot
+        # be NaN/+Inf, and CONSTR cannot be NaN/-Inf.
+        assert not (np.isnan(f) or np.isposinf(f))
+        assert not any(np.isnan(constr) | np.isposinf(constr))
+
+    return f, constr
diff --git a/.venv/lib/python3.12/site-packages/scipy/_external/pyprima/common/history.py b/.venv/lib/python3.12/site-packages/scipy/_external/pyprima/common/history.py
new file mode 100644
index 0000000000000000000000000000000000000000..212db7305d890d0133afb312ed6c73b79f8bb0fa
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/_external/pyprima/common/history.py
@@ -0,0 +1,38 @@
+'''
+This module provides subroutines that handle the X/F/C histories of the solver, taking into
+account that MAXHIST may be smaller than NF.
+
+Translated from Zaikun Zhang's modern-Fortran reference implementation in PRIMA.
+
+Dedicated to late Professor M. J. D. Powell FRS (1936--2015).
+
+Python translation by Nickolai Belakovski.
+'''
+
+def savehist(maxhist, x, xhist, f, fhist, cstrv, chist, constr, conhist):
+    '''
+    Save the data values to the history lists.
+
+    The implementation of this function is vastly different from the Fortran implementation.
+    This is mostly due to the ease of creating and appending to lists in Python
+
+    However just like the Fortran version we should be concerned about both performance
+    and memory constraints. It will probably be better to initialize an array of NaN for
+    each of the histories and keep track of how many indices we have stored. Not needed for
+    the moment.
+    '''
+    if len(xhist) < maxhist:
+        xhist.append(x)
+        fhist.append(f)
+        chist.append(cstrv)
+        conhist.append(constr)
+    else:
+        # This effectively accomplishes what rangehist does in the Fortran implementation
+        xhist.pop(0)
+        fhist.pop(0)
+        chist.pop(0)
+        conhist.pop(0)
+        xhist.append(x)
+        fhist.append(f)
+        chist.append(cstrv)
+        conhist.append(constr)
diff --git a/.venv/lib/python3.12/site-packages/scipy/_external/pyprima/common/infos.py b/.venv/lib/python3.12/site-packages/scipy/_external/pyprima/common/infos.py
new file mode 100644
index 0000000000000000000000000000000000000000..27d0f1e144bdfabf1633ccfccaab2ac5dd93781f
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/_external/pyprima/common/infos.py
@@ -0,0 +1,30 @@
+'''
+This is a module defining exit flags.
+
+Translated from Zaikun Zhang's modern-Fortran reference implementation in PRIMA.
+
+Dedicated to late Professor M. J. D. Powell FRS (1936--2015).
+
+Python translation by Nickolai Belakovski.
+'''
+
+INFO_DEFAULT = 0
+SMALL_TR_RADIUS = 0
+FTARGET_ACHIEVED = 1
+TRSUBP_FAILED = 2
+MAXFUN_REACHED = 3
+MAXTR_REACHED = 20
+NAN_INF_X = -1
+NAN_INF_F = -2
+NAN_INF_MODEL = -3
+NO_SPACE_BETWEEN_BOUNDS = 6
+DAMAGING_ROUNDING = 7
+ZERO_LINEAR_CONSTRAINT = 8
+CALLBACK_TERMINATE = 30
+
+# Stop-codes.
+# The following codes are used by ERROR STOP as stop-codes, which should be default integers.
+INVALID_INPUT = 100
+ASSERTION_FAILS = 101
+VALIDATION_FAILS = 102
+MEMORY_ALLOCATION_FAILS = 103
diff --git a/.venv/lib/python3.12/site-packages/scipy/_external/pyprima/common/linalg.py b/.venv/lib/python3.12/site-packages/scipy/_external/pyprima/common/linalg.py
new file mode 100644
index 0000000000000000000000000000000000000000..a5ee756aaf867ca76afe9cbb5f768c2097ecbadc
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/_external/pyprima/common/linalg.py
@@ -0,0 +1,435 @@
+'''
+This module provides some basic linear algebra procedures.
+
+Translated from Zaikun Zhang's modern-Fortran reference implementation in PRIMA.
+
+Dedicated to late Professor M. J. D. Powell FRS (1936--2015).
+
+Python translation by Nickolai Belakovski.
+'''
+
+import numpy as np
+from .consts import DEBUGGING, EPS, REALMAX, REALMIN
+from .present import present
+
+
+# We use naive implementations of matrix multiplication and other routines for two
+# reasons:
+# 1. When Fortran is compiled in debug mode, and Python is using these routines, we
+#    can get bit for bit identical results as compared to Fortran. This is helpful
+#    for comparing the two implementations. It will be particularly helpful when porting
+#    the other implementations like LINCOA, etc.
+# 2. On some problems this algorithm is very sensitive to errors in finite precision
+#    arithmetic. Switching to naive implementation will slow down the algorithm, but
+#    may be more stable.
+USE_NAIVE_MATH = False
+
+
+def inprod(x, y):
+    if not USE_NAIVE_MATH:
+        return np.dot(x, y)
+    result = 0
+    for i in range(len(x)):
+        result += x[i] * y[i]
+    return result
+
+
+def matprod12(x, y):
+    result = np.zeros(y.shape[1])
+    for i in range(y.shape[1]):
+        result[i] = inprod(x, y[:, i])
+    return result
+
+
+def matprod21(x, y):
+    result = np.zeros(x.shape[0])
+    for i in range(x.shape[1]):
+        result += x[:, i] * y[i]
+    return result
+
+
+def matprod22(x, y):
+    result = np.zeros((x.shape[0], y.shape[1]))
+    for i in range(y.shape[1]):
+        for j in range(x.shape[1]):
+            result[:, j] += x[:, i] * y[i, j]
+    return result
+
+
+def matprod(x, y):
+    if not USE_NAIVE_MATH:
+        return x@y
+    if len(x.shape) == 1 and len(y.shape) == 1:
+        return inprod(x, y)
+    elif len(x.shape) == 1 and len(y.shape) == 2:
+        return matprod12(x, y)
+    elif len(x.shape) == 2 and len(y.shape) == 1:
+        return matprod21(x, y)
+    elif len(x.shape) == 2 and len(y.shape) == 2:
+        return matprod22(x, y)
+    else:
+        raise ValueError(f'Invalid shapes for x and y: {x.shape} and {y.shape}')
+
+
+def outprod(x, y):
+    if not USE_NAIVE_MATH:
+        return np.outer(x, y)
+    result = np.zeros((len(x), len(y)))
+    for i in range(len(x)):
+            result[:, i] = x * y[i]
+    return result
+
+
+def lsqr(A, b, Q, Rdiag):
+    if not USE_NAIVE_MATH:
+        return np.linalg.lstsq(A, b, rcond=None)[0]
+
+    m = A.shape[0]
+    n = A.shape[1]
+
+    rank = min(m, n)
+
+    x = np.zeros(n)
+    y = b.copy()
+
+    for i in range(rank - 1, -1, -1):
+        yq = inprod(y, Q[:, i])
+        yqa = inprod(np.abs(y), np.abs(Q[:, i]))
+        if isminor(yq, yqa):
+            x[i] = 0
+        else:
+            x[i] = yq / Rdiag[i]
+            y = y - x[i] * A[:, i]
+    return x
+
+
+def hypot(x1, x2):
+    if not USE_NAIVE_MATH:
+        return np.hypot(x1, x2)
+    if not np.isfinite(x1):
+        r = abs(x1)
+    elif not np.isfinite(x2):
+        r = abs(x2)
+    else:
+        y = abs(np.array([x1, x2]))
+        y = np.array([min(y), max(y)])
+        if y[0] > np.sqrt(REALMIN) and y[1] < np.sqrt(REALMAX/2.1):
+            r = np.sqrt(sum(y*y))
+        elif y[1] > 0:
+            r = y[1] * np.sqrt((y[0]/y[1])*(y[0]/y[1]) + 1)
+        else:
+            r = 0
+    return r
+
+
+def norm(x):
+    if not USE_NAIVE_MATH:
+        return np.linalg.norm(x)
+    # NOTE: Avoid np.pow! And exponentiation in general!
+    # It appears that in Fortran, x*x and x**2 are the same, but in Python they are not!
+    # Try it with x = 5 - 1e-15
+    result = np.sqrt(sum([xi*xi for xi in x]))
+    return result
+
+
+def istril(A, tol=0):
+    return primasum(abs(A) - np.tril(abs(A))) <= tol
+
+def istriu(A, tol=0):
+    return primasum(abs(A) - np.triu(abs(A))) <= tol
+
+
+def inv(A):
+    if not USE_NAIVE_MATH:
+        return np.linalg.inv(A)
+    A = A.copy()
+    n = A.shape[0]
+    if istril(A):
+        # This case is invoked in COBYLA.
+        R = A.T
+        B = np.zeros((n, n))
+        for i in range(n):
+            B[i, i] = 1 / R[i, i]
+            B[:i, i] = -matprod(B[:i, :i], R[:i, i]) / R[i, i]
+        return B.T
+    elif istriu(A):
+        B = np.zeros((n, n))
+        for i in range(n):
+            B[i, i] = 1 / A[i, i]
+            B[:i, i] = -matprod(B[:i, :i], A[:i, i]) / A[i, i]
+    else:
+        # This is NOT the best algorithm for the inverse, but since the QR subroutine is available ...
+        Q, R, P = qr(A)
+        R = R.T
+        B = np.zeros((n, n))
+        for i in range(n - 1, -1, -1):
+            B[:, i] = (Q[:, i] - matprod(B[:, i + 1:n], R[i + 1:n, i])) / R[i, i]
+        InvP = np.zeros(n, dtype=int)
+        InvP[P] = np.linspace(0, n-1, n)
+        B = B[:, InvP].T
+    return B
+
+
+def qr(A):
+    m = A.shape[0]
+    n = A.shape[1]
+
+    Q = np.eye(m)
+    T = A.T
+    P = np.linspace(0, n-1, n, dtype=int)
+
+    for j in range(n):
+        k = np.argmax(primasum(primapow2(T[j:n+1, j:m+1]), axis=1), axis=0)
+        if k > 0 and k <= n - j - 1:
+            k += j
+            P[j], P[k] = P[k], P[j]
+            T[[j, k], :] = T[[k, j], :]
+        for i in range(m-1, j, -1):
+            G = planerot(T[j, [j, i]]).T
+            T[j, [j, i]] = np.append(hypot(T[j, j], T[j, i]), 0)
+            T[j + 1:n + 1, [j, i]] = matprod(T[j + 1:n + 1, [j, i]], G)
+            Q[:, [j, i]] = matprod(Q[:, [j, i]], G)
+
+    R = T.T
+
+    return Q, R, P
+
+
+def primasum(x, axis=None):
+    '''
+    According to its documentation, np.sum will sometimes do partial pairwise summation.
+    For our purposes, when comparing, we want don't want to do anything fancy, and we
+    just want to add things up one at a time.
+    '''
+    if not USE_NAIVE_MATH:
+        return np.sum(x, axis=axis)
+    if axis is None:
+        if x.ndim == 2:
+            # Sum columns first, then sum the result
+            return sum(primasum(x, axis=0))
+        else:
+            return sum(x)
+    elif axis == 0:
+        result = np.zeros(x.shape[1])
+        for i in range(x.shape[1]):
+            result[i] = sum(x[:, i])
+        return result
+    elif axis == 1:
+        result = np.zeros(x.shape[0])
+        for i in range(x.shape[0]):
+            result[i] = sum(x[i, :])
+        return result
+
+
+def primapow2(x):
+    '''
+    Believe it or now, x**2 is not always the same as x*x in Python. In Fortran they
+    appear to be identical. Here's a quick one-line to find an example on your system
+    (well, two liner after importing numpy):
+    list(filter(lambda x: x[1], [(x:=np.random.random(), x**2 - x*x != 0) for _ in range(10000)]))
+    '''
+    return x*x
+
+
+def planerot(x):
+    '''
+    As in MATLAB, planerot(x) returns a 2x2 Givens matrix G for x in R2 so that Y=G@x has Y[1] = 0.
+    Roughly speaking, G = np.array([[x[0]/R, x[1]/R], [-x[1]/R, x[0]/R]]), where R = np.linalg.norm(x).
+    0. We need to take care of the possibilities of R=0, Inf, NaN, and over/underflow.
+    1. The G defined above is continuous with respect to X except at 0. Following this definition,
+    G = np.array([[np.sign(x[0]), 0], [0, np.sign(x[0])]]) if x[1] == 0,
+    G = np.array([[0, np.sign(x[1])], [np.sign(x[1]), 0]]) if x[0] == 0
+    Yet some implementations ignore the signs, leading to discontinuity and numerical instability.
+    2. Difference from MATLAB: if x contains NaN of consists of only Inf, MATLAB returns a NaN matrix,
+    but we return an identity matrix or a matrix of +/-np.sqrt(2). We intend to keep G always orthogonal.
+    '''
+
+    # Preconditions
+    if DEBUGGING:
+        assert len(x) == 2, "x must be a 2-vector"
+
+    # ==================
+    # Calculation starts
+    # ==================
+
+    # Define C = X(1) / R and S = X(2) / R with R = HYPOT(X(1), X(2)). Handle Inf/NaN, over/underflow.
+    if (any(np.isnan(x))):
+        # In this case, MATLAB sets G to NaN(2, 2). We refrain from doing so to keep G orthogonal.
+        c = 1
+        s = 0
+    elif (all(np.isinf(x))):
+        # In this case, MATLAB sets G to NaN(2, 2). We refrain from doing so to keep G orthogonal.
+        c = 1 / np.sqrt(2) * np.sign(x[0])
+        s = 1 / np.sqrt(2) * np.sign(x[1])
+    elif (abs(x[0]) <= 0 and abs(x[1]) <= 0): # X(1) == 0 == X(2).
+        c = 1
+        s = 0
+    elif (abs(x[1]) <= EPS * abs(x[0])):
+        # N.B.:
+        # 0. With <= instead of <, this case covers X(1) == 0 == X(2), which is treated above separately
+        # to avoid the confusing SIGN(., 0) (see 1).
+        # 1. SIGN(A, 0) = ABS(A) in Fortran but sign(0) = 0 in MATLAB, Python, Julia, and R#
+        # 2. Taking SIGN(X(1)) into account ensures the continuity of G with respect to X except at 0.
+        c = np.sign(x[0])
+        s = 0
+    elif (abs(x[0]) <= EPS * abs(x[1])):
+        # N.B.: SIGN(A, X) = ABS(A) * sign of X /= A * sign of X # Therefore, it is WRONG to define G
+        # as SIGN(RESHAPE([ZERO, -ONE, ONE, ZERO], [2, 2]), X(2)). This mistake was committed on
+        # 20211206 and took a whole day to debug! NEVER use SIGN on arrays unless you are really sure.
+        c = 0
+        s = np.sign(x[1])
+    else:
+        # Here is the normal case. It implements the Givens rotation in a stable & continuous way as in:
+        # Bindel, D., Demmel, J., Kahan, W., and Marques, O. (2002). On computing Givens rotations
+        # reliably and efficiently. ACM Transactions on Mathematical Software (TOMS), 28(2), 206-238.
+        # N.B.: 1. Modern compilers compute SQRT(REALMIN) and SQRT(REALMAX/2.1) at compilation time.
+        # 2. The direct calculation without involving T and U seems to work better; use it if possible.
+        if (all(np.logical_and(np.sqrt(REALMIN) < np.abs(x), np.abs(x) < np.sqrt(REALMAX / 2.1)))):
+            # Do NOT use HYPOTENUSE here; the best implementation for one may be suboptimal for the other
+            r = norm(x)
+            c = x[0] / r
+            s = x[1] / r
+        elif (abs(x[0]) > abs(x[1])):
+            t = x[1] / x[0]
+            u = max(1, abs(t), np.sqrt(1 + t*t))  # MAXVAL: precaution against rounding error.
+            u *= np.sign(x[0]) ##MATLAB: u = sign(x(1))*sqrt(1 + t**2)
+            c = 1 / u
+            s = t / u
+        else:
+            t = x[0] / x[1]
+            u = max([1, abs(t), np.sqrt(1 + t*t)])  # MAXVAL: precaution against rounding error.
+            u *= np.sign(x[1]) ##MATLAB: u = sign(x(2))*sqrt(1 + t**2)
+            c = t / u
+            s = 1 / u
+
+    G = np.array([[c, s], [-s, c]]) #  MATLAB: G = [c, s; -s, c]
+
+    #====================#
+    #  Calculation ends  #
+    #====================#
+
+    # Postconditions
+    if DEBUGGING:
+        assert G.shape == (2,2)
+        assert np.all(np.isfinite(G))
+        assert abs(G[0, 0] - G[1, 1]) + abs(G[0, 1] + G[1, 0]) <= 0
+        tol = np.maximum(1.0E-10, np.minimum(1.0E-1, 1.0E6 * EPS))
+        assert isorth(G, tol)
+        if all(np.logical_and(np.isfinite(x), np.abs(x) < np.sqrt(REALMAX / 2.1))):
+            r = np.linalg.norm(x)
+            assert max(abs(G@x - [r, 0])) <= max(tol, tol * r), 'G @ X = [||X||, 0]'
+
+    return G
+
+
+def isminor(x, ref):
+    '''
+    This function tests whether x is minor compared to ref. It is used by Powell, e.g., in COBYLA.
+    In precise arithmetic, isminor(x, ref) is true if and only if x == 0; in floating point
+    arithmetic, isminor(x, ref) is true if x is 0 or its nonzero value can be attributed to
+    computer rounding errors according to ref.
+    Larger sensitivity means the function is more strict/precise, the value 0.1 being due to Powell.
+
+    For example:
+    isminor(1e-20, 1e300) -> True, because in floating point arithmetic 1e-20 cannot be added to
+    1e300 without being rounded to 1e300.
+    isminor(1e300, 1e-20) -> False, because in floating point arithmetic adding 1e300 to 1e-20
+    dominates the latter number.
+    isminor(3, 4) -> False, because 3 can be added to 4 without being rounded off
+    '''
+
+    sensitivity = 0.1
+    refa = abs(ref) + sensitivity * abs(x)
+    refb = abs(ref) + 2 * sensitivity * abs(x)
+    return np.logical_or(abs(ref) >= refa, refa >= refb)
+
+
+def isinv(A, B, tol=None):
+    '''
+    This procedure tests whether A = B^{-1} up to the tolerance TOL.
+    '''
+
+    # Sizes
+    n = np.size(A, 0)
+
+    # Preconditions
+    if DEBUGGING:
+        assert np.size(A, 0) == np.size(A, 1)
+        assert np.size(B, 0) == np.size(B, 1)
+        assert np.size(A, 0) == np.size(B, 0)
+        if present(tol):
+            assert tol >= 0
+
+    #====================#
+    # Calculation starts #
+    #====================#
+
+    tol = tol if present(tol) else np.minimum(1e-3, 1e2 * EPS * np.maximum(np.size(A, 0), np.size(A, 1)))
+    tol = np.max([tol, tol * np.max(abs(A)), tol * np.max(abs(B))])
+    is_inv = ((abs(matprod(A, B)) - np.eye(n)) <= tol).all() or ((abs(matprod(B, A) - np.eye(n))) <= tol).all()
+
+    #===================#
+    #  Calculation ends #
+    #===================#
+    return is_inv
+
+
+def isorth(A, tol=None):
+    '''
+    This function tests whether the matrix A has orthonormal columns up to the tolerance TOL.
+    '''
+
+    # Preconditions
+    if DEBUGGING:
+        if present(tol):
+            assert tol >= 0
+
+    #====================#
+    # Calculation starts #
+    #====================#
+
+    num_vars = np.size(A, 1)
+
+    if num_vars > np.size(A, 0):
+        is_orth = False
+    elif (np.isnan(primasum(abs(A)))):
+        is_orth = False
+    else:
+        if present(tol):
+            is_orth = (abs(matprod(A.T, A) - np.eye(num_vars)) <= np.maximum(tol, tol * np.max(abs(A)))).all()
+        else:
+            is_orth = (abs(matprod(A.T, A) - np.eye(num_vars)) <= 0).all()
+
+    #====================#
+    #  Calculation ends  #
+    #====================#
+    return is_orth
+
+
+def get_arrays_tol(*arrays):
+    """
+    Get a relative tolerance for a set of arrays. Borrowed from COBYQA
+
+    Parameters
+    ----------
+    *arrays: tuple
+        Set of `numpy.ndarray` to get the tolerance for.
+
+    Returns
+    -------
+    float
+        Relative tolerance for the set of arrays.
+
+    Raises
+    ------
+    ValueError
+        If no array is provided.
+    """
+    if len(arrays) == 0:
+        raise ValueError("At least one array must be provided.")
+    size = max(array.size for array in arrays)
+    weight = max(
+        np.max(np.abs(array[np.isfinite(array)]), initial=1.0)
+        for array in arrays
+    )
+    return 10.0 * EPS * max(size, 1.0) * weight
diff --git a/.venv/lib/python3.12/site-packages/scipy/_external/pyprima/common/message.py b/.venv/lib/python3.12/site-packages/scipy/_external/pyprima/common/message.py
new file mode 100644
index 0000000000000000000000000000000000000000..899d5fa63daa2b55bc6a1050f27786b569c0e92c
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/_external/pyprima/common/message.py
@@ -0,0 +1,290 @@
+'''
+This module provides some functions that print messages to terminal/files.
+
+Translated from Zaikun Zhang's modern-Fortran reference implementation in PRIMA.
+
+Dedicated to late Professor M. J. D. Powell FRS (1936--2015).
+
+Python translation by Nickolai Belakovski.
+
+N.B.:
+1. In case parallelism is desirable (especially during initialization), the functions may
+have to be modified or disabled due to the IO operations.
+2. IPRINT indicates the level of verbosity, which increases with the absolute value of IPRINT.
+IPRINT = +/-3 can be expensive due to high IO operations.
+'''
+
+from .consts import DEBUGGING
+from .infos import FTARGET_ACHIEVED, MAXFUN_REACHED, MAXTR_REACHED, \
+    SMALL_TR_RADIUS, TRSUBP_FAILED, NAN_INF_F, NAN_INF_X, NAN_INF_MODEL, DAMAGING_ROUNDING, \
+    NO_SPACE_BETWEEN_BOUNDS, ZERO_LINEAR_CONSTRAINT, CALLBACK_TERMINATE
+from .present import present
+import numpy as np
+
+spaces = '   '
+
+
+def get_info_string(solver, info):
+    if info == FTARGET_ACHIEVED:
+        reason = 'the target function value is achieved.'
+    elif info == MAXFUN_REACHED:
+        reason = 'the objective function has been evaluated MAXFUN times.'
+    elif info == MAXTR_REACHED:
+        reason = 'the maximal number of trust region iterations has been reached.'
+    elif info == SMALL_TR_RADIUS:
+        reason = 'the trust region radius reaches its lower bound.'
+    elif info == TRSUBP_FAILED:
+        reason = 'a trust region step has failed to reduce the quadratic model.'
+    elif info == NAN_INF_X:
+        reason = 'NaN or Inf occurs in x.'
+    elif info == NAN_INF_F:
+        reason = 'the objective function returns NaN/+Inf.'
+    elif info == NAN_INF_MODEL:
+        reason = 'NaN or Inf occurs in the models.'
+    elif info == DAMAGING_ROUNDING:
+        reason = 'rounding errors are becoming damaging.'
+    elif info == NO_SPACE_BETWEEN_BOUNDS:
+        reason = 'there is no space between the lower and upper bounds of variable.'
+    elif info == ZERO_LINEAR_CONSTRAINT:
+        reason = 'one of the linear constraints has a zero gradient'
+    elif info == CALLBACK_TERMINATE:
+        reason = 'the callback function requested termination'
+    else:
+        reason = 'UNKNOWN EXIT FLAG'
+    ret_message = f'Return from {solver} because {reason.strip()}'
+    return ret_message
+
+
+def retmsg(solver, info, iprint, nf, f, x, cstrv=None, constr=None):
+    '''
+    This function prints messages at return.
+    '''
+    # Local variables
+    valid_exit_codes = [FTARGET_ACHIEVED, MAXFUN_REACHED, MAXTR_REACHED,
+        SMALL_TR_RADIUS, TRSUBP_FAILED, NAN_INF_F, NAN_INF_X, NAN_INF_MODEL, DAMAGING_ROUNDING,
+        NO_SPACE_BETWEEN_BOUNDS, ZERO_LINEAR_CONSTRAINT, CALLBACK_TERMINATE]
+
+    # Preconditions
+    if DEBUGGING:
+        assert info in valid_exit_codes
+
+    #====================#
+    # Calculation starts #
+    #====================#
+
+    if abs(iprint) < 1:  # No printing (iprint == 0)
+        return
+    elif iprint > 0:  # Print the message to the standard out.
+        fname = ''
+    else:  # Print the message to a file named FNAME.
+        fname = f'{solver}_output.txt'
+
+    # Decide whether the problem is truly constrained.
+    if present(constr):
+        is_constrained = (np.size(constr) > 0)
+    else:
+        is_constrained = present(cstrv)
+
+    # Decide the constraint violation.
+    if present(cstrv):
+        cstrv_loc = cstrv
+    elif present(constr):
+        cstrv_loc = np.max(np.append(0, -constr))  # N.B.: We assume that the constraint is CONSTR >= 0.
+    else:
+        cstrv_loc = 0
+
+    # Decide the return message.
+    ret_message = get_info_string(solver, info)
+
+    if np.size(x) <= 2:
+        x_message = f'\nThe corresponding X is: {x}'  # Printed in one line
+    else:
+        x_message = f'\nThe corresponding X is:\n{x}'
+
+    if is_constrained:
+        nf_message = (f'\nNumber of function values = {nf}{spaces}'
+            f'Least value of F = {f}{spaces}Constraint violation = {cstrv_loc}')
+    else:
+        nf_message = f'\nNumber of function values = {nf}{spaces}Least value of F = {f}'
+
+    if is_constrained and present(constr):
+        if np.size(constr) <= 2:
+            constr_message = f'\nThe constraint value is: {constr}'  # Printed in one line
+        else:
+            constr_message = f'\nThe constraint value is:\n{constr}'
+    else:
+        constr_message = ''
+
+    # Print the message.
+    if abs(iprint) >= 2:
+        message = f'\n{ret_message}{nf_message}{x_message}{constr_message}\n'
+    else:
+        message = f'{ret_message}{nf_message}{x_message}{constr_message}\n'
+    if len(fname) > 0:
+        with open(fname, 'a') as f: f.write(message)
+    else:
+        print(message)
+
+
+def rhomsg(solver, iprint, nf, delta, f, rho, x, cstrv=None, constr=None, cpen=None):
+    '''
+    This function prints messages when RHO is updated.
+    '''
+
+    #====================#
+    # Calculation starts #
+    #====================#
+
+    if abs(iprint) < 2:  # No printing
+        return
+    elif iprint > 0:  # Print the message to the standard out.
+        fname = ''
+    else:  # Print the message to a file named FNAME.
+        fname = f'{solver.strip()}_output.txt'
+
+    # Decide whether the problem is truly constrained.
+    if present(constr):
+        is_constrained = (np.size(constr) > 0)
+    else:
+        is_constrained = present(cstrv)
+
+    # Decide the constraint violation.
+    if present(cstrv):
+        cstrv_loc = cstrv
+    elif present(constr):
+        cstrv_loc = np.max(np.append(0, -constr))  # N.B.: We assume that the constraint is CONSTR >= 0.
+    else:
+        cstrv_loc = 0
+
+    if present(cpen):
+        rho_message = (f'\nNew RHO = {rho}{spaces}Delta = {delta}{spaces}'
+            f'CPEN = {cpen}')
+    else:
+        rho_message = f'\nNew RHO = {rho}{spaces}Delta = {delta}'
+
+    if np.size(x) <= 2:
+        x_message = f'\nThe corresponding X is: {x}'  # Printed in one line
+    else:
+        x_message = f'\nThe corresponding X is:\n{x}'
+
+    if is_constrained:
+        nf_message = (f'\nNumber of function values = {nf}{spaces}'
+            f'Least value of F = {f}{spaces}Constraint violation = {cstrv_loc}')
+    else:
+        nf_message = f'\nNumber of function values = {nf}{spaces}Least value of F = {f}'
+
+    if is_constrained and present(constr):
+        if np.size(constr) <= 2:
+            constr_message = f'\nThe constraint value is: {constr}'  # Printed in one line
+        else:
+            constr_message = f'\nThe constraint value is:\n{constr}'
+    else:
+        constr_message = ''
+
+    # Print the message.
+    if abs(iprint) >= 3:
+        message = f'\n{rho_message}{nf_message}{x_message}{constr_message}'
+    else:
+        message = f'{rho_message}{nf_message}{x_message}{constr_message}'
+    if len(fname) > 0:
+        with open(fname, 'a') as f: f.write(message)
+    else:
+        print(message)
+
+    #====================#
+    #  Calculation ends  #
+    #====================#
+
+
+def cpenmsg(solver, iprint, cpen):
+    '''
+    This function prints a message when CPEN is updated.
+    '''
+
+    #====================#
+    # Calculation starts #
+    #====================#
+
+    if abs(iprint) < 2:  # No printing
+        return
+    elif iprint > 0:  # Print the message to the standard out.
+        fname = ''
+    else:  # Print the message to a file named FNAME.
+        fname = f'{solver.strip()}_output.txt'
+
+    # Print the message.
+    if abs(iprint) >= 3:
+        message = f'\nSet CPEN to {cpen}'
+    else:
+        message = f'\n\nSet CPEN to {cpen}'
+    if len(fname) > 0:
+        with open(fname, 'a') as f: f.write(message)
+    else:
+        print(message)
+
+    #====================#
+    #  Calculation ends  #
+    #====================#
+
+
+def fmsg(solver, state, iprint, nf, delta, f, x, cstrv=None, constr=None):
+    '''
+    This subroutine prints messages for each evaluation of the objective function.
+    '''
+
+    #====================#
+    # Calculation starts #
+    #====================#
+
+    if abs(iprint) < 2:  # No printing
+        return
+    elif iprint > 0:  # Print the message to the standard out.
+        fname = ''
+    else:  # Print the message to a file named FNAME.
+        fname = f'{solver.strip()}_output.txt'
+
+    # Decide whether the problem is truly constrained.
+    if present(constr):
+        is_constrained = (np.size(constr) > 0)
+    else:
+        is_constrained = present(cstrv)
+
+    # Decide the constraint violation.
+    if present(cstrv):
+        cstrv_loc = cstrv
+    elif present(constr):
+        cstrv_loc = np.max(np.append(0, -constr))  # N.B.: We assume that the constraint is CONSTR >= 0.
+    else:
+        cstrv_loc = 0
+
+    delta_message = f'\n{state} step with radius = {delta}'
+
+    if is_constrained:
+        nf_message = (f'\nNumber of function values = {nf}{spaces}'
+            f'Least value of F = {f}{spaces}Constraint violation = {cstrv_loc}')
+    else:
+        nf_message = f'\nNumber of function values = {nf}{spaces}Least value of F = {f}'
+
+    if np.size(x) <= 2:
+        x_message = f'\nThe corresponding X is: {x}'  # Printed in one line
+    else:
+        x_message = f'\nThe corresponding X is:\n{x}'
+
+    if is_constrained and present(constr):
+        if np.size(constr) <= 2:
+            constr_message = f'\nThe constraint value is: {constr}'  # Printed in one line
+        else:
+            constr_message = f'\nThe constraint value is:\n{constr}'
+    else:
+        constr_message = ''
+
+    # Print the message.
+    message = f'{delta_message}{nf_message}{x_message}{constr_message}'
+    if len(fname) > 0:
+        with open(fname, 'a') as f: f.write(message)
+    else:
+        print(message)
+
+    #====================#
+    #  Calculation ends  #
+    #====================#
diff --git a/.venv/lib/python3.12/site-packages/scipy/_external/pyprima/common/powalg.py b/.venv/lib/python3.12/site-packages/scipy/_external/pyprima/common/powalg.py
new file mode 100644
index 0000000000000000000000000000000000000000..1a8268b2631ba830f8bd36129dd10a3fb9133dc1
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/_external/pyprima/common/powalg.py
@@ -0,0 +1,131 @@
+'''
+This module provides some Powell-style linear algebra procedures.
+
+Translated from Zaikun Zhang's modern-Fortran reference implementation in PRIMA.
+
+Dedicated to late Professor M. J. D. Powell FRS (1936--2015).
+
+Python translation by Nickolai Belakovski.
+'''
+
+import numpy as np
+from .linalg import isminor, planerot, matprod, inprod, hypot
+from .consts import DEBUGGING, EPS
+
+
+def qradd_Rdiag(c, Q, Rdiag, n):
+    '''
+    This function updates the QR factorization of an MxN matrix A of full column rank, attempting to
+    add a new column C to this matrix as the LAST column while maintaining the full-rankness.
+    Case 1. If C is not in range(A) (theoretically, it implies N < M), then the new matrix is np.hstack([A, C])
+    Case 2. If C is in range(A), then the new matrix is np.hstack([A[:, :n-1], C])
+    N.B.:
+    0. Instead of R, this subroutine updates Rdiag, which is np.diag(R), with a size at most M and at
+    least min(m, n+1). The number is min(m, n+1) rather than min(m, n) as n may be augmented by 1 in
+    the function.
+    1. With the two cases specified as above, this function does not need A as an input.
+    2. The function changes only Q[:, nsave:m] (nsave is the original value of n) and
+    R[:, n-1] (n takes the updated value)
+    3. Indeed, when C is in range(A), Powell wrote in comments that "set iOUT to the index of the
+    constraint (here, column of A --- Zaikun) to be deleted, but branch if no suitable index can be
+    found". The idea is to replace a column of A by C so that the new matrix still has full rank
+    (such a column must exist unless C = 0). But his code essentially sets iout=n always. Maybe he
+    found this worked well enough in practice. Meanwhile, Powell's code includes a snippet that can
+    never be reached, which was probably intended to deal with the case that IOUT != n
+    '''
+    m = Q.shape[1]
+    nsave = n  # Needed for debugging (only)
+
+    # As in Powell's COBYLA, CQ is set to 0 at the positions with CQ being negligible as per ISMINOR.
+    # This may not be the best choice if the subroutine is used in other contexts, e.g. LINCOA.
+    cq = matprod(c, Q)
+    cqa = matprod(abs(c), abs(Q))
+    # The line below basically makes an element of cq 0 if adding it to the corresponding element of
+    # cqa does not change the latter.
+    cq = np.array([0 if isminor(cqi, cqai) else cqi for cqi, cqai in zip(cq, cqa)])
+
+    # Update Q so that the columns of Q[:, n+1:m] are orthogonal to C. This is done by applying a 2D
+    # Givens rotation to Q[:, [k, k+1]] from the right to zero C' @ Q[:, k+1] out for K=n+1, ... m-1.
+    # Nothing will be done if n >= m-1
+    for k in range(m-2, n-1, -1):
+        if abs(cq[k+1]) > 0:
+            # Powell wrote cq[k+1] != 0 instead of abs. The two differ if cq[k+1] is NaN.
+            # If we apply the rotation below when cq[k+1] = 0, then cq[k] will get updated to |cq[k]|.
+            G = planerot(cq[k:k+2])
+            Q[:, [k, k+1]] = matprod(Q[:, [k, k+1]], G.T)
+            cq[k] = hypot(*cq[k:k+2])
+
+    # Augment n by 1 if C is not in range(A)
+    if n < m:
+        # Powell's condition for the following if: cq[n+1] != 0
+        if abs(cq[n]) > EPS**2 and not isminor(cq[n], cqa[n]):
+            n += 1
+
+    # Update Rdiag so that Rdiag[n] = cq[n] = np.dot(c, q[:, n]). Note that N may be been augmented.
+    if n - 1 >= 0 and n - 1 < m:  # n >= m should not happen unless the input is wrong
+        Rdiag[n - 1] = cq[n - 1]
+
+    if DEBUGGING:
+        assert nsave <= n <= min(nsave + 1, m)
+        assert n <= len(Rdiag) <= m
+        assert Q.shape == (m, m)
+
+    return Q, Rdiag, n
+
+
+def qrexc_Rdiag(A, Q, Rdiag, i):  # Used in COBYLA
+    '''
+    This function updates the QR factorization for an MxN matrix A=Q@R so that the updated Q and
+    R form a QR factorization of [A_0, ..., A_{I-1}, A_{I+1}, ..., A_{N-1}, A_I] which is the matrix
+    obtained by rearranging columns [I, I+1, ... N-1] of A to [I+1, ..., N-1, I]. Here A is ASSUMED TO
+    BE OF FULL COLUMN RANK, Q is a matrix whose columns are orthogonal, and R, which is not present,
+    is an upper triangular matrix whose diagonal entries are nonzero. Q and R need not be square.
+    N.B.:
+    0. Instead of R, this function updates Rdiag, which is np.diag(R), the size being n.
+    1. With L = Q.shape[1] = R.shape[0], we have M >= L >= N. Most often L = M or N.
+    2. This function changes only Q[:, i:] and Rdiag[i:]
+    3. (NDB 20230919) In Python, i is either icon or nact - 2, whereas in FORTRAN it is either icon or nact - 1.
+    '''
+
+    # Sizes
+    m, n = A.shape
+
+    # Preconditions
+    assert n >= 1 and n <= m
+    assert i >= 0 and i < n
+    assert len(Rdiag) == n
+    assert Q.shape[0] == m and Q.shape[1] >= n and Q.shape[1] <= m
+    # tol = max(1.0E-8, min(1.0E-1, 1.0E8 * EPS * m + 1))
+    # assert isorth(Q, tol)  # Costly!
+
+
+    if i < 0 or i >= n:
+        return Q, Rdiag
+
+    # Let R be the upper triangular matrix in the QR factorization, namely R = Q.T@A.
+    # For each k, find the Givens rotation G with G@(R[k:k+2, :]) = [hypt, 0], and update Q[:, k:k+2]
+    # to Q[:, k:k+2]@(G.T). Then R = Q.T@A is an upper triangular matrix as long as A[:, [k, k+1]] is
+    # updated to A[:, [k+1, k]]. Indeed, this new upper triangular matrix can be obtained by first
+    # updating R[[k, k+1], :] to G@(R[[k, k+1], :]) and then exchanging its columns K and K+1; at the same
+    # time, entries k and k+1 of R's diagonal Rdiag become [hypt, -(Rdiag[k+1]/hypt)*RDiag[k]].
+    # After this is done for each k = 0, ..., n-2, we obtain the QR factorization of the matrix that
+    # rearranges columns [i, i+1, ... n-1] of A as [i+1, ..., n-1, i].
+    # Powell's code, however, is slightly different: before everything, he first exchanged columns k and
+    # k+1 of Q (as well as rows k and k+1 of R). This makes sure that the entries of the update Rdiag
+    # are all positive if it is the case for the original Rdiag.
+    for k in range(i, n-1):
+        G = planerot([Rdiag[k+1], inprod(Q[:, k], A[:, k+1])])
+        Q[:, [k, k+1]] = matprod(Q[:, [k+1, k]], (G.T))
+        # Powell's code updates Rdiag in the following way:
+        # hypt = np.sqrt(Rdiag[k+1]**2 + np.dot(Q[:, k], A[:, k+1])**2)
+        # Rdiag[[k, k+1]] = [hypt, (Rdiag[k+1]/hypt)*Rdiag[k]]
+        # Note that Rdiag[n-1] inherits all rounding in Rdiag[i:n-1] and Q[:, i:n-1] and hence contains
+        # significant errors. Thus we may modify Powell's code to set only Rdiag[k] = hypt here and then
+        # calculate Rdiag[n] by an inner product after the loop. Nevertheless, we simple calculate RDiag
+        # from scratch below.
+
+    # Calculate Rdiag(i:n) from scratch
+    Rdiag[i:n-1] = [inprod(Q[:, k], A[:, k+1]) for k in range(i, n-1)]
+    Rdiag[n-1] = inprod(Q[:, n-1], A[:, i])
+
+    return Q, Rdiag
diff --git a/.venv/lib/python3.12/site-packages/scipy/_external/pyprima/common/preproc.py b/.venv/lib/python3.12/site-packages/scipy/_external/pyprima/common/preproc.py
new file mode 100644
index 0000000000000000000000000000000000000000..465b0b2de289b61be4c560dec89482887002aa24
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/_external/pyprima/common/preproc.py
@@ -0,0 +1,277 @@
+'''
+This is a module that preprocesses the inputs.
+
+Translated from Zaikun Zhang's modern-Fortran reference implementation in PRIMA.
+
+Dedicated to late Professor M. J. D. Powell FRS (1936--2015).
+
+Python translation by Nickolai Belakovski.
+'''
+
+from .consts import DEBUGGING, EPS, IPRINT_DEFAULT, FTARGET_DEFAULT, \
+    MIN_MAXFILT, MAXFILT_DEFAULT, MAXHISTMEM, ETA1_DEFAULT, ETA2_DEFAULT, \
+    GAMMA1_DEFAULT, GAMMA2_DEFAULT, RHOBEG_DEFAULT, RHOEND_DEFAULT, \
+    CTOL_DEFAULT, CWEIGHT_DEFAULT
+from .present import present
+from warnings import warn
+import numpy as np
+
+
+def preproc(solver, num_vars, iprint, maxfun, maxhist, ftarget, rhobeg, rhoend,
+            num_constraints=None, npt=None, maxfilt=None, ctol=None, cweight=None,
+            eta1=None, eta2=None, gamma1=None, gamma2=None, is_constrained=None, has_rhobeg=None,
+            honour_x0=None, xl=None, xu=None, x0=None):
+    '''
+    This subroutine preprocesses the inputs. It does nothing to the inputs that are valid.
+    '''
+    # Preconditions
+    if DEBUGGING:
+        assert num_vars >= 1
+        if present(num_constraints):
+            assert num_constraints >= 0
+            assert num_constraints == 0 or solver.lower() == 'cobyla'
+        if solver.lower() == 'cobyla' and present(num_constraints) and present(is_constrained):
+            assert num_constraints == 0 or is_constrained
+        if solver.lower() == 'bobyqa':
+            assert present(xl) and present(xu)
+            assert all(xu - xl >= 2 * EPS)
+        if present(honour_x0):
+            assert solver.lower() == 'bobyqa' and present(has_rhobeg) and present(xl) and present(xu) and present(x0)
+
+    #====================#
+    # Calculation starts #
+    #====================#
+
+    # Read num_constraints, if necessary
+    num_constraints = num_constraints if (present(num_constraints) and solver.lower() == 'cobyla') else 0
+
+    # Decide whether the problem is truly constrained
+    is_constrained = is_constrained if (present(is_constrained)) else num_constraints > 0
+
+    # Validate IPRINT
+    if np.abs(iprint) > 3:
+        iprint = IPRINT_DEFAULT
+        warn(f'{solver}: Invalid IPRINT; it should be 0, 1, -1, 2, -2, 3, or -3; it is set to {iprint}')
+
+    # Validate MAXFUN
+    if solver.lower() == 'uobyqa':
+        min_maxfun = (num_vars + 1) * (num_vars + 2) / 2 + 1
+        min_maxfun_str = '(N+1)(N+2)/2 + 1'
+    elif solver.lower() == 'cobyla':
+        min_maxfun = num_vars + 2
+        min_maxfun_str = 'num_vars + 2'
+    else:  # CASE ('NEWUOA', 'BOBYQA', 'LINCOA')
+        min_maxfun = num_vars + 3
+        min_maxfun_str = 'num_vars + 3'
+    if maxfun < min_maxfun:
+        maxfun = min_maxfun
+        warn(f'{solver}: Invalid MAXFUN; it should be at least {min_maxfun_str}; it is set to {maxfun}')
+
+    # Validate MAXHIST
+    if maxhist < 0:
+        maxhist = maxfun
+        warn(f'{solver}: Invalid MAXHIST; it should be a nonnegative integer; it is set to {maxhist}')
+    maxhist = min(maxhist, maxfun)  # MAXHIST > MAXFUN is never needed.
+
+    # Validate FTARGET
+    if np.isnan(ftarget):
+        ftarget = FTARGET_DEFAULT
+        warn(f'{solver}: Invalid FTARGET; it should be a real number; it is set to {ftarget}')
+
+    # Validate NPT
+    if (solver.lower() == 'newuoa' or solver.lower() == 'bobyqa' or solver.lower() == 'lincoa') and present(npt):
+        if (npt < num_vars + 2 or npt > min(maxfun - 1, ((num_vars + 2) * (num_vars + 1)) / 2)):
+            npt = int(min(maxfun - 1, 2 * num_vars + 1))
+            warn(f'{solver}: Invalid NPT; it should be an integer in the interval [N+2, (N+1)(N+2)/2] and less than MAXFUN; it is set to {npt}')
+
+    # Validate MAXFILT
+    if present(maxfilt) and (solver.lower() == 'lincoa' or solver.lower() == 'cobyla'):
+        maxfilt_in = maxfilt
+        if maxfilt < 1:
+            maxfilt = MAXFILT_DEFAULT  # The inputted MAXFILT is obviously wrong.
+        else:
+            maxfilt = max(MIN_MAXFILT, maxfilt)  # The inputted MAXFILT is too small.
+        # Further revise MAXFILT according to MAXHISTMEM.
+        if solver.lower() == 'lincoa':
+            unit_memo = (num_vars + 2) * np.dtype(float).itemsize
+        elif solver.lower() == 'cobyla':
+            unit_memo = (num_constraints + num_vars + 2) * np.dtype(float).itemsize
+        else:
+            unit_memo = 1
+        # We cannot simply set MAXFILT = MIN(MAXFILT, MAXHISTMEM/...), as they may not have
+        # the same kind, and compilers may complain. We may convert them, but overflow may occur.
+        if maxfilt > MAXHISTMEM / unit_memo:
+            maxfilt = int(MAXHISTMEM / unit_memo)  # Integer division.
+        maxfilt = min(maxfun, max(MIN_MAXFILT, maxfilt))
+        if is_constrained:
+            if maxfilt_in < 1:
+                warn(f'{solver}: Invalid MAXFILT; it should be a positive integer; it is set to  {maxfilt}')
+            elif maxfilt_in < min(maxfun, MIN_MAXFILT):
+                warn(f'{solver}: MAXFILT is too small; it is set to {maxfilt}')
+            elif maxfilt < min(maxfilt_in, maxfun):
+                warn(f'{solver}: MAXFILT is set to {maxfilt} due to memory limit')
+
+    # Validate ETA1 and ETA2
+    eta1_local = eta1 if present(eta1) else ETA1_DEFAULT
+    eta2_local = eta2 if present(eta2) else ETA2_DEFAULT
+
+    # When the difference between ETA1 and ETA2 is tiny, we force them to equal.
+    # See the explanation around RHOBEG and RHOEND for the reason.
+    if present(eta1) and present(eta2):
+        if np.abs(eta1 - eta2) < 1.0E2 * EPS * max(np.abs(eta1), 1):
+            eta2 = eta1
+
+    if present(eta1):
+        if np.isnan(eta1):
+            # In this case, we take the value hard coded in Powell's original code
+            # without any warning. It is useful when interfacing with MATLAB/Python.
+            eta1 = ETA1_DEFAULT
+        elif eta1 < 0 or eta1 >= 1:
+            # Take ETA2 into account if it has a valid value.
+            if present(eta2) and eta2_local > 0 and eta2_local <= 1:
+                eta1 = max(EPS, eta2 / 7.0)
+            else:
+                eta1 = ETA1_DEFAULT
+            warn(f'{solver}: Invalid ETA1; it should be in the interval [0, 1) and not more than ETA2; it is set to {eta1}')
+
+    if present(eta2):
+        if np.isnan(eta2):
+            # In this case, we take the value hard coded in Powell's original code
+            # without any warning. It is useful when interfacing with MATLAB/Python.
+            eta2 = ETA2_DEFAULT
+        elif present(eta1) and (eta2 < eta1_local or eta2 > 1):
+            eta2 = (eta1 + 2) / 3.0
+            warn(f'{solver}: Invalid ETA2; it should be in the interval [0, 1) and not less than ETA1; it is set to {eta2}')
+
+    # Validate GAMMA1 and GAMMA2
+    if present(gamma1):
+        if np.isnan(gamma1):
+            # In this case, we take the value hard coded in Powell's original code
+            # without any warning. It is useful when interfacing with MATLAB/Python.
+            gamma1 = GAMMA1_DEFAULT
+        elif gamma1 <= 0 or gamma1 >= 1:
+            gamma1 = GAMMA1_DEFAULT
+            warn(f'{solver}: Invalid GAMMA1; it should in the interval (0, 1); it is set to {gamma1}')
+
+    if present(gamma2):
+        if np.isnan(gamma2):
+            # In this case, we take the value hard coded in Powell's original code
+            # without any warning. It is useful when interfacing with MATLAB/Python.
+            gamma2 = GAMMA2_DEFAULT
+        elif gamma2 < 1 or np.isinf(gamma2):
+            gamma2 = GAMMA2_DEFAULT
+            warn(f'{solver}: Invalid GAMMA2; it should be a real number not less than 1; it is set to {gamma2}')
+
+    # Validate RHOBEG and RHOEND
+
+    if np.abs(rhobeg - rhoend) < 1.0e2 * EPS * np.maximum(np.abs(rhobeg), 1):
+        # When the data is passed from the interfaces (e.g., MEX) to the Fortran code, RHOBEG, and RHOEND
+        # may change a bit. It was observed in a MATLAB test that MEX passed 1 to Fortran as
+        # 0.99999999999999978. Therefore, if we set RHOEND = RHOBEG in the interfaces, then it may happen
+        # that RHOEND > RHOBEG, which is considered as an invalid input. To avoid this situation, we
+        # force RHOBEG and RHOEND to equal when the difference is tiny.
+        rhoend = rhobeg
+
+    # Revise the default values for RHOBEG/RHOEND according to the solver.
+    if solver.lower() == 'bobyqa':
+        rhobeg_default = np.maximum(EPS, np.min(RHOBEG_DEFAULT, np.min(xu - xl) / 4.0))
+        rhoend_default = np.maximum(EPS, np.min(0.1 * rhobeg_default, RHOEND_DEFAULT))
+    else:
+        rhobeg_default = RHOBEG_DEFAULT
+        rhoend_default = RHOEND_DEFAULT
+
+    if solver.lower() == 'bobyqa':
+        # Do NOT merge the IF below into the ELIF above! Otherwise, XU and XL may be accessed even if
+        # the solver is not BOBYQA, because the logical evaluation is not short-circuit.
+        if rhobeg > np.min(xu - xl) / 2:
+            # Do NOT make this revision if RHOBEG not positive or not finite, because otherwise RHOBEG
+            # will get a huge value when XU or XL contains huge values that indicate unbounded variables.
+            rhobeg = np.min(xu - xl) / 4.0  # Here, we do not take RHOBEG_DEFAULT.
+            warn(f'{solver}: Invalid RHOBEG; {solver} requires 0 < RHOBEG <= np.min(XU-XL)/2; it is set to np.min(XU-XL)/4')
+    if rhobeg <= 0 or np.isnan(rhobeg) or np.isinf(rhobeg):
+        # Take RHOEND into account if it has a valid value. We do not do this if the solver is BOBYQA,
+        # which requires that RHOBEG <= (XU-XL)/2.
+        if np.isfinite(rhoend) and rhoend > 0 and solver.lower() != 'bobyqa':
+            rhobeg = max(10 * rhoend, rhobeg_default)
+        else:
+            rhobeg = rhobeg_default
+        warn(f'{solver}: Invalid RHOBEG; it should be a positive number; it is set to {rhobeg}')
+
+    if rhoend <= 0 or rhobeg < rhoend or np.isnan(rhoend) or np.isinf(rhoend):
+        rhoend = max(EPS, min(0.1 * rhobeg, rhoend_default))
+        warn(f'{solver}: Invalid RHOEND; it should be a positive number and RHOEND <= RHOBEG; it is set to {rhoend}')
+
+    # For BOBYQA, revise X0 or RHOBEG so that the distance between X0 and the inactive bounds is at
+    # least RHOBEG. If HONOUR_X0 == TRUE, revise RHOBEG if needed; otherwise, revise HONOUR_X0 if needed.
+    if present(honour_x0):
+        if honour_x0:
+            rhobeg_old = rhobeg;
+            lbx = np.isfinite(xl) & (x0 - xl <= EPS * np.maximum(1, np.abs(xl))) # X0 essentially equals XL
+            ubx = np.isfinite(xu) & (x0 - xu >= -EPS * np.maximum(1, np.abs(xu))) # X0 essentially equals XU
+            x0[lbx] = xl[lbx]
+            x0[ubx] = xu[ubx]
+            rhobeg = max(EPS, np.min([rhobeg, x0[~lbx] - xl[~lbx], xu[~ubx] - x0[~ubx]]))
+            if rhobeg_old - rhobeg > EPS * max(1, rhobeg_old):
+                rhoend = max(EPS, min(0.1 * rhobeg, rhoend)) # We do not revise RHOEND unless RHOBEG is truly revised.
+                if has_rhobeg:
+                    warn(f'{solver}: RHOBEG is revised to {rhobeg} and RHOEND to at most 0.1*RHOBEG so that the distance between X0 and the inactive bounds is at least RHOBEG')
+            else:
+                rhoend = np.minimum(rhoend, rhobeg)  # This may update RHOEND slightly.
+        else:
+            x0_old = x0  # Recorded to see whether X0 is really revised.
+            # N.B.: The following revision is valid only if XL <= X0 <= XU and RHOBEG <= MINVAL(XU-XL)/2,
+            # which should hold at this point due to the revision of RHOBEG and moderation of X0.
+            # The cases below are mutually exclusive in precise arithmetic as MINVAL(XU-XL) >= 2*RHOBEG.
+            lbx = x0 <= xl + 0.5 * rhobeg
+            lbx_plus = (x0 > xl + 0.5 * rhobeg) & (x0 < xl + rhobeg)
+            ubx = x0 >= xu - 0.5 * rhobeg
+            ubx_minus = (x0 < xu - 0.5 * rhobeg) & (x0 > xu - rhobeg)
+            x0[lbx] = xl[lbx]
+            x0[lbx_plus] = xl[lbx_plus] + rhobeg
+            x0[ubx] = xu[ubx]
+            x0[ubx_minus] = xu[ubx_minus] - rhobeg
+
+            if (any(np.abs(x0_old - x0) > 0)):
+                warn(f'{solver}: X0 is revised so that the distance between X0 and the inactive bounds is at least RHOBEG set HONOUR_X0 to .TRUE. if you prefer to keep X0 unchanged')
+
+    # Validate CTOL (it can be 0)
+    if (present(ctol)):
+        if (np.isnan(ctol) or ctol < 0):
+            ctol = CTOL_DEFAULT
+            if (is_constrained):
+                warn(f'{solver}: Invalid CTOL; it should be a nonnegative number; it is set to {ctol}')
+
+    # Validate CWEIGHT (it can be +Inf)
+    if (present(cweight)):
+        if (np.isnan(cweight) or cweight < 0):
+            cweight = CWEIGHT_DEFAULT
+            if (is_constrained):
+                warn(f'{solver}: Invalid CWEIGHT; it should be a nonnegative number; it is set to {cweight}')
+
+    #====================#
+    #  Calculation ends  #
+    #====================#
+
+    # Postconditions
+    if DEBUGGING:
+        assert abs(iprint) <= 3
+        assert maxhist >= 0 and maxhist <= maxfun
+        if present(npt):
+            assert maxfun >= npt + 1
+            assert npt >= 3
+        if present(maxfilt):
+            assert maxfilt >= np.minimum(MIN_MAXFILT, maxfun) and maxfilt <= maxfun
+        if present(eta1) and present(eta2):
+            assert eta1 >= 0 and eta1 <= eta2 and eta2 < 1
+        if present(gamma1) and present(gamma2):
+            assert gamma1 > 0 and gamma1 < 1 and gamma2 > 1
+        assert rhobeg >= rhoend and rhoend > 0
+        if solver.lower() == 'bobyqa':
+            assert all(rhobeg <= (xu - xl) / 2)
+            assert all(np.isfinite(x0))
+            assert all(x0 >= xl and (x0 <= xl or x0 >= xl + rhobeg))
+            assert all(x0 <= xu and (x0 >= xu or x0 <= xu - rhobeg))
+        if present(ctol):
+            assert ctol >= 0
+
+    return iprint, maxfun, maxhist, ftarget, rhobeg, rhoend, npt, maxfilt, ctol, cweight, eta1, eta2, gamma1, gamma2, x0
diff --git a/.venv/lib/python3.12/site-packages/scipy/_external/pyprima/common/present.py b/.venv/lib/python3.12/site-packages/scipy/_external/pyprima/common/present.py
new file mode 100644
index 0000000000000000000000000000000000000000..15f8b47b6721994399ebafff419087afe582b2b8
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/_external/pyprima/common/present.py
@@ -0,0 +1,5 @@
+def present(x):
+    '''
+    This is a Python equivalent of the Fortran 'present' function for optional arguments.
+    '''
+    return x is not None
\ No newline at end of file
diff --git a/.venv/lib/python3.12/site-packages/scipy/_external/pyprima/common/ratio.py b/.venv/lib/python3.12/site-packages/scipy/_external/pyprima/common/ratio.py
new file mode 100644
index 0000000000000000000000000000000000000000..c1c3a28ef4a49eeb47438c4a6ad3fb10e83dbc92
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/_external/pyprima/common/ratio.py
@@ -0,0 +1,54 @@
+'''
+This module calculates the reduction ratio for trust-region methods.
+
+Translated from Zaikun Zhang's modern-Fortran reference implementation in PRIMA.
+
+Dedicated to late Professor M. J. D. Powell FRS (1936--2015).
+
+Python translation by Nickolai Belakovski.
+'''
+
+from .consts import DEBUGGING, REALMAX
+import numpy as np
+
+def redrat(ared, pred, rshrink):
+    '''
+    This function evaluates the reduction ratio of a trust-region step, handling inf/nan properly.
+    '''
+
+    # Preconditions
+    if DEBUGGING:
+        assert rshrink >= 0
+
+    #====================#
+    # Calculation starts #
+    #====================#
+
+    if np.isnan(ared):
+        # This should not happen in unconstrained problems due to the moderated extreme barrier.
+        ratio = -REALMAX
+    elif np.isnan(pred) or pred <= 0:
+        # The trust-region subproblem solver fails in this rare case. Instead of terminating as Powell's
+        # original code does, we set ratio as follows so that the solver may continue to progress.
+        if ared > 0:
+            # The trial point will be accepted, but the trust-region radius will be shrunk if rshrink>0
+            ratio = rshrink/2
+        else:
+            # Set the ration to a large negative number to signify a bad trust-region step, so that the
+            # solver will check whether to take a geometry step or reduce rho.
+            ratio = -REALMAX
+    elif np.isposinf(pred) and np.isposinf(ared):
+        ratio = 1  # ared/pred = NaN if calculated directly
+    elif np.isposinf(pred) and np.isneginf(ared):
+        ratio = -REALMAX  # ared/pred = NaN if calculated directly
+    else:
+        ratio = ared/pred
+
+    #==================#
+    # Calculation ends #
+    #==================#
+
+    # Postconditions
+    if DEBUGGING:
+        assert not np.isnan(ratio)
+    return ratio
diff --git a/.venv/lib/python3.12/site-packages/scipy/_external/pyprima/common/redrho.py b/.venv/lib/python3.12/site-packages/scipy/_external/pyprima/common/redrho.py
new file mode 100644
index 0000000000000000000000000000000000000000..4b4c09b8400e694ed6f7016273aecfd384bf38a0
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/_external/pyprima/common/redrho.py
@@ -0,0 +1,47 @@
+'''
+This module provides a function that calculates RHO when it needs to be reduced.
+
+Translated from Zaikun Zhang's modern-Fortran reference implementation in PRIMA.
+
+Dedicated to late Professor M. J. D. Powell FRS (1936--2015).
+
+Python translation by Nickolai Belakovski.
+'''
+
+from .consts import DEBUGGING
+import numpy as np
+
+def redrho(rho_in, rhoend):
+    '''
+    This function calculates RHO when it needs to be reduced.
+    The scheme is shared by UOBYQA, NEWUOA, BOBYQA, LINCOA. For COBYLA, Powell's code reduces RHO by
+    'RHO *= 0.5; if RHO <= 1.5 * RHOEND: RHO = RHOEND' as specified in (11) of the COBYLA
+    paper. However, this scheme seems to work better, especially after we introduce DELTA.
+    '''
+
+    # Preconditions
+    if DEBUGGING:
+        assert rho_in > rhoend > 0
+
+    #====================#
+    # Calculation starts #
+    #====================#
+
+    rho_ratio = rho_in / rhoend
+
+    if rho_ratio > 250:
+        rho = 0.1 * rho_in
+    elif rho_ratio <= 16:
+        rho = rhoend
+    else:
+        rho = np.sqrt(rho_ratio) * rhoend  # rho = np.sqrt(rho * rhoend)
+
+    #==================#
+    # Calculation ends #
+    #==================#
+
+    # Postconditions
+    if DEBUGGING:
+        assert rho_in > rho >= rhoend
+
+    return rho
diff --git a/.venv/lib/python3.12/site-packages/scipy/_external/pyprima/common/selectx.py b/.venv/lib/python3.12/site-packages/scipy/_external/pyprima/common/selectx.py
new file mode 100644
index 0000000000000000000000000000000000000000..63d76ad709dac1c0a4d246ba24566f6c8e655124
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/_external/pyprima/common/selectx.py
@@ -0,0 +1,296 @@
+'''
+This module provides subroutines that ensure the returned X is optimal among all the calculated
+points in the sense that no other point achieves both lower function value and lower constraint
+violation at the same time. This module is needed only in the constrained case.
+
+Translated from Zaikun Zhang's modern-Fortran reference implementation in PRIMA.
+
+Dedicated to late Professor M. J. D. Powell FRS (1936--2015).
+
+Python translation by Nickolai Belakovski.
+'''
+
+import numpy as np
+import numpy.typing as npt
+from .consts import DEBUGGING, EPS, CONSTRMAX, REALMAX, FUNCMAX
+from .present import present
+
+def isbetter(f1: float, c1: float, f2: float, c2: float, ctol: float) -> bool:
+    '''
+    This function compares whether FC1 = (F1, C1) is (strictly) better than FC2 = (F2, C2), which
+    basically means that (F1 < F2 and C1 <= C2) or (F1 <= F2 and C1 < C2).
+    It takes care of the cases where some of these values are NaN or Inf, even though some cases
+    should never happen due to the moderated extreme barrier.
+    At return, BETTER = TRUE if and only if (F1, C1) is better than (F2, C2).
+    Here, C means constraint violation, which is a nonnegative number.
+    '''
+
+    # Preconditions
+    if DEBUGGING:
+        assert not any(np.isnan([f1, c1]) | np.isposinf([f2, c2]))
+        assert not any(np.isnan([f2, c2]) | np.isposinf([f2, c2]))
+        assert c1 >= 0 and c2 >= 0
+        assert ctol >= 0
+
+    #====================#
+    # Calculation starts #
+    #====================#
+
+    is_better = False
+    # Even though NaN/+Inf should not occur in FC1 or FC2 due to the moderated extreme barrier, for
+    # security and robustness, the code below does not make this assumption.
+    is_better = is_better or (any(np.isnan([f1, c1]) | np.isposinf([f1, c1])) and not any(np.isnan([f2, c2]) | np.isposinf([f2, c2])))
+
+    is_better = is_better or (f1 < f2 and c1 <= c2)
+    is_better = is_better or (f1 <= f2 and c1 < c2)
+
+    # If C1 <= CTOL and C2 is significantly larger/worse than CTOL, i.e., C2 > MAX(CTOL,CREF),
+    # then FC1 is better than FC2 as long as F1 < REALMAX. Normally CREF >= CTOL so MAX(CTOL, CREF)
+    # is indeed CREF. However, this may not be true if CTOL > 1E-1*CONSTRMAX.
+    cref = 10 * max(EPS, min(ctol, 1.0E-2 * CONSTRMAX))  # The MIN avoids overflow.
+    is_better = is_better or (f1 < REALMAX and c1 <= ctol and (c2 > max(ctol, cref) or np.isnan(c2)))
+
+    #==================#
+    # Calculation ends #
+    #==================#
+
+    # Postconditions
+    if DEBUGGING:
+        assert not (is_better and f1 >= f2 and c1 >= c2)
+        assert is_better or not (f1 <= f2 and c1 < c2)
+        assert is_better or not (f1 < f2 and c1 <= c2)
+
+    return is_better
+
+
+def savefilt(cstrv, ctol, cweight, f, x, nfilt, cfilt, ffilt, xfilt, constr=None, confilt=None):
+    '''
+    This subroutine saves X, F, and CSTRV in XFILT, FFILT, and CFILT (and CONSTR in CONFILT
+    if they are present), unless a vector in XFILT[:, :NFILT] is better than X.
+    If X is better than some vectors in XFILT[:, :NFILT] then these vectors will be
+    removed. If X is not better than any of XFILT[:, :NFILT], but NFILT == MAXFILT,
+    then we remove a column from XFILT according to the merit function
+    PHI = FFILT + CWEIGHT * max(CFILT - CTOL, 0)
+    N.B.:
+    1. Only XFILT[:, :NFILT] and FFILT[:, :NFILT] etc contains valid information,
+    while XFILT[:, NFILT+1:MAXFILT] and FFILT[:, NFILT+1:MAXFILT] etc are not
+    initialized yet.
+    2. We decide whether and X is better than another by the ISBETTER function
+    '''
+
+    # Sizes
+    if present(constr):
+        num_constraints = len(constr)
+    else:
+        num_constraints = 0
+    num_vars = len(x)
+    maxfilt = len(ffilt)
+
+    # Preconditions
+    if DEBUGGING:
+        # Check the size of X.
+        assert num_vars >= 1
+        # Check CWEIGHT and CTOL
+        assert cweight >= 0
+        assert ctol >= 0
+        # Check NFILT
+        assert nfilt >= 0 and nfilt <= maxfilt
+        # Check the sizes of XFILT, FFILT, CFILT.
+        assert maxfilt >= 1
+        assert np.size(xfilt, 0) == num_vars and np.size(xfilt, 1) == maxfilt
+        assert np.size(cfilt) == maxfilt
+        # Check the values of XFILT, FFILT, CFILT.
+        assert not (np.isnan(xfilt[:, :nfilt])).any()
+        assert not any(np.isnan(ffilt[:nfilt]) | np.isposinf(ffilt[:nfilt]))
+        assert not any(cfilt[:nfilt] < 0 | np.isnan(cfilt[:nfilt]) | np.isposinf(cfilt[:nfilt]))
+        # Check the values of X, F, CSTRV.
+        # X does not contain NaN if X0 does not and the trust-region/geometry steps are proper.
+        assert not any(np.isnan(x))
+        # F cannot be NaN/+Inf due to the moderated extreme barrier.
+        assert not (np.isnan(f) | np.isposinf(f))
+        # CSTRV cannot be NaN/+Inf due to the moderated extreme barrier.
+        assert not (cstrv < 0 | np.isnan(cstrv) | np.isposinf(cstrv))
+        # Check CONSTR and CONFILT.
+        assert present(constr) == present(confilt)
+        if present(constr):
+            # CONSTR cannot contain NaN/-Inf due to the moderated extreme barrier.
+            assert not any(np.isnan(constr) | np.isneginf(constr))
+            assert np.size(confilt, 0) == num_constraints and np.size(confilt, 1) == maxfilt
+            assert not (np.isnan(confilt[:, :nfilt]) | np.isneginf(confilt[:, :nfilt])).any()
+
+    #====================#
+    # Calculation starts #
+    #====================#
+
+    # Return immediately if any column of XFILT is better than X.
+    if any((isbetter(ffilt_i, cfilt_i, f, cstrv, ctol) for ffilt_i, cfilt_i in zip(ffilt[:nfilt], cfilt[:nfilt]))) or \
+        any(np.logical_and(ffilt[:nfilt] <= f, cfilt[:nfilt] <= cstrv)):
+        return nfilt, cfilt, ffilt, xfilt, confilt
+
+    # Decide which columns of XFILT to keep.
+    keep = np.logical_not([isbetter(f, cstrv, ffilt_i, cfilt_i, ctol) for ffilt_i, cfilt_i in zip(ffilt[:nfilt], cfilt[:nfilt])])
+
+    # If NFILT == MAXFILT and X is not better than any column of XFILT, then we remove the worst column
+    # of XFILT according to the merit function PHI = FFILT + CWEIGHT * MAX(CFILT - CTOL, ZERO).
+    if sum(keep) == maxfilt:  # In this case, NFILT = SIZE(KEEP) = COUNT(KEEP) = MAXFILT > 0.
+        cfilt_shifted = np.maximum(cfilt - ctol, 0)
+        if cweight <= 0:
+            phi = ffilt
+        elif np.isposinf(cweight):
+            phi = cfilt_shifted
+            # We should not use CFILT here; if MAX(CFILT_SHIFTED) is attained at multiple indices, then
+            # we will check FFILT to exhaust the remaining degree of freedom.
+        else:
+            phi = np.maximum(ffilt, -REALMAX)
+            phi = np.nan_to_num(phi, nan=-REALMAX)  # Replace NaN with -REALMAX and +/- inf with large numbers
+            phi += cweight * cfilt_shifted
+        # We select X to maximize PHI. In case there are multiple maximizers, we take the one with the
+        # largest CSTRV_SHIFTED; if there are more than one choices, we take the one with the largest F;
+        # if there are several candidates, we take the one with the largest CSTRV; if the last comparison
+        # still leads to more than one possibilities, then they are equally bad and we choose the first.
+        # N.B.:
+        # 1. This process is the opposite of selecting KOPT in SELECTX.
+        # 2. In finite-precision arithmetic, PHI_1 == PHI_2 and CSTRV_SHIFTED_1 == CSTRV_SHIFTED_2 do
+        # not ensure that F_1 == F_2!
+        phimax = max(phi)
+        cref = max(cfilt_shifted[phi >= phimax])
+        fref = max(ffilt[cfilt_shifted >= cref])
+        kworst = np.ma.array(cfilt, mask=(ffilt > fref)).argmax()
+        if kworst < 0 or kworst >= len(keep):  #  For security. Should not happen.
+            kworst = 0
+        keep[kworst] = False
+
+    # Keep the good xfilt values and remove all the ones that are strictly worse than the new x.
+    nfilt = sum(keep)
+    index_to_keep = np.where(keep)[0]
+    xfilt[:, :nfilt] = xfilt[:, index_to_keep]
+    ffilt[:nfilt] = ffilt[index_to_keep]
+    cfilt[:nfilt] = cfilt[index_to_keep]
+    if confilt is not None and constr is not None:
+        confilt[:, :nfilt] = confilt[:, index_to_keep]
+
+    # Once we have removed all the vectors that are strictly worse than x,
+    # we add x to the filter.
+    xfilt[:, nfilt] = x
+    ffilt[nfilt] = f
+    cfilt[nfilt] = cstrv
+    if confilt is not None and constr is not None:
+        confilt[:, nfilt] = constr
+    nfilt += 1  # In Python we need to increment the index afterwards
+
+    #==================#
+    # Calculation ends #
+    #==================#
+
+    # Postconditions
+    if DEBUGGING:
+        # Check NFILT and the sizes of XFILT, FFILT, CFILT.
+        assert nfilt >= 1 and nfilt <= maxfilt
+        assert np.size(xfilt, 0) == num_vars and np.size(xfilt, 1) == maxfilt
+        assert np.size(ffilt) == maxfilt
+        assert np.size(cfilt) == maxfilt
+        # Check the values of XFILT, FFILT, CFILT.
+        assert not (np.isnan(xfilt[:, :nfilt])).any()
+        assert not any(np.isnan(ffilt[:nfilt]) | np.isposinf(ffilt[:nfilt]))
+        assert not any(cfilt[:nfilt] < 0 | np.isnan(cfilt[:nfilt]) | np.isposinf(cfilt[:nfilt]))
+        # Check that no point in the filter is better than X, and X is better than no point.
+        assert not any([isbetter(ffilt_i, cfilt_i, f, cstrv, ctol) for ffilt_i, cfilt_i in zip(ffilt[:nfilt], cfilt[:nfilt])])
+        assert not any([isbetter(f, cstrv, ffilt_i, cfilt_i, ctol) for ffilt_i, cfilt_i in zip(ffilt[:nfilt], cfilt[:nfilt])])
+        # Check CONFILT.
+        if present(confilt):
+            assert np.size(confilt, 0) == num_constraints and np.size(confilt, 1) == maxfilt
+            assert not (np.isnan(confilt[:, :nfilt]) | np.isneginf(confilt[:, :nfilt])).any()
+
+
+    return nfilt, cfilt, ffilt, xfilt, confilt
+
+
+def selectx(fhist: npt.NDArray, chist: npt.NDArray, cweight: float, ctol: float):
+    '''
+    This subroutine selects X according to FHIST and CHIST, which represents (a part of) history
+    of F and CSTRV. Normally, FHIST and CHIST are not the full history but only a filter, e.g. ffilt
+    and CFILT generated by SAVEFILT. However, we name them as FHIST and CHIST because the [F, CSTRV]
+    in a filter should not dominate each other, but this subroutine does NOT assume such a property.
+    N.B.: CTOL is the tolerance of the constraint violation (CSTRV). A point is considered feasible if
+    its constraint violation is at most CTOL. Not that CTOL is absolute, not relative.
+    '''
+
+    # Sizes
+    nhist = len(fhist)
+
+    # Preconditions
+    if DEBUGGING:
+        assert nhist >= 1
+        assert np.size(chist) == nhist
+        assert not any(np.isnan(fhist) | np.isposinf(fhist))
+        assert not any(chist < 0 | np.isnan(chist) | np.isposinf(chist))
+        assert cweight >= 0
+        assert ctol >= 0
+
+    #====================#
+    # Calculation starts #
+    #====================#
+
+    # We select X among the points with F < FREF and CSTRV < CREF.
+    # Do NOT use F <= FREF, because F == FREF (FUNCMAX or REALMAX) may mean F == INF in practice!
+    if any(np.logical_and(fhist < FUNCMAX, chist < CONSTRMAX)):
+        fref = FUNCMAX
+        cref = CONSTRMAX
+    elif any(np.logical_and(fhist < REALMAX, chist < CONSTRMAX)):
+        fref = REALMAX
+        cref = CONSTRMAX
+    elif any(np.logical_and(fhist < FUNCMAX, chist < REALMAX)):
+        fref = FUNCMAX
+        cref = REALMAX
+    else:
+        fref = REALMAX
+        cref = REALMAX
+
+    if not any(np.logical_and(fhist < fref, chist < cref)):
+        kopt = nhist - 1
+    else:
+        # Shift the constraint violations by ctol, so that cstrv <= ctol is regarded as no violation.
+        chist_shifted = np.maximum(chist - ctol, 0)
+        # cmin is the minimal shift constraint violation attained in the history.
+        cmin = np.min(chist_shifted[fhist < fref])
+        # We consider only the points whose shifted constraint violations are at most the cref below.
+        # N.B.: Without taking np.maximum(EPS, .), cref would be 0 if cmin = 0. In that case, asking for
+        # cstrv_shift < cref would be WRONG!
+        cref = np.maximum(EPS, 2*cmin)
+        # We use the following phi as our merit function to select X.
+        if cweight <= 0:
+            phi = fhist
+        elif np.isposinf(cweight):
+            phi = chist_shifted
+            # We should not use chist here; if np.minimum(chist_shifted) is attained at multiple indices, then
+            # we will check fhist to exhaust the remaining degree of freedom.
+        else:
+            phi = np.maximum(fhist, -REALMAX) + cweight * chist_shifted
+            # np.maximum(fhist, -REALMAX) makes sure that phi will not contain NaN (unless there is a bug).
+
+        # We select X to minimize phi subject to f < fref and cstrv_shift <= cref (see the comments
+        # above for the reason of taking "<" and "<=" in these two constraints). In case there are
+        # multiple minimizers, we take the one with the least cstrv_shift; if there is more than one
+        # choice, we take the one with the least f; if there are several candidates, we take the one
+        # with the least cstrv; if the last comparison still leads to more than one possibility, then
+        # they are equally good and we choose the first.
+        # N.B.:
+        # 1. This process is the opposite of selecting kworst in savefilt
+        # 2. In finite-precision arithmetic, phi_2 == phi_2 and cstrv_shift_1 == cstrv_shifted_2 do
+        # not ensure thatn f_1 == f_2!
+        phimin = np.min(phi[np.logical_and(fhist < fref, chist_shifted <= cref)])
+        cref = np.min(chist_shifted[np.logical_and(fhist < fref, phi <= phimin)])
+        fref = np.min(fhist[chist_shifted <= cref])
+        # Can't use argmin here because using it with a mask throws off the index
+        kopt = np.ma.array(chist, mask=(fhist > fref)).argmin()
+
+    #==================#
+    # Calculation ends #
+    #==================#
+
+    # Postconditions
+    if DEBUGGING:
+        assert kopt >= 0 and kopt < nhist
+        assert not any([isbetter(fhisti, chisti, fhist[kopt], chist[kopt], ctol) for fhisti, chisti in zip(fhist[:nhist], chist[:nhist])])
+
+    return kopt
diff --git a/.venv/lib/python3.12/site-packages/scipy/_lib/__init__.py b/.venv/lib/python3.12/site-packages/scipy/_lib/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..2140970015d099763797d60a98a3a3b6f4b5f219
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/_lib/__init__.py
@@ -0,0 +1,14 @@
+"""
+Module containing private utility functions
+===========================================
+
+The ``scipy._lib`` namespace is empty (for now). Tests for all
+utilities in submodules of ``_lib`` can be run with::
+
+    from scipy import _lib
+    _lib.test()
+
+"""
+from scipy._lib._testutils import PytestTester
+test = PytestTester(__name__)
+del PytestTester
diff --git a/.venv/lib/python3.12/site-packages/scipy/_lib/__pycache__/__init__.cpython-312.pyc b/.venv/lib/python3.12/site-packages/scipy/_lib/__pycache__/__init__.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..983f2ac90d872c518f31b705566e3fbc53764e8f
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/scipy/_lib/__pycache__/__init__.cpython-312.pyc differ
diff --git a/.venv/lib/python3.12/site-packages/scipy/_lib/__pycache__/_array_api.cpython-312.pyc b/.venv/lib/python3.12/site-packages/scipy/_lib/__pycache__/_array_api.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..210a8142ba30c1e9e305bdba04afd8e7741efc85
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/scipy/_lib/__pycache__/_array_api.cpython-312.pyc differ
diff --git a/.venv/lib/python3.12/site-packages/scipy/_lib/__pycache__/_array_api_override.cpython-312.pyc b/.venv/lib/python3.12/site-packages/scipy/_lib/__pycache__/_array_api_override.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..5b30025864606cfeee1238758f62ee88f6d346b7
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/scipy/_lib/__pycache__/_array_api_override.cpython-312.pyc differ
diff --git a/.venv/lib/python3.12/site-packages/scipy/_lib/__pycache__/_ccallback.cpython-312.pyc b/.venv/lib/python3.12/site-packages/scipy/_lib/__pycache__/_ccallback.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..76e8a3dac5ec59e11ce177ffeba8c2704b1276c8
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/scipy/_lib/__pycache__/_ccallback.cpython-312.pyc differ
diff --git a/.venv/lib/python3.12/site-packages/scipy/_lib/__pycache__/_docscrape.cpython-312.pyc b/.venv/lib/python3.12/site-packages/scipy/_lib/__pycache__/_docscrape.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..414231848c8e61e0575eb0ecf943f6494999345d
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/scipy/_lib/__pycache__/_docscrape.cpython-312.pyc differ
diff --git a/.venv/lib/python3.12/site-packages/scipy/_lib/__pycache__/_sparse.cpython-312.pyc b/.venv/lib/python3.12/site-packages/scipy/_lib/__pycache__/_sparse.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..71840599a5f1b3abc8eb3fc9491d3d55e9cce00b
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/scipy/_lib/__pycache__/_sparse.cpython-312.pyc differ
diff --git a/.venv/lib/python3.12/site-packages/scipy/_lib/__pycache__/_testutils.cpython-312.pyc b/.venv/lib/python3.12/site-packages/scipy/_lib/__pycache__/_testutils.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..2f2611f12d7c2ff66f11be7f654263fc0958723a
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/scipy/_lib/__pycache__/_testutils.cpython-312.pyc differ
diff --git a/.venv/lib/python3.12/site-packages/scipy/_lib/__pycache__/_util.cpython-312.pyc b/.venv/lib/python3.12/site-packages/scipy/_lib/__pycache__/_util.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..c0a557aca070b7b80cc1a492f1e6f7135fdb67f3
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/scipy/_lib/__pycache__/_util.cpython-312.pyc differ
diff --git a/.venv/lib/python3.12/site-packages/scipy/_lib/__pycache__/deprecation.cpython-312.pyc b/.venv/lib/python3.12/site-packages/scipy/_lib/__pycache__/deprecation.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..87579e2612df2eab8665910aaa8653979766d4a1
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/scipy/_lib/__pycache__/deprecation.cpython-312.pyc differ
diff --git a/.venv/lib/python3.12/site-packages/scipy/_lib/__pycache__/uarray.cpython-312.pyc b/.venv/lib/python3.12/site-packages/scipy/_lib/__pycache__/uarray.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..21b5fe8febfdb80c59d6b9968260bac622cf9787
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/scipy/_lib/__pycache__/uarray.cpython-312.pyc differ
diff --git a/.venv/lib/python3.12/site-packages/scipy/_lib/_array_api.py b/.venv/lib/python3.12/site-packages/scipy/_lib/_array_api.py
new file mode 100644
index 0000000000000000000000000000000000000000..dbd393b5deae8e7b025b5d006e25333faab483da
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/_lib/_array_api.py
@@ -0,0 +1,1193 @@
+"""Utility functions to use Python Array API compatible libraries.
+
+For the context about the Array API see:
+https://data-apis.org/array-api/latest/purpose_and_scope.html
+
+The SciPy use case of the Array API is described on the following page:
+https://data-apis.org/array-api/latest/use_cases.html#use-case-scipy
+"""
+import operator
+import dataclasses
+import functools
+import textwrap
+
+from collections.abc import Generator
+from contextlib import contextmanager
+from contextvars import ContextVar
+from types import ModuleType
+from typing import Any, Literal
+from collections.abc import Iterable
+
+import numpy as np
+import numpy.typing as npt
+
+from scipy._external.array_api_compat import (
+    is_array_api_obj,
+    is_lazy_array,
+    is_numpy_array,
+    is_cupy_array,
+    is_torch_array,
+    is_jax_array,
+    is_dask_array,
+    is_pydata_sparse_array,
+    size as xp_size,
+    numpy as np_compat,
+    device as xp_device,
+    is_numpy_namespace as is_numpy,
+    is_cupy_namespace as is_cupy,
+    is_torch_namespace as is_torch,
+    is_jax_namespace as is_jax,
+    is_dask_namespace as is_dask,
+    is_array_api_strict_namespace as is_array_api_strict,
+)
+from scipy._external.array_api_compat.common._helpers import _compat_module_name
+from scipy._external.array_api_extra.testing import lazy_xp_function
+from scipy._lib._array_api_override import (
+    array_namespace, SCIPY_ARRAY_API, SCIPY_DEVICE
+)
+from scipy._lib._docscrape import FunctionDoc
+from scipy._external import array_api_extra as xpx
+
+
+__all__ = [
+    '_asarray', 'array_namespace', 'assert_almost_equal', 'assert_array_almost_equal',
+    'default_xp', 'eager_warns', 'is_lazy_array', 'is_marray', 'is_pydata_sparse_array',
+    'is_array_api_strict', 'is_complex', 'is_cupy', 'is_jax', 'is_numpy', 'is_torch',
+    'np_compat', 'get_native_namespace_name',
+    'SCIPY_ARRAY_API', 'SCIPY_DEVICE', 'scipy_namespace_for',
+    'xp_assert_close', 'xp_assert_equal', 'xp_assert_less',
+    'xp_copy', 'xp_device', 'xp_ravel', 'xp_size',
+    'xp_unsupported_param_msg', 'xp_vector_norm', 'xp_capabilities',
+    'xp_result_type', 'xp_promote',
+    'make_xp_test_case', 'make_xp_pytest_marks', 'make_xp_pytest_param',
+]
+
+
+type Array = Any  # To be changed to a Protocol later (see array-api#589)
+type ArrayLike = Array | npt.ArrayLike
+
+
+def _check_finite(array: Array, xp: ModuleType) -> None:
+    """Check for NaNs or Infs."""
+    if not xp.all(xp.isfinite(array)):
+        msg = "array must not contain infs or NaNs"
+        raise ValueError(msg)
+
+def _asarray(
+        array: ArrayLike,
+        dtype: Any = None,
+        order: Literal['K', 'A', 'C', 'F'] | None = None,
+        copy: bool | None = None,
+        *,
+        xp: ModuleType | None = None,
+        check_finite: bool = False,
+        subok: bool = False,
+    ) -> Array:
+    """SciPy-specific replacement for `np.asarray` with `order`, `check_finite`, and
+    `subok`.
+
+    Memory layout parameter `order` is not exposed in the Array API standard.
+    `order` is only enforced if the input array implementation
+    is NumPy based, otherwise `order` is just silently ignored.
+
+    `check_finite` is also not a keyword in the array API standard; included
+    here for convenience rather than that having to be a separate function
+    call inside SciPy functions.
+
+    `subok` is included to allow this function to preserve the behaviour of
+    `np.asanyarray` for NumPy based inputs.
+    """
+    if xp is None:
+        xp = array_namespace(array)
+    if is_numpy(xp):
+        # Use NumPy API to support order
+        if copy is True:
+            array = np.array(array, order=order, dtype=dtype, subok=subok)
+        elif subok:
+            array = np.asanyarray(array, order=order, dtype=dtype)
+        else:
+            array = np.asarray(array, order=order, dtype=dtype)
+    else:
+        try:
+            array = xp.asarray(array, dtype=dtype, copy=copy)
+        except TypeError:
+            coerced_xp = array_namespace(xp.asarray(3))
+            array = coerced_xp.asarray(array, dtype=dtype, copy=copy)
+
+    if check_finite:
+        _check_finite(array, xp)
+
+    return array
+
+
+def xp_copy(x: Array, *, xp: ModuleType | None = None) -> Array:
+    """
+    Copies an array.
+
+    Parameters
+    ----------
+    x : array
+
+    xp : array_namespace
+
+    Returns
+    -------
+    copy : array
+        Copied array
+
+    Notes
+    -----
+    This copy function does not offer all the semantics of `np.copy`, i.e. the
+    `subok` and `order` keywords are not used.
+    """
+    # Note: for older NumPy versions, `np.asarray` did not support the `copy` kwarg,
+    # so this uses our other helper `_asarray`.
+    if xp is None:
+        xp = array_namespace(x)
+
+    return _asarray(x, copy=True, xp=xp)
+
+
+def _xp_copy_to_numpy(x: Array) -> np.ndarray:
+    """Copies a possibly on device array to a NumPy array.
+
+    This function is intended only for converting alternative backend
+    arrays to numpy arrays within test code, to make it easier for use
+    of the alternative backend to be isolated only to the function being
+    tested. `_xp_copy_to_numpy` should NEVER be used except in test code
+    for the specific purpose mentioned above. In production code, attempts
+    to copy device arrays to NumPy arrays should fail, or else functions
+    may appear to be working on the GPU when they actually aren't.
+
+    Parameters
+    ----------
+    x : array
+
+    Returns
+    -------
+    ndarray
+    """
+    xp = array_namespace(x)
+    if is_numpy(xp):
+        # Just return x if it is a Python scalar without a copy attribute.
+        return x.copy() if hasattr(x, "copy") else x
+    if is_cupy(xp):
+        return x.get()
+    if is_torch(xp):
+        return x.cpu().numpy()
+    if is_array_api_strict(xp):
+        # array api strict supports multiple devices, so need to
+        # ensure x is on the cpu before copying to NumPy.
+        return np.asarray(
+            xp.asarray(x, device=xp.Device("CPU_DEVICE")), copy=True
+        )
+    # Fall back to np.asarray. This works for dask.array. It
+    # currently works for jax.numpy, but hopefully JAX will make
+    # the transfer guard workable enough for use in scipy tests, in
+    # which case, JAX will have to be handled explicitly.
+    # If new backends are added, they may require explicit handling as
+    # well.
+    return np.asarray(x, copy=True)
+
+
+_default_xp_ctxvar: ContextVar[ModuleType] = ContextVar("_default_xp")
+
+@contextmanager
+def default_xp(xp: ModuleType) -> Generator[None, None, None]:
+    """In all ``xp_assert_*`` and ``assert_*`` function calls executed within this
+    context manager, test by default that the array namespace is
+    the provided across all arrays, unless one explicitly passes the ``xp=``
+    parameter or ``check_namespace=False``.
+
+    Without this context manager, the default value for `xp` is the namespace
+    for the desired array (the second parameter of the tests).
+    """
+    token = _default_xp_ctxvar.set(xp)
+    try:
+        yield
+    finally:
+        _default_xp_ctxvar.reset(token)
+
+
+def eager_warns(warning_type, *, match=None, xp):
+    """pytest.warns context manager if arrays of specified namespace are always eager.
+
+    Otherwise, context manager that *ignores* specified warning.
+    """
+    import pytest
+    from scipy._lib._util import ignore_warns
+    if is_numpy(xp) or is_array_api_strict(xp) or is_cupy(xp):
+        return pytest.warns(warning_type, match=match)
+    return ignore_warns(warning_type, match='' if match is None else match)
+
+
+def _strict_check(actual, desired, xp, *,
+                  check_namespace=True, check_dtype=True, check_shape=True,
+                  check_0d=True):
+    __tracebackhide__ = True  # Hide traceback for py.test
+
+    if xp is None:
+        try:
+            xp = _default_xp_ctxvar.get()
+        except LookupError:
+            xp = array_namespace(desired)
+
+    if check_namespace:
+        _assert_matching_namespace(actual, desired, xp)
+
+    # only NumPy distinguishes between scalars and arrays; we do if check_0d=True.
+    # do this first so we can then cast to array (and thus use the array API) below.
+    if is_numpy(xp) and check_0d:
+        _msg = ("Array-ness does not match:\n Actual: "
+                f"{type(actual)}\n Desired: {type(desired)}")
+        assert ((xp.isscalar(actual) and xp.isscalar(desired))
+                or (not xp.isscalar(actual) and not xp.isscalar(desired))), _msg
+
+    actual = xp.asarray(actual)
+    desired = xp.asarray(desired)
+
+    if check_dtype:
+        _msg = f"dtypes do not match.\nActual: {actual.dtype}\nDesired: {desired.dtype}"
+        assert actual.dtype == desired.dtype, _msg
+
+    if check_shape:
+        if is_dask(xp):
+            actual.compute_chunk_sizes()
+            desired.compute_chunk_sizes()
+        _msg = f"Shapes do not match.\nActual: {actual.shape}\nDesired: {desired.shape}"
+        assert actual.shape == desired.shape, _msg
+
+    desired = xp.broadcast_to(desired, actual.shape)
+    return actual, desired, xp
+
+
+def _assert_matching_namespace(actual, desired, xp):
+    __tracebackhide__ = True  # Hide traceback for py.test
+
+    desired_arr_space = array_namespace(desired)
+    _msg = ("Namespace of desired array does not match expectations "
+            "set by the `default_xp` context manager or by the `xp`"
+            "pytest fixture.\n"
+            f"Desired array's space: {desired_arr_space.__name__}\n"
+            f"Expected namespace: {xp.__name__}")
+    assert desired_arr_space == xp, _msg
+
+    actual_arr_space = array_namespace(actual)
+    _msg = ("Namespace of actual and desired arrays do not match.\n"
+            f"Actual: {actual_arr_space.__name__}\n"
+            f"Desired: {xp.__name__}")
+    assert actual_arr_space == xp, _msg
+
+
+def xp_assert_equal(actual, desired, *, check_namespace=True, check_dtype=True,
+                    check_shape=True, check_0d=True, err_msg='', xp=None):
+    __tracebackhide__ = True  # Hide traceback for py.test
+
+    actual, desired, xp = _strict_check(
+        actual, desired, xp, check_namespace=check_namespace,
+        check_dtype=check_dtype, check_shape=check_shape,
+        check_0d=check_0d
+    )
+
+    if is_cupy(xp):
+        return xp.testing.assert_array_equal(actual, desired, err_msg=err_msg)
+    elif is_torch(xp):
+        # PyTorch recommends using `rtol=0, atol=0` like this
+        # to test for exact equality
+        err_msg = None if err_msg == '' else err_msg
+        return xp.testing.assert_close(actual, desired, rtol=0, atol=0, equal_nan=True,
+                                       check_dtype=False, msg=err_msg)
+    # JAX uses `np.testing`
+    return np.testing.assert_array_equal(actual, desired, err_msg=err_msg)
+
+
+def xp_assert_close(actual, desired, *, rtol=None, atol=0, check_namespace=True,
+                    check_dtype=True, check_shape=True, check_0d=True,
+                    err_msg='', xp=None):
+    __tracebackhide__ = True  # Hide traceback for py.test
+
+    actual, desired, xp = _strict_check(
+        actual, desired, xp,
+        check_namespace=check_namespace, check_dtype=check_dtype,
+        check_shape=check_shape, check_0d=check_0d
+    )
+
+    floating = xp.isdtype(actual.dtype, ('real floating', 'complex floating'))
+    if rtol is None and floating:
+        # multiplier of 4 is used as for `np.float64` this puts the default `rtol`
+        # roughly half way between sqrt(eps) and the default for
+        # `numpy.testing.assert_allclose`, 1e-7
+        rtol = xp.finfo(actual.dtype).eps**0.5 * 4
+    elif rtol is None:
+        rtol = 1e-7
+
+    if is_cupy(xp):
+        return xp.testing.assert_allclose(actual, desired, rtol=rtol,
+                                          atol=atol, err_msg=err_msg)
+    elif is_torch(xp):
+        err_msg = None if err_msg == '' else err_msg
+        return xp.testing.assert_close(actual, desired, rtol=rtol, atol=atol,
+                                       equal_nan=True, check_dtype=False, msg=err_msg)
+    # JAX uses `np.testing`
+    return np.testing.assert_allclose(actual, desired, rtol=rtol,
+                                      atol=atol, err_msg=err_msg)
+
+
+def xp_assert_close_nulp(actual, desired, *, nulp=1, check_namespace=True,
+                         check_dtype=True, check_shape=True, check_0d=True,
+                         err_msg='', xp=None):
+    __tracebackhide__ = True  # Hide traceback for py.test
+
+    actual, desired, xp = _strict_check(
+        actual, desired, xp,
+        check_namespace=check_namespace, check_dtype=check_dtype,
+        check_shape=check_shape, check_0d=check_0d
+    )
+
+    actual, desired = map(_xp_copy_to_numpy, (actual, desired))
+    return np.testing.assert_array_almost_equal_nulp(actual, desired, nulp=nulp)
+
+
+def _assert_less(actual, desired, *, err_msg, verbose, xp):
+    if is_cupy(xp):
+        return xp.testing.assert_array_less(actual, desired,
+                                            err_msg=err_msg, verbose=verbose)
+    elif is_torch(xp):
+        if actual.device.type != 'cpu':
+            actual = actual.cpu()
+        if desired.device.type != 'cpu':
+            desired = desired.cpu()
+    # JAX uses `np.testing`
+    return np.testing.assert_array_less(actual, desired,
+                                        err_msg=err_msg, verbose=verbose)
+
+
+def xp_assert_less(actual, desired, *, check_namespace=True, check_dtype=True,
+                   check_shape=True, check_0d=True, err_msg='', verbose=True, xp=None):
+    __tracebackhide__ = True  # Hide traceback for py.test
+
+    actual, desired, xp = _strict_check(
+        actual, desired, xp, check_namespace=check_namespace,
+        check_dtype=check_dtype, check_shape=check_shape,
+        check_0d=check_0d
+    )
+
+    _assert_less(actual, desired, err_msg=err_msg, verbose=verbose, xp=xp)
+
+
+def xp_assert_less_equal(
+    actual, desired, *, check_namespace=True, check_dtype=True,
+    check_shape=True, check_0d=True, err_msg='', verbose=True, xp=None
+):
+    __tracebackhide__ = True  # Hide traceback for py.test
+
+    actual, desired, xp = _strict_check(
+        actual, desired, xp, check_namespace=check_namespace,
+        check_dtype=check_dtype, check_shape=check_shape,
+        check_0d=check_0d
+    )
+
+    # we call `_strict_check` before `_assert_less` so that scalars are
+    # coerced to the `xp` namespace before we apply `xp.nextafter`
+    _assert_less(
+        actual, xp.nextafter(desired, desired + 1),
+        err_msg=err_msg, verbose=verbose, xp=xp
+    )
+
+
+def assert_array_almost_equal(actual, desired, decimal=6, *args, **kwds):
+    """Backwards compatible replacement. In new code, use xp_assert_close instead.
+    """
+    rtol, atol = 0, 1.5*10**(-decimal)
+    return xp_assert_close(actual, desired,
+                           atol=atol, rtol=rtol, check_dtype=False, check_shape=False,
+                           *args, **kwds)
+
+
+def assert_almost_equal(actual, desired, decimal=7, *args, **kwds):
+    """Backwards compatible replacement. In new code, use xp_assert_close instead.
+    """
+    rtol, atol = 0, 1.5*10**(-decimal)
+    return xp_assert_close(actual, desired,
+                           atol=atol, rtol=rtol, check_dtype=False, check_shape=False,
+                           *args, **kwds)
+
+
+def xp_unsupported_param_msg(param: Any) -> str:
+    return f'Providing {param!r} is only supported for numpy arrays.'
+
+
+def is_complex(x: Array, xp: ModuleType) -> bool:
+    return xp.isdtype(x.dtype, 'complex floating')
+
+
+def get_native_namespace_name(xp: ModuleType) -> str:
+    """Return name for native namespace (without array_api_compat prefix)."""
+    name = xp.__name__
+    return name.removeprefix(f"{_compat_module_name()}.")
+
+
+def scipy_namespace_for(xp: ModuleType) -> ModuleType | None:
+    """Return the `scipy`-like namespace of a non-NumPy backend
+
+    That is, return the namespace corresponding with backend `xp` that contains
+    `scipy` sub-namespaces like `linalg` and `special`. If no such namespace
+    exists, return ``None``. Useful for dispatching.
+    """
+
+    if is_cupy(xp):
+        import cupyx  # type: ignore[import-not-found,import-untyped]
+        return cupyx.scipy
+
+    if is_jax(xp):
+        import jax  # type: ignore[import-not-found]
+        return jax.scipy
+
+    if is_torch(xp):
+        return xp
+
+    return None
+
+
+# maybe use `scipy.linalg` if/when array API support is added
+def xp_vector_norm(x: Array, /, *,
+                   axis: int | tuple[int, int] | None = None,
+                   keepdims: bool = False,
+                   ord: int | float = 2,
+                   xp: ModuleType | None = None) -> Array:
+    xp = array_namespace(x) if xp is None else xp
+
+    if SCIPY_ARRAY_API:
+        # check for optional `linalg` extension
+        if hasattr(xp, 'linalg'):
+            return xp.linalg.vector_norm(x, axis=axis, keepdims=keepdims, ord=ord)
+        else:
+            if ord != 2:
+                raise ValueError(
+                    "only the Euclidean norm (`ord=2`) is currently supported in "
+                    "`xp_vector_norm` for backends not implementing the `linalg` "
+                    "extension."
+                )
+            # return (x @ x)**0.5
+            # or to get the right behavior with nd, complex arrays
+            return xp.sum(xp.conj(x) * x, axis=axis, keepdims=keepdims)**0.5
+    else:
+        # to maintain backwards compatibility
+        return np.linalg.norm(x, ord=ord, axis=axis, keepdims=keepdims)
+
+
+def xp_ravel(x: Array, /, *, xp: ModuleType | None = None) -> Array:
+    # Equivalent of np.ravel written in terms of array API
+    # Even though it's one line, it comes up so often that it's worth having
+    # this function for readability
+    xp = array_namespace(x) if xp is None else xp
+    return xp.reshape(x, (-1,))
+
+
+def xp_swapaxes(a, axis1, axis2, xp=None):
+    # Equivalent of np.swapaxes written in terms of array API
+    xp = array_namespace(a) if xp is None else xp
+    axes = list(range(a.ndim))
+    axes[axis1], axes[axis2] = axes[axis2], axes[axis1]
+    a = xp.permute_dims(a, axes)
+    return a
+
+
+# utility to find common dtype with option to force floating
+def xp_result_type(*args, force_floating=False, xp):
+    """
+    Returns the dtype that results from applying type promotion rules
+    (see Array API Standard Type Promotion Rules) to the arguments. Augments
+    standard `result_type` in a few ways:
+
+    - There is a `force_floating` argument that ensures that the result type
+      is floating point, even when all args are integer.
+    - When a TypeError is raised (e.g. due to an unsupported promotion)
+      and `force_floating=True`, we define a custom rule: use the result type
+      of the default float and any other floats passed. See
+      https://github.com/scipy/scipy/pull/22695/files#r1997905891
+      for rationale.
+    - This function accepts array-like iterables, which are immediately converted
+      to the namespace's arrays before result type calculation. Consequently, the
+      result dtype may be different when an argument is `1.` vs `[1.]`.
+
+    Typically, this function will be called shortly after `array_namespace`
+    on a subset of the arguments passed to `array_namespace`.
+    """
+    # prevent double conversion of iterable to array
+    # avoid `np.iterable` for torch arrays due to pytorch/pytorch#143334
+    # don't use `array_api_compat.is_array_api_obj` as it returns True for NumPy scalars
+    args = [(_asarray(arg, subok=True, xp=xp) if is_torch_array(arg) or np.iterable(arg)
+            else arg) for arg in args]
+    args_not_none = [arg for arg in args if arg is not None]
+    if force_floating:
+        args_not_none.append(1.0)
+
+    try:  # follow library's preferred promotion rules
+        return xp.result_type(*args_not_none)
+    except ValueError:  # all scalars; need at least one array/dtype
+        if not force_floating:
+            raise
+        return xp.result_type(*(args_not_none + [xp.asarray(1.0)])) # skip device check
+    except TypeError:  # mixed type promotion isn't defined
+        if not force_floating:
+            raise
+        # use `result_type` of default floating point type and any floats present
+        # This can be revisited, but right now, the only backends that get here
+        # are array-api-strict (which is not for production use) and PyTorch
+        # (due to data-apis/array-api-compat#279).
+        float_args = []
+        for arg in args_not_none:
+            arg_array = xp.asarray(arg) if np.isscalar(arg) else arg
+            dtype = getattr(arg_array, 'dtype', arg)
+            if xp.isdtype(dtype, ('real floating', 'complex floating')):
+                float_args.append(arg)
+        return xp.result_type(*float_args, xp_default_dtype(xp))
+
+
+def xp_promote(*args, broadcast=False, force_floating=False, xp):
+    """
+    Promotes elements of *args to result dtype, ignoring `None`s.
+    Includes options for forcing promotion to floating point and
+    broadcasting the arrays, again ignoring `None`s.
+    Type promotion rules follow `xp_result_type` instead of `xp.result_type`.
+
+    Typically, this function will be called shortly after `array_namespace`
+    on a subset of the arguments passed to `array_namespace`.
+
+    This function accepts array-like iterables, which are immediately converted
+    to the namespace's arrays before result type calculation. Consequently, the
+    result dtype may be different when an argument is `1.` vs `[1.]`.
+
+    See Also
+    --------
+    xp_result_type
+    """
+    if not args:
+        return args
+
+    # prevent double conversion of iterable to array
+    # avoid `np.iterable` for torch arrays due to pytorch/pytorch#143334
+    # don't use `array_api_compat.is_array_api_obj` as it returns True for NumPy scalars
+    args = [(_asarray(arg, subok=True, xp=xp) if is_torch_array(arg) or np.iterable(arg)
+            else arg) for arg in args]
+
+    dtype = xp_result_type(*args, force_floating=force_floating, xp=xp)
+
+    args = [(_asarray(arg, dtype=dtype, subok=True, xp=xp) if arg is not None else arg)
+            for arg in args]
+
+    if not broadcast:
+        return args[0] if len(args)==1 else tuple(args)
+
+    args_not_none = [arg for arg in args if arg is not None]
+
+    # determine result shape
+    shapes = {arg.shape for arg in args_not_none}
+    try:
+        shape = (np.broadcast_shapes(*shapes) if len(shapes) != 1
+                 else args_not_none[0].shape)
+    except ValueError as e:
+        message = "Array shapes are incompatible for broadcasting."
+        raise ValueError(message) from e
+
+    out = []
+    for arg in args:
+        if arg is None:
+            out.append(arg)
+            continue
+
+        # broadcast only if needed
+        # Even if two arguments need broadcasting, this is faster than
+        # `broadcast_arrays`, especially since we've already determined `shape`
+        if arg.shape != shape:
+            kwargs = {'subok': True} if is_numpy(xp) else {}
+            arg = xp.broadcast_to(arg, shape, **kwargs)
+
+        # This is much faster than xp.astype(arg, dtype, copy=False)
+        if arg.dtype != dtype:
+            arg = xp.astype(arg, dtype)
+
+        out.append(arg)
+
+    return out[0] if len(out)==1 else tuple(out)
+
+
+def xp_float_to_complex(arr: Array, xp: ModuleType | None = None) -> Array:
+    xp = array_namespace(arr) if xp is None else xp
+    arr_dtype = arr.dtype
+    # The standard float dtypes are float32 and float64.
+    # Convert float32 to complex64,
+    # and float64 (and non-standard real dtypes) to complex128
+    if xp.isdtype(arr_dtype, xp.float32):
+        arr = xp.astype(arr, xp.complex64)
+    elif xp.isdtype(arr_dtype, 'real floating'):
+        arr = xp.astype(arr, xp.complex128)
+
+    return arr
+
+
+def xp_default_dtype(xp):
+    """Query the namespace-dependent default floating-point dtype.
+    """
+    if is_torch(xp):
+        # historically, we allow pytorch to keep its default of float32
+        return xp.get_default_dtype()
+    else:
+        # we default to float64
+        return xp.float64
+
+
+def xp_result_device(*args):
+    """Return the device of an array in `args`, for the purpose of
+    input-output device propagation.
+    If there are multiple devices, return an arbitrary one.
+    If there are no arrays, return None (this typically happens only on NumPy).
+    """
+    for arg in args:
+        # Do not do a duck-type test for the .device attribute, as many backends today
+        # don't have it yet. See workarouunds in array_api_compat.device().
+        if is_array_api_obj(arg):
+            return xp_device(arg)
+    return None
+
+
+# np.r_ replacement
+def concat_1d(xp: ModuleType | None, *arrays: Iterable[ArrayLike]) -> Array:
+    """A replacement for `np.r_` as `xp.concat` does not accept python scalars
+       or 0-D arrays.
+    """
+    arys = [xpx.atleast_nd(xp.asarray(a), ndim=1, xp=xp) for a in arrays]  # type:ignore[union-attr]
+    return xp.concat(arys)  # type:ignore[union-attr]
+
+
+### MArray Helpers ###
+
+
+def is_marray(xp):
+    """Returns True if `xp` is an MArray namespace; False otherwise."""
+    return "marray" in xp.__name__
+
+
+def _count_nonmasked(x, axis, keepdims=False, xp=None):
+    xp = array_namespace(x) if xp is None else xp
+    if is_marray(xp):
+        if np.iterable(axis):
+            message = '`axis` must be an integer or None for use with `MArray`.'
+            raise NotImplementedError(message)
+        return xp.astype(xp.count(x, axis=axis, keepdims=keepdims), x.dtype)
+    return (xp_size(x) if axis is None else
+            # compact way to deal with axis tuples or ints
+            int(np.prod(np.asarray(x.shape)[np.asarray(axis)])))
+
+
+def _share_masks(*args, xp):
+    if is_marray(xp):
+        mask = functools.reduce(operator.or_, (arg.mask for arg in args))
+        args = [xp.asarray(arg.data, mask=mask) for arg in args]
+    return args[0] if len(args) == 1 else args
+
+
+def _masked_apply(f, *, args, kwargs=None, xp):
+    # Unmask array arguments, evaluate function, and apply result mask to outputs.
+    # Assumes that when `xp` is an MArray namespace, there is at least one MArray
+    # in `args`/`kwargs` and MArrays are the only objects in `args`/`kwargs` with
+    # `data` and `mask` attributes. Could/should combine with `xpx.lazy_apply`.
+    kwargs = {} if kwargs is None else kwargs
+
+    if not is_marray(xp):
+        return f(*args, **kwargs)
+
+    arg_data = (getattr(arg, 'data', arg) for arg in args)
+    kwarg_data = (getattr(val, 'data', val) for val in kwargs.values())
+    res = f(*arg_data, **dict(zip(kwarg_data, kwargs.keys())))
+
+    masks = (arr.mask for arr in (*args, *kwargs.values()) if hasattr(arr, 'mask'))
+    mask = functools.reduce(operator.or_, masks)
+    return ((xp.asarray(out, mask=mask) for out in res) if isinstance(res, tuple)
+            else xp.asarray(res, mask=mask))
+
+
+### End MArray Helpers ###
+
+
+@dataclasses.dataclass(repr=False)
+class _XPSphinxCapability:
+    cpu: bool | None  # None if not applicable
+    gpu: bool | None
+    warnings: list[str] = dataclasses.field(default_factory=list)
+
+    def _render(self, value):
+        if value is None:
+            return "n/a"
+        if not value:
+            return "⛔"
+        if self.warnings:
+            res = "⚠️ " + '; '.join(self.warnings)
+            assert len(res) <= 20, "Warnings too long"
+            return res
+        return "✅"
+
+    def __str__(self):
+        cpu = self._render(self.cpu)
+        gpu = self._render(self.gpu)
+        return f"{cpu:20}  {gpu:20}"
+
+
+def _make_sphinx_capabilities(
+    # lists of tuples [(module name, reason), ...]
+    skip_backends=(), xfail_backends=(),
+    # @pytest.mark.skip/xfail_xp_backends kwargs
+    cpu_only=False, np_only=False, out_of_scope=False, exceptions=(),
+    # xpx.lazy_xp_backends kwargs
+    allow_dask_compute=False, jax_jit=True,
+    # list of tuples [(module name, reason), ...]
+    warnings = (),
+    # Whether the function supports MArrays that wrap one of the supported backends
+    marray=None,
+    # unused in documentation
+    reason=None,
+    method_capabilities=None,
+):
+    if out_of_scope:
+        return {"out_of_scope": True}
+
+    exceptions = set(exceptions)
+
+    # Default capabilities
+    capabilities = {
+        "numpy": _XPSphinxCapability(cpu=True, gpu=None),
+        "array_api_strict": _XPSphinxCapability(cpu=True, gpu=None),
+        "cupy": _XPSphinxCapability(cpu=None, gpu=True),
+        "torch": _XPSphinxCapability(cpu=True, gpu=True),
+        "jax.numpy": _XPSphinxCapability(cpu=True, gpu=True,
+            warnings=[] if jax_jit else ["no JIT"]),
+        # Note: Dask+CuPy is currently untested and unsupported
+        "dask.array": _XPSphinxCapability(cpu=True, gpu=None,
+            warnings=["computes graph"] if allow_dask_compute else []),
+    }
+
+    # documentation doesn't display the reason
+    for module, _ in list(skip_backends) + list(xfail_backends):
+        backend = capabilities[module]
+        if backend.cpu is not None:
+            backend.cpu = False
+        if backend.gpu is not None:
+            backend.gpu = False
+
+    for module, backend in capabilities.items():
+        if np_only and module not in exceptions | {"numpy"}:
+            if backend.cpu is not None:
+                backend.cpu = False
+            if backend.gpu is not None:
+                backend.gpu = False
+        elif cpu_only and module not in exceptions and backend.gpu is not None:
+            backend.gpu = False
+
+    for module, warning in warnings:
+        backend = capabilities[module]
+        backend.warnings.append(warning)
+
+    # MArrays are either supported or not. If supported, they work with all combinations
+    # of device + backend that are supported by the function and MArray itself. This is
+    # indicated with an extra note after the backend table.
+    capabilities.update({'marray': marray})
+
+    return capabilities
+
+
+def _make_capabilities_note(fun_name, capabilities, extra_note=None):
+    if "out_of_scope" in capabilities:
+        # It will be better to link to a section of the dev-arrayapi docs
+        # that explains what is and isn't in-scope, but such a section
+        # doesn't exist yet. Using :ref:`dev-arrayapi` as a placeholder.
+        note = f"""
+        **Array API Standard Support**
+
+        `{fun_name}` is not in-scope for support of Python Array API Standard compatible
+        backends other than NumPy.
+
+        See :ref:`dev-arrayapi` for more information.
+        """
+        return textwrap.dedent(note)
+
+    marray_note = (f"`{fun_name}` also accepts "
+        "`MArrays `__ "
+        "backed by the backends indicated above; masked values will be treated as "
+        "though they were not present." if capabilities.get("marray", False) else "")
+
+    # Note: deliberately not documenting array-api-strict
+    note = f"""
+    **Array API Standard Support**
+
+    `{fun_name}` has experimental support for Python Array API Standard compatible
+    backends in addition to NumPy. Please consider testing these features
+    by setting an environment variable ``SCIPY_ARRAY_API=1`` and providing
+    CuPy, PyTorch, JAX, or Dask arrays as array arguments. The following
+    combinations of backend and device (or other capability) are supported.
+
+    ====================  ====================  ====================
+    Library               CPU                   GPU
+    ====================  ====================  ====================
+    NumPy                 {capabilities['numpy']                   }
+    CuPy                  {capabilities['cupy']                    }
+    PyTorch               {capabilities['torch']                   }
+    JAX                   {capabilities['jax.numpy']               }
+    Dask                  {capabilities['dask.array']              }
+    ====================  ====================  ====================
+
+    {marray_note or ""}
+    {extra_note or ""}
+    See :ref:`dev-arrayapi` for more information.
+    """
+
+    return textwrap.dedent(note)
+
+
+def xp_capabilities(
+    *,
+    # Alternative capabilities table.
+    # Used only for testing this decorator.
+    capabilities_table=None,
+    # Generate pytest.mark.skip/xfail_xp_backends.
+    # See documentation in conftest.py.
+    # lists of tuples [(module name, reason), ...]
+    skip_backends=(), xfail_backends=(),
+    cpu_only=False, np_only=False, reason=None,
+    out_of_scope=False, exceptions=(),
+    # lists of tuples [(module name, reason), ...]
+    warnings=(),
+    # xpx.testing.lazy_xp_function kwargs.
+    # Refer to array-api-extra documentation.
+    allow_dask_compute=False, jax_jit=True,
+    # Extra note to inject into the docstring
+    extra_note=None,
+    # Dictionary mapping method names to dictionaries of method
+    # specific capabilities for use when when xp_capabilities is
+    # applied to a class with varying capabilities per method
+    method_capabilities=None,
+    # Whether the function supports MArrays that wrap one of the supported backends
+    marray=False,
+):
+    """Decorator for a function that states its support among various
+    Array API compatible backends.
+
+    This decorator has two effects:
+    1. It allows tagging tests with ``@make_xp_test_case`` or
+       ``make_xp_pytest_param`` (see below) to automatically generate
+       SKIP/XFAIL markers and perform additional backend-specific
+       testing, such as extra validation for Dask and JAX;
+    2. It automatically adds a note to the function's docstring, containing
+       a table matching what has been tested.
+
+    See Also
+    --------
+    make_xp_test_case
+    make_xp_pytest_param
+    array_api_extra.testing.lazy_xp_function
+    """
+    capabilities_table = (xp_capabilities_table if capabilities_table is None
+                          else capabilities_table)
+
+    if out_of_scope:
+        np_only = True
+
+    if method_capabilities is None:
+        method_capabilities = {}
+    for method, capabilities in method_capabilities.items():
+        # Fill in missing entries of method capabilities with
+        # defaults if any entries are missing.
+        method_capabilities[method] = dict(
+            skip_backends=(),
+            xfail_backends=(),
+            cpu_only=False,
+            np_only=False,
+            out_of_scope=False,
+            reason=None,
+            exceptions=(),
+            warnings=(),
+            allow_dask_compute=False,
+            jax_jit=True,
+            marray=False,
+        ) | capabilities
+
+    capabilities = dict(
+        skip_backends=skip_backends,
+        xfail_backends=xfail_backends,
+        cpu_only=cpu_only,
+        np_only=np_only,
+        out_of_scope=out_of_scope,
+        reason=reason,
+        exceptions=exceptions,
+        allow_dask_compute=allow_dask_compute,
+        jax_jit=jax_jit,
+        warnings=warnings,
+        method_capabilities=method_capabilities,
+        marray=marray,
+    )
+    sphinx_capabilities = _make_sphinx_capabilities(**capabilities)
+
+    def decorator(f):
+        # Don't use a wrapper, as in some cases @xp_capabilities is
+        # applied to a ufunc
+        capabilities_table[f] = capabilities
+        doc = FunctionDoc(f)
+        if not np_only or out_of_scope:
+            note = _make_capabilities_note(f.__name__, sphinx_capabilities, extra_note)
+            doc['Notes'].append(note)
+        doc = str(doc).split("\n", 1)[1].lstrip(" \n")  # remove signature
+        try:
+            f.__doc__ = doc
+        except AttributeError:
+            # Can't update __doc__ on ufuncs if SciPy
+            # was compiled against NumPy < 2.2.
+            pass
+
+        return f
+    return decorator
+
+
+def make_xp_test_case(*funcs, capabilities_table=None):
+    capabilities_table = (xp_capabilities_table if capabilities_table is None
+                          else capabilities_table)
+    """Generate pytest decorator for a test function that tests functionality
+    of one or more Array API compatible functions.
+
+    Read the parameters of the ``@xp_capabilities`` decorator applied to the
+    listed functions and:
+
+    - Generate the ``@pytest.mark.skip_xp_backends`` and
+      ``@pytest.mark.xfail_xp_backends`` decorators
+      for the decorated test function
+    - Tag the function with `xpx.testing.lazy_xp_function`
+
+    Example::
+
+        @make_xp_test_case(f1)
+        def test_f1(xp):
+            ...
+
+        @make_xp_test_case(f2)
+        def test_f2(xp):
+            ...
+
+        @make_xp_test_case(f1, f2)
+        def test_f1_and_f2(xp):
+            ...
+
+    The above is equivalent to::
+        @pytest.mark.skip_xp_backends(...)
+        @pytest.mark.skip_xp_backends(...)
+        @pytest.mark.xfail_xp_backends(...)
+        @pytest.mark.xfail_xp_backends(...)
+        def test_f1(xp):
+            ...
+
+    etc., where the arguments of ``skip_xp_backends`` and ``xfail_xp_backends`` are
+    determined by the ``@xp_capabilities`` decorator applied to the functions.
+
+    Notes
+    -----
+
+    To allow use of ``make_xp_test_case`` with classes, elements of ``funcs`` may
+    also be tuples of the form ``(cls, method_name)`` consisting of a ``type`` and
+    a string giving the name of a method. ``lazy_xp_function`` will be applied to the
+    method of interest. Capabilities for the method with name ``method_name`` can
+    be specified in the ``method_capabilities`` kwarg in the application of
+    ``xp_capabilities`` to ``cls``. If no ``method_capabilities`` entry is given
+    for ``method_name``, then the capabilities default to the class level
+    capabilities.
+
+    Tuples of the form ``(cls, method_name)`` are used instead of ``cls.method`` in
+    order to handle inheritance gracefully, since if ``cls`` derives from a parent
+    class, ``cls.method`` will be a reference to the parent method, potentially
+    causing problems for ``lazy_xp_function``.
+
+    See Also
+    --------
+    xp_capabilities
+    make_xp_pytest_marks
+    make_xp_pytest_param
+    array_api_extra.testing.lazy_xp_function
+    """
+    marks = make_xp_pytest_marks(*funcs, capabilities_table=capabilities_table)
+    return lambda func: functools.reduce(lambda f, g: g(f), marks, func)
+
+
+def make_xp_pytest_param(func, *args, additional_marks=None, capabilities_table=None):
+    """Variant of ``make_xp_test_case`` that returns a pytest.param for a function,
+    with all necessary skip_xp_backends and xfail_xp_backends marks applied::
+
+        @pytest.mark.parametrize(
+            "func", [make_xp_pytest_param(f1), make_xp_pytest_param(f2)]
+        )
+        def test(func, xp):
+            ...
+
+    The above is equivalent to::
+
+        @pytest.mark.parametrize(
+            "func", [
+                pytest.param(f1, marks=[
+                    pytest.mark.skip_xp_backends(...),
+                    pytest.mark.xfail_xp_backends(...), ...]),
+                pytest.param(f2, marks=[
+                    pytest.mark.skip_xp_backends(...),
+                    pytest.mark.xfail_xp_backends(...), ...]),
+        )
+        def test(func, xp):
+            ...
+
+    Parameters
+    ----------
+    func : Callable | tuple[type, str]
+        Function to be tested. It must be decorated with ``@xp_capabilities``.
+        Alternatively, a tuple of the form ``(cls, method_name)``, where
+        ``cls`` must be decorated with ``@xp_capabilities``, specifying
+        that one wants marks for a particular method of the given class.
+        See the Notes section of the docstring for ``make_xp_test_case`` for
+        more info.
+
+        Note that if func is a tuple, then only the first entry is actually
+        used in the resulting pytest param, and the second entry is only
+        used to specify capabilities for a particular given method and tell
+        the testing infra to apply ``lazy_xp_function`` to that method.::
+
+        @pytest.mark.parametrize("cls", [(A, "f"), (B, "f"), C])
+        def test(cls, xp):
+            # cls iterates over A, B, C.
+    *args : Any, optional
+        Extra pytest parameters for the use case, e.g.::
+
+        @pytest.mark.parametrize("func,verb", [
+            make_xp_pytest_param(f1, "hello"),
+            make_xp_pytest_param(f2, "world")])
+        def test(func, verb, xp):
+            # iterates on (func=f1, verb="hello")
+            # and (func=f2, verb="world")
+    additional_marks : pytest.MarkDecorator | list[pytest.MarkDecorator]
+        Additional pytest marks to add to the parameter, e.g.
+        ``pytest.mark.slow``.
+
+    See Also
+    --------
+    xp_capabilities
+    make_xp_test_case
+    make_xp_pytest_marks
+    array_api_extra.testing.lazy_xp_function
+    """
+    import pytest
+
+    marks = make_xp_pytest_marks(func, capabilities_table=capabilities_table)
+    if additional_marks is not None:
+        if isinstance(additional_marks, pytest.MarkDecorator):
+            additional_marks = [additional_marks]
+        marks.extend(additional_marks)
+    if isinstance(func, tuple):
+        func, _ = func
+    return pytest.param(func, *args, marks=marks, id=func.__name__)
+
+
+def make_xp_pytest_marks(*funcs, capabilities_table=None):
+    """Variant of ``make_xp_test_case`` that returns a list of pytest marks,
+    which can be used with the module-level `pytestmark = ...` variable::
+
+        pytestmark = make_xp_pytest_marks(f1, f2)
+
+        def test(xp):
+            ...
+
+    In this example, the whole test module is dedicated to testing `f1` or `f2`,
+    and the two functions have the same capabilities, so it's unnecessary to
+    cherry-pick which test tests which function.
+    The above is equivalent to::
+
+        pytestmark = [
+            pytest.mark.skip_xp_backends(...),
+            pytest.mark.xfail_xp_backends(...), ...]),
+        ]
+
+        def test(xp):
+            ...
+
+    See Also
+    --------
+    xp_capabilities
+    make_xp_test_case
+    make_xp_pytest_param
+    array_api_extra.testing.lazy_xp_function
+    """
+    capabilities_table = (xp_capabilities_table if capabilities_table is None
+                          else capabilities_table)
+    import pytest
+
+    marks = []
+    # func may be a (cls, method_name) pair. This objs list will store cls
+    # if the corresponding entry of funcs is such a tuple, and func otherwise.
+    # the objs list is passed to the uses_xp_capabilities mark and used in
+    # check_xp_untested. The intention is that all classes ``cls`` which advertise
+    # support must have at least one test that uses the ``xp`` fixture along
+    # with ``make_xp_test_case(cls)``. Testing is not enforced at the method level
+    # since the documentation of capabilities is done at the class level.
+    objs = []
+
+    for func in funcs:
+        if isinstance(func, tuple):
+            cls, method = func
+            capabilities = capabilities_table[cls]
+            if method in capabilities["method_capabilities"]:
+                capabilities = capabilities["method_capabilities"][method]
+            objs.append(cls)
+        else:
+            capabilities = capabilities_table[func]
+            objs.append(func)
+
+        exceptions = capabilities['exceptions']
+        reason = capabilities['reason']
+
+        if capabilities['cpu_only']:
+            marks.append(pytest.mark.skip_xp_backends(
+                cpu_only=True, exceptions=exceptions, reason=reason))
+        if capabilities['np_only']:
+            marks.append(pytest.mark.skip_xp_backends(
+                np_only=True, exceptions=exceptions, reason=reason))
+
+        for mod_name, reason in capabilities['skip_backends']:
+            marks.append(pytest.mark.skip_xp_backends(mod_name, reason=reason))
+        for mod_name, reason in capabilities['xfail_backends']:
+            marks.append(pytest.mark.xfail_xp_backends(mod_name, reason=reason))
+
+        lazy_kwargs = {k: capabilities[k]
+                       for k in ('allow_dask_compute', 'jax_jit')}
+        lazy_xp_function(func, **lazy_kwargs)
+
+    # Inject a marker which will help us identify tests using the xp
+    # fixture which do not use xp_capabilities.
+    marks.append(pytest.mark.uses_xp_capabilities(True, funcs=objs))
+
+    return marks
+
+
+# Is it OK to have a dictionary that is mutated (once upon import) in many places?
+xp_capabilities_table = {}  # type: ignore[var-annotated]
+
+
+def xp_device_type(a: Array) -> Literal["cpu", "cuda", None]:
+    if is_numpy_array(a):
+        return "cpu"
+    if is_cupy_array(a):
+        return "cuda"
+    if is_torch_array(a):
+        # TODO this can return other backends e.g. tpu but they're unsupported in scipy
+        return a.device.type
+    if is_jax_array(a):
+        # TODO this can return other backends e.g. tpu but they're unsupported in scipy
+        return "cuda" if (p := a.device.platform) == "gpu" else p
+    if is_dask_array(a):
+        return xp_device_type(a._meta)
+    # array-api-strict is a stand-in for unknown libraries; don't special-case it
+    return None
+
+
+def xp_isscalar(x):
+    return np.isscalar(x) or (is_array_api_obj(x) and x.ndim == 0)
diff --git a/.venv/lib/python3.12/site-packages/scipy/_lib/_array_api_docs_tables.py b/.venv/lib/python3.12/site-packages/scipy/_lib/_array_api_docs_tables.py
new file mode 100644
index 0000000000000000000000000000000000000000..ab1c6ce849d3564b4aa60776cc6cdc149472efa6
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/_lib/_array_api_docs_tables.py
@@ -0,0 +1,296 @@
+"""Generate flat tables showing Array API capabilities for use in docs.
+
+These tables are intended for presenting Array API capabilities across
+a wide number of functions at once. Rows correspond to functions and
+columns correspond to library/device/option combinations.
+"""
+
+from collections import defaultdict
+from enum import auto, Enum
+from importlib import import_module
+from types import ModuleType
+from typing import Any
+
+from scipy._lib._array_api import xp_capabilities_table
+from scipy._lib._array_api import _make_sphinx_capabilities
+
+# For undocumented aliases of public functions which are kept around for
+# backwards compatibility reasons. These should be excluded from the
+# tables since they would be redundant. There are also no docs pages to
+# link entries to.
+ALIASES = {
+    "scipy.cluster.vq": {
+        # Deprecated ~alias of `vq`
+        "py_vq",
+    },
+    "scipy.linalg": {
+        # Alias of scipy.linalg.solve_continuous_lyapunov
+        "solve_lyapunov",
+    },
+    "scipy.ndimage": {
+        # Alias of scipy.ndimage.sum_labels
+        "sum",
+    },
+    "scipy.special": {
+        # Alias of scipy.special.jv
+        "jn",
+        # Alias of scipy.special.roots_legendre
+        "p_roots",
+        # Alias of scipy.special.roots_chebyt
+        "t_roots",
+        # Alias of scipy.special.roots_chebyu
+        "u_roots",
+        # Alias of scipy.special.roots_chebyc
+        "c_roots",
+        # Alias of scipy.special.roots_chebys
+        "s_roots",
+        # Alias of scipy.special.roots_jacobi
+        "j_roots",
+        # Alias of scipy.special.roots_laguerre
+        "l_roots",
+        # Alias of scipy.special.roots_genlaguerre
+        "la_roots",
+        # Alias of scipy.special.roots_hermite
+        "h_roots",
+        # Alias of scipy.special.roots_hermitenorm
+        "he_roots",
+        # Alias of scipy.special.roots_gegenbauer
+        "cg_roots",
+        # Alias of scipy.special.roots_sh_legendre
+        "ps_roots",
+        # Alias of scipy.special.roots_sh_chebyt
+        "ts_roots",
+        # Alias of scipy.special.roots_chebyu
+        "us_roots",
+        # Alias of scipy.special.roots_sh_jacobi
+        "js_roots",
+    }
+}
+
+# Shortened names for use in table.
+BACKEND_NAMES_MAP = {
+    "jax.numpy": "jax",
+    "dask.array": "dask",
+}
+
+
+class BackendSupportStatus(Enum):
+    YES = auto()
+    NO = auto()
+    OUT_OF_SCOPE = auto()
+    UNKNOWN = auto()
+
+
+def _process_capabilities_table_entry(
+    entry: dict | None
+) -> dict[str, dict[str, BackendSupportStatus]]:
+    """Returns dict showing alternative backend support in easy to consume form.
+
+    Parameters
+    ----------
+    entry : dict | None
+       A dict with the structure of the values of the dict
+       scipy._lib._array_api.xp_capabilities_table. If None, it is
+       assumped that no alternative backends are supported.
+       Default: None.
+
+    Returns
+    -------
+    dict[str, dict[str, bool]]
+        The output dict currently has keys "cpu", "gpu", "jit" and "lazy".
+        The value associated to each key is itself a dict. The keys of
+        the inner dicts correspond to backends, with bool values stating
+        whether or not the backend is supported with a given device or
+        mode. Inapplicable backends do not appear in the inner dicts
+        (e.g. since cupy is gpu-only, it does not appear in the inner
+        dict keyed on "cpu"). Only alternative backends to NumPy are
+        included since NumPY support should be guaranteed.
+
+    """
+    # This is a template for the output format. If more backends and
+    # backend options are added, it will need to be updated manually.
+    # Entries start as boolean, but upon returning, will take values
+    # from the BackendSupportStatus Enum.
+    output = {
+        "cpu": {"torch": False, "jax": False, "dask": False},
+        "gpu": {"cupy": False, "torch": False, "jax": False},
+        "jit": {"jax": False},
+        "lazy": {"dask": False},
+    }
+    S = BackendSupportStatus
+    if entry is None:
+        # If there is no entry, assume no alternative backends are supported.
+        # If the list of supported backends will grows, this hard-coded dict
+        # will need to be updated.
+        return {
+            outer_key: {inner_key: S.UNKNOWN for inner_key in outer_value}
+            for outer_key, outer_value in output.items()
+        }
+
+    if entry["out_of_scope"]:
+        # None is used to signify out-of-scope functions.
+        return {
+            outer_key: {inner_key: S.OUT_OF_SCOPE for inner_key in outer_value}
+            for outer_key, outer_value in output.items()
+        }
+
+    # For now, use _make_sphinx_capabilities because that's where
+    # the relevant logic for determining what is and isn't
+    # supported based on xp_capabilities_table entries lives.
+    # This logic should be decoupled from this function due to exceptions; e.g. marray.
+    sphinx_capabilities = _make_sphinx_capabilities(**entry)
+    sphinx_capabilities.pop("marray")
+    for backend, capabilities in sphinx_capabilities.items():
+        if backend in {"array_api_strict", "numpy"}:
+            continue
+        backend = BACKEND_NAMES_MAP.get(backend, backend)
+        cpu, gpu = capabilities.cpu, capabilities.gpu
+        if cpu is not None:
+            if backend not in output["cpu"]:
+                raise ValueError(
+                    "Input capabilities table entry contains unhandled"
+                    f" backend {backend} on cpu."
+                )
+            output["cpu"][backend] = cpu
+        if gpu is not None:
+            if backend not in output["gpu"]:
+                raise ValueError(
+                    "Input capabilities table entry contains unhandled"
+                    f" backend {backend} on gpu."
+                )
+            output["gpu"][backend] = gpu
+        if backend == "jax":
+            output["jit"]["jax"] = entry["jax_jit"] and output["cpu"]["jax"]
+        if backend == "dask.array":
+            support_lazy = not entry["allow_dask_compute"] and output["dask"]
+            output["lazy"]["dask"] = bool(support_lazy)
+    return {
+        outer_key: {
+            inner_key: S.YES if inner_value else S.NO
+            for inner_key, inner_value in outer_value.items()
+        }
+        for outer_key, outer_value in output.items()
+    }
+
+
+def is_inherently_out_of_scope(obj):
+    # modules, exceptions, and things that are not named callables
+    # are inherently out of scope.
+    return (
+        isinstance(obj, ModuleType)
+        or (isinstance(obj, type) and issubclass(obj, Exception))
+        or not (callable(obj) and hasattr(obj, "__name__"))
+    )
+
+
+def make_flat_capabilities_table(
+        modules: str | list[str],
+        backend_type: str,
+        /,
+        *,
+        capabilities_table: dict | None = None,
+) -> list[dict[str, str | int]]:
+    """Generate full table of array api capabilities across public functions.
+
+    Parameters
+    ----------
+    modules : str | list[str]
+        A string containing single SciPy module, (e.g `scipy.stats`, `scipy.fft`)
+        or a list of such strings.
+
+    backend_type : {'cpu', 'gpu', 'jit', 'lazy'}
+
+    capabilities_table : dict | None
+        Table in the form of `scipy._lib._array_api.xp_capabilities_table`.
+        If None, uses `scipy._lib._array_api.xp_capabilities_table`.
+        Default: None.
+
+    Returns
+    -------
+    output : list[dict[str, str]]
+        `output` is a table in dict format
+        (keys corresponding to column names). The first column is "module".
+        The other columns correspond to supported backends for the given
+        `backend_type`, e.g. jax.numpy, torch, and dask on cpu.
+         numpy is excluded because it should always be supported.
+         See the helper function
+        `_process_capabilities_table_entry` above).
+
+    """
+    if backend_type not in {"cpu", "gpu", "jit", "lazy"}:
+        raise ValueError(f"Received unhandled backend type {backend_type}")
+
+    if isinstance(modules, str):
+        modules = [modules]
+
+    if capabilities_table is None:
+        capabilities_table = xp_capabilities_table
+
+    output = []
+
+    for module_name in modules:
+        module = import_module(module_name)
+        public_things = module.__all__
+        for name in public_things:
+            if name in ALIASES.get(module_name, {}):
+                # Skip undocumented aliases that are kept
+                # for backwards compatibility reasons.
+                continue
+            thing = getattr(module, name)
+            if is_inherently_out_of_scope(thing):
+                continue
+            entry = capabilities_table.get(thing, None)
+            capabilities = _process_capabilities_table_entry(entry)[backend_type]
+            row: dict[str, Any] = {"module": module_name}
+            row.update({"function": name})
+            row.update(capabilities)
+            output.append(row)
+    return output
+
+
+def calculate_table_statistics(
+    flat_table: list[dict[str, str]]
+) -> dict[str, dict[str, int]]:
+    """Get counts of what is supported per module.
+
+    Parameters
+    ----------
+    flat_table : list[dict[str, str]]
+        A table as returned by `make_flat_capabilities_table`
+
+    Returns
+    -------
+    dict[str, dict[str, int]]
+        dict mapping module names to inner dicts.
+        bool. The inner dicts have a key "total" along with keys for each
+        backend column of the supplied flat capabilities table. The value
+        corresponding to total is the total count of functions in the given
+        module, and the value associated to the other keys is the count of
+        functions that support that particular backend.
+    """
+    if not flat_table:
+        return {}
+
+    counter: defaultdict[str, defaultdict[str, int]]
+    counter = defaultdict(lambda: defaultdict(int))
+
+    S = BackendSupportStatus
+    for entry in flat_table:
+        entry = entry.copy()
+        entry.pop("function")
+        module = entry.pop("module")
+        current_counter = counter[module]
+
+        # By design, all backends and options must be considered out-of-scope
+        # if one is, so just pick an arbitrary entry here to test if function is
+        # in-scope.
+        if next(iter(entry.values())) != S.OUT_OF_SCOPE:
+            current_counter["total"] += 1
+            for key, value in entry.items():
+                # Functions missing xp_capabilities will be tabulated as
+                # unsupported, but may actually be supported. There is a
+                # note about this in the documentation and this function is
+                # set up to return information needed to put asterisks next
+                # to percentages impacted by missing xp_capabilities decorators.
+                current_counter[key] += 1 if value == S.YES else 0
+    return {mod: dict(counts) for mod, counts in counter.items()}
diff --git a/.venv/lib/python3.12/site-packages/scipy/_lib/_array_api_no_0d.py b/.venv/lib/python3.12/site-packages/scipy/_lib/_array_api_no_0d.py
new file mode 100644
index 0000000000000000000000000000000000000000..0ea40ff00a57413d3c3df5579b1b40d292875d7d
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/_lib/_array_api_no_0d.py
@@ -0,0 +1,103 @@
+"""
+Extra testing functions that forbid 0d-input, see #21044
+
+While the xp_assert_* functions generally aim to follow the conventions of the
+underlying `xp` library, NumPy in particular is inconsistent in its handling
+of scalars vs. 0d-arrays, see https://github.com/numpy/numpy/issues/24897.
+
+For example, this means that the following operations (as of v2.0.1) currently
+return scalars, even though a 0d-array would often be more appropriate:
+
+    import numpy as np
+    np.array(0) * 2     # scalar, not 0d array
+    - np.array(0)       # scalar, not 0d-array
+    np.sin(np.array(0)) # scalar, not 0d array
+    np.mean([1, 2, 3])  # scalar, not 0d array
+
+Libraries like CuPy tend to return a 0d-array in scenarios like those above,
+and even `xp.asarray(0)[()]` remains a 0d-array there. To deal with the reality
+of the inconsistencies present in NumPy, as well as 20+ years of code on top,
+the `xp_assert_*` functions here enforce consistency in the only way that
+doesn't go against the tide, i.e. by forbidding 0d-arrays as the return type.
+
+However, when scalars are not generally the expected NumPy return type,
+it remains preferable to use the assert functions from
+the `scipy._lib._array_api` module, which have less surprising behaviour.
+"""
+from scipy._lib._array_api import array_namespace, is_numpy
+from scipy._lib._array_api import (xp_assert_close as xp_assert_close_base,
+                                   xp_assert_equal as xp_assert_equal_base,
+                                   xp_assert_less as xp_assert_less_base)
+
+__all__: list[str] = []
+
+
+def _check_scalar(actual, desired, *, xp=None, **kwargs):
+    __tracebackhide__ = True  # Hide traceback for py.test
+
+    if xp is None:
+        xp = array_namespace(actual)
+
+    # necessary to handle non-numpy scalars, e.g. bare `0.0` has no shape
+    desired = xp.asarray(desired)
+
+    # Only NumPy distinguishes between scalars and arrays;
+    # shape check in xp_assert_* is sufficient except for shape == ()
+    if not (is_numpy(xp) and desired.shape == ()):
+        return
+
+    _msg = ("Result is a NumPy 0d-array. Many SciPy functions intend to follow "
+            "the convention of many NumPy functions, returning a scalar when a "
+            "0d-array would be correct. The specialized `xp_assert_*` functions "
+            "in the `scipy._lib._array_api_no_0d` module err on the side of "
+            "caution and do not accept 0d-arrays by default. If the correct "
+            "result may legitimately be a 0d-array, pass `check_0d=True`, "
+            "or use the `xp_assert_*` functions from `scipy._lib._array_api`.")
+    assert xp.isscalar(actual), _msg
+
+
+def xp_assert_equal(actual, desired, *, check_0d=False, **kwargs):
+    # in contrast to xp_assert_equal_base, this defaults to check_0d=False,
+    # but will do an extra check in that case, which forbids 0d-arrays for `actual`
+    __tracebackhide__ = True  # Hide traceback for py.test
+
+    # array-ness (check_0d == True) is taken care of by the *_base functions
+    if not check_0d:
+        _check_scalar(actual, desired, **kwargs)
+    return xp_assert_equal_base(actual, desired, check_0d=check_0d, **kwargs)
+
+
+def xp_assert_close(actual, desired, *, check_0d=False, **kwargs):
+    # as for xp_assert_equal
+    __tracebackhide__ = True
+
+    if not check_0d:
+        _check_scalar(actual, desired, **kwargs)
+    return xp_assert_close_base(actual, desired, check_0d=check_0d, **kwargs)
+
+
+def xp_assert_less(actual, desired, *, check_0d=False, **kwargs):
+    # as for xp_assert_equal
+    __tracebackhide__ = True
+
+    if not check_0d:
+        _check_scalar(actual, desired, **kwargs)
+    return xp_assert_less_base(actual, desired, check_0d=check_0d, **kwargs)
+
+
+def assert_array_almost_equal(actual, desired, decimal=6, **kwds):
+    """Backwards compatible replacement. In new code, use xp_assert_close instead.
+    """
+    rtol, atol = 0, 1.5*10**(-decimal)
+    return xp_assert_close(actual, desired,
+                           atol=atol, rtol=rtol, check_dtype=False, check_shape=False,
+                           **kwds)
+
+
+def assert_almost_equal(actual, desired, decimal=7, **kwds):
+    """Backwards compatible replacement. In new code, use xp_assert_close instead.
+    """
+    rtol, atol = 0, 1.5*10**(-decimal)
+    return xp_assert_close(actual, desired,
+                           atol=atol, rtol=rtol, check_dtype=False, check_shape=False,
+                           **kwds)
diff --git a/.venv/lib/python3.12/site-packages/scipy/_lib/_array_api_override.py b/.venv/lib/python3.12/site-packages/scipy/_lib/_array_api_override.py
new file mode 100644
index 0000000000000000000000000000000000000000..3781c6ea5a0ccacee6d5c49b6962fc7d1f02e873
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/_lib/_array_api_override.py
@@ -0,0 +1,156 @@
+"""
+Override functions from array_api_compat, for use by array-api-extra
+and internally.
+
+See also _array_api_compat_vendor.py
+"""
+import enum
+import os
+
+from functools import lru_cache
+from types import ModuleType
+from typing import Any
+
+import numpy as np
+import numpy.typing as npt
+
+from scipy._external import array_api_compat
+import scipy._external.array_api_compat.numpy as np_compat
+from scipy._external.array_api_compat import is_array_api_obj, is_jax_array
+from scipy._lib._sparse import SparseABC
+
+
+type Array = Any  # To be changed to a Protocol later (see array-api#589)
+type ArrayLike = Array | npt.ArrayLike
+
+# To enable array API and strict array-like input validation
+SCIPY_ARRAY_API: str | bool = os.environ.get("SCIPY_ARRAY_API", False)
+# To control the default device - for use in the test suite only
+SCIPY_DEVICE = os.environ.get("SCIPY_DEVICE", "cpu")
+
+
+class _ArrayClsInfo(enum.Enum):
+    skip = 0
+    numpy = 1
+    array_like = 2
+    unknown = 3
+
+
+@lru_cache(100)
+def _validate_array_cls(cls: type, sparse_ok=False) -> _ArrayClsInfo:
+    if issubclass(cls, list | tuple):
+        return _ArrayClsInfo.array_like
+
+    # this comes from `_util._asarray_validated`
+    if issubclass(cls, SparseABC):
+        if not sparse_ok:
+            msg = ('Sparse arrays/matrices are not supported by this function. '
+                    'Perhaps one of the `scipy.sparse.linalg` functions '
+                    'would work instead.')
+            raise ValueError(msg)
+        # `scipy.sparse` arrays are treated as compatible with NumPy
+        # and assumed incompatible with other namespaces
+        return _ArrayClsInfo.numpy
+
+    if issubclass(cls, np.ma.MaskedArray):
+        raise TypeError("Inputs of type `numpy.ma.MaskedArray` are not supported.")
+
+    if issubclass(cls, np.matrix):
+        raise TypeError("Inputs of type `numpy.matrix` are not supported.")
+
+    if issubclass(cls, np.ndarray | np.generic):
+        return _ArrayClsInfo.numpy
+
+    # Note: this must happen after the test for np.generic, because
+    # np.float64 and np.complex128 are subclasses of float and complex respectively.
+    # This matches the behavior of array_api_compat.
+    if issubclass(cls, int | float | complex | bool | type(None)):
+        return _ArrayClsInfo.skip
+
+    return _ArrayClsInfo.unknown
+
+
+def array_namespace(*arrays: Array, sparse_ok=False) -> ModuleType:
+    """Get the array API compatible namespace for the arrays xs.
+
+    Parameters
+    ----------
+    *arrays : sequence of array_like
+        Arrays used to infer the common namespace.
+    sparse_ok : bool
+        ``True`` if `scipy.sparse` arrays should be accepted where the
+        namespace would otherwise be NumPy. Default: ``False``.
+
+    Returns
+    -------
+    namespace : module
+        Common namespace.
+
+    Notes
+    -----
+    Wrapper around `array_api_compat.array_namespace`.
+
+    1. Check for the global switch `SCIPY_ARRAY_API`. If disabled, just
+       return array_api_compat.numpy namespace and skip all compliance checks.
+
+    2. Check for known-bad array classes.
+       The following subclasses are not supported and raise and error:
+
+       - `numpy.ma.MaskedArray`
+       - `numpy.matrix`
+       - NumPy arrays which do not have a boolean or numerical dtype
+
+    3. Coerce array-likes to NumPy arrays and check their dtype.
+       Note that non-scalar array-likes can't be mixed with non-NumPy Array
+       API objects; e.g.
+
+       - `array_namespace([1, 2])` returns NumPy namespace;
+       - `array_namespace(np.asarray([1, 2], [3, 4])` returns NumPy namespace;
+       - `array_namespace(cp.asarray([1, 2], [3, 4])` raises an error.
+    """
+    if not SCIPY_ARRAY_API:
+        # here we could wrap the namespace if needed
+        return np_compat
+
+    numpy_arrays = []
+    api_arrays = []
+
+    for array in arrays:
+        arr_info = _validate_array_cls(type(array), sparse_ok=sparse_ok)  # type:ignore[arg-type]
+        if arr_info is _ArrayClsInfo.skip:
+            pass
+
+        elif arr_info is _ArrayClsInfo.numpy:
+            if array.dtype.kind in 'iufcb':  # Numeric or bool
+                numpy_arrays.append(array)
+            elif array.dtype.kind == 'V' and is_jax_array(array):
+                # Special case for JAX zero gradient arrays;
+                # see array_api_compat._common._helpers._is_jax_zero_gradient_array
+                api_arrays.append(array)  # JAX zero gradient array
+            else:
+                raise TypeError(f"An argument has dtype `{array.dtype!r}`; "
+                                "only boolean and numerical dtypes are supported.")
+
+        elif arr_info is _ArrayClsInfo.unknown and is_array_api_obj(array):
+            api_arrays.append(array)
+
+        else:
+            # list, tuple, or arbitrary object
+            try:
+                array = np.asanyarray(array)
+            except TypeError:
+                raise TypeError("An argument is neither array API compatible nor "
+                                "coercible by NumPy.")
+            if array.dtype.kind not in 'iufcb':  # Numeric or bool
+                raise TypeError(f"An argument has dtype `{array.dtype!r}`; "
+                                "only boolean and numerical dtypes are supported.")
+            numpy_arrays.append(array)
+
+    # When there are exclusively NumPy and ArrayLikes, skip calling
+    # array_api_compat.array_namespace for performance.
+    if not api_arrays:
+        return np_compat
+
+    # In case of mix of NumPy/ArrayLike and non-NumPy Array API arrays,
+    # let array_api_compat.array_namespace raise an error.
+    return array_api_compat.array_namespace(*numpy_arrays, *api_arrays)
diff --git a/.venv/lib/python3.12/site-packages/scipy/_lib/_bunch.py b/.venv/lib/python3.12/site-packages/scipy/_lib/_bunch.py
new file mode 100644
index 0000000000000000000000000000000000000000..172e7dce1b25d0a70c1810e3d133f4b6bd12a538
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/_lib/_bunch.py
@@ -0,0 +1,229 @@
+import sys as _sys
+from keyword import iskeyword as _iskeyword
+
+
+def _validate_names(typename, field_names, extra_field_names):
+    """
+    Ensure that all the given names are valid Python identifiers that
+    do not start with '_'.  Also check that there are no duplicates
+    among field_names + extra_field_names.
+    """
+    for name in [typename] + field_names + extra_field_names:
+        if not isinstance(name, str):
+            raise TypeError('typename and all field names must be strings')
+        if not name.isidentifier():
+            raise ValueError('typename and all field names must be valid '
+                             f'identifiers: {name!r}')
+        if _iskeyword(name):
+            raise ValueError('typename and all field names cannot be a '
+                             f'keyword: {name!r}')
+
+    seen = set()
+    for name in field_names + extra_field_names:
+        if name.startswith('_'):
+            raise ValueError('Field names cannot start with an underscore: '
+                             f'{name!r}')
+        if name in seen:
+            raise ValueError(f'Duplicate field name: {name!r}')
+        seen.add(name)
+
+
+# Note: This code is adapted from CPython:Lib/collections/__init__.py
+def _make_tuple_bunch(typename, field_names, extra_field_names=None,
+                      module=None):
+    """
+    Create a namedtuple-like class with additional attributes.
+
+    This function creates a subclass of tuple that acts like a namedtuple
+    and that has additional attributes.
+
+    The additional attributes are listed in `extra_field_names`.  The
+    values assigned to these attributes are not part of the tuple.
+
+    The reason this function exists is to allow functions in SciPy
+    that currently return a tuple or a namedtuple to returned objects
+    that have additional attributes, while maintaining backwards
+    compatibility.
+
+    This should only be used to enhance *existing* functions in SciPy.
+    New functions are free to create objects as return values without
+    having to maintain backwards compatibility with an old tuple or
+    namedtuple return value.
+
+    Parameters
+    ----------
+    typename : str
+        The name of the type.
+    field_names : list of str
+        List of names of the values to be stored in the tuple. These names
+        will also be attributes of instances, so the values in the tuple
+        can be accessed by indexing or as attributes.  At least one name
+        is required.  See the Notes for additional restrictions.
+    extra_field_names : list of str, optional
+        List of names of values that will be stored as attributes of the
+        object.  See the notes for additional restrictions.
+
+    Returns
+    -------
+    cls : type
+        The new class.
+
+    Notes
+    -----
+    There are restrictions on the names that may be used in `field_names`
+    and `extra_field_names`:
+
+    * The names must be unique--no duplicates allowed.
+    * The names must be valid Python identifiers, and must not begin with
+      an underscore.
+    * The names must not be Python keywords (e.g. 'def', 'and', etc., are
+      not allowed).
+
+    Examples
+    --------
+    >>> from scipy._lib._bunch import _make_tuple_bunch
+
+    Create a class that acts like a namedtuple with length 2 (with field
+    names `x` and `y`) that will also have the attributes `w` and `beta`:
+
+    >>> Result = _make_tuple_bunch('Result', ['x', 'y'], ['w', 'beta'])
+
+    `Result` is the new class.  We call it with keyword arguments to create
+    a new instance with given values.
+
+    >>> result1 = Result(x=1, y=2, w=99, beta=0.5)
+    >>> result1
+    Result(x=1, y=2, w=99, beta=0.5)
+
+    `result1` acts like a tuple of length 2:
+
+    >>> len(result1)
+    2
+    >>> result1[:]
+    (1, 2)
+
+    The values assigned when the instance was created are available as
+    attributes:
+
+    >>> result1.y
+    2
+    >>> result1.beta
+    0.5
+    """
+    if len(field_names) == 0:
+        raise ValueError('field_names must contain at least one name')
+
+    if extra_field_names is None:
+        extra_field_names = []
+    _validate_names(typename, field_names, extra_field_names)
+
+    typename = _sys.intern(str(typename))
+    field_names = tuple(map(_sys.intern, field_names))
+    extra_field_names = tuple(map(_sys.intern, extra_field_names))
+
+    all_names = field_names + extra_field_names
+    arg_list = ', '.join(field_names)
+    full_list = ', '.join(all_names)
+    repr_fmt = ''.join(('(',
+                        ', '.join(f'{name}=%({name})r' for name in all_names),
+                        ')'))
+    tuple_new = tuple.__new__
+    _dict, _tuple, _zip = dict, tuple, zip
+
+    # Create all the named tuple methods to be added to the class namespace
+
+    s = f"""\
+def __new__(_cls, {arg_list}, **extra_fields):
+    return _tuple_new(_cls, ({arg_list},))
+
+def __init__(self, {arg_list}, **extra_fields):
+    for key in self._extra_fields:
+        if key not in extra_fields:
+            raise TypeError("missing keyword argument '%s'" % (key,))
+    for key, val in extra_fields.items():
+        if key not in self._extra_fields:
+            raise TypeError("unexpected keyword argument '%s'" % (key,))
+        self.__dict__[key] = val
+
+def __setattr__(self, key, val):
+    if key in {repr(field_names)}:
+        raise AttributeError("can't set attribute %r of class %r"
+                             % (key, self.__class__.__name__))
+    else:
+        self.__dict__[key] = val
+"""
+    del arg_list
+    namespace = {'_tuple_new': tuple_new,
+                 '__builtins__': dict(TypeError=TypeError,
+                                      AttributeError=AttributeError),
+                 '__name__': f'namedtuple_{typename}'}
+    exec(s, namespace)
+    __new__ = namespace['__new__']
+    __new__.__doc__ = f'Create new instance of {typename}({full_list})'
+    __init__ = namespace['__init__']
+    __init__.__doc__ = f'Instantiate instance of {typename}({full_list})'
+    __setattr__ = namespace['__setattr__']
+
+    def __repr__(self):
+        'Return a nicely formatted representation string'
+        return self.__class__.__name__ + repr_fmt % self._asdict()
+
+    def _asdict(self):
+        'Return a new dict which maps field names to their values.'
+        out = _dict(_zip(self._fields, self))
+        out.update(self.__dict__)
+        return out
+
+    def __getnewargs_ex__(self):
+        'Return self as a plain tuple.  Used by copy and pickle.'
+        return _tuple(self), self.__dict__
+
+    # Modify function metadata to help with introspection and debugging
+    for method in (__new__, __repr__, _asdict, __getnewargs_ex__):
+        method.__qualname__ = f'{typename}.{method.__name__}'
+
+    # Build-up the class namespace dictionary
+    # and use type() to build the result class
+    class_namespace = {
+        '__doc__': f'{typename}({full_list})',
+        '_fields': field_names,
+        '__new__': __new__,
+        '__init__': __init__,
+        '__repr__': __repr__,
+        '__setattr__': __setattr__,
+        '_asdict': _asdict,
+        '_extra_fields': extra_field_names,
+        '__getnewargs_ex__': __getnewargs_ex__,
+        # _field_defaults and _replace are added to get Polars to detect
+        # a bunch object as a namedtuple. See gh-22450
+        '_field_defaults': {},
+        '_replace': None,
+    }
+    for index, name in enumerate(field_names):
+
+        def _get(self, index=index):
+            return self[index]
+        class_namespace[name] = property(_get)
+    for name in extra_field_names:
+
+        def _get(self, name=name):
+            return self.__dict__[name]
+        class_namespace[name] = property(_get)
+
+    result = type(typename, (tuple,), class_namespace)
+
+    # For pickling to work, the __module__ variable needs to be set to the
+    # frame where the named tuple is created.  Bypass this step in environments
+    # where sys._getframe is not defined (Jython for example) or sys._getframe
+    # is not defined for arguments greater than 0 (IronPython), or where the
+    # user has specified a particular module.
+    if module is None:
+        try:
+            module = _sys._getframe(1).f_globals.get('__name__', '__main__')
+        except (AttributeError, ValueError):
+            pass
+    if module is not None:
+        result.__module__ = module
+        __new__.__module__ = module
+
+    return result
diff --git a/.venv/lib/python3.12/site-packages/scipy/_lib/_ccallback.py b/.venv/lib/python3.12/site-packages/scipy/_lib/_ccallback.py
new file mode 100644
index 0000000000000000000000000000000000000000..1980d06f5489e6633fb611c35bfb56903bd63e7f
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/_lib/_ccallback.py
@@ -0,0 +1,251 @@
+from . import _ccallback_c
+
+import ctypes
+
+PyCFuncPtr = ctypes.CFUNCTYPE(ctypes.c_void_p).__bases__[0]
+
+ffi = None
+
+class CData:
+    pass
+
+def _import_cffi():
+    global ffi, CData
+
+    if ffi is not None:
+        return
+
+    try:
+        import cffi
+        ffi = cffi.FFI()
+        CData = ffi.CData
+    except ImportError:
+        ffi = False
+
+
+class LowLevelCallable(tuple):
+    """
+    Low-level callback function.
+
+    Some functions in SciPy take as arguments callback functions, which
+    can either be python callables or low-level compiled functions. Using
+    compiled callback functions can improve performance somewhat by
+    avoiding wrapping data in Python objects.
+
+    Such low-level functions in SciPy are wrapped in `LowLevelCallable`
+    objects, which can be constructed from function pointers obtained from
+    ctypes, cffi, Cython, or contained in Python `PyCapsule` objects.
+
+    .. seealso::
+
+       Functions accepting low-level callables:
+
+       `scipy.integrate.quad`, `scipy.ndimage.generic_filter`,
+       `scipy.ndimage.generic_filter1d`, `scipy.ndimage.geometric_transform`
+
+       Usage examples:
+
+       :ref:`ndimage-ccallbacks`, :ref:`quad-callbacks`
+
+    Parameters
+    ----------
+    function : {PyCapsule, ctypes function pointer, cffi function pointer}
+        Low-level callback function.
+    user_data : {PyCapsule, ctypes void pointer, cffi void pointer}
+        User data to pass on to the callback function.
+    signature : str, optional
+        Signature of the function. If omitted, determined from *function*,
+        if possible.
+
+    Attributes
+    ----------
+    function
+        Callback function given.
+    user_data
+        User data given.
+    signature
+        Signature of the function.
+
+    Methods
+    -------
+    from_cython
+        Class method for constructing callables from Cython C-exported
+        functions.
+
+    Notes
+    -----
+    The argument ``function`` can be one of:
+
+    - PyCapsule, whose name contains the C function signature
+    - ctypes function pointer
+    - cffi function pointer
+
+    The signature of the low-level callback must match one of those expected
+    by the routine it is passed to.
+
+    If constructing low-level functions from a PyCapsule, the name of the
+    capsule must be the corresponding signature, in the format::
+
+        return_type (arg1_type, arg2_type, ...)
+
+    For example::
+
+        "void (double)"
+        "double (double, int *, void *)"
+
+    The context of a PyCapsule passed in as ``function`` is used as ``user_data``,
+    if an explicit value for ``user_data`` was not given.
+
+    """
+
+    # Make the class immutable
+    __slots__ = ()
+
+    def __new__(cls, function, user_data=None, signature=None):
+        # We need to hold a reference to the function & user data,
+        # to prevent them going out of scope
+        item = cls._parse_callback(function, user_data, signature)
+        return tuple.__new__(cls, (item, function, user_data))
+
+    def __repr__(self):
+        return f"LowLevelCallable({self.function!r}, {self.user_data!r})"
+
+    @property
+    def function(self):
+        return tuple.__getitem__(self, 1)
+
+    @property
+    def user_data(self):
+        return tuple.__getitem__(self, 2)
+
+    @property
+    def signature(self):
+        return _ccallback_c.get_capsule_signature(tuple.__getitem__(self, 0))
+
+    def __getitem__(self, idx):
+        raise ValueError()
+
+    @classmethod
+    def from_cython(cls, module, name, user_data=None, signature=None):
+        """
+        Create a low-level callback function from an exported Cython function.
+
+        Parameters
+        ----------
+        module : module
+            Cython module where the exported function resides
+        name : str
+            Name of the exported function
+        user_data : {PyCapsule, ctypes void pointer, cffi void pointer}, optional
+            User data to pass on to the callback function.
+        signature : str, optional
+            Signature of the function. If omitted, determined from *function*.
+
+        """
+        try:
+            function = module.__pyx_capi__[name]
+        except AttributeError as e:
+            message = "Given module is not a Cython module with __pyx_capi__ attribute"
+            raise ValueError(message) from e
+        except KeyError as e:
+            message = f"No function {name!r} found in __pyx_capi__ of the module"
+            raise ValueError(message) from e
+        return cls(function, user_data, signature)
+
+    @classmethod
+    def _parse_callback(cls, obj, user_data=None, signature=None):
+        _import_cffi()
+
+        if isinstance(obj, LowLevelCallable):
+            func = tuple.__getitem__(obj, 0)
+        elif isinstance(obj, PyCFuncPtr):
+            func, signature = _get_ctypes_func(obj, signature)
+        elif isinstance(obj, CData):
+            func, signature = _get_cffi_func(obj, signature)
+        elif _ccallback_c.check_capsule(obj):
+            func = obj
+        else:
+            raise ValueError("Given input is not a callable or a "
+                             "low-level callable (pycapsule/ctypes/cffi)")
+
+        if isinstance(user_data, ctypes.c_void_p):
+            context = _get_ctypes_data(user_data)
+        elif isinstance(user_data, CData):
+            context = _get_cffi_data(user_data)
+        elif user_data is None:
+            context = 0
+        elif _ccallback_c.check_capsule(user_data):
+            context = user_data
+        else:
+            raise ValueError("Given user data is not a valid "
+                             "low-level void* pointer (pycapsule/ctypes/cffi)")
+
+        return _ccallback_c.get_raw_capsule(func, signature, context)
+
+
+#
+# ctypes helpers
+#
+
+def _get_ctypes_func(func, signature=None):
+    # Get function pointer
+    func_ptr = ctypes.cast(func, ctypes.c_void_p).value
+
+    # Construct function signature
+    if signature is None:
+        signature = _typename_from_ctypes(func.restype) + " ("
+        for j, arg in enumerate(func.argtypes):
+            if j == 0:
+                signature += _typename_from_ctypes(arg)
+            else:
+                signature += ", " + _typename_from_ctypes(arg)
+        signature += ")"
+
+    return func_ptr, signature
+
+
+def _typename_from_ctypes(item):
+    if item is None:
+        return "void"
+    elif item is ctypes.c_void_p:
+        return "void *"
+
+    name = item.__name__
+
+    pointer_level = 0
+    while name.startswith("LP_"):
+        pointer_level += 1
+        name = name[3:]
+
+    if name.startswith('c_'):
+        name = name[2:]
+
+    if pointer_level > 0:
+        name += " " + "*"*pointer_level
+
+    return name
+
+
+def _get_ctypes_data(data):
+    # Get voidp pointer
+    return ctypes.cast(data, ctypes.c_void_p).value
+
+
+#
+# CFFI helpers
+#
+
+def _get_cffi_func(func, signature=None):
+    # Get function pointer
+    func_ptr = ffi.cast('uintptr_t', func)
+
+    # Get signature
+    if signature is None:
+        signature = ffi.getctype(ffi.typeof(func)).replace('(*)', ' ')
+
+    return func_ptr, signature
+
+
+def _get_cffi_data(data):
+    # Get pointer
+    return ffi.cast('uintptr_t', data)
diff --git a/.venv/lib/python3.12/site-packages/scipy/_lib/_ccallback_c.cpython-312-x86_64-linux-gnu.so b/.venv/lib/python3.12/site-packages/scipy/_lib/_ccallback_c.cpython-312-x86_64-linux-gnu.so
new file mode 100644
index 0000000000000000000000000000000000000000..a80d8624026841cfed071bffd1b66638440ab7a9
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/scipy/_lib/_ccallback_c.cpython-312-x86_64-linux-gnu.so differ
diff --git a/.venv/lib/python3.12/site-packages/scipy/_lib/_disjoint_set.py b/.venv/lib/python3.12/site-packages/scipy/_lib/_disjoint_set.py
new file mode 100644
index 0000000000000000000000000000000000000000..58dbf37ed4b883136d810dceceb3e5a9738abdd5
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/_lib/_disjoint_set.py
@@ -0,0 +1,264 @@
+"""
+Disjoint set data structure
+"""
+
+
+class DisjointSet:
+    """Disjoint set data structure for incremental connectivity queries.
+
+    .. versionadded:: 1.6.0
+
+    Parameters
+    ----------
+    elements : sequence of hashable objects
+        Elements of the disjoint set.
+
+    Attributes
+    ----------
+    n_subsets : int
+        The number of subsets.
+
+    Methods
+    -------
+    add
+    merge
+    connected
+    subset
+    subset_size
+    subsets
+    __getitem__
+
+    Notes
+    -----
+    This class implements the disjoint set [1]_, also known as the *union-find*
+    or *merge-find* data structure. The *find* operation (implemented in
+    `__getitem__`) implements the *path halving* variant. The *merge* method
+    implements the *merge by size* variant.
+
+    References
+    ----------
+    .. [1] https://en.wikipedia.org/wiki/Disjoint-set_data_structure
+
+    Examples
+    --------
+    >>> from scipy.cluster.hierarchy import DisjointSet
+
+    Initialize a disjoint set:
+
+    >>> disjoint_set = DisjointSet([1, 2, 3, 'a', 'b'])
+
+    Merge some subsets:
+
+    >>> disjoint_set.merge(1, 2)
+    True
+    >>> disjoint_set.merge(3, 'a')
+    True
+    >>> disjoint_set.merge('a', 'b')
+    True
+    >>> disjoint_set.merge('b', 'b')
+    False
+
+    Find root elements:
+
+    >>> disjoint_set[2]
+    1
+    >>> disjoint_set['b']
+    3
+
+    Test connectivity:
+
+    >>> disjoint_set.connected(1, 2)
+    True
+    >>> disjoint_set.connected(1, 'b')
+    False
+
+    List elements in disjoint set:
+
+    >>> list(disjoint_set)
+    [1, 2, 3, 'a', 'b']
+
+    Get the subset containing 'a':
+
+    >>> disjoint_set.subset('a')
+    {'a', 3, 'b'}
+
+    Get the size of the subset containing 'a' (without actually instantiating
+    the subset):
+
+    >>> disjoint_set.subset_size('a')
+    3
+
+    Get all subsets in the disjoint set:
+
+    >>> disjoint_set.subsets()
+    [{1, 2}, {'a', 3, 'b'}]
+    """
+    def __init__(self, elements=None):
+        self.n_subsets = 0
+        self._sizes = {}
+        self._parents = {}
+        # _nbrs is a circular linked list which links connected elements.
+        self._nbrs = {}
+        # _indices tracks the element insertion order in `__iter__`.
+        self._indices = {}
+        if elements is not None:
+            for x in elements:
+                self.add(x)
+
+    def __iter__(self):
+        """Returns an iterator of the elements in the disjoint set.
+
+        Elements are ordered by insertion order.
+        """
+        return iter(self._indices)
+
+    def __len__(self):
+        return len(self._indices)
+
+    def __contains__(self, x):
+        return x in self._indices
+
+    def __getitem__(self, x):
+        """Find the root element of `x`.
+
+        Parameters
+        ----------
+        x : hashable object
+            Input element.
+
+        Returns
+        -------
+        root : hashable object
+            Root element of `x`.
+        """
+        if x not in self._indices:
+            raise KeyError(x)
+
+        # find by "path halving"
+        parents = self._parents
+        while self._indices[x] != self._indices[parents[x]]:
+            parents[x] = parents[parents[x]]
+            x = parents[x]
+        return x
+
+    def add(self, x):
+        """Add element `x` to disjoint set.
+
+        Parameters
+        ----------
+        x : hashable object
+            Element to add to the disjoint set.
+        """
+        if x in self._indices:
+            return
+
+        self._sizes[x] = 1
+        self._parents[x] = x
+        self._nbrs[x] = x
+        self._indices[x] = len(self._indices)
+        self.n_subsets += 1
+
+    def merge(self, x, y):
+        """Merge the subsets of `x` and `y`.
+
+        The smaller subset (the child) is merged into the larger subset (the
+        parent). If the subsets are of equal size, the root element which was
+        first inserted into the disjoint set is selected as the parent.
+
+        Parameters
+        ----------
+        x, y : hashable object
+            Elements to merge.
+
+        Returns
+        -------
+        merged : bool
+            True if `x` and `y` were in disjoint sets, False otherwise.
+        """
+        xr = self[x]
+        yr = self[y]
+        if self._indices[xr] == self._indices[yr]:
+            return False
+
+        sizes = self._sizes
+        if (sizes[xr], self._indices[yr]) < (sizes[yr], self._indices[xr]):
+            xr, yr = yr, xr
+        self._parents[yr] = xr
+        self._sizes[xr] += self._sizes[yr]
+        self._nbrs[xr], self._nbrs[yr] = self._nbrs[yr], self._nbrs[xr]
+        self.n_subsets -= 1
+        return True
+
+    def connected(self, x, y):
+        """Test whether `x` and `y` are in the same subset.
+
+        Parameters
+        ----------
+        x, y : hashable object
+            Elements to test.
+
+        Returns
+        -------
+        result : bool
+            True if `x` and `y` are in the same set, False otherwise.
+        """
+        return self._indices[self[x]] == self._indices[self[y]]
+
+    def subset(self, x):
+        """Get the subset containing `x`.
+
+        Parameters
+        ----------
+        x : hashable object
+            Input element.
+
+        Returns
+        -------
+        result : set
+            Subset containing `x`.
+        """
+        if x not in self._indices:
+            raise KeyError(x)
+
+        result = [x]
+        nxt = self._nbrs[x]
+        while self._indices[nxt] != self._indices[x]:
+            result.append(nxt)
+            nxt = self._nbrs[nxt]
+        return set(result)
+
+    def subset_size(self, x):
+        """Get the size of the subset containing `x`.
+
+        Note that this method is faster than ``len(self.subset(x))`` because
+        the size is directly read off an internal field, without the need to
+        instantiate the full subset.
+
+        Parameters
+        ----------
+        x : hashable object
+            Input element.
+
+        Returns
+        -------
+        result : int
+            Size of the subset containing `x`.
+        """
+        return self._sizes[self[x]]
+
+    def subsets(self):
+        """Get all the subsets in the disjoint set.
+
+        Returns
+        -------
+        result : list
+            Subsets in the disjoint set.
+        """
+        result = []
+        visited = set()
+        for x in self:
+            if x not in visited:
+                xset = self.subset(x)
+                visited.update(xset)
+                result.append(xset)
+        return result
diff --git a/.venv/lib/python3.12/site-packages/scipy/_lib/_docscrape.py b/.venv/lib/python3.12/site-packages/scipy/_lib/_docscrape.py
new file mode 100644
index 0000000000000000000000000000000000000000..a6613158b979d84b7486f603e1173a017cb3de18
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/_lib/_docscrape.py
@@ -0,0 +1,761 @@
+# copied from numpydoc/docscrape.py, commit 97a6026508e0dd5382865672e9563a72cc113bd2
+"""Extract reference documentation from the NumPy source tree."""
+
+import copy
+import inspect
+import pydoc
+import re
+import sys
+import textwrap
+from collections import namedtuple
+from collections.abc import Callable, Mapping
+from functools import cached_property
+from warnings import warn
+
+
+def strip_blank_lines(l):
+    "Remove leading and trailing blank lines from a list of lines"
+    while l and not l[0].strip():
+        del l[0]
+    while l and not l[-1].strip():
+        del l[-1]
+    return l
+
+
+class Reader:
+    """A line-based string reader."""
+
+    def __init__(self, data):
+        """
+        Parameters
+        ----------
+        data : str
+           String with lines separated by '\\n'.
+
+        """
+        if isinstance(data, list):
+            self._str = data
+        else:
+            self._str = data.split("\n")  # store string as list of lines
+
+        self.reset()
+
+    def __getitem__(self, n):
+        return self._str[n]
+
+    def reset(self):
+        self._l = 0  # current line nr
+
+    def read(self):
+        if not self.eof():
+            out = self[self._l]
+            self._l += 1
+            return out
+        else:
+            return ""
+
+    def seek_next_non_empty_line(self):
+        for l in self[self._l :]:
+            if l.strip():
+                break
+            else:
+                self._l += 1
+
+    def eof(self):
+        return self._l >= len(self._str)
+
+    def read_to_condition(self, condition_func):
+        start = self._l
+        for line in self[start:]:
+            if condition_func(line):
+                return self[start : self._l]
+            self._l += 1
+            if self.eof():
+                return self[start : self._l + 1]
+        return []
+
+    def read_to_next_empty_line(self):
+        self.seek_next_non_empty_line()
+
+        def is_empty(line):
+            return not line.strip()
+
+        return self.read_to_condition(is_empty)
+
+    def read_to_next_unindented_line(self):
+        def is_unindented(line):
+            return line.strip() and (len(line.lstrip()) == len(line))
+
+        return self.read_to_condition(is_unindented)
+
+    def peek(self, n=0):
+        if self._l + n < len(self._str):
+            return self[self._l + n]
+        else:
+            return ""
+
+    def is_empty(self):
+        return not "".join(self._str).strip()
+
+
+class ParseError(Exception):
+    def __str__(self):
+        message = self.args[0]
+        if hasattr(self, "docstring"):
+            message = f"{message} in {self.docstring!r}"
+        return message
+
+
+Parameter = namedtuple("Parameter", ["name", "type", "desc"])
+
+
+class NumpyDocString(Mapping):
+    """Parses a numpydoc string to an abstract representation
+
+    Instances define a mapping from section title to structured data.
+
+    """
+
+    sections = {
+        "Signature": "",
+        "Summary": [""],
+        "Extended Summary": [],
+        "Parameters": [],
+        "Attributes": [],
+        "Methods": [],
+        "Returns": [],
+        "Yields": [],
+        "Receives": [],
+        "Other Parameters": [],
+        "Raises": [],
+        "Warns": [],
+        "Warnings": [],
+        "See Also": [],
+        "Notes": [],
+        "References": "",
+        "Examples": "",
+        "index": {},
+    }
+
+    def __init__(self, docstring, config=None):
+        orig_docstring = docstring
+        docstring = textwrap.dedent(docstring).split("\n")
+
+        self._doc = Reader(docstring)
+        self._parsed_data = copy.deepcopy(self.sections)
+
+        try:
+            self._parse()
+        except ParseError as e:
+            e.docstring = orig_docstring
+            raise
+
+    def __getitem__(self, key):
+        return self._parsed_data[key]
+
+    def __setitem__(self, key, val):
+        if key not in self._parsed_data:
+            self._error_location(f"Unknown section {key}", error=False)
+        else:
+            self._parsed_data[key] = val
+
+    def __iter__(self):
+        return iter(self._parsed_data)
+
+    def __len__(self):
+        return len(self._parsed_data)
+
+    def _is_at_section(self):
+        self._doc.seek_next_non_empty_line()
+
+        if self._doc.eof():
+            return False
+
+        l1 = self._doc.peek().strip()  # e.g. Parameters
+
+        if l1.startswith(".. index::"):
+            return True
+
+        l2 = self._doc.peek(1).strip()  # ---------- or ==========
+        if len(l2) >= 3 and (set(l2) in ({"-"}, {"="})) and len(l2) != len(l1):
+            snip = "\n".join(self._doc._str[:2]) + "..."
+            self._error_location(
+                f"potentially wrong underline length... \n{l1} \n{l2} in \n{snip}",
+                error=False,
+            )
+        return l2.startswith("-" * len(l1)) or l2.startswith("=" * len(l1))
+
+    def _strip(self, doc):
+        i = 0
+        j = 0
+        for i, line in enumerate(doc):
+            if line.strip():
+                break
+
+        for j, line in enumerate(doc[::-1]):
+            if line.strip():
+                break
+
+        return doc[i : len(doc) - j]
+
+    def _read_to_next_section(self):
+        section = self._doc.read_to_next_empty_line()
+
+        while not self._is_at_section() and not self._doc.eof():
+            if not self._doc.peek(-1).strip():  # previous line was empty
+                section += [""]
+
+            section += self._doc.read_to_next_empty_line()
+
+        return section
+
+    def _read_sections(self):
+        while not self._doc.eof():
+            data = self._read_to_next_section()
+            name = data[0].strip()
+
+            if name.startswith(".."):  # index section
+                yield name, data[1:]
+            elif len(data) < 2:
+                yield StopIteration
+            else:
+                yield name, self._strip(data[2:])
+
+    def _parse_param_list(self, content, single_element_is_type=False):
+        content = dedent_lines(content)
+        r = Reader(content)
+        params = []
+        while not r.eof():
+            header = r.read().strip()
+            if " : " in header:
+                arg_name, arg_type = header.split(" : ", maxsplit=1)
+            else:
+                # NOTE: param line with single element should never have a
+                # a " :" before the description line, so this should probably
+                # warn.
+                if header.endswith(" :"):
+                    header = header[:-2]
+                if single_element_is_type:
+                    arg_name, arg_type = "", header
+                else:
+                    arg_name, arg_type = header, ""
+
+            desc = r.read_to_next_unindented_line()
+            desc = dedent_lines(desc)
+            desc = strip_blank_lines(desc)
+
+            params.append(Parameter(arg_name, arg_type, desc))
+
+        return params
+
+    # See also supports the following formats.
+    #
+    # 
+    #  SPACE* COLON SPACE+  SPACE*
+    #  ( COMMA SPACE+ )+ (COMMA | PERIOD)? SPACE*
+    #  ( COMMA SPACE+ )* SPACE* COLON SPACE+  SPACE*
+
+    #  is one of
+    #   
+    #   COLON  COLON BACKTICK  BACKTICK
+    # where
+    #    is a legal function name, and
+    #    is any nonempty sequence of word characters.
+    # Examples: func_f1  :meth:`func_h1` :obj:`~baz.obj_r` :class:`class_j`
+    #  is a string describing the function.
+
+    _role = r":(?P(py:)?\w+):"
+    _funcbacktick = r"`(?P(?:~\w+\.)?[a-zA-Z0-9_\.-]+)`"
+    _funcplain = r"(?P[a-zA-Z0-9_\.-]+)"
+    _funcname = r"(" + _role + _funcbacktick + r"|" + _funcplain + r")"
+    _funcnamenext = _funcname.replace("role", "rolenext")
+    _funcnamenext = _funcnamenext.replace("name", "namenext")
+    _description = r"(?P\s*:(\s+(?P\S+.*))?)?\s*$"
+    _func_rgx = re.compile(r"^\s*" + _funcname + r"\s*")
+    _line_rgx = re.compile(
+        r"^\s*"
+        + r"(?P"
+        + _funcname  # group for all function names
+        + r"(?P([,]\s+"
+        + _funcnamenext
+        + r")*)"
+        + r")"
+        + r"(?P[,\.])?"  # end of "allfuncs"
+        + _description  # Some function lists have a trailing comma (or period)  '\s*'
+    )
+
+    # Empty  elements are replaced with '..'
+    empty_description = ".."
+
+    def _parse_see_also(self, content):
+        """
+        func_name : Descriptive text
+            continued text
+        another_func_name : Descriptive text
+        func_name1, func_name2, :meth:`func_name`, func_name3
+
+        """
+
+        content = dedent_lines(content)
+
+        items = []
+
+        def parse_item_name(text):
+            """Match ':role:`name`' or 'name'."""
+            m = self._func_rgx.match(text)
+            if not m:
+                self._error_location(f"Error parsing See Also entry {line!r}")
+            role = m.group("role")
+            name = m.group("name") if role else m.group("name2")
+            return name, role, m.end()
+
+        rest = []
+        for line in content:
+            if not line.strip():
+                continue
+
+            line_match = self._line_rgx.match(line)
+            description = None
+            if line_match:
+                description = line_match.group("desc")
+                if line_match.group("trailing") and description:
+                    self._error_location(
+                        "Unexpected comma or period after function list at index %d of "
+                        'line "%s"' % (line_match.end("trailing"), line),
+                        error=False,
+                    )
+            if not description and line.startswith(" "):
+                rest.append(line.strip())
+            elif line_match:
+                funcs = []
+                text = line_match.group("allfuncs")
+                while True:
+                    if not text.strip():
+                        break
+                    name, role, match_end = parse_item_name(text)
+                    funcs.append((name, role))
+                    text = text[match_end:].strip()
+                    if text and text[0] == ",":
+                        text = text[1:].strip()
+                rest = list(filter(None, [description]))
+                items.append((funcs, rest))
+            else:
+                self._error_location(f"Error parsing See Also entry {line!r}")
+        return items
+
+    def _parse_index(self, section, content):
+        """
+        .. index:: default
+           :refguide: something, else, and more
+
+        """
+
+        def strip_each_in(lst):
+            return [s.strip() for s in lst]
+
+        out = {}
+        section = section.split("::")
+        if len(section) > 1:
+            out["default"] = strip_each_in(section[1].split(","))[0]
+        for line in content:
+            line = line.split(":")
+            if len(line) > 2:
+                out[line[1]] = strip_each_in(line[2].split(","))
+        return out
+
+    def _parse_summary(self):
+        """Grab signature (if given) and summary"""
+        if self._is_at_section():
+            return
+
+        # If several signatures present, take the last one
+        while True:
+            summary = self._doc.read_to_next_empty_line()
+            summary_str = " ".join([s.strip() for s in summary]).strip()
+            compiled = re.compile(r"^([\w., ]+=)?\s*[\w\.]+\(.*\)$")
+            if compiled.match(summary_str):
+                self["Signature"] = summary_str
+                if not self._is_at_section():
+                    continue
+            break
+
+        if summary is not None:
+            self["Summary"] = summary
+
+        if not self._is_at_section():
+            self["Extended Summary"] = self._read_to_next_section()
+
+    def _parse(self):
+        self._doc.reset()
+        self._parse_summary()
+
+        sections = list(self._read_sections())
+        section_names = {section for section, content in sections}
+
+        has_yields = "Yields" in section_names
+        # We could do more tests, but we are not. Arbitrarily.
+        if not has_yields and "Receives" in section_names:
+            msg = "Docstring contains a Receives section but not Yields."
+            raise ValueError(msg)
+
+        for section, content in sections:
+            if not section.startswith(".."):
+                section = (s.capitalize() for s in section.split(" "))
+                section = " ".join(section)
+                if self.get(section):
+                    self._error_location(
+                        "The section %s appears twice in  %s"
+                        % (section, "\n".join(self._doc._str))
+                    )
+
+            if section in ("Parameters", "Other Parameters", "Attributes", "Methods"):
+                self[section] = self._parse_param_list(content)
+            elif section in ("Returns", "Yields", "Raises", "Warns", "Receives"):
+                self[section] = self._parse_param_list(
+                    content, single_element_is_type=True
+                )
+            elif section.startswith(".. index::"):
+                self["index"] = self._parse_index(section, content)
+            elif section == "See Also":
+                self["See Also"] = self._parse_see_also(content)
+            else:
+                self[section] = content
+
+    @property
+    def _obj(self):
+        if hasattr(self, "_cls"):
+            return self._cls
+        elif hasattr(self, "_f"):
+            return self._f
+        return None
+
+    def _error_location(self, msg, error=True):
+        if self._obj is not None:
+            # we know where the docs came from:
+            try:
+                filename = inspect.getsourcefile(self._obj)
+            except TypeError:
+                filename = None
+            # Make UserWarning more descriptive via object introspection.
+            # Skip if introspection fails
+            name = getattr(self._obj, "__name__", None)
+            if name is None:
+                name = getattr(getattr(self._obj, "__class__", None), "__name__", None)
+            if name is not None:
+                msg += f" in the docstring of {name}"
+            msg += f" in {filename}." if filename else ""
+        if error:
+            raise ValueError(msg)
+        else:
+            warn(msg, stacklevel=3)
+
+    # string conversion routines
+
+    def _str_header(self, name, symbol="-"):
+        return [name, len(name) * symbol]
+
+    def _str_indent(self, doc, indent=4):
+        return [" " * indent + line for line in doc]
+
+    def _str_signature(self):
+        if self["Signature"]:
+            return [self["Signature"].replace("*", r"\*")] + [""]
+        return [""]
+
+    def _str_summary(self):
+        if self["Summary"]:
+            return self["Summary"] + [""]
+        return []
+
+    def _str_extended_summary(self):
+        if self["Extended Summary"]:
+            return self["Extended Summary"] + [""]
+        return []
+
+    def _str_param_list(self, name):
+        out = []
+        if self[name]:
+            out += self._str_header(name)
+            for param in self[name]:
+                parts = []
+                if param.name:
+                    parts.append(param.name)
+                if param.type:
+                    parts.append(param.type)
+                out += [" : ".join(parts)]
+                if param.desc and "".join(param.desc).strip():
+                    out += self._str_indent(param.desc)
+            out += [""]
+        return out
+
+    def _str_section(self, name):
+        out = []
+        if self[name]:
+            out += self._str_header(name)
+            out += self[name]
+            out += [""]
+        return out
+
+    def _str_see_also(self, func_role):
+        if not self["See Also"]:
+            return []
+        out = []
+        out += self._str_header("See Also")
+        out += [""]
+        last_had_desc = True
+        for funcs, desc in self["See Also"]:
+            assert isinstance(funcs, list)
+            links = []
+            for func, role in funcs:
+                if role:
+                    link = f":{role}:`{func}`"
+                elif func_role:
+                    link = f":{func_role}:`{func}`"
+                else:
+                    link = f"`{func}`_"
+                links.append(link)
+            link = ", ".join(links)
+            out += [link]
+            if desc:
+                out += self._str_indent([" ".join(desc)])
+                last_had_desc = True
+            else:
+                last_had_desc = False
+                out += self._str_indent([self.empty_description])
+
+        if last_had_desc:
+            out += [""]
+        out += [""]
+        return out
+
+    def _str_index(self):
+        idx = self["index"]
+        out = []
+        output_index = False
+        default_index = idx.get("default", "")
+        if default_index:
+            output_index = True
+        out += [f".. index:: {default_index}"]
+        for section, references in idx.items():
+            if section == "default":
+                continue
+            output_index = True
+            out += [f"   :{section}: {', '.join(references)}"]
+        if output_index:
+            return out
+        return ""
+
+    def __str__(self, func_role=""):
+        out = []
+        out += self._str_signature()
+        out += self._str_summary()
+        out += self._str_extended_summary()
+        out += self._str_param_list("Parameters")
+        for param_list in ("Attributes", "Methods"):
+            out += self._str_param_list(param_list)
+        for param_list in (
+            "Returns",
+            "Yields",
+            "Receives",
+            "Other Parameters",
+            "Raises",
+            "Warns",
+        ):
+            out += self._str_param_list(param_list)
+        out += self._str_section("Warnings")
+        out += self._str_see_also(func_role)
+        for s in ("Notes", "References", "Examples"):
+            out += self._str_section(s)
+        out += self._str_index()
+        return "\n".join(out)
+
+
+def dedent_lines(lines):
+    """Deindent a list of lines maximally"""
+    return textwrap.dedent("\n".join(lines)).split("\n")
+
+
+class FunctionDoc(NumpyDocString):
+    def __init__(self, func, role="func", doc=None, config=None):
+        self._f = func
+        self._role = role  # e.g. "func" or "meth"
+
+        if doc is None:
+            if func is None:
+                raise ValueError("No function or docstring given")
+            doc = inspect.getdoc(func) or ""
+        if config is None:
+            config = {}
+        NumpyDocString.__init__(self, doc, config)
+
+    def get_func(self):
+        func_name = getattr(self._f, "__name__", self.__class__.__name__)
+        if inspect.isclass(self._f):
+            func = getattr(self._f, "__call__", self._f.__init__)
+        else:
+            func = self._f
+        return func, func_name
+
+    def __str__(self):  # pyrefly:ignore[bad-override]
+        out = ""
+
+        func, func_name = self.get_func()
+
+        roles = {"func": "function", "meth": "method"}
+
+        if self._role:
+            if self._role not in roles:
+                print(f"Warning: invalid role {self._role}")
+            out += f".. {roles.get(self._role, '')}:: {func_name}\n    \n\n"
+
+        out += super().__str__(func_role=self._role)
+        return out
+
+
+class ObjDoc(NumpyDocString):
+    def __init__(self, obj, doc=None, config=None):
+        self._f = obj
+        if config is None:
+            config = {}
+        NumpyDocString.__init__(self, doc, config=config)
+
+
+class ClassDoc(NumpyDocString):
+    extra_public_methods = ["__call__"]
+
+    def __init__(self, cls, doc=None, modulename="", func_doc=FunctionDoc, config=None):
+        if not inspect.isclass(cls) and cls is not None:
+            raise ValueError(f"Expected a class or None, but got {cls!r}")
+        self._cls = cls
+
+        if "sphinx" in sys.modules:
+            from sphinx.ext.autodoc import ALL
+        else:
+            ALL = object()
+
+        if config is None:
+            config = {}
+        self.show_inherited_members = config.get("show_inherited_class_members", True)
+
+        if modulename and not modulename.endswith("."):
+            modulename += "."
+        self._mod = modulename
+
+        if doc is None:
+            if cls is None:
+                raise ValueError("No class or documentation string given")
+            doc = pydoc.getdoc(cls)
+
+        NumpyDocString.__init__(self, doc)
+
+        _members = config.get("members", [])
+        if _members is ALL:
+            _members = None
+        _exclude = config.get("exclude-members", [])
+
+        if config.get("show_class_members", True) and _exclude is not ALL:
+
+            def splitlines_x(s):
+                if not s:
+                    return []
+                else:
+                    return s.splitlines()
+
+            for field, items in [
+                ("Methods", self.methods),
+                ("Attributes", self.properties),
+            ]:
+                if not self[field]:
+                    doc_list = []
+                    for name in sorted(items):
+                        if name in _exclude or (_members and name not in _members):
+                            continue
+                        try:
+                            doc_item = pydoc.getdoc(getattr(self._cls, name))
+                            doc_list.append(Parameter(name, "", splitlines_x(doc_item)))
+                        except AttributeError:
+                            pass  # method doesn't exist
+                    self[field] = doc_list
+
+    @property
+    def methods(self):
+        if self._cls is None:
+            return []
+        return [
+            name
+            for name, func in inspect.getmembers(self._cls)
+            if (
+                (not name.startswith("_") or name in self.extra_public_methods)
+                and isinstance(func, Callable)
+                and self._is_show_member(name)
+            )
+        ]
+
+    @property
+    def properties(self):
+        if self._cls is None:
+            return []
+        return [
+            name
+            for name, func in inspect.getmembers(self._cls)
+            if (
+                not name.startswith("_")
+                and not self._should_skip_member(name, self._cls)
+                and (
+                    func is None
+                    or isinstance(func, property | cached_property)
+                    or inspect.isdatadescriptor(func)
+                )
+                and self._is_show_member(name)
+            )
+        ]
+
+    @staticmethod
+    def _should_skip_member(name, klass):
+        return (
+            # Namedtuples should skip everything in their ._fields as the
+            # docstrings for each of the members is: "Alias for field number X"
+            issubclass(klass, tuple)
+            and hasattr(klass, "_asdict")
+            and hasattr(klass, "_fields")
+            and name in klass._fields
+        )
+
+    def _is_show_member(self, name):
+        return (
+            # show all class members
+            self.show_inherited_members
+            # or class member is not inherited
+            or name in self._cls.__dict__
+        )
+
+
+def get_doc_object(
+    obj,
+    what=None,
+    doc=None,
+    config=None,
+    class_doc=ClassDoc,
+    func_doc=FunctionDoc,
+    obj_doc=ObjDoc,
+):
+    if what is None:
+        if inspect.isclass(obj):
+            what = "class"
+        elif inspect.ismodule(obj):
+            what = "module"
+        elif isinstance(obj, Callable):
+            what = "function"
+        else:
+            what = "object"
+    if config is None:
+        config = {}
+
+    if what == "class":
+        return class_doc(obj, func_doc=func_doc, doc=doc, config=config)
+    elif what in ("function", "method"):
+        return func_doc(obj, doc=doc, config=config)
+    else:
+        if doc is None:
+            doc = pydoc.getdoc(obj)
+        return obj_doc(obj, doc, config=config)
diff --git a/.venv/lib/python3.12/site-packages/scipy/_lib/_elementwise_iterative_method.py b/.venv/lib/python3.12/site-packages/scipy/_lib/_elementwise_iterative_method.py
new file mode 100644
index 0000000000000000000000000000000000000000..5a7eea1d9888b77047acda544e7514cfc0e79bf1
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/_lib/_elementwise_iterative_method.py
@@ -0,0 +1,357 @@
+# `_elementwise_iterative_method.py` includes tools for writing functions that
+# - are vectorized to work elementwise on arrays,
+# - implement non-trivial, iterative algorithms with a callback interface, and
+# - return rich objects with iteration count, termination status, etc.
+#
+# Examples include:
+# `scipy.optimize._chandrupatla._chandrupatla for scalar rootfinding,
+# `scipy.optimize._chandrupatla._chandrupatla_minimize for scalar minimization,
+# `scipy.optimize._differentiate._differentiate for numerical differentiation,
+# `scipy.optimize._bracket._bracket_root for finding rootfinding brackets,
+# `scipy.optimize._bracket._bracket_minimize for finding minimization brackets,
+# `scipy.integrate._tanhsinh._tanhsinh` for numerical quadrature,
+# `scipy.differentiate.derivative` for finite difference based differentiation.
+
+import math
+import numpy as np
+from ._util import _RichResult, _call_callback_maybe_halt
+from ._array_api import array_namespace, xp_size, xp_result_type
+import scipy._external.array_api_extra as xpx
+
+_ESIGNERR = -1
+_ECONVERR = -2
+_EVALUEERR = -3
+_ECALLBACK = -4
+_EINPUTERR = -5
+_ECONVERGED = 0
+_EINPROGRESS = 1
+
+def _initialize(func, xs, args, kwargs=None,
+                complex_ok=False, preserve_shape=None, xp=None):
+    """Initialize abscissa, function, and args arrays for elementwise function
+
+    Parameters
+    ----------
+    func : callable
+        An elementwise function with signature
+
+            func(x: ndarray, *args) -> ndarray
+
+        where each element of ``x`` is a finite real and ``args`` is a tuple,
+        which may contain an arbitrary number of arrays that are broadcastable
+        with ``x``.
+    xs : tuple of arrays
+        Finite real abscissa arrays. Must be broadcastable.
+    args : tuple, optional
+        Additional positional arguments to be passed to `func`.
+    kwargs : tuple, optional
+        Additional keyword arguments to be passed to `func`.
+    preserve_shape : bool, default:False
+        When ``preserve_shape=False`` (default), `func` may be passed
+        arguments of any shape; `_scalar_optimization_loop` is permitted
+        to reshape and compress arguments at will. When
+        ``preserve_shape=False``, arguments passed to `func` must have shape
+        `shape` or ``shape + (n,)``, where ``n`` is any integer.
+    xp : namespace
+        Namespace of array arguments in `xs`.
+
+    Returns
+    -------
+    xs, fs, args : tuple of arrays
+        Broadcasted, writeable, 1D abscissa and function value arrays (or
+        NumPy floats, if appropriate). The dtypes of the `xs` and `fs` are
+        `xfat`; the dtype of the `args` are unchanged.
+    shape : tuple of ints
+        Original shape of broadcasted arrays.
+    xfat : NumPy dtype
+        Result dtype of abscissae, function values, and args determined using
+        `np.result_type`, except integer types are promoted to `np.float64`.
+
+    Raises
+    ------
+    ValueError
+        If the result dtype is not that of a real scalar
+
+    Notes
+    -----
+    Useful for initializing the input of SciPy functions that accept
+    an elementwise callable, abscissae, and arguments; e.g.
+    `scipy.optimize._chandrupatla`.
+    """
+    nx = len(xs)
+    xp = array_namespace(*xs) if xp is None else xp
+
+    if kwargs is not None:
+        args = (*args, *kwargs.values())
+        kwnames = tuple(kwargs.keys())
+        def func(x, *args, kwnames=kwnames, func=func, **kwargs):
+            nargs = len(args) - len(kwnames)
+            kwarrays = dict(zip(kwnames, args[nargs:]))
+            return func(x, *args[:nargs], **kwarrays, **kwargs)
+
+    # Try to preserve `dtype`, but we need to ensure that the arguments are at
+    # least floats before passing them into the function; integers can overflow
+    # and cause failure.
+    # There might be benefit to combining the `xs` into a single array and
+    # calling `func` once on the combined array. For now, keep them separate.
+    xat = xp_result_type(*xs, force_floating=True, xp=xp)
+    xas = xp.broadcast_arrays(*xs, *args)  # broadcast and rename
+    xs, args = xas[:nx], xas[nx:]
+    xs = [xp.asarray(x, dtype=xat) for x in xs]  # use copy=False when implemented
+    fs = [xp.asarray(func(x, *args)) for x in xs]
+    shape = xs[0].shape
+    fshape = fs[0].shape
+
+    if preserve_shape:
+        # bind original shape/func now to avoid late-binding gotcha
+        def func(x, *args, shape=shape, func=func,  **kwargs):
+            i = (0,)*(len(fshape) - len(shape))
+            return func(x[i], *args, **kwargs)
+        shape = np.broadcast_shapes(fshape, shape)  # just shapes; use of NumPy OK
+        xs = [xp.broadcast_to(x, shape) for x in xs]
+        args = [xp.broadcast_to(arg, shape) for arg in args]
+
+    message = ("The shape of the array returned by `func` must be the same as "
+               "the broadcasted shape of `x` and all other `args`.")
+    if preserve_shape is not None:  # only in tanhsinh for now
+        message = f"When `preserve_shape=False`, {message.lower()}"
+    shapes_equal = [f.shape == shape for f in fs]
+    if not all(shapes_equal):  # use Python all to reduce overhead
+        raise ValueError(message)
+
+    # These algorithms tend to mix the dtypes of the abscissae and function
+    # values, so figure out what the result will be and convert them all to
+    # that type from the outset.
+    xfat = xp.result_type(*([f.dtype for f in fs] + [xat]))
+    if not complex_ok and not xp.isdtype(xfat, "real floating"):
+        raise ValueError("Abscissae and function output must be real numbers.")
+    xs = [xp.asarray(x, dtype=xfat, copy=True) for x in xs]
+    fs = [xp.asarray(f, dtype=xfat, copy=True) for f in fs]
+
+    # To ensure that we can do indexing, we'll work with at least 1d arrays,
+    # but remember the appropriate shape of the output.
+    xs = [xp.reshape(x, (-1,)) for x in xs]
+    fs = [xp.reshape(f, (-1,)) for f in fs]
+    args = [xp.reshape(xp.asarray(arg, copy=True), (-1,)) for arg in args]
+    return func, xs, fs, args, shape, xfat, xp
+
+
+def _loop(work, callback, shape, maxiter, func, args, dtype, pre_func_eval,
+          post_func_eval, check_termination, post_termination_check,
+          customize_result, res_work_pairs, xp, preserve_shape=False):
+    """Main loop of a vectorized scalar optimization algorithm
+
+    Parameters
+    ----------
+    work : _RichResult
+        All variables that need to be retained between iterations. Must
+        contain attributes `nit`, `nfev`, and `success`. All arrays are
+        subject to being "compressed" if `preserve_shape is False`; nest
+        arrays that should not be compressed inside another object (e.g.
+        `dict` or `_RichResult`).
+    callback : callable
+        User-specified callback function
+    shape : tuple of ints
+        The shape of all output arrays
+    maxiter :
+        Maximum number of iterations of the algorithm
+    func : callable
+        The user-specified callable that is being optimized or solved
+    args : tuple
+        Additional positional arguments to be passed to `func`.
+    dtype : NumPy dtype
+        The common dtype of all abscissae and function values
+    pre_func_eval : callable
+        A function that accepts `work` and returns `x`, the active elements
+        of `x` at which `func` will be evaluated. May modify attributes
+        of `work` with any algorithmic steps that need to happen
+         at the beginning of an iteration, before `func` is evaluated,
+    post_func_eval : callable
+        A function that accepts `x`, `func(x)`, and `work`. May modify
+        attributes of `work` with any algorithmic steps that need to happen
+         in the middle of an iteration, after `func` is evaluated but before
+         the termination check.
+    check_termination : callable
+        A function that accepts `work` and returns `stop`, a boolean array
+        indicating which of the active elements have met a termination
+        condition.
+    post_termination_check : callable
+        A function that accepts `work`. May modify `work` with any algorithmic
+        steps that need to happen after the termination check and before the
+        end of the iteration.
+    customize_result : callable
+        A function that accepts `res` and `shape` and returns `shape`. May
+        modify `res` (in-place) according to preferences (e.g. rearrange
+        elements between attributes) and modify `shape` if needed.
+    res_work_pairs : list of (str, str)
+        Identifies correspondence between attributes of `res` and attributes
+        of `work`; i.e., attributes of active elements of `work` will be
+        copied to the appropriate indices of `res` when appropriate. The order
+        determines the order in which _RichResult attributes will be
+        pretty-printed.
+    preserve_shape : bool, default: False
+        Whether to compress the attributes of `work` (to avoid unnecessary
+        computation on elements that have already converged).
+
+    Returns
+    -------
+    res : _RichResult
+        The final result object
+
+    Notes
+    -----
+    Besides providing structure, this framework provides several important
+    services for a vectorized optimization algorithm.
+
+    - It handles common tasks involving iteration count, function evaluation
+      count, a user-specified callback, and associated termination conditions.
+    - It compresses the attributes of `work` to eliminate unnecessary
+      computation on elements that have already converged.
+
+    """
+    if xp is None:
+        raise NotImplementedError("Must provide xp.")
+
+    cb_terminate = False
+
+    # Initialize the result object and active element index array
+    n_elements = math.prod(shape)
+    active = xp.arange(n_elements)  # in-progress element indices
+    res_dict = {i: xp.zeros(n_elements, dtype=dtype) for i, j in res_work_pairs}
+    res_dict['success'] = xp.zeros(n_elements, dtype=xp.bool)
+    res_dict['status'] = xp.full(n_elements, xp.asarray(_EINPROGRESS), dtype=xp.int32)
+    res_dict['nit'] = xp.zeros(n_elements, dtype=xp.int32)
+    res_dict['nfev'] = xp.zeros(n_elements, dtype=xp.int32)
+    res = _RichResult(res_dict)
+    work.args = args
+
+    active = _check_termination(work, res, res_work_pairs, active,
+                                check_termination, preserve_shape, xp)
+
+    if callback is not None:
+        temp = _prepare_result(work, res, res_work_pairs, active, shape,
+                               customize_result, preserve_shape, xp)
+        if _call_callback_maybe_halt(callback, temp):
+            cb_terminate = True
+
+    while work.nit < maxiter and xp_size(active) and not cb_terminate and n_elements:
+        x = pre_func_eval(work)
+
+        if work.args and work.args[0].ndim != x.ndim:
+            # `x` always starts as 1D. If the SciPy function that uses
+            # _loop added dimensions to `x`, we need to
+            # add them to the elements of `args`.
+            args = []
+            for arg in work.args:
+                n_new_dims = x.ndim - arg.ndim
+                new_shape = arg.shape + (1,)*n_new_dims
+                args.append(xp.reshape(arg, new_shape))
+            work.args = args
+
+        x_shape = x.shape
+        if preserve_shape:
+            x = xp.reshape(x, (shape + (-1,)))
+        f = func(x, *work.args)
+        f = xp.asarray(f, dtype=dtype)
+        if preserve_shape:
+            x = xp.reshape(x, x_shape)
+            f = xp.reshape(f, x_shape)
+        work.nfev += 1 if x.ndim == 1 else x.shape[-1]
+
+        post_func_eval(x, f, work)
+
+        work.nit += 1
+        active = _check_termination(work, res, res_work_pairs, active,
+                                    check_termination, preserve_shape, xp)
+
+        if callback is not None:
+            temp = _prepare_result(work, res, res_work_pairs, active, shape,
+                                   customize_result, preserve_shape, xp)
+            if _call_callback_maybe_halt(callback, temp):
+                cb_terminate = True
+                break
+        if xp_size(active) == 0:
+            break
+
+        post_termination_check(work)
+
+    work.status = xpx.at(work.status)[:].set(_ECALLBACK if cb_terminate else _ECONVERR)
+    return _prepare_result(work, res, res_work_pairs, active, shape,
+                           customize_result, preserve_shape, xp)
+
+
+def _check_termination(work, res, res_work_pairs, active, check_termination,
+                       preserve_shape, xp):
+    # Checks termination conditions, updates elements of `res` with
+    # corresponding elements of `work`, and compresses `work`.
+
+    stop = check_termination(work)
+
+    if xp.any(stop):
+        # update the active elements of the result object with the active
+        # elements for which a termination condition has been met
+        _update_active(work, res, res_work_pairs, active, stop, preserve_shape, xp)
+
+        if preserve_shape:
+            stop = stop[active]
+
+        proceed = ~stop
+        active = active[proceed]
+
+        if not preserve_shape:
+            # compress the arrays to avoid unnecessary computation
+            for key, val in work.items():
+                # `continued_fraction` hacks `n`; improve if this becomes a problem
+                if key in {'args', 'n'}:
+                    continue
+                work[key] = val[proceed] if getattr(val, 'ndim', 0) > 0 else val
+            work.args = [arg[proceed] for arg in work.args]
+
+    return active
+
+
+def _update_active(work, res, res_work_pairs, active, mask, preserve_shape, xp):
+    # Update `active` indices of the arrays in result object `res` with the
+    # contents of the scalars and arrays in `update_dict`. When provided,
+    # `mask` is a boolean array applied both to the arrays in `update_dict`
+    # that are to be used and to the arrays in `res` that are to be updated.
+    update_dict = {key1: work[key2] for key1, key2 in res_work_pairs}
+    update_dict['success'] = work.status == 0
+
+    if mask is not None:
+        if preserve_shape:
+            active_mask = xp.zeros_like(mask)
+            active_mask = xpx.at(active_mask)[active].set(True)
+            active_mask = active_mask & mask
+            for key, val in update_dict.items():
+                val = val[active_mask] if getattr(val, 'ndim', 0) > 0 else val
+                res[key] = xpx.at(res[key])[active_mask].set(val)
+        else:
+            active_mask = active[mask]
+            for key, val in update_dict.items():
+                val = val[mask] if getattr(val, 'ndim', 0) > 0 else val
+                res[key] = xpx.at(res[key])[active_mask].set(val)
+    else:
+        for key, val in update_dict.items():
+            if preserve_shape and getattr(val, 'ndim', 0) > 0:
+                val = val[active]
+            res[key] = xpx.at(res[key])[active].set(val)
+
+
+def _prepare_result(work, res, res_work_pairs, active, shape, customize_result,
+                    preserve_shape, xp):
+    # Prepare the result object `res` by creating a copy, copying the latest
+    # data from work, running the provided result customization function,
+    # and reshaping the data to the original shapes.
+    res = res.copy()
+    _update_active(work, res, res_work_pairs, active, None, preserve_shape, xp)
+
+    shape = customize_result(res, shape)
+
+    for key, val in res.items():
+        # this looks like it won't work for xp != np if val is not numeric
+        temp = xp.reshape(val, shape)
+        res[key] = temp[()] if temp.ndim == 0 else temp
+
+    res['_order_keys'] = ['success'] + [i for i, j in res_work_pairs]
+    return _RichResult(**res)
diff --git a/.venv/lib/python3.12/site-packages/scipy/_lib/_fpumode.cpython-312-x86_64-linux-gnu.so b/.venv/lib/python3.12/site-packages/scipy/_lib/_fpumode.cpython-312-x86_64-linux-gnu.so
new file mode 100644
index 0000000000000000000000000000000000000000..778702c99bd0efa8477f1d23040b9aa01936f533
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/scipy/_lib/_fpumode.cpython-312-x86_64-linux-gnu.so differ
diff --git a/.venv/lib/python3.12/site-packages/scipy/_lib/_gcutils.py b/.venv/lib/python3.12/site-packages/scipy/_lib/_gcutils.py
new file mode 100644
index 0000000000000000000000000000000000000000..8bd3b7ce7b1da64157013302bf149cf214d98e31
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/_lib/_gcutils.py
@@ -0,0 +1,96 @@
+"""
+Module for testing automatic garbage collection of objects
+
+.. autosummary::
+   :toctree: generated/
+
+   set_gc_state - enable or disable garbage collection
+   gc_state - context manager for given state of garbage collector
+   assert_deallocated - context manager to check for circular references on object
+
+"""
+import weakref
+import gc
+
+from contextlib import contextmanager
+
+__all__ = ['set_gc_state', 'gc_state', 'assert_deallocated']
+
+
+class ReferenceError(AssertionError):
+    pass
+
+
+def set_gc_state(state):
+    """ Set status of garbage collector """
+    if gc.isenabled() == state:
+        return
+    if state:
+        gc.enable()
+    else:
+        gc.disable()
+
+
+@contextmanager
+def gc_state(state):
+    """ Context manager to set state of garbage collector to `state`
+
+    Parameters
+    ----------
+    state : bool
+        True for gc enabled, False for disabled
+
+    Examples
+    --------
+    >>> with gc_state(False):
+    ...     assert not gc.isenabled()
+    >>> with gc_state(True):
+    ...     assert gc.isenabled()
+    """
+    orig_state = gc.isenabled()
+    set_gc_state(state)
+    yield
+    set_gc_state(orig_state)
+
+
+@contextmanager
+def assert_deallocated(func, *args, **kwargs):
+    """Context manager to check that object is deallocated
+
+    This is useful for checking that an object can be freed directly by
+    reference counting, without requiring gc to break reference cycles.
+    GC is disabled inside the context manager.
+
+    Parameters
+    ----------
+    func : callable
+        Callable to create object to check
+    \\*args : sequence
+        positional arguments to `func` in order to create object to check
+    \\*\\*kwargs : dict
+        keyword arguments to `func` in order to create object to check
+
+    Examples
+    --------
+    >>> class C: pass
+    >>> with assert_deallocated(C) as c:
+    ...     # do something
+    ...     del c
+
+    >>> class C:
+    ...     def __init__(self):
+    ...         self._circular = self # Make circular reference
+    >>> with assert_deallocated(C) as c: #doctest: +IGNORE_EXCEPTION_DETAIL
+    ...     # do something
+    ...     del c
+    Traceback (most recent call last):
+        ...
+    ReferenceError: Remaining reference(s) to object
+    """
+    with gc_state(False):
+        obj = func(*args, **kwargs)
+        ref = weakref.ref(obj)
+        yield obj
+        del obj
+        if ref() is not None:
+            raise ReferenceError("Remaining reference(s) to object")
diff --git a/.venv/lib/python3.12/site-packages/scipy/_lib/_public_api.py b/.venv/lib/python3.12/site-packages/scipy/_lib/_public_api.py
new file mode 100644
index 0000000000000000000000000000000000000000..53dd3b7e73bc8e68834cd9b4f27d4d9e2a2d5b18
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/_lib/_public_api.py
@@ -0,0 +1,64 @@
+"""PUBLIC_MODULES was once included in scipy._lib.tests.test_public_api.
+
+It has been separated into this file so that this list of public modules
+could be used when generating tables showing support for alternative
+array API backends across modules in
+scipy/doc/source/array_api_capabilities.py.
+"""
+
+# Historically SciPy has not used leading underscores for private submodules
+# much.  This has resulted in lots of things that look like public modules
+# (i.e. things that can be imported as `import scipy.somesubmodule.somefile`),
+# but were never intended to be public.  The PUBLIC_MODULES list contains
+import pathlib
+
+# modules that are either public because they were meant to be, or because they
+# contain public functions/objects that aren't present in any other namespace
+# for whatever reason and therefore should be treated as public.
+PUBLIC_MODULES = ["scipy." + s for s in [
+    "cluster",
+    "cluster.vq",
+    "cluster.hierarchy",
+    "constants",
+    "datasets",
+    "differentiate",
+    "fft",
+    "fftpack",
+    "integrate",
+    "interpolate",
+    "io",
+    "io.arff",
+    "io.matlab",
+    "io.wavfile",
+    "linalg",
+    "linalg.blas",
+    "linalg.cython_blas",
+    "linalg.lapack",
+    "linalg.cython_lapack",
+    "linalg.interpolative",
+    "ndimage",
+    "odr",
+    "optimize",
+    "optimize.elementwise",
+    "signal",
+    "signal.windows",
+    "sparse",
+    "sparse.linalg",
+    "sparse.csgraph",
+    "spatial",
+    "spatial.distance",
+    "spatial.transform",
+    "special",
+    "stats",
+    "stats.contingency",
+    "stats.distributions",
+    "stats.mstats",
+    "stats.qmc",
+    "stats.sampling"
+]]
+
+# Handle the `_without-fortran` build option
+_without_fortran = False
+if not (pathlib.Path(__file__).parent.parent / 'odr').is_dir():
+    _without_fortran = True
+    PUBLIC_MODULES.remove('scipy.odr')
diff --git a/.venv/lib/python3.12/site-packages/scipy/_lib/_sparse.py b/.venv/lib/python3.12/site-packages/scipy/_lib/_sparse.py
new file mode 100644
index 0000000000000000000000000000000000000000..b7ce9a4d73b633784ea12696d290de609fed6d92
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/_lib/_sparse.py
@@ -0,0 +1,42 @@
+from abc import ABC
+
+__all__ = ["SparseABC", "issparse"]
+
+
+class SparseABC(ABC):
+    pass
+
+
+def issparse(x):
+    """Is `x` either sparse array or sparse matrix type?
+
+    Parameters
+    ----------
+    x : object
+        object to check for being a sparse array or a sparse matrix
+
+    Returns
+    -------
+    bool
+        True if `x` is a sparse array or a sparse matrix, False otherwise
+
+    Notes
+    -----
+    Use `sp.sparse.isspmatrix(x)` or `isinstance(x, sp.sparse.sparray)` to
+    check between sparray or spmatrix.
+    Use `a.format` to check the sparse format, e.g. `a.format == 'csr'`.
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy.sparse import csr_array, csr_matrix, issparse
+    >>> issparse(csr_matrix([[5]]))
+    True
+    >>> issparse(csr_array([[5]]))
+    True
+    >>> issparse(np.array([[5]]))
+    False
+    >>> issparse(5)
+    False
+    """  # numpydoc ignore=SS03
+    return isinstance(x, SparseABC)
diff --git a/.venv/lib/python3.12/site-packages/scipy/_lib/_test_ccallback.cpython-312-x86_64-linux-gnu.so b/.venv/lib/python3.12/site-packages/scipy/_lib/_test_ccallback.cpython-312-x86_64-linux-gnu.so
new file mode 100644
index 0000000000000000000000000000000000000000..5af1125741b633c095b37df465a6114f2eb607cc
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/scipy/_lib/_test_ccallback.cpython-312-x86_64-linux-gnu.so differ
diff --git a/.venv/lib/python3.12/site-packages/scipy/_lib/_test_deprecation_call.cpython-312-x86_64-linux-gnu.so b/.venv/lib/python3.12/site-packages/scipy/_lib/_test_deprecation_call.cpython-312-x86_64-linux-gnu.so
new file mode 100644
index 0000000000000000000000000000000000000000..020547c54751b074d1b305919f5c020cbb7b695c
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/scipy/_lib/_test_deprecation_call.cpython-312-x86_64-linux-gnu.so differ
diff --git a/.venv/lib/python3.12/site-packages/scipy/_lib/_test_deprecation_def.cpython-312-x86_64-linux-gnu.so b/.venv/lib/python3.12/site-packages/scipy/_lib/_test_deprecation_def.cpython-312-x86_64-linux-gnu.so
new file mode 100644
index 0000000000000000000000000000000000000000..5aed9ee009447eec55ad34205ff8fe5cc833158d
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/scipy/_lib/_test_deprecation_def.cpython-312-x86_64-linux-gnu.so differ
diff --git a/.venv/lib/python3.12/site-packages/scipy/_lib/_testutils.py b/.venv/lib/python3.12/site-packages/scipy/_lib/_testutils.py
new file mode 100644
index 0000000000000000000000000000000000000000..613e0b9e8ae013f589ca3d22eb2a2dd9921d1e6c
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/_lib/_testutils.py
@@ -0,0 +1,376 @@
+"""
+Generic test utilities.
+
+"""
+
+import inspect
+import os
+import re
+import shutil
+import subprocess
+import sys
+import sysconfig
+import threading
+from concurrent.futures import ThreadPoolExecutor
+from importlib.util import module_from_spec, spec_from_file_location
+
+import numpy as np
+import scipy
+
+try:
+    # Need type: ignore[import-untyped] for mypy >= 1.6
+    import cython  # type: ignore[import-untyped]
+    from Cython.Compiler.Version import (  # type: ignore[import-untyped]
+        version as cython_version,
+    )
+except ImportError:
+    cython = None
+else:
+    from scipy._external.packaging_version import version
+    required_version = '3.2.0'
+    if version.parse(cython_version) < version.Version(required_version):
+        # too old or wrong cython, skip Cython API tests
+        cython = None
+
+
+__all__ = ['PytestTester', 'check_free_memory', '_TestPythranFunc', 'IS_MUSL']
+
+
+IS_MUSL = False
+# alternate way is
+# from packaging.tags import sys_tags
+#     _tags = list(sys_tags())
+#     if 'musllinux' in _tags[0].platform:
+_v = sysconfig.get_config_var('HOST_GNU_TYPE') or ''
+if 'musl' in _v:
+    IS_MUSL = True
+
+
+IS_EDITABLE = 'editable' in scipy.__path__[0]
+
+
+class FPUModeChangeWarning(RuntimeWarning):
+    """Warning about FPU mode change"""
+    pass
+
+
+class PytestTester:
+    """
+    Run tests for this namespace
+
+    ``scipy.test()`` runs tests for all of SciPy, with the default settings.
+    When used from a submodule (e.g., ``scipy.cluster.test()``, only the tests
+    for that namespace are run.
+
+    Parameters
+    ----------
+    label : {'fast', 'full'}, optional
+        Whether to run only the fast tests, or also those marked as slow.
+        Default is 'fast'.
+    verbose : int, optional
+        Test output verbosity. Default is 1.
+    extra_argv : list, optional
+        Arguments to pass through to Pytest.
+    doctests : bool, optional
+        Whether to run doctests or not. Default is False.
+    coverage : bool, optional
+        Whether to run tests with code coverage measurements enabled.
+        Default is False.
+    tests : list of str, optional
+        List of module names to run tests for. By default, uses the module
+        from which the ``test`` function is called.
+    parallel : int, optional
+        Run tests in parallel with pytest-xdist, if number given is larger than
+        1. Default is 1.
+
+    """
+    def __init__(self, module_name):
+        self.module_name = module_name
+
+    def __call__(self, label="fast", verbose=1, extra_argv=None, doctests=False,
+                 coverage=False, tests=None, parallel=None):
+        import pytest
+
+        module = sys.modules[self.module_name]
+        module_path = os.path.abspath(module.__path__[0])
+
+        pytest_args = ['--showlocals', '--tb=short']
+
+        if extra_argv is None:
+            extra_argv = []
+        pytest_args += extra_argv
+        if any(arg == "-m" or arg == "--markers" for arg in extra_argv):
+            # Likely conflict with default --mode=fast
+            raise ValueError("Must specify -m before --")
+
+        if verbose and int(verbose) > 1:
+            pytest_args += ["-" + "v"*(int(verbose)-1)]
+
+        if coverage:
+            pytest_args += ["--cov=" + module_path]
+
+        if label == "fast":
+            pytest_args += ["-m", "not slow"]
+        elif label != "full":
+            pytest_args += ["-m", label]
+
+        if tests is None:
+            tests = [self.module_name]
+
+        if parallel is not None and parallel > 1:
+            if _pytest_has_xdist():
+                pytest_args += ['-n', str(parallel)]
+            else:
+                import warnings
+                warnings.warn('Could not run tests in parallel because '
+                              'pytest-xdist plugin is not available.',
+                              stacklevel=2)
+
+        pytest_args += ['--pyargs'] + list(tests)
+
+        try:
+            code = pytest.main(pytest_args)
+        except SystemExit as exc:
+            code = exc.code
+
+        return (code == 0)
+
+
+class _TestPythranFunc:
+    '''
+    These are situations that can be tested in our pythran tests:
+    - A function with multiple array arguments and then
+      other positional and keyword arguments.
+    - A function with array-like keywords (e.g. `def somefunc(x0, x1=None)`.
+    Note: list/tuple input is not yet tested!
+
+    `self.arguments`: A dictionary which key is the index of the argument,
+                      value is tuple(array value, all supported dtypes)
+    `self.partialfunc`: A function used to freeze some non-array argument
+                        that of no interests in the original function
+    '''
+    ALL_INTEGER = [np.int8, np.int16, np.int32, np.int64, np.intc, np.intp]
+    ALL_FLOAT = [np.float32, np.float64]
+    ALL_COMPLEX = [np.complex64, np.complex128]
+
+    def setup_method(self):
+        self.arguments = {}
+        self.partialfunc = None
+        self.expected = None
+
+    def get_optional_args(self, func):
+        # get optional arguments with its default value,
+        # used for testing keywords
+        signature = inspect.signature(func)
+        optional_args = {}
+        for k, v in signature.parameters.items():
+            if v.default is not inspect.Parameter.empty:
+                optional_args[k] = v.default
+        return optional_args
+
+    def get_max_dtype_list_length(self):
+        # get the max supported dtypes list length in all arguments
+        max_len = 0
+        for arg_idx in self.arguments:
+            cur_len = len(self.arguments[arg_idx][1])
+            if cur_len > max_len:
+                max_len = cur_len
+        return max_len
+
+    def get_dtype(self, dtype_list, dtype_idx):
+        # get the dtype from dtype_list via index
+        # if the index is out of range, then return the last dtype
+        if dtype_idx > len(dtype_list)-1:
+            return dtype_list[-1]
+        else:
+            return dtype_list[dtype_idx]
+
+    def test_all_dtypes(self):
+        for type_idx in range(self.get_max_dtype_list_length()):
+            args_array = []
+            for arg_idx in self.arguments:
+                new_dtype = self.get_dtype(self.arguments[arg_idx][1],
+                                           type_idx)
+                args_array.append(self.arguments[arg_idx][0].astype(new_dtype))
+            self.pythranfunc(*args_array)
+
+    def test_views(self):
+        args_array = []
+        for arg_idx in self.arguments:
+            args_array.append(self.arguments[arg_idx][0][::-1][::-1])
+        self.pythranfunc(*args_array)
+
+    def test_strided(self):
+        args_array = []
+        for arg_idx in self.arguments:
+            args_array.append(np.repeat(self.arguments[arg_idx][0],
+                                        2, axis=0)[::2])
+        self.pythranfunc(*args_array)
+
+
+def _pytest_has_xdist():
+    """
+    Check if the pytest-xdist plugin is installed, providing parallel tests
+    """
+    # Check xdist exists without importing, otherwise pytests emits warnings
+    from importlib.util import find_spec
+    return find_spec('xdist') is not None
+
+
+def check_free_memory(free_mb):
+    """
+    Check *free_mb* of memory is available, otherwise do pytest.skip
+    """
+    import pytest
+
+    try:
+        mem_free = _parse_size(os.environ['SCIPY_AVAILABLE_MEM'])
+        msg = '{} MB memory required, but environment SCIPY_AVAILABLE_MEM={}'.format(
+            free_mb, os.environ['SCIPY_AVAILABLE_MEM'])
+    except KeyError:
+        mem_free = _get_mem_available()
+        if mem_free is None:
+            pytest.skip("Could not determine available memory; set SCIPY_AVAILABLE_MEM "
+                        "variable to free memory in MB to run the test.")
+        msg = f'{free_mb} MB memory required, but {mem_free/1e6} MB available'
+
+    if mem_free < free_mb * 1e6:
+        pytest.skip(msg)
+
+
+def _parse_size(size_str):
+    suffixes = {'': 1e6,
+                'b': 1.0,
+                'k': 1e3, 'M': 1e6, 'G': 1e9, 'T': 1e12,
+                'kb': 1e3, 'Mb': 1e6, 'Gb': 1e9, 'Tb': 1e12,
+                'kib': 1024.0, 'Mib': 1024.0**2, 'Gib': 1024.0**3, 'Tib': 1024.0**4}
+    m = re.match(r'^\s*(\d+)\s*({})\s*$'.format('|'.join(suffixes.keys())),
+                 size_str,
+                 re.I)
+    if not m or m.group(2) not in suffixes:
+        raise ValueError("Invalid size string")
+
+    return float(m.group(1)) * suffixes[m.group(2)]
+
+
+def _get_mem_available():
+    """
+    Get information about memory available, not counting swap.
+    """
+    try:
+        import psutil
+        return psutil.virtual_memory().available
+    except (ImportError, AttributeError):
+        pass
+
+    if sys.platform.startswith('linux'):
+        info = {}
+        with open('/proc/meminfo') as f:
+            for line in f:
+                p = line.split()
+                info[p[0].strip(':').lower()] = float(p[1]) * 1e3
+
+        if 'memavailable' in info:
+            # Linux >= 3.14
+            return info['memavailable']
+        else:
+            return info['memfree'] + info['cached']
+
+    return None
+
+def _test_cython_extension(tmp_path, srcdir):
+    """
+    Helper function to test building and importing Cython modules that
+    make use of the Cython APIs for BLAS, LAPACK, optimize, and special.
+    """
+    import pytest
+    try:
+        subprocess.check_call(["meson", "--version"])
+    except FileNotFoundError:
+        pytest.skip("No usable 'meson' found")
+
+    # Make safe for being called by multiple threads within one test
+    tmp_path = tmp_path / str(threading.get_ident())
+
+    # build the examples in a temporary directory
+    mod_name = os.path.split(srcdir)[1]
+    shutil.copytree(srcdir, tmp_path / mod_name)
+    build_dir = tmp_path / mod_name / 'tests' / '_cython_examples'
+    target_dir = build_dir / 'build'
+    os.makedirs(target_dir, exist_ok=True)
+
+    # Ensure we use the correct Python interpreter even when `meson` is
+    # installed in a different Python environment (see numpy#24956)
+    native_file = str(build_dir / 'interpreter-native-file.ini')
+    with open(native_file, 'w') as f:
+        f.write("[binaries]\n")
+        f.write(f"python = '{sys.executable}'")
+
+    if sys.platform == "win32":
+        subprocess.check_call(["meson", "setup",
+                               "--buildtype=release",
+                               "--native-file", native_file,
+                               "--vsenv", str(build_dir)],
+                              cwd=target_dir,
+                              )
+    else:
+        subprocess.check_call(["meson", "setup",
+                               "--native-file", native_file, str(build_dir)],
+                              cwd=target_dir
+                              )
+    subprocess.check_call(["meson", "compile", "-vv"], cwd=target_dir)
+
+    # import without adding the directory to sys.path
+    suffix = sysconfig.get_config_var('EXT_SUFFIX')
+
+    def load(modname):
+        so = (target_dir / modname).with_suffix(suffix)
+        spec = spec_from_file_location(modname, so)
+        mod = module_from_spec(spec)
+        spec.loader.exec_module(mod)
+        return mod
+
+    # test that the module can be imported
+    return load("extending"), load("extending_cpp")
+
+
+def _run_concurrent_barrier(n_workers, fn, *args, **kwargs):
+    """
+    Run a given function concurrently across a given number of threads.
+
+    This function ensures that the closure passed by parameter gets called
+    concurrently by setting up a barrier before it gets called before any of the
+    threads.
+
+    Returns a list of values returned by the worker threads.
+
+    Arguments
+    ---------
+    n_workers: int
+        Number of concurrent threads to spawn.
+    fn: callable
+        Function closure to execute concurrently. Its first argument will
+        be the thread id.
+    *args: tuple
+        Variable number of positional arguments to pass to the function.
+    **kwargs: dict
+        Keyword arguments to pass to the function.
+
+    """
+    barrier = threading.Barrier(n_workers)
+
+    def closure(i, *args, **kwargs):
+        barrier.wait()
+        return fn(i, *args, **kwargs)
+
+    with ThreadPoolExecutor(max_workers=n_workers) as tpe:
+        try:
+            futures = []
+            for i in range(0, n_workers):
+                futures.append(tpe.submit(closure, i, *args, **kwargs))
+        finally:
+            if len(futures) < n_workers:
+                # to avoid deadlocks if spawning failed for some reason
+                barrier.abort()
+
+    return [f.result() for f in futures]
diff --git a/.venv/lib/python3.12/site-packages/scipy/_lib/_uarray/LICENSE b/.venv/lib/python3.12/site-packages/scipy/_lib/_uarray/LICENSE
new file mode 100644
index 0000000000000000000000000000000000000000..5f2b90a026aaecbdc090b3d3234954ab29fce8ae
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/_lib/_uarray/LICENSE
@@ -0,0 +1,29 @@
+BSD 3-Clause License
+
+Copyright (c) 2018, Quansight-Labs
+All rights reserved.
+
+Redistribution and use in source and binary forms, with or without
+modification, are permitted provided that the following conditions are met:
+
+* Redistributions of source code must retain the above copyright notice, this
+  list of conditions and the following disclaimer.
+
+* Redistributions in binary form must reproduce the above copyright notice,
+  this list of conditions and the following disclaimer in the documentation
+  and/or other materials provided with the distribution.
+
+* Neither the name of the copyright holder nor the names of its
+  contributors may be used to endorse or promote products derived from
+  this software without specific prior written permission.
+
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
+FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
+CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
+OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
diff --git a/.venv/lib/python3.12/site-packages/scipy/_lib/_uarray/__init__.py b/.venv/lib/python3.12/site-packages/scipy/_lib/_uarray/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..91afdcedb180599a41758cdd8c03416cf6c20d76
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/_lib/_uarray/__init__.py
@@ -0,0 +1,116 @@
+"""
+.. note:
+    If you are looking for overrides for NumPy-specific methods, see the
+    documentation for :obj:`unumpy`. This page explains how to write
+    back-ends and multimethods.
+
+``uarray`` is built around a back-end protocol, and overridable multimethods.
+It is necessary to define multimethods for back-ends to be able to override them.
+See the documentation of :obj:`generate_multimethod` on how to write multimethods.
+
+
+
+Let's start with the simplest:
+
+``__ua_domain__`` defines the back-end *domain*. The domain consists of period-
+separated string consisting of the modules you extend plus the submodule. For
+example, if a submodule ``module2.submodule`` extends ``module1``
+(i.e., it exposes dispatchables marked as types available in ``module1``),
+then the domain string should be ``"module1.module2.submodule"``.
+
+
+For the purpose of this demonstration, we'll be creating an object and setting
+its attributes directly. However, note that you can use a module or your own type
+as a backend as well.
+
+>>> class Backend: pass
+>>> be = Backend()
+>>> be.__ua_domain__ = "ua_examples"
+
+It might be useful at this point to sidetrack to the documentation of
+:obj:`generate_multimethod` to find out how to generate a multimethod
+overridable by :obj:`uarray`. Needless to say, writing a backend and
+creating multimethods are mostly orthogonal activities, and knowing
+one doesn't necessarily require knowledge of the other, although it
+is certainly helpful. We expect core API designers/specifiers to write the
+multimethods, and implementors to override them. But, as is often the case,
+similar people write both.
+
+Without further ado, here's an example multimethod:
+
+>>> import uarray as ua
+>>> from uarray import Dispatchable
+>>> def override_me(a, b):
+...   return Dispatchable(a, int),
+>>> def override_replacer(args, kwargs, dispatchables):
+...     return (dispatchables[0], args[1]), {}
+>>> overridden_me = ua.generate_multimethod(
+...     override_me, override_replacer, "ua_examples"
+... )
+
+Next comes the part about overriding the multimethod. This requires
+the ``__ua_function__`` protocol, and the ``__ua_convert__``
+protocol. The ``__ua_function__`` protocol has the signature
+``(method, args, kwargs)`` where ``method`` is the passed
+multimethod, ``args``/``kwargs`` specify the arguments and ``dispatchables``
+is the list of converted dispatchables passed in.
+
+>>> def __ua_function__(method, args, kwargs):
+...     return method.__name__, args, kwargs
+>>> be.__ua_function__ = __ua_function__
+
+The other protocol of interest is the ``__ua_convert__`` protocol. It has the
+signature ``(dispatchables, coerce)``. When ``coerce`` is ``False``, conversion
+between the formats should ideally be an ``O(1)`` operation, but it means that
+no memory copying should be involved, only views of the existing data.
+
+>>> def __ua_convert__(dispatchables, coerce):
+...     for d in dispatchables:
+...         if d.type is int:
+...             if coerce and d.coercible:
+...                 yield str(d.value)
+...             else:
+...                 yield d.value
+>>> be.__ua_convert__ = __ua_convert__
+
+Now that we have defined the backend, the next thing to do is to call the multimethod.
+
+>>> with ua.set_backend(be):
+...      overridden_me(1, "2")
+('override_me', (1, '2'), {})
+
+Note that the marked type has no effect on the actual type of the passed object.
+We can also coerce the type of the input.
+
+>>> with ua.set_backend(be, coerce=True):
+...     overridden_me(1, "2")
+...     overridden_me(1.0, "2")
+('override_me', ('1', '2'), {})
+('override_me', ('1.0', '2'), {})
+
+Another feature is that if you remove ``__ua_convert__``, the arguments are not
+converted at all and it's up to the backend to handle that.
+
+>>> del be.__ua_convert__
+>>> with ua.set_backend(be):
+...     overridden_me(1, "2")
+('override_me', (1, '2'), {})
+
+You also have the option to return ``NotImplemented``, in which case processing moves on
+to the next back-end, which in this case, doesn't exist. The same applies to
+``__ua_convert__``.
+
+>>> be.__ua_function__ = lambda *a, **kw: NotImplemented
+>>> with ua.set_backend(be):
+...     overridden_me(1, "2")
+Traceback (most recent call last):
+    ...
+uarray.BackendNotImplementedError: ...
+
+The last possibility is if we don't have ``__ua_convert__``, in which case the job is
+left up to ``__ua_function__``, but putting things back into arrays after conversion
+will not be possible.
+"""
+
+from ._backend import *
+__version__ = '0.8.8.dev0+aa94c5a4.scipy'
diff --git a/.venv/lib/python3.12/site-packages/scipy/_lib/_uarray/__pycache__/__init__.cpython-312.pyc b/.venv/lib/python3.12/site-packages/scipy/_lib/_uarray/__pycache__/__init__.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..d57d3fb090bc5ab568cf08a4a724927bebf8ee6e
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/scipy/_lib/_uarray/__pycache__/__init__.cpython-312.pyc differ
diff --git a/.venv/lib/python3.12/site-packages/scipy/_lib/_uarray/__pycache__/_backend.cpython-312.pyc b/.venv/lib/python3.12/site-packages/scipy/_lib/_uarray/__pycache__/_backend.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..408eb7aa4edafe56aa124522d07dcad6678f6e9c
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/scipy/_lib/_uarray/__pycache__/_backend.cpython-312.pyc differ
diff --git a/.venv/lib/python3.12/site-packages/scipy/_lib/_uarray/_backend.py b/.venv/lib/python3.12/site-packages/scipy/_lib/_uarray/_backend.py
new file mode 100644
index 0000000000000000000000000000000000000000..87ea71965761ca6916485828ee23d3402bfb1b7d
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/_lib/_uarray/_backend.py
@@ -0,0 +1,707 @@
+import typing
+import types
+import inspect
+import functools
+from . import _uarray
+import copyreg
+import pickle
+import contextlib
+import threading
+
+from ._uarray import (  # type: ignore
+    BackendNotImplementedError,
+    _Function,
+    _SkipBackendContext,
+    _SetBackendContext,
+    _BackendState,
+)
+
+__all__ = [
+    "set_backend",
+    "set_global_backend",
+    "skip_backend",
+    "register_backend",
+    "determine_backend",
+    "determine_backend_multi",
+    "clear_backends",
+    "create_multimethod",
+    "generate_multimethod",
+    "_Function",
+    "BackendNotImplementedError",
+    "Dispatchable",
+    "wrap_single_convertor",
+    "wrap_single_convertor_instance",
+    "all_of_type",
+    "mark_as",
+    "set_state",
+    "get_state",
+    "reset_state",
+    "_BackendState",
+    "_SkipBackendContext",
+    "_SetBackendContext",
+]
+
+ArgumentExtractorType = typing.Callable[..., tuple["Dispatchable", ...]]
+ArgumentReplacerType = typing.Callable[
+    [tuple, dict, tuple], tuple[tuple, dict]
+]
+
+def unpickle_function(mod_name, qname, self_):
+    import importlib
+
+    try:
+        module = importlib.import_module(mod_name)
+        qname = qname.split(".")
+        func = module
+        for q in qname:
+            func = getattr(func, q)
+
+        if self_ is not None:
+            func = types.MethodType(func, self_)
+
+        return func
+    except (ImportError, AttributeError) as e:
+        from pickle import UnpicklingError
+
+        raise UnpicklingError from e
+
+
+def pickle_function(func):
+    mod_name = getattr(func, "__module__", None)
+    qname = getattr(func, "__qualname__", None)
+    self_ = getattr(func, "__self__", None)
+
+    try:
+        test = unpickle_function(mod_name, qname, self_)
+    except pickle.UnpicklingError:
+        test = None
+
+    if test is not func:
+        raise pickle.PicklingError(
+            f"Can't pickle {func}: it's not the same object as {test}"
+        )
+
+    return unpickle_function, (mod_name, qname, self_)
+
+
+def pickle_state(state):
+    return _uarray._BackendState._unpickle, state._pickle()
+
+
+def pickle_set_backend_context(ctx):
+    return _SetBackendContext, ctx._pickle()
+
+
+def pickle_skip_backend_context(ctx):
+    return _SkipBackendContext, ctx._pickle()
+
+
+copyreg.pickle(_Function, pickle_function)
+copyreg.pickle(_uarray._BackendState, pickle_state)
+copyreg.pickle(_SetBackendContext, pickle_set_backend_context)
+copyreg.pickle(_SkipBackendContext, pickle_skip_backend_context)
+
+
+def get_state():
+    """
+    Returns an opaque object containing the current state of all the backends.
+
+    Can be used for synchronization between threads/processes.
+
+    See Also
+    --------
+    set_state
+        Sets the state returned by this function.
+    """
+    return _uarray.get_state()
+
+
+@contextlib.contextmanager
+def reset_state():
+    """
+    Returns a context manager that resets all state once exited.
+
+    See Also
+    --------
+    set_state
+        Context manager that sets the backend state.
+    get_state
+        Gets a state to be set by this context manager.
+    """
+    with set_state(get_state()):
+        yield
+
+
+@contextlib.contextmanager
+def set_state(state):
+    """
+    A context manager that sets the state of the backends to one returned by :obj:`get_state`.
+
+    See Also
+    --------
+    get_state
+        Gets a state to be set by this context manager.
+    """  # noqa: E501
+    old_state = get_state()
+    _uarray.set_state(state)
+    try:
+        yield
+    finally:
+        _uarray.set_state(old_state, True)
+
+
+def create_multimethod(*args, **kwargs):
+    """
+    Creates a decorator for generating multimethods.
+
+    This function creates a decorator that can be used with an argument
+    extractor in order to generate a multimethod. Other than for the
+    argument extractor, all arguments are passed on to
+    :obj:`generate_multimethod`.
+
+    See Also
+    --------
+    generate_multimethod
+        Generates a multimethod.
+    """
+
+    def wrapper(a):
+        return generate_multimethod(a, *args, **kwargs)
+
+    return wrapper
+
+
+def generate_multimethod(
+    argument_extractor: ArgumentExtractorType,
+    argument_replacer: ArgumentReplacerType,
+    domain: str,
+    default: typing.Callable | None = None,
+):
+    """
+    Generates a multimethod.
+
+    Parameters
+    ----------
+    argument_extractor : ArgumentExtractorType
+        A callable which extracts the dispatchable arguments. Extracted arguments
+        should be marked by the :obj:`Dispatchable` class. It has the same signature
+        as the desired multimethod.
+    argument_replacer : ArgumentReplacerType
+        A callable with the signature (args, kwargs, dispatchables), which should also
+        return an (args, kwargs) pair with the dispatchables replaced inside the
+        args/kwargs.
+    domain : str
+        A string value indicating the domain of this multimethod.
+    default: Optional[Callable], optional
+        The default implementation of this multimethod, where ``None`` (the default)
+        specifies there is no default implementation.
+
+    Examples
+    --------
+    In this example, ``a`` is to be dispatched over, so we return it, while marking it
+    as an ``int``.
+    The trailing comma is needed because the args have to be returned as an iterable.
+
+    >>> def override_me(a, b):
+    ...   return Dispatchable(a, int),
+
+    Next, we define the argument replacer that replaces the dispatchables inside
+    args/kwargs with the supplied ones.
+
+    >>> def override_replacer(args, kwargs, dispatchables):
+    ...     return (dispatchables[0], args[1]), {}
+
+    Next, we define the multimethod.
+
+    >>> overridden_me = generate_multimethod(
+    ...     override_me, override_replacer, "ua_examples"
+    ... )
+
+    Notice that there's no default implementation, unless you supply one.
+
+    >>> overridden_me(1, "a")
+    Traceback (most recent call last):
+        ...
+    uarray.BackendNotImplementedError: ...
+
+    >>> overridden_me2 = generate_multimethod(
+    ...     override_me, override_replacer, "ua_examples", default=lambda x, y: (x, y)
+    ... )
+    >>> overridden_me2(1, "a")
+    (1, 'a')
+
+    See Also
+    --------
+    uarray
+        See the module documentation for how to override the method by creating
+        backends.
+    """
+    kw_defaults, arg_defaults, opts = get_defaults(argument_extractor)
+    ua_func = _Function(
+        argument_extractor,
+        argument_replacer,
+        domain,
+        arg_defaults,
+        kw_defaults,
+        default,
+    )
+
+    return functools.update_wrapper(ua_func, argument_extractor)
+
+
+def set_backend(backend, coerce=False, only=False):
+    """
+    A context manager that sets the preferred backend.
+
+    Parameters
+    ----------
+    backend
+        The backend to set.
+    coerce
+        Whether or not to coerce to a specific backend's types. Implies ``only``.
+    only
+        Whether or not this should be the last backend to try.
+
+    See Also
+    --------
+    skip_backend: A context manager that allows skipping of backends.
+    set_global_backend: Set a single, global backend for a domain.
+    """
+    tid = threading.get_native_id()
+    try:
+        return backend.__ua_cache__[tid, "set", coerce, only]
+    except AttributeError:
+        backend.__ua_cache__ = {}
+    except KeyError:
+        pass
+
+    ctx = _SetBackendContext(backend, coerce, only)
+    backend.__ua_cache__[tid, "set", coerce, only] = ctx
+    return ctx
+
+
+def skip_backend(backend):
+    """
+    A context manager that allows one to skip a given backend from processing
+    entirely. This allows one to use another backend's code in a library that
+    is also a consumer of the same backend.
+
+    Parameters
+    ----------
+    backend
+        The backend to skip.
+
+    See Also
+    --------
+    set_backend: A context manager that allows setting of backends.
+    set_global_backend: Set a single, global backend for a domain.
+    """
+    tid = threading.get_native_id()
+    try:
+        return backend.__ua_cache__[tid, "skip"]
+    except AttributeError:
+        backend.__ua_cache__ = {}
+    except KeyError:
+        pass
+
+    ctx = _SkipBackendContext(backend)
+    backend.__ua_cache__[tid, "skip"] = ctx
+    return ctx
+
+
+def get_defaults(f):
+    sig = inspect.signature(f)
+    kw_defaults = {}
+    arg_defaults = []
+    opts = set()
+    for k, v in sig.parameters.items():
+        if v.default is not inspect.Parameter.empty:
+            kw_defaults[k] = v.default
+        if v.kind in (
+            inspect.Parameter.POSITIONAL_ONLY,
+            inspect.Parameter.POSITIONAL_OR_KEYWORD,
+        ):
+            arg_defaults.append(v.default)
+        opts.add(k)
+
+    return kw_defaults, tuple(arg_defaults), opts
+
+
+def set_global_backend(backend, coerce=False, only=False, *, try_last=False):
+    """
+    This utility method replaces the default backend for permanent use. It
+    will be tried in the list of backends automatically, unless the
+    ``only`` flag is set on a backend. This will be the first tried
+    backend outside the :obj:`set_backend` context manager.
+
+    Note that this method is not thread-safe.
+
+    .. warning::
+        We caution library authors against using this function in
+        their code. We do *not* support this use-case. This function
+        is meant to be used only by users themselves, or by a reference
+        implementation, if one exists.
+
+    Parameters
+    ----------
+    backend
+        The backend to register.
+    coerce : bool
+        Whether to coerce input types when trying this backend.
+    only : bool
+        If ``True``, no more backends will be tried if this fails.
+        Implied by ``coerce=True``.
+    try_last : bool
+        If ``True``, the global backend is tried after registered backends.
+
+    See Also
+    --------
+    set_backend: A context manager that allows setting of backends.
+    skip_backend: A context manager that allows skipping of backends.
+    """
+    _uarray.set_global_backend(backend, coerce, only, try_last)
+
+
+def register_backend(backend):
+    """
+    This utility method sets registers backend for permanent use. It
+    will be tried in the list of backends automatically, unless the
+    ``only`` flag is set on a backend.
+
+    Note that this method is not thread-safe.
+
+    Parameters
+    ----------
+    backend
+        The backend to register.
+    """
+    _uarray.register_backend(backend)
+
+
+def clear_backends(domain, registered=True, globals=False):
+    """
+    This utility method clears registered backends.
+
+    .. warning::
+        We caution library authors against using this function in
+        their code. We do *not* support this use-case. This function
+        is meant to be used only by users themselves.
+
+    .. warning::
+        Do NOT use this method inside a multimethod call, or the
+        program is likely to crash.
+
+    Parameters
+    ----------
+    domain : Optional[str]
+        The domain for which to de-register backends. ``None`` means
+        de-register for all domains.
+    registered : bool
+        Whether or not to clear registered backends. See :obj:`register_backend`.
+    globals : bool
+        Whether or not to clear global backends. See :obj:`set_global_backend`.
+
+    See Also
+    --------
+    register_backend : Register a backend globally.
+    set_global_backend : Set a global backend.
+    """
+    _uarray.clear_backends(domain, registered, globals)
+
+
+class Dispatchable:
+    """
+    A utility class which marks an argument with a specific dispatch type.
+
+
+    Attributes
+    ----------
+    value
+        The value of the Dispatchable.
+
+    type
+        The type of the Dispatchable.
+
+    Examples
+    --------
+    >>> x = Dispatchable(1, str)
+    >>> x
+    , value=1>
+
+    See Also
+    --------
+    all_of_type
+        Marks all unmarked parameters of a function.
+
+    mark_as
+        Allows one to create a utility function to mark as a given type.
+    """
+
+    def __init__(self, value, dispatch_type, coercible=True):
+        self.value = value
+        self.type = dispatch_type
+        self.coercible = coercible
+
+    def __getitem__(self, index):
+        return (self.type, self.value)[index]
+
+    def __str__(self):
+        return f"<{type(self).__name__}: type={self.type!r}, value={self.value!r}>"
+
+    __repr__ = __str__
+
+
+def mark_as(dispatch_type):
+    """
+    Creates a utility function to mark something as a specific type.
+
+    Examples
+    --------
+    >>> mark_int = mark_as(int)
+    >>> mark_int(1)
+    , value=1>
+    """
+    return functools.partial(Dispatchable, dispatch_type=dispatch_type)
+
+
+def all_of_type(arg_type):
+    """
+    Marks all unmarked arguments as a given type.
+
+    Examples
+    --------
+    >>> @all_of_type(str)
+    ... def f(a, b):
+    ...     return a, Dispatchable(b, int)
+    >>> f('a', 1)
+    (, value='a'>,
+     , value=1>)
+    """
+
+    def outer(func):
+        @functools.wraps(func)
+        def inner(*args, **kwargs):
+            extracted_args = func(*args, **kwargs)
+            return tuple(
+                Dispatchable(arg, arg_type)
+                if not isinstance(arg, Dispatchable)
+                else arg
+                for arg in extracted_args
+            )
+
+        return inner
+
+    return outer
+
+
+def wrap_single_convertor(convert_single):
+    """
+    Wraps a ``__ua_convert__`` defined for a single element to all elements.
+    If any of them return ``NotImplemented``, the operation is assumed to be
+    undefined.
+
+    Accepts a signature of (value, type, coerce).
+    """
+
+    @functools.wraps(convert_single)
+    def __ua_convert__(dispatchables, coerce):
+        converted = []
+        for d in dispatchables:
+            c = convert_single(d.value, d.type, coerce and d.coercible)
+
+            if c is NotImplemented:
+                return NotImplemented
+
+            converted.append(c)
+
+        return converted
+
+    return __ua_convert__
+
+
+def wrap_single_convertor_instance(convert_single):
+    """
+    Wraps a ``__ua_convert__`` defined for a single element to all elements.
+    If any of them return ``NotImplemented``, the operation is assumed to be
+    undefined.
+
+    Accepts a signature of (value, type, coerce).
+    """
+
+    @functools.wraps(convert_single)
+    def __ua_convert__(self, dispatchables, coerce):
+        converted = []
+        for d in dispatchables:
+            c = convert_single(self, d.value, d.type, coerce and d.coercible)
+
+            if c is NotImplemented:
+                return NotImplemented
+
+            converted.append(c)
+
+        return converted
+
+    return __ua_convert__
+
+
+def determine_backend(value, dispatch_type, *, domain, only=True, coerce=False):
+    """Set the backend to the first active backend that supports ``value``
+
+    This is useful for functions that call multimethods without any dispatchable
+    arguments. You can use :func:`determine_backend` to ensure the same backend
+    is used everywhere in a block of multimethod calls.
+
+    Parameters
+    ----------
+    value
+        The value being tested
+    dispatch_type
+        The dispatch type associated with ``value``, aka
+        ":ref:`marking `".
+    domain: string
+        The domain to query for backends and set.
+    coerce: bool
+        Whether or not to allow coercion to the backend's types. Implies ``only``.
+    only: bool
+        Whether or not this should be the last backend to try.
+
+    See Also
+    --------
+    set_backend: For when you know which backend to set
+
+    Notes
+    -----
+
+    Support is determined by the ``__ua_convert__`` protocol. Backends not
+    supporting the type must return ``NotImplemented`` from their
+    ``__ua_convert__`` if they don't support input of that type.
+
+    Examples
+    --------
+
+    Suppose we have two backends ``BackendA`` and ``BackendB`` each supporting
+    different types, ``TypeA`` and ``TypeB``. Neither supporting the other type:
+
+    >>> with ua.set_backend(ex.BackendA):
+    ...     ex.call_multimethod(ex.TypeB(), ex.TypeB())
+    Traceback (most recent call last):
+        ...
+    uarray.BackendNotImplementedError: ...
+
+    Now consider a multimethod that creates a new object of ``TypeA``, or
+    ``TypeB`` depending on the active backend.
+
+    >>> with ua.set_backend(ex.BackendA), ua.set_backend(ex.BackendB):
+    ...         res = ex.creation_multimethod()
+    ...         ex.call_multimethod(res, ex.TypeA())
+    Traceback (most recent call last):
+        ...
+    uarray.BackendNotImplementedError: ...
+
+    ``res`` is an object of ``TypeB`` because ``BackendB`` is set in the
+    innermost with statement. So, ``call_multimethod`` fails since the types
+    don't match.
+
+    Instead, we need to first find a backend suitable for all of our objects.
+
+    >>> with ua.set_backend(ex.BackendA), ua.set_backend(ex.BackendB):
+    ...     x = ex.TypeA()
+    ...     with ua.determine_backend(x, "mark", domain="ua_examples"):
+    ...         res = ex.creation_multimethod()
+    ...         ex.call_multimethod(res, x)
+    TypeA
+
+    """
+    dispatchables = (Dispatchable(value, dispatch_type, coerce),)
+    backend = _uarray.determine_backend(domain, dispatchables, coerce)
+
+    return set_backend(backend, coerce=coerce, only=only)
+
+
+def determine_backend_multi(
+    dispatchables, *, domain, only=True, coerce=False, **kwargs
+):
+    """Set a backend supporting all ``dispatchables``
+
+    This is useful for functions that call multimethods without any dispatchable
+    arguments. You can use :func:`determine_backend_multi` to ensure the same
+    backend is used everywhere in a block of multimethod calls involving
+    multiple arrays.
+
+    Parameters
+    ----------
+    dispatchables: Sequence[Union[uarray.Dispatchable, Any]]
+        The dispatchables that must be supported
+    domain: string
+        The domain to query for backends and set.
+    coerce: bool
+        Whether or not to allow coercion to the backend's types. Implies ``only``.
+    only: bool
+        Whether or not this should be the last backend to try.
+    dispatch_type: Optional[Any]
+        The default dispatch type associated with ``dispatchables``, aka
+        ":ref:`marking `".
+
+    See Also
+    --------
+    determine_backend: For a single dispatch value
+    set_backend: For when you know which backend to set
+
+    Notes
+    -----
+
+    Support is determined by the ``__ua_convert__`` protocol. Backends not
+    supporting the type must return ``NotImplemented`` from their
+    ``__ua_convert__`` if they don't support input of that type.
+
+    Examples
+    --------
+
+    :func:`determine_backend` allows the backend to be set from a single
+    object. :func:`determine_backend_multi` allows multiple objects to be
+    checked simultaneously for support in the backend. Suppose we have a
+    ``BackendAB`` which supports ``TypeA`` and ``TypeB`` in the same call,
+    and a ``BackendBC`` that doesn't support ``TypeA``.
+
+    >>> with ua.set_backend(ex.BackendAB), ua.set_backend(ex.BackendBC):
+    ...     a, b = ex.TypeA(), ex.TypeB()
+    ...     with ua.determine_backend_multi(
+    ...         [ua.Dispatchable(a, "mark"), ua.Dispatchable(b, "mark")],
+    ...         domain="ua_examples"
+    ...     ):
+    ...         res = ex.creation_multimethod()
+    ...         ex.call_multimethod(res, a, b)
+    TypeA
+
+    This won't call ``BackendBC`` because it doesn't support ``TypeA``.
+
+    We can also use leave out the ``ua.Dispatchable`` if we specify the
+    default ``dispatch_type`` for the ``dispatchables`` argument.
+
+    >>> with ua.set_backend(ex.BackendAB), ua.set_backend(ex.BackendBC):
+    ...     a, b = ex.TypeA(), ex.TypeB()
+    ...     with ua.determine_backend_multi(
+    ...         [a, b], dispatch_type="mark", domain="ua_examples"
+    ...     ):
+    ...         res = ex.creation_multimethod()
+    ...         ex.call_multimethod(res, a, b)
+    TypeA
+
+    """
+    if "dispatch_type" in kwargs:
+        disp_type = kwargs.pop("dispatch_type")
+        dispatchables = tuple(
+            d if isinstance(d, Dispatchable) else Dispatchable(d, disp_type)
+            for d in dispatchables
+        )
+    else:
+        dispatchables = tuple(dispatchables)
+        if not all(isinstance(d, Dispatchable) for d in dispatchables):
+            raise TypeError("dispatchables must be instances of uarray.Dispatchable")
+
+    if len(kwargs) != 0:
+        raise TypeError(f"Received unexpected keyword arguments: {kwargs}")
+
+    backend = _uarray.determine_backend(domain, dispatchables, coerce)
+
+    return set_backend(backend, coerce=coerce, only=only)
diff --git a/.venv/lib/python3.12/site-packages/scipy/_lib/_uarray/_uarray.cpython-312-x86_64-linux-gnu.so b/.venv/lib/python3.12/site-packages/scipy/_lib/_uarray/_uarray.cpython-312-x86_64-linux-gnu.so
new file mode 100644
index 0000000000000000000000000000000000000000..23660579f6a2d1bf5dc364306b1f3629b7f985bf
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/_lib/_uarray/_uarray.cpython-312-x86_64-linux-gnu.so
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:ca83664f94c09db3b054260ec762112b16fc6543d259b3477f26fa6f6639c7c0
+size 115080
diff --git a/.venv/lib/python3.12/site-packages/scipy/_lib/_util.py b/.venv/lib/python3.12/site-packages/scipy/_lib/_util.py
new file mode 100644
index 0000000000000000000000000000000000000000..2b07179e393c9ef3cdd9d1ce4198f695282bc941
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/_lib/_util.py
@@ -0,0 +1,1196 @@
+import re
+from contextlib import contextmanager
+import functools
+import operator
+import warnings
+import numbers
+from collections import namedtuple
+import inspect
+import math
+import sys
+import textwrap
+from types import ModuleType
+from typing import Literal, TypeVar
+
+import numpy as np
+from scipy._lib._array_api import (Array, array_namespace, is_lazy_array, is_numpy,
+                                   is_marray, xp_size, xp_result_device, xp_result_type)
+from scipy._lib._docscrape import FunctionDoc, Parameter
+from scipy._lib._sparse import issparse
+
+from numpy.exceptions import AxisError
+
+
+type IntNumber = int | np.integer
+type DecimalNumber = float | np.floating | np.integer
+
+copy_if_needed: bool | None = None
+
+
+# Wrapped function for inspect.signature for compatibility with Python 3.14+
+# See gh-23913
+#
+# PEP 649/749 allows for underfined annotations at runtime, and added the
+# `annotation_format` parameter to handle these cases.
+# `annotationlib.Format.FORWARDREF` is the closest to previous behavior,
+# returning ForwardRef objects fornew undefined annotations cases.
+#
+# Consider dropping this wrapper when support for Python 3.13 is dropped.
+if sys.version_info >= (3, 14):
+    import annotationlib
+    def wrapped_inspect_signature(callable):
+        """Get a signature object for the passed callable."""
+        return inspect.signature(callable,
+                                 annotation_format=annotationlib.Format.FORWARDREF)
+else:
+    wrapped_inspect_signature = inspect.signature
+
+
+type _RNG = np.random.Generator | np.random.RandomState
+type SeedType = IntNumber | _RNG | None
+
+GeneratorType = TypeVar("GeneratorType", bound=_RNG)
+
+
+def _lazyselect(condlist, choicelist, arrays, default=0):
+    """
+    Mimic `np.select(condlist, choicelist)`.
+
+    Notice, it assumes that all `arrays` are of the same shape or can be
+    broadcasted together.
+
+    All functions in `choicelist` must accept array arguments in the order
+    given in `arrays` and must return an array of the same shape as broadcasted
+    `arrays`.
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> x = np.arange(6)
+    >>> np.select([x <3, x > 3], [x**2, x**3], default=0)
+    array([  0,   1,   4,   0,  64, 125])
+
+    >>> _lazyselect([x < 3, x > 3], [lambda x: x**2, lambda x: x**3], (x,))
+    array([   0.,    1.,    4.,   0.,   64.,  125.])
+
+    >>> a = -np.ones_like(x)
+    >>> _lazyselect([x < 3, x > 3],
+    ...             [lambda x, a: x**2, lambda x, a: a * x**3],
+    ...             (x, a), default=np.nan)
+    array([   0.,    1.,    4.,   nan,  -64., -125.])
+
+    """
+    arrays = np.broadcast_arrays(*arrays)
+    tcode = np.mintypecode([a.dtype.char for a in arrays])
+    out = np.full(np.shape(arrays[0]), fill_value=default, dtype=tcode)
+    for func, cond in zip(choicelist, condlist):
+        if np.all(cond is False):
+            continue
+        cond, _ = np.broadcast_arrays(cond, arrays[0])
+        temp = tuple(np.extract(cond, arr) for arr in arrays)
+        np.place(out, cond, func(*temp))
+    return out
+
+
+def _prune_array(array):
+    """Return an array equivalent to the input array. If the input
+    array is a view of a much larger array, copy its contents to a
+    newly allocated array. Otherwise, return the input unchanged.
+    """
+    if array.base is not None and array.size < array.base.size // 2:
+        return array.copy()
+    return array
+
+
+def float_factorial(n: int) -> float:
+    """Compute the factorial and return as a float
+
+    Returns infinity when result is too large for a double
+    """
+    return float(math.factorial(n)) if n < 171 else np.inf
+
+
+_rng_desc = (
+    r"""If `rng` is passed by keyword, types other than `numpy.random.Generator` are
+    passed to `numpy.random.default_rng` to instantiate a ``Generator``.
+    If `rng` is already a ``Generator`` instance, then the provided instance is
+    used. Specify `rng` for repeatable function behavior.
+
+    If this argument is passed by position or `{old_name}` is passed by keyword,
+    legacy behavior for the argument `{old_name}` applies:
+
+    - If `{old_name}` is None (or `numpy.random`), the `numpy.random.RandomState`
+      singleton is used.
+    - If `{old_name}` is an int, a new ``RandomState`` instance is used,
+      seeded with `{old_name}`.
+    - If `{old_name}` is already a ``Generator`` or ``RandomState`` instance then
+      that instance is used.
+
+    .. versionchanged:: 1.15.0
+        As part of the `SPEC-007 `_
+        transition from use of `numpy.random.RandomState` to
+        `numpy.random.Generator`, this keyword was changed from `{old_name}` to `rng`.
+        For an interim period, both keywords will continue to work, although only one
+        may be specified at a time. After the interim period, function calls using the
+        `{old_name}` keyword will emit warnings. The behavior of both `{old_name}` and
+        `rng` are outlined above, but only the `rng` keyword should be used in new code.
+        """
+)
+
+
+# SPEC 7
+def _transition_to_rng(old_name, *, position_num=None, end_version=None,
+                       replace_doc=True):
+    """Example decorator to transition from old PRNG usage to new `rng` behavior
+
+    Suppose the decorator is applied to a function that used to accept parameter
+    `old_name='random_state'` either by keyword or as a positional argument at
+    `position_num=1`. At the time of application, the name of the argument in the
+    function signature is manually changed to the new name, `rng`. If positional
+    use was allowed before, this is not changed.*
+
+    - If the function is called with both `random_state` and `rng`, the decorator
+      raises an error.
+    - If `random_state` is provided as a keyword argument, the decorator passes
+      `random_state` to the function's `rng` argument as a keyword. If `end_version`
+      is specified, the decorator will emit a `DeprecationWarning` about the
+      deprecation of keyword `random_state`.
+    - If `random_state` is provided as a positional argument, the decorator passes
+      `random_state` to the function's `rng` argument by position. If `end_version`
+      is specified, the decorator will emit a `FutureWarning` about the changing
+      interpretation of the argument.
+    - If `rng` is provided as a keyword argument, the decorator validates `rng` using
+      `numpy.random.default_rng` before passing it to the function.
+    - If `end_version` is specified and neither `random_state` nor `rng` is provided
+      by the user, the decorator checks whether `np.random.seed` has been used to set
+      the global seed. If so, it emits a `FutureWarning`, noting that usage of
+      `numpy.random.seed` will eventually have no effect. Either way, the decorator
+      calls the function without explicitly passing the `rng` argument.
+
+    If `end_version` is specified, a user must pass `rng` as a keyword to avoid
+    warnings.
+
+    After the deprecation period, the decorator can be removed, and the function
+    can simply validate the `rng` argument by calling `np.random.default_rng(rng)`.
+
+    * A `FutureWarning` is emitted when the PRNG argument is used by
+      position. It indicates that the "Hinsen principle" (same
+      code yielding different results in two versions of the software)
+      will be violated, unless positional use is deprecated. Specifically:
+
+      - If `None` is passed by position and `np.random.seed` has been used,
+        the function will change from being seeded to being unseeded.
+      - If an integer is passed by position, the random stream will change.
+      - If `np.random` or an instance of `RandomState` is passed by position,
+        an error will be raised.
+
+      We suggest that projects consider deprecating positional use of
+      `random_state`/`rng` (i.e., change their function signatures to
+      ``def my_func(..., *, rng=None)``); that might not make sense
+      for all projects, so this SPEC does not make that
+      recommendation, neither does this decorator enforce it.
+
+    Parameters
+    ----------
+    old_name : str
+        The old name of the PRNG argument (e.g. `seed` or `random_state`).
+    position_num : int, optional
+        The (0-indexed) position of the old PRNG argument (if accepted by position).
+        Maintainers are welcome to eliminate this argument and use, for example,
+        `inspect`, if preferred.
+    end_version : str, optional
+        The full version number of the library when the behavior described in
+        `DeprecationWarning`s and `FutureWarning`s will take effect. If left
+        unspecified, no warnings will be emitted by the decorator.
+    replace_doc : bool, default: True
+        Whether the decorator should replace the documentation for parameter `rng` with
+        `_rng_desc` (defined above), which documents both new `rng` keyword behavior
+        and typical legacy `random_state`/`seed` behavior. If True, manually replace
+        the first paragraph of the function's old `random_state`/`seed` documentation
+        with the desired *final* `rng` documentation; this way, no changes to
+        documentation are needed when the decorator is removed. Documentation of `rng`
+        after the first blank line is preserved. Use False if the function's old
+        `random_state`/`seed` behavior does not match that described by `_rng_desc`.
+
+    """
+    NEW_NAME = "rng"
+
+    cmn_msg = (
+        "To silence this warning and ensure consistent behavior in SciPy "
+        f"{end_version}, control the RNG using argument `{NEW_NAME}`. Arguments passed "
+        f"to keyword `{NEW_NAME}` will be validated by `np.random.default_rng`, so the "
+        "behavior corresponding with a given value may change compared to use of "
+        f"`{old_name}`. For example, "
+        "1) `None` will result in unpredictable random numbers, "
+        "2) an integer will result in a different stream of random numbers, (with the "
+        "same distribution), and "
+        "3) `np.random` or `RandomState` instances will result in an error. "
+        "See the documentation of `default_rng` for more information."
+    )
+
+    def decorator(fun):
+        @functools.wraps(fun)
+        def wrapper(*args, **kwargs):
+            # Determine how PRNG was passed
+            as_old_kwarg = old_name in kwargs
+            as_new_kwarg = NEW_NAME in kwargs
+            as_pos_arg = position_num is not None and len(args) >= position_num + 1
+            emit_warning = end_version is not None
+
+            # Can only specify PRNG one of the three ways
+            if int(as_old_kwarg) + int(as_new_kwarg) + int(as_pos_arg) > 1:
+                message = (
+                    f"{fun.__name__}() got multiple values for "
+                    f"argument now known as `{NEW_NAME}`. Specify one of "
+                    f"`{NEW_NAME}` or `{old_name}`."
+                )
+                raise TypeError(message)
+
+            # Check whether global random state has been set
+            global_seed_set = np.random.mtrand._rand._bit_generator._seed_seq is None
+
+            if as_old_kwarg:  # warn about deprecated use of old kwarg
+                kwargs[NEW_NAME] = kwargs.pop(old_name)
+                if emit_warning:
+                    message = (
+                        f"Use of keyword argument `{old_name}` is "
+                        f"deprecated and replaced by `{NEW_NAME}`.  "
+                        f"Support for `{old_name}` will be removed "
+                        f"in SciPy {end_version}. "
+                    ) + cmn_msg
+                    warnings.warn(message, DeprecationWarning, stacklevel=2)
+
+            elif as_pos_arg:
+                # Warn about changing meaning of positional arg
+
+                # Note that this decorator does not deprecate positional use of the
+                # argument; it only warns that the behavior will change in the future.
+                # Simultaneously transitioning to keyword-only use is another option.
+
+                arg = args[position_num]
+                # If the argument is None and the global seed wasn't set, or if the
+                # argument is one of a few new classes, the user will not notice change
+                # in behavior.
+                ok_classes = (
+                    np.random.Generator,
+                    np.random.SeedSequence,
+                    np.random.BitGenerator,
+                )
+                if (arg is None and not global_seed_set) or isinstance(arg, ok_classes):
+                    pass
+                elif emit_warning:
+                    message = (
+                        f"Positional use of `{NEW_NAME}` (formerly known as "
+                        f"`{old_name}`) is still allowed, but the behavior is "
+                        "changing: the argument will be normalized using "
+                        f"`np.random.default_rng` beginning in SciPy {end_version}, "
+                        "and the resulting `Generator` will be used to generate "
+                        "random numbers."
+                    ) + cmn_msg
+                    warnings.warn(message, FutureWarning, stacklevel=2)
+
+            elif as_new_kwarg:  # no warnings; this is the preferred use
+                # After the removal of the decorator, normalization with
+                # np.random.default_rng will be done inside the decorated function
+                kwargs[NEW_NAME] = np.random.default_rng(kwargs[NEW_NAME])
+
+            elif global_seed_set and emit_warning:
+                # Emit FutureWarning if `np.random.seed` was used and no PRNG was passed
+                message = (
+                    "The NumPy global RNG was seeded by calling "
+                    f"`np.random.seed`. Beginning in {end_version}, this "
+                    "function will no longer use the global RNG."
+                ) + cmn_msg
+                warnings.warn(message, FutureWarning, stacklevel=2)
+
+            return fun(*args, **kwargs)
+
+        # Add the old parameter name to the function signature
+        wrapped_signature = inspect.signature(fun)
+        wrapper.__signature__ = wrapped_signature.replace(parameters=[
+            *wrapped_signature.parameters.values(),
+            inspect.Parameter(old_name, inspect.Parameter.KEYWORD_ONLY, default=None),
+        ])
+
+        if replace_doc:
+            doc = FunctionDoc(wrapper)
+            parameter_names = [param.name for param in doc['Parameters']]
+            if 'rng' in parameter_names:
+                _type = "{None, int, `numpy.random.Generator`}, optional"
+                _desc = _rng_desc.replace("{old_name}", old_name)
+                old_doc = doc['Parameters'][parameter_names.index('rng')].desc
+                old_doc_keep = old_doc[old_doc.index("") + 1:] if "" in old_doc else []
+                new_doc = [_desc] + old_doc_keep
+                _rng_parameter_doc = Parameter('rng', _type, new_doc)
+                doc['Parameters'][parameter_names.index('rng')] = _rng_parameter_doc
+                doc = str(doc).split("\n", 1)[1].lstrip(" \n")  # remove signature
+                wrapper.__doc__ = str(doc)
+        return wrapper
+
+    return decorator
+
+
+# copy-pasted from scikit-learn utils/validation.py
+def check_random_state(seed):
+    """Turn `seed` into a `np.random.RandomState` instance.
+
+    Parameters
+    ----------
+    seed : {None, int, `numpy.random.Generator`, `numpy.random.RandomState`}, optional
+        If `seed` is None (or `np.random`), the `numpy.random.RandomState`
+        singleton is used.
+        If `seed` is an int, a new ``RandomState`` instance is used,
+        seeded with `seed`.
+        If `seed` is already a ``Generator`` or ``RandomState`` instance then
+        that instance is used.
+
+    Returns
+    -------
+    seed : {`numpy.random.Generator`, `numpy.random.RandomState`}
+        Random number generator.
+
+    """
+    if seed is None or seed is np.random:
+        return np.random.mtrand._rand
+    if isinstance(seed, numbers.Integral | np.integer):
+        return np.random.RandomState(seed)
+    if isinstance(seed, np.random.RandomState | np.random.Generator):
+        return seed
+
+    raise ValueError(f"'{seed}' cannot be used to seed a numpy.random.RandomState"
+                     " instance")
+
+
+def _asarray_validated(a, check_finite=True,
+                       sparse_ok=False, objects_ok=False, mask_ok=False,
+                       as_inexact=False):
+    """
+    Helper function for SciPy argument validation.
+
+    Many SciPy linear algebra functions do support arbitrary array-like
+    input arguments. Examples of commonly unsupported inputs include
+    matrices containing inf/nan, sparse matrix representations, and
+    matrices with complicated elements.
+
+    Parameters
+    ----------
+    a : array_like
+        The array-like input.
+    check_finite : bool, optional
+        Whether to check that the input matrices contain only finite numbers.
+        Disabling may give a performance gain, but may result in problems
+        (crashes, non-termination) if the inputs do contain infinities or NaNs.
+        Default: True
+    sparse_ok : bool, optional
+        True if scipy sparse matrices are allowed.
+    objects_ok : bool, optional
+        True if arrays with dype('O') are allowed.
+    mask_ok : bool, optional
+        True if masked arrays are allowed.
+    as_inexact : bool, optional
+        True to convert the input array to a np.inexact dtype.
+
+    Returns
+    -------
+    ret : ndarray
+        The converted validated array.
+
+    """
+    if not sparse_ok:
+        if issparse(a):
+            msg = ('Sparse arrays/matrices are not supported by this function. '
+                   'Perhaps one of the `scipy.sparse.linalg` functions '
+                   'would work instead.')
+            raise ValueError(msg)
+    if not mask_ok:
+        if np.ma.isMaskedArray(a):
+            raise ValueError('masked arrays are not supported')
+    toarray = np.asarray_chkfinite if check_finite else np.asarray
+    a = toarray(a)
+    if not objects_ok:
+        if a.dtype is np.dtype('O'):
+            raise ValueError('object arrays are not supported')
+    if as_inexact:
+        if not np.issubdtype(a.dtype, np.inexact):
+            a = toarray(a, dtype=np.float64)
+    return a
+
+
+def _validate_int(k, name, minimum=None):
+    """
+    Validate a scalar integer.
+
+    This function can be used to validate an argument to a function
+    that expects the value to be an integer.  It uses `operator.index`
+    to validate the value (so, for example, k=2.0 results in a
+    TypeError).
+
+    Parameters
+    ----------
+    k : int
+        The value to be validated.
+    name : str
+        The name of the parameter.
+    minimum : int, optional
+        An optional lower bound.
+    """
+    try:
+        k = operator.index(k)
+    except TypeError:
+        raise TypeError(f'{name} must be an integer.') from None
+    if minimum is not None and k < minimum:
+        raise ValueError(f'{name} must be an integer not less '
+                         f'than {minimum}') from None
+    return k
+
+
+# Add a replacement for inspect.getfullargspec()/
+# The version below is borrowed from Django,
+# https://github.com/django/django/pull/4846.
+
+# Note an inconsistency between inspect.getfullargspec(func) and
+# inspect.signature(func). If `func` is a bound method, the latter does *not*
+# list `self` as a first argument, while the former *does*.
+# Hence, cook up a common ground replacement: `getfullargspec_no_self` which
+# mimics `inspect.getfullargspec` but does not list `self`.
+#
+# This way, the caller code does not need to know whether it uses a legacy
+# .getfullargspec or a bright and shiny .signature.
+
+FullArgSpec = namedtuple('FullArgSpec',
+                         ['args', 'varargs', 'varkw', 'defaults',
+                          'kwonlyargs', 'kwonlydefaults', 'annotations'])
+
+
+def getfullargspec_no_self(func):
+    """inspect.getfullargspec replacement using inspect.signature.
+
+    If func is a bound method, do not list the 'self' parameter.
+
+    Parameters
+    ----------
+    func : callable
+        A callable to inspect
+
+    Returns
+    -------
+    fullargspec : FullArgSpec(args, varargs, varkw, defaults, kwonlyargs,
+                              kwonlydefaults, annotations)
+
+        NOTE: if the first argument of `func` is self, it is *not*, I repeat
+        *not*, included in fullargspec.args.
+        This is done for consistency between inspect.getargspec() under
+        Python 2.x, and inspect.signature() under Python 3.x.
+
+    """
+    sig = wrapped_inspect_signature(func)
+    args = [
+        p.name for p in sig.parameters.values()
+        if p.kind in [inspect.Parameter.POSITIONAL_OR_KEYWORD,
+                      inspect.Parameter.POSITIONAL_ONLY]
+    ]
+    varargs = [
+        p.name for p in sig.parameters.values()
+        if p.kind == inspect.Parameter.VAR_POSITIONAL
+    ]
+    varargs = varargs[0] if varargs else None
+    varkw = [
+        p.name for p in sig.parameters.values()
+        if p.kind == inspect.Parameter.VAR_KEYWORD
+    ]
+    varkw = varkw[0] if varkw else None
+    defaults = tuple(
+        p.default for p in sig.parameters.values()
+        if (p.kind == inspect.Parameter.POSITIONAL_OR_KEYWORD and
+            p.default is not p.empty)
+    ) or None
+    kwonlyargs = [
+        p.name for p in sig.parameters.values()
+        if p.kind == inspect.Parameter.KEYWORD_ONLY
+    ]
+    kwdefaults = {p.name: p.default for p in sig.parameters.values()
+                  if p.kind == inspect.Parameter.KEYWORD_ONLY and
+                  p.default is not p.empty}
+    annotations = {p.name: p.annotation for p in sig.parameters.values()
+                   if p.annotation is not p.empty}
+    return FullArgSpec(args, varargs, varkw, defaults, kwonlyargs,
+                       kwdefaults or None, annotations)
+
+
+class _FunctionWrapper:
+    """
+    Object to wrap user's function, allowing picklability
+    """
+    def __init__(self, f, args):
+        self.f = f
+        self.args = [] if args is None else args
+
+    def __call__(self, x):
+        return self.f(x, *self.args)
+
+
+class _ScalarFunctionWrapper:
+    """
+    Object to wrap scalar user function, allowing picklability
+    """
+    def __init__(self, f, args=None):
+        self.f = f
+        self.args = [] if args is None else args
+        self.nfev = 0
+
+    def __call__(self, x):
+        # Send a copy because the user may overwrite it.
+        # The user of this class might want `x` to remain unchanged.
+        fx = self.f(np.copy(x), *self.args)
+        self.nfev += 1
+
+        # Make sure the function returns a true scalar
+        if not np.isscalar(fx):
+            _dt = getattr(fx, "dtype", np.dtype(np.float64))
+            try:
+                fx = _dt.type(np.asarray(fx).item())
+            except (TypeError, ValueError) as e:
+                raise ValueError(
+                    "The user-provided objective function "
+                    "must return a scalar value."
+                ) from e
+        return fx
+
+class MapWrapper:
+    """
+    Parallelisation wrapper for working with map-like callables, such as
+    `multiprocessing.Pool.map`.
+
+    Parameters
+    ----------
+    pool : int or map-like callable
+        If `pool` is an integer, then it specifies the number of threads to
+        use for parallelization. If ``int(pool) == 1``, then no parallel
+        processing is used and the map builtin is used.
+        If ``pool == -1``, then the pool will utilize all available CPUs.
+        If `pool` is a map-like callable that follows the same
+        calling sequence as the built-in map function, then this callable is
+        used for parallelization.
+    """
+    def __init__(self, pool=1):
+        self.pool = None
+        self._mapfunc = map
+        self._own_pool = False
+
+        if callable(pool):
+            self.pool = pool
+            self._mapfunc = self.pool
+        else:
+            from multiprocessing import (
+                get_all_start_methods, get_context, get_start_method
+            )
+
+            method = get_start_method(allow_none=True)
+
+            if (method is None and sys.version_info < (3, 14)
+                    and 'forkserver' in get_all_start_methods()):
+                # Python 3.13 and older used "fork" on posix, which can lead to
+                # deadlocks. This backports that fix to older Python versions.
+                method = 'forkserver'
+
+            # user supplies a number
+            if int(pool) == -1:
+                # use as many processors as possible
+                self.pool = get_context(method=method).Pool()
+                self._mapfunc = self.pool.map
+                self._own_pool = True
+            elif int(pool) == 1:
+                pass
+            elif int(pool) > 1:
+                # use the number of processors requested
+                self.pool = get_context(method=method).Pool(processes=int(pool))
+                self._mapfunc = self.pool.map
+                self._own_pool = True
+            else:
+                raise RuntimeError("Number of workers specified must be -1,"
+                                   " an int >= 1, or an object with a 'map' "
+                                   "method")
+
+    def __enter__(self):
+        return self
+
+    def terminate(self):
+        if self._own_pool:
+            self.pool.terminate()
+
+    def join(self):
+        if self._own_pool:
+            self.pool.join()
+
+    def close(self):
+        if self._own_pool:
+            self.pool.close()
+
+    def __exit__(self, exc_type, exc_value, traceback):
+        if self._own_pool:
+            self.pool.close()
+            self.pool.terminate()
+
+    def __call__(self, func, iterable):
+        # only accept one iterable because that's all Pool.map accepts
+        try:
+            return self._mapfunc(func, iterable)
+        except TypeError as e:
+            # wrong number of arguments
+            raise TypeError("The map-like callable must be of the"
+                            " form f(func, iterable)") from e
+
+
+def _workers_wrapper(func):
+    """
+    Wrapper to deal with setup-cleanup of workers outside a user function via a
+    ContextManager. It saves having to do the setup/tear down with within that
+    function, which can be messy.
+    """
+    @functools.wraps(func)
+    def inner(*args, **kwds):
+        kwargs = kwds.copy()
+        if 'workers' not in kwargs:
+            _workers = map
+        elif 'workers' in kwargs and kwargs['workers'] is None:
+            _workers = map
+        else:
+            _workers = kwargs['workers']
+
+        with MapWrapper(_workers) as mf:
+            kwargs['workers'] = mf
+            return func(*args, **kwargs)
+
+    return inner
+
+
+def rng_integers(gen, low, high=None, size=None, dtype='int64',
+                 endpoint=False):
+    """
+    Return random integers from low (inclusive) to high (exclusive), or if
+    endpoint=True, low (inclusive) to high (inclusive). Replaces
+    `RandomState.randint` (with endpoint=False) and
+    `RandomState.random_integers` (with endpoint=True).
+
+    Return random integers from the "discrete uniform" distribution of the
+    specified dtype. If high is None (the default), then results are from
+    0 to low.
+
+    Parameters
+    ----------
+    gen : {None, np.random.RandomState, np.random.Generator}
+        Random number generator. If None, then the np.random.RandomState
+        singleton is used.
+    low : int or array-like of ints
+        Lowest (signed) integers to be drawn from the distribution (unless
+        high=None, in which case this parameter is 0 and this value is used
+        for high).
+    high : int or array-like of ints
+        If provided, one above the largest (signed) integer to be drawn from
+        the distribution (see above for behavior if high=None). If array-like,
+        must contain integer values.
+    size : array-like of ints, optional
+        Output shape. If the given shape is, e.g., (m, n, k), then m * n * k
+        samples are drawn. Default is None, in which case a single value is
+        returned.
+    dtype : {str, dtype}, optional
+        Desired dtype of the result. All dtypes are determined by their name,
+        i.e., 'int64', 'int', etc, so byteorder is not available and a specific
+        precision may have different C types depending on the platform.
+        The default value is 'int64'.
+    endpoint : bool, optional
+        If True, sample from the interval [low, high] instead of the default
+        [low, high) Defaults to False.
+
+    Returns
+    -------
+    out: int or ndarray of ints
+        size-shaped array of random integers from the appropriate distribution,
+        or a single such random int if size not provided.
+    """
+    if isinstance(gen, np.random.Generator):
+        return gen.integers(low, high=high, size=size, dtype=dtype,
+                            endpoint=endpoint)
+    else:
+        if gen is None:
+            # default is RandomState singleton used by np.random.
+            gen = np.random.mtrand._rand
+        if endpoint:
+            # inclusive of endpoint
+            # remember that low and high can be arrays, so don't modify in
+            # place
+            if high is None:
+                return gen.randint(low + 1, size=size, dtype=dtype)
+            if high is not None:
+                return gen.randint(low, high=high + 1, size=size, dtype=dtype)
+
+        # exclusive
+        return gen.randint(low, high=high, size=size, dtype=dtype)
+
+
+@contextmanager
+def _fixed_default_rng(seed=1638083107694713882823079058616272161):
+    """Context with a fixed np.random.default_rng seed."""
+    orig_fun = np.random.default_rng
+    np.random.default_rng = lambda seed=seed: orig_fun(seed)
+    try:
+        yield
+    finally:
+        np.random.default_rng = orig_fun
+
+
+@contextmanager
+def ignore_warns(expected_warning, *, match=None):
+    with warnings.catch_warnings():
+        warnings.filterwarnings("ignore", match, expected_warning)
+        yield
+
+
+def _rng_html_rewrite(func):
+    """Rewrite the HTML rendering of ``np.random.default_rng``.
+
+    This is intended to decorate
+    ``numpydoc.docscrape_sphinx.SphinxDocString._str_examples``.
+
+    Examples are only run by Sphinx when there are plot involved. Even so,
+    it does not change the result values getting printed.
+    """
+    # hexadecimal or number seed, case-insensitive
+    pattern = re.compile(r'np.random.default_rng\((0x[0-9A-F]+|\d+)\)', re.I)
+
+    def _wrapped(*args, **kwargs):
+        res = func(*args, **kwargs)
+        lines = [
+            re.sub(pattern, 'np.random.default_rng()', line)
+            for line in res
+        ]
+        return lines
+
+    return _wrapped
+
+
+def _contains_nan(
+    a: Array,
+    nan_policy: Literal["propagate", "raise", "omit"] = "propagate",
+    *,
+    xp_omit_okay: bool = False,
+    xp: ModuleType | None = None,
+) -> Array | bool:
+    # Regarding `xp_omit_okay`: Temporarily, while `_axis_nan_policy` does not
+    # handle non-NumPy arrays, most functions that call `_contains_nan` want
+    # it to raise an error if `nan_policy='omit'` and `xp` is not `np`.
+    # Some functions support `nan_policy='omit'` natively, so setting this to
+    # `True` prevents the error from being raised.
+    policies = {"propagate", "raise", "omit"}
+    if nan_policy not in policies:
+        msg = f"nan_policy must be one of {policies}."
+        raise ValueError(msg)
+
+    if xp_size(a) == 0:
+        return False
+
+    if xp is None:
+        xp = array_namespace(a)
+
+    if xp.isdtype(a.dtype, "real floating"):
+        # Faster and less memory-intensive than xp.any(xp.isnan(a)), and unlike other
+        # reductions, `max`/`min` won't return NaN unless there is a NaN in the data.
+        contains_nan = xp.isnan(xp.max(a))
+    elif xp.isdtype(a.dtype, "complex floating"):
+        # Typically `real` and `imag` produce views; otherwise, `xp.any(xp.isnan(a))`
+        # would be more efficient.
+        contains_nan = xp.isnan(xp.max(xp.real(a))) | xp.isnan(xp.max(xp.imag(a)))
+    elif is_numpy(xp) and np.issubdtype(a.dtype, object):
+        contains_nan = False
+        for el in a.ravel():
+            # isnan doesn't work on non-numeric elements
+            if np.issubdtype(type(el), np.number) and np.isnan(el):
+                contains_nan = True
+                break
+    else:
+        # Only `object` and `inexact` arrays can have NaNs
+        return False
+
+    # The implicit call to bool(contains_nan) must happen after testing
+    # nan_policy to prevent lazy and device-bound xps from raising in the
+    # default policy='propagate' case.
+    if nan_policy == 'raise':
+        if is_lazy_array(a):
+            msg = "nan_policy='raise' is not supported for lazy arrays."
+            raise TypeError(msg)
+        if contains_nan:
+            msg = "The input contains nan values"
+            raise ValueError(msg)
+    elif nan_policy == 'omit' and not xp_omit_okay and not is_numpy(xp):
+        if is_lazy_array(a):
+            msg = "nan_policy='omit' is not supported for lazy arrays."
+            raise TypeError(msg)
+
+    return contains_nan
+
+
+def _rename_parameter(old_name, new_name, dep_version=None):
+    """
+    Generate decorator for backward-compatible keyword renaming.
+
+    Apply the decorator generated by `_rename_parameter` to functions with a
+    recently renamed parameter to maintain backward-compatibility.
+
+    After decoration, the function behaves as follows:
+    If only the new parameter is passed into the function, behave as usual.
+    If only the old parameter is passed into the function (as a keyword), raise
+    a DeprecationWarning if `dep_version` is provided, and behave as usual
+    otherwise.
+    If both old and new parameters are passed into the function, raise a
+    DeprecationWarning if `dep_version` is provided, and raise the appropriate
+    TypeError (function got multiple values for argument).
+
+    Parameters
+    ----------
+    old_name : str
+        Old name of parameter
+    new_name : str
+        New name of parameter
+    dep_version : str, optional
+        Version of SciPy in which old parameter was deprecated in the format
+        'X.Y.Z'. If supplied, the deprecation message will indicate that
+        support for the old parameter will be removed in version 'X.Y+2.Z'
+
+    Notes
+    -----
+    Untested with functions that accept *args. Probably won't work as written.
+
+    """
+    def decorator(fun):
+        @functools.wraps(fun)
+        def wrapper(*args, **kwargs):
+            if old_name in kwargs:
+                if dep_version:
+                    end_version = dep_version.split('.')
+                    end_version[1] = str(int(end_version[1]) + 2)
+                    end_version = '.'.join(end_version)
+                    message = (f"Use of keyword argument `{old_name}` is "
+                               f"deprecated and replaced by `{new_name}`.  "
+                               f"Support for `{old_name}` will be removed "
+                               f"in SciPy {end_version}.")
+                    warnings.warn(message, DeprecationWarning, stacklevel=2)
+                if new_name in kwargs:
+                    message = (f"{fun.__name__}() got multiple values for "
+                               f"argument now known as `{new_name}`")
+                    raise TypeError(message)
+                kwargs[new_name] = kwargs.pop(old_name)
+            return fun(*args, **kwargs)
+        return wrapper
+    return decorator
+
+
+def _rng_spawn(rng, n_children):
+    # spawns independent RNGs from a parent RNG
+    bg = rng._bit_generator
+    ss = bg._seed_seq
+    child_rngs = [np.random.Generator(type(bg)(child_ss))
+                  for child_ss in ss.spawn(n_children)]
+    return child_rngs
+
+
+def _get_nan(*data, shape=(), xp=None):
+    xp = array_namespace(*data) if xp is None else xp
+    # Get NaN of appropriate dtype for data
+    dtype = xp_result_type(*data, force_floating=True, xp=xp)
+    device = xp_result_device(*data)
+    res = xp.full(shape, xp.nan, dtype=dtype, device=device)
+    if not shape:
+        res = res[()]
+    # whenever mdhaber/marray#89 is resolved, could just return `res`
+    return res.data if is_marray(xp) else res
+
+
+def normalize_axis_index(axis, ndim):
+    # Check if `axis` is in the correct range and normalize it
+    if axis < -ndim or axis >= ndim:
+        msg = f"axis {axis} is out of bounds for array of dimension {ndim}"
+        raise AxisError(msg)
+
+    if axis < 0:
+        axis = axis + ndim
+    return axis
+
+
+def _call_callback_maybe_halt(callback, res):
+    """Call wrapped callback; return True if algorithm should stop.
+
+    Parameters
+    ----------
+    callback : callable or None
+        A user-provided callback wrapped with `_wrap_callback`
+    res : OptimizeResult
+        Information about the current iterate
+
+    Returns
+    -------
+    halt : bool
+        True if minimization should stop
+
+    """
+    if callback is None:
+        return False
+    try:
+        callback(res)
+        return False
+    except StopIteration:
+        callback.stop_iteration = True
+        return True
+
+
+class _RichResult(dict):
+    """ Container for multiple outputs with pretty-printing """
+    def __getattr__(self, name):
+        try:
+            return self[name]
+        except KeyError as e:
+            raise AttributeError(name) from e
+
+    __setattr__ = dict.__setitem__  # type: ignore[assignment]
+    __delattr__ = dict.__delitem__  # type: ignore[assignment]
+
+    def __repr__(self):
+        order_keys = ['message', 'success', 'status', 'fun', 'funl', 'x', 'xl',
+                      'col_ind', 'nit', 'lower', 'upper', 'eqlin', 'ineqlin',
+                      'converged', 'flag', 'function_calls', 'iterations',
+                      'root']
+        order_keys = getattr(self, '_order_keys', order_keys)
+        # 'slack', 'con' are redundant with residuals
+        # 'crossover_nit' is probably not interesting to most users
+        omit_keys = {'slack', 'con', 'crossover_nit', '_order_keys'}
+
+        def key(item):
+            try:
+                return order_keys.index(item[0].lower())
+            except ValueError:  # item not in list
+                return np.inf
+
+        def omit_redundant(items):
+            for item in items:
+                if item[0] in omit_keys:
+                    continue
+                yield item
+
+        def item_sorter(d):
+            return sorted(omit_redundant(d.items()), key=key)
+
+        if self.keys():
+            return _dict_formatter(self, sorter=item_sorter)
+        else:
+            return self.__class__.__name__ + "()"
+
+    def __dir__(self):
+        return list(self.keys())
+
+
+def _indenter(s, n=0):
+    """
+    Ensures that lines after the first are indented by the specified amount
+    """
+    split = s.split("\n")
+    indent = " "*n
+    return ("\n" + indent).join(split)
+
+
+def _float_formatter_10(x):
+    """
+    Returns a string representation of a float with exactly ten characters
+    """
+    if np.isposinf(x):
+        return "       inf"
+    elif np.isneginf(x):
+        return "      -inf"
+    elif np.isnan(x):
+        return "       nan"
+    return np.format_float_scientific(x, precision=3, pad_left=2, unique=False)
+
+
+def _dict_formatter(d, n=0, mplus=1, sorter=None):
+    """
+    Pretty printer for dictionaries
+
+    `n` keeps track of the starting indentation;
+    lines are indented by this much after a line break.
+    `mplus` is additional left padding applied to keys
+    """
+    if isinstance(d, dict):
+        m = max(map(len, list(d.keys()))) + mplus  # width to print keys
+        s = '\n'.join([k.rjust(m) + ': ' +  # right justified, width m
+                       _indenter(_dict_formatter(v, m+n+2, 0, sorter), m+2)
+                       for k, v in sorter(d)])  # +2 for ': '
+    else:
+        # By default, NumPy arrays print with linewidth=76. `n` is
+        # the indent at which a line begins printing, so it is subtracted
+        # from the default to avoid exceeding 76 characters total.
+        # `edgeitems` is the number of elements to include before and after
+        # ellipses when arrays are not shown in full.
+        # `threshold` is the maximum number of elements for which an
+        # array is shown in full.
+        # These values tend to work well for use with OptimizeResult.
+        with np.printoptions(linewidth=76-n, edgeitems=2, threshold=12,
+                             formatter={'float_kind': _float_formatter_10}):
+            s = str(d)
+    return s
+
+
+
+def _deprecate_dtypes(func_name, *arrays):
+    """
+    A temporary helper for deprecating non-LAPACK dtypes.
+    """
+    # XXX Once the deprecation expires, merge
+    # linalg/lapack.py::_normalize_lapack_dtype and _normalize_lapack_dtype1, and
+    # simplify _ensure_dtype_cdsz
+    for a in arrays:
+        if a is None:
+            continue
+        if a.dtype.char not in np.typecodes['AllInteger'] + 'fdFD':
+            msg = (f"Calling {func_name} with arguments of dtype={a.dtype} "
+                   f"({a.dtype.char = }) is deprecated in SciPy 1.18.0 and "
+                    "will be removed in SciPy 1.20.0. Please cast array inputs to "
+                    "one of np.float{32,64} or np.complex{64,128} manually."
+            )
+            import warnings
+            warnings.warn(msg, category=DeprecationWarning, stacklevel=3)
+            return
+
+
+_batch_note = """
+The documentation is written assuming array arguments are of specified
+"core" shapes. However, array argument(s) of this function may have additional
+"batch" dimensions prepended to the core shape. In this case, the array is treated
+as a batch of lower-dimensional slices; see :ref:`linalg_batch` for details.
+Note that calls with zero-size batches are unsupported and will raise a ``ValueError``.
+"""
+
+
+def _apply_over_batch(*argdefs):
+    """
+    Factory for decorator that applies a function over batched arguments.
+
+    Array arguments may have any number of core dimensions (typically 0,
+    1, or 2) and any broadcastable batch shapes. There may be any
+    number of array outputs of any number of dimensions. Assumptions
+    right now - which are satisfied by all functions of interest in `linalg` -
+    are that all array inputs are consecutive keyword or positional arguments,
+    and that the wrapped function returns either a single array or a tuple of
+    arrays. It's only as general as it needs to be right now - it can be extended.
+
+    Parameters
+    ----------
+    *argdefs : tuple of (str, int)
+        Definitions of array arguments: the keyword name of the argument, and
+        the number of core dimensions.
+
+    Example:
+    --------
+    `linalg.eig` accepts two matrices as the first two arguments `a` and `b`, where
+    `b` is optional, and returns one array or a tuple of arrays, depending on the
+    values of other positional or keyword arguments. To generate a wrapper that applies
+    the function over batches of `a` and optionally `b` :
+
+    >>> _apply_over_batch(('a', 2), ('b', 2))
+    """
+    names, ndims = list(zip(*argdefs))
+    n_arrays = len(names)
+
+    def decorator(f):
+        @functools.wraps(f)
+        def wrapper(*args, **kwargs):
+            args = list(args)
+
+            # Ensure all arrays in `arrays`, other arguments in `other_args`/`kwargs`
+            arrays, other_args = args[:n_arrays], args[n_arrays:]
+            for i, name in enumerate(names):
+                if name in kwargs:
+                    if i + 1 <= len(args):
+                        raise ValueError(f'{f.__name__}() got multiple values '
+                                         f'for argument `{name}`.')
+                    else:
+                        arrays.append(kwargs.pop(name))
+
+            xp = array_namespace(*arrays)
+
+            # Determine core and batch shapes
+            batch_shapes = []
+            core_shapes = []
+            for i, (array, ndim) in enumerate(zip(arrays, ndims)):
+                array = None if array is None else xp.asarray(array)
+                shape = () if array is None else array.shape
+
+                if ndim == "1|2":  # special case for `solve`, etc.
+                    ndim = 2 if array.ndim >= 2 else 1
+
+                arrays[i] = array
+                batch_shapes.append(shape[:-ndim] if ndim > 0 else shape)
+                core_shapes.append(shape[-ndim:] if ndim > 0 else ())
+
+            # complain on dtypes
+            if is_numpy(xp):
+                _deprecate_dtypes(f.__name__, *arrays)
+
+            # Early exit if call is not batched
+            if not any(batch_shapes):
+                return f(*arrays, *other_args, **kwargs)
+
+            # Determine broadcasted batch shape
+            batch_shape = np.broadcast_shapes(*batch_shapes)  # Gives OK error message
+
+            # We can't support zero-size batches right now because without data with
+            # which to call the function, the decorator doesn't even know the *number*
+            # of outputs, let alone their core shapes or dtypes.
+            if math.prod(batch_shape) == 0:
+                message = f'`{f.__name__}` does not support zero-size batches.'
+                raise ValueError(message)
+
+            # Broadcast arrays to appropriate shape
+            for i, (array, core_shape) in enumerate(zip(arrays, core_shapes)):
+                if array is None:
+                    continue
+                arrays[i] = xp.broadcast_to(array, batch_shape + core_shape)
+
+            # Main loop
+            results = []
+            for index in np.ndindex(batch_shape):
+                result = f(*((array[index] if array is not None else None)
+                             for array in arrays), *other_args, **kwargs)
+                # Assume `result` is either a tuple or single array. This is easily
+                # generalized by allowing the contributor to pass an `unpack_result`
+                # callable to the decorator factory.
+                result = (result,) if not isinstance(result, tuple) else result
+                results.append(result)
+            results = list(zip(*results))
+
+            # Reshape results
+            for i, result in enumerate(results):
+                result = xp.stack(result)
+                core_shape = result.shape[1:]
+                results[i] = xp.reshape(result, batch_shape + core_shape)
+
+            # Assume `result` should be a single array if there is only one element or
+            # a `tuple` otherwise. This is easily generalized by allowing the
+            # contributor to pass an `pack_result` callable to the decorator factory.
+            return results[0] if len(results) == 1 else results
+
+        doc = FunctionDoc(wrapper)
+        doc['Extended Summary'].append(_batch_note.rstrip())
+        wrapper.__doc__ = str(doc).split("\n", 1)[1].lstrip(" \n")  # remove signature
+
+        return wrapper
+    return decorator
+
+
+def _dedent_for_py313(s):
+    """Apply textwrap.dedent to s for Python versions 3.13 or later."""
+    return s if sys.version_info < (3, 13) else textwrap.dedent(s)
+
+
+def broadcastable(shape_a: tuple[int, ...], shape_b: tuple[int, ...]) -> bool:
+    """Check if two shapes are broadcastable."""
+    return all(
+        (m == n) or (m == 1) or (n == 1) for m, n in zip(shape_a[::-1], shape_b[::-1])
+    )
diff --git a/.venv/lib/python3.12/site-packages/scipy/_lib/deprecation.py b/.venv/lib/python3.12/site-packages/scipy/_lib/deprecation.py
new file mode 100644
index 0000000000000000000000000000000000000000..ea60d3809bf9b11309f8a6613caffb6aaab7e667
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/_lib/deprecation.py
@@ -0,0 +1,274 @@
+from inspect import Parameter, signature
+import functools
+import warnings
+from importlib import import_module
+from scipy._lib._docscrape import FunctionDoc
+
+
+__all__ = ["_deprecated"]
+
+
+# Object to use as default value for arguments to be deprecated. This should
+# be used over 'None' as the user could parse 'None' as a positional argument
+_NoValue = object()
+
+def _sub_module_deprecation(*, sub_package, module, private_modules, all,
+                            attribute, correct_module=None, dep_version="1.16.0"):
+    """Helper function for deprecating modules that are public but were
+    intended to be private.
+
+    Parameters
+    ----------
+    sub_package : str
+        Subpackage the module belongs to eg. stats
+    module : str
+        Public but intended private module to deprecate
+    private_modules : list
+        Private replacement(s) for `module`; should contain the
+        content of ``all``, possibly spread over several modules.
+    all : list
+        ``__all__`` belonging to `module`
+    attribute : str
+        The attribute in `module` being accessed
+    correct_module : str, optional
+        Module in `sub_package` that `attribute` should be imported from.
+        Default is that `attribute` should be imported from ``scipy.sub_package``.
+    dep_version : str, optional
+        Version in which deprecated attributes will be removed.
+    """
+    if correct_module is not None:
+        correct_import = f"scipy.{sub_package}.{correct_module}"
+    else:
+        correct_import = f"scipy.{sub_package}"
+
+    if attribute not in all:
+        raise AttributeError(
+            f"`scipy.{sub_package}.{module}` has no attribute `{attribute}`; "
+            f"furthermore, `scipy.{sub_package}.{module}` is deprecated "
+            f"and will be removed in SciPy 2.0.0."
+        )
+
+    attr = getattr(import_module(correct_import), attribute, None)
+
+    if attr is not None:
+        message = (
+            f"Please import `{attribute}` from the `{correct_import}` namespace; "
+            f"the `scipy.{sub_package}.{module}` namespace is deprecated "
+            f"and will be removed in SciPy 2.0.0."
+        )
+    else:
+        message = (
+            f"`scipy.{sub_package}.{module}.{attribute}` is deprecated along with "
+            f"the `scipy.{sub_package}.{module}` namespace. "
+            f"`scipy.{sub_package}.{module}.{attribute}` will be removed "
+            f"in SciPy {dep_version}, and the `scipy.{sub_package}.{module}` namespace "
+            f"will be removed in SciPy 2.0.0."
+        )
+
+    warnings.warn(message, category=DeprecationWarning, stacklevel=3)
+
+    for module in private_modules:
+        try:
+            return getattr(import_module(f"scipy.{sub_package}.{module}"), attribute)
+        except AttributeError as e:
+            # still raise an error if the attribute isn't in any of the expected
+            # private modules
+            if module == private_modules[-1]:
+                raise e
+            continue
+    
+
+def _deprecated(msg, stacklevel=2):
+    """Deprecate a function by emitting a warning on use."""
+    def wrap(fun):
+        if isinstance(fun, type):
+            warnings.warn(
+                f"Trying to deprecate class {fun!r}",
+                category=RuntimeWarning, stacklevel=2)
+            return fun
+
+        @functools.wraps(fun)
+        def call(*args, **kwargs):
+            warnings.warn(msg, category=DeprecationWarning,
+                          stacklevel=stacklevel)
+            return fun(*args, **kwargs)
+        call.__doc__ = fun.__doc__
+        return call
+
+    return wrap
+
+
+class _DeprecationHelperStr:
+    """
+    Helper class used by deprecate_cython_api
+    """
+    def __init__(self, content, message):
+        self._content = content
+        self._message = message
+
+    def __hash__(self):
+        return hash(self._content)
+
+    def __eq__(self, other):
+        res = (self._content == other)
+        if res:
+            warnings.warn(self._message, category=DeprecationWarning,
+                          stacklevel=2)
+        return res
+
+
+def deprecate_cython_api(module, routine_name, new_name=None, message=None):
+    """
+    Deprecate an exported cdef function in a public Cython API module.
+
+    Only functions can be deprecated; typedefs etc. cannot.
+
+    Parameters
+    ----------
+    module : module
+        Public Cython API module (e.g. scipy.linalg.cython_blas).
+    routine_name : str
+        Name of the routine to deprecate. May also be a fused-type
+        routine (in which case its all specializations are deprecated).
+    new_name : str
+        New name to include in the deprecation warning message
+    message : str
+        Additional text in the deprecation warning message
+
+    Examples
+    --------
+    Usually, this function would be used in the top-level of the
+    module ``.pyx`` file:
+
+    >>> from scipy._lib.deprecation import deprecate_cython_api
+    >>> import scipy.linalg.cython_blas as mod
+    >>> deprecate_cython_api(mod, "dgemm", "dgemm_new",
+    ...                      message="Deprecated in Scipy 1.5.0")
+    >>> del deprecate_cython_api, mod
+
+    After this, Cython modules that use the deprecated function emit a
+    deprecation warning when they are imported.
+
+    """
+    old_name = f"{module.__name__}.{routine_name}"
+
+    if new_name is None:
+        depdoc = f"`{old_name}` is deprecated!"
+    else:
+        depdoc = f"`{old_name}` is deprecated, use `{new_name}` instead!"
+
+    if message is not None:
+        depdoc += "\n" + message
+
+    d = module.__pyx_capi__
+
+    # Check if the function is a fused-type function with a mangled name
+    j = 0
+    has_fused = False
+    while True:
+        fused_name = f"__pyx_fuse_{j}{routine_name}"
+        if fused_name in d:
+            has_fused = True
+            d[_DeprecationHelperStr(fused_name, depdoc)] = d.pop(fused_name)
+            j += 1
+        else:
+            break
+
+    # If not, apply deprecation to the named routine
+    if not has_fused:
+        d[_DeprecationHelperStr(routine_name, depdoc)] = d.pop(routine_name)
+
+
+# taken from scikit-learn, see
+# https://github.com/scikit-learn/scikit-learn/blob/1.3.0/sklearn/utils/validation.py#L38
+def _deprecate_positional_args(func=None, *, version=None,
+                               deprecated_args=None, custom_message=""):
+    """Decorator for methods that issues warnings for positional arguments.
+
+    Using the keyword-only argument syntax in pep 3102, arguments after the
+    * will issue a warning when passed as a positional argument.
+
+    Parameters
+    ----------
+    func : callable, default=None
+        Function to check arguments on.
+    version : callable, default=None
+        The version when positional arguments will result in error.
+    deprecated_args : set of str, optional
+        Arguments to deprecate - whether passed by position or keyword.
+    custom_message : str, optional
+        Custom message to add to deprecation warning and documentation.
+    """
+    if version is None:
+        msg = "Need to specify a version where signature will be changed"
+        raise ValueError(msg)
+
+    deprecated_args = set() if deprecated_args is None else set(deprecated_args)
+
+    def _inner_deprecate_positional_args(f):
+        sig = signature(f)
+        kwonly_args = []
+        all_args = []
+
+        for name, param in sig.parameters.items():
+            if param.kind == Parameter.POSITIONAL_OR_KEYWORD:
+                all_args.append(name)
+            elif param.kind == Parameter.KEYWORD_ONLY:
+                kwonly_args.append(name)
+
+        def warn_deprecated_args(kwargs):
+            intersection = deprecated_args.intersection(kwargs)
+            if intersection:
+                message = (f"Arguments {intersection} are deprecated, whether passed "
+                           "by position or keyword. They will be removed in SciPy "
+                           f"{version}. ")
+                message += custom_message
+                warnings.warn(message, category=DeprecationWarning, stacklevel=3)
+
+        @functools.wraps(f)
+        def inner_f(*args, **kwargs):
+
+            extra_args = len(args) - len(all_args)
+            if extra_args <= 0:
+                warn_deprecated_args(kwargs)
+                return f(*args, **kwargs)
+
+            # extra_args > 0
+            kwonly_extra_args = set(kwonly_args[:extra_args]) - deprecated_args
+            args_msg = ", ".join(kwonly_extra_args)
+            warnings.warn(
+                (
+                    f"You are passing as positional arguments: {args_msg}. "
+                    "Please change your invocation to use keyword arguments. "
+                    f"From SciPy {version}, passing these as positional "
+                    "arguments will result in an error."
+                ),
+                DeprecationWarning,
+                stacklevel=2,
+            )
+            kwargs.update(zip(sig.parameters, args))
+            warn_deprecated_args(kwargs)
+            return f(**kwargs)
+
+        doc = FunctionDoc(inner_f)
+        kwonly_extra_args = set(kwonly_args) - deprecated_args
+        admonition = f"""
+.. deprecated:: {version}
+    Use of argument(s) ``{kwonly_extra_args}`` by position is deprecated; beginning in 
+    SciPy {version}, these will be keyword-only. """
+        if deprecated_args:
+            admonition += (f"Argument(s) ``{deprecated_args}`` are deprecated, whether "
+                           "passed by position or keyword; they will be removed in "
+                           f"SciPy {version}. ")
+        admonition += custom_message
+        doc['Extended Summary'] += [admonition]
+
+        doc = str(doc).split("\n", 1)[1].lstrip(" \n")  # remove signature
+        inner_f.__doc__ = str(doc)
+
+        return inner_f
+
+    if func is not None:
+        return _inner_deprecate_positional_args(func)
+
+    return _inner_deprecate_positional_args
diff --git a/.venv/lib/python3.12/site-packages/scipy/_lib/doccer.py b/.venv/lib/python3.12/site-packages/scipy/_lib/doccer.py
new file mode 100644
index 0000000000000000000000000000000000000000..7fd8fef0b4c49a60fdd71427d134528aee00a216
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/_lib/doccer.py
@@ -0,0 +1,366 @@
+"""Utilities to allow inserting docstring fragments for common
+parameters into function and method docstrings."""
+
+from collections.abc import Callable, Iterable, Mapping
+from typing import Protocol, TypeVar
+import sys
+
+__all__ = [
+    "docformat",
+    "inherit_docstring_from",
+    "indentcount_lines",
+    "filldoc",
+    "unindent_dict",
+    "unindent_string",
+    "extend_notes_in_docstring",
+    "replace_notes_in_docstring",
+    "doc_replace",
+]
+
+_F = TypeVar("_F", bound=Callable[..., object])
+
+
+class Decorator(Protocol):
+    """A decorator of a function."""
+
+    def __call__(self, func: _F, /) -> _F: ...
+
+
+def docformat(docstring: str, docdict: Mapping[str, str] | None = None) -> str:
+    """Fill a function docstring from variables in dictionary.
+
+    Adapt the indent of the inserted docs
+
+    Parameters
+    ----------
+    docstring : str
+        A docstring from a function, possibly with dict formatting strings.
+    docdict : dict[str, str], optional
+        A dictionary with keys that match the dict formatting strings
+        and values that are docstring fragments to be inserted. The
+        indentation of the inserted docstrings is set to match the
+        minimum indentation of the ``docstring`` by adding this
+        indentation to all lines of the inserted string, except the
+        first.
+
+    Returns
+    -------
+    docstring : str
+        string with requested ``docdict`` strings inserted.
+
+    Examples
+    --------
+    >>> docformat(' Test string with %(value)s', {'value':'inserted value'})
+    ' Test string with inserted value'
+    >>> docstring = 'First line\\n    Second line\\n    %(value)s'
+    >>> inserted_string = "indented\\nstring"
+    >>> docdict = {'value': inserted_string}
+    >>> docformat(docstring, docdict)
+    'First line\\n    Second line\\n    indented\\n    string'
+    """
+    if not docstring:
+        return docstring
+    if docdict is None:
+        docdict = {}
+    if not docdict:
+        return docstring
+    lines = docstring.expandtabs().splitlines()
+    # Find the minimum indent of the main docstring, after first line
+    if len(lines) < 2:
+        icount = 0
+    else:
+        icount = indentcount_lines(lines[1:])
+    indent = " " * icount
+    # Insert this indent to dictionary docstrings
+    indented = {}
+    for name, dstr in docdict.items():
+        lines = dstr.expandtabs().splitlines()
+        indented[name] = ("\n" + indent).join(lines)
+    return docstring % indented
+
+
+def inherit_docstring_from(cls: object) -> Decorator:
+    """This decorator modifies the decorated function's docstring by
+    replacing occurrences of '%(super)s' with the docstring of the
+    method of the same name from the class `cls`.
+
+    If the decorated method has no docstring, it is simply given the
+    docstring of `cls`s method.
+
+    Parameters
+    ----------
+    cls : type or object
+        A class with a method with the same name as the decorated method.
+        The docstring of the method in this class replaces '%(super)s' in the
+        docstring of the decorated method.
+
+    Returns
+    -------
+    decfunc : function
+        The decorator function that modifies the __doc__ attribute
+        of its argument.
+
+    Examples
+    --------
+    In the following, the docstring for Bar.func created using the
+    docstring of `Foo.func`.
+
+    >>> class Foo:
+    ...     def func(self):
+    ...         '''Do something useful.'''
+    ...         return
+    ...
+    >>> class Bar(Foo):
+    ...     @inherit_docstring_from(Foo)
+    ...     def func(self):
+    ...         '''%(super)s
+    ...         Do it fast.
+    ...         '''
+    ...         return
+    ...
+    >>> b = Bar()
+    >>> b.func.__doc__
+    'Do something useful.\n        Do it fast.\n        '
+    """
+
+    def _doc(func: _F) -> _F:
+        cls_docstring = getattr(cls, func.__name__).__doc__
+        func_docstring = func.__doc__
+        if func_docstring is None:
+            func.__doc__ = cls_docstring
+        else:
+            new_docstring = func_docstring % dict(super=cls_docstring)
+            func.__doc__ = new_docstring
+        return func
+
+    return _doc
+
+
+def extend_notes_in_docstring(cls: object, notes: str) -> Decorator:
+    """This decorator replaces the decorated function's docstring
+    with the docstring from corresponding method in `cls`.
+    It extends the 'Notes' section of that docstring to include
+    the given `notes`.
+
+    Parameters
+    ----------
+    cls : type or object
+        A class with a method with the same name as the decorated method.
+        The docstring of the method in this class replaces the docstring of the
+        decorated method.
+    notes : str
+        Additional notes to append to the 'Notes' section of the docstring.
+
+    Returns
+    -------
+    decfunc : function
+        The decorator function that modifies the __doc__ attribute
+        of its argument.
+    """
+
+    def _doc(func: _F) -> _F:
+        cls_docstring = getattr(cls, func.__name__).__doc__
+        # If python is called with -OO option,
+        # there is no docstring
+        if cls_docstring is None:
+            return func
+        end_of_notes = cls_docstring.find("        References\n")
+        if end_of_notes == -1:
+            end_of_notes = cls_docstring.find("        Examples\n")
+            if end_of_notes == -1:
+                end_of_notes = len(cls_docstring)
+        func.__doc__ = (
+            cls_docstring[:end_of_notes] + notes + cls_docstring[end_of_notes:]
+        )
+        return func
+
+    return _doc
+
+
+def replace_notes_in_docstring(cls: object, notes: str) -> Decorator:
+    """This decorator replaces the decorated function's docstring
+    with the docstring from corresponding method in `cls`.
+    It replaces the 'Notes' section of that docstring with
+    the given `notes`.
+
+    Parameters
+    ----------
+    cls : type or object
+        A class with a method with the same name as the decorated method.
+        The docstring of the method in this class replaces the docstring of the
+        decorated method.
+    notes : str
+        The notes to replace the existing 'Notes' section with.
+
+    Returns
+    -------
+    decfunc : function
+        The decorator function that modifies the __doc__ attribute
+        of its argument.
+    """
+
+    def _doc(func: _F) -> _F:
+        cls_docstring = getattr(cls, func.__name__).__doc__
+        notes_header = "        Notes\n        -----\n"
+        # If python is called with -OO option,
+        # there is no docstring
+        if cls_docstring is None:
+            return func
+        start_of_notes = cls_docstring.find(notes_header)
+        end_of_notes = cls_docstring.find("        References\n")
+        if end_of_notes == -1:
+            end_of_notes = cls_docstring.find("        Examples\n")
+            if end_of_notes == -1:
+                end_of_notes = len(cls_docstring)
+        func.__doc__ = (
+            cls_docstring[: start_of_notes + len(notes_header)]
+            + notes
+            + cls_docstring[end_of_notes:]
+        )
+        return func
+
+    return _doc
+
+
+def indentcount_lines(lines: Iterable[str]) -> int:
+    """Minimum indent for all lines in line list
+
+    Parameters
+    ----------
+    lines : Iterable[str]
+        The lines to find the minimum indent of.
+
+    Returns
+    -------
+    indent : int
+        The minimum indent.
+
+
+    Examples
+    --------
+    >>> lines = [' one', '  two', '   three']
+    >>> indentcount_lines(lines)
+    1
+    >>> lines = []
+    >>> indentcount_lines(lines)
+    0
+    >>> lines = [' one']
+    >>> indentcount_lines(lines)
+    1
+    >>> indentcount_lines(['    '])
+    0
+    """
+    indentno = sys.maxsize
+    for line in lines:
+        stripped = line.lstrip()
+        if stripped:
+            indentno = min(indentno, len(line) - len(stripped))
+    if indentno == sys.maxsize:
+        return 0
+    return indentno
+
+
+def filldoc(docdict: Mapping[str, str], unindent_params: bool = True) -> Decorator:
+    """Return docstring decorator using docdict variable dictionary.
+
+    Parameters
+    ----------
+    docdict : dict[str, str]
+        A dictionary containing name, docstring fragment pairs.
+    unindent_params : bool, optional
+        If True, strip common indentation from all parameters in docdict.
+        Default is False.
+
+    Returns
+    -------
+    decfunc : function
+        The decorator function that applies dictionary to its
+        argument's __doc__ attribute.
+    """
+    if unindent_params:
+        docdict = unindent_dict(docdict)
+
+    def decorate(func: _F) -> _F:
+        # __doc__ may be None for optimized Python (-OO)
+        doc = func.__doc__ or ""
+        func.__doc__ = docformat(doc, docdict)
+        return func
+
+    return decorate
+
+
+def unindent_dict(docdict: Mapping[str, str]) -> dict[str, str]:
+    """Unindent all strings in a docdict.
+
+    Parameters
+    ----------
+    docdict : dict[str, str]
+        A dictionary with string values to unindent.
+
+    Returns
+    -------
+    docdict : dict[str, str]
+        The `docdict` dictionary but each of its string values are unindented.
+    """
+    can_dict: dict[str, str] = {}
+    for name, dstr in docdict.items():
+        can_dict[name] = unindent_string(dstr)
+    return can_dict
+
+
+def unindent_string(docstring: str) -> str:
+    """Set docstring to minimum indent for all lines, including first.
+
+    Parameters
+    ----------
+    docstring : str
+        The input docstring to unindent.
+
+    Returns
+    -------
+    docstring : str
+        The unindented docstring.
+
+    Examples
+    --------
+    >>> unindent_string(' two')
+    'two'
+    >>> unindent_string('  two\\n   three')
+    'two\\n three'
+    """
+    lines = docstring.expandtabs().splitlines()
+    icount = indentcount_lines(lines)
+    if icount == 0:
+        return docstring
+    return "\n".join([line[icount:] for line in lines])
+
+
+def doc_replace(obj: object, oldval: str, newval: str) -> Decorator:
+    """Decorator to take the docstring from obj, with oldval replaced by newval
+
+    Equivalent to ``func.__doc__ = obj.__doc__.replace(oldval, newval)``
+
+    Parameters
+    ----------
+    obj : object
+        A class or object whose docstring will be used as the basis for the
+        replacement operation.
+    oldval : str
+        The string to search for in the docstring.
+    newval : str
+        The string to replace `oldval` with in the docstring.
+
+    Returns
+    -------
+    decfunc : function
+        A decorator function that replaces occurrences of `oldval` with `newval`
+        in the docstring of the decorated function.
+    """
+    # __doc__ may be None for optimized Python (-OO)
+    doc = (obj.__doc__ or "").replace(oldval, newval)
+
+    def inner(func: _F) -> _F:
+        func.__doc__ = doc
+        return func
+
+    return inner
diff --git a/.venv/lib/python3.12/site-packages/scipy/_lib/messagestream.cpython-312-x86_64-linux-gnu.so b/.venv/lib/python3.12/site-packages/scipy/_lib/messagestream.cpython-312-x86_64-linux-gnu.so
new file mode 100644
index 0000000000000000000000000000000000000000..b03dd22c98ac1131095ca4051e88af00e1ced1b7
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/scipy/_lib/messagestream.cpython-312-x86_64-linux-gnu.so differ
diff --git a/.venv/lib/python3.12/site-packages/scipy/_lib/tests/__init__.py b/.venv/lib/python3.12/site-packages/scipy/_lib/tests/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/.venv/lib/python3.12/site-packages/scipy/_lib/tests/test__gcutils.py b/.venv/lib/python3.12/site-packages/scipy/_lib/tests/test__gcutils.py
new file mode 100644
index 0000000000000000000000000000000000000000..429c89b4116b68af5decb3029a9033a19f480525
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/_lib/tests/test__gcutils.py
@@ -0,0 +1,106 @@
+""" Test for assert_deallocated context manager and gc utilities
+"""
+import gc
+from threading import Lock
+
+from scipy._lib._gcutils import (set_gc_state, gc_state, assert_deallocated,
+                                 ReferenceError)
+
+from numpy.testing import assert_equal
+
+import pytest
+
+
+@pytest.fixture
+def gc_lock():
+    return Lock()
+
+
+def test_set_gc_state(gc_lock):
+    with gc_lock:
+        gc_status = gc.isenabled()
+        try:
+            for state in (True, False):
+                gc.enable()
+                set_gc_state(state)
+                assert_equal(gc.isenabled(), state)
+                gc.disable()
+                set_gc_state(state)
+                assert_equal(gc.isenabled(), state)
+        finally:
+            if gc_status:
+                gc.enable()
+
+
+def test_gc_state(gc_lock):
+    # Test gc_state context manager
+    with gc_lock:
+        gc_status = gc.isenabled()
+        try:
+            for pre_state in (True, False):
+                set_gc_state(pre_state)
+                for with_state in (True, False):
+                    # Check the gc state is with_state in with block
+                    with gc_state(with_state):
+                        assert_equal(gc.isenabled(), with_state)
+                    # And returns to previous state outside block
+                    assert_equal(gc.isenabled(), pre_state)
+                    # Even if the gc state is set explicitly within the block
+                    with gc_state(with_state):
+                        assert_equal(gc.isenabled(), with_state)
+                        set_gc_state(not with_state)
+                    assert_equal(gc.isenabled(), pre_state)
+        finally:
+            if gc_status:
+                gc.enable()
+
+
+def test_assert_deallocated(gc_lock):
+    # Ordinary use
+    class C:
+        def __init__(self, arg0, arg1, name='myname'):
+            self.name = name
+    with gc_lock:
+        for gc_current in (True, False):
+            with gc_state(gc_current):
+                # We are deleting from with-block context, so that's OK
+                with assert_deallocated(C, 0, 2, 'another name') as c:
+                    assert_equal(c.name, 'another name')
+                    del c
+                # Or not using the thing in with-block context, also OK
+                with assert_deallocated(C, 0, 2, name='third name'):
+                    pass
+                assert_equal(gc.isenabled(), gc_current)
+
+
+def test_assert_deallocated_nodel():
+    class C:
+        pass
+    with pytest.raises(ReferenceError):
+        # Need to delete after using if in with-block context
+        # Note: assert_deallocated(C) needs to be assigned for the test
+        # to function correctly.  It is assigned to _, but _ itself is
+        # not referenced in the body of the with, it is only there for
+        # the refcount.
+        with assert_deallocated(C) as _:
+            pass
+
+
+def test_assert_deallocated_circular():
+    class C:
+        def __init__(self):
+            self._circular = self
+    with pytest.raises(ReferenceError):
+        # Circular reference, no automatic garbage collection
+        with assert_deallocated(C) as c:
+            del c
+
+
+def test_assert_deallocated_circular2():
+    class C:
+        def __init__(self):
+            self._circular = self
+    with pytest.raises(ReferenceError):
+        # Still circular reference, no automatic garbage collection
+        with assert_deallocated(C):
+            pass
diff --git a/.venv/lib/python3.12/site-packages/scipy/_lib/tests/test__testutils.py b/.venv/lib/python3.12/site-packages/scipy/_lib/tests/test__testutils.py
new file mode 100644
index 0000000000000000000000000000000000000000..88db113d6d5a35c96ecc0a6a36ab42d74be49153
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/_lib/tests/test__testutils.py
@@ -0,0 +1,32 @@
+import sys
+from scipy._lib._testutils import _parse_size, _get_mem_available
+import pytest
+
+
+def test__parse_size():
+    expected = {
+        '12': 12e6,
+        '12 b': 12,
+        '12k': 12e3,
+        '  12  M  ': 12e6,
+        '  12  G  ': 12e9,
+        ' 12Tb ': 12e12,
+        '12  Mib ': 12 * 1024.0**2,
+        '12Tib': 12 * 1024.0**4,
+    }
+
+    for inp, outp in sorted(expected.items()):
+        if outp is None:
+            with pytest.raises(ValueError):
+                _parse_size(inp)
+        else:
+            assert _parse_size(inp) == outp
+
+
+def test__mem_available():
+    # May return None on non-Linux platforms
+    available = _get_mem_available()
+    if sys.platform.startswith('linux'):
+        assert available >= 0
+    else:
+        assert available is None or available >= 0
diff --git a/.venv/lib/python3.12/site-packages/scipy/_lib/tests/test__util.py b/.venv/lib/python3.12/site-packages/scipy/_lib/tests/test__util.py
new file mode 100644
index 0000000000000000000000000000000000000000..4cf29ae9c7b16d8b0a5f8441ac05694a11540b8b
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/_lib/tests/test__util.py
@@ -0,0 +1,604 @@
+from multiprocessing import Pool
+from multiprocessing.pool import Pool as PWL
+import re
+import math
+import functools
+from fractions import Fraction
+
+import numpy as np
+from numpy.testing import assert_equal, assert_
+import pytest
+from pytest import raises as assert_raises
+from scipy.conftest import skip_xp_invalid_arg
+
+from scipy._lib._array_api import xp_assert_equal
+from scipy._lib._util import (check_random_state, MapWrapper,
+                              getfullargspec_no_self, FullArgSpec,
+                              rng_integers, _validate_int, _rename_parameter,
+                              _contains_nan, _rng_html_rewrite, _workers_wrapper)
+import scipy._external.array_api_extra as xpx
+from scipy._external.array_api_extra.testing import lazy_xp_function
+from scipy import cluster, interpolate, linalg, optimize, sparse, spatial, stats
+
+
+lazy_xp_function(_contains_nan)
+
+
+def test_check_random_state():
+    # If seed is None, return the RandomState singleton used by np.random.
+    # If seed is an int, return a new RandomState instance seeded with seed.
+    # If seed is already a RandomState instance, return it.
+    # Otherwise raise ValueError.
+    rsi = check_random_state(1)
+    assert_equal(type(rsi), np.random.RandomState)
+    rsi = check_random_state(rsi)
+    assert_equal(type(rsi), np.random.RandomState)
+    rsi = check_random_state(None)
+    assert_equal(type(rsi), np.random.RandomState)
+    assert_raises(ValueError, check_random_state, 'a')
+    rg = np.random.Generator(np.random.PCG64())
+    rsi = check_random_state(rg)
+    assert_equal(type(rsi), np.random.Generator)
+
+
+def test_getfullargspec_no_self():
+    p = MapWrapper(1)
+    argspec = getfullargspec_no_self(p.__init__)
+    assert_equal(argspec, FullArgSpec(['pool'], None, None, (1,), [],
+                                      None, {}))
+    argspec = getfullargspec_no_self(p.__call__)
+    assert_equal(argspec, FullArgSpec(['func', 'iterable'], None, None, None,
+                                      [], None, {}))
+
+    class _rv_generic:
+        def _rvs(self, a, b=2, c=3, *args, size=None, **kwargs):
+            return None
+
+    rv_obj = _rv_generic()
+    argspec = getfullargspec_no_self(rv_obj._rvs)
+    assert_equal(argspec, FullArgSpec(['a', 'b', 'c'], 'args', 'kwargs',
+                                      (2, 3), ['size'], {'size': None}, {}))
+
+
+def test_mapwrapper_serial():
+    in_arg = np.arange(10.)
+    out_arg = np.sin(in_arg)
+
+    p = MapWrapper(1)
+    assert_(p._mapfunc is map)
+    assert_(p.pool is None)
+    assert_(p._own_pool is False)
+    out = list(p(np.sin, in_arg))
+    assert_equal(out, out_arg)
+
+    with assert_raises(RuntimeError):
+        p = MapWrapper(0)
+
+
+def test_pool():
+    with Pool(2) as p:
+        p.map(math.sin, [1, 2, 3, 4])
+
+
+def test_mapwrapper_parallel():
+    in_arg = np.arange(10.)
+    out_arg = np.sin(in_arg)
+
+    with MapWrapper(2) as p:
+        out = p(np.sin, in_arg)
+        assert_equal(list(out), out_arg)
+
+        assert_(p._own_pool is True)
+        assert_(isinstance(p.pool, PWL))
+        assert_(p._mapfunc is not None)
+
+    # the context manager should've closed the internal pool
+    # check that it has by asking it to calculate again.
+    with assert_raises(Exception) as excinfo:
+        p(np.sin, in_arg)
+
+    assert_(excinfo.type is ValueError)
+
+    # can also set a PoolWrapper up with a map-like callable instance
+    with Pool(2) as p:
+        q = MapWrapper(p.map)
+
+        assert_(q._own_pool is False)
+        q.close()
+
+        # closing the PoolWrapper shouldn't close the internal pool
+        # because it didn't create it
+        out = p.map(np.sin, in_arg)
+        assert_equal(list(out), out_arg)
+
+
+@_workers_wrapper
+def user_of_workers(x, b=1, workers=None):
+    assert workers is not None
+    assert isinstance(workers, MapWrapper)
+    return np.array(list(workers(np.sin, x * b)))
+
+
+def test__workers_wrapper():
+    arr = np.linspace(0, np.pi)
+    req = np.sin(arr * 2.0)
+
+    with Pool(2) as p:
+        v = user_of_workers(arr, workers=p.map, b=2)
+        assert_equal(v, req)
+
+    v = user_of_workers(arr, workers=None, b=2)
+    assert_equal(v, req)
+
+    v = user_of_workers(arr, workers=2, b=2)
+    assert_equal(v, req)
+
+    # assess if decorator works with partial functions
+    part_f = functools.partial(user_of_workers, b=2)
+    assert_equal(part_f(arr), req)
+
+    with Pool(2) as p:
+        part_f = functools.partial(user_of_workers, b=2, workers=p.map)
+        assert_equal(part_f(arr), req)
+
+
+def test_rng_integers():
+    rng = np.random.RandomState()
+
+    # test that numbers are inclusive of high point
+    arr = rng_integers(rng, low=2, high=5, size=100, endpoint=True)
+    assert np.max(arr) == 5
+    assert np.min(arr) == 2
+    assert arr.shape == (100, )
+
+    # test that numbers are inclusive of high point
+    arr = rng_integers(rng, low=5, size=100, endpoint=True)
+    assert np.max(arr) == 5
+    assert np.min(arr) == 0
+    assert arr.shape == (100, )
+
+    # test that numbers are exclusive of high point
+    arr = rng_integers(rng, low=2, high=5, size=100, endpoint=False)
+    assert np.max(arr) == 4
+    assert np.min(arr) == 2
+    assert arr.shape == (100, )
+
+    # test that numbers are exclusive of high point
+    arr = rng_integers(rng, low=5, size=100, endpoint=False)
+    assert np.max(arr) == 4
+    assert np.min(arr) == 0
+    assert arr.shape == (100, )
+
+    # now try with np.random.Generator
+    try:
+        rng = np.random.default_rng()
+    except AttributeError:
+        return
+
+    # test that numbers are inclusive of high point
+    arr = rng_integers(rng, low=2, high=5, size=100, endpoint=True)
+    assert np.max(arr) == 5
+    assert np.min(arr) == 2
+    assert arr.shape == (100, )
+
+    # test that numbers are inclusive of high point
+    arr = rng_integers(rng, low=5, size=100, endpoint=True)
+    assert np.max(arr) == 5
+    assert np.min(arr) == 0
+    assert arr.shape == (100, )
+
+    # test that numbers are exclusive of high point
+    arr = rng_integers(rng, low=2, high=5, size=100, endpoint=False)
+    assert np.max(arr) == 4
+    assert np.min(arr) == 2
+    assert arr.shape == (100, )
+
+    # test that numbers are exclusive of high point
+    arr = rng_integers(rng, low=5, size=100, endpoint=False)
+    assert np.max(arr) == 4
+    assert np.min(arr) == 0
+    assert arr.shape == (100, )
+
+
+class TestValidateInt:
+
+    @pytest.mark.parametrize('n', [4, np.uint8(4), np.int16(4), np.array(4)])
+    def test_validate_int(self, n):
+        n = _validate_int(n, 'n')
+        assert n == 4
+
+    @pytest.mark.parametrize('n', [4.0, np.array([4]), Fraction(4, 1)])
+    def test_validate_int_bad(self, n):
+        with pytest.raises(TypeError, match='n must be an integer'):
+            _validate_int(n, 'n')
+
+    def test_validate_int_below_min(self):
+        with pytest.raises(ValueError, match='n must be an integer not '
+                                             'less than 0'):
+            _validate_int(-1, 'n', 0)
+
+
+class TestRenameParameter:
+    # check that wrapper `_rename_parameter` for backward-compatible
+    # keyword renaming works correctly
+
+    # Example method/function that still accepts keyword `old`
+    @_rename_parameter("old", "new")
+    def old_keyword_still_accepted(self, new):
+        return new
+
+    # Example method/function for which keyword `old` is deprecated
+    @_rename_parameter("old", "new", dep_version="1.9.0")
+    def old_keyword_deprecated(self, new):
+        return new
+
+    def test_old_keyword_still_accepted(self):
+        # positional argument and both keyword work identically
+        res1 = self.old_keyword_still_accepted(10)
+        res2 = self.old_keyword_still_accepted(new=10)
+        res3 = self.old_keyword_still_accepted(old=10)
+        assert res1 == res2 == res3 == 10
+
+        # unexpected keyword raises an error
+        message = re.escape("old_keyword_still_accepted() got an unexpected")
+        with pytest.raises(TypeError, match=message):
+            self.old_keyword_still_accepted(unexpected=10)
+
+        # multiple values for the same parameter raises an error
+        message = re.escape("old_keyword_still_accepted() got multiple")
+        with pytest.raises(TypeError, match=message):
+            self.old_keyword_still_accepted(10, new=10)
+        with pytest.raises(TypeError, match=message):
+            self.old_keyword_still_accepted(10, old=10)
+        with pytest.raises(TypeError, match=message):
+            self.old_keyword_still_accepted(new=10, old=10)
+
+    @pytest.fixture
+    def kwarg_lock(self):
+        from threading import Lock
+        return Lock()
+
+    def test_old_keyword_deprecated(self, kwarg_lock):
+        # positional argument and both keyword work identically,
+        # but use of old keyword results in DeprecationWarning
+        dep_msg = "Use of keyword argument `old` is deprecated"
+        res1 = self.old_keyword_deprecated(10)
+        res2 = self.old_keyword_deprecated(new=10)
+        # pytest warning filter is not thread-safe, enforce serialization
+        with kwarg_lock:
+            with pytest.warns(DeprecationWarning, match=dep_msg):
+                    res3 = self.old_keyword_deprecated(old=10)
+        assert res1 == res2 == res3 == 10
+
+        # unexpected keyword raises an error
+        message = re.escape("old_keyword_deprecated() got an unexpected")
+        with pytest.raises(TypeError, match=message):
+            self.old_keyword_deprecated(unexpected=10)
+
+        # multiple values for the same parameter raises an error and,
+        # if old keyword is used, results in DeprecationWarning
+        message = re.escape("old_keyword_deprecated() got multiple")
+        with pytest.raises(TypeError, match=message):
+            self.old_keyword_deprecated(10, new=10)
+        with kwarg_lock:
+            with pytest.raises(TypeError, match=message), \
+                    pytest.warns(DeprecationWarning, match=dep_msg):
+                    # breakpoint()
+                    self.old_keyword_deprecated(10, old=10)
+        with kwarg_lock:
+            with pytest.raises(TypeError, match=message), \
+                    pytest.warns(DeprecationWarning, match=dep_msg):
+                    self.old_keyword_deprecated(new=10, old=10)
+
+
+class TestContainsNaN:
+    def test_policy(self):
+        data = np.array([1, 2, 3, np.nan])
+
+        assert _contains_nan(data)  # default policy is "propagate"
+        assert _contains_nan(data, nan_policy="propagate")
+        assert _contains_nan(data, nan_policy="omit")
+        assert not _contains_nan(data[:3])
+        assert not _contains_nan(data[:3], nan_policy="propagate")
+        assert not _contains_nan(data[:3], nan_policy="omit")
+
+        with pytest.raises(ValueError, match="The input contains nan values"):
+            _contains_nan(data, nan_policy="raise")
+        assert not _contains_nan(data[:3], nan_policy="raise")
+
+        with pytest.raises(ValueError, match="nan_policy must be one of"):
+            _contains_nan(data, nan_policy="nan")
+
+    def test_contains_nan(self):
+        # Special case: empty array
+        assert not _contains_nan(np.array([], dtype=float))
+
+        # Integer arrays cannot contain NaN
+        assert not _contains_nan(np.array([1, 2, 3]))
+        assert not _contains_nan(np.array([[1, 2], [3, 4]]))
+
+        assert not _contains_nan(np.array([1., 2., 3.]))
+        assert not _contains_nan(np.array([1., 2.j, 3.]))
+        assert _contains_nan(np.array([1., 2.j, np.nan]))
+        assert _contains_nan(np.array([1., 2., np.nan]))
+        assert _contains_nan(np.array([np.nan, 2., np.nan]))
+        assert not _contains_nan(np.array([[1., 2.], [3., 4.]]))
+        assert _contains_nan(np.array([[1., 2.], [3., np.nan]]))
+
+    @skip_xp_invalid_arg
+    def test_contains_nan_with_strings(self):
+        data1 = np.array([1, 2, "3", np.nan])  # converted to string "nan"
+        assert not _contains_nan(data1)
+
+        data2 = np.array([1, 2, "3", np.nan], dtype='object')
+        assert _contains_nan(data2)
+
+        data3 = np.array([["1", 2], [3, np.nan]])  # converted to string "nan"
+        assert not _contains_nan(data3)
+
+        data4 = np.array([["1", 2], [3, np.nan]], dtype='object')
+        assert _contains_nan(data4)
+
+    @pytest.mark.skip_xp_backends(eager_only=True,
+                                  reason="lazy backends tested separately")
+    @pytest.mark.parametrize("nan_policy", ['propagate', 'omit', 'raise'])
+    @pytest.mark.uses_xp_capabilities(False, reason="not applicable")
+    def test_array_api(self, xp, nan_policy):
+        rng = np.random.default_rng(932347235892482)
+        x0 = rng.random(size=(2, 3, 4))
+        x = xp.asarray(x0)
+        assert not _contains_nan(x, nan_policy)
+
+        x = xpx.at(x)[1, 2, 1].set(xp.nan)
+
+        if nan_policy == 'raise':
+            with pytest.raises(ValueError, match="The input contains nan values"):
+                _contains_nan(x, nan_policy)
+        elif nan_policy == 'omit':
+            assert _contains_nan(x, nan_policy, xp_omit_okay=True)
+        elif nan_policy == 'propagate':
+            assert _contains_nan(x, nan_policy)
+
+    @pytest.mark.skip_xp_backends("numpy", reason="lazy backends only")
+    @pytest.mark.skip_xp_backends("cupy", reason="lazy backends only")
+    @pytest.mark.skip_xp_backends("array_api_strict", reason="lazy backends only")
+    @pytest.mark.skip_xp_backends("torch", reason="lazy backends only")
+    @pytest.mark.uses_xp_capabilities(False, reason="not applicable")
+    def test_array_api_lazy(self, xp):
+        rng = np.random.default_rng(932347235892482)
+        x0 = rng.random(size=(2, 3, 4))
+        x = xp.asarray(x0)
+
+        xp_assert_equal(_contains_nan(x), xp.asarray(False))
+        xp_assert_equal(_contains_nan(x, "propagate"), xp.asarray(False))
+        xp_assert_equal(_contains_nan(x, "omit", xp_omit_okay=True), xp.asarray(False))
+        # Lazy arrays don't support "omit" and "raise" policies
+        match = "not supported for lazy arrays"
+        with pytest.raises(TypeError, match=match):
+            _contains_nan(x, "omit")
+        with pytest.raises(TypeError, match=match):
+            _contains_nan(x, "raise")
+
+        x = xpx.at(x)[1, 2, 1].set(np.nan)
+
+        xp_assert_equal(_contains_nan(x), xp.asarray(True))
+        xp_assert_equal(_contains_nan(x, "propagate"), xp.asarray(True))
+        xp_assert_equal(_contains_nan(x, "omit", xp_omit_okay=True), xp.asarray(True))
+        with pytest.raises(TypeError, match=match):
+            _contains_nan(x, "omit")
+        with pytest.raises(TypeError, match=match):
+            _contains_nan(x, "raise")
+
+
+def test__rng_html_rewrite():
+    def mock_str():
+        lines = [
+            'np.random.default_rng(8989843)',
+            'np.random.default_rng(seed)',
+            'np.random.default_rng(0x9a71b21474694f919882289dc1559ca)',
+            ' bob ',
+        ]
+        return lines
+
+    res = _rng_html_rewrite(mock_str)()
+    ref = [
+        'np.random.default_rng()',
+        'np.random.default_rng(seed)',
+        'np.random.default_rng()',
+        ' bob ',
+    ]
+
+    assert res == ref
+
+
+class TestTransitionToRNG:
+    def kmeans(self, **kwargs):
+        rng = np.random.default_rng(3458934594269824562)
+        return cluster.vq.kmeans2(rng.random(size=(20, 3)), 3, **kwargs)
+
+    def kmeans2(self, **kwargs):
+        rng = np.random.default_rng(3458934594269824562)
+        return cluster.vq.kmeans2(rng.random(size=(20, 3)), 3, **kwargs)
+
+    def barycentric(self, **kwargs):
+        rng = np.random.default_rng(3458934594269824562)
+        x1, x2, y1 = rng.random((3, 10))
+        f = interpolate.BarycentricInterpolator(x1, y1, **kwargs)
+        return f(x2)
+
+    def clarkson_woodruff_transform(self, **kwargs):
+        rng = np.random.default_rng(3458934594269824562)
+        return linalg.clarkson_woodruff_transform(rng.random((10, 10)), 3, **kwargs)
+
+    def basinhopping(self, **kwargs):
+        rng = np.random.default_rng(3458934594269824562)
+        return optimize.basinhopping(optimize.rosen, rng.random(3), **kwargs).x
+
+    def opt(self, fun, **kwargs):
+        rng = np.random.default_rng(3458934594269824562)
+        bounds = optimize.Bounds(-rng.random(3) * 10, rng.random(3) * 10)
+        return fun(optimize.rosen, bounds, **kwargs).x
+
+    def differential_evolution(self, **kwargs):
+        return self.opt(optimize.differential_evolution, **kwargs)
+
+    def dual_annealing(self, **kwargs):
+        return self.opt(optimize.dual_annealing, **kwargs)
+
+    def check_grad(self, **kwargs):
+        rng = np.random.default_rng(3458934594269824562)
+        x = rng.random(3)
+        return optimize.check_grad(optimize.rosen, optimize.rosen_der, x,
+                                   direction='random', **kwargs)
+
+    def random_array(self, **kwargs):
+        return sparse.random_array((10, 10), density=1.0, **kwargs).toarray()
+
+    def random(self, **kwargs):
+        return sparse.random(10, 10, density=1.0, **kwargs).toarray()
+
+    def rand(self, **kwargs):
+        return sparse.rand(10, 10, density=1.0, **kwargs).toarray()
+
+    def svds(self, **kwargs):
+        rng = np.random.default_rng(3458934594269824562)
+        A = rng.random((10, 10))
+        return sparse.linalg.svds(A, **kwargs)
+
+    def random_rotation(self, **kwargs):
+        return spatial.transform.Rotation.random(3, **kwargs).as_matrix()
+
+    def goodness_of_fit(self, **kwargs):
+        rng = np.random.default_rng(3458934594269824562)
+        data = rng.random(100)
+        return stats.goodness_of_fit(stats.laplace, data, **kwargs).pvalue
+
+    def permutation_test(self, **kwargs):
+        rng = np.random.default_rng(3458934594269824562)
+        data = tuple(rng.random((2, 100)))
+        def statistic(x, y, axis): return np.mean(x, axis=axis) - np.mean(y, axis=axis)
+        return stats.permutation_test(data, statistic, **kwargs).pvalue
+
+    def bootstrap(self, **kwargs):
+        rng = np.random.default_rng(3458934594269824562)
+        data = (rng.random(100),)
+        return stats.bootstrap(data, np.mean, **kwargs).confidence_interval
+
+    def dunnett(self, **kwargs):
+        rng = np.random.default_rng(3458934594269824562)
+        x, y, control = rng.random((3, 100))
+        return stats.dunnett(x, y, control=control, **kwargs).pvalue
+
+    def sobol_indices(self, **kwargs):
+        def f_ishigami(x): return (np.sin(x[0]) + 7 * np.sin(x[1]) ** 2
+                                   + 0.1 * (x[2] ** 4) * np.sin(x[0]))
+        dists = [stats.uniform(loc=-np.pi, scale=2 * np.pi),
+                 stats.uniform(loc=-np.pi, scale=2 * np.pi),
+                 stats.uniform(loc=-np.pi, scale=2 * np.pi)]
+        res = stats.sobol_indices(func=f_ishigami, n=1024, dists=dists, **kwargs)
+        return res.first_order
+
+    def qmc_engine(self, engine, **kwargs):
+        qrng = engine(d=1, **kwargs)
+        return qrng.random(4)
+
+    def halton(self, **kwargs):
+        return self.qmc_engine(stats.qmc.Halton, **kwargs)
+
+    def sobol(self, **kwargs):
+        return self.qmc_engine(stats.qmc.Sobol, **kwargs)
+
+    def latin_hypercube(self, **kwargs):
+        return self.qmc_engine(stats.qmc.LatinHypercube, **kwargs)
+
+    def poisson_disk(self, **kwargs):
+        return self.qmc_engine(stats.qmc.PoissonDisk, **kwargs)
+
+    def multivariate_normal_qmc(self, **kwargs):
+        X = stats.qmc.MultivariateNormalQMC([0], **kwargs)
+        return X.random(4)
+
+    def multinomial_qmc(self, **kwargs):
+        X = stats.qmc.MultinomialQMC([0.5, 0.5], 4, **kwargs)
+        return X.random(4)
+
+    def permutation_method(self, **kwargs):
+        rng = np.random.default_rng(3458934594269824562)
+        data = tuple(rng.random((2, 100)))
+        method = stats.PermutationMethod(**kwargs)
+        return stats.pearsonr(*data, method=method).pvalue
+
+    def bootstrap_method(self, **kwargs):
+        rng = np.random.default_rng(3458934594269824562)
+        data = tuple(rng.random((2, 100)))
+        res = stats.pearsonr(*data)
+        method = stats.BootstrapMethod(**kwargs)
+        return res.confidence_interval(method=method)
+
+    @pytest.mark.fail_slow(10)
+    @pytest.mark.slow
+    @pytest.mark.parametrize("method, arg_name", [
+        (kmeans, "seed"),
+        (kmeans2, "seed"),
+        (barycentric, "random_state"),
+        (clarkson_woodruff_transform, "seed"),
+        (basinhopping, "seed"),
+        (differential_evolution, "seed"),
+        (dual_annealing, "seed"),
+        (check_grad, "seed"),
+        (random_array, 'random_state'),
+        (random, 'random_state'),
+        (rand, 'random_state'),
+        (random_rotation, "random_state"),
+        (goodness_of_fit, "random_state"),
+        (permutation_test, "random_state"),
+        (bootstrap, "random_state"),
+        (permutation_method, "random_state"),
+        (bootstrap_method, "random_state"),
+        (dunnett, "random_state"),
+        (sobol_indices, "random_state"),
+        (halton, "seed"),
+        (sobol, "seed"),
+        (latin_hypercube, "seed"),
+        (poisson_disk, "seed"),
+        (multivariate_normal_qmc, "seed"),
+        (multinomial_qmc, "seed"),
+    ])
+    def test_rng_deterministic(self, method, arg_name):
+        np.random.seed(None)
+        seed = 2949672964
+
+        rng = np.random.default_rng(seed)
+        message = "got multiple values for argument now known as `rng`"
+        with pytest.raises(TypeError, match=message):
+            method(self, **{'rng': rng, arg_name: seed})
+
+        rng = np.random.default_rng(seed)
+        res1 = method(self, rng=rng)
+        res2 = method(self, rng=seed)
+        assert_equal(res2, res1)
+
+        if method.__name__ in {"dunnett", "sobol_indices"}:
+            # the two kwargs have essentially the same behavior for these functions
+            res3 = method(self, **{arg_name: seed})
+            assert_equal(res3, res1)
+            return
+
+        rng = np.random.RandomState(seed)
+        res1 = method(self, **{arg_name: rng})
+        res2 = method(self, **{arg_name: seed})
+
+        if method.__name__ in {"halton", "sobol", "latin_hypercube", "poisson_disk",
+                               "multivariate_normal_qmc", "multinomial_qmc"}:
+            # For these, passing `random_state=RandomState(seed)` is not the same as
+            # passing integer `seed`.
+            res1b = method(self, **{arg_name: np.random.RandomState(seed)})
+            assert_equal(res1b, res1)
+            res2b = method(self, **{arg_name: seed})
+            assert_equal(res2b, res2)
+            return
+
+        np.random.seed(seed)
+        res3 = method(self, **{arg_name: None})
+        assert_equal(res2, res1)
+        assert_equal(res3, res1)
diff --git a/.venv/lib/python3.12/site-packages/scipy/_lib/tests/test_array_api.py b/.venv/lib/python3.12/site-packages/scipy/_lib/tests/test_array_api.py
new file mode 100644
index 0000000000000000000000000000000000000000..cb0811e791dc808e1e6b7cd39787b31517bf0254
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/_lib/tests/test_array_api.py
@@ -0,0 +1,373 @@
+import re
+
+import numpy as np
+import pytest
+
+from scipy._lib._array_api import (
+    SCIPY_ARRAY_API, array_namespace, _asarray, xp_copy, xp_assert_equal, is_numpy,
+    np_compat, xp_default_dtype, xp_result_type, is_torch, _xp_copy_to_numpy
+)
+from scipy._external import array_api_extra as xpx
+from scipy._lib._array_api_no_0d import xp_assert_equal as xp_assert_equal_no_0d
+from scipy._external.array_api_extra.testing import lazy_xp_function
+
+# Run all tests in this module in the Array API CI,
+# including those without the `xp` fixture
+pytestmark = pytest.mark.array_api_backends
+
+lazy_xp_function(_asarray)
+lazy_xp_function(xp_copy)
+
+
+@pytest.mark.uses_xp_capabilities(False, reason="not applicable")
+@pytest.mark.skipif(not SCIPY_ARRAY_API,
+        reason="Array API test; set environment variable SCIPY_ARRAY_API=1 to run it")
+class TestArrayAPI:
+
+    def test_array_namespace(self):
+        x, y = np.array([0, 1, 2]), np.array([0, 1, 2])
+        xp = array_namespace(x, y)
+        assert 'array_api_compat.numpy' in xp.__name__
+
+    def test_asarray(self, xp):
+        x, y = _asarray([0, 1, 2], xp=xp), _asarray(np.arange(3), xp=xp)
+        ref = xp.asarray([0, 1, 2])
+        xp_assert_equal(x, ref)
+        xp_assert_equal(y, ref)
+
+    @pytest.mark.filterwarnings("ignore: the matrix subclass")
+    def test_raises(self):
+        msg = "of type `numpy.ma.MaskedArray` are not supported"
+        with pytest.raises(TypeError, match=msg):
+            array_namespace(np.ma.array(1), np.array(1))
+
+        msg = "of type `numpy.matrix` are not supported"
+        with pytest.raises(TypeError, match=msg):
+            array_namespace(np.array(1), np.matrix(1))
+
+        msg = "only boolean and numerical dtypes are supported"
+        with pytest.raises(TypeError, match=msg):
+            array_namespace([object()])
+        with pytest.raises(TypeError, match=msg):
+            array_namespace('abc')
+
+    @pytest.mark.skip_xp_backends(np_only=True, reason="Array-likes")
+    def test_array_likes(self, xp):
+        """Test that if all parameters of array_namespace are Array-likes,
+        the output is array_api_compat.numpy
+        """
+        assert array_namespace([0, 1, 2]) is xp
+        assert array_namespace((0, 1, 2)) is xp
+        assert array_namespace(1, 2, 3) is xp
+        assert array_namespace(1) is xp
+        assert array_namespace(np.int64(1)) is xp
+        assert array_namespace([0, 1, 2], 3) is xp
+        assert array_namespace() is xp
+        assert array_namespace(None) is xp
+        assert array_namespace(1, None) is xp
+        assert array_namespace(None, 1) is xp
+
+        # This only works when xp is numpy!
+        assert array_namespace(np.asarray([1, 2]), [3, 4]) is xp
+        assert array_namespace(np.int64(1), [3, 4]) is xp
+
+    def test_array_and_array_likes_mix(self, xp):
+        """Test that if there is at least one Array API object among
+        the parameters of array_namespace, and all other parameters
+        are scalars, the output is its namespace.
+
+        If there are non-scalar Array-Likes, raise as in array-api-compat.
+        """
+        x = xp.asarray(1)
+        assert array_namespace(x) is xp
+        assert array_namespace(x, 1) is xp
+        assert array_namespace(1, x) is xp
+        assert array_namespace(None, x) is xp
+
+        if is_numpy(xp):
+            assert array_namespace(x, [1, 2]) is xp
+        else:
+            with pytest.raises(TypeError, match="Multiple namespaces"):
+                array_namespace(x, [1, 2])
+            with pytest.raises(TypeError, match="Multiple namespaces"):
+                array_namespace(x, np.int64(1))
+            with pytest.raises(TypeError, match="Multiple namespaces"):
+                 # Subclass of float; matches array_api_compat behavior
+                array_namespace(x, np.float64(1))
+            with pytest.raises(TypeError, match="Multiple namespaces"):
+                # Subclass of complex; matches array_api_compat behavior
+                array_namespace(x, np.complex128(1))
+
+    def test_array_api_extra_hook(self):
+        """Test that the `array_namespace` function used by
+        array-api-extra has been overridden by scipy
+        """
+        msg = "only boolean and numerical dtypes are supported"
+        with pytest.raises(TypeError, match=msg):
+            xpx.atleast_nd("abc", ndim=0)
+
+    def test_jax_zero_gradient_array(self):
+        """Test array_namespace special case for JAX zero-gradient arrays, which are
+        numpy arrays but must be treated as JAX arrays.
+        See matching code and tests in array_api_compat.
+        """
+        jax = pytest.importorskip("jax")
+        xp = pytest.importorskip("jax.numpy")
+        # Create numpy array with dtype=jax.float0
+        jax_zero = jax.vmap(jax.grad(xp.float32, allow_int=True))(xp.arange(4))
+        assert array_namespace(jax_zero) is xp
+
+    def test_void_but_not_jax_zero_gradient_array(self):
+        """A void dtype that is not a jax.float0 must not be caught in the
+        special case for JAX zero-gradient arrays.
+        """
+        void = np.empty(0, dtype=np.dtype([]))
+        with pytest.raises(TypeError, match="only boolean and numerical dtypes"):
+            array_namespace(void)
+        with pytest.raises(TypeError, match="only boolean and numerical dtypes"):
+            array_namespace([void, void])
+
+    def test_copy(self, xp):
+        for _xp in [xp, None]:
+            x = xp.asarray([1, 2, 3])
+            y = xp_copy(x, xp=_xp)
+            # with numpy we'd want to use np.shared_memory, but that's not specified
+            # in the array-api
+            assert id(x) != id(y)
+            try:
+                y[0] = 10
+            except (TypeError, ValueError):
+                pass
+            else:
+                assert x[0] != y[0]
+
+    @pytest.mark.parametrize(
+        "dtype",
+        ["float32", "float64", "complex64", "complex128", "int32", "int64"],
+    )
+    @pytest.mark.parametrize(
+        "data", [[], 1, [1, 2, 3], [[1, 2], [2, 3]]],
+    )
+    def test_copy_to_numpy(self, xp, data, dtype):
+        xp_dtype = getattr(xp, dtype)
+        np_dtype = getattr(np, dtype)
+        x = xp.asarray(data, dtype=xp_dtype)
+        y = _xp_copy_to_numpy(x)
+        assert isinstance(y, np.ndarray)
+        assert y.dtype == np_dtype
+        assert x.shape == y.shape
+        np.testing.assert_equal(y, np.asarray(data, dtype=np_dtype))
+        if is_numpy(xp):
+            # Ensure y is a copy when xp is numpy.
+            assert id(x) != id(y)
+
+    
+    @pytest.mark.parametrize('dtype', ['int32', 'int64', 'float32', 'float64'])
+    @pytest.mark.parametrize('shape', [(), (3,)])
+    def test_strict_checks(self, xp, dtype, shape):
+        # Check that `_strict_check` behaves as expected
+        dtype = getattr(xp, dtype)
+        x = xp.broadcast_to(xp.asarray(1, dtype=dtype), shape)
+        x = x if shape else x[()]
+        y = np_compat.asarray(1)[()]
+
+        kwarg_names = ["check_namespace", "check_dtype", "check_shape", "check_0d"]
+        options = dict(zip(kwarg_names, [True, False, False, False]))
+        if is_numpy(xp):
+            xp_assert_equal(x, y, **options)
+        else:
+            with pytest.raises(
+                AssertionError,
+                match="Namespace of desired array does not match",
+            ):
+                xp_assert_equal(x, y, **options)
+            with pytest.raises(
+                AssertionError,
+                match="Namespace of actual and desired arrays do not match",
+            ):
+                xp_assert_equal(y, x, **options)
+
+        options = dict(zip(kwarg_names, [False, True, False, False]))
+        if y.dtype.name in str(x.dtype):
+            xp_assert_equal(x, y, **options)
+        else:
+            with pytest.raises(AssertionError, match="dtypes do not match."):
+                xp_assert_equal(x, y, **options)
+
+        options = dict(zip(kwarg_names, [False, False, True, False]))
+        if x.shape == y.shape:
+            xp_assert_equal(x, y, **options)
+        else:
+            with pytest.raises(AssertionError, match="Shapes do not match."):
+                xp_assert_equal(x, xp.asarray(y), **options)
+
+        options = dict(zip(kwarg_names, [False, False, False, True]))
+        if is_numpy(xp) and x.shape == y.shape:
+            xp_assert_equal(x, y, **options)
+        elif is_numpy(xp):
+            with pytest.raises(AssertionError, match="Array-ness does not match."):
+                xp_assert_equal(x, y, **options)
+
+    @pytest.mark.skip_xp_backends(np_only=True, reason="Scalars only exist in NumPy")
+    def test_check_scalar(self, xp):
+        # identity always passes
+        xp_assert_equal(xp.float64(0), xp.float64(0))
+        xp_assert_equal(xp.asarray(0.), xp.asarray(0.))
+        xp_assert_equal(xp.float64(0), xp.float64(0), check_0d=False)
+        xp_assert_equal(xp.asarray(0.), xp.asarray(0.), check_0d=False)
+
+        # Check default convention: 0d-arrays are distinguished from scalars
+        message = "Array-ness does not match:.*"
+        with pytest.raises(AssertionError, match=message):
+            xp_assert_equal(xp.asarray(0.), xp.float64(0))
+        with pytest.raises(AssertionError, match=message):
+            xp_assert_equal(xp.float64(0), xp.asarray(0.))
+        with pytest.raises(AssertionError, match=message):
+            xp_assert_equal(xp.asarray(42), xp.int64(42))
+        with pytest.raises(AssertionError, match=message):
+            xp_assert_equal(xp.int64(42), xp.asarray(42))
+
+        # with `check_0d=False`, scalars-vs-0d passes (if values match)
+        xp_assert_equal(xp.asarray(0.), xp.float64(0), check_0d=False)
+        xp_assert_equal(xp.float64(0), xp.asarray(0.), check_0d=False)
+        # also with regular python objects
+        xp_assert_equal(xp.asarray(0.), 0., check_0d=False)
+        xp_assert_equal(0., xp.asarray(0.), check_0d=False)
+        xp_assert_equal(xp.asarray(42), 42, check_0d=False)
+        xp_assert_equal(42, xp.asarray(42), check_0d=False)
+
+        # as an alternative to `check_0d=False`, explicitly expect scalar
+        xp_assert_equal(xp.float64(0), xp.asarray(0.)[()])
+
+    @pytest.mark.skip_xp_backends(np_only=True, reason="Scalars only exist in NumPy")
+    def test_check_scalar_no_0d(self, xp):
+        # identity passes, if first argument is not 0d (or check_0d=True)
+        xp_assert_equal_no_0d(xp.float64(0), xp.float64(0))
+        xp_assert_equal_no_0d(xp.float64(0), xp.float64(0), check_0d=True)
+        xp_assert_equal_no_0d(xp.asarray(0.), xp.asarray(0.), check_0d=True)
+
+        # by default, 0d values are forbidden as the first argument
+        message = "Result is a NumPy 0d-array.*"
+        with pytest.raises(AssertionError, match=message):
+            xp_assert_equal_no_0d(xp.asarray(0.), xp.asarray(0.))
+        with pytest.raises(AssertionError, match=message):
+            xp_assert_equal_no_0d(xp.asarray(0.), xp.float64(0))
+        with pytest.raises(AssertionError, match=message):
+            xp_assert_equal_no_0d(xp.asarray(42), xp.int64(42))
+
+        # Check default convention: 0d-arrays are NOT distinguished from scalars
+        xp_assert_equal_no_0d(xp.float64(0), xp.asarray(0.))
+        xp_assert_equal_no_0d(xp.int64(42), xp.asarray(42))
+
+        # opt in to 0d-check remains possible
+        message = "Array-ness does not match:.*"
+        with pytest.raises(AssertionError, match=message):
+            xp_assert_equal_no_0d(xp.asarray(0.), xp.float64(0), check_0d=True)
+        with pytest.raises(AssertionError, match=message):
+            xp_assert_equal_no_0d(xp.float64(0), xp.asarray(0.), check_0d=True)
+        with pytest.raises(AssertionError, match=message):
+            xp_assert_equal_no_0d(xp.asarray(42), xp.int64(0), check_0d=True)
+        with pytest.raises(AssertionError, match=message):
+            xp_assert_equal_no_0d(xp.int64(0), xp.asarray(42), check_0d=True)
+
+        # scalars-vs-0d passes (if values match) also with regular python objects
+        xp_assert_equal_no_0d(0., xp.asarray(0.))
+        xp_assert_equal_no_0d(42, xp.asarray(42))
+
+    def test_default_dtype(self, xp):
+        assert xp_default_dtype(xp) == xp.asarray(1.).dtype
+
+
+scalars = [1, 1., 1. + 1j]
+lists = [[1], [1.], [1. + 1j]]
+types = ('int8 int16 int32 int64 '
+         'uint8 uint16 uint32 uint64 '
+         'float32 float64 complex64 complex128').split()
+arrays = [np.asarray([1], dtype=getattr(np, t)) for t in types]
+
+
+def convert_type(x, xp):
+    # Convert NumPy array to xp-array
+    # Convert string to indicated dtype from xp
+    # Return Python scalars unchanged
+    if isinstance(x, np.ndarray):
+        return xp.asarray(x)
+    elif isinstance(x, str):
+        return getattr(xp, x)
+    return x
+
+
+def is_inexact(x, xp):
+    # Determine whether `x` is of inexact (real of complex floating) dtype
+    x = xp.asarray(x) if np.isscalar(x) or isinstance(x, list) else x
+    dtype = getattr(x, 'dtype', x)
+    return xp.isdtype(dtype, ('real floating', 'complex floating'))
+
+
+@pytest.mark.parametrize('x', scalars + lists + types + arrays)
+@pytest.mark.parametrize('y', scalars + lists + types + arrays)
+@pytest.mark.uses_xp_capabilities(False, reason="not applicable")
+def test_xp_result_type_no_force(x, y, xp):
+    # When force_floating==False (default), behavior of `xp_result_type`
+    # should match that of `xp.result_type` on the same arguments after
+    # converting lists to arrays of type `xp`.
+    x = convert_type(x, xp)
+    y = convert_type(y, xp)
+    x_ref = xp.asarray(x) if isinstance(x, list) else x
+    y_ref = xp.asarray(y) if isinstance(y, list) else y
+
+    try:
+        dtype_ref = xp.result_type(x_ref, y_ref)
+        expected_error = None
+    except Exception as e:
+        expected_error = (type(e), str(e))
+
+    if expected_error is not None:
+        with pytest.raises(expected_error[0], match=re.escape(expected_error[1])):
+            xp_result_type(x, y, xp=xp)
+        return
+
+    dtype_res = xp_result_type(x, y, xp=xp)
+    assert dtype_res == dtype_ref
+
+
+@pytest.mark.parametrize('x', scalars + lists + types + arrays)
+@pytest.mark.parametrize('y', scalars + lists + types + arrays)
+@pytest.mark.uses_xp_capabilities(False, reason="not applicable")
+def test_xp_result_type_force_floating(x, y, xp):
+    # When `force_floating==True`, behavior of `xp_result_type`
+    # should match that of `xp.result_type` with `1.0` appended to the set of
+    # arguments (after converting lists to arrays of type `xp`).
+    # If this raises a `TypeError`, which is the case when the result
+    # type is not defined by the standard, the result type should be
+    # the result type of any inexact (real or complex floating) arguments
+    # and the default floating point type.
+    if (is_torch(xp) and not(isinstance(x, str) or isinstance(y, str))
+            and np.isscalar(x) and np.isscalar(y)):
+        pytest.skip("See 3/27/2024 comment at  data-apis/array-api-compat#277")
+
+    x = convert_type(x, xp)
+    y = convert_type(y, xp)
+    x_ref = xp.asarray(x) if isinstance(x, list) else x
+    y_ref = xp.asarray(y) if isinstance(y, list) else y
+
+    expected_error = None
+    try:
+        dtype_ref = xp.result_type(x_ref, y_ref, 1.0)
+    except TypeError:
+        args = []
+        if is_inexact(x_ref, xp):
+            args.append(x_ref)
+        if is_inexact(y_ref, xp):
+            args.append(y_ref)
+        dtype_ref = xp.result_type(*args, xp.asarray(1.0))
+    except Exception as e:
+        expected_error = (type(e), str(e))
+
+    if expected_error is not None:
+        with pytest.raises(expected_error[0], match=expected_error[1]):
+            xp_result_type(x, y, xp=xp)
+        return
+
+    dtype_res = xp_result_type(x, y, force_floating=True, xp=xp)
+    assert dtype_res == dtype_ref
diff --git a/.venv/lib/python3.12/site-packages/scipy/_lib/tests/test_bunch.py b/.venv/lib/python3.12/site-packages/scipy/_lib/tests/test_bunch.py
new file mode 100644
index 0000000000000000000000000000000000000000..96008627e3afef540913071c95ea543c718a326c
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/_lib/tests/test_bunch.py
@@ -0,0 +1,169 @@
+import pytest
+import pickle
+from numpy.testing import assert_equal
+from scipy._lib._bunch import _make_tuple_bunch
+
+
+# `Result` is defined at the top level of the module so it can be
+# used to test pickling.
+Result = _make_tuple_bunch('Result', ['x', 'y', 'z'], ['w', 'beta'])
+
+
+class TestMakeTupleBunch:
+
+    # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
+    # Tests with Result
+    # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
+
+    def setup_method(self):
+        # Set up an instance of Result.
+        self.result = Result(x=1, y=2, z=3, w=99, beta=0.5)
+
+    def test_attribute_access(self):
+        assert_equal(self.result.x, 1)
+        assert_equal(self.result.y, 2)
+        assert_equal(self.result.z, 3)
+        assert_equal(self.result.w, 99)
+        assert_equal(self.result.beta, 0.5)
+
+    def test_indexing(self):
+        assert_equal(self.result[0], 1)
+        assert_equal(self.result[1], 2)
+        assert_equal(self.result[2], 3)
+        assert_equal(self.result[-1], 3)
+        with pytest.raises(IndexError, match='index out of range'):
+            self.result[3]
+
+    def test_unpacking(self):
+        x0, y0, z0 = self.result
+        assert_equal((x0, y0, z0), (1, 2, 3))
+        assert_equal(self.result, (1, 2, 3))
+
+    def test_slice(self):
+        assert_equal(self.result[1:], (2, 3))
+        assert_equal(self.result[::2], (1, 3))
+        assert_equal(self.result[::-1], (3, 2, 1))
+
+    def test_len(self):
+        assert_equal(len(self.result), 3)
+
+    def test_repr(self):
+        s = repr(self.result)
+        assert_equal(s, 'Result(x=1, y=2, z=3, w=99, beta=0.5)')
+
+    def test_hash(self):
+        assert_equal(hash(self.result), hash((1, 2, 3)))
+
+    def test_pickle(self):
+        s = pickle.dumps(self.result)
+        obj = pickle.loads(s)
+        assert isinstance(obj, Result)
+        assert_equal(obj.x, self.result.x)
+        assert_equal(obj.y, self.result.y)
+        assert_equal(obj.z, self.result.z)
+        assert_equal(obj.w, self.result.w)
+        assert_equal(obj.beta, self.result.beta)
+
+    def test_read_only_existing(self):
+        with pytest.raises(AttributeError, match="can't set attribute"):
+            self.result.x = -1
+
+    def test_read_only_new(self):
+        self.result.plate_of_shrimp = "lattice of coincidence"
+        assert self.result.plate_of_shrimp == "lattice of coincidence"
+
+    def test_constructor_missing_parameter(self):
+        with pytest.raises(TypeError, match='missing'):
+            # `w` is missing.
+            Result(x=1, y=2, z=3, beta=0.75)
+
+    def test_constructor_incorrect_parameter(self):
+        with pytest.raises(TypeError, match='unexpected'):
+            # `foo` is not an existing field.
+            Result(x=1, y=2, z=3, w=123, beta=0.75, foo=999)
+
+    def test_module(self):
+        m = 'scipy._lib.tests.test_bunch'
+        assert_equal(Result.__module__, m)
+        assert_equal(self.result.__module__, m)
+
+    def test_extra_fields_per_instance(self):
+        # This test exists to ensure that instances of the same class
+        # store their own values for the extra fields. That is, the values
+        # are stored per instance and not in the class.
+        result1 = Result(x=1, y=2, z=3, w=-1, beta=0.0)
+        result2 = Result(x=4, y=5, z=6, w=99, beta=1.0)
+        assert_equal(result1.w, -1)
+        assert_equal(result1.beta, 0.0)
+        # The rest of these checks aren't essential, but let's check
+        # them anyway.
+        assert_equal(result1[:], (1, 2, 3))
+        assert_equal(result2.w, 99)
+        assert_equal(result2.beta, 1.0)
+        assert_equal(result2[:], (4, 5, 6))
+
+    # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
+    # Other tests
+    # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
+
+    def test_extra_field_names_is_optional(self):
+        Square = _make_tuple_bunch('Square', ['width', 'height'])
+        sq = Square(width=1, height=2)
+        assert_equal(sq.width, 1)
+        assert_equal(sq.height, 2)
+        s = repr(sq)
+        assert_equal(s, 'Square(width=1, height=2)')
+
+    def test_tuple_like(self):
+        Tup = _make_tuple_bunch('Tup', ['a', 'b'])
+        tu = Tup(a=1, b=2)
+        assert isinstance(tu, tuple)
+        assert isinstance(tu + (1,), tuple)
+
+    def test_explicit_module(self):
+        m = 'some.module.name'
+        Foo = _make_tuple_bunch('Foo', ['x'], ['a', 'b'], module=m)
+        foo = Foo(x=1, a=355, b=113)
+        assert_equal(Foo.__module__, m)
+        assert_equal(foo.__module__, m)
+
+    def test_passes_polars_checks(self):
+        # gh-22450
+        Square = _make_tuple_bunch('Square', ['width', 'height'])
+        assert hasattr(Square, '_replace')
+        assert hasattr(Square, '_field_defaults')
+
+
+    # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
+    # Argument validation
+    # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
+
+    @pytest.mark.parametrize('args', [('123', ['a'], ['b']),
+                                      ('Foo', ['-3'], ['x']),
+                                      ('Foo', ['a'], ['+-*/'])])
+    def test_identifiers_not_allowed(self, args):
+        with pytest.raises(ValueError, match='identifiers'):
+            _make_tuple_bunch(*args)
+
+    @pytest.mark.parametrize('args', [('Foo', ['a', 'b', 'a'], ['x']),
+                                      ('Foo', ['a', 'b'], ['b', 'x'])])
+    def test_repeated_field_names(self, args):
+        with pytest.raises(ValueError, match='Duplicate'):
+            _make_tuple_bunch(*args)
+
+    @pytest.mark.parametrize('args', [('Foo', ['_a'], ['x']),
+                                      ('Foo', ['a'], ['_x'])])
+    def test_leading_underscore_not_allowed(self, args):
+        with pytest.raises(ValueError, match='underscore'):
+            _make_tuple_bunch(*args)
+
+    @pytest.mark.parametrize('args', [('Foo', ['def'], ['x']),
+                                      ('Foo', ['a'], ['or']),
+                                      ('and', ['a'], ['x'])])
+    def test_keyword_not_allowed_in_fields(self, args):
+        with pytest.raises(ValueError, match='keyword'):
+            _make_tuple_bunch(*args)
+
+    def test_at_least_one_field_name_required(self):
+        with pytest.raises(ValueError, match='at least one name'):
+            _make_tuple_bunch('Qwerty', [], ['a', 'b'])
diff --git a/.venv/lib/python3.12/site-packages/scipy/_lib/tests/test_ccallback.py b/.venv/lib/python3.12/site-packages/scipy/_lib/tests/test_ccallback.py
new file mode 100644
index 0000000000000000000000000000000000000000..e8a2c97c6f67732f55eea6ed5cad297f5068a714
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/_lib/tests/test_ccallback.py
@@ -0,0 +1,196 @@
+from numpy.testing import assert_equal, assert_
+from pytest import raises as assert_raises
+
+import time
+import pytest
+import ctypes
+import threading
+from scipy._lib import _ccallback_c as _test_ccallback_cython
+from scipy._lib import _test_ccallback
+from scipy._lib._ccallback import LowLevelCallable
+
+
+ERROR_VALUE = 2.0
+
+
+def callback_python(a, user_data=None):
+    if a == ERROR_VALUE:
+        raise ValueError("bad value")
+
+    if user_data is None:
+        return a + 1
+    else:
+        return a + user_data
+
+def _get_cffi_func(base, signature):
+    cffi = pytest.importorskip("cffi")
+
+    # Get function address
+    voidp = ctypes.cast(base, ctypes.c_void_p)
+    address = voidp.value
+
+    # Create corresponding cffi handle
+    ffi = cffi.FFI()
+    func = ffi.cast(signature, address)
+    return func
+
+
+def _get_ctypes_data():
+    value = ctypes.c_double(2.0)
+    return ctypes.cast(ctypes.pointer(value), ctypes.c_voidp)
+
+
+def _get_cffi_data():
+    cffi = pytest.importorskip("cffi")
+    ffi = cffi.FFI()
+    return ffi.new('double *', 2.0)
+
+
+CALLERS = {
+    'simple': _test_ccallback.test_call_simple,
+    'nodata': _test_ccallback.test_call_nodata,
+    'nonlocal': _test_ccallback.test_call_nonlocal,
+    'cython': _test_ccallback_cython.test_call_cython,
+}
+
+# These functions have signatures known to the callers
+FUNCS = {
+    'python': lambda: callback_python,
+    'capsule': lambda: _test_ccallback.test_get_plus1_capsule(),
+    'cython': lambda: LowLevelCallable.from_cython(_test_ccallback_cython,
+                                                   "plus1_cython"),
+    'ctypes': lambda: _test_ccallback_cython.plus1_ctypes,
+    'cffi': lambda: _get_cffi_func(_test_ccallback_cython.plus1_ctypes,
+                                   'double (*)(double, int *, void *)'),
+    'capsule_b': lambda: _test_ccallback.test_get_plus1b_capsule(),
+    'cython_b': lambda: LowLevelCallable.from_cython(_test_ccallback_cython,
+                                                     "plus1b_cython"),
+    'ctypes_b': lambda: _test_ccallback_cython.plus1b_ctypes,
+    'cffi_b': lambda: _get_cffi_func(_test_ccallback_cython.plus1b_ctypes,
+                                     'double (*)(double, double, int *, void *)'),
+}
+
+# These functions have signatures the callers don't know
+BAD_FUNCS = {
+    'capsule_bc': lambda: _test_ccallback.test_get_plus1bc_capsule(),
+    'cython_bc': lambda: LowLevelCallable.from_cython(_test_ccallback_cython,
+                                                      "plus1bc_cython"),
+    'ctypes_bc': lambda: _test_ccallback_cython.plus1bc_ctypes,
+    'cffi_bc': lambda: _get_cffi_func(
+        _test_ccallback_cython.plus1bc_ctypes,
+        'double (*)(double, double, double, int *, void *)'
+    ),
+}
+
+USER_DATAS = {
+    'ctypes': _get_ctypes_data,
+    'cffi': _get_cffi_data,
+    'capsule': _test_ccallback.test_get_data_capsule,
+}
+
+
+def test_callbacks():
+    def check(caller, func, user_data):
+        caller = CALLERS[caller]
+        func = FUNCS[func]()
+        user_data = USER_DATAS[user_data]()
+
+        if func is callback_python:
+            def func2(x):
+                return func(x, 2.0)
+        else:
+            func2 = LowLevelCallable(func, user_data)
+            func = LowLevelCallable(func)
+
+        # Test basic call
+        assert_equal(caller(func, 1.0), 2.0)
+
+        # Test 'bad' value resulting to an error
+        assert_raises(ValueError, caller, func, ERROR_VALUE)
+
+        # Test passing in user_data
+        assert_equal(caller(func2, 1.0), 3.0)
+
+    for caller in sorted(CALLERS.keys()):
+        for func in sorted(FUNCS.keys()):
+            for user_data in sorted(USER_DATAS.keys()):
+                check(caller, func, user_data)
+
+
+def test_bad_callbacks():
+    def check(caller, func, user_data):
+        caller = CALLERS[caller]
+        user_data = USER_DATAS[user_data]()
+        func = BAD_FUNCS[func]()
+
+        if func is callback_python:
+            def func2(x):
+                return func(x, 2.0)
+        else:
+            func2 = LowLevelCallable(func, user_data)
+            func = LowLevelCallable(func)
+
+        # Test that basic call fails
+        assert_raises(ValueError, caller, LowLevelCallable(func), 1.0)
+
+        # Test that passing in user_data also fails
+        assert_raises(ValueError, caller, func2, 1.0)
+
+        # Test error message
+        llfunc = LowLevelCallable(func)
+        try:
+            caller(llfunc, 1.0)
+        except ValueError as err:
+            msg = str(err)
+            assert_(llfunc.signature in msg, msg)
+            assert_('double (double, double, int *, void *)' in msg, msg)
+
+    for caller in sorted(CALLERS.keys()):
+        for func in sorted(BAD_FUNCS.keys()):
+            for user_data in sorted(USER_DATAS.keys()):
+                check(caller, func, user_data)
+
+
+def test_signature_override():
+    caller = _test_ccallback.test_call_simple
+    func = _test_ccallback.test_get_plus1_capsule()
+
+    llcallable = LowLevelCallable(func, signature="bad signature")
+    assert_equal(llcallable.signature, "bad signature")
+    assert_raises(ValueError, caller, llcallable, 3)
+
+    llcallable = LowLevelCallable(func, signature="double (double, int *, void *)")
+    assert_equal(llcallable.signature, "double (double, int *, void *)")
+    assert_equal(caller(llcallable, 3), 4)
+
+
+def test_threadsafety():
+    def callback(a, caller):
+        if a <= 0:
+            return 1
+        else:
+            res = caller(lambda x: callback(x, caller), a - 1)
+            return 2*res
+
+    def check(caller):
+        caller = CALLERS[caller]
+
+        results = []
+
+        count = 10
+
+        def run():
+            time.sleep(0.01)
+            r = caller(lambda x: callback(x, caller), count)
+            results.append(r)
+
+        threads = [threading.Thread(target=run) for j in range(20)]
+        for thread in threads:
+            thread.start()
+        for thread in threads:
+            thread.join()
+
+        assert_equal(results, [2.0**count]*len(threads))
+
+    for caller in CALLERS.keys():
+        check(caller)
diff --git a/.venv/lib/python3.12/site-packages/scipy/_lib/tests/test_config.py b/.venv/lib/python3.12/site-packages/scipy/_lib/tests/test_config.py
new file mode 100644
index 0000000000000000000000000000000000000000..b43d3f9f0da39a86b78cb2210cb21d670e5cf978
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/_lib/tests/test_config.py
@@ -0,0 +1,44 @@
+"""
+Check the SciPy config is valid.
+"""
+import scipy
+import pytest
+from unittest.mock import patch
+
+pytestmark = pytest.mark.skipif(
+    not hasattr(scipy.__config__, "_built_with_meson"),
+    reason="Requires Meson builds",
+)
+
+
+class TestSciPyConfigs:
+    REQUIRED_CONFIG_KEYS = [
+        "Compilers",
+        "Machine Information",
+        "Python Information",
+    ]
+
+    @patch("scipy.__config__._check_pyyaml")
+    def test_pyyaml_not_found(self, mock_yaml_importer):
+        mock_yaml_importer.side_effect = ModuleNotFoundError()
+        with pytest.warns(UserWarning):
+            scipy.show_config()
+
+    def test_dict_mode(self):
+        config = scipy.show_config(mode="dicts")
+
+        assert isinstance(config, dict)
+        assert all([key in config for key in self.REQUIRED_CONFIG_KEYS]), (
+            "Required key missing,"
+            " see index of `False` with `REQUIRED_CONFIG_KEYS`"
+        )
+
+    def test_invalid_mode(self):
+        with pytest.raises(AttributeError):
+            scipy.show_config(mode="foo")
+
+    def test_warn_to_add_tests(self):
+        assert len(scipy.__config__.DisplayModes) == 2, (
+            "New mode detected,"
+            " please add UT if applicable and increment this count"
+        )
diff --git a/.venv/lib/python3.12/site-packages/scipy/_lib/tests/test_deprecation.py b/.venv/lib/python3.12/site-packages/scipy/_lib/tests/test_deprecation.py
new file mode 100644
index 0000000000000000000000000000000000000000..36d4b671117ba54fa612e7de504382c238dc18ff
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/_lib/tests/test_deprecation.py
@@ -0,0 +1,10 @@
+import pytest
+
+@pytest.mark.thread_unsafe(reason="deprecate_cython_api is not thread-safe")
+def test_cython_api_deprecation():
+    match = ("`scipy._lib._test_deprecation_def.foo_deprecated` "
+             "is deprecated, use `foo` instead!\n"
+             "Deprecated in Scipy 42.0.0")
+    with pytest.warns(DeprecationWarning, match=match):
+        from .. import _test_deprecation_call
+    assert _test_deprecation_call.call() == (1, 1)
diff --git a/.venv/lib/python3.12/site-packages/scipy/_lib/tests/test_doccer.py b/.venv/lib/python3.12/site-packages/scipy/_lib/tests/test_doccer.py
new file mode 100644
index 0000000000000000000000000000000000000000..d351b12da33e0f873e71b6ab6c11fa3aff5e9430
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/_lib/tests/test_doccer.py
@@ -0,0 +1,144 @@
+''' Some tests for the documenting decorator and support functions '''
+
+import sys
+import warnings
+import pytest
+from numpy.testing import assert_equal
+
+from scipy._lib import doccer
+
+# python -OO strips docstrings
+DOCSTRINGS_STRIPPED = sys.flags.optimize > 1
+
+docstring = \
+"""Docstring
+    %(strtest1)s
+        %(strtest2)s
+     %(strtest3)s
+"""
+param_doc1 = \
+"""Another test
+   with some indent"""
+
+param_doc2 = \
+"""Another test, one line"""
+
+param_doc3 = \
+"""    Another test
+       with some indent"""
+
+doc_dict = {'strtest1':param_doc1,
+            'strtest2':param_doc2,
+            'strtest3':param_doc3}
+
+filled_docstring = \
+"""Docstring
+    Another test
+       with some indent
+        Another test, one line
+     Another test
+       with some indent
+"""
+
+
+def test_unindent():
+    with warnings.catch_warnings():
+        warnings.simplefilter("ignore", category=DeprecationWarning)
+        assert_equal(doccer.unindent_string(param_doc1), param_doc1)
+        assert_equal(doccer.unindent_string(param_doc2), param_doc2)
+        assert_equal(doccer.unindent_string(param_doc3), param_doc1)
+
+
+def test_unindent_dict():
+    with warnings.catch_warnings():
+        warnings.simplefilter("ignore", category=DeprecationWarning)
+        d2 = doccer.unindent_dict(doc_dict)
+    assert_equal(d2['strtest1'], doc_dict['strtest1'])
+    assert_equal(d2['strtest2'], doc_dict['strtest2'])
+    assert_equal(d2['strtest3'], doc_dict['strtest1'])
+
+
+def test_docformat():
+    with warnings.catch_warnings():
+        warnings.simplefilter("ignore", category=DeprecationWarning)
+        udd = doccer.unindent_dict(doc_dict)
+        formatted = doccer.docformat(docstring, udd)
+        assert_equal(formatted, filled_docstring)
+        single_doc = 'Single line doc %(strtest1)s'
+        formatted = doccer.docformat(single_doc, doc_dict)
+        # Note - initial indent of format string does not
+        # affect subsequent indent of inserted parameter
+        assert_equal(formatted, """Single line doc Another test
+   with some indent""")
+
+
+@pytest.mark.skipif(DOCSTRINGS_STRIPPED, reason="docstrings stripped")
+def test_decorator():
+    with warnings.catch_warnings():
+        warnings.simplefilter("ignore", category=DeprecationWarning)
+        # with unindentation of parameters
+        decorator = doccer.filldoc(doc_dict, True)
+
+        @decorator
+        def func():
+            """ Docstring
+            %(strtest3)s
+            """
+
+        def expected():
+            """ Docstring
+            Another test
+               with some indent
+            """
+        assert_equal(func.__doc__, expected.__doc__)
+
+        # without unindentation of parameters
+
+        # The docstring should be unindented for Python 3.13+
+        # because of https://github.com/python/cpython/issues/81283
+        decorator = doccer.filldoc(doc_dict, False if \
+                                   sys.version_info < (3, 13) else True)
+
+        @decorator
+        def func():
+            """ Docstring
+            %(strtest3)s
+            """
+        def expected():
+            """ Docstring
+                Another test
+                   with some indent
+            """
+        assert_equal(func.__doc__, expected.__doc__)
+
+
+@pytest.mark.skipif(DOCSTRINGS_STRIPPED, reason="docstrings stripped")
+def test_inherit_docstring_from():
+
+    with warnings.catch_warnings():
+        warnings.simplefilter("ignore", category=DeprecationWarning)
+
+        class Foo:
+            def func(self):
+                '''Do something useful.'''
+                return
+
+            def func2(self):
+                '''Something else.'''
+
+        class Bar(Foo):
+            @doccer.inherit_docstring_from(Foo)
+            def func(self):
+                '''%(super)sABC'''
+                return
+
+            @doccer.inherit_docstring_from(Foo)
+            def func2(self):
+                # No docstring.
+                return
+
+    assert_equal(Bar.func.__doc__, Foo.func.__doc__ + 'ABC')
+    assert_equal(Bar.func2.__doc__, Foo.func2.__doc__)
+    bar = Bar()
+    assert_equal(bar.func.__doc__, Foo.func.__doc__ + 'ABC')
+    assert_equal(bar.func2.__doc__, Foo.func2.__doc__)
diff --git a/.venv/lib/python3.12/site-packages/scipy/_lib/tests/test_import_cycles.py b/.venv/lib/python3.12/site-packages/scipy/_lib/tests/test_import_cycles.py
new file mode 100644
index 0000000000000000000000000000000000000000..d1d7c2bfca4976019b77bfbbfbc0cc4ca96a6962
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/_lib/tests/test_import_cycles.py
@@ -0,0 +1,26 @@
+import multiprocessing
+import subprocess
+import sys
+
+import pytest
+
+from .test_public_api import PUBLIC_MODULES
+
+# Regression tests for gh-6793.
+# Check that all modules are importable in a new Python process.
+# This is not necessarily true if there are import cycles present.
+
+
+def _check_single_module(module):
+    pid = subprocess.Popen([sys.executable, '-X', 'faulthandler', '-c',
+                            f'import {module}'])
+    assert pid.wait() == 0, f'Failed to import {module}'
+
+
+@pytest.mark.fail_slow(40)
+@pytest.mark.slow
+def test_public_modules_importable_2():
+    # Ensure we use max 6 processes, to limit peak resource usage (memory, file handles)
+    # on resource-constrained systems (e.g., RISC-V - see gh-24163).
+    with multiprocessing.Pool(processes=6) as pool:
+        pool.map(_check_single_module, PUBLIC_MODULES)
diff --git a/.venv/lib/python3.12/site-packages/scipy/_lib/tests/test_public_api.py b/.venv/lib/python3.12/site-packages/scipy/_lib/tests/test_public_api.py
new file mode 100644
index 0000000000000000000000000000000000000000..e7c3d03130d5ca3033efd8d3c5a2b4b41549a0d9
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/_lib/tests/test_public_api.py
@@ -0,0 +1,437 @@
+"""
+This test script is adopted from:
+    https://github.com/numpy/numpy/blob/main/numpy/tests/test_public_api.py
+"""
+
+import pkgutil
+import types
+import importlib
+import warnings
+from importlib import import_module
+
+import pytest
+
+import scipy
+
+from scipy._lib._public_api import PUBLIC_MODULES, _without_fortran
+from scipy.conftest import xp_available_backends
+
+
+def test_dir_testing():
+    """Assert that output of dir has only one "testing/tester"
+    attribute without duplicate"""
+    assert len(dir(scipy)) == len(set(dir(scipy)))
+
+
+# The PRIVATE_BUT_PRESENT_MODULES list contains modules that lacked underscores
+# in their name and hence looked public, but weren't meant to be. All these
+# namespace were deprecated in the 1.8.0 release - see "clear split between
+# public and private API" in the 1.8.0 release notes.
+# These private modules support will be removed in SciPy v2.0.0, as the
+# deprecation messages emitted by each of these modules say.
+PRIVATE_BUT_PRESENT_MODULES = [
+    'scipy.constants.codata',
+    'scipy.constants.constants',
+    'scipy.fftpack.basic',
+    'scipy.fftpack.convolve',
+    'scipy.fftpack.helper',
+    'scipy.fftpack.pseudo_diffs',
+    'scipy.fftpack.realtransforms',
+    'scipy.integrate.dop',
+    'scipy.integrate.odepack',
+    'scipy.integrate.quadpack',
+    'scipy.integrate.vode',
+    'scipy.interpolate.dfitpack',
+    'scipy.interpolate.fitpack',
+    'scipy.interpolate.fitpack2',
+    'scipy.interpolate.interpnd',
+    'scipy.interpolate.interpolate',
+    'scipy.interpolate.ndgriddata',
+    'scipy.interpolate.polyint',
+    'scipy.interpolate.rbf',
+    'scipy.io.arff.arffread',
+    'scipy.io.harwell_boeing',
+    'scipy.io.idl',
+    'scipy.io.matlab.byteordercodes',
+    'scipy.io.matlab.mio',
+    'scipy.io.matlab.mio4',
+    'scipy.io.matlab.mio5',
+    'scipy.io.matlab.mio5_params',
+    'scipy.io.matlab.mio5_utils',
+    'scipy.io.matlab.mio_utils',
+    'scipy.io.matlab.miobase',
+    'scipy.io.matlab.streams',
+    'scipy.io.mmio',
+    'scipy.io.netcdf',
+    'scipy.linalg.basic',
+    'scipy.linalg.decomp',
+    'scipy.linalg.decomp_cholesky',
+    'scipy.linalg.decomp_lu',
+    'scipy.linalg.decomp_qr',
+    'scipy.linalg.decomp_schur',
+    'scipy.linalg.decomp_svd',
+    'scipy.linalg.matfuncs',
+    'scipy.linalg.misc',
+    'scipy.linalg.special_matrices',
+    'scipy.misc',
+    'scipy.misc.common',
+    'scipy.misc.doccer',
+    'scipy.ndimage.filters',
+    'scipy.ndimage.fourier',
+    'scipy.ndimage.interpolation',
+    'scipy.ndimage.measurements',
+    'scipy.ndimage.morphology',
+    'scipy.odr.models',
+    'scipy.odr.odrpack',
+    'scipy.optimize.cobyla',
+    'scipy.optimize.cython_optimize',
+    'scipy.optimize.lbfgsb',
+    'scipy.optimize.linesearch',
+    'scipy.optimize.minpack',
+    'scipy.optimize.minpack2',
+    'scipy.optimize.moduleTNC',
+    'scipy.optimize.nonlin',
+    'scipy.optimize.optimize',
+    'scipy.optimize.slsqp',
+    'scipy.optimize.tnc',
+    'scipy.optimize.zeros',
+    'scipy.signal.bsplines',
+    'scipy.signal.filter_design',
+    'scipy.signal.fir_filter_design',
+    'scipy.signal.lti_conversion',
+    'scipy.signal.ltisys',
+    'scipy.signal.signaltools',
+    'scipy.signal.spectral',
+    'scipy.signal.spline',
+    'scipy.signal.waveforms',
+    'scipy.signal.wavelets',
+    'scipy.signal.windows.windows',
+    'scipy.sparse.base',
+    'scipy.sparse.bsr',
+    'scipy.sparse.compressed',
+    'scipy.sparse.construct',
+    'scipy.sparse.coo',
+    'scipy.sparse.csc',
+    'scipy.sparse.csr',
+    'scipy.sparse.data',
+    'scipy.sparse.dia',
+    'scipy.sparse.dok',
+    'scipy.sparse.extract',
+    'scipy.sparse.lil',
+    'scipy.sparse.linalg.dsolve',
+    'scipy.sparse.linalg.eigen',
+    'scipy.sparse.linalg.interface',
+    'scipy.sparse.linalg.isolve',
+    'scipy.sparse.linalg.matfuncs',
+    'scipy.sparse.sparsetools',
+    'scipy.sparse.spfuncs',
+    'scipy.sparse.sputils',
+    'scipy.spatial.ckdtree',
+    'scipy.spatial.kdtree',
+    'scipy.spatial.qhull',
+    'scipy.spatial.transform.rotation',
+    'scipy.special.add_newdocs',
+    'scipy.special.basic',
+    'scipy.special.cython_special',
+    'scipy.special.orthogonal',
+    'scipy.special.sf_error',
+    'scipy.special.specfun',
+    'scipy.special.spfun_stats',
+    'scipy.stats.biasedurn',
+    'scipy.stats.kde',
+    'scipy.stats.morestats',
+    'scipy.stats.mstats_basic',
+    'scipy.stats.mstats_extras',
+    'scipy.stats.mvn',
+    'scipy.stats.stats',
+]
+
+if _without_fortran:
+    PRIVATE_BUT_PRESENT_MODULES.remove('scipy.odr.models')
+    PRIVATE_BUT_PRESENT_MODULES.remove('scipy.odr.odrpack')
+
+
+def is_unexpected(name):
+    """Check if this needs to be considered."""
+    if '._' in name or '.tests' in name or '.setup' in name:
+        return False
+
+    if name in PUBLIC_MODULES:
+        return False
+
+    if name in PRIVATE_BUT_PRESENT_MODULES:
+        return False
+
+    return True
+
+
+SKIP_LIST = [
+    'scipy.conftest',
+    'scipy.version',
+    'scipy.special.libsf_error_state',
+    'scipy.integrate.lsoda'
+]
+
+
+# XXX: this test does more than it says on the tin - in using `pkgutil.walk_packages`,
+# it will raise if it encounters any exceptions which are not handled by `ignore_errors`
+# while attempting to import each discovered package.
+# For now, `ignore_errors` only ignores what is necessary, but this could be expanded -
+# for example, to all errors from private modules or git subpackages - if desired.
+@pytest.mark.thread_unsafe(
+    reason=("crashes in pkgutil.walk_packages, see "
+            "https://github.com/data-apis/array-api-compat/issues/343"))
+def test_all_modules_are_expected():
+    """
+    Test that we don't add anything that looks like a new public module by
+    accident.  Check is based on filenames.
+    """
+
+    def ignore_errors(name):
+        # if versions of other array libraries are installed which are incompatible
+        # with the installed NumPy version, there can be errors on importing
+        # `array_api_compat`. This should only raise if SciPy is configured with
+        # that library as an available backend.
+        backends = {'cupy', 'torch', 'dask.array'}
+        for backend in backends:
+            path = f'array_api_compat.{backend}'
+            if path in name and backend not in xp_available_backends:
+                return
+        raise
+
+    modnames = []
+
+    with warnings.catch_warnings():
+        warnings.filterwarnings("ignore", "scipy.misc", DeprecationWarning)
+        for _, modname, _ in pkgutil.walk_packages(path=scipy.__path__,
+                                                   prefix=scipy.__name__ + '.',
+                                                   onerror=ignore_errors):
+            if is_unexpected(modname) and modname not in SKIP_LIST:
+                # We have a name that is new.  If that's on purpose, add it to
+                # PUBLIC_MODULES.  We don't expect to have to add anything to
+                # PRIVATE_BUT_PRESENT_MODULES.  Use an underscore in the name!
+                modnames.append(modname)
+
+    if modnames:
+        raise AssertionError(f'Found unexpected modules: {modnames}')
+
+
+# Stuff that clearly shouldn't be in the API and is detected by the next test
+# below
+SKIP_LIST_2 = [
+    'scipy.char',
+    'scipy.rec',
+    'scipy.emath',
+    'scipy.math',
+    'scipy.random',
+    'scipy.ctypeslib',
+    'scipy.ma',
+    'scipy.integrate.lsoda'
+]
+
+
+def test_all_modules_are_expected_2():
+    """
+    Method checking all objects. The pkgutil-based method in
+    `test_all_modules_are_expected` does not catch imports into a namespace,
+    only filenames.
+    """
+
+    def find_unexpected_members(mod_name):
+        members = []
+        module = importlib.import_module(mod_name)
+        if hasattr(module, '__all__'):
+            objnames = module.__all__
+        else:
+            objnames = dir(module)
+
+        for objname in objnames:
+            if not objname.startswith('_'):
+                fullobjname = mod_name + '.' + objname
+                if isinstance(getattr(module, objname), types.ModuleType):
+                    if is_unexpected(fullobjname) and fullobjname not in SKIP_LIST_2:
+                        members.append(fullobjname)
+
+        return members
+    with warnings.catch_warnings():
+        warnings.filterwarnings("ignore",  "scipy.misc", DeprecationWarning)
+        unexpected_members = find_unexpected_members("scipy")
+
+    for modname in PUBLIC_MODULES:
+        unexpected_members.extend(find_unexpected_members(modname))
+
+    if unexpected_members:
+        raise AssertionError("Found unexpected object(s) that look like "
+                             f"modules: {unexpected_members}")
+
+
+def test_api_importable():
+    """
+    Check that all submodules listed higher up in this file can be imported
+    Note that if a PRIVATE_BUT_PRESENT_MODULES entry goes missing, it may
+    simply need to be removed from the list (deprecation may or may not be
+    needed - apply common sense).
+    """
+    def check_importable(module_name):
+        try:
+            importlib.import_module(module_name)
+        except (ImportError, AttributeError):
+            return False
+
+        return True
+
+    module_names = []
+    for module_name in PUBLIC_MODULES:
+        if not check_importable(module_name):
+            module_names.append(module_name)
+
+    if module_names:
+        raise AssertionError("Modules in the public API that cannot be "
+                             f"imported: {module_names}")
+
+    with warnings.catch_warnings(record=True):
+        warnings.simplefilter('always', category=DeprecationWarning)
+        warnings.simplefilter('always', category=ImportWarning)
+        for module_name in PRIVATE_BUT_PRESENT_MODULES:
+            if not check_importable(module_name):
+                module_names.append(module_name)
+
+    if module_names:
+        raise AssertionError("Modules that are not really public but looked "
+                             "public and can not be imported: "
+                             f"{module_names}")
+
+
+@pytest.mark.parametrize(("module_name", "correct_module"),
+                         [('scipy.constants.codata', None),
+                          ('scipy.constants.constants', None),
+                          ('scipy.fftpack.basic', None),
+                          ('scipy.fftpack.helper', None),
+                          ('scipy.fftpack.pseudo_diffs', None),
+                          ('scipy.fftpack.realtransforms', None),
+                          ('scipy.integrate.dop', None),
+                          ('scipy.integrate.odepack', None),
+                          ('scipy.integrate.quadpack', None),
+                          ('scipy.integrate.vode', None),
+                          ('scipy.interpolate.dfitpack', None),
+                          ('scipy.interpolate.fitpack', None),
+                          ('scipy.interpolate.fitpack2', None),
+                          ('scipy.interpolate.interpnd', None),
+                          ('scipy.interpolate.interpolate', None),
+                          ('scipy.interpolate.ndgriddata', None),
+                          ('scipy.interpolate.polyint', None),
+                          ('scipy.interpolate.rbf', None),
+                          ('scipy.io.harwell_boeing', None),
+                          ('scipy.io.idl', None),
+                          ('scipy.io.mmio', None),
+                          ('scipy.io.netcdf', None),
+                          ('scipy.io.arff.arffread', 'arff'),
+                          ('scipy.io.matlab.byteordercodes', 'matlab'),
+                          ('scipy.io.matlab.mio_utils', 'matlab'),
+                          ('scipy.io.matlab.mio', 'matlab'),
+                          ('scipy.io.matlab.mio4', 'matlab'),
+                          ('scipy.io.matlab.mio5_params', 'matlab'),
+                          ('scipy.io.matlab.mio5_utils', 'matlab'),
+                          ('scipy.io.matlab.mio5', 'matlab'),
+                          ('scipy.io.matlab.miobase', 'matlab'),
+                          ('scipy.io.matlab.streams', 'matlab'),
+                          ('scipy.linalg.basic', None),
+                          ('scipy.linalg.decomp', None),
+                          ('scipy.linalg.decomp_cholesky', None),
+                          ('scipy.linalg.decomp_lu', None),
+                          ('scipy.linalg.decomp_qr', None),
+                          ('scipy.linalg.decomp_schur', None),
+                          ('scipy.linalg.decomp_svd', None),
+                          ('scipy.linalg.matfuncs', None),
+                          ('scipy.linalg.misc', None),
+                          ('scipy.linalg.special_matrices', None),
+                          ('scipy.ndimage.filters', None),
+                          ('scipy.ndimage.fourier', None),
+                          ('scipy.ndimage.interpolation', None),
+                          ('scipy.ndimage.measurements', None),
+                          ('scipy.ndimage.morphology', None),
+                          ('scipy.optimize.cobyla', None),
+                          ('scipy.optimize.lbfgsb', None),
+                          ('scipy.optimize.linesearch', None),
+                          ('scipy.optimize.minpack', None),
+                          ('scipy.optimize.minpack2', None),
+                          ('scipy.optimize.moduleTNC', None),
+                          ('scipy.optimize.nonlin', None),
+                          ('scipy.optimize.optimize', None),
+                          ('scipy.optimize.slsqp', None),
+                          ('scipy.optimize.tnc', None),
+                          ('scipy.optimize.zeros', None),
+                          ('scipy.signal.bsplines', None),
+                          ('scipy.signal.filter_design', None),
+                          ('scipy.signal.fir_filter_design', None),
+                          ('scipy.signal.lti_conversion', None),
+                          ('scipy.signal.ltisys', None),
+                          ('scipy.signal.signaltools', None),
+                          ('scipy.signal.spectral', None),
+                          ('scipy.signal.spline', None),
+                          ('scipy.signal.waveforms', None),
+                          ('scipy.signal.wavelets', None),
+                          ('scipy.signal.windows.windows', 'windows'),
+                          ('scipy.sparse.base', None),
+                          ('scipy.sparse.bsr', None),
+                          ('scipy.sparse.compressed', None),
+                          ('scipy.sparse.construct', None),
+                          ('scipy.sparse.coo', None),
+                          ('scipy.sparse.csc', None),
+                          ('scipy.sparse.csr', None),
+                          ('scipy.sparse.data', None),
+                          ('scipy.sparse.dia', None),
+                          ('scipy.sparse.dok', None),
+                          ('scipy.sparse.extract', None),
+                          ('scipy.sparse.lil', None),
+                          ('scipy.sparse.linalg.dsolve', 'linalg'),
+                          ('scipy.sparse.linalg.eigen', 'linalg'),
+                          ('scipy.sparse.linalg.interface', 'linalg'),
+                          ('scipy.sparse.linalg.isolve', 'linalg'),
+                          ('scipy.sparse.linalg.matfuncs', 'linalg'),
+                          ('scipy.sparse.sparsetools', None),
+                          ('scipy.sparse.spfuncs', None),
+                          ('scipy.sparse.sputils', None),
+                          ('scipy.spatial.ckdtree', None),
+                          ('scipy.spatial.kdtree', None),
+                          ('scipy.spatial.qhull', None),
+                          ('scipy.spatial.transform.rotation', 'transform'),
+                          ('scipy.special.add_newdocs', None),
+                          ('scipy.special.basic', None),
+                          ('scipy.special.orthogonal', None),
+                          ('scipy.special.sf_error', None),
+                          ('scipy.special.specfun', None),
+                          ('scipy.special.spfun_stats', None),
+                          ('scipy.stats.biasedurn', None),
+                          ('scipy.stats.kde', None),
+                          ('scipy.stats.morestats', None),
+                          ('scipy.stats.mstats_basic', 'mstats'),
+                          ('scipy.stats.mstats_extras', 'mstats'),
+                          ('scipy.stats.mvn', None),
+                          ('scipy.stats.stats', None)])
+def test_private_but_present_deprecation(module_name, correct_module):
+    # gh-18279, gh-17572, gh-17771 noted that deprecation warnings
+    # for imports from private modules
+    # were misleading. Check that this is resolved.
+    module = import_module(module_name)
+    if correct_module is None:
+        import_name = f'scipy.{module_name.split(".")[1]}'
+    else:
+        import_name = f'scipy.{module_name.split(".")[1]}.{correct_module}'
+
+    correct_import = import_module(import_name)
+
+    # Attributes that were formerly in `module_name` can still be imported from
+    # `module_name`, albeit with a deprecation warning.
+    for attr_name in module.__all__:
+        # ensure attribute is present where the warning is pointing
+        assert getattr(correct_import, attr_name, None) is not None
+        message = f"Please import `{attr_name}` from the `{import_name}`..."
+        with pytest.deprecated_call(match=message):
+            getattr(module, attr_name)
+
+    # Attributes that were not in `module_name` get an error notifying the user
+    # that the attribute is not in `module_name` and that `module_name` is deprecated.
+    message = f"`{module_name}` is deprecated..."
+    with pytest.raises(AttributeError, match=message):
+        getattr(module, "ekki")
diff --git a/.venv/lib/python3.12/site-packages/scipy/_lib/tests/test_scipy_version.py b/.venv/lib/python3.12/site-packages/scipy/_lib/tests/test_scipy_version.py
new file mode 100644
index 0000000000000000000000000000000000000000..68e1a43c3fb329b6a4274ba76b53a215738da6ad
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/_lib/tests/test_scipy_version.py
@@ -0,0 +1,28 @@
+import re
+
+import scipy
+import scipy.version
+
+
+def test_valid_scipy_version():
+    # Verify that the SciPy version is a valid one (no .post suffix or other
+    # nonsense). See NumPy issue gh-6431 for an issue caused by an invalid
+    # version.
+    version_pattern = r"^[0-9]+\.[0-9]+\.[0-9]+(|a[0-9]|b[0-9]|rc[0-9])"
+    dev_suffix = r"((.dev0)|(\.dev0+\+git[0-9]{8}.[0-9a-f]{7}))"
+    if scipy.version.release:
+        res = re.match(version_pattern, scipy.__version__)
+    else:
+        res = re.match(version_pattern + dev_suffix, scipy.__version__)
+
+    assert res is not None
+    assert scipy.__version__
+
+
+def test_version_submodule_members():
+    """`scipy.version` may not be quite public, but we install it.
+
+    So check that we don't silently change its contents.
+    """
+    for attr in ('version', 'full_version', 'short_version', 'git_revision', 'release'):
+        assert hasattr(scipy.version, attr)
diff --git a/.venv/lib/python3.12/site-packages/scipy/_lib/tests/test_warnings.py b/.venv/lib/python3.12/site-packages/scipy/_lib/tests/test_warnings.py
new file mode 100644
index 0000000000000000000000000000000000000000..c193f9d04e78bbe3dd1cccbf06ef2587b12e5c98
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/_lib/tests/test_warnings.py
@@ -0,0 +1,136 @@
+"""
+Tests which scan for certain occurrences in the code, they may not find
+all of these occurrences but should catch almost all. This file was adapted
+from NumPy.
+"""
+
+
+import os
+from pathlib import Path
+import ast
+import tokenize
+
+import scipy
+
+import pytest
+
+
+class ParseCall(ast.NodeVisitor):
+    def __init__(self):
+        self.ls = []
+
+    def visit_Attribute(self, node):
+        ast.NodeVisitor.generic_visit(self, node)
+        self.ls.append(node.attr)
+
+    def visit_Name(self, node):
+        self.ls.append(node.id)
+
+
+class FindFuncs(ast.NodeVisitor):
+    def __init__(self, filename):
+        super().__init__()
+        self.__filename = filename
+        self.bad_filters = []
+        self.bad_stacklevels = []
+
+    def visit_Call(self, node):
+        p = ParseCall()
+        p.visit(node.func)
+        ast.NodeVisitor.generic_visit(self, node)
+
+        if p.ls[-1] == 'simplefilter' or p.ls[-1] == 'filterwarnings':
+            # get first argument of the `args` node of the filter call
+            match node.args[0]:
+                case ast.Constant() as c:
+                    argtext = c.value
+                case ast.JoinedStr() as js:
+                    # if we get an f-string, discard the templated pieces, which
+                    # are likely the type or specific message; we're interested
+                    # in the action, which is less likely to use a template
+                    argtext = "".join(
+                        x.value for x in js.values if isinstance(x, ast.Constant)
+                    )
+                case _:
+                    raise ValueError("unknown ast node type")
+            # check if filter is set to ignore outside of test code
+            if argtext == "ignore" and "tests" not in self.__filename.parts:
+                self.bad_filters.append(
+                    f"{self.__filename}:{node.lineno}")
+
+        if p.ls[-1] == 'warn' and (
+                len(p.ls) == 1 or p.ls[-2] == 'warnings'):
+
+            if self.__filename == "_lib/tests/test_warnings.py":
+                # This file
+                return
+
+            # See if stacklevel exists:
+            if len(node.args) == 3:
+                return
+            args = {kw.arg for kw in node.keywords}
+            if "stacklevel" not in args:
+                self.bad_stacklevels.append(
+                    f"{self.__filename}:{node.lineno}")
+
+
+@pytest.fixture(scope="session")
+def warning_calls():
+    # combined "ignore" and stacklevel error
+    base = Path(scipy.__file__).parent
+
+    bad_filters = []
+    bad_stacklevels = []
+
+    for path in base.rglob("*.py"):
+        # use tokenize to auto-detect encoding on systems where no
+        # default encoding is defined (e.g., LANG='C')
+        with tokenize.open(str(path)) as file:
+            tree = ast.parse(file.read(), filename=str(path))
+            finder = FindFuncs(path.relative_to(base))
+            finder.visit(tree)
+            bad_filters.extend(finder.bad_filters)
+            bad_stacklevels.extend(finder.bad_stacklevels)
+
+    return bad_filters, bad_stacklevels
+
+
+@pytest.mark.fail_slow(40)
+@pytest.mark.slow
+def test_warning_calls_filters(warning_calls):
+    bad_filters, bad_stacklevels = warning_calls
+
+    # We try not to add filters in the code base, because those filters aren't
+    # thread-safe. We aim to only filter in tests with
+    # warnings.catch_warnings. However, in some cases it may prove
+    # necessary to filter out warnings, because we can't (easily) fix the root
+    # cause for them and we don't want users to see some warnings when they use
+    # SciPy correctly. So we list exceptions here.  Add new entries only if
+    # there's a good reason.
+    allowed_filters = (
+        os.path.join('datasets', '_fetchers.py'),
+        os.path.join('datasets', '__init__.py'),
+        os.path.join('optimize', '_optimize.py'),
+        os.path.join('optimize', '_constraints.py'),
+        os.path.join('optimize', '_nnls.py'),
+        os.path.join('signal', '_ltisys.py'),
+        os.path.join('sparse', '__init__.py'),  # np.matrix pending-deprecation
+        os.path.join('special', '_basic.py'),  # gh-21801
+        os.path.join('stats', '_discrete_distns.py'),  # gh-14901
+        os.path.join('stats', '_continuous_distns.py'),
+        os.path.join('stats', '_binned_statistic.py'),  # gh-19345
+        os.path.join('stats', '_stats_py.py'),  # gh-20743
+        os.path.join('stats', '_variation.py'),  # gh-22827
+        os.path.join('stats', 'tests', 'test_axis_nan_policy.py'),  # gh-20694
+        os.path.join('_lib', '_util.py'),  # gh-19341
+        os.path.join('sparse', 'linalg', '_dsolve', 'linsolve.py'),  # gh-17924
+        "conftest.py",
+    )
+    bad_filters = [item for item in bad_filters if item.split(':')[0] not in
+                   allowed_filters]
+
+    if bad_filters:
+        raise AssertionError(
+            "Warning ignore filters should not be used outside of tests.\n"
+            "Found in:\n    {}".format(
+                "\n    ".join(bad_filters)))
diff --git a/.venv/lib/python3.12/site-packages/scipy/_lib/tests/test_xp_capabilities.py b/.venv/lib/python3.12/site-packages/scipy/_lib/tests/test_xp_capabilities.py
new file mode 100644
index 0000000000000000000000000000000000000000..ba00df862ca767a65e84e76ded4aaf0488f4f88b
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/_lib/tests/test_xp_capabilities.py
@@ -0,0 +1,69 @@
+import pytest
+
+from scipy._lib._array_api import np_compat as np
+from scipy._lib._array_api import (
+    array_namespace, make_xp_pytest_param, xp_assert_close, xp_capabilities
+)
+
+local_capabilities_table = {}  # type:ignore[var-annotated]
+
+# B is a child of A which inherits the method g which is array-agnostic
+# so long as the method f is supported. A.f does not support the JAX jit but
+# B.f does support the JAX jit. Test that this inheritence does not
+# cause problems when testing with JAX jit.
+
+@xp_capabilities(
+    capabilities_table=local_capabilities_table,
+    cpu_only=True,
+    jax_jit=False,
+    skip_backends=[
+        ("dask.array", ""),
+    ],
+)
+class A:
+    def __init__(self, x):
+        xp = array_namespace(x)
+        self._xp = xp
+        self.x = np.asarray(x)
+
+    def f(self, y):
+        y = np.asarray(y)
+        return self._xp.asarray(np.matmul(self.x, y))
+
+    def g(self, y, z):
+        return self.f(y) + self.f(z)
+
+
+@xp_capabilities(
+    capabilities_table=local_capabilities_table,
+    cpu_only=True,
+    skip_backends=[("dask.array", "")],
+)
+class B(A):
+    def __init__(self, x):
+        xp = array_namespace(x)
+        self._xp = xp
+        self.x = xp.asarray(x)
+
+    def f(self, y):
+        return self._xp.matmul(self.x, y)
+
+
+@pytest.mark.parametrize(
+    "cls",
+    [
+        make_xp_pytest_param((A, "g"), capabilities_table=local_capabilities_table),
+        make_xp_pytest_param((B, "g"), capabilities_table=local_capabilities_table),
+    ],
+)
+def test_no_spooky_action_at_a_distance(cls, xp):
+    # test that application of lazy_xp_function to a method which is inherited
+    # from a parent class do not propagate to the parent class. Calls to A.g
+    # will raise here if A.g was accidentally jitted.
+    x = xp.asarray([1.1, 2.2, 3.3])
+    y = xp.asarray([1.0, 2.0, 3.0])
+    z = xp.asarray([3.0, 4.0, 5.0])
+    foo = cls(x)
+    observed = foo.g(y, z)
+    expected = xp.asarray(44.0)[()]
+    xp_assert_close(observed, expected)
diff --git a/.venv/lib/python3.12/site-packages/scipy/_lib/uarray.py b/.venv/lib/python3.12/site-packages/scipy/_lib/uarray.py
new file mode 100644
index 0000000000000000000000000000000000000000..7bfa3e3a14a7bfea3ee1160d342d11b3a123ed33
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/_lib/uarray.py
@@ -0,0 +1,31 @@
+"""`uarray` provides functions for generating multimethods that dispatch to
+multiple different backends
+
+This should be imported, rather than `_uarray` so that an installed version could
+be used instead, if available. This means that users can call
+`uarray.set_backend` directly instead of going through SciPy.
+
+"""
+
+
+# Prefer an installed version of uarray, if available
+try:
+    import uarray as _uarray
+except ImportError:
+    _has_uarray = False
+else:
+    from scipy._external.packaging_version.version import Version as _Version
+
+    _has_uarray = _Version(_uarray.__version__) >= _Version("0.8")
+    del _uarray
+    del _Version
+
+
+if _has_uarray:
+    from uarray import *  # noqa: F403
+    from uarray import _Function
+else:
+    from ._uarray import *  # noqa: F403
+    from ._uarray import _Function  # noqa: F401
+
+del _has_uarray
diff --git a/.venv/lib/python3.12/site-packages/scipy/cluster/__init__.py b/.venv/lib/python3.12/site-packages/scipy/cluster/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..7b7784969a573d05cc6b98ee9066c42720156d1d
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/cluster/__init__.py
@@ -0,0 +1,31 @@
+"""
+=========================================
+Clustering package (:mod:`scipy.cluster`)
+=========================================
+
+.. currentmodule:: scipy.cluster
+
+Clustering algorithms are useful in information theory, target detection,
+communications, compression, and other areas. The `vq` module only
+supports vector quantization and the k-means algorithms.
+
+The `hierarchy` module provides functions for hierarchical and
+agglomerative clustering.  Its features include generating hierarchical
+clusters from distance matrices,
+calculating statistics on clusters, cutting linkages
+to generate flat clusters, and visualizing clusters with dendrograms.
+
+.. toctree::
+   :maxdepth: 1
+
+   cluster.vq
+   cluster.hierarchy
+
+"""
+__all__ = ['vq', 'hierarchy']
+
+from . import vq, hierarchy
+
+from scipy._lib._testutils import PytestTester
+test = PytestTester(__name__)
+del PytestTester
diff --git a/.venv/lib/python3.12/site-packages/scipy/cluster/hierarchy/__init__.py b/.venv/lib/python3.12/site-packages/scipy/cluster/hierarchy/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..1d20c1d4a7d9dc712b1c621278685adf1ba33b68
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/cluster/hierarchy/__init__.py
@@ -0,0 +1,116 @@
+"""
+Hierarchical clustering (:mod:`scipy.cluster.hierarchy`)
+========================================================
+
+.. currentmodule:: scipy.cluster.hierarchy
+
+These functions cut hierarchical clusterings into flat clusterings
+or find the roots of the forest formed by a cut by providing the flat
+cluster ids of each observation.
+
+.. autosummary::
+   :toctree: generated/
+
+   fcluster
+   fclusterdata
+   leaders
+
+These are routines for agglomerative clustering.
+
+.. autosummary::
+   :toctree: generated/
+
+   linkage
+   single
+   complete
+   average
+   weighted
+   centroid
+   median
+   ward
+
+These routines compute statistics on hierarchies.
+
+.. autosummary::
+   :toctree: generated/
+
+   cophenet
+   from_mlab_linkage
+   inconsistent
+   maxinconsts
+   maxdists
+   maxRstat
+   to_mlab_linkage
+
+Routines for visualizing flat clusters.
+
+.. autosummary::
+   :toctree: generated/
+
+   dendrogram
+
+These are data structures and routines for representing hierarchies as
+tree objects.
+
+.. autosummary::
+   :toctree: generated/
+
+   ClusterNode
+   leaves_list
+   to_tree
+   cut_tree
+   optimal_leaf_ordering
+
+These are predicates for checking the validity of linkage and
+inconsistency matrices as well as for checking isomorphism of two
+flat cluster assignments.
+
+.. autosummary::
+   :toctree: generated/
+
+   is_valid_im
+   is_valid_linkage
+   is_isomorphic
+   is_monotonic
+   correspond
+   num_obs_linkage
+
+Utility routines for plotting:
+
+.. autosummary::
+   :toctree: generated/
+
+   set_link_color_palette
+
+Utility classes:
+
+.. autosummary::
+   :toctree: generated/
+
+   DisjointSet -- data structure for incremental connectivity queries
+   
+Warnings:
+    
+.. autosummary::
+   :toctree: generated/
+
+   ClusterWarning
+
+"""
+from ._hierarchy_impl import (
+    ClusterNode, ClusterWarning, DisjointSet, average, centroid, complete, cophenet,
+    correspond, cut_tree, dendrogram, fcluster, fclusterdata, from_mlab_linkage,
+    inconsistent, is_isomorphic, is_monotonic, is_valid_im, is_valid_linkage, leaders,
+    leaves_list, linkage, maxRstat, maxdists, maxinconsts, median, num_obs_linkage,
+    optimal_leaf_ordering, set_link_color_palette, single, to_mlab_linkage, to_tree,
+    ward, weighted
+)
+
+__all__ = ['ClusterNode', 'ClusterWarning', 'DisjointSet', 'average', 'centroid',
+           'complete', 'cophenet', 'correspond', 'cut_tree', 'dendrogram', 'fcluster',
+           'fclusterdata', 'from_mlab_linkage', 'inconsistent',
+           'is_isomorphic', 'is_monotonic', 'is_valid_im', 'is_valid_linkage',
+           'leaders', 'leaves_list', 'linkage', 'maxRstat', 'maxdists',
+           'maxinconsts', 'median', 'num_obs_linkage', 'optimal_leaf_ordering',
+           'set_link_color_palette', 'single', 'to_mlab_linkage', 'to_tree',
+           'ward', 'weighted']
diff --git a/.venv/lib/python3.12/site-packages/scipy/cluster/hierarchy/_hierarchy.cpython-312-x86_64-linux-gnu.so b/.venv/lib/python3.12/site-packages/scipy/cluster/hierarchy/_hierarchy.cpython-312-x86_64-linux-gnu.so
new file mode 100644
index 0000000000000000000000000000000000000000..c56f4097adb6f97f6c057b1a01954985cfbf87c0
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/cluster/hierarchy/_hierarchy.cpython-312-x86_64-linux-gnu.so
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:a0cf8c91c53d84f4c4786866faaa5c9d672925620b1192b777904ed90c593d33
+size 254472
diff --git a/.venv/lib/python3.12/site-packages/scipy/cluster/hierarchy/_hierarchy_impl.py b/.venv/lib/python3.12/site-packages/scipy/cluster/hierarchy/_hierarchy_impl.py
new file mode 100644
index 0000000000000000000000000000000000000000..a7dbe2ac08845ea95072011eb968d8ea8a5e9c8f
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/cluster/hierarchy/_hierarchy_impl.py
@@ -0,0 +1,4232 @@
+# Copyright (C) Damian Eads, 2007-2008. New BSD License.
+
+# hierarchy.py (derived from cluster.py, http://scipy-cluster.googlecode.com)
+#
+# Author: Damian Eads
+# Date:   September 22, 2007
+#
+# Copyright (c) 2007, 2008, Damian Eads
+#
+# 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 author 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.
+
+import warnings
+import bisect
+from collections import deque
+
+import numpy as np
+from . import _hierarchy, _optimal_leaf_ordering  # type:ignore[attr-defined]
+import scipy.spatial.distance as distance
+from scipy._lib._array_api import (_asarray, array_namespace, is_dask,
+                                   is_lazy_array, xp_capabilities, xp_copy)
+from scipy._lib._disjoint_set import DisjointSet
+import scipy._external.array_api_extra as xpx
+
+
+_LINKAGE_METHODS = {'single': 0, 'complete': 1, 'average': 2, 'centroid': 3,
+                    'median': 4, 'ward': 5, 'weighted': 6}
+_EUCLIDEAN_METHODS = ('centroid', 'median', 'ward')
+
+__all__ = ['ClusterNode', 'ClusterWarning', 'DisjointSet',
+           'average', 'centroid', 'complete',
+           'cophenet', 'correspond', 'cut_tree', 'dendrogram', 'fcluster',
+           'fclusterdata', 'from_mlab_linkage', 'inconsistent',
+           'is_isomorphic', 'is_monotonic', 'is_valid_im', 'is_valid_linkage',
+           'leaders', 'leaves_list', 'linkage', 'maxRstat', 'maxdists',
+           'maxinconsts', 'median', 'num_obs_linkage', 'optimal_leaf_ordering',
+           'set_link_color_palette', 'single', 'to_mlab_linkage', 'to_tree',
+           'ward', 'weighted']
+
+
+class ClusterWarning(UserWarning):
+    """
+    A ``UserWarning`` raised during clustering.
+    """
+    pass
+
+
+def _warning(s):
+    warnings.warn(f'scipy.cluster: {s}', ClusterWarning, stacklevel=3)
+
+
+def _int_floor(arr, xp):
+    # array_api_strict is strict about not allowing `int()` on a float array.
+    # That's typically not needed, here it is - so explicitly convert
+    return int(xp.asarray(arr, dtype=xp.int64))
+
+
+lazy_cython = xp_capabilities(
+    cpu_only=True, reason="Cython code",
+    warnings=[("dask.array", "merges chunks")])
+
+
+@lazy_cython
+def single(y):
+    """
+    Perform single/min/nearest linkage on the condensed distance matrix ``y``.
+
+    Parameters
+    ----------
+    y : ndarray
+        The upper triangular of the distance matrix. The result of
+        ``pdist`` is returned in this form.
+
+    Returns
+    -------
+    Z : ndarray
+        The linkage matrix.
+
+    See Also
+    --------
+    linkage : for advanced creation of hierarchical clusterings.
+    scipy.spatial.distance.pdist : pairwise distance metrics
+
+    Examples
+    --------
+    >>> from scipy.cluster.hierarchy import single, fcluster
+    >>> from scipy.spatial.distance import pdist
+
+    First, we need a toy dataset to play with::
+
+        x x    x x
+        x        x
+
+        x        x
+        x x    x x
+
+    >>> X = [[0, 0], [0, 1], [1, 0],
+    ...      [0, 4], [0, 3], [1, 4],
+    ...      [4, 0], [3, 0], [4, 1],
+    ...      [4, 4], [3, 4], [4, 3]]
+
+    Then, we get a condensed distance matrix from this dataset:
+
+    >>> y = pdist(X)
+
+    Finally, we can perform the clustering:
+
+    >>> Z = single(y)
+    >>> Z
+    array([[ 0.,  1.,  1.,  2.],
+           [ 2., 12.,  1.,  3.],
+           [ 3.,  4.,  1.,  2.],
+           [ 5., 14.,  1.,  3.],
+           [ 6.,  7.,  1.,  2.],
+           [ 8., 16.,  1.,  3.],
+           [ 9., 10.,  1.,  2.],
+           [11., 18.,  1.,  3.],
+           [13., 15.,  2.,  6.],
+           [17., 20.,  2.,  9.],
+           [19., 21.,  2., 12.]])
+
+    The linkage matrix ``Z`` represents a dendrogram - see
+    `scipy.cluster.hierarchy.linkage` for a detailed explanation of its
+    contents.
+
+    We can use `scipy.cluster.hierarchy.fcluster` to see to which cluster
+    each initial point would belong given a distance threshold:
+
+    >>> fcluster(Z, 0.9, criterion='distance')
+    array([ 7,  8,  9, 10, 11, 12,  4,  5,  6,  1,  2,  3], dtype=int32)
+    >>> fcluster(Z, 1, criterion='distance')
+    array([3, 3, 3, 4, 4, 4, 2, 2, 2, 1, 1, 1], dtype=int32)
+    >>> fcluster(Z, 2, criterion='distance')
+    array([1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], dtype=int32)
+
+    Also, `scipy.cluster.hierarchy.dendrogram` can be used to generate a
+    plot of the dendrogram.
+    """
+    return linkage(y, method='single', metric='euclidean')
+
+
+@lazy_cython
+def complete(y):
+    """
+    Perform complete/max/farthest point linkage on a condensed distance matrix.
+
+    Parameters
+    ----------
+    y : ndarray
+        The upper triangular of the distance matrix. The result of
+        ``pdist`` is returned in this form.
+
+    Returns
+    -------
+    Z : ndarray
+        A linkage matrix containing the hierarchical clustering. See
+        the `linkage` function documentation for more information
+        on its structure.
+
+    See Also
+    --------
+    linkage : for advanced creation of hierarchical clusterings.
+    scipy.spatial.distance.pdist : pairwise distance metrics
+
+    Examples
+    --------
+    >>> from scipy.cluster.hierarchy import complete, fcluster
+    >>> from scipy.spatial.distance import pdist
+
+    First, we need a toy dataset to play with::
+
+        x x    x x
+        x        x
+
+        x        x
+        x x    x x
+
+    >>> X = [[0, 0], [0, 1], [1, 0],
+    ...      [0, 4], [0, 3], [1, 4],
+    ...      [4, 0], [3, 0], [4, 1],
+    ...      [4, 4], [3, 4], [4, 3]]
+
+    Then, we get a condensed distance matrix from this dataset:
+
+    >>> y = pdist(X)
+
+    Finally, we can perform the clustering:
+
+    >>> Z = complete(y)
+    >>> Z
+    array([[ 0.        ,  1.        ,  1.        ,  2.        ],
+           [ 3.        ,  4.        ,  1.        ,  2.        ],
+           [ 6.        ,  7.        ,  1.        ,  2.        ],
+           [ 9.        , 10.        ,  1.        ,  2.        ],
+           [ 2.        , 12.        ,  1.41421356,  3.        ],
+           [ 5.        , 13.        ,  1.41421356,  3.        ],
+           [ 8.        , 14.        ,  1.41421356,  3.        ],
+           [11.        , 15.        ,  1.41421356,  3.        ],
+           [16.        , 17.        ,  4.12310563,  6.        ],
+           [18.        , 19.        ,  4.12310563,  6.        ],
+           [20.        , 21.        ,  5.65685425, 12.        ]])
+
+    The linkage matrix ``Z`` represents a dendrogram - see
+    `scipy.cluster.hierarchy.linkage` for a detailed explanation of its
+    contents.
+
+    We can use `scipy.cluster.hierarchy.fcluster` to see to which cluster
+    each initial point would belong given a distance threshold:
+
+    >>> fcluster(Z, 0.9, criterion='distance')
+    array([ 1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12], dtype=int32)
+    >>> fcluster(Z, 1.5, criterion='distance')
+    array([1, 1, 1, 2, 2, 2, 3, 3, 3, 4, 4, 4], dtype=int32)
+    >>> fcluster(Z, 4.5, criterion='distance')
+    array([1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2], dtype=int32)
+    >>> fcluster(Z, 6, criterion='distance')
+    array([1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], dtype=int32)
+
+    Also, `scipy.cluster.hierarchy.dendrogram` can be used to generate a
+    plot of the dendrogram.
+    """
+    return linkage(y, method='complete', metric='euclidean')
+
+
+@lazy_cython
+def average(y):
+    """
+    Perform average/UPGMA linkage on a condensed distance matrix.
+
+    Parameters
+    ----------
+    y : ndarray
+        The upper triangular of the distance matrix. The result of
+        ``pdist`` is returned in this form.
+
+    Returns
+    -------
+    Z : ndarray
+        A linkage matrix containing the hierarchical clustering. See
+        `linkage` for more information on its structure.
+
+    See Also
+    --------
+    linkage : for advanced creation of hierarchical clusterings.
+    scipy.spatial.distance.pdist : pairwise distance metrics
+
+    Examples
+    --------
+    >>> from scipy.cluster.hierarchy import average, fcluster
+    >>> from scipy.spatial.distance import pdist
+
+    First, we need a toy dataset to play with::
+
+        x x    x x
+        x        x
+
+        x        x
+        x x    x x
+
+    >>> X = [[0, 0], [0, 1], [1, 0],
+    ...      [0, 4], [0, 3], [1, 4],
+    ...      [4, 0], [3, 0], [4, 1],
+    ...      [4, 4], [3, 4], [4, 3]]
+
+    Then, we get a condensed distance matrix from this dataset:
+
+    >>> y = pdist(X)
+
+    Finally, we can perform the clustering:
+
+    >>> Z = average(y)
+    >>> Z
+    array([[ 0.        ,  1.        ,  1.        ,  2.        ],
+           [ 3.        ,  4.        ,  1.        ,  2.        ],
+           [ 6.        ,  7.        ,  1.        ,  2.        ],
+           [ 9.        , 10.        ,  1.        ,  2.        ],
+           [ 2.        , 12.        ,  1.20710678,  3.        ],
+           [ 5.        , 13.        ,  1.20710678,  3.        ],
+           [ 8.        , 14.        ,  1.20710678,  3.        ],
+           [11.        , 15.        ,  1.20710678,  3.        ],
+           [16.        , 17.        ,  3.39675184,  6.        ],
+           [18.        , 19.        ,  3.39675184,  6.        ],
+           [20.        , 21.        ,  4.09206523, 12.        ]])
+
+    The linkage matrix ``Z`` represents a dendrogram - see
+    `scipy.cluster.hierarchy.linkage` for a detailed explanation of its
+    contents.
+
+    We can use `scipy.cluster.hierarchy.fcluster` to see to which cluster
+    each initial point would belong given a distance threshold:
+
+    >>> fcluster(Z, 0.9, criterion='distance')
+    array([ 1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12], dtype=int32)
+    >>> fcluster(Z, 1.5, criterion='distance')
+    array([1, 1, 1, 2, 2, 2, 3, 3, 3, 4, 4, 4], dtype=int32)
+    >>> fcluster(Z, 4, criterion='distance')
+    array([1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2], dtype=int32)
+    >>> fcluster(Z, 6, criterion='distance')
+    array([1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], dtype=int32)
+
+    Also, `scipy.cluster.hierarchy.dendrogram` can be used to generate a
+    plot of the dendrogram.
+
+    """
+    return linkage(y, method='average', metric='euclidean')
+
+
+@lazy_cython
+def weighted(y):
+    """
+    Perform weighted/WPGMA linkage on the condensed distance matrix.
+
+    See `linkage` for more information on the return
+    structure and algorithm.
+
+    Parameters
+    ----------
+    y : ndarray
+        The upper triangular of the distance matrix. The result of
+        ``pdist`` is returned in this form.
+
+    Returns
+    -------
+    Z : ndarray
+        A linkage matrix containing the hierarchical clustering. See
+        `linkage` for more information on its structure.
+
+    See Also
+    --------
+    linkage : for advanced creation of hierarchical clusterings.
+    scipy.spatial.distance.pdist : pairwise distance metrics
+
+    Examples
+    --------
+    >>> from scipy.cluster.hierarchy import weighted, fcluster
+    >>> from scipy.spatial.distance import pdist
+
+    First, we need a toy dataset to play with::
+
+        x x    x x
+        x        x
+
+        x        x
+        x x    x x
+
+    >>> X = [[0, 0], [0, 1], [1, 0],
+    ...      [0, 4], [0, 3], [1, 4],
+    ...      [4, 0], [3, 0], [4, 1],
+    ...      [4, 4], [3, 4], [4, 3]]
+
+    Then, we get a condensed distance matrix from this dataset:
+
+    >>> y = pdist(X)
+
+    Finally, we can perform the clustering:
+
+    >>> Z = weighted(y)
+    >>> Z
+    array([[ 0.        ,  1.        ,  1.        ,  2.        ],
+           [ 6.        ,  7.        ,  1.        ,  2.        ],
+           [ 3.        ,  4.        ,  1.        ,  2.        ],
+           [ 9.        , 11.        ,  1.        ,  2.        ],
+           [ 2.        , 12.        ,  1.20710678,  3.        ],
+           [ 8.        , 13.        ,  1.20710678,  3.        ],
+           [ 5.        , 14.        ,  1.20710678,  3.        ],
+           [10.        , 15.        ,  1.20710678,  3.        ],
+           [18.        , 19.        ,  3.05595762,  6.        ],
+           [16.        , 17.        ,  3.32379407,  6.        ],
+           [20.        , 21.        ,  4.06357713, 12.        ]])
+
+    The linkage matrix ``Z`` represents a dendrogram - see
+    `scipy.cluster.hierarchy.linkage` for a detailed explanation of its
+    contents.
+
+    We can use `scipy.cluster.hierarchy.fcluster` to see to which cluster
+    each initial point would belong given a distance threshold:
+
+    >>> fcluster(Z, 0.9, criterion='distance')
+    array([ 7,  8,  9,  1,  2,  3, 10, 11, 12,  4,  6,  5], dtype=int32)
+    >>> fcluster(Z, 1.5, criterion='distance')
+    array([3, 3, 3, 1, 1, 1, 4, 4, 4, 2, 2, 2], dtype=int32)
+    >>> fcluster(Z, 4, criterion='distance')
+    array([2, 2, 2, 1, 1, 1, 2, 2, 2, 1, 1, 1], dtype=int32)
+    >>> fcluster(Z, 6, criterion='distance')
+    array([1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], dtype=int32)
+
+    Also, `scipy.cluster.hierarchy.dendrogram` can be used to generate a
+    plot of the dendrogram.
+
+    """
+    return linkage(y, method='weighted', metric='euclidean')
+
+
+@lazy_cython
+def centroid(y):
+    """
+    Perform centroid/UPGMC linkage.
+
+    See `linkage` for more information on the input matrix,
+    return structure, and algorithm.
+
+    The following are common calling conventions:
+
+    1. ``Z = centroid(y)``
+
+       Performs centroid/UPGMC linkage on the condensed distance
+       matrix ``y``.
+
+    2. ``Z = centroid(X)``
+
+       Performs centroid/UPGMC linkage on the observation matrix ``X``
+       using Euclidean distance as the distance metric.
+
+    Parameters
+    ----------
+    y : ndarray
+        A condensed distance matrix. A condensed
+        distance matrix is a flat array containing the upper
+        triangular of the distance matrix. This is the form that
+        ``pdist`` returns. Alternatively, a collection of
+        m observation vectors in n dimensions may be passed as
+        an m by n array.
+
+    Returns
+    -------
+    Z : ndarray
+        A linkage matrix containing the hierarchical clustering. See
+        the `linkage` function documentation for more information
+        on its structure.
+
+    See Also
+    --------
+    linkage : for advanced creation of hierarchical clusterings.
+    scipy.spatial.distance.pdist : pairwise distance metrics
+
+    Examples
+    --------
+    >>> from scipy.cluster.hierarchy import centroid, fcluster
+    >>> from scipy.spatial.distance import pdist
+
+    First, we need a toy dataset to play with::
+
+        x x    x x
+        x        x
+
+        x        x
+        x x    x x
+
+    >>> X = [[0, 0], [0, 1], [1, 0],
+    ...      [0, 4], [0, 3], [1, 4],
+    ...      [4, 0], [3, 0], [4, 1],
+    ...      [4, 4], [3, 4], [4, 3]]
+
+    Then, we get a condensed distance matrix from this dataset:
+
+    >>> y = pdist(X)
+
+    Finally, we can perform the clustering:
+
+    >>> Z = centroid(y)
+    >>> Z
+    array([[ 0.        ,  1.        ,  1.        ,  2.        ],
+           [ 3.        ,  4.        ,  1.        ,  2.        ],
+           [ 9.        , 10.        ,  1.        ,  2.        ],
+           [ 6.        ,  7.        ,  1.        ,  2.        ],
+           [ 2.        , 12.        ,  1.11803399,  3.        ],
+           [ 5.        , 13.        ,  1.11803399,  3.        ],
+           [ 8.        , 15.        ,  1.11803399,  3.        ],
+           [11.        , 14.        ,  1.11803399,  3.        ],
+           [18.        , 19.        ,  3.33333333,  6.        ],
+           [16.        , 17.        ,  3.33333333,  6.        ],
+           [20.        , 21.        ,  3.33333333, 12.        ]]) # may vary
+
+    The linkage matrix ``Z`` represents a dendrogram - see
+    `scipy.cluster.hierarchy.linkage` for a detailed explanation of its
+    contents.
+
+    We can use `scipy.cluster.hierarchy.fcluster` to see to which cluster
+    each initial point would belong given a distance threshold:
+
+    >>> fcluster(Z, 0.9, criterion='distance')
+    array([ 7,  8,  9, 10, 11, 12,  1,  2,  3,  4,  5,  6], dtype=int32) # may vary
+    >>> fcluster(Z, 1.1, criterion='distance')
+    array([5, 5, 6, 7, 7, 8, 1, 1, 2, 3, 3, 4], dtype=int32) # may vary
+    >>> fcluster(Z, 2, criterion='distance')
+    array([3, 3, 3, 4, 4, 4, 1, 1, 1, 2, 2, 2], dtype=int32) # may vary
+    >>> fcluster(Z, 4, criterion='distance')
+    array([1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], dtype=int32)
+
+    Also, `scipy.cluster.hierarchy.dendrogram` can be used to generate a
+    plot of the dendrogram.
+
+    """
+    return linkage(y, method='centroid', metric='euclidean')
+
+
+@lazy_cython
+def median(y):
+    """
+    Perform median/WPGMC linkage.
+
+    See `linkage` for more information on the return structure
+    and algorithm.
+
+    The following are common calling conventions:
+
+    1. ``Z = median(y)``:
+       Performs median/WPGMC linkage on the condensed distance matrix
+       ``y``.  See ``linkage`` for more information on the return
+       structure and algorithm.
+    2. ``Z = median(X)``:
+       Performs median/WPGMC linkage on the observation matrix ``X``
+       using Euclidean distance as the distance metric. See `linkage`
+       for more information on the return structure and algorithm.
+
+    Parameters
+    ----------
+    y : ndarray
+        A condensed distance matrix. A condensed
+        distance matrix is a flat array containing the upper
+        triangular of the distance matrix. This is the form that
+        ``pdist`` returns.  Alternatively, a collection of
+        m observation vectors in n dimensions may be passed as
+        an m by n array.
+
+    Returns
+    -------
+    Z : ndarray
+        The hierarchical clustering encoded as a linkage matrix.
+
+    See Also
+    --------
+    linkage : for advanced creation of hierarchical clusterings.
+    scipy.spatial.distance.pdist : pairwise distance metrics
+
+    Examples
+    --------
+    >>> from scipy.cluster.hierarchy import median, fcluster
+    >>> from scipy.spatial.distance import pdist
+
+    First, we need a toy dataset to play with::
+
+        x x    x x
+        x        x
+
+        x        x
+        x x    x x
+
+    >>> X = [[0, 0], [0, 1], [1, 0],
+    ...      [0, 4], [0, 3], [1, 4],
+    ...      [4, 0], [3, 0], [4, 1],
+    ...      [4, 4], [3, 4], [4, 3]]
+
+    Then, we get a condensed distance matrix from this dataset:
+
+    >>> y = pdist(X)
+
+    Finally, we can perform the clustering:
+
+    >>> Z = median(y)
+    >>> Z
+    array([[ 0.        ,  1.        ,  1.        ,  2.        ],
+           [ 3.        ,  4.        ,  1.        ,  2.        ],
+           [ 9.        , 10.        ,  1.        ,  2.        ],
+           [ 6.        ,  7.        ,  1.        ,  2.        ],
+           [ 2.        , 12.        ,  1.11803399,  3.        ],
+           [ 5.        , 13.        ,  1.11803399,  3.        ],
+           [ 8.        , 15.        ,  1.11803399,  3.        ],
+           [11.        , 14.        ,  1.11803399,  3.        ],
+           [18.        , 19.        ,  3.        ,  6.        ],
+           [16.        , 17.        ,  3.5       ,  6.        ],
+           [20.        , 21.        ,  3.25      , 12.        ]])
+
+    The linkage matrix ``Z`` represents a dendrogram - see
+    `scipy.cluster.hierarchy.linkage` for a detailed explanation of its
+    contents.
+
+    We can use `scipy.cluster.hierarchy.fcluster` to see to which cluster
+    each initial point would belong given a distance threshold:
+
+    >>> fcluster(Z, 0.9, criterion='distance')
+    array([ 7,  8,  9, 10, 11, 12,  1,  2,  3,  4,  5,  6], dtype=int32)
+    >>> fcluster(Z, 1.1, criterion='distance')
+    array([5, 5, 6, 7, 7, 8, 1, 1, 2, 3, 3, 4], dtype=int32)
+    >>> fcluster(Z, 2, criterion='distance')
+    array([3, 3, 3, 4, 4, 4, 1, 1, 1, 2, 2, 2], dtype=int32)
+    >>> fcluster(Z, 4, criterion='distance')
+    array([1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], dtype=int32)
+
+    Also, `scipy.cluster.hierarchy.dendrogram` can be used to generate a
+    plot of the dendrogram.
+
+    """
+    return linkage(y, method='median', metric='euclidean')
+
+
+@lazy_cython
+def ward(y):
+    """
+    Perform Ward's linkage on a condensed distance matrix.
+
+    See `linkage` for more information on the return structure
+    and algorithm.
+
+    The following are common calling conventions:
+
+    1. ``Z = ward(y)``
+       Performs Ward's linkage on the condensed distance matrix ``y``.
+
+    2. ``Z = ward(X)``
+       Performs Ward's linkage on the observation matrix ``X`` using
+       Euclidean distance as the distance metric.
+
+    Parameters
+    ----------
+    y : ndarray
+        A condensed distance matrix. A condensed
+        distance matrix is a flat array containing the upper
+        triangular of the distance matrix. This is the form that
+        ``pdist`` returns.  Alternatively, a collection of
+        m observation vectors in n dimensions may be passed as
+        an m by n array.
+
+    Returns
+    -------
+    Z : ndarray
+        The hierarchical clustering encoded as a linkage matrix. See
+        `linkage` for more information on the return structure and
+        algorithm.
+
+    See Also
+    --------
+    linkage : for advanced creation of hierarchical clusterings.
+    scipy.spatial.distance.pdist : pairwise distance metrics
+
+    Examples
+    --------
+    >>> from scipy.cluster.hierarchy import ward, fcluster
+    >>> from scipy.spatial.distance import pdist
+
+    First, we need a toy dataset to play with::
+
+        x x    x x
+        x        x
+
+        x        x
+        x x    x x
+
+    >>> X = [[0, 0], [0, 1], [1, 0],
+    ...      [0, 4], [0, 3], [1, 4],
+    ...      [4, 0], [3, 0], [4, 1],
+    ...      [4, 4], [3, 4], [4, 3]]
+
+    Then, we get a condensed distance matrix from this dataset:
+
+    >>> y = pdist(X)
+
+    Finally, we can perform the clustering:
+
+    >>> Z = ward(y)
+    >>> Z
+    array([[ 0.        ,  1.        ,  1.        ,  2.        ],
+           [ 3.        ,  4.        ,  1.        ,  2.        ],
+           [ 6.        ,  7.        ,  1.        ,  2.        ],
+           [ 9.        , 10.        ,  1.        ,  2.        ],
+           [ 2.        , 12.        ,  1.29099445,  3.        ],
+           [ 5.        , 13.        ,  1.29099445,  3.        ],
+           [ 8.        , 14.        ,  1.29099445,  3.        ],
+           [11.        , 15.        ,  1.29099445,  3.        ],
+           [16.        , 17.        ,  5.77350269,  6.        ],
+           [18.        , 19.        ,  5.77350269,  6.        ],
+           [20.        , 21.        ,  8.16496581, 12.        ]])
+
+    The linkage matrix ``Z`` represents a dendrogram - see
+    `scipy.cluster.hierarchy.linkage` for a detailed explanation of its
+    contents.
+
+    We can use `scipy.cluster.hierarchy.fcluster` to see to which cluster
+    each initial point would belong given a distance threshold:
+
+    >>> fcluster(Z, 0.9, criterion='distance')
+    array([ 1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12], dtype=int32)
+    >>> fcluster(Z, 1.1, criterion='distance')
+    array([1, 1, 2, 3, 3, 4, 5, 5, 6, 7, 7, 8], dtype=int32)
+    >>> fcluster(Z, 3, criterion='distance')
+    array([1, 1, 1, 2, 2, 2, 3, 3, 3, 4, 4, 4], dtype=int32)
+    >>> fcluster(Z, 9, criterion='distance')
+    array([1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], dtype=int32)
+
+    Also, `scipy.cluster.hierarchy.dendrogram` can be used to generate a
+    plot of the dendrogram.
+
+    """
+    return linkage(y, method='ward', metric='euclidean')
+
+
+@lazy_cython
+def linkage(y, method='single', metric='euclidean', optimal_ordering=False):
+    """
+    Perform hierarchical/agglomerative clustering.
+
+    The input y may be either a 1-D condensed distance matrix
+    or a 2-D array of observation vectors.
+
+    If y is a 1-D condensed distance matrix,
+    then y must be a :math:`\\binom{n}{2}` sized
+    vector, where n is the number of original observations paired
+    in the distance matrix. The behavior of this function is very
+    similar to the MATLAB linkage function.
+
+    A :math:`(n-1)` by 4 matrix ``Z`` is returned. At the
+    :math:`i`-th iteration, clusters with indices ``Z[i, 0]`` and
+    ``Z[i, 1]`` are combined to form cluster :math:`n + i`. A
+    cluster with an index less than :math:`n` corresponds to one of
+    the :math:`n` original observations. The distance between
+    clusters ``Z[i, 0]`` and ``Z[i, 1]`` is given by ``Z[i, 2]``. The
+    fourth value ``Z[i, 3]`` represents the number of original
+    observations in the newly formed cluster.
+
+    The following linkage methods are used to compute the distance
+    :math:`d(s, t)` between two clusters :math:`s` and
+    :math:`t`. The algorithm begins with a forest of clusters that
+    have yet to be used in the hierarchy being formed. When two
+    clusters :math:`s` and :math:`t` from this forest are combined
+    into a single cluster :math:`u`, :math:`s` and :math:`t` are
+    removed from the forest, and :math:`u` is added to the
+    forest. When only one cluster remains in the forest, the algorithm
+    stops, and this cluster becomes the root.
+
+    A distance matrix is maintained at each iteration. The ``d[i,j]``
+    entry corresponds to the distance between cluster :math:`i` and
+    :math:`j` in the original forest.
+
+    At each iteration, the algorithm must update the distance matrix
+    to reflect the distance of the newly formed cluster u with the
+    remaining clusters in the forest.
+
+    Suppose there are :math:`|u|` original observations
+    :math:`u[0], \\ldots, u[|u|-1]` in cluster :math:`u` and
+    :math:`|v|` original objects :math:`v[0], \\ldots, v[|v|-1]` in
+    cluster :math:`v`. Recall, :math:`s` and :math:`t` are
+    combined to form cluster :math:`u`. Let :math:`v` be any
+    remaining cluster in the forest that is not :math:`u`.
+
+    The following are methods for calculating the distance between the
+    newly formed cluster :math:`u` and each :math:`v`.
+
+    * method='single' assigns
+
+      .. math::
+          d(u,v) = \\min(dist(u[i],v[j]))
+
+      for all points :math:`i` in cluster :math:`u` and
+      :math:`j` in cluster :math:`v`. This is also known as the
+      Nearest Point Algorithm.
+    * method='complete' assigns
+
+      .. math::
+          d(u, v) = \\max(dist(u[i],v[j]))
+
+      for all points :math:`i` in cluster u and :math:`j` in
+      cluster :math:`v`. This is also known by the Farthest Point
+      Algorithm or Voor Hees Algorithm.
+    * method='average' assigns
+
+      .. math::
+          d(u,v) = \\sum_{ij} \\frac{d(u[i], v[j])}
+                                  {(|u|*|v|)}
+
+      for all points :math:`i` and :math:`j` where :math:`|u|`
+      and :math:`|v|` are the cardinalities of clusters :math:`u`
+      and :math:`v`, respectively. This is also called the UPGMA
+      algorithm.
+    * method='weighted' assigns
+
+      .. math::
+          d(u,v) = (dist(s,v) + dist(t,v))/2
+
+      where cluster u was formed with cluster s and t and v
+      is a remaining cluster in the forest (also called WPGMA).
+    * method='centroid' assigns
+
+      .. math::
+          dist(s,t) = ||c_s-c_t||_2
+
+      where :math:`c_s` and :math:`c_t` are the centroids of
+      clusters :math:`s` and :math:`t`, respectively. When two
+      clusters :math:`s` and :math:`t` are combined into a new
+      cluster :math:`u`, the new centroid is computed over all the
+      original objects in clusters :math:`s` and :math:`t`. The
+      distance then becomes the Euclidean distance between the
+      centroid of :math:`u` and the centroid of a remaining cluster
+      :math:`v` in the forest. This is also known as the UPGMC
+      algorithm.
+    * method='median' assigns :math:`d(s,t)` like the ``centroid``
+      method. When two clusters :math:`s` and :math:`t` are combined
+      into a new cluster :math:`u`, the average of centroids s and t
+      give the new centroid :math:`u`. This is also known as the
+      WPGMC algorithm.
+    * method='ward' uses the Ward variance minimization algorithm.
+      The new entry :math:`d(u,v)` is computed as follows,
+
+      .. math::
+
+          d(u,v) = \\sqrt{\\frac{|v|+|s|}
+                              {T}d(v,s)^2
+                      + \\frac{|v|+|t|}
+                              {T}d(v,t)^2
+                      - \\frac{|v|}
+                              {T}d(s,t)^2}
+
+      where :math:`u` is the newly joined cluster consisting of
+      clusters :math:`s` and :math:`t`, :math:`v` is an unused
+      cluster in the forest, :math:`T=|v|+|s|+|t|`, and
+      :math:`|*|` is the cardinality of its argument. This is also
+      known as the incremental algorithm.
+
+    Warning: When the minimum distance pair in the forest is chosen, there
+    may be two or more pairs with the same minimum distance. This
+    implementation may choose a different minimum than the MATLAB
+    version.
+
+    Parameters
+    ----------
+    y : ndarray
+        A condensed distance matrix. A condensed distance matrix
+        is a flat array containing the upper triangular of the distance matrix.
+        This is the form that ``pdist`` returns. Alternatively, a collection of
+        :math:`m` observation vectors in :math:`n` dimensions may be passed as
+        an :math:`m` by :math:`n` array. All elements of the condensed distance
+        matrix must be finite, i.e., no NaNs or infs.
+    method : str, optional
+        The linkage algorithm to use. See the ``Linkage Methods`` section below
+        for full descriptions.
+    metric : str or function, optional
+        The distance metric to use in the case that y is a collection of
+        observation vectors; ignored otherwise. See the ``pdist``
+        function for a list of valid distance metrics. A custom distance
+        function can also be used.
+    optimal_ordering : bool, optional
+        If True, the linkage matrix will be reordered so that the distance
+        between successive leaves is minimal. This results in a more intuitive
+        tree structure when the data are visualized. defaults to False, because
+        this algorithm can be slow, particularly on large datasets [2]_. See
+        also the `optimal_leaf_ordering` function.
+
+        .. versionadded:: 1.0.0
+
+    Returns
+    -------
+    Z : ndarray
+        The hierarchical clustering encoded as a linkage matrix.
+
+    Notes
+    -----
+    1. For method 'single', an optimized algorithm based on minimum spanning
+       tree is implemented. It has time complexity :math:`O(n^2)`.
+       For methods 'complete', 'average', 'weighted' and 'ward', an algorithm
+       called nearest-neighbors chain is implemented. It also has time
+       complexity :math:`O(n^2)`.
+       For other methods, a naive algorithm is implemented with :math:`O(n^3)`
+       time complexity.
+       All algorithms use :math:`O(n^2)` memory.
+       Refer to [1]_ for details about the algorithms.
+    2. Methods 'centroid', 'median', and 'ward' are correctly defined only if
+       Euclidean pairwise metric is used. If `y` is passed as precomputed
+       pairwise distances, then it is the user's responsibility to assure that
+       these distances are in fact Euclidean, otherwise the produced result
+       will be incorrect.
+
+    See Also
+    --------
+    scipy.spatial.distance.pdist : pairwise distance metrics
+
+    References
+    ----------
+    .. [1] Daniel Mullner, "Modern hierarchical, agglomerative clustering
+           algorithms", :arXiv:`1109.2378v1`.
+    .. [2] Ziv Bar-Joseph, David K. Gifford, Tommi S. Jaakkola, "Fast optimal
+           leaf ordering for hierarchical clustering", 2001. Bioinformatics
+           :doi:`10.1093/bioinformatics/17.suppl_1.S22`
+
+    Examples
+    --------
+    >>> from scipy.cluster.hierarchy import dendrogram, linkage
+    >>> from matplotlib import pyplot as plt
+    >>> X = [[i] for i in [2, 8, 0, 4, 1, 9, 9, 0]]
+
+    >>> Z = linkage(X, 'ward')
+    >>> fig = plt.figure(figsize=(25, 10))
+    >>> dn = dendrogram(Z)
+
+    >>> Z = linkage(X, 'single')
+    >>> fig = plt.figure(figsize=(25, 10))
+    >>> dn = dendrogram(Z)
+    >>> plt.show()
+    """
+    xp = array_namespace(y)
+    y = _asarray(y, order='C', dtype=xp.float64, xp=xp)
+    lazy = is_lazy_array(y)
+
+    if method not in _LINKAGE_METHODS:
+        raise ValueError(f"Invalid method: {method}")
+
+    if method in _EUCLIDEAN_METHODS and metric != 'euclidean' and y.ndim == 2:
+        msg = f"`method={method}` requires the distance metric to be Euclidean"
+        raise ValueError(msg)
+
+    if y.ndim == 1:
+        distance.is_valid_y(y, throw=True, name='y')
+    elif y.ndim == 2:
+        if (not lazy and y.shape[0] == y.shape[1]
+            and xp.all(xpx.isclose(xp.linalg.diagonal(y), 0))
+            and xp.all(y >= 0) and xp.all(xpx.isclose(y, y.T))):
+            warnings.warn('The symmetric non-negative hollow observation '
+                          'matrix looks suspiciously like an uncondensed '
+                          'distance matrix',
+                          ClusterWarning, stacklevel=2)
+        y = distance.pdist(y, metric)
+    else:
+        raise ValueError("`y` must be 1 or 2 dimensional.")
+
+    if not lazy and not xp.all(xp.isfinite(y)):
+        raise ValueError("The condensed distance matrix must contain only "
+                         "finite values.")
+
+    n = distance.num_obs_y(y)
+    method_code = _LINKAGE_METHODS[method]
+
+    def cy_linkage(y, validate):
+        if validate and not np.all(np.isfinite(y)):
+            raise ValueError("The condensed distance matrix must contain only "
+                            "finite values.")
+
+        if method == 'single':
+            return _hierarchy.mst_single_linkage(y, n)
+        elif method in ('complete', 'average', 'weighted', 'ward'):
+            return _hierarchy.nn_chain(y, n, method_code)
+        else:
+            return _hierarchy.fast_linkage(y, n, method_code)
+
+    result = xpx.lazy_apply(cy_linkage, y, validate=lazy,
+                            shape=(n - 1, 4), dtype=xp.float64,
+                            as_numpy=True, xp=xp)
+
+    if optimal_ordering:
+        return optimal_leaf_ordering(result, y)
+    else:
+        return result
+
+
+class ClusterNode:
+    """
+    A tree node class for representing a cluster.
+
+    Leaf nodes correspond to original observations, while non-leaf nodes
+    correspond to non-singleton clusters.
+
+    The `to_tree` function converts a matrix returned by the linkage
+    function into an easy-to-use tree representation.
+
+    All parameter names are also attributes.
+
+    Parameters
+    ----------
+    id : int
+        The node id.
+    left : ClusterNode instance, optional
+        The left child tree node.
+    right : ClusterNode instance, optional
+        The right child tree node.
+    dist : float, optional
+        Distance for this cluster in the linkage matrix.
+    count : int, optional
+        The number of samples in this cluster.
+
+    See Also
+    --------
+    to_tree : for converting a linkage matrix ``Z`` into a tree object.
+
+    """
+
+    def __init__(self, id, left=None, right=None, dist=0.0, count=1):
+        if id < 0:
+            raise ValueError('The id must be non-negative.')
+        if dist < 0:
+            raise ValueError('The distance must be non-negative.')
+        if (left is None and right is not None) or \
+           (left is not None and right is None):
+            raise ValueError('Only full or proper binary trees are permitted.'
+                             '  This node has one child.')
+        if count < 1:
+            raise ValueError('A cluster must contain at least one original '
+                             'observation.')
+        self.id = id
+        self.left = left
+        self.right = right
+        self.dist = dist
+        if self.left is None:
+            self.count = count
+        else:
+            self.count = left.count + right.count
+
+    def __lt__(self, node):
+        if not isinstance(node, ClusterNode):
+            raise ValueError("Can't compare ClusterNode "
+                             f"to type {type(node)}")
+        return self.dist < node.dist
+
+    def __gt__(self, node):
+        if not isinstance(node, ClusterNode):
+            raise ValueError("Can't compare ClusterNode "
+                             f"to type {type(node)}")
+        return self.dist > node.dist
+
+    def __eq__(self, node):
+        if not isinstance(node, ClusterNode):
+            raise ValueError("Can't compare ClusterNode "
+                             f"to type {type(node)}")
+        return self.dist == node.dist
+
+    def get_id(self):
+        """
+        The identifier of the target node.
+
+        For ``0 <= i < n``, `i` corresponds to original observation i.
+        For ``n <= i < 2n-1``, `i` corresponds to non-singleton cluster formed
+        at iteration ``i-n``.
+
+        Returns
+        -------
+        id : int
+            The identifier of the target node.
+
+        """
+        return self.id
+
+    def get_count(self):
+        """
+        The number of leaf nodes (original observations) belonging to
+        the cluster node nd. If the target node is a leaf, 1 is
+        returned.
+
+        Returns
+        -------
+        get_count : int
+            The number of leaf nodes below the target node.
+
+        """
+        return self.count
+
+    def get_left(self):
+        """
+        Return a reference to the left child tree object.
+
+        Returns
+        -------
+        left : ClusterNode
+            The left child of the target node. If the node is a leaf,
+            None is returned.
+
+        """
+        return self.left
+
+    def get_right(self):
+        """
+        Return a reference to the right child tree object.
+
+        Returns
+        -------
+        right : ClusterNode
+            The left child of the target node. If the node is a leaf,
+            None is returned.
+
+        """
+        return self.right
+
+    def is_leaf(self):
+        """
+        Return True if the target node is a leaf.
+
+        Returns
+        -------
+        leafness : bool
+            True if the target node is a leaf node.
+
+        """
+        return self.left is None
+
+    def pre_order(self, func=(lambda x: x.id)):
+        """
+        Perform pre-order traversal without recursive function calls.
+
+        When a leaf node is first encountered, ``func`` is called with
+        the leaf node as its argument, and its result is appended to
+        the list.
+
+        For example, the statement::
+
+           ids = root.pre_order(lambda x: x.id)
+
+        returns a list of the node ids corresponding to the leaf nodes
+        of the tree as they appear from left to right.
+
+        Parameters
+        ----------
+        func : function
+            Applied to each leaf ClusterNode object in the pre-order traversal.
+            Given the ``i``-th leaf node in the pre-order traversal ``n[i]``,
+            the result of ``func(n[i])`` is stored in ``L[i]``. If not
+            provided, the index of the original observation to which the node
+            corresponds is used.
+
+        Returns
+        -------
+        L : list
+            The pre-order traversal.
+
+        """
+        # Do a preorder traversal, caching the result. To avoid having to do
+        # recursion, we'll store the previous index we've visited in a vector.
+        n = self.count
+
+        curNode = [None] * (2 * n)
+        lvisited = set()
+        rvisited = set()
+        curNode[0] = self
+        k = 0
+        preorder = []
+        while k >= 0:
+            nd = curNode[k]
+            ndid = nd.id
+            if nd.is_leaf():
+                preorder.append(func(nd))
+                k = k - 1
+            else:
+                if ndid not in lvisited:
+                    curNode[k + 1] = nd.left
+                    lvisited.add(ndid)
+                    k = k + 1
+                elif ndid not in rvisited:
+                    curNode[k + 1] = nd.right
+                    rvisited.add(ndid)
+                    k = k + 1
+                # If we've visited the left and right of this non-leaf
+                # node already, go up in the tree.
+                else:
+                    k = k - 1
+
+        return preorder
+
+
+_cnode_bare = ClusterNode(0)
+_cnode_type = type(ClusterNode)
+
+
+def _order_cluster_tree(Z):
+    """
+    Return clustering nodes in bottom-up order by distance.
+
+    Parameters
+    ----------
+    Z : scipy.cluster.linkage array
+        The linkage matrix.
+
+    Returns
+    -------
+    nodes : list
+        A list of ClusterNode objects.
+    """
+    q = deque()
+    tree = to_tree(Z)
+    q.append(tree)
+    nodes = []
+
+    while q:
+        node = q.popleft()
+        if not node.is_leaf():
+            bisect.insort_left(nodes, node)
+            q.append(node.get_right())
+            q.append(node.get_left())
+    return nodes
+
+
+@xp_capabilities(np_only=True, reason="non-standard indexing")
+def cut_tree(Z, n_clusters=None, height=None):
+    """
+    Given a linkage matrix Z, return the cut tree.
+
+    Parameters
+    ----------
+    Z : scipy.cluster.linkage array
+        The linkage matrix.
+    n_clusters : array_like, optional
+        Number of clusters in the tree at the cut point.
+    height : array_like, optional
+        The height at which to cut the tree. Only possible for ultrametric
+        trees.
+
+    Returns
+    -------
+    cutree : array
+        An array indicating group membership at each agglomeration step. I.e.,
+        for a full cut tree, in the first column each data point is in its own
+        cluster. At the next step, two nodes are merged. Finally, all
+        singleton and non-singleton clusters are in one group. If `n_clusters`
+        or `height` are given, the columns correspond to the columns of
+        `n_clusters` or `height`.
+
+    Examples
+    --------
+    >>> from scipy import cluster
+    >>> import numpy as np
+    >>> from numpy.random import default_rng
+    >>> rng = default_rng()
+    >>> X = rng.random((50, 4))
+    >>> Z = cluster.hierarchy.ward(X)
+    >>> cutree = cluster.hierarchy.cut_tree(Z, n_clusters=[5, 10])
+    >>> cutree[:10]
+    array([[0, 0],
+           [1, 1],
+           [2, 2],
+           [3, 3],
+           [3, 4],
+           [2, 2],
+           [0, 0],
+           [1, 5],
+           [3, 6],
+           [4, 7]])  # random
+
+    """
+    xp = array_namespace(Z)
+    nobs = num_obs_linkage(Z)
+    nodes = _order_cluster_tree(Z)
+
+    if height is not None and n_clusters is not None:
+        raise ValueError("At least one of either height or n_clusters "
+                         "must be None")
+    elif height is None and n_clusters is None:  # return the full cut tree
+        cols_idx = xp.arange(nobs)
+    elif height is not None:
+        height = xp.asarray(height)
+        heights = xp.asarray([x.dist for x in nodes])
+        cols_idx = xp.searchsorted(heights, height)
+    else:
+        n_clusters = xp.asarray(n_clusters)
+        cols_idx = nobs - xp.searchsorted(xp.arange(nobs), n_clusters)
+
+    try:
+        n_cols = len(cols_idx)
+    except TypeError:  # scalar
+        n_cols = 1
+        cols_idx = xp.asarray([cols_idx])
+
+    groups = xp.zeros((n_cols, nobs), dtype=xp.int64)
+    last_group = xp.arange(nobs)
+    if 0 in cols_idx:
+        groups[0] = last_group
+
+    for i, node in enumerate(nodes):
+        idx = node.pre_order()
+        this_group = xp_copy(last_group, xp=xp)
+        # TODO ARRAY_API complex indexing not supported
+        this_group[idx] = xp.min(last_group[idx])
+        this_group[this_group > xp.max(last_group[idx])] -= 1
+        if i + 1 in cols_idx:
+            groups[np.nonzero(i + 1 == cols_idx)[0]] = this_group
+        last_group = this_group
+
+    return groups.T
+
+
+@xp_capabilities(jax_jit=False, allow_dask_compute=True)
+def to_tree(Z, rd=False):
+    """
+    Convert a linkage matrix into an easy-to-use tree object.
+
+    The reference to the root `ClusterNode` object is returned (by default).
+
+    Each `ClusterNode` object has a ``left``, ``right``, ``dist``, ``id``,
+    and ``count`` attribute. The left and right attributes point to
+    ClusterNode objects that were combined to generate the cluster.
+    If both are None then the `ClusterNode` object is a leaf node, its count
+    must be 1, and its distance is meaningless but set to 0.
+
+    *Note: This function is provided for the convenience of the library
+    user. ClusterNodes are not used as input to any of the functions in this
+    library.*
+
+    Parameters
+    ----------
+    Z : ndarray
+        The linkage matrix in proper form (see the `linkage`
+        function documentation).
+    rd : bool, optional
+        When False (default), a reference to the root `ClusterNode` object is
+        returned.  Otherwise, a tuple ``(r, d)`` is returned. ``r`` is a
+        reference to the root node while ``d`` is a list of `ClusterNode`
+        objects - one per original entry in the linkage matrix plus entries
+        for all clustering steps. If a cluster id is
+        less than the number of samples ``n`` in the data that the linkage
+        matrix describes, then it corresponds to a singleton cluster (leaf
+        node).
+        See `linkage` for more information on the assignment of cluster ids
+        to clusters.
+
+    Returns
+    -------
+    tree : ClusterNode or tuple (ClusterNode, list of ClusterNode)
+        If ``rd`` is False, a `ClusterNode`.
+        If ``rd`` is True, a list of length ``2*n - 1``, with ``n`` the number
+        of samples.  See the description of `rd` above for more details.
+
+    See Also
+    --------
+    linkage, is_valid_linkage, ClusterNode
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy.cluster import hierarchy
+    >>> rng = np.random.default_rng()
+    >>> x = rng.random((5, 2))
+    >>> Z = hierarchy.linkage(x)
+    >>> hierarchy.to_tree(Z)
+    >> rootnode, nodelist = hierarchy.to_tree(Z, rd=True)
+    >>> rootnode
+    >> len(nodelist)
+    9
+
+    """
+    xp = array_namespace(Z)
+    Z = _asarray(Z, order='C', xp=xp)
+    _is_valid_linkage(Z, throw=True, name='Z', materialize=True, xp=xp)
+
+    # Number of original objects is equal to the number of rows plus 1.
+    n = Z.shape[0] + 1
+
+    # Create a list full of None's to store the node objects
+    d = [None] * (n * 2 - 1)
+
+    # Create the nodes corresponding to the n original objects.
+    for i in range(0, n):
+        d[i] = ClusterNode(i)
+
+    nd = None
+
+    for i in range(Z.shape[0]):
+        row = Z[i, :]
+
+        fi = _int_floor(row[0], xp)
+        fj = _int_floor(row[1], xp)
+        if fi > i + n:
+            raise ValueError('Corrupt matrix Z. Index to derivative cluster '
+                              f'is used before it is formed. See row {fi}, '
+                              'column 0')
+        if fj > i + n:
+            raise ValueError('Corrupt matrix Z. Index to derivative cluster '
+                              f'is used before it is formed. See row {fj}, '
+                              'column 1')
+
+        nd = ClusterNode(i + n, d[fi], d[fj], row[2])
+        #                ^ id   ^ left ^ right ^ dist
+        if row[3] != nd.count:
+            raise ValueError(f'Corrupt matrix Z. The count Z[{i},3] is '
+                              'incorrect.')
+        d[n + i] = nd
+
+    if rd:
+        return (nd, d)
+    else:
+        return nd
+
+
+@lazy_cython
+def optimal_leaf_ordering(Z, y, metric='euclidean'):
+    """
+    Given a linkage matrix Z and distance, reorder the cut tree.
+
+    Parameters
+    ----------
+    Z : ndarray
+        The hierarchical clustering encoded as a linkage matrix. See
+        `linkage` for more information on the return structure and
+        algorithm.
+    y : ndarray
+        The condensed distance matrix from which Z was generated.
+        Alternatively, a collection of m observation vectors in n
+        dimensions may be passed as an m by n array.
+    metric : str or function, optional
+        The distance metric to use in the case that y is a collection of
+        observation vectors; ignored otherwise. See the ``pdist``
+        function for a list of valid distance metrics. A custom distance
+        function can also be used.
+
+    Returns
+    -------
+    Z_ordered : ndarray
+        A copy of the linkage matrix Z, reordered to minimize the distance
+        between adjacent leaves.
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy.cluster import hierarchy
+    >>> rng = np.random.default_rng()
+    >>> X = rng.standard_normal((10, 10))
+    >>> Z = hierarchy.ward(X)
+    >>> hierarchy.leaves_list(Z)
+    array([0, 3, 1, 9, 2, 5, 7, 4, 6, 8], dtype=int32)
+    >>> hierarchy.leaves_list(hierarchy.optimal_leaf_ordering(Z, X))
+    array([3, 0, 2, 5, 7, 4, 8, 6, 9, 1], dtype=int32)
+
+    """
+    xp = array_namespace(Z, y)
+    Z = _asarray(Z, order='C', xp=xp)
+    y = _asarray(y, order='C', dtype=xp.float64, xp=xp)
+    lazy = is_lazy_array(Z)
+    _is_valid_linkage(Z, throw=True, name='Z', xp=xp)
+
+    if y.ndim == 1:
+        distance.is_valid_y(y, throw=True, name='y')
+    elif y.ndim == 2:
+        if (not lazy and y.shape[0] == y.shape[1]
+            and xp.all(xpx.isclose(xp.linalg.diagonal(y), 0))
+            and xp.all(y >= 0) and xp.all(xpx.isclose(y, y.T))):
+            warnings.warn('The symmetric non-negative hollow observation '
+                          'matrix looks suspiciously like an uncondensed '
+                          'distance matrix',
+                          ClusterWarning, stacklevel=2)
+        y = distance.pdist(y, metric)
+    else:
+        raise ValueError("`y` must be 1 or 2 dimensional.")
+    if not lazy and not xp.all(xp.isfinite(y)):
+        raise ValueError("The condensed distance matrix must contain only "
+                         "finite values.")
+
+    # The function name is prominently visible on the user-facing Dask dashboard;
+    # make sure it is meaningful.
+    def cy_optimal_leaf_ordering(Z, y, validate):
+        if validate:
+            _is_valid_linkage(Z, throw=True, name='Z', xp=np)
+            if not np.all(np.isfinite(y)):
+                raise ValueError("The condensed distance matrix must contain only "
+                                 "finite values.")
+        return _optimal_leaf_ordering.optimal_leaf_ordering(Z, y)
+
+    return xpx.lazy_apply(cy_optimal_leaf_ordering, Z, y, validate=lazy,
+                          shape=Z.shape, dtype=Z.dtype, as_numpy=True, xp=xp)
+
+
+@lazy_cython
+def cophenet(Z, Y=None):
+    """
+    Calculate the cophenetic distances between each observation in
+    the hierarchical clustering defined by the linkage ``Z``.
+
+    Suppose ``p`` and ``q`` are original observations in
+    disjoint clusters ``s`` and ``t``, respectively and
+    ``s`` and ``t`` are joined by a direct parent cluster
+    ``u``. The cophenetic distance between observations
+    ``i`` and ``j`` is simply the distance between
+    clusters ``s`` and ``t``.
+
+    Parameters
+    ----------
+    Z : ndarray
+        The hierarchical clustering encoded as an array
+        (see `linkage` function).
+    Y : ndarray (optional)
+        Calculates the cophenetic correlation coefficient ``c`` of a
+        hierarchical clustering defined by the linkage matrix `Z`
+        of a set of :math:`n` observations in :math:`m`
+        dimensions. `Y` is the condensed distance matrix from which
+        `Z` was generated.
+
+    Returns
+    -------
+    c : ndarray
+        The cophentic correlation distance (if ``Y`` is passed).
+    d : ndarray
+        The cophenetic distance matrix in condensed form. The
+        :math:`ij` th entry is the cophenetic distance between
+        original observations :math:`i` and :math:`j`.
+
+    See Also
+    --------
+    linkage :
+        for a description of what a linkage matrix is.
+    scipy.spatial.distance.squareform :
+        transforming condensed matrices into square ones.
+
+    Examples
+    --------
+    >>> from scipy.cluster.hierarchy import single, cophenet
+    >>> from scipy.spatial.distance import pdist, squareform
+
+    Given a dataset ``X`` and a linkage matrix ``Z``, the cophenetic distance
+    between two points of ``X`` is the distance between the largest two
+    distinct clusters that each of the points:
+
+    >>> X = [[0, 0], [0, 1], [1, 0],
+    ...      [0, 4], [0, 3], [1, 4],
+    ...      [4, 0], [3, 0], [4, 1],
+    ...      [4, 4], [3, 4], [4, 3]]
+
+    ``X`` corresponds to this dataset ::
+
+        x x    x x
+        x        x
+
+        x        x
+        x x    x x
+
+    >>> Z = single(pdist(X))
+    >>> Z
+    array([[ 0.,  1.,  1.,  2.],
+           [ 2., 12.,  1.,  3.],
+           [ 3.,  4.,  1.,  2.],
+           [ 5., 14.,  1.,  3.],
+           [ 6.,  7.,  1.,  2.],
+           [ 8., 16.,  1.,  3.],
+           [ 9., 10.,  1.,  2.],
+           [11., 18.,  1.,  3.],
+           [13., 15.,  2.,  6.],
+           [17., 20.,  2.,  9.],
+           [19., 21.,  2., 12.]])
+    >>> cophenet(Z)
+    array([1., 1., 2., 2., 2., 2., 2., 2., 2., 2., 2., 1., 2., 2., 2., 2., 2.,
+           2., 2., 2., 2., 2., 2., 2., 2., 2., 2., 2., 2., 2., 1., 1., 2., 2.,
+           2., 2., 2., 2., 1., 2., 2., 2., 2., 2., 2., 2., 2., 2., 2., 2., 2.,
+           1., 1., 2., 2., 2., 1., 2., 2., 2., 2., 2., 2., 1., 1., 1.])
+
+    The output of the `scipy.cluster.hierarchy.cophenet` method is
+    represented in condensed form. We can use
+    `scipy.spatial.distance.squareform` to see the output as a
+    regular matrix (where each element ``ij`` denotes the cophenetic distance
+    between each ``i``, ``j`` pair of points in ``X``):
+
+    >>> squareform(cophenet(Z))
+    array([[0., 1., 1., 2., 2., 2., 2., 2., 2., 2., 2., 2.],
+           [1., 0., 1., 2., 2., 2., 2., 2., 2., 2., 2., 2.],
+           [1., 1., 0., 2., 2., 2., 2., 2., 2., 2., 2., 2.],
+           [2., 2., 2., 0., 1., 1., 2., 2., 2., 2., 2., 2.],
+           [2., 2., 2., 1., 0., 1., 2., 2., 2., 2., 2., 2.],
+           [2., 2., 2., 1., 1., 0., 2., 2., 2., 2., 2., 2.],
+           [2., 2., 2., 2., 2., 2., 0., 1., 1., 2., 2., 2.],
+           [2., 2., 2., 2., 2., 2., 1., 0., 1., 2., 2., 2.],
+           [2., 2., 2., 2., 2., 2., 1., 1., 0., 2., 2., 2.],
+           [2., 2., 2., 2., 2., 2., 2., 2., 2., 0., 1., 1.],
+           [2., 2., 2., 2., 2., 2., 2., 2., 2., 1., 0., 1.],
+           [2., 2., 2., 2., 2., 2., 2., 2., 2., 1., 1., 0.]])
+
+    In this example, the cophenetic distance between points on ``X`` that are
+    very close (i.e., in the same corner) is 1. For other pairs of points is 2,
+    because the points will be located in clusters at different
+    corners - thus, the distance between these clusters will be larger.
+
+    """
+    xp = array_namespace(Z, Y)
+    # Ensure float64 C-contiguous array. Cython code doesn't deal with striding.
+    Z = _asarray(Z, order='C', dtype=xp.float64, xp=xp)
+    _is_valid_linkage(Z, throw=True, name='Z', xp=xp)
+
+    def cy_cophenet(Z, validate):
+        if validate:
+            _is_valid_linkage(Z, throw=True, name='Z', xp=np)
+        n = Z.shape[0] + 1
+        zz = np.zeros((n * (n-1)) // 2, dtype=np.float64)
+        _hierarchy.cophenetic_distances(Z, zz, n)
+        return zz
+
+    n = Z.shape[0] + 1
+    zz = xpx.lazy_apply(cy_cophenet, Z, validate=is_lazy_array(Z),
+                        shape=((n * (n-1)) // 2, ), dtype=xp.float64,
+                        as_numpy=True, xp=xp)
+
+    if Y is None:
+        return zz
+
+    Y = _asarray(Y, order='C', xp=xp)
+    distance.is_valid_y(Y, throw=True, name='Y')
+
+    z = xp.mean(zz)
+    y = xp.mean(Y)
+    Yy = Y - y
+    Zz = zz - z
+    numerator = (Yy * Zz)
+    denomA = Yy**2
+    denomB = Zz**2
+    c = xp.sum(numerator) / xp.sqrt(xp.sum(denomA) * xp.sum(denomB))
+    return (c, zz)
+
+
+@lazy_cython
+def inconsistent(Z, d=2):
+    r"""
+    Calculate inconsistency statistics on a linkage matrix.
+
+    Parameters
+    ----------
+    Z : ndarray
+        The :math:`(n-1)` by 4 matrix encoding the linkage (hierarchical
+        clustering).  See `linkage` documentation for more information on its
+        form.
+    d : int, optional
+        The number of links up to `d` levels below each non-singleton cluster.
+
+    Returns
+    -------
+    R : ndarray
+        A :math:`(n-1)` by 4 matrix where the ``i``'th row contains the link
+        statistics for the non-singleton cluster ``i``. The link statistics are
+        computed over the link heights for links :math:`d` levels below the
+        cluster ``i``. ``R[i,0]`` and ``R[i,1]`` are the mean and standard
+        deviation of the link heights, respectively; ``R[i,2]`` is the number
+        of links included in the calculation; and ``R[i,3]`` is the
+        inconsistency coefficient,
+
+        .. math:: \frac{\mathtt{Z[i,2]} - \mathtt{R[i,0]}} {R[i,1]}
+
+    Notes
+    -----
+    This function behaves similarly to the MATLAB(TM) ``inconsistent``
+    function.
+
+    Examples
+    --------
+    >>> from scipy.cluster.hierarchy import inconsistent, linkage
+    >>> from matplotlib import pyplot as plt
+    >>> X = [[i] for i in [2, 8, 0, 4, 1, 9, 9, 0]]
+    >>> Z = linkage(X, 'ward')
+    >>> print(Z)
+    [[ 5.          6.          0.          2.        ]
+     [ 2.          7.          0.          2.        ]
+     [ 0.          4.          1.          2.        ]
+     [ 1.          8.          1.15470054  3.        ]
+     [ 9.         10.          2.12132034  4.        ]
+     [ 3.         12.          4.11096096  5.        ]
+     [11.         13.         14.07183949  8.        ]]
+    >>> inconsistent(Z)
+    array([[ 0.        ,  0.        ,  1.        ,  0.        ],
+           [ 0.        ,  0.        ,  1.        ,  0.        ],
+           [ 1.        ,  0.        ,  1.        ,  0.        ],
+           [ 0.57735027,  0.81649658,  2.        ,  0.70710678],
+           [ 1.04044011,  1.06123822,  3.        ,  1.01850858],
+           [ 3.11614065,  1.40688837,  2.        ,  0.70710678],
+           [ 6.44583366,  6.76770586,  3.        ,  1.12682288]])
+
+    """
+    xp = array_namespace(Z)
+    Z = _asarray(Z, order='C', dtype=xp.float64, xp=xp)
+    _is_valid_linkage(Z, throw=True, name='Z', xp=xp)
+
+    if d != np.floor(d) or d < 0:
+        raise ValueError('The second argument d must be a nonnegative '
+                         'integer value.')
+
+    def cy_inconsistent(Z, d, validate):
+        if validate:
+            _is_valid_linkage(Z, throw=True, name='Z', xp=np)
+        R = np.zeros((Z.shape[0], 4), dtype=np.float64)
+        n = Z.shape[0] + 1
+        _hierarchy.inconsistent(Z, R, n, d)
+        return R
+
+    return xpx.lazy_apply(cy_inconsistent, Z, d=int(d), validate=is_lazy_array(Z),
+                          shape=(Z.shape[0], 4), dtype=xp.float64,
+                          as_numpy=True, xp=xp)
+
+
+@lazy_cython
+def from_mlab_linkage(Z):
+    """
+    Convert a linkage matrix generated by MATLAB(TM) to a new
+    linkage matrix compatible with this module.
+
+    The conversion does two things:
+
+     * the indices are converted from ``1..N`` to ``0..(N-1)`` form,
+       and
+
+     * a fourth column ``Z[:,3]`` is added where ``Z[i,3]`` represents the
+       number of original observations (leaves) in the non-singleton
+       cluster ``i``.
+
+    This function is useful when loading in linkages from legacy data
+    files generated by MATLAB.
+
+    Parameters
+    ----------
+    Z : ndarray
+        A linkage matrix generated by MATLAB(TM).
+
+    Returns
+    -------
+    ZS : ndarray
+        A linkage matrix compatible with ``scipy.cluster.hierarchy``.
+
+    See Also
+    --------
+    linkage : for a description of what a linkage matrix is.
+    to_mlab_linkage : transform from SciPy to MATLAB format.
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy.cluster.hierarchy import ward, from_mlab_linkage
+
+    Given a linkage matrix in MATLAB format ``mZ``, we can use
+    `scipy.cluster.hierarchy.from_mlab_linkage` to import
+    it into SciPy format:
+
+    >>> mZ = np.array([[1, 2, 1], [4, 5, 1], [7, 8, 1],
+    ...                [10, 11, 1], [3, 13, 1.29099445],
+    ...                [6, 14, 1.29099445],
+    ...                [9, 15, 1.29099445],
+    ...                [12, 16, 1.29099445],
+    ...                [17, 18, 5.77350269],
+    ...                [19, 20, 5.77350269],
+    ...                [21, 22,  8.16496581]])
+
+    >>> Z = from_mlab_linkage(mZ)
+    >>> Z
+    array([[  0.        ,   1.        ,   1.        ,   2.        ],
+           [  3.        ,   4.        ,   1.        ,   2.        ],
+           [  6.        ,   7.        ,   1.        ,   2.        ],
+           [  9.        ,  10.        ,   1.        ,   2.        ],
+           [  2.        ,  12.        ,   1.29099445,   3.        ],
+           [  5.        ,  13.        ,   1.29099445,   3.        ],
+           [  8.        ,  14.        ,   1.29099445,   3.        ],
+           [ 11.        ,  15.        ,   1.29099445,   3.        ],
+           [ 16.        ,  17.        ,   5.77350269,   6.        ],
+           [ 18.        ,  19.        ,   5.77350269,   6.        ],
+           [ 20.        ,  21.        ,   8.16496581,  12.        ]])
+
+    As expected, the linkage matrix ``Z`` returned includes an
+    additional column counting the number of original samples in
+    each cluster. Also, all cluster indices are reduced by 1
+    (MATLAB format uses 1-indexing, whereas SciPy uses 0-indexing).
+
+    """
+    xp = array_namespace(Z)
+    Z = _asarray(Z, dtype=xp.float64, order='C', xp=xp)
+
+    # If it's empty, return it.
+    if Z.shape in ((), (0, )):
+        return xp_copy(Z, xp=xp)
+
+    if Z.ndim != 2:
+        raise ValueError("The linkage array must be rectangular.")
+
+    # If it contains no rows, return it.
+    n = Z.shape[0]
+    if n == 0:
+        return xp_copy(Z, xp=xp)
+
+    lazy = is_lazy_array(Z)
+
+    if not lazy and xp.min(Z[:, :2]) != 1.0 and xp.max(Z[:, :2]) != 2 * n:
+        raise ValueError('The format of the indices is not 1..N')
+
+    res = xp.empty((Z.shape[0], Z.shape[1] + 1), dtype=Z.dtype)
+    res = xpx.at(res)[:, :2].set(Z[:, :2] - 1.0)
+    res = xpx.at(res)[:, 2:-1].set(Z[:, 2:])
+
+    def cy_from_mlab_linkage(Zpart, validate):
+        n = Zpart.shape[0]
+        if validate and np.min(Zpart[:, :2]) != 0.0 and np.max(Zpart[:, :2]) != 2 * n:
+            raise ValueError('The format of the indices is not 1..N')
+
+        if not Zpart.flags.writeable:
+            Zpart = Zpart.copy()  # xp=jax.numpy
+
+        CS = np.zeros((n,))
+        _hierarchy.calculate_cluster_sizes(Zpart, CS, n + 1)
+        return CS
+
+    CS = xpx.lazy_apply(cy_from_mlab_linkage, res[:, :-1], validate=lazy,
+                        shape=(res.shape[0],), dtype=xp.float64,
+                        as_numpy=True, xp=xp)
+
+    return xpx.at(res)[:, -1].set(CS)
+
+
+@xp_capabilities()
+def to_mlab_linkage(Z):
+    """
+    Convert a linkage matrix to a MATLAB(TM) compatible one.
+
+    Converts a linkage matrix ``Z`` generated by the linkage function
+    of this module to a MATLAB(TM) compatible one. The return linkage
+    matrix has the last column removed and the cluster indices are
+    converted to ``1..N`` indexing.
+
+    Parameters
+    ----------
+    Z : ndarray
+        A linkage matrix generated by ``scipy.cluster.hierarchy``.
+
+    Returns
+    -------
+    to_mlab_linkage : ndarray
+        A linkage matrix compatible with MATLAB(TM)'s hierarchical
+        clustering functions.
+
+        The return linkage matrix has the last column removed
+        and the cluster indices are converted to ``1..N`` indexing.
+
+    See Also
+    --------
+    linkage : for a description of what a linkage matrix is.
+    from_mlab_linkage : transform from Matlab to SciPy format.
+
+    Examples
+    --------
+    >>> from scipy.cluster.hierarchy import ward, to_mlab_linkage
+    >>> from scipy.spatial.distance import pdist
+
+    >>> X = [[0, 0], [0, 1], [1, 0],
+    ...      [0, 4], [0, 3], [1, 4],
+    ...      [4, 0], [3, 0], [4, 1],
+    ...      [4, 4], [3, 4], [4, 3]]
+
+    >>> Z = ward(pdist(X))
+    >>> Z
+    array([[ 0.        ,  1.        ,  1.        ,  2.        ],
+           [ 3.        ,  4.        ,  1.        ,  2.        ],
+           [ 6.        ,  7.        ,  1.        ,  2.        ],
+           [ 9.        , 10.        ,  1.        ,  2.        ],
+           [ 2.        , 12.        ,  1.29099445,  3.        ],
+           [ 5.        , 13.        ,  1.29099445,  3.        ],
+           [ 8.        , 14.        ,  1.29099445,  3.        ],
+           [11.        , 15.        ,  1.29099445,  3.        ],
+           [16.        , 17.        ,  5.77350269,  6.        ],
+           [18.        , 19.        ,  5.77350269,  6.        ],
+           [20.        , 21.        ,  8.16496581, 12.        ]])
+
+    After a linkage matrix ``Z`` has been created, we can use
+    `scipy.cluster.hierarchy.to_mlab_linkage` to convert it
+    into MATLAB format:
+
+    >>> mZ = to_mlab_linkage(Z)
+    >>> mZ
+    array([[  1.        ,   2.        ,   1.        ],
+           [  4.        ,   5.        ,   1.        ],
+           [  7.        ,   8.        ,   1.        ],
+           [ 10.        ,  11.        ,   1.        ],
+           [  3.        ,  13.        ,   1.29099445],
+           [  6.        ,  14.        ,   1.29099445],
+           [  9.        ,  15.        ,   1.29099445],
+           [ 12.        ,  16.        ,   1.29099445],
+           [ 17.        ,  18.        ,   5.77350269],
+           [ 19.        ,  20.        ,   5.77350269],
+           [ 21.        ,  22.        ,   8.16496581]])
+
+    The new linkage matrix ``mZ`` uses 1-indexing for all the
+    clusters (instead of 0-indexing). Also, the last column of
+    the original linkage matrix has been dropped.
+
+    """
+    xp = array_namespace(Z)
+    Z = _asarray(Z, dtype=xp.float64, xp=xp)
+    if Z.shape in ((), (0, )):
+        return xp_copy(Z, xp=xp)
+    _is_valid_linkage(Z, throw=True, name='Z', xp=xp)
+
+    return xp.concat((Z[:, :2] + 1.0, Z[:, 2:3]), axis=1)
+
+
+@xp_capabilities()
+def is_monotonic(Z):
+    """
+    Return True if the linkage passed is monotonic.
+
+    The linkage is monotonic if for every cluster :math:`s` and :math:`t`
+    joined, the distance between them is no less than the distance
+    between any previously joined clusters.
+
+    Parameters
+    ----------
+    Z : ndarray
+        The linkage matrix to check for monotonicity.
+
+    Returns
+    -------
+    b : bool
+        A boolean indicating whether the linkage is monotonic.
+
+    See Also
+    --------
+    linkage : for a description of what a linkage matrix is.
+
+    Examples
+    --------
+    >>> from scipy.cluster.hierarchy import median, ward, is_monotonic
+    >>> from scipy.spatial.distance import pdist
+
+    By definition, some hierarchical clustering algorithms - such as
+    `scipy.cluster.hierarchy.ward` - produce monotonic assignments of
+    samples to clusters; however, this is not always true for other
+    hierarchical methods - e.g. `scipy.cluster.hierarchy.median`.
+
+    Given a linkage matrix ``Z`` (as the result of a hierarchical clustering
+    method) we can test programmatically whether it has the monotonicity
+    property or not, using `scipy.cluster.hierarchy.is_monotonic`:
+
+    >>> X = [[0, 0], [0, 1], [1, 0],
+    ...      [0, 4], [0, 3], [1, 4],
+    ...      [4, 0], [3, 0], [4, 1],
+    ...      [4, 4], [3, 4], [4, 3]]
+
+    >>> Z = ward(pdist(X))
+    >>> Z
+    array([[ 0.        ,  1.        ,  1.        ,  2.        ],
+           [ 3.        ,  4.        ,  1.        ,  2.        ],
+           [ 6.        ,  7.        ,  1.        ,  2.        ],
+           [ 9.        , 10.        ,  1.        ,  2.        ],
+           [ 2.        , 12.        ,  1.29099445,  3.        ],
+           [ 5.        , 13.        ,  1.29099445,  3.        ],
+           [ 8.        , 14.        ,  1.29099445,  3.        ],
+           [11.        , 15.        ,  1.29099445,  3.        ],
+           [16.        , 17.        ,  5.77350269,  6.        ],
+           [18.        , 19.        ,  5.77350269,  6.        ],
+           [20.        , 21.        ,  8.16496581, 12.        ]])
+    >>> is_monotonic(Z)
+    True
+
+    >>> Z = median(pdist(X))
+    >>> Z
+    array([[ 0.        ,  1.        ,  1.        ,  2.        ],
+           [ 3.        ,  4.        ,  1.        ,  2.        ],
+           [ 9.        , 10.        ,  1.        ,  2.        ],
+           [ 6.        ,  7.        ,  1.        ,  2.        ],
+           [ 2.        , 12.        ,  1.11803399,  3.        ],
+           [ 5.        , 13.        ,  1.11803399,  3.        ],
+           [ 8.        , 15.        ,  1.11803399,  3.        ],
+           [11.        , 14.        ,  1.11803399,  3.        ],
+           [18.        , 19.        ,  3.        ,  6.        ],
+           [16.        , 17.        ,  3.5       ,  6.        ],
+           [20.        , 21.        ,  3.25      , 12.        ]])
+    >>> is_monotonic(Z)
+    False
+
+    Note that this method is equivalent to just verifying that the distances
+    in the third column of the linkage matrix appear in a monotonically
+    increasing order.
+
+    """
+    xp = array_namespace(Z)
+    Z = _asarray(Z, xp=xp)
+    _is_valid_linkage(Z, throw=True, name='Z', xp=xp)
+
+    # We expect the i'th value to be greater than its successor.
+    return xp.all(Z[1:, 2] >= Z[:-1, 2])
+
+
+@xp_capabilities(warnings=[("dask.array", "see notes"), ("jax.numpy", "see notes")])
+def is_valid_im(R, warning=False, throw=False, name=None):
+    """Return True if the inconsistency matrix passed is valid.
+
+    It must be a :math:`n` by 4 array of doubles. The standard
+    deviations ``R[:,1]`` must be nonnegative. The link counts
+    ``R[:,2]`` must be positive and no greater than :math:`n-1`.
+
+    Parameters
+    ----------
+    R : ndarray
+        The inconsistency matrix to check for validity.
+    warning : bool, optional
+        When True, issues a Python warning if the linkage
+        matrix passed is invalid.
+    throw : bool, optional
+        When True, throws a Python exception if the linkage
+        matrix passed is invalid.
+    name : str, optional
+        This string refers to the variable name of the invalid
+        linkage matrix.
+
+    Returns
+    -------
+    b : bool
+        True if the inconsistency matrix is valid; False otherwise.
+
+    Notes
+    -----
+    *Array API support (experimental):* If the input is a lazy Array (e.g. Dask
+    or JAX), the return value may be a 0-dimensional bool Array. When warning=True
+    or throw=True, calling this function materializes the array.
+
+    See Also
+    --------
+    linkage : for a description of what a linkage matrix is.
+    inconsistent : for the creation of a inconsistency matrix.
+
+    Examples
+    --------
+    >>> from scipy.cluster.hierarchy import ward, inconsistent, is_valid_im
+    >>> from scipy.spatial.distance import pdist
+
+    Given a data set ``X``, we can apply a clustering method to obtain a
+    linkage matrix ``Z``. `scipy.cluster.hierarchy.inconsistent` can
+    be also used to obtain the inconsistency matrix ``R`` associated to
+    this clustering process:
+
+    >>> X = [[0, 0], [0, 1], [1, 0],
+    ...      [0, 4], [0, 3], [1, 4],
+    ...      [4, 0], [3, 0], [4, 1],
+    ...      [4, 4], [3, 4], [4, 3]]
+
+    >>> Z = ward(pdist(X))
+    >>> R = inconsistent(Z)
+    >>> Z
+    array([[ 0.        ,  1.        ,  1.        ,  2.        ],
+           [ 3.        ,  4.        ,  1.        ,  2.        ],
+           [ 6.        ,  7.        ,  1.        ,  2.        ],
+           [ 9.        , 10.        ,  1.        ,  2.        ],
+           [ 2.        , 12.        ,  1.29099445,  3.        ],
+           [ 5.        , 13.        ,  1.29099445,  3.        ],
+           [ 8.        , 14.        ,  1.29099445,  3.        ],
+           [11.        , 15.        ,  1.29099445,  3.        ],
+           [16.        , 17.        ,  5.77350269,  6.        ],
+           [18.        , 19.        ,  5.77350269,  6.        ],
+           [20.        , 21.        ,  8.16496581, 12.        ]])
+    >>> R
+    array([[1.        , 0.        , 1.        , 0.        ],
+           [1.        , 0.        , 1.        , 0.        ],
+           [1.        , 0.        , 1.        , 0.        ],
+           [1.        , 0.        , 1.        , 0.        ],
+           [1.14549722, 0.20576415, 2.        , 0.70710678],
+           [1.14549722, 0.20576415, 2.        , 0.70710678],
+           [1.14549722, 0.20576415, 2.        , 0.70710678],
+           [1.14549722, 0.20576415, 2.        , 0.70710678],
+           [2.78516386, 2.58797734, 3.        , 1.15470054],
+           [2.78516386, 2.58797734, 3.        , 1.15470054],
+           [6.57065706, 1.38071187, 3.        , 1.15470054]])
+
+    Now we can use `scipy.cluster.hierarchy.is_valid_im` to verify that
+    ``R`` is correct:
+
+    >>> is_valid_im(R)
+    True
+
+    However, if ``R`` is wrongly constructed (e.g., one of the standard
+    deviations is set to a negative value), then the check will fail:
+
+    >>> R[-1,1] = R[-1,1] * -1
+    >>> is_valid_im(R)
+    False
+
+    """
+    xp = array_namespace(R)
+    R = _asarray(R, xp=xp)
+    return _is_valid_im(R, warning=warning, throw=throw, name=name,
+                        materialize=True, xp=xp)
+
+
+def _is_valid_im(R, warning=False, throw=False, name=None, materialize=False, *, xp):
+    """Variant of `is_valid_im` to be called internally by other scipy functions,
+    which by default does not materialize lazy input arrays (Dask, JAX, etc.) when
+    warning=True or throw=True.
+    """
+    name_str = f"{name!r} " if name else ''
+    try:
+        if R.dtype != xp.float64:
+            raise TypeError(f'Inconsistency matrix {name_str}must contain doubles '
+                            '(double).')
+        if len(R.shape) != 2:
+            raise ValueError(f'Inconsistency matrix {name_str}must have shape=2 (i.e. '
+                             'be two-dimensional).')
+        if R.shape[1] != 4:
+            raise ValueError(f'Inconsistency matrix {name_str}'
+                             'must have 4 columns.')
+        if R.shape[0] < 1:
+            raise ValueError(f'Inconsistency matrix {name_str}'
+                             'must have at least one row.')
+    except (TypeError, ValueError) as e:
+        if throw:
+            raise
+        if warning:
+            _warning(str(e))
+        return False
+
+    return _lazy_valid_checks(
+        (xp.any(R[:, 0] < 0),
+         f'Inconsistency matrix {name_str} contains negative link height means.'),
+        (xp.any(R[:, 1] < 0),
+         f'Inconsistency matrix {name_str} contains negative link height standard '
+         'deviations.'),
+        (xp.any(R[:, 2] < 0),
+         f'Inconsistency matrix {name_str} contains negative link counts.'),
+        throw=throw, warning=warning, materialize=materialize, xp=xp
+    )
+
+
+@xp_capabilities(warnings=[("dask.array", "see notes"), ("jax.numpy", "see notes")])
+def is_valid_linkage(Z, warning=False, throw=False, name=None):
+    """
+    Check the validity of a linkage matrix.
+
+    A linkage matrix is valid if it is a 2-D array (type double)
+    with :math:`n` rows and 4 columns. The first two columns must contain
+    indices between 0 and :math:`2n-1`. For a given row ``i``, the following
+    two expressions have to hold:
+
+    .. math::
+
+        0 \\leq \\mathtt{Z[i,0]} \\leq i+n-1
+        0 \\leq Z[i,1] \\leq i+n-1
+
+    I.e., a cluster cannot join another cluster unless the cluster being joined
+    has been generated.
+
+    The fourth column of `Z` represents the number of original observations
+    in a cluster, so a valid ``Z[i, 3]`` value may not exceed the number of
+    original observations.
+
+    Parameters
+    ----------
+    Z : array_like
+        Linkage matrix.
+    warning : bool, optional
+        When True, issues a Python warning if the linkage
+        matrix passed is invalid.
+    throw : bool, optional
+        When True, throws a Python exception if the linkage
+        matrix passed is invalid.
+    name : str, optional
+        This string refers to the variable name of the invalid
+        linkage matrix.
+
+    Returns
+    -------
+    b : bool
+        True if the inconsistency matrix is valid; False otherwise.
+
+    Notes
+    -----
+    *Array API support (experimental):* If the input is a lazy Array (e.g. Dask
+    or JAX), the return value may be a 0-dimensional bool Array. When warning=True
+    or throw=True, calling this function materializes the array.
+
+    See Also
+    --------
+    linkage: for a description of what a linkage matrix is.
+
+    Examples
+    --------
+    >>> from scipy.cluster.hierarchy import ward, is_valid_linkage
+    >>> from scipy.spatial.distance import pdist
+
+    All linkage matrices generated by the clustering methods in this module
+    will be valid (i.e., they will have the appropriate dimensions and the two
+    required expressions will hold for all the rows).
+
+    We can check this using `scipy.cluster.hierarchy.is_valid_linkage`:
+
+    >>> X = [[0, 0], [0, 1], [1, 0],
+    ...      [0, 4], [0, 3], [1, 4],
+    ...      [4, 0], [3, 0], [4, 1],
+    ...      [4, 4], [3, 4], [4, 3]]
+
+    >>> Z = ward(pdist(X))
+    >>> Z
+    array([[ 0.        ,  1.        ,  1.        ,  2.        ],
+           [ 3.        ,  4.        ,  1.        ,  2.        ],
+           [ 6.        ,  7.        ,  1.        ,  2.        ],
+           [ 9.        , 10.        ,  1.        ,  2.        ],
+           [ 2.        , 12.        ,  1.29099445,  3.        ],
+           [ 5.        , 13.        ,  1.29099445,  3.        ],
+           [ 8.        , 14.        ,  1.29099445,  3.        ],
+           [11.        , 15.        ,  1.29099445,  3.        ],
+           [16.        , 17.        ,  5.77350269,  6.        ],
+           [18.        , 19.        ,  5.77350269,  6.        ],
+           [20.        , 21.        ,  8.16496581, 12.        ]])
+    >>> is_valid_linkage(Z)
+    True
+
+    However, if we create a linkage matrix in a wrong way - or if we modify
+    a valid one in a way that any of the required expressions don't hold
+    anymore, then the check will fail:
+
+    >>> Z[3][1] = 20    # the cluster number 20 is not defined at this point
+    >>> is_valid_linkage(Z)
+    False
+
+    """
+    xp = array_namespace(Z)
+    Z = _asarray(Z, xp=xp)
+    return _is_valid_linkage(Z, warning=warning, throw=throw,
+                             name=name, materialize=True, xp=xp)
+
+
+def _is_valid_linkage(Z, warning=False, throw=False, name=None,
+                      materialize=False, *, xp):
+    """Variant of `is_valid_linkage` to be called internally by other scipy functions,
+    which by default does not materialize lazy input arrays (Dask, JAX, etc.) when
+    warning=True or throw=True.
+    """
+    name_str = f"{name!r} " if name else ''
+    try:
+        if Z.dtype != xp.float64:
+            raise TypeError(f'Linkage matrix {name_str}must contain doubles.')
+        if len(Z.shape) != 2:
+            raise ValueError(f'Linkage matrix {name_str}must have shape=2 (i.e. be'
+                             ' two-dimensional).')
+        if Z.shape[1] != 4:
+            raise ValueError(f'Linkage matrix {name_str}must have 4 columns.')
+        if Z.shape[0] == 0:
+            raise ValueError('Linkage must be computed on at least two '
+                             'observations.')
+    except (TypeError, ValueError) as e:
+        if throw:
+            raise
+        if warning:
+            _warning(str(e))
+        return False
+
+    n = Z.shape[0]
+    if n < 2:
+        return True
+
+    return _lazy_valid_checks(
+        (xp.any(Z[:, :2] < 0),
+         f'Linkage {name_str}contains negative indices.'),
+        (xp.any(Z[:, 2] < 0),
+         f'Linkage {name_str}contains negative distances.'),
+        (xp.any(Z[:, 3] < 0),
+         f'Linkage {name_str}contains negative counts.'),
+        (xp.any(Z[:, 3] > n + 1),
+         f'Linkage {name_str}contains excessive observations in a cluster'),
+        (xp.any(xp.max(Z[:, :2], axis=1) >= xp.arange(n + 1, 2 * n + 1, dtype=Z.dtype)),
+         f'Linkage {name_str}uses non-singleton cluster before it is formed.'),
+        (xpx.nunique(Z[:, :2]) < n * 2,
+         f'Linkage {name_str}uses the same cluster more than once.'),
+        throw=throw, warning=warning, materialize=materialize, xp=xp
+    )
+
+
+def _lazy_valid_checks(*args, throw=False, warning=False, materialize=False, xp):
+    """Validate a set of conditions on the contents of possibly lazy arrays.
+
+    Parameters
+    ----------
+    args : tuples of (Array, str)
+        The first element of each tuple must be a 0-dimensional Array
+        that evaluates to bool; the second element must be the message to convey
+        if the  first element evaluates to True.
+    throw: bool
+        Set to True to `raise ValueError(args[i][1])` if `args[i][0]` is True.
+    warning: bool
+        Set to True to issue a warning with message `args[i][1]` if `args[i][0]`
+        is True.
+    materialize: bool
+        Set to True to force materialization of lazy arrays when throw=True or
+        warning=True. If the inputs are lazy and materialize=False, ignore the
+        `throw` and `warning` flags.
+    xp: module
+        Array API namespace
+
+    Returns
+    -------
+    If xp is an eager backend (e.g. numpy) and all conditions are False, return True.
+    If throw is True, raise. Otherwise, return False.
+
+    If xp is a lazy backend (e.g. Dask or JAX), return a 0-dimensional bool Array.
+    """
+    conds = xp.concat([xp.reshape(cond, (1, )) for cond, _ in args])
+
+    lazy = is_lazy_array(conds)
+    if not throw and not warning or (lazy and not materialize):
+        out = ~xp.any(conds)
+        return out if lazy else bool(out)
+
+    if is_dask(xp):
+        # Only materialize the graph once, instead of once per check
+        conds = conds.compute()
+
+    # Don't call np.asarray(conds), as it would be blocked by the device transfer
+    # guard on CuPy and PyTorch and the densification guard on Sparse, whereas
+    # bool() will not.
+    conds = [bool(cond) for cond in conds]
+
+    for cond, (_, msg) in zip(conds, args):
+        if throw and cond:
+            raise ValueError(msg)
+        elif warning and cond:
+            warnings.warn(msg, ClusterWarning, stacklevel=3)
+
+    return not any(conds)
+
+
+@xp_capabilities()
+def num_obs_linkage(Z):
+    """
+    Return the number of original observations of the linkage matrix passed.
+
+    Parameters
+    ----------
+    Z : ndarray
+        The linkage matrix on which to perform the operation.
+
+    Returns
+    -------
+    n : int
+        The number of original observations in the linkage.
+
+    Examples
+    --------
+    >>> from scipy.cluster.hierarchy import ward, num_obs_linkage
+    >>> from scipy.spatial.distance import pdist
+
+    >>> X = [[0, 0], [0, 1], [1, 0],
+    ...      [0, 4], [0, 3], [1, 4],
+    ...      [4, 0], [3, 0], [4, 1],
+    ...      [4, 4], [3, 4], [4, 3]]
+
+    >>> Z = ward(pdist(X))
+
+    ``Z`` is a linkage matrix obtained after using the Ward clustering method
+    with ``X``, a dataset with 12 data points.
+
+    >>> num_obs_linkage(Z)
+    12
+
+    """
+    xp = array_namespace(Z)
+    Z = _asarray(Z, xp=xp)
+    _is_valid_linkage(Z, throw=True, name='Z', xp=xp)
+    return Z.shape[0] + 1
+
+
+@xp_capabilities()
+def correspond(Z, Y):
+    """
+    Check for correspondence between linkage and condensed distance matrices.
+
+    They must have the same number of original observations for
+    the check to succeed.
+
+    This function is useful as a sanity check in algorithms that make
+    extensive use of linkage and distance matrices that must
+    correspond to the same set of original observations.
+
+    Parameters
+    ----------
+    Z : array_like
+        The linkage matrix to check for correspondence.
+    Y : array_like
+        The condensed distance matrix to check for correspondence.
+
+    Returns
+    -------
+    b : bool
+        A boolean indicating whether the linkage matrix and distance
+        matrix could possibly correspond to one another.
+
+    See Also
+    --------
+    linkage : for a description of what a linkage matrix is.
+
+    Examples
+    --------
+    >>> from scipy.cluster.hierarchy import ward, correspond
+    >>> from scipy.spatial.distance import pdist
+
+    This method can be used to check if a given linkage matrix ``Z`` has been
+    obtained from the application of a cluster method over a dataset ``X``:
+
+    >>> X = [[0, 0], [0, 1], [1, 0],
+    ...      [0, 4], [0, 3], [1, 4],
+    ...      [4, 0], [3, 0], [4, 1],
+    ...      [4, 4], [3, 4], [4, 3]]
+    >>> X_condensed = pdist(X)
+    >>> Z = ward(X_condensed)
+
+    Here, we can compare ``Z`` and ``X`` (in condensed form):
+
+    >>> correspond(Z, X_condensed)
+    True
+
+    """
+    xp = array_namespace(Z, Y)
+    Z = _asarray(Z, xp=xp)
+    Y = _asarray(Y, xp=xp)
+    _is_valid_linkage(Z, throw=True, xp=xp)
+    distance.is_valid_y(Y, throw=True)
+    return distance.num_obs_y(Y) == num_obs_linkage(Z)
+
+
+@xp_capabilities(cpu_only=True, reason="Cython code",
+                 jax_jit=False, allow_dask_compute=True)
+def fcluster(Z, t, criterion='inconsistent', depth=2, R=None, monocrit=None):
+    """
+    Form flat clusters from the hierarchical clustering defined by
+    the given linkage matrix.
+
+    Parameters
+    ----------
+    Z : ndarray
+        The hierarchical clustering encoded with the matrix returned
+        by the `linkage` function.
+    t : scalar
+        For criteria 'inconsistent', 'distance' or 'monocrit',
+         this is the threshold to apply when forming flat clusters.
+        For 'maxclust' or 'maxclust_monocrit' criteria,
+         this would be max number of clusters requested.
+    criterion : str, optional
+        The criterion to use in forming flat clusters. This can
+        be any of the following values:
+
+        * ``inconsistent`` :
+          If a cluster node and all its
+          descendants have an inconsistent value less than or equal
+          to `t`, then all its leaf descendants belong to the
+          same flat cluster. When no non-singleton cluster meets
+          this criterion, every node is assigned to its own
+          cluster. (Default)
+        * ``distance`` :
+          Forms flat clusters so that the original
+          observations in each flat cluster have no greater a
+          cophenetic distance than `t`.
+        * ``maxclust`` :
+          Finds a minimum threshold ``r`` so that
+          the cophenetic distance between any two original
+          observations in the same flat cluster is no more than
+          ``r`` and no more than `t` flat clusters are formed.
+        * ``monocrit`` :
+          Forms a flat cluster from a cluster node c
+          with index i when ``monocrit[j] <= t``.
+
+          For example, to threshold on the maximum mean distance
+          as computed in the inconsistency matrix R with a
+          threshold of 0.8 do::
+
+              MR = maxRstat(Z, R, 3)
+              fcluster(Z, t=0.8, criterion='monocrit', monocrit=MR)
+        * ``maxclust_monocrit`` :
+          Forms a flat cluster from a
+          non-singleton cluster node ``c`` when ``monocrit[i] <=
+          r`` for all cluster indices ``i`` below and including
+          ``c``. ``r`` is minimized such that no more than ``t``
+          flat clusters are formed. monocrit must be
+          monotonic. For example, to minimize the threshold t on
+          maximum inconsistency values so that no more than 3 flat
+          clusters are formed, do::
+
+              MI = maxinconsts(Z, R)
+              fcluster(Z, t=3, criterion='maxclust_monocrit', monocrit=MI)
+    depth : int, optional
+        The maximum depth to perform the inconsistency calculation.
+        It has no meaning for the other criteria. Default is 2.
+    R : ndarray, optional
+        The inconsistency matrix to use for the ``'inconsistent'``
+        criterion. This matrix is computed if not provided.
+    monocrit : ndarray, optional
+        An array of length n-1. `monocrit[i]` is the
+        statistics upon which non-singleton i is thresholded. The
+        monocrit vector must be monotonic, i.e., given a node c with
+        index i, for all node indices j corresponding to nodes
+        below c, ``monocrit[i] >= monocrit[j]``.
+
+    Returns
+    -------
+    fcluster : ndarray
+        An array of length ``n``. ``T[i]`` is the flat cluster number to
+        which original observation ``i`` belongs.
+
+    See Also
+    --------
+    linkage : for information about hierarchical clustering methods work.
+
+    Examples
+    --------
+    >>> from scipy.cluster.hierarchy import ward, fcluster
+    >>> from scipy.spatial.distance import pdist
+
+    All cluster linkage methods - e.g., `scipy.cluster.hierarchy.ward`
+    generate a linkage matrix ``Z`` as their output:
+
+    >>> X = [[0, 0], [0, 1], [1, 0],
+    ...      [0, 4], [0, 3], [1, 4],
+    ...      [4, 0], [3, 0], [4, 1],
+    ...      [4, 4], [3, 4], [4, 3]]
+
+    >>> Z = ward(pdist(X))
+
+    >>> Z
+    array([[ 0.        ,  1.        ,  1.        ,  2.        ],
+           [ 3.        ,  4.        ,  1.        ,  2.        ],
+           [ 6.        ,  7.        ,  1.        ,  2.        ],
+           [ 9.        , 10.        ,  1.        ,  2.        ],
+           [ 2.        , 12.        ,  1.29099445,  3.        ],
+           [ 5.        , 13.        ,  1.29099445,  3.        ],
+           [ 8.        , 14.        ,  1.29099445,  3.        ],
+           [11.        , 15.        ,  1.29099445,  3.        ],
+           [16.        , 17.        ,  5.77350269,  6.        ],
+           [18.        , 19.        ,  5.77350269,  6.        ],
+           [20.        , 21.        ,  8.16496581, 12.        ]])
+
+    This matrix represents a dendrogram, where the first and second elements
+    are the two clusters merged at each step, the third element is the
+    distance between these clusters, and the fourth element is the size of
+    the new cluster - the number of original data points included.
+
+    `scipy.cluster.hierarchy.fcluster` can be used to flatten the
+    dendrogram, obtaining as a result an assignation of the original data
+    points to single clusters.
+
+    This assignation mostly depends on a distance threshold ``t`` - the maximum
+    inter-cluster distance allowed:
+
+    >>> fcluster(Z, t=0.9, criterion='distance')
+    array([ 1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12], dtype=int32)
+
+    >>> fcluster(Z, t=1.1, criterion='distance')
+    array([1, 1, 2, 3, 3, 4, 5, 5, 6, 7, 7, 8], dtype=int32)
+
+    >>> fcluster(Z, t=3, criterion='distance')
+    array([1, 1, 1, 2, 2, 2, 3, 3, 3, 4, 4, 4], dtype=int32)
+
+    >>> fcluster(Z, t=9, criterion='distance')
+    array([1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], dtype=int32)
+
+    In the first case, the threshold ``t`` is too small to allow any two
+    samples in the data to form a cluster, so 12 different clusters are
+    returned.
+
+    In the second case, the threshold is large enough to allow the first
+    4 points to be merged with their nearest neighbors. So, here, only 8
+    clusters are returned.
+
+    The third case, with a much higher threshold, allows for up to 8 data
+    points to be connected - so 4 clusters are returned here.
+
+    Lastly, the threshold of the fourth case is large enough to allow for
+    all data points to be merged together - so a single cluster is returned.
+
+    """
+    xp = array_namespace(Z)
+    Z = _asarray(Z, order='C', dtype=xp.float64, xp=xp)
+    _is_valid_linkage(Z, throw=True, name='Z', materialize=True, xp=xp)
+
+    n = Z.shape[0] + 1
+    T = np.zeros((n,), dtype='i')
+
+    if monocrit is not None:
+        monocrit = np.asarray(monocrit, order='C', dtype=np.float64)
+
+    Z = np.asarray(Z)
+    monocrit = np.asarray(monocrit)
+    if criterion == 'inconsistent':
+        if R is None:
+            R = inconsistent(Z, depth)
+        else:
+            R = _asarray(R, order='C', dtype=xp.float64, xp=xp)
+            _is_valid_im(R, throw=True, name='R', materialize=True, xp=xp)
+            # Since the C code does not support striding using strides.
+            # The dimensions are used instead.
+            R = np.asarray(R)
+        _hierarchy.cluster_in(Z, R, T, float(t), int(n))
+    elif criterion == 'distance':
+        _hierarchy.cluster_dist(Z, T, float(t), int(n))
+    elif criterion == 'maxclust':
+        _hierarchy.cluster_maxclust_dist(Z, T, int(n), t)
+    elif criterion == 'monocrit':
+        _hierarchy.cluster_monocrit(Z, monocrit, T, float(t), int(n))
+    elif criterion == 'maxclust_monocrit':
+        _hierarchy.cluster_maxclust_monocrit(Z, monocrit, T, int(n), int(t))
+    else:
+        raise ValueError(f'Invalid cluster formation criterion: {str(criterion)}')
+    return xp.asarray(T)
+
+
+@xp_capabilities(cpu_only=True, reason="Cython code",
+                 jax_jit=False, allow_dask_compute=True)
+def fclusterdata(X, t, criterion='inconsistent',
+                 metric='euclidean', depth=2, method='single', R=None):
+    """
+    Cluster observation data using a given metric.
+
+    Clusters the original observations in the n-by-m data
+    matrix X (n observations in m dimensions), using the euclidean
+    distance metric to calculate distances between original observations,
+    performs hierarchical clustering using the single linkage algorithm,
+    and forms flat clusters using the inconsistency method with `t` as the
+    cut-off threshold.
+
+    A 1-D array ``T`` of length ``n`` is returned. ``T[i]`` is
+    the index of the flat cluster to which the original observation ``i``
+    belongs.
+
+    Parameters
+    ----------
+    X : (N, M) ndarray
+        N by M data matrix with N observations in M dimensions.
+    t : scalar
+        For criteria 'inconsistent', 'distance' or 'monocrit',
+         this is the threshold to apply when forming flat clusters.
+        For 'maxclust' or 'maxclust_monocrit' criteria,
+         this would be max number of clusters requested.
+    criterion : str, optional
+        Specifies the criterion for forming flat clusters. Valid
+        values are 'inconsistent' (default), 'distance', or 'maxclust'
+        cluster formation algorithms. See `fcluster` for descriptions.
+    metric : str or function, optional
+        The distance metric for calculating pairwise distances. See
+        ``distance.pdist`` for descriptions and linkage to verify
+        compatibility with the linkage method.
+    depth : int, optional
+        The maximum depth for the inconsistency calculation. See
+        `inconsistent` for more information.
+    method : str, optional
+        The linkage method to use (single, complete, average,
+        weighted, median centroid, ward). See `linkage` for more
+        information. Default is "single".
+    R : ndarray, optional
+        The inconsistency matrix. It will be computed if necessary
+        if it is not passed.
+
+    Returns
+    -------
+    fclusterdata : ndarray
+        A vector of length n. T[i] is the flat cluster number to
+        which original observation i belongs.
+
+    See Also
+    --------
+    scipy.spatial.distance.pdist : pairwise distance metrics
+
+    Notes
+    -----
+    This function is similar to the MATLAB function ``clusterdata``.
+
+    Examples
+    --------
+    >>> from scipy.cluster.hierarchy import fclusterdata
+
+    This is a convenience method that abstracts all the steps to perform in a
+    typical SciPy's hierarchical clustering workflow.
+
+    * Transform the input data into a condensed matrix with
+      `scipy.spatial.distance.pdist`.
+
+    * Apply a clustering method.
+
+    * Obtain flat clusters at a user defined distance threshold ``t`` using
+      `scipy.cluster.hierarchy.fcluster`.
+
+    >>> X = [[0, 0], [0, 1], [1, 0],
+    ...      [0, 4], [0, 3], [1, 4],
+    ...      [4, 0], [3, 0], [4, 1],
+    ...      [4, 4], [3, 4], [4, 3]]
+
+    >>> fclusterdata(X, t=1)
+    array([3, 3, 3, 4, 4, 4, 2, 2, 2, 1, 1, 1], dtype=int32)
+
+    The output here (for the dataset ``X``, distance threshold ``t``, and the
+    default settings) is four clusters with three data points each.
+
+    """
+    xp = array_namespace(X)
+    X = _asarray(X, order='C', dtype=xp.float64, xp=xp)
+
+    if X.ndim != 2:
+        raise TypeError('The observation matrix X must be an n by m array.')
+
+    Y = distance.pdist(X, metric=metric)
+    Z = linkage(Y, method=method)
+    if R is None:
+        R = inconsistent(Z, d=depth)
+    else:
+        R = _asarray(R, order='C', xp=xp)
+    T = fcluster(Z, criterion=criterion, depth=depth, R=R, t=t)
+    return T
+
+
+@lazy_cython
+def leaves_list(Z):
+    """
+    Return a list of leaf node ids.
+
+    The return corresponds to the observation vector index as it appears
+    in the tree from left to right. Z is a linkage matrix.
+
+    Parameters
+    ----------
+    Z : ndarray
+        The hierarchical clustering encoded as a matrix.  `Z` is
+        a linkage matrix.  See `linkage` for more information.
+
+    Returns
+    -------
+    leaves_list : ndarray
+        The list of leaf node ids.
+
+    See Also
+    --------
+    dendrogram : for information about dendrogram structure.
+
+    Examples
+    --------
+    >>> from scipy.cluster.hierarchy import ward, dendrogram, leaves_list
+    >>> from scipy.spatial.distance import pdist
+    >>> from matplotlib import pyplot as plt
+
+    >>> X = [[0, 0], [0, 1], [1, 0],
+    ...      [0, 4], [0, 3], [1, 4],
+    ...      [4, 0], [3, 0], [4, 1],
+    ...      [4, 4], [3, 4], [4, 3]]
+
+    >>> Z = ward(pdist(X))
+
+    The linkage matrix ``Z`` represents a dendrogram, that is, a tree that
+    encodes the structure of the clustering performed.
+    `scipy.cluster.hierarchy.leaves_list` shows the mapping between
+    indices in the ``X`` dataset and leaves in the dendrogram:
+
+    >>> leaves_list(Z)
+    array([ 2,  0,  1,  5,  3,  4,  8,  6,  7, 11,  9, 10], dtype=int32)
+
+    >>> fig = plt.figure(figsize=(25, 10))
+    >>> dn = dendrogram(Z)
+    >>> plt.show()
+
+    """
+    xp = array_namespace(Z)
+    Z = _asarray(Z, order='C', xp=xp)
+    _is_valid_linkage(Z, throw=True, name='Z', xp=xp)
+
+    def cy_leaves_list(Z, validate):
+        if validate:
+            _is_valid_linkage(Z, throw=True, name='Z', xp=np)
+        n = Z.shape[0] + 1
+        ML = np.zeros((n,), dtype=np.int32)
+        _hierarchy.prelist(Z, ML, n)
+        return ML
+
+    n = Z.shape[0] + 1
+    return xpx.lazy_apply(cy_leaves_list, Z, validate=is_lazy_array(Z),
+                          shape=(n, ), dtype=xp.int32,
+                          as_numpy=True, xp=xp)
+
+
+# Maps number of leaves to text size.
+#
+# p <= 20, size="12"
+# 20 < p <= 30, size="10"
+# 30 < p <= 50, size="8"
+# 50 < p <= np.inf, size="6"
+
+_dtextsizes = {20: 12, 30: 10, 50: 8, 85: 6, np.inf: 5}
+_drotation = {20: 0, 40: 45, np.inf: 90}
+_dtextsortedkeys = list(_dtextsizes.keys())
+_dtextsortedkeys.sort()
+_drotationsortedkeys = list(_drotation.keys())
+_drotationsortedkeys.sort()
+
+
+def _remove_dups(L):
+    """
+    Remove duplicates AND preserve the original order of the elements.
+
+    The set class is not guaranteed to do this.
+    """
+    seen_before = set()
+    L2 = []
+    for i in L:
+        if i not in seen_before:
+            seen_before.add(i)
+            L2.append(i)
+    return L2
+
+
+def _get_tick_text_size(p):
+    for k in _dtextsortedkeys:
+        if p <= k:
+            return _dtextsizes[k]
+
+
+def _get_tick_rotation(p):
+    for k in _drotationsortedkeys:
+        if p <= k:
+            return _drotation[k]
+
+
+def _plot_dendrogram(icoords, dcoords, ivl, p, n, mh, orientation,
+                     no_labels, color_list, leaf_font_size=None,
+                     leaf_rotation=None, contraction_marks=None,
+                     ax=None, above_threshold_color='C0'):
+    # Import matplotlib here so that it's not imported unless dendrograms
+    # are plotted. Raise an informative error if importing fails.
+    try:
+        # if an axis is provided, don't use pylab at all
+        if ax is None:
+            import matplotlib.pylab
+        import matplotlib.patches
+        import matplotlib.collections
+    except ImportError as e:
+        raise ImportError("You must install the matplotlib library to plot "
+                          "the dendrogram. Use no_plot=True to calculate the "
+                          "dendrogram without plotting.") from e
+
+    if ax is None:
+        ax = matplotlib.pylab.gca()
+        # if we're using pylab, we want to trigger a draw at the end
+        trigger_redraw = True
+    else:
+        trigger_redraw = False
+
+    # Independent variable plot width
+    ivw = len(ivl) * 10
+    # Dependent variable plot height
+    dvw = mh + mh * 0.05
+
+    iv_ticks = np.arange(5, len(ivl) * 10 + 5, 10)
+    if orientation in ('top', 'bottom'):
+        if orientation == 'top':
+            ax.set_ylim([0, dvw])
+            ax.set_xlim([0, ivw])
+        else:
+            ax.set_ylim([dvw, 0])
+            ax.set_xlim([0, ivw])
+
+        xlines = icoords
+        ylines = dcoords
+        if no_labels:
+            ax.set_xticks([])
+            ax.set_xticklabels([])
+        else:
+            ax.set_xticks(iv_ticks)
+
+            if orientation == 'top':
+                ax.xaxis.set_ticks_position('bottom')
+            else:
+                ax.xaxis.set_ticks_position('top')
+
+            # Make the tick marks invisible because they cover up the links
+            for line in ax.get_xticklines():
+                line.set_visible(False)
+
+            leaf_rot = (float(_get_tick_rotation(len(ivl)))
+                        if (leaf_rotation is None) else leaf_rotation)
+            leaf_font = (float(_get_tick_text_size(len(ivl)))
+                         if (leaf_font_size is None) else leaf_font_size)
+            ax.set_xticklabels(ivl, rotation=leaf_rot, size=leaf_font)
+
+    elif orientation in ('left', 'right'):
+        if orientation == 'left':
+            ax.set_xlim([dvw, 0])
+            ax.set_ylim([0, ivw])
+        else:
+            ax.set_xlim([0, dvw])
+            ax.set_ylim([0, ivw])
+
+        xlines = dcoords
+        ylines = icoords
+        if no_labels:
+            ax.set_yticks([])
+            ax.set_yticklabels([])
+        else:
+            ax.set_yticks(iv_ticks)
+
+            if orientation == 'left':
+                ax.yaxis.set_ticks_position('right')
+            else:
+                ax.yaxis.set_ticks_position('left')
+
+            # Make the tick marks invisible because they cover up the links
+            for line in ax.get_yticklines():
+                line.set_visible(False)
+
+            leaf_font = (float(_get_tick_text_size(len(ivl)))
+                         if (leaf_font_size is None) else leaf_font_size)
+
+            if leaf_rotation is not None:
+                ax.set_yticklabels(ivl, rotation=leaf_rotation, size=leaf_font)
+            else:
+                ax.set_yticklabels(ivl, size=leaf_font)
+
+    # Let's use collections instead. This way there is a separate legend item
+    # for each tree grouping, rather than stupidly one for each line segment.
+    colors_used = _remove_dups(color_list)
+    color_to_lines = {}
+    for color in colors_used:
+        color_to_lines[color] = []
+    for (xline, yline, color) in zip(xlines, ylines, color_list):
+        color_to_lines[color].append(list(zip(xline, yline)))
+
+    colors_to_collections = {}
+    # Construct the collections.
+    for color in colors_used:
+        coll = matplotlib.collections.LineCollection(color_to_lines[color],
+                                                     colors=(color,))
+        colors_to_collections[color] = coll
+
+    # Add all the groupings below the color threshold.
+    for color in colors_used:
+        if color != above_threshold_color:
+            ax.add_collection(colors_to_collections[color])
+    # If there's a grouping of links above the color threshold, it goes last.
+    if above_threshold_color in colors_to_collections:
+        ax.add_collection(colors_to_collections[above_threshold_color])
+
+    if contraction_marks is not None:
+        Ellipse = matplotlib.patches.Ellipse
+        for (x, y) in contraction_marks:
+            if orientation in ('left', 'right'):
+                ell = Ellipse((y, x), width=dvw / 100, height=1.0)
+            else:
+                ell = Ellipse((x, y), width=1.0, height=dvw / 100)
+            ax.add_artist(ell)
+            ell.set_clip_box(ax.bbox)
+            ell.set_alpha(0.5)
+            ell.set_facecolor('k')
+
+    if trigger_redraw:
+        matplotlib.pylab.draw_if_interactive()
+
+
+# C0  is used for above threshold color
+_link_line_colors_default = ('C1', 'C2', 'C3', 'C4', 'C5', 'C6', 'C7', 'C8', 'C9')
+_link_line_colors = list(_link_line_colors_default)
+
+
+@xp_capabilities(out_of_scope=True)
+def set_link_color_palette(palette):
+    """
+    Set list of matplotlib color codes for use by dendrogram.
+
+    Note that this palette is global (i.e., setting it once changes the colors
+    for all subsequent calls to `dendrogram`) and that it affects only the
+    the colors below ``color_threshold``.
+
+    Note that `dendrogram` also accepts a custom coloring function through its
+    ``link_color_func`` keyword, which is more flexible and non-global.
+
+    Parameters
+    ----------
+    palette : list of str or None
+        A list of matplotlib color codes.  The order of the color codes is the
+        order in which the colors are cycled through when color thresholding in
+        the dendrogram.
+
+        If ``None``, resets the palette to its default (which are matplotlib
+        default colors C1 to C9).
+
+    See Also
+    --------
+    dendrogram
+
+    Notes
+    -----
+    Ability to reset the palette with ``None`` added in SciPy 0.17.0.
+
+    Thread safety: using this function in a multi-threaded fashion may
+    result in `dendrogram` producing plots with unexpected colors.
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy.cluster import hierarchy
+    >>> ytdist = np.array([662., 877., 255., 412., 996., 295., 468., 268.,
+    ...                    400., 754., 564., 138., 219., 869., 669.])
+    >>> Z = hierarchy.linkage(ytdist, 'single')
+    >>> dn = hierarchy.dendrogram(Z, no_plot=True)
+    >>> dn['color_list']
+    ['C1', 'C0', 'C0', 'C0', 'C0']
+    >>> hierarchy.set_link_color_palette(['c', 'm', 'y', 'k'])
+    >>> dn = hierarchy.dendrogram(Z, no_plot=True, above_threshold_color='b')
+    >>> dn['color_list']
+    ['c', 'b', 'b', 'b', 'b']
+    >>> dn = hierarchy.dendrogram(Z, no_plot=True, color_threshold=267,
+    ...                           above_threshold_color='k')
+    >>> dn['color_list']
+    ['c', 'm', 'm', 'k', 'k']
+
+    Now, reset the color palette to its default:
+
+    >>> hierarchy.set_link_color_palette(None)
+
+    """
+    if palette is None:
+        # reset to its default
+        palette = _link_line_colors_default
+    elif not isinstance(palette, list | tuple):
+        raise TypeError("palette must be a list or tuple")
+    _ptypes = [isinstance(p, str) for p in palette]
+
+    if False in _ptypes:
+        raise TypeError("all palette list elements must be color strings")
+
+    global _link_line_colors
+    _link_line_colors = palette
+
+
+@xp_capabilities(cpu_only=True, jax_jit=False, allow_dask_compute=True)
+def dendrogram(Z, p=30, truncate_mode=None, color_threshold=None,
+               get_leaves=True, orientation='top', labels=None,
+               count_sort=False, distance_sort=False, show_leaf_counts=True,
+               no_plot=False, no_labels=False, leaf_font_size=None,
+               leaf_rotation=None, leaf_label_func=None,
+               show_contracted=False, link_color_func=None, ax=None,
+               above_threshold_color='C0'):
+    """
+    Plot the hierarchical clustering as a dendrogram.
+
+    The dendrogram illustrates how each cluster is
+    composed by drawing a U-shaped link between a non-singleton
+    cluster and its children. The top of the U-link indicates a
+    cluster merge. The two legs of the U-link indicate which clusters
+    were merged. The length of the two legs of the U-link represents
+    the distance between the child clusters. It is also the
+    cophenetic distance between original observations in the two
+    children clusters.
+
+    Parameters
+    ----------
+    Z : ndarray
+        The linkage matrix encoding the hierarchical clustering to
+        render as a dendrogram. See the ``linkage`` function for more
+        information on the format of ``Z``.
+    p : int, optional
+        The ``p`` parameter for ``truncate_mode``.
+    truncate_mode : str, optional
+        The dendrogram can be hard to read when the original
+        observation matrix from which the linkage is derived is
+        large. Truncation is used to condense the dendrogram. There
+        are several modes:
+
+        ``None``
+          No truncation is performed (default).
+          Note: ``'none'`` is an alias for ``None`` that's kept for
+          backward compatibility.
+
+        ``'lastp'``
+          The last ``p`` non-singleton clusters formed in the linkage are the
+          only non-leaf nodes in the linkage; they correspond to rows
+          ``Z[n-p-2:end]`` in ``Z``. All other non-singleton clusters are
+          contracted into leaf nodes.
+
+        ``'level'``
+          No more than ``p`` levels of the dendrogram tree are displayed.
+          A "level" includes all nodes with ``p`` merges from the final merge.
+
+          Note: ``'mtica'`` is an alias for ``'level'`` that's kept for
+          backward compatibility.
+
+    color_threshold : double, optional
+        For brevity, let :math:`t` be the ``color_threshold``.
+        Colors all the descendent links below a cluster node
+        :math:`k` the same color if :math:`k` is the first node below
+        the cut threshold :math:`t`. All links connecting nodes with
+        distances greater than or equal to the threshold are colored
+        with de default matplotlib color ``'C0'``. If :math:`t` is less
+        than or equal to zero, all nodes are colored ``'C0'``.
+        If ``color_threshold`` is None or 'default',
+        corresponding with MATLAB(TM) behavior, the threshold is set to
+        ``0.7*max(Z[:,2])``.
+    get_leaves : bool, optional
+        Includes a list ``R['leaves']=H`` in the result
+        dictionary. For each :math:`i`, ``H[i] == j``, cluster node
+        ``j`` appears in position ``i`` in the left-to-right traversal
+        of the leaves, where :math:`j < 2n-1` and :math:`i < n`.
+    orientation : str, optional
+        The direction to plot the dendrogram, which can be any
+        of the following strings:
+
+        ``'top'``
+          Plots the root at the top, and plot descendent links going downwards.
+          (default).
+
+        ``'bottom'``
+          Plots the root at the bottom, and plot descendent links going
+          upwards.
+
+        ``'left'``
+          Plots the root at the left, and plot descendent links going right.
+
+        ``'right'``
+          Plots the root at the right, and plot descendent links going left.
+
+    labels : ndarray, optional
+        By default, ``labels`` is None so the index of the original observation
+        is used to label the leaf nodes.  Otherwise, this is an :math:`n`-sized
+        sequence, with ``n == Z.shape[0] + 1``. The ``labels[i]`` value is the
+        text to put under the :math:`i` th leaf node only if it corresponds to
+        an original observation and not a non-singleton cluster.
+    count_sort : str or bool, optional
+        For each node n, the order (visually, from left-to-right) n's
+        two descendent links are plotted is determined by this
+        parameter, which can be any of the following values:
+
+        ``False``
+          Nothing is done.
+
+        ``'ascending'`` or ``True``
+          The child with the minimum number of original objects in its cluster
+          is plotted first.
+
+        ``'descending'``
+          The child with the maximum number of original objects in its cluster
+          is plotted first.
+
+        Note, ``distance_sort`` and ``count_sort`` cannot both be True.
+    distance_sort : str or bool, optional
+        For each node n, the order (visually, from left-to-right) n's
+        two descendent links are plotted is determined by this
+        parameter, which can be any of the following values:
+
+        ``False``
+          Nothing is done.
+
+        ``'ascending'`` or ``True``
+          The child with the minimum distance between its direct descendents is
+          plotted first.
+
+        ``'descending'``
+          The child with the maximum distance between its direct descendents is
+          plotted first.
+
+        Note ``distance_sort`` and ``count_sort`` cannot both be True.
+    show_leaf_counts : bool, optional
+         When True, leaf nodes representing :math:`k>1` original
+         observation are labeled with the number of observations they
+         contain in parentheses.
+    no_plot : bool, optional
+        When True, the final rendering is not performed. This is
+        useful if only the data structures computed for the rendering
+        are needed or if matplotlib is not available.
+    no_labels : bool, optional
+        When True, no labels appear next to the leaf nodes in the
+        rendering of the dendrogram.
+    leaf_font_size : int, optional
+        Specifies the font size (in points) of the leaf labels. When
+        unspecified, the size based on the number of nodes in the
+        dendrogram.
+    leaf_rotation : double, optional
+        Specifies the angle (in degrees) to rotate the leaf
+        labels. When unspecified, the rotation is based on the number of
+        nodes in the dendrogram (default is 0).
+    leaf_label_func : lambda or function, optional
+        When ``leaf_label_func`` is a callable function, for each
+        leaf with cluster index :math:`k < 2n-1`. The function
+        is expected to return a string with the label for the
+        leaf.
+
+        Indices :math:`k < n` correspond to original observations
+        while indices :math:`k \\geq n` correspond to non-singleton
+        clusters.
+
+        For example, to label singletons with their node id and
+        non-singletons with their id, count, and inconsistency
+        coefficient, simply do::
+
+            # First define the leaf label function.
+            def llf(id):
+                if id < n:
+                    return str(id)
+                else:
+                    return '[%d %d %1.2f]' % (id, count, R[n-id,3])
+
+            # The text for the leaf nodes is going to be big so force
+            # a rotation of 90 degrees.
+            dendrogram(Z, leaf_label_func=llf, leaf_rotation=90)
+
+            # leaf_label_func can also be used together with ``truncate_mode``,
+            # in which case you will get your leaves labeled after truncation:
+            dendrogram(Z, leaf_label_func=llf, leaf_rotation=90,
+                       truncate_mode='level', p=2)
+
+    show_contracted : bool, optional
+        When True the heights of non-singleton nodes contracted
+        into a leaf node are plotted as crosses along the link
+        connecting that leaf node.  This really is only useful when
+        truncation is used (see ``truncate_mode`` parameter).
+    link_color_func : callable, optional
+        If given, `link_color_function` is called with each non-singleton id
+        corresponding to each U-shaped link it will paint. The function is
+        expected to return the color to paint the link, encoded as a matplotlib
+        color string code. For example::
+
+            dendrogram(Z, link_color_func=lambda k: colors[k])
+
+        colors the direct links below each untruncated non-singleton node
+        ``k`` using ``colors[k]``.
+    ax : matplotlib Axes instance, optional
+        If None and `no_plot` is not True, the dendrogram will be plotted
+        on the current axes.  Otherwise if `no_plot` is not True the
+        dendrogram will be plotted on the given ``Axes`` instance. This can be
+        useful if the dendrogram is part of a more complex figure.
+    above_threshold_color : str, optional
+        This matplotlib color string sets the color of the links above the
+        color_threshold. The default is ``'C0'``.
+
+    Returns
+    -------
+    R : dict
+        A dictionary of data structures computed to render the
+        dendrogram. Its has the following keys:
+
+        ``'color_list'``
+          A list of color names. The k'th element represents the color of the
+          k'th link.
+
+        ``'icoord'`` and ``'dcoord'``
+          Each of them is a list of lists. Let ``icoord = [I1, I2, ..., Ip]``
+          where ``Ik = [xk1, xk2, xk3, xk4]`` and ``dcoord = [D1, D2, ..., Dp]``
+          where ``Dk = [yk1, yk2, yk3, yk4]``, then the k'th link painted is
+          ``(xk1, yk1)`` - ``(xk2, yk2)`` - ``(xk3, yk3)`` - ``(xk4, yk4)``.
+
+        ``'ivl'``
+          A list of labels corresponding to the leaf nodes.
+
+        ``'leaves'``
+          For each i, ``H[i] == j``, cluster node ``j`` appears in position
+          ``i`` in the left-to-right traversal of the leaves, where
+          :math:`j < 2n-1` and :math:`i < n`. If ``j`` is less than ``n``, the
+          ``i``-th leaf node corresponds to an original observation.
+          Otherwise, it corresponds to a non-singleton cluster.
+
+        ``'leaves_color_list'``
+          A list of color names. The k'th element represents the color of the
+          k'th leaf.
+
+    See Also
+    --------
+    linkage, set_link_color_palette
+
+    Notes
+    -----
+    It is expected that the distances in ``Z[:,2]`` be monotonic, otherwise
+    crossings appear in the dendrogram.
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy.cluster import hierarchy
+    >>> import matplotlib.pyplot as plt
+
+    A very basic example:
+
+    >>> ytdist = np.array([662., 877., 255., 412., 996., 295., 468., 268.,
+    ...                    400., 754., 564., 138., 219., 869., 669.])
+    >>> Z = hierarchy.linkage(ytdist, 'single')
+    >>> plt.figure()
+    >>> dn = hierarchy.dendrogram(Z)
+
+    Now, plot in given axes, improve the color scheme and use both vertical and
+    horizontal orientations:
+
+    >>> hierarchy.set_link_color_palette(['m', 'c', 'y', 'k'])
+    >>> fig, axes = plt.subplots(1, 2, figsize=(8, 3))
+    >>> dn1 = hierarchy.dendrogram(Z, ax=axes[0], above_threshold_color='y',
+    ...                            orientation='top')
+    >>> dn2 = hierarchy.dendrogram(Z, ax=axes[1],
+    ...                            above_threshold_color='#bcbddc',
+    ...                            orientation='right')
+    >>> hierarchy.set_link_color_palette(None)  # reset to default after use
+    >>> plt.show()
+
+    """
+    # This feature was thought about but never implemented (still useful?):
+    #
+    #         ... = dendrogram(..., leaves_order=None)
+    #
+    #         Plots the leaves in the order specified by a vector of
+    #         original observation indices. If the vector contains duplicates
+    #         or results in a crossing, an exception will be thrown. Passing
+    #         None orders leaf nodes based on the order they appear in the
+    #         pre-order traversal.
+    xp = array_namespace(Z)
+    Z = _asarray(Z, order='C', xp=xp)
+
+    if orientation not in ["top", "left", "bottom", "right"]:
+        raise ValueError("orientation must be one of 'top', 'left', "
+                         "'bottom', or 'right'")
+
+    if labels is not None:
+        try:
+            len_labels = len(labels)
+        except (TypeError, AttributeError):
+            len_labels = labels.shape[0]
+        if Z.shape[0] + 1 != len_labels:
+            raise ValueError("Dimensions of Z and labels must be consistent.")
+
+    _is_valid_linkage(Z, throw=True, name='Z', materialize=True, xp=xp)
+    Zs = Z.shape
+    n = Zs[0] + 1
+    if isinstance(p, int | float):
+        p = int(p)
+    else:
+        raise TypeError('The second argument must be a number')
+
+    if truncate_mode not in ('lastp', 'mtica', 'level', 'none', None):
+        # 'mtica' is kept working for backwards compat.
+        raise ValueError('Invalid truncation mode.')
+
+    if truncate_mode == 'lastp':
+        if p > n or p == 0:
+            p = n
+
+    if truncate_mode == 'mtica':
+        # 'mtica' is an alias
+        truncate_mode = 'level'
+
+    if truncate_mode == 'level':
+        if p <= 0:
+            p = np.inf
+
+    if get_leaves:
+        lvs = []
+    else:
+        lvs = None
+
+    icoord_list = []
+    dcoord_list = []
+    color_list = []
+    current_color = [0]
+    currently_below_threshold = [False]
+    ivl = []  # list of leaves
+
+    if color_threshold is None or (isinstance(color_threshold, str) and
+                                   color_threshold == 'default'):
+        color_threshold = xp.max(Z[:, 2]) * 0.7
+
+    R = {'icoord': icoord_list, 'dcoord': dcoord_list, 'ivl': ivl,
+         'leaves': lvs, 'color_list': color_list}
+
+    # Empty list will be filled in _dendrogram_calculate_info
+    contraction_marks = [] if show_contracted else None
+
+    _dendrogram_calculate_info(
+        Z=Z, p=p,
+        truncate_mode=truncate_mode,
+        color_threshold=color_threshold,
+        get_leaves=get_leaves,
+        orientation=orientation,
+        labels=labels,
+        count_sort=count_sort,
+        distance_sort=distance_sort,
+        show_leaf_counts=show_leaf_counts,
+        i=2*n - 2,
+        iv=0.0,
+        ivl=ivl,
+        n=n,
+        icoord_list=icoord_list,
+        dcoord_list=dcoord_list,
+        lvs=lvs,
+        current_color=current_color,
+        color_list=color_list,
+        currently_below_threshold=currently_below_threshold,
+        leaf_label_func=leaf_label_func,
+        contraction_marks=contraction_marks,
+        link_color_func=link_color_func,
+        above_threshold_color=above_threshold_color)
+
+    if not no_plot:
+        mh = xp.max(Z[:, 2])
+        _plot_dendrogram(icoord_list, dcoord_list, ivl, p, n, mh, orientation,
+                         no_labels, color_list,
+                         leaf_font_size=leaf_font_size,
+                         leaf_rotation=leaf_rotation,
+                         contraction_marks=contraction_marks,
+                         ax=ax,
+                         above_threshold_color=above_threshold_color)
+
+    R["leaves_color_list"] = _get_leaves_color_list(R)
+
+    return R
+
+
+def _get_leaves_color_list(R):
+    leaves_color_list = [None] * len(R['leaves'])
+    for link_x, link_y, link_color in zip(R['icoord'],
+                                          R['dcoord'],
+                                          R['color_list']):
+        for (xi, yi) in zip(link_x, link_y):
+            if yi == 0.0 and (xi % 5 == 0 and xi % 2 == 1):
+                # if yi is 0.0 and xi is divisible by 5 and odd,
+                # the point is a leaf
+                # xi of leaves are      5, 15, 25, 35, ... (see `iv_ticks`)
+                # index of leaves are   0,  1,  2,  3, ... as below
+                leaf_index = (int(xi) - 5) // 10
+                # each leaf has a same color of its link.
+                leaves_color_list[leaf_index] = link_color
+    return leaves_color_list
+
+
+def _append_singleton_leaf_node(Z, p, n, level, lvs, ivl, leaf_label_func,
+                                i, labels):
+    # If the leaf id structure is not None and is a list then the caller
+    # to dendrogram has indicated that cluster id's corresponding to the
+    # leaf nodes should be recorded.
+
+    if lvs is not None:
+        lvs.append(int(i))
+
+    # If leaf node labels are to be displayed...
+    if ivl is not None:
+        # If a leaf_label_func has been provided, the label comes from the
+        # string returned from the leaf_label_func, which is a function
+        # passed to dendrogram.
+        if leaf_label_func:
+            ivl.append(leaf_label_func(int(i)))
+        else:
+            # Otherwise, if the dendrogram caller has passed a labels list
+            # for the leaf nodes, use it.
+            if labels is not None:
+                ivl.append(labels[int(i - n)])
+            else:
+                # Otherwise, use the id as the label for the leaf.x
+                ivl.append(str(int(i)))
+
+
+def _append_nonsingleton_leaf_node(Z, p, n, level, lvs, ivl, leaf_label_func,
+                                   i, labels, show_leaf_counts):
+    # If the leaf id structure is not None and is a list then the caller
+    # to dendrogram has indicated that cluster id's corresponding to the
+    # leaf nodes should be recorded.
+
+    if lvs is not None:
+        lvs.append(int(i))
+    if ivl is not None:
+        if leaf_label_func:
+            ivl.append(leaf_label_func(int(i)))
+        else:
+            if show_leaf_counts:
+                ivl.append("(" + str(np.asarray(Z[i - n, 3], dtype=np.int64)) + ")")
+            else:
+                ivl.append("")
+
+
+def _append_contraction_marks(Z, iv, i, n, contraction_marks, xp):
+    _append_contraction_marks_sub(Z, iv, _int_floor(Z[i - n, 0], xp),
+                                  n, contraction_marks, xp)
+    _append_contraction_marks_sub(Z, iv, _int_floor(Z[i - n, 1], xp),
+                                  n, contraction_marks, xp)
+
+
+def _append_contraction_marks_sub(Z, iv, i, n, contraction_marks, xp):
+    if i >= n:
+        contraction_marks.append((iv, Z[i - n, 2]))
+        _append_contraction_marks_sub(Z, iv, _int_floor(Z[i - n, 0], xp),
+                                      n, contraction_marks, xp)
+        _append_contraction_marks_sub(Z, iv, _int_floor(Z[i - n, 1], xp),
+                                      n, contraction_marks, xp)
+
+
+def _dendrogram_calculate_info(Z, p, truncate_mode,
+                               color_threshold=np.inf, get_leaves=True,
+                               orientation='top', labels=None,
+                               count_sort=False, distance_sort=False,
+                               show_leaf_counts=False, i=-1, iv=0.0,
+                               ivl=None, n=0, icoord_list=None, dcoord_list=None,
+                               lvs=None, mhr=False,
+                               current_color=None, color_list=None,
+                               currently_below_threshold=None,
+                               leaf_label_func=None, level=0,
+                               contraction_marks=None,
+                               link_color_func=None,
+                               above_threshold_color='C0'):
+    """
+    Calculate the endpoints of the links as well as the labels for the
+    the dendrogram rooted at the node with index i. iv is the independent
+    variable value to plot the left-most leaf node below the root node i
+    (if orientation='top', this would be the left-most x value where the
+    plotting of this root node i and its descendents should begin).
+
+    ivl is a list to store the labels of the leaf nodes. The leaf_label_func
+    is called whenever ivl != None, labels == None, and
+    leaf_label_func != None. When ivl != None and labels != None, the
+    labels list is used only for labeling the leaf nodes. When
+    ivl == None, no labels are generated for leaf nodes.
+
+    When get_leaves==True, a list of leaves is built as they are visited
+    in the dendrogram.
+
+    Returns a tuple with l being the independent variable coordinate that
+    corresponds to the midpoint of cluster to the left of cluster i if
+    i is non-singleton, otherwise the independent coordinate of the leaf
+    node if i is a leaf node.
+
+    Returns
+    -------
+    A tuple (left, w, h, md), where:
+        * left is the independent variable coordinate of the center of the
+          the U of the subtree
+
+        * w is the amount of space used for the subtree (in independent
+          variable units)
+
+        * h is the height of the subtree in dependent variable units
+
+        * md is the ``max(Z[*,2]``) for all nodes ``*`` below and including
+          the target node.
+
+    """
+    xp = array_namespace(Z)
+    if n == 0:
+        raise ValueError("Invalid singleton cluster count n.")
+
+    if i == -1:
+        raise ValueError("Invalid root cluster index i.")
+
+    if truncate_mode == 'lastp':
+        # If the node is a leaf node but corresponds to a non-singleton
+        # cluster, its label is either the empty string or the number of
+        # original observations belonging to cluster i.
+        if 2*n - p > i >= n:
+            d = Z[i - n, 2]
+            _append_nonsingleton_leaf_node(Z, p, n, level, lvs, ivl,
+                                           leaf_label_func, i, labels,
+                                           show_leaf_counts)
+            if contraction_marks is not None:
+                _append_contraction_marks(Z, iv + 5.0, i, n, contraction_marks, xp)
+            return (iv + 5.0, 10.0, 0.0, d)
+        elif i < n:
+            _append_singleton_leaf_node(Z, p, n, level, lvs, ivl,
+                                        leaf_label_func, i, labels)
+            return (iv + 5.0, 10.0, 0.0, 0.0)
+    elif truncate_mode == 'level':
+        if i > n and level > p:
+            d = Z[i - n, 2]
+            _append_nonsingleton_leaf_node(Z, p, n, level, lvs, ivl,
+                                           leaf_label_func, i, labels,
+                                           show_leaf_counts)
+            if contraction_marks is not None:
+                _append_contraction_marks(Z, iv + 5.0, i, n, contraction_marks, xp)
+            return (iv + 5.0, 10.0, 0.0, d)
+        elif i < n:
+            _append_singleton_leaf_node(Z, p, n, level, lvs, ivl,
+                                        leaf_label_func, i, labels)
+            return (iv + 5.0, 10.0, 0.0, 0.0)
+
+    # Otherwise, only truncate if we have a leaf node.
+    #
+    # Only place leaves if they correspond to original observations.
+    if i < n:
+        _append_singleton_leaf_node(Z, p, n, level, lvs, ivl,
+                                    leaf_label_func, i, labels)
+        return (iv + 5.0, 10.0, 0.0, 0.0)
+
+    # !!! Otherwise, we don't have a leaf node, so work on plotting a
+    # non-leaf node.
+    # Actual indices of a and b
+    aa = _int_floor(Z[i - n, 0], xp)
+    ab = _int_floor(Z[i - n, 1], xp)
+    if aa >= n:
+        # The number of singletons below cluster a
+        na = Z[aa - n, 3]
+        # The distance between a's two direct children.
+        da = Z[aa - n, 2]
+    else:
+        na = 1
+        da = 0.0
+    if ab >= n:
+        nb = Z[ab - n, 3]
+        db = Z[ab - n, 2]
+    else:
+        nb = 1
+        db = 0.0
+
+    if count_sort == 'ascending' or count_sort is True:
+        # If a has a count greater than b, it and its descendents should
+        # be drawn to the right. Otherwise, to the left.
+        if na > nb:
+            # The cluster index to draw to the left (ua) will be ab
+            # and the one to draw to the right (ub) will be aa
+            ua = ab
+            ub = aa
+        else:
+            ua = aa
+            ub = ab
+    elif count_sort == 'descending':
+        # If a has a count less than or equal to b, it and its
+        # descendents should be drawn to the left. Otherwise, to
+        # the right.
+        if na > nb:
+            ua = aa
+            ub = ab
+        else:
+            ua = ab
+            ub = aa
+    elif distance_sort == 'ascending' or distance_sort is True:
+        # If a has a distance greater than b, it and its descendents should
+        # be drawn to the right. Otherwise, to the left.
+        if da > db:
+            ua = ab
+            ub = aa
+        else:
+            ua = aa
+            ub = ab
+    elif distance_sort == 'descending':
+        # If a has a distance less than or equal to b, it and its
+        # descendents should be drawn to the left. Otherwise, to
+        # the right.
+        if da > db:
+            ua = aa
+            ub = ab
+        else:
+            ua = ab
+            ub = aa
+    else:
+        ua = aa
+        ub = ab
+
+    # Updated iv variable and the amount of space used.
+    (uiva, uwa, uah, uamd) = \
+        _dendrogram_calculate_info(
+            Z=Z, p=p,
+            truncate_mode=truncate_mode,
+            color_threshold=color_threshold,
+            get_leaves=get_leaves,
+            orientation=orientation,
+            labels=labels,
+            count_sort=count_sort,
+            distance_sort=distance_sort,
+            show_leaf_counts=show_leaf_counts,
+            i=ua, iv=iv, ivl=ivl, n=n,
+            icoord_list=icoord_list,
+            dcoord_list=dcoord_list, lvs=lvs,
+            current_color=current_color,
+            color_list=color_list,
+            currently_below_threshold=currently_below_threshold,
+            leaf_label_func=leaf_label_func,
+            level=level + 1, contraction_marks=contraction_marks,
+            link_color_func=link_color_func,
+            above_threshold_color=above_threshold_color)
+
+    h = Z[i - n, 2]
+    if h >= color_threshold or color_threshold <= 0:
+        c = above_threshold_color
+
+        if currently_below_threshold[0]:
+            current_color[0] = (current_color[0] + 1) % len(_link_line_colors)
+        currently_below_threshold[0] = False
+    else:
+        currently_below_threshold[0] = True
+        c = _link_line_colors[current_color[0]]
+
+    (uivb, uwb, ubh, ubmd) = \
+        _dendrogram_calculate_info(
+            Z=Z, p=p,
+            truncate_mode=truncate_mode,
+            color_threshold=color_threshold,
+            get_leaves=get_leaves,
+            orientation=orientation,
+            labels=labels,
+            count_sort=count_sort,
+            distance_sort=distance_sort,
+            show_leaf_counts=show_leaf_counts,
+            i=ub, iv=iv + uwa, ivl=ivl, n=n,
+            icoord_list=icoord_list,
+            dcoord_list=dcoord_list, lvs=lvs,
+            current_color=current_color,
+            color_list=color_list,
+            currently_below_threshold=currently_below_threshold,
+            leaf_label_func=leaf_label_func,
+            level=level + 1, contraction_marks=contraction_marks,
+            link_color_func=link_color_func,
+            above_threshold_color=above_threshold_color)
+
+    max_dist = max(uamd, ubmd, h)
+
+    icoord_list.append([uiva, uiva, uivb, uivb])
+    dcoord_list.append([uah, h, h, ubh])
+    if link_color_func is not None:
+        v = link_color_func(int(i))
+        if not isinstance(v, str):
+            raise TypeError("link_color_func must return a matplotlib "
+                            "color string!")
+        color_list.append(v)
+    else:
+        color_list.append(c)
+
+    return (((uiva + uivb) / 2), uwa + uwb, h, max_dist)
+
+
+@xp_capabilities()
+def is_isomorphic(T1, T2):
+    """
+    Determine if two different cluster assignments are equivalent.
+
+    Parameters
+    ----------
+    T1 : array_like
+        An assignment of singleton cluster ids to flat cluster ids.
+    T2 : array_like
+        An assignment of singleton cluster ids to flat cluster ids.
+
+    Returns
+    -------
+    b : bool
+        Whether the flat cluster assignments `T1` and `T2` are
+        equivalent.
+
+    See Also
+    --------
+    linkage : for a description of what a linkage matrix is.
+    fcluster : for the creation of flat cluster assignments.
+
+    Examples
+    --------
+    >>> from scipy.cluster.hierarchy import fcluster, is_isomorphic
+    >>> from scipy.cluster.hierarchy import single, complete
+    >>> from scipy.spatial.distance import pdist
+
+    Two flat cluster assignments can be isomorphic if they represent the same
+    cluster assignment, with different labels.
+
+    For example, we can use the `scipy.cluster.hierarchy.single` method
+    and flatten the output to four clusters:
+
+    >>> X = [[0, 0], [0, 1], [1, 0],
+    ...      [0, 4], [0, 3], [1, 4],
+    ...      [4, 0], [3, 0], [4, 1],
+    ...      [4, 4], [3, 4], [4, 3]]
+
+    >>> Z = single(pdist(X))
+    >>> T = fcluster(Z, 1, criterion='distance')
+    >>> T
+    array([3, 3, 3, 4, 4, 4, 2, 2, 2, 1, 1, 1], dtype=int32)
+
+    We can then do the same using the
+    `scipy.cluster.hierarchy.complete`: method:
+
+    >>> Z = complete(pdist(X))
+    >>> T_ = fcluster(Z, 1.5, criterion='distance')
+    >>> T_
+    array([1, 1, 1, 2, 2, 2, 3, 3, 3, 4, 4, 4], dtype=int32)
+
+    As we can see, in both cases we obtain four clusters and all the data
+    points are distributed in the same way - the only thing that changes
+    are the flat cluster labels (3 => 1, 4 =>2, 2 =>3 and 4 =>1), so both
+    cluster assignments are isomorphic:
+
+    >>> is_isomorphic(T, T_)
+    True
+
+    """
+    xp = array_namespace(T1, T2)
+    T1 = _asarray(T1, xp=xp)
+    T2 = _asarray(T2, xp=xp)
+
+    if T1.ndim != 1:
+        raise ValueError('T1 must be one-dimensional.')
+    if T2.ndim != 1:
+        raise ValueError('T2 must be one-dimensional.')
+    if T1.shape != T2.shape:
+        raise ValueError('T1 and T2 must have the same number of elements.')
+
+    # For each pair of (i, j) indices, test that
+    # T1[i] == T1[j] <--> T2[i] == T2[j]
+    # In other words, if the same symbol appears multiple times in T1,
+    # then a potentially different symbol must also be repeated in the same
+    # positions in T2, and vice versa.
+
+    # O(n*log(n)) algorithm.
+    # It is also possible to write a O(n) algorithm on top of unique_all(),
+    # but in practice it's much slower even for large clusters.
+    idx = xp.argsort(T1)
+    T1 = xp.take(T1, idx)
+    T2 = xp.take(T2, idx)
+    changes1 = T1 != xp.roll(T1, -1)
+    changes2 = T2 != xp.roll(T2, -1)
+    return xp.all(changes1 == changes2)
+
+
+@lazy_cython
+def maxdists(Z):
+    """
+    Return the maximum distance between any non-singleton cluster.
+
+    Parameters
+    ----------
+    Z : ndarray
+        The hierarchical clustering encoded as a matrix. See
+        ``linkage`` for more information.
+
+    Returns
+    -------
+    maxdists : ndarray
+        A ``(n-1)`` sized numpy array of doubles; ``MD[i]`` represents
+        the maximum distance between any cluster (including
+        singletons) below and including the node with index i. More
+        specifically, ``MD[i] = Z[Q(i)-n, 2].max()`` where ``Q(i)`` is the
+        set of all node indices below and including node i.
+
+    See Also
+    --------
+    linkage : for a description of what a linkage matrix is.
+    is_monotonic : for testing for monotonicity of a linkage matrix.
+
+    Examples
+    --------
+    >>> from scipy.cluster.hierarchy import median, maxdists
+    >>> from scipy.spatial.distance import pdist
+
+    Given a linkage matrix ``Z``, `scipy.cluster.hierarchy.maxdists`
+    computes for each new cluster generated (i.e., for each row of the linkage
+    matrix) what is the maximum distance between any two child clusters.
+
+    Due to the nature of hierarchical clustering, in many cases this is going
+    to be just the distance between the two child clusters that were merged
+    to form the current one - that is, Z[:,2].
+
+    However, for non-monotonic cluster assignments such as
+    `scipy.cluster.hierarchy.median` clustering this is not always the
+    case: There may be cluster formations were the distance between the two
+    clusters merged is smaller than the distance between their children.
+
+    We can see this in an example:
+
+    >>> X = [[0, 0], [0, 1], [1, 0],
+    ...      [0, 4], [0, 3], [1, 4],
+    ...      [4, 0], [3, 0], [4, 1],
+    ...      [4, 4], [3, 4], [4, 3]]
+
+    >>> Z = median(pdist(X))
+    >>> Z
+    array([[ 0.        ,  1.        ,  1.        ,  2.        ],
+           [ 3.        ,  4.        ,  1.        ,  2.        ],
+           [ 9.        , 10.        ,  1.        ,  2.        ],
+           [ 6.        ,  7.        ,  1.        ,  2.        ],
+           [ 2.        , 12.        ,  1.11803399,  3.        ],
+           [ 5.        , 13.        ,  1.11803399,  3.        ],
+           [ 8.        , 15.        ,  1.11803399,  3.        ],
+           [11.        , 14.        ,  1.11803399,  3.        ],
+           [18.        , 19.        ,  3.        ,  6.        ],
+           [16.        , 17.        ,  3.5       ,  6.        ],
+           [20.        , 21.        ,  3.25      , 12.        ]])
+    >>> maxdists(Z)
+    array([1.        , 1.        , 1.        , 1.        , 1.11803399,
+           1.11803399, 1.11803399, 1.11803399, 3.        , 3.5       ,
+           3.5       ])
+
+    Note that while the distance between the two clusters merged when creating the
+    last cluster is 3.25, there are two children (clusters 16 and 17) whose distance
+    is larger (3.5). Thus, `scipy.cluster.hierarchy.maxdists` returns 3.5 in
+    this case.
+
+    """
+    xp = array_namespace(Z)
+    Z = _asarray(Z, order='C', dtype=xp.float64, xp=xp)
+    _is_valid_linkage(Z, throw=True, name='Z', xp=xp)
+
+    def cy_maxdists(Z, validate):
+        if validate:
+            _is_valid_linkage(Z, throw=True, name='Z', xp=np)
+        MD = np.zeros((Z.shape[0],))
+        _hierarchy.get_max_dist_for_each_cluster(Z, MD, Z.shape[0] + 1)
+        return MD
+
+    return xpx.lazy_apply(cy_maxdists, Z, validate=is_lazy_array(Z),
+                          shape=(Z.shape[0], ), dtype=xp.float64,
+                          as_numpy=True, xp=xp)
+
+
+@lazy_cython
+def maxinconsts(Z, R):
+    """
+    Return the maximum inconsistency coefficient for each
+    non-singleton cluster and its children.
+
+    Parameters
+    ----------
+    Z : ndarray
+        The hierarchical clustering encoded as a matrix. See
+        `linkage` for more information.
+    R : ndarray
+        The inconsistency matrix.
+
+    Returns
+    -------
+    MI : ndarray
+        A monotonic ``(n-1)``-sized numpy array of doubles.
+
+    See Also
+    --------
+    linkage : for a description of what a linkage matrix is.
+    inconsistent : for the creation of a inconsistency matrix.
+
+    Examples
+    --------
+    >>> from scipy.cluster.hierarchy import median, inconsistent, maxinconsts
+    >>> from scipy.spatial.distance import pdist
+
+    Given a data set ``X``, we can apply a clustering method to obtain a
+    linkage matrix ``Z``. `scipy.cluster.hierarchy.inconsistent` can
+    be also used to obtain the inconsistency matrix ``R`` associated to
+    this clustering process:
+
+    >>> X = [[0, 0], [0, 1], [1, 0],
+    ...      [0, 4], [0, 3], [1, 4],
+    ...      [4, 0], [3, 0], [4, 1],
+    ...      [4, 4], [3, 4], [4, 3]]
+
+    >>> Z = median(pdist(X))
+    >>> R = inconsistent(Z)
+    >>> Z
+    array([[ 0.        ,  1.        ,  1.        ,  2.        ],
+           [ 3.        ,  4.        ,  1.        ,  2.        ],
+           [ 9.        , 10.        ,  1.        ,  2.        ],
+           [ 6.        ,  7.        ,  1.        ,  2.        ],
+           [ 2.        , 12.        ,  1.11803399,  3.        ],
+           [ 5.        , 13.        ,  1.11803399,  3.        ],
+           [ 8.        , 15.        ,  1.11803399,  3.        ],
+           [11.        , 14.        ,  1.11803399,  3.        ],
+           [18.        , 19.        ,  3.        ,  6.        ],
+           [16.        , 17.        ,  3.5       ,  6.        ],
+           [20.        , 21.        ,  3.25      , 12.        ]])
+    >>> R
+    array([[1.        , 0.        , 1.        , 0.        ],
+           [1.        , 0.        , 1.        , 0.        ],
+           [1.        , 0.        , 1.        , 0.        ],
+           [1.        , 0.        , 1.        , 0.        ],
+           [1.05901699, 0.08346263, 2.        , 0.70710678],
+           [1.05901699, 0.08346263, 2.        , 0.70710678],
+           [1.05901699, 0.08346263, 2.        , 0.70710678],
+           [1.05901699, 0.08346263, 2.        , 0.70710678],
+           [1.74535599, 1.08655358, 3.        , 1.15470054],
+           [1.91202266, 1.37522872, 3.        , 1.15470054],
+           [3.25      , 0.25      , 3.        , 0.        ]])
+
+    Here, `scipy.cluster.hierarchy.maxinconsts` can be used to compute
+    the maximum value of the inconsistency statistic (the last column of
+    ``R``) for each non-singleton cluster and its children:
+
+    >>> maxinconsts(Z, R)
+    array([0.        , 0.        , 0.        , 0.        , 0.70710678,
+           0.70710678, 0.70710678, 0.70710678, 1.15470054, 1.15470054,
+           1.15470054])
+
+    """
+    xp = array_namespace(Z, R)
+    Z = _asarray(Z, order='C', dtype=xp.float64, xp=xp)
+    R = _asarray(R, order='C', dtype=xp.float64, xp=xp)
+    _is_valid_linkage(Z, throw=True, name='Z', xp=xp)
+    _is_valid_im(R, throw=True, name='R', xp=xp)
+
+    if Z.shape[0] != R.shape[0]:
+        raise ValueError("The inconsistency matrix and linkage matrix each "
+                         "have a different number of rows.")
+
+    def cy_maxinconsts(Z, R, validate):
+        if validate:
+            _is_valid_linkage(Z, throw=True, name='Z', xp=np)
+            _is_valid_im(R, throw=True, name='R', xp=np)
+        n = Z.shape[0] + 1
+        MI = np.zeros((n - 1,))
+        _hierarchy.get_max_Rfield_for_each_cluster(Z, R, MI, n, 3)
+        return MI
+
+    return xpx.lazy_apply(cy_maxinconsts, Z, R, validate=is_lazy_array(Z),
+                          shape=(Z.shape[0], ), dtype=xp.float64,
+                          as_numpy=True, xp=xp)
+
+
+@lazy_cython
+def maxRstat(Z, R, i):
+    """
+    Return the maximum statistic for each non-singleton cluster and its
+    children.
+
+    Parameters
+    ----------
+    Z : array_like
+        The hierarchical clustering encoded as a matrix. See `linkage` for more
+        information.
+    R : array_like
+        The inconsistency matrix.
+    i : int
+        The column of `R` to use as the statistic.
+
+    Returns
+    -------
+    MR : ndarray
+        Calculates the maximum statistic for the i'th column of the
+        inconsistency matrix `R` for each non-singleton cluster
+        node. ``MR[j]`` is the maximum over ``R[Q(j)-n, i]``, where
+        ``Q(j)`` the set of all node ids corresponding to nodes below
+        and including ``j``.
+
+    See Also
+    --------
+    linkage : for a description of what a linkage matrix is.
+    inconsistent : for the creation of a inconsistency matrix.
+
+    Examples
+    --------
+    >>> from scipy.cluster.hierarchy import median, inconsistent, maxRstat
+    >>> from scipy.spatial.distance import pdist
+
+    Given a data set ``X``, we can apply a clustering method to obtain a
+    linkage matrix ``Z``. `scipy.cluster.hierarchy.inconsistent` can
+    be also used to obtain the inconsistency matrix ``R`` associated to
+    this clustering process:
+
+    >>> X = [[0, 0], [0, 1], [1, 0],
+    ...      [0, 4], [0, 3], [1, 4],
+    ...      [4, 0], [3, 0], [4, 1],
+    ...      [4, 4], [3, 4], [4, 3]]
+
+    >>> Z = median(pdist(X))
+    >>> R = inconsistent(Z)
+    >>> R
+    array([[1.        , 0.        , 1.        , 0.        ],
+           [1.        , 0.        , 1.        , 0.        ],
+           [1.        , 0.        , 1.        , 0.        ],
+           [1.        , 0.        , 1.        , 0.        ],
+           [1.05901699, 0.08346263, 2.        , 0.70710678],
+           [1.05901699, 0.08346263, 2.        , 0.70710678],
+           [1.05901699, 0.08346263, 2.        , 0.70710678],
+           [1.05901699, 0.08346263, 2.        , 0.70710678],
+           [1.74535599, 1.08655358, 3.        , 1.15470054],
+           [1.91202266, 1.37522872, 3.        , 1.15470054],
+           [3.25      , 0.25      , 3.        , 0.        ]])
+
+    `scipy.cluster.hierarchy.maxRstat` can be used to compute
+    the maximum value of each column of ``R``, for each non-singleton
+    cluster and its children:
+
+    >>> maxRstat(Z, R, 0)
+    array([1.        , 1.        , 1.        , 1.        , 1.05901699,
+           1.05901699, 1.05901699, 1.05901699, 1.74535599, 1.91202266,
+           3.25      ])
+    >>> maxRstat(Z, R, 1)
+    array([0.        , 0.        , 0.        , 0.        , 0.08346263,
+           0.08346263, 0.08346263, 0.08346263, 1.08655358, 1.37522872,
+           1.37522872])
+    >>> maxRstat(Z, R, 3)
+    array([0.        , 0.        , 0.        , 0.        , 0.70710678,
+           0.70710678, 0.70710678, 0.70710678, 1.15470054, 1.15470054,
+           1.15470054])
+
+    """
+    xp = array_namespace(Z, R)
+    Z = _asarray(Z, order='C', dtype=xp.float64, xp=xp)
+    R = _asarray(R, order='C', dtype=xp.float64, xp=xp)
+    _is_valid_linkage(Z, throw=True, name='Z', xp=xp)
+    _is_valid_im(R, throw=True, name='R', xp=xp)
+
+    if not isinstance(i, int):
+        raise TypeError('The third argument must be an integer.')
+
+    if i < 0 or i > 3:
+        raise ValueError('i must be an integer between 0 and 3 inclusive.')
+
+    if Z.shape[0] != R.shape[0]:
+        raise ValueError("The inconsistency matrix and linkage matrix each "
+                         "have a different number of rows.")
+
+    def cy_maxRstat(Z, R, i, validate):
+        if validate:
+            _is_valid_linkage(Z, throw=True, name='Z', xp=np)
+            _is_valid_im(R, throw=True, name='R', xp=np)
+        MR = np.zeros((Z.shape[0],))
+        n = Z.shape[0] + 1
+        _hierarchy.get_max_Rfield_for_each_cluster(Z, R, MR, n, i)
+        return MR
+
+    return xpx.lazy_apply(cy_maxRstat, Z, R, i=i, validate=is_lazy_array(Z),
+                          shape=(Z.shape[0], ), dtype=xp.float64,
+                          as_numpy=True, xp=xp)
+
+
+# Data-dependent output shape makes it impossible to use jax.jit
+@xp_capabilities(cpu_only=True, reason="Cython code", jax_jit=False,
+                 warnings=[("dask.array", "merges chunks")])
+def leaders(Z, T):
+    """
+    Return the root nodes in a hierarchical clustering.
+
+    Returns the root nodes in a hierarchical clustering corresponding
+    to a cut defined by a flat cluster assignment vector ``T``. See
+    the ``fcluster`` function for more information on the format of ``T``.
+
+    For each flat cluster :math:`j` of the :math:`k` flat clusters
+    represented in the n-sized flat cluster assignment vector ``T``,
+    this function finds the lowest cluster node :math:`i` in the linkage
+    tree Z, such that:
+
+    * leaf descendants belong only to flat cluster j
+      (i.e., ``T[p]==j`` for all :math:`p` in :math:`S(i)`, where
+      :math:`S(i)` is the set of leaf ids of descendant leaf nodes
+      with cluster node :math:`i`)
+
+    * there does not exist a leaf that is not a descendant with
+      :math:`i` that also belongs to cluster :math:`j`
+      (i.e., ``T[q]!=j`` for all :math:`q` not in :math:`S(i)`). If
+      this condition is violated, ``T`` is not a valid cluster
+      assignment vector, and an exception will be thrown.
+
+    Parameters
+    ----------
+    Z : ndarray
+        The hierarchical clustering encoded as a matrix. See
+        `linkage` for more information.
+    T : ndarray
+        The flat cluster assignment vector.
+
+    Returns
+    -------
+    L : ndarray
+        The leader linkage node id's stored as a k-element 1-D array,
+        where ``k`` is the number of flat clusters found in ``T``.
+
+        ``L[j]=i`` is the linkage cluster node id that is the
+        leader of flat cluster with id M[j]. If ``i < n``, ``i``
+        corresponds to an original observation, otherwise it
+        corresponds to a non-singleton cluster.
+    M : ndarray
+        The leader linkage node id's stored as a k-element 1-D array, where
+        ``k`` is the number of flat clusters found in ``T``. This allows the
+        set of flat cluster ids to be any arbitrary set of ``k`` integers.
+
+        For example: if ``L[3]=2`` and ``M[3]=8``, the flat cluster with
+        id 8's leader is linkage node 2.
+
+    See Also
+    --------
+    fcluster : for the creation of flat cluster assignments.
+
+    Examples
+    --------
+    >>> from scipy.cluster.hierarchy import ward, fcluster, leaders
+    >>> from scipy.spatial.distance import pdist
+
+    Given a linkage matrix ``Z`` - obtained after apply a clustering method
+    to a dataset ``X`` - and a flat cluster assignment array ``T``:
+
+    >>> X = [[0, 0], [0, 1], [1, 0],
+    ...      [0, 4], [0, 3], [1, 4],
+    ...      [4, 0], [3, 0], [4, 1],
+    ...      [4, 4], [3, 4], [4, 3]]
+
+    >>> Z = ward(pdist(X))
+    >>> Z
+    array([[ 0.        ,  1.        ,  1.        ,  2.        ],
+           [ 3.        ,  4.        ,  1.        ,  2.        ],
+           [ 6.        ,  7.        ,  1.        ,  2.        ],
+           [ 9.        , 10.        ,  1.        ,  2.        ],
+           [ 2.        , 12.        ,  1.29099445,  3.        ],
+           [ 5.        , 13.        ,  1.29099445,  3.        ],
+           [ 8.        , 14.        ,  1.29099445,  3.        ],
+           [11.        , 15.        ,  1.29099445,  3.        ],
+           [16.        , 17.        ,  5.77350269,  6.        ],
+           [18.        , 19.        ,  5.77350269,  6.        ],
+           [20.        , 21.        ,  8.16496581, 12.        ]])
+
+    >>> T = fcluster(Z, 3, criterion='distance')
+    >>> T
+    array([1, 1, 1, 2, 2, 2, 3, 3, 3, 4, 4, 4], dtype=int32)
+
+    `scipy.cluster.hierarchy.leaders` returns the indices of the nodes
+    in the dendrogram that are the leaders of each flat cluster:
+
+    >>> L, M = leaders(Z, T)
+    >>> L
+    array([16, 17, 18, 19], dtype=int32)
+
+    (remember that indices 0-11 point to the 12 data points in ``X``,
+    whereas indices 12-22 point to the 11 rows of ``Z``)
+
+    `scipy.cluster.hierarchy.leaders` also returns the indices of
+    the flat clusters in ``T``:
+
+    >>> M
+    array([1, 2, 3, 4], dtype=int32)
+
+    Notes
+    -----
+    *Array API support (experimental):* This function returns arrays
+    with data-dependent shape. In JAX, at the moment of writing this makes it
+    impossible to execute it inside `@jax.jit`.
+    """
+    xp = array_namespace(Z, T)
+    Z = _asarray(Z, order='C', dtype=xp.float64, xp=xp)
+    T = _asarray(T, order='C', xp=xp)
+    _is_valid_linkage(Z, throw=True, name='Z', xp=xp)
+
+    if T.dtype != xp.int32:
+        raise TypeError('T must be a 1-D array of dtype int32.')
+
+    if T.shape[0] != Z.shape[0] + 1:
+        raise ValueError('Mismatch: len(T)!=Z.shape[0] + 1.')
+
+    n_obs = Z.shape[0] + 1
+
+    def cy_leaders(Z, T, validate):
+        if validate:
+            _is_valid_linkage(Z, throw=True, name='Z', xp=np)
+        n_clusters = int(xpx.nunique(T))
+        L = np.zeros(n_clusters, dtype=np.int32)
+        M = np.zeros(n_clusters, dtype=np.int32)
+        s = _hierarchy.leaders(Z, T, L, M, n_clusters, n_obs)
+        if s >= 0:
+            raise ValueError('T is not a valid assignment vector. Error found '
+                             f'when examining linkage node {s} (< 2n-1).')
+        return L, M
+
+    return xpx.lazy_apply(cy_leaders, Z, T, validate=is_lazy_array(Z),
+                          shape=((None,), (None, )), dtype=(xp.int32, xp.int32),
+                          as_numpy=True, xp=xp)
diff --git a/.venv/lib/python3.12/site-packages/scipy/cluster/hierarchy/_optimal_leaf_ordering.cpython-312-x86_64-linux-gnu.so b/.venv/lib/python3.12/site-packages/scipy/cluster/hierarchy/_optimal_leaf_ordering.cpython-312-x86_64-linux-gnu.so
new file mode 100644
index 0000000000000000000000000000000000000000..e47cdd71fab691a0e444f3a04a14a935619c99e5
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/cluster/hierarchy/_optimal_leaf_ordering.cpython-312-x86_64-linux-gnu.so
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:f8a4de7eefb74603cb803c118ef6739c7c4a1b009e9fddbb7e33ae9f6e62ab9e
+size 179248
diff --git a/.venv/lib/python3.12/site-packages/scipy/cluster/hierarchy/tests/__init__.py b/.venv/lib/python3.12/site-packages/scipy/cluster/hierarchy/tests/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/.venv/lib/python3.12/site-packages/scipy/cluster/hierarchy/tests/hierarchy_test_data.py b/.venv/lib/python3.12/site-packages/scipy/cluster/hierarchy/tests/hierarchy_test_data.py
new file mode 100644
index 0000000000000000000000000000000000000000..7d874ca5eb7141a44559307d1c28dd412171396f
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/cluster/hierarchy/tests/hierarchy_test_data.py
@@ -0,0 +1,145 @@
+from numpy import array
+
+
+Q_X = array([[5.26563660e-01, 3.14160190e-01, 8.00656370e-02],
+             [7.50205180e-01, 4.60299830e-01, 8.98696460e-01],
+             [6.65461230e-01, 6.94011420e-01, 9.10465700e-01],
+             [9.64047590e-01, 1.43082200e-03, 7.39874220e-01],
+             [1.08159060e-01, 5.53028790e-01, 6.63804780e-02],
+             [9.31359130e-01, 8.25424910e-01, 9.52315440e-01],
+             [6.78086960e-01, 3.41903970e-01, 5.61481950e-01],
+             [9.82730940e-01, 7.04605210e-01, 8.70978630e-02],
+             [6.14691610e-01, 4.69989230e-02, 6.02406450e-01],
+             [5.80161260e-01, 9.17354970e-01, 5.88163850e-01],
+             [1.38246310e+00, 1.96358160e+00, 1.94437880e+00],
+             [2.10675860e+00, 1.67148730e+00, 1.34854480e+00],
+             [1.39880070e+00, 1.66142050e+00, 1.32224550e+00],
+             [1.71410460e+00, 1.49176380e+00, 1.45432170e+00],
+             [1.54102340e+00, 1.84374950e+00, 1.64658950e+00],
+             [2.08512480e+00, 1.84524350e+00, 2.17340850e+00],
+             [1.30748740e+00, 1.53801650e+00, 2.16007740e+00],
+             [1.41447700e+00, 1.99329070e+00, 1.99107420e+00],
+             [1.61943490e+00, 1.47703280e+00, 1.89788160e+00],
+             [1.59880600e+00, 1.54988980e+00, 1.57563350e+00],
+             [3.37247380e+00, 2.69635310e+00, 3.39981700e+00],
+             [3.13705120e+00, 3.36528090e+00, 3.06089070e+00],
+             [3.29413250e+00, 3.19619500e+00, 2.90700170e+00],
+             [2.65510510e+00, 3.06785900e+00, 2.97198540e+00],
+             [3.30941040e+00, 2.59283970e+00, 2.57714110e+00],
+             [2.59557220e+00, 3.33477370e+00, 3.08793190e+00],
+             [2.58206180e+00, 3.41615670e+00, 3.26441990e+00],
+             [2.71127000e+00, 2.77032450e+00, 2.63466500e+00],
+             [2.79617850e+00, 3.25473720e+00, 3.41801560e+00],
+             [2.64741750e+00, 2.54538040e+00, 3.25354110e+00]])
+
+ytdist = array([662., 877., 255., 412., 996., 295., 468., 268., 400., 754.,
+                564., 138., 219., 869., 669.])
+
+linkage_ytdist_single = array([[2., 5., 138., 2.],
+                               [3., 4., 219., 2.],
+                               [0., 7., 255., 3.],
+                               [1., 8., 268., 4.],
+                               [6., 9., 295., 6.]])
+
+linkage_ytdist_complete = array([[2., 5., 138., 2.],
+                                 [3., 4., 219., 2.],
+                                 [1., 6., 400., 3.],
+                                 [0., 7., 412., 3.],
+                                 [8., 9., 996., 6.]])
+
+linkage_ytdist_average = array([[2., 5., 138., 2.],
+                                [3., 4., 219., 2.],
+                                [0., 7., 333.5, 3.],
+                                [1., 6., 347.5, 3.],
+                                [8., 9., 680.77777778, 6.]])
+
+linkage_ytdist_weighted = array([[2., 5., 138., 2.],
+                                 [3., 4., 219., 2.],
+                                 [0., 7., 333.5, 3.],
+                                 [1., 6., 347.5, 3.],
+                                 [8., 9., 670.125, 6.]])
+
+# the optimal leaf ordering of linkage_ytdist_single
+linkage_ytdist_single_olo = array([[5., 2., 138., 2.],
+                                   [4., 3., 219., 2.],
+                                   [7., 0., 255., 3.],
+                                   [1., 8., 268., 4.],
+                                   [6., 9., 295., 6.]])
+
+X = array([[1.43054825, -7.5693489],
+           [6.95887839, 6.82293382],
+           [2.87137846, -9.68248579],
+           [7.87974764, -6.05485803],
+           [8.24018364, -6.09495602],
+           [7.39020262, 8.54004355]])
+ 
+linkage_X_centroid = array([[3., 4., 0.36265956, 2.],
+                            [1., 5., 1.77045373, 2.],
+                            [0., 2., 2.55760419, 2.],
+                            [6., 8., 6.43614494, 4.],
+                            [7., 9., 15.17363237, 6.]])
+
+linkage_X_median = array([[3., 4., 0.36265956, 2.],
+                          [1., 5., 1.77045373, 2.],
+                          [0., 2., 2.55760419, 2.],
+                          [6., 8., 6.43614494, 4.],
+                          [7., 9., 15.17363237, 6.]])
+
+linkage_X_ward = array([[3., 4., 0.36265956, 2.],
+                        [1., 5., 1.77045373, 2.],
+                        [0., 2., 2.55760419, 2.],
+                        [6., 8., 9.10208346, 4.],
+                        [7., 9., 24.7784379, 6.]])
+
+# the optimal leaf ordering of linkage_X_ward
+linkage_X_ward_olo = array([[4., 3., 0.36265956, 2.],
+                            [5., 1., 1.77045373, 2.],
+                            [2., 0., 2.55760419, 2.],
+                            [6., 8., 9.10208346, 4.],
+                            [7., 9., 24.7784379, 6.]])
+
+inconsistent_ytdist = {
+    1: array([[138., 0., 1., 0.],
+              [219., 0., 1., 0.],
+              [255., 0., 1., 0.],
+              [268., 0., 1., 0.],
+              [295., 0., 1., 0.]]),
+    2: array([[138., 0., 1., 0.],
+              [219., 0., 1., 0.],
+              [237., 25.45584412, 2., 0.70710678],
+              [261.5, 9.19238816, 2., 0.70710678],
+              [233.66666667, 83.9424406, 3., 0.7306594]]),
+    3: array([[138., 0., 1., 0.],
+              [219., 0., 1., 0.],
+              [237., 25.45584412, 2., 0.70710678],
+              [247.33333333, 25.38372182, 3., 0.81417007],
+              [239., 69.36377537, 4., 0.80733783]]),
+    4: array([[138., 0., 1., 0.],
+              [219., 0., 1., 0.],
+              [237., 25.45584412, 2., 0.70710678],
+              [247.33333333, 25.38372182, 3., 0.81417007],
+              [235., 60.73302232, 5., 0.98793042]])}
+
+fcluster_inconsistent = {
+    0.8: array([6, 2, 2, 4, 6, 2, 3, 7, 3, 5, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 1,
+                1, 1, 1, 1, 1, 1, 1, 1, 1]),
+    1.0: array([6, 2, 2, 4, 6, 2, 3, 7, 3, 5, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 1,
+                1, 1, 1, 1, 1, 1, 1, 1, 1]),
+    2.0: array([1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
+                1, 1, 1, 1, 1, 1, 1, 1, 1])}
+
+fcluster_distance = {
+    0.6: array([4, 4, 4, 4, 4, 4, 4, 5, 4, 4, 6, 6, 6, 6, 6, 7, 6, 6, 6, 6, 3,
+                1, 1, 1, 2, 1, 1, 1, 1, 1]),
+    1.0: array([2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 1,
+                1, 1, 1, 1, 1, 1, 1, 1, 1]),
+    2.0: array([1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
+                1, 1, 1, 1, 1, 1, 1, 1, 1])}
+
+fcluster_maxclust = {
+    8.0: array([5, 5, 5, 5, 5, 5, 5, 6, 5, 5, 7, 7, 7, 7, 7, 8, 7, 7, 7, 7, 4,
+                1, 1, 1, 3, 1, 1, 1, 1, 2]),
+    4.0: array([3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 2,
+                1, 1, 1, 1, 1, 1, 1, 1, 1]),
+    1.0: array([1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
+                1, 1, 1, 1, 1, 1, 1, 1, 1])}
diff --git a/.venv/lib/python3.12/site-packages/scipy/cluster/hierarchy/tests/test_disjoint_set.py b/.venv/lib/python3.12/site-packages/scipy/cluster/hierarchy/tests/test_disjoint_set.py
new file mode 100644
index 0000000000000000000000000000000000000000..a73512d35eef168f625a1942a87d248e73a71aa2
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/cluster/hierarchy/tests/test_disjoint_set.py
@@ -0,0 +1,202 @@
+import pytest
+from pytest import raises as assert_raises
+import numpy as np
+from scipy.cluster.hierarchy import DisjointSet
+import string
+
+
+def generate_random_token():
+    k = len(string.ascii_letters)
+    tokens = list(np.arange(k, dtype=int))
+    tokens += list(np.arange(k, dtype=float))
+    tokens += list(string.ascii_letters)
+    tokens += [None for i in range(k)]
+    tokens = np.array(tokens, dtype=object)
+    rng = np.random.RandomState(seed=0)
+
+    while 1:
+        size = rng.randint(1, 3)
+        element = rng.choice(tokens, size)
+        if size == 1:
+            yield element[0]
+        else:
+            yield tuple(element)
+
+
+def get_elements(n):
+    # dict is deterministic without difficulty of comparing numpy ints
+    elements = {}
+    for element in generate_random_token():
+        if element not in elements:
+            elements[element] = len(elements)
+            if len(elements) >= n:
+                break
+    return list(elements.keys())
+
+
+def test_init():
+    n = 10
+    elements = get_elements(n)
+    dis = DisjointSet(elements)
+    assert dis.n_subsets == n
+    assert list(dis) == elements
+
+
+def test_len():
+    n = 10
+    elements = get_elements(n)
+    dis = DisjointSet(elements)
+    assert len(dis) == n
+
+    dis.add("dummy")
+    assert len(dis) == n + 1
+
+
+@pytest.mark.parametrize("n", [10, 100])
+def test_contains(n):
+    elements = get_elements(n)
+    dis = DisjointSet(elements)
+    for x in elements:
+        assert x in dis
+
+    assert "dummy" not in dis
+
+
+@pytest.mark.parametrize("n", [10, 100])
+def test_add(n):
+    elements = get_elements(n)
+    dis1 = DisjointSet(elements)
+
+    dis2 = DisjointSet()
+    for i, x in enumerate(elements):
+        dis2.add(x)
+        assert len(dis2) == i + 1
+
+        # test idempotency by adding element again
+        dis2.add(x)
+        assert len(dis2) == i + 1
+
+    assert list(dis1) == list(dis2)
+
+
+def test_element_not_present():
+    elements = get_elements(n=10)
+    dis = DisjointSet(elements)
+
+    with assert_raises(KeyError):
+        dis["dummy"]
+
+    with assert_raises(KeyError):
+        dis.merge(elements[0], "dummy")
+
+    with assert_raises(KeyError):
+        dis.connected(elements[0], "dummy")
+
+
+@pytest.mark.parametrize("direction", ["forwards", "backwards"])
+@pytest.mark.parametrize("n", [10, 100])
+def test_linear_union_sequence(n, direction):
+    elements = get_elements(n)
+    dis = DisjointSet(elements)
+    assert elements == list(dis)
+
+    indices = list(range(n - 1))
+    if direction == "backwards":
+        indices = indices[::-1]
+
+    for it, i in enumerate(indices):
+        assert not dis.connected(elements[i], elements[i + 1])
+        assert dis.merge(elements[i], elements[i + 1])
+        assert dis.connected(elements[i], elements[i + 1])
+        assert dis.n_subsets == n - 1 - it
+
+    roots = [dis[i] for i in elements]
+    if direction == "forwards":
+        assert all(elements[0] == r for r in roots)
+    else:
+        assert all(elements[-2] == r for r in roots)
+    assert not dis.merge(elements[0], elements[-1])
+
+
+@pytest.mark.parametrize("n", [10, 100])
+def test_self_unions(n):
+    elements = get_elements(n)
+    dis = DisjointSet(elements)
+
+    for x in elements:
+        assert dis.connected(x, x)
+        assert not dis.merge(x, x)
+        assert dis.connected(x, x)
+    assert dis.n_subsets == len(elements)
+
+    assert elements == list(dis)
+    roots = [dis[x] for x in elements]
+    assert elements == roots
+
+
+@pytest.mark.parametrize("order", ["ab", "ba"])
+@pytest.mark.parametrize("n", [10, 100])
+def test_equal_size_ordering(n, order):
+    elements = get_elements(n)
+    dis = DisjointSet(elements)
+
+    rng = np.random.RandomState(seed=0)
+    indices = np.arange(n)
+    rng.shuffle(indices)
+
+    for i in range(0, len(indices), 2):
+        a, b = elements[indices[i]], elements[indices[i + 1]]
+        if order == "ab":
+            assert dis.merge(a, b)
+        else:
+            assert dis.merge(b, a)
+
+        expected = elements[min(indices[i], indices[i + 1])]
+        assert dis[a] == expected
+        assert dis[b] == expected
+
+
+@pytest.mark.parametrize("kmax", [5, 10])
+def test_binary_tree(kmax):
+    n = 2**kmax
+    elements = get_elements(n)
+    dis = DisjointSet(elements)
+    rng = np.random.RandomState(seed=0)
+
+    for k in 2**np.arange(kmax):
+        for i in range(0, n, 2 * k):
+            r1, r2 = rng.randint(0, k, size=2)
+            a, b = elements[i + r1], elements[i + k + r2]
+            assert not dis.connected(a, b)
+            assert dis.merge(a, b)
+            assert dis.connected(a, b)
+
+        assert elements == list(dis)
+        roots = [dis[i] for i in elements]
+        expected_indices = np.arange(n) - np.arange(n) % (2 * k)
+        expected = [elements[i] for i in expected_indices]
+        assert roots == expected
+
+
+@pytest.mark.parametrize("n", [10, 100])
+def test_subsets(n):
+    elements = get_elements(n)
+    dis = DisjointSet(elements)
+
+    rng = np.random.RandomState(seed=0)
+    for i, j in rng.randint(0, n, (n, 2)):
+        x = elements[i]
+        y = elements[j]
+
+        expected = {element for element in dis if {dis[element]} == {dis[x]}}
+        assert dis.subset_size(x) == len(dis.subset(x))
+        assert expected == dis.subset(x)
+
+        expected = {dis[element]: set() for element in dis}
+        for element in dis:
+            expected[dis[element]].add(element)
+        expected = list(expected.values())
+        assert expected == dis.subsets()
+
+        dis.merge(x, y)
+        assert dis.subset(x) == dis.subset(y)
diff --git a/.venv/lib/python3.12/site-packages/scipy/cluster/hierarchy/tests/test_hierarchy.py b/.venv/lib/python3.12/site-packages/scipy/cluster/hierarchy/tests/test_hierarchy.py
new file mode 100644
index 0000000000000000000000000000000000000000..33a3e223b02d127f678b49cda79b6b8e02c0eb4e
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/cluster/hierarchy/tests/test_hierarchy.py
@@ -0,0 +1,1257 @@
+#
+# Author: Damian Eads
+# Date: April 17, 2008
+#
+# Copyright (C) 2008 Damian Eads
+#
+# Redistribution and use in source and binary forms, with or without
+# modification, are permitted provided that the following conditions
+# are met:
+#
+# 1. Redistributions of source code must retain the above copyright
+#    notice, this list of conditions and the following disclaimer.
+#
+# 2. Redistributions in binary form must reproduce the above
+#    copyright notice, this list of conditions and the following
+#    disclaimer in the documentation and/or other materials provided
+#    with the distribution.
+#
+# 3. The name of the author may 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.
+import numpy as np
+from numpy.testing import assert_allclose, assert_equal, assert_array_equal, assert_
+import pytest
+from pytest import raises as assert_raises
+
+from scipy.cluster.hierarchy import (
+    ClusterWarning, linkage, from_mlab_linkage, to_mlab_linkage,
+    num_obs_linkage, inconsistent, cophenet, fclusterdata, fcluster,
+    is_isomorphic, single, ward, leaders,
+    correspond, is_monotonic, maxdists, maxinconsts, maxRstat,
+    is_valid_linkage, is_valid_im, to_tree, leaves_list, dendrogram,
+    set_link_color_palette, cut_tree, optimal_leaf_ordering,
+    complete, average, weighted, centroid, median)
+from scipy.cluster.hierarchy._hierarchy import Heap
+from scipy.cluster.hierarchy._hierarchy_impl import (
+    _order_cluster_tree, _hierarchy, _EUCLIDEAN_METHODS, _LINKAGE_METHODS
+)
+from scipy.spatial.distance import pdist
+from scipy._lib._array_api import (eager_warns, make_xp_test_case,
+                                   xp_assert_close, xp_assert_equal,
+                                   make_xp_pytest_param, _xp_copy_to_numpy)
+import scipy._external.array_api_extra as xpx
+
+from threading import Lock
+
+from . import hierarchy_test_data
+
+class eager:
+    # Bypass xpx.testing.lazy_xp_function when calling
+    # these functions from this namespace
+    is_valid_im = is_valid_im
+    is_valid_linkage = is_valid_linkage
+
+
+# Matplotlib is not a scipy dependency but is optionally used in dendrogram, so
+# check if it's available
+try:
+    import matplotlib
+    # and set the backend to be Agg (no gui)
+    matplotlib.use('Agg')
+    # before importing pyplot
+    import matplotlib.pyplot as plt
+    have_matplotlib = True
+except Exception:
+    have_matplotlib = False
+
+skip_xp_backends = pytest.mark.skip_xp_backends
+
+
+@make_xp_test_case(linkage)
+class TestLinkage:
+
+    @skip_xp_backends("jax.numpy", reason="Can't raise inside jax.pure_callback")
+    def test_linkage_non_finite_elements_in_distance_matrix(self, xp):
+        # Tests linkage(Y) where Y contains a non-finite element (e.g. NaN or Inf).
+        # Exception expected.
+        y = xp.asarray([xp.nan] + [0.0]*5)
+        assert_raises(ValueError, linkage, y)
+
+    def test_linkage_empty_distance_matrix(self, xp):
+        # Tests linkage(Y) where Y is a 0x4 linkage matrix. Exception expected.
+        y = xp.zeros((0,))
+        assert_raises(ValueError, linkage, y)
+
+    def test_linkage_tdist(self, xp):
+        for method in ['single', 'complete', 'average', 'weighted']:
+            self.check_linkage_tdist(method, xp)
+
+    def check_linkage_tdist(self, method, xp):
+        # Tests linkage(Y, method) on the tdist data set.
+        Z = linkage(xp.asarray(hierarchy_test_data.ytdist), method)
+        expectedZ = getattr(hierarchy_test_data, 'linkage_ytdist_' + method)
+        xp_assert_close(Z, xp.asarray(expectedZ), atol=1e-10)
+
+    def test_linkage_X(self, xp):
+        for method in ['centroid', 'median', 'ward']:
+            self.check_linkage_q(method, xp)
+
+    def check_linkage_q(self, method, xp):
+        # Tests linkage(Y, method) on the Q data set.
+        Z = linkage(xp.asarray(hierarchy_test_data.X), method)
+        expectedZ = getattr(hierarchy_test_data, 'linkage_X_' + method)
+        xp_assert_close(Z, xp.asarray(expectedZ), atol=1e-06)
+
+        X = xp.asarray(hierarchy_test_data.X)
+        y = pdist(X, metric="euclidean")
+        Z = linkage(y, method)
+        xp_assert_close(Z, xp.asarray(expectedZ), atol=1e-06)
+
+    def test_compare_with_trivial(self, xp):
+        rng = np.random.RandomState(0)
+        n = 20
+        X = rng.rand(n, 2)
+        d = pdist(X)
+
+        for method, code in _LINKAGE_METHODS.items():
+            Z_trivial = _hierarchy.linkage(d, n, code)
+            Z = linkage(xp.asarray(d), method)
+            xp_assert_close(Z, xp.asarray(Z_trivial), rtol=1e-14, atol=1e-15)
+
+    def test_optimal_leaf_ordering(self, xp):
+        Z = linkage(xp.asarray(hierarchy_test_data.ytdist), optimal_ordering=True)
+        expectedZ = getattr(hierarchy_test_data, 'linkage_ytdist_single_olo')
+        xp_assert_close(Z, xp.asarray(expectedZ), atol=1e-10)
+
+    @pytest.mark.parametrize("method,expect", [
+        ('single',   [[0, 1, 1.41421356, 2],
+                      [2, 3, 1.41421356, 3]]),
+        ('complete', [[0, 1, 1.41421356, 2],
+                      [2, 3, 2.82842712, 3]]),
+        ('average',  [[0, 1, 1.41421356, 2],
+                      [2, 3, 2.12132034, 3]]),
+        ('weighted', [[0, 1, 1.41421356, 2],
+                      [2, 3, 2.12132034, 3]]),
+        ('centroid', [[0, 1, 1.41421356, 2],
+                      [2, 3, 2.12132034, 3]]),
+        ('median',   [[0, 1, 1.41421356, 2],
+                      [2, 3, 2.12132034, 3]]),
+        ('ward',     [[0, 1, 1.41421356, 2],
+                      [2, 3, 2.44948974, 3]]),
+    ])
+    def test_linkage_ties(self, method, expect, xp):
+        X = xp.asarray([[-1, -1], [0, 0], [1, 1]])
+        Z = linkage(X, method=method)
+        expect = xp.asarray(expect, dtype=xp.float64)
+        xp_assert_close(Z, expect, atol=1e-06)
+
+    def test_unsupported_uncondensed_distance_matrix_linkage_warning(self, xp):
+        X = xp.asarray([[0, 1], [1, 0]])
+        with eager_warns(ClusterWarning, xp=xp):
+            linkage(X)
+
+    @pytest.mark.parametrize("method", _EUCLIDEAN_METHODS)
+    def test_euclidean_linkage_value_error(self, method, xp):
+        X = xp.asarray([[1, 1], [1, 1]])
+        with pytest.raises(ValueError):
+            linkage(X, method=method, metric='cityblock')
+
+    def test_2x2_linkage(self, xp):
+        Z1 = linkage(xp.asarray([1]), method='single', metric='euclidean')
+        Z2 = linkage(xp.asarray([[0, 1], [0, 0]]), method='single', metric='euclidean')
+        xp_assert_close(Z1, Z2, rtol=1e-15)
+
+    @skip_xp_backends("jax.numpy", reason="Can't raise inside jax.pure_callback")
+    def test_centroid_neg_distance(self, xp):
+        # gh-21011
+        values = xp.asarray([0, 0, -1])
+        with pytest.raises(ValueError):
+            # This is just checking that this doesn't crash
+            linkage(values, method='centroid')
+
+    @pytest.mark.parametrize(
+        "func", [
+            make_xp_pytest_param(func)
+            for func in [complete, average, weighted, centroid, median, ward]
+        ]
+    )
+    def test_wrappers(self, func, xp):
+        # This test is required because all functions advertised as
+        # supporting alt-backends must be tested with the xp fixture.
+        X = xp.asarray([[-1, -1], [0, 0], [1, 1]])
+        expected = xp.asarray(
+            linkage(_xp_copy_to_numpy(X), method=func.__name__, metric="euclidean")
+        )
+        observed = func(X)
+        xp_assert_close(observed, expected)
+
+
+@make_xp_test_case(inconsistent)
+class TestInconsistent:
+
+    def test_inconsistent_tdist(self, xp):
+        for depth in hierarchy_test_data.inconsistent_ytdist:
+            self.check_inconsistent_tdist(depth, xp)
+
+    def check_inconsistent_tdist(self, depth, xp):
+        Z = xp.asarray(hierarchy_test_data.linkage_ytdist_single)
+        xp_assert_close(inconsistent(Z, depth),
+                        xp.asarray(hierarchy_test_data.inconsistent_ytdist[depth]))
+
+
+@make_xp_test_case(cophenet)
+class TestCopheneticDistance:
+
+    def test_linkage_cophenet_tdist_Z(self, xp):
+        # Tests cophenet(Z) on tdist data set.
+        expectedM = xp.asarray([268, 295, 255, 255, 295, 295, 268, 268, 295, 295,
+                                295, 138, 219, 295, 295])
+        Z = xp.asarray(hierarchy_test_data.linkage_ytdist_single)
+        M = cophenet(Z)
+        xp_assert_close(M, xp.asarray(expectedM, dtype=xp.float64), atol=1e-10)
+
+    def test_linkage_cophenet_tdist_Z_Y(self, xp):
+        # Tests cophenet(Z, Y) on tdist data set.
+        Z = xp.asarray(hierarchy_test_data.linkage_ytdist_single)
+        (c, M) = cophenet(Z, xp.asarray(hierarchy_test_data.ytdist))
+        expectedM = xp.asarray([268, 295, 255, 255, 295, 295, 268, 268, 295, 295,
+                                295, 138, 219, 295, 295], dtype=xp.float64)
+        expectedc = xp.asarray(0.639931296433393415057366837573, dtype=xp.float64)[()]
+        xp_assert_close(c, expectedc, atol=1e-10)
+        xp_assert_close(M, expectedM, atol=1e-10)
+
+    @skip_xp_backends("jax.numpy", reason="Can't raise inside jax.pure_callback")
+    def test_gh_22183(self, xp):
+        # check for lack of segfault
+        # (out of bounds memory access)
+        # and correct interception of
+        # invalid linkage matrix
+        arr=[[0.0, 1.0, 1.0, 2.0],
+             [2.0, 12.0, 1.0, 3.0],
+             [3.0, 4.0, 1.0, 2.0],
+             [5.0, 14.0, 1.0, 3.0],
+             [6.0, 7.0, 1.0, 2.0],
+             [8.0, 16.0, 1.0, 3.0],
+             [9.0, 10.0, 1.0, 2.0],
+             [11.0, 18.0, 1.0, 3.0],
+             [13.0, 15.0, 2.0, 6.0],
+             [17.0, 20.0, 2.0, 32.0],
+             [19.0, 21.0, 2.0, 12.0]]
+        with pytest.raises(ValueError, match="excessive observations"):
+            cophenet(xp.asarray(arr))
+
+
+@make_xp_test_case(from_mlab_linkage, to_mlab_linkage)
+class TestMLabLinkageConversion:
+
+    def test_mlab_linkage_conversion_empty(self, xp):
+        # Tests from/to_mlab_linkage on empty linkage array.
+        X = xp.asarray([], dtype=xp.float64)
+        xp_assert_equal(from_mlab_linkage(X), X)
+        xp_assert_equal(to_mlab_linkage(X), X)
+
+    def test_mlab_linkage_conversion_single_row(self, xp):
+        # Tests from/to_mlab_linkage on linkage array with single row.
+        Z = xp.asarray([[0., 1., 3., 2.]])
+        Zm = xp.asarray([[1, 2, 3]])
+        xp_assert_close(from_mlab_linkage(Zm), xp.asarray(Z, dtype=xp.float64),
+                        rtol=1e-15)
+        xp_assert_close(to_mlab_linkage(Z), xp.asarray(Zm, dtype=xp.float64),
+                        rtol=1e-15)
+
+    def test_mlab_linkage_conversion_multiple_rows(self, xp):
+        # Tests from/to_mlab_linkage on linkage array with multiple rows.
+        Zm = xp.asarray([[3, 6, 138], [4, 5, 219],
+                         [1, 8, 255], [2, 9, 268], [7, 10, 295]])
+        Z = xp.asarray([[2., 5., 138., 2.],
+                        [3., 4., 219., 2.],
+                        [0., 7., 255., 3.],
+                        [1., 8., 268., 4.],
+                        [6., 9., 295., 6.]],
+                       dtype=xp.float64)
+        xp_assert_close(from_mlab_linkage(Zm), Z, rtol=1e-15)
+        xp_assert_close(to_mlab_linkage(Z), xp.asarray(Zm, dtype=xp.float64),
+                        rtol=1e-15)
+
+
+@make_xp_test_case(fclusterdata)
+class TestFclusterData:
+
+    @make_xp_test_case(is_isomorphic)
+    @pytest.mark.parametrize("criterion,t",
+        [("inconsistent", t) for t in hierarchy_test_data.fcluster_inconsistent]
+        + [("distance", t) for t in hierarchy_test_data.fcluster_distance]
+        + [("maxclust", t) for t in hierarchy_test_data.fcluster_maxclust]
+    )
+    def test_fclusterdata(self, t, criterion, xp):
+        # Tests fclusterdata(X, criterion=criterion, t=t) on a random 3-cluster data set
+        expectedT = xp.asarray(getattr(hierarchy_test_data, 'fcluster_' + criterion)[t])
+        X = xp.asarray(hierarchy_test_data.Q_X)
+        T = fclusterdata(X, criterion=criterion, t=t)
+        assert is_isomorphic(T, expectedT)
+
+
+@make_xp_test_case(fcluster)
+class TestFcluster:
+
+    @make_xp_test_case(single, is_isomorphic)
+    @pytest.mark.parametrize("criterion,t",
+        [("inconsistent", t) for t in hierarchy_test_data.fcluster_inconsistent]
+        + [("distance", t) for t in hierarchy_test_data.fcluster_distance]
+        + [("maxclust", t) for t in hierarchy_test_data.fcluster_maxclust]
+    )
+    def test_fcluster(self, t, criterion, xp):
+        # Tests fcluster(Z, criterion=criterion, t=t) on a random 3-cluster data set.
+        expectedT = xp.asarray(getattr(hierarchy_test_data, 'fcluster_' + criterion)[t])
+        Z = single(xp.asarray(hierarchy_test_data.Q_X))
+        T = fcluster(Z, criterion=criterion, t=t)
+        assert_(is_isomorphic(T, expectedT))
+
+    @make_xp_test_case(single, is_isomorphic, maxdists)
+    @pytest.mark.parametrize("t", hierarchy_test_data.fcluster_distance)
+    def test_fcluster_monocrit(self, t, xp):
+        expectedT = xp.asarray(hierarchy_test_data.fcluster_distance[t])
+        Z = single(xp.asarray(hierarchy_test_data.Q_X))
+        T = fcluster(Z, t, criterion='monocrit', monocrit=maxdists(Z))
+        assert_(is_isomorphic(T, expectedT))
+
+    @make_xp_test_case(single, is_isomorphic, maxdists)
+    @pytest.mark.parametrize("t", hierarchy_test_data.fcluster_maxclust)
+    def test_fcluster_maxclust_monocrit(self, t, xp):
+        expectedT = xp.asarray(hierarchy_test_data.fcluster_maxclust[t])
+        Z = single(xp.asarray(hierarchy_test_data.Q_X))
+        T = fcluster(Z, t, criterion='maxclust_monocrit', monocrit=maxdists(Z))
+        assert_(is_isomorphic(T, expectedT))
+
+    @make_xp_test_case(single)
+    def test_fcluster_maxclust_gh_12651(self, xp):
+        y = xp.asarray([[1], [4], [5]])
+        Z = single(y)
+        assert_array_equal(fcluster(Z, t=1, criterion="maxclust"),
+                           xp.asarray([1, 1, 1]))
+        assert_array_equal(fcluster(Z, t=2, criterion="maxclust"),
+                           xp.asarray([2, 1, 1]))
+        assert_array_equal(fcluster(Z, t=3, criterion="maxclust"),
+                           xp.asarray([1, 2, 3]))
+        assert_array_equal(fcluster(Z, t=5, criterion="maxclust"),
+                           xp.asarray([1, 2, 3]))
+
+
+@make_xp_test_case(leaders)
+class TestLeaders:
+
+    def test_leaders_single(self, xp):
+        # Tests leaders using a flat clustering generated by single linkage.
+        X = hierarchy_test_data.Q_X
+        Y = pdist(X)
+        Z = linkage(Y)
+        T = fcluster(Z, criterion='maxclust', t=3)
+        Z = xp.asarray(Z)
+        T = xp.asarray(T, dtype=xp.int32)
+        L = leaders(Z, T)
+        expect = xp.asarray([53, 55, 56, 2, 3, 1], dtype=xp.int32)
+        xp_assert_close(xp.concat(L), expect, rtol=1e-15)
+
+
+@make_xp_test_case(is_isomorphic)
+class TestIsIsomorphic:
+
+    def test_array_like(self):
+        assert is_isomorphic([1, 1, 1], [2, 2, 2])
+        assert is_isomorphic([], [])
+
+    def test_is_isomorphic_1(self, xp):
+        # Tests is_isomorphic on test case #1 (one flat cluster, different labellings)
+        a = xp.asarray([1, 1, 1])
+        b = xp.asarray([2, 2, 2])
+        assert is_isomorphic(a, b)
+        assert is_isomorphic(b, a)
+
+    def test_is_isomorphic_2(self, xp):
+        # Tests is_isomorphic on test case #2 (two flat clusters, different labelings)
+        a = xp.asarray([1, 7, 1])
+        b = xp.asarray([2, 3, 2])
+        assert is_isomorphic(a, b)
+        assert is_isomorphic(b, a)
+
+    def test_is_isomorphic_3(self, xp):
+        # Tests is_isomorphic on test case #3 (no flat clusters)
+        a = xp.asarray([])
+        b = xp.asarray([])
+        assert is_isomorphic(a, b)
+
+    def test_is_isomorphic_4A(self, xp):
+        # Tests is_isomorphic on test case #4A
+        # (3 flat clusters, different labelings, isomorphic)
+        a = xp.asarray([1, 2, 3])
+        b = xp.asarray([1, 3, 2])
+        assert is_isomorphic(a, b)
+        assert is_isomorphic(b, a)
+
+    def test_is_isomorphic_4B(self, xp):
+        # Tests is_isomorphic on test case #4B
+        # (3 flat clusters, different labelings, nonisomorphic)
+        a = xp.asarray([1, 2, 3, 3])
+        b = xp.asarray([1, 3, 2, 3])
+        assert not is_isomorphic(a, b)
+        assert not is_isomorphic(b, a)
+
+    def test_is_isomorphic_4C(self, xp):
+        # Tests is_isomorphic on test case #4C
+        # (3 flat clusters, different labelings, isomorphic)
+        a = xp.asarray([7, 2, 3])
+        b = xp.asarray([6, 3, 2])
+        assert is_isomorphic(a, b)
+        assert is_isomorphic(b, a)
+
+    @pytest.mark.parametrize("nclusters", [2, 3, 5])
+    def test_is_isomorphic_5(self, nclusters, xp):
+        # Tests is_isomorphic on test case #5 (1000 observations, 2/3/5 random
+        # clusters, random permutation of the labeling).
+        self.is_isomorphic_randperm(1000, nclusters, xp=xp)
+
+    @pytest.mark.parametrize("nclusters", [2, 3, 5])
+    def test_is_isomorphic_6(self, nclusters, xp):
+        # Tests is_isomorphic on test case #5A (1000 observations, 2/3/5 random
+        # clusters, random permutation of the labeling, slightly
+        # nonisomorphic.)
+        self.is_isomorphic_randperm(1000, nclusters, True, 5, xp=xp)
+
+    def test_is_isomorphic_7(self, xp):
+        # Regression test for gh-6271
+        a = xp.asarray([1, 2, 3])
+        b = xp.asarray([1, 1, 1])
+        assert not is_isomorphic(a, b)
+
+    def is_isomorphic_randperm(self, nobs, nclusters, noniso=False, nerrors=0, *, xp):
+        rng = np.random.default_rng()
+        for _ in range(3):
+            a = rng.integers(0, nclusters, size=nobs)
+            p = rng.permutation(nclusters)
+            b = p.take(a.astype(np.intp))
+            if noniso:
+                q = rng.permutation(nobs)
+                b[q[0:nerrors]] += 1
+                b[q[0:nerrors]] %= nclusters
+            a = xp.asarray(a)
+            b = xp.asarray(b)
+            assert is_isomorphic(a, b) == (not noniso)
+            assert is_isomorphic(b, a) == (not noniso)
+
+
+@make_xp_test_case(is_valid_linkage)
+class TestIsValidLinkage:
+
+    @pytest.mark.parametrize("nrow, ncol, valid", [(2, 5, False), (2, 3, False),
+                                                  (1, 4, True), (2, 4, True)])
+    def test_is_valid_linkage_various_size(self, nrow, ncol, valid, xp):
+        # Tests is_valid_linkage(Z) with linkage matrices of various sizes
+        Z = xp.asarray([[0, 1, 3.0, 2, 5],
+                        [3, 2, 4.0, 3, 3]], dtype=xp.float64)
+        Z = Z[:nrow, :ncol]
+        xp_assert_equal(is_valid_linkage(Z), valid, check_namespace=False)
+        if not valid:
+            assert_raises(ValueError, is_valid_linkage, Z, throw=True)
+
+    def test_is_valid_linkage_int_type(self, xp):
+        # Tests is_valid_linkage(Z) with integer type.
+        Z = xp.asarray([[0, 1, 3.0, 2],
+                        [3, 2, 4.0, 3]], dtype=xp.int64)
+        xp_assert_equal(is_valid_linkage(Z), False, check_namespace=False)
+        assert_raises(TypeError, is_valid_linkage, Z, throw=True)
+
+    def test_is_valid_linkage_empty(self, xp):
+        # Tests is_valid_linkage(Z) with empty linkage.
+        Z = xp.zeros((0, 4), dtype=xp.float64)
+        xp_assert_equal(is_valid_linkage(Z), False, check_namespace=False)
+        assert_raises(ValueError, is_valid_linkage, Z, throw=True)
+
+    def test_is_valid_linkage_4_and_up(self, xp):
+        # Tests is_valid_linkage(Z) on linkage on observation sets between
+        # sizes 4 and 15 (step size 3).
+        for i in range(4, 15, 3):
+            y = np.random.rand(i*(i-1)//2)
+            Z = xp.asarray(linkage(y))
+            y = xp.asarray(y)
+            xp_assert_equal(is_valid_linkage(Z), True, check_namespace=False)
+
+    def test_is_valid_linkage_4_and_up_neg_index_left(self, xp):
+        # Tests is_valid_linkage(Z) on linkage on observation sets between
+        # sizes 4 and 15 (step size 3) with negative indices (left).
+        for i in range(4, 15, 3):
+            y = np.random.rand(i*(i-1)//2)
+            Z = xp.asarray(linkage(y))
+            y = xp.asarray(y)
+            Z = xpx.at(Z)[i//2, 0].set(-2)
+            xp_assert_equal(is_valid_linkage(Z), False, check_namespace=False)
+            with pytest.raises(ValueError):
+                eager.is_valid_linkage(Z, throw=True)
+
+    def test_is_valid_linkage_4_and_up_neg_index_right(self, xp):
+        # Tests is_valid_linkage(Z) on linkage on observation sets between
+        # sizes 4 and 15 (step size 3) with negative indices (right).
+        for i in range(4, 15, 3):
+            y = np.random.rand(i*(i-1)//2)
+            Z = xp.asarray(linkage(y))
+            y = xp.asarray(y)
+            Z = xpx.at(Z)[i//2, 1].set(-2)
+            xp_assert_equal(is_valid_linkage(Z), False, check_namespace=False)
+            with pytest.raises(ValueError):
+                eager.is_valid_linkage(Z, throw=True)
+
+    def test_is_valid_linkage_4_and_up_neg_dist(self, xp):
+        # Tests is_valid_linkage(Z) on linkage on observation sets between
+        # sizes 4 and 15 (step size 3) with negative distances.
+        for i in range(4, 15, 3):
+            y = np.random.rand(i*(i-1)//2)
+            Z = xp.asarray(linkage(y))
+            y = xp.asarray(y)
+            Z = xpx.at(Z)[i//2, 2].set(-0.5)
+            xp_assert_equal(is_valid_linkage(Z), False, check_namespace=False)
+            with pytest.raises(ValueError):
+                eager.is_valid_linkage(Z, throw=True)
+
+    def test_is_valid_linkage_4_and_up_neg_counts(self, xp):
+        # Tests is_valid_linkage(Z) on linkage on observation sets between
+        # sizes 4 and 15 (step size 3) with negative counts.
+        for i in range(4, 15, 3):
+            y = np.random.rand(i*(i-1)//2)
+            Z = xp.asarray(linkage(y))
+            y = xp.asarray(y)
+            Z = xpx.at(Z)[i//2, 3].set(-2)
+            xp_assert_equal(is_valid_linkage(Z), False, check_namespace=False)
+            with pytest.raises(ValueError):
+                eager.is_valid_linkage(Z, throw=True)
+
+
+@make_xp_test_case(is_valid_im)
+class TestIsValidInconsistent:
+
+    def test_is_valid_im_int_type(self, xp):
+        # Tests is_valid_im(R) with integer type.
+        R = xp.asarray([[0, 1, 3.0, 2],
+                        [3, 2, 4.0, 3]], dtype=xp.int64)
+        xp_assert_equal(is_valid_im(R), False, check_namespace=False)
+        assert_raises(TypeError, is_valid_im, R, throw=True)
+
+    @pytest.mark.parametrize("nrow, ncol, valid", [(2, 5, False), (2, 3, False),
+                                                  (1, 4, True), (2, 4, True)])
+    def test_is_valid_im_various_size(self, nrow, ncol, valid, xp):
+        # Tests is_valid_im(R) with linkage matrices of various sizes
+        R = xp.asarray([[0, 1, 3.0, 2, 5],
+                        [3, 2, 4.0, 3, 3]], dtype=xp.float64)
+        R = R[:nrow, :ncol]
+        xp_assert_equal(is_valid_im(R), valid, check_namespace=False)
+        if not valid:
+            assert_raises(ValueError, is_valid_im, R, throw=True)
+
+    def test_is_valid_im_empty(self, xp):
+        # Tests is_valid_im(R) with empty inconsistency matrix.
+        R = xp.zeros((0, 4), dtype=xp.float64)
+        xp_assert_equal(is_valid_im(R), False, check_namespace=False)
+        assert_raises(ValueError, is_valid_im, R, throw=True)
+
+    def test_is_valid_im_4_and_up(self, xp):
+        # Tests is_valid_im(R) on im on observation sets between sizes 4 and 15
+        # (step size 3).
+        for i in range(4, 15, 3):
+            y = np.random.rand(i*(i-1)//2)
+            Z = linkage(y)
+            R = inconsistent(Z)
+            R = xp.asarray(R)
+            xp_assert_equal(is_valid_im(R), True, check_namespace=False)
+
+    def test_is_valid_im_4_and_up_neg_index_left(self, xp):
+        # Tests is_valid_im(R) on im on observation sets between sizes 4 and 15
+        # (step size 3) with negative link height means.
+        for i in range(4, 15, 3):
+            y = np.random.rand(i*(i-1)//2)
+            Z = linkage(y)
+            R = inconsistent(Z)
+            R = xpx.at(R)[i//2 , 0].set(-2.0)
+            R = xp.asarray(R)
+            xp_assert_equal(is_valid_im(R), False, check_namespace=False)
+            with pytest.raises(ValueError):
+                eager.is_valid_im(R, throw=True)
+
+    def test_is_valid_im_4_and_up_neg_index_right(self, xp):
+        # Tests is_valid_im(R) on im on observation sets between sizes 4 and 15
+        # (step size 3) with negative link height standard deviations.
+        for i in range(4, 15, 3):
+            y = np.random.rand(i*(i-1)//2)
+            Z = linkage(y)
+            R = inconsistent(Z)
+            R = xpx.at(R)[i//2 , 1].set(-2.0)
+            R = xp.asarray(R)
+            xp_assert_equal(is_valid_im(R), False, check_namespace=False)
+            with pytest.raises(ValueError):
+                eager.is_valid_im(R, throw=True)
+
+    def test_is_valid_im_4_and_up_neg_dist(self, xp):
+        # Tests is_valid_im(R) on im on observation sets between sizes 4 and 15
+        # (step size 3) with negative link counts.
+        for i in range(4, 15, 3):
+            y = np.random.rand(i*(i-1)//2)
+            Z = linkage(y)
+            R = inconsistent(Z)
+            R = xpx.at(R)[i//2, 2].set(-0.5)
+            R = xp.asarray(R)
+            xp_assert_equal(is_valid_im(R), False, check_namespace=False)
+            with pytest.raises(ValueError):
+                eager.is_valid_im(R, throw=True)
+
+
+@make_xp_test_case(num_obs_linkage)
+class TestNumObsLinkage:
+
+    def test_num_obs_linkage_empty(self, xp):
+        # Tests num_obs_linkage(Z) with empty linkage.
+        Z = xp.zeros((0, 4), dtype=xp.float64)
+        assert_raises(ValueError, num_obs_linkage, Z)
+
+    def test_num_obs_linkage_1x4(self, xp):
+        # Tests num_obs_linkage(Z) on linkage over 2 observations.
+        Z = xp.asarray([[0, 1, 3.0, 2]], dtype=xp.float64)
+        assert num_obs_linkage(Z) == 2
+
+    def test_num_obs_linkage_2x4(self, xp):
+        # Tests num_obs_linkage(Z) on linkage over 3 observations.
+        Z = xp.asarray([[0, 1, 3.0, 2],
+                        [3, 2, 4.0, 3]], dtype=xp.float64)
+        assert num_obs_linkage(Z) == 3
+
+    def test_num_obs_linkage_4_and_up(self, xp):
+        # Tests num_obs_linkage(Z) on linkage on observation sets between sizes
+        # 4 and 15 (step size 3).
+        for i in range(4, 15, 3):
+            y = np.random.rand(i*(i-1)//2)
+            Z = xp.asarray(linkage(y))
+            assert num_obs_linkage(Z) == i
+
+    def test_num_obs_linkage_multi_matrix(self, xp):
+        # Tests num_obs_linkage with observation matrices of multiple sizes.
+        for n in range(2, 10):
+            X = np.random.rand(n, 4)
+            Y = pdist(X)
+            Z = xp.asarray(linkage(Y))
+            assert num_obs_linkage(Z) == n
+
+
+@make_xp_test_case(leaves_list, to_tree)
+class TestLeavesList:
+
+    def test_leaves_list_1x4(self, xp):
+        # Tests leaves_list(Z) on a 1x4 linkage.
+        Z = xp.asarray([[0, 1, 3.0, 2]], dtype=xp.float64)
+        to_tree(Z)
+        assert_allclose(leaves_list(Z), [0, 1], rtol=1e-15)
+
+    def test_leaves_list_2x4(self, xp):
+        # Tests leaves_list(Z) on a 2x4 linkage.
+        Z = xp.asarray([[0, 1, 3.0, 2],
+                        [3, 2, 4.0, 3]], dtype=xp.float64)
+        to_tree(Z)
+        assert_allclose(leaves_list(Z), [0, 1, 2], rtol=1e-15)
+
+    @pytest.mark.parametrize("method",
+        ['single', 'complete', 'average', 'weighted', 'centroid', 'median', 'ward'])
+    def test_leaves_list_Q(self, method, xp):
+        # Tests leaves_list(Z) on the Q data set
+        X = hierarchy_test_data.Q_X
+        Z = xp.asarray(linkage(X, method))
+        node = to_tree(Z)
+        assert_allclose(node.pre_order(), leaves_list(Z), rtol=1e-15)
+
+    def test_Q_subtree_pre_order(self, xp):
+        # Tests that pre_order() works when called on sub-trees.
+        X = hierarchy_test_data.Q_X
+        Z = xp.asarray(linkage(X, 'single'))
+        node = to_tree(Z)
+        assert_allclose(node.pre_order(),
+                        (node.get_left().pre_order() + node.get_right().pre_order()),
+                        rtol=1e-15)
+
+
+@make_xp_test_case(correspond)
+class TestCorrespond:
+
+    def test_correspond_empty(self, xp):
+        # Tests correspond(Z, y) with empty linkage and condensed distance matrix.
+        y = xp.zeros((0,), dtype=xp.float64)
+        Z = xp.zeros((0,4), dtype=xp.float64)
+        assert_raises(ValueError, correspond, Z, y)
+
+    def test_correspond_2_and_up(self, xp):
+        # Tests correspond(Z, y) on linkage and CDMs over observation sets of
+        # different sizes.
+        for i in range(2, 4):
+            y = np.random.rand(i*(i-1)//2)
+            Z = xp.asarray(linkage(y))
+            y = xp.asarray(y)
+            assert_(correspond(Z, y))
+        for i in range(4, 15, 3):
+            y = np.random.rand(i*(i-1)//2)
+            Z = xp.asarray(linkage(y))
+            y = xp.asarray(y)
+            assert_(correspond(Z, y))
+
+    def test_correspond_4_and_up(self, xp):
+        # Tests correspond(Z, y) on linkage and CDMs over observation sets of
+        # different sizes. Correspondence should be false.
+        for (i, j) in (list(zip(list(range(2, 4)), list(range(3, 5)))) +
+                       list(zip(list(range(3, 5)), list(range(2, 4))))):
+            y = np.random.rand(i*(i-1)//2)
+            y2 = np.random.rand(j*(j-1)//2)
+            Z = xp.asarray(linkage(y))
+            Z2 = xp.asarray(linkage(y2))
+            y = xp.asarray(y)
+            y2 = xp.asarray(y2)
+            assert not correspond(Z, y2)
+            assert not correspond(Z2, y)
+
+    def test_correspond_4_and_up_2(self, xp):
+        # Tests correspond(Z, y) on linkage and CDMs over observation sets of
+        # different sizes. Correspondence should be false.
+        for (i, j) in (list(zip(list(range(2, 7)), list(range(16, 21)))) +
+                       list(zip(list(range(2, 7)), list(range(16, 21))))):
+            y = np.random.rand(i*(i-1)//2)
+            y2 = np.random.rand(j*(j-1)//2)
+            Z = xp.asarray(linkage(y))
+            Z2 = xp.asarray(linkage(y2))
+            y = xp.asarray(y)
+            y2 = xp.asarray(y2)
+            assert not correspond(Z, y2)
+            assert not correspond(Z2, y)
+
+
+@make_xp_test_case(is_monotonic)
+class TestIsMonotonic:
+
+    def test_is_monotonic_empty(self, xp):
+        # Tests is_monotonic(Z) on an empty linkage.
+        Z = xp.zeros((0, 4), dtype=xp.float64)
+        assert_raises(ValueError, is_monotonic, Z)
+
+    def test_is_monotonic_1x4(self, xp):
+        # Tests is_monotonic(Z) on 1x4 linkage. Expecting True.
+        Z = xp.asarray([[0, 1, 0.3, 2]], dtype=xp.float64)
+        assert is_monotonic(Z)
+
+    def test_is_monotonic_2x4_T(self, xp):
+        # Tests is_monotonic(Z) on 2x4 linkage. Expecting True.
+        Z = xp.asarray([[0, 1, 0.3, 2],
+                        [2, 3, 0.4, 3]], dtype=xp.float64)
+        assert is_monotonic(Z)
+
+    def test_is_monotonic_2x4_F(self, xp):
+        # Tests is_monotonic(Z) on 2x4 linkage. Expecting False.
+        Z = xp.asarray([[0, 1, 0.4, 2],
+                        [2, 3, 0.3, 3]], dtype=xp.float64)
+        assert not is_monotonic(Z)
+
+    def test_is_monotonic_3x4_T(self, xp):
+        # Tests is_monotonic(Z) on 3x4 linkage. Expecting True.
+        Z = xp.asarray([[0, 1, 0.3, 2],
+                        [2, 3, 0.4, 2],
+                        [4, 5, 0.6, 4]], dtype=xp.float64)
+        assert is_monotonic(Z)
+
+    def test_is_monotonic_3x4_F1(self, xp):
+        # Tests is_monotonic(Z) on 3x4 linkage (case 1). Expecting False.
+        Z = xp.asarray([[0, 1, 0.3, 2],
+                        [2, 3, 0.2, 2],
+                        [4, 5, 0.6, 4]], dtype=xp.float64)
+        assert not is_monotonic(Z)
+
+    def test_is_monotonic_3x4_F2(self, xp):
+        # Tests is_monotonic(Z) on 3x4 linkage (case 2). Expecting False.
+        Z = xp.asarray([[0, 1, 0.8, 2],
+                        [2, 3, 0.4, 2],
+                        [4, 5, 0.6, 4]], dtype=xp.float64)
+        assert not is_monotonic(Z)
+
+    def test_is_monotonic_3x4_F3(self, xp):
+        # Tests is_monotonic(Z) on 3x4 linkage (case 3). Expecting False
+        Z = xp.asarray([[0, 1, 0.3, 2],
+                        [2, 3, 0.4, 2],
+                        [4, 5, 0.2, 4]], dtype=xp.float64)
+        assert not is_monotonic(Z)
+
+    def test_is_monotonic_tdist_linkage1(self, xp):
+        # Tests is_monotonic(Z) on clustering generated by single linkage on
+        # tdist data set. Expecting True.
+        Z = xp.asarray(linkage(hierarchy_test_data.ytdist, 'single'))
+        assert is_monotonic(Z)
+
+    def test_is_monotonic_tdist_linkage2(self, xp):
+        # Tests is_monotonic(Z) on clustering generated by single linkage on
+        # tdist data set. Perturbing. Expecting False.
+        Z = xp.asarray(linkage(hierarchy_test_data.ytdist, 'single'))
+        Z = xpx.at(Z)[2, 2].set(0.0)
+        assert not is_monotonic(Z)
+
+    def test_is_monotonic_Q_linkage(self, xp):
+        # Tests is_monotonic(Z) on clustering generated by single linkage on
+        # Q data set. Expecting True.
+        X = hierarchy_test_data.Q_X
+        Z = xp.asarray(linkage(X, 'single'))
+        assert is_monotonic(Z)
+
+
+@make_xp_test_case(maxdists)
+class TestMaxDists:
+
+    def test_maxdists_empty_linkage(self, xp):
+        # Tests maxdists(Z) on empty linkage. Expecting exception.
+        Z = xp.zeros((0, 4), dtype=xp.float64)
+        assert_raises(ValueError, maxdists, Z)
+
+    def test_maxdists_one_cluster_linkage(self, xp):
+        # Tests maxdists(Z) on linkage with one cluster.
+        Z = xp.asarray([[0, 1, 0.3, 4]], dtype=xp.float64)
+        MD = maxdists(Z)
+        expectedMD = calculate_maximum_distances(Z, xp)
+        xp_assert_close(MD, expectedMD, atol=1e-15)
+
+    @pytest.mark.parametrize(
+        "method", ['single', 'complete', 'ward', 'centroid', 'median'])
+    def test_maxdists_Q_linkage(self, method, xp):
+        # Tests maxdists(Z) on the Q data set
+        X = hierarchy_test_data.Q_X
+        Z = xp.asarray(linkage(X, method))
+        MD = maxdists(Z)
+        expectedMD = calculate_maximum_distances(Z, xp)
+        xp_assert_close(MD, expectedMD, atol=1e-15)
+
+
+@make_xp_test_case(maxinconsts)
+class TestMaxInconsts:
+
+    def test_maxinconsts_empty_linkage(self, xp):
+        # Tests maxinconsts(Z, R) on empty linkage. Expecting exception.
+        Z = xp.zeros((0, 4), dtype=xp.float64)
+        R = xp.zeros((0, 4), dtype=xp.float64)
+        assert_raises(ValueError, maxinconsts, Z, R)
+
+    def test_maxinconsts_difrow_linkage(self, xp):
+        # Tests maxinconsts(Z, R) on linkage and inconsistency matrices with
+        # different numbers of clusters. Expecting exception.
+        Z = xp.asarray([[0, 1, 0.3, 4]], dtype=xp.float64)
+        R = np.random.rand(2, 4)
+        R = xp.asarray(R)
+        assert_raises(ValueError, maxinconsts, Z, R)
+
+    def test_maxinconsts_one_cluster_linkage(self, xp):
+        # Tests maxinconsts(Z, R) on linkage with one cluster.
+        Z = xp.asarray([[0, 1, 0.3, 4]], dtype=xp.float64)
+        R = xp.asarray([[0, 0, 0, 0.3]], dtype=xp.float64)
+        MD = maxinconsts(Z, R)
+        expectedMD = calculate_maximum_inconsistencies(Z, R, xp=xp)
+        xp_assert_close(MD, expectedMD, atol=1e-15)
+
+    @pytest.mark.parametrize(
+        "method", ['single', 'complete', 'ward', 'centroid', 'median'])
+    def test_maxinconsts_Q_linkage(self, method, xp):
+        # Tests maxinconsts(Z, R) on the Q data set
+        X = hierarchy_test_data.Q_X
+        Z = linkage(X, method)
+        R = xp.asarray(inconsistent(Z))
+        Z = xp.asarray(Z)
+        MD = maxinconsts(Z, R)
+        expectedMD = calculate_maximum_inconsistencies(Z, R, xp=xp)
+        xp_assert_close(MD, expectedMD, atol=1e-15)
+
+
+@make_xp_test_case(maxRstat)
+class TestMaxRStat:
+
+    def test_maxRstat_invalid_index(self, xp):
+        # Tests maxRstat(Z, R, i). Expecting exception.
+        Z = xp.asarray([[0, 1, 0.3, 4]], dtype=xp.float64)
+        R = xp.asarray([[0, 0, 0, 0.3]], dtype=xp.float64)
+        with pytest.raises(TypeError):
+            maxRstat(Z, R, 3.3)
+        with pytest.raises(ValueError):
+            maxRstat(Z, R, -1)
+        with pytest.raises(ValueError):
+            maxRstat(Z, R, 4)
+
+    @pytest.mark.parametrize("i", range(4))
+    def test_maxRstat_empty_linkage(self, i, xp):
+        # Tests maxRstat(Z, R, i) on empty linkage. Expecting exception.
+        Z = xp.zeros((0, 4), dtype=xp.float64)
+        R = xp.zeros((0, 4), dtype=xp.float64)
+        assert_raises(ValueError, maxRstat, Z, R, i)
+
+    @pytest.mark.parametrize("i", range(4))
+    def test_maxRstat_difrow_linkage(self, i, xp):
+        # Tests maxRstat(Z, R, i) on linkage and inconsistency matrices with
+        # different numbers of clusters. Expecting exception.
+        Z = xp.asarray([[0, 1, 0.3, 4]], dtype=xp.float64)
+        R = np.random.rand(2, 4)
+        R = xp.asarray(R)
+        assert_raises(ValueError, maxRstat, Z, R, i)
+
+    def test_maxRstat_one_cluster_linkage(self, xp):
+        # Tests maxRstat(Z, R, i) on linkage with one cluster.
+        Z = xp.asarray([[0, 1, 0.3, 4]], dtype=xp.float64)
+        R = xp.asarray([[0, 0, 0, 0.3]], dtype=xp.float64)
+        MD = maxRstat(Z, R, 1)
+        expectedMD = calculate_maximum_inconsistencies(Z, R, 1, xp)
+        xp_assert_close(MD, expectedMD, atol=1e-15)
+
+    @pytest.mark.parametrize(
+        "method", ['single', 'complete', 'ward', 'centroid', 'median'])
+    def test_maxRstat_Q_linkage(self, method, xp):
+        # Tests maxRstat(Z, R, 1) on the Q data set
+        X = hierarchy_test_data.Q_X
+        Z = linkage(X, method)
+        R = xp.asarray(inconsistent(Z))
+        Z = xp.asarray(Z)
+        MD = maxRstat(Z, R, 1)
+        expectedMD = calculate_maximum_inconsistencies(Z, R, 1, xp)
+        xp_assert_close(MD, expectedMD, atol=1e-15)
+
+
+@make_xp_test_case(dendrogram)
+class TestDendrogram:
+
+    def test_dendrogram_single_linkage_tdist(self, xp):
+        # Tests dendrogram calculation on single linkage of the tdist data set.
+        Z = xp.asarray(linkage(hierarchy_test_data.ytdist, 'single'))
+        R = dendrogram(Z, no_plot=True)
+        leaves = R["leaves"]
+        assert_equal(leaves, [2, 5, 1, 0, 3, 4])
+
+    def test_valid_orientation(self, xp):
+        Z = xp.asarray(linkage(hierarchy_test_data.ytdist, 'single'))
+        assert_raises(ValueError, dendrogram, Z, orientation="foo")
+
+    def test_labels_as_array_or_list(self, xp):
+        # test for gh-12418
+        Z = xp.asarray(linkage(hierarchy_test_data.ytdist, 'single'))
+        labels = [1, 3, 2, 6, 4, 5]
+        result1 = dendrogram(Z, labels=xp.asarray(labels), no_plot=True)
+        result2 = dendrogram(Z, labels=labels, no_plot=True)
+        assert result1 == result2
+
+    @pytest.mark.skipif(not have_matplotlib, reason="no matplotlib")
+    def test_valid_label_size(self, xp):
+        link = xp.asarray([
+            [0, 1, 1.0, 4],
+            [2, 3, 1.0, 5],
+            [4, 5, 2.0, 6],
+        ])
+        plt.figure()
+        with pytest.raises(ValueError) as exc_info:
+            dendrogram(link, labels=list(range(100)))
+        assert "Dimensions of Z and labels must be consistent."\
+               in str(exc_info.value)
+
+        with pytest.raises(
+                ValueError,
+                match="Dimensions of Z and labels must be consistent."):
+            dendrogram(link, labels=[])
+
+        plt.close()
+
+    @skip_xp_backends('torch',
+         reason='MPL 3.9.2 & torch DeprecationWarning from __array_wrap__'
+                ' and NumPy 2.0'
+    )
+    @skip_xp_backends('dask.array',
+         reason='dask.array has bad interaction with matplotlib'
+    )
+    @pytest.mark.skipif(not have_matplotlib, reason="no matplotlib")
+    @pytest.mark.parametrize("orientation", ['top', 'bottom', 'left', 'right'])
+    def test_dendrogram_plot(self, orientation, xp):
+        # Tests dendrogram plotting.
+        Z = xp.asarray(linkage(hierarchy_test_data.ytdist, 'single'))
+        expected = {'color_list': ['C1', 'C0', 'C0', 'C0', 'C0'],
+                    'dcoord': [[0.0, 138.0, 138.0, 0.0],
+                               [0.0, 219.0, 219.0, 0.0],
+                               [0.0, 255.0, 255.0, 219.0],
+                               [0.0, 268.0, 268.0, 255.0],
+                               [138.0, 295.0, 295.0, 268.0]],
+                    'icoord': [[5.0, 5.0, 15.0, 15.0],
+                               [45.0, 45.0, 55.0, 55.0],
+                               [35.0, 35.0, 50.0, 50.0],
+                               [25.0, 25.0, 42.5, 42.5],
+                               [10.0, 10.0, 33.75, 33.75]],
+                    'ivl': ['2', '5', '1', '0', '3', '4'],
+                    'leaves': [2, 5, 1, 0, 3, 4],
+                    'leaves_color_list': ['C1', 'C1', 'C0', 'C0', 'C0', 'C0'],
+                    }
+
+        fig = plt.figure()
+        ax = fig.add_subplot(221)
+
+        # test that dendrogram accepts ax keyword
+        R1 = dendrogram(Z, ax=ax, orientation=orientation)
+        R1['dcoord'] = np.asarray(R1['dcoord'])
+        assert_equal(R1, expected)
+
+        # test that dendrogram accepts and handle the leaf_font_size and
+        # leaf_rotation keywords
+        dendrogram(Z, ax=ax, orientation=orientation,
+                   leaf_font_size=20, leaf_rotation=90)
+        testlabel = (
+            ax.get_xticklabels()[0]
+            if orientation in ['top', 'bottom']
+            else ax.get_yticklabels()[0]
+        )
+        assert_equal(testlabel.get_rotation(), 90)
+        assert_equal(testlabel.get_size(), 20)
+        dendrogram(Z, ax=ax, orientation=orientation,
+                   leaf_rotation=90)
+        testlabel = (
+            ax.get_xticklabels()[0]
+            if orientation in ['top', 'bottom']
+            else ax.get_yticklabels()[0]
+        )
+        assert_equal(testlabel.get_rotation(), 90)
+        dendrogram(Z, ax=ax, orientation=orientation,
+                   leaf_font_size=20)
+        testlabel = (
+            ax.get_xticklabels()[0]
+            if orientation in ['top', 'bottom']
+            else ax.get_yticklabels()[0]
+        )
+        assert_equal(testlabel.get_size(), 20)
+        plt.close()
+
+        # test plotting to gca (will import pylab)
+        R2 = dendrogram(Z, orientation=orientation)
+        plt.close()
+        R2['dcoord'] = np.asarray(R2['dcoord'])
+        assert_equal(R2, expected)
+
+    @skip_xp_backends('torch',
+          reason='MPL 3.9.2 & torch DeprecationWarning from __array_wrap__'
+                 ' and NumPy 2.0'
+     )
+    @skip_xp_backends('dask.array',
+         reason='dask.array has bad interaction with matplotlib'
+    )
+    @pytest.mark.skipif(not have_matplotlib, reason="no matplotlib")
+    def test_dendrogram_truncate_mode(self, xp):
+        Z = xp.asarray(linkage(hierarchy_test_data.ytdist, 'single'))
+
+        R = dendrogram(Z, 2, 'lastp', show_contracted=True)
+        plt.close()
+        R['dcoord'] = np.asarray(R['dcoord'])
+        assert_equal(R, {'color_list': ['C0'],
+                         'dcoord': [[0.0, 295.0, 295.0, 0.0]],
+                         'icoord': [[5.0, 5.0, 15.0, 15.0]],
+                         'ivl': ['(2)', '(4)'],
+                         'leaves': [6, 9],
+                         'leaves_color_list': ['C0', 'C0'],
+                         })
+
+        R = dendrogram(Z, 2, 'mtica', show_contracted=True)
+        plt.close()
+        R['dcoord'] = np.asarray(R['dcoord'])
+        assert_equal(R, {'color_list': ['C1', 'C0', 'C0', 'C0'],
+                         'dcoord': [[0.0, 138.0, 138.0, 0.0],
+                                    [0.0, 255.0, 255.0, 0.0],
+                                    [0.0, 268.0, 268.0, 255.0],
+                                    [138.0, 295.0, 295.0, 268.0]],
+                         'icoord': [[5.0, 5.0, 15.0, 15.0],
+                                    [35.0, 35.0, 45.0, 45.0],
+                                    [25.0, 25.0, 40.0, 40.0],
+                                    [10.0, 10.0, 32.5, 32.5]],
+                         'ivl': ['2', '5', '1', '0', '(2)'],
+                         'leaves': [2, 5, 1, 0, 7],
+                         'leaves_color_list': ['C1', 'C1', 'C0', 'C0', 'C0'],
+                         })
+
+    @pytest.fixture
+    def dendrogram_lock(self):
+        return Lock()
+
+    def test_dendrogram_colors(self, xp, dendrogram_lock):
+        # Tests dendrogram plots with alternate colors
+        Z = xp.asarray(linkage(hierarchy_test_data.ytdist, 'single'))
+
+        with dendrogram_lock:
+            # Global color palette might be changed concurrently
+            set_link_color_palette(['c', 'm', 'y', 'k'])
+            R = dendrogram(Z, no_plot=True,
+                           above_threshold_color='g', color_threshold=250)
+            set_link_color_palette(['g', 'r', 'c', 'm', 'y', 'k'])
+
+            color_list = R['color_list']
+            assert_equal(color_list, ['c', 'm', 'g', 'g', 'g'])
+
+            # reset color palette (global list)
+            set_link_color_palette(None)
+
+    def test_dendrogram_leaf_colors_zero_dist(self, xp):
+        # tests that the colors of leafs are correct for tree
+        # with two identical points
+        X = np.asarray([[1, 0, 0],
+                        [0, 0, 1],
+                        [0, 2, 0],
+                        [0, 0, 1],
+                        [0, 1, 0],
+                        [0, 1, 0]])
+        Z = xp.asarray(linkage(X, "single"))
+        d = dendrogram(Z, no_plot=True)
+        exp_colors = ['C0', 'C1', 'C1', 'C0', 'C2', 'C2']
+        colors = d["leaves_color_list"]
+        assert_equal(colors, exp_colors)
+
+    def test_dendrogram_leaf_colors(self, xp):
+        # tests that the colors are correct for a tree
+        # with two near points ((0, 0, 1.1) and (0, 0, 1))
+        X = np.asarray([[1, 0, 0],
+                        [0, 0, 1.1],
+                        [0, 2, 0],
+                        [0, 0, 1],
+                        [0, 1, 0],
+                        [0, 1, 0]])
+        Z = xp.asarray(linkage(X, "single"))
+        d = dendrogram(Z, no_plot=True)
+        exp_colors = ['C0', 'C1', 'C1', 'C0', 'C2', 'C2']
+        colors = d["leaves_color_list"]
+        assert_equal(colors, exp_colors)
+
+
+def calculate_maximum_distances(Z, xp):
+    # Used for testing correctness of maxdists.
+    n = Z.shape[0] + 1
+    B = xp.zeros((n-1,), dtype=Z.dtype)
+    for i in range(0, n - 1):
+        q = xp.zeros((3,))
+        left = Z[i, 0]
+        right = Z[i, 1]
+        if left >= n:
+            b_left = B[xp.asarray(left, dtype=xp.int64) - n]
+            q = xpx.at(q, 0).set(b_left)
+        if right >= n:
+            b_right = B[xp.asarray(right, dtype=xp.int64) - n]
+            q = xpx.at(q, 1).set(b_right)
+        q = xpx.at(q, 2).set(Z[i, 2])
+        B = xpx.at(B, i).set(xp.max(q))
+    return B
+
+
+def calculate_maximum_inconsistencies(Z, R, k=3, xp=np):
+    # Used for testing correctness of maxinconsts.
+    n = Z.shape[0] + 1
+    dtype = xp.result_type(Z, R)
+    B = xp.zeros((n-1,), dtype=dtype)
+    for i in range(0, n - 1):
+        q = xp.zeros((3,))
+        left = Z[i, 0]
+        right = Z[i, 1]
+        if left >= n:
+            b_left = B[xp.asarray(left, dtype=xp.int64) - n]
+            q = xpx.at(q, 0).set(b_left)
+        if right >= n:
+            b_right = B[xp.asarray(right, dtype=xp.int64) - n]
+            q = xpx.at(q, 1).set(b_right)
+        q = xpx.at(q, 2).set(R[i, k])
+        B = xpx.at(B, i).set(xp.max(q))
+    return B
+
+
+@make_xp_test_case(to_tree)
+def test_node_compare(xp):
+    np.random.seed(23)
+    nobs = 50
+    X = np.random.randn(nobs, 4)
+    Z = xp.asarray(ward(X))
+    tree = to_tree(Z)
+    assert_(tree > tree.get_left())
+    assert_(tree.get_right() > tree.get_left())
+    assert_(tree.get_right() == tree.get_right())
+    assert_(tree.get_right() != tree.get_left())
+
+
+@make_xp_test_case(cut_tree)
+def test_cut_tree(xp):
+    np.random.seed(23)
+    nobs = 50
+    X = np.random.randn(nobs, 4)
+    Z = xp.asarray(ward(X))
+    cutree = cut_tree(Z)
+
+    # cutree.dtype varies between int32 and int64 over platforms
+    xp_assert_close(cutree[:, 0], xp.arange(nobs), rtol=1e-15, check_dtype=False)
+    xp_assert_close(cutree[:, -1], xp.zeros(nobs), rtol=1e-15, check_dtype=False)
+    assert_equal(np.asarray(cutree).max(0), np.arange(nobs - 1, -1, -1))
+
+    xp_assert_close(cutree[:, [-5]], cut_tree(Z, n_clusters=5), rtol=1e-15)
+    xp_assert_close(cutree[:, [-5, -10]], cut_tree(Z, n_clusters=[5, 10]), rtol=1e-15)
+    xp_assert_close(cutree[:, [-10, -5]], cut_tree(Z, n_clusters=[10, 5]), rtol=1e-15)
+
+    nodes = _order_cluster_tree(Z)
+    heights = xp.asarray([node.dist for node in nodes])
+
+    xp_assert_close(cutree[:, np.searchsorted(heights, [5])],
+                    cut_tree(Z, height=5), rtol=1e-15)
+    xp_assert_close(cutree[:, np.searchsorted(heights, [5, 10])],
+                    cut_tree(Z, height=[5, 10]), rtol=1e-15)
+    xp_assert_close(cutree[:, np.searchsorted(heights, [10, 5])],
+                    cut_tree(Z, height=[10, 5]), rtol=1e-15)
+
+
+@make_xp_test_case(optimal_leaf_ordering)
+def test_optimal_leaf_ordering(xp):
+    # test with the distance vector y
+    Z = optimal_leaf_ordering(xp.asarray(linkage(hierarchy_test_data.ytdist)),
+                              xp.asarray(hierarchy_test_data.ytdist))
+    expectedZ = hierarchy_test_data.linkage_ytdist_single_olo
+    xp_assert_close(Z, xp.asarray(expectedZ), atol=1e-10)
+
+    # test with the observation matrix X
+    Z = optimal_leaf_ordering(xp.asarray(linkage(hierarchy_test_data.X, 'ward')),
+                              xp.asarray(hierarchy_test_data.X))
+    expectedZ = hierarchy_test_data.linkage_X_ward_olo
+    xp_assert_close(Z, xp.asarray(expectedZ), atol=1e-06)
+
+
+def test_Heap():  # `Heap` only supports NumPy backend
+    values = np.asarray([2, -1, 0, -1.5, 3])
+    heap = Heap(values)
+
+    pair = heap.get_min()
+    assert_equal(pair['key'], 3)
+    assert_equal(pair['value'], -1.5)
+
+    heap.remove_min()
+    pair = heap.get_min()
+    assert_equal(pair['key'], 1)
+    assert_equal(pair['value'], -1)
+
+    heap.change_value(1, 2.5)
+    pair = heap.get_min()
+    assert_equal(pair['key'], 2)
+    assert_equal(pair['value'], 0)
+
+    heap.remove_min()
+    heap.remove_min()
+
+    heap.change_value(1, 10)
+    pair = heap.get_min()
+    assert_equal(pair['key'], 4)
+    assert_equal(pair['value'], 3)
+
+    heap.remove_min()
+    pair = heap.get_min()
+    assert_equal(pair['key'], 1)
+    assert_equal(pair['value'], 10)
diff --git a/.venv/lib/python3.12/site-packages/scipy/cluster/vq/__init__.py b/.venv/lib/python3.12/site-packages/scipy/cluster/vq/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..919ee6097a2e05e19d8167af57f761c7c9b1cf59
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/cluster/vq/__init__.py
@@ -0,0 +1,84 @@
+"""
+K-means clustering and vector quantization (:mod:`scipy.cluster.vq`)
+====================================================================
+
+Provides routines for k-means clustering, generating code books
+from k-means models and quantizing vectors by comparing them with
+centroids in a code book.
+
+.. autosummary::
+   :toctree: generated/
+
+   whiten -- Normalize a group of observations so each feature has unit variance
+   vq -- Calculate code book membership of a set of observation vectors
+   kmeans -- Perform k-means on a set of observation vectors forming k clusters
+   kmeans2 -- A different implementation of k-means with more methods
+           -- for initializing centroids
+
+Exceptions:
+
+.. autosummary::
+   :toctree: generated/
+
+   ClusterError
+
+Background information
+----------------------
+The k-means algorithm takes as input the number of clusters to
+generate, k, and a set of observation vectors to cluster. It
+returns a set of centroids, one for each of the k clusters. An
+observation vector is classified with the cluster number or
+centroid index of the centroid closest to it.
+
+A vector v belongs to cluster i if it is closer to centroid i than
+any other centroid. If v belongs to i, we say centroid i is the
+dominating centroid of v. The k-means algorithm tries to
+minimize distortion, which is defined as the sum of the squared distances
+between each observation vector and its dominating centroid.
+The minimization is achieved by iteratively reclassifying
+the observations into clusters and recalculating the centroids until
+a configuration is reached in which the centroids are stable. One can
+also define a maximum number of iterations.
+
+Since vector quantization is a natural application for k-means,
+information theory terminology is often used. The centroid index
+or cluster index is also referred to as a "code" and the table
+mapping codes to centroids and, vice versa, is often referred to as a
+"code book". The result of k-means, a set of centroids, can be
+used to quantize vectors. Quantization aims to find an encoding of
+vectors that reduces the expected distortion.
+
+All routines expect obs to be an M by N array, where the rows are
+the observation vectors. The codebook is a k by N array, where the
+ith row is the centroid of code word i. The observation vectors
+and centroids have the same feature dimension.
+
+As an example, suppose we wish to compress a 24-bit color image
+(each pixel is represented by one byte for red, one for blue, and
+one for green) before sending it over the web. By using a smaller
+8-bit encoding, we can reduce the amount of data by two
+thirds. Ideally, the colors for each of the 256 possible 8-bit
+encoding values should be chosen to minimize distortion of the
+color. Running k-means with k=256 generates a code book of 256
+codes, which fills up all possible 8-bit sequences. Instead of
+sending a 3-byte value for each pixel, the 8-bit centroid index
+(or code word) of the dominating centroid is transmitted. The code
+book is also sent over the wire so each 8-bit code can be
+translated back to a 24-bit pixel value representation. If the
+image of interest was of an ocean, we would expect many 24-bit
+blues to be represented by 8-bit codes. If it was an image of a
+human face, more flesh-tone colors would be represented in the
+code book.
+
+"""
+from ._vq_impl import ClusterError, kmeans, kmeans2, vq, whiten
+from ._vq_impl import py_vq
+
+__all__ = ["ClusterError", "kmeans", "kmeans2", "vq", "whiten"]
+
+# deprecated attributes
+__all__ += ["py_vq"]
+
+
+def __dir__(): 
+    return __all__ 
diff --git a/.venv/lib/python3.12/site-packages/scipy/cluster/vq/_vq.cpython-312-x86_64-linux-gnu.so b/.venv/lib/python3.12/site-packages/scipy/cluster/vq/_vq.cpython-312-x86_64-linux-gnu.so
new file mode 100644
index 0000000000000000000000000000000000000000..d86c11bc2520698a7aca10981ac7e2a9c46792b0
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/cluster/vq/_vq.cpython-312-x86_64-linux-gnu.so
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:758e46021be3085f56e24ec72d8cea2bdb7ca688144f59038a6dfd91b189c4bb
+size 123064
diff --git a/.venv/lib/python3.12/site-packages/scipy/cluster/vq/_vq_impl.py b/.venv/lib/python3.12/site-packages/scipy/cluster/vq/_vq_impl.py
new file mode 100644
index 0000000000000000000000000000000000000000..d22112dbdb656d771df5cb89a5a561537a386373
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/cluster/vq/_vq_impl.py
@@ -0,0 +1,777 @@
+import warnings
+import numpy as np
+from collections import deque
+from scipy._lib._array_api import (_asarray, array_namespace, is_lazy_array,
+                                   xp_capabilities, xp_copy, xp_size)
+from scipy._lib._util import (check_random_state, rng_integers,
+                              _transition_to_rng)
+from scipy._lib.deprecation import _deprecated
+from scipy._external import array_api_extra as xpx
+from scipy.spatial.distance import cdist
+
+from . import _vq  # type:ignore[attr-defined]
+
+__all__ = ['ClusterError', 'kmeans', 'kmeans2', 'py_vq', 'vq', 'whiten']
+
+
+class ClusterError(Exception):
+    """
+    An ``Exception`` raised during clustering.
+    """
+    pass
+
+
+@xp_capabilities()
+def whiten(obs, check_finite=None):
+    """
+    Normalize a group of observations on a per feature basis.
+
+    Before running k-means, it is beneficial to rescale each feature
+    dimension of the observation set by its standard deviation (i.e. "whiten"
+    it - as in "white noise" where each frequency has equal power).
+    Each feature is divided by its standard deviation across all observations
+    to give it unit variance.
+
+    Parameters
+    ----------
+    obs : ndarray
+        Each row of the array is an observation.  The
+        columns are the features seen during each observation::
+
+            #        f0  f1  f2
+            obs = [[ 1., 1., 1.],  #o0
+                   [ 2., 2., 2.],  #o1
+                   [ 3., 3., 3.],  #o2
+                   [ 4., 4., 4.]]  #o3
+
+    check_finite : bool, optional
+        Whether to check that the input matrices contain only finite numbers.
+        Disabling may give a performance gain, but may result in problems
+        (crashes, non-termination) if the inputs do contain infinities or NaNs.
+        Default: True for eager backends and False for lazy ones.
+
+    Returns
+    -------
+    result : ndarray
+        Contains the values in `obs` scaled by the standard deviation
+        of each column.
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy.cluster.vq import whiten
+    >>> features  = np.array([[1.9, 2.3, 1.7],
+    ...                       [1.5, 2.5, 2.2],
+    ...                       [0.8, 0.6, 1.7,]])
+    >>> whiten(features)
+    array([[ 4.17944278,  2.69811351,  7.21248917],
+           [ 3.29956009,  2.93273208,  9.33380951],
+           [ 1.75976538,  0.7038557 ,  7.21248917]])
+
+    """
+    xp = array_namespace(obs)
+    if check_finite is None:
+        check_finite = not is_lazy_array(obs)
+    obs = _asarray(obs, check_finite=check_finite, xp=xp)
+    std_dev = xp.std(obs, axis=0)
+    zero_std_mask = std_dev == 0
+    std_dev = xpx.at(std_dev, zero_std_mask).set(1.0)
+    if check_finite and xp.any(zero_std_mask):
+        warnings.warn("Some columns have standard deviation zero. "
+                      "The values of these columns will not change.",
+                      RuntimeWarning, stacklevel=2)
+    return obs / std_dev
+
+
+@xp_capabilities(cpu_only=True, reason="uses spatial.distance.cdist",
+                 jax_jit=False, allow_dask_compute=True)
+def vq(obs, code_book, check_finite=True):
+    """
+    Assign codes from a code book to observations.
+
+    Assigns a code from a code book to each observation. Each
+    observation vector in the 'M' by 'N' `obs` array is compared with the
+    centroids in the code book and assigned the code of the closest
+    centroid.
+
+    The features in `obs` should have unit variance, which can be
+    achieved by passing them through the whiten function. The code
+    book can be created with the k-means algorithm or a different
+    encoding algorithm.
+
+    Parameters
+    ----------
+    obs : ndarray
+        Each row of the 'M' x 'N' array is an observation. The columns are
+        the "features" seen during each observation. The features must be
+        whitened first using the whiten function or something equivalent.
+    code_book : ndarray
+        The code book is usually generated using the k-means algorithm.
+        Each row of the array holds a different code, and the columns are
+        the features of the code::
+
+            #              f0  f1  f2  f3
+            code_book = [[ 1., 2., 3., 4.],  #c0
+                         [ 1., 2., 3., 4.],  #c1
+                         [ 1., 2., 3., 4.]]  #c2
+
+    check_finite : bool, optional
+        Whether to check that the input matrices contain only finite numbers.
+        Disabling may give a performance gain, but may result in problems
+        (crashes, non-termination) if the inputs do contain infinities or NaNs.
+        Default: True
+
+    Returns
+    -------
+    code : ndarray
+        A length M array holding the code book index for each observation.
+    dist : ndarray
+        The distortion (distance) between the observation and its nearest
+        code.
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy.cluster.vq import vq
+    >>> code_book = np.array([[1., 1., 1.],
+    ...                       [2., 2., 2.]])
+    >>> features  = np.array([[1.9, 2.3, 1.7],
+    ...                       [1.5, 2.5, 2.2],
+    ...                       [0.8, 0.6, 1.7]])
+    >>> vq(features, code_book)
+    (array([1, 1, 0], dtype=int32), array([0.43588989, 0.73484692, 0.83066239]))
+
+    """
+    xp = array_namespace(obs, code_book)
+    obs = _asarray(obs, xp=xp, check_finite=check_finite)
+    code_book = _asarray(code_book, xp=xp, check_finite=check_finite)
+    ct = xp.result_type(obs, code_book)
+
+    if xp.isdtype(ct, kind='real floating'):
+        c_obs = xp.astype(obs, ct, copy=False)
+        c_code_book = xp.astype(code_book, ct, copy=False)
+        c_obs = np.asarray(c_obs)
+        c_code_book = np.asarray(c_code_book)
+        result = _vq.vq(c_obs, c_code_book)
+        return xp.asarray(result[0]), xp.asarray(result[1])
+    return _py_vq(obs, code_book, check_finite=False)
+
+
+def _py_vq(obs, code_book, check_finite=True):
+    """ Python version of vq algorithm.
+
+    The algorithm computes the Euclidean distance between each
+    observation and every frame in the code_book.
+
+    Parameters
+    ----------
+    obs : ndarray
+        Expects a rank 2 array. Each row is one observation.
+    code_book : ndarray
+        Code book to use. Same format than obs. Should have same number of
+        features (e.g., columns) than obs.
+    check_finite : bool, optional
+        Whether to check that the input matrices contain only finite numbers.
+        Disabling may give a performance gain, but may result in problems
+        (crashes, non-termination) if the inputs do contain infinities or NaNs.
+        Default: True
+
+    Returns
+    -------
+    code : ndarray
+        code[i] gives the label of the ith obversation; its code is
+        code_book[code[i]].
+    mind_dist : ndarray
+        min_dist[i] gives the distance between the ith observation and its
+        corresponding code.
+
+    Notes
+    -----
+    This function is slower than the C version but works for
+    all input types. If the inputs have the wrong types for the
+    C versions of the function, this one is called as a last resort.
+
+    It is about 20 times slower than the C version.
+
+    """
+    xp = array_namespace(obs, code_book)
+    obs = _asarray(obs, xp=xp, check_finite=check_finite)
+    code_book = _asarray(code_book, xp=xp, check_finite=check_finite)
+
+    if obs.ndim != code_book.ndim:
+        raise ValueError("Observation and code_book should have the same rank")
+
+    if obs.ndim == 1:
+        obs = obs[:, xp.newaxis]
+        code_book = code_book[:, xp.newaxis]
+
+    # Once `cdist` has array API support, this `xp.asarray` call can be removed
+    dist = xp.asarray(cdist(obs, code_book))
+    code = xp.argmin(dist, axis=1)
+    min_dist = xp.min(dist, axis=1)
+    return code, min_dist
+
+
+_py_vq_dep_msg = (
+    "`scipy.cluster.vq.py_vq` was unintentionally public, "
+    "and will be removed in SciPy 1.20.0, use `scipy.cluster.vq.vq` instead."
+)
+py_vq = _deprecated(_py_vq_dep_msg)(_py_vq)
+
+
+def _kmeans(obs, guess, thresh=1e-5, xp=None):
+    """ "raw" version of k-means.
+
+    Returns
+    -------
+    code_book
+        The lowest distortion codebook found.
+    avg_dist
+        The average distance a observation is from a code in the book.
+        Lower means the code_book matches the data better.
+
+    See Also
+    --------
+    kmeans : wrapper around k-means
+
+    Examples
+    --------
+    Note: not whitened in this example.
+
+    >>> import numpy as np
+    >>> from scipy.cluster.vq import _kmeans
+    >>> features  = np.array([[ 1.9,2.3],
+    ...                       [ 1.5,2.5],
+    ...                       [ 0.8,0.6],
+    ...                       [ 0.4,1.8],
+    ...                       [ 1.0,1.0]])
+    >>> book = np.array((features[0],features[2]))
+    >>> _kmeans(features,book)
+    (array([[ 1.7       ,  2.4       ],
+           [ 0.73333333,  1.13333333]]), 0.40563916697728591)
+
+    """
+    xp = np if xp is None else xp
+    code_book = guess
+    diff = xp.inf
+    prev_avg_dists = deque([diff], maxlen=2)
+
+    np_obs = np.asarray(obs)
+    while diff > thresh:
+        # compute membership and distances between obs and code_book
+        obs_code, distort = vq(obs, code_book, check_finite=False)
+        prev_avg_dists.append(xp.mean(distort, axis=-1))
+        # recalc code_book as centroids of associated obs
+        obs_code = np.asarray(obs_code)
+        code_book, has_members = _vq.update_cluster_means(np_obs, obs_code,
+                                                          code_book.shape[0])
+        code_book = code_book[has_members]
+        code_book = xp.asarray(code_book)
+        diff = xp.abs(prev_avg_dists[0] - prev_avg_dists[1])
+
+    _, final_distortions = vq(obs, code_book, check_finite=False)
+    final_distortions_avg = xp.mean(final_distortions, axis=-1)
+    return code_book, final_distortions_avg
+
+
+@xp_capabilities(cpu_only=True, jax_jit=False, allow_dask_compute=True)
+@_transition_to_rng("seed")
+def kmeans(obs, k_or_guess, iter=20, thresh=1e-5, check_finite=True,
+           *, rng=None):
+    """
+    Performs k-means on a set of observation vectors forming k clusters.
+
+    The k-means algorithm adjusts the classification of the observations
+    into clusters and updates the cluster centroids until the position of
+    the centroids is stable over successive iterations. In this
+    implementation of the algorithm, the stability of the centroids is
+    determined by comparing the absolute value of the change in the average
+    Euclidean distance between the observations and their corresponding
+    centroids against a threshold. This yields
+    a code book mapping centroids to codes and vice versa.
+
+    Parameters
+    ----------
+    obs : ndarray
+       Each row of the M by N array is an observation vector. The
+       columns are the features seen during each observation.
+       The features must be whitened first with the `whiten` function.
+
+    k_or_guess : int or ndarray
+       The number of centroids to generate. A code is assigned to
+       each centroid, which is also the row index of the centroid
+       in the code_book matrix generated.
+
+       The initial k centroids are chosen by randomly selecting
+       observations from the observation matrix. Alternatively,
+       passing a k by N array specifies the initial k centroids.
+
+    iter : int, optional
+       The number of times to run k-means, returning the codebook
+       with the lowest distortion. This argument is ignored if
+       initial centroids are specified with an array for the
+       ``k_or_guess`` parameter. This parameter does not represent the
+       number of iterations of the k-means algorithm.
+
+    thresh : float, optional
+       Terminates the k-means algorithm if the change in
+       distortion since the last k-means iteration is less than
+       or equal to threshold.
+
+    check_finite : bool, optional
+        Whether to check that the input matrices contain only finite numbers.
+        Disabling may give a performance gain, but may result in problems
+        (crashes, non-termination) if the inputs do contain infinities or NaNs.
+        Default: True
+    rng : `numpy.random.Generator`, optional
+        Pseudorandom number generator state. When `rng` is None, a new
+        `numpy.random.Generator` is created using entropy from the
+        operating system. Types other than `numpy.random.Generator` are
+        passed to `numpy.random.default_rng` to instantiate a ``Generator``.
+
+    Returns
+    -------
+    codebook : ndarray
+       A k by N array of k centroids. The ith centroid
+       codebook[i] is represented with the code i. The centroids
+       and codes generated represent the lowest distortion seen,
+       not necessarily the globally minimal distortion.
+       Note that the number of centroids is not necessarily the same as the
+       ``k_or_guess`` parameter, because centroids assigned to no observations
+       are removed during iterations.
+
+    distortion : float
+       The mean (non-squared) Euclidean distance between the observations
+       passed and the centroids generated. Note the difference to the standard
+       definition of distortion in the context of the k-means algorithm, which
+       is the sum of the squared distances.
+
+    See Also
+    --------
+    kmeans2 : a different implementation of k-means clustering
+       with more methods for generating initial centroids but without
+       using a distortion change threshold as a stopping criterion.
+
+    whiten : must be called prior to passing an observation matrix
+       to kmeans.
+
+    Notes
+    -----
+    For more functionalities or optimal performance, you can use
+    `sklearn.cluster.KMeans `_.
+    `This `_
+    is a benchmark result of several implementations.
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy.cluster.vq import vq, kmeans, whiten
+    >>> import matplotlib.pyplot as plt
+    >>> features  = np.array([[ 1.9,2.3],
+    ...                       [ 1.5,2.5],
+    ...                       [ 0.8,0.6],
+    ...                       [ 0.4,1.8],
+    ...                       [ 0.1,0.1],
+    ...                       [ 0.2,1.8],
+    ...                       [ 2.0,0.5],
+    ...                       [ 0.3,1.5],
+    ...                       [ 1.0,1.0]])
+    >>> whitened = whiten(features)
+    >>> book = np.array((whitened[0],whitened[2]))
+    >>> kmeans(whitened,book)
+    (array([[ 2.3110306 ,  2.86287398],    # random
+           [ 0.93218041,  1.24398691]]), 0.85684700941625547)
+
+    >>> codes = 3
+    >>> kmeans(whitened,codes)
+    (array([[ 2.3110306 ,  2.86287398],    # random
+           [ 1.32544402,  0.65607529],
+           [ 0.40782893,  2.02786907]]), 0.5196582527686241)
+
+    >>> # Create 50 datapoints in two clusters a and b
+    >>> pts = 50
+    >>> rng = np.random.default_rng()
+    >>> a = rng.multivariate_normal([0, 0], [[4, 1], [1, 4]], size=pts)
+    >>> b = rng.multivariate_normal([30, 10],
+    ...                             [[10, 2], [2, 1]],
+    ...                             size=pts)
+    >>> features = np.concatenate((a, b))
+    >>> # Whiten data
+    >>> whitened = whiten(features)
+    >>> # Find 2 clusters in the data
+    >>> codebook, distortion = kmeans(whitened, 2)
+    >>> # Plot whitened data and cluster centers in red
+    >>> plt.scatter(whitened[:, 0], whitened[:, 1])
+    >>> plt.scatter(codebook[:, 0], codebook[:, 1], c='r')
+    >>> plt.show()
+
+    """
+    if isinstance(k_or_guess, int):
+        xp = array_namespace(obs)
+    else:
+        xp = array_namespace(obs, k_or_guess)
+    obs = _asarray(obs, xp=xp, check_finite=check_finite)
+    guess = _asarray(k_or_guess, xp=xp, check_finite=check_finite)
+    if iter < 1:
+        raise ValueError(f"iter must be at least 1, got {iter}")
+
+    # Determine whether a count (scalar) or an initial guess (array) was passed.
+    if xp_size(guess) != 1:
+        if xp_size(guess) < 1:
+            raise ValueError(f"Asked for 0 clusters. Initial book was {guess}")
+        return _kmeans(obs, guess, thresh=thresh, xp=xp)
+
+    # k_or_guess is a scalar, now verify that it's an integer
+    k = int(guess)
+    if k != guess:
+        raise ValueError("If k_or_guess is a scalar, it must be an integer.")
+    if k < 1:
+        raise ValueError(f"Asked for {k} clusters.")
+
+    rng = check_random_state(rng)
+
+    # initialize best distance value to a large value
+    best_dist = xp.inf
+    for i in range(iter):
+        # the initial code book is randomly selected from observations
+        guess = _kpoints(obs, k, rng, xp)
+        book, dist = _kmeans(obs, guess, thresh=thresh, xp=xp)
+        if dist < best_dist:
+            best_book = book
+            best_dist = dist
+    return best_book, best_dist
+
+
+def _kpoints(data, k, rng, xp):
+    """Pick k points at random in data (one row = one observation).
+
+    Parameters
+    ----------
+    data : ndarray
+        Expect a rank 1 or 2 array. Rank 1 are assumed to describe one
+        dimensional data, rank 2 multidimensional data, in which case one
+        row is one observation.
+    k : int
+        Number of samples to generate.
+    rng : `numpy.random.Generator` or `numpy.random.RandomState`
+        Random number generator.
+
+    Returns
+    -------
+    x : ndarray
+        A 'k' by 'N' containing the initial centroids
+
+    """
+    idx = rng.choice(data.shape[0], size=int(k), replace=False)
+    # convert to array with default integer dtype (avoids numpy#25607)
+    idx = xp.asarray(idx, dtype=xp.asarray([1]).dtype)
+    return xp.take(data, idx, axis=0)
+
+
+def _krandinit(data, k, rng, xp):
+    """Returns k samples of a random variable whose parameters depend on data.
+
+    More precisely, it returns k observations sampled from a Gaussian random
+    variable whose mean and covariances are the ones estimated from the data.
+
+    Parameters
+    ----------
+    data : ndarray
+        Expect a rank 1 or 2 array. Rank 1 is assumed to describe 1-D
+        data, rank 2 multidimensional data, in which case one
+        row is one observation.
+    k : int
+        Number of samples to generate.
+    rng : `numpy.random.Generator` or `numpy.random.RandomState`
+        Random number generator.
+
+    Returns
+    -------
+    x : ndarray
+        A 'k' by 'N' containing the initial centroids
+
+    """
+    mu = xp.mean(data, axis=0)
+    k = np.asarray(k)
+
+    if data.ndim == 1:
+        _cov = xpx.cov(data, xp=xp)
+        x = rng.standard_normal(size=k)
+        x = xp.asarray(x)
+        x *= xp.sqrt(_cov)
+    elif data.shape[1] > data.shape[0]:
+        # initialize when the covariance matrix is rank deficient
+        _, s, vh = xp.linalg.svd(data - mu, full_matrices=False)
+        x = rng.standard_normal(size=(k, xp_size(s)))
+        x = xp.asarray(x)
+        sVh = s[:, None] * vh / xp.sqrt(data.shape[0] - xp.asarray(1.))
+        x = x @ sVh
+    else:
+        _cov = xpx.atleast_nd(xpx.cov(data.T, xp=xp), ndim=2, xp=xp)
+
+        # k rows, d cols (one row = one obs)
+        # Generate k sample of a random variable ~ Gaussian(mu, cov)
+        x = rng.standard_normal(size=(k, xp_size(mu)))
+        x = xp.asarray(x)
+        x = x @ xp.linalg.cholesky(_cov).T
+
+    x += mu
+    return x
+
+
+def _kpp(data, k, rng, xp):
+    """ Picks k points in the data based on the kmeans++ method.
+
+    Parameters
+    ----------
+    data : ndarray
+        Expect a rank 1 or 2 array. Rank 1 is assumed to describe 1-D
+        data, rank 2 multidimensional data, in which case one
+        row is one observation.
+    k : int
+        Number of samples to generate.
+    rng : `numpy.random.Generator` or `numpy.random.RandomState`
+        Random number generator.
+
+    Returns
+    -------
+    init : ndarray
+        A 'k' by 'N' containing the initial centroids.
+
+    References
+    ----------
+    .. [1] D. Arthur and S. Vassilvitskii, "k-means++: the advantages of
+       careful seeding", Proceedings of the Eighteenth Annual ACM-SIAM Symposium
+       on Discrete Algorithms, 2007.
+    """
+
+    ndim = len(data.shape)
+    if ndim == 1:
+        data = data[:, None]
+
+    dims = data.shape[1]
+
+    init = xp.empty((int(k), dims))
+
+    for i in range(k):
+        if i == 0:
+            data_idx = rng_integers(rng, data.shape[0])
+        else:
+            D2 = cdist(init[:i,:], data, metric='sqeuclidean').min(axis=0)
+            probs = D2/D2.sum()
+            cumprobs = probs.cumsum()
+            r = rng.uniform()
+            cumprobs = np.asarray(cumprobs)
+            data_idx = int(np.searchsorted(cumprobs, r))
+
+        init = xpx.at(init)[i, :].set(data[data_idx, :])
+
+    if ndim == 1:
+        init = init[:, 0]
+    return init
+
+
+_valid_init_meth = {'random': _krandinit, 'points': _kpoints, '++': _kpp}
+
+
+def _missing_warn():
+    """Print a warning when called."""
+    warnings.warn("One of the clusters is empty. "
+                  "Re-run kmeans with a different initialization.",
+                  stacklevel=3)
+
+
+def _missing_raise():
+    """Raise a ClusterError when called."""
+    raise ClusterError("One of the clusters is empty. "
+                       "Re-run kmeans with a different initialization.")
+
+
+_valid_miss_meth = {'warn': _missing_warn, 'raise': _missing_raise}
+
+
+@xp_capabilities(cpu_only=True, jax_jit=False, allow_dask_compute=True)
+@_transition_to_rng("seed")
+def kmeans2(data, k, iter=10, thresh=1e-5, minit='random',
+            missing='warn', check_finite=True, *, rng=None):
+    """
+    Classify a set of observations into k clusters using the k-means algorithm.
+
+    The algorithm attempts to minimize the Euclidean distance between
+    observations and centroids. Several initialization methods are
+    included.
+
+    Parameters
+    ----------
+    data : ndarray
+        A 'M' by 'N' array of 'M' observations in 'N' dimensions or a length
+        'M' array of 'M' 1-D observations.
+    k : int or ndarray
+        The number of clusters to form as well as the number of
+        centroids to generate. If `minit` initialization string is
+        'matrix', or if an ndarray is given instead, it is
+        interpreted as initial cluster to use instead.
+    iter : int, optional
+        Number of iterations of the k-means algorithm to run. Note
+        that this differs in meaning from the iters parameter to
+        the kmeans function.
+    thresh : float, optional
+        (not used yet)
+    minit : str, optional
+        Method for initialization. Available methods are 'random',
+        'points', '++' and 'matrix':
+
+        'random': generate k centroids from a Gaussian with mean and
+        variance estimated from the data.
+
+        'points': choose k observations (rows) at random from data for
+        the initial centroids.
+
+        '++': choose k observations accordingly to the kmeans++ method
+        (careful seeding)
+
+        'matrix': interpret the k parameter as a k by M (or length k
+        array for 1-D data) array of initial centroids.
+    missing : str, optional
+        Method to deal with empty clusters. Available methods are
+        'warn' and 'raise':
+
+        'warn': give a warning and continue.
+
+        'raise': raise a ClusterError and terminate the algorithm.
+    check_finite : bool, optional
+        Whether to check that the input matrices contain only finite numbers.
+        Disabling may give a performance gain, but may result in problems
+        (crashes, non-termination) if the inputs do contain infinities or NaNs.
+        Default: True
+    rng : `numpy.random.Generator`, optional
+        Pseudorandom number generator state. When `rng` is None, a new
+        `numpy.random.Generator` is created using entropy from the
+        operating system. Types other than `numpy.random.Generator` are
+        passed to `numpy.random.default_rng` to instantiate a ``Generator``.
+
+    Returns
+    -------
+    centroid : ndarray
+        A 'k' by 'N' array of centroids found at the last iteration of
+        k-means.
+    label : ndarray
+        label[i] is the code or index of the centroid the
+        ith observation is closest to.
+
+    See Also
+    --------
+    kmeans
+
+    References
+    ----------
+    .. [1] D. Arthur and S. Vassilvitskii, "k-means++: the advantages of
+       careful seeding", Proceedings of the Eighteenth Annual ACM-SIAM Symposium
+       on Discrete Algorithms, 2007.
+
+    Examples
+    --------
+    >>> from scipy.cluster.vq import kmeans2
+    >>> import matplotlib.pyplot as plt
+    >>> import numpy as np
+
+    Create z, an array with shape (100, 2) containing a mixture of samples
+    from three multivariate normal distributions.
+
+    >>> rng = np.random.default_rng()
+    >>> a = rng.multivariate_normal([0, 6], [[2, 1], [1, 1.5]], size=45)
+    >>> b = rng.multivariate_normal([2, 0], [[1, -1], [-1, 3]], size=30)
+    >>> c = rng.multivariate_normal([6, 4], [[5, 0], [0, 1.2]], size=25)
+    >>> z = np.concatenate((a, b, c))
+    >>> rng.shuffle(z)
+
+    Compute three clusters.
+
+    >>> centroid, label = kmeans2(z, 3, minit='points')
+    >>> centroid
+    array([[ 2.22274463, -0.61666946],  # may vary
+           [ 0.54069047,  5.86541444],
+           [ 6.73846769,  4.01991898]])
+
+    How many points are in each cluster?
+
+    >>> counts = np.bincount(label)
+    >>> counts
+    array([29, 51, 20])  # may vary
+
+    Plot the clusters.
+
+    >>> w0 = z[label == 0]
+    >>> w1 = z[label == 1]
+    >>> w2 = z[label == 2]
+    >>> plt.plot(w0[:, 0], w0[:, 1], 'o', alpha=0.5, label='cluster 0')
+    >>> plt.plot(w1[:, 0], w1[:, 1], 'd', alpha=0.5, label='cluster 1')
+    >>> plt.plot(w2[:, 0], w2[:, 1], 's', alpha=0.5, label='cluster 2')
+    >>> plt.plot(centroid[:, 0], centroid[:, 1], 'k*', label='centroids')
+    >>> plt.axis('equal')
+    >>> plt.legend(shadow=True)
+    >>> plt.show()
+
+    """
+    if int(iter) < 1:
+        raise ValueError(f"Invalid iter ({iter}), must be a positive integer.")
+    try:
+        miss_meth = _valid_miss_meth[missing]
+    except KeyError as e:
+        raise ValueError(f"Unknown missing method {missing!r}") from e
+
+    if isinstance(k, int):
+        xp = array_namespace(data)
+    else:
+        xp = array_namespace(data, k)
+    data = _asarray(data, xp=xp, check_finite=check_finite)
+    code_book = xp_copy(k, xp=xp)
+    if data.ndim == 1:
+        d = 1
+    elif data.ndim == 2:
+        d = data.shape[1]
+    else:
+        raise ValueError("Input of rank > 2 is not supported.")
+
+    if xp_size(data) < 1 or xp_size(code_book) < 1:
+        raise ValueError("Empty input is not supported.")
+
+    # If k is not a single value, it should be compatible with data's shape
+    if minit == 'matrix' or xp_size(code_book) > 1:
+        if data.ndim != code_book.ndim:
+            raise ValueError("k array doesn't match data rank")
+        nc = code_book.shape[0]
+        if data.ndim > 1 and code_book.shape[1] != d:
+            raise ValueError("k array doesn't match data dimension")
+    else:
+        nc = int(code_book)
+
+        if nc < 1:
+            raise ValueError(
+                f"Cannot ask kmeans2 for {nc} clusters (k was {code_book})"
+            )
+        elif nc != code_book:
+            warnings.warn("k was not an integer, was converted.", stacklevel=2)
+
+        try:
+            init_meth = _valid_init_meth[minit]
+        except KeyError as e:
+            raise ValueError(f"Unknown init method {minit!r}") from e
+        else:
+            rng = check_random_state(rng)
+            code_book = init_meth(data, code_book, rng, xp)
+
+    data = np.asarray(data)
+    code_book = np.asarray(code_book)
+    for _ in range(iter):
+        # Compute the nearest neighbor for each obs using the current code book
+        label = vq(data, code_book, check_finite=check_finite)[0]
+        # Update the code book by computing centroids
+        new_code_book, has_members = _vq.update_cluster_means(data, label, nc)
+        if not has_members.all():
+            miss_meth()
+            # Set the empty clusters to their previous positions
+            new_code_book[~has_members] = code_book[~has_members]
+        code_book = new_code_book
+
+    return xp.asarray(code_book), xp.asarray(label)
diff --git a/.venv/lib/python3.12/site-packages/scipy/cluster/vq/tests/__init__.py b/.venv/lib/python3.12/site-packages/scipy/cluster/vq/tests/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/.venv/lib/python3.12/site-packages/scipy/cluster/vq/tests/test_vq.py b/.venv/lib/python3.12/site-packages/scipy/cluster/vq/tests/test_vq.py
new file mode 100644
index 0000000000000000000000000000000000000000..8e7157bc9afb5045dd8efe77c0cac5670afd6dba
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/cluster/vq/tests/test_vq.py
@@ -0,0 +1,456 @@
+import math
+import sys
+import warnings
+from copy import deepcopy
+from threading import Lock
+
+import numpy as np
+from numpy.testing import assert_array_equal
+import pytest
+from pytest import raises as assert_raises
+
+from scipy.cluster.vq import ClusterError, kmeans, kmeans2, vq, whiten
+from scipy.cluster.vq._vq_impl import _py_vq, _krandinit, _vq
+from scipy.sparse._sputils import matrix
+
+from scipy._external import array_api_extra as xpx
+from scipy._lib._array_api import (
+    SCIPY_ARRAY_API, eager_warns, is_lazy_array, make_xp_test_case,
+    xp_copy, xp_assert_close, xp_assert_equal
+)
+
+xfail_xp_backends = pytest.mark.xfail_xp_backends
+skip_xp_backends = pytest.mark.skip_xp_backends
+
+TESTDATA_2D = np.array([
+    -2.2, 1.17, -1.63, 1.69, -2.04, 4.38, -3.09, 0.95, -1.7, 4.79, -1.68, 0.68,
+    -2.26, 3.34, -2.29, 2.55, -1.72, -0.72, -1.99, 2.34, -2.75, 3.43, -2.45,
+    2.41, -4.26, 3.65, -1.57, 1.87, -1.96, 4.03, -3.01, 3.86, -2.53, 1.28,
+    -4.0, 3.95, -1.62, 1.25, -3.42, 3.17, -1.17, 0.12, -3.03, -0.27, -2.07,
+    -0.55, -1.17, 1.34, -2.82, 3.08, -2.44, 0.24, -1.71, 2.48, -5.23, 4.29,
+    -2.08, 3.69, -1.89, 3.62, -2.09, 0.26, -0.92, 1.07, -2.25, 0.88, -2.25,
+    2.02, -4.31, 3.86, -2.03, 3.42, -2.76, 0.3, -2.48, -0.29, -3.42, 3.21,
+    -2.3, 1.73, -2.84, 0.69, -1.81, 2.48, -5.24, 4.52, -2.8, 1.31, -1.67,
+    -2.34, -1.18, 2.17, -2.17, 2.82, -1.85, 2.25, -2.45, 1.86, -6.79, 3.94,
+    -2.33, 1.89, -1.55, 2.08, -1.36, 0.93, -2.51, 2.74, -2.39, 3.92, -3.33,
+    2.99, -2.06, -0.9, -2.83, 3.35, -2.59, 3.05, -2.36, 1.85, -1.69, 1.8,
+    -1.39, 0.66, -2.06, 0.38, -1.47, 0.44, -4.68, 3.77, -5.58, 3.44, -2.29,
+    2.24, -1.04, -0.38, -1.85, 4.23, -2.88, 0.73, -2.59, 1.39, -1.34, 1.75,
+    -1.95, 1.3, -2.45, 3.09, -1.99, 3.41, -5.55, 5.21, -1.73, 2.52, -2.17,
+    0.85, -2.06, 0.49, -2.54, 2.07, -2.03, 1.3, -3.23, 3.09, -1.55, 1.44,
+    -0.81, 1.1, -2.99, 2.92, -1.59, 2.18, -2.45, -0.73, -3.12, -1.3, -2.83,
+    0.2, -2.77, 3.24, -1.98, 1.6, -4.59, 3.39, -4.85, 3.75, -2.25, 1.71, -3.28,
+    3.38, -1.74, 0.88, -2.41, 1.92, -2.24, 1.19, -2.48, 1.06, -1.68, -0.62,
+    -1.3, 0.39, -1.78, 2.35, -3.54, 2.44, -1.32, 0.66, -2.38, 2.76, -2.35,
+    3.95, -1.86, 4.32, -2.01, -1.23, -1.79, 2.76, -2.13, -0.13, -5.25, 3.84,
+    -2.24, 1.59, -4.85, 2.96, -2.41, 0.01, -0.43, 0.13, -3.92, 2.91, -1.75,
+    -0.53, -1.69, 1.69, -1.09, 0.15, -2.11, 2.17, -1.53, 1.22, -2.1, -0.86,
+    -2.56, 2.28, -3.02, 3.33, -1.12, 3.86, -2.18, -1.19, -3.03, 0.79, -0.83,
+    0.97, -3.19, 1.45, -1.34, 1.28, -2.52, 4.22, -4.53, 3.22, -1.97, 1.75,
+    -2.36, 3.19, -0.83, 1.53, -1.59, 1.86, -2.17, 2.3, -1.63, 2.71, -2.03,
+    3.75, -2.57, -0.6, -1.47, 1.33, -1.95, 0.7, -1.65, 1.27, -1.42, 1.09, -3.0,
+    3.87, -2.51, 3.06, -2.6, 0.74, -1.08, -0.03, -2.44, 1.31, -2.65, 2.99,
+    -1.84, 1.65, -4.76, 3.75, -2.07, 3.98, -2.4, 2.67, -2.21, 1.49, -1.21,
+    1.22, -5.29, 2.38, -2.85, 2.28, -5.6, 3.78, -2.7, 0.8, -1.81, 3.5, -3.75,
+    4.17, -1.29, 2.99, -5.92, 3.43, -1.83, 1.23, -1.24, -1.04, -2.56, 2.37,
+    -3.26, 0.39, -4.63, 2.51, -4.52, 3.04, -1.7, 0.36, -1.41, 0.04, -2.1, 1.0,
+    -1.87, 3.78, -4.32, 3.59, -2.24, 1.38, -1.99, -0.22, -1.87, 1.95, -0.84,
+    2.17, -5.38, 3.56, -1.27, 2.9, -1.79, 3.31, -5.47, 3.85, -1.44, 3.69,
+    -2.02, 0.37, -1.29, 0.33, -2.34, 2.56, -1.74, -1.27, -1.97, 1.22, -2.51,
+    -0.16, -1.64, -0.96, -2.99, 1.4, -1.53, 3.31, -2.24, 0.45, -2.46, 1.71,
+    -2.88, 1.56, -1.63, 1.46, -1.41, 0.68, -1.96, 2.76, -1.61,
+    2.11]).reshape((200, 2))
+
+
+# Global data
+X = np.array([[3.0, 3], [4, 3], [4, 2],
+              [9, 2], [5, 1], [6, 2], [9, 4],
+              [5, 2], [5, 4], [7, 4], [6, 5]])
+
+CODET1 = np.array([[3.0000, 3.0000],
+                   [6.2000, 4.0000],
+                   [5.8000, 1.8000]])
+
+CODET2 = np.array([[11.0/3, 8.0/3],
+                   [6.7500, 4.2500],
+                   [6.2500, 1.7500]])
+
+LABEL1 = np.array([0, 1, 2, 2, 2, 2, 1, 2, 1, 1, 1])
+
+
+@make_xp_test_case(whiten)
+class TestWhiten:
+
+    def test_whiten(self, xp):
+        desired = xp.asarray([[5.08738849, 2.97091878],
+                            [3.19909255, 0.69660580],
+                            [4.51041982, 0.02640918],
+                            [4.38567074, 0.95120889],
+                            [2.32191480, 1.63195503]])
+
+        obs = xp.asarray([[0.98744510, 0.82766775],
+                          [0.62093317, 0.19406729],
+                          [0.87545741, 0.00735733],
+                          [0.85124403, 0.26499712],
+                          [0.45067590, 0.45464607]])
+        xp_assert_close(whiten(obs), desired, rtol=1e-5)
+
+    def test_whiten_zero_std(self, xp):
+        desired = xp.asarray([[0., 1.0, 2.86666544],
+                              [0., 1.0, 1.32460034],
+                              [0., 1.0, 3.74382172]])
+
+        obs = xp.asarray([[0., 1., 0.74109533],
+                          [0., 1., 0.34243798],
+                          [0., 1., 0.96785929]])
+
+        with eager_warns(RuntimeWarning, match="Some columns have standard...", xp=xp):
+            actual = whiten(obs)
+        xp_assert_close(actual, desired, rtol=1e-5)
+
+    @pytest.mark.filterwarnings("ignore:invalid value encountered:RuntimeWarning:dask")
+    @pytest.mark.parametrize("bad_value", [math.nan, math.inf, -math.inf])
+    def test_whiten_not_finite(self, bad_value, xp):
+        obs = xp.asarray([[0.98744510, bad_value],
+                          [0.62093317, 0.19406729],
+                          [0.87545741, 0.00735733],
+                          [0.85124403, 0.26499712],
+                          [0.45067590, 0.45464607]])
+
+        if is_lazy_array(obs):
+            desired = xp.asarray([[5.08738849, math.nan],
+                                  [3.19909255, math.nan],
+                                  [4.51041982, math.nan],
+                                  [4.38567074, math.nan],
+                                  [2.32191480, math.nan]])
+            xp_assert_close(whiten(obs), desired, rtol=1e-5)
+        else:
+            assert_raises(ValueError, whiten, obs)
+
+    @pytest.mark.skipif(SCIPY_ARRAY_API,
+                        reason='`np.matrix` unsupported in array API mode')
+    def test_whiten_not_finite_matrix(self):
+        for bad_value in np.nan, np.inf, -np.inf:
+            obs = matrix([[0.98744510, bad_value],
+                          [0.62093317, 0.19406729],
+                          [0.87545741, 0.00735733],
+                          [0.85124403, 0.26499712],
+                          [0.45067590, 0.45464607]])
+            assert_raises(ValueError, whiten, obs)
+
+
+@make_xp_test_case(vq)
+class TestVq:
+
+    def test_py_vq(self, xp):
+        initc = np.concatenate([[X[0]], [X[1]], [X[2]]])
+        # label1.dtype varies between int32 and int64 over platforms
+        label1 = _py_vq(xp.asarray(X), xp.asarray(initc))[0]
+        xp_assert_equal(label1, xp.asarray(LABEL1, dtype=xp.int64),
+                        check_dtype=False)
+
+    @pytest.mark.skipif(SCIPY_ARRAY_API,
+                        reason='`np.matrix` unsupported in array API mode')
+    def test_py_vq_matrix(self):
+        initc = np.concatenate([[X[0]], [X[1]], [X[2]]])
+        # label1.dtype varies between int32 and int64 over platforms
+        label1 = _py_vq(matrix(X), matrix(initc))[0]
+        assert_array_equal(label1, LABEL1)
+
+    @pytest.mark.parametrize("dtype", ["float64", "int64"])
+    def test_vq(self, dtype, xp):
+        dtype = getattr(xp, dtype)
+        initc = np.concatenate([[X[0]], [X[1]], [X[2]]])
+        label1, _ = _vq.vq(X, initc)
+        assert_array_equal(label1, LABEL1)
+        _, _ = vq(xp.asarray(X, dtype=dtype), xp.asarray(initc, dtype=dtype))
+
+    @pytest.mark.skipif(SCIPY_ARRAY_API,
+                        reason='`np.matrix` unsupported in array API mode')
+    def test_vq_matrix(self):
+        initc = np.concatenate([[X[0]], [X[1]], [X[2]]])
+        label1, _ = _vq.vq(matrix(X), matrix(initc))
+        assert_array_equal(label1, LABEL1)
+        _, _ = vq(matrix(X), matrix(initc))
+
+    def test_vq_1d(self, xp):
+        # Test special rank 1 vq algo, python implementation.
+        data = X[:, 0]
+        initc = data[:3]
+        a, b = _vq.vq(data, initc)
+        data = xp.asarray(data)
+        initc = xp.asarray(initc)
+        ta, tb = _py_vq(data[:, np.newaxis], initc[:, np.newaxis])
+        # ta.dtype varies between int32 and int64 over platforms
+        xp_assert_equal(ta, xp.asarray(a, dtype=xp.int64), check_dtype=False)
+        xp_assert_equal(tb, xp.asarray(b))
+
+    def test__vq_sametype(self):
+        a = np.asarray([1.0, 2.0])
+        b = a.astype(np.float32)
+        assert_raises(TypeError, _vq.vq, a, b)
+
+    def test__vq_invalid_type(self):
+        a = np.asarray([1, 2], dtype=int)
+        assert_raises(TypeError, _vq.vq, a, a)
+
+    def test_vq_large_nfeat(self, xp):
+        X = np.random.rand(20, 20)
+        code_book = np.random.rand(3, 20)
+
+        codes0, dis0 = _vq.vq(X, code_book)
+        codes1, dis1 = _py_vq(
+            xp.asarray(X), xp.asarray(code_book)
+        )
+        xp_assert_close(dis1, xp.asarray(dis0), rtol=1e-5)
+        # codes1.dtype varies between int32 and int64 over platforms
+        xp_assert_equal(codes1, xp.asarray(codes0, dtype=xp.int64), check_dtype=False)
+
+        X = X.astype(np.float32)
+        code_book = code_book.astype(np.float32)
+
+        codes0, dis0 = _vq.vq(X, code_book)
+        codes1, dis1 = _py_vq(
+            xp.asarray(X), xp.asarray(code_book)
+        )
+        xp_assert_close(dis1, xp.asarray(dis0, dtype=xp.float64), rtol=1e-5)
+        # codes1.dtype varies between int32 and int64 over platforms
+        xp_assert_equal(codes1, xp.asarray(codes0, dtype=xp.int64), check_dtype=False)
+
+    def test_vq_large_features(self, xp):
+        X = np.random.rand(10, 5) * 1000000
+        code_book = np.random.rand(2, 5) * 1000000
+
+        codes0, dis0 = _vq.vq(X, code_book)
+        codes1, dis1 = _py_vq(
+            xp.asarray(X), xp.asarray(code_book)
+        )
+        xp_assert_close(dis1, xp.asarray(dis0), rtol=1e-5)
+        # codes1.dtype varies between int32 and int64 over platforms
+        xp_assert_equal(codes1, xp.asarray(codes0, dtype=xp.int64), check_dtype=False)
+
+
+# Whole class skipped on GPU for now;
+# once pdist/cdist are hooked up for CuPy, more tests will work
+@make_xp_test_case(kmeans, kmeans2)
+class TestKMeans:
+
+    def test_large_features(self, xp):
+        # Generate a data set with large values, and run kmeans on it to
+        # (regression for 1077).
+        d = 300
+        n = 100
+
+        m1 = np.random.randn(d)
+        m2 = np.random.randn(d)
+        x = 10000 * np.random.randn(n, d) - 20000 * m1
+        y = 10000 * np.random.randn(n, d) + 20000 * m2
+
+        data = np.empty((x.shape[0] + y.shape[0], d), np.float64)
+        data[:x.shape[0]] = x
+        data[x.shape[0]:] = y
+
+        # use `seed` to ensure backwards compatibility after SPEC7
+        kmeans(xp.asarray(data), 2, seed=1)
+
+    def test_kmeans_simple(self, xp):
+        rng = np.random.default_rng(54321)
+        initc = np.concatenate([[X[0]], [X[1]], [X[2]]])
+        code1 = kmeans(xp.asarray(X), xp.asarray(initc), iter=1, rng=rng)[0]
+        xp_assert_close(code1, xp.asarray(CODET2))
+
+    @pytest.mark.skipif(SCIPY_ARRAY_API,
+                        reason='`np.matrix` unsupported in array API mode')
+    def test_kmeans_simple_matrix(self):
+        rng = np.random.default_rng(54321)
+        initc = np.concatenate([[X[0]], [X[1]], [X[2]]])
+        code1 = kmeans(matrix(X), matrix(initc), iter=1, rng=rng)[0]
+        xp_assert_close(code1, CODET2)
+
+    def test_kmeans_lost_cluster(self, xp):
+        # This will cause kmeans to have a cluster with no points.
+        data = xp.asarray(TESTDATA_2D)
+        initk = xp.asarray([[-1.8127404, -0.67128041],
+                            [2.04621601, 0.07401111],
+                            [-2.31149087, -0.05160469]])
+
+        kmeans(data, initk)
+        with warnings.catch_warnings():
+            warnings.filterwarnings(
+                "ignore",
+                ("One of the clusters is empty. Re-run kmeans with a different "
+                 "initialization"),
+                UserWarning,
+            )
+            kmeans2(data, initk, missing='warn')
+
+        assert_raises(ClusterError, kmeans2, data, initk, missing='raise')
+
+    def test_kmeans2_simple(self, xp):
+        rng = np.random.default_rng(12345678)
+        initc = xp.asarray(np.concatenate([[X[0]], [X[1]], [X[2]]]))
+        arrays = [xp.asarray] if SCIPY_ARRAY_API else [np.asarray, matrix]
+        for tp in arrays:
+            code1 = kmeans2(tp(X), tp(initc), iter=1, rng=rng)[0]
+            code2 = kmeans2(tp(X), tp(initc), iter=2, rng=rng)[0]
+
+            xp_assert_close(code1, xp.asarray(CODET1))
+            xp_assert_close(code2, xp.asarray(CODET2))
+
+    @pytest.mark.skipif(SCIPY_ARRAY_API,
+                        reason='`np.matrix` unsupported in array API mode')
+    def test_kmeans2_simple_matrix(self):
+        rng = np.random.default_rng(12345678)
+        initc = np.concatenate([[X[0]], [X[1]], [X[2]]])
+        code1 = kmeans2(matrix(X), matrix(initc), iter=1, rng=rng)[0]
+        code2 = kmeans2(matrix(X), matrix(initc), iter=2, rng=rng)[0]
+
+        xp_assert_close(code1, CODET1)
+        xp_assert_close(code2, CODET2)
+
+    def test_kmeans2_rank1(self, xp):
+        data = xp.asarray(TESTDATA_2D)
+        data1 = data[:, 0]
+
+        initc = data1[:3]
+        code = xp_copy(initc, xp=xp)
+
+        # use `seed` to ensure backwards compatibility after SPEC7
+        kmeans2(data1, code, iter=1, seed=1)[0]
+        kmeans2(data1, code, iter=2)[0]
+
+    def test_kmeans2_rank1_2(self, xp):
+        data = xp.asarray(TESTDATA_2D)
+        data1 = data[:, 0]
+        rng = np.random.default_rng(42)
+        kmeans2(data1, 2, iter=1, rng=rng)
+
+    def test_kmeans2_high_dim(self, xp):
+        # test kmeans2 when the number of dimensions exceeds the number
+        # of input points
+        data = xp.asarray(TESTDATA_2D)
+        data = xp.reshape(data, (20, 20))[:10, :]
+        rng = np.random.default_rng(42)
+        kmeans2(data, 2, rng=rng)     
+
+    def test_kmeans2_init(self, xp):
+        rng = np.random.default_rng(12345678)
+        data = xp.asarray(TESTDATA_2D)
+        k = 3
+
+        kmeans2(data, k, minit='points', rng=rng)
+        kmeans2(data[:, 1], k, minit='points', rng=rng)  # special case (1-D)
+
+        kmeans2(data, k, minit='++', rng=rng)
+        kmeans2(data[:, 1], k, minit='++', rng=rng)  # special case (1-D)
+
+        # minit='random' can give warnings, filter those
+        with warnings.catch_warnings():
+            warnings.filterwarnings("ignore", "One of the clusters is empty. Re-run.")
+            kmeans2(data, k, minit='random', rng=rng)
+            kmeans2(data[:, 1], k, minit='random', rng=rng)  # special case (1-D)
+
+    @pytest.fixture
+    def krand_lock(self):
+        return Lock()
+
+    @xfail_xp_backends('dask.array', reason="Wrong answer")
+    @pytest.mark.skipif(sys.platform == 'win32',
+                        reason='Fails with MemoryError in Wine.')
+    def test_krandinit(self, xp, krand_lock):
+        data = xp.asarray(TESTDATA_2D)
+        datas = [xp.reshape(data, (200, 2)),
+                 xp.reshape(data, (20, 20))[:10, :]]
+        k = int(1e6)
+        with krand_lock:
+            for data in datas:
+                rng = np.random.default_rng(1234)
+                init = _krandinit(data, k, rng, xp)
+                orig_cov = xpx.cov(data.T, xp=xp)
+                init_cov = xpx.cov(init.T, xp=xp)
+                xp_assert_close(orig_cov, init_cov, atol=1.1e-2)
+
+    def test_kmeans2_empty(self, xp):
+        # Regression test for gh-1032.
+        assert_raises(ValueError, kmeans2, xp.asarray([]), 2)
+
+    def test_kmeans_0k(self, xp):
+        # Regression test for gh-1073: fail when k arg is 0.
+        assert_raises(ValueError, kmeans, xp.asarray(X), 0)
+        assert_raises(ValueError, kmeans2, xp.asarray(X), 0)
+        assert_raises(ValueError, kmeans2, xp.asarray(X), xp.asarray([]))
+
+    def test_kmeans_large_thres(self, xp):
+        # Regression test for gh-1774
+        x = xp.asarray([1, 2, 3, 4, 10], dtype=xp.float64)
+        res = kmeans(x, 1, thresh=1e16)
+        xp_assert_close(res[0], xp.asarray([4.], dtype=xp.float64))
+        xp_assert_close(res[1], xp.asarray(2.3999999999999999, dtype=xp.float64)[()])
+
+    def test_kmeans_distortion_matches_vq_mean_regression_24069(self, xp):
+        # Regression test for gh-24069
+        rows = [[8.0, 1e-5, 1e-5, 1e-5]]
+        rows += [[1e-5, 1e-5, 1e-5, 1e-5]] * 51
+        rows += [[0.0, 1e-5, 1e-5, 1e-5]]
+
+        wh = whiten(np.asarray(rows, dtype=np.float64))
+        wh = xp.asarray(wh, dtype=xp.float64)
+
+        rng = np.random.default_rng(1)
+        codebook, distortion = kmeans(wh, 3, iter=5, rng=rng)
+
+        _, dists = vq(wh, codebook, check_finite=False)
+        xp_assert_close(distortion, xp.mean(dists, axis=-1), rtol=1e-12, atol=1e-12)
+
+
+    def test_kmeans2_kpp_low_dim(self, xp):
+        # Regression test for gh-11462
+        rng = np.random.default_rng(2358792345678234568)
+        prev_res = xp.asarray([[-1.95266667, 0.898],
+                               [-3.153375, 3.3945]], dtype=xp.float64)
+        res, _ = kmeans2(xp.asarray(TESTDATA_2D), 2, minit='++', rng=rng)
+        xp_assert_close(res, prev_res)
+
+    def test_kmeans2_kpp_high_dim(self, xp):
+        # Regression test for gh-11462
+        rng = np.random.default_rng(23587923456834568)
+        n_dim = 100
+        size = 10
+        centers = np.vstack([5 * np.ones(n_dim),
+                             -5 * np.ones(n_dim)])
+
+        data = np.vstack([
+            rng.multivariate_normal(centers[0], np.eye(n_dim), size=size),
+            rng.multivariate_normal(centers[1], np.eye(n_dim), size=size)
+        ])
+
+        data = xp.asarray(data)
+        res, _ = kmeans2(data, 2, minit='++', rng=rng)
+        xp_assert_equal(xp.sign(res), xp.sign(xp.asarray(centers)))
+
+    def test_kmeans_diff_convergence(self, xp):
+        # Regression test for gh-8727
+        obs = xp.asarray([-3, -1, 0, 1, 1, 8], dtype=xp.float64)
+        res = kmeans(obs, xp.asarray([-3., 0.99]))
+        xp_assert_close(res[0], xp.asarray([-0.4,  8.], dtype=xp.float64))
+        xp_assert_close(res[1], xp.asarray(1.0666666666666667, dtype=xp.float64)[()])
+
+    def test_kmeans_and_kmeans2_random_seed(self, xp):
+
+        seed_list = [
+            1234, np.random.RandomState(1234), np.random.default_rng(1234)
+        ]
+
+        for seed in seed_list:
+            seed1 = deepcopy(seed)
+            seed2 = deepcopy(seed)
+            data = xp.asarray(TESTDATA_2D)
+            # test for kmeans
+            res1, _ = kmeans(data, 2, seed=seed1)
+            res2, _ = kmeans(data, 2, seed=seed2)
+            xp_assert_close(res1, res2)  # should be same results
+            # test for kmeans2
+            for minit in ["random", "points", "++"]:
+                res1, _ = kmeans2(data, 2, minit=minit, seed=seed1)
+                res2, _ = kmeans2(data, 2, minit=minit, seed=seed2)
+                xp_assert_close(res1, res2)  # should be same results
diff --git a/.venv/lib/python3.12/site-packages/scipy/conftest.py b/.venv/lib/python3.12/site-packages/scipy/conftest.py
new file mode 100644
index 0000000000000000000000000000000000000000..38217f64067e36ead402b978a62965cd479d097f
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/conftest.py
@@ -0,0 +1,741 @@
+# Pytest customization
+import json
+import multiprocessing
+import os
+import sys
+import warnings
+import tempfile
+from contextlib import contextmanager
+from typing import Literal
+
+import numpy as np
+import pytest
+try:
+    import hypothesis
+    hypothesis_available = True
+except ImportError:
+    hypothesis_available = False
+
+from scipy._lib._fpumode import get_fpu_mode
+from scipy._lib._array_api import (
+    SCIPY_ARRAY_API, SCIPY_DEVICE, array_namespace, default_xp,
+    is_cupy, is_dask, is_jax, is_torch,
+)
+from scipy._lib._testutils import FPUModeChangeWarning
+from scipy._external.array_api_extra.testing import patch_lazy_xp_functions
+from scipy._external.packaging_version import version
+
+try:
+    from scipy_doctest.conftest import dt_config
+    HAVE_SCPDT = True
+except ModuleNotFoundError:
+    HAVE_SCPDT = False
+
+try:
+    import pytest_run_parallel  # noqa:F401
+    PARALLEL_RUN_AVAILABLE = True
+except Exception:
+    PARALLEL_RUN_AVAILABLE = False
+
+
+def pytest_configure(config):
+    """
+    Add pytest markers to avoid PytestUnknownMarkWarning
+
+    This needs to contain all markers that are SciPy-specific, as well as
+    dummy fallbacks for markers defined in optional test packages.
+
+    Note that we need both the registration here *and* in `pytest.ini`.
+    """
+    config.addinivalue_line("markers",
+        "slow: Tests that are very slow.")
+    config.addinivalue_line("markers",
+        "xslow: mark test as extremely slow (not run unless explicitly requested)")
+    config.addinivalue_line("markers",
+        "xfail_on_32bit: mark test as failing on 32-bit platforms")
+    config.addinivalue_line("markers",
+        "array_api_backends: test iterates on all array API backends")
+    config.addinivalue_line("markers",
+        ("skip_xp_backends(backends, reason=None, np_only=False, cpu_only=False, " +
+         "eager_only=False, exceptions=None): mark the desired skip configuration " +
+         "for the `skip_xp_backends` fixture"))
+    config.addinivalue_line("markers",
+        ("xfail_xp_backends(backends, reason=None, np_only=False, cpu_only=False, " +
+         "eager_only=False, exceptions=None): mark the desired xfail configuration " +
+         "for the `xfail_xp_backends` fixture"))
+    config.addinivalue_line("markers",
+                            ("uses_xp_capabilities(status, funcs=None, " +
+                             "reason=None): mark " +
+                            "whether pytest markers for array API backends are " +
+                            " generated from the xp_capabilities entries for one or "
+                             " more functions"))
+
+    try:
+        import pytest_timeout  # noqa:F401
+    except Exception:
+        config.addinivalue_line(
+            "markers", 'timeout: mark a test for a non-default timeout')
+    try:
+        # This is a more reliable test of whether pytest_fail_slow is installed
+        # When I uninstalled it, `import pytest_fail_slow` didn't fail!
+        from pytest_fail_slow import parse_duration  # type: ignore[import-not-found] # noqa:F401,E501
+    except Exception:
+        config.addinivalue_line(
+            "markers", 'fail_slow: mark a test for a non-default timeout failure')
+
+    if not PARALLEL_RUN_AVAILABLE:
+        config.addinivalue_line(
+            'markers',
+            'parallel_threads_limit(n): run the given test function in parallel '
+            'using `n` threads.')
+        config.addinivalue_line(
+            "markers",
+            "thread_unsafe: mark the test function as single-threaded",
+        )
+        config.addinivalue_line(
+            "markers",
+            "iterations(n): run the given test function `n` times in each thread",
+        )
+
+    if (sys.version_info < (3, 14)
+            and 'forkserver' in multiprocessing.get_all_start_methods()):
+        # On POSIX, Python 3.13 and older uses the 'fork' context by
+        # default. Calling fork() from multiple threads leads to
+        # deadlocks. This has been changed in 3.14 to 'forkserver'.
+        multiprocessing.set_start_method('forkserver', force=True)
+
+
+def pytest_runtest_setup(item):
+    mark = item.get_closest_marker("xslow")
+    if mark is not None:
+        try:
+            v = int(os.environ.get('SCIPY_XSLOW', '0'))
+        except ValueError:
+            v = False
+        if not v:
+            pytest.skip("very slow test; "
+                        "set environment variable SCIPY_XSLOW=1 to run it")
+    mark = item.get_closest_marker("xfail_on_32bit")
+    if mark is not None and np.intp(0).itemsize < 8:
+        pytest.xfail(f'Fails on our 32-bit test platform(s): {mark.args[0]}')
+
+    # Older versions of threadpoolctl have an issue that may lead to this
+    # warning being emitted, see gh-14441
+    with warnings.catch_warnings():
+        warnings.simplefilter("ignore", pytest.PytestUnraisableExceptionWarning)
+
+        try:
+            from threadpoolctl import threadpool_limits
+
+            HAS_THREADPOOLCTL = True
+        except Exception:  # observed in gh-14441: (ImportError, AttributeError)
+            # Optional dependency only. All exceptions are caught, for robustness
+            HAS_THREADPOOLCTL = False
+
+        if HAS_THREADPOOLCTL:
+            # Set the number of openmp threads based on the number of workers
+            # xdist is using to prevent oversubscription. Simplified version of what
+            # sklearn does (it can rely on threadpoolctl and its builtin OpenMP helper
+            # functions)
+            try:
+                xdist_worker_count = int(os.environ['PYTEST_XDIST_WORKER_COUNT'])
+            except KeyError:
+                # raises when pytest-xdist is not installed
+                return
+
+            if not os.getenv('OMP_NUM_THREADS'):
+                max_openmp_threads = os.cpu_count() // 2  # use nr of physical cores
+                threads_per_worker = max(max_openmp_threads // xdist_worker_count, 1)
+                try:
+                    threadpool_limits(threads_per_worker, user_api='blas')
+                except Exception:
+                    # May raise AttributeError for older versions of OpenBLAS.
+                    # Catch any error for robustness.
+                    return
+
+
+@pytest.fixture(scope="function", autouse=True)
+def check_fpu_mode(request):
+    """
+    Check FPU mode was not changed during the test.
+    """
+    old_mode = get_fpu_mode()
+    yield
+    new_mode = get_fpu_mode()
+
+    if old_mode != new_mode:
+        warnings.warn(f"FPU mode changed from {old_mode:#x} to {new_mode:#x} during "
+                      "the test",
+                      category=FPUModeChangeWarning, stacklevel=0)
+
+
+if not PARALLEL_RUN_AVAILABLE:
+    @pytest.fixture
+    def num_parallel_threads():
+        return 1
+
+
+# Array API backend handling
+xp_known_backends = {'numpy', 'array_api_strict', 'torch', 'cupy', 'jax.numpy',
+                     'dask.array'}
+xp_available_backends = [
+    pytest.param(np, id='numpy', marks=pytest.mark.array_api_backends)
+]
+xp_skip_cpu_only_backends = set()
+xp_skip_eager_only_backends = set()
+
+if SCIPY_ARRAY_API:
+    # fill the dict of backends with available libraries
+    try:
+        import array_api_strict
+        xp_available_backends.append(
+            pytest.param(array_api_strict, id='array_api_strict',
+                         marks=pytest.mark.array_api_backends))
+        if version.parse(array_api_strict.__version__) < version.Version('2.3'):
+            raise ImportError("array-api-strict must be >= version 2.3")
+        array_api_strict.set_array_api_strict_flags(
+            api_version='2025.12'
+        )
+    except ImportError:
+        pass
+
+    try:
+        import torch  # type: ignore[import-not-found]
+        xp_available_backends.append(
+            pytest.param(torch, id='torch',
+            marks=pytest.mark.array_api_backends))
+        torch.set_default_device(SCIPY_DEVICE)
+        if SCIPY_DEVICE != "cpu":
+            xp_skip_cpu_only_backends.add('torch')
+
+        # default to float64 unless explicitly requested
+        default = os.getenv('SCIPY_DEFAULT_DTYPE', default='float64')
+        if default == 'float64':
+            torch.set_default_dtype(torch.float64)
+        elif default != "float32":
+            raise ValueError(
+                "SCIPY_DEFAULT_DTYPE env var, if set, can only be either 'float64' "
+               f"or 'float32'. Got '{default}' instead."
+            )
+    except ImportError:
+        pass
+
+    try:
+        import cupy  # type: ignore[import-not-found]
+        # Note: cupy disregards SCIPY_DEVICE and always runs on cuda.
+        # It will fail to import if you don't have CUDA hardware and drivers.
+        xp_available_backends.append(
+            pytest.param(cupy, id='cupy',
+            marks=pytest.mark.array_api_backends))
+        xp_skip_cpu_only_backends.add('cupy')
+
+        # this is annoying in CuPy 13.x
+        warnings.filterwarnings(
+            'ignore', 'cupyx.jit.rawkernel is experimental', category=FutureWarning
+        )
+        from cupyx.scipy import signal
+        del signal
+    except ImportError:
+        pass
+
+    try:
+        import jax.numpy  # type: ignore[import-not-found]
+        
+        xp_available_backends.append(
+            pytest.param(jax.numpy, id='jax.numpy',
+            marks=[pytest.mark.array_api_backends,
+                   # Uses xpx.testing.patch_lazy_xp_functions to monkey-patch module
+                   pytest.mark.thread_unsafe]))
+
+        jax.config.update("jax_enable_x64", True)
+        # Make sure JAX won't default to less accurate TensorFloat32 precision
+        # in matmuls with float32 inputs on GPUs that support this floating
+        # point format.
+        jax.config.update("jax_default_matmul_precision", "float32")
+        jax.config.update("jax_default_device", jax.devices(SCIPY_DEVICE)[0])
+        if SCIPY_DEVICE != "cpu":
+            xp_skip_cpu_only_backends.add('jax.numpy')
+        # JAX can be eager or lazy (when wrapped in jax.jit). However it is
+        # recommended by upstream devs to assume it's always lazy.
+        xp_skip_eager_only_backends.add('jax.numpy')
+    except ImportError:
+        pass
+
+    try:
+        import dask.array as da
+
+        xp_available_backends.append(
+            pytest.param(da, id='dask.array',
+            marks=[pytest.mark.array_api_backends,
+                   # Uses xpx.testing.patch_lazy_xp_functions to monkey-patch module
+                   pytest.mark.thread_unsafe]))
+
+        # Dask can wrap around cupy. However, this is untested in scipy
+        # (and will almost surely not work as delegation will misbehave).
+
+        # Dask, strictly speaking, can be eager, in the sense that
+        # __array__, __bool__ etc. are implemented and do not raise.
+        # However, calling them triggers an extra computation of the whole graph
+        # until that point, which is highly destructive for performance.
+        xp_skip_eager_only_backends.add('dask.array')
+    except ImportError:
+        pass
+
+    xp_available_backend_ids = {p.id for p in xp_available_backends}
+    assert not xp_available_backend_ids - xp_known_backends
+
+    # by default, use all available backends
+    if (
+        isinstance(SCIPY_ARRAY_API, str)
+        and SCIPY_ARRAY_API.lower() not in ("1", "true", "all")
+    ):
+        SCIPY_ARRAY_API_ = set(json.loads(SCIPY_ARRAY_API))
+        if SCIPY_ARRAY_API_ != {'all'}:
+            if SCIPY_ARRAY_API_ - xp_available_backend_ids:
+                msg = ("'--array-api-backend' must be in "
+                       f"{xp_available_backend_ids}; got {SCIPY_ARRAY_API_}")
+                raise ValueError(msg)
+            # Only select a subset of backends
+            xp_available_backends = [
+                param for param in xp_available_backends
+                if param.id in SCIPY_ARRAY_API_
+            ]
+
+
+@pytest.fixture(params=xp_available_backends)
+def xp(request):
+    """Run the test that uses this fixture on each available array API library.
+
+    You can select all and only the tests that use the `xp` fixture by
+    passing `-m array_api_backends` to pytest.
+
+    You can select where individual tests run through the `@skip_xp_backends`,
+    `@xfail_xp_backends`, and `@skip_xp_invalid_arg` pytest markers.
+
+    Please read: https://docs.scipy.org/doc/scipy/dev/api-dev/array_api.html#adding-tests
+    """
+    # Read all @pytest.marks.skip_xp_backends markers that decorate to the test,
+    # if any, and raise pytest.skip() if the current xp is in the list.
+    skip_or_xfail_xp_backends(request, "skip")
+    # Read all @pytest.marks.xfail_xp_backends markers that decorate the test,
+    # if any, and raise pytest.xfail() if the current xp is in the list.
+    skip_or_xfail_xp_backends(request, "xfail")
+
+    # Check if ``uses_xp_capabilities`` mark is present.
+    # ``scipy._lib._array_api.make_xp_pytest_marks``, which draws from
+    # ``xp_capabilities``, will set ``pytest.mark.uses_xp_capabilities(True)``.
+    # Tests which are unconverted or which are for private functions without
+    # ``xp_capabilities`` entries should have
+    # ``pytest.mark.uses_xp_capabilities(False)`` explicitly set.
+    if request.node.get_closest_marker("uses_xp_capabilities") is None:
+        warnings.warn(
+            "test uses `xp` fixture without drawing from `xp_capabilities` "
+            " but is not explicitly marked with"
+            " ``pytest.mark.uses_xp_capabilities(False)``",
+            stacklevel=0,
+        )
+
+    xp = request.param
+    # Potentially wrap namespace with array_api_compat
+    xp = array_namespace(xp.empty(0))
+
+    if SCIPY_ARRAY_API:
+        # If xp==jax.numpy, wrap tested functions in jax.jit
+        # If xp==dask.array, wrap tested functions to test that graph is not computed
+        with patch_lazy_xp_functions(request=request, xp=request.param):
+            # Throughout all calls to assert_almost_equal, assert_array_almost_equal,
+            # and xp_assert_* functions, test that the array namespace is xp in both
+            # the expected and actual arrays. This is to detect the case where both
+            # arrays are erroneously just plain numpy while xp is something else.
+            with default_xp(xp):
+                yield xp
+    else:
+        yield xp
+
+
+skip_xp_invalid_arg = pytest.mark.skipif(SCIPY_ARRAY_API,
+    reason = ('Test involves masked arrays, object arrays, or other types '
+              'that are not valid input when `SCIPY_ARRAY_API` is used.'))
+
+
+def _backends_kwargs_from_request(request, skip_or_xfail):
+    """A helper for {skip,xfail}_xp_backends.
+
+    Return dict of {backend to skip/xfail: top reason to skip/xfail it}
+    """
+    markers = list(request.node.iter_markers(f'{skip_or_xfail}_xp_backends'))
+    reasons = {backend: [] for backend in xp_known_backends}
+
+    for marker in markers:
+        invalid_kwargs = set(marker.kwargs) - {
+            "cpu_only", "np_only", "eager_only", "reason", "exceptions"}
+        if invalid_kwargs:
+            raise TypeError(f"Invalid kwargs: {invalid_kwargs}")
+
+        exceptions = set(marker.kwargs.get('exceptions', []))
+        invalid_exceptions = exceptions - xp_known_backends
+        if (invalid_exceptions := list(exceptions - xp_known_backends)):
+            raise ValueError(f"Unknown backend(s): {invalid_exceptions}; "
+                             f"must be a subset of {list(xp_known_backends)}")
+
+        if marker.kwargs.get('np_only', False):
+            reason = marker.kwargs.get("reason") or "do not run with non-NumPy backends"
+            for backend, backend_reasons in reasons.items():
+                if backend != 'numpy' and backend not in exceptions:
+                    backend_reasons.append(reason)
+
+        elif marker.kwargs.get('cpu_only', False):
+            reason = marker.kwargs.get("reason") or (
+                "no array-agnostic implementation or delegation available "
+                "for this backend and device")
+            for backend in xp_skip_cpu_only_backends - exceptions:
+                reasons[backend].append(reason)
+
+        elif marker.kwargs.get('eager_only', False):
+            reason = marker.kwargs.get("reason") or (
+                "eager checks not executed on lazy backends")
+            for backend in xp_skip_eager_only_backends - exceptions:
+                reasons[backend].append(reason)
+
+        # add backends, if any
+        if len(marker.args) == 1:
+            backend = marker.args[0]
+            if backend not in xp_known_backends:
+                raise ValueError(f"Unknown backend: {backend}; "
+                                 f"must be one of {list(xp_known_backends)}")
+            reason = marker.kwargs.get("reason") or (
+                f"do not run with array API backend: {backend}")
+            # reason overrides the ones from cpu_only, np_only, and eager_only.
+            # This is regardless of order of appearence of the markers.
+            reasons[backend].insert(0, reason)
+
+            for kwarg in ("cpu_only", "np_only", "eager_only", "exceptions"):
+                if kwarg in marker.kwargs:
+                    raise ValueError(f"{kwarg} is mutually exclusive with {backend}")
+
+        elif len(marker.args) == 2 and isinstance(marker.args[1], bool | type(None)):
+            # condition is provided:
+            #   1. check it
+            #   2. reason is required (similar to pytest's xfail/skipif)
+            backend, condition = marker.args
+
+            if backend not in xp_known_backends:
+                raise ValueError(f"Unknown backend: {backend}; "
+                                 f"must be one of {list(xp_known_backends)}")
+
+            if condition:
+                reason = marker.kwargs.get("reason")
+                # reason overrides the ones from cpu_only, np_only, and eager_only.
+                # This is regardless of order of appearance of the markers.
+                reasons[backend].insert(0, reason)
+
+            for kwarg in ("cpu_only", "np_only", "eager_only", "exceptions"):
+                if kwarg in marker.kwargs:
+                    raise ValueError(f"{kwarg} is mutually exclusive with {backend}")
+
+        elif len(marker.args) > 1:
+            raise ValueError(
+                f"Please specify only one backend per marker: {marker.args}"
+            )
+
+    return {backend: backend_reasons[0]
+            for backend, backend_reasons in reasons.items()
+            if backend_reasons}
+
+
+def skip_or_xfail_xp_backends(request: pytest.FixtureRequest,
+                              skip_or_xfail: Literal['skip', 'xfail']) -> None:
+    """
+    Helper of the `xp` fixture.
+    Skip or xfail based on the ``skip_xp_backends`` or ``xfail_xp_backends`` markers.
+
+    See the "Support for the array API standard" docs page for usage examples.
+
+    Usage
+    -----
+    ::
+        skip_xp_backends = pytest.mark.skip_xp_backends
+        xfail_xp_backends = pytest.mark.xfail_xp_backends
+        ...
+
+        @skip_xp_backends(backend, *, reason=None)
+        @skip_xp_backends(backend, condition, /, *, reason='skip because condition')
+        @skip_xp_backends(*, cpu_only=True, exceptions=(), reason=None)
+        @skip_xp_backends(*, eager_only=True, exceptions=(), reason=None)
+        @skip_xp_backends(*, np_only=True, exceptions=(), reason=None)
+
+        @xfail_xp_backends(backend, *, reason=None)
+        @xfail_xp_backends(backend, condition, /, *, reason='xfail because condition')
+        @xfail_xp_backends(*, cpu_only=True, exceptions=(), reason=None)
+        @xfail_xp_backends(*, eager_only=True, exceptions=(), reason=None)
+        @xfail_xp_backends(*, np_only=True, exceptions=(), reason=None)
+
+    Parameters
+    ----------
+    backend : str, optional
+        Backend to skip/xfail, e.g. ``"torch"``.
+        Mutually exclusive with ``cpu_only``, ``eager_only``, and ``np_only``.
+    cpu_only : bool, optional
+        When ``True``, the test is skipped/xfailed on non-CPU devices,
+        minus exceptions. Mutually exclusive with ``backend``.
+    eager_only : bool, optional
+        When ``True``, the test is skipped/xfailed for lazy backends, e.g. those
+        with major caveats when invoking ``__array__``, ``__bool__``, ``__float__``,
+        or ``__complex__``, minus exceptions. Mutually exclusive with ``backend``.
+    np_only : bool, optional
+        When ``True``, the test is skipped/xfailed for all backends other
+        than the default NumPy backend and the exceptions.
+        Mutually exclusive with ``backend``. Implies ``cpu_only`` and ``eager_only``.
+    reason : str, optional
+        A reason for the skip/xfail. If omitted, a default reason is used.
+    exceptions : list[str], optional
+        A list of exceptions for use with ``cpu_only``, ``eager_only``, or ``np_only``.
+        This should be provided when delegation is implemented for some,
+        but not all, non-CPU/non-NumPy backends.
+    """
+    if f"{skip_or_xfail}_xp_backends" not in request.keywords:
+        return
+
+    skip_xfail_reasons = _backends_kwargs_from_request(
+        request, skip_or_xfail=skip_or_xfail
+    )
+    xp = request.param
+    if xp.__name__ in skip_xfail_reasons:
+        reason = skip_xfail_reasons[xp.__name__]
+        assert reason  # Default reason applied above
+        skip_or_xfail = getattr(pytest, skip_or_xfail)
+        skip_or_xfail(reason=reason)
+
+
+@pytest.fixture
+def devices(xp):
+    """Fixture that returns a list of all devices for the backend, plus None.
+    Used to test input->output device propagation.
+
+    Usage
+    -----
+    from scipy._lib._array_api import xp_device
+
+    def test_device(xp, devices):
+        for d in devices:
+            x = xp.asarray(..., device=d)
+            y = f(x)
+            assert xp_device(y) == xp_device(x)
+    """
+    if is_cupy(xp):
+        # CuPy does not support devices other than the current one
+        # data-apis/array-api-compat#293
+        pytest.xfail(reason="data-apis/array-api-compat#293")
+    if is_dask(xp):
+        # Skip dummy DASK_DEVICE from array-api-compat, which does not propagate
+        return ["cpu", None]
+    if is_jax(xp):
+        # The .device attribute is not accessible inside jax.jit; the consequence
+        # (downstream of array-api-compat hacks) is that a non-default device in
+        # input is not guaranteed to propagate to the output even if the scipy code
+        # states `device=xp_device(arg)`` in all array creation functions.
+        # While this issue is specific to jax.jit, it would be unnecessarily
+        # verbose to skip the test for each jit-capable function and run it for
+        # those that only support eager mode.
+        pytest.xfail(reason="jax-ml/jax#26000")
+    if is_torch(xp):
+        devices = xp.__array_namespace_info__().devices()
+        # open an issue about this - cannot branch based on `any`/`all`?
+        return (device for device in devices if device.type != 'meta')
+    return tuple(xp.__array_namespace_info__().devices()) + (None,)
+
+
+if hypothesis_available:
+    # Following the approach of NumPy's conftest.py...
+    # Use a known and persistent tmpdir for hypothesis' caches, which
+    # can be automatically cleared by the OS or user.
+    hypothesis.configuration.set_hypothesis_home_dir(  # pyrefly:ignore[unbound-name]
+        os.path.join(tempfile.gettempdir(), ".hypothesis")
+    )
+
+    # We register two custom profiles for SciPy - for details see
+    # https://hypothesis.readthedocs.io/en/latest/settings.html
+    # The first is designed for our own CI runs; the latter also
+    # forces determinism and is designed for use via scipy.test()
+    hypothesis.settings.register_profile(
+        name="nondeterministic", deadline=None, print_blob=True,
+    )
+    hypothesis.settings.register_profile(
+        name="deterministic",
+        deadline=None, print_blob=True, database=None, derandomize=True,
+        suppress_health_check=list(hypothesis.HealthCheck),
+    )
+
+    # Profile is currently set by environment variable `SCIPY_HYPOTHESIS_PROFILE`
+    # In the future, it would be good to work the choice into `.spin/cmds.py`.
+    SCIPY_HYPOTHESIS_PROFILE = os.environ.get("SCIPY_HYPOTHESIS_PROFILE",
+                                              "deterministic")
+    hypothesis.settings.load_profile(SCIPY_HYPOTHESIS_PROFILE)
+
+
+############################################################################
+# doctesting stuff
+
+if HAVE_SCPDT:
+
+    # FIXME: populate the dict once
+    @contextmanager
+    def warnings_errors_and_rng(test=None):
+        """Temporarily turn (almost) all warnings to errors.
+
+        Filter out known warnings which we allow.
+        """
+        known_warnings = dict()
+
+        # these functions are known to emit "divide by zero" RuntimeWarnings
+        divide_by_zero = [
+            'scipy.linalg.norm', 'scipy.ndimage.center_of_mass',
+        ]
+        for name in divide_by_zero:
+            known_warnings[name] = dict(category=RuntimeWarning,
+                                        message='divide by zero')
+
+        # Deprecated stuff
+        deprecated = []
+        for name in deprecated:
+            known_warnings[name] = dict(category=DeprecationWarning)
+
+        from scipy import integrate
+        # the functions are known to emit IntegrationWarnings
+        integration_w = ['scipy.special.ellip_normal',
+                         'scipy.special.ellip_harm_2',
+        ]
+        for name in integration_w:
+            known_warnings[name] = dict(category=integrate.IntegrationWarning,
+                                        message='The occurrence of roundoff')
+
+        # scipy.stats deliberately emits UserWarnings sometimes
+        user_w = ['scipy.stats.anderson_ksamp', 'scipy.stats.kurtosistest',
+                  'scipy.stats.normaltest', 'scipy.sparse.linalg.norm']
+        for name in user_w:
+            known_warnings[name] = dict(category=UserWarning)
+
+        # additional one-off warnings to filter
+        dct = {
+            'scipy.sparse.linalg.norm':
+                dict(category=UserWarning, message="Exited at iteration"),
+            # tutorials
+            'linalg.rst':
+                dict(message='the matrix subclass is not',
+                     category=PendingDeprecationWarning),
+            'stats.rst':
+                dict(message='The maximum number of subdivisions',
+                     category=integrate.IntegrationWarning),
+        }
+        known_warnings.update(dct)
+
+        # these legitimately emit warnings in examples
+        legit = set('scipy.signal.normalize')
+
+        # Now, the meat of the matter: filter warnings,
+        # also control the random seed for each doctest.
+
+        # XXX: this matches the refguide-check behavior, but is a tad strange:
+        # makes sure that the seed the old-fashioned np.random* methods is
+        # *NOT* reproducible but the new-style `default_rng()` *IS* repoducible.
+        # Should these two be either both repro or both not repro?
+
+        from scipy._lib._util import _fixed_default_rng
+        import numpy as np
+        with _fixed_default_rng():
+            np.random.seed(None)
+            with warnings.catch_warnings():
+                if test and test.name in known_warnings:
+                    warnings.filterwarnings('ignore', **known_warnings[test.name])
+                    yield
+                elif test and test.name in legit:
+                    yield
+                else:
+                    warnings.simplefilter('error', Warning)
+                    warnings.filterwarnings('ignore', ".*odr.*", DeprecationWarning)
+                    yield
+
+    dt_config.user_context_mgr = warnings_errors_and_rng  # pyrefly:ignore[unbound-name]
+    dt_config.skiplist = set([
+        'scipy.linalg.LinAlgError',     # comes from numpy
+        'scipy.fftpack.fftshift',       # fftpack stuff is also from numpy
+        'scipy.fftpack.ifftshift',
+        'scipy.fftpack.fftfreq',
+        'scipy.special.sinc',           # sinc is from numpy
+        'scipy.optimize.show_options',  # does not have much to doctest
+        'scipy.signal.normalize',       # manipulates warnings (XXX temp skip)
+        'scipy.sparse.linalg.norm',     # XXX temp skip
+        # these below test things which inherit from np.ndarray
+        # cross-ref https://github.com/numpy/numpy/issues/28019
+        'scipy.io.matlab.MatlabObject.strides',
+        'scipy.io.matlab.MatlabObject.dtype',
+        'scipy.io.matlab.MatlabOpaque.dtype',
+        'scipy.io.matlab.MatlabOpaque.strides',
+        'scipy.io.matlab.MatlabFunction.strides',
+        'scipy.io.matlab.MatlabFunction.dtype',
+        # deprecated
+        'scipy.interpolate.lagrange',
+        'scipy.interpolate.approximate_taylor_polynomial',
+        'scipy.interpolate.pade',
+        'scipy.spatial.tsearch',
+        'scipy.spatial.minkowski_distance_p',
+        'scipy.spatial.minkowski_distance',
+        'scipy.spatial.distance_matrix',
+    ])
+
+    # help pytest collection a bit: these names are either private
+    # (distributions), or just do not need doctesting.
+    dt_config.pytest_extra_ignore = [
+        "scipy.stats.distributions",
+        "scipy.optimize.cython_optimize",
+        "scipy.test",
+        "scipy.show_config",
+        # equivalent to "pytest --ignore=path/to/file"
+        "scipy/special/_precompute",
+        "scipy/interpolate/_interpnd_info.py",
+        "scipy/interpolate/_rbfinterp_pythran.py",
+        "scipy/_build_utils/tempita.py",
+        "scipy/_external",
+        "scipy/_lib/array_api_compat",
+        "scipy/_lib/highs",
+        "scipy/_lib/unuran",
+        "scipy/_lib/_gcutils.py",
+        "scipy/_lib/doccer.py",
+        "scipy/_lib/_uarray",
+        "scipy/linalg/_cython_signature_generator.py",
+        "scipy/linalg/_generate_pyx.py",
+        "scipy/linalg/_linalg_pythran.py",
+        "scipy/linalg/_matfuncs_sqrtm_triu.py",
+        "scipy/ndimage/utils/generate_label_testvectors.py",
+        "scipy/optimize/_group_columns.py",
+        "scipy/optimize/_max_len_seq_inner.py",
+        "scipy/signal/_max_len_seq_inner.py",
+        "scipy/sparse/_generate_sparsetools.py",
+        "scipy/special/_generate_pyx.py",
+        "scipy/stats/_stats_pythran.py",
+    ]
+
+    dt_config.pytest_extra_xfail = {
+        # name: reason
+        "ND_regular_grid.rst": "ReST parser limitation",
+        "extrapolation_examples.rst": "ReST parser limitation",
+        "sampling_pinv.rst": "__cinit__ unexpected argument",
+        "sampling_srou.rst": "nan in scalar_power",
+        "probability_distributions.rst": "integration warning",
+    }
+
+    # tutorials
+    dt_config.pseudocode = set(['integrate.nquad(func,'])
+    dt_config.local_resources = {
+        'io.rst': [
+            "octave_a.mat",
+            "octave_cells.mat",
+            "octave_struct.mat"
+        ]
+    }
+
+    dt_config.strict_check = True
+
+    # ignore Matplotlib's `ax.text`:
+    dt_config.stopwords.add('.text(')
+############################################################################
diff --git a/.venv/lib/python3.12/site-packages/scipy/constants/__init__.py b/.venv/lib/python3.12/site-packages/scipy/constants/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..5973652389600c29f09c9813266224e1dbe0ef94
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/constants/__init__.py
@@ -0,0 +1,357 @@
+r"""
+==================================
+Constants (:mod:`scipy.constants`)
+==================================
+
+.. currentmodule:: scipy.constants
+
+Physical and mathematical constants and units.
+
+
+Mathematical constants
+======================
+
+================  =================================================================
+``pi``            Pi
+``golden``        Golden ratio
+``golden_ratio``  Golden ratio
+================  =================================================================
+
+
+Physical constants
+==================
+The following physical constants are available as attributes of `scipy.constants`.
+All units are `SI `_.
+
+===========================  ================================================================  ===============
+Attribute                    Quantity                                                          Units
+===========================  ================================================================  ===============
+``c``                        speed of light in vacuum                                          m s^-1
+``speed_of_light``           speed of light in vacuum                                          m s^-1
+``mu_0``                     the magnetic constant :math:`\mu_0`                               N A^-2
+``epsilon_0``                the electric constant (vacuum permittivity), :math:`\epsilon_0`   F m^-1
+``h``                        the Planck constant :math:`h`                                     J Hz^-1
+``Planck``                   the Planck constant :math:`h`                                     J Hz^-1
+``hbar``                     the reduced Planck constant, :math:`\hbar = h/(2\pi)`             J s
+``G``                        Newtonian constant of gravitation                                 m^3 kg^-1 s^-2
+``gravitational_constant``   Newtonian constant of gravitation                                 m^3 kg^-1 s^-2
+``g``                        standard acceleration of gravity                                  m s^-2
+``e``                        elementary charge                                                 C
+``elementary_charge``        elementary charge                                                 C
+``R``                        molar gas constant                                                J mol^-1 K^-1
+``gas_constant``             molar gas constant                                                J mol^-1 K^-1
+``alpha``                    fine-structure constant                                           (unitless)
+``fine_structure``           fine-structure constant                                           (unitless)
+``N_A``                      Avogadro constant                                                 mol^-1
+``Avogadro``                 Avogadro constant                                                 mol^-1
+``k``                        Boltzmann constant                                                J K^-1
+``Boltzmann``                Boltzmann constant                                                J K^-1
+``sigma``                    Stefan-Boltzmann constant :math:`\sigma`                          W m^-2 K^-4
+``Stefan_Boltzmann``         Stefan-Boltzmann constant :math:`\sigma`                          W m^-2 K^-4
+``Wien``                     Wien wavelength displacement law constant                         m K
+``Rydberg``                  Rydberg constant                                                  m^-1
+``m_e``                      electron mass                                                     kg
+``electron_mass``            electron mass                                                     kg
+``m_p``                      proton mass                                                       kg
+``proton_mass``              proton mass                                                       kg
+``m_n``                      neutron mass                                                      kg
+``neutron_mass``             neutron mass                                                      kg
+===========================  ================================================================  ===============
+
+
+Constants database
+------------------
+
+In addition to the above variables, :mod:`scipy.constants` also contains the
+2022 CODATA recommended values [CODATA2022]_ database containing more physical
+constants.
+
+.. autosummary::
+   :toctree: generated/
+
+   value      -- Value in physical_constants indexed by key
+   unit       -- Unit in physical_constants indexed by key
+   precision  -- Relative precision in physical_constants indexed by key
+   find       -- Return list of physical_constant keys with a given string
+   ConstantWarning -- Constant sought not in newest CODATA data set
+
+.. data:: physical_constants
+
+   Dictionary of physical constants, of the format
+   ``physical_constants[name] = (value, unit, uncertainty)``.
+   The CODATA database uses ellipses to indicate that a value is defined
+   (exactly) in terms of others but cannot be represented exactly with the
+   allocated number of digits. In these cases, SciPy calculates the derived
+   value and reports it to the full precision of a Python ``float``. Although 
+   ``physical_constants`` lists the uncertainty as ``0.0`` to indicate that
+   the CODATA value is exact, the value in ``physical_constants`` is still
+   subject to the truncation error inherent in double-precision representation.
+
+Available constants:
+
+======================================================================  ====
+%(constant_names)s
+======================================================================  ====
+
+
+Units
+=====
+
+SI prefixes
+-----------
+
+============  =================================================================
+``quetta``    :math:`10^{30}`
+``ronna``     :math:`10^{27}`
+``yotta``     :math:`10^{24}`
+``zetta``     :math:`10^{21}`
+``exa``       :math:`10^{18}`
+``peta``      :math:`10^{15}`
+``tera``      :math:`10^{12}`
+``giga``      :math:`10^{9}`
+``mega``      :math:`10^{6}`
+``kilo``      :math:`10^{3}`
+``hecto``     :math:`10^{2}`
+``deka``      :math:`10^{1}`
+``deci``      :math:`10^{-1}`
+``centi``     :math:`10^{-2}`
+``milli``     :math:`10^{-3}`
+``micro``     :math:`10^{-6}`
+``nano``      :math:`10^{-9}`
+``pico``      :math:`10^{-12}`
+``femto``     :math:`10^{-15}`
+``atto``      :math:`10^{-18}`
+``zepto``     :math:`10^{-21}`
+``yocto``     :math:`10^{-24}`
+``ronto``     :math:`10^{-27}`
+``quecto``    :math:`10^{-30}`
+============  =================================================================
+
+Binary prefixes
+---------------
+
+============  =================================================================
+``kibi``      :math:`2^{10}`
+``mebi``      :math:`2^{20}`
+``gibi``      :math:`2^{30}`
+``tebi``      :math:`2^{40}`
+``pebi``      :math:`2^{50}`
+``exbi``      :math:`2^{60}`
+``zebi``      :math:`2^{70}`
+``yobi``      :math:`2^{80}`
+============  =================================================================
+
+Mass
+----
+
+=================  ============================================================
+``gram``           :math:`10^{-3}` kg
+``metric_ton``     :math:`10^{3}` kg
+``grain``          one grain in kg
+``lb``             one pound (avoirdupous) in kg
+``pound``          one pound (avoirdupous) in kg
+``blob``           one inch version of a slug in kg (added in 1.0.0)
+``slinch``         one inch version of a slug in kg (added in 1.0.0)
+``slug``           one slug in kg (added in 1.0.0)
+``oz``             one ounce in kg
+``ounce``          one ounce in kg
+``stone``          one stone in kg
+``long_ton``       one long ton in kg
+``short_ton``      one short ton in kg
+``troy_ounce``     one Troy ounce in kg
+``troy_pound``     one Troy pound in kg
+``carat``          one carat in kg
+``m_u``            atomic mass constant (in kg)
+``u``              atomic mass constant (in kg)
+``atomic_mass``    atomic mass constant (in kg)
+=================  ============================================================
+
+Angle
+-----
+
+=================  ============================================================
+``degree``         degree in radians
+``arcmin``         arc minute in radians
+``arcminute``      arc minute in radians
+``arcsec``         arc second in radians
+``arcsecond``      arc second in radians
+=================  ============================================================
+
+
+Time
+----
+
+=================  ============================================================
+``minute``         one minute in seconds
+``hour``           one hour in seconds
+``day``            one day in seconds
+``week``           one week in seconds
+``year``           one year (365 days) in seconds
+``Julian_year``    one Julian year (365.25 days) in seconds
+=================  ============================================================
+
+
+Length
+------
+
+=====================  ============================================================
+``inch``               one inch in meters
+``foot``               one foot in meters
+``yard``               one yard in meters
+``mile``               one mile in meters
+``mil``                one mil in meters
+``pt``                 one point in meters
+``point``              one point in meters
+``survey_foot``        one survey foot in meters
+``survey_mile``        one survey mile in meters
+``nautical_mile``      one nautical mile in meters
+``fermi``              one Fermi in meters
+``angstrom``           one Angstrom in meters
+``micron``             one micron in meters
+``au``                 one astronomical unit in meters
+``astronomical_unit``  one astronomical unit in meters
+``light_year``         one light year in meters
+``parsec``             one parsec in meters
+=====================  ============================================================
+
+Pressure
+--------
+
+=================  ============================================================
+``atm``            standard atmosphere in pascals
+``atmosphere``     standard atmosphere in pascals
+``bar``            one bar in pascals
+``torr``           one torr (mmHg) in pascals
+``mmHg``           one torr (mmHg) in pascals
+``psi``            one psi in pascals
+=================  ============================================================
+
+Area
+----
+
+=================  ============================================================
+``hectare``        one hectare in square meters
+``acre``           one acre in square meters
+=================  ============================================================
+
+
+Volume
+------
+
+===================    ========================================================
+``liter``              one liter in cubic meters
+``litre``              one liter in cubic meters
+``gallon``             one gallon (US) in cubic meters
+``gallon_US``          one gallon (US) in cubic meters
+``gallon_imp``         one gallon (UK) in cubic meters
+``fluid_ounce``        one fluid ounce (US) in cubic meters
+``fluid_ounce_US``     one fluid ounce (US) in cubic meters
+``fluid_ounce_imp``    one fluid ounce (UK) in cubic meters
+``bbl``                one barrel in cubic meters
+``barrel``             one barrel in cubic meters
+===================    ========================================================
+
+Speed
+-----
+
+==================    ==========================================================
+``kmh``               kilometers per hour in meters per second
+``mph``               miles per hour in meters per second
+``mach``              one Mach (approx., at 15 C, 1 atm) in meters per second
+``speed_of_sound``    one Mach (approx., at 15 C, 1 atm) in meters per second
+``knot``              one knot in meters per second
+==================    ==========================================================
+
+
+Temperature
+-----------
+
+=====================  =======================================================
+``zero_Celsius``       zero of Celsius scale in Kelvin
+``degree_Fahrenheit``  one Fahrenheit (only differences) in Kelvins
+=====================  =======================================================
+
+.. autosummary::
+   :toctree: generated/
+
+   convert_temperature
+
+Energy
+------
+
+====================  =======================================================
+``eV``                one electron volt in Joules
+``electron_volt``     one electron volt in Joules
+``calorie``           one calorie (thermochemical) in Joules
+``calorie_th``        one calorie (thermochemical) in Joules
+``calorie_IT``        one calorie (International Steam Table calorie, 1956) in Joules
+``erg``               one erg in Joules
+``Btu``               one British thermal unit (International Steam Table) in Joules
+``Btu_IT``            one British thermal unit (International Steam Table) in Joules
+``Btu_th``            one British thermal unit (thermochemical) in Joules
+``ton_TNT``           one ton of TNT in Joules
+====================  =======================================================
+
+Power
+-----
+
+====================  =======================================================
+``hp``                one horsepower in watts
+``horsepower``        one horsepower in watts
+====================  =======================================================
+
+Force
+-----
+
+====================  =======================================================
+``dyn``               one dyne in newtons
+``dyne``              one dyne in newtons
+``lbf``               one pound force in newtons
+``pound_force``       one pound force in newtons
+``kgf``               one kilogram force in newtons
+``kilogram_force``    one kilogram force in newtons
+====================  =======================================================
+
+Optics
+------
+
+.. autosummary::
+   :toctree: generated/
+
+   lambda2nu
+   nu2lambda
+
+References
+==========
+
+.. [CODATA2022] CODATA Recommended Values of the Fundamental
+   Physical Constants 2022.
+
+   https://physics.nist.gov/cuu/Constants/
+
+"""  # noqa: E501
+# Modules contributed by BasSw (wegwerp@gmail.com)
+from ._codata import *
+from ._constants import *
+from ._codata import _obsolete_constants, physical_constants
+
+# Deprecated namespaces, to be removed in v2.0.0
+from . import codata, constants
+
+_constant_names_list = [(_k.lower(), _k, _v)
+                        for _k, _v in physical_constants.items()
+                        if _k not in _obsolete_constants]
+_constant_names = "\n".join(["``{}``{}  {} {}".format(_x[1], " "*(66-len(_x[1])),
+                                                  _x[2][0], _x[2][1])
+                             for _x in sorted(_constant_names_list)])
+if __doc__:
+    __doc__ = __doc__ % dict(constant_names=_constant_names)
+
+del _constant_names
+del _constant_names_list
+
+__all__ = [s for s in dir() if not s.startswith('_')]
+
+from scipy._lib._testutils import PytestTester
+test = PytestTester(__name__)
+del PytestTester
diff --git a/.venv/lib/python3.12/site-packages/scipy/constants/_codata.py b/.venv/lib/python3.12/site-packages/scipy/constants/_codata.py
new file mode 100644
index 0000000000000000000000000000000000000000..d02d5bc7cb3ad96b428337f8ecc3ac5244ccf86b
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/constants/_codata.py
@@ -0,0 +1,2272 @@
+"""
+Fundamental Physical Constants
+------------------------------
+
+These constants are taken from CODATA Recommended Values of the Fundamental
+Physical Constants 2022.
+
+Object
+------
+physical_constants : dict
+    A dictionary containing physical constants. Keys are the names of physical
+    constants, values are tuples (value, units, precision).
+
+Functions
+---------
+value(key):
+    Returns the value of the physical constant(key).
+unit(key):
+    Returns the units of the physical constant(key).
+precision(key):
+    Returns the relative precision of the physical constant(key).
+find(sub):
+    Prints or returns list of keys containing the string sub, default is all.
+
+Source
+------
+The values of the constants provided at this site are recommended for
+international use by CODATA and are the latest available. Termed the "2018
+CODATA recommended values," they are generally recognized worldwide for use in
+all fields of science and technology. The values became available on 20 May
+2019 and replaced the 2014 CODATA set. Also available is an introduction to the
+constants for non-experts at
+
+https://physics.nist.gov/cuu/Constants/introduction.html
+
+References
+----------
+Theoretical and experimental publications relevant to the fundamental constants
+and closely related precision measurements published since the mid 1980s, but
+also including many older papers of particular interest, some of which date
+back to the 1800s. To search the bibliography, visit
+
+https://physics.nist.gov/cuu/Constants/
+
+"""
+
+# Compiled by Charles Harris, dated October 3, 2002
+# updated to 2002 values by BasSw, 2006
+# Updated to 2006 values by Vincent Davis June 2010
+# Updated to 2014 values by Joseph Booker, 2015
+# Updated to 2018 values by Jakob Jakobson, 2019
+# Updated to 2022 values by Jakob Jakobson, 2024
+
+import warnings
+import math
+
+from typing import Any
+from collections.abc import Callable
+
+from scipy._lib._array_api import xp_capabilities
+
+__all__ = ['physical_constants', 'value', 'unit', 'precision', 'find',
+           'ConstantWarning']
+
+"""
+Source:  https://physics.nist.gov/cuu/Constants/
+
+The values of the constants provided at this site are recommended for
+international use by CODATA and are the latest available. Termed the "2018
+CODATA recommended values," they are generally recognized worldwide for use in
+all fields of science and technology. The values became available on 20 May
+2019 and replaced the 2014 CODATA set.
+"""
+
+#
+# Source:  https://physics.nist.gov/cuu/Constants/
+#
+
+# Quantity                                             Value                 Uncertainty          Unit
+# ---------------------------------------------------- --------------------- -------------------- -------------
+txt2002 = """\
+Wien displacement law constant                         2.897 7685e-3         0.000 0051e-3         m K
+atomic unit of 1st hyperpolarizablity                  3.206 361 51e-53      0.000 000 28e-53      C^3 m^3 J^-2
+atomic unit of 2nd hyperpolarizablity                  6.235 3808e-65        0.000 0011e-65        C^4 m^4 J^-3
+atomic unit of electric dipole moment                  8.478 353 09e-30      0.000 000 73e-30      C m
+atomic unit of electric polarizablity                  1.648 777 274e-41     0.000 000 016e-41     C^2 m^2 J^-1
+atomic unit of electric quadrupole moment              4.486 551 24e-40      0.000 000 39e-40      C m^2
+atomic unit of magn. dipole moment                     1.854 801 90e-23      0.000 000 16e-23      J T^-1
+atomic unit of magn. flux density                      2.350 517 42e5        0.000 000 20e5        T
+deuteron magn. moment                                  0.433 073 482e-26     0.000 000 038e-26     J T^-1
+deuteron magn. moment to Bohr magneton ratio           0.466 975 4567e-3     0.000 000 0050e-3
+deuteron magn. moment to nuclear magneton ratio        0.857 438 2329        0.000 000 0092
+deuteron-electron magn. moment ratio                   -4.664 345 548e-4     0.000 000 050e-4
+deuteron-proton magn. moment ratio                     0.307 012 2084        0.000 000 0045
+deuteron-neutron magn. moment ratio                    -0.448 206 52         0.000 000 11
+electron gyromagn. ratio                               1.760 859 74e11       0.000 000 15e11       s^-1 T^-1
+electron gyromagn. ratio over 2 pi                     28 024.9532           0.0024                MHz T^-1
+electron magn. moment                                  -928.476 412e-26      0.000 080e-26         J T^-1
+electron magn. moment to Bohr magneton ratio           -1.001 159 652 1859   0.000 000 000 0038
+electron magn. moment to nuclear magneton ratio        -1838.281 971 07      0.000 000 85
+electron magn. moment anomaly                          1.159 652 1859e-3     0.000 000 0038e-3
+electron to shielded proton magn. moment ratio         -658.227 5956         0.000 0071
+electron to shielded helion magn. moment ratio         864.058 255           0.000 010
+electron-deuteron magn. moment ratio                   -2143.923 493         0.000 023
+electron-muon magn. moment ratio                       206.766 9894          0.000 0054
+electron-neutron magn. moment ratio                    960.920 50            0.000 23
+electron-proton magn. moment ratio                     -658.210 6862         0.000 0066
+magn. constant                                         12.566 370 614...e-7  (exact)               N A^-2
+magn. flux quantum                                     2.067 833 72e-15      0.000 000 18e-15      Wb
+muon magn. moment                                      -4.490 447 99e-26     0.000 000 40e-26      J T^-1
+muon magn. moment to Bohr magneton ratio               -4.841 970 45e-3      0.000 000 13e-3
+muon magn. moment to nuclear magneton ratio            -8.890 596 98         0.000 000 23
+muon-proton magn. moment ratio                         -3.183 345 118        0.000 000 089
+neutron gyromagn. ratio                                1.832 471 83e8        0.000 000 46e8        s^-1 T^-1
+neutron gyromagn. ratio over 2 pi                      29.164 6950           0.000 0073            MHz T^-1
+neutron magn. moment                                   -0.966 236 45e-26     0.000 000 24e-26      J T^-1
+neutron magn. moment to Bohr magneton ratio            -1.041 875 63e-3      0.000 000 25e-3
+neutron magn. moment to nuclear magneton ratio         -1.913 042 73         0.000 000 45
+neutron to shielded proton magn. moment ratio          -0.684 996 94         0.000 000 16
+neutron-electron magn. moment ratio                    1.040 668 82e-3       0.000 000 25e-3
+neutron-proton magn. moment ratio                      -0.684 979 34         0.000 000 16
+proton gyromagn. ratio                                 2.675 222 05e8        0.000 000 23e8        s^-1 T^-1
+proton gyromagn. ratio over 2 pi                       42.577 4813           0.000 0037            MHz T^-1
+proton magn. moment                                    1.410 606 71e-26      0.000 000 12e-26      J T^-1
+proton magn. moment to Bohr magneton ratio             1.521 032 206e-3      0.000 000 015e-3
+proton magn. moment to nuclear magneton ratio          2.792 847 351         0.000 000 028
+proton magn. shielding correction                      25.689e-6             0.015e-6
+proton-neutron magn. moment ratio                      -1.459 898 05         0.000 000 34
+shielded helion gyromagn. ratio                        2.037 894 70e8        0.000 000 18e8        s^-1 T^-1
+shielded helion gyromagn. ratio over 2 pi              32.434 1015           0.000 0028            MHz T^-1
+shielded helion magn. moment                           -1.074 553 024e-26    0.000 000 093e-26     J T^-1
+shielded helion magn. moment to Bohr magneton ratio    -1.158 671 474e-3     0.000 000 014e-3
+shielded helion magn. moment to nuclear magneton ratio -2.127 497 723        0.000 000 025
+shielded helion to proton magn. moment ratio           -0.761 766 562        0.000 000 012
+shielded helion to shielded proton magn. moment ratio  -0.761 786 1313       0.000 000 0033
+shielded helion gyromagn. ratio                        2.037 894 70e8        0.000 000 18e8        s^-1 T^-1
+shielded helion gyromagn. ratio over 2 pi              32.434 1015           0.000 0028            MHz T^-1
+shielded proton magn. moment                           1.410 570 47e-26      0.000 000 12e-26      J T^-1
+shielded proton magn. moment to Bohr magneton ratio    1.520 993 132e-3      0.000 000 016e-3
+shielded proton magn. moment to nuclear magneton ratio 2.792 775 604         0.000 000 030
+{220} lattice spacing of silicon                       192.015 5965e-12      0.000 0070e-12        m"""
+
+
+def exact2002(exact):
+    replace = {
+        'magn. constant': 4e-7 * math.pi,
+    }
+    return replace
+
+
+txt2006 = """\
+lattice spacing of silicon                             192.015 5762 e-12     0.000 0050 e-12       m
+alpha particle-electron mass ratio                     7294.299 5365         0.000 0031
+alpha particle mass                                    6.644 656 20 e-27     0.000 000 33 e-27     kg
+alpha particle mass energy equivalent                  5.971 919 17 e-10     0.000 000 30 e-10     J
+alpha particle mass energy equivalent in MeV           3727.379 109          0.000 093             MeV
+alpha particle mass in u                               4.001 506 179 127     0.000 000 000 062     u
+alpha particle molar mass                              4.001 506 179 127 e-3 0.000 000 000 062 e-3 kg mol^-1
+alpha particle-proton mass ratio                       3.972 599 689 51      0.000 000 000 41
+Angstrom star                                          1.000 014 98 e-10     0.000 000 90 e-10     m
+atomic mass constant                                   1.660 538 782 e-27    0.000 000 083 e-27    kg
+atomic mass constant energy equivalent                 1.492 417 830 e-10    0.000 000 074 e-10    J
+atomic mass constant energy equivalent in MeV          931.494 028           0.000 023             MeV
+atomic mass unit-electron volt relationship            931.494 028 e6        0.000 023 e6          eV
+atomic mass unit-hartree relationship                  3.423 177 7149 e7     0.000 000 0049 e7     E_h
+atomic mass unit-hertz relationship                    2.252 342 7369 e23    0.000 000 0032 e23    Hz
+atomic mass unit-inverse meter relationship            7.513 006 671 e14     0.000 000 011 e14     m^-1
+atomic mass unit-joule relationship                    1.492 417 830 e-10    0.000 000 074 e-10    J
+atomic mass unit-kelvin relationship                   1.080 9527 e13        0.000 0019 e13        K
+atomic mass unit-kilogram relationship                 1.660 538 782 e-27    0.000 000 083 e-27    kg
+atomic unit of 1st hyperpolarizability                 3.206 361 533 e-53    0.000 000 081 e-53    C^3 m^3 J^-2
+atomic unit of 2nd hyperpolarizability                 6.235 380 95 e-65     0.000 000 31 e-65     C^4 m^4 J^-3
+atomic unit of action                                  1.054 571 628 e-34    0.000 000 053 e-34    J s
+atomic unit of charge                                  1.602 176 487 e-19    0.000 000 040 e-19    C
+atomic unit of charge density                          1.081 202 300 e12     0.000 000 027 e12     C m^-3
+atomic unit of current                                 6.623 617 63 e-3      0.000 000 17 e-3      A
+atomic unit of electric dipole mom.                    8.478 352 81 e-30     0.000 000 21 e-30     C m
+atomic unit of electric field                          5.142 206 32 e11      0.000 000 13 e11      V m^-1
+atomic unit of electric field gradient                 9.717 361 66 e21      0.000 000 24 e21      V m^-2
+atomic unit of electric polarizability                 1.648 777 2536 e-41   0.000 000 0034 e-41   C^2 m^2 J^-1
+atomic unit of electric potential                      27.211 383 86         0.000 000 68          V
+atomic unit of electric quadrupole mom.                4.486 551 07 e-40     0.000 000 11 e-40     C m^2
+atomic unit of energy                                  4.359 743 94 e-18     0.000 000 22 e-18     J
+atomic unit of force                                   8.238 722 06 e-8      0.000 000 41 e-8      N
+atomic unit of length                                  0.529 177 208 59 e-10 0.000 000 000 36 e-10 m
+atomic unit of mag. dipole mom.                        1.854 801 830 e-23    0.000 000 046 e-23    J T^-1
+atomic unit of mag. flux density                       2.350 517 382 e5      0.000 000 059 e5      T
+atomic unit of magnetizability                         7.891 036 433 e-29    0.000 000 027 e-29    J T^-2
+atomic unit of mass                                    9.109 382 15 e-31     0.000 000 45 e-31     kg
+atomic unit of momentum                                1.992 851 565 e-24    0.000 000 099 e-24    kg m s^-1
+atomic unit of permittivity                            1.112 650 056... e-10 (exact)               F m^-1
+atomic unit of time                                    2.418 884 326 505 e-17 0.000 000 000 016 e-17 s
+atomic unit of velocity                                2.187 691 2541 e6     0.000 000 0015 e6     m s^-1
+Avogadro constant                                      6.022 141 79 e23      0.000 000 30 e23      mol^-1
+Bohr magneton                                          927.400 915 e-26      0.000 023 e-26        J T^-1
+Bohr magneton in eV/T                                  5.788 381 7555 e-5    0.000 000 0079 e-5    eV T^-1
+Bohr magneton in Hz/T                                  13.996 246 04 e9      0.000 000 35 e9       Hz T^-1
+Bohr magneton in inverse meters per tesla              46.686 4515           0.000 0012            m^-1 T^-1
+Bohr magneton in K/T                                   0.671 7131            0.000 0012            K T^-1
+Bohr radius                                            0.529 177 208 59 e-10 0.000 000 000 36 e-10 m
+Boltzmann constant                                     1.380 6504 e-23       0.000 0024 e-23       J K^-1
+Boltzmann constant in eV/K                             8.617 343 e-5         0.000 015 e-5         eV K^-1
+Boltzmann constant in Hz/K                             2.083 6644 e10        0.000 0036 e10        Hz K^-1
+Boltzmann constant in inverse meters per kelvin        69.503 56             0.000 12              m^-1 K^-1
+characteristic impedance of vacuum                     376.730 313 461...    (exact)               ohm
+classical electron radius                              2.817 940 2894 e-15   0.000 000 0058 e-15   m
+Compton wavelength                                     2.426 310 2175 e-12   0.000 000 0033 e-12   m
+Compton wavelength over 2 pi                           386.159 264 59 e-15   0.000 000 53 e-15     m
+conductance quantum                                    7.748 091 7004 e-5    0.000 000 0053 e-5    S
+conventional value of Josephson constant               483 597.9 e9          (exact)               Hz V^-1
+conventional value of von Klitzing constant            25 812.807            (exact)               ohm
+Cu x unit                                              1.002 076 99 e-13     0.000 000 28 e-13     m
+deuteron-electron mag. mom. ratio                      -4.664 345 537 e-4    0.000 000 039 e-4
+deuteron-electron mass ratio                           3670.482 9654         0.000 0016
+deuteron g factor                                      0.857 438 2308        0.000 000 0072
+deuteron mag. mom.                                     0.433 073 465 e-26    0.000 000 011 e-26    J T^-1
+deuteron mag. mom. to Bohr magneton ratio              0.466 975 4556 e-3    0.000 000 0039 e-3
+deuteron mag. mom. to nuclear magneton ratio           0.857 438 2308        0.000 000 0072
+deuteron mass                                          3.343 583 20 e-27     0.000 000 17 e-27     kg
+deuteron mass energy equivalent                        3.005 062 72 e-10     0.000 000 15 e-10     J
+deuteron mass energy equivalent in MeV                 1875.612 793          0.000 047             MeV
+deuteron mass in u                                     2.013 553 212 724     0.000 000 000 078     u
+deuteron molar mass                                    2.013 553 212 724 e-3 0.000 000 000 078 e-3 kg mol^-1
+deuteron-neutron mag. mom. ratio                       -0.448 206 52         0.000 000 11
+deuteron-proton mag. mom. ratio                        0.307 012 2070        0.000 000 0024
+deuteron-proton mass ratio                             1.999 007 501 08      0.000 000 000 22
+deuteron rms charge radius                             2.1402 e-15           0.0028 e-15           m
+electric constant                                      8.854 187 817... e-12 (exact)               F m^-1
+electron charge to mass quotient                       -1.758 820 150 e11    0.000 000 044 e11     C kg^-1
+electron-deuteron mag. mom. ratio                      -2143.923 498         0.000 018
+electron-deuteron mass ratio                           2.724 437 1093 e-4    0.000 000 0012 e-4
+electron g factor                                      -2.002 319 304 3622   0.000 000 000 0015
+electron gyromag. ratio                                1.760 859 770 e11     0.000 000 044 e11     s^-1 T^-1
+electron gyromag. ratio over 2 pi                      28 024.953 64         0.000 70              MHz T^-1
+electron mag. mom.                                     -928.476 377 e-26     0.000 023 e-26        J T^-1
+electron mag. mom. anomaly                             1.159 652 181 11 e-3  0.000 000 000 74 e-3
+electron mag. mom. to Bohr magneton ratio              -1.001 159 652 181 11 0.000 000 000 000 74
+electron mag. mom. to nuclear magneton ratio           -1838.281 970 92      0.000 000 80
+electron mass                                          9.109 382 15 e-31     0.000 000 45 e-31     kg
+electron mass energy equivalent                        8.187 104 38 e-14     0.000 000 41 e-14     J
+electron mass energy equivalent in MeV                 0.510 998 910         0.000 000 013         MeV
+electron mass in u                                     5.485 799 0943 e-4    0.000 000 0023 e-4    u
+electron molar mass                                    5.485 799 0943 e-7    0.000 000 0023 e-7    kg mol^-1
+electron-muon mag. mom. ratio                          206.766 9877          0.000 0052
+electron-muon mass ratio                               4.836 331 71 e-3      0.000 000 12 e-3
+electron-neutron mag. mom. ratio                       960.920 50            0.000 23
+electron-neutron mass ratio                            5.438 673 4459 e-4    0.000 000 0033 e-4
+electron-proton mag. mom. ratio                        -658.210 6848         0.000 0054
+electron-proton mass ratio                             5.446 170 2177 e-4    0.000 000 0024 e-4
+electron-tau mass ratio                                2.875 64 e-4          0.000 47 e-4
+electron to alpha particle mass ratio                  1.370 933 555 70 e-4  0.000 000 000 58 e-4
+electron to shielded helion mag. mom. ratio            864.058 257           0.000 010
+electron to shielded proton mag. mom. ratio            -658.227 5971         0.000 0072
+electron volt                                          1.602 176 487 e-19    0.000 000 040 e-19    J
+electron volt-atomic mass unit relationship            1.073 544 188 e-9     0.000 000 027 e-9     u
+electron volt-hartree relationship                     3.674 932 540 e-2     0.000 000 092 e-2     E_h
+electron volt-hertz relationship                       2.417 989 454 e14     0.000 000 060 e14     Hz
+electron volt-inverse meter relationship               8.065 544 65 e5       0.000 000 20 e5       m^-1
+electron volt-joule relationship                       1.602 176 487 e-19    0.000 000 040 e-19    J
+electron volt-kelvin relationship                      1.160 4505 e4         0.000 0020 e4         K
+electron volt-kilogram relationship                    1.782 661 758 e-36    0.000 000 044 e-36    kg
+elementary charge                                      1.602 176 487 e-19    0.000 000 040 e-19    C
+elementary charge over h                               2.417 989 454 e14     0.000 000 060 e14     A J^-1
+Faraday constant                                       96 485.3399           0.0024                C mol^-1
+Faraday constant for conventional electric current     96 485.3401           0.0048                C_90 mol^-1
+Fermi coupling constant                                1.166 37 e-5          0.000 01 e-5          GeV^-2
+fine-structure constant                                7.297 352 5376 e-3    0.000 000 0050 e-3
+first radiation constant                               3.741 771 18 e-16     0.000 000 19 e-16     W m^2
+first radiation constant for spectral radiance         1.191 042 759 e-16    0.000 000 059 e-16    W m^2 sr^-1
+hartree-atomic mass unit relationship                  2.921 262 2986 e-8    0.000 000 0042 e-8    u
+hartree-electron volt relationship                     27.211 383 86         0.000 000 68          eV
+Hartree energy                                         4.359 743 94 e-18     0.000 000 22 e-18     J
+Hartree energy in eV                                   27.211 383 86         0.000 000 68          eV
+hartree-hertz relationship                             6.579 683 920 722 e15 0.000 000 000 044 e15 Hz
+hartree-inverse meter relationship                     2.194 746 313 705 e7  0.000 000 000 015 e7  m^-1
+hartree-joule relationship                             4.359 743 94 e-18     0.000 000 22 e-18     J
+hartree-kelvin relationship                            3.157 7465 e5         0.000 0055 e5         K
+hartree-kilogram relationship                          4.850 869 34 e-35     0.000 000 24 e-35     kg
+helion-electron mass ratio                             5495.885 2765         0.000 0052
+helion mass                                            5.006 411 92 e-27     0.000 000 25 e-27     kg
+helion mass energy equivalent                          4.499 538 64 e-10     0.000 000 22 e-10     J
+helion mass energy equivalent in MeV                   2808.391 383          0.000 070             MeV
+helion mass in u                                       3.014 932 2473        0.000 000 0026        u
+helion molar mass                                      3.014 932 2473 e-3    0.000 000 0026 e-3    kg mol^-1
+helion-proton mass ratio                               2.993 152 6713        0.000 000 0026
+hertz-atomic mass unit relationship                    4.439 821 6294 e-24   0.000 000 0064 e-24   u
+hertz-electron volt relationship                       4.135 667 33 e-15     0.000 000 10 e-15     eV
+hertz-hartree relationship                             1.519 829 846 006 e-16 0.000 000 000010e-16 E_h
+hertz-inverse meter relationship                       3.335 640 951... e-9  (exact)               m^-1
+hertz-joule relationship                               6.626 068 96 e-34     0.000 000 33 e-34     J
+hertz-kelvin relationship                              4.799 2374 e-11       0.000 0084 e-11       K
+hertz-kilogram relationship                            7.372 496 00 e-51     0.000 000 37 e-51     kg
+inverse fine-structure constant                        137.035 999 679       0.000 000 094
+inverse meter-atomic mass unit relationship            1.331 025 0394 e-15   0.000 000 0019 e-15   u
+inverse meter-electron volt relationship               1.239 841 875 e-6     0.000 000 031 e-6     eV
+inverse meter-hartree relationship                     4.556 335 252 760 e-8 0.000 000 000 030 e-8 E_h
+inverse meter-hertz relationship                       299 792 458           (exact)               Hz
+inverse meter-joule relationship                       1.986 445 501 e-25    0.000 000 099 e-25    J
+inverse meter-kelvin relationship                      1.438 7752 e-2        0.000 0025 e-2        K
+inverse meter-kilogram relationship                    2.210 218 70 e-42     0.000 000 11 e-42     kg
+inverse of conductance quantum                         12 906.403 7787       0.000 0088            ohm
+Josephson constant                                     483 597.891 e9        0.012 e9              Hz V^-1
+joule-atomic mass unit relationship                    6.700 536 41 e9       0.000 000 33 e9       u
+joule-electron volt relationship                       6.241 509 65 e18      0.000 000 16 e18      eV
+joule-hartree relationship                             2.293 712 69 e17      0.000 000 11 e17      E_h
+joule-hertz relationship                               1.509 190 450 e33     0.000 000 075 e33     Hz
+joule-inverse meter relationship                       5.034 117 47 e24      0.000 000 25 e24      m^-1
+joule-kelvin relationship                              7.242 963 e22         0.000 013 e22         K
+joule-kilogram relationship                            1.112 650 056... e-17 (exact)               kg
+kelvin-atomic mass unit relationship                   9.251 098 e-14        0.000 016 e-14        u
+kelvin-electron volt relationship                      8.617 343 e-5         0.000 015 e-5         eV
+kelvin-hartree relationship                            3.166 8153 e-6        0.000 0055 e-6        E_h
+kelvin-hertz relationship                              2.083 6644 e10        0.000 0036 e10        Hz
+kelvin-inverse meter relationship                      69.503 56             0.000 12              m^-1
+kelvin-joule relationship                              1.380 6504 e-23       0.000 0024 e-23       J
+kelvin-kilogram relationship                           1.536 1807 e-40       0.000 0027 e-40       kg
+kilogram-atomic mass unit relationship                 6.022 141 79 e26      0.000 000 30 e26      u
+kilogram-electron volt relationship                    5.609 589 12 e35      0.000 000 14 e35      eV
+kilogram-hartree relationship                          2.061 486 16 e34      0.000 000 10 e34      E_h
+kilogram-hertz relationship                            1.356 392 733 e50     0.000 000 068 e50     Hz
+kilogram-inverse meter relationship                    4.524 439 15 e41      0.000 000 23 e41      m^-1
+kilogram-joule relationship                            8.987 551 787... e16  (exact)               J
+kilogram-kelvin relationship                           6.509 651 e39         0.000 011 e39         K
+lattice parameter of silicon                           543.102 064 e-12      0.000 014 e-12        m
+Loschmidt constant (273.15 K, 101.325 kPa)             2.686 7774 e25        0.000 0047 e25        m^-3
+mag. constant                                          12.566 370 614... e-7 (exact)               N A^-2
+mag. flux quantum                                      2.067 833 667 e-15    0.000 000 052 e-15    Wb
+molar gas constant                                     8.314 472             0.000 015             J mol^-1 K^-1
+molar mass constant                                    1 e-3                 (exact)               kg mol^-1
+molar mass of carbon-12                                12 e-3                (exact)               kg mol^-1
+molar Planck constant                                  3.990 312 6821 e-10   0.000 000 0057 e-10   J s mol^-1
+molar Planck constant times c                          0.119 626 564 72      0.000 000 000 17      J m mol^-1
+molar volume of ideal gas (273.15 K, 100 kPa)          22.710 981 e-3        0.000 040 e-3         m^3 mol^-1
+molar volume of ideal gas (273.15 K, 101.325 kPa)      22.413 996 e-3        0.000 039 e-3         m^3 mol^-1
+molar volume of silicon                                12.058 8349 e-6       0.000 0011 e-6        m^3 mol^-1
+Mo x unit                                              1.002 099 55 e-13     0.000 000 53 e-13     m
+muon Compton wavelength                                11.734 441 04 e-15    0.000 000 30 e-15     m
+muon Compton wavelength over 2 pi                      1.867 594 295 e-15    0.000 000 047 e-15    m
+muon-electron mass ratio                               206.768 2823          0.000 0052
+muon g factor                                          -2.002 331 8414       0.000 000 0012
+muon mag. mom.                                         -4.490 447 86 e-26    0.000 000 16 e-26     J T^-1
+muon mag. mom. anomaly                                 1.165 920 69 e-3      0.000 000 60 e-3
+muon mag. mom. to Bohr magneton ratio                  -4.841 970 49 e-3     0.000 000 12 e-3
+muon mag. mom. to nuclear magneton ratio               -8.890 597 05         0.000 000 23
+muon mass                                              1.883 531 30 e-28     0.000 000 11 e-28     kg
+muon mass energy equivalent                            1.692 833 510 e-11    0.000 000 095 e-11    J
+muon mass energy equivalent in MeV                     105.658 3668          0.000 0038            MeV
+muon mass in u                                         0.113 428 9256        0.000 000 0029        u
+muon molar mass                                        0.113 428 9256 e-3    0.000 000 0029 e-3    kg mol^-1
+muon-neutron mass ratio                                0.112 454 5167        0.000 000 0029
+muon-proton mag. mom. ratio                            -3.183 345 137        0.000 000 085
+muon-proton mass ratio                                 0.112 609 5261        0.000 000 0029
+muon-tau mass ratio                                    5.945 92 e-2          0.000 97 e-2
+natural unit of action                                 1.054 571 628 e-34    0.000 000 053 e-34    J s
+natural unit of action in eV s                         6.582 118 99 e-16     0.000 000 16 e-16     eV s
+natural unit of energy                                 8.187 104 38 e-14     0.000 000 41 e-14     J
+natural unit of energy in MeV                          0.510 998 910         0.000 000 013         MeV
+natural unit of length                                 386.159 264 59 e-15   0.000 000 53 e-15     m
+natural unit of mass                                   9.109 382 15 e-31     0.000 000 45 e-31     kg
+natural unit of momentum                               2.730 924 06 e-22     0.000 000 14 e-22     kg m s^-1
+natural unit of momentum in MeV/c                      0.510 998 910         0.000 000 013         MeV/c
+natural unit of time                                   1.288 088 6570 e-21   0.000 000 0018 e-21   s
+natural unit of velocity                               299 792 458           (exact)               m s^-1
+neutron Compton wavelength                             1.319 590 8951 e-15   0.000 000 0020 e-15   m
+neutron Compton wavelength over 2 pi                   0.210 019 413 82 e-15 0.000 000 000 31 e-15 m
+neutron-electron mag. mom. ratio                       1.040 668 82 e-3      0.000 000 25 e-3
+neutron-electron mass ratio                            1838.683 6605         0.000 0011
+neutron g factor                                       -3.826 085 45         0.000 000 90
+neutron gyromag. ratio                                 1.832 471 85 e8       0.000 000 43 e8       s^-1 T^-1
+neutron gyromag. ratio over 2 pi                       29.164 6954           0.000 0069            MHz T^-1
+neutron mag. mom.                                      -0.966 236 41 e-26    0.000 000 23 e-26     J T^-1
+neutron mag. mom. to Bohr magneton ratio               -1.041 875 63 e-3     0.000 000 25 e-3
+neutron mag. mom. to nuclear magneton ratio            -1.913 042 73         0.000 000 45
+neutron mass                                           1.674 927 211 e-27    0.000 000 084 e-27    kg
+neutron mass energy equivalent                         1.505 349 505 e-10    0.000 000 075 e-10    J
+neutron mass energy equivalent in MeV                  939.565 346           0.000 023             MeV
+neutron mass in u                                      1.008 664 915 97      0.000 000 000 43      u
+neutron molar mass                                     1.008 664 915 97 e-3  0.000 000 000 43 e-3  kg mol^-1
+neutron-muon mass ratio                                8.892 484 09          0.000 000 23
+neutron-proton mag. mom. ratio                         -0.684 979 34         0.000 000 16
+neutron-proton mass ratio                              1.001 378 419 18      0.000 000 000 46
+neutron-tau mass ratio                                 0.528 740             0.000 086
+neutron to shielded proton mag. mom. ratio             -0.684 996 94         0.000 000 16
+Newtonian constant of gravitation                      6.674 28 e-11         0.000 67 e-11         m^3 kg^-1 s^-2
+Newtonian constant of gravitation over h-bar c         6.708 81 e-39         0.000 67 e-39         (GeV/c^2)^-2
+nuclear magneton                                       5.050 783 24 e-27     0.000 000 13 e-27     J T^-1
+nuclear magneton in eV/T                               3.152 451 2326 e-8    0.000 000 0045 e-8    eV T^-1
+nuclear magneton in inverse meters per tesla           2.542 623 616 e-2     0.000 000 064 e-2     m^-1 T^-1
+nuclear magneton in K/T                                3.658 2637 e-4        0.000 0064 e-4        K T^-1
+nuclear magneton in MHz/T                              7.622 593 84          0.000 000 19          MHz T^-1
+Planck constant                                        6.626 068 96 e-34     0.000 000 33 e-34     J s
+Planck constant in eV s                                4.135 667 33 e-15     0.000 000 10 e-15     eV s
+Planck constant over 2 pi                              1.054 571 628 e-34    0.000 000 053 e-34    J s
+Planck constant over 2 pi in eV s                      6.582 118 99 e-16     0.000 000 16 e-16     eV s
+Planck constant over 2 pi times c in MeV fm            197.326 9631          0.000 0049            MeV fm
+Planck length                                          1.616 252 e-35        0.000 081 e-35        m
+Planck mass                                            2.176 44 e-8          0.000 11 e-8          kg
+Planck mass energy equivalent in GeV                   1.220 892 e19         0.000 061 e19         GeV
+Planck temperature                                     1.416 785 e32         0.000 071 e32         K
+Planck time                                            5.391 24 e-44         0.000 27 e-44         s
+proton charge to mass quotient                         9.578 833 92 e7       0.000 000 24 e7       C kg^-1
+proton Compton wavelength                              1.321 409 8446 e-15   0.000 000 0019 e-15   m
+proton Compton wavelength over 2 pi                    0.210 308 908 61 e-15 0.000 000 000 30 e-15 m
+proton-electron mass ratio                             1836.152 672 47       0.000 000 80
+proton g factor                                        5.585 694 713         0.000 000 046
+proton gyromag. ratio                                  2.675 222 099 e8      0.000 000 070 e8      s^-1 T^-1
+proton gyromag. ratio over 2 pi                        42.577 4821           0.000 0011            MHz T^-1
+proton mag. mom.                                       1.410 606 662 e-26    0.000 000 037 e-26    J T^-1
+proton mag. mom. to Bohr magneton ratio                1.521 032 209 e-3     0.000 000 012 e-3
+proton mag. mom. to nuclear magneton ratio             2.792 847 356         0.000 000 023
+proton mag. shielding correction                       25.694 e-6            0.014 e-6
+proton mass                                            1.672 621 637 e-27    0.000 000 083 e-27    kg
+proton mass energy equivalent                          1.503 277 359 e-10    0.000 000 075 e-10    J
+proton mass energy equivalent in MeV                   938.272 013           0.000 023             MeV
+proton mass in u                                       1.007 276 466 77      0.000 000 000 10      u
+proton molar mass                                      1.007 276 466 77 e-3  0.000 000 000 10 e-3  kg mol^-1
+proton-muon mass ratio                                 8.880 243 39          0.000 000 23
+proton-neutron mag. mom. ratio                         -1.459 898 06         0.000 000 34
+proton-neutron mass ratio                              0.998 623 478 24      0.000 000 000 46
+proton rms charge radius                               0.8768 e-15           0.0069 e-15           m
+proton-tau mass ratio                                  0.528 012             0.000 086
+quantum of circulation                                 3.636 947 5199 e-4    0.000 000 0050 e-4    m^2 s^-1
+quantum of circulation times 2                         7.273 895 040 e-4     0.000 000 010 e-4     m^2 s^-1
+Rydberg constant                                       10 973 731.568 527    0.000 073             m^-1
+Rydberg constant times c in Hz                         3.289 841 960 361 e15 0.000 000 000 022 e15 Hz
+Rydberg constant times hc in eV                        13.605 691 93         0.000 000 34          eV
+Rydberg constant times hc in J                         2.179 871 97 e-18     0.000 000 11 e-18     J
+Sackur-Tetrode constant (1 K, 100 kPa)                 -1.151 7047           0.000 0044
+Sackur-Tetrode constant (1 K, 101.325 kPa)             -1.164 8677           0.000 0044
+second radiation constant                              1.438 7752 e-2        0.000 0025 e-2        m K
+shielded helion gyromag. ratio                         2.037 894 730 e8      0.000 000 056 e8      s^-1 T^-1
+shielded helion gyromag. ratio over 2 pi               32.434 101 98         0.000 000 90          MHz T^-1
+shielded helion mag. mom.                              -1.074 552 982 e-26   0.000 000 030 e-26    J T^-1
+shielded helion mag. mom. to Bohr magneton ratio       -1.158 671 471 e-3    0.000 000 014 e-3
+shielded helion mag. mom. to nuclear magneton ratio    -2.127 497 718        0.000 000 025
+shielded helion to proton mag. mom. ratio              -0.761 766 558        0.000 000 011
+shielded helion to shielded proton mag. mom. ratio     -0.761 786 1313       0.000 000 0033
+shielded proton gyromag. ratio                         2.675 153 362 e8      0.000 000 073 e8      s^-1 T^-1
+shielded proton gyromag. ratio over 2 pi               42.576 3881           0.000 0012            MHz T^-1
+shielded proton mag. mom.                              1.410 570 419 e-26    0.000 000 038 e-26    J T^-1
+shielded proton mag. mom. to Bohr magneton ratio       1.520 993 128 e-3     0.000 000 017 e-3
+shielded proton mag. mom. to nuclear magneton ratio    2.792 775 598         0.000 000 030
+speed of light in vacuum                               299 792 458           (exact)               m s^-1
+standard acceleration of gravity                       9.806 65              (exact)               m s^-2
+standard atmosphere                                    101 325               (exact)               Pa
+Stefan-Boltzmann constant                              5.670 400 e-8         0.000 040 e-8         W m^-2 K^-4
+tau Compton wavelength                                 0.697 72 e-15         0.000 11 e-15         m
+tau Compton wavelength over 2 pi                       0.111 046 e-15        0.000 018 e-15        m
+tau-electron mass ratio                                3477.48               0.57
+tau mass                                               3.167 77 e-27         0.000 52 e-27         kg
+tau mass energy equivalent                             2.847 05 e-10         0.000 46 e-10         J
+tau mass energy equivalent in MeV                      1776.99               0.29                  MeV
+tau mass in u                                          1.907 68              0.000 31              u
+tau molar mass                                         1.907 68 e-3          0.000 31 e-3          kg mol^-1
+tau-muon mass ratio                                    16.8183               0.0027
+tau-neutron mass ratio                                 1.891 29              0.000 31
+tau-proton mass ratio                                  1.893 90              0.000 31
+Thomson cross section                                  0.665 245 8558 e-28   0.000 000 0027 e-28   m^2
+triton-electron mag. mom. ratio                        -1.620 514 423 e-3    0.000 000 021 e-3
+triton-electron mass ratio                             5496.921 5269         0.000 0051
+triton g factor                                        5.957 924 896         0.000 000 076
+triton mag. mom.                                       1.504 609 361 e-26    0.000 000 042 e-26    J T^-1
+triton mag. mom. to Bohr magneton ratio                1.622 393 657 e-3     0.000 000 021 e-3
+triton mag. mom. to nuclear magneton ratio             2.978 962 448         0.000 000 038
+triton mass                                            5.007 355 88 e-27     0.000 000 25 e-27     kg
+triton mass energy equivalent                          4.500 387 03 e-10     0.000 000 22 e-10     J
+triton mass energy equivalent in MeV                   2808.920 906          0.000 070             MeV
+triton mass in u                                       3.015 500 7134        0.000 000 0025        u
+triton molar mass                                      3.015 500 7134 e-3    0.000 000 0025 e-3    kg mol^-1
+triton-neutron mag. mom. ratio                         -1.557 185 53         0.000 000 37
+triton-proton mag. mom. ratio                          1.066 639 908         0.000 000 010
+triton-proton mass ratio                               2.993 717 0309        0.000 000 0025
+unified atomic mass unit                               1.660 538 782 e-27    0.000 000 083 e-27    kg
+von Klitzing constant                                  25 812.807 557        0.000 018             ohm
+weak mixing angle                                      0.222 55              0.000 56
+Wien frequency displacement law constant               5.878 933 e10         0.000 010 e10         Hz K^-1
+Wien wavelength displacement law constant              2.897 7685 e-3        0.000 0051 e-3        m K"""
+
+
+def exact2006(exact):
+    mu0 = 4e-7 * math.pi
+    c = exact['speed of light in vacuum']
+    epsilon0 = 1 / (mu0 * c**2)
+    replace = {
+        'mag. constant': mu0,
+        'electric constant': epsilon0,
+        'atomic unit of permittivity': 4*math.pi*epsilon0,
+        'characteristic impedance of vacuum': math.sqrt(mu0 / epsilon0),
+        'hertz-inverse meter relationship': 1/c,
+        'joule-kilogram relationship': 1/c**2,
+        'kilogram-joule relationship': c**2,
+    }
+    return replace
+
+
+txt2010 = """\
+{220} lattice spacing of silicon                       192.015 5714 e-12     0.000 0032 e-12       m
+alpha particle-electron mass ratio                     7294.299 5361         0.000 0029
+alpha particle mass                                    6.644 656 75 e-27     0.000 000 29 e-27     kg
+alpha particle mass energy equivalent                  5.971 919 67 e-10     0.000 000 26 e-10     J
+alpha particle mass energy equivalent in MeV           3727.379 240          0.000 082             MeV
+alpha particle mass in u                               4.001 506 179 125     0.000 000 000 062     u
+alpha particle molar mass                              4.001 506 179 125 e-3 0.000 000 000 062 e-3 kg mol^-1
+alpha particle-proton mass ratio                       3.972 599 689 33      0.000 000 000 36
+Angstrom star                                          1.000 014 95 e-10     0.000 000 90 e-10     m
+atomic mass constant                                   1.660 538 921 e-27    0.000 000 073 e-27    kg
+atomic mass constant energy equivalent                 1.492 417 954 e-10    0.000 000 066 e-10    J
+atomic mass constant energy equivalent in MeV          931.494 061           0.000 021             MeV
+atomic mass unit-electron volt relationship            931.494 061 e6        0.000 021 e6          eV
+atomic mass unit-hartree relationship                  3.423 177 6845 e7     0.000 000 0024 e7     E_h
+atomic mass unit-hertz relationship                    2.252 342 7168 e23    0.000 000 0016 e23    Hz
+atomic mass unit-inverse meter relationship            7.513 006 6042 e14    0.000 000 0053 e14    m^-1
+atomic mass unit-joule relationship                    1.492 417 954 e-10    0.000 000 066 e-10    J
+atomic mass unit-kelvin relationship                   1.080 954 08 e13      0.000 000 98 e13      K
+atomic mass unit-kilogram relationship                 1.660 538 921 e-27    0.000 000 073 e-27    kg
+atomic unit of 1st hyperpolarizability                 3.206 361 449 e-53    0.000 000 071 e-53    C^3 m^3 J^-2
+atomic unit of 2nd hyperpolarizability                 6.235 380 54 e-65     0.000 000 28 e-65     C^4 m^4 J^-3
+atomic unit of action                                  1.054 571 726 e-34    0.000 000 047 e-34    J s
+atomic unit of charge                                  1.602 176 565 e-19    0.000 000 035 e-19    C
+atomic unit of charge density                          1.081 202 338 e12     0.000 000 024 e12     C m^-3
+atomic unit of current                                 6.623 617 95 e-3      0.000 000 15 e-3      A
+atomic unit of electric dipole mom.                    8.478 353 26 e-30     0.000 000 19 e-30     C m
+atomic unit of electric field                          5.142 206 52 e11      0.000 000 11 e11      V m^-1
+atomic unit of electric field gradient                 9.717 362 00 e21      0.000 000 21 e21      V m^-2
+atomic unit of electric polarizability                 1.648 777 2754 e-41   0.000 000 0016 e-41   C^2 m^2 J^-1
+atomic unit of electric potential                      27.211 385 05         0.000 000 60          V
+atomic unit of electric quadrupole mom.                4.486 551 331 e-40    0.000 000 099 e-40    C m^2
+atomic unit of energy                                  4.359 744 34 e-18     0.000 000 19 e-18     J
+atomic unit of force                                   8.238 722 78 e-8      0.000 000 36 e-8      N
+atomic unit of length                                  0.529 177 210 92 e-10 0.000 000 000 17 e-10 m
+atomic unit of mag. dipole mom.                        1.854 801 936 e-23    0.000 000 041 e-23    J T^-1
+atomic unit of mag. flux density                       2.350 517 464 e5      0.000 000 052 e5      T
+atomic unit of magnetizability                         7.891 036 607 e-29    0.000 000 013 e-29    J T^-2
+atomic unit of mass                                    9.109 382 91 e-31     0.000 000 40 e-31     kg
+atomic unit of mom.um                                  1.992 851 740 e-24    0.000 000 088 e-24    kg m s^-1
+atomic unit of permittivity                            1.112 650 056... e-10 (exact)               F m^-1
+atomic unit of time                                    2.418 884 326 502e-17 0.000 000 000 012e-17 s
+atomic unit of velocity                                2.187 691 263 79 e6   0.000 000 000 71 e6   m s^-1
+Avogadro constant                                      6.022 141 29 e23      0.000 000 27 e23      mol^-1
+Bohr magneton                                          927.400 968 e-26      0.000 020 e-26        J T^-1
+Bohr magneton in eV/T                                  5.788 381 8066 e-5    0.000 000 0038 e-5    eV T^-1
+Bohr magneton in Hz/T                                  13.996 245 55 e9      0.000 000 31 e9       Hz T^-1
+Bohr magneton in inverse meters per tesla              46.686 4498           0.000 0010            m^-1 T^-1
+Bohr magneton in K/T                                   0.671 713 88          0.000 000 61          K T^-1
+Bohr radius                                            0.529 177 210 92 e-10 0.000 000 000 17 e-10 m
+Boltzmann constant                                     1.380 6488 e-23       0.000 0013 e-23       J K^-1
+Boltzmann constant in eV/K                             8.617 3324 e-5        0.000 0078 e-5        eV K^-1
+Boltzmann constant in Hz/K                             2.083 6618 e10        0.000 0019 e10        Hz K^-1
+Boltzmann constant in inverse meters per kelvin        69.503 476            0.000 063             m^-1 K^-1
+characteristic impedance of vacuum                     376.730 313 461...    (exact)               ohm
+classical electron radius                              2.817 940 3267 e-15   0.000 000 0027 e-15   m
+Compton wavelength                                     2.426 310 2389 e-12   0.000 000 0016 e-12   m
+Compton wavelength over 2 pi                           386.159 268 00 e-15   0.000 000 25 e-15     m
+conductance quantum                                    7.748 091 7346 e-5    0.000 000 0025 e-5    S
+conventional value of Josephson constant               483 597.9 e9          (exact)               Hz V^-1
+conventional value of von Klitzing constant            25 812.807            (exact)               ohm
+Cu x unit                                              1.002 076 97 e-13     0.000 000 28 e-13     m
+deuteron-electron mag. mom. ratio                      -4.664 345 537 e-4    0.000 000 039 e-4
+deuteron-electron mass ratio                           3670.482 9652         0.000 0015
+deuteron g factor                                      0.857 438 2308        0.000 000 0072
+deuteron mag. mom.                                     0.433 073 489 e-26    0.000 000 010 e-26    J T^-1
+deuteron mag. mom. to Bohr magneton ratio              0.466 975 4556 e-3    0.000 000 0039 e-3
+deuteron mag. mom. to nuclear magneton ratio           0.857 438 2308        0.000 000 0072
+deuteron mass                                          3.343 583 48 e-27     0.000 000 15 e-27     kg
+deuteron mass energy equivalent                        3.005 062 97 e-10     0.000 000 13 e-10     J
+deuteron mass energy equivalent in MeV                 1875.612 859          0.000 041             MeV
+deuteron mass in u                                     2.013 553 212 712     0.000 000 000 077     u
+deuteron molar mass                                    2.013 553 212 712 e-3 0.000 000 000 077 e-3 kg mol^-1
+deuteron-neutron mag. mom. ratio                       -0.448 206 52         0.000 000 11
+deuteron-proton mag. mom. ratio                        0.307 012 2070        0.000 000 0024
+deuteron-proton mass ratio                             1.999 007 500 97      0.000 000 000 18
+deuteron rms charge radius                             2.1424 e-15           0.0021 e-15           m
+electric constant                                      8.854 187 817... e-12 (exact)               F m^-1
+electron charge to mass quotient                       -1.758 820 088 e11    0.000 000 039 e11     C kg^-1
+electron-deuteron mag. mom. ratio                      -2143.923 498         0.000 018
+electron-deuteron mass ratio                           2.724 437 1095 e-4    0.000 000 0011 e-4
+electron g factor                                      -2.002 319 304 361 53 0.000 000 000 000 53
+electron gyromag. ratio                                1.760 859 708 e11     0.000 000 039 e11     s^-1 T^-1
+electron gyromag. ratio over 2 pi                      28 024.952 66         0.000 62              MHz T^-1
+electron-helion mass ratio                             1.819 543 0761 e-4    0.000 000 0017 e-4
+electron mag. mom.                                     -928.476 430 e-26     0.000 021 e-26        J T^-1
+electron mag. mom. anomaly                             1.159 652 180 76 e-3  0.000 000 000 27 e-3
+electron mag. mom. to Bohr magneton ratio              -1.001 159 652 180 76 0.000 000 000 000 27
+electron mag. mom. to nuclear magneton ratio           -1838.281 970 90      0.000 000 75
+electron mass                                          9.109 382 91 e-31     0.000 000 40 e-31     kg
+electron mass energy equivalent                        8.187 105 06 e-14     0.000 000 36 e-14     J
+electron mass energy equivalent in MeV                 0.510 998 928         0.000 000 011         MeV
+electron mass in u                                     5.485 799 0946 e-4    0.000 000 0022 e-4    u
+electron molar mass                                    5.485 799 0946 e-7    0.000 000 0022 e-7    kg mol^-1
+electron-muon mag. mom. ratio                          206.766 9896          0.000 0052
+electron-muon mass ratio                               4.836 331 66 e-3      0.000 000 12 e-3
+electron-neutron mag. mom. ratio                       960.920 50            0.000 23
+electron-neutron mass ratio                            5.438 673 4461 e-4    0.000 000 0032 e-4
+electron-proton mag. mom. ratio                        -658.210 6848         0.000 0054
+electron-proton mass ratio                             5.446 170 2178 e-4    0.000 000 0022 e-4
+electron-tau mass ratio                                2.875 92 e-4          0.000 26 e-4
+electron to alpha particle mass ratio                  1.370 933 555 78 e-4  0.000 000 000 55 e-4
+electron to shielded helion mag. mom. ratio            864.058 257           0.000 010
+electron to shielded proton mag. mom. ratio            -658.227 5971         0.000 0072
+electron-triton mass ratio                             1.819 200 0653 e-4    0.000 000 0017 e-4
+electron volt                                          1.602 176 565 e-19    0.000 000 035 e-19    J
+electron volt-atomic mass unit relationship            1.073 544 150 e-9     0.000 000 024 e-9     u
+electron volt-hartree relationship                     3.674 932 379 e-2     0.000 000 081 e-2     E_h
+electron volt-hertz relationship                       2.417 989 348 e14     0.000 000 053 e14     Hz
+electron volt-inverse meter relationship               8.065 544 29 e5       0.000 000 18 e5       m^-1
+electron volt-joule relationship                       1.602 176 565 e-19    0.000 000 035 e-19    J
+electron volt-kelvin relationship                      1.160 4519 e4         0.000 0011 e4         K
+electron volt-kilogram relationship                    1.782 661 845 e-36    0.000 000 039 e-36    kg
+elementary charge                                      1.602 176 565 e-19    0.000 000 035 e-19    C
+elementary charge over h                               2.417 989 348 e14     0.000 000 053 e14     A J^-1
+Faraday constant                                       96 485.3365           0.0021                C mol^-1
+Faraday constant for conventional electric current     96 485.3321           0.0043                C_90 mol^-1
+Fermi coupling constant                                1.166 364 e-5         0.000 005 e-5         GeV^-2
+fine-structure constant                                7.297 352 5698 e-3    0.000 000 0024 e-3
+first radiation constant                               3.741 771 53 e-16     0.000 000 17 e-16     W m^2
+first radiation constant for spectral radiance         1.191 042 869 e-16    0.000 000 053 e-16    W m^2 sr^-1
+hartree-atomic mass unit relationship                  2.921 262 3246 e-8    0.000 000 0021 e-8    u
+hartree-electron volt relationship                     27.211 385 05         0.000 000 60          eV
+Hartree energy                                         4.359 744 34 e-18     0.000 000 19 e-18     J
+Hartree energy in eV                                   27.211 385 05         0.000 000 60          eV
+hartree-hertz relationship                             6.579 683 920 729 e15 0.000 000 000 033 e15 Hz
+hartree-inverse meter relationship                     2.194 746 313 708 e7  0.000 000 000 011 e7  m^-1
+hartree-joule relationship                             4.359 744 34 e-18     0.000 000 19 e-18     J
+hartree-kelvin relationship                            3.157 7504 e5         0.000 0029 e5         K
+hartree-kilogram relationship                          4.850 869 79 e-35     0.000 000 21 e-35     kg
+helion-electron mass ratio                             5495.885 2754         0.000 0050
+helion g factor                                        -4.255 250 613        0.000 000 050
+helion mag. mom.                                       -1.074 617 486 e-26   0.000 000 027 e-26    J T^-1
+helion mag. mom. to Bohr magneton ratio                -1.158 740 958 e-3    0.000 000 014 e-3
+helion mag. mom. to nuclear magneton ratio             -2.127 625 306        0.000 000 025
+helion mass                                            5.006 412 34 e-27     0.000 000 22 e-27     kg
+helion mass energy equivalent                          4.499 539 02 e-10     0.000 000 20 e-10     J
+helion mass energy equivalent in MeV                   2808.391 482          0.000 062             MeV
+helion mass in u                                       3.014 932 2468        0.000 000 0025        u
+helion molar mass                                      3.014 932 2468 e-3    0.000 000 0025 e-3    kg mol^-1
+helion-proton mass ratio                               2.993 152 6707        0.000 000 0025
+hertz-atomic mass unit relationship                    4.439 821 6689 e-24   0.000 000 0031 e-24   u
+hertz-electron volt relationship                       4.135 667 516 e-15    0.000 000 091 e-15    eV
+hertz-hartree relationship                             1.519 829 8460045e-16 0.000 000 0000076e-16 E_h
+hertz-inverse meter relationship                       3.335 640 951... e-9  (exact)               m^-1
+hertz-joule relationship                               6.626 069 57 e-34     0.000 000 29 e-34     J
+hertz-kelvin relationship                              4.799 2434 e-11       0.000 0044 e-11       K
+hertz-kilogram relationship                            7.372 496 68 e-51     0.000 000 33 e-51     kg
+inverse fine-structure constant                        137.035 999 074       0.000 000 044
+inverse meter-atomic mass unit relationship            1.331 025 051 20 e-15 0.000 000 000 94 e-15 u
+inverse meter-electron volt relationship               1.239 841 930 e-6     0.000 000 027 e-6     eV
+inverse meter-hartree relationship                     4.556 335 252 755 e-8 0.000 000 000 023 e-8 E_h
+inverse meter-hertz relationship                       299 792 458           (exact)               Hz
+inverse meter-joule relationship                       1.986 445 684 e-25    0.000 000 088 e-25    J
+inverse meter-kelvin relationship                      1.438 7770 e-2        0.000 0013 e-2        K
+inverse meter-kilogram relationship                    2.210 218 902 e-42    0.000 000 098 e-42    kg
+inverse of conductance quantum                         12 906.403 7217       0.000 0042            ohm
+Josephson constant                                     483 597.870 e9        0.011 e9              Hz V^-1
+joule-atomic mass unit relationship                    6.700 535 85 e9       0.000 000 30 e9       u
+joule-electron volt relationship                       6.241 509 34 e18      0.000 000 14 e18      eV
+joule-hartree relationship                             2.293 712 48 e17      0.000 000 10 e17      E_h
+joule-hertz relationship                               1.509 190 311 e33     0.000 000 067 e33     Hz
+joule-inverse meter relationship                       5.034 117 01 e24      0.000 000 22 e24      m^-1
+joule-kelvin relationship                              7.242 9716 e22        0.000 0066 e22        K
+joule-kilogram relationship                            1.112 650 056... e-17 (exact)               kg
+kelvin-atomic mass unit relationship                   9.251 0868 e-14       0.000 0084 e-14       u
+kelvin-electron volt relationship                      8.617 3324 e-5        0.000 0078 e-5        eV
+kelvin-hartree relationship                            3.166 8114 e-6        0.000 0029 e-6        E_h
+kelvin-hertz relationship                              2.083 6618 e10        0.000 0019 e10        Hz
+kelvin-inverse meter relationship                      69.503 476            0.000 063             m^-1
+kelvin-joule relationship                              1.380 6488 e-23       0.000 0013 e-23       J
+kelvin-kilogram relationship                           1.536 1790 e-40       0.000 0014 e-40       kg
+kilogram-atomic mass unit relationship                 6.022 141 29 e26      0.000 000 27 e26      u
+kilogram-electron volt relationship                    5.609 588 85 e35      0.000 000 12 e35      eV
+kilogram-hartree relationship                          2.061 485 968 e34     0.000 000 091 e34     E_h
+kilogram-hertz relationship                            1.356 392 608 e50     0.000 000 060 e50     Hz
+kilogram-inverse meter relationship                    4.524 438 73 e41      0.000 000 20 e41      m^-1
+kilogram-joule relationship                            8.987 551 787... e16  (exact)               J
+kilogram-kelvin relationship                           6.509 6582 e39        0.000 0059 e39        K
+lattice parameter of silicon                           543.102 0504 e-12     0.000 0089 e-12       m
+Loschmidt constant (273.15 K, 100 kPa)                 2.651 6462 e25        0.000 0024 e25        m^-3
+Loschmidt constant (273.15 K, 101.325 kPa)             2.686 7805 e25        0.000 0024 e25        m^-3
+mag. constant                                          12.566 370 614... e-7 (exact)               N A^-2
+mag. flux quantum                                      2.067 833 758 e-15    0.000 000 046 e-15    Wb
+molar gas constant                                     8.314 4621            0.000 0075            J mol^-1 K^-1
+molar mass constant                                    1 e-3                 (exact)               kg mol^-1
+molar mass of carbon-12                                12 e-3                (exact)               kg mol^-1
+molar Planck constant                                  3.990 312 7176 e-10   0.000 000 0028 e-10   J s mol^-1
+molar Planck constant times c                          0.119 626 565 779     0.000 000 000 084     J m mol^-1
+molar volume of ideal gas (273.15 K, 100 kPa)          22.710 953 e-3        0.000 021 e-3         m^3 mol^-1
+molar volume of ideal gas (273.15 K, 101.325 kPa)      22.413 968 e-3        0.000 020 e-3         m^3 mol^-1
+molar volume of silicon                                12.058 833 01 e-6     0.000 000 80 e-6      m^3 mol^-1
+Mo x unit                                              1.002 099 52 e-13     0.000 000 53 e-13     m
+muon Compton wavelength                                11.734 441 03 e-15    0.000 000 30 e-15     m
+muon Compton wavelength over 2 pi                      1.867 594 294 e-15    0.000 000 047 e-15    m
+muon-electron mass ratio                               206.768 2843          0.000 0052
+muon g factor                                          -2.002 331 8418       0.000 000 0013
+muon mag. mom.                                         -4.490 448 07 e-26    0.000 000 15 e-26     J T^-1
+muon mag. mom. anomaly                                 1.165 920 91 e-3      0.000 000 63 e-3
+muon mag. mom. to Bohr magneton ratio                  -4.841 970 44 e-3     0.000 000 12 e-3
+muon mag. mom. to nuclear magneton ratio               -8.890 596 97         0.000 000 22
+muon mass                                              1.883 531 475 e-28    0.000 000 096 e-28    kg
+muon mass energy equivalent                            1.692 833 667 e-11    0.000 000 086 e-11    J
+muon mass energy equivalent in MeV                     105.658 3715          0.000 0035            MeV
+muon mass in u                                         0.113 428 9267        0.000 000 0029        u
+muon molar mass                                        0.113 428 9267 e-3    0.000 000 0029 e-3    kg mol^-1
+muon-neutron mass ratio                                0.112 454 5177        0.000 000 0028
+muon-proton mag. mom. ratio                            -3.183 345 107        0.000 000 084
+muon-proton mass ratio                                 0.112 609 5272        0.000 000 0028
+muon-tau mass ratio                                    5.946 49 e-2          0.000 54 e-2
+natural unit of action                                 1.054 571 726 e-34    0.000 000 047 e-34    J s
+natural unit of action in eV s                         6.582 119 28 e-16     0.000 000 15 e-16     eV s
+natural unit of energy                                 8.187 105 06 e-14     0.000 000 36 e-14     J
+natural unit of energy in MeV                          0.510 998 928         0.000 000 011         MeV
+natural unit of length                                 386.159 268 00 e-15   0.000 000 25 e-15     m
+natural unit of mass                                   9.109 382 91 e-31     0.000 000 40 e-31     kg
+natural unit of mom.um                                 2.730 924 29 e-22     0.000 000 12 e-22     kg m s^-1
+natural unit of mom.um in MeV/c                        0.510 998 928         0.000 000 011         MeV/c
+natural unit of time                                   1.288 088 668 33 e-21 0.000 000 000 83 e-21 s
+natural unit of velocity                               299 792 458           (exact)               m s^-1
+neutron Compton wavelength                             1.319 590 9068 e-15   0.000 000 0011 e-15   m
+neutron Compton wavelength over 2 pi                   0.210 019 415 68 e-15 0.000 000 000 17 e-15 m
+neutron-electron mag. mom. ratio                       1.040 668 82 e-3      0.000 000 25 e-3
+neutron-electron mass ratio                            1838.683 6605         0.000 0011
+neutron g factor                                       -3.826 085 45         0.000 000 90
+neutron gyromag. ratio                                 1.832 471 79 e8       0.000 000 43 e8       s^-1 T^-1
+neutron gyromag. ratio over 2 pi                       29.164 6943           0.000 0069            MHz T^-1
+neutron mag. mom.                                      -0.966 236 47 e-26    0.000 000 23 e-26     J T^-1
+neutron mag. mom. to Bohr magneton ratio               -1.041 875 63 e-3     0.000 000 25 e-3
+neutron mag. mom. to nuclear magneton ratio            -1.913 042 72         0.000 000 45
+neutron mass                                           1.674 927 351 e-27    0.000 000 074 e-27    kg
+neutron mass energy equivalent                         1.505 349 631 e-10    0.000 000 066 e-10    J
+neutron mass energy equivalent in MeV                  939.565 379           0.000 021             MeV
+neutron mass in u                                      1.008 664 916 00      0.000 000 000 43      u
+neutron molar mass                                     1.008 664 916 00 e-3  0.000 000 000 43 e-3  kg mol^-1
+neutron-muon mass ratio                                8.892 484 00          0.000 000 22
+neutron-proton mag. mom. ratio                         -0.684 979 34         0.000 000 16
+neutron-proton mass difference                         2.305 573 92 e-30     0.000 000 76 e-30
+neutron-proton mass difference energy equivalent       2.072 146 50 e-13     0.000 000 68 e-13
+neutron-proton mass difference energy equivalent in MeV 1.293 332 17          0.000 000 42
+neutron-proton mass difference in u                    0.001 388 449 19      0.000 000 000 45
+neutron-proton mass ratio                              1.001 378 419 17      0.000 000 000 45
+neutron-tau mass ratio                                 0.528 790             0.000 048
+neutron to shielded proton mag. mom. ratio             -0.684 996 94         0.000 000 16
+Newtonian constant of gravitation                      6.673 84 e-11         0.000 80 e-11         m^3 kg^-1 s^-2
+Newtonian constant of gravitation over h-bar c         6.708 37 e-39         0.000 80 e-39         (GeV/c^2)^-2
+nuclear magneton                                       5.050 783 53 e-27     0.000 000 11 e-27     J T^-1
+nuclear magneton in eV/T                               3.152 451 2605 e-8    0.000 000 0022 e-8    eV T^-1
+nuclear magneton in inverse meters per tesla           2.542 623 527 e-2     0.000 000 056 e-2     m^-1 T^-1
+nuclear magneton in K/T                                3.658 2682 e-4        0.000 0033 e-4        K T^-1
+nuclear magneton in MHz/T                              7.622 593 57          0.000 000 17          MHz T^-1
+Planck constant                                        6.626 069 57 e-34     0.000 000 29 e-34     J s
+Planck constant in eV s                                4.135 667 516 e-15    0.000 000 091 e-15    eV s
+Planck constant over 2 pi                              1.054 571 726 e-34    0.000 000 047 e-34    J s
+Planck constant over 2 pi in eV s                      6.582 119 28 e-16     0.000 000 15 e-16     eV s
+Planck constant over 2 pi times c in MeV fm            197.326 9718          0.000 0044            MeV fm
+Planck length                                          1.616 199 e-35        0.000 097 e-35        m
+Planck mass                                            2.176 51 e-8          0.000 13 e-8          kg
+Planck mass energy equivalent in GeV                   1.220 932 e19         0.000 073 e19         GeV
+Planck temperature                                     1.416 833 e32         0.000 085 e32         K
+Planck time                                            5.391 06 e-44         0.000 32 e-44         s
+proton charge to mass quotient                         9.578 833 58 e7       0.000 000 21 e7       C kg^-1
+proton Compton wavelength                              1.321 409 856 23 e-15 0.000 000 000 94 e-15 m
+proton Compton wavelength over 2 pi                    0.210 308 910 47 e-15 0.000 000 000 15 e-15 m
+proton-electron mass ratio                             1836.152 672 45       0.000 000 75
+proton g factor                                        5.585 694 713         0.000 000 046
+proton gyromag. ratio                                  2.675 222 005 e8      0.000 000 063 e8      s^-1 T^-1
+proton gyromag. ratio over 2 pi                        42.577 4806           0.000 0010            MHz T^-1
+proton mag. mom.                                       1.410 606 743 e-26    0.000 000 033 e-26    J T^-1
+proton mag. mom. to Bohr magneton ratio                1.521 032 210 e-3     0.000 000 012 e-3
+proton mag. mom. to nuclear magneton ratio             2.792 847 356         0.000 000 023
+proton mag. shielding correction                       25.694 e-6            0.014 e-6
+proton mass                                            1.672 621 777 e-27    0.000 000 074 e-27    kg
+proton mass energy equivalent                          1.503 277 484 e-10    0.000 000 066 e-10    J
+proton mass energy equivalent in MeV                   938.272 046           0.000 021             MeV
+proton mass in u                                       1.007 276 466 812     0.000 000 000 090     u
+proton molar mass                                      1.007 276 466 812 e-3 0.000 000 000 090 e-3 kg mol^-1
+proton-muon mass ratio                                 8.880 243 31          0.000 000 22
+proton-neutron mag. mom. ratio                         -1.459 898 06         0.000 000 34
+proton-neutron mass ratio                              0.998 623 478 26      0.000 000 000 45
+proton rms charge radius                               0.8775 e-15           0.0051 e-15           m
+proton-tau mass ratio                                  0.528 063             0.000 048
+quantum of circulation                                 3.636 947 5520 e-4    0.000 000 0024 e-4    m^2 s^-1
+quantum of circulation times 2                         7.273 895 1040 e-4    0.000 000 0047 e-4    m^2 s^-1
+Rydberg constant                                       10 973 731.568 539    0.000 055             m^-1
+Rydberg constant times c in Hz                         3.289 841 960 364 e15 0.000 000 000 017 e15 Hz
+Rydberg constant times hc in eV                        13.605 692 53         0.000 000 30          eV
+Rydberg constant times hc in J                         2.179 872 171 e-18    0.000 000 096 e-18    J
+Sackur-Tetrode constant (1 K, 100 kPa)                 -1.151 7078           0.000 0023
+Sackur-Tetrode constant (1 K, 101.325 kPa)             -1.164 8708           0.000 0023
+second radiation constant                              1.438 7770 e-2        0.000 0013 e-2        m K
+shielded helion gyromag. ratio                         2.037 894 659 e8      0.000 000 051 e8      s^-1 T^-1
+shielded helion gyromag. ratio over 2 pi               32.434 100 84         0.000 000 81          MHz T^-1
+shielded helion mag. mom.                              -1.074 553 044 e-26   0.000 000 027 e-26    J T^-1
+shielded helion mag. mom. to Bohr magneton ratio       -1.158 671 471 e-3    0.000 000 014 e-3
+shielded helion mag. mom. to nuclear magneton ratio    -2.127 497 718        0.000 000 025
+shielded helion to proton mag. mom. ratio              -0.761 766 558        0.000 000 011
+shielded helion to shielded proton mag. mom. ratio     -0.761 786 1313       0.000 000 0033
+shielded proton gyromag. ratio                         2.675 153 268 e8      0.000 000 066 e8      s^-1 T^-1
+shielded proton gyromag. ratio over 2 pi               42.576 3866           0.000 0010            MHz T^-1
+shielded proton mag. mom.                              1.410 570 499 e-26    0.000 000 035 e-26    J T^-1
+shielded proton mag. mom. to Bohr magneton ratio       1.520 993 128 e-3     0.000 000 017 e-3
+shielded proton mag. mom. to nuclear magneton ratio    2.792 775 598         0.000 000 030
+speed of light in vacuum                               299 792 458           (exact)               m s^-1
+standard acceleration of gravity                       9.806 65              (exact)               m s^-2
+standard atmosphere                                    101 325               (exact)               Pa
+standard-state pressure                                100 000               (exact)               Pa
+Stefan-Boltzmann constant                              5.670 373 e-8         0.000 021 e-8         W m^-2 K^-4
+tau Compton wavelength                                 0.697 787 e-15        0.000 063 e-15        m
+tau Compton wavelength over 2 pi                       0.111 056 e-15        0.000 010 e-15        m
+tau-electron mass ratio                                3477.15               0.31
+tau mass                                               3.167 47 e-27         0.000 29 e-27         kg
+tau mass energy equivalent                             2.846 78 e-10         0.000 26 e-10         J
+tau mass energy equivalent in MeV                      1776.82               0.16                  MeV
+tau mass in u                                          1.907 49              0.000 17              u
+tau molar mass                                         1.907 49 e-3          0.000 17 e-3          kg mol^-1
+tau-muon mass ratio                                    16.8167               0.0015
+tau-neutron mass ratio                                 1.891 11              0.000 17
+tau-proton mass ratio                                  1.893 72              0.000 17
+Thomson cross section                                  0.665 245 8734 e-28   0.000 000 0013 e-28   m^2
+triton-electron mass ratio                             5496.921 5267         0.000 0050
+triton g factor                                        5.957 924 896         0.000 000 076
+triton mag. mom.                                       1.504 609 447 e-26    0.000 000 038 e-26    J T^-1
+triton mag. mom. to Bohr magneton ratio                1.622 393 657 e-3     0.000 000 021 e-3
+triton mag. mom. to nuclear magneton ratio             2.978 962 448         0.000 000 038
+triton mass                                            5.007 356 30 e-27     0.000 000 22 e-27     kg
+triton mass energy equivalent                          4.500 387 41 e-10     0.000 000 20 e-10     J
+triton mass energy equivalent in MeV                   2808.921 005          0.000 062             MeV
+triton mass in u                                       3.015 500 7134        0.000 000 0025        u
+triton molar mass                                      3.015 500 7134 e-3    0.000 000 0025 e-3    kg mol^-1
+triton-proton mass ratio                               2.993 717 0308        0.000 000 0025
+unified atomic mass unit                               1.660 538 921 e-27    0.000 000 073 e-27    kg
+von Klitzing constant                                  25 812.807 4434       0.000 0084            ohm
+weak mixing angle                                      0.2223                0.0021
+Wien frequency displacement law constant               5.878 9254 e10        0.000 0053 e10        Hz K^-1
+Wien wavelength displacement law constant              2.897 7721 e-3        0.000 0026 e-3        m K"""
+
+
+exact2010 = exact2006
+
+
+txt2014 = """\
+{220} lattice spacing of silicon                       192.015 5714 e-12     0.000 0032 e-12       m
+alpha particle-electron mass ratio                     7294.299 541 36       0.000 000 24
+alpha particle mass                                    6.644 657 230 e-27    0.000 000 082 e-27    kg
+alpha particle mass energy equivalent                  5.971 920 097 e-10    0.000 000 073 e-10    J
+alpha particle mass energy equivalent in MeV           3727.379 378          0.000 023             MeV
+alpha particle mass in u                               4.001 506 179 127     0.000 000 000 063     u
+alpha particle molar mass                              4.001 506 179 127 e-3 0.000 000 000 063 e-3 kg mol^-1
+alpha particle-proton mass ratio                       3.972 599 689 07      0.000 000 000 36
+Angstrom star                                          1.000 014 95 e-10     0.000 000 90 e-10     m
+atomic mass constant                                   1.660 539 040 e-27    0.000 000 020 e-27    kg
+atomic mass constant energy equivalent                 1.492 418 062 e-10    0.000 000 018 e-10    J
+atomic mass constant energy equivalent in MeV          931.494 0954          0.000 0057            MeV
+atomic mass unit-electron volt relationship            931.494 0954 e6       0.000 0057 e6         eV
+atomic mass unit-hartree relationship                  3.423 177 6902 e7     0.000 000 0016 e7     E_h
+atomic mass unit-hertz relationship                    2.252 342 7206 e23    0.000 000 0010 e23    Hz
+atomic mass unit-inverse meter relationship            7.513 006 6166 e14    0.000 000 0034 e14    m^-1
+atomic mass unit-joule relationship                    1.492 418 062 e-10    0.000 000 018 e-10    J
+atomic mass unit-kelvin relationship                   1.080 954 38 e13      0.000 000 62 e13      K
+atomic mass unit-kilogram relationship                 1.660 539 040 e-27    0.000 000 020 e-27    kg
+atomic unit of 1st hyperpolarizability                 3.206 361 329 e-53    0.000 000 020 e-53    C^3 m^3 J^-2
+atomic unit of 2nd hyperpolarizability                 6.235 380 085 e-65    0.000 000 077 e-65    C^4 m^4 J^-3
+atomic unit of action                                  1.054 571 800 e-34    0.000 000 013 e-34    J s
+atomic unit of charge                                  1.602 176 6208 e-19   0.000 000 0098 e-19   C
+atomic unit of charge density                          1.081 202 3770 e12    0.000 000 0067 e12    C m^-3
+atomic unit of current                                 6.623 618 183 e-3     0.000 000 041 e-3     A
+atomic unit of electric dipole mom.                    8.478 353 552 e-30    0.000 000 052 e-30    C m
+atomic unit of electric field                          5.142 206 707 e11     0.000 000 032 e11     V m^-1
+atomic unit of electric field gradient                 9.717 362 356 e21     0.000 000 060 e21     V m^-2
+atomic unit of electric polarizability                 1.648 777 2731 e-41   0.000 000 0011 e-41   C^2 m^2 J^-1
+atomic unit of electric potential                      27.211 386 02         0.000 000 17          V
+atomic unit of electric quadrupole mom.                4.486 551 484 e-40    0.000 000 028 e-40    C m^2
+atomic unit of energy                                  4.359 744 650 e-18    0.000 000 054 e-18    J
+atomic unit of force                                   8.238 723 36 e-8      0.000 000 10 e-8      N
+atomic unit of length                                  0.529 177 210 67 e-10 0.000 000 000 12 e-10 m
+atomic unit of mag. dipole mom.                        1.854 801 999 e-23    0.000 000 011 e-23    J T^-1
+atomic unit of mag. flux density                       2.350 517 550 e5      0.000 000 014 e5      T
+atomic unit of magnetizability                         7.891 036 5886 e-29   0.000 000 0090 e-29   J T^-2
+atomic unit of mass                                    9.109 383 56 e-31     0.000 000 11 e-31     kg
+atomic unit of mom.um                                  1.992 851 882 e-24    0.000 000 024 e-24    kg m s^-1
+atomic unit of permittivity                            1.112 650 056... e-10 (exact)               F m^-1
+atomic unit of time                                    2.418 884 326509e-17  0.000 000 000014e-17  s
+atomic unit of velocity                                2.187 691 262 77 e6   0.000 000 000 50 e6   m s^-1
+Avogadro constant                                      6.022 140 857 e23     0.000 000 074 e23     mol^-1
+Bohr magneton                                          927.400 9994 e-26     0.000 0057 e-26       J T^-1
+Bohr magneton in eV/T                                  5.788 381 8012 e-5    0.000 000 0026 e-5    eV T^-1
+Bohr magneton in Hz/T                                  13.996 245 042 e9     0.000 000 086 e9      Hz T^-1
+Bohr magneton in inverse meters per tesla              46.686 448 14         0.000 000 29          m^-1 T^-1
+Bohr magneton in K/T                                   0.671 714 05          0.000 000 39          K T^-1
+Bohr radius                                            0.529 177 210 67 e-10 0.000 000 000 12 e-10 m
+Boltzmann constant                                     1.380 648 52 e-23     0.000 000 79 e-23     J K^-1
+Boltzmann constant in eV/K                             8.617 3303 e-5        0.000 0050 e-5        eV K^-1
+Boltzmann constant in Hz/K                             2.083 6612 e10        0.000 0012 e10        Hz K^-1
+Boltzmann constant in inverse meters per kelvin        69.503 457            0.000 040             m^-1 K^-1
+characteristic impedance of vacuum                     376.730 313 461...    (exact)               ohm
+classical electron radius                              2.817 940 3227 e-15   0.000 000 0019 e-15   m
+Compton wavelength                                     2.426 310 2367 e-12   0.000 000 0011 e-12   m
+Compton wavelength over 2 pi                           386.159 267 64 e-15   0.000 000 18 e-15     m
+conductance quantum                                    7.748 091 7310 e-5    0.000 000 0018 e-5    S
+conventional value of Josephson constant               483 597.9 e9          (exact)               Hz V^-1
+conventional value of von Klitzing constant            25 812.807            (exact)               ohm
+Cu x unit                                              1.002 076 97 e-13     0.000 000 28 e-13     m
+deuteron-electron mag. mom. ratio                      -4.664 345 535 e-4    0.000 000 026 e-4
+deuteron-electron mass ratio                           3670.482 967 85       0.000 000 13
+deuteron g factor                                      0.857 438 2311        0.000 000 0048
+deuteron mag. mom.                                     0.433 073 5040 e-26   0.000 000 0036 e-26   J T^-1
+deuteron mag. mom. to Bohr magneton ratio              0.466 975 4554 e-3    0.000 000 0026 e-3
+deuteron mag. mom. to nuclear magneton ratio           0.857 438 2311        0.000 000 0048
+deuteron mass                                          3.343 583 719 e-27    0.000 000 041 e-27    kg
+deuteron mass energy equivalent                        3.005 063 183 e-10    0.000 000 037 e-10    J
+deuteron mass energy equivalent in MeV                 1875.612 928          0.000 012             MeV
+deuteron mass in u                                     2.013 553 212 745     0.000 000 000 040     u
+deuteron molar mass                                    2.013 553 212 745 e-3 0.000 000 000 040 e-3 kg mol^-1
+deuteron-neutron mag. mom. ratio                       -0.448 206 52         0.000 000 11
+deuteron-proton mag. mom. ratio                        0.307 012 2077        0.000 000 0015
+deuteron-proton mass ratio                             1.999 007 500 87      0.000 000 000 19
+deuteron rms charge radius                             2.1413 e-15           0.0025 e-15           m
+electric constant                                      8.854 187 817... e-12 (exact)               F m^-1
+electron charge to mass quotient                       -1.758 820 024 e11    0.000 000 011 e11     C kg^-1
+electron-deuteron mag. mom. ratio                      -2143.923 499         0.000 012
+electron-deuteron mass ratio                           2.724 437 107 484 e-4 0.000 000 000 096 e-4
+electron g factor                                      -2.002 319 304 361 82 0.000 000 000 000 52
+electron gyromag. ratio                                1.760 859 644 e11     0.000 000 011 e11     s^-1 T^-1
+electron gyromag. ratio over 2 pi                      28 024.951 64         0.000 17              MHz T^-1
+electron-helion mass ratio                             1.819 543 074 854 e-4 0.000 000 000 088 e-4
+electron mag. mom.                                     -928.476 4620 e-26    0.000 0057 e-26       J T^-1
+electron mag. mom. anomaly                             1.159 652 180 91 e-3  0.000 000 000 26 e-3
+electron mag. mom. to Bohr magneton ratio              -1.001 159 652 180 91 0.000 000 000 000 26
+electron mag. mom. to nuclear magneton ratio           -1838.281 972 34      0.000 000 17
+electron mass                                          9.109 383 56 e-31     0.000 000 11 e-31     kg
+electron mass energy equivalent                        8.187 105 65 e-14     0.000 000 10 e-14     J
+electron mass energy equivalent in MeV                 0.510 998 9461        0.000 000 0031        MeV
+electron mass in u                                     5.485 799 090 70 e-4  0.000 000 000 16 e-4  u
+electron molar mass                                    5.485 799 090 70 e-7  0.000 000 000 16 e-7  kg mol^-1
+electron-muon mag. mom. ratio                          206.766 9880          0.000 0046
+electron-muon mass ratio                               4.836 331 70 e-3      0.000 000 11 e-3
+electron-neutron mag. mom. ratio                       960.920 50            0.000 23
+electron-neutron mass ratio                            5.438 673 4428 e-4    0.000 000 0027 e-4
+electron-proton mag. mom. ratio                        -658.210 6866         0.000 0020
+electron-proton mass ratio                             5.446 170 213 52 e-4  0.000 000 000 52 e-4
+electron-tau mass ratio                                2.875 92 e-4          0.000 26 e-4
+electron to alpha particle mass ratio                  1.370 933 554 798 e-4 0.000 000 000 045 e-4
+electron to shielded helion mag. mom. ratio            864.058 257           0.000 010
+electron to shielded proton mag. mom. ratio            -658.227 5971         0.000 0072
+electron-triton mass ratio                             1.819 200 062 203 e-4 0.000 000 000 084 e-4
+electron volt                                          1.602 176 6208 e-19   0.000 000 0098 e-19   J
+electron volt-atomic mass unit relationship            1.073 544 1105 e-9    0.000 000 0066 e-9    u
+electron volt-hartree relationship                     3.674 932 248 e-2     0.000 000 023 e-2     E_h
+electron volt-hertz relationship                       2.417 989 262 e14     0.000 000 015 e14     Hz
+electron volt-inverse meter relationship               8.065 544 005 e5      0.000 000 050 e5      m^-1
+electron volt-joule relationship                       1.602 176 6208 e-19   0.000 000 0098 e-19   J
+electron volt-kelvin relationship                      1.160 452 21 e4       0.000 000 67 e4       K
+electron volt-kilogram relationship                    1.782 661 907 e-36    0.000 000 011 e-36    kg
+elementary charge                                      1.602 176 6208 e-19   0.000 000 0098 e-19   C
+elementary charge over h                               2.417 989 262 e14     0.000 000 015 e14     A J^-1
+Faraday constant                                       96 485.332 89         0.000 59              C mol^-1
+Faraday constant for conventional electric current     96 485.3251           0.0012                C_90 mol^-1
+Fermi coupling constant                                1.166 3787 e-5        0.000 0006 e-5        GeV^-2
+fine-structure constant                                7.297 352 5664 e-3    0.000 000 0017 e-3
+first radiation constant                               3.741 771 790 e-16    0.000 000 046 e-16    W m^2
+first radiation constant for spectral radiance         1.191 042 953 e-16    0.000 000 015 e-16    W m^2 sr^-1
+hartree-atomic mass unit relationship                  2.921 262 3197 e-8    0.000 000 0013 e-8    u
+hartree-electron volt relationship                     27.211 386 02         0.000 000 17          eV
+Hartree energy                                         4.359 744 650 e-18    0.000 000 054 e-18    J
+Hartree energy in eV                                   27.211 386 02         0.000 000 17          eV
+hartree-hertz relationship                             6.579 683 920 711 e15 0.000 000 000 039 e15 Hz
+hartree-inverse meter relationship                     2.194 746 313 702 e7  0.000 000 000 013 e7  m^-1
+hartree-joule relationship                             4.359 744 650 e-18    0.000 000 054 e-18    J
+hartree-kelvin relationship                            3.157 7513 e5         0.000 0018 e5         K
+hartree-kilogram relationship                          4.850 870 129 e-35    0.000 000 060 e-35    kg
+helion-electron mass ratio                             5495.885 279 22       0.000 000 27
+helion g factor                                        -4.255 250 616        0.000 000 050
+helion mag. mom.                                       -1.074 617 522 e-26   0.000 000 014 e-26    J T^-1
+helion mag. mom. to Bohr magneton ratio                -1.158 740 958 e-3    0.000 000 014 e-3
+helion mag. mom. to nuclear magneton ratio             -2.127 625 308        0.000 000 025
+helion mass                                            5.006 412 700 e-27    0.000 000 062 e-27    kg
+helion mass energy equivalent                          4.499 539 341 e-10    0.000 000 055 e-10    J
+helion mass energy equivalent in MeV                   2808.391 586          0.000 017             MeV
+helion mass in u                                       3.014 932 246 73      0.000 000 000 12      u
+helion molar mass                                      3.014 932 246 73 e-3  0.000 000 000 12 e-3  kg mol^-1
+helion-proton mass ratio                               2.993 152 670 46      0.000 000 000 29
+hertz-atomic mass unit relationship                    4.439 821 6616 e-24   0.000 000 0020 e-24   u
+hertz-electron volt relationship                       4.135 667 662 e-15    0.000 000 025 e-15    eV
+hertz-hartree relationship                             1.5198298460088 e-16  0.0000000000090e-16   E_h
+hertz-inverse meter relationship                       3.335 640 951... e-9  (exact)               m^-1
+hertz-joule relationship                               6.626 070 040 e-34    0.000 000 081 e-34    J
+hertz-kelvin relationship                              4.799 2447 e-11       0.000 0028 e-11       K
+hertz-kilogram relationship                            7.372 497 201 e-51    0.000 000 091 e-51    kg
+inverse fine-structure constant                        137.035 999 139       0.000 000 031
+inverse meter-atomic mass unit relationship            1.331 025 049 00 e-15 0.000 000 000 61 e-15 u
+inverse meter-electron volt relationship               1.239 841 9739 e-6    0.000 000 0076 e-6    eV
+inverse meter-hartree relationship                     4.556 335 252 767 e-8 0.000 000 000 027 e-8 E_h
+inverse meter-hertz relationship                       299 792 458           (exact)               Hz
+inverse meter-joule relationship                       1.986 445 824 e-25    0.000 000 024 e-25    J
+inverse meter-kelvin relationship                      1.438 777 36 e-2      0.000 000 83 e-2      K
+inverse meter-kilogram relationship                    2.210 219 057 e-42    0.000 000 027 e-42    kg
+inverse of conductance quantum                         12 906.403 7278       0.000 0029            ohm
+Josephson constant                                     483 597.8525 e9       0.0030 e9             Hz V^-1
+joule-atomic mass unit relationship                    6.700 535 363 e9      0.000 000 082 e9      u
+joule-electron volt relationship                       6.241 509 126 e18     0.000 000 038 e18     eV
+joule-hartree relationship                             2.293 712 317 e17     0.000 000 028 e17     E_h
+joule-hertz relationship                               1.509 190 205 e33     0.000 000 019 e33     Hz
+joule-inverse meter relationship                       5.034 116 651 e24     0.000 000 062 e24     m^-1
+joule-kelvin relationship                              7.242 9731 e22        0.000 0042 e22        K
+joule-kilogram relationship                            1.112 650 056... e-17 (exact)               kg
+kelvin-atomic mass unit relationship                   9.251 0842 e-14       0.000 0053 e-14       u
+kelvin-electron volt relationship                      8.617 3303 e-5        0.000 0050 e-5        eV
+kelvin-hartree relationship                            3.166 8105 e-6        0.000 0018 e-6        E_h
+kelvin-hertz relationship                              2.083 6612 e10        0.000 0012 e10        Hz
+kelvin-inverse meter relationship                      69.503 457            0.000 040             m^-1
+kelvin-joule relationship                              1.380 648 52 e-23     0.000 000 79 e-23     J
+kelvin-kilogram relationship                           1.536 178 65 e-40     0.000 000 88 e-40     kg
+kilogram-atomic mass unit relationship                 6.022 140 857 e26     0.000 000 074 e26     u
+kilogram-electron volt relationship                    5.609 588 650 e35     0.000 000 034 e35     eV
+kilogram-hartree relationship                          2.061 485 823 e34     0.000 000 025 e34     E_h
+kilogram-hertz relationship                            1.356 392 512 e50     0.000 000 017 e50     Hz
+kilogram-inverse meter relationship                    4.524 438 411 e41     0.000 000 056 e41     m^-1
+kilogram-joule relationship                            8.987 551 787... e16  (exact)               J
+kilogram-kelvin relationship                           6.509 6595 e39        0.000 0037 e39        K
+lattice parameter of silicon                           543.102 0504 e-12     0.000 0089 e-12       m
+Loschmidt constant (273.15 K, 100 kPa)                 2.651 6467 e25        0.000 0015 e25        m^-3
+Loschmidt constant (273.15 K, 101.325 kPa)             2.686 7811 e25        0.000 0015 e25        m^-3
+mag. constant                                          12.566 370 614... e-7 (exact)               N A^-2
+mag. flux quantum                                      2.067 833 831 e-15    0.000 000 013 e-15    Wb
+molar gas constant                                     8.314 4598            0.000 0048            J mol^-1 K^-1
+molar mass constant                                    1 e-3                 (exact)               kg mol^-1
+molar mass of carbon-12                                12 e-3                (exact)               kg mol^-1
+molar Planck constant                                  3.990 312 7110 e-10   0.000 000 0018 e-10   J s mol^-1
+molar Planck constant times c                          0.119 626 565 582     0.000 000 000 054     J m mol^-1
+molar volume of ideal gas (273.15 K, 100 kPa)          22.710 947 e-3        0.000 013 e-3         m^3 mol^-1
+molar volume of ideal gas (273.15 K, 101.325 kPa)      22.413 962 e-3        0.000 013 e-3         m^3 mol^-1
+molar volume of silicon                                12.058 832 14 e-6     0.000 000 61 e-6      m^3 mol^-1
+Mo x unit                                              1.002 099 52 e-13     0.000 000 53 e-13     m
+muon Compton wavelength                                11.734 441 11 e-15    0.000 000 26 e-15     m
+muon Compton wavelength over 2 pi                      1.867 594 308 e-15    0.000 000 042 e-15    m
+muon-electron mass ratio                               206.768 2826          0.000 0046
+muon g factor                                          -2.002 331 8418       0.000 000 0013
+muon mag. mom.                                         -4.490 448 26 e-26    0.000 000 10 e-26     J T^-1
+muon mag. mom. anomaly                                 1.165 920 89 e-3      0.000 000 63 e-3
+muon mag. mom. to Bohr magneton ratio                  -4.841 970 48 e-3     0.000 000 11 e-3
+muon mag. mom. to nuclear magneton ratio               -8.890 597 05         0.000 000 20
+muon mass                                              1.883 531 594 e-28    0.000 000 048 e-28    kg
+muon mass energy equivalent                            1.692 833 774 e-11    0.000 000 043 e-11    J
+muon mass energy equivalent in MeV                     105.658 3745          0.000 0024            MeV
+muon mass in u                                         0.113 428 9257        0.000 000 0025        u
+muon molar mass                                        0.113 428 9257 e-3    0.000 000 0025 e-3    kg mol^-1
+muon-neutron mass ratio                                0.112 454 5167        0.000 000 0025
+muon-proton mag. mom. ratio                            -3.183 345 142        0.000 000 071
+muon-proton mass ratio                                 0.112 609 5262        0.000 000 0025
+muon-tau mass ratio                                    5.946 49 e-2          0.000 54 e-2
+natural unit of action                                 1.054 571 800 e-34    0.000 000 013 e-34    J s
+natural unit of action in eV s                         6.582 119 514 e-16    0.000 000 040 e-16    eV s
+natural unit of energy                                 8.187 105 65 e-14     0.000 000 10 e-14     J
+natural unit of energy in MeV                          0.510 998 9461        0.000 000 0031        MeV
+natural unit of length                                 386.159 267 64 e-15   0.000 000 18 e-15     m
+natural unit of mass                                   9.109 383 56 e-31     0.000 000 11 e-31     kg
+natural unit of mom.um                                 2.730 924 488 e-22    0.000 000 034 e-22    kg m s^-1
+natural unit of mom.um in MeV/c                        0.510 998 9461        0.000 000 0031        MeV/c
+natural unit of time                                   1.288 088 667 12 e-21 0.000 000 000 58 e-21 s
+natural unit of velocity                               299 792 458           (exact)               m s^-1
+neutron Compton wavelength                             1.319 590 904 81 e-15 0.000 000 000 88 e-15 m
+neutron Compton wavelength over 2 pi                   0.210 019 415 36 e-15 0.000 000 000 14 e-15 m
+neutron-electron mag. mom. ratio                       1.040 668 82 e-3      0.000 000 25 e-3
+neutron-electron mass ratio                            1838.683 661 58       0.000 000 90
+neutron g factor                                       -3.826 085 45         0.000 000 90
+neutron gyromag. ratio                                 1.832 471 72 e8       0.000 000 43 e8       s^-1 T^-1
+neutron gyromag. ratio over 2 pi                       29.164 6933           0.000 0069            MHz T^-1
+neutron mag. mom.                                      -0.966 236 50 e-26    0.000 000 23 e-26     J T^-1
+neutron mag. mom. to Bohr magneton ratio               -1.041 875 63 e-3     0.000 000 25 e-3
+neutron mag. mom. to nuclear magneton ratio            -1.913 042 73         0.000 000 45
+neutron mass                                           1.674 927 471 e-27    0.000 000 021 e-27    kg
+neutron mass energy equivalent                         1.505 349 739 e-10    0.000 000 019 e-10    J
+neutron mass energy equivalent in MeV                  939.565 4133          0.000 0058            MeV
+neutron mass in u                                      1.008 664 915 88      0.000 000 000 49      u
+neutron molar mass                                     1.008 664 915 88 e-3  0.000 000 000 49 e-3  kg mol^-1
+neutron-muon mass ratio                                8.892 484 08          0.000 000 20
+neutron-proton mag. mom. ratio                         -0.684 979 34         0.000 000 16
+neutron-proton mass difference                         2.305 573 77 e-30     0.000 000 85 e-30
+neutron-proton mass difference energy equivalent       2.072 146 37 e-13     0.000 000 76 e-13
+neutron-proton mass difference energy equivalent in MeV 1.293 332 05         0.000 000 48
+neutron-proton mass difference in u                    0.001 388 449 00      0.000 000 000 51
+neutron-proton mass ratio                              1.001 378 418 98      0.000 000 000 51
+neutron-tau mass ratio                                 0.528 790             0.000 048
+neutron to shielded proton mag. mom. ratio             -0.684 996 94         0.000 000 16
+Newtonian constant of gravitation                      6.674 08 e-11         0.000 31 e-11         m^3 kg^-1 s^-2
+Newtonian constant of gravitation over h-bar c         6.708 61 e-39         0.000 31 e-39         (GeV/c^2)^-2
+nuclear magneton                                       5.050 783 699 e-27    0.000 000 031 e-27    J T^-1
+nuclear magneton in eV/T                               3.152 451 2550 e-8    0.000 000 0015 e-8    eV T^-1
+nuclear magneton in inverse meters per tesla           2.542 623 432 e-2     0.000 000 016 e-2     m^-1 T^-1
+nuclear magneton in K/T                                3.658 2690 e-4        0.000 0021 e-4        K T^-1
+nuclear magneton in MHz/T                              7.622 593 285         0.000 000 047         MHz T^-1
+Planck constant                                        6.626 070 040 e-34    0.000 000 081 e-34    J s
+Planck constant in eV s                                4.135 667 662 e-15    0.000 000 025 e-15    eV s
+Planck constant over 2 pi                              1.054 571 800 e-34    0.000 000 013 e-34    J s
+Planck constant over 2 pi in eV s                      6.582 119 514 e-16    0.000 000 040 e-16    eV s
+Planck constant over 2 pi times c in MeV fm            197.326 9788          0.000 0012            MeV fm
+Planck length                                          1.616 229 e-35        0.000 038 e-35        m
+Planck mass                                            2.176 470 e-8         0.000 051 e-8         kg
+Planck mass energy equivalent in GeV                   1.220 910 e19         0.000 029 e19         GeV
+Planck temperature                                     1.416 808 e32         0.000 033 e32         K
+Planck time                                            5.391 16 e-44         0.000 13 e-44         s
+proton charge to mass quotient                         9.578 833 226 e7      0.000 000 059 e7      C kg^-1
+proton Compton wavelength                              1.321 409 853 96 e-15 0.000 000 000 61 e-15 m
+proton Compton wavelength over 2 pi                    0.210 308910109e-15   0.000 000 000097e-15  m
+proton-electron mass ratio                             1836.152 673 89       0.000 000 17
+proton g factor                                        5.585 694 702         0.000 000 017
+proton gyromag. ratio                                  2.675 221 900 e8      0.000 000 018 e8      s^-1 T^-1
+proton gyromag. ratio over 2 pi                        42.577 478 92         0.000 000 29          MHz T^-1
+proton mag. mom.                                       1.410 606 7873 e-26   0.000 000 0097 e-26   J T^-1
+proton mag. mom. to Bohr magneton ratio                1.521 032 2053 e-3    0.000 000 0046 e-3
+proton mag. mom. to nuclear magneton ratio             2.792 847 3508        0.000 000 0085
+proton mag. shielding correction                       25.691 e-6            0.011 e-6
+proton mass                                            1.672 621 898 e-27    0.000 000 021 e-27    kg
+proton mass energy equivalent                          1.503 277 593 e-10    0.000 000 018 e-10    J
+proton mass energy equivalent in MeV                   938.272 0813          0.000 0058            MeV
+proton mass in u                                       1.007 276 466 879     0.000 000 000 091     u
+proton molar mass                                      1.007 276 466 879 e-3 0.000 000 000 091 e-3 kg mol^-1
+proton-muon mass ratio                                 8.880 243 38          0.000 000 20
+proton-neutron mag. mom. ratio                         -1.459 898 05         0.000 000 34
+proton-neutron mass ratio                              0.998 623 478 44      0.000 000 000 51
+proton rms charge radius                               0.8751 e-15           0.0061 e-15           m
+proton-tau mass ratio                                  0.528 063             0.000 048
+quantum of circulation                                 3.636 947 5486 e-4    0.000 000 0017 e-4    m^2 s^-1
+quantum of circulation times 2                         7.273 895 0972 e-4    0.000 000 0033 e-4    m^2 s^-1
+Rydberg constant                                       10 973 731.568 508    0.000 065             m^-1
+Rydberg constant times c in Hz                         3.289 841 960 355 e15 0.000 000 000 019 e15 Hz
+Rydberg constant times hc in eV                        13.605 693 009        0.000 000 084         eV
+Rydberg constant times hc in J                         2.179 872 325 e-18    0.000 000 027 e-18    J
+Sackur-Tetrode constant (1 K, 100 kPa)                 -1.151 7084           0.000 0014
+Sackur-Tetrode constant (1 K, 101.325 kPa)             -1.164 8714           0.000 0014
+second radiation constant                              1.438 777 36 e-2      0.000 000 83 e-2      m K
+shielded helion gyromag. ratio                         2.037 894 585 e8      0.000 000 027 e8      s^-1 T^-1
+shielded helion gyromag. ratio over 2 pi               32.434 099 66         0.000 000 43          MHz T^-1
+shielded helion mag. mom.                              -1.074 553 080 e-26   0.000 000 014 e-26    J T^-1
+shielded helion mag. mom. to Bohr magneton ratio       -1.158 671 471 e-3    0.000 000 014 e-3
+shielded helion mag. mom. to nuclear magneton ratio    -2.127 497 720        0.000 000 025
+shielded helion to proton mag. mom. ratio              -0.761 766 5603       0.000 000 0092
+shielded helion to shielded proton mag. mom. ratio     -0.761 786 1313       0.000 000 0033
+shielded proton gyromag. ratio                         2.675 153 171 e8      0.000 000 033 e8      s^-1 T^-1
+shielded proton gyromag. ratio over 2 pi               42.576 385 07         0.000 000 53          MHz T^-1
+shielded proton mag. mom.                              1.410 570 547 e-26    0.000 000 018 e-26    J T^-1
+shielded proton mag. mom. to Bohr magneton ratio       1.520 993 128 e-3     0.000 000 017 e-3
+shielded proton mag. mom. to nuclear magneton ratio    2.792 775 600         0.000 000 030
+speed of light in vacuum                               299 792 458           (exact)               m s^-1
+standard acceleration of gravity                       9.806 65              (exact)               m s^-2
+standard atmosphere                                    101 325               (exact)               Pa
+standard-state pressure                                100 000               (exact)               Pa
+Stefan-Boltzmann constant                              5.670 367 e-8         0.000 013 e-8         W m^-2 K^-4
+tau Compton wavelength                                 0.697 787 e-15        0.000 063 e-15        m
+tau Compton wavelength over 2 pi                       0.111 056 e-15        0.000 010 e-15        m
+tau-electron mass ratio                                3477.15               0.31
+tau mass                                               3.167 47 e-27         0.000 29 e-27         kg
+tau mass energy equivalent                             2.846 78 e-10         0.000 26 e-10         J
+tau mass energy equivalent in MeV                      1776.82               0.16                  MeV
+tau mass in u                                          1.907 49              0.000 17              u
+tau molar mass                                         1.907 49 e-3          0.000 17 e-3          kg mol^-1
+tau-muon mass ratio                                    16.8167               0.0015
+tau-neutron mass ratio                                 1.891 11              0.000 17
+tau-proton mass ratio                                  1.893 72              0.000 17
+Thomson cross section                                  0.665 245 871 58 e-28 0.000 000 000 91 e-28 m^2
+triton-electron mass ratio                             5496.921 535 88       0.000 000 26
+triton g factor                                        5.957 924 920         0.000 000 028
+triton mag. mom.                                       1.504 609 503 e-26    0.000 000 012 e-26    J T^-1
+triton mag. mom. to Bohr magneton ratio                1.622 393 6616 e-3    0.000 000 0076 e-3
+triton mag. mom. to nuclear magneton ratio             2.978 962 460         0.000 000 014
+triton mass                                            5.007 356 665 e-27    0.000 000 062 e-27    kg
+triton mass energy equivalent                          4.500 387 735 e-10    0.000 000 055 e-10    J
+triton mass energy equivalent in MeV                   2808.921 112          0.000 017             MeV
+triton mass in u                                       3.015 500 716 32      0.000 000 000 11      u
+triton molar mass                                      3.015 500 716 32 e-3  0.000 000 000 11 e-3  kg mol^-1
+triton-proton mass ratio                               2.993 717 033 48      0.000 000 000 22
+unified atomic mass unit                               1.660 539 040 e-27    0.000 000 020 e-27    kg
+von Klitzing constant                                  25 812.807 4555       0.000 0059            ohm
+weak mixing angle                                      0.2223                0.0021
+Wien frequency displacement law constant               5.878 9238 e10        0.000 0034 e10        Hz K^-1
+Wien wavelength displacement law constant              2.897 7729 e-3        0.000 0017 e-3        m K"""
+
+
+exact2014 = exact2010
+
+
+txt2018 = """\
+alpha particle-electron mass ratio                          7294.299 541 42          0.000 000 24
+alpha particle mass                                         6.644 657 3357 e-27      0.000 000 0020 e-27      kg
+alpha particle mass energy equivalent                       5.971 920 1914 e-10      0.000 000 0018 e-10      J
+alpha particle mass energy equivalent in MeV                3727.379 4066            0.000 0011               MeV
+alpha particle mass in u                                    4.001 506 179 127        0.000 000 000 063        u
+alpha particle molar mass                                   4.001 506 1777 e-3       0.000 000 0012 e-3       kg mol^-1
+alpha particle-proton mass ratio                            3.972 599 690 09         0.000 000 000 22
+alpha particle relative atomic mass                         4.001 506 179 127        0.000 000 000 063
+Angstrom star                                               1.000 014 95 e-10        0.000 000 90 e-10        m
+atomic mass constant                                        1.660 539 066 60 e-27    0.000 000 000 50 e-27    kg
+atomic mass constant energy equivalent                      1.492 418 085 60 e-10    0.000 000 000 45 e-10    J
+atomic mass constant energy equivalent in MeV               931.494 102 42           0.000 000 28             MeV
+atomic mass unit-electron volt relationship                 9.314 941 0242 e8        0.000 000 0028 e8        eV
+atomic mass unit-hartree relationship                       3.423 177 6874 e7        0.000 000 0010 e7        E_h
+atomic mass unit-hertz relationship                         2.252 342 718 71 e23     0.000 000 000 68 e23     Hz
+atomic mass unit-inverse meter relationship                 7.513 006 6104 e14       0.000 000 0023 e14       m^-1
+atomic mass unit-joule relationship                         1.492 418 085 60 e-10    0.000 000 000 45 e-10    J
+atomic mass unit-kelvin relationship                        1.080 954 019 16 e13     0.000 000 000 33 e13     K
+atomic mass unit-kilogram relationship                      1.660 539 066 60 e-27    0.000 000 000 50 e-27    kg
+atomic unit of 1st hyperpolarizability                      3.206 361 3061 e-53      0.000 000 0015 e-53      C^3 m^3 J^-2
+atomic unit of 2nd hyperpolarizability                      6.235 379 9905 e-65      0.000 000 0038 e-65      C^4 m^4 J^-3
+atomic unit of action                                       1.054 571 817... e-34    (exact)                  J s
+atomic unit of charge                                       1.602 176 634 e-19       (exact)                  C
+atomic unit of charge density                               1.081 202 384 57 e12     0.000 000 000 49 e12     C m^-3
+atomic unit of current                                      6.623 618 237 510 e-3    0.000 000 000 013 e-3    A
+atomic unit of electric dipole mom.                         8.478 353 6255 e-30      0.000 000 0013 e-30      C m
+atomic unit of electric field                               5.142 206 747 63 e11     0.000 000 000 78 e11     V m^-1
+atomic unit of electric field gradient                      9.717 362 4292 e21       0.000 000 0029 e21       V m^-2
+atomic unit of electric polarizability                      1.648 777 274 36 e-41    0.000 000 000 50 e-41    C^2 m^2 J^-1
+atomic unit of electric potential                           27.211 386 245 988       0.000 000 000 053        V
+atomic unit of electric quadrupole mom.                     4.486 551 5246 e-40      0.000 000 0014 e-40      C m^2
+atomic unit of energy                                       4.359 744 722 2071 e-18  0.000 000 000 0085 e-18  J
+atomic unit of force                                        8.238 723 4983 e-8       0.000 000 0012 e-8       N
+atomic unit of length                                       5.291 772 109 03 e-11    0.000 000 000 80 e-11    m
+atomic unit of mag. dipole mom.                             1.854 802 015 66 e-23    0.000 000 000 56 e-23    J T^-1
+atomic unit of mag. flux density                            2.350 517 567 58 e5      0.000 000 000 71 e5      T
+atomic unit of magnetizability                              7.891 036 6008 e-29      0.000 000 0048 e-29      J T^-2
+atomic unit of mass                                         9.109 383 7015 e-31      0.000 000 0028 e-31      kg
+atomic unit of momentum                                     1.992 851 914 10 e-24    0.000 000 000 30 e-24    kg m s^-1
+atomic unit of permittivity                                 1.112 650 055 45 e-10    0.000 000 000 17 e-10    F m^-1
+atomic unit of time                                         2.418 884 326 5857 e-17  0.000 000 000 0047 e-17  s
+atomic unit of velocity                                     2.187 691 263 64 e6      0.000 000 000 33 e6      m s^-1
+Avogadro constant                                           6.022 140 76 e23         (exact)                  mol^-1
+Bohr magneton                                               9.274 010 0783 e-24      0.000 000 0028 e-24      J T^-1
+Bohr magneton in eV/T                                       5.788 381 8060 e-5       0.000 000 0017 e-5       eV T^-1
+Bohr magneton in Hz/T                                       1.399 624 493 61 e10     0.000 000 000 42 e10     Hz T^-1
+Bohr magneton in inverse meter per tesla                    46.686 447 783           0.000 000 014            m^-1 T^-1
+Bohr magneton in K/T                                        0.671 713 815 63         0.000 000 000 20         K T^-1
+Bohr radius                                                 5.291 772 109 03 e-11    0.000 000 000 80 e-11    m
+Boltzmann constant                                          1.380 649 e-23           (exact)                  J K^-1
+Boltzmann constant in eV/K                                  8.617 333 262... e-5     (exact)                  eV K^-1
+Boltzmann constant in Hz/K                                  2.083 661 912... e10     (exact)                  Hz K^-1
+Boltzmann constant in inverse meter per kelvin              69.503 480 04...         (exact)                  m^-1 K^-1
+characteristic impedance of vacuum                          376.730 313 668          0.000 000 057            ohm
+classical electron radius                                   2.817 940 3262 e-15      0.000 000 0013 e-15      m
+Compton wavelength                                          2.426 310 238 67 e-12    0.000 000 000 73 e-12    m
+conductance quantum                                         7.748 091 729... e-5     (exact)                  S
+conventional value of ampere-90                             1.000 000 088 87...      (exact)                  A
+conventional value of coulomb-90                            1.000 000 088 87...      (exact)                  C
+conventional value of farad-90                              0.999 999 982 20...      (exact)                  F
+conventional value of henry-90                              1.000 000 017 79...      (exact)                  H
+conventional value of Josephson constant                    483 597.9 e9             (exact)                  Hz V^-1
+conventional value of ohm-90                                1.000 000 017 79...      (exact)                  ohm
+conventional value of volt-90                               1.000 000 106 66...      (exact)                  V
+conventional value of von Klitzing constant                 25 812.807               (exact)                  ohm
+conventional value of watt-90                               1.000 000 195 53...      (exact)                  W
+Cu x unit                                                   1.002 076 97 e-13        0.000 000 28 e-13        m
+deuteron-electron mag. mom. ratio                           -4.664 345 551 e-4       0.000 000 012 e-4
+deuteron-electron mass ratio                                3670.482 967 88          0.000 000 13
+deuteron g factor                                           0.857 438 2338           0.000 000 0022
+deuteron mag. mom.                                          4.330 735 094 e-27       0.000 000 011 e-27       J T^-1
+deuteron mag. mom. to Bohr magneton ratio                   4.669 754 570 e-4        0.000 000 012 e-4
+deuteron mag. mom. to nuclear magneton ratio                0.857 438 2338           0.000 000 0022
+deuteron mass                                               3.343 583 7724 e-27      0.000 000 0010 e-27      kg
+deuteron mass energy equivalent                             3.005 063 231 02 e-10    0.000 000 000 91 e-10    J
+deuteron mass energy equivalent in MeV                      1875.612 942 57          0.000 000 57             MeV
+deuteron mass in u                                          2.013 553 212 745        0.000 000 000 040        u
+deuteron molar mass                                         2.013 553 212 05 e-3     0.000 000 000 61 e-3     kg mol^-1
+deuteron-neutron mag. mom. ratio                            -0.448 206 53            0.000 000 11
+deuteron-proton mag. mom. ratio                             0.307 012 209 39         0.000 000 000 79
+deuteron-proton mass ratio                                  1.999 007 501 39         0.000 000 000 11
+deuteron relative atomic mass                               2.013 553 212 745        0.000 000 000 040
+deuteron rms charge radius                                  2.127 99 e-15            0.000 74 e-15            m
+electron charge to mass quotient                            -1.758 820 010 76 e11    0.000 000 000 53 e11     C kg^-1
+electron-deuteron mag. mom. ratio                           -2143.923 4915           0.000 0056
+electron-deuteron mass ratio                                2.724 437 107 462 e-4    0.000 000 000 096 e-4
+electron g factor                                           -2.002 319 304 362 56    0.000 000 000 000 35
+electron gyromag. ratio                                     1.760 859 630 23 e11     0.000 000 000 53 e11     s^-1 T^-1
+electron gyromag. ratio in MHz/T                            28 024.951 4242          0.000 0085               MHz T^-1
+electron-helion mass ratio                                  1.819 543 074 573 e-4    0.000 000 000 079 e-4
+electron mag. mom.                                          -9.284 764 7043 e-24     0.000 000 0028 e-24      J T^-1
+electron mag. mom. anomaly                                  1.159 652 181 28 e-3     0.000 000 000 18 e-3
+electron mag. mom. to Bohr magneton ratio                   -1.001 159 652 181 28    0.000 000 000 000 18
+electron mag. mom. to nuclear magneton ratio                -1838.281 971 88         0.000 000 11
+electron mass                                               9.109 383 7015 e-31      0.000 000 0028 e-31      kg
+electron mass energy equivalent                             8.187 105 7769 e-14      0.000 000 0025 e-14      J
+electron mass energy equivalent in MeV                      0.510 998 950 00         0.000 000 000 15         MeV
+electron mass in u                                          5.485 799 090 65 e-4     0.000 000 000 16 e-4     u
+electron molar mass                                         5.485 799 0888 e-7       0.000 000 0017 e-7       kg mol^-1
+electron-muon mag. mom. ratio                               206.766 9883             0.000 0046
+electron-muon mass ratio                                    4.836 331 69 e-3         0.000 000 11 e-3
+electron-neutron mag. mom. ratio                            960.920 50               0.000 23
+electron-neutron mass ratio                                 5.438 673 4424 e-4       0.000 000 0026 e-4
+electron-proton mag. mom. ratio                             -658.210 687 89          0.000 000 20
+electron-proton mass ratio                                  5.446 170 214 87 e-4     0.000 000 000 33 e-4
+electron relative atomic mass                               5.485 799 090 65 e-4     0.000 000 000 16 e-4
+electron-tau mass ratio                                     2.875 85 e-4             0.000 19 e-4
+electron to alpha particle mass ratio                       1.370 933 554 787 e-4    0.000 000 000 045 e-4
+electron to shielded helion mag. mom. ratio                 864.058 257              0.000 010
+electron to shielded proton mag. mom. ratio                 -658.227 5971            0.000 0072
+electron-triton mass ratio                                  1.819 200 062 251 e-4    0.000 000 000 090 e-4
+electron volt                                               1.602 176 634 e-19       (exact)                  J
+electron volt-atomic mass unit relationship                 1.073 544 102 33 e-9     0.000 000 000 32 e-9     u
+electron volt-hartree relationship                          3.674 932 217 5655 e-2   0.000 000 000 0071 e-2   E_h
+electron volt-hertz relationship                            2.417 989 242... e14     (exact)                  Hz
+electron volt-inverse meter relationship                    8.065 543 937... e5      (exact)                  m^-1
+electron volt-joule relationship                            1.602 176 634 e-19       (exact)                  J
+electron volt-kelvin relationship                           1.160 451 812... e4      (exact)                  K
+electron volt-kilogram relationship                         1.782 661 921... e-36    (exact)                  kg
+elementary charge                                           1.602 176 634 e-19       (exact)                  C
+elementary charge over h-bar                                1.519 267 447... e15     (exact)                  A J^-1
+Faraday constant                                            96 485.332 12...         (exact)                  C mol^-1
+Fermi coupling constant                                     1.166 3787 e-5           0.000 0006 e-5           GeV^-2
+fine-structure constant                                     7.297 352 5693 e-3       0.000 000 0011 e-3
+first radiation constant                                    3.741 771 852... e-16    (exact)                  W m^2
+first radiation constant for spectral radiance              1.191 042 972... e-16    (exact)                  W m^2 sr^-1
+hartree-atomic mass unit relationship                       2.921 262 322 05 e-8     0.000 000 000 88 e-8     u
+hartree-electron volt relationship                          27.211 386 245 988       0.000 000 000 053        eV
+Hartree energy                                              4.359 744 722 2071 e-18  0.000 000 000 0085 e-18  J
+Hartree energy in eV                                        27.211 386 245 988       0.000 000 000 053        eV
+hartree-hertz relationship                                  6.579 683 920 502 e15    0.000 000 000 013 e15    Hz
+hartree-inverse meter relationship                          2.194 746 313 6320 e7    0.000 000 000 0043 e7    m^-1
+hartree-joule relationship                                  4.359 744 722 2071 e-18  0.000 000 000 0085 e-18  J
+hartree-kelvin relationship                                 3.157 750 248 0407 e5    0.000 000 000 0061 e5    K
+hartree-kilogram relationship                               4.850 870 209 5432 e-35  0.000 000 000 0094 e-35  kg
+helion-electron mass ratio                                  5495.885 280 07          0.000 000 24
+helion g factor                                             -4.255 250 615           0.000 000 050
+helion mag. mom.                                            -1.074 617 532 e-26      0.000 000 013 e-26       J T^-1
+helion mag. mom. to Bohr magneton ratio                     -1.158 740 958 e-3       0.000 000 014 e-3
+helion mag. mom. to nuclear magneton ratio                  -2.127 625 307           0.000 000 025
+helion mass                                                 5.006 412 7796 e-27      0.000 000 0015 e-27      kg
+helion mass energy equivalent                               4.499 539 4125 e-10      0.000 000 0014 e-10      J
+helion mass energy equivalent in MeV                        2808.391 607 43          0.000 000 85             MeV
+helion mass in u                                            3.014 932 247 175        0.000 000 000 097        u
+helion molar mass                                           3.014 932 246 13 e-3     0.000 000 000 91 e-3     kg mol^-1
+helion-proton mass ratio                                    2.993 152 671 67         0.000 000 000 13
+helion relative atomic mass                                 3.014 932 247 175        0.000 000 000 097
+helion shielding shift                                      5.996 743 e-5            0.000 010 e-5
+hertz-atomic mass unit relationship                         4.439 821 6652 e-24      0.000 000 0013 e-24      u
+hertz-electron volt relationship                            4.135 667 696... e-15    (exact)                  eV
+hertz-hartree relationship                                  1.519 829 846 0570 e-16  0.000 000 000 0029 e-16  E_h
+hertz-inverse meter relationship                            3.335 640 951... e-9     (exact)                  m^-1
+hertz-joule relationship                                    6.626 070 15 e-34        (exact)                  J
+hertz-kelvin relationship                                   4.799 243 073... e-11    (exact)                  K
+hertz-kilogram relationship                                 7.372 497 323... e-51    (exact)                  kg
+hyperfine transition frequency of Cs-133                    9 192 631 770            (exact)                  Hz
+inverse fine-structure constant                             137.035 999 084          0.000 000 021
+inverse meter-atomic mass unit relationship                 1.331 025 050 10 e-15    0.000 000 000 40 e-15    u
+inverse meter-electron volt relationship                    1.239 841 984... e-6     (exact)                  eV
+inverse meter-hartree relationship                          4.556 335 252 9120 e-8   0.000 000 000 0088 e-8   E_h
+inverse meter-hertz relationship                            299 792 458              (exact)                  Hz
+inverse meter-joule relationship                            1.986 445 857... e-25    (exact)                  J
+inverse meter-kelvin relationship                           1.438 776 877... e-2     (exact)                  K
+inverse meter-kilogram relationship                         2.210 219 094... e-42    (exact)                  kg
+inverse of conductance quantum                              12 906.403 72...         (exact)                  ohm
+Josephson constant                                          483 597.848 4... e9      (exact)                  Hz V^-1
+joule-atomic mass unit relationship                         6.700 535 2565 e9        0.000 000 0020 e9        u
+joule-electron volt relationship                            6.241 509 074... e18     (exact)                  eV
+joule-hartree relationship                                  2.293 712 278 3963 e17   0.000 000 000 0045 e17   E_h
+joule-hertz relationship                                    1.509 190 179... e33     (exact)                  Hz
+joule-inverse meter relationship                            5.034 116 567... e24     (exact)                  m^-1
+joule-kelvin relationship                                   7.242 970 516... e22     (exact)                  K
+joule-kilogram relationship                                 1.112 650 056... e-17    (exact)                  kg
+kelvin-atomic mass unit relationship                        9.251 087 3014 e-14      0.000 000 0028 e-14      u
+kelvin-electron volt relationship                           8.617 333 262... e-5     (exact)                  eV
+kelvin-hartree relationship                                 3.166 811 563 4556 e-6   0.000 000 000 0061 e-6   E_h
+kelvin-hertz relationship                                   2.083 661 912... e10     (exact)                  Hz
+kelvin-inverse meter relationship                           69.503 480 04...         (exact)                  m^-1
+kelvin-joule relationship                                   1.380 649 e-23           (exact)                  J
+kelvin-kilogram relationship                                1.536 179 187... e-40    (exact)                  kg
+kilogram-atomic mass unit relationship                      6.022 140 7621 e26       0.000 000 0018 e26       u
+kilogram-electron volt relationship                         5.609 588 603... e35     (exact)                  eV
+kilogram-hartree relationship                               2.061 485 788 7409 e34   0.000 000 000 0040 e34   E_h
+kilogram-hertz relationship                                 1.356 392 489... e50     (exact)                  Hz
+kilogram-inverse meter relationship                         4.524 438 335... e41     (exact)                  m^-1
+kilogram-joule relationship                                 8.987 551 787... e16     (exact)                  J
+kilogram-kelvin relationship                                6.509 657 260... e39     (exact)                  K
+lattice parameter of silicon                                5.431 020 511 e-10       0.000 000 089 e-10       m
+lattice spacing of ideal Si (220)                           1.920 155 716 e-10       0.000 000 032 e-10       m
+Loschmidt constant (273.15 K, 100 kPa)                      2.651 645 804... e25     (exact)                  m^-3
+Loschmidt constant (273.15 K, 101.325 kPa)                  2.686 780 111... e25     (exact)                  m^-3
+luminous efficacy                                           683                      (exact)                  lm W^-1
+mag. flux quantum                                           2.067 833 848... e-15    (exact)                  Wb
+molar gas constant                                          8.314 462 618...         (exact)                  J mol^-1 K^-1
+molar mass constant                                         0.999 999 999 65 e-3     0.000 000 000 30 e-3     kg mol^-1
+molar mass of carbon-12                                     11.999 999 9958 e-3      0.000 000 0036 e-3       kg mol^-1
+molar Planck constant                                       3.990 312 712... e-10    (exact)                  J Hz^-1 mol^-1
+molar volume of ideal gas (273.15 K, 100 kPa)               22.710 954 64... e-3     (exact)                  m^3 mol^-1
+molar volume of ideal gas (273.15 K, 101.325 kPa)           22.413 969 54... e-3     (exact)                  m^3 mol^-1
+molar volume of silicon                                     1.205 883 199 e-5        0.000 000 060 e-5        m^3 mol^-1
+Mo x unit                                                   1.002 099 52 e-13        0.000 000 53 e-13        m
+muon Compton wavelength                                     1.173 444 110 e-14       0.000 000 026 e-14       m
+muon-electron mass ratio                                    206.768 2830             0.000 0046
+muon g factor                                               -2.002 331 8418          0.000 000 0013
+muon mag. mom.                                              -4.490 448 30 e-26       0.000 000 10 e-26        J T^-1
+muon mag. mom. anomaly                                      1.165 920 89 e-3         0.000 000 63 e-3
+muon mag. mom. to Bohr magneton ratio                       -4.841 970 47 e-3        0.000 000 11 e-3
+muon mag. mom. to nuclear magneton ratio                    -8.890 597 03            0.000 000 20
+muon mass                                                   1.883 531 627 e-28       0.000 000 042 e-28       kg
+muon mass energy equivalent                                 1.692 833 804 e-11       0.000 000 038 e-11       J
+muon mass energy equivalent in MeV                          105.658 3755             0.000 0023               MeV
+muon mass in u                                              0.113 428 9259           0.000 000 0025           u
+muon molar mass                                             1.134 289 259 e-4        0.000 000 025 e-4        kg mol^-1
+muon-neutron mass ratio                                     0.112 454 5170           0.000 000 0025
+muon-proton mag. mom. ratio                                 -3.183 345 142           0.000 000 071
+muon-proton mass ratio                                      0.112 609 5264           0.000 000 0025
+muon-tau mass ratio                                         5.946 35 e-2             0.000 40 e-2
+natural unit of action                                      1.054 571 817... e-34    (exact)                  J s
+natural unit of action in eV s                              6.582 119 569... e-16    (exact)                  eV s
+natural unit of energy                                      8.187 105 7769 e-14      0.000 000 0025 e-14      J
+natural unit of energy in MeV                               0.510 998 950 00         0.000 000 000 15         MeV
+natural unit of length                                      3.861 592 6796 e-13      0.000 000 0012 e-13      m
+natural unit of mass                                        9.109 383 7015 e-31      0.000 000 0028 e-31      kg
+natural unit of momentum                                    2.730 924 530 75 e-22    0.000 000 000 82 e-22    kg m s^-1
+natural unit of momentum in MeV/c                           0.510 998 950 00         0.000 000 000 15         MeV/c
+natural unit of time                                        1.288 088 668 19 e-21    0.000 000 000 39 e-21    s
+natural unit of velocity                                    299 792 458              (exact)                  m s^-1
+neutron Compton wavelength                                  1.319 590 905 81 e-15    0.000 000 000 75 e-15    m
+neutron-electron mag. mom. ratio                            1.040 668 82 e-3         0.000 000 25 e-3
+neutron-electron mass ratio                                 1838.683 661 73          0.000 000 89
+neutron g factor                                            -3.826 085 45            0.000 000 90
+neutron gyromag. ratio                                      1.832 471 71 e8          0.000 000 43 e8          s^-1 T^-1
+neutron gyromag. ratio in MHz/T                             29.164 6931              0.000 0069               MHz T^-1
+neutron mag. mom.                                           -9.662 3651 e-27         0.000 0023 e-27          J T^-1
+neutron mag. mom. to Bohr magneton ratio                    -1.041 875 63 e-3        0.000 000 25 e-3
+neutron mag. mom. to nuclear magneton ratio                 -1.913 042 73            0.000 000 45
+neutron mass                                                1.674 927 498 04 e-27    0.000 000 000 95 e-27    kg
+neutron mass energy equivalent                              1.505 349 762 87 e-10    0.000 000 000 86 e-10    J
+neutron mass energy equivalent in MeV                       939.565 420 52           0.000 000 54             MeV
+neutron mass in u                                           1.008 664 915 95         0.000 000 000 49         u
+neutron molar mass                                          1.008 664 915 60 e-3     0.000 000 000 57 e-3     kg mol^-1
+neutron-muon mass ratio                                     8.892 484 06             0.000 000 20
+neutron-proton mag. mom. ratio                              -0.684 979 34            0.000 000 16
+neutron-proton mass difference                              2.305 574 35 e-30        0.000 000 82 e-30        kg
+neutron-proton mass difference energy equivalent            2.072 146 89 e-13        0.000 000 74 e-13        J
+neutron-proton mass difference energy equivalent in MeV     1.293 332 36             0.000 000 46             MeV
+neutron-proton mass difference in u                         1.388 449 33 e-3         0.000 000 49 e-3         u
+neutron-proton mass ratio                                   1.001 378 419 31         0.000 000 000 49
+neutron relative atomic mass                                1.008 664 915 95         0.000 000 000 49
+neutron-tau mass ratio                                      0.528 779                0.000 036
+neutron to shielded proton mag. mom. ratio                  -0.684 996 94            0.000 000 16
+Newtonian constant of gravitation                           6.674 30 e-11            0.000 15 e-11            m^3 kg^-1 s^-2
+Newtonian constant of gravitation over h-bar c              6.708 83 e-39            0.000 15 e-39            (GeV/c^2)^-2
+nuclear magneton                                            5.050 783 7461 e-27      0.000 000 0015 e-27      J T^-1
+nuclear magneton in eV/T                                    3.152 451 258 44 e-8     0.000 000 000 96 e-8     eV T^-1
+nuclear magneton in inverse meter per tesla                 2.542 623 413 53 e-2     0.000 000 000 78 e-2     m^-1 T^-1
+nuclear magneton in K/T                                     3.658 267 7756 e-4       0.000 000 0011 e-4       K T^-1
+nuclear magneton in MHz/T                                   7.622 593 2291           0.000 000 0023           MHz T^-1
+Planck constant                                             6.626 070 15 e-34        (exact)                  J Hz^-1
+Planck constant in eV/Hz                                    4.135 667 696... e-15    (exact)                  eV Hz^-1
+Planck length                                               1.616 255 e-35           0.000 018 e-35           m
+Planck mass                                                 2.176 434 e-8            0.000 024 e-8            kg
+Planck mass energy equivalent in GeV                        1.220 890 e19            0.000 014 e19            GeV
+Planck temperature                                          1.416 784 e32            0.000 016 e32            K
+Planck time                                                 5.391 247 e-44           0.000 060 e-44           s
+proton charge to mass quotient                              9.578 833 1560 e7        0.000 000 0029 e7        C kg^-1
+proton Compton wavelength                                   1.321 409 855 39 e-15    0.000 000 000 40 e-15    m
+proton-electron mass ratio                                  1836.152 673 43          0.000 000 11
+proton g factor                                             5.585 694 6893           0.000 000 0016
+proton gyromag. ratio                                       2.675 221 8744 e8        0.000 000 0011 e8        s^-1 T^-1
+proton gyromag. ratio in MHz/T                              42.577 478 518           0.000 000 018            MHz T^-1
+proton mag. mom.                                            1.410 606 797 36 e-26    0.000 000 000 60 e-26    J T^-1
+proton mag. mom. to Bohr magneton ratio                     1.521 032 202 30 e-3     0.000 000 000 46 e-3
+proton mag. mom. to nuclear magneton ratio                  2.792 847 344 63         0.000 000 000 82
+proton mag. shielding correction                            2.5689 e-5               0.0011 e-5
+proton mass                                                 1.672 621 923 69 e-27    0.000 000 000 51 e-27    kg
+proton mass energy equivalent                               1.503 277 615 98 e-10    0.000 000 000 46 e-10    J
+proton mass energy equivalent in MeV                        938.272 088 16           0.000 000 29             MeV
+proton mass in u                                            1.007 276 466 621        0.000 000 000 053        u
+proton molar mass                                           1.007 276 466 27 e-3     0.000 000 000 31 e-3     kg mol^-1
+proton-muon mass ratio                                      8.880 243 37             0.000 000 20
+proton-neutron mag. mom. ratio                              -1.459 898 05            0.000 000 34
+proton-neutron mass ratio                                   0.998 623 478 12         0.000 000 000 49
+proton relative atomic mass                                 1.007 276 466 621        0.000 000 000 053
+proton rms charge radius                                    8.414 e-16               0.019 e-16               m
+proton-tau mass ratio                                       0.528 051                0.000 036
+quantum of circulation                                      3.636 947 5516 e-4       0.000 000 0011 e-4       m^2 s^-1
+quantum of circulation times 2                              7.273 895 1032 e-4       0.000 000 0022 e-4       m^2 s^-1
+reduced Compton wavelength                                  3.861 592 6796 e-13      0.000 000 0012 e-13      m
+reduced muon Compton wavelength                             1.867 594 306 e-15       0.000 000 042 e-15       m
+reduced neutron Compton wavelength                          2.100 194 1552 e-16      0.000 000 0012 e-16      m
+reduced Planck constant                                     1.054 571 817... e-34    (exact)                  J s
+reduced Planck constant in eV s                             6.582 119 569... e-16    (exact)                  eV s
+reduced Planck constant times c in MeV fm                   197.326 980 4...         (exact)                  MeV fm
+reduced proton Compton wavelength                           2.103 089 103 36 e-16    0.000 000 000 64 e-16    m
+reduced tau Compton wavelength                              1.110 538 e-16           0.000 075 e-16           m
+Rydberg constant                                            10 973 731.568 160       0.000 021                m^-1
+Rydberg constant times c in Hz                              3.289 841 960 2508 e15   0.000 000 000 0064 e15   Hz
+Rydberg constant times hc in eV                             13.605 693 122 994       0.000 000 000 026        eV
+Rydberg constant times hc in J                              2.179 872 361 1035 e-18  0.000 000 000 0042 e-18  J
+Sackur-Tetrode constant (1 K, 100 kPa)                      -1.151 707 537 06        0.000 000 000 45
+Sackur-Tetrode constant (1 K, 101.325 kPa)                  -1.164 870 523 58        0.000 000 000 45
+second radiation constant                                   1.438 776 877... e-2     (exact)                  m K
+shielded helion gyromag. ratio                              2.037 894 569 e8         0.000 000 024 e8         s^-1 T^-1
+shielded helion gyromag. ratio in MHz/T                     32.434 099 42            0.000 000 38             MHz T^-1
+shielded helion mag. mom.                                   -1.074 553 090 e-26      0.000 000 013 e-26       J T^-1
+shielded helion mag. mom. to Bohr magneton ratio            -1.158 671 471 e-3       0.000 000 014 e-3
+shielded helion mag. mom. to nuclear magneton ratio         -2.127 497 719           0.000 000 025
+shielded helion to proton mag. mom. ratio                   -0.761 766 5618          0.000 000 0089
+shielded helion to shielded proton mag. mom. ratio          -0.761 786 1313          0.000 000 0033
+shielded proton gyromag. ratio                              2.675 153 151 e8         0.000 000 029 e8         s^-1 T^-1
+shielded proton gyromag. ratio in MHz/T                     42.576 384 74            0.000 000 46             MHz T^-1
+shielded proton mag. mom.                                   1.410 570 560 e-26       0.000 000 015 e-26       J T^-1
+shielded proton mag. mom. to Bohr magneton ratio            1.520 993 128 e-3        0.000 000 017 e-3
+shielded proton mag. mom. to nuclear magneton ratio         2.792 775 599            0.000 000 030
+shielding difference of d and p in HD                       2.0200 e-8               0.0020 e-8
+shielding difference of t and p in HT                       2.4140 e-8               0.0020 e-8
+speed of light in vacuum                                    299 792 458              (exact)                  m s^-1
+standard acceleration of gravity                            9.806 65                 (exact)                  m s^-2
+standard atmosphere                                         101 325                  (exact)                  Pa
+standard-state pressure                                     100 000                  (exact)                  Pa
+Stefan-Boltzmann constant                                   5.670 374 419... e-8     (exact)                  W m^-2 K^-4
+tau Compton wavelength                                      6.977 71 e-16            0.000 47 e-16            m
+tau-electron mass ratio                                     3477.23                  0.23
+tau energy equivalent                                       1776.86                  0.12                     MeV
+tau mass                                                    3.167 54 e-27            0.000 21 e-27            kg
+tau mass energy equivalent                                  2.846 84 e-10            0.000 19 e-10            J
+tau mass in u                                               1.907 54                 0.000 13                 u
+tau molar mass                                              1.907 54 e-3             0.000 13 e-3             kg mol^-1
+tau-muon mass ratio                                         16.8170                  0.0011
+tau-neutron mass ratio                                      1.891 15                 0.000 13
+tau-proton mass ratio                                       1.893 76                 0.000 13
+Thomson cross section                                       6.652 458 7321 e-29      0.000 000 0060 e-29      m^2
+triton-electron mass ratio                                  5496.921 535 73          0.000 000 27
+triton g factor                                             5.957 924 931            0.000 000 012
+triton mag. mom.                                            1.504 609 5202 e-26      0.000 000 0030 e-26      J T^-1
+triton mag. mom. to Bohr magneton ratio                     1.622 393 6651 e-3       0.000 000 0032 e-3
+triton mag. mom. to nuclear magneton ratio                  2.978 962 4656           0.000 000 0059
+triton mass                                                 5.007 356 7446 e-27      0.000 000 0015 e-27      kg
+triton mass energy equivalent                               4.500 387 8060 e-10      0.000 000 0014 e-10      J
+triton mass energy equivalent in MeV                        2808.921 132 98          0.000 000 85             MeV
+triton mass in u                                            3.015 500 716 21         0.000 000 000 12         u
+triton molar mass                                           3.015 500 715 17 e-3     0.000 000 000 92 e-3     kg mol^-1
+triton-proton mass ratio                                    2.993 717 034 14         0.000 000 000 15
+triton relative atomic mass                                 3.015 500 716 21         0.000 000 000 12
+triton to proton mag. mom. ratio                            1.066 639 9191           0.000 000 0021
+unified atomic mass unit                                    1.660 539 066 60 e-27    0.000 000 000 50 e-27    kg
+vacuum electric permittivity                                8.854 187 8128 e-12      0.000 000 0013 e-12      F m^-1
+vacuum mag. permeability                                    1.256 637 062 12 e-6     0.000 000 000 19 e-6     N A^-2
+von Klitzing constant                                       25 812.807 45...         (exact)                  ohm
+weak mixing angle                                           0.222 90                 0.000 30
+Wien frequency displacement law constant                    5.878 925 757... e10     (exact)                  Hz K^-1
+Wien wavelength displacement law constant                   2.897 771 955... e-3     (exact)                  m K
+W to Z mass ratio                                           0.881 53                 0.000 17                   """
+
+
+def exact2018(exact):
+    # SI base constants
+    c = exact['speed of light in vacuum']
+    h = exact['Planck constant']
+    e = exact['elementary charge']
+    k = exact['Boltzmann constant']
+    N_A = exact['Avogadro constant']
+
+    # Other useful constants
+    R = N_A * k
+    hbar = h / (2*math.pi)
+    G_0 = 2 * e**2 / h
+
+    # Wien law numerical constants: https://en.wikipedia.org/wiki/Wien%27s_displacement_law
+    # (alpha - 3)*exp(alpha) + 3 = 0
+    # (x - 5)*exp(x) + 5 = 0
+    alpha_W = 2.821439372122078893403  # 3 + lambertw(-3 * exp(-3))
+    x_W = 4.965114231744276303699  # 5 + lambertw(-5 * exp(-5))
+
+    # Conventional electrical unit
+    # See https://en.wikipedia.org/wiki/Conventional_electrical_unit
+    K_J90 = exact['conventional value of Josephson constant']
+    K_J = 2 * e / h
+    R_K90 = exact['conventional value of von Klitzing constant']
+    R_K = h / e**2
+    V_90 = K_J90 / K_J
+    ohm_90 = R_K / R_K90
+    A_90 = V_90 / ohm_90
+
+    replace = {
+        'atomic unit of action': hbar,
+        'Boltzmann constant in eV/K': k / e,
+        'Boltzmann constant in Hz/K': k / h,
+        'Boltzmann constant in inverse meter per kelvin': k / (h * c),
+        'conductance quantum': G_0,
+        'conventional value of ampere-90': A_90,
+        'conventional value of coulomb-90': A_90,
+        'conventional value of farad-90': 1 / ohm_90,
+        'conventional value of henry-90': ohm_90,
+        'conventional value of ohm-90': ohm_90,
+        'conventional value of volt-90': V_90,
+        'conventional value of watt-90': V_90**2 / ohm_90,
+        'electron volt-hertz relationship': e / h,
+        'electron volt-inverse meter relationship': e / (h * c),
+        'electron volt-kelvin relationship': e / k,
+        'electron volt-kilogram relationship': e / c**2,
+        'elementary charge over h-bar': e / hbar,
+        'Faraday constant': e * N_A,
+        'first radiation constant': 2 * math.pi * h * c**2,
+        'first radiation constant for spectral radiance': 2 * h * c**2,
+        'hertz-electron volt relationship': h / e,
+        'hertz-inverse meter relationship': 1 / c,
+        'hertz-kelvin relationship': h / k,
+        'hertz-kilogram relationship': h / c**2,
+        'inverse meter-electron volt relationship': (h * c) / e,
+        'inverse meter-joule relationship': h * c,
+        'inverse meter-kelvin relationship': h * c / k,
+        'inverse meter-kilogram relationship': h / c,
+        'inverse of conductance quantum': 1 / G_0,
+        'Josephson constant': K_J,
+        'joule-electron volt relationship': 1 / e,
+        'joule-hertz relationship': 1 / h,
+        'joule-inverse meter relationship': 1 / (h * c),
+        'joule-kelvin relationship': 1 / k,
+        'joule-kilogram relationship': 1 / c**2,
+        'kelvin-electron volt relationship': k / e,
+        'kelvin-hertz relationship': k / h,
+        'kelvin-inverse meter relationship': k / (h * c),
+        'kelvin-kilogram relationship': k / c**2,
+        'kilogram-electron volt relationship': c**2 / e,
+        'kilogram-hertz relationship': c**2 / h,
+        'kilogram-inverse meter relationship': c / h,
+        'kilogram-joule relationship': c**2,
+        'kilogram-kelvin relationship': c**2 / k,
+        'Loschmidt constant (273.15 K, 100 kPa)': 100e3 / 273.15 / k,
+        'Loschmidt constant (273.15 K, 101.325 kPa)': 101.325e3 / 273.15 / k,
+        'mag. flux quantum': h / (2 * e),
+        'molar gas constant': R,
+        'molar Planck constant': h * N_A,
+        'molar volume of ideal gas (273.15 K, 100 kPa)': R * 273.15 / 100e3,
+        'molar volume of ideal gas (273.15 K, 101.325 kPa)': R * 273.15 / 101.325e3,
+        'natural unit of action': hbar,
+        'natural unit of action in eV s': hbar / e,
+        'Planck constant in eV/Hz': h / e,
+        'reduced Planck constant': hbar,
+        'reduced Planck constant in eV s': hbar / e,
+        'reduced Planck constant times c in MeV fm': hbar * c / (e * 1e6 * 1e-15),
+        'second radiation constant': h * c / k,
+        'Stefan-Boltzmann constant': 2 * math.pi**5 * k**4 / (15 * h**3 * c**2),
+        'von Klitzing constant': R_K,
+        'Wien frequency displacement law constant': alpha_W * k / h,
+        'Wien wavelength displacement law constant': h * c / (x_W * k),
+    }
+    return replace
+
+
+txt2022 = """\
+alpha particle-electron mass ratio                          7294.299 541 71          0.000 000 17             
+alpha particle mass                                         6.644 657 3450 e-27      0.000 000 0021 e-27      kg
+alpha particle mass energy equivalent                       5.971 920 1997 e-10      0.000 000 0019 e-10      J
+alpha particle mass energy equivalent in MeV                3727.379 4118            0.000 0012               MeV
+alpha particle mass in u                                    4.001 506 179 129        0.000 000 000 062        u
+alpha particle molar mass                                   4.001 506 1833 e-3       0.000 000 0012 e-3       kg mol^-1
+alpha particle-proton mass ratio                            3.972 599 690 252        0.000 000 000 070        
+alpha particle relative atomic mass                         4.001 506 179 129        0.000 000 000 062        
+alpha particle rms charge radius                            1.6785 e-15              0.0021 e-15              m
+Angstrom star                                               1.000 014 95 e-10        0.000 000 90 e-10        m
+atomic mass constant                                        1.660 539 068 92 e-27    0.000 000 000 52 e-27    kg
+atomic mass constant energy equivalent                      1.492 418 087 68 e-10    0.000 000 000 46 e-10    J
+atomic mass constant energy equivalent in MeV               931.494 103 72           0.000 000 29             MeV
+atomic mass unit-electron volt relationship                 9.314 941 0372 e8        0.000 000 0029 e8        eV
+atomic mass unit-hartree relationship                       3.423 177 6922 e7        0.000 000 0011 e7        E_h
+atomic mass unit-hertz relationship                         2.252 342 721 85 e23     0.000 000 000 70 e23     Hz
+atomic mass unit-inverse meter relationship                 7.513 006 6209 e14       0.000 000 0023 e14       m^-1
+atomic mass unit-joule relationship                         1.492 418 087 68 e-10    0.000 000 000 46 e-10    J
+atomic mass unit-kelvin relationship                        1.080 954 020 67 e13     0.000 000 000 34 e13     K
+atomic mass unit-kilogram relationship                      1.660 539 068 92 e-27    0.000 000 000 52 e-27    kg
+atomic unit of 1st hyperpolarizability                      3.206 361 2996 e-53      0.000 000 0015 e-53      C^3 m^3 J^-2
+atomic unit of 2nd hyperpolarizability                      6.235 379 9735 e-65      0.000 000 0039 e-65      C^4 m^4 J^-3
+atomic unit of action                                       1.054 571 817... e-34    (exact)                  J s
+atomic unit of charge                                       1.602 176 634 e-19       (exact)                  C
+atomic unit of charge density                               1.081 202 386 77 e12     0.000 000 000 51 e12     C m^-3
+atomic unit of current                                      6.623 618 237 5082 e-3   0.000 000 000 0072 e-3   A
+atomic unit of electric dipole mom.                         8.478 353 6198 e-30      0.000 000 0013 e-30      C m
+atomic unit of electric field                               5.142 206 751 12 e11     0.000 000 000 80 e11     V m^-1
+atomic unit of electric field gradient                      9.717 362 4424 e21       0.000 000 0030 e21       V m^-2
+atomic unit of electric polarizability                      1.648 777 272 12 e-41    0.000 000 000 51 e-41    C^2 m^2 J^-1
+atomic unit of electric potential                           27.211 386 245 981       0.000 000 000 030        V
+atomic unit of electric quadrupole mom.                     4.486 551 5185 e-40      0.000 000 0014 e-40      C m^2
+atomic unit of energy                                       4.359 744 722 2060 e-18  0.000 000 000 0048 e-18  J
+atomic unit of force                                        8.238 723 5038 e-8       0.000 000 0013 e-8       N
+atomic unit of length                                       5.291 772 105 44 e-11    0.000 000 000 82 e-11    m
+atomic unit of mag. dipole mom.                             1.854 802 013 15 e-23    0.000 000 000 58 e-23    J T^-1
+atomic unit of mag. flux density                            2.350 517 570 77 e5      0.000 000 000 73 e5      T
+atomic unit of magnetizability                              7.891 036 5794 e-29      0.000 000 0049 e-29      J T^-2
+atomic unit of mass                                         9.109 383 7139 e-31      0.000 000 0028 e-31      kg
+atomic unit of momentum                                     1.992 851 915 45 e-24    0.000 000 000 31 e-24    kg m s^-1
+atomic unit of permittivity                                 1.112 650 056 20 e-10    0.000 000 000 17 e-10    F m^-1
+atomic unit of time                                         2.418 884 326 5864 e-17  0.000 000 000 0026 e-17  s
+atomic unit of velocity                                     2.187 691 262 16 e6      0.000 000 000 34 e6      m s^-1
+Avogadro constant                                           6.022 140 76 e23         (exact)                  mol^-1
+Bohr magneton                                               9.274 010 0657 e-24      0.000 000 0029 e-24      J T^-1
+Bohr magneton in eV/T                                       5.788 381 7982 e-5       0.000 000 0018 e-5       eV T^-1
+Bohr magneton in Hz/T                                       1.399 624 491 71 e10     0.000 000 000 44 e10     Hz T^-1
+Bohr magneton in inverse meter per tesla                    46.686 447 719           0.000 000 015            m^-1 T^-1
+Bohr magneton in K/T                                        0.671 713 814 72         0.000 000 000 21         K T^-1
+Bohr radius                                                 5.291 772 105 44 e-11    0.000 000 000 82 e-11    m
+Boltzmann constant                                          1.380 649 e-23           (exact)                  J K^-1
+Boltzmann constant in eV/K                                  8.617 333 262... e-5     (exact)                  eV K^-1
+Boltzmann constant in Hz/K                                  2.083 661 912... e10     (exact)                  Hz K^-1
+Boltzmann constant in inverse meter per kelvin              69.503 480 04...         (exact)                  m^-1 K^-1
+characteristic impedance of vacuum                          376.730 313 412          0.000 000 059            ohm
+classical electron radius                                   2.817 940 3205 e-15      0.000 000 0013 e-15      m
+Compton wavelength                                          2.426 310 235 38 e-12    0.000 000 000 76 e-12    m
+conductance quantum                                         7.748 091 729... e-5     (exact)                  S
+conventional value of ampere-90                             1.000 000 088 87...      (exact)                  A
+conventional value of coulomb-90                            1.000 000 088 87...      (exact)                  C
+conventional value of farad-90                              0.999 999 982 20...      (exact)                  F
+conventional value of henry-90                              1.000 000 017 79...      (exact)                  H
+conventional value of Josephson constant                    483 597.9 e9             (exact)                  Hz V^-1
+conventional value of ohm-90                                1.000 000 017 79...      (exact)                  ohm
+conventional value of volt-90                               1.000 000 106 66...      (exact)                  V
+conventional value of von Klitzing constant                 25 812.807               (exact)                  ohm
+conventional value of watt-90                               1.000 000 195 53...      (exact)                  W
+Copper x unit                                               1.002 076 97 e-13        0.000 000 28 e-13        m
+deuteron-electron mag. mom. ratio                           -4.664 345 550 e-4       0.000 000 012 e-4        
+deuteron-electron mass ratio                                3670.482 967 655         0.000 000 063            
+deuteron g factor                                           0.857 438 2335           0.000 000 0022           
+deuteron mag. mom.                                          4.330 735 087 e-27       0.000 000 011 e-27       J T^-1
+deuteron mag. mom. to Bohr magneton ratio                   4.669 754 568 e-4        0.000 000 012 e-4        
+deuteron mag. mom. to nuclear magneton ratio                0.857 438 2335           0.000 000 0022           
+deuteron mass                                               3.343 583 7768 e-27      0.000 000 0010 e-27      kg
+deuteron mass energy equivalent                             3.005 063 234 91 e-10    0.000 000 000 94 e-10    J
+deuteron mass energy equivalent in MeV                      1875.612 945 00          0.000 000 58             MeV
+deuteron mass in u                                          2.013 553 212 544        0.000 000 000 015        u
+deuteron molar mass                                         2.013 553 214 66 e-3     0.000 000 000 63 e-3     kg mol^-1
+deuteron-neutron mag. mom. ratio                            -0.448 206 52            0.000 000 11             
+deuteron-proton mag. mom. ratio                             0.307 012 209 30         0.000 000 000 79         
+deuteron-proton mass ratio                                  1.999 007 501 2699       0.000 000 000 0084       
+deuteron relative atomic mass                               2.013 553 212 544        0.000 000 000 015        
+deuteron rms charge radius                                  2.127 78 e-15            0.000 27 e-15            m
+electron charge to mass quotient                            -1.758 820 008 38 e11    0.000 000 000 55 e11     C kg^-1
+electron-deuteron mag. mom. ratio                           -2143.923 4921           0.000 0056               
+electron-deuteron mass ratio                                2.724 437 107 629 e-4    0.000 000 000 047 e-4    
+electron g factor                                           -2.002 319 304 360 92    0.000 000 000 000 36     
+electron gyromag. ratio                                     1.760 859 627 84 e11     0.000 000 000 55 e11     s^-1 T^-1
+electron gyromag. ratio in MHz/T                            28 024.951 3861          0.000 0087               MHz T^-1
+electron-helion mass ratio                                  1.819 543 074 649 e-4    0.000 000 000 053 e-4    
+electron mag. mom.                                          -9.284 764 6917 e-24     0.000 000 0029 e-24      J T^-1
+electron mag. mom. anomaly                                  1.159 652 180 46 e-3     0.000 000 000 18 e-3     
+electron mag. mom. to Bohr magneton ratio                   -1.001 159 652 180 46    0.000 000 000 000 18     
+electron mag. mom. to nuclear magneton ratio                -1838.281 971 877        0.000 000 032            
+electron mass                                               9.109 383 7139 e-31      0.000 000 0028 e-31      kg
+electron mass energy equivalent                             8.187 105 7880 e-14      0.000 000 0026 e-14      J
+electron mass energy equivalent in MeV                      0.510 998 950 69         0.000 000 000 16         MeV
+electron mass in u                                          5.485 799 090 441 e-4    0.000 000 000 097 e-4    u
+electron molar mass                                         5.485 799 0962 e-7       0.000 000 0017 e-7       kg mol^-1
+electron-muon mag. mom. ratio                               206.766 9881             0.000 0046               
+electron-muon mass ratio                                    4.836 331 70 e-3         0.000 000 11 e-3         
+electron-neutron mag. mom. ratio                            960.920 48               0.000 23                 
+electron-neutron mass ratio                                 5.438 673 4416 e-4       0.000 000 0022 e-4       
+electron-proton mag. mom. ratio                             -658.210 687 89          0.000 000 19             
+electron-proton mass ratio                                  5.446 170 214 889 e-4    0.000 000 000 094 e-4    
+electron relative atomic mass                               5.485 799 090 441 e-4    0.000 000 000 097 e-4    
+electron-tau mass ratio                                     2.875 85 e-4             0.000 19 e-4             
+electron to alpha particle mass ratio                       1.370 933 554 733 e-4    0.000 000 000 032 e-4    
+electron to shielded helion mag. mom. ratio                 864.058 239 86           0.000 000 70             
+electron to shielded proton mag. mom. ratio                 -658.227 5856            0.000 0027               
+electron-triton mass ratio                                  1.819 200 062 327 e-4    0.000 000 000 068 e-4    
+electron volt                                               1.602 176 634 e-19       (exact)                  J
+electron volt-atomic mass unit relationship                 1.073 544 100 83 e-9     0.000 000 000 33 e-9     u
+electron volt-hartree relationship                          3.674 932 217 5665 e-2   0.000 000 000 0040 e-2   E_h
+electron volt-hertz relationship                            2.417 989 242... e14     (exact)                  Hz
+electron volt-inverse meter relationship                    8.065 543 937... e5      (exact)                  m^-1
+electron volt-joule relationship                            1.602 176 634 e-19       (exact)                  J
+electron volt-kelvin relationship                           1.160 451 812... e4      (exact)                  K
+electron volt-kilogram relationship                         1.782 661 921... e-36    (exact)                  kg
+elementary charge                                           1.602 176 634 e-19       (exact)                  C
+elementary charge over h-bar                                1.519 267 447... e15     (exact)                  A J^-1
+Faraday constant                                            96 485.332 12...         (exact)                  C mol^-1
+Fermi coupling constant                                     1.166 3787 e-5           0.000 0006 e-5           GeV^-2
+fine-structure constant                                     7.297 352 5643 e-3       0.000 000 0011 e-3       
+first radiation constant                                    3.741 771 852... e-16    (exact)                  W m^2
+first radiation constant for spectral radiance              1.191 042 972... e-16    (exact)                  W m^2 sr^-1
+hartree-atomic mass unit relationship                       2.921 262 317 97 e-8     0.000 000 000 91 e-8     u
+hartree-electron volt relationship                          27.211 386 245 981       0.000 000 000 030        eV
+Hartree energy                                              4.359 744 722 2060 e-18  0.000 000 000 0048 e-18  J
+Hartree energy in eV                                        27.211 386 245 981       0.000 000 000 030        eV
+hartree-hertz relationship                                  6.579 683 920 4999 e15   0.000 000 000 0072 e15   Hz
+hartree-inverse meter relationship                          2.194 746 313 6314 e7    0.000 000 000 0024 e7    m^-1
+hartree-joule relationship                                  4.359 744 722 2060 e-18  0.000 000 000 0048 e-18  J
+hartree-kelvin relationship                                 3.157 750 248 0398 e5    0.000 000 000 0034 e5    K
+hartree-kilogram relationship                               4.850 870 209 5419 e-35  0.000 000 000 0053 e-35  kg
+helion-electron mass ratio                                  5495.885 279 84          0.000 000 16             
+helion g factor                                             -4.255 250 6995          0.000 000 0034           
+helion mag. mom.                                            -1.074 617 551 98 e-26   0.000 000 000 93 e-26    J T^-1
+helion mag. mom. to Bohr magneton ratio                     -1.158 740 980 83 e-3    0.000 000 000 94 e-3     
+helion mag. mom. to nuclear magneton ratio                  -2.127 625 3498          0.000 000 0017           
+helion mass                                                 5.006 412 7862 e-27      0.000 000 0016 e-27      kg
+helion mass energy equivalent                               4.499 539 4185 e-10      0.000 000 0014 e-10      J
+helion mass energy equivalent in MeV                        2808.391 611 12          0.000 000 88             MeV
+helion mass in u                                            3.014 932 246 932        0.000 000 000 074        u
+helion molar mass                                           3.014 932 250 10 e-3     0.000 000 000 94 e-3     kg mol^-1
+helion-proton mass ratio                                    2.993 152 671 552        0.000 000 000 070        
+helion relative atomic mass                                 3.014 932 246 932        0.000 000 000 074        
+helion shielding shift                                      5.996 7029 e-5           0.000 0023 e-5           
+hertz-atomic mass unit relationship                         4.439 821 6590 e-24      0.000 000 0014 e-24      u
+hertz-electron volt relationship                            4.135 667 696... e-15    (exact)                  eV
+hertz-hartree relationship                                  1.519 829 846 0574 e-16  0.000 000 000 0017 e-16  E_h
+hertz-inverse meter relationship                            3.335 640 951... e-9     (exact)                  m^-1
+hertz-joule relationship                                    6.626 070 15 e-34        (exact)                  J
+hertz-kelvin relationship                                   4.799 243 073... e-11    (exact)                  K
+hertz-kilogram relationship                                 7.372 497 323... e-51    (exact)                  kg
+hyperfine transition frequency of Cs-133                    9 192 631 770            (exact)                  Hz
+inverse fine-structure constant                             137.035 999 177          0.000 000 021            
+inverse meter-atomic mass unit relationship                 1.331 025 048 24 e-15    0.000 000 000 41 e-15    u
+inverse meter-electron volt relationship                    1.239 841 984... e-6     (exact)                  eV
+inverse meter-hartree relationship                          4.556 335 252 9132 e-8   0.000 000 000 0050 e-8   E_h
+inverse meter-hertz relationship                            299 792 458              (exact)                  Hz
+inverse meter-joule relationship                            1.986 445 857... e-25    (exact)                  J
+inverse meter-kelvin relationship                           1.438 776 877... e-2     (exact)                  K
+inverse meter-kilogram relationship                         2.210 219 094... e-42    (exact)                  kg
+inverse of conductance quantum                              12 906.403 72...         (exact)                  ohm
+Josephson constant                                          483 597.848 4... e9      (exact)                  Hz V^-1
+joule-atomic mass unit relationship                         6.700 535 2471 e9        0.000 000 0021 e9        u
+joule-electron volt relationship                            6.241 509 074... e18     (exact)                  eV
+joule-hartree relationship                                  2.293 712 278 3969 e17   0.000 000 000 0025 e17   E_h
+joule-hertz relationship                                    1.509 190 179... e33     (exact)                  Hz
+joule-inverse meter relationship                            5.034 116 567... e24     (exact)                  m^-1
+joule-kelvin relationship                                   7.242 970 516... e22     (exact)                  K
+joule-kilogram relationship                                 1.112 650 056... e-17    (exact)                  kg
+kelvin-atomic mass unit relationship                        9.251 087 2884 e-14      0.000 000 0029 e-14      u
+kelvin-electron volt relationship                           8.617 333 262... e-5     (exact)                  eV
+kelvin-hartree relationship                                 3.166 811 563 4564 e-6   0.000 000 000 0035 e-6   E_h
+kelvin-hertz relationship                                   2.083 661 912... e10     (exact)                  Hz
+kelvin-inverse meter relationship                           69.503 480 04...         (exact)                  m^-1
+kelvin-joule relationship                                   1.380 649 e-23           (exact)                  J
+kelvin-kilogram relationship                                1.536 179 187... e-40    (exact)                  kg
+kilogram-atomic mass unit relationship                      6.022 140 7537 e26       0.000 000 0019 e26       u
+kilogram-electron volt relationship                         5.609 588 603... e35     (exact)                  eV
+kilogram-hartree relationship                               2.061 485 788 7415 e34   0.000 000 000 0022 e34   E_h
+kilogram-hertz relationship                                 1.356 392 489... e50     (exact)                  Hz
+kilogram-inverse meter relationship                         4.524 438 335... e41     (exact)                  m^-1
+kilogram-joule relationship                                 8.987 551 787... e16     (exact)                  J
+kilogram-kelvin relationship                                6.509 657 260... e39     (exact)                  K
+lattice parameter of silicon                                5.431 020 511 e-10       0.000 000 089 e-10       m
+lattice spacing of ideal Si (220)                           1.920 155 716 e-10       0.000 000 032 e-10       m
+Loschmidt constant (273.15 K, 100 kPa)                      2.651 645 804... e25     (exact)                  m^-3
+Loschmidt constant (273.15 K, 101.325 kPa)                  2.686 780 111... e25     (exact)                  m^-3
+luminous efficacy                                           683                      (exact)                  lm W^-1
+mag. flux quantum                                           2.067 833 848... e-15    (exact)                  Wb
+molar gas constant                                          8.314 462 618...         (exact)                  J mol^-1 K^-1
+molar mass constant                                         1.000 000 001 05 e-3     0.000 000 000 31 e-3     kg mol^-1
+molar mass of carbon-12                                     12.000 000 0126 e-3      0.000 000 0037 e-3       kg mol^-1
+molar Planck constant                                       3.990 312 712... e-10    (exact)                  J Hz^-1 mol^-1
+molar volume of ideal gas (273.15 K, 100 kPa)               22.710 954 64... e-3     (exact)                  m^3 mol^-1
+molar volume of ideal gas (273.15 K, 101.325 kPa)           22.413 969 54... e-3     (exact)                  m^3 mol^-1
+molar volume of silicon                                     1.205 883 199 e-5        0.000 000 060 e-5        m^3 mol^-1
+Molybdenum x unit                                           1.002 099 52 e-13        0.000 000 53 e-13        m
+muon Compton wavelength                                     1.173 444 110 e-14       0.000 000 026 e-14       m
+muon-electron mass ratio                                    206.768 2827             0.000 0046               
+muon g factor                                               -2.002 331 841 23        0.000 000 000 82         
+muon mag. mom.                                              -4.490 448 30 e-26       0.000 000 10 e-26        J T^-1
+muon mag. mom. anomaly                                      1.165 920 62 e-3         0.000 000 41 e-3         
+muon mag. mom. to Bohr magneton ratio                       -4.841 970 48 e-3        0.000 000 11 e-3         
+muon mag. mom. to nuclear magneton ratio                    -8.890 597 04            0.000 000 20             
+muon mass                                                   1.883 531 627 e-28       0.000 000 042 e-28       kg
+muon mass energy equivalent                                 1.692 833 804 e-11       0.000 000 038 e-11       J
+muon mass energy equivalent in MeV                          105.658 3755             0.000 0023               MeV
+muon mass in u                                              0.113 428 9257           0.000 000 0025           u
+muon molar mass                                             1.134 289 258 e-4        0.000 000 025 e-4        kg mol^-1
+muon-neutron mass ratio                                     0.112 454 5168           0.000 000 0025           
+muon-proton mag. mom. ratio                                 -3.183 345 146           0.000 000 071            
+muon-proton mass ratio                                      0.112 609 5262           0.000 000 0025           
+muon-tau mass ratio                                         5.946 35 e-2             0.000 40 e-2             
+natural unit of action                                      1.054 571 817... e-34    (exact)                  J s
+natural unit of action in eV s                              6.582 119 569... e-16    (exact)                  eV s
+natural unit of energy                                      8.187 105 7880 e-14      0.000 000 0026 e-14      J
+natural unit of energy in MeV                               0.510 998 950 69         0.000 000 000 16         MeV
+natural unit of length                                      3.861 592 6744 e-13      0.000 000 0012 e-13      m
+natural unit of mass                                        9.109 383 7139 e-31      0.000 000 0028 e-31      kg
+natural unit of momentum                                    2.730 924 534 46 e-22    0.000 000 000 85 e-22    kg m s^-1
+natural unit of momentum in MeV/c                           0.510 998 950 69         0.000 000 000 16         MeV/c
+natural unit of time                                        1.288 088 666 44 e-21    0.000 000 000 40 e-21    s
+natural unit of velocity                                    299 792 458              (exact)                  m s^-1
+neutron Compton wavelength                                  1.319 590 903 82 e-15    0.000 000 000 67 e-15    m
+neutron-electron mag. mom. ratio                            1.040 668 84 e-3         0.000 000 24 e-3         
+neutron-electron mass ratio                                 1838.683 662 00          0.000 000 74             
+neutron g factor                                            -3.826 085 52            0.000 000 90             
+neutron gyromag. ratio                                      1.832 471 74 e8          0.000 000 43 e8          s^-1 T^-1
+neutron gyromag. ratio in MHz/T                             29.164 6935              0.000 0069               MHz T^-1
+neutron mag. mom.                                           -9.662 3653 e-27         0.000 0023 e-27          J T^-1
+neutron mag. mom. to Bohr magneton ratio                    -1.041 875 65 e-3        0.000 000 25 e-3         
+neutron mag. mom. to nuclear magneton ratio                 -1.913 042 76            0.000 000 45             
+neutron mass                                                1.674 927 500 56 e-27    0.000 000 000 85 e-27    kg
+neutron mass energy equivalent                              1.505 349 765 14 e-10    0.000 000 000 76 e-10    J
+neutron mass energy equivalent in MeV                       939.565 421 94           0.000 000 48             MeV
+neutron mass in u                                           1.008 664 916 06         0.000 000 000 40         u
+neutron molar mass                                          1.008 664 917 12 e-3     0.000 000 000 51 e-3     kg mol^-1
+neutron-muon mass ratio                                     8.892 484 08             0.000 000 20             
+neutron-proton mag. mom. ratio                              -0.684 979 35            0.000 000 16             
+neutron-proton mass difference                              2.305 574 61 e-30        0.000 000 67 e-30        kg
+neutron-proton mass difference energy equivalent            2.072 147 12 e-13        0.000 000 60 e-13        J
+neutron-proton mass difference energy equivalent in MeV     1.293 332 51             0.000 000 38             MeV
+neutron-proton mass difference in u                         1.388 449 48 e-3         0.000 000 40 e-3         u
+neutron-proton mass ratio                                   1.001 378 419 46         0.000 000 000 40         
+neutron relative atomic mass                                1.008 664 916 06         0.000 000 000 40         
+neutron-tau mass ratio                                      0.528 779                0.000 036                
+neutron to shielded proton mag. mom. ratio                  -0.684 996 94            0.000 000 16             
+Newtonian constant of gravitation                           6.674 30 e-11            0.000 15 e-11            m^3 kg^-1 s^-2
+Newtonian constant of gravitation over h-bar c              6.708 83 e-39            0.000 15 e-39            (GeV/c^2)^-2
+nuclear magneton                                            5.050 783 7393 e-27      0.000 000 0016 e-27      J T^-1
+nuclear magneton in eV/T                                    3.152 451 254 17 e-8     0.000 000 000 98 e-8     eV T^-1
+nuclear magneton in inverse meter per tesla                 2.542 623 410 09 e-2     0.000 000 000 79 e-2     m^-1 T^-1
+nuclear magneton in K/T                                     3.658 267 7706 e-4       0.000 000 0011 e-4       K T^-1
+nuclear magneton in MHz/T                                   7.622 593 2188           0.000 000 0024           MHz T^-1
+Planck constant                                             6.626 070 15 e-34        (exact)                  J Hz^-1
+Planck constant in eV/Hz                                    4.135 667 696... e-15    (exact)                  eV Hz^-1
+Planck length                                               1.616 255 e-35           0.000 018 e-35           m
+Planck mass                                                 2.176 434 e-8            0.000 024 e-8            kg
+Planck mass energy equivalent in GeV                        1.220 890 e19            0.000 014 e19            GeV
+Planck temperature                                          1.416 784 e32            0.000 016 e32            K
+Planck time                                                 5.391 247 e-44           0.000 060 e-44           s
+proton charge to mass quotient                              9.578 833 1430 e7        0.000 000 0030 e7        C kg^-1
+proton Compton wavelength                                   1.321 409 853 60 e-15    0.000 000 000 41 e-15    m
+proton-electron mass ratio                                  1836.152 673 426         0.000 000 032            
+proton g factor                                             5.585 694 6893           0.000 000 0016           
+proton gyromag. ratio                                       2.675 221 8708 e8        0.000 000 0011 e8        s^-1 T^-1
+proton gyromag. ratio in MHz/T                              42.577 478 461           0.000 000 018            MHz T^-1
+proton mag. mom.                                            1.410 606 795 45 e-26    0.000 000 000 60 e-26    J T^-1
+proton mag. mom. to Bohr magneton ratio                     1.521 032 202 30 e-3     0.000 000 000 45 e-3     
+proton mag. mom. to nuclear magneton ratio                  2.792 847 344 63         0.000 000 000 82         
+proton mag. shielding correction                            2.567 15 e-5             0.000 41 e-5             
+proton mass                                                 1.672 621 925 95 e-27    0.000 000 000 52 e-27    kg
+proton mass energy equivalent                               1.503 277 618 02 e-10    0.000 000 000 47 e-10    J
+proton mass energy equivalent in MeV                        938.272 089 43           0.000 000 29             MeV
+proton mass in u                                            1.007 276 466 5789       0.000 000 000 0083       u
+proton molar mass                                           1.007 276 467 64 e-3     0.000 000 000 31 e-3     kg mol^-1
+proton-muon mass ratio                                      8.880 243 38             0.000 000 20             
+proton-neutron mag. mom. ratio                              -1.459 898 02            0.000 000 34             
+proton-neutron mass ratio                                   0.998 623 477 97         0.000 000 000 40         
+proton relative atomic mass                                 1.007 276 466 5789       0.000 000 000 0083       
+proton rms charge radius                                    8.4075 e-16              0.0064 e-16              m
+proton-tau mass ratio                                       0.528 051                0.000 036                
+quantum of circulation                                      3.636 947 5467 e-4       0.000 000 0011 e-4       m^2 s^-1
+quantum of circulation times 2                              7.273 895 0934 e-4       0.000 000 0023 e-4       m^2 s^-1
+reduced Compton wavelength                                  3.861 592 6744 e-13      0.000 000 0012 e-13      m
+reduced muon Compton wavelength                             1.867 594 306 e-15       0.000 000 042 e-15       m
+reduced neutron Compton wavelength                          2.100 194 1520 e-16      0.000 000 0011 e-16      m
+reduced Planck constant                                     1.054 571 817... e-34    (exact)                  J s
+reduced Planck constant in eV s                             6.582 119 569... e-16    (exact)                  eV s
+reduced Planck constant times c in MeV fm                   197.326 980 4...         (exact)                  MeV fm
+reduced proton Compton wavelength                           2.103 089 100 51 e-16    0.000 000 000 66 e-16    m
+reduced tau Compton wavelength                              1.110 538 e-16           0.000 075 e-16           m
+Rydberg constant                                            10 973 731.568 157       0.000 012                m^-1
+Rydberg constant times c in Hz                              3.289 841 960 2500 e15   0.000 000 000 0036 e15   Hz
+Rydberg constant times hc in eV                             13.605 693 122 990       0.000 000 000 015        eV
+Rydberg constant times hc in J                              2.179 872 361 1030 e-18  0.000 000 000 0024 e-18  J
+Sackur-Tetrode constant (1 K, 100 kPa)                      -1.151 707 534 96        0.000 000 000 47         
+Sackur-Tetrode constant (1 K, 101.325 kPa)                  -1.164 870 521 49        0.000 000 000 47         
+second radiation constant                                   1.438 776 877... e-2     (exact)                  m K
+shielded helion gyromag. ratio                              2.037 894 6078 e8        0.000 000 0018 e8        s^-1 T^-1
+shielded helion gyromag. ratio in MHz/T                     32.434 100 033           0.000 000 028            MHz T^-1
+shielded helion mag. mom.                                   -1.074 553 110 35 e-26   0.000 000 000 93 e-26    J T^-1
+shielded helion mag. mom. to Bohr magneton ratio            -1.158 671 494 57 e-3    0.000 000 000 94 e-3     
+shielded helion mag. mom. to nuclear magneton ratio         -2.127 497 7624          0.000 000 0017           
+shielded helion to proton mag. mom. ratio                   -0.761 766 577 21        0.000 000 000 66         
+shielded helion to shielded proton mag. mom. ratio          -0.761 786 1334          0.000 000 0031           
+shielded proton gyromag. ratio                              2.675 153 194 e8         0.000 000 011 e8         s^-1 T^-1
+shielded proton gyromag. ratio in MHz/T                     42.576 385 43            0.000 000 17             MHz T^-1
+shielded proton mag. mom.                                   1.410 570 5830 e-26      0.000 000 0058 e-26      J T^-1
+shielded proton mag. mom. to Bohr magneton ratio            1.520 993 1551 e-3       0.000 000 0062 e-3       
+shielded proton mag. mom. to nuclear magneton ratio         2.792 775 648            0.000 000 011            
+shielding difference of d and p in HD                       1.987 70 e-8             0.000 10 e-8             
+shielding difference of t and p in HT                       2.394 50 e-8             0.000 20 e-8             
+speed of light in vacuum                                    299 792 458              (exact)                  m s^-1
+standard acceleration of gravity                            9.806 65                 (exact)                  m s^-2
+standard atmosphere                                         101 325                  (exact)                  Pa
+standard-state pressure                                     100 000                  (exact)                  Pa
+Stefan-Boltzmann constant                                   5.670 374 419... e-8     (exact)                  W m^-2 K^-4
+tau Compton wavelength                                      6.977 71 e-16            0.000 47 e-16            m
+tau-electron mass ratio                                     3477.23                  0.23                     
+tau energy equivalent                                       1776.86                  0.12                     MeV
+tau mass                                                    3.167 54 e-27            0.000 21 e-27            kg
+tau mass energy equivalent                                  2.846 84 e-10            0.000 19 e-10            J
+tau mass in u                                               1.907 54                 0.000 13                 u
+tau molar mass                                              1.907 54 e-3             0.000 13 e-3             kg mol^-1
+tau-muon mass ratio                                         16.8170                  0.0011                   
+tau-neutron mass ratio                                      1.891 15                 0.000 13                 
+tau-proton mass ratio                                       1.893 76                 0.000 13                 
+Thomson cross section                                       6.652 458 7051 e-29      0.000 000 0062 e-29      m^2
+triton-electron mass ratio                                  5496.921 535 51          0.000 000 21             
+triton g factor                                             5.957 924 930            0.000 000 012            
+triton mag. mom.                                            1.504 609 5178 e-26      0.000 000 0030 e-26      J T^-1
+triton mag. mom. to Bohr magneton ratio                     1.622 393 6648 e-3       0.000 000 0032 e-3       
+triton mag. mom. to nuclear magneton ratio                  2.978 962 4650           0.000 000 0059           
+triton mass                                                 5.007 356 7512 e-27      0.000 000 0016 e-27      kg
+triton mass energy equivalent                               4.500 387 8119 e-10      0.000 000 0014 e-10      J
+triton mass energy equivalent in MeV                        2808.921 136 68          0.000 000 88             MeV
+triton mass in u                                            3.015 500 715 97         0.000 000 000 10         u
+triton molar mass                                           3.015 500 719 13 e-3     0.000 000 000 94 e-3     kg mol^-1
+triton-proton mass ratio                                    2.993 717 034 03         0.000 000 000 10         
+triton relative atomic mass                                 3.015 500 715 97         0.000 000 000 10         
+triton to proton mag. mom. ratio                            1.066 639 9189           0.000 000 0021           
+unified atomic mass unit                                    1.660 539 068 92 e-27    0.000 000 000 52 e-27    kg
+vacuum electric permittivity                                8.854 187 8188 e-12      0.000 000 0014 e-12      F m^-1
+vacuum mag. permeability                                    1.256 637 061 27 e-6     0.000 000 000 20 e-6     N A^-2
+von Klitzing constant                                       25 812.807 45...         (exact)                  ohm
+weak mixing angle                                           0.223 05                 0.000 23                 
+Wien frequency displacement law constant                    5.878 925 757... e10     (exact)                  Hz K^-1
+Wien wavelength displacement law constant                   2.897 771 955... e-3     (exact)                  m K
+W to Z mass ratio                                           0.881 45                 0.000 13                    """
+
+
+exact2022 = exact2018
+
+
+# -----------------------------------------------------------------------------
+
+
+def parse_constants_2002to2014(
+    d: str, exact_func: Callable[[Any], Any]
+) -> dict[str, tuple[float, str, float]]:
+    constants: dict[str, tuple[float, str, float]] = {}
+    exact: dict[str, float] = {}
+    need_replace = set()
+    for line in d.split('\n'):
+        name = line[:55].rstrip()
+        val = float(line[55:77].replace(' ', '').replace('...', ''))
+        is_truncated = '...' in line[55:77]
+        is_exact = '(exact)' in line[77:99]
+        if is_truncated and is_exact:
+            # missing decimals, use computed exact value
+            need_replace.add(name)
+        elif is_exact:
+            exact[name] = val
+        else:
+            assert not is_truncated
+        uncert = float(line[77:99].replace(' ', '').replace('(exact)', '0'))
+        units = line[99:].rstrip()
+        constants[name] = (val, units, uncert)
+    replace = exact_func(exact)
+    replace_exact(constants, need_replace, replace)
+    return constants
+
+
+def parse_constants_2018toXXXX(
+    d: str, exact_func: Callable[[Any], Any]
+) -> dict[str, tuple[float, str, float]]:
+    constants: dict[str, tuple[float, str, float]] = {}
+    exact: dict[str, float] = {}
+    need_replace = set()
+    for line in d.split('\n'):
+        name = line[:60].rstrip()
+        val = float(line[60:85].replace(' ', '').replace('...', ''))
+        is_truncated = '...' in line[60:85]
+        is_exact = '(exact)' in line[85:110]
+        if is_truncated and is_exact:
+            # missing decimals, use computed exact value
+            need_replace.add(name)
+        elif is_exact:
+            exact[name] = val
+        else:
+            assert not is_truncated
+        uncert = float(line[85:110].replace(' ', '').replace('(exact)', '0'))
+        units = line[110:].rstrip()
+        constants[name] = (val, units, uncert)
+    replace = exact_func(exact)
+    replace_exact(constants, need_replace, replace)
+    return constants
+
+
+def replace_exact(d, to_replace, exact):
+    for name in to_replace:
+        assert name in exact, f'Missing exact value: {name}'
+        assert abs(exact[name]/d[name][0] - 1) <= 1e-9, \
+            f'Bad exact value: {name}: { exact[name]}, {d[name][0]}'
+        d[name] = (exact[name],) + d[name][1:]
+    assert set(exact.keys()) == set(to_replace)
+
+
+_physical_constants_2002 = parse_constants_2002to2014(txt2002, exact2002)
+_physical_constants_2006 = parse_constants_2002to2014(txt2006, exact2006)
+_physical_constants_2010 = parse_constants_2002to2014(txt2010, exact2010)
+_physical_constants_2014 = parse_constants_2002to2014(txt2014, exact2014)
+_physical_constants_2018 = parse_constants_2018toXXXX(txt2018, exact2018)
+_physical_constants_2022 = parse_constants_2018toXXXX(txt2022, exact2022)
+
+physical_constants: dict[str, tuple[float, str, float]] = {}
+physical_constants.update(_physical_constants_2002)
+physical_constants.update(_physical_constants_2006)
+physical_constants.update(_physical_constants_2010)
+physical_constants.update(_physical_constants_2014)
+physical_constants.update(_physical_constants_2018)
+physical_constants.update(_physical_constants_2022)
+_current_constants = _physical_constants_2022
+_current_codata = "CODATA 2022"
+
+# check obsolete values
+_obsolete_constants = {}
+for k in physical_constants:
+    if k not in _current_constants:
+        _obsolete_constants[k] = True
+
+# generate some additional aliases
+_aliases = {}
+for k in _physical_constants_2002:
+    if 'magn.' in k:
+        _aliases[k] = k.replace('magn.', 'mag.')
+for k in _physical_constants_2006:
+    if 'momentum' in k:
+        _aliases[k] = k.replace('momentum', 'mom.um')
+for k in _physical_constants_2018:
+    if 'momentum' in k:
+        _aliases[k] = k.replace('momentum', 'mom.um')
+for k in _physical_constants_2022:
+    if 'momentum' in k:
+        _aliases[k] = k.replace('momentum', 'mom.um')
+
+# CODATA 2018 and 2022: renamed and no longer exact; use as aliases
+_aliases['mag. constant'] = 'vacuum mag. permeability'
+_aliases['electric constant'] = 'vacuum electric permittivity'
+
+
+_extra_alias_keys = ['natural unit of velocity',
+                     'natural unit of action',
+                     'natural unit of action in eV s',
+                     'natural unit of mass',
+                     'natural unit of energy',
+                     'natural unit of energy in MeV',
+                     'natural unit of mom.um',
+                     'natural unit of mom.um in MeV/c',
+                     'natural unit of length',
+                     'natural unit of time']
+
+# finally, insert aliases for values
+for k, v in list(_aliases.items()):
+    if v in _current_constants or v in _extra_alias_keys:
+        physical_constants[k] = physical_constants[v]
+    else:
+        del _aliases[k]
+
+
+class ConstantWarning(DeprecationWarning):
+    """Accessing a constant no longer in current CODATA data set."""
+    pass
+
+
+def _check_obsolete(key: str) -> None:
+    if key in _obsolete_constants and key not in _aliases:
+        warnings.warn(f"Constant '{key}' is not in current {_current_codata} data set",
+                      ConstantWarning, stacklevel=3)
+
+
+@xp_capabilities(out_of_scope=True)
+def value(key: str) -> float:
+    """
+    Value in physical_constants indexed by key.
+
+    Parameters
+    ----------
+    key : str
+        Key in dictionary `physical_constants`
+
+    Returns
+    -------
+    value : float
+        Value in `physical_constants` corresponding to `key`
+
+    Examples
+    --------
+    >>> from scipy import constants
+    >>> constants.value('elementary charge')
+    1.602176634e-19
+
+    """
+    _check_obsolete(key)
+    return physical_constants[key][0]
+
+
+@xp_capabilities(out_of_scope=True)
+def unit(key: str) -> str:
+    """
+    Unit in physical_constants indexed by key.
+
+    Parameters
+    ----------
+    key : str
+        Key in dictionary `physical_constants`
+
+    Returns
+    -------
+    unit : str
+        Unit in `physical_constants` corresponding to `key`
+
+    Examples
+    --------
+    >>> from scipy import constants
+    >>> constants.unit('proton mass')
+    'kg'
+
+    """
+    _check_obsolete(key)
+    return physical_constants[key][1]
+
+
+@xp_capabilities(out_of_scope=True)
+def precision(key: str) -> float:
+    """
+    Relative precision in physical_constants indexed by key.
+
+    Parameters
+    ----------
+    key : str
+        Key in dictionary `physical_constants`
+
+    Returns
+    -------
+    prec : float
+        Relative precision in `physical_constants` corresponding to `key`
+
+    Examples
+    --------
+    >>> from scipy import constants
+    >>> constants.precision('proton mass')
+    5.1e-37
+
+    """
+    _check_obsolete(key)
+    return physical_constants[key][2] / physical_constants[key][0]
+
+
+@xp_capabilities(out_of_scope=True)
+def find(sub: str | None = None, disp: bool = False) -> Any:
+    """
+    Return list of physical_constant keys containing a given string.
+
+    Parameters
+    ----------
+    sub : str
+        Sub-string to search keys for. By default, return all keys.
+    disp : bool
+        If True, print the keys that are found and return None.
+        Otherwise, return the list of keys without printing anything.
+
+    Returns
+    -------
+    keys : list or None
+        If `disp` is False, the list of keys is returned.
+        Otherwise, None is returned.
+
+    Examples
+    --------
+    >>> from scipy.constants import find, physical_constants
+
+    Which keys in the ``physical_constants`` dictionary contain 'boltzmann'?
+
+    >>> find('boltzmann')
+    ['Boltzmann constant',
+     'Boltzmann constant in Hz/K',
+     'Boltzmann constant in eV/K',
+     'Boltzmann constant in inverse meter per kelvin',
+     'Stefan-Boltzmann constant']
+
+    Get the constant called 'Boltzmann constant in Hz/K':
+
+    >>> physical_constants['Boltzmann constant in Hz/K']
+    (20836619120.0, 'Hz K^-1', 0.0)
+
+    Find constants with 'radius' in the key:
+
+    >>> find('radius')
+    ['Bohr radius',
+     'alpha particle rms charge radius',
+     'classical electron radius',
+     'deuteron rms charge radius',
+     'proton rms charge radius']
+    >>> physical_constants['classical electron radius']
+    (2.8179403262e-15, 'm', 1.3e-24)
+
+    """
+    if sub is None:
+        result = list(_current_constants.keys())
+    else:
+        result = [key for key in _current_constants
+                  if sub.lower() in key.lower()]
+
+    result.sort()
+    if disp:
+        for key in result:
+            print(key)
+        return
+    else:
+        return result
+
+# This is not used here, but it must be defined to pass
+# scipy/_lib/tests/test_public_api.py::test_private_but_present_deprecation
+c = value('speed of light in vacuum')
diff --git a/.venv/lib/python3.12/site-packages/scipy/constants/_constants.py b/.venv/lib/python3.12/site-packages/scipy/constants/_constants.py
new file mode 100644
index 0000000000000000000000000000000000000000..4057a86a493d8f815c29bed54abfe4a144a138f6
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/constants/_constants.py
@@ -0,0 +1,369 @@
+"""
+Collection of physical constants and conversion factors.
+
+Most constants are in SI units, so you can do
+print '10 mile per minute is', 10*mile/minute, 'm/s or', 10*mile/(minute*knot), 'knots'
+
+The list is not meant to be comprehensive, but just convenient for everyday use.
+"""
+
+import math as _math
+from typing import TYPE_CHECKING, Any
+
+from ._codata import value as _cd
+
+if TYPE_CHECKING:
+    import numpy.typing as npt
+
+from scipy._lib._array_api import array_namespace, _asarray, xp_capabilities
+
+
+"""
+BasSw 2006
+physical constants: imported from CODATA
+unit conversion: see e.g., NIST special publication 811
+Use at own risk: double-check values before calculating your Mars orbit-insertion burn.
+Some constants exist in a few variants, which are marked with suffixes.
+The ones without any suffix should be the most common ones.
+"""
+
+__all__ = [
+    'Avogadro', 'Boltzmann', 'Btu', 'Btu_IT', 'Btu_th', 'G',
+    'Julian_year', 'N_A', 'Planck', 'R', 'Rydberg',
+    'Stefan_Boltzmann', 'Wien', 'acre', 'alpha',
+    'angstrom', 'arcmin', 'arcminute', 'arcsec',
+    'arcsecond', 'astronomical_unit', 'atm',
+    'atmosphere', 'atomic_mass', 'atto', 'au', 'bar',
+    'barrel', 'bbl', 'blob', 'c', 'calorie',
+    'calorie_IT', 'calorie_th', 'carat', 'centi',
+    'convert_temperature', 'day', 'deci', 'degree',
+    'degree_Fahrenheit', 'deka', 'dyn', 'dyne', 'e',
+    'eV', 'electron_mass', 'electron_volt',
+    'elementary_charge', 'epsilon_0', 'erg',
+    'exa', 'exbi', 'femto', 'fermi', 'fine_structure',
+    'fluid_ounce', 'fluid_ounce_US', 'fluid_ounce_imp',
+    'foot', 'g', 'gallon', 'gallon_US', 'gallon_imp',
+    'gas_constant', 'gibi', 'giga', 'golden', 'golden_ratio',
+    'grain', 'gram', 'gravitational_constant', 'h', 'hbar',
+    'hectare', 'hecto', 'horsepower', 'hour', 'hp',
+    'inch', 'k', 'kgf', 'kibi', 'kilo', 'kilogram_force',
+    'kmh', 'knot', 'lambda2nu', 'lb', 'lbf',
+    'light_year', 'liter', 'litre', 'long_ton', 'm_e',
+    'm_n', 'm_p', 'm_u', 'mach', 'mebi', 'mega',
+    'metric_ton', 'micro', 'micron', 'mil', 'mile',
+    'milli', 'minute', 'mmHg', 'mph', 'mu_0', 'nano',
+    'nautical_mile', 'neutron_mass', 'nu2lambda',
+    'ounce', 'oz', 'parsec', 'pebi', 'peta',
+    'pi', 'pico', 'point', 'pound', 'pound_force',
+    'proton_mass', 'psi', 'pt', 'quecto', 'quetta', 'ronna', 'ronto',
+    'short_ton', 'sigma', 'slinch', 'slug', 'speed_of_light',
+    'speed_of_sound', 'stone', 'survey_foot',
+    'survey_mile', 'tebi', 'tera', 'ton_TNT',
+    'torr', 'troy_ounce', 'troy_pound', 'u',
+    'week', 'yard', 'year', 'yobi', 'yocto',
+    'yotta', 'zebi', 'zepto', 'zero_Celsius', 'zetta'
+]
+
+
+# mathematical constants
+pi = _math.pi
+golden = golden_ratio = (1 + _math.sqrt(5)) / 2
+
+# SI prefixes
+quetta = 1e30
+ronna = 1e27
+yotta = 1e24
+zetta = 1e21
+exa = 1e18
+peta = 1e15
+tera = 1e12
+giga = 1e9
+mega = 1e6
+kilo = 1e3
+hecto = 1e2
+deka = 1e1
+deci = 1e-1
+centi = 1e-2
+milli = 1e-3
+micro = 1e-6
+nano = 1e-9
+pico = 1e-12
+femto = 1e-15
+atto = 1e-18
+zepto = 1e-21
+yocto = 1e-24
+ronto = 1e-27
+quecto = 1e-30
+
+# binary prefixes
+kibi = 2**10
+mebi = 2**20
+gibi = 2**30
+tebi = 2**40
+pebi = 2**50
+exbi = 2**60
+zebi = 2**70
+yobi = 2**80
+
+# physical constants
+c = speed_of_light = _cd('speed of light in vacuum')
+mu_0 = _cd('vacuum mag. permeability')
+epsilon_0 = _cd('vacuum electric permittivity')
+h = Planck = _cd('Planck constant')
+hbar = _cd('reduced Planck constant')
+G = gravitational_constant = _cd('Newtonian constant of gravitation')
+g = _cd('standard acceleration of gravity')
+e = elementary_charge = _cd('elementary charge')
+R = gas_constant = _cd('molar gas constant')
+alpha = fine_structure = _cd('fine-structure constant')
+N_A = Avogadro = _cd('Avogadro constant')
+k = Boltzmann = _cd('Boltzmann constant')
+sigma = Stefan_Boltzmann = _cd('Stefan-Boltzmann constant')
+Wien = _cd('Wien wavelength displacement law constant')
+Rydberg = _cd('Rydberg constant')
+
+# mass in kg
+gram = 1e-3
+metric_ton = 1e3
+grain = 64.79891e-6
+lb = pound = 7000 * grain  # avoirdupois
+blob = slinch = pound * g / 0.0254  # lbf*s**2/in (added in 1.0.0)
+slug = blob / 12  # lbf*s**2/foot (added in 1.0.0)
+oz = ounce = pound / 16
+stone = 14 * pound
+long_ton = 2240 * pound
+short_ton = 2000 * pound
+
+troy_ounce = 480 * grain  # only for metals / gems
+troy_pound = 12 * troy_ounce
+carat = 200e-6
+
+m_e = electron_mass = _cd('electron mass')
+m_p = proton_mass = _cd('proton mass')
+m_n = neutron_mass = _cd('neutron mass')
+m_u = u = atomic_mass = _cd('atomic mass constant')
+
+# angle in rad
+degree = pi / 180
+arcmin = arcminute = degree / 60
+arcsec = arcsecond = arcmin / 60
+
+# time in second
+minute = 60.0
+hour = 60 * minute
+day = 24 * hour
+week = 7 * day
+year = 365 * day
+Julian_year = 365.25 * day
+
+# length in meter
+inch = 0.0254
+foot = 12 * inch
+yard = 3 * foot
+mile = 1760 * yard
+mil = inch / 1000
+pt = point = inch / 72  # typography
+survey_foot = 1200.0 / 3937
+survey_mile = 5280 * survey_foot
+nautical_mile = 1852.0
+fermi = 1e-15
+angstrom = 1e-10
+micron = 1e-6
+au = astronomical_unit = 149597870700.0
+light_year = Julian_year * c
+parsec = au / arcsec
+
+# pressure in pascal
+atm = atmosphere = _cd('standard atmosphere')
+bar = 1e5
+torr = mmHg = atm / 760
+psi = pound * g / (inch * inch)
+
+# area in meter**2
+hectare = 1e4
+acre = 43560 * foot**2
+
+# volume in meter**3
+litre = liter = 1e-3
+gallon = gallon_US = 231 * inch**3  # US
+# pint = gallon_US / 8
+fluid_ounce = fluid_ounce_US = gallon_US / 128
+bbl = barrel = 42 * gallon_US  # for oil
+
+gallon_imp = 4.54609e-3  # UK
+fluid_ounce_imp = gallon_imp / 160
+
+# speed in meter per second
+kmh = 1e3 / hour
+mph = mile / hour
+# approx value of mach at 15 degrees in 1 atm. Is this a common value?
+mach = speed_of_sound = 340.5
+knot = nautical_mile / hour
+
+# temperature in kelvin
+zero_Celsius = 273.15
+degree_Fahrenheit = 1/1.8  # only for differences
+
+# energy in joule
+eV = electron_volt = elementary_charge  # * 1 Volt
+calorie = calorie_th = 4.184
+calorie_IT = 4.1868
+erg = 1e-7
+Btu_th = pound * degree_Fahrenheit * calorie_th / gram
+Btu = Btu_IT = pound * degree_Fahrenheit * calorie_IT / gram
+ton_TNT = 1e9 * calorie_th
+# Wh = watt_hour
+
+# power in watt
+hp = horsepower = 550 * foot * pound * g
+
+# force in newton
+dyn = dyne = 1e-5
+lbf = pound_force = pound * g
+kgf = kilogram_force = g  # * 1 kg
+
+# functions for conversions that are not linear
+
+
+@xp_capabilities()
+def convert_temperature(
+    val: "npt.ArrayLike",
+    old_scale: str,
+    new_scale: str,
+) -> Any:
+    """
+    Convert from a temperature scale to another one among Celsius, Kelvin,
+    Fahrenheit, and Rankine scales.
+
+    Parameters
+    ----------
+    val : array_like
+        Value(s) of the temperature(s) to be converted expressed in the
+        original scale.
+    old_scale : str
+        Specifies as a string the original scale from which the temperature
+        value(s) will be converted. Supported scales are Celsius ('Celsius',
+        'celsius', 'C' or 'c'), Kelvin ('Kelvin', 'kelvin', 'K', 'k'),
+        Fahrenheit ('Fahrenheit', 'fahrenheit', 'F' or 'f'), and Rankine
+        ('Rankine', 'rankine', 'R', 'r').
+    new_scale : str
+        Specifies as a string the new scale to which the temperature
+        value(s) will be converted. Supported scales are Celsius ('Celsius',
+        'celsius', 'C' or 'c'), Kelvin ('Kelvin', 'kelvin', 'K', 'k'),
+        Fahrenheit ('Fahrenheit', 'fahrenheit', 'F' or 'f'), and Rankine
+        ('Rankine', 'rankine', 'R', 'r').
+
+    Returns
+    -------
+    res : float or array of floats
+        Value(s) of the converted temperature(s) expressed in the new scale.
+
+    Notes
+    -----
+    .. versionadded:: 0.18.0
+
+    Examples
+    --------
+    >>> from scipy.constants import convert_temperature
+    >>> import numpy as np
+    >>> convert_temperature(np.array([-40, 40]), 'Celsius', 'Kelvin')
+    array([ 233.15,  313.15])
+
+    """
+    xp = array_namespace(val)
+    _val = _asarray(val, xp=xp, subok=True)
+    # Convert from `old_scale` to Kelvin
+    if old_scale.lower() in ['celsius', 'c']:
+        tempo = _val + zero_Celsius
+    elif old_scale.lower() in ['kelvin', 'k']:
+        tempo = _val
+    elif old_scale.lower() in ['fahrenheit', 'f']:
+        tempo = (_val - 32) * 5 / 9 + zero_Celsius
+    elif old_scale.lower() in ['rankine', 'r']:
+        tempo = _val * 5 / 9
+    else:
+        raise NotImplementedError(f"{old_scale=} is unsupported: supported scales "
+                                   "are Celsius, Kelvin, Fahrenheit, and "
+                                   "Rankine")
+    # and from Kelvin to `new_scale`.
+    if new_scale.lower() in ['celsius', 'c']:
+        res = tempo - zero_Celsius
+    elif new_scale.lower() in ['kelvin', 'k']:
+        res = tempo
+    elif new_scale.lower() in ['fahrenheit', 'f']:
+        res = (tempo - zero_Celsius) * 9 / 5 + 32
+    elif new_scale.lower() in ['rankine', 'r']:
+        res = tempo * 9 / 5
+    else:
+        raise NotImplementedError(f"{new_scale=} is unsupported: supported "
+                                   "scales are 'Celsius', 'Kelvin', "
+                                   "'Fahrenheit', and 'Rankine'")
+
+    return res
+
+
+# optics
+
+
+@xp_capabilities()
+def lambda2nu(lambda_: "npt.ArrayLike") -> Any:
+    """
+    Convert wavelength to optical frequency.
+
+    Parameters
+    ----------
+    lambda_ : array_like
+        Wavelength(s) to be converted.
+
+    Returns
+    -------
+    nu : float or array of floats
+        Equivalent optical frequency.
+
+    Notes
+    -----
+    Computes ``nu = c / lambda`` where c = 299792458.0, i.e., the
+    (vacuum) speed of light in meters/second.
+
+    Examples
+    --------
+    >>> from scipy.constants import lambda2nu, speed_of_light
+    >>> import numpy as np
+    >>> lambda2nu(np.array((1, speed_of_light)))
+    array([  2.99792458e+08,   1.00000000e+00])
+
+    """
+    xp = array_namespace(lambda_)
+    return c / _asarray(lambda_, xp=xp, subok=True)
+
+
+@xp_capabilities()
+def nu2lambda(nu: "npt.ArrayLike") -> Any:
+    """
+    Convert optical frequency to wavelength.
+
+    Parameters
+    ----------
+    nu : array_like
+        Optical frequency to be converted.
+
+    Returns
+    -------
+    lambda : float or array of floats
+        Equivalent wavelength(s).
+
+    Notes
+    -----
+    Computes ``lambda = c / nu`` where c = 299792458.0, i.e., the
+    (vacuum) speed of light in meters/second.
+
+    Examples
+    --------
+    >>> from scipy.constants import nu2lambda, speed_of_light
+    >>> import numpy as np
+    >>> nu2lambda(np.array((1, speed_of_light)))
+    array([  2.99792458e+08,   1.00000000e+00])
+
+    """
+    xp = array_namespace(nu)
+    return c / _asarray(nu, xp=xp, subok=True)
diff --git a/.venv/lib/python3.12/site-packages/scipy/constants/codata.py b/.venv/lib/python3.12/site-packages/scipy/constants/codata.py
new file mode 100644
index 0000000000000000000000000000000000000000..912e0bbf7c4f14d23ced4546b6704f7789996d97
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/constants/codata.py
@@ -0,0 +1,21 @@
+# This file is not meant for public use and will be removed in SciPy v2.0.0.
+# Use the `scipy.constants` namespace for importing the functions
+# included below.
+
+from scipy._lib.deprecation import _sub_module_deprecation
+
+__all__ = [  # noqa: F822
+    'physical_constants', 'value', 'unit', 'precision', 'find',
+    'ConstantWarning', 'k', 'c',
+
+]
+
+
+def __dir__():
+    return __all__
+
+
+def __getattr__(name):
+    return _sub_module_deprecation(sub_package="constants", module="codata",
+                                   private_modules=["_codata"], all=__all__,
+                                   attribute=name)
diff --git a/.venv/lib/python3.12/site-packages/scipy/constants/constants.py b/.venv/lib/python3.12/site-packages/scipy/constants/constants.py
new file mode 100644
index 0000000000000000000000000000000000000000..855901ba802881090b99b7e8972de741331c7ab9
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/constants/constants.py
@@ -0,0 +1,53 @@
+# This file is not meant for public use and will be removed in SciPy v2.0.0.
+# Use the `scipy.constants` namespace for importing the functions
+# included below.
+
+from scipy._lib.deprecation import _sub_module_deprecation
+
+
+__all__ = [  # noqa: F822
+    'Avogadro', 'Boltzmann', 'Btu', 'Btu_IT', 'Btu_th', 'G',
+    'Julian_year', 'N_A', 'Planck', 'R', 'Rydberg',
+    'Stefan_Boltzmann', 'Wien', 'acre', 'alpha',
+    'angstrom', 'arcmin', 'arcminute', 'arcsec',
+    'arcsecond', 'astronomical_unit', 'atm',
+    'atmosphere', 'atomic_mass', 'atto', 'au', 'bar',
+    'barrel', 'bbl', 'blob', 'c', 'calorie',
+    'calorie_IT', 'calorie_th', 'carat', 'centi',
+    'convert_temperature', 'day', 'deci', 'degree',
+    'degree_Fahrenheit', 'deka', 'dyn', 'dyne', 'e',
+    'eV', 'electron_mass', 'electron_volt',
+    'elementary_charge', 'epsilon_0', 'erg',
+    'exa', 'exbi', 'femto', 'fermi', 'fine_structure',
+    'fluid_ounce', 'fluid_ounce_US', 'fluid_ounce_imp',
+    'foot', 'g', 'gallon', 'gallon_US', 'gallon_imp',
+    'gas_constant', 'gibi', 'giga', 'golden', 'golden_ratio',
+    'grain', 'gram', 'gravitational_constant', 'h', 'hbar',
+    'hectare', 'hecto', 'horsepower', 'hour', 'hp',
+    'inch', 'k', 'kgf', 'kibi', 'kilo', 'kilogram_force',
+    'kmh', 'knot', 'lambda2nu', 'lb', 'lbf',
+    'light_year', 'liter', 'litre', 'long_ton', 'm_e',
+    'm_n', 'm_p', 'm_u', 'mach', 'mebi', 'mega',
+    'metric_ton', 'micro', 'micron', 'mil', 'mile',
+    'milli', 'minute', 'mmHg', 'mph', 'mu_0', 'nano',
+    'nautical_mile', 'neutron_mass', 'nu2lambda',
+    'ounce', 'oz', 'parsec', 'pebi', 'peta',
+    'pi', 'pico', 'point', 'pound', 'pound_force',
+    'proton_mass', 'psi', 'pt', 'short_ton',
+    'sigma', 'slinch', 'slug', 'speed_of_light',
+    'speed_of_sound', 'stone', 'survey_foot',
+    'survey_mile', 'tebi', 'tera', 'ton_TNT',
+    'torr', 'troy_ounce', 'troy_pound', 'u',
+    'week', 'yard', 'year', 'yobi', 'yocto',
+    'yotta', 'zebi', 'zepto', 'zero_Celsius', 'zetta'
+]
+
+
+def __dir__():
+    return __all__
+
+
+def __getattr__(name):
+    return _sub_module_deprecation(sub_package="constants", module="constants",
+                                   private_modules=["_constants"], all=__all__,
+                                   attribute=name)
diff --git a/.venv/lib/python3.12/site-packages/scipy/constants/tests/__init__.py b/.venv/lib/python3.12/site-packages/scipy/constants/tests/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/.venv/lib/python3.12/site-packages/scipy/constants/tests/test_codata.py b/.venv/lib/python3.12/site-packages/scipy/constants/tests/test_codata.py
new file mode 100644
index 0000000000000000000000000000000000000000..ece796136a43ef6f3078272e4d0223263c9e31e8
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/constants/tests/test_codata.py
@@ -0,0 +1,78 @@
+from scipy.constants import find, value, c, speed_of_light, precision
+from numpy.testing import assert_equal, assert_, assert_almost_equal
+import scipy.constants._codata as _cd
+from scipy import constants
+
+
+def test_find():
+    keys = find('weak mixing', disp=False)
+    assert_equal(keys, ['weak mixing angle'])
+
+    keys = find('qwertyuiop', disp=False)
+    assert_equal(keys, [])
+
+    keys = find('natural unit', disp=False)
+    assert_equal(keys, sorted(['natural unit of velocity',
+                                'natural unit of action',
+                                'natural unit of action in eV s',
+                                'natural unit of mass',
+                                'natural unit of energy',
+                                'natural unit of energy in MeV',
+                                'natural unit of momentum',
+                                'natural unit of momentum in MeV/c',
+                                'natural unit of length',
+                                'natural unit of time']))
+
+
+def test_basic_table_parse():
+    c_s = 'speed of light in vacuum'
+    assert_equal(value(c_s), c)
+    assert_equal(value(c_s), speed_of_light)
+
+
+def test_basic_lookup():
+    assert_equal('{} {}'.format(int(_cd.value('speed of light in vacuum')),
+                                _cd.unit('speed of light in vacuum')),
+                 '299792458 m s^-1')
+
+
+def test_find_all():
+    assert_(len(find(disp=False)) > 300)
+
+
+def test_find_single():
+    assert_equal(find('Wien freq', disp=False)[0],
+                 'Wien frequency displacement law constant')
+
+
+def test_2002_vs_2006():
+    assert_almost_equal(value('magn. flux quantum'),
+                        value('mag. flux quantum'))
+
+
+def test_exact_values():
+    # Check that updating stored values with exact ones worked.
+    exact = dict((k, v[0]) for k, v in _cd._physical_constants_2018.items())
+    replace = _cd.exact2018(exact)
+    for key, val in replace.items():
+        assert_equal(val, value(key))
+        assert precision(key) == 0
+
+
+def test_gh11341():
+    # gh-11341 noted that these three constants should exist (for backward
+    # compatibility) and should always have the same value:
+    a = constants.epsilon_0
+    b = constants.physical_constants['electric constant'][0]
+    c = constants.physical_constants['vacuum electric permittivity'][0]
+    assert a == b == c
+
+
+def test_gh14467():
+    # gh-14467 noted that some physical constants in CODATA are rounded
+    # to only ten significant figures even though they are supposed to be
+    # exact. Check that (at least) the case mentioned in the issue is resolved.
+    res = constants.physical_constants['Boltzmann constant in eV/K'][0]
+    ref = (constants.physical_constants['Boltzmann constant'][0]
+           / constants.physical_constants['elementary charge'][0])
+    assert res == ref
diff --git a/.venv/lib/python3.12/site-packages/scipy/constants/tests/test_constants.py b/.venv/lib/python3.12/site-packages/scipy/constants/tests/test_constants.py
new file mode 100644
index 0000000000000000000000000000000000000000..672fac18884ddb012232d6e1a09a6d1ec8e277ef
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/constants/tests/test_constants.py
@@ -0,0 +1,83 @@
+import pytest
+
+import scipy.constants as sc
+from scipy._lib._array_api_no_0d import xp_assert_equal, xp_assert_close
+from scipy._lib._array_api import make_xp_test_case
+
+lazy_xp_modules = [sc]
+
+
+@make_xp_test_case(sc.convert_temperature)
+class TestConvertTemperature:
+    def test_convert_temperature(self, xp):
+        xp_assert_equal(sc.convert_temperature(xp.asarray(32.), 'f', 'Celsius'),
+                        xp.asarray(0.0))
+        xp_assert_equal(sc.convert_temperature(xp.asarray([0., 0.]),
+                                               'celsius', 'Kelvin'),
+                        xp.asarray([273.15, 273.15]))
+        xp_assert_equal(sc.convert_temperature(xp.asarray([0., 0.]), 'kelvin', 'c'),
+                        xp.asarray([-273.15, -273.15]))
+        xp_assert_equal(sc.convert_temperature(xp.asarray([32., 32.]), 'f', 'k'),
+                        xp.asarray([273.15, 273.15]))
+        xp_assert_equal(sc.convert_temperature(xp.asarray([273.15, 273.15]),
+                                               'kelvin', 'F'),
+                        xp.asarray([32., 32.]))
+        xp_assert_equal(sc.convert_temperature(xp.asarray([0., 0.]), 'C', 'fahrenheit'),
+                        xp.asarray([32., 32.]))
+        xp_assert_close(sc.convert_temperature(xp.asarray([0., 0.], dtype=xp.float64),
+                                               'c', 'r'),
+                        xp.asarray([491.67, 491.67], dtype=xp.float64),
+                        rtol=0., atol=1e-13)
+        xp_assert_close(sc.convert_temperature(xp.asarray([491.67, 491.67],
+                                                        dtype=xp.float64),
+                                               'Rankine', 'C'),
+                        xp.asarray([0., 0.], dtype=xp.float64), rtol=0., atol=1e-13)
+        xp_assert_close(sc.convert_temperature(xp.asarray([491.67, 491.67],
+                                                        dtype=xp.float64),
+                                               'r', 'F'),
+                        xp.asarray([32., 32.], dtype=xp.float64), rtol=0., atol=1e-13)
+        xp_assert_close(sc.convert_temperature(xp.asarray([32., 32.], dtype=xp.float64),
+                                               'fahrenheit', 'R'),
+                        xp.asarray([491.67, 491.67], dtype=xp.float64),
+                        rtol=0., atol=1e-13)
+        xp_assert_close(sc.convert_temperature(xp.asarray([273.15, 273.15],
+                                                        dtype=xp.float64),
+                                               'K', 'R'),
+                        xp.asarray([491.67, 491.67], dtype=xp.float64),
+                        rtol=0., atol=1e-13)
+        xp_assert_close(sc.convert_temperature(xp.asarray([491.67, 0.],
+                                                          dtype=xp.float64),
+                                               'rankine', 'kelvin'),
+                        xp.asarray([273.15, 0.], dtype=xp.float64), rtol=0., atol=1e-13)
+
+    def test_convert_temperature_array_like(self):
+        xp_assert_close(sc.convert_temperature([491.67, 0.], 'rankine', 'kelvin'),
+                        [273.15, 0.], rtol=0., atol=1e-13)
+
+
+    def test_convert_temperature_errors(self):
+        with pytest.raises(NotImplementedError, match="old_scale="):
+            sc.convert_temperature(1, old_scale="cheddar", new_scale="kelvin")
+        with pytest.raises(NotImplementedError, match="new_scale="):
+            sc.convert_temperature(1, old_scale="kelvin", new_scale="brie")
+
+
+@make_xp_test_case(sc.lambda2nu)
+class TestLambdaToNu:
+    def test_lambda_to_nu(self, xp):
+        xp_assert_equal(sc.lambda2nu(xp.asarray([sc.speed_of_light, 1])),
+                        xp.asarray([1, sc.speed_of_light]))
+
+
+    def test_lambda_to_nu_array_like(self):
+        xp_assert_close(sc.lambda2nu([sc.speed_of_light, 1]), [1, sc.speed_of_light])
+
+
+@make_xp_test_case(sc.nu2lambda)
+class TestNuToLambda:
+    def test_nu_to_lambda(self, xp):
+        xp_assert_equal(sc.nu2lambda(xp.asarray([sc.speed_of_light, 1])),
+                        xp.asarray([1, sc.speed_of_light]))
+
+    def test_nu_to_lambda_array_like(self):
+        xp_assert_close(sc.nu2lambda([sc.speed_of_light, 1]), [1, sc.speed_of_light])
diff --git a/.venv/lib/python3.12/site-packages/scipy/datasets/__init__.py b/.venv/lib/python3.12/site-packages/scipy/datasets/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..fdd4ffebec4c57f6d399a0f76df2b66056f0b225
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/datasets/__init__.py
@@ -0,0 +1,90 @@
+"""
+================================
+Datasets (:mod:`scipy.datasets`)
+================================
+
+.. currentmodule:: scipy.datasets
+
+Dataset Methods
+===============
+
+.. autosummary::
+   :toctree: generated/
+
+   ascent
+   face
+   electrocardiogram
+
+Utility Methods
+===============
+
+.. autosummary::
+   :toctree: generated/
+
+   download_all    -- Download all the dataset files to specified path.
+   clear_cache     -- Clear cached dataset directory.
+
+
+Usage of Datasets
+=================
+
+SciPy dataset methods can be simply called as follows: ``'()'``
+This downloads the dataset files over the network once, and saves the cache,
+before returning a `numpy.ndarray` object representing the dataset.
+
+Note that the return data structure and data type might be different for
+different dataset methods. For a more detailed example on usage, please look
+into the particular dataset method documentation above.
+
+
+How dataset retrieval and storage works
+=======================================
+
+SciPy dataset files are stored within individual GitHub repositories under the
+SciPy GitHub organization, following a naming convention as
+``'dataset-'``, for example `scipy.datasets.face` files live at
+https://github.com/scipy/dataset-face.  The `scipy.datasets` submodule utilizes
+and depends on `Pooch `_, a Python
+package built to simplify fetching data files. Pooch uses these repos to
+retrieve the respective dataset files when calling the dataset function.
+
+A registry of all the datasets, essentially a mapping of filenames with their
+SHA256 hash and repo urls are maintained, which Pooch uses to handle and verify
+the downloads on function call. After downloading the dataset once, the files
+are saved in the system cache directory under ``'scipy-data'``.
+
+Dataset cache locations may vary on different platforms.
+
+For macOS::
+
+    '~/Library/Caches/scipy-data'
+
+For Linux and other Unix-like platforms::
+
+    '~/.cache/scipy-data'  # or the value of the XDG_CACHE_HOME env var, if defined
+
+For Windows::
+
+    'C:\\Users\\\\AppData\\Local\\\\scipy-data\\Cache'
+
+
+In environments with constrained network connectivity for various security
+reasons or on systems without continuous internet connections, one may manually
+load the cache of the datasets by placing the contents of the dataset repo in
+the above mentioned cache directory to avoid fetching dataset errors without
+the internet connectivity.
+
+"""
+
+
+from ._fetchers import face, ascent, electrocardiogram
+from ._download_all import download_all
+from ._utils import clear_cache
+
+__all__ = ['ascent', 'electrocardiogram', 'face',
+           'download_all', 'clear_cache']
+
+
+from scipy._lib._testutils import PytestTester
+test = PytestTester(__name__)
+del PytestTester
diff --git a/.venv/lib/python3.12/site-packages/scipy/datasets/_download_all.py b/.venv/lib/python3.12/site-packages/scipy/datasets/_download_all.py
new file mode 100644
index 0000000000000000000000000000000000000000..4152b9f0f4ba053d7e71ff98f0da8a473492d927
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/datasets/_download_all.py
@@ -0,0 +1,74 @@
+"""
+Platform independent script to download all the
+`scipy.datasets` module data files.
+This doesn't require a full scipy build.
+
+Run: python _download_all.py 
+"""
+
+from scipy._lib._array_api import xp_capabilities
+
+import argparse
+try:
+    import pooch
+except ImportError:
+    pooch = None
+
+
+if __spec__.parent is None or __spec__.parent == '':
+    # Running as python script, use absolute import
+    import _registry  # type: ignore
+else:
+    # Running as python module, use relative import
+    from . import _registry
+
+
+@xp_capabilities(out_of_scope=True)
+def download_all(path=None):
+    """
+    Utility method to download all the dataset files
+    for `scipy.datasets` module.
+
+    Parameters
+    ----------
+    path : str, optional
+        Directory path to download all the dataset files.
+        If None, default to the system cache_dir detected by pooch.
+
+    Examples
+    --------
+    Download the datasets to the default cache location:
+
+    >>> from scipy import datasets
+    >>> datasets.download_all()
+
+    Download the datasets to the current directory:
+
+    >>> datasets.download_all(".")
+
+    """
+    if pooch is None:
+        raise ImportError("Missing optional dependency 'pooch' required "
+                          "for scipy.datasets module. Please use pip or "
+                          "conda to install 'pooch'.")
+    if path is None:
+        path = pooch.os_cache('scipy-data')
+    # https://github.com/scipy/scipy/issues/21879
+    downloader = pooch.HTTPDownloader(headers={"User-Agent": "SciPy"})
+    for dataset_name, dataset_hash in _registry.registry.items():
+        pooch.retrieve(url=_registry.registry_urls[dataset_name],
+                       known_hash=dataset_hash,
+                       fname=dataset_name, path=path, downloader=downloader)
+
+
+def main():
+    parser = argparse.ArgumentParser(description='Download SciPy data files.')
+    parser.add_argument("path", nargs='?', type=str,
+                        default=pooch.os_cache('scipy-data'),
+                        help="Directory path to download all the data files.")
+    args = parser.parse_args()
+    download_all(args.path)
+
+
+if __name__ == "__main__":
+    main()
diff --git a/.venv/lib/python3.12/site-packages/scipy/datasets/_fetchers.py b/.venv/lib/python3.12/site-packages/scipy/datasets/_fetchers.py
new file mode 100644
index 0000000000000000000000000000000000000000..ec69d75c854d8bffbb54fe15409ae1dc323d4383
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/datasets/_fetchers.py
@@ -0,0 +1,225 @@
+import sys
+
+from numpy import array, frombuffer, load
+from ._registry import registry, registry_urls
+
+from scipy._lib._array_api import xp_capabilities
+
+try:
+    import pooch
+except ImportError:
+    pooch = None
+    data_fetcher = None
+else:
+    data_fetcher = pooch.create(  # type:ignore[union-attr]
+        # Use the default cache folder for the operating system
+        # Pooch uses appdirs (https://github.com/ActiveState/appdirs) to
+        # select an appropriate directory for the cache on each platform.
+        path=pooch.os_cache("scipy-data"),  # type:ignore[union-attr]
+
+        # The remote data is on Github
+        # base_url is a required param, even though we override this
+        # using individual urls in the registry.
+        base_url="https://github.com/scipy/",
+        registry=registry,
+        urls=registry_urls
+    )
+
+
+def fetch_data(dataset_name, data_fetcher=data_fetcher):
+    if data_fetcher is None:
+        raise ImportError("Missing optional dependency 'pooch' required "
+                          "for scipy.datasets module. Please use pip or "
+                          "conda to install 'pooch'.")
+    # https://github.com/scipy/scipy/issues/21879
+    downloader = pooch.HTTPDownloader(
+        headers={"User-Agent": f"SciPy {sys.modules['scipy'].__version__}"}
+    )
+    # The "fetch" method returns the full path to the downloaded data file.
+    return data_fetcher.fetch(dataset_name, downloader=downloader)
+
+
+@xp_capabilities(out_of_scope=True)
+def ascent():
+    """
+    Get an 8-bit grayscale bit-depth, 512 x 512 derived image for easy
+    use in demos.
+
+    The image is derived from
+    https://pixnio.com/people/accent-to-the-top
+
+    Returns
+    -------
+    ascent : ndarray
+       convenient image to use for testing and demonstration
+
+    Examples
+    --------
+    >>> import scipy.datasets
+    >>> ascent = scipy.datasets.ascent()
+    >>> ascent.shape
+    (512, 512)
+    >>> ascent.max()
+    np.uint8(255)
+
+    >>> import matplotlib.pyplot as plt
+    >>> plt.gray()
+    >>> plt.imshow(ascent)
+    >>> plt.show()
+
+    """
+    import pickle
+
+    # The file will be downloaded automatically the first time this is run,
+    # returning the path to the downloaded file. Afterwards, Pooch finds
+    # it in the local cache and doesn't repeat the download.
+    fname = fetch_data("ascent.dat")
+    # Now we just need to load it with our standard Python tools.
+    with open(fname, 'rb') as f:
+        ascent = array(pickle.load(f))
+    return ascent
+
+
+@xp_capabilities(out_of_scope=True)
+def electrocardiogram():
+    """
+    Load an electrocardiogram as an example for a 1-D signal.
+
+    The returned signal is a 5 minute long electrocardiogram (ECG), a medical
+    recording of the heart's electrical activity, sampled at 360 Hz.
+
+    Returns
+    -------
+    ecg : ndarray
+        The electrocardiogram in millivolt (mV) sampled at 360 Hz.
+
+    Notes
+    -----
+    The provided signal is an excerpt (19:35 to 24:35) from the `record 208`_
+    (lead MLII) provided by the MIT-BIH Arrhythmia Database [1]_ on
+    PhysioNet [2]_. The excerpt includes noise induced artifacts, typical
+    heartbeats as well as pathological changes.
+
+    .. _record 208: https://physionet.org/physiobank/database/html/mitdbdir/records.htm#208
+
+    .. versionadded:: 1.1.0
+
+    References
+    ----------
+    .. [1] Moody GB, Mark RG. The impact of the MIT-BIH Arrhythmia Database.
+           IEEE Eng in Med and Biol 20(3):45-50 (May-June 2001).
+           (PMID: 11446209); :doi:`10.13026/C2F305`
+    .. [2] Goldberger AL, Amaral LAN, Glass L, Hausdorff JM, Ivanov PCh,
+           Mark RG, Mietus JE, Moody GB, Peng C-K, Stanley HE. PhysioBank,
+           PhysioToolkit, and PhysioNet: Components of a New Research Resource
+           for Complex Physiologic Signals. Circulation 101(23):e215-e220;
+           :doi:`10.1161/01.CIR.101.23.e215`
+
+    Examples
+    --------
+    >>> from scipy.datasets import electrocardiogram
+    >>> ecg = electrocardiogram()
+    >>> ecg
+    array([-0.245, -0.215, -0.185, ..., -0.405, -0.395, -0.385], shape=(108000,))
+    >>> ecg.shape, ecg.mean(), ecg.std()
+    ((108000,), -0.16510875, 0.5992473991177294)
+
+    As stated the signal features several areas with a different morphology.
+    E.g., the first few seconds show the electrical activity of a heart in
+    normal sinus rhythm as seen below.
+
+    >>> import numpy as np
+    >>> import matplotlib.pyplot as plt
+    >>> fs = 360
+    >>> time = np.arange(ecg.size) / fs
+    >>> plt.plot(time, ecg)
+    >>> plt.xlabel("time in s")
+    >>> plt.ylabel("ECG in mV")
+    >>> plt.xlim(9, 10.2)
+    >>> plt.ylim(-1, 1.5)
+    >>> plt.show()
+
+    After second 16, however, the first premature ventricular contractions,
+    also called extrasystoles, appear. These have a different morphology
+    compared to typical heartbeats. The difference can easily be observed
+    in the following plot.
+
+    >>> plt.plot(time, ecg)
+    >>> plt.xlabel("time in s")
+    >>> plt.ylabel("ECG in mV")
+    >>> plt.xlim(46.5, 50)
+    >>> plt.ylim(-2, 1.5)
+    >>> plt.show()
+
+    At several points large artifacts disturb the recording, e.g.:
+
+    >>> plt.plot(time, ecg)
+    >>> plt.xlabel("time in s")
+    >>> plt.ylabel("ECG in mV")
+    >>> plt.xlim(207, 215)
+    >>> plt.ylim(-2, 3.5)
+    >>> plt.show()
+
+    Finally, examining the power spectrum reveals that most of the biosignal is
+    made up of lower frequencies. At 60 Hz the noise induced by the mains
+    electricity can be clearly observed.
+
+    >>> from scipy.signal import welch
+    >>> f, Pxx = welch(ecg, fs=fs, nperseg=2048, scaling="spectrum")
+    >>> plt.semilogy(f, Pxx)
+    >>> plt.xlabel("Frequency in Hz")
+    >>> plt.ylabel("Power spectrum of the ECG in mV**2")
+    >>> plt.xlim(f[[0, -1]])
+    >>> plt.show()
+    """
+    fname = fetch_data("ecg.dat")
+    with load(fname) as file:
+        ecg = file["ecg"].astype(int)  # np.uint16 -> int
+    # Convert raw output of ADC to mV: (ecg - adc_zero) / adc_gain
+    ecg = (ecg - 1024) / 200.0
+    return ecg
+
+
+@xp_capabilities(out_of_scope=True)
+def face(gray=False):
+    """
+    Get a 1024 x 768, color image of a raccoon face.
+
+    The image is derived from
+    https://pixnio.com/fauna-animals/raccoons/raccoon-procyon-lotor
+
+    Parameters
+    ----------
+    gray : bool, optional
+        If True return 8-bit grey-scale image, otherwise return a color image
+
+    Returns
+    -------
+    face : ndarray
+        image of a raccoon face
+
+    Examples
+    --------
+    >>> import scipy.datasets
+    >>> face = scipy.datasets.face()
+    >>> face.shape
+    (768, 1024, 3)
+    >>> face.max()
+    np.uint8(255)
+
+    >>> import matplotlib.pyplot as plt
+    >>> plt.gray()
+    >>> plt.imshow(face)
+    >>> plt.show()
+
+    """
+    import bz2
+    fname = fetch_data("face.dat")
+    with open(fname, 'rb') as f:
+        rawdata = f.read()
+    face_data = bz2.decompress(rawdata)
+    face = frombuffer(face_data, dtype='uint8').reshape((768, 1024, 3))
+    if gray is True:
+        face = (0.21 * face[:, :, 0] + 0.71 * face[:, :, 1] +
+                0.07 * face[:, :, 2]).astype('uint8')
+    return face
diff --git a/.venv/lib/python3.12/site-packages/scipy/datasets/_registry.py b/.venv/lib/python3.12/site-packages/scipy/datasets/_registry.py
new file mode 100644
index 0000000000000000000000000000000000000000..969384ad9843159e766100bfa9755aed8102dd09
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/datasets/_registry.py
@@ -0,0 +1,26 @@
+##########################################################################
+# This file serves as the dataset registry for SciPy Datasets SubModule.
+##########################################################################
+
+
+# To generate the SHA256 hash, use the command
+# openssl sha256 
+registry = {
+    "ascent.dat": "03ce124c1afc880f87b55f6b061110e2e1e939679184f5614e38dacc6c1957e2",
+    "ecg.dat": "f20ad3365fb9b7f845d0e5c48b6fe67081377ee466c3a220b7f69f35c8958baf",
+    "face.dat": "9d8b0b4d081313e2b485748c770472e5a95ed1738146883d84c7030493e82886"
+}
+
+registry_urls = {
+    "ascent.dat": "https://raw.githubusercontent.com/scipy/dataset-ascent/main/ascent.dat",
+    "ecg.dat": "https://raw.githubusercontent.com/scipy/dataset-ecg/main/ecg.dat",
+    "face.dat": "https://raw.githubusercontent.com/scipy/dataset-face/main/face.dat"
+}
+
+# dataset method mapping with their associated filenames
+#  : ["filename1", "filename2", ...]
+method_files_map = {
+    "ascent": ["ascent.dat"],
+    "electrocardiogram": ["ecg.dat"],
+    "face": ["face.dat"]
+}
diff --git a/.venv/lib/python3.12/site-packages/scipy/datasets/_utils.py b/.venv/lib/python3.12/site-packages/scipy/datasets/_utils.py
new file mode 100644
index 0000000000000000000000000000000000000000..468f095441870d22c02ca5777a5284fdbd807418
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/datasets/_utils.py
@@ -0,0 +1,80 @@
+import os
+import shutil
+from ._registry import method_files_map
+
+from scipy._lib._array_api import xp_capabilities
+
+try:
+    import platformdirs
+except ImportError:
+    platformdirs = None  # type: ignore[assignment]
+
+
+def _clear_cache(datasets, cache_dir=None, method_map=None):
+    if method_map is None:
+        # Use SciPy Datasets method map
+        method_map = method_files_map
+    if cache_dir is None:
+        # Use default cache_dir path
+        if platformdirs is None:
+            # platformdirs is pooch dependency
+            raise ImportError("Missing optional dependency 'pooch' required "
+                              "for scipy.datasets module. Please use pip or "
+                              "conda to install 'pooch'.")
+        cache_dir = platformdirs.user_cache_dir("scipy-data")
+
+    if not os.path.exists(cache_dir):
+        print(f"Cache Directory {cache_dir} doesn't exist. Nothing to clear.")
+        return
+
+    if datasets is None:
+        print(f"Cleaning the cache directory {cache_dir}!")
+        shutil.rmtree(cache_dir)
+    else:
+        if not isinstance(datasets, list | tuple):
+            # single dataset method passed should be converted to list
+            datasets = [datasets, ]
+        for dataset in datasets:
+            assert callable(dataset)
+            dataset_name = dataset.__name__  # Name of the dataset method
+            if dataset_name not in method_map:
+                raise ValueError(f"Dataset method {dataset_name} doesn't "
+                                 "exist. Please check if the passed dataset "
+                                 "is a subset of the following dataset "
+                                 f"methods: {list(method_map.keys())}")
+
+            data_files = method_map[dataset_name]
+            data_filepaths = [os.path.join(cache_dir, file)
+                              for file in data_files]
+            for data_filepath in data_filepaths:
+                if os.path.exists(data_filepath):
+                    print("Cleaning the file "
+                          f"{os.path.split(data_filepath)[1]} "
+                          f"for dataset {dataset_name}")
+                    os.remove(data_filepath)
+                else:
+                    print(f"Path {data_filepath} doesn't exist. "
+                          "Nothing to clear.")
+
+
+@xp_capabilities(out_of_scope=True)
+def clear_cache(datasets=None):
+    """
+    Cleans the SciPy datasets cache directory.
+
+    Parameters
+    ----------
+    datasets : callable or list/tuple of callable or None
+        Dataset whose cached files are to be removed. If None (default), all cached
+        files are removed.
+
+    Examples
+    --------
+    >>> from scipy import datasets
+    >>> ascent_array = datasets.ascent()
+    >>> ascent_array.shape
+    (512, 512)
+    >>> datasets.clear_cache([datasets.ascent])
+    Cleaning the file ascent.dat for dataset ascent
+    """
+    _clear_cache(datasets)
diff --git a/.venv/lib/python3.12/site-packages/scipy/datasets/tests/__init__.py b/.venv/lib/python3.12/site-packages/scipy/datasets/tests/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/.venv/lib/python3.12/site-packages/scipy/datasets/tests/test_data.py b/.venv/lib/python3.12/site-packages/scipy/datasets/tests/test_data.py
new file mode 100644
index 0000000000000000000000000000000000000000..c535fcac7c20c7cb2ce0f313b5ea5c2bd2907e42
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/datasets/tests/test_data.py
@@ -0,0 +1,123 @@
+from scipy.datasets._registry import registry
+from scipy.datasets._fetchers import data_fetcher
+from scipy.datasets._utils import _clear_cache
+from scipy.datasets import ascent, face, electrocardiogram, download_all
+from numpy.testing import assert_equal, assert_almost_equal
+import os
+from threading import get_ident
+import pytest
+
+pooch = pytest.importorskip("pooch")
+
+
+data_dir = data_fetcher.path  # type: ignore
+
+
+def _has_hash(path, expected_hash):
+    """Check if the provided path has the expected hash."""
+    if not os.path.exists(path):
+        return False
+    return pooch.file_hash(path) == expected_hash
+
+
+class TestDatasets:
+
+    @pytest.fixture(scope='module', autouse=True)
+    def test_download_all(self):
+        # This fixture requires INTERNET CONNECTION
+
+        # test_setup phase
+        download_all()
+
+        yield
+
+    @pytest.mark.fail_slow(10)
+    def test_existence_all(self):
+        assert len(os.listdir(data_dir)) >= len(registry)
+
+    def test_ascent(self):
+        assert_equal(ascent().shape, (512, 512))
+
+        # hash check
+        assert _has_hash(os.path.join(data_dir, "ascent.dat"),
+                         registry["ascent.dat"])
+
+    def test_face(self):
+        assert_equal(face().shape, (768, 1024, 3))
+
+        # hash check
+        assert _has_hash(os.path.join(data_dir, "face.dat"),
+                         registry["face.dat"])
+
+    def test_electrocardiogram(self):
+        # Test shape, dtype and stats of signal
+        ecg = electrocardiogram()
+        assert_equal(ecg.dtype, float)
+        assert_equal(ecg.shape, (108000,))
+        assert_almost_equal(ecg.mean(), -0.16510875)
+        assert_almost_equal(ecg.std(), 0.5992473991177294)
+
+        # hash check
+        assert _has_hash(os.path.join(data_dir, "ecg.dat"),
+                         registry["ecg.dat"])
+
+
+def test_clear_cache(tmp_path):
+    # Note: `tmp_path` is a pytest fixture, it handles cleanup
+    thread_basepath = tmp_path / str(get_ident())
+    thread_basepath.mkdir()
+
+    dummy_basepath = thread_basepath / "dummy_cache_dir"
+    dummy_basepath.mkdir()
+
+    # Create three dummy dataset files for dummy dataset methods
+    dummy_method_map = {}
+    for i in range(4):
+        dummy_method_map[f"data{i}"] = [f"data{i}.dat"]
+        data_filepath = dummy_basepath / f"data{i}.dat"
+        data_filepath.write_text("")
+
+    # clear files associated to single dataset method data0
+    # also test callable argument instead of list of callables
+    def data0():
+        pass
+    _clear_cache(datasets=data0, cache_dir=dummy_basepath,
+                 method_map=dummy_method_map)
+    assert not os.path.exists(dummy_basepath/"data0.dat")
+
+    # clear files associated to multiple dataset methods "data3" and "data4"
+    def data1():
+        pass
+
+    def data2():
+        pass
+    _clear_cache(datasets=[data1, data2], cache_dir=dummy_basepath,
+                 method_map=dummy_method_map)
+    assert not os.path.exists(dummy_basepath/"data1.dat")
+    assert not os.path.exists(dummy_basepath/"data2.dat")
+
+    # clear multiple dataset files "data3_0.dat" and "data3_1.dat"
+    # associated with dataset method "data3"
+    def data4():
+        pass
+    # create files
+    (dummy_basepath / "data4_0.dat").write_text("")
+    (dummy_basepath / "data4_1.dat").write_text("")
+
+    dummy_method_map["data4"] = ["data4_0.dat", "data4_1.dat"]
+    _clear_cache(datasets=[data4], cache_dir=dummy_basepath,
+                 method_map=dummy_method_map)
+    assert not os.path.exists(dummy_basepath/"data4_0.dat")
+    assert not os.path.exists(dummy_basepath/"data4_1.dat")
+
+    # wrong dataset method should raise ValueError since it
+    # doesn't exist in the dummy_method_map
+    def data5():
+        pass
+    with pytest.raises(ValueError):
+        _clear_cache(datasets=[data5], cache_dir=dummy_basepath,
+                     method_map=dummy_method_map)
+
+    # remove all dataset cache
+    _clear_cache(datasets=None, cache_dir=dummy_basepath)
+    assert not os.path.exists(dummy_basepath)
diff --git a/.venv/lib/python3.12/site-packages/scipy/differentiate/__init__.py b/.venv/lib/python3.12/site-packages/scipy/differentiate/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..c3a7ccc4b33f27dbae7958641a89106cf9580326
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/differentiate/__init__.py
@@ -0,0 +1,27 @@
+"""
+==============================================================
+Finite Difference Differentiation (:mod:`scipy.differentiate`)
+==============================================================
+
+.. currentmodule:: scipy.differentiate
+
+SciPy ``differentiate`` provides functions for performing finite difference
+numerical differentiation of black-box functions.
+
+.. autosummary::
+   :toctree: generated/
+
+   derivative
+   jacobian
+   hessian
+
+"""
+
+
+from ._differentiate import *
+
+__all__ = ['derivative', 'jacobian', 'hessian']
+
+from scipy._lib._testutils import PytestTester
+test = PytestTester(__name__)
+del PytestTester
diff --git a/.venv/lib/python3.12/site-packages/scipy/differentiate/_differentiate.py b/.venv/lib/python3.12/site-packages/scipy/differentiate/_differentiate.py
new file mode 100644
index 0000000000000000000000000000000000000000..2779f37e0ea6c72ccad1655a9692243da5c59e91
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/differentiate/_differentiate.py
@@ -0,0 +1,1141 @@
+# mypy: disable-error-code="attr-defined"
+import warnings
+import numpy as np
+import scipy._lib._elementwise_iterative_method as eim
+from scipy._lib._util import _RichResult
+from scipy._lib._array_api import array_namespace, xp_copy, xp_promote, xp_capabilities
+import scipy._external.array_api_extra as xpx
+
+_EERRORINCREASE = -1  # used in derivative
+
+def _derivative_iv(f, x, args, kwargs, tolerances, maxiter, order, initial_step,
+                   step_factor, step_direction, preserve_shape, callback):
+    # Input validation for `derivative`
+    xp = array_namespace(x)
+
+    if not callable(f):
+        raise ValueError('`f` must be callable.')
+
+    if not np.iterable(args):
+        args = (args,)
+
+    tolerances = {} if tolerances is None else tolerances
+    atol = tolerances.get('atol', None)
+    rtol = tolerances.get('rtol', None)
+
+    # tolerances are floats, not arrays; OK to use NumPy
+    message = 'Tolerances and step parameters must be non-negative scalars.'
+    tols = np.asarray([atol if atol is not None else 1,
+                       rtol if rtol is not None else 1,
+                       step_factor])
+    if (not np.issubdtype(tols.dtype, np.number) or np.any(tols < 0)
+            or np.any(np.isnan(tols)) or tols.shape != (3,)):
+        raise ValueError(message)
+    step_factor = float(tols[2])
+
+    maxiter_int = int(maxiter)
+    if maxiter != maxiter_int or maxiter <= 0:
+        raise ValueError('`maxiter` must be a positive integer.')
+
+    order_int = int(order)
+    if order_int != order or order <= 0:
+        raise ValueError('`order` must be a positive integer.')
+
+    step_direction = xp.asarray(step_direction)
+    initial_step = xp.asarray(initial_step)
+    temp = xp.broadcast_arrays(x, step_direction, initial_step)
+    x, step_direction, initial_step = temp
+
+    message = '`preserve_shape` must be True or False.'
+    if preserve_shape not in {True, False}:
+        raise ValueError(message)
+
+    if callback is not None and not callable(callback):
+        raise ValueError('`callback` must be callable.')
+
+    return (f, x, args, kwargs, atol, rtol, maxiter_int, order_int, initial_step,
+            step_factor, step_direction, preserve_shape, callback)
+
+
+
+_array_api_strict_skip_reason = 'Array API does not support fancy indexing assignment.'
+_dask_reason = 'boolean indexing assignment'
+
+
+@xp_capabilities(skip_backends=[('array_api_strict', _array_api_strict_skip_reason),
+                                ('dask.array', _dask_reason)], jax_jit=False)
+def derivative(f, x, *, args=(), kwargs=None, tolerances=None, maxiter=10,
+               order=8, initial_step=0.5, step_factor=2.0,
+               step_direction=0, preserve_shape=False, callback=None):
+    """Evaluate the derivative of an elementwise, real scalar function numerically.
+
+    For each element of the output of `f`, `derivative` approximates the first
+    derivative of `f` at the corresponding element of `x` using finite difference
+    differentiation.
+
+    This function works elementwise when `x`, `step_direction`, and `args` contain
+    (broadcastable) arrays.
+
+    Parameters
+    ----------
+    f : callable
+        The function whose derivative is desired. The signature must be::
+
+            f(xi: ndarray, *argsi) -> ndarray
+
+        where each element of ``xi`` is a finite real number and ``argsi`` is a tuple,
+        which may contain an arbitrary number of arrays that are broadcastable with
+        ``xi``. `f` must be an elementwise function: each scalar element ``f(xi)[j]``
+        must equal ``f(xi[j])`` for valid indices ``j``. It must not mutate the array
+        ``xi`` or the arrays in ``argsi``.
+    x : float array_like
+        Abscissae at which to evaluate the derivative. Must be broadcastable with
+        `args` and `step_direction`.
+    args : tuple of array_like, optional
+        Additional positional array arguments to be passed to `f`. Arrays
+        must be broadcastable with one another and the arrays of `init`.
+        If the callable for which the root is desired requires arguments that are
+        not broadcastable with `x`, wrap that callable with `f` such that `f`
+        accepts only `x` and broadcastable ``*args``.
+    kwargs : dict of str:array_like, optional
+        Additional keyword arguments to be passed to `f`. See `args`.
+    tolerances : dictionary of floats, optional
+        Absolute and relative tolerances. Valid keys of the dictionary are:
+
+        - ``atol`` - absolute tolerance on the derivative
+        - ``rtol`` - relative tolerance on the derivative
+
+        Iteration will stop when ``res.error < atol + rtol * abs(res.df)``. The default
+        `atol` is the smallest normal number of the appropriate dtype, and
+        the default `rtol` is the square root of the precision of the
+        appropriate dtype.
+    maxiter : int, default: 10
+        The maximum number of iterations of the algorithm to perform. See Notes.
+    order : int, default: 8
+        The (positive integer) order of the finite difference formula to be
+        used. Odd integers will be rounded up to the next even integer.
+    initial_step : float array_like, default: 0.5
+        The (absolute) initial step size for the finite difference derivative
+        approximation.
+    step_factor : float, default: 2.0
+        The factor by which the step size is *reduced* in each iteration; i.e.
+        the step size in iteration 1 is ``initial_step/step_factor``. If
+        ``step_factor < 1``, subsequent steps will be greater than the initial
+        step; this may be useful if steps smaller than some threshold are
+        undesirable (e.g. due to subtractive cancellation error).
+    step_direction : int array_like
+        An array representing the direction of the finite difference steps (for
+        use when `x` lies near to the boundary of the domain of the function.)
+        Must be broadcastable with `x` and all `args`.
+        Where 0 (default), central differences are used; where negative (e.g.
+        -1), steps are non-positive; and where positive (e.g. 1), all steps are
+        non-negative.
+    preserve_shape : bool, default: False
+        In the following, "arguments of `f`" refers to the array ``xi`` and
+        any arrays within ``argsi``. Let ``shape`` be the broadcasted shape
+        of `x` and all elements of `args` (which is conceptually
+        distinct from ``xi` and ``argsi`` passed into `f`).
+
+        - When ``preserve_shape=False`` (default), `f` must accept arguments
+          of *any* broadcastable shapes.
+
+        - When ``preserve_shape=True``, `f` must accept arguments of shape
+          ``shape`` *or* ``shape + (n,)``, where ``(n,)`` is the number of
+          abscissae at which the function is being evaluated.
+
+        In either case, for each scalar element ``xi[j]`` within ``xi``, the array
+        returned by `f` must include the scalar ``f(xi[j])`` at the same index.
+        Consequently, the shape of the output is always the shape of the input
+        ``xi``.
+
+        See Examples.
+    callback : callable, optional
+        An optional user-supplied function to be called before the first
+        iteration and after each iteration.
+        Called as ``callback(res)``, where ``res`` is a ``_RichResult``
+        similar to that returned by `derivative` (but containing the current
+        iterate's values of all variables). If `callback` raises a
+        ``StopIteration``, the algorithm will terminate immediately and
+        `derivative` will return a result. `callback` must not mutate
+        `res` or its attributes.
+
+    Returns
+    -------
+    res : _RichResult
+        An object similar to an instance of `scipy.optimize.OptimizeResult` with the
+        following attributes. The descriptions are written as though the values will
+        be scalars; however, if `f` returns an array, the outputs will be
+        arrays of the same shape.
+
+        success : bool array
+            ``True`` where the algorithm terminated successfully (status ``0``);
+            ``False`` otherwise.
+        status : int array
+            An integer representing the exit status of the algorithm.
+
+            - ``0`` : The algorithm converged to the specified tolerances.
+            - ``-1`` : The error estimate increased, so iteration was terminated.
+            - ``-2`` : The maximum number of iterations was reached.
+            - ``-3`` : A non-finite value was encountered.
+            - ``-4`` : Iteration was terminated by `callback`.
+            - ``1`` : The algorithm is proceeding normally (in `callback` only).
+
+        df : float array
+            The derivative of `f` at `x`, if the algorithm terminated
+            successfully.
+        error : float array
+            An estimate of the error: the magnitude of the difference between
+            the current estimate of the derivative and the estimate in the
+            previous iteration.
+        nit : int array
+            The number of iterations of the algorithm that were performed.
+        nfev : int array
+            The number of points at which `f` was evaluated.
+        x : float array
+            The value at which the derivative of `f` was evaluated
+            (after broadcasting with `args` and `step_direction`).
+
+    See Also
+    --------
+    jacobian, hessian
+
+    Notes
+    -----
+    The implementation was inspired by jacobi [1]_, numdifftools [2]_, and
+    DERIVEST [3]_, but the implementation follows the theory of Taylor series
+    more straightforwardly (and arguably naively so).
+    In the first iteration, the derivative is estimated using a finite
+    difference formula of order `order` with maximum step size `initial_step`.
+    Each subsequent iteration, the maximum step size is reduced by
+    `step_factor`, and the derivative is estimated again until a termination
+    condition is reached. The error estimate is the magnitude of the difference
+    between the current derivative approximation and that of the previous
+    iteration.
+
+    The stencils of the finite difference formulae are designed such that
+    abscissae are "nested": after `f` is evaluated at ``order + 1``
+    points in the first iteration, `f` is evaluated at only two new points
+    in each subsequent iteration; ``order - 1`` previously evaluated function
+    values required by the finite difference formula are reused, and two
+    function values (evaluations at the points furthest from `x`) are unused.
+
+    Step sizes are absolute. When the step size is small relative to the
+    magnitude of `x`, precision is lost; for example, if `x` is ``1e20``, the
+    default initial step size of ``0.5`` cannot be resolved. Accordingly,
+    consider using larger initial step sizes for large magnitudes of `x`.
+
+    The default tolerances are challenging to satisfy at points where the
+    true derivative is exactly zero. If the derivative may be exactly zero,
+    consider specifying an absolute tolerance (e.g. ``atol=1e-12``) to
+    improve convergence.
+
+    References
+    ----------
+    .. [1] Hans Dembinski (@HDembinski). jacobi.
+           https://github.com/HDembinski/jacobi
+    .. [2] Per A. Brodtkorb and John D'Errico. numdifftools.
+           https://numdifftools.readthedocs.io/en/latest/
+    .. [3] John D'Errico. DERIVEST: Adaptive Robust Numerical Differentiation.
+           https://www.mathworks.com/matlabcentral/fileexchange/13490-adaptive-robust-numerical-differentiation
+    .. [4] Numerical Differentition. Wikipedia.
+           https://en.wikipedia.org/wiki/Numerical_differentiation
+
+    Examples
+    --------
+    Evaluate the derivative of ``np.exp`` at several points ``x``.
+
+    >>> import numpy as np
+    >>> from scipy.differentiate import derivative
+    >>> f = np.exp
+    >>> df = np.exp  # true derivative
+    >>> x = np.linspace(1, 2, 5)
+    >>> res = derivative(f, x)
+    >>> res.df  # approximation of the derivative
+    array([2.71828183, 3.49034296, 4.48168907, 5.75460268, 7.3890561 ])
+    >>> res.error  # estimate of the error
+    array([7.13740178e-12, 9.16600129e-12, 1.17594823e-11, 1.51061386e-11,
+           1.94262384e-11])
+    >>> abs(res.df - df(x))  # true error
+    array([2.53130850e-14, 3.55271368e-14, 5.77315973e-14, 5.59552404e-14,
+           6.92779167e-14])
+
+    Show the convergence of the approximation as the step size is reduced.
+    Each iteration, the step size is reduced by `step_factor`, so for
+    sufficiently small initial step, each iteration reduces the error by a
+    factor of ``1/step_factor**order`` until finite precision arithmetic
+    inhibits further improvement.
+
+    >>> import matplotlib.pyplot as plt
+    >>> iter = list(range(1, 12))  # maximum iterations
+    >>> hfac = 2  # step size reduction per iteration
+    >>> hdir = [-1, 0, 1]  # compare left-, central-, and right- steps
+    >>> order = 4  # order of differentiation formula
+    >>> x = 1
+    >>> ref = df(x)
+    >>> errors = []  # true error
+    >>> for i in iter:
+    ...     res = derivative(f, x, maxiter=i, step_factor=hfac,
+    ...                      step_direction=hdir, order=order,
+    ...                      # prevent early termination
+    ...                      tolerances=dict(atol=0, rtol=0))
+    ...     errors.append(abs(res.df - ref))
+    >>> errors = np.array(errors)
+    >>> plt.semilogy(iter, errors[:, 0], label='left differences')
+    >>> plt.semilogy(iter, errors[:, 1], label='central differences')
+    >>> plt.semilogy(iter, errors[:, 2], label='right differences')
+    >>> plt.xlabel('iteration')
+    >>> plt.ylabel('error')
+    >>> plt.legend()
+    >>> plt.show()
+    >>> (errors[1, 1] / errors[0, 1], 1 / hfac**order)
+    (0.06215223140159822, 0.0625)
+
+    The implementation is vectorized over `x`, `step_direction`, and `args`.
+    The function is evaluated once before the first iteration to perform input
+    validation and standardization, and once per iteration thereafter.
+
+    >>> def f(x, p):
+    ...     f.nit += 1
+    ...     return x**p
+    >>> f.nit = 0
+    >>> def df(x, p):
+    ...     return p*x**(p-1)
+    >>> x = np.arange(1, 5)
+    >>> p = np.arange(1, 6).reshape((-1, 1))
+    >>> hdir = np.arange(-1, 2).reshape((-1, 1, 1))
+    >>> res = derivative(f, x, args=(p,), step_direction=hdir, maxiter=1)
+    >>> np.allclose(res.df, df(x, p))
+    True
+    >>> res.df.shape
+    (3, 5, 4)
+    >>> f.nit
+    2
+
+    By default, `preserve_shape` is False, and therefore the callable
+    `f` may be called with arrays of any broadcastable shapes.
+    For example:
+
+    >>> shapes = []
+    >>> def f(x, c):
+    ...    shape = np.broadcast_shapes(x.shape, c.shape)
+    ...    shapes.append(shape)
+    ...    return np.sin(c*x)
+    >>>
+    >>> c = [1, 5, 10, 20]
+    >>> res = derivative(f, 0, args=(c,))
+    >>> shapes
+    [(4,), (4, 8), (4, 2), (3, 2), (2, 2), (1, 2)]
+
+    To understand where these shapes are coming from - and to better
+    understand how `derivative` computes accurate results - note that
+    higher values of ``c`` correspond with higher frequency sinusoids.
+    The higher frequency sinusoids make the function's derivative change
+    faster, so more function evaluations are required to achieve the target
+    accuracy:
+
+    >>> res.nfev
+    array([11, 13, 15, 17], dtype=int32)
+
+    The initial ``shape``, ``(4,)``, corresponds with evaluating the
+    function at a single abscissa and all four frequencies; this is used
+    for input validation and to determine the size and dtype of the arrays
+    that store results. The next shape corresponds with evaluating the
+    function at an initial grid of abscissae and all four frequencies.
+    Successive calls to the function evaluate the function at two more
+    abscissae, increasing the effective order of the approximation by two.
+    However, in later function evaluations, the function is evaluated at
+    fewer frequencies because the corresponding derivative has already
+    converged to the required tolerance. This saves function evaluations to
+    improve performance, but it requires the function to accept arguments of
+    any shape.
+
+    "Vector-valued" functions are unlikely to satisfy this requirement.
+    For example, consider
+
+    >>> def f(x):
+    ...    return [x, np.sin(3*x), x+np.sin(10*x), np.sin(20*x)*(x-1)**2]
+
+    This integrand is not compatible with `derivative` as written; for instance,
+    the shape of the output will not be the same as the shape of ``x``. Such a
+    function *could* be converted to a compatible form with the introduction of
+    additional parameters, but this would be inconvenient. In such cases,
+    a simpler solution would be to use `preserve_shape`.
+
+    >>> shapes = []
+    >>> def f(x):
+    ...     shapes.append(x.shape)
+    ...     x0, x1, x2, x3 = x
+    ...     return [x0, np.sin(3*x1), x2+np.sin(10*x2), np.sin(20*x3)*(x3-1)**2]
+    >>>
+    >>> x = np.zeros(4)
+    >>> res = derivative(f, x, preserve_shape=True)
+    >>> shapes
+    [(4,), (4, 8), (4, 2), (4, 2), (4, 2), (4, 2)]
+
+    Here, the shape of ``x`` is ``(4,)``. With ``preserve_shape=True``, the
+    function may be called with argument ``x`` of shape ``(4,)`` or ``(4, n)``,
+    and this is what we observe.
+
+    """
+    # TODO (followup):
+    #  - investigate behavior at saddle points
+    #  - multivariate functions?
+    #  - relative steps?
+    #  - show example of `np.vectorize`
+
+    res = _derivative_iv(f, x, args, kwargs, tolerances, maxiter, order, initial_step,
+                         step_factor, step_direction, preserve_shape, callback)
+    (func, x, args, kwargs, atol, rtol, maxiter, order,
+     h0, fac, hdir, preserve_shape, callback) = res
+
+    # Initialization
+    # Since f(x) (no step) is not needed for central differences, it may be
+    # possible to eliminate this function evaluation. However, it's useful for
+    # input validation and standardization, and everything else is designed to
+    # reduce function calls, so let's keep it simple.
+    temp = eim._initialize(func, (x,), args, kwargs=kwargs,
+                           preserve_shape=preserve_shape)
+    func, xs, fs, args, shape, dtype, xp = temp
+
+    finfo = xp.finfo(dtype)
+    atol = finfo.smallest_normal if atol is None else atol
+    rtol = finfo.eps**0.5 if rtol is None else rtol  # keep same as `hessian`
+
+    x, f = xs[0], fs[0]
+    df = xp.full_like(f, xp.nan)
+
+    # Ideally we'd broadcast the shape of `hdir` in `_elementwise_algo_init`, but
+    # it's simpler to do it here than to generalize `_elementwise_algo_init` further.
+    # `hdir` and `x` are already broadcasted in `_derivative_iv`, so we know
+    # that `hdir` can be broadcasted to the final shape. Same with `h0`.
+    hdir = xp.broadcast_to(hdir, shape)
+    hdir = xp.reshape(hdir, (-1,))
+    hdir = xp.astype(xp.sign(hdir), dtype)
+    h0 = xp.broadcast_to(h0, shape)
+    h0 = xp.reshape(h0, (-1,))
+    h0 = xp.astype(h0, dtype)
+    h0 = xpx.at(h0)[h0 <= 0].set(xp.nan)
+
+    status = xp.full_like(x, eim._EINPROGRESS, dtype=xp.int32)  # in progress
+    nit, nfev = 0, 1  # one function evaluations performed above
+    # Boolean indices of left, central, right, and (all) one-sided steps
+    il = hdir < 0
+    ic = hdir == 0
+    ir = hdir > 0
+    io = il | ir
+
+    # Most of these attributes are reasonably obvious, but:
+    # - `fs` holds all the function values of all active `x`. The zeroth
+    #   axis corresponds with active points `x`, the first axis corresponds
+    #   with the different steps (in the order described in
+    #   `_derivative_weights`).
+    # - `terms` (which could probably use a better name) is half the `order`,
+    #   which is always even.
+    work = _RichResult(x=x, df=df, fs=f[:, xp.newaxis], error=xp.nan, h=h0,
+                       df_last=xp.nan, error_last=xp.nan, fac=fac,
+                       atol=atol, rtol=rtol, nit=nit, nfev=nfev,
+                       status=status, dtype=dtype, terms=(order+1)//2,
+                       hdir=hdir, il=il, ic=ic, ir=ir, io=io,
+                       # Store the weights in an object so they can't get compressed
+                       # Using RichResult to allow dot notation, but a dict would work
+                       diff_state=_RichResult(central=[], right=[], fac=None))
+
+    # This is the correspondence between terms in the `work` object and the
+    # final result. In this case, the mapping is trivial. Note that `success`
+    # is prepended automatically.
+    res_work_pairs = [('status', 'status'), ('df', 'df'), ('error', 'error'),
+                      ('nit', 'nit'), ('nfev', 'nfev'), ('x', 'x')]
+
+    def pre_func_eval(work):
+        """Determine the abscissae at which the function needs to be evaluated.
+
+        See `_derivative_weights` for a description of the stencil (pattern
+        of the abscissae).
+
+        In the first iteration, there is only one stored function value in
+        `work.fs`, `f(x)`, so we need to evaluate at `order` new points. In
+        subsequent iterations, we evaluate at two new points. Note that
+        `work.x` is always flattened into a 1D array after broadcasting with
+        all `args`, so we add a new axis at the end and evaluate all point
+        in one call to the function.
+
+        For improvement:
+        - Consider measuring the step size actually taken, since ``(x + h) - x``
+          is not identically equal to `h` with floating point arithmetic.
+        - Adjust the step size automatically if `x` is too big to resolve the
+          step.
+        - We could probably save some work if there are no central difference
+          steps or no one-sided steps.
+        """
+        n = work.terms  # half the order
+        h = work.h[:, xp.newaxis]  # step size
+        c = work.fac  # step reduction factor
+        d = c**0.5  # square root of step reduction factor (one-sided stencil)
+        # Note - no need to be careful about dtypes until we allocate `x_eval`
+
+        if work.nit == 0:
+            hc = h / c**xp.arange(n, dtype=work.dtype)
+            hc = xp.concat((-xp.flip(hc, axis=-1), hc), axis=-1)
+        else:
+            hc = xp.concat((-h, h), axis=-1) / c**(n-1)
+
+        if work.nit == 0:
+            hr = h / d**xp.arange(2*n, dtype=work.dtype)
+        else:
+            hr = xp.concat((h, h/d), axis=-1) / c**(n-1)
+
+        n_new = 2*n if work.nit == 0 else 2  # number of new abscissae
+        x_eval = xp.zeros((work.hdir.shape[0], n_new), dtype=work.dtype)
+        il, ic, ir = work.il, work.ic, work.ir
+        x_eval = xpx.at(x_eval)[ir].set(work.x[ir][:, xp.newaxis] + hr[ir])
+        x_eval = xpx.at(x_eval)[ic].set(work.x[ic][:, xp.newaxis] + hc[ic])
+        x_eval = xpx.at(x_eval)[il].set(work.x[il][:, xp.newaxis] - hr[il])
+        return x_eval
+
+    def post_func_eval(x, f, work):
+        """ Estimate the derivative and error from the function evaluations
+
+        As in `pre_func_eval`: in the first iteration, there is only one stored
+        function value in `work.fs`, `f(x)`, so we need to add the `order` new
+        points. In subsequent iterations, we add two new points. The tricky
+        part is getting the order to match that of the weights, which is
+        described in `_derivative_weights`.
+
+        For improvement:
+        - Change the order of the weights (and steps in `pre_func_eval`) to
+          simplify `work_fc` concatenation and eliminate `fc` concatenation.
+        - It would be simple to do one-step Richardson extrapolation with `df`
+          and `df_last` to increase the order of the estimate and/or improve
+          the error estimate.
+        - Process the function evaluations in a more numerically favorable
+          way. For instance, combining the pairs of central difference evals
+          into a second-order approximation and using Richardson extrapolation
+          to produce a higher order approximation seemed to retain accuracy up
+          to very high order.
+        - Alternatively, we could use `polyfit` like Jacobi. An advantage of
+          fitting polynomial to more points than necessary is improved noise
+          tolerance.
+        """
+        n = work.terms
+        n_new = n if work.nit == 0 else 1
+        il, ic, io = work.il, work.ic, work.io
+
+        # Central difference
+        # `work_fc` is *all* the points at which the function has been evaluated
+        # `fc` is the points we're using *this iteration* to produce the estimate
+        work_fc = (f[ic][:, :n_new], work.fs[ic], f[ic][:, -n_new:])
+        work_fc = xp.concat(work_fc, axis=-1)
+        if work.nit == 0:
+            fc = work_fc
+        else:
+            fc = (work_fc[:, :n], work_fc[:, n:n+1], work_fc[:, -n:])
+            fc = xp.concat(fc, axis=-1)
+
+        # One-sided difference
+        work_fo = xp.concat((work.fs[io], f[io]), axis=-1)
+        if work.nit == 0:
+            fo = work_fo
+        else:
+            fo = xp.concat((work_fo[:, 0:1], work_fo[:, -2*n:]), axis=-1)
+
+        work.fs = xp.zeros((ic.shape[0], work.fs.shape[-1] + 2*n_new), dtype=work.dtype)
+        work.fs = xpx.at(work.fs)[ic].set(work_fc)
+        work.fs = xpx.at(work.fs)[io].set(work_fo)
+
+        wc, wo = _derivative_weights(work, n, xp)
+        work.df_last = xp.asarray(work.df, copy=True)
+        work.df = xpx.at(work.df)[ic].set(fc @ wc / work.h[ic])
+        work.df = xpx.at(work.df)[io].set(fo @ wo / work.h[io])
+        work.df = xpx.at(work.df)[il].multiply(-1)
+
+        work.h /= work.fac
+        work.error_last = work.error
+        # Simple error estimate - the difference in derivative estimates between
+        # this iteration and the last. This is typically conservative because if
+        # convergence has begin, the true error is much closer to the difference
+        # between the current estimate and the *next* error estimate. However,
+        # we could use Richarson extrapolation to produce an error estimate that
+        # is one order higher, and take the difference between that and
+        # `work.df` (which would just be constant factor that depends on `fac`.)
+        work.error = xp.abs(work.df - work.df_last)
+
+    def check_termination(work):
+        """Terminate due to convergence, non-finite values, or error increase"""
+        stop = xp.astype(xp.zeros_like(work.df), xp.bool)
+
+        i = work.error < work.atol + work.rtol*abs(work.df)
+        work.status = xpx.at(work.status)[i].set(eim._ECONVERGED)
+        stop = xpx.at(stop)[i].set(True)
+
+        if work.nit > 0:
+            i = ~((xp.isfinite(work.x) & xp.isfinite(work.df)) | stop)
+            work.df = xpx.at(work.df)[i].set(xp.nan)
+            work.status = xpx.at(work.status)[i].set(eim._EVALUEERR)
+            stop = xpx.at(stop)[i].set(True)
+
+        # With infinite precision, there is a step size below which
+        # all smaller step sizes will reduce the error. But in floating point
+        # arithmetic, catastrophic cancellation will begin to cause the error
+        # to increase again. This heuristic tries to avoid step sizes that are
+        # too small. There may be more theoretically sound approaches for
+        # detecting a step size that minimizes the total error, but this
+        # heuristic seems simple and effective.
+        i = (work.error > work.error_last*10) & ~stop
+        work.status = xpx.at(work.status)[i].set(_EERRORINCREASE)
+        stop = xpx.at(stop)[i].set(True)
+
+        return stop
+
+    def post_termination_check(work):
+        return
+
+    def customize_result(res, shape):
+        return shape
+
+    return eim._loop(work, callback, shape, maxiter, func, args, dtype,
+                     pre_func_eval, post_func_eval, check_termination,
+                     post_termination_check, customize_result, res_work_pairs,
+                     xp, preserve_shape)
+
+
+def _derivative_weights(work, n, xp):
+    # This produces the weights of the finite difference formula for a given
+    # stencil. In experiments, use of a second-order central difference formula
+    # with Richardson extrapolation was more accurate numerically, but it was
+    # more complicated, and it would have become even more complicated when
+    # adding support for one-sided differences. However, now that all the
+    # function evaluation values are stored, they can be processed in whatever
+    # way is desired to produce the derivative estimate. We leave alternative
+    # approaches to future work. To be more self-contained, here is the theory
+    # for deriving the weights below.
+    #
+    # Recall that the Taylor expansion of a univariate, scalar-values function
+    # about a point `x` may be expressed as:
+    #      f(x + h)  =     f(x) + f'(x)*h + f''(x)/2!*h**2  + O(h**3)
+    # Suppose we evaluate f(x), f(x+h), and f(x-h).  We have:
+    #      f(x)      =     f(x)
+    #      f(x + h)  =     f(x) + f'(x)*h + f''(x)/2!*h**2  + O(h**3)
+    #      f(x - h)  =     f(x) - f'(x)*h + f''(x)/2!*h**2  + O(h**3)
+    # We can solve for weights `wi` such that:
+    #   w1*f(x)      = w1*(f(x))
+    # + w2*f(x + h)  = w2*(f(x) + f'(x)*h + f''(x)/2!*h**2) + O(h**3)
+    # + w3*f(x - h)  = w3*(f(x) - f'(x)*h + f''(x)/2!*h**2) + O(h**3)
+    #                =     0    + f'(x)*h + 0               + O(h**3)
+    # Then
+    #     f'(x) ~ (w1*f(x) + w2*f(x+h) + w3*f(x-h))/h
+    # is a finite difference derivative approximation with error O(h**2),
+    # and so it is said to be a "second-order" approximation. Under certain
+    # conditions (e.g. well-behaved function, `h` sufficiently small), the
+    # error in the approximation will decrease with h**2; that is, if `h` is
+    # reduced by a factor of 2, the error is reduced by a factor of 4.
+    #
+    # By default, we use eighth-order formulae. Our central-difference formula
+    # uses abscissae:
+    #   x-h/c**3, x-h/c**2, x-h/c, x-h, x, x+h, x+h/c, x+h/c**2, x+h/c**3
+    # where `c` is the step factor. (Typically, the step factor is greater than
+    # one, so the outermost points - as written above - are actually closest to
+    # `x`.) This "stencil" is chosen so that each iteration, the step can be
+    # reduced by the factor `c`, and most of the function evaluations can be
+    # reused with the new step size. For example, in the next iteration, we
+    # will have:
+    #   x-h/c**4, x-h/c**3, x-h/c**2, x-h/c, x, x+h/c, x+h/c**2, x+h/c**3, x+h/c**4
+    # We do not reuse `x-h` and `x+h` for the new derivative estimate.
+    # While this would increase the order of the formula and thus the
+    # theoretical convergence rate, it is also less stable numerically.
+    # (As noted above, there are other ways of processing the values that are
+    # more stable. Thus, even now we store `f(x-h)` and `f(x+h)` in `work.fs`
+    # to simplify future development of this sort of improvement.)
+    #
+    # The (right) one-sided formula is produced similarly using abscissae
+    #   x, x+h, x+h/d, x+h/d**2, ..., x+h/d**6, x+h/d**7, x+h/d**7
+    # where `d` is the square root of `c`. (The left one-sided formula simply
+    # uses -h.) When the step size is reduced by factor `c = d**2`, we have
+    # abscissae:
+    #   x, x+h/d**2, x+h/d**3..., x+h/d**8, x+h/d**9, x+h/d**9
+    # `d` is chosen as the square root of `c` so that the rate of the step-size
+    # reduction is the same per iteration as in the central difference case.
+    # Note that because the central difference formulas are inherently of even
+    # order, for simplicity, we use only even-order formulas for one-sided
+    # differences, too.
+
+    # It's possible for the user to specify `fac` in, say, double precision but
+    # `x` and `args` in single precision. `fac` gets converted to single
+    # precision, but we should always use double precision for the intermediate
+    # calculations here to avoid additional error in the weights.
+    fac = float(work.fac)
+
+    # Note that if the user switches back to floating point precision with
+    # `x` and `args`, then `fac` will not necessarily equal the (lower
+    # precision) cached `_derivative_weights.fac`, and the weights will
+    # need to be recalculated. This could be fixed, but it's late, and of
+    # low consequence.
+
+    diff_state = work.diff_state
+    if fac != diff_state.fac:
+        diff_state.central = []
+        diff_state.right = []
+        diff_state.fac = fac
+
+    if len(diff_state.central) != 2*n + 1:
+        # Central difference weights. Consider refactoring this; it could
+        # probably be more compact.
+        # Note: Using NumPy here is OK; we convert to xp-type at the end
+        i = np.arange(-n, n + 1)
+        p = np.abs(i) - 1.  # center point has power `p` -1, but sign `s` is 0
+        s = np.sign(i)
+
+        h = s / fac ** p
+        A = np.vander(h, increasing=True).T
+        b = np.zeros(2*n + 1)
+        b[1] = 1
+        weights = np.linalg.solve(A, b)
+
+        # Enforce identities to improve accuracy
+        weights[n] = 0
+        for i in range(n):
+            weights[-i-1] = -weights[i]
+
+        # Cache the weights. We only need to calculate them once unless
+        # the step factor changes.
+        diff_state.central = weights
+
+        # One-sided difference weights. The left one-sided weights (with
+        # negative steps) are simply the negative of the right one-sided
+        # weights, so no need to compute them separately.
+        i = np.arange(2*n + 1)
+        p = i - 1.
+        s = np.sign(i)
+
+        h = s / np.sqrt(fac) ** p
+        A = np.vander(h, increasing=True).T
+        b = np.zeros(2 * n + 1)
+        b[1] = 1
+        weights = np.linalg.solve(A, b)
+
+        diff_state.right = weights
+
+    return (xp.asarray(diff_state.central, dtype=work.dtype),
+            xp.asarray(diff_state.right, dtype=work.dtype))
+
+
+@xp_capabilities(skip_backends=[('array_api_strict', _array_api_strict_skip_reason),
+                                ('dask.array', _dask_reason)], jax_jit=False)
+def jacobian(f, x, *, tolerances=None, maxiter=10, order=8, initial_step=0.5,
+             step_factor=2.0, step_direction=0):
+    r"""Evaluate the Jacobian of a function numerically.
+
+    Parameters
+    ----------
+    f : callable
+        The function whose Jacobian is desired. The signature must be::
+
+            f(xi: ndarray) -> ndarray
+
+        where each element of ``xi`` is a finite real. If the function to be
+        differentiated accepts additional arguments, wrap it (e.g. using
+        `functools.partial` or ``lambda``) and pass the wrapped callable
+        into `jacobian`. `f` must not mutate the array ``xi``. See Notes
+        regarding vectorization and the dimensionality of the input and output.
+    x : float array_like
+        Points at which to evaluate the Jacobian. Must have at least one dimension.
+        See Notes regarding the dimensionality and vectorization.
+    tolerances : dictionary of floats, optional
+        Absolute and relative tolerances. Valid keys of the dictionary are:
+
+        - ``atol`` - absolute tolerance on the derivative
+        - ``rtol`` - relative tolerance on the derivative
+
+        Iteration will stop when ``res.error < atol + rtol * abs(res.df)``. The default
+        `atol` is the smallest normal number of the appropriate dtype, and
+        the default `rtol` is the square root of the precision of the
+        appropriate dtype.
+    maxiter : int, default: 10
+        The maximum number of iterations of the algorithm to perform. See
+        Notes.
+    order : int, default: 8
+        The (positive integer) order of the finite difference formula to be
+        used. Odd integers will be rounded up to the next even integer.
+    initial_step : float array_like, default: 0.5
+        The (absolute) initial step size for the finite difference derivative
+        approximation. Must be broadcastable with `x` and `step_direction`.
+    step_factor : float, default: 2.0
+        The factor by which the step size is *reduced* in each iteration; i.e.
+        the step size in iteration 1 is ``initial_step/step_factor``. If
+        ``step_factor < 1``, subsequent steps will be greater than the initial
+        step; this may be useful if steps smaller than some threshold are
+        undesirable (e.g. due to subtractive cancellation error).
+    step_direction : int array_like
+        An array representing the direction of the finite difference steps (e.g.
+        for use when `x` lies near to the boundary of the domain of the function.)
+        Must be broadcastable with `x` and `initial_step`.
+        Where 0 (default), central differences are used; where negative (e.g.
+        -1), steps are non-positive; and where positive (e.g. 1), all steps are
+        non-negative.
+
+    Returns
+    -------
+    res : _RichResult
+        An object similar to an instance of `scipy.optimize.OptimizeResult` with the
+        following attributes. The descriptions are written as though the values will
+        be scalars; however, if `f` returns an array, the outputs will be
+        arrays of the same shape.
+
+        success : bool array
+            ``True`` where the algorithm terminated successfully (status ``0``);
+            ``False`` otherwise.
+        status : int array
+            An integer representing the exit status of the algorithm.
+
+            - ``0`` : The algorithm converged to the specified tolerances.
+            - ``-1`` : The error estimate increased, so iteration was terminated.
+            - ``-2`` : The maximum number of iterations was reached.
+            - ``-3`` : A non-finite value was encountered.
+
+        df : float array
+            The Jacobian of `f` at `x`, if the algorithm terminated
+            successfully.
+        error : float array
+            An estimate of the error: the magnitude of the difference between
+            the current estimate of the Jacobian and the estimate in the
+            previous iteration.
+        nit : int array
+            The number of iterations of the algorithm that were performed.
+        nfev : int array
+            The number of points at which `f` was evaluated.
+
+        Each element of an attribute is associated with the corresponding
+        element of `df`. For instance, element ``i`` of `nfev` is the
+        number of points at which `f` was evaluated for the sake of
+        computing element ``i`` of `df`.
+
+    See Also
+    --------
+    derivative, hessian
+
+    Notes
+    -----
+    Suppose we wish to evaluate the Jacobian of a function
+    :math:`f: \mathbf{R}^m \rightarrow \mathbf{R}^n`. Assign to variables
+    ``m`` and ``n`` the positive integer values of :math:`m` and :math:`n`,
+    respectively, and let ``...`` represent an arbitrary tuple of integers.
+    If we wish to evaluate the Jacobian at a single point, then:
+
+    - argument `x` must be an array of shape ``(m,)``
+    - argument `f` must be vectorized to accept an array of shape ``(m, ...)``.
+      The first axis represents the :math:`m` inputs of :math:`f`; the remainder
+      are for evaluating the function at multiple points in a single call.
+    - argument `f` must return an array of shape ``(n, ...)``. The first
+      axis represents the :math:`n` outputs of :math:`f`; the remainder
+      are for the result of evaluating the function at multiple points.
+    - attribute ``df`` of the result object will be an array of shape ``(n, m)``,
+      the Jacobian.
+
+    This function is also vectorized in the sense that the Jacobian can be
+    evaluated at ``k`` points in a single call. In this case, `x` would be an
+    array of shape ``(m, k)``, `f` would accept an array of shape
+    ``(m, k, ...)`` and return an array of shape ``(n, k, ...)``, and the ``df``
+    attribute of the result would have shape ``(n, m, k)``.
+
+    Suppose the desired callable ``f_not_vectorized`` is not vectorized; it can
+    only accept an array of shape ``(m,)``. A simple solution to satisfy the required
+    interface is to wrap ``f_not_vectorized`` as follows::
+
+        def f(x):
+            return np.apply_along_axis(f_not_vectorized, axis=0, arr=x)
+
+    Alternatively, suppose the desired callable ``f_vec_q`` is vectorized, but
+    only for 2-D arrays of shape ``(m, q)``. To satisfy the required interface,
+    consider::
+
+        def f(x):
+            m, batch = x.shape[0], x.shape[1:]  # x.shape is (m, ...)
+            x = np.reshape(x, (m, -1))  # `-1` is short for q = prod(batch)
+            res = f_vec_q(x)  # pass shape (m, q) to function
+            n = res.shape[0]
+            return np.reshape(res, (n,) + batch)  # return shape (n, ...)
+
+    Then pass the wrapped callable ``f`` as the first argument of `jacobian`.
+
+    References
+    ----------
+    .. [1] Jacobian matrix and determinant, *Wikipedia*,
+           https://en.wikipedia.org/wiki/Jacobian_matrix_and_determinant
+
+    Examples
+    --------
+    The Rosenbrock function maps from :math:`\mathbf{R}^m \rightarrow \mathbf{R}`;
+    the SciPy implementation `scipy.optimize.rosen` is vectorized to accept an
+    array of shape ``(m, p)`` and return an array of shape ``p``. Suppose we wish
+    to evaluate the Jacobian (AKA the gradient because the function returns a scalar)
+    at ``[0.5, 0.5, 0.5]``.
+
+    >>> import numpy as np
+    >>> from scipy.differentiate import jacobian
+    >>> from scipy.optimize import rosen, rosen_der
+    >>> m = 3
+    >>> x = np.full(m, 0.5)
+    >>> res = jacobian(rosen, x)
+    >>> ref = rosen_der(x)  # reference value of the gradient
+    >>> res.df, ref
+    (array([-51.,  -1.,  50.]), array([-51.,  -1.,  50.]))
+
+    As an example of a function with multiple outputs, consider Example 4
+    from [1]_.
+
+    >>> def f(x):
+    ...     x1, x2, x3 = x
+    ...     return [x1, 5*x3, 4*x2**2 - 2*x3, x3*np.sin(x1)]
+
+    The true Jacobian is given by:
+
+    >>> def df(x):
+    ...         x1, x2, x3 = x
+    ...         one = np.ones_like(x1)
+    ...         return [[one, 0*one, 0*one],
+    ...                 [0*one, 0*one, 5*one],
+    ...                 [0*one, 8*x2, -2*one],
+    ...                 [x3*np.cos(x1), 0*one, np.sin(x1)]]
+
+    Evaluate the Jacobian at an arbitrary point.
+
+    >>> rng = np.random.default_rng(389252938452)
+    >>> x = rng.random(size=3)
+    >>> res = jacobian(f, x)
+    >>> ref = df(x)
+    >>> res.df.shape == (4, 3)
+    True
+    >>> np.allclose(res.df, ref)
+    True
+
+    Evaluate the Jacobian at 10 arbitrary points in a single call.
+
+    >>> x = rng.random(size=(3, 10))
+    >>> res = jacobian(f, x)
+    >>> ref = df(x)
+    >>> res.df.shape == (4, 3, 10)
+    True
+    >>> np.allclose(res.df, ref)
+    True
+
+    """
+    xp = array_namespace(x)
+    x0 = xp_promote(x, force_floating=True, xp=xp)
+
+    if x0.ndim < 1:
+        message = "Argument `x` must be at least 1-D."
+        raise ValueError(message)
+
+    m = x0.shape[0]
+    i = xp.arange(m)
+
+    def wrapped(x):
+        p = () if x.ndim == x0.ndim else (x.shape[-1],)  # number of abscissae
+
+        new_shape = (m, m) + x0.shape[1:] + p
+        xph = xp.expand_dims(x0, axis=1)
+        if x.ndim != x0.ndim:
+            xph = xp.expand_dims(xph, axis=-1)
+        xph = xp_copy(xp.broadcast_to(xph, new_shape), xp=xp)
+        xph = xpx.at(xph)[i, i].set(x)
+        return f(xph)
+
+    res = derivative(wrapped, x, tolerances=tolerances,
+                     maxiter=maxiter, order=order, initial_step=initial_step,
+                     step_factor=step_factor, preserve_shape=True,
+                     step_direction=step_direction)
+
+    del res.x  # the user knows `x`, and the way it gets broadcasted is meaningless here
+    return res
+
+
+@xp_capabilities(skip_backends=[('array_api_strict', _array_api_strict_skip_reason),
+                                ('dask.array', _dask_reason)], jax_jit=False)
+def hessian(f, x, *, tolerances=None, maxiter=10,
+            order=8, initial_step=0.5, step_factor=2.0):
+    r"""Evaluate the Hessian of a function numerically.
+
+    Parameters
+    ----------
+    f : callable
+        The function whose Hessian is desired. The signature must be::
+
+            f(xi: ndarray) -> ndarray
+
+        where each element of ``xi`` is a finite real. If the function to be
+        differentiated accepts additional arguments, wrap it (e.g. using
+        `functools.partial` or ``lambda``) and pass the wrapped callable
+        into `hessian`. `f` must not mutate the array ``xi``. See Notes
+        regarding vectorization and the dimensionality of the input and output.
+    x : float array_like
+        Points at which to evaluate the Hessian. Must have at least one dimension.
+        See Notes regarding the dimensionality and vectorization.
+    tolerances : dictionary of floats, optional
+        Absolute and relative tolerances. Valid keys of the dictionary are:
+
+        - ``atol`` - absolute tolerance on the derivative
+        - ``rtol`` - relative tolerance on the derivative
+
+        Iteration will stop when ``res.error < atol + rtol * abs(res.df)``. The default
+        `atol` is the smallest normal number of the appropriate dtype, and
+        the default `rtol` is the square root of the precision of the
+        appropriate dtype.
+    maxiter : int, default: 10
+        The maximum number of iterations of the algorithm to perform. See Notes.
+    order : int, default: 8
+        The (positive integer) order of the finite difference formula to be
+        used. Odd integers will be rounded up to the next even integer.
+    initial_step : float, default: 0.5
+        The (absolute) initial step size for the finite difference derivative
+        approximation.
+    step_factor : float, default: 2.0
+        The factor by which the step size is *reduced* in each iteration; i.e.
+        the step size in iteration 1 is ``initial_step/step_factor``. If
+        ``step_factor < 1``, subsequent steps will be greater than the initial
+        step; this may be useful if steps smaller than some threshold are
+        undesirable (e.g. due to subtractive cancellation error).
+
+    Returns
+    -------
+    res : _RichResult
+        An object similar to an instance of `scipy.optimize.OptimizeResult` with the
+        following attributes. The descriptions are written as though the values will
+        be scalars; however, if `f` returns an array, the outputs will be
+        arrays of the same shape.
+
+        success : bool array
+            ``True`` where the algorithm terminated successfully (status ``0``);
+            ``False`` otherwise.
+        status : int array
+            An integer representing the exit status of the algorithm.
+
+            - ``0`` : The algorithm converged to the specified tolerances.
+            - ``-1`` : The error estimate increased, so iteration was terminated.
+            - ``-2`` : The maximum number of iterations was reached.
+            - ``-3`` : A non-finite value was encountered.
+
+        ddf : float array
+            The Hessian of `f` at `x`, if the algorithm terminated
+            successfully.
+        error : float array
+            An estimate of the error: the magnitude of the difference between
+            the current estimate of the Hessian and the estimate in the
+            previous iteration.
+        nfev : int array
+            The number of points at which `f` was evaluated.
+
+        Each element of an attribute is associated with the corresponding
+        element of `ddf`. For instance, element ``[i, j]`` of `nfev` is the
+        number of points at which `f` was evaluated for the sake of
+        computing element ``[i, j]`` of `ddf`.
+
+    See Also
+    --------
+    derivative, jacobian
+
+    Notes
+    -----
+    Suppose we wish to evaluate the Hessian of a function
+    :math:`f: \mathbf{R}^m \rightarrow \mathbf{R}`, and we assign to variable
+    ``m`` the positive integer value of :math:`m`. If we wish to evaluate
+    the Hessian at a single point, then:
+
+    - argument `x` must be an array of shape ``(m,)``
+    - argument `f` must be vectorized to accept an array of shape
+      ``(m, ...)``. The first axis represents the :math:`m` inputs of
+      :math:`f`; the remaining axes indicated by ellipses are for evaluating
+      the function at several abscissae in a single call.
+    - argument `f` must return an array of shape ``(...)``.
+    - attribute ``dff`` of the result object will be an array of shape ``(m, m)``,
+      the Hessian.
+
+    This function is also vectorized in the sense that the Hessian can be
+    evaluated at ``k`` points in a single call. In this case, `x` would be an
+    array of shape ``(m, k)``, `f` would accept an array of shape
+    ``(m, ...)`` and return an array of shape ``(...)``, and the ``ddf``
+    attribute of the result would have shape ``(m, m, k)``. Note that the
+    axis associated with the ``k`` points is included within the axes
+    denoted by ``(...)``.
+
+    Currently, `hessian` is implemented by nesting calls to `jacobian`.
+    All options passed to `hessian` are used for both the inner and outer
+    calls with one exception: the `rtol` used in the inner `jacobian` call
+    is tightened by a factor of 100 with the expectation that the inner
+    error can be ignored. A consequence is that `rtol` should not be set
+    less than 100 times the precision of the dtype of `x`; a warning is
+    emitted otherwise.
+
+    References
+    ----------
+    .. [1] Hessian matrix, *Wikipedia*,
+           https://en.wikipedia.org/wiki/Hessian_matrix
+
+    Examples
+    --------
+    The Rosenbrock function maps from :math:`\mathbf{R}^m \rightarrow \mathbf{R}`;
+    the SciPy implementation `scipy.optimize.rosen` is vectorized to accept an
+    array of shape ``(m, ...)`` and return an array of shape ``...``. Suppose we
+    wish to evaluate the Hessian at ``[0.5, 0.5, 0.5]``.
+
+    >>> import numpy as np
+    >>> from scipy.differentiate import hessian
+    >>> from scipy.optimize import rosen, rosen_hess
+    >>> m = 3
+    >>> x = np.full(m, 0.5)
+    >>> res = hessian(rosen, x)
+    >>> ref = rosen_hess(x)  # reference value of the Hessian
+    >>> np.allclose(res.ddf, ref)
+    True
+
+    `hessian` is vectorized to evaluate the Hessian at multiple points
+    in a single call.
+
+    >>> rng = np.random.default_rng(4589245925010)
+    >>> x = rng.random((m, 10))
+    >>> res = hessian(rosen, x)
+    >>> ref = [rosen_hess(xi) for xi in x.T]
+    >>> ref = np.moveaxis(ref, 0, -1)
+    >>> np.allclose(res.ddf, ref)
+    True
+
+    """
+    # todo:
+    # - add ability to vectorize over additional parameters (*args?)
+    # - error estimate stack with inner jacobian (or use legit 2D stencil)
+
+    kwargs = dict(maxiter=maxiter, order=order, initial_step=initial_step,
+                  step_factor=step_factor)
+    tolerances = {} if tolerances is None else tolerances
+    atol = tolerances.get('atol', None)
+    rtol = tolerances.get('rtol', None)
+
+    xp = array_namespace(x)
+    x0 = xp_promote(x, force_floating=True, xp=xp)
+
+    finfo = xp.finfo(x0.dtype)
+    rtol = finfo.eps**0.5 if rtol is None else rtol  # keep same as `derivative`
+
+    # tighten the inner tolerance to make the inner error negligible
+    rtol_min = finfo.eps * 100
+    message = (f"The specified `{rtol=}`, but error estimates are likely to be "
+               f"unreliable when `rtol < {rtol_min}`.")
+    if 0 < rtol < rtol_min:  # rtol <= 0 is an error
+        warnings.warn(message, RuntimeWarning, stacklevel=2)
+        rtol = rtol_min
+
+    def df(x):
+        tolerances = dict(rtol=rtol/100, atol=atol)
+        temp = jacobian(f, x, tolerances=tolerances, **kwargs)
+        nfev.append(temp.nfev if len(nfev) == 0 else temp.nfev.sum(axis=-1))
+        return temp.df
+
+    nfev = []  # track inner function evaluations
+    res = jacobian(df, x, tolerances=tolerances, **kwargs)  # jacobian of jacobian
+
+    nfev = xp.cumulative_sum(xp.stack(nfev), axis=0)
+    res_nit = xp.astype(res.nit[xp.newaxis, ...], xp.int64)  # appease torch
+    res.nfev = xp.take_along_axis(nfev, res_nit, axis=0)[0]
+    res.ddf = res.df
+    del res.df  # this is renamed to ddf
+    del res.nit  # this is only the outer-jacobian nit
+
+    return res
diff --git a/.venv/lib/python3.12/site-packages/scipy/differentiate/tests/__init__.py b/.venv/lib/python3.12/site-packages/scipy/differentiate/tests/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/.venv/lib/python3.12/site-packages/scipy/differentiate/tests/test_differentiate.py b/.venv/lib/python3.12/site-packages/scipy/differentiate/tests/test_differentiate.py
new file mode 100644
index 0000000000000000000000000000000000000000..1427bf03813d78528987421bdbd028be3ae5333c
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/differentiate/tests/test_differentiate.py
@@ -0,0 +1,703 @@
+import math
+import pytest
+
+import numpy as np
+
+import scipy._lib._elementwise_iterative_method as eim
+import scipy._external.array_api_extra as xpx
+from scipy._lib._array_api_no_0d import xp_assert_close, xp_assert_equal, xp_assert_less
+from scipy._lib._array_api import is_numpy, is_torch, make_xp_test_case
+
+from scipy import stats, optimize, special
+from scipy.differentiate import derivative, jacobian, hessian
+from scipy.differentiate._differentiate import _EERRORINCREASE
+
+
+
+@make_xp_test_case(derivative)
+class TestDerivative:
+
+    def f(self, x):
+        return special.ndtr(x)
+
+    @pytest.mark.parametrize('x', [0.6, np.linspace(-0.05, 1.05, 10)])
+    def test_basic(self, x, xp):
+        # Invert distribution CDF and compare against distribution `ppf`
+        default_dtype = xp.asarray(1.).dtype
+        res = derivative(self.f, xp.asarray(x, dtype=default_dtype))
+        ref = xp.asarray(stats.norm().pdf(x), dtype=default_dtype)
+        xp_assert_close(res.df, ref)
+        # This would be nice, but doesn't always work out. `error` is an
+        # estimate, not a bound.
+        if not is_torch(xp):
+            xp_assert_less(xp.abs(res.df - ref), res.error)
+
+    @pytest.mark.parametrize('case', stats._distr_params.distcont)
+    def test_accuracy(self, case):
+        distname, params = case
+        dist = getattr(stats, distname)(*params)
+        x = dist.median() + 0.1
+        res = derivative(dist.cdf, x)
+        ref = dist.pdf(x)
+        xp_assert_close(res.df, ref, atol=1e-10)
+
+    @pytest.mark.parametrize('order', [1, 6])
+    @pytest.mark.parametrize('shape', [tuple(), (12,), (3, 4), (3, 2, 2)])
+    def test_vectorization(self, order, shape, xp):
+        # Test for correct functionality, output shapes, and dtypes for various
+        # input shapes.
+        x = np.linspace(-0.05, 1.05, 12).reshape(shape) if shape else 0.6
+        n = np.size(x)
+        state = {}
+
+        @np.vectorize
+        def _derivative_single(x):
+            return derivative(self.f, x, order=order)
+
+        def f(x, *args, **kwargs):
+            state['nit'] += 1
+            state['feval'] += 1 if (x.size == n or x.ndim <=1) else x.shape[-1]
+            return self.f(x, *args, **kwargs)
+
+        state['nit'] = -1
+        state['feval'] = 0
+
+        res = derivative(f, xp.asarray(x, dtype=xp.float64), order=order)
+        refs = _derivative_single(x).ravel()
+
+        ref_x = [ref.x for ref in refs]
+        xp_assert_close(xp.reshape(res.x, (-1,)), xp.asarray(ref_x))
+
+        ref_df = [ref.df for ref in refs]
+        xp_assert_close(xp.reshape(res.df, (-1,)), xp.asarray(ref_df))
+
+        ref_error = [ref.error for ref in refs]
+        xp_assert_close(xp.reshape(res.error, (-1,)), xp.asarray(ref_error),
+                        atol=1e-12)
+
+        ref_success = [bool(ref.success) for ref in refs]
+        xp_assert_equal(xp.reshape(res.success, (-1,)), xp.asarray(ref_success))
+
+        ref_flag = [np.int32(ref.status) for ref in refs]
+        xp_assert_equal(xp.reshape(res.status, (-1,)), xp.asarray(ref_flag))
+
+        ref_nfev = [np.int32(ref.nfev) for ref in refs]
+        xp_assert_equal(xp.reshape(res.nfev, (-1,)), xp.asarray(ref_nfev))
+        if is_numpy(xp):  # can't expect other backends to be exactly the same
+            assert xp.max(res.nfev) == state['feval']
+
+        ref_nit = [np.int32(ref.nit) for ref in refs]
+        xp_assert_equal(xp.reshape(res.nit, (-1,)), xp.asarray(ref_nit))
+        if is_numpy(xp):  # can't expect other backends to be exactly the same
+            assert xp.max(res.nit) == state['nit']
+
+    def test_flags(self, xp):
+        # Test cases that should produce different status flags; show that all
+        # can be produced simultaneously.
+        rng = np.random.default_rng(5651219684984213)
+        def f(xs, js):
+            f.nit += 1
+            funcs = [lambda x: x - 2.5,  # converges
+                     lambda x: xp.exp(x)*rng.random(),  # error increases
+                     lambda x: xp.exp(x),  # reaches maxiter due to order=2
+                     lambda x: xp.full_like(x, xp.nan)]  # stops due to NaN
+            res = [funcs[int(j)](x) for x, j in zip(xs, xp.reshape(js, (-1,)))]
+            return xp.stack(res)
+        f.nit = 0
+
+        args = (xp.arange(4, dtype=xp.int64),)
+        res = derivative(f, xp.ones(4, dtype=xp.float64),
+                         tolerances=dict(rtol=1e-14),
+                         order=2, args=args)
+
+        ref_flags = xp.asarray([eim._ECONVERGED,
+                                _EERRORINCREASE,
+                                eim._ECONVERR,
+                                eim._EVALUEERR], dtype=xp.int32)
+        xp_assert_equal(res.status, ref_flags)
+
+    def test_flags_preserve_shape(self, xp):
+        # Same test as above but using `preserve_shape` option to simplify.
+        rng = np.random.default_rng(5651219684984213)
+        def f(x):
+            out = [x - 2.5,  # converges
+                   xp.exp(x)*rng.random(),  # error increases
+                   xp.exp(x),  # reaches maxiter due to order=2
+                   xp.full_like(x, xp.nan)]  # stops due to NaN
+            return xp.stack(out)
+
+        res = derivative(f, xp.asarray(1, dtype=xp.float64),
+                         tolerances=dict(rtol=1e-14),
+                         order=2, preserve_shape=True)
+
+        ref_flags = xp.asarray([eim._ECONVERGED,
+                                _EERRORINCREASE,
+                                eim._ECONVERR,
+                                eim._EVALUEERR], dtype=xp.int32)
+        xp_assert_equal(res.status, ref_flags)
+
+    def test_preserve_shape(self, xp):
+        # Test `preserve_shape` option
+        def f(x):
+            out = [x, xp.sin(3*x), x+xp.sin(10*x), xp.sin(20*x)*(x-1)**2]
+            return xp.stack(out)
+
+        x = xp.asarray(0.)
+        ref = xp.asarray([xp.asarray(1), 3*xp.cos(3*x), 1+10*xp.cos(10*x),
+                          20*xp.cos(20*x)*(x-1)**2 + 2*xp.sin(20*x)*(x-1)])
+        res = derivative(f, x, preserve_shape=True)
+        xp_assert_close(res.df, ref)
+
+    def test_convergence(self, xp):
+        # Test that the convergence tolerances behave as expected
+        x = xp.asarray(1., dtype=xp.float64)
+        f = special.ndtr
+        ref = float(stats.norm.pdf(1.))
+        tolerances0 = dict(atol=0, rtol=0)
+
+        tolerances = tolerances0.copy()
+        tolerances['atol'] = 1e-3
+        res1 = derivative(f, x, tolerances=tolerances, order=4)
+        assert abs(res1.df - ref) < 1e-3
+        tolerances['atol'] = 1e-6
+        res2 = derivative(f, x, tolerances=tolerances, order=4)
+        assert abs(res2.df - ref) < 1e-6
+        assert abs(res2.df - ref) < abs(res1.df - ref)
+
+        tolerances = tolerances0.copy()
+        tolerances['rtol'] = 1e-3
+        res1 = derivative(f, x, tolerances=tolerances, order=4)
+        assert abs(res1.df - ref) < 1e-3 * ref
+        tolerances['rtol'] = 1e-6
+        res2 = derivative(f, x, tolerances=tolerances, order=4)
+        assert abs(res2.df - ref) < 1e-6 * ref
+        assert abs(res2.df - ref) < abs(res1.df - ref)
+
+    def test_step_parameters(self, xp):
+        # Test that step factors have the expected effect on accuracy
+        x = xp.asarray(1., dtype=xp.float64)
+        f = special.ndtr
+        ref = float(stats.norm.pdf(1.))
+
+        res1 = derivative(f, x, initial_step=0.5, maxiter=1)
+        res2 = derivative(f, x, initial_step=0.05, maxiter=1)
+        assert abs(res2.df - ref) < abs(res1.df - ref)
+
+        res1 = derivative(f, x, step_factor=2, maxiter=1)
+        res2 = derivative(f, x, step_factor=20, maxiter=1)
+        assert abs(res2.df - ref) < abs(res1.df - ref)
+
+        # `step_factor` can be less than 1: `initial_step` is the minimum step
+        kwargs = dict(order=4, maxiter=1, step_direction=0)
+        res = derivative(f, x, initial_step=0.5, step_factor=0.5, **kwargs)
+        ref = derivative(f, x, initial_step=1, step_factor=2, **kwargs)
+        xp_assert_close(res.df, ref.df, rtol=5e-15)
+
+        # This is a similar test for one-sided difference
+        kwargs = dict(order=2, maxiter=1, step_direction=1)
+        res = derivative(f, x, initial_step=1, step_factor=2, **kwargs)
+        ref = derivative(f, x, initial_step=1/np.sqrt(2), step_factor=0.5, **kwargs)
+        xp_assert_close(res.df, ref.df, rtol=5e-15)
+
+        kwargs['step_direction'] = -1
+        res = derivative(f, x, initial_step=1, step_factor=2, **kwargs)
+        ref = derivative(f, x, initial_step=1/np.sqrt(2), step_factor=0.5, **kwargs)
+        xp_assert_close(res.df, ref.df, rtol=5e-15)
+
+    def test_step_direction(self, xp):
+        # test that `step_direction` works as expected
+        def f(x):
+            y = xp.exp(x)
+            y = xpx.at(y)[(x < 0) + (x > 2)].set(xp.nan)
+            return y
+
+        x = xp.linspace(0, 2, 10)
+        step_direction = xp.zeros_like(x)
+        step_direction = xpx.at(step_direction)[x < 0.6].set(1)
+        step_direction = xpx.at(step_direction)[x > 1.4].set(-1)
+        res = derivative(f, x, step_direction=step_direction)
+        xp_assert_close(res.df, xp.exp(x))
+        assert xp.all(res.success)
+
+    def test_vectorized_step_direction_args(self, xp):
+        # test that `step_direction` and `args` are vectorized properly
+        def f(x, p):
+            return x ** p
+
+        def df(x, p):
+            return p * x ** (p - 1)
+
+        x = xp.reshape(xp.asarray([1, 2, 3, 4]), (-1, 1, 1))
+        hdir = xp.reshape(xp.asarray([-1, 0, 1]), (1, -1, 1))
+        p = xp.reshape(xp.asarray([2, 3]), (1, 1, -1))
+        res = derivative(f, x, step_direction=hdir, args=(p,))
+        ref = xp.broadcast_to(df(x, p), res.df.shape)
+        ref = xp.asarray(ref, dtype=xp.asarray(1.).dtype)
+        xp_assert_close(res.df, ref)
+
+    def test_initial_step(self, xp):
+        # Test that `initial_step` works as expected and is vectorized
+        def f(x):
+            return xp.exp(x)
+
+        x = xp.asarray(0., dtype=xp.float64)
+        step_direction = xp.asarray([-1, 0, 1])
+        h0 = xp.reshape(xp.logspace(-3, 0, 10), (-1, 1))
+        res = derivative(f, x, initial_step=h0, order=2, maxiter=1,
+                         step_direction=step_direction)
+        err = xp.abs(res.df - f(x))
+
+        # error should be smaller for smaller step sizes
+        assert xp.all(err[:-1, ...] < err[1:, ...])
+
+        # results of vectorized call should match results with
+        # initial_step taken one at a time
+        for i in range(h0.shape[0]):
+            ref = derivative(f, x, initial_step=h0[i, 0], order=2, maxiter=1,
+                             step_direction=step_direction)
+            xp_assert_close(res.df[i, :], ref.df, rtol=5e-13)
+
+    def test_maxiter_callback(self, xp):
+        # Test behavior of `maxiter` parameter and `callback` interface
+        x = xp.asarray(0.612814, dtype=xp.float64)
+        maxiter = 3
+
+        def f(x):
+            res = special.ndtr(x)
+            return res
+
+        default_order = 8
+        res = derivative(f, x, maxiter=maxiter, tolerances=dict(rtol=1e-15))
+        assert not xp.any(res.success)
+        assert xp.all(res.nfev == default_order + 1 + (maxiter - 1)*2)
+        assert xp.all(res.nit == maxiter)
+
+        def callback(res):
+            callback.iter += 1
+            callback.res = res
+            assert hasattr(res, 'x')
+            assert float(res.df) not in callback.dfs
+            callback.dfs.add(float(res.df))
+            assert res.status == eim._EINPROGRESS
+            if callback.iter == maxiter:
+                raise StopIteration
+        callback.iter = -1  # callback called once before first iteration
+        callback.res = None
+        callback.dfs = set()
+
+        res2 = derivative(f, x, callback=callback, tolerances=dict(rtol=1e-15))
+        # terminating with callback is identical to terminating due to maxiter
+        # (except for `status`)
+        for key in res.keys():
+            if key == 'status':
+                assert res[key] == eim._ECONVERR
+                assert res2[key] == eim._ECALLBACK
+            elif key == 'error':
+                # switched from equality check to accommodate
+                # macosx-x86_64/Accelerate
+                xp_assert_close(res2[key], res[key], atol=1e-14)
+                xp_assert_close(callback.res[key], res[key], atol=1e-14)
+            else:
+                assert res2[key] == callback.res[key] == res[key]
+
+    @pytest.mark.parametrize("hdir", (-1, 0, 1))
+    @pytest.mark.parametrize("x", (0.65, [0.65, 0.7]))
+    @pytest.mark.parametrize("dtype", ('float32', 'float64'))
+    def test_dtype(self, hdir, x, dtype, xp):
+        # Test that dtypes are preserved
+        dtype = getattr(xp, dtype)
+        x = xp.asarray(x, dtype=dtype)
+
+        def f(x):
+            assert x.dtype == dtype
+            return xp.exp(x)
+
+        def callback(res):
+            assert res.x.dtype == dtype
+            assert res.df.dtype == dtype
+            assert res.error.dtype == dtype
+
+        res = derivative(f, x, order=4, step_direction=hdir, callback=callback)
+        assert res.x.dtype == dtype
+        assert res.df.dtype == dtype
+        assert res.error.dtype == dtype
+        eps = xp.finfo(dtype).eps
+        # not sure why torch is less accurate here; might be worth investigating
+        rtol = eps**0.5 * 50 if is_torch(xp) else eps**0.5
+        xp_assert_close(res.df, xp.exp(res.x), rtol=rtol)
+
+    def test_input_validation(self, xp):
+        # Test input validation for appropriate error messages
+        one = xp.asarray(1)
+
+        message = '`f` must be callable.'
+        with pytest.raises(ValueError, match=message):
+            derivative(None, one)
+
+        message = 'Abscissae and function output must be real numbers.'
+        with pytest.raises(ValueError, match=message):
+            derivative(lambda x: x, xp.asarray(-4+1j))
+
+        message = "When `preserve_shape=False`, the shape of the array..."
+        with pytest.raises(ValueError, match=message):
+            derivative(lambda x: [1, 2, 3], xp.asarray([-2, -3]))
+
+        message = 'Tolerances and step parameters must be non-negative...'
+        with pytest.raises(ValueError, match=message):
+            derivative(lambda x: x, one, tolerances=dict(atol=-1))
+        with pytest.raises(ValueError, match=message):
+            derivative(lambda x: x, one, tolerances=dict(rtol='ekki'))
+        with pytest.raises(ValueError, match=message):
+            derivative(lambda x: x, one, step_factor=object())
+
+        message = '`maxiter` must be a positive integer.'
+        with pytest.raises(ValueError, match=message):
+            derivative(lambda x: x, one, maxiter=1.5)
+        with pytest.raises(ValueError, match=message):
+            derivative(lambda x: x, one, maxiter=0)
+
+        message = '`order` must be a positive integer'
+        with pytest.raises(ValueError, match=message):
+            derivative(lambda x: x, one, order=1.5)
+        with pytest.raises(ValueError, match=message):
+            derivative(lambda x: x, one, order=0)
+
+        message = '`preserve_shape` must be True or False.'
+        with pytest.raises(ValueError, match=message):
+            derivative(lambda x: x, one, preserve_shape='herring')
+
+        message = '`callback` must be callable.'
+        with pytest.raises(ValueError, match=message):
+            derivative(lambda x: x, one, callback='shrubbery')
+
+    def test_special_cases(self, xp):
+        # Test edge cases and other special cases
+
+        # Test that integers are not passed to `f`
+        # (otherwise this would overflow)
+        def f(x):
+            assert xp.isdtype(x.dtype, 'real floating')
+            return x ** 99 - 1
+
+        if not is_torch(xp):  # torch defaults to float32
+            res = derivative(f, xp.asarray(7), tolerances=dict(rtol=1e-10))
+            assert res.success
+            xp_assert_close(res.df, xp.asarray(99*7.**98))
+
+        # Test invalid step size and direction
+        res = derivative(xp.exp, xp.asarray(1), step_direction=xp.nan)
+        xp_assert_equal(res.df, xp.asarray(xp.nan))
+        xp_assert_equal(res.status, xp.asarray(-3, dtype=xp.int32))
+
+        res = derivative(xp.exp, xp.asarray(1), initial_step=0)
+        xp_assert_equal(res.df, xp.asarray(xp.nan))
+        xp_assert_equal(res.status, xp.asarray(-3, dtype=xp.int32))
+
+        # Test that if success is achieved in the correct number
+        # of iterations if function is a polynomial. Ideally, all polynomials
+        # of order 0-2 would get exact result with 0 refinement iterations,
+        # all polynomials of order 3-4 would be differentiated exactly after
+        # 1 iteration, etc. However, it seems that `derivative` needs an
+        # extra iteration to detect convergence based on the error estimate.
+
+        for n in range(6):
+            x = xp.asarray(1.5, dtype=xp.float64)
+            def f(x):
+                return 2*x**n
+
+            ref = 2*n*x**(n-1)
+
+            res = derivative(f, x, maxiter=1, order=max(1, n))
+            xp_assert_close(res.df, ref, rtol=1e-15)
+            xp_assert_equal(res.error, xp.asarray(xp.nan, dtype=xp.float64))
+
+            res = derivative(f, x, order=max(1, n))
+            assert res.success
+            assert res.nit == 2
+            xp_assert_close(res.df, ref, rtol=1e-15)
+
+        # Test scalar `args` (not in tuple)
+        def f(x, c):
+            return c*x - 1
+
+        res = derivative(f, xp.asarray(2), args=xp.asarray(3))
+        xp_assert_close(res.df, xp.asarray(3.))
+
+    # no need to run a test on multiple backends if it's xfailed
+    @pytest.mark.skip_xp_backends(np_only=True)
+    @pytest.mark.xfail
+    @pytest.mark.parametrize("case", (  # function, evaluation point
+        (lambda x: (x - 1) ** 3, 1),
+        (lambda x: np.where(x > 1, (x - 1) ** 5, (x - 1) ** 3), 1)
+    ))
+    def test_saddle_gh18811(self, case, xp):
+        # With default settings, `derivative` will not always converge when
+        # the true derivative is exactly zero. This tests that specifying a
+        # (tight) `atol` alleviates the problem. See discussion in gh-18811.
+        atol = 1e-16
+        res = derivative(*case, step_direction=[-1, 0, 1], atol=atol)
+        assert np.all(res.success)
+        xp_assert_close(res.df, 0, atol=atol)
+
+    @pytest.mark.parametrize('dtype', ['float32', 'float64'])
+    def test_kwargs(self, xp, dtype):
+        # test that `kwargs` is used, broadcasts correctly, and affects dtype
+        def f(x, c, *, p):
+            return x**p + c*x
+
+        x = xp.asarray(1.23, dtype=xp.float32)
+        c = xp.asarray([1, 2, 3], dtype=xp.float32)
+        p = xp.asarray([2, 3, 4], dtype=getattr(xp, dtype))[:, xp.newaxis]
+        res = derivative(f, x, args=(c,), kwargs={'p': p})
+        ref = p*x**(p-1.) + c
+        xp_assert_close(res.df, ref)
+
+
+class JacobianHessianTest:
+    def test_iv(self, xp):
+        jh_func = self.jh_func.__func__
+
+        # Test input validation
+        message = "Argument `x` must be at least 1-D."
+        with pytest.raises(ValueError, match=message):
+            jh_func(xp.sin, 1, tolerances=dict(atol=-1))
+
+        # Confirm that other parameters are being passed to `derivative`,
+        # which raises an appropriate error message.
+        x = xp.ones(3)
+        func = optimize.rosen
+        message = 'Tolerances and step parameters must be non-negative scalars.'
+        with pytest.raises(ValueError, match=message):
+            jh_func(func, x, tolerances=dict(atol=-1))
+        with pytest.raises(ValueError, match=message):
+            jh_func(func, x, tolerances=dict(rtol=-1))
+        with pytest.raises(ValueError, match=message):
+            jh_func(func, x, step_factor=-1)
+
+        message = '`order` must be a positive integer.'
+        with pytest.raises(ValueError, match=message):
+            jh_func(func, x, order=-1)
+
+        message = '`maxiter` must be a positive integer.'
+        with pytest.raises(ValueError, match=message):
+            jh_func(func, x, maxiter=-1)
+
+
+@make_xp_test_case(jacobian)
+class TestJacobian(JacobianHessianTest):
+    jh_func = jacobian
+
+    # Example functions and Jacobians from Wikipedia:
+    # https://en.wikipedia.org/wiki/Jacobian_matrix_and_determinant#Examples
+
+    def f1(z, xp):
+        x, y = z
+        return xp.stack([x ** 2 * y, 5 * x + xp.sin(y)])
+
+    def df1(z):
+        x, y = z
+        return [[2 * x * y, x ** 2], [np.full_like(x, 5), np.cos(y)]]
+
+    f1.mn = 2, 2  # type: ignore[attr-defined]
+    f1.ref = df1  # type: ignore[attr-defined]
+
+    def f2(z, xp):
+        r, phi = z
+        return xp.stack([r * xp.cos(phi), r * xp.sin(phi)])
+
+    def df2(z):
+        r, phi = z
+        return [[np.cos(phi), -r * np.sin(phi)],
+                [np.sin(phi), r * np.cos(phi)]]
+
+    f2.mn = 2, 2  # type: ignore[attr-defined]
+    f2.ref = df2  # type: ignore[attr-defined]
+
+    def f3(z, xp):
+        r, phi, th = z
+        return xp.stack([r * xp.sin(phi) * xp.cos(th), r * xp.sin(phi) * xp.sin(th),
+                         r * xp.cos(phi)])
+
+    def df3(z):
+        r, phi, th = z
+        return [[np.sin(phi) * np.cos(th), r * np.cos(phi) * np.cos(th),
+                 -r * np.sin(phi) * np.sin(th)],
+                [np.sin(phi) * np.sin(th), r * np.cos(phi) * np.sin(th),
+                 r * np.sin(phi) * np.cos(th)],
+                [np.cos(phi), -r * np.sin(phi), np.zeros_like(r)]]
+
+    f3.mn = 3, 3  # type: ignore[attr-defined]
+    f3.ref = df3  # type: ignore[attr-defined]
+
+    def f4(x, xp):
+        x1, x2, x3 = x
+        return xp.stack([x1, 5 * x3, 4 * x2 ** 2 - 2 * x3, x3 * xp.sin(x1)])
+
+    def df4(x):
+        x1, x2, x3 = x
+        one = np.ones_like(x1)
+        return [[one, 0 * one, 0 * one],
+                [0 * one, 0 * one, 5 * one],
+                [0 * one, 8 * x2, -2 * one],
+                [x3 * np.cos(x1), 0 * one, np.sin(x1)]]
+
+    f4.mn = 3, 4  # type: ignore[attr-defined]
+    f4.ref = df4  # type: ignore[attr-defined]
+
+    def f5(x, xp):
+        x1, x2, x3 = x
+        return xp.stack([5 * x2, 4 * x1 ** 2 - 2 * xp.sin(x2 * x3), x2 * x3])
+
+    def df5(x):
+        x1, x2, x3 = x
+        one = np.ones_like(x1)
+        return [[0 * one, 5 * one, 0 * one],
+                [8 * x1, -2 * x3 * np.cos(x2 * x3), -2 * x2 * np.cos(x2 * x3)],
+                [0 * one, x3, x2]]
+
+    f5.mn = 3, 3  # type: ignore[attr-defined]
+    f5.ref = df5  # type: ignore[attr-defined]
+
+    def rosen(x, _): return optimize.rosen(x)
+    rosen.mn = 5, 1  # type: ignore[attr-defined]
+    rosen.ref = optimize.rosen_der  # type: ignore[attr-defined]
+
+    @pytest.mark.parametrize('dtype', ('float32', 'float64'))
+    @pytest.mark.parametrize('size', [(), (6,), (2, 3)])
+    @pytest.mark.parametrize('func', [f1, f2, f3, f4, f5, rosen])
+    def test_examples(self, dtype, size, func, xp):
+        atol = 1e-10 if dtype == 'float64' else 1.99e-3
+        dtype = getattr(xp, dtype)
+        rng = np.random.default_rng(458912319542)
+        m, n = func.mn
+        x = rng.random(size=(m,) + size)
+        res = jacobian(lambda x: func(x , xp), xp.asarray(x, dtype=dtype))
+        # convert list of arrays to single array before converting to xp array
+        ref = xp.asarray(np.asarray(func.ref(x)), dtype=dtype)
+        xp_assert_close(res.df, ref, atol=atol)
+
+    def test_attrs(self, xp):
+        # Test attributes of result object
+        z = xp.asarray([0.5, 0.25])
+
+        # case in which some elements of the Jacobian are harder
+        # to calculate than others
+        def df1(z):
+            x, y = z
+            return xp.stack([xp.cos(0.5*x) * xp.cos(y), xp.sin(2*x) * y**2])
+
+        def df1_0xy(x, y):
+            return xp.cos(0.5*x) * xp.cos(y)
+
+        def df1_1xy(x, y):
+            return xp.sin(2*x) * y**2
+
+        res = jacobian(df1, z, initial_step=10)
+        # FIXME https://github.com/scipy/scipy/pull/22320#discussion_r1914898175
+        if not is_torch(xp):
+            assert xpx.nunique(res.nit) == 4
+            assert xpx.nunique(res.nfev) == 4
+
+        res00 = jacobian(lambda x: df1_0xy(x, z[1]), z[0:1], initial_step=10)
+        res01 = jacobian(lambda y: df1_0xy(z[0], y), z[1:2], initial_step=10)
+        res10 = jacobian(lambda x: df1_1xy(x, z[1]), z[0:1], initial_step=10)
+        res11 = jacobian(lambda y: df1_1xy(z[0], y), z[1:2], initial_step=10)
+        ref = optimize.OptimizeResult()
+        for attr in ['success', 'status', 'df', 'nit', 'nfev']:
+            ref_attr = xp.asarray([[getattr(res00, attr), getattr(res01, attr)],
+                                   [getattr(res10, attr), getattr(res11, attr)]])
+            ref[attr] = xp.squeeze(
+                ref_attr,
+                axis=tuple(ax for ax, size in enumerate(ref_attr.shape) if size == 1)
+            )
+            rtol = 1.5e-5 if res[attr].dtype == xp.float32 else 1.5e-14
+            xp_assert_close(res[attr], ref[attr], rtol=rtol)
+
+    def test_step_direction_size(self, xp):
+        # Check that `step_direction` and `initial_step` can be used to ensure that
+        # the usable domain of a function is respected.
+        rng = np.random.default_rng(23892589425245)
+        b = rng.random(3)
+        eps = 1e-7  # torch needs wiggle room?
+
+        def f(x):
+            x = xpx.at(x)[0, x[0] < b[0]].set(xp.nan)
+            x = xpx.at(x)[0, x[0] > b[0] + 0.25].set(xp.nan)
+            x = xpx.at(x)[1, x[1] > b[1]].set(xp.nan)
+            x = xpx.at(x)[1, x[1] < b[1] - 0.1-eps].set(xp.nan)
+            return TestJacobian.f5(x, xp)
+
+        dir = [1, -1, 0]
+        h0 = [0.25, 0.1, 0.5]
+        atol = {'atol': 1e-8}
+        res = jacobian(f, xp.asarray(b, dtype=xp.float64), initial_step=h0,
+                       step_direction=dir, tolerances=atol)
+        ref = xp.asarray(TestJacobian.df5(b), dtype=xp.float64)
+        xp_assert_close(res.df, ref, atol=1e-8)
+        assert xp.all(xp.isfinite(ref))
+
+
+@make_xp_test_case(hessian)
+class TestHessian(JacobianHessianTest):
+    jh_func = hessian
+
+    @pytest.mark.parametrize('shape', [(), (4,), (2, 4)])
+    def test_example(self, shape, xp):
+        rng = np.random.default_rng(458912319542)
+        m = 3
+        x = xp.asarray(rng.random((m,) + shape), dtype=xp.float64)
+        res = hessian(optimize.rosen, x)
+        if shape:
+            x = xp.reshape(x, (m, -1))
+            ref = xp.stack([optimize.rosen_hess(xi) for xi in x.T])
+            ref = xp.moveaxis(ref, 0, -1)
+            ref = xp.reshape(ref, (m, m,) + shape)
+        else:
+            ref = optimize.rosen_hess(x)
+        xp_assert_close(res.ddf, ref, atol=1e-8)
+
+        # # Removed symmetry enforcement; consider adding back in as a feature
+        # # check symmetry
+        # for key in ['ddf', 'error', 'nfev', 'success', 'status']:
+        #     assert_equal(res[key], np.swapaxes(res[key], 0, 1))
+
+    def test_float32(self, xp):
+        rng = np.random.default_rng(458912319542)
+        x = xp.asarray(rng.random(3), dtype=xp.float32)
+        res = hessian(optimize.rosen, x)
+        ref = optimize.rosen_hess(x)
+        mask = (ref != 0)
+        xp_assert_close(res.ddf[mask], ref[mask])
+        atol = 1e-2 * xp.abs(xp.min(ref[mask]))
+        xp_assert_close(res.ddf[~mask], ref[~mask], atol=atol)
+
+    def test_nfev(self, xp):
+        z = xp.asarray([0.5, 0.25])
+
+        def f1(z):
+            x, y = xp.broadcast_arrays(*z)
+            f1.nfev = f1.nfev + (math.prod(x.shape[2:]) if x.ndim > 2 else 1)
+            return xp.sin(x) * y ** 3
+        f1.nfev = 0
+
+
+        res = hessian(f1, z, initial_step=10)
+        f1.nfev = 0
+        res00 = hessian(lambda x: f1([x[0], z[1]]), z[0:1], initial_step=10)
+        assert res.nfev[0, 0] == f1.nfev == res00.nfev[0, 0]
+
+        f1.nfev = 0
+        res11 = hessian(lambda y: f1([z[0], y[0]]), z[1:2], initial_step=10)
+        assert res.nfev[1, 1] == f1.nfev == res11.nfev[0, 0]
+
+        # Removed symmetry enforcement; consider adding back in as a feature
+        # assert_equal(res.nfev, res.nfev.T)  # check symmetry
+        # assert np.unique(res.nfev).size == 3
+
+
+    @pytest.mark.skip_xp_backends(np_only=True,
+                                  reason='Python list input uses NumPy backend')
+    def test_small_rtol_warning(self, xp):
+        message = 'The specified `rtol=1e-15`, but...'
+        with pytest.warns(RuntimeWarning, match=message):
+            hessian(xp.sin, [1.], tolerances=dict(rtol=1e-15))
diff --git a/.venv/lib/python3.12/site-packages/scipy/fft/__init__.py b/.venv/lib/python3.12/site-packages/scipy/fft/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..efb1a2955dd882ee57878c86d2e6667f279eff59
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/fft/__init__.py
@@ -0,0 +1,114 @@
+"""
+==============================================
+Discrete Fourier transforms (:mod:`scipy.fft`)
+==============================================
+
+.. currentmodule:: scipy.fft
+
+Fast Fourier Transforms (FFTs)
+==============================
+
+.. autosummary::
+   :toctree: generated/
+
+   fft - Fast (discrete) Fourier Transform (FFT)
+   ifft - Inverse FFT
+   fft2 - 2-D FFT
+   ifft2 - 2-D inverse FFT
+   fftn - N-D FFT
+   ifftn - N-D inverse FFT
+   rfft - FFT of strictly real-valued sequence
+   irfft - Inverse of rfft
+   rfft2 - 2-D FFT of real sequence
+   irfft2 - Inverse of rfft2
+   rfftn - N-D FFT of real sequence
+   irfftn - Inverse of rfftn
+   hfft - FFT of a Hermitian sequence (real spectrum)
+   ihfft - Inverse of hfft
+   hfft2 - 2-D FFT of a Hermitian sequence
+   ihfft2 - Inverse of hfft2
+   hfftn - N-D FFT of a Hermitian sequence
+   ihfftn - Inverse of hfftn
+
+Discrete Sin and Cosine Transforms (DST and DCT)
+================================================
+
+.. autosummary::
+   :toctree: generated/
+
+   dct - Discrete cosine transform
+   idct - Inverse discrete cosine transform
+   dctn - N-D Discrete cosine transform
+   idctn - N-D Inverse discrete cosine transform
+   dst - Discrete sine transform
+   idst - Inverse discrete sine transform
+   dstn - N-D Discrete sine transform
+   idstn - N-D Inverse discrete sine transform
+
+Fast Hankel Transforms
+======================
+
+.. autosummary::
+   :toctree: generated/
+
+   fht - Fast Hankel transform
+   ifht - Inverse of fht
+
+Helper functions
+================
+
+.. autosummary::
+   :toctree: generated/
+
+   fftshift - Shift the zero-frequency component to the center of the spectrum
+   ifftshift - The inverse of `fftshift`
+   fftfreq - Return the Discrete Fourier Transform sample frequencies
+   rfftfreq - DFT sample frequencies (for usage with rfft, irfft)
+   fhtoffset - Compute an optimal offset for the Fast Hankel Transform
+   next_fast_len - Find the optimal length to zero-pad an FFT for speed
+   prev_fast_len - Find the maximum slice length that results in a fast FFT
+   set_workers - Context manager to set default number of workers
+   get_workers - Get the current default number of workers
+
+Backend control
+===============
+
+.. autosummary::
+   :toctree: generated/
+
+   set_backend - Context manager to set the backend within a fixed scope
+   skip_backend - Context manager to skip a backend within a fixed scope
+   set_global_backend - Sets the global fft backend
+   register_backend - Register a backend for permanent use
+
+"""
+
+from ._basic import (
+    fft, ifft, fft2, ifft2, fftn, ifftn,
+    rfft, irfft, rfft2, irfft2, rfftn, irfftn,
+    hfft, ihfft, hfft2, ihfft2, hfftn, ihfftn)
+from ._realtransforms import dct, idct, dst, idst, dctn, idctn, dstn, idstn
+from ._fftlog import fht, ifht, fhtoffset
+from ._helper import (
+    next_fast_len, prev_fast_len, fftfreq,
+    rfftfreq, fftshift, ifftshift)
+from ._backend import (set_backend, skip_backend, set_global_backend,
+                       register_backend)
+from ._duccfft.helper import set_workers, get_workers
+
+__all__ = [
+    'fft', 'ifft', 'fft2', 'ifft2', 'fftn', 'ifftn',
+    'rfft', 'irfft', 'rfft2', 'irfft2', 'rfftn', 'irfftn',
+    'hfft', 'ihfft', 'hfft2', 'ihfft2', 'hfftn', 'ihfftn',
+    'fftfreq', 'rfftfreq', 'fftshift', 'ifftshift',
+    'next_fast_len', 'prev_fast_len',
+    'dct', 'idct', 'dst', 'idst', 'dctn', 'idctn', 'dstn', 'idstn',
+    'fht', 'ifht',
+    'fhtoffset',
+    'set_backend', 'skip_backend', 'set_global_backend', 'register_backend',
+    'get_workers', 'set_workers']
+
+
+from scipy._lib._testutils import PytestTester
+test = PytestTester(__name__)
+del PytestTester
diff --git a/.venv/lib/python3.12/site-packages/scipy/fft/__pycache__/__init__.cpython-312.pyc b/.venv/lib/python3.12/site-packages/scipy/fft/__pycache__/__init__.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..ddbbd2d03436fded8059ac3df92947eb563586de
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/scipy/fft/__pycache__/__init__.cpython-312.pyc differ
diff --git a/.venv/lib/python3.12/site-packages/scipy/fft/__pycache__/_backend.cpython-312.pyc b/.venv/lib/python3.12/site-packages/scipy/fft/__pycache__/_backend.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..c27b014a7bfc72b92652f9d80210ff06a30768d6
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/scipy/fft/__pycache__/_backend.cpython-312.pyc differ
diff --git a/.venv/lib/python3.12/site-packages/scipy/fft/__pycache__/_basic.cpython-312.pyc b/.venv/lib/python3.12/site-packages/scipy/fft/__pycache__/_basic.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..f509c0c1505895c4665f85980f39aa5b4f89fc5b
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/scipy/fft/__pycache__/_basic.cpython-312.pyc differ
diff --git a/.venv/lib/python3.12/site-packages/scipy/fft/__pycache__/_basic_backend.cpython-312.pyc b/.venv/lib/python3.12/site-packages/scipy/fft/__pycache__/_basic_backend.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..57b7557956f54ee2d983461291ec62394e105b0c
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/scipy/fft/__pycache__/_basic_backend.cpython-312.pyc differ
diff --git a/.venv/lib/python3.12/site-packages/scipy/fft/__pycache__/_fftlog.cpython-312.pyc b/.venv/lib/python3.12/site-packages/scipy/fft/__pycache__/_fftlog.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..208bd72a0033142f35d0455b1c28db810b9e2e88
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/scipy/fft/__pycache__/_fftlog.cpython-312.pyc differ
diff --git a/.venv/lib/python3.12/site-packages/scipy/fft/__pycache__/_fftlog_backend.cpython-312.pyc b/.venv/lib/python3.12/site-packages/scipy/fft/__pycache__/_fftlog_backend.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..68d3c063f88f6426f86c6358de803bcde61fe503
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/scipy/fft/__pycache__/_fftlog_backend.cpython-312.pyc differ
diff --git a/.venv/lib/python3.12/site-packages/scipy/fft/__pycache__/_helper.cpython-312.pyc b/.venv/lib/python3.12/site-packages/scipy/fft/__pycache__/_helper.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..6eb53d3c484406cb44855426bd4e282afd353903
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/scipy/fft/__pycache__/_helper.cpython-312.pyc differ
diff --git a/.venv/lib/python3.12/site-packages/scipy/fft/__pycache__/_realtransforms.cpython-312.pyc b/.venv/lib/python3.12/site-packages/scipy/fft/__pycache__/_realtransforms.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..bb3e6a075638a7373ff3e03c2bf133876e0efa02
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/scipy/fft/__pycache__/_realtransforms.cpython-312.pyc differ
diff --git a/.venv/lib/python3.12/site-packages/scipy/fft/__pycache__/_realtransforms_backend.cpython-312.pyc b/.venv/lib/python3.12/site-packages/scipy/fft/__pycache__/_realtransforms_backend.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..7877ab90ed7ecddeddd689c85ea1ba48e3b36676
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/scipy/fft/__pycache__/_realtransforms_backend.cpython-312.pyc differ
diff --git a/.venv/lib/python3.12/site-packages/scipy/fft/_backend.py b/.venv/lib/python3.12/site-packages/scipy/fft/_backend.py
new file mode 100644
index 0000000000000000000000000000000000000000..59c80ce83d8eb143e44b142176e7da7e4bf7b175
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/fft/_backend.py
@@ -0,0 +1,211 @@
+import scipy._lib.uarray as ua
+from scipy._lib._array_api import xp_capabilities
+from . import _basic_backend
+from . import _realtransforms_backend
+from . import _fftlog_backend
+
+
+class _ScipyBackend:
+    """The default backend for fft calculations
+
+    Notes
+    -----
+    We use the domain ``numpy.scipy`` rather than ``scipy`` because ``uarray``
+    treats the domain as a hierarchy. This means the user can install a single
+    backend for ``numpy`` and have it implement ``numpy.scipy.fft`` as well.
+    """
+    __ua_domain__ = "numpy.scipy.fft"
+
+    @staticmethod
+    def __ua_function__(method, args, kwargs):
+
+        fn = getattr(_basic_backend, method.__name__, None)
+        if fn is None:
+            fn = getattr(_realtransforms_backend, method.__name__, None)
+        if fn is None:
+            fn = getattr(_fftlog_backend, method.__name__, None)
+        if fn is None:
+            return NotImplemented
+        return fn(*args, **kwargs)
+
+
+_named_backends = {
+    'scipy': _ScipyBackend,
+}
+
+
+def _backend_from_arg(backend):
+    """Maps strings to known backends and validates the backend"""
+
+    if isinstance(backend, str):
+        try:
+            backend = _named_backends[backend]
+        except KeyError as e:
+            raise ValueError(f'Unknown backend {backend}') from e
+
+    if backend.__ua_domain__ != 'numpy.scipy.fft':
+        raise ValueError('Backend does not implement "numpy.scipy.fft"')
+
+    return backend
+
+
+@xp_capabilities(out_of_scope=True)
+def set_global_backend(backend, coerce=False, only=False, try_last=False):
+    """Sets the global fft backend.
+
+    This utility method replaces the default backend for permanent use. It
+    will be tried in the list of backends automatically, unless the
+    ``only`` flag is set on a backend. This will be the first tried
+    backend outside the :obj:`set_backend` context manager.
+
+    Parameters
+    ----------
+    backend : {object, 'scipy'}
+        The backend to use.
+        Can either be a ``str`` containing the name of a known backend
+        {'scipy'} or an object that implements the uarray protocol.
+    coerce : bool
+        Whether to coerce input types when trying this backend.
+    only : bool
+        If ``True``, no more backends will be tried if this fails.
+        Implied by ``coerce=True``.
+    try_last : bool
+        If ``True``, the global backend is tried after registered backends.
+
+    Raises
+    ------
+    ValueError: If the backend does not implement ``numpy.scipy.fft``.
+
+    Notes
+    -----
+    This will overwrite the previously set global backend, which, by default, is
+    the SciPy implementation.
+
+    Examples
+    --------
+    We can set the global fft backend:
+
+    >>> from scipy.fft import fft, set_global_backend
+    >>> set_global_backend("scipy")  # Sets global backend (default is "scipy").
+    >>> fft([1])  # Calls the global backend
+    array([1.+0.j])
+    """
+    backend = _backend_from_arg(backend)
+    ua.set_global_backend(backend, coerce=coerce, only=only, try_last=try_last)
+
+
+@xp_capabilities(out_of_scope=True)
+def register_backend(backend):
+    """
+    Register a backend for permanent use.
+
+    Registered backends have the lowest priority and will be tried after the
+    global backend.
+
+    Parameters
+    ----------
+    backend : {object, 'scipy'}
+        The backend to use.
+        Can either be a ``str`` containing the name of a known backend
+        {'scipy'} or an object that implements the uarray protocol.
+
+    Raises
+    ------
+    ValueError: If the backend does not implement ``numpy.scipy.fft``.
+
+    Examples
+    --------
+    We can register a new fft backend:
+
+    >>> from scipy.fft import fft, register_backend, set_global_backend
+    >>> class NoopBackend:  # Define an invalid Backend
+    ...     __ua_domain__ = "numpy.scipy.fft"
+    ...     def __ua_function__(self, func, args, kwargs):
+    ...          return NotImplemented
+    >>> set_global_backend(NoopBackend())  # Set the invalid backend as global
+    >>> register_backend("scipy")  # Register a new backend
+    # The registered backend is called because
+    # the global backend returns `NotImplemented`
+    >>> fft([1])
+    array([1.+0.j])
+    >>> set_global_backend("scipy")  # Restore global backend to default
+
+    """
+    backend = _backend_from_arg(backend)
+    ua.register_backend(backend)
+
+
+@xp_capabilities(out_of_scope=True)
+def set_backend(backend, coerce=False, only=False):
+    """Context manager to set the backend within a fixed scope.
+
+    Upon entering the ``with`` statement, the given backend will be added to
+    the list of available backends with the highest priority. Upon exit, the
+    backend is reset to the state before entering the scope.
+
+    Parameters
+    ----------
+    backend : {object, 'scipy'}
+        The backend to use.
+        Can either be a ``str`` containing the name of a known backend
+        {'scipy'} or an object that implements the uarray protocol.
+    coerce : bool, optional
+        Whether to allow expensive conversions for the ``x`` parameter. e.g.,
+        copying a NumPy array to the GPU for a CuPy backend. Implies ``only``.
+    only : bool, optional
+        If only is ``True`` and this backend returns ``NotImplemented``, then a
+        BackendNotImplemented error will be raised immediately. Ignoring any
+        lower priority backends.
+
+    Returns
+    -------
+    context : uarray._SetBackendContext
+        Context manager that sets the backend.
+
+    Examples
+    --------
+    >>> import scipy.fft as fft
+    >>> with fft.set_backend('scipy', only=True):
+    ...     fft.fft([1])  # Always calls the scipy implementation
+    array([1.+0.j])
+    """
+    backend = _backend_from_arg(backend)
+    return ua.set_backend(backend, coerce=coerce, only=only)
+
+
+@xp_capabilities(out_of_scope=True)
+def skip_backend(backend):
+    """Context manager to skip a backend within a fixed scope.
+
+    Within the context of a ``with`` statement, the given backend will not be
+    called. This covers backends registered both locally and globally. Upon
+    exit, the backend will again be considered.
+
+    Parameters
+    ----------
+    backend : {object, 'scipy'}
+        The backend to skip.
+        Can either be a ``str`` containing the name of a known backend
+        {'scipy'} or an object that implements the uarray protocol.
+
+    Returns
+    -------
+    context : uarray._SetBackendContext
+        Context manager that skips the backend.
+
+    Examples
+    --------
+    >>> import scipy.fft as fft
+    >>> fft.fft([1])  # Calls default SciPy backend
+    array([1.+0.j])
+    >>> with fft.skip_backend('scipy'):  # We explicitly skip the SciPy backend
+    ...     fft.fft([1])                 # leaving no implementation available
+    Traceback (most recent call last):
+        ...
+    BackendNotImplementedError: No selected backends had an implementation ...
+    """
+    backend = _backend_from_arg(backend)
+    return ua.skip_backend(backend)
+
+
+set_global_backend('scipy', try_last=True)
diff --git a/.venv/lib/python3.12/site-packages/scipy/fft/_basic.py b/.venv/lib/python3.12/site-packages/scipy/fft/_basic.py
new file mode 100644
index 0000000000000000000000000000000000000000..12ebf012089f95254d1f64bfe8fe80a310bb21f8
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/fft/_basic.py
@@ -0,0 +1,1670 @@
+from scipy._lib.uarray import generate_multimethod, Dispatchable
+from scipy._lib._array_api import xp_capabilities
+
+import numpy as np
+
+
+def _x_replacer(args, kwargs, dispatchables):
+    """
+    uarray argument replacer to replace the transform input array (``x``)
+    """
+    if len(args) > 0:
+        return (dispatchables[0],) + args[1:], kwargs
+    kw = kwargs.copy()
+    kw['x'] = dispatchables[0]
+    return args, kw
+
+
+def _dispatch(func):
+    """
+    Function annotation that creates a uarray multimethod from the function
+    """
+    return generate_multimethod(func, _x_replacer, domain="numpy.scipy.fft")
+
+
+@xp_capabilities(allow_dask_compute=True)
+@_dispatch
+def fft(x, n=None, axis=-1, norm=None, overwrite_x=False, workers=None, *,
+        plan=None):
+    """
+    Compute the 1-D discrete Fourier Transform.
+
+    This function computes the 1-D *n*-point discrete Fourier
+    Transform (DFT) with the efficient Fast Fourier Transform (FFT)
+    algorithm [1]_.
+
+    Parameters
+    ----------
+    x : array_like
+        Input array, can be complex.
+    n : int, optional
+        Length of the transformed axis of the output.
+        If `n` is smaller than the length of the input, the input is cropped.
+        If it is larger, the input is padded with zeros. If `n` is not given,
+        the length of the input along the axis specified by `axis` is used.
+    axis : int, optional
+        Axis over which to compute the FFT. If not given, the last axis is
+        used.
+    norm : {"backward", "ortho", "forward"}, optional
+        Normalization mode. Default is "backward", meaning no normalization on
+        the forward transforms and scaling by ``1/n`` on the `ifft`.
+        "forward" instead applies the ``1/n`` factor on the forward transform.
+        For ``norm="ortho"``, both directions are scaled by ``1/sqrt(n)``.
+
+        .. versionadded:: 1.6.0
+           ``norm={"forward", "backward"}`` options were added
+
+    overwrite_x : bool, optional
+        If True, the contents of `x` can be destroyed; the default is False.
+        See the notes below for more details.
+    workers : int, optional
+        Maximum number of workers to use for parallel computation. If negative,
+        the value wraps around from ``os.cpu_count()``. See below for more
+        details.
+    plan : object, optional
+        This argument is reserved for passing in a precomputed plan provided
+        by downstream FFT vendors. It is currently not used in SciPy.
+
+        .. versionadded:: 1.5.0
+
+    Returns
+    -------
+    out : complex ndarray
+        The truncated or zero-padded input, transformed along the axis
+        indicated by `axis`, or the last one if `axis` is not specified.
+
+    Raises
+    ------
+    IndexError
+        if `axes` is larger than the last axis of `x`.
+
+    See Also
+    --------
+    ifft : The inverse of `fft`.
+    fft2 : The 2-D FFT.
+    fftn : The N-D FFT.
+    rfftn : The N-D FFT of real input.
+    fftfreq : Frequency bins for given FFT parameters.
+    next_fast_len : Size to pad input to for most efficient transforms
+
+    Notes
+    -----
+    FFT (Fast Fourier Transform) refers to a way the discrete Fourier Transform
+    (DFT) can be calculated efficiently, by using symmetries in the calculated
+    terms. The symmetry is highest when `n` is a power of 2, and the transform
+    is therefore most efficient for these sizes. For poorly factorizable sizes,
+    `scipy.fft` uses Bluestein's algorithm [2]_ and so is never worse than
+    O(`n` log `n`). Further performance improvements may be seen by zero-padding
+    the input using `next_fast_len`.
+
+    If ``x`` is a 1d array, then the `fft` is equivalent to ::
+
+        y[k] = np.sum(x * np.exp(-2j * np.pi * k * np.arange(n)/n))
+
+    The frequency term ``f=k/n`` is found at ``y[k]``. At ``y[n/2]`` we reach
+    the Nyquist frequency and wrap around to the negative-frequency terms. So,
+    for an 8-point transform, the frequencies of the result are
+    [0, 1, 2, 3, -4, -3, -2, -1]. To rearrange the fft output so that the
+    zero-frequency component is centered, like [-4, -3, -2, -1, 0, 1, 2, 3],
+    use `fftshift`.
+
+    Transforms can be done in single, double, or extended precision (long
+    double) floating point. Half precision inputs will be converted to single
+    precision and non-floating-point inputs will be converted to double
+    precision.
+
+    If the data type of ``x`` is real, a "real FFT" algorithm is automatically
+    used, which roughly halves the computation time. To increase efficiency
+    a little further, use `rfft`, which does the same calculation, but only
+    outputs half of the symmetrical spectrum. If the data are both real and
+    symmetrical, the `dct` can again double the efficiency, by generating
+    half of the spectrum from half of the signal.
+
+    When ``overwrite_x=True`` is specified, the memory referenced by ``x`` may
+    be used by the implementation in any way. This may include reusing the
+    memory for the result, but this is in no way guaranteed. You should not
+    rely on the contents of ``x`` after the transform as this may change in
+    future without warning.
+
+    The ``workers`` argument specifies the maximum number of parallel jobs to
+    split the FFT computation into. This will execute independent 1-D
+    FFTs within ``x``. So, ``x`` must be at least 2-D and the
+    non-transformed axes must be large enough to split into chunks. If ``x`` is
+    too small, fewer jobs may be used than requested.
+
+    References
+    ----------
+    .. [1] Cooley, James W., and John W. Tukey, 1965, "An algorithm for the
+           machine calculation of complex Fourier series," *Math. Comput.*
+           19: 297-301.
+    .. [2] Bluestein, L., 1970, "A linear filtering approach to the
+           computation of discrete Fourier transform". *IEEE Transactions on
+           Audio and Electroacoustics.* 18 (4): 451-455.
+
+    Examples
+    --------
+    >>> import scipy.fft
+    >>> import numpy as np
+    >>> scipy.fft.fft(np.exp(2j * np.pi * np.arange(8) / 8))
+    array([-2.33486982e-16+1.14423775e-17j,  8.00000000e+00-1.25557246e-15j,
+            2.33486982e-16+2.33486982e-16j,  0.00000000e+00+1.22464680e-16j,
+           -1.14423775e-17+2.33486982e-16j,  0.00000000e+00+5.20784380e-16j,
+            1.14423775e-17+1.14423775e-17j,  0.00000000e+00+1.22464680e-16j])
+
+    In this example, real input has an FFT which is Hermitian, i.e., symmetric
+    in the real part and anti-symmetric in the imaginary part:
+
+    >>> from scipy.fft import fft, fftfreq, fftshift
+    >>> import matplotlib.pyplot as plt
+    >>> t = np.arange(256)
+    >>> sp = fftshift(fft(np.sin(t)))
+    >>> freq = fftshift(fftfreq(t.shape[-1]))
+    >>> plt.plot(freq, sp.real, freq, sp.imag)
+    [,
+     ]
+    >>> plt.show()
+
+    """
+    return (Dispatchable(x, np.ndarray),)
+
+
+@xp_capabilities(allow_dask_compute=True)
+@_dispatch
+def ifft(x, n=None, axis=-1, norm=None, overwrite_x=False, workers=None, *,
+         plan=None):
+    """
+    Compute the 1-D inverse discrete Fourier Transform.
+
+    This function computes the inverse of the 1-D *n*-point
+    discrete Fourier transform computed by `fft`.  In other words,
+    ``ifft(fft(x)) == x`` to within numerical accuracy.
+
+    The input should be ordered in the same way as is returned by `fft`,
+    i.e.,
+
+    * ``x[0]`` should contain the zero frequency term,
+    * ``x[1:n//2]`` should contain the positive-frequency terms,
+    * ``x[n//2 + 1:]`` should contain the negative-frequency terms, in
+      increasing order starting from the most negative frequency.
+
+    For an even number of input points, ``x[n//2]`` represents the sum of
+    the values at the positive and negative Nyquist frequencies, as the two
+    are aliased together. See `fft` for details.
+
+    Parameters
+    ----------
+    x : array_like
+        Input array, can be complex.
+    n : int, optional
+        Length of the transformed axis of the output.
+        If `n` is smaller than the length of the input, the input is cropped.
+        If it is larger, the input is padded with zeros. If `n` is not given,
+        the length of the input along the axis specified by `axis` is used.
+        See notes about padding issues.
+    axis : int, optional
+        Axis over which to compute the inverse DFT. If not given, the last
+        axis is used.
+    norm : {"backward", "ortho", "forward"}, optional
+        Normalization mode (see `fft`). Default is "backward".
+    overwrite_x : bool, optional
+        If True, the contents of `x` can be destroyed; the default is False.
+        See :func:`fft` for more details.
+    workers : int, optional
+        Maximum number of workers to use for parallel computation. If negative,
+        the value wraps around from ``os.cpu_count()``.
+        See :func:`~scipy.fft.fft` for more details.
+    plan : object, optional
+        This argument is reserved for passing in a precomputed plan provided
+        by downstream FFT vendors. It is currently not used in SciPy.
+
+        .. versionadded:: 1.5.0
+
+    Returns
+    -------
+    out : complex ndarray
+        The truncated or zero-padded input, transformed along the axis
+        indicated by `axis`, or the last one if `axis` is not specified.
+
+    Raises
+    ------
+    IndexError
+        If `axes` is larger than the last axis of `x`.
+
+    See Also
+    --------
+    fft : The 1-D (forward) FFT, of which `ifft` is the inverse.
+    ifft2 : The 2-D inverse FFT.
+    ifftn : The N-D inverse FFT.
+
+    Notes
+    -----
+    If the input parameter `n` is larger than the size of the input, the input
+    is padded by appending zeros at the end. Even though this is the common
+    approach, it might lead to surprising results. If a different padding is
+    desired, it must be performed before calling `ifft`.
+
+    If ``x`` is a 1-D array, then the `ifft` is equivalent to ::
+
+        y[k] = np.sum(x * np.exp(2j * np.pi * k * np.arange(n)/n)) / len(x)
+
+    As with `fft`, `ifft` has support for all floating point types and is
+    optimized for real input.
+
+    Examples
+    --------
+    >>> import scipy.fft
+    >>> import numpy as np
+    >>> scipy.fft.ifft([0, 4, 0, 0])
+    array([ 1.+0.j,  0.+1.j, -1.+0.j,  0.-1.j]) # may vary
+
+    Create and plot a band-limited signal with random phases:
+
+    >>> import matplotlib.pyplot as plt
+    >>> rng = np.random.default_rng()
+    >>> t = np.arange(400)
+    >>> n = np.zeros((400,), dtype=complex)
+    >>> n[40:60] = np.exp(1j*rng.uniform(0, 2*np.pi, (20,)))
+    >>> s = scipy.fft.ifft(n)
+    >>> plt.plot(t, s.real, 'b-', t, s.imag, 'r--')
+    [, ]
+    >>> plt.legend(('real', 'imaginary'))
+    
+    >>> plt.show()
+
+    """
+    return (Dispatchable(x, np.ndarray),)
+
+
+@xp_capabilities(allow_dask_compute=True)
+@_dispatch
+def rfft(x, n=None, axis=-1, norm=None, overwrite_x=False, workers=None, *,
+         plan=None):
+    """
+    Compute the 1-D discrete Fourier Transform for real input.
+
+    This function computes the 1-D *n*-point discrete Fourier
+    Transform (DFT) of a real-valued array by means of an efficient algorithm
+    called the Fast Fourier Transform (FFT).
+
+    Parameters
+    ----------
+    x : array_like
+        Input array
+    n : int, optional
+        Number of points along transformation axis in the input to use.
+        If `n` is smaller than the length of the input, the input is cropped.
+        If it is larger, the input is padded with zeros. If `n` is not given,
+        the length of the input along the axis specified by `axis` is used.
+    axis : int, optional
+        Axis over which to compute the FFT. If not given, the last axis is
+        used.
+    norm : {"backward", "ortho", "forward"}, optional
+        Normalization mode (see `fft`). Default is "backward".
+    overwrite_x : bool, optional
+        If True, the contents of `x` can be destroyed; the default is False.
+        See :func:`fft` for more details.
+    workers : int, optional
+        Maximum number of workers to use for parallel computation. If negative,
+        the value wraps around from ``os.cpu_count()``.
+        See :func:`~scipy.fft.fft` for more details.
+    plan : object, optional
+        This argument is reserved for passing in a precomputed plan provided
+        by downstream FFT vendors. It is currently not used in SciPy.
+
+        .. versionadded:: 1.5.0
+
+    Returns
+    -------
+    out : complex ndarray
+        The truncated or zero-padded input, transformed along the axis
+        indicated by `axis`, or the last one if `axis` is not specified.
+        If `n` is even, the length of the transformed axis is ``(n/2)+1``.
+        If `n` is odd, the length is ``(n+1)/2``.
+
+    Raises
+    ------
+    IndexError
+        If `axis` is larger than the last axis of `a`.
+
+    See Also
+    --------
+    irfft : The inverse of `rfft`.
+    fft : The 1-D FFT of general (complex) input.
+    fftn : The N-D FFT.
+    rfft2 : The 2-D FFT of real input.
+    rfftn : The N-D FFT of real input.
+
+    Notes
+    -----
+    When the DFT is computed for purely real input, the output is
+    Hermitian-symmetric, i.e., the negative frequency terms are just the complex
+    conjugates of the corresponding positive-frequency terms, and the
+    negative-frequency terms are therefore redundant. This function does not
+    compute the negative frequency terms, and the length of the transformed
+    axis of the output is therefore ``n//2 + 1``.
+
+    When ``X = rfft(x)`` and fs is the sampling frequency, ``X[0]`` contains
+    the zero-frequency term 0*fs, which is real due to Hermitian symmetry.
+
+    If `n` is even, ``A[-1]`` contains the term representing both positive
+    and negative Nyquist frequency (+fs/2 and -fs/2), and must also be purely
+    real. If `n` is odd, there is no term at fs/2; ``A[-1]`` contains
+    the largest positive frequency (fs/2*(n-1)/n), and is complex in the
+    general case.
+
+    If the input `a` contains an imaginary part, it is silently discarded.
+
+    Examples
+    --------
+    >>> import scipy.fft
+    >>> scipy.fft.fft([0, 1, 0, 0])
+    array([ 1.+0.j,  0.-1.j, -1.+0.j,  0.+1.j]) # may vary
+    >>> scipy.fft.rfft([0, 1, 0, 0])
+    array([ 1.+0.j,  0.-1.j, -1.+0.j]) # may vary
+
+    Notice how the final element of the `fft` output is the complex conjugate
+    of the second element, for real input. For `rfft`, this symmetry is
+    exploited to compute only the non-negative frequency terms.
+
+    """
+    return (Dispatchable(x, np.ndarray),)
+
+
+@xp_capabilities(allow_dask_compute=True)
+@_dispatch
+def irfft(x, n=None, axis=-1, norm=None, overwrite_x=False, workers=None, *,
+          plan=None):
+    """
+    Computes the inverse of `rfft`.
+
+    This function computes the inverse of the 1-D *n*-point
+    discrete Fourier Transform of real input computed by `rfft`.
+    In other words, ``irfft(rfft(x), len(x)) == x`` to within numerical
+    accuracy. (See Notes below for why ``len(a)`` is necessary here.)
+
+    The input is expected to be in the form returned by `rfft`, i.e., the
+    real zero-frequency term followed by the complex positive frequency terms
+    in order of increasing frequency. Since the discrete Fourier Transform of
+    real input is Hermitian-symmetric, the negative frequency terms are taken
+    to be the complex conjugates of the corresponding positive frequency terms.
+
+    Parameters
+    ----------
+    x : array_like
+        The input array.
+    n : int, optional
+        Length of the transformed axis of the output.
+        For `n` output points, ``n//2+1`` input points are necessary. If the
+        input is longer than this, it is cropped. If it is shorter than this,
+        it is padded with zeros. If `n` is not given, it is taken to be
+        ``2*(m-1)``, where ``m`` is the length of the input along the axis
+        specified by `axis`.
+    axis : int, optional
+        Axis over which to compute the inverse FFT. If not given, the last
+        axis is used.
+    norm : {"backward", "ortho", "forward"}, optional
+        Normalization mode (see `fft`). Default is "backward".
+    overwrite_x : bool, optional
+        If True, the contents of `x` can be destroyed; the default is False.
+        See :func:`fft` for more details.
+    workers : int, optional
+        Maximum number of workers to use for parallel computation. If negative,
+        the value wraps around from ``os.cpu_count()``.
+        See :func:`~scipy.fft.fft` for more details.
+    plan : object, optional
+        This argument is reserved for passing in a precomputed plan provided
+        by downstream FFT vendors. It is currently not used in SciPy.
+
+        .. versionadded:: 1.5.0
+
+    Returns
+    -------
+    out : ndarray
+        The truncated or zero-padded input, transformed along the axis
+        indicated by `axis`, or the last one if `axis` is not specified.
+        The length of the transformed axis is `n`, or, if `n` is not given,
+        ``2*(m-1)`` where ``m`` is the length of the transformed axis of the
+        input. To get an odd number of output points, `n` must be specified.
+
+    Raises
+    ------
+    IndexError
+        If `axis` is larger than the last axis of `x`.
+
+    See Also
+    --------
+    rfft : The 1-D FFT of real input, of which `irfft` is inverse.
+    fft : The 1-D FFT.
+    irfft2 : The inverse of the 2-D FFT of real input.
+    irfftn : The inverse of the N-D FFT of real input.
+
+    Notes
+    -----
+    Returns the real valued `n`-point inverse discrete Fourier transform
+    of `x`, where `x` contains the non-negative frequency terms of a
+    Hermitian-symmetric sequence. `n` is the length of the result, not the
+    input.
+
+    If you specify an `n` such that `a` must be zero-padded or truncated, the
+    extra/removed values will be added/removed at high frequencies. One can
+    thus resample a series to `m` points via Fourier interpolation by:
+    ``a_resamp = irfft(rfft(a), m)``.
+
+    The default value of `n` assumes an even output length. By the Hermitian
+    symmetry, the last imaginary component must be 0 and so is ignored. To
+    avoid losing information, the correct length of the real input *must* be
+    given.
+
+    Examples
+    --------
+    >>> import scipy.fft
+    >>> scipy.fft.ifft([1, -1j, -1, 1j])
+    array([0.+0.j,  1.+0.j,  0.+0.j,  0.+0.j]) # may vary
+    >>> scipy.fft.irfft([1, -1j, -1])
+    array([0.,  1.,  0.,  0.])
+
+    Notice how the last term in the input to the ordinary `ifft` is the
+    complex conjugate of the second term, and the output has zero imaginary
+    part everywhere. When calling `irfft`, the negative frequencies are not
+    specified, and the output array is purely real.
+
+    """
+    return (Dispatchable(x, np.ndarray),)
+
+
+@xp_capabilities(allow_dask_compute=True)
+@_dispatch
+def hfft(x, n=None, axis=-1, norm=None, overwrite_x=False, workers=None, *,
+         plan=None):
+    """
+    Compute the FFT of a signal that has Hermitian symmetry, i.e., a real
+    spectrum.
+
+    Parameters
+    ----------
+    x : array_like
+        The input array.
+    n : int, optional
+        Length of the transformed axis of the output. For `n` output
+        points, ``n//2 + 1`` input points are necessary. If the input is
+        longer than this, it is cropped. If it is shorter than this, it is
+        padded with zeros. If `n` is not given, it is taken to be ``2*(m-1)``,
+        where ``m`` is the length of the input along the axis specified by
+        `axis`.
+    axis : int, optional
+        Axis over which to compute the FFT. If not given, the last
+        axis is used.
+    norm : {"backward", "ortho", "forward"}, optional
+        Normalization mode (see `fft`). Default is "backward".
+    overwrite_x : bool, optional
+        If True, the contents of `x` can be destroyed; the default is False.
+        See `fft` for more details.
+    workers : int, optional
+        Maximum number of workers to use for parallel computation. If negative,
+        the value wraps around from ``os.cpu_count()``.
+        See :func:`~scipy.fft.fft` for more details.
+    plan : object, optional
+        This argument is reserved for passing in a precomputed plan provided
+        by downstream FFT vendors. It is currently not used in SciPy.
+
+        .. versionadded:: 1.5.0
+
+    Returns
+    -------
+    out : ndarray
+        The truncated or zero-padded input, transformed along the axis
+        indicated by `axis`, or the last one if `axis` is not specified.
+        The length of the transformed axis is `n`, or, if `n` is not given,
+        ``2*m - 2``, where ``m`` is the length of the transformed axis of
+        the input. To get an odd number of output points, `n` must be
+        specified, for instance, as ``2*m - 1`` in the typical case,
+
+    Raises
+    ------
+    IndexError
+        If `axis` is larger than the last axis of `a`.
+
+    See Also
+    --------
+    rfft : Compute the 1-D FFT for real input.
+    ihfft : The inverse of `hfft`.
+    hfftn : Compute the N-D FFT of a Hermitian signal.
+
+    Notes
+    -----
+    `hfft`/`ihfft` are a pair analogous to `rfft`/`irfft`, but for the
+    opposite case: here the signal has Hermitian symmetry in the time
+    domain and is real in the frequency domain. So, here, it's `hfft`, for
+    which you must supply the length of the result if it is to be odd.
+    * even: ``ihfft(hfft(a, 2*len(a) - 2) == a``, within roundoff error,
+    * odd: ``ihfft(hfft(a, 2*len(a) - 1) == a``, within roundoff error.
+
+    Examples
+    --------
+    >>> from scipy.fft import fft, hfft
+    >>> import numpy as np
+    >>> a = 2 * np.pi * np.arange(10) / 10
+    >>> signal = np.cos(a) + 3j * np.sin(3 * a)
+    >>> fft(signal).round(10)
+    array([ -0.+0.j,   5.+0.j,  -0.+0.j,  15.-0.j,   0.+0.j,   0.+0.j,
+            -0.+0.j, -15.-0.j,   0.+0.j,   5.+0.j])
+    >>> hfft(signal[:6]).round(10) # Input first half of signal
+    array([  0.,   5.,   0.,  15.,  -0.,   0.,   0., -15.,  -0.,   5.])
+    >>> hfft(signal, 10)  # Input entire signal and truncate
+    array([  0.,   5.,   0.,  15.,  -0.,   0.,   0., -15.,  -0.,   5.])
+    """
+    return (Dispatchable(x, np.ndarray),)
+
+
+@xp_capabilities(allow_dask_compute=True)
+@_dispatch
+def ihfft(x, n=None, axis=-1, norm=None, overwrite_x=False, workers=None, *,
+          plan=None):
+    """
+    Compute the inverse FFT of a signal that has Hermitian symmetry.
+
+    Parameters
+    ----------
+    x : array_like
+        Input array.
+    n : int, optional
+        Length of the inverse FFT, the number of points along
+        transformation axis in the input to use.  If `n` is smaller than
+        the length of the input, the input is cropped. If it is larger,
+        the input is padded with zeros. If `n` is not given, the length of
+        the input along the axis specified by `axis` is used.
+    axis : int, optional
+        Axis over which to compute the inverse FFT. If not given, the last
+        axis is used.
+    norm : {"backward", "ortho", "forward"}, optional
+        Normalization mode (see `fft`). Default is "backward".
+    overwrite_x : bool, optional
+        If True, the contents of `x` can be destroyed; the default is False.
+        See `fft` for more details.
+    workers : int, optional
+        Maximum number of workers to use for parallel computation. If negative,
+        the value wraps around from ``os.cpu_count()``.
+        See :func:`~scipy.fft.fft` for more details.
+    plan : object, optional
+        This argument is reserved for passing in a precomputed plan provided
+        by downstream FFT vendors. It is currently not used in SciPy.
+
+        .. versionadded:: 1.5.0
+
+    Returns
+    -------
+    out : complex ndarray
+        The truncated or zero-padded input, transformed along the axis
+        indicated by `axis`, or the last one if `axis` is not specified.
+        The length of the transformed axis is ``n//2 + 1``.
+
+    See Also
+    --------
+    hfft, irfft
+
+    Notes
+    -----
+    `hfft`/`ihfft` are a pair analogous to `rfft`/`irfft`, but for the
+    opposite case: here, the signal has Hermitian symmetry in the time
+    domain and is real in the frequency domain. So, here, it's `hfft`, for
+    which you must supply the length of the result if it is to be odd:
+    * even: ``ihfft(hfft(a, 2*len(a) - 2) == a``, within roundoff error,
+    * odd: ``ihfft(hfft(a, 2*len(a) - 1) == a``, within roundoff error.
+
+    Examples
+    --------
+    >>> from scipy.fft import ifft, ihfft
+    >>> import numpy as np
+    >>> spectrum = np.array([ 15, -4, 0, -1, 0, -4])
+    >>> ifft(spectrum)
+    array([1.+0.j,  2.+0.j,  3.+0.j,  4.+0.j,  3.+0.j,  2.+0.j]) # may vary
+    >>> ihfft(spectrum)
+    array([ 1.-0.j,  2.-0.j,  3.-0.j,  4.-0.j]) # may vary
+    """
+    return (Dispatchable(x, np.ndarray),)
+
+
+@xp_capabilities(allow_dask_compute=True)
+@_dispatch
+def fftn(x, s=None, axes=None, norm=None, overwrite_x=False, workers=None, *,
+         plan=None):
+    """
+    Compute the N-D discrete Fourier Transform.
+
+    This function computes the N-D discrete Fourier Transform over
+    any number of axes in an M-D array by means of the Fast Fourier
+    Transform (FFT).
+
+    Parameters
+    ----------
+    x : array_like
+        Input array, can be complex.
+    s : sequence of ints, optional
+        Shape (length of each transformed axis) of the output
+        (``s[0]`` refers to axis 0, ``s[1]`` to axis 1, etc.).
+        This corresponds to ``n`` for ``fft(x, n)``.
+        Along any axis, if the given shape is smaller than that of the input,
+        the input is cropped. If it is larger, the input is padded with zeros.
+        if `s` is not given, the shape of the input along the axes specified
+        by `axes` is used.
+    axes : sequence of ints, optional
+        Axes over which to compute the FFT. If not given, the last ``len(s)``
+        axes are used, or all axes if `s` is also not specified.
+    norm : {"backward", "ortho", "forward"}, optional
+        Normalization mode (see `fft`). Default is "backward".
+    overwrite_x : bool, optional
+        If True, the contents of `x` can be destroyed; the default is False.
+        See :func:`fft` for more details.
+    workers : int, optional
+        Maximum number of workers to use for parallel computation. If negative,
+        the value wraps around from ``os.cpu_count()``.
+        See :func:`~scipy.fft.fft` for more details.
+    plan : object, optional
+        This argument is reserved for passing in a precomputed plan provided
+        by downstream FFT vendors. It is currently not used in SciPy.
+
+        .. versionadded:: 1.5.0
+
+    Returns
+    -------
+    out : complex ndarray
+        The truncated or zero-padded input, transformed along the axes
+        indicated by `axes`, or by a combination of `s` and `x`,
+        as explained in the parameters section above.
+
+    Raises
+    ------
+    ValueError
+        If `s` and `axes` have different length.
+    IndexError
+        If an element of `axes` is larger than the number of axes of `x`.
+
+    See Also
+    --------
+    ifftn : The inverse of `fftn`, the inverse N-D FFT.
+    fft : The 1-D FFT, with definitions and conventions used.
+    rfftn : The N-D FFT of real input.
+    fft2 : The 2-D FFT.
+    fftshift : Shifts zero-frequency terms to centre of array.
+
+    Notes
+    -----
+    The output, analogously to `fft`, contains the term for zero frequency in
+    the low-order corner of all axes, the positive frequency terms in the
+    first half of all axes, the term for the Nyquist frequency in the middle
+    of all axes and the negative frequency terms in the second half of all
+    axes, in order of decreasingly negative frequency.
+
+    Examples
+    --------
+    >>> import scipy.fft
+    >>> import numpy as np
+    >>> x = np.mgrid[:3, :3, :3][0]
+    >>> scipy.fft.fftn(x, axes=(1, 2))
+    array([[[ 0.+0.j,   0.+0.j,   0.+0.j], # may vary
+            [ 0.+0.j,   0.+0.j,   0.+0.j],
+            [ 0.+0.j,   0.+0.j,   0.+0.j]],
+           [[ 9.+0.j,   0.+0.j,   0.+0.j],
+            [ 0.+0.j,   0.+0.j,   0.+0.j],
+            [ 0.+0.j,   0.+0.j,   0.+0.j]],
+           [[18.+0.j,   0.+0.j,   0.+0.j],
+            [ 0.+0.j,   0.+0.j,   0.+0.j],
+            [ 0.+0.j,   0.+0.j,   0.+0.j]]])
+    >>> scipy.fft.fftn(x, (2, 2), axes=(0, 1))
+    array([[[ 2.+0.j,  2.+0.j,  2.+0.j], # may vary
+            [ 0.+0.j,  0.+0.j,  0.+0.j]],
+           [[-2.+0.j, -2.+0.j, -2.+0.j],
+            [ 0.+0.j,  0.+0.j,  0.+0.j]]])
+
+    >>> import matplotlib.pyplot as plt
+    >>> rng = np.random.default_rng()
+    >>> [X, Y] = np.meshgrid(2 * np.pi * np.arange(200) / 12,
+    ...                      2 * np.pi * np.arange(200) / 34)
+    >>> S = np.sin(X) + np.cos(Y) + rng.uniform(0, 1, X.shape)
+    >>> FS = scipy.fft.fftn(S)
+    >>> plt.imshow(np.log(np.abs(scipy.fft.fftshift(FS))**2))
+    
+    >>> plt.show()
+
+    """
+    return (Dispatchable(x, np.ndarray),)
+
+
+@xp_capabilities(allow_dask_compute=True)
+@_dispatch
+def ifftn(x, s=None, axes=None, norm=None, overwrite_x=False, workers=None, *,
+          plan=None):
+    """
+    Compute the N-D inverse discrete Fourier Transform.
+
+    This function computes the inverse of the N-D discrete
+    Fourier Transform over any number of axes in an M-D array by
+    means of the Fast Fourier Transform (FFT).  In other words,
+    ``ifftn(fftn(x)) == x`` to within numerical accuracy.
+
+    The input, analogously to `ifft`, should be ordered in the same way as is
+    returned by `fftn`, i.e., it should have the term for zero frequency
+    in all axes in the low-order corner, the positive frequency terms in the
+    first half of all axes, the term for the Nyquist frequency in the middle
+    of all axes and the negative frequency terms in the second half of all
+    axes, in order of decreasingly negative frequency.
+
+    Parameters
+    ----------
+    x : array_like
+        Input array, can be complex.
+    s : sequence of ints, optional
+        Shape (length of each transformed axis) of the output
+        (``s[0]`` refers to axis 0, ``s[1]`` to axis 1, etc.).
+        This corresponds to ``n`` for ``ifft(x, n)``.
+        Along any axis, if the given shape is smaller than that of the input,
+        the input is cropped. If it is larger, the input is padded with zeros.
+        if `s` is not given, the shape of the input along the axes specified
+        by `axes` is used. See notes for issue on `ifft` zero padding.
+    axes : sequence of ints, optional
+        Axes over which to compute the IFFT.  If not given, the last ``len(s)``
+        axes are used, or all axes if `s` is also not specified.
+    norm : {"backward", "ortho", "forward"}, optional
+        Normalization mode (see `fft`). Default is "backward".
+    overwrite_x : bool, optional
+        If True, the contents of `x` can be destroyed; the default is False.
+        See :func:`fft` for more details.
+    workers : int, optional
+        Maximum number of workers to use for parallel computation. If negative,
+        the value wraps around from ``os.cpu_count()``.
+        See :func:`~scipy.fft.fft` for more details.
+    plan : object, optional
+        This argument is reserved for passing in a precomputed plan provided
+        by downstream FFT vendors. It is currently not used in SciPy.
+
+        .. versionadded:: 1.5.0
+
+    Returns
+    -------
+    out : complex ndarray
+        The truncated or zero-padded input, transformed along the axes
+        indicated by `axes`, or by a combination of `s` or `x`,
+        as explained in the parameters section above.
+
+    Raises
+    ------
+    ValueError
+        If `s` and `axes` have different length.
+    IndexError
+        If an element of `axes` is larger than the number of axes of `x`.
+
+    See Also
+    --------
+    fftn : The forward N-D FFT, of which `ifftn` is the inverse.
+    ifft : The 1-D inverse FFT.
+    ifft2 : The 2-D inverse FFT.
+    ifftshift : Undoes `fftshift`, shifts zero-frequency terms to beginning
+        of array.
+
+    Notes
+    -----
+    Zero-padding, analogously with `ifft`, is performed by appending zeros to
+    the input along the specified dimension. Although this is the common
+    approach, it might lead to surprising results. If another form of zero
+    padding is desired, it must be performed before `ifftn` is called.
+
+    Examples
+    --------
+    >>> import scipy.fft
+    >>> import numpy as np
+    >>> x = np.eye(4)
+    >>> scipy.fft.ifftn(scipy.fft.fftn(x, axes=(0,)), axes=(1,))
+    array([[1.+0.j,  0.+0.j,  0.+0.j,  0.+0.j], # may vary
+           [0.+0.j,  1.+0.j,  0.+0.j,  0.+0.j],
+           [0.+0.j,  0.+0.j,  1.+0.j,  0.+0.j],
+           [0.+0.j,  0.+0.j,  0.+0.j,  1.+0.j]])
+
+
+    Create and plot an image with band-limited frequency content:
+
+    >>> import matplotlib.pyplot as plt
+    >>> rng = np.random.default_rng()
+    >>> n = np.zeros((200,200), dtype=complex)
+    >>> n[60:80, 20:40] = np.exp(1j*rng.uniform(0, 2*np.pi, (20, 20)))
+    >>> im = scipy.fft.ifftn(n).real
+    >>> plt.imshow(im)
+    
+    >>> plt.show()
+
+    """
+    return (Dispatchable(x, np.ndarray),)
+
+
+@xp_capabilities(allow_dask_compute=True)
+@_dispatch
+def fft2(x, s=None, axes=(-2, -1), norm=None, overwrite_x=False, workers=None, *,
+         plan=None):
+    """
+    Compute the 2-D discrete Fourier Transform.
+
+    This function computes the N-D discrete Fourier Transform
+    over any axes in an M-D array by means of the
+    Fast Fourier Transform (FFT). By default, the transform is computed over
+    the last two axes of the input array, i.e., a 2-dimensional FFT.
+
+    Parameters
+    ----------
+    x : array_like
+        Input array, can be complex
+    s : sequence of ints, optional
+        Shape (length of each transformed axis) of the output
+        (``s[0]`` refers to axis 0, ``s[1]`` to axis 1, etc.).
+        This corresponds to ``n`` for ``fft(x, n)``.
+        Along each axis, if the given shape is smaller than that of the input,
+        the input is cropped. If it is larger, the input is padded with zeros.
+        if `s` is not given, the shape of the input along the axes specified
+        by `axes` is used.
+    axes : sequence of ints, optional
+        Axes over which to compute the FFT. If not given, the last two axes are
+        used.
+    norm : {"backward", "ortho", "forward"}, optional
+        Normalization mode (see `fft`). Default is "backward".
+    overwrite_x : bool, optional
+        If True, the contents of `x` can be destroyed; the default is False.
+        See :func:`fft` for more details.
+    workers : int, optional
+        Maximum number of workers to use for parallel computation. If negative,
+        the value wraps around from ``os.cpu_count()``.
+        See :func:`~scipy.fft.fft` for more details.
+    plan : object, optional
+        This argument is reserved for passing in a precomputed plan provided
+        by downstream FFT vendors. It is currently not used in SciPy.
+
+        .. versionadded:: 1.5.0
+
+    Returns
+    -------
+    out : complex ndarray
+        The truncated or zero-padded input, transformed along the axes
+        indicated by `axes`, or the last two axes if `axes` is not given.
+
+    Raises
+    ------
+    ValueError
+        If `s` and `axes` have different length, or `axes` not given and
+        ``len(s) != 2``.
+    IndexError
+        If an element of `axes` is larger than the number of axes of `x`.
+
+    See Also
+    --------
+    ifft2 : The inverse 2-D FFT.
+    fft : The 1-D FFT.
+    fftn : The N-D FFT.
+    fftshift : Shifts zero-frequency terms to the center of the array.
+        For 2-D input, swaps first and third quadrants, and second
+        and fourth quadrants.
+
+    Notes
+    -----
+    `fft2` is just `fftn` with a different default for `axes`.
+
+    The output, analogously to `fft`, contains the term for zero frequency in
+    the low-order corner of the transformed axes, the positive frequency terms
+    in the first half of these axes, the term for the Nyquist frequency in the
+    middle of the axes and the negative frequency terms in the second half of
+    the axes, in order of decreasingly negative frequency.
+
+    See `fftn` for details and a plotting example, and `fft` for
+    definitions and conventions used.
+
+
+    Examples
+    --------
+    >>> import scipy.fft
+    >>> import numpy as np
+    >>> x = np.mgrid[:5, :5][0]
+    >>> scipy.fft.fft2(x)
+    array([[ 50.  +0.j        ,   0.  +0.j        ,   0.  +0.j        , # may vary
+              0.  +0.j        ,   0.  +0.j        ],
+           [-12.5+17.20477401j,   0.  +0.j        ,   0.  +0.j        ,
+              0.  +0.j        ,   0.  +0.j        ],
+           [-12.5 +4.0614962j ,   0.  +0.j        ,   0.  +0.j        ,
+              0.  +0.j        ,   0.  +0.j        ],
+           [-12.5 -4.0614962j ,   0.  +0.j        ,   0.  +0.j        ,
+              0.  +0.j        ,   0.  +0.j        ],
+           [-12.5-17.20477401j,   0.  +0.j        ,   0.  +0.j        ,
+              0.  +0.j        ,   0.  +0.j        ]])
+
+    """
+    return (Dispatchable(x, np.ndarray),)
+
+
+@xp_capabilities(allow_dask_compute=True)
+@_dispatch
+def ifft2(x, s=None, axes=(-2, -1), norm=None, overwrite_x=False, workers=None, *,
+          plan=None):
+    """
+    Compute the 2-D inverse discrete Fourier Transform.
+
+    This function computes the inverse of the 2-D discrete Fourier
+    Transform over any number of axes in an M-D array by means of
+    the Fast Fourier Transform (FFT). In other words, ``ifft2(fft2(x)) == x``
+    to within numerical accuracy. By default, the inverse transform is
+    computed over the last two axes of the input array.
+
+    The input, analogously to `ifft`, should be ordered in the same way as is
+    returned by `fft2`, i.e., it should have the term for zero frequency
+    in the low-order corner of the two axes, the positive frequency terms in
+    the first half of these axes, the term for the Nyquist frequency in the
+    middle of the axes and the negative frequency terms in the second half of
+    both axes, in order of decreasingly negative frequency.
+
+    Parameters
+    ----------
+    x : array_like
+        Input array, can be complex.
+    s : sequence of ints, optional
+        Shape (length of each axis) of the output (``s[0]`` refers to axis 0,
+        ``s[1]`` to axis 1, etc.). This corresponds to `n` for ``ifft(x, n)``.
+        Along each axis, if the given shape is smaller than that of the input,
+        the input is cropped. If it is larger, the input is padded with zeros.
+        if `s` is not given, the shape of the input along the axes specified
+        by `axes` is used.  See notes for issue on `ifft` zero padding.
+    axes : sequence of ints, optional
+        Axes over which to compute the FFT. If not given, the last two
+        axes are used.
+    norm : {"backward", "ortho", "forward"}, optional
+        Normalization mode (see `fft`). Default is "backward".
+    overwrite_x : bool, optional
+        If True, the contents of `x` can be destroyed; the default is False.
+        See :func:`fft` for more details.
+    workers : int, optional
+        Maximum number of workers to use for parallel computation. If negative,
+        the value wraps around from ``os.cpu_count()``.
+        See :func:`~scipy.fft.fft` for more details.
+    plan : object, optional
+        This argument is reserved for passing in a precomputed plan provided
+        by downstream FFT vendors. It is currently not used in SciPy.
+
+        .. versionadded:: 1.5.0
+
+    Returns
+    -------
+    out : complex ndarray
+        The truncated or zero-padded input, transformed along the axes
+        indicated by `axes`, or the last two axes if `axes` is not given.
+
+    Raises
+    ------
+    ValueError
+        If `s` and `axes` have different length, or `axes` not given and
+        ``len(s) != 2``.
+    IndexError
+        If an element of `axes` is larger than the number of axes of `x`.
+
+    See Also
+    --------
+    fft2 : The forward 2-D FFT, of which `ifft2` is the inverse.
+    ifftn : The inverse of the N-D FFT.
+    fft : The 1-D FFT.
+    ifft : The 1-D inverse FFT.
+
+    Notes
+    -----
+    `ifft2` is just `ifftn` with a different default for `axes`.
+
+    See `ifftn` for details and a plotting example, and `fft` for
+    definition and conventions used.
+
+    Zero-padding, analogously with `ifft`, is performed by appending zeros to
+    the input along the specified dimension. Although this is the common
+    approach, it might lead to surprising results. If another form of zero
+    padding is desired, it must be performed before `ifft2` is called.
+
+    Examples
+    --------
+    >>> import scipy.fft
+    >>> import numpy as np
+    >>> x = 4 * np.eye(4)
+    >>> scipy.fft.ifft2(x)
+    array([[1.+0.j,  0.+0.j,  0.+0.j,  0.+0.j], # may vary
+           [0.+0.j,  0.+0.j,  0.+0.j,  1.+0.j],
+           [0.+0.j,  0.+0.j,  1.+0.j,  0.+0.j],
+           [0.+0.j,  1.+0.j,  0.+0.j,  0.+0.j]])
+
+    """
+    return (Dispatchable(x, np.ndarray),)
+
+
+@xp_capabilities(allow_dask_compute=True)
+@_dispatch
+def rfftn(x, s=None, axes=None, norm=None, overwrite_x=False, workers=None, *,
+          plan=None):
+    """
+    Compute the N-D discrete Fourier Transform for real input.
+
+    This function computes the N-D discrete Fourier Transform over
+    any number of axes in an M-D real array by means of the Fast
+    Fourier Transform (FFT). By default, all axes are transformed, with the
+    real transform performed over the last axis, while the remaining
+    transforms are complex.
+
+    Parameters
+    ----------
+    x : array_like
+        Input array, taken to be real.
+    s : sequence of ints, optional
+        Shape (length along each transformed axis) to use from the input.
+        (``s[0]`` refers to axis 0, ``s[1]`` to axis 1, etc.).
+        The final element of `s` corresponds to `n` for ``rfft(x, n)``, while
+        for the remaining axes, it corresponds to `n` for ``fft(x, n)``.
+        Along any axis, if the given shape is smaller than that of the input,
+        the input is cropped. If it is larger, the input is padded with zeros.
+        if `s` is not given, the shape of the input along the axes specified
+        by `axes` is used.
+    axes : sequence of ints, optional
+        Axes over which to compute the FFT. If not given, the last ``len(s)``
+        axes are used, or all axes if `s` is also not specified.
+    norm : {"backward", "ortho", "forward"}, optional
+        Normalization mode (see `fft`). Default is "backward".
+    overwrite_x : bool, optional
+        If True, the contents of `x` can be destroyed; the default is False.
+        See :func:`fft` for more details.
+    workers : int, optional
+        Maximum number of workers to use for parallel computation. If negative,
+        the value wraps around from ``os.cpu_count()``.
+        See :func:`~scipy.fft.fft` for more details.
+    plan : object, optional
+        This argument is reserved for passing in a precomputed plan provided
+        by downstream FFT vendors. It is currently not used in SciPy.
+
+        .. versionadded:: 1.5.0
+
+    Returns
+    -------
+    out : complex ndarray
+        The truncated or zero-padded input, transformed along the axes
+        indicated by `axes`, or by a combination of `s` and `x`,
+        as explained in the parameters section above.
+        The length of the last axis transformed will be ``s[-1]//2+1``,
+        while the remaining transformed axes will have lengths according to
+        `s`, or unchanged from the input.
+
+    Raises
+    ------
+    ValueError
+        If `s` and `axes` have different length.
+    IndexError
+        If an element of `axes` is larger than the number of axes of `x`.
+
+    See Also
+    --------
+    irfftn : The inverse of `rfftn`, i.e., the inverse of the N-D FFT
+         of real input.
+    fft : The 1-D FFT, with definitions and conventions used.
+    rfft : The 1-D FFT of real input.
+    fftn : The N-D FFT.
+    rfft2 : The 2-D FFT of real input.
+
+    Notes
+    -----
+    The transform for real input is performed over the last transformation
+    axis, as by `rfft`, then the transform over the remaining axes is
+    performed as by `fftn`. The order of the output is as for `rfft` for the
+    final transformation axis, and as for `fftn` for the remaining
+    transformation axes.
+
+    See `fft` for details, definitions and conventions used.
+
+    Examples
+    --------
+    >>> import scipy.fft
+    >>> import numpy as np
+    >>> x = np.ones((2, 2, 2))
+    >>> scipy.fft.rfftn(x)
+    array([[[8.+0.j,  0.+0.j], # may vary
+            [0.+0.j,  0.+0.j]],
+           [[0.+0.j,  0.+0.j],
+            [0.+0.j,  0.+0.j]]])
+
+    >>> scipy.fft.rfftn(x, axes=(2, 0))
+    array([[[4.+0.j,  0.+0.j], # may vary
+            [4.+0.j,  0.+0.j]],
+           [[0.+0.j,  0.+0.j],
+            [0.+0.j,  0.+0.j]]])
+
+    """
+    return (Dispatchable(x, np.ndarray),)
+
+
+@xp_capabilities(allow_dask_compute=True)
+@_dispatch
+def rfft2(x, s=None, axes=(-2, -1), norm=None, overwrite_x=False, workers=None, *,
+          plan=None):
+    """
+    Compute the 2-D FFT of a real array.
+
+    Parameters
+    ----------
+    x : array
+        Input array, taken to be real.
+    s : sequence of ints, optional
+        Shape of the FFT.
+    axes : sequence of ints, optional
+        Axes over which to compute the FFT.
+    norm : {"backward", "ortho", "forward"}, optional
+        Normalization mode (see `fft`). Default is "backward".
+    overwrite_x : bool, optional
+        If True, the contents of `x` can be destroyed; the default is False.
+        See :func:`fft` for more details.
+    workers : int, optional
+        Maximum number of workers to use for parallel computation. If negative,
+        the value wraps around from ``os.cpu_count()``.
+        See :func:`~scipy.fft.fft` for more details.
+    plan : object, optional
+        This argument is reserved for passing in a precomputed plan provided
+        by downstream FFT vendors. It is currently not used in SciPy.
+
+        .. versionadded:: 1.5.0
+
+    Returns
+    -------
+    out : ndarray
+        The result of the real 2-D FFT.
+
+    See Also
+    --------
+    irfft2 : The inverse of the 2-D FFT of real input.
+    rfft : The 1-D FFT of real input.
+    rfftn : Compute the N-D discrete Fourier Transform for real
+            input.
+
+    Notes
+    -----
+    This is really just `rfftn` with different default behavior.
+    For more details see `rfftn`.
+
+    Examples
+    --------
+    >>> import scipy.fft
+    >>> import numpy as np
+    >>> x = np.broadcast_to([1, 0, -1, 0], (4, 4))
+    >>> scipy.fft.rfft2(x)
+    array([[0.+0.j, 8.+0.j, 0.+0.j],
+           [0.+0.j, 0.+0.j, 0.+0.j],
+           [0.+0.j, 0.+0.j, 0.+0.j],
+           [0.+0.j, 0.+0.j, 0.+0.j]])
+
+    """
+    return (Dispatchable(x, np.ndarray),)
+
+
+@xp_capabilities(allow_dask_compute=True)
+@_dispatch
+def irfftn(x, s=None, axes=None, norm=None, overwrite_x=False, workers=None, *,
+           plan=None):
+    """
+    Computes the inverse of `rfftn`.
+
+    This function computes the inverse of the N-D discrete
+    Fourier Transform for real input over any number of axes in an
+    M-D array by means of the Fast Fourier Transform (FFT). In
+    other words, ``irfftn(rfftn(x), x.shape) == x`` to within numerical
+    accuracy. (The ``a.shape`` is necessary like ``len(a)`` is for `irfft`,
+    and for the same reason.)
+
+    The input should be ordered in the same way as is returned by `rfftn`,
+    i.e., as for `irfft` for the final transformation axis, and as for `ifftn`
+    along all the other axes.
+
+    Parameters
+    ----------
+    x : array_like
+        Input array.
+    s : sequence of ints, optional
+        Shape (length of each transformed axis) of the output
+        (``s[0]`` refers to axis 0, ``s[1]`` to axis 1, etc.). `s` is also the
+        number of input points used along this axis, except for the last axis,
+        where ``s[-1]//2+1`` points of the input are used.
+        Along any axis, if the shape indicated by `s` is smaller than that of
+        the input, the input is cropped. If it is larger, the input is padded
+        with zeros. If `s` is not given, the shape of the input along the axes
+        specified by axes is used. Except for the last axis which is taken to be
+        ``2*(m-1)``, where ``m`` is the length of the input along that axis.
+    axes : sequence of ints, optional
+        Axes over which to compute the inverse FFT. If not given, the last
+        `len(s)` axes are used, or all axes if `s` is also not specified.
+    norm : {"backward", "ortho", "forward"}, optional
+        Normalization mode (see `fft`). Default is "backward".
+    overwrite_x : bool, optional
+        If True, the contents of `x` can be destroyed; the default is False.
+        See :func:`fft` for more details.
+    workers : int, optional
+        Maximum number of workers to use for parallel computation. If negative,
+        the value wraps around from ``os.cpu_count()``.
+        See :func:`~scipy.fft.fft` for more details.
+    plan : object, optional
+        This argument is reserved for passing in a precomputed plan provided
+        by downstream FFT vendors. It is currently not used in SciPy.
+
+        .. versionadded:: 1.5.0
+
+    Returns
+    -------
+    out : ndarray
+        The truncated or zero-padded input, transformed along the axes
+        indicated by `axes`, or by a combination of `s` or `x`,
+        as explained in the parameters section above.
+        The length of each transformed axis is as given by the corresponding
+        element of `s`, or the length of the input in every axis except for the
+        last one if `s` is not given. In the final transformed axis the length
+        of the output when `s` is not given is ``2*(m-1)``, where ``m`` is the
+        length of the final transformed axis of the input. To get an odd
+        number of output points in the final axis, `s` must be specified.
+
+    Raises
+    ------
+    ValueError
+        If `s` and `axes` have different length.
+    IndexError
+        If an element of `axes` is larger than the number of axes of `x`.
+
+    See Also
+    --------
+    rfftn : The forward N-D FFT of real input,
+            of which `ifftn` is the inverse.
+    fft : The 1-D FFT, with definitions and conventions used.
+    irfft : The inverse of the 1-D FFT of real input.
+    irfft2 : The inverse of the 2-D FFT of real input.
+
+    Notes
+    -----
+    See `fft` for definitions and conventions used.
+
+    See `rfft` for definitions and conventions used for real input.
+
+    The default value of `s` assumes an even output length in the final
+    transformation axis. When performing the final complex to real
+    transformation, the Hermitian symmetry requires that the last imaginary
+    component along that axis must be 0 and so it is ignored. To avoid losing
+    information, the correct length of the real input *must* be given.
+
+    Examples
+    --------
+    >>> import scipy.fft
+    >>> import numpy as np
+    >>> x = np.zeros((3, 2, 2))
+    >>> x[0, 0, 0] = 3 * 2 * 2
+    >>> scipy.fft.irfftn(x)
+    array([[[1.,  1.],
+            [1.,  1.]],
+           [[1.,  1.],
+            [1.,  1.]],
+           [[1.,  1.],
+            [1.,  1.]]])
+
+    """
+    return (Dispatchable(x, np.ndarray),)
+
+
+@xp_capabilities(allow_dask_compute=True)
+@_dispatch
+def irfft2(x, s=None, axes=(-2, -1), norm=None, overwrite_x=False, workers=None, *,
+           plan=None):
+    """
+    Computes the inverse of `rfft2`.
+
+    Parameters
+    ----------
+    x : array_like
+        The input array
+    s : sequence of ints, optional
+        Shape of the real output to the inverse FFT.
+    axes : sequence of ints, optional
+        The axes over which to compute the inverse fft.
+        Default is the last two axes.
+    norm : {"backward", "ortho", "forward"}, optional
+        Normalization mode (see `fft`). Default is "backward".
+    overwrite_x : bool, optional
+        If True, the contents of `x` can be destroyed; the default is False.
+        See :func:`fft` for more details.
+    workers : int, optional
+        Maximum number of workers to use for parallel computation. If negative,
+        the value wraps around from ``os.cpu_count()``.
+        See :func:`~scipy.fft.fft` for more details.
+    plan : object, optional
+        This argument is reserved for passing in a precomputed plan provided
+        by downstream FFT vendors. It is currently not used in SciPy.
+
+        .. versionadded:: 1.5.0
+
+    Returns
+    -------
+    out : ndarray
+        The result of the inverse real 2-D FFT.
+
+    See Also
+    --------
+    rfft2 : The 2-D FFT of real input.
+    irfft : The inverse of the 1-D FFT of real input.
+    irfftn : The inverse of the N-D FFT of real input.
+
+    Notes
+    -----
+    This is really `irfftn` with different defaults.
+    For more details see `irfftn`.
+
+    """
+    return (Dispatchable(x, np.ndarray),)
+
+
+@xp_capabilities(allow_dask_compute=True)
+@_dispatch
+def hfftn(x, s=None, axes=None, norm=None, overwrite_x=False, workers=None, *,
+          plan=None):
+    """
+    Compute the N-D FFT of Hermitian symmetric complex input, i.e., a
+    signal with a real spectrum.
+
+    This function computes the N-D discrete Fourier Transform for a
+    Hermitian symmetric complex input over any number of axes in an
+    M-D array by means of the Fast Fourier Transform (FFT). In other
+    words, ``ihfftn(hfftn(x, s)) == x`` to within numerical accuracy. (``s``
+    here is ``x.shape`` with ``s[-1] = x.shape[-1] * 2 - 1``, this is necessary
+    for the same reason ``x.shape`` would be necessary for `irfft`.)
+
+    Parameters
+    ----------
+    x : array_like
+        Input array.
+    s : sequence of ints, optional
+        Shape (length of each transformed axis) of the output
+        (``s[0]`` refers to axis 0, ``s[1]`` to axis 1, etc.). `s` is also the
+        number of input points used along this axis, except for the last axis,
+        where ``s[-1]//2+1`` points of the input are used.
+        Along any axis, if the shape indicated by `s` is smaller than that of
+        the input, the input is cropped. If it is larger, the input is padded
+        with zeros. If `s` is not given, the shape of the input along the axes
+        specified by axes is used. Except for the last axis which is taken to be
+        ``2*(m-1)`` where ``m`` is the length of the input along that axis.
+    axes : sequence of ints, optional
+        Axes over which to compute the inverse FFT. If not given, the last
+        `len(s)` axes are used, or all axes if `s` is also not specified.
+    norm : {"backward", "ortho", "forward"}, optional
+        Normalization mode (see `fft`). Default is "backward".
+    overwrite_x : bool, optional
+        If True, the contents of `x` can be destroyed; the default is False.
+        See :func:`fft` for more details.
+    workers : int, optional
+        Maximum number of workers to use for parallel computation. If negative,
+        the value wraps around from ``os.cpu_count()``.
+        See :func:`~scipy.fft.fft` for more details.
+    plan : object, optional
+        This argument is reserved for passing in a precomputed plan provided
+        by downstream FFT vendors. It is currently not used in SciPy.
+
+        .. versionadded:: 1.5.0
+
+    Returns
+    -------
+    out : ndarray
+        The truncated or zero-padded input, transformed along the axes
+        indicated by `axes`, or by a combination of `s` or `x`,
+        as explained in the parameters section above.
+        The length of each transformed axis is as given by the corresponding
+        element of `s`, or the length of the input in every axis except for the
+        last one if `s` is not given.  In the final transformed axis the length
+        of the output when `s` is not given is ``2*(m-1)`` where ``m`` is the
+        length of the final transformed axis of the input.  To get an odd
+        number of output points in the final axis, `s` must be specified.
+
+    Raises
+    ------
+    ValueError
+        If `s` and `axes` have different length.
+    IndexError
+        If an element of `axes` is larger than the number of axes of `x`.
+
+    See Also
+    --------
+    ihfftn : The inverse N-D FFT with real spectrum. Inverse of `hfftn`.
+    fft : The 1-D FFT, with definitions and conventions used.
+    rfft : Forward FFT of real input.
+
+    Notes
+    -----
+    For a 1-D signal ``x`` to have a real spectrum, it must satisfy
+    the Hermitian property::
+
+        x[i] == np.conj(x[-i]) for all i
+
+    This generalizes into higher dimensions by reflecting over each axis in
+    turn::
+
+        x[i, j, k, ...] == np.conj(x[-i, -j, -k, ...]) for all i, j, k, ...
+
+    This should not be confused with a Hermitian matrix, for which the
+    transpose is its own conjugate::
+
+        x[i, j] == np.conj(x[j, i]) for all i, j
+
+
+    The default value of `s` assumes an even output length in the final
+    transformation axis. When performing the final complex to real
+    transformation, the Hermitian symmetry requires that the last imaginary
+    component along that axis must be 0 and so it is ignored. To avoid losing
+    information, the correct length of the real input *must* be given.
+
+    Examples
+    --------
+    >>> import scipy.fft
+    >>> import numpy as np
+    >>> x = np.ones((3, 2, 2))
+    >>> scipy.fft.hfftn(x)
+    array([[[12.,  0.],
+            [ 0.,  0.]],
+           [[ 0.,  0.],
+            [ 0.,  0.]],
+           [[ 0.,  0.],
+            [ 0.,  0.]]])
+
+    """
+    return (Dispatchable(x, np.ndarray),)
+
+
+@xp_capabilities(allow_dask_compute=True)
+@_dispatch
+def hfft2(x, s=None, axes=(-2, -1), norm=None, overwrite_x=False, workers=None, *,
+          plan=None):
+    """
+    Compute the 2-D FFT of a Hermitian complex array.
+
+    Parameters
+    ----------
+    x : array
+        Input array, taken to be Hermitian complex.
+    s : sequence of ints, optional
+        Shape of the real output.
+    axes : sequence of ints, optional
+        Axes over which to compute the FFT.
+    norm : {"backward", "ortho", "forward"}, optional
+        Normalization mode (see `fft`). Default is "backward".
+    overwrite_x : bool, optional
+        If True, the contents of `x` can be destroyed; the default is False.
+        See `fft` for more details.
+    workers : int, optional
+        Maximum number of workers to use for parallel computation. If negative,
+        the value wraps around from ``os.cpu_count()``.
+        See :func:`~scipy.fft.fft` for more details.
+    plan : object, optional
+        This argument is reserved for passing in a precomputed plan provided
+        by downstream FFT vendors. It is currently not used in SciPy.
+
+        .. versionadded:: 1.5.0
+
+    Returns
+    -------
+    out : ndarray
+        The real result of the 2-D Hermitian complex real FFT.
+
+    See Also
+    --------
+    hfftn : Compute the N-D discrete Fourier Transform for Hermitian
+            complex input.
+
+    Notes
+    -----
+    This is really just `hfftn` with different default behavior.
+    For more details see `hfftn`.
+
+    Examples
+    --------
+    >>> import scipy.fft
+    >>> import numpy as np
+    >>> x = np.array([[1+0j, 2+0j], [2+0j, 1+0j]])  # Hermitian-symmetric input
+    >>> scipy.fft.hfft2(x, s=(2, 2))
+    array([[ 6.,  0.],
+           [ 0., -2.]])
+
+    """
+    return (Dispatchable(x, np.ndarray),)
+
+
+@xp_capabilities(allow_dask_compute=True)
+@_dispatch
+def ihfftn(x, s=None, axes=None, norm=None, overwrite_x=False, workers=None, *,
+           plan=None):
+    """
+    Compute the N-D inverse discrete Fourier Transform for a real
+    spectrum.
+
+    This function computes the N-D inverse discrete Fourier Transform
+    over any number of axes in an M-D real array by means of the Fast
+    Fourier Transform (FFT). By default, all axes are transformed, with the
+    real transform performed over the last axis, while the remaining transforms
+    are complex.
+
+    Parameters
+    ----------
+    x : array_like
+        Input array, taken to be real.
+    s : sequence of ints, optional
+        Shape (length along each transformed axis) to use from the input.
+        (``s[0]`` refers to axis 0, ``s[1]`` to axis 1, etc.).
+        Along any axis, if the given shape is smaller than that of the input,
+        the input is cropped. If it is larger, the input is padded with zeros.
+        if `s` is not given, the shape of the input along the axes specified
+        by `axes` is used.
+    axes : sequence of ints, optional
+        Axes over which to compute the FFT. If not given, the last ``len(s)``
+        axes are used, or all axes if `s` is also not specified.
+    norm : {"backward", "ortho", "forward"}, optional
+        Normalization mode (see `fft`). Default is "backward".
+    overwrite_x : bool, optional
+        If True, the contents of `x` can be destroyed; the default is False.
+        See :func:`fft` for more details.
+    workers : int, optional
+        Maximum number of workers to use for parallel computation. If negative,
+        the value wraps around from ``os.cpu_count()``.
+        See :func:`~scipy.fft.fft` for more details.
+    plan : object, optional
+        This argument is reserved for passing in a precomputed plan provided
+        by downstream FFT vendors. It is currently not used in SciPy.
+
+        .. versionadded:: 1.5.0
+
+    Returns
+    -------
+    out : complex ndarray
+        The truncated or zero-padded input, transformed along the axes
+        indicated by `axes`, or by a combination of `s` and `x`,
+        as explained in the parameters section above.
+        The length of the last axis transformed will be ``s[-1]//2+1``,
+        while the remaining transformed axes will have lengths according to
+        `s`, or unchanged from the input.
+
+    Raises
+    ------
+    ValueError
+        If `s` and `axes` have different length.
+    IndexError
+        If an element of `axes` is larger than the number of axes of `x`.
+
+    See Also
+    --------
+    hfftn : The forward N-D FFT of Hermitian input.
+    hfft : The 1-D FFT of Hermitian input.
+    fft : The 1-D FFT, with definitions and conventions used.
+    fftn : The N-D FFT.
+    hfft2 : The 2-D FFT of Hermitian input.
+
+    Notes
+    -----
+    The transform for real input is performed over the last transformation
+    axis, as by `ihfft`, then the transform over the remaining axes is
+    performed as by `ifftn`. The order of the output is the positive part of
+    the Hermitian output signal, in the same format as `rfft`.
+
+    Examples
+    --------
+    >>> import scipy.fft
+    >>> import numpy as np
+    >>> x = np.ones((2, 2, 2))
+    >>> scipy.fft.ihfftn(x)
+    array([[[1.+0.j,  0.+0.j], # may vary
+            [0.+0.j,  0.+0.j]],
+           [[0.+0.j,  0.+0.j],
+            [0.+0.j,  0.+0.j]]])
+    >>> scipy.fft.ihfftn(x, axes=(2, 0))
+    array([[[1.+0.j,  0.+0.j], # may vary
+            [1.+0.j,  0.+0.j]],
+           [[0.+0.j,  0.+0.j],
+            [0.+0.j,  0.+0.j]]])
+
+    """
+    return (Dispatchable(x, np.ndarray),)
+
+
+@xp_capabilities(allow_dask_compute=True)
+@_dispatch
+def ihfft2(x, s=None, axes=(-2, -1), norm=None, overwrite_x=False, workers=None, *,
+           plan=None):
+    """
+    Compute the 2-D inverse FFT of a real spectrum.
+
+    Parameters
+    ----------
+    x : array_like
+        The input array
+    s : sequence of ints, optional
+        Shape of the real input to the inverse FFT.
+    axes : sequence of ints, optional
+        The axes over which to compute the inverse fft.
+        Default is the last two axes.
+    norm : {"backward", "ortho", "forward"}, optional
+        Normalization mode (see `fft`). Default is "backward".
+    overwrite_x : bool, optional
+        If True, the contents of `x` can be destroyed; the default is False.
+        See :func:`fft` for more details.
+    workers : int, optional
+        Maximum number of workers to use for parallel computation. If negative,
+        the value wraps around from ``os.cpu_count()``.
+        See :func:`~scipy.fft.fft` for more details.
+    plan : object, optional
+        This argument is reserved for passing in a precomputed plan provided
+        by downstream FFT vendors. It is currently not used in SciPy.
+
+        .. versionadded:: 1.5.0
+
+    Returns
+    -------
+    out : ndarray
+        The result of the inverse real 2-D FFT.
+
+    See Also
+    --------
+    ihfftn : Compute the inverse of the N-D FFT of Hermitian input.
+
+    Notes
+    -----
+    This is really `ihfftn` with different defaults.
+    For more details see `ihfftn`.
+
+    """
+    return (Dispatchable(x, np.ndarray),)
diff --git a/.venv/lib/python3.12/site-packages/scipy/fft/_basic_backend.py b/.venv/lib/python3.12/site-packages/scipy/fft/_basic_backend.py
new file mode 100644
index 0000000000000000000000000000000000000000..a2149101f413b14104d7fbbc2603b61e905e0132
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/fft/_basic_backend.py
@@ -0,0 +1,197 @@
+from scipy._lib._array_api import (
+    array_namespace, is_numpy, xp_unsupported_param_msg, is_complex, xp_float_to_complex
+)
+from . import _duccfft
+import numpy as np
+
+
+def _validate_fft_args(workers, plan, norm):
+    if workers is not None:
+        raise ValueError(xp_unsupported_param_msg("workers"))
+    if plan is not None:
+        raise ValueError(xp_unsupported_param_msg("plan"))
+    if norm is None:
+        norm = 'backward'
+    return norm
+
+
+# these functions expect complex input in the fft standard extension
+complex_funcs = {'fft', 'ifft', 'fftn', 'ifftn', 'hfft', 'irfft', 'irfftn'}
+
+# duccfft is used whenever SCIPY_ARRAY_API is not set,
+# or x is a NumPy array or array-like.
+# When SCIPY_ARRAY_API is set, we try to use xp.fft for CuPy arrays,
+# PyTorch arrays and other array API standard supporting objects.
+# If xp.fft does not exist, we attempt to convert to np and back to use duccfft.
+
+def _execute_1D(func_str, duccfft_func, x, n, axis, norm, overwrite_x, workers, plan):
+    xp = array_namespace(x)
+
+    if is_numpy(xp):
+        x = np.asarray(x)
+        return duccfft_func(x, n=n, axis=axis, norm=norm,
+                              overwrite_x=overwrite_x, workers=workers, plan=plan)
+
+    norm = _validate_fft_args(workers, plan, norm)
+    if hasattr(xp, 'fft'):
+        xp_func = getattr(xp.fft, func_str)
+        if func_str in complex_funcs:
+            try:
+                res = xp_func(x, n=n, axis=axis, norm=norm)
+            except: # backends may require complex input  # noqa: E722
+                x = xp_float_to_complex(x, xp)
+                res = xp_func(x, n=n, axis=axis, norm=norm)
+            return res
+        return xp_func(x, n=n, axis=axis, norm=norm)
+
+    x = np.asarray(x)
+    y = duccfft_func(x, n=n, axis=axis, norm=norm)
+    return xp.asarray(y)
+
+
+def _execute_nD(func_str, duccfft_func, x, s, axes, norm, overwrite_x, workers, plan):
+    xp = array_namespace(x)
+
+    if is_numpy(xp):
+        x = np.asarray(x)
+        return duccfft_func(x, s=s, axes=axes, norm=norm,
+                              overwrite_x=overwrite_x, workers=workers, plan=plan)
+
+    norm = _validate_fft_args(workers, plan, norm)
+    if hasattr(xp, 'fft'):
+        xp_func = getattr(xp.fft, func_str)
+        if func_str in complex_funcs:
+            try:
+                res = xp_func(x, s=s, axes=axes, norm=norm)
+            except: # backends may require complex input  # noqa: E722
+                x = xp_float_to_complex(x, xp)
+                res = xp_func(x, s=s, axes=axes, norm=norm)
+            return res
+        return xp_func(x, s=s, axes=axes, norm=norm)
+
+    x = np.asarray(x)
+    y = duccfft_func(x, s=s, axes=axes, norm=norm)
+    return xp.asarray(y)
+
+
+def fft(x, n=None, axis=-1, norm=None,
+        overwrite_x=False, workers=None, *, plan=None):
+    return _execute_1D('fft', _duccfft.fft, x, n=n, axis=axis, norm=norm,
+                       overwrite_x=overwrite_x, workers=workers, plan=plan)
+
+
+def ifft(x, n=None, axis=-1, norm=None, overwrite_x=False, workers=None, *,
+         plan=None):
+    return _execute_1D('ifft', _duccfft.ifft, x, n=n, axis=axis, norm=norm,
+                       overwrite_x=overwrite_x, workers=workers, plan=plan)
+
+
+def rfft(x, n=None, axis=-1, norm=None,
+         overwrite_x=False, workers=None, *, plan=None):
+    return _execute_1D('rfft', _duccfft.rfft, x, n=n, axis=axis, norm=norm,
+                       overwrite_x=overwrite_x, workers=workers, plan=plan)
+
+
+def irfft(x, n=None, axis=-1, norm=None,
+          overwrite_x=False, workers=None, *, plan=None):
+    return _execute_1D('irfft', _duccfft.irfft, x, n=n, axis=axis, norm=norm,
+                       overwrite_x=overwrite_x, workers=workers, plan=plan)
+
+
+def hfft(x, n=None, axis=-1, norm=None,
+         overwrite_x=False, workers=None, *, plan=None):
+    return _execute_1D('hfft', _duccfft.hfft, x, n=n, axis=axis, norm=norm,
+                       overwrite_x=overwrite_x, workers=workers, plan=plan)
+
+
+def ihfft(x, n=None, axis=-1, norm=None,
+          overwrite_x=False, workers=None, *, plan=None):
+    return _execute_1D('ihfft', _duccfft.ihfft, x, n=n, axis=axis, norm=norm,
+                       overwrite_x=overwrite_x, workers=workers, plan=plan)
+
+
+def fftn(x, s=None, axes=None, norm=None,
+         overwrite_x=False, workers=None, *, plan=None):
+    return _execute_nD('fftn', _duccfft.fftn, x, s=s, axes=axes, norm=norm,
+                       overwrite_x=overwrite_x, workers=workers, plan=plan)
+
+
+
+def ifftn(x, s=None, axes=None, norm=None,
+          overwrite_x=False, workers=None, *, plan=None):
+    return _execute_nD('ifftn', _duccfft.ifftn, x, s=s, axes=axes, norm=norm,
+                       overwrite_x=overwrite_x, workers=workers, plan=plan)
+
+
+def fft2(x, s=None, axes=(-2, -1), norm=None,
+         overwrite_x=False, workers=None, *, plan=None):
+    return fftn(x, s, axes, norm, overwrite_x, workers, plan=plan)
+
+
+def ifft2(x, s=None, axes=(-2, -1), norm=None,
+          overwrite_x=False, workers=None, *, plan=None):
+    return ifftn(x, s, axes, norm, overwrite_x, workers, plan=plan)
+
+
+def rfftn(x, s=None, axes=None, norm=None,
+          overwrite_x=False, workers=None, *, plan=None):
+    return _execute_nD('rfftn', _duccfft.rfftn, x, s=s, axes=axes, norm=norm,
+                       overwrite_x=overwrite_x, workers=workers, plan=plan)
+
+
+def rfft2(x, s=None, axes=(-2, -1), norm=None,
+         overwrite_x=False, workers=None, *, plan=None):
+    return rfftn(x, s, axes, norm, overwrite_x, workers, plan=plan)
+
+
+def irfftn(x, s=None, axes=None, norm=None,
+           overwrite_x=False, workers=None, *, plan=None):
+    return _execute_nD('irfftn', _duccfft.irfftn, x, s=s, axes=axes, norm=norm,
+                       overwrite_x=overwrite_x, workers=workers, plan=plan)
+
+
+def irfft2(x, s=None, axes=(-2, -1), norm=None,
+           overwrite_x=False, workers=None, *, plan=None):
+    return irfftn(x, s, axes, norm, overwrite_x, workers, plan=plan)
+
+
+def _swap_direction(norm):
+    if norm in (None, 'backward'):
+        norm = 'forward'
+    elif norm == 'forward':
+        norm = 'backward'
+    elif norm != 'ortho':
+        raise ValueError(f'Invalid norm value {norm}; should be "backward", '
+                         '"ortho", or "forward".')
+    return norm
+
+
+def hfftn(x, s=None, axes=None, norm=None,
+          overwrite_x=False, workers=None, *, plan=None):
+    xp = array_namespace(x)
+    if is_numpy(xp):
+        x = np.asarray(x)
+        return _duccfft.hfftn(x, s, axes, norm, overwrite_x, workers, plan=plan)
+    if is_complex(x, xp):
+        x = xp.conj(x)
+    return irfftn(x, s, axes, _swap_direction(norm),
+                  overwrite_x, workers, plan=plan)
+
+
+def hfft2(x, s=None, axes=(-2, -1), norm=None,
+          overwrite_x=False, workers=None, *, plan=None):
+    return hfftn(x, s, axes, norm, overwrite_x, workers, plan=plan)
+
+
+def ihfftn(x, s=None, axes=None, norm=None,
+           overwrite_x=False, workers=None, *, plan=None):
+    xp = array_namespace(x)
+    if is_numpy(xp):
+        x = np.asarray(x)
+        return _duccfft.ihfftn(x, s, axes, norm, overwrite_x, workers, plan=plan)
+    return xp.conj(rfftn(x, s, axes, _swap_direction(norm),
+                         overwrite_x, workers, plan=plan))
+
+def ihfft2(x, s=None, axes=(-2, -1), norm=None,
+           overwrite_x=False, workers=None, *, plan=None):
+    return ihfftn(x, s, axes, norm, overwrite_x, workers, plan=plan)
diff --git a/.venv/lib/python3.12/site-packages/scipy/fft/_debug_backends.py b/.venv/lib/python3.12/site-packages/scipy/fft/_debug_backends.py
new file mode 100644
index 0000000000000000000000000000000000000000..c9647c5d6ceddc73b97d95f562662ada02c1ae74
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/fft/_debug_backends.py
@@ -0,0 +1,22 @@
+import numpy as np
+
+class NumPyBackend:
+    """Backend that uses numpy.fft"""
+    __ua_domain__ = "numpy.scipy.fft"
+
+    @staticmethod
+    def __ua_function__(method, args, kwargs):
+        kwargs.pop("overwrite_x", None)
+
+        fn = getattr(np.fft, method.__name__, None)
+        return (NotImplemented if fn is None
+                else fn(*args, **kwargs))
+
+
+class EchoBackend:
+    """Backend that just prints the __ua_function__ arguments"""
+    __ua_domain__ = "numpy.scipy.fft"
+
+    @staticmethod
+    def __ua_function__(method, args, kwargs):
+        print(method, args, kwargs, sep='\n')
diff --git a/.venv/lib/python3.12/site-packages/scipy/fft/_duccfft/LICENSE.md b/.venv/lib/python3.12/site-packages/scipy/fft/_duccfft/LICENSE.md
new file mode 100644
index 0000000000000000000000000000000000000000..1b5163d8435976c24988afbd39ded304947178cb
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/fft/_duccfft/LICENSE.md
@@ -0,0 +1,25 @@
+Copyright (C) 2010-2019 Max-Planck-Society
+All rights reserved.
+
+Redistribution and use in source and binary forms, with or without modification,
+are permitted provided that the following conditions are met:
+
+* Redistributions of source code must retain the above copyright notice, this
+  list of conditions and the following disclaimer.
+* Redistributions in binary form must reproduce the above copyright notice, this
+  list of conditions and the following disclaimer in the documentation and/or
+  other materials provided with the distribution.
+* Neither the name of the copyright holder nor the names of its contributors may
+  be used to endorse or promote products derived from this software without
+  specific prior written permission.
+
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
+ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
+ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
+ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
+SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
diff --git a/.venv/lib/python3.12/site-packages/scipy/fft/_duccfft/__init__.py b/.venv/lib/python3.12/site-packages/scipy/fft/_duccfft/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..b79a31f43c34521c281d18cc9f722d04eaa6e2ed
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/fft/_duccfft/__init__.py
@@ -0,0 +1,9 @@
+""" FFT backend using pyduccfft """
+
+from .basic import *
+from .realtransforms import *
+from .helper import *
+
+from scipy._lib._testutils import PytestTester
+test = PytestTester(__name__)
+del PytestTester
diff --git a/.venv/lib/python3.12/site-packages/scipy/fft/_duccfft/__pycache__/__init__.cpython-312.pyc b/.venv/lib/python3.12/site-packages/scipy/fft/_duccfft/__pycache__/__init__.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..40efed1d477f5bc42568a69961195197dba15289
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/scipy/fft/_duccfft/__pycache__/__init__.cpython-312.pyc differ
diff --git a/.venv/lib/python3.12/site-packages/scipy/fft/_duccfft/__pycache__/basic.cpython-312.pyc b/.venv/lib/python3.12/site-packages/scipy/fft/_duccfft/__pycache__/basic.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..0a3cf019a62a28db6ccfc0182549d3981bd44456
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/scipy/fft/_duccfft/__pycache__/basic.cpython-312.pyc differ
diff --git a/.venv/lib/python3.12/site-packages/scipy/fft/_duccfft/__pycache__/helper.cpython-312.pyc b/.venv/lib/python3.12/site-packages/scipy/fft/_duccfft/__pycache__/helper.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..4170aca710e99a09e6e9e498bf948a0c2ae5f5cf
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/scipy/fft/_duccfft/__pycache__/helper.cpython-312.pyc differ
diff --git a/.venv/lib/python3.12/site-packages/scipy/fft/_duccfft/__pycache__/realtransforms.cpython-312.pyc b/.venv/lib/python3.12/site-packages/scipy/fft/_duccfft/__pycache__/realtransforms.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..bf29f9b6c8753bb2a25a1b59bc963bd5a1979ef3
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/scipy/fft/_duccfft/__pycache__/realtransforms.cpython-312.pyc differ
diff --git a/.venv/lib/python3.12/site-packages/scipy/fft/_duccfft/basic.py b/.venv/lib/python3.12/site-packages/scipy/fft/_duccfft/basic.py
new file mode 100644
index 0000000000000000000000000000000000000000..8b80a03e075f1847a1df070aea2861ca2edd2bcf
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/fft/_duccfft/basic.py
@@ -0,0 +1,251 @@
+"""
+Discrete Fourier Transforms - basic.py
+"""
+import numpy as np
+import functools
+from . import pyduccfft as pfft
+from .helper import (_asfarray, _init_nd_shape_and_axes, _datacopied,
+                     _fix_shape, _fix_shape_1d, _normalization,
+                     _workers)
+
+def c2c(forward, x, n=None, axis=-1, norm=None, overwrite_x=False,
+        workers=None, *, plan=None):
+    """ Return discrete Fourier transform of real or complex sequence. """
+    if plan is not None:
+        raise NotImplementedError('Passing a precomputed plan is not yet '
+                                  'supported by scipy.fft functions')
+    tmp = _asfarray(x)
+    overwrite_x = overwrite_x or _datacopied(tmp, x)
+    norm = _normalization(norm, forward)
+    workers = _workers(workers)
+
+    if n is not None:
+        tmp, copied = _fix_shape_1d(tmp, n, axis)
+        overwrite_x = overwrite_x or copied
+    elif tmp.shape[axis] < 1:
+        message = f"invalid number of data points ({tmp.shape[axis]}) specified"
+        raise ValueError(message)
+
+    out = (tmp if overwrite_x and tmp.dtype.kind == 'c' else None)
+
+    return pfft.c2c(tmp, (axis,), forward, norm, out, workers)
+
+
+fft = functools.partial(c2c, True)
+fft.__name__ = 'fft'  # pyrefly:ignore[missing-attribute]
+ifft = functools.partial(c2c, False)
+ifft.__name__ = 'ifft'  # pyrefly:ignore[missing-attribute]
+
+
+def r2c(forward, x, n=None, axis=-1, norm=None, overwrite_x=False,
+        workers=None, *, plan=None):
+    """
+    Discrete Fourier transform of a real sequence.
+    """
+    if plan is not None:
+        raise NotImplementedError('Passing a precomputed plan is not yet '
+                                  'supported by scipy.fft functions')
+    tmp = _asfarray(x)
+    norm = _normalization(norm, forward)
+    workers = _workers(workers)
+
+    if not np.isrealobj(tmp):
+        raise TypeError("x must be a real sequence")
+
+    if n is not None:
+        tmp, _ = _fix_shape_1d(tmp, n, axis)
+    elif tmp.shape[axis] < 1:
+        raise ValueError(f"invalid number of data points ({tmp.shape[axis]}) specified")
+
+    # Note: overwrite_x is not utilised
+    return pfft.r2c(tmp, (axis,), forward, norm, None, workers)
+
+
+rfft = functools.partial(r2c, True)
+rfft.__name__ = 'rfft'  # pyrefly:ignore[missing-attribute]
+ihfft = functools.partial(r2c, False)
+ihfft.__name__ = 'ihfft'  # pyrefly:ignore[missing-attribute]
+
+
+def c2r(forward, x, n=None, axis=-1, norm=None, overwrite_x=False,
+        workers=None, *, plan=None):
+    """
+    Return inverse discrete Fourier transform of real sequence x.
+    """
+    if plan is not None:
+        raise NotImplementedError('Passing a precomputed plan is not yet '
+                                  'supported by scipy.fft functions')
+    tmp = _asfarray(x)
+    norm = _normalization(norm, forward)
+    workers = _workers(workers)
+
+    # TODO: Optimize for hermitian and real?
+    if np.isrealobj(tmp):
+        tmp = tmp + 0.j
+
+    # Last axis utilizes hermitian symmetry
+    if n is None:
+        n = (tmp.shape[axis] - 1) * 2
+        if n < 1:
+            raise ValueError(f"Invalid number of data points ({n}) specified")
+    else:
+        tmp, _ = _fix_shape_1d(tmp, (n//2) + 1, axis)
+
+    # Note: overwrite_x is not utilized
+    return pfft.c2r(tmp, (axis,), n, forward, norm, None, workers)
+
+
+hfft = functools.partial(c2r, True)
+hfft.__name__ = 'hfft'  # pyrefly:ignore[missing-attribute]
+irfft = functools.partial(c2r, False)
+irfft.__name__ = 'irfft'  # pyrefly:ignore[missing-attribute]
+
+
+def hfft2(x, s=None, axes=(-2,-1), norm=None, overwrite_x=False, workers=None,
+          *, plan=None):
+    """
+    2-D discrete Fourier transform of a Hermitian sequence
+    """
+    if plan is not None:
+        raise NotImplementedError('Passing a precomputed plan is not yet '
+                                  'supported by scipy.fft functions')
+    return hfftn(x, s, axes, norm, overwrite_x, workers)
+
+
+def ihfft2(x, s=None, axes=(-2,-1), norm=None, overwrite_x=False, workers=None,
+           *, plan=None):
+    """
+    2-D discrete inverse Fourier transform of a Hermitian sequence
+    """
+    if plan is not None:
+        raise NotImplementedError('Passing a precomputed plan is not yet '
+                                  'supported by scipy.fft functions')
+    return ihfftn(x, s, axes, norm, overwrite_x, workers)
+
+
+def c2cn(forward, x, s=None, axes=None, norm=None, overwrite_x=False,
+         workers=None, *, plan=None):
+    """
+    Return multidimensional discrete Fourier transform.
+    """
+    if plan is not None:
+        raise NotImplementedError('Passing a precomputed plan is not yet '
+                                  'supported by scipy.fft functions')
+    tmp = _asfarray(x)
+
+    shape, axes = _init_nd_shape_and_axes(tmp, s, axes)
+    overwrite_x = overwrite_x or _datacopied(tmp, x)
+    workers = _workers(workers)
+
+    if len(axes) == 0:
+        return x
+
+    tmp, copied = _fix_shape(tmp, shape, axes)
+    overwrite_x = overwrite_x or copied
+
+    norm = _normalization(norm, forward)
+    out = (tmp if overwrite_x and tmp.dtype.kind == 'c' else None)
+
+    return pfft.c2c(tmp, axes, forward, norm, out, workers)
+
+
+fftn = functools.partial(c2cn, True)
+fftn.__name__ = 'fftn'  # pyrefly:ignore[missing-attribute]
+ifftn = functools.partial(c2cn, False)
+ifftn.__name__ = 'ifftn'  # pyrefly:ignore[missing-attribute]
+
+def r2cn(forward, x, s=None, axes=None, norm=None, overwrite_x=False,
+         workers=None, *, plan=None):
+    """Return multidimensional discrete Fourier transform of real input"""
+    if plan is not None:
+        raise NotImplementedError('Passing a precomputed plan is not yet '
+                                  'supported by scipy.fft functions')
+    tmp = _asfarray(x)
+
+    if not np.isrealobj(tmp):
+        raise TypeError("x must be a real sequence")
+
+    shape, axes = _init_nd_shape_and_axes(tmp, s, axes)
+    tmp, _ = _fix_shape(tmp, shape, axes)
+    norm = _normalization(norm, forward)
+    workers = _workers(workers)
+
+    if len(axes) == 0:
+        raise ValueError("at least 1 axis must be transformed")
+
+    # Note: overwrite_x is not utilized
+    return pfft.r2c(tmp, axes, forward, norm, None, workers)
+
+
+rfftn = functools.partial(r2cn, True)
+rfftn.__name__ = 'rfftn'  # pyrefly:ignore[missing-attribute]
+ihfftn = functools.partial(r2cn, False)
+ihfftn.__name__ = 'ihfftn'  # pyrefly:ignore[missing-attribute]
+
+
+def c2rn(forward, x, s=None, axes=None, norm=None, overwrite_x=False,
+         workers=None, *, plan=None):
+    """Multidimensional inverse discrete fourier transform with real output"""
+    if plan is not None:
+        raise NotImplementedError('Passing a precomputed plan is not yet '
+                                  'supported by scipy.fft functions')
+    tmp = _asfarray(x)
+
+    # TODO: Optimize for hermitian and real?
+    if np.isrealobj(tmp):
+        tmp = tmp + 0.j
+
+    noshape = s is None
+    shape, axes = _init_nd_shape_and_axes(tmp, s, axes)
+
+    if len(axes) == 0:
+        raise ValueError("at least 1 axis must be transformed")
+
+    shape = list(shape)
+    if noshape:
+        shape[-1] = (x.shape[axes[-1]] - 1) * 2
+
+    norm = _normalization(norm, forward)
+    workers = _workers(workers)
+
+    # Last axis utilizes hermitian symmetry
+    lastsize = shape[-1]
+    shape[-1] = (shape[-1] // 2) + 1
+
+    tmp, _ = tuple(_fix_shape(tmp, shape, axes))
+
+    # Note: overwrite_x is not utilized
+    return pfft.c2r(tmp, axes, lastsize, forward, norm, None, workers)
+
+
+hfftn = functools.partial(c2rn, True)
+hfftn.__name__ = 'hfftn'  # pyrefly:ignore[missing-attribute]
+irfftn = functools.partial(c2rn, False)
+irfftn.__name__ = 'irfftn'  # pyrefly:ignore[missing-attribute]
+
+
+def r2r_fftpack(forward, x, n=None, axis=-1, norm=None, overwrite_x=False):
+    """FFT of a real sequence, returning fftpack half complex format"""
+    tmp = _asfarray(x)
+    overwrite_x = overwrite_x or _datacopied(tmp, x)
+    norm = _normalization(norm, forward)
+    workers = _workers(None)
+
+    if tmp.dtype.kind == 'c':
+        raise TypeError('x must be a real sequence')
+
+    if n is not None:
+        tmp, copied = _fix_shape_1d(tmp, n, axis)
+        overwrite_x = overwrite_x or copied
+    elif tmp.shape[axis] < 1:
+        raise ValueError(f"invalid number of data points ({tmp.shape[axis]}) specified")
+
+    out = (tmp if overwrite_x else None)
+
+    return pfft.r2r_fftpack(tmp, (axis,), forward, forward, norm, out, workers)
+
+
+rfft_fftpack = functools.partial(r2r_fftpack, True)
+rfft_fftpack.__name__ = 'rfft_fftpack'  # pyrefly:ignore[missing-attribute]
+irfft_fftpack = functools.partial(r2r_fftpack, False)
+irfft_fftpack.__name__ = 'irfft_fftpack'  # pyrefly:ignore[missing-attribute]
diff --git a/.venv/lib/python3.12/site-packages/scipy/fft/_duccfft/helper.py b/.venv/lib/python3.12/site-packages/scipy/fft/_duccfft/helper.py
new file mode 100644
index 0000000000000000000000000000000000000000..48ba8ca677c4de16c7f6759167d95bc2ed4b9b80
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/fft/_duccfft/helper.py
@@ -0,0 +1,257 @@
+from numbers import Number
+import operator
+import os
+import threading
+import contextlib
+
+import numpy as np
+
+from scipy._lib._util import copy_if_needed
+from scipy._lib._array_api import xp_capabilities
+
+# good_size is exposed (and used) from this import
+from .pyduccfft import good_size, prev_good_size
+
+
+__all__ = ['good_size', 'prev_good_size', 'set_workers', 'get_workers']
+
+_config = threading.local()
+_cpu_count = os.cpu_count()
+
+
+def _iterable_of_int(x, name=None):
+    """Convert ``x`` to an iterable sequence of int
+
+    Parameters
+    ----------
+    x : value, or sequence of values, convertible to int
+    name : str, optional
+        Name of the argument being converted, only used in the error message
+
+    Returns
+    -------
+    y : ``list[int]``
+    """
+    if isinstance(x, Number):
+        x = (x,)
+
+    try:
+        x = [operator.index(a) for a in x]
+    except TypeError as e:
+        name = name or "value"
+        raise ValueError(f"{name} must be a scalar or iterable of integers") from e
+
+    return x
+
+
+def _init_nd_shape_and_axes(x, shape, axes):
+    """
+    Handle shape and axes arguments for N-D transforms.
+
+    Returns the shape and axes in a standard form, taking into account negative
+    values and checking for various potential errors.
+
+    Parameters
+    ----------
+    x : ndarray
+        The input array.
+    shape : int or array_like of ints or None
+        The shape of the result. If both `shape` and `axes` (see below) are
+        None, `shape` is ``x.shape``; if `shape` is None but `axes` is
+        not None, then `shape` is ``numpy.take(x.shape, axes, axis=0)``.
+        If `shape` is -1, the size of the corresponding dimension of `x` is
+        used.
+    axes : int or array_like of ints or None
+        Axes along which the calculation is computed.
+        The default is over all axes.
+        Negative indices are automatically converted to their positive
+        counterparts.
+
+    Returns
+    -------
+    shape : tuple
+        The shape of the result as a tuple of integers.
+    axes : list
+        Axes along which the calculation is computed, as a list of integers.
+    """
+    noshape = shape is None
+    noaxes = axes is None
+
+    if not noaxes:
+        axes = _iterable_of_int(axes, 'axes')
+        axes = [a + x.ndim if a < 0 else a for a in axes]
+
+        if any(a >= x.ndim or a < 0 for a in axes):
+            raise ValueError("axes exceeds dimensionality of input")
+        if len(set(axes)) != len(axes):
+            raise ValueError("all axes must be unique")
+
+    if not noshape:
+        shape = _iterable_of_int(shape, 'shape')
+
+        if axes and len(axes) != len(shape):
+            raise ValueError("when given, axes and shape arguments"
+                             " have to be of the same length")
+        if noaxes:
+            if len(shape) > x.ndim:
+                raise ValueError("shape requires more axes than are present")
+            axes = range(x.ndim - len(shape), x.ndim)
+
+        shape = [x.shape[a] if s == -1 else s for s, a in zip(shape, axes)]
+    elif noaxes:
+        shape = list(x.shape)
+        axes = range(x.ndim)
+    else:
+        shape = [x.shape[a] for a in axes]
+
+    if any(s < 1 for s in shape):
+        raise ValueError(
+            f"invalid number of data points ({shape}) specified")
+
+    return tuple(shape), list(axes)
+
+
+def _asfarray(x):
+    """
+    Convert to array with floating or complex dtype.
+
+    float16 values are also promoted to float32.
+    """
+    if not hasattr(x, "dtype"):
+        x = np.asarray(x)
+
+    if x.dtype == np.float16:
+        return np.asarray(x, np.float32)
+    elif x.dtype.kind not in 'fc':
+        return np.asarray(x, np.float64)
+
+    # Require native byte order
+    dtype = x.dtype.newbyteorder('=')
+    # Always align input
+    copy = True if not x.flags['ALIGNED'] else copy_if_needed
+    return np.array(x, dtype=dtype, copy=copy)
+
+def _datacopied(arr, original):
+    """
+    Strict check for `arr` not sharing any data with `original`,
+    under the assumption that arr = asarray(original)
+    """
+    if arr is original:
+        return False
+    if not isinstance(original, np.ndarray) and hasattr(original, '__array__'):
+        return False
+    return arr.base is None
+
+
+def _fix_shape(x, shape, axes):
+    """Internal auxiliary function for _raw_fft, _raw_fftnd."""
+    must_copy = False
+
+    # Build an nd slice with the dimensions to be read from x
+    index = [slice(None)]*x.ndim
+    for n, ax in zip(shape, axes):
+        if x.shape[ax] >= n:
+            index[ax] = slice(0, n)
+        else:
+            index[ax] = slice(0, x.shape[ax])
+            must_copy = True
+
+    index = tuple(index)
+
+    if not must_copy:
+        return x[index], False
+
+    s = list(x.shape)
+    for n, axis in zip(shape, axes):
+        s[axis] = n
+
+    z = np.zeros(s, x.dtype)
+    z[index] = x[index]
+    return z, True
+
+
+def _fix_shape_1d(x, n, axis):
+    if n < 1:
+        raise ValueError(
+            f"invalid number of data points ({n}) specified")
+
+    return _fix_shape(x, (n,), (axis,))
+
+
+_NORM_MAP = {None: 0, 'backward': 0, 'ortho': 1, 'forward': 2}
+
+
+def _normalization(norm, forward):
+    """Returns the pyduccfft normalization mode from the norm argument"""
+    try:
+        inorm = _NORM_MAP[norm]
+        return inorm if forward else (2 - inorm)
+    except KeyError:
+        raise ValueError(
+            f'Invalid norm value {norm!r}, should '
+            'be "backward", "ortho" or "forward"') from None
+
+
+def _workers(workers):
+    if workers is None:
+        return getattr(_config, 'default_workers', 1)
+
+    if workers < 0:
+        if workers >= -_cpu_count:
+            workers += 1 + _cpu_count
+        else:
+            raise ValueError(f"workers value out of range; got {workers}, must not be"
+                             f" less than {-_cpu_count}")
+    elif workers == 0:
+        raise ValueError("workers must not be zero")
+
+    return workers
+
+
+@xp_capabilities(out_of_scope=True)
+@contextlib.contextmanager
+def set_workers(workers):
+    """Context manager for the default number of workers used in `scipy.fft`.
+
+    Parameters
+    ----------
+    workers : int
+        The default number of workers to use
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy import fft, signal
+    >>> rng = np.random.default_rng()
+    >>> x = rng.standard_normal((128, 64))
+    >>> with fft.set_workers(4):
+    ...     y = signal.fftconvolve(x, x)
+
+    """  # numpydoc ignore=YD01
+    old_workers = get_workers()
+    _config.default_workers = _workers(operator.index(workers))
+    try:
+        yield
+    finally:
+        _config.default_workers = old_workers
+
+
+@xp_capabilities(out_of_scope=True)
+def get_workers():
+    """Returns the default number of workers within the current context.
+
+    Returns
+    -------
+    n_workers : int
+        The default number of workers
+
+    Examples
+    --------
+    >>> from scipy import fft
+    >>> fft.get_workers()
+    1
+    >>> with fft.set_workers(4):
+    ...     fft.get_workers()
+    4
+    """
+    return getattr(_config, 'default_workers', 1)
diff --git a/.venv/lib/python3.12/site-packages/scipy/fft/_duccfft/pyduccfft.cpython-312-x86_64-linux-gnu.so b/.venv/lib/python3.12/site-packages/scipy/fft/_duccfft/pyduccfft.cpython-312-x86_64-linux-gnu.so
new file mode 100644
index 0000000000000000000000000000000000000000..9c1e331e16f217b07a091b7315eb3a0beab8ebab
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/fft/_duccfft/pyduccfft.cpython-312-x86_64-linux-gnu.so
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:37411194f8151a3535904980eefcb60a3a2a3b0a240d1cbda3f73e7a86ff5904
+size 2389288
diff --git a/.venv/lib/python3.12/site-packages/scipy/fft/_duccfft/realtransforms.py b/.venv/lib/python3.12/site-packages/scipy/fft/_duccfft/realtransforms.py
new file mode 100644
index 0000000000000000000000000000000000000000..d90663a7f75032d4396357a8ec335f78a12a8b5a
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/fft/_duccfft/realtransforms.py
@@ -0,0 +1,109 @@
+import numpy as np
+from . import pyduccfft as pfft
+from .helper import (_asfarray, _init_nd_shape_and_axes, _datacopied,
+                     _fix_shape, _fix_shape_1d, _normalization, _workers)
+import functools
+
+
+def _r2r(forward, transform, x, type=2, n=None, axis=-1, norm=None,
+         overwrite_x=False, workers=None, orthogonalize=None):
+    """Forward or backward 1-D DCT/DST
+
+    Parameters
+    ----------
+    forward : bool
+        Transform direction (determines type and normalisation)
+    transform : {pyduccfft.dct, pyduccfft.dst}
+        The transform to perform
+    """
+    tmp = _asfarray(x)
+    overwrite_x = overwrite_x or _datacopied(tmp, x)
+    norm = _normalization(norm, forward)
+    workers = _workers(workers)
+
+    if not forward:
+        if type == 2:
+            type = 3
+        elif type == 3:
+            type = 2
+
+    if n is not None:
+        tmp, copied = _fix_shape_1d(tmp, n, axis)
+        overwrite_x = overwrite_x or copied
+    elif tmp.shape[axis] < 1:
+        raise ValueError(f"invalid number of data points ({tmp.shape[axis]}) specified")
+
+    out = (tmp if overwrite_x else None)
+
+    # For complex input, transform real and imaginary components separably
+    if np.iscomplexobj(x):
+        out = np.empty_like(tmp) if out is None else out
+        transform(tmp.real, type, (axis,), norm, out.real, workers)
+        transform(tmp.imag, type, (axis,), norm, out.imag, workers)
+        return out
+
+    return transform(tmp, type, (axis,), norm, out, workers, orthogonalize)
+
+
+dct = functools.partial(_r2r, True, pfft.dct)
+dct.__name__ = 'dct'  # pyrefly:ignore[missing-attribute]
+idct = functools.partial(_r2r, False, pfft.dct)
+idct.__name__ = 'idct'  # pyrefly:ignore[missing-attribute]
+
+dst = functools.partial(_r2r, True, pfft.dst)
+dst.__name__ = 'dst'  # pyrefly:ignore[missing-attribute]
+idst = functools.partial(_r2r, False, pfft.dst)
+idst.__name__ = 'idst'  # pyrefly:ignore[missing-attribute]
+
+
+def _r2rn(forward, transform, x, type=2, s=None, axes=None, norm=None,
+          overwrite_x=False, workers=None, orthogonalize=None):
+    """Forward or backward nd DCT/DST
+
+    Parameters
+    ----------
+    forward : bool
+        Transform direction (determines type and normalisation)
+    transform : {pyduccfft.dct, pyduccfft.dst}
+        The transform to perform
+    """
+    tmp = _asfarray(x)
+
+    shape, axes = _init_nd_shape_and_axes(tmp, s, axes)
+    overwrite_x = overwrite_x or _datacopied(tmp, x)
+
+    if len(axes) == 0:
+        return x
+
+    tmp, copied = _fix_shape(tmp, shape, axes)
+    overwrite_x = overwrite_x or copied
+
+    if not forward:
+        if type == 2:
+            type = 3
+        elif type == 3:
+            type = 2
+
+    norm = _normalization(norm, forward)
+    workers = _workers(workers)
+    out = (tmp if overwrite_x else None)
+
+    # For complex input, transform real and imaginary components separably
+    if np.iscomplexobj(x):
+        out = np.empty_like(tmp) if out is None else out
+        transform(tmp.real, type, axes, norm, out.real, workers)
+        transform(tmp.imag, type, axes, norm, out.imag, workers)
+        return out
+
+    return transform(tmp, type, axes, norm, out, workers, orthogonalize)
+
+
+dctn = functools.partial(_r2rn, True, pfft.dct)
+dctn.__name__ = 'dctn'  # pyrefly:ignore[missing-attribute]
+idctn = functools.partial(_r2rn, False, pfft.dct)
+idctn.__name__ = 'idctn'  # pyrefly:ignore[missing-attribute]
+
+dstn = functools.partial(_r2rn, True, pfft.dst)
+dstn.__name__ = 'dstn'  # pyrefly:ignore[missing-attribute]
+idstn = functools.partial(_r2rn, False, pfft.dst)
+idstn.__name__ = 'idstn'  # pyrefly:ignore[missing-attribute]
diff --git a/.venv/lib/python3.12/site-packages/scipy/fft/_duccfft/tests/__init__.py b/.venv/lib/python3.12/site-packages/scipy/fft/_duccfft/tests/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/.venv/lib/python3.12/site-packages/scipy/fft/_duccfft/tests/test_basic.py b/.venv/lib/python3.12/site-packages/scipy/fft/_duccfft/tests/test_basic.py
new file mode 100644
index 0000000000000000000000000000000000000000..3c9d83561e4c128281735b7305d372d69890ae26
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/fft/_duccfft/tests/test_basic.py
@@ -0,0 +1,1011 @@
+# Created by Pearu Peterson, September 2002
+
+from numpy.testing import (assert_, assert_equal, assert_array_almost_equal,
+                           assert_array_almost_equal_nulp, assert_array_less,
+                           assert_allclose)
+import pytest
+from pytest import raises as assert_raises
+from scipy.fft._duccfft import (ifft, fft, fftn, ifftn,
+                                rfft, irfft, rfftn, irfftn,
+                                hfft, ihfft, hfftn, ihfftn)
+
+from numpy import (arange, array, asarray, zeros, dot, exp, pi,
+                   swapaxes, cdouble)
+import numpy as np
+import numpy.fft
+from numpy.random import rand
+
+# "large" composite numbers supported by FFT._PYDUCCFFT
+LARGE_COMPOSITE_SIZES = [
+    2**13,
+    2**5 * 3**5,
+    2**3 * 3**3 * 5**2,
+]
+SMALL_COMPOSITE_SIZES = [
+    2,
+    2*3*5,
+    2*2*3*3,
+]
+# prime
+LARGE_PRIME_SIZES = [
+    2011
+]
+SMALL_PRIME_SIZES = [
+    29
+]
+
+
+def _assert_close_in_norm(x, y, rtol, size, rdt):
+    # helper function for testing
+    err_msg = f"size: {size}  rdt: {rdt}"
+    assert_array_less(np.linalg.norm(x - y), rtol*np.linalg.norm(x), err_msg)
+
+
+def random(size):
+    return rand(*size)
+
+def swap_byteorder(arr):
+    """Returns the same array with swapped byteorder"""
+    dtype = arr.dtype.newbyteorder('S')
+    return arr.astype(dtype)
+
+def direct_dft(x):
+    x = asarray(x)
+    n = len(x)
+    y = zeros(n, dtype=cdouble)
+    w = -arange(n)*(2j*pi/n)
+    for i in range(n):
+        y[i] = dot(exp(i*w), x)
+    return y
+
+
+def direct_idft(x):
+    x = asarray(x)
+    n = len(x)
+    y = zeros(n, dtype=cdouble)
+    w = arange(n)*(2j*pi/n)
+    for i in range(n):
+        y[i] = dot(exp(i*w), x)/n
+    return y
+
+
+def direct_dftn(x):
+    x = asarray(x)
+    for axis in range(x.ndim):
+        x = fft(x, axis=axis)
+    return x
+
+
+def direct_idftn(x):
+    x = asarray(x)
+    for axis in range(x.ndim):
+        x = ifft(x, axis=axis)
+    return x
+
+
+def direct_rdft(x):
+    x = asarray(x)
+    n = len(x)
+    w = -arange(n)*(2j*pi/n)
+    y = zeros(n//2+1, dtype=cdouble)
+    for i in range(n//2+1):
+        y[i] = dot(exp(i*w), x)
+    return y
+
+
+def direct_irdft(x, n):
+    x = asarray(x)
+    x1 = zeros(n, dtype=cdouble)
+    for i in range(n//2+1):
+        x1[i] = x[i]
+        if i > 0 and 2*i < n:
+            x1[n-i] = np.conj(x[i])
+    return direct_idft(x1).real
+
+
+def direct_rdftn(x):
+    return fftn(rfft(x), axes=range(x.ndim - 1))
+
+
+class _TestFFTBase:
+    def setup_method(self):
+        self.cdt = None
+        self.rdt = None
+        np.random.seed(1234)
+
+    def test_definition(self):
+        x = np.array([1,2,3,4+1j,1,2,3,4+2j], dtype=self.cdt)
+        y = fft(x)
+        assert_equal(y.dtype, self.cdt)
+        y1 = direct_dft(x)
+        assert_array_almost_equal(y,y1)
+        x = np.array([1,2,3,4+0j,5], dtype=self.cdt)
+        assert_array_almost_equal(fft(x),direct_dft(x))
+
+    def test_n_argument_real(self):
+        x1 = np.array([1,2,3,4], dtype=self.rdt)
+        x2 = np.array([1,2,3,4], dtype=self.rdt)
+        y = fft([x1,x2],n=4)
+        assert_equal(y.dtype, self.cdt)
+        assert_equal(y.shape,(2,4))
+        assert_array_almost_equal(y[0],direct_dft(x1))
+        assert_array_almost_equal(y[1],direct_dft(x2))
+
+    def _test_n_argument_complex(self):
+        x1 = np.array([1,2,3,4+1j], dtype=self.cdt)
+        x2 = np.array([1,2,3,4+1j], dtype=self.cdt)
+        y = fft([x1,x2],n=4)
+        assert_equal(y.dtype, self.cdt)
+        assert_equal(y.shape,(2,4))
+        assert_array_almost_equal(y[0],direct_dft(x1))
+        assert_array_almost_equal(y[1],direct_dft(x2))
+
+    def test_djbfft(self):
+        for i in range(2,14):
+            n = 2**i
+            x = np.arange(n)
+            y = fft(x.astype(complex))
+            y2 = numpy.fft.fft(x)
+            assert_array_almost_equal(y,y2)
+            y = fft(x)
+            assert_array_almost_equal(y,y2)
+
+    def test_invalid_sizes(self):
+        assert_raises(ValueError, fft, [])
+        assert_raises(ValueError, fft, [[1,1],[2,2]], -5)
+
+
+class TestLongDoubleFFT(_TestFFTBase):
+    def setup_method(self):
+        self.cdt = np.clongdouble
+        self.rdt = np.longdouble
+
+
+class TestDoubleFFT(_TestFFTBase):
+    def setup_method(self):
+        self.cdt = np.cdouble
+        self.rdt = np.float64
+
+
+class TestSingleFFT(_TestFFTBase):
+    def setup_method(self):
+        self.cdt = np.complex64
+        self.rdt = np.float32
+
+
+class TestFloat16FFT:
+
+    def test_1_argument_real(self):
+        x1 = np.array([1, 2, 3, 4], dtype=np.float16)
+        y = fft(x1, n=4)
+        assert_equal(y.dtype, np.complex64)
+        assert_equal(y.shape, (4, ))
+        assert_array_almost_equal(y, direct_dft(x1.astype(np.float32)))
+
+    def test_n_argument_real(self):
+        x1 = np.array([1, 2, 3, 4], dtype=np.float16)
+        x2 = np.array([1, 2, 3, 4], dtype=np.float16)
+        y = fft([x1, x2], n=4)
+        assert_equal(y.dtype, np.complex64)
+        assert_equal(y.shape, (2, 4))
+        assert_array_almost_equal(y[0], direct_dft(x1.astype(np.float32)))
+        assert_array_almost_equal(y[1], direct_dft(x2.astype(np.float32)))
+
+
+class _TestIFFTBase:
+    def setup_method(self):
+        np.random.seed(1234)
+
+    def test_definition(self):
+        x = np.array([1,2,3,4+1j,1,2,3,4+2j], self.cdt)
+        y = ifft(x)
+        y1 = direct_idft(x)
+        assert_equal(y.dtype, self.cdt)
+        assert_array_almost_equal(y,y1)
+
+        x = np.array([1,2,3,4+0j,5], self.cdt)
+        assert_array_almost_equal(ifft(x),direct_idft(x))
+
+    def test_definition_real(self):
+        x = np.array([1,2,3,4,1,2,3,4], self.rdt)
+        y = ifft(x)
+        assert_equal(y.dtype, self.cdt)
+        y1 = direct_idft(x)
+        assert_array_almost_equal(y,y1)
+
+        x = np.array([1,2,3,4,5], dtype=self.rdt)
+        assert_equal(y.dtype, self.cdt)
+        assert_array_almost_equal(ifft(x),direct_idft(x))
+
+    def test_djbfft(self):
+        for i in range(2,14):
+            n = 2**i
+            x = np.arange(n)
+            y = ifft(x.astype(self.cdt))
+            y2 = numpy.fft.ifft(x.astype(self.cdt))
+            assert_allclose(y,y2, rtol=self.rtol, atol=self.atol)
+            y = ifft(x)
+            assert_allclose(y,y2, rtol=self.rtol, atol=self.atol)
+
+    def test_random_complex(self):
+        for size in [1,51,111,100,200,64,128,256,1024]:
+            x = random([size]).astype(self.cdt)
+            x = random([size]).astype(self.cdt) + 1j*x
+            y1 = ifft(fft(x))
+            y2 = fft(ifft(x))
+            assert_equal(y1.dtype, self.cdt)
+            assert_equal(y2.dtype, self.cdt)
+            assert_array_almost_equal(y1, x)
+            assert_array_almost_equal(y2, x)
+
+    def test_random_real(self):
+        for size in [1,51,111,100,200,64,128,256,1024]:
+            x = random([size]).astype(self.rdt)
+            y1 = ifft(fft(x))
+            y2 = fft(ifft(x))
+            assert_equal(y1.dtype, self.cdt)
+            assert_equal(y2.dtype, self.cdt)
+            assert_array_almost_equal(y1, x)
+            assert_array_almost_equal(y2, x)
+
+    def test_size_accuracy(self):
+        # Sanity check for the accuracy for prime and non-prime sized inputs
+        for size in LARGE_COMPOSITE_SIZES + LARGE_PRIME_SIZES:
+            np.random.seed(1234)
+            x = np.random.rand(size).astype(self.rdt)
+            y = ifft(fft(x))
+            _assert_close_in_norm(x, y, self.rtol, size, self.rdt)
+            y = fft(ifft(x))
+            _assert_close_in_norm(x, y, self.rtol, size, self.rdt)
+
+            x = (x + 1j*np.random.rand(size)).astype(self.cdt)
+            y = ifft(fft(x))
+            _assert_close_in_norm(x, y, self.rtol, size, self.rdt)
+            y = fft(ifft(x))
+            _assert_close_in_norm(x, y, self.rtol, size, self.rdt)
+
+    def test_invalid_sizes(self):
+        assert_raises(ValueError, ifft, [])
+        assert_raises(ValueError, ifft, [[1,1],[2,2]], -5)
+
+
+@pytest.mark.skipif(np.longdouble is np.float64,
+                    reason="Long double is aliased to double")
+class TestLongDoubleIFFT(_TestIFFTBase):
+    def setup_method(self):
+        self.cdt = np.clongdouble
+        self.rdt = np.longdouble
+        self.rtol = 1e-10
+        self.atol = 1e-10
+
+
+class TestDoubleIFFT(_TestIFFTBase):
+    def setup_method(self):
+        self.cdt = np.complex128
+        self.rdt = np.float64
+        self.rtol = 1e-10
+        self.atol = 1e-10
+
+
+class TestSingleIFFT(_TestIFFTBase):
+    def setup_method(self):
+        self.cdt = np.complex64
+        self.rdt = np.float32
+        self.rtol = 1e-5
+        self.atol = 1.5e-4
+
+
+class _TestRFFTBase:
+    def setup_method(self):
+        np.random.seed(1234)
+
+    def test_definition(self):
+        for t in [[1, 2, 3, 4, 1, 2, 3, 4], [1, 2, 3, 4, 1, 2, 3, 4, 5]]:
+            x = np.array(t, dtype=self.rdt)
+            y = rfft(x)
+            y1 = direct_rdft(x)
+            assert_array_almost_equal(y,y1)
+            assert_equal(y.dtype, self.cdt)
+
+    def test_djbfft(self):
+        for i in range(2,14):
+            n = 2**i
+            x = np.arange(n)
+            y1 = np.fft.rfft(x)
+            y = rfft(x)
+            assert_array_almost_equal(y,y1)
+
+    def test_invalid_sizes(self):
+        assert_raises(ValueError, rfft, [])
+        assert_raises(ValueError, rfft, [[1,1],[2,2]], -5)
+
+    def test_complex_input(self):
+        x = np.zeros(10, dtype=self.cdt)
+        with assert_raises(TypeError, match="x must be a real sequence"):
+            rfft(x)
+
+    # See gh-5790
+    class MockSeries:
+        def __init__(self, data):
+            self.data = np.asarray(data)
+
+        def __getattr__(self, item):
+            try:
+                return getattr(self.data, item)
+            except AttributeError as e:
+                raise AttributeError("'MockSeries' object "
+                                      f"has no attribute '{item}'") from e
+
+    def test_non_ndarray_with_dtype(self):
+        x = np.array([1., 2., 3., 4., 5.])
+        xs = _TestRFFTBase.MockSeries(x)
+
+        expected = [1, 2, 3, 4, 5]
+        rfft(xs)
+
+        # Data should not have been overwritten
+        assert_equal(x, expected)
+        assert_equal(xs.data, expected)
+
+@pytest.mark.skipif(np.longdouble is np.float64,
+                    reason="Long double is aliased to double")
+class TestRFFTLongDouble(_TestRFFTBase):
+    def setup_method(self):
+        self.cdt = np.clongdouble
+        self.rdt = np.longdouble
+
+
+class TestRFFTDouble(_TestRFFTBase):
+    def setup_method(self):
+        self.cdt = np.complex128
+        self.rdt = np.float64
+
+
+class TestRFFTSingle(_TestRFFTBase):
+    def setup_method(self):
+        self.cdt = np.complex64
+        self.rdt = np.float32
+
+
+class _TestIRFFTBase:
+    def setup_method(self):
+        np.random.seed(1234)
+
+    def test_definition(self):
+        x1 = [1,2+3j,4+1j,1+2j,3+4j]
+        x1_1 = [1,2+3j,4+1j,2+3j,4,2-3j,4-1j,2-3j]
+        x1 = x1_1[:5]
+        x2_1 = [1,2+3j,4+1j,2+3j,4+5j,4-5j,2-3j,4-1j,2-3j]
+        x2 = x2_1[:5]
+
+        def _test(x, xr):
+            y = irfft(np.array(x, dtype=self.cdt), n=len(xr))
+            y1 = direct_irdft(x, len(xr))
+            assert_equal(y.dtype, self.rdt)
+            assert_array_almost_equal(y,y1, decimal=self.ndec)
+            assert_array_almost_equal(y,ifft(xr), decimal=self.ndec)
+
+        _test(x1, x1_1)
+        _test(x2, x2_1)
+
+    def test_djbfft(self):
+        for i in range(2,14):
+            n = 2**i
+            x = np.arange(-1, n, 2) + 1j * np.arange(0, n+1, 2)
+            x[0] = 0
+            if n % 2 == 0:
+                x[-1] = np.real(x[-1])
+            y1 = np.fft.irfft(x)
+            y = irfft(x)
+            assert_array_almost_equal(y,y1)
+
+    def test_random_real(self):
+        for size in [1,51,111,100,200,64,128,256,1024]:
+            x = random([size]).astype(self.rdt)
+            y1 = irfft(rfft(x), n=size)
+            y2 = rfft(irfft(x, n=(size*2-1)))
+            assert_equal(y1.dtype, self.rdt)
+            assert_equal(y2.dtype, self.cdt)
+            assert_array_almost_equal(y1, x, decimal=self.ndec, err_msg=f"size={size}")
+            assert_array_almost_equal(y2, x, decimal=self.ndec, err_msg=f"size={size}")
+
+    def test_size_accuracy(self):
+        # Sanity check for the accuracy for prime and non-prime sized inputs
+        if self.rdt == np.float32:
+            rtol = 1e-5
+        elif self.rdt == np.float64:
+            rtol = 1e-10
+
+        for size in LARGE_COMPOSITE_SIZES + LARGE_PRIME_SIZES:
+            np.random.seed(1234)
+            x = np.random.rand(size).astype(self.rdt)
+            y = irfft(rfft(x), len(x))
+            _assert_close_in_norm(x, y, rtol, size, self.rdt)
+            y = rfft(irfft(x, 2 * len(x) - 1))
+            _assert_close_in_norm(x, y, rtol, size, self.rdt)
+
+    def test_invalid_sizes(self):
+        assert_raises(ValueError, irfft, [])
+        assert_raises(ValueError, irfft, [[1,1],[2,2]], -5)
+
+
+# self.ndec is bogus; we should have a assert_array_approx_equal for number of
+# significant digits
+
+@pytest.mark.skipif(np.longdouble is np.float64,
+                    reason="Long double is aliased to double")
+class TestIRFFTLongDouble(_TestIRFFTBase):
+    def setup_method(self):
+        self.cdt = np.complex128
+        self.rdt = np.float64
+        self.ndec = 14
+
+
+class TestIRFFTDouble(_TestIRFFTBase):
+    def setup_method(self):
+        self.cdt = np.complex128
+        self.rdt = np.float64
+        self.ndec = 14
+
+
+class TestIRFFTSingle(_TestIRFFTBase):
+    def setup_method(self):
+        self.cdt = np.complex64
+        self.rdt = np.float32
+        self.ndec = 5
+
+
+class TestFftnSingle:
+    def setup_method(self):
+        np.random.seed(1234)
+
+    def test_definition(self):
+        x = [[1, 2, 3],
+             [4, 5, 6],
+             [7, 8, 9]]
+        y = fftn(np.array(x, np.float32))
+        assert_(y.dtype == np.complex64,
+                msg="double precision output with single precision")
+
+        y_r = np.array(fftn(x), np.complex64)
+        assert_array_almost_equal_nulp(y, y_r)
+
+    @pytest.mark.parametrize('size', SMALL_COMPOSITE_SIZES + SMALL_PRIME_SIZES)
+    def test_size_accuracy_small(self, size):
+        rng = np.random.default_rng(1234)
+        x = rng.random((size, size)) + 1j * rng.random((size, size))
+        y1 = fftn(x.real.astype(np.float32))
+        y2 = fftn(x.real.astype(np.float64)).astype(np.complex64)
+
+        assert_equal(y1.dtype, np.complex64)
+        assert_array_almost_equal_nulp(y1, y2, 2000)
+
+    @pytest.mark.parametrize('size', LARGE_COMPOSITE_SIZES + LARGE_PRIME_SIZES)
+    def test_size_accuracy_large(self, size):
+        rng = np.random.default_rng(1234)
+        x = rng.random((size, 3)) + 1j * rng.random((size, 3))
+        y1 = fftn(x.real.astype(np.float32))
+        y2 = fftn(x.real.astype(np.float64)).astype(np.complex64)
+
+        assert_equal(y1.dtype, np.complex64)
+        assert_array_almost_equal_nulp(y1, y2, 2000)
+
+    def test_definition_float16(self):
+        x = [[1, 2, 3],
+             [4, 5, 6],
+             [7, 8, 9]]
+        y = fftn(np.array(x, np.float16))
+        assert_equal(y.dtype, np.complex64)
+        y_r = np.array(fftn(x), np.complex64)
+        assert_array_almost_equal_nulp(y, y_r)
+
+    @pytest.mark.parametrize('size', SMALL_COMPOSITE_SIZES + SMALL_PRIME_SIZES)
+    def test_float16_input_small(self, size):
+        rng = np.random.default_rng(1234)
+        x = rng.random((size, size)) + 1j*rng.random((size, size))
+        y1 = fftn(x.real.astype(np.float16))
+        y2 = fftn(x.real.astype(np.float64)).astype(np.complex64)
+
+        assert_equal(y1.dtype, np.complex64)
+        assert_array_almost_equal_nulp(y1, y2, 5e5)
+
+    @pytest.mark.parametrize('size', LARGE_COMPOSITE_SIZES + LARGE_PRIME_SIZES)
+    def test_float16_input_large(self, size):
+        rng = np.random.default_rng(1234)
+        x = rng.random((size, 3)) + 1j*rng.random((size, 3))
+        y1 = fftn(x.real.astype(np.float16))
+        y2 = fftn(x.real.astype(np.float64)).astype(np.complex64)
+
+        assert_equal(y1.dtype, np.complex64)
+        assert_array_almost_equal_nulp(y1, y2, 2e6)
+
+
+class TestFftn:
+    def setup_method(self):
+        np.random.seed(1234)
+
+    def test_definition(self):
+        x = [[1, 2, 3],
+             [4, 5, 6],
+             [7, 8, 9]]
+        y = fftn(x)
+        assert_array_almost_equal(y, direct_dftn(x))
+
+        x = random((20, 26))
+        assert_array_almost_equal(fftn(x), direct_dftn(x))
+
+        x = random((5, 4, 3, 20))
+        assert_array_almost_equal(fftn(x), direct_dftn(x))
+
+    def test_axes_argument(self):
+        # plane == ji_plane, x== kji_space
+        plane1 = [[1, 2, 3],
+                  [4, 5, 6],
+                  [7, 8, 9]]
+        plane2 = [[10, 11, 12],
+                  [13, 14, 15],
+                  [16, 17, 18]]
+        plane3 = [[19, 20, 21],
+                  [22, 23, 24],
+                  [25, 26, 27]]
+        ki_plane1 = [[1, 2, 3],
+                     [10, 11, 12],
+                     [19, 20, 21]]
+        ki_plane2 = [[4, 5, 6],
+                     [13, 14, 15],
+                     [22, 23, 24]]
+        ki_plane3 = [[7, 8, 9],
+                     [16, 17, 18],
+                     [25, 26, 27]]
+        jk_plane1 = [[1, 10, 19],
+                     [4, 13, 22],
+                     [7, 16, 25]]
+        jk_plane2 = [[2, 11, 20],
+                     [5, 14, 23],
+                     [8, 17, 26]]
+        jk_plane3 = [[3, 12, 21],
+                     [6, 15, 24],
+                     [9, 18, 27]]
+        kj_plane1 = [[1, 4, 7],
+                     [10, 13, 16], [19, 22, 25]]
+        kj_plane2 = [[2, 5, 8],
+                     [11, 14, 17], [20, 23, 26]]
+        kj_plane3 = [[3, 6, 9],
+                     [12, 15, 18], [21, 24, 27]]
+        ij_plane1 = [[1, 4, 7],
+                     [2, 5, 8],
+                     [3, 6, 9]]
+        ij_plane2 = [[10, 13, 16],
+                     [11, 14, 17],
+                     [12, 15, 18]]
+        ij_plane3 = [[19, 22, 25],
+                     [20, 23, 26],
+                     [21, 24, 27]]
+        ik_plane1 = [[1, 10, 19],
+                     [2, 11, 20],
+                     [3, 12, 21]]
+        ik_plane2 = [[4, 13, 22],
+                     [5, 14, 23],
+                     [6, 15, 24]]
+        ik_plane3 = [[7, 16, 25],
+                     [8, 17, 26],
+                     [9, 18, 27]]
+        ijk_space = [jk_plane1, jk_plane2, jk_plane3]
+        ikj_space = [kj_plane1, kj_plane2, kj_plane3]
+        jik_space = [ik_plane1, ik_plane2, ik_plane3]
+        jki_space = [ki_plane1, ki_plane2, ki_plane3]
+        kij_space = [ij_plane1, ij_plane2, ij_plane3]
+        x = array([plane1, plane2, plane3])
+
+        assert_array_almost_equal(fftn(x),
+                                  fftn(x, axes=(-3, -2, -1)))  # kji_space
+        assert_array_almost_equal(fftn(x), fftn(x, axes=(0, 1, 2)))
+        assert_array_almost_equal(fftn(x, axes=(0, 2)), fftn(x, axes=(0, -1)))
+        y = fftn(x, axes=(2, 1, 0))  # ijk_space
+        assert_array_almost_equal(swapaxes(y, -1, -3), fftn(ijk_space))
+        y = fftn(x, axes=(2, 0, 1))  # ikj_space
+        assert_array_almost_equal(swapaxes(swapaxes(y, -1, -3), -1, -2),
+                                  fftn(ikj_space))
+        y = fftn(x, axes=(1, 2, 0))  # jik_space
+        assert_array_almost_equal(swapaxes(swapaxes(y, -1, -3), -3, -2),
+                                  fftn(jik_space))
+        y = fftn(x, axes=(1, 0, 2))  # jki_space
+        assert_array_almost_equal(swapaxes(y, -2, -3), fftn(jki_space))
+        y = fftn(x, axes=(0, 2, 1))  # kij_space
+        assert_array_almost_equal(swapaxes(y, -2, -1), fftn(kij_space))
+
+        y = fftn(x, axes=(-2, -1))  # ji_plane
+        assert_array_almost_equal(fftn(plane1), y[0])
+        assert_array_almost_equal(fftn(plane2), y[1])
+        assert_array_almost_equal(fftn(plane3), y[2])
+
+        y = fftn(x, axes=(1, 2))  # ji_plane
+        assert_array_almost_equal(fftn(plane1), y[0])
+        assert_array_almost_equal(fftn(plane2), y[1])
+        assert_array_almost_equal(fftn(plane3), y[2])
+
+        y = fftn(x, axes=(-3, -2))  # kj_plane
+        assert_array_almost_equal(fftn(x[:, :, 0]), y[:, :, 0])
+        assert_array_almost_equal(fftn(x[:, :, 1]), y[:, :, 1])
+        assert_array_almost_equal(fftn(x[:, :, 2]), y[:, :, 2])
+
+        y = fftn(x, axes=(-3, -1))  # ki_plane
+        assert_array_almost_equal(fftn(x[:, 0, :]), y[:, 0, :])
+        assert_array_almost_equal(fftn(x[:, 1, :]), y[:, 1, :])
+        assert_array_almost_equal(fftn(x[:, 2, :]), y[:, 2, :])
+
+        y = fftn(x, axes=(-1, -2))  # ij_plane
+        assert_array_almost_equal(fftn(ij_plane1), swapaxes(y[0], -2, -1))
+        assert_array_almost_equal(fftn(ij_plane2), swapaxes(y[1], -2, -1))
+        assert_array_almost_equal(fftn(ij_plane3), swapaxes(y[2], -2, -1))
+
+        y = fftn(x, axes=(-1, -3))  # ik_plane
+        assert_array_almost_equal(fftn(ik_plane1),
+                                  swapaxes(y[:, 0, :], -1, -2))
+        assert_array_almost_equal(fftn(ik_plane2),
+                                  swapaxes(y[:, 1, :], -1, -2))
+        assert_array_almost_equal(fftn(ik_plane3),
+                                  swapaxes(y[:, 2, :], -1, -2))
+
+        y = fftn(x, axes=(-2, -3))  # jk_plane
+        assert_array_almost_equal(fftn(jk_plane1),
+                                  swapaxes(y[:, :, 0], -1, -2))
+        assert_array_almost_equal(fftn(jk_plane2),
+                                  swapaxes(y[:, :, 1], -1, -2))
+        assert_array_almost_equal(fftn(jk_plane3),
+                                  swapaxes(y[:, :, 2], -1, -2))
+
+        y = fftn(x, axes=(-1,))  # i_line
+        for i in range(3):
+            for j in range(3):
+                assert_array_almost_equal(fft(x[i, j, :]), y[i, j, :])
+        y = fftn(x, axes=(-2,))  # j_line
+        for i in range(3):
+            for j in range(3):
+                assert_array_almost_equal(fft(x[i, :, j]), y[i, :, j])
+        y = fftn(x, axes=(0,))  # k_line
+        for i in range(3):
+            for j in range(3):
+                assert_array_almost_equal(fft(x[:, i, j]), y[:, i, j])
+
+        y = fftn(x, axes=())  # point
+        assert_array_almost_equal(y, x)
+
+    def test_shape_argument(self):
+        small_x = [[1, 2, 3],
+                   [4, 5, 6]]
+        large_x1 = [[1, 2, 3, 0],
+                    [4, 5, 6, 0],
+                    [0, 0, 0, 0],
+                    [0, 0, 0, 0]]
+
+        y = fftn(small_x, s=(4, 4))
+        assert_array_almost_equal(y, fftn(large_x1))
+
+        y = fftn(small_x, s=(3, 4))
+        assert_array_almost_equal(y, fftn(large_x1[:-1]))
+
+    def test_shape_axes_argument(self):
+        small_x = [[1, 2, 3],
+                   [4, 5, 6],
+                   [7, 8, 9]]
+        large_x1 = array([[1, 2, 3, 0],
+                          [4, 5, 6, 0],
+                          [7, 8, 9, 0],
+                          [0, 0, 0, 0]])
+        y = fftn(small_x, s=(4, 4), axes=(-2, -1))
+        assert_array_almost_equal(y, fftn(large_x1))
+        y = fftn(small_x, s=(4, 4), axes=(-1, -2))
+
+        assert_array_almost_equal(y, swapaxes(
+            fftn(swapaxes(large_x1, -1, -2)), -1, -2))
+
+    def test_shape_axes_argument2(self):
+        # Change shape of the last axis
+        x = numpy.random.random((10, 5, 3, 7))
+        y = fftn(x, axes=(-1,), s=(8,))
+        assert_array_almost_equal(y, fft(x, axis=-1, n=8))
+
+        # Change shape of an arbitrary axis which is not the last one
+        x = numpy.random.random((10, 5, 3, 7))
+        y = fftn(x, axes=(-2,), s=(8,))
+        assert_array_almost_equal(y, fft(x, axis=-2, n=8))
+
+        # Change shape of axes: cf #244, where shape and axes were mixed up
+        x = numpy.random.random((4, 4, 2))
+        y = fftn(x, axes=(-3, -2), s=(8, 8))
+        assert_array_almost_equal(y,
+                                  numpy.fft.fftn(x, axes=(-3, -2), s=(8, 8)))
+
+    def test_shape_argument_more(self):
+        x = zeros((4, 4, 2))
+        with assert_raises(ValueError,
+                           match="shape requires more axes than are present"):
+            fftn(x, s=(8, 8, 2, 1))
+
+    def test_invalid_sizes(self):
+        with assert_raises(ValueError,
+                           match="invalid number of data points"
+                           r" \(\[1, 0\]\) specified"):
+            fftn([[]])
+
+        with assert_raises(ValueError,
+                           match="invalid number of data points"
+                           r" \(\[4, -3\]\) specified"):
+            fftn([[1, 1], [2, 2]], (4, -3))
+
+    def test_no_axes(self):
+        x = numpy.random.random((2,2,2))
+        assert_allclose(fftn(x, axes=[]), x, atol=1e-7)
+
+    def test_regression_244(self):
+        """FFT returns wrong result with axes parameter."""
+        # fftn (and hence fft2) used to break when both axes and shape were used
+        x = numpy.ones((4, 4, 2))
+        y = fftn(x, s=(8, 8), axes=(-3, -2))
+        y_r = numpy.fft.fftn(x, s=(8, 8), axes=(-3, -2))
+        assert_allclose(y, y_r)
+
+
+class TestIfftn:
+    dtype = None
+    cdtype = None
+
+    def setup_method(self):
+        np.random.seed(1234)
+
+    @pytest.mark.parametrize('dtype,cdtype,maxnlp',
+                             [(np.float64, np.complex128, 2000),
+                              (np.float32, np.complex64, 3500)])
+    def test_definition(self, dtype, cdtype, maxnlp):
+        rng = np.random.default_rng(1234)
+        x = np.array([[1, 2, 3],
+                      [4, 5, 6],
+                      [7, 8, 9]], dtype=dtype)
+        y = ifftn(x)
+        assert_equal(y.dtype, cdtype)
+        assert_array_almost_equal_nulp(y, direct_idftn(x), maxnlp)
+
+        x = rng.random((20, 26))
+        assert_array_almost_equal_nulp(ifftn(x), direct_idftn(x), maxnlp)
+
+        x = rng.random((5, 4, 3, 20))
+        assert_array_almost_equal_nulp(ifftn(x), direct_idftn(x), maxnlp)
+
+    @pytest.mark.parametrize('maxnlp', [2000, 3500])
+    @pytest.mark.parametrize('size', [1, 2, 51, 32, 64, 92])
+    def test_random_complex(self, maxnlp, size):
+        rng = np.random.default_rng(1234)
+        x = rng.random([size, size]) + 1j * rng.random([size, size])
+        assert_array_almost_equal_nulp(ifftn(fftn(x)), x, maxnlp)
+        assert_array_almost_equal_nulp(fftn(ifftn(x)), x, maxnlp)
+
+    def test_invalid_sizes(self):
+        with assert_raises(ValueError,
+                           match="invalid number of data points"
+                           r" \(\[1, 0\]\) specified"):
+            ifftn([[]])
+
+        with assert_raises(ValueError,
+                           match="invalid number of data points"
+                           r" \(\[4, -3\]\) specified"):
+            ifftn([[1, 1], [2, 2]], (4, -3))
+
+    def test_no_axes(self):
+        x = numpy.random.random((2,2,2))
+        assert_allclose(ifftn(x, axes=[]), x, atol=1e-7)
+
+class TestRfftn:
+    dtype = None
+    cdtype = None
+
+    def setup_method(self):
+        np.random.seed(1234)
+
+    @pytest.mark.parametrize('dtype,cdtype,maxnlp',
+                             [(np.float64, np.complex128, 2000),
+                              (np.float32, np.complex64, 3500)])
+    def test_definition(self, dtype, cdtype, maxnlp):
+        rng = np.random.default_rng(1234)
+        x = np.array([[1, 2, 3],
+                      [4, 5, 6],
+                      [7, 8, 9]], dtype=dtype)
+        y = rfftn(x)
+        assert_equal(y.dtype, cdtype)
+        assert_array_almost_equal_nulp(y, direct_rdftn(x), maxnlp)
+
+        x = rng.random((20, 26))
+        assert_array_almost_equal_nulp(rfftn(x), direct_rdftn(x), maxnlp)
+
+        x = rng.random((5, 4, 3, 20))
+        assert_array_almost_equal_nulp(rfftn(x), direct_rdftn(x), maxnlp)
+
+    @pytest.mark.parametrize('size', [1, 2, 51, 32, 64, 92])
+    def test_random(self, size):
+        rng = np.random.default_rng(1234)
+        x = rng.random([size, size])
+        assert_allclose(irfftn(rfftn(x), x.shape), x, atol=1e-10)
+
+    @pytest.mark.parametrize('func', [rfftn, irfftn])
+    def test_invalid_sizes(self, func):
+        with assert_raises(ValueError,
+                           match="invalid number of data points"
+                           r" \(\[1, 0\]\) specified"):
+            func([[]])
+
+        with assert_raises(ValueError,
+                           match="invalid number of data points"
+                           r" \(\[4, -3\]\) specified"):
+            func([[1, 1], [2, 2]], (4, -3))
+
+    @pytest.mark.parametrize('func', [rfftn, irfftn])
+    def test_no_axes(self, func):
+        with assert_raises(ValueError,
+                           match="at least 1 axis must be transformed"):
+            func([], axes=[])
+
+    def test_complex_input(self):
+        with assert_raises(TypeError, match="x must be a real sequence"):
+            rfftn(np.zeros(10, dtype=np.complex64))
+
+
+class FakeArray:
+    def __init__(self, data):
+        self._data = data
+        self.__array_interface__ = data.__array_interface__
+
+
+class FakeArray2:
+    def __init__(self, data):
+        self._data = data
+
+    def __array__(self, dtype=None, copy=None):
+        return self._data
+
+# TODO: Is this test actually valuable? The behavior it's testing shouldn't be
+# relied upon by users except for overwrite_x = False
+class TestOverwrite:
+    """Check input overwrite behavior of the FFT functions."""
+
+    real_dtypes = [np.float32, np.float64, np.longdouble]
+    dtypes = real_dtypes + [np.complex64, np.complex128, np.clongdouble]
+    fftsizes = [8, 16, 32]
+
+    def _check(self, x, routine, fftsize, axis, overwrite_x, should_overwrite):
+        x2 = x.copy()
+        for fake in [lambda x: x, FakeArray, FakeArray2]:
+            routine(fake(x2), fftsize, axis, overwrite_x=overwrite_x)
+
+            sig = (f"{routine.__name__}({x.dtype}{x.shape!r}, {fftsize!r}, "
+                   f"axis={axis!r}, overwrite_x={overwrite_x!r})")
+            if not should_overwrite:
+                assert_equal(x2, x, err_msg=f"spurious overwrite in {sig}")
+
+    def _check_1d(self, routine, dtype, shape, axis, overwritable_dtypes,
+                  fftsize, overwrite_x):
+        np.random.seed(1234)
+        if np.issubdtype(dtype, np.complexfloating):
+            data = np.random.randn(*shape) + 1j*np.random.randn(*shape)
+        else:
+            data = np.random.randn(*shape)
+        data = data.astype(dtype)
+
+        should_overwrite = (overwrite_x
+                            and dtype in overwritable_dtypes
+                            and fftsize <= shape[axis])
+        self._check(data, routine, fftsize, axis,
+                    overwrite_x=overwrite_x,
+                    should_overwrite=should_overwrite)
+
+    @pytest.mark.parametrize('dtype', dtypes)
+    @pytest.mark.parametrize('fftsize', fftsizes)
+    @pytest.mark.parametrize('overwrite_x', [True, False])
+    @pytest.mark.parametrize('shape,axes', [((16,), -1),
+                                            ((16, 2), 0),
+                                            ((2, 16), 1)])
+    def test_fft_ifft(self, dtype, fftsize, overwrite_x, shape, axes):
+        overwritable = (np.clongdouble, np.complex128, np.complex64)
+        self._check_1d(fft, dtype, shape, axes, overwritable,
+                       fftsize, overwrite_x)
+        self._check_1d(ifft, dtype, shape, axes, overwritable,
+                       fftsize, overwrite_x)
+
+    @pytest.mark.parametrize('dtype', real_dtypes)
+    @pytest.mark.parametrize('fftsize', fftsizes)
+    @pytest.mark.parametrize('overwrite_x', [True, False])
+    @pytest.mark.parametrize('shape,axes', [((16,), -1),
+                                            ((16, 2), 0),
+                                            ((2, 16), 1)])
+    def test_rfft_irfft(self, dtype, fftsize, overwrite_x, shape, axes):
+        overwritable = self.real_dtypes
+        self._check_1d(irfft, dtype, shape, axes, overwritable,
+                       fftsize, overwrite_x)
+        self._check_1d(rfft, dtype, shape, axes, overwritable,
+                       fftsize, overwrite_x)
+
+    def _check_nd_one(self, routine, dtype, shape, axes, overwritable_dtypes,
+                      overwrite_x):
+        np.random.seed(1234)
+        if np.issubdtype(dtype, np.complexfloating):
+            data = np.random.randn(*shape) + 1j*np.random.randn(*shape)
+        else:
+            data = np.random.randn(*shape)
+        data = data.astype(dtype)
+
+        def fftshape_iter(shp):
+            if len(shp) <= 0:
+                yield ()
+            else:
+                for j in (shp[0]//2, shp[0], shp[0]*2):
+                    for rest in fftshape_iter(shp[1:]):
+                        yield (j,) + rest
+
+        def part_shape(shape, axes):
+            if axes is None:
+                return shape
+            else:
+                return tuple(np.take(shape, axes))
+
+        def should_overwrite(data, shape, axes):
+            s = part_shape(data.shape, axes)
+            return (overwrite_x and
+                    np.prod(shape) <= np.prod(s)
+                    and dtype in overwritable_dtypes)
+
+        for fftshape in fftshape_iter(part_shape(shape, axes)):
+            self._check(data, routine, fftshape, axes,
+                        overwrite_x=overwrite_x,
+                        should_overwrite=should_overwrite(data, fftshape, axes))
+            if data.ndim > 1:
+                # check fortran order
+                self._check(data.T, routine, fftshape, axes,
+                            overwrite_x=overwrite_x,
+                            should_overwrite=should_overwrite(
+                                data.T, fftshape, axes))
+
+    @pytest.mark.parametrize('dtype', dtypes)
+    @pytest.mark.parametrize('overwrite_x', [True, False])
+    @pytest.mark.parametrize('shape,axes', [((16,), None),
+                                            ((16,), (0,)),
+                                            ((16, 2), (0,)),
+                                            ((2, 16), (1,)),
+                                            ((8, 16), None),
+                                            ((8, 16), (0, 1)),
+                                            ((8, 16, 2), (0, 1)),
+                                            ((8, 16, 2), (1, 2)),
+                                            ((8, 16, 2), (0,)),
+                                            ((8, 16, 2), (1,)),
+                                            ((8, 16, 2), (2,)),
+                                            ((8, 16, 2), None),
+                                            ((8, 16, 2), (0, 1, 2))])
+    def test_fftn_ifftn(self, dtype, overwrite_x, shape, axes):
+        overwritable = (np.clongdouble, np.complex128, np.complex64)
+        self._check_nd_one(fftn, dtype, shape, axes, overwritable,
+                           overwrite_x)
+        self._check_nd_one(ifftn, dtype, shape, axes, overwritable,
+                           overwrite_x)
+
+
+@pytest.mark.parametrize('func', [fft, ifft, fftn, ifftn,
+                                 rfft, irfft, rfftn, irfftn])
+def test_invalid_norm(func):
+    x = np.arange(10, dtype=float)
+    with assert_raises(ValueError,
+                       match='Invalid norm value \'o\', should be'
+                             ' "backward", "ortho" or "forward"'):
+        func(x, norm='o')
+
+
+@pytest.mark.parametrize('func', [fft, ifft, fftn, ifftn,
+                                   irfft, irfftn, hfft, hfftn])
+def test_swapped_byte_order_complex(func):
+    rng = np.random.RandomState(1234)
+    x = rng.rand(10) + 1j * rng.rand(10)
+    assert_allclose(func(swap_byteorder(x)), func(x))
+
+
+@pytest.mark.parametrize('func', [ihfft, ihfftn, rfft, rfftn])
+def test_swapped_byte_order_real(func):
+    rng = np.random.RandomState(1234)
+    x = rng.rand(10)
+    assert_allclose(func(swap_byteorder(x)), func(x))
diff --git a/.venv/lib/python3.12/site-packages/scipy/fft/_duccfft/tests/test_real_transforms.py b/.venv/lib/python3.12/site-packages/scipy/fft/_duccfft/tests/test_real_transforms.py
new file mode 100644
index 0000000000000000000000000000000000000000..647cb6a55a2d974b52358801dff877ef9c1d90b2
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/fft/_duccfft/tests/test_real_transforms.py
@@ -0,0 +1,506 @@
+from os.path import join, dirname
+from collections.abc import Callable
+from threading import Lock
+
+import numpy as np
+from numpy.testing import (
+    assert_array_almost_equal, assert_equal, assert_allclose)
+import pytest
+from pytest import raises as assert_raises
+
+from scipy.fft._duccfft.realtransforms import (
+    dct, idct, dst, idst, dctn, idctn, dstn, idstn)
+
+fftpack_test_dir = join(dirname(__file__), '..', '..', '..', 'fftpack', 'tests')
+
+MDATA_COUNT = 8
+FFTWDATA_COUNT = 14
+
+
+def is_longdouble_binary_compatible():
+    try:
+        one = np.frombuffer(
+            b'\x00\x00\x00\x00\x00\x00\x00\x80\xff\x3f\x00\x00\x00\x00\x00\x00',
+            dtype=' decimal
+dec_map: DecMapType = {
+    # DCT
+    (dct, np.float64, 1): 13,
+    (dct, np.float32, 1): 6,
+
+    (dct, np.float64, 2): 14,
+    (dct, np.float32, 2): 5,
+
+    (dct, np.float64, 3): 14,
+    (dct, np.float32, 3): 5,
+
+    (dct, np.float64, 4): 13,
+    (dct, np.float32, 4): 6,
+
+    # IDCT
+    (idct, np.float64, 1): 14,
+    (idct, np.float32, 1): 6,
+
+    (idct, np.float64, 2): 14,
+    (idct, np.float32, 2): 5,
+
+    (idct, np.float64, 3): 14,
+    (idct, np.float32, 3): 5,
+
+    (idct, np.float64, 4): 14,
+    (idct, np.float32, 4): 6,
+
+    # DST
+    (dst, np.float64, 1): 13,
+    (dst, np.float32, 1): 6,
+
+    (dst, np.float64, 2): 14,
+    (dst, np.float32, 2): 6,
+
+    (dst, np.float64, 3): 14,
+    (dst, np.float32, 3): 7,
+
+    (dst, np.float64, 4): 13,
+    (dst, np.float32, 4): 5,
+
+    # IDST
+    (idst, np.float64, 1): 14,
+    (idst, np.float32, 1): 6,
+
+    (idst, np.float64, 2): 14,
+    (idst, np.float32, 2): 6,
+
+    (idst, np.float64, 3): 14,
+    (idst, np.float32, 3): 6,
+
+    (idst, np.float64, 4): 14,
+    (idst, np.float32, 4): 6,
+}
+
+for k,v in dec_map.copy().items():
+    if k[1] == np.float64:
+        dec_map[(k[0], np.longdouble, k[2])] = v
+    elif k[1] == np.float32:
+        dec_map[(k[0], int, k[2])] = v
+
+
+@pytest.mark.parametrize('rdt', [np.longdouble, np.float64, np.float32, int])
+@pytest.mark.parametrize('type', [1, 2, 3, 4])
+class TestDCT:
+    def test_definition(self, rdt, type, fftwdata_size,
+                        reference_data, ref_lock):
+        with ref_lock:
+            x, yr, dt = fftw_dct_ref(type, fftwdata_size, rdt, reference_data)
+        y = dct(x, type=type)
+        assert_equal(y.dtype, dt)
+        dec = dec_map[(dct, rdt, type)]
+        assert_allclose(y, yr, rtol=0., atol=np.max(yr)*10**(-dec))
+
+    @pytest.mark.parametrize('size', [7, 8, 9, 16, 32, 64])
+    def test_axis(self, rdt, type, size):
+        nt = 2
+        dec = dec_map[(dct, rdt, type)]
+        x = np.random.randn(nt, size)
+        y = dct(x, type=type)
+        for j in range(nt):
+            assert_array_almost_equal(y[j], dct(x[j], type=type),
+                                      decimal=dec)
+
+        x = x.T
+        y = dct(x, axis=0, type=type)
+        for j in range(nt):
+            assert_array_almost_equal(y[:,j], dct(x[:,j], type=type),
+                                      decimal=dec)
+
+
+@pytest.mark.parametrize('rdt', [np.longdouble, np.float64, np.float32, int])
+def test_dct1_definition_ortho(rdt, mdata_x):
+    # Test orthornomal mode.
+    dec = dec_map[(dct, rdt, 1)]
+    x = np.array(mdata_x, dtype=rdt)
+    dt = np.result_type(np.float32, rdt)
+    y = dct(x, norm='ortho', type=1)
+    y2 = naive_dct1(x, norm='ortho')
+    assert_equal(y.dtype, dt)
+    assert_allclose(y, y2, rtol=0., atol=np.max(y2)*10**(-dec))
+
+
+@pytest.mark.parametrize('rdt', [np.longdouble, np.float64, np.float32, int])
+def test_dct2_definition_matlab(mdata_xy, rdt):
+    # Test correspondence with matlab (orthornomal mode).
+    dt = np.result_type(np.float32, rdt)
+    x = np.array(mdata_xy[0], dtype=dt)
+
+    yr = mdata_xy[1]
+    y = dct(x, norm="ortho", type=2)
+    dec = dec_map[(dct, rdt, 2)]
+    assert_equal(y.dtype, dt)
+    assert_array_almost_equal(y, yr, decimal=dec)
+
+
+@pytest.mark.parametrize('rdt', [np.longdouble, np.float64, np.float32, int])
+def test_dct3_definition_ortho(mdata_x, rdt):
+    # Test orthornomal mode.
+    x = np.array(mdata_x, dtype=rdt)
+    dt = np.result_type(np.float32, rdt)
+    y = dct(x, norm='ortho', type=2)
+    xi = dct(y, norm="ortho", type=3)
+    dec = dec_map[(dct, rdt, 3)]
+    assert_equal(xi.dtype, dt)
+    assert_array_almost_equal(xi, x, decimal=dec)
+
+
+@pytest.mark.parametrize('rdt', [np.longdouble, np.float64, np.float32, int])
+def test_dct4_definition_ortho(mdata_x, rdt):
+    # Test orthornomal mode.
+    x = np.array(mdata_x, dtype=rdt)
+    dt = np.result_type(np.float32, rdt)
+    y = dct(x, norm='ortho', type=4)
+    y2 = naive_dct4(x, norm='ortho')
+    dec = dec_map[(dct, rdt, 4)]
+    assert_equal(y.dtype, dt)
+    assert_allclose(y, y2, rtol=0., atol=np.max(y2)*10**(-dec))
+
+
+@pytest.mark.parametrize('rdt', [np.longdouble, np.float64, np.float32, int])
+@pytest.mark.parametrize('type', [1, 2, 3, 4])
+def test_idct_definition(fftwdata_size, rdt, type, reference_data, ref_lock):
+    with ref_lock:
+        xr, yr, dt = fftw_dct_ref(type, fftwdata_size, rdt, reference_data)
+    x = idct(yr, type=type)
+    dec = dec_map[(idct, rdt, type)]
+    assert_equal(x.dtype, dt)
+    assert_allclose(x, xr, rtol=0., atol=np.max(xr)*10**(-dec))
+
+
+@pytest.mark.parametrize('rdt', [np.longdouble, np.float64, np.float32, int])
+@pytest.mark.parametrize('type', [1, 2, 3, 4])
+def test_definition(fftwdata_size, rdt, type, reference_data, ref_lock):
+    with ref_lock:
+        xr, yr, dt = fftw_dst_ref(type, fftwdata_size, rdt, reference_data)
+    y = dst(xr, type=type)
+    dec = dec_map[(dst, rdt, type)]
+    assert_equal(y.dtype, dt)
+    assert_allclose(y, yr, rtol=0., atol=np.max(yr)*10**(-dec))
+
+
+@pytest.mark.parametrize('rdt', [np.longdouble, np.float64, np.float32, int])
+def test_dst1_definition_ortho(rdt, mdata_x):
+    # Test orthornomal mode.
+    dec = dec_map[(dst, rdt, 1)]
+    x = np.array(mdata_x, dtype=rdt)
+    dt = np.result_type(np.float32, rdt)
+    y = dst(x, norm='ortho', type=1)
+    y2 = naive_dst1(x, norm='ortho')
+    assert_equal(y.dtype, dt)
+    assert_allclose(y, y2, rtol=0., atol=np.max(y2)*10**(-dec))
+
+
+@pytest.mark.parametrize('rdt', [np.longdouble, np.float64, np.float32, int])
+def test_dst4_definition_ortho(rdt, mdata_x):
+    # Test orthornomal mode.
+    dec = dec_map[(dst, rdt, 4)]
+    x = np.array(mdata_x, dtype=rdt)
+    dt = np.result_type(np.float32, rdt)
+    y = dst(x, norm='ortho', type=4)
+    y2 = naive_dst4(x, norm='ortho')
+    assert_equal(y.dtype, dt)
+    assert_array_almost_equal(y, y2, decimal=dec)
+
+
+@pytest.mark.parametrize('rdt', [np.longdouble, np.float64, np.float32, int])
+@pytest.mark.parametrize('type', [1, 2, 3, 4])
+def test_idst_definition(fftwdata_size, rdt, type, reference_data, ref_lock):
+    with ref_lock:
+        xr, yr, dt = fftw_dst_ref(type, fftwdata_size, rdt, reference_data)
+    x = idst(yr, type=type)
+    dec = dec_map[(idst, rdt, type)]
+    assert_equal(x.dtype, dt)
+    assert_allclose(x, xr, rtol=0., atol=np.max(xr)*10**(-dec))
+
+
+@pytest.mark.parametrize('routine', [dct, dst, idct, idst])
+@pytest.mark.parametrize('dtype', [np.float32, np.float64, np.longdouble])
+@pytest.mark.parametrize('shape, axis', [
+    ((16,), -1), ((16, 2), 0), ((2, 16), 1)
+])
+@pytest.mark.parametrize('type', [1, 2, 3, 4])
+@pytest.mark.parametrize('overwrite_x', [True, False])
+@pytest.mark.parametrize('norm', [None, 'ortho'])
+def test_overwrite(routine, dtype, shape, axis, type, norm, overwrite_x):
+    # Check input overwrite behavior
+    np.random.seed(1234)
+    if np.issubdtype(dtype, np.complexfloating):
+        x = np.random.randn(*shape) + 1j*np.random.randn(*shape)
+    else:
+        x = np.random.randn(*shape)
+    x = x.astype(dtype)
+    x2 = x.copy()
+    routine(x2, type, None, axis, norm, overwrite_x=overwrite_x)
+
+    sig = (f"{routine.__name__}({x.dtype}{x.shape!r}, {None!r}, axis={axis!r}, "
+           f"overwrite_x={overwrite_x!r})")
+    if not overwrite_x:
+        assert_equal(x2, x, err_msg=f"spurious overwrite in {sig}")
+
+
+class Test_DCTN_IDCTN:
+    dec = 14
+    dct_type = [1, 2, 3, 4]
+    norms = [None, 'backward', 'ortho', 'forward']
+    rstate = np.random.RandomState(1234)
+    shape = (32, 16)
+    data = rstate.randn(*shape)
+
+    @pytest.mark.parametrize('fforward,finverse', [(dctn, idctn),
+                                                   (dstn, idstn)])
+    @pytest.mark.parametrize('axes', [None,
+                                      1, (1,), [1],
+                                      0, (0,), [0],
+                                      (0, 1), [0, 1],
+                                      (-2, -1), [-2, -1]])
+    @pytest.mark.parametrize('dct_type', dct_type)
+    @pytest.mark.parametrize('norm', ['ortho'])
+    def test_axes_round_trip(self, fforward, finverse, axes, dct_type, norm):
+        tmp = fforward(self.data, type=dct_type, axes=axes, norm=norm)
+        tmp = finverse(tmp, type=dct_type, axes=axes, norm=norm)
+        assert_array_almost_equal(self.data, tmp, decimal=12)
+
+    @pytest.mark.parametrize('funcn,func', [(dctn, dct), (dstn, dst)])
+    @pytest.mark.parametrize('dct_type', dct_type)
+    @pytest.mark.parametrize('norm', norms)
+    def test_dctn_vs_2d_reference(self, funcn, func, dct_type, norm):
+        y1 = funcn(self.data, type=dct_type, axes=None, norm=norm)
+        y2 = ref_2d(func, self.data, type=dct_type, norm=norm)
+        assert_array_almost_equal(y1, y2, decimal=11)
+
+    @pytest.mark.parametrize('funcn,func', [(idctn, idct), (idstn, idst)])
+    @pytest.mark.parametrize('dct_type', dct_type)
+    @pytest.mark.parametrize('norm', norms)
+    def test_idctn_vs_2d_reference(self, funcn, func, dct_type, norm):
+        fdata = dctn(self.data, type=dct_type, norm=norm)
+        y1 = funcn(fdata, type=dct_type, norm=norm)
+        y2 = ref_2d(func, fdata, type=dct_type, norm=norm)
+        assert_array_almost_equal(y1, y2, decimal=11)
+
+    @pytest.mark.parametrize('fforward,finverse', [(dctn, idctn),
+                                                   (dstn, idstn)])
+    def test_axes_and_shape(self, fforward, finverse):
+        with assert_raises(ValueError,
+                           match="when given, axes and shape arguments"
+                           " have to be of the same length"):
+            fforward(self.data, s=self.data.shape[0], axes=(0, 1))
+
+        with assert_raises(ValueError,
+                           match="when given, axes and shape arguments"
+                           " have to be of the same length"):
+            fforward(self.data, s=self.data.shape, axes=0)
+
+    @pytest.mark.parametrize('fforward', [dctn, dstn])
+    def test_shape(self, fforward):
+        tmp = fforward(self.data, s=(128, 128), axes=None)
+        assert_equal(tmp.shape, (128, 128))
+
+    @pytest.mark.parametrize('fforward,finverse', [(dctn, idctn),
+                                                   (dstn, idstn)])
+    @pytest.mark.parametrize('axes', [1, (1,), [1],
+                                      0, (0,), [0]])
+    def test_shape_is_none_with_axes(self, fforward, finverse, axes):
+        tmp = fforward(self.data, s=None, axes=axes, norm='ortho')
+        tmp = finverse(tmp, s=None, axes=axes, norm='ortho')
+        assert_array_almost_equal(self.data, tmp, decimal=self.dec)
+
+
+@pytest.mark.parametrize('func', [dct, dctn, idct, idctn,
+                                  dst, dstn, idst, idstn])
+def test_swapped_byte_order(func):
+    rng = np.random.RandomState(1234)
+    x = rng.rand(10)
+    swapped_dt = x.dtype.newbyteorder('S')
+    assert_allclose(func(x.astype(swapped_dt)), func(x))
diff --git a/.venv/lib/python3.12/site-packages/scipy/fft/_fftlog.py b/.venv/lib/python3.12/site-packages/scipy/fft/_fftlog.py
new file mode 100644
index 0000000000000000000000000000000000000000..7a01e2cc4a2734fdf9c11e33faf5bdd8bbfd8367
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/fft/_fftlog.py
@@ -0,0 +1,227 @@
+"""Fast Hankel transforms using the FFTLog algorithm.
+
+The implementation closely follows the Fortran code of Hamilton (2000).
+
+added: 14/11/2020 Nicolas Tessore 
+"""
+
+from ._basic import _dispatch
+from scipy._lib.uarray import Dispatchable
+from ._fftlog_backend import fhtoffset
+from scipy._lib._array_api import xp_capabilities
+
+import numpy as np
+
+__all__ = ['fht', 'ifht', 'fhtoffset']
+
+
+@xp_capabilities(allow_dask_compute=True)
+@_dispatch
+def fht(a, dln, mu, offset=0.0, bias=0.0):
+    r'''Compute the fast Hankel transform.
+
+    Computes the discrete Hankel transform of a logarithmically spaced periodic
+    sequence using the FFTLog algorithm [1]_, [2]_.
+
+    Parameters
+    ----------
+    a : array_like (..., n)
+        Real periodic input array, uniformly logarithmically spaced.  For
+        multidimensional input, the transform is performed over the last axis.
+    dln : float
+        Uniform logarithmic spacing of the input array.
+    mu : float
+        Order of the Hankel transform, any positive or negative real number.
+    offset : float, optional
+        Offset of the uniform logarithmic spacing of the output array.
+    bias : float, optional
+        Exponent of power law bias, any positive or negative real number.
+
+    Returns
+    -------
+    A : array_like (..., n)
+        The transformed output array, which is real, periodic, uniformly
+        logarithmically spaced, and of the same shape as the input array.
+
+    See Also
+    --------
+    ifht : The inverse of `fht`.
+    fhtoffset : Return an optimal offset for `fht`.
+
+    Notes
+    -----
+    This function computes a discrete version of the Hankel transform
+
+    .. math::
+
+        A(k) = \int_{0}^{\infty} \! a(r) \, J_\mu(kr) \, k \, dr \;,
+
+    where :math:`J_\mu` is the Bessel function of order :math:`\mu`.  The index
+    :math:`\mu` may be any real number, positive or negative.  Note that the
+    numerical Hankel transform uses an integrand of :math:`k \, dr`, while the
+    mathematical Hankel transform is commonly defined using :math:`r \, dr`.
+
+    The input array `a` is a periodic sequence of length :math:`n`, uniformly
+    logarithmically spaced with spacing `dln`,
+
+    .. math::
+
+        a_j = a(r_j) \;, \quad
+        r_j = r_c \exp[(j-j_c) \, \mathtt{dln}]
+
+    centred about the point :math:`r_c`.  Note that the central index
+    :math:`j_c = (n-1)/2` is half-integral if :math:`n` is even, so that
+    :math:`r_c` falls between two input elements.  Similarly, the output
+    array `A` is a periodic sequence of length :math:`n`, also uniformly
+    logarithmically spaced with spacing `dln`
+
+    .. math::
+
+       A_j = A(k_j) \;, \quad
+       k_j = k_c \exp[(j-j_c) \, \mathtt{dln}]
+
+    centred about the point :math:`k_c`.
+
+    The centre points :math:`r_c` and :math:`k_c` of the periodic intervals may
+    be chosen arbitrarily, but it would be usual to choose the product
+    :math:`k_c r_c = k_j r_{n-1-j} = k_{n-1-j} r_j` to be unity.  This can be
+    changed using the `offset` parameter, which controls the logarithmic offset
+    :math:`\log(k_c) = \mathtt{offset} - \log(r_c)` of the output array.
+    Choosing an optimal value for `offset` may reduce ringing of the discrete
+    Hankel transform.
+
+    If the `bias` parameter is nonzero, this function computes a discrete
+    version of the biased Hankel transform
+
+    .. math::
+
+        A(k) = \int_{0}^{\infty} \! a_q(r) \, (kr)^q \, J_\mu(kr) \, k \, dr
+
+    where :math:`q` is the value of `bias`, and a power law bias
+    :math:`a_q(r) = a(r) \, (kr)^{-q}` is applied to the input sequence.
+    Biasing the transform can help approximate the continuous transform of
+    :math:`a(r)` if there is a value :math:`q` such that :math:`a_q(r)` is
+    close to a periodic sequence, in which case the resulting :math:`A(k)` will
+    be close to the continuous transform.
+
+    References
+    ----------
+    .. [1] Talman J. D., 1978, J. Comp. Phys., 29, 35
+    .. [2] Hamilton A. J. S., 2000, MNRAS, 312, 257 (astro-ph/9905191)
+
+    Examples
+    --------
+
+    This example is the adapted version of ``fftlogtest.f`` which is provided
+    in [2]_. It evaluates the integral
+
+    .. math::
+
+        \int^\infty_0 r^{\mu+1} \exp(-r^2/2) J_\mu(kr) k dr
+        = k^{\mu+1} \exp(-k^2/2) .
+
+    >>> import numpy as np
+    >>> from scipy import fft
+    >>> import matplotlib.pyplot as plt
+
+    Parameters for the transform.
+
+    >>> mu = 0.0                     # Order mu of Bessel function
+    >>> r = np.logspace(-7, 1, 128)  # Input evaluation points
+    >>> dln = np.log(r[1]/r[0])      # Step size
+    >>> offset = fft.fhtoffset(dln, initial=-6*np.log(10), mu=mu)
+    >>> k = np.exp(offset)/r[::-1]   # Output evaluation points
+
+    Define the analytical function.
+
+    >>> def f(x, mu):
+    ...     """Analytical function: x^(mu+1) exp(-x^2/2)."""
+    ...     return x**(mu + 1)*np.exp(-x**2/2)
+
+    Evaluate the function at ``r`` and compute the corresponding values at
+    ``k`` using FFTLog.
+
+    >>> a_r = f(r, mu)
+    >>> fht = fft.fht(a_r, dln, mu=mu, offset=offset)
+
+    For this example we can actually compute the analytical response (which in
+    this case is the same as the input function) for comparison and compute the
+    relative error.
+
+    >>> a_k = f(k, mu)
+    >>> rel_err = abs((fht-a_k)/a_k)
+
+    Plot the result.
+
+    >>> figargs = {'sharex': True, 'sharey': True, 'constrained_layout': True}
+    >>> fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(10, 4), **figargs)
+    >>> ax1.set_title(r'$r^{\mu+1}\ \exp(-r^2/2)$')
+    >>> ax1.loglog(r, a_r, 'k', lw=2)
+    >>> ax1.set_xlabel('r')
+    >>> ax2.set_title(r'$k^{\mu+1} \exp(-k^2/2)$')
+    >>> ax2.loglog(k, a_k, 'k', lw=2, label='Analytical')
+    >>> ax2.loglog(k, fht, 'C3--', lw=2, label='FFTLog')
+    >>> ax2.set_xlabel('k')
+    >>> ax2.legend(loc=3, framealpha=1)
+    >>> ax2.set_ylim([1e-10, 1e1])
+    >>> ax2b = ax2.twinx()
+    >>> ax2b.loglog(k, rel_err, 'C0', label='Rel. Error (-)')
+    >>> ax2b.set_ylabel('Rel. Error (-)', color='C0')
+    >>> ax2b.tick_params(axis='y', labelcolor='C0')
+    >>> ax2b.legend(loc=4, framealpha=1)
+    >>> ax2b.set_ylim([1e-9, 1e-3])
+    >>> plt.show()
+
+    '''
+    return (Dispatchable(a, np.ndarray),)
+
+
+@xp_capabilities(allow_dask_compute=True)
+@_dispatch
+def ifht(A, dln, mu, offset=0.0, bias=0.0):
+    r"""Compute the inverse fast Hankel transform.
+
+    Computes the discrete inverse Hankel transform of a logarithmically spaced
+    periodic sequence. This is the inverse operation to `fht`.
+
+    Parameters
+    ----------
+    A : array_like (..., n)
+        Real periodic input array, uniformly logarithmically spaced.  For
+        multidimensional input, the transform is performed over the last axis.
+    dln : float
+        Uniform logarithmic spacing of the input array.
+    mu : float
+        Order of the Hankel transform, any positive or negative real number.
+    offset : float, optional
+        Offset of the uniform logarithmic spacing of the output array.
+    bias : float, optional
+        Exponent of power law bias, any positive or negative real number.
+
+    Returns
+    -------
+    a : array_like (..., n)
+        The transformed output array, which is real, periodic, uniformly
+        logarithmically spaced, and of the same shape as the input array.
+
+    See Also
+    --------
+    fht : Definition of the fast Hankel transform.
+    fhtoffset : Return an optimal offset for `ifht`.
+
+    Notes
+    -----
+    This function computes a discrete version of the Hankel transform
+
+    .. math::
+
+        a(r) = \int_{0}^{\infty} \! A(k) \, J_\mu(kr) \, r \, dk \;,
+
+    where :math:`J_\mu` is the Bessel function of order :math:`\mu`.  The index
+    :math:`\mu` may be any real number, positive or negative. Note that the
+    numerical inverse Hankel transform uses an integrand of :math:`r \, dk`, while the
+    mathematical inverse Hankel transform is commonly defined using :math:`k \, dk`.
+
+    See `fht` for further details.
+    """
+    return (Dispatchable(A, np.ndarray),)
diff --git a/.venv/lib/python3.12/site-packages/scipy/fft/_fftlog_backend.py b/.venv/lib/python3.12/site-packages/scipy/fft/_fftlog_backend.py
new file mode 100644
index 0000000000000000000000000000000000000000..d361708ea96c0bb590ec023e775e9bcfdad71a16
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/fft/_fftlog_backend.py
@@ -0,0 +1,201 @@
+import numpy as np
+from warnings import warn
+from ._basic import rfft, irfft
+from ..special import loggamma, poch
+
+from scipy._lib._array_api import array_namespace, xp_capabilities
+
+__all__ = ['fht', 'ifht', 'fhtoffset']
+
+# constants
+LN_2 = np.log(2)
+
+
+def fht(a, dln, mu, offset=0.0, bias=0.0):
+    xp = array_namespace(a)
+    a = xp.asarray(a)
+
+    # size of transform
+    n = a.shape[-1]
+
+    # bias input array
+    if bias != 0:
+        # a_q(r) = a(r) (r/r_c)^{-q}
+        j_c = (n-1)/2
+        j = xp.arange(n, dtype=xp.float64)
+        a = a * xp.exp(-bias*(j - j_c)*dln)
+
+    # compute FHT coefficients
+    u = xp.asarray(fhtcoeff(n, dln, mu, offset=offset, bias=bias))
+
+    # transform
+    A = _fhtq(a, u, xp=xp)
+
+    # bias output array
+    if bias != 0:
+        # A(k) = A_q(k) (k/k_c)^{-q} (k_c r_c)^{-q}
+        A *= xp.exp(-bias*((j - j_c)*dln + offset))
+
+    return A
+
+
+def ifht(A, dln, mu, offset=0.0, bias=0.0):
+    xp = array_namespace(A)
+    A = xp.asarray(A)
+
+    # size of transform
+    n = A.shape[-1]
+
+    # bias input array
+    if bias != 0:
+        # A_q(k) = A(k) (k/k_c)^{q} (k_c r_c)^{q}
+        j_c = (n-1)/2
+        j = xp.arange(n, dtype=xp.float64)
+        A = A * xp.exp(bias*((j - j_c)*dln + offset))
+
+    # compute FHT coefficients
+    u = xp.asarray(fhtcoeff(n, dln, mu, offset=offset, bias=bias, inverse=True))
+
+    # transform
+    a = _fhtq(A, u, inverse=True, xp=xp)
+
+    # bias output array
+    if bias != 0:
+        # a(r) = a_q(r) (r/r_c)^{q}
+        a /= xp.exp(-bias*(j - j_c)*dln)
+
+    return a
+
+
+def fhtcoeff(n, dln, mu, offset=0.0, bias=0.0, inverse=False):
+    """Compute the coefficient array for a fast Hankel transform."""
+    lnkr, q = offset, bias
+
+    # Hankel transform coefficients
+    # u_m = (kr)^{-i 2m pi/(n dlnr)} U_mu(q + i 2m pi/(n dlnr))
+    # with U_mu(x) = 2^x Gamma((mu+1+x)/2)/Gamma((mu+1-x)/2)
+    xp = (mu+1+q)/2
+    xm = (mu+1-q)/2
+    y = np.linspace(0, np.pi*(n//2)/(n*dln), n//2+1)
+    u = np.empty(n//2+1, dtype=complex)
+    v = np.empty(n//2+1, dtype=complex)
+    u.imag[:] = y
+    u.real[:] = xm
+    loggamma(u, out=v)
+    u.real[:] = xp
+    loggamma(u, out=u)
+    y *= 2*(LN_2 - lnkr)
+    u.real -= v.real
+    u.real += LN_2*q
+    u.imag += v.imag
+    u.imag += y
+    np.exp(u, out=u)
+
+    # fix last coefficient to be real
+    if n % 2 == 0:
+        u.imag[-1] = 0
+
+    # deal with special cases
+    if not np.isfinite(u[0]):
+        # write u_0 = 2^q Gamma(xp)/Gamma(xm) = 2^q poch(xm, xp-xm)
+        # poch() handles special cases for negative integers correctly
+        u[0] = 2**q * poch(xm, xp-xm)
+        # the coefficient may be inf or 0, meaning the transform or the
+        # inverse transform, respectively, is singular
+
+    # check for singular transform or singular inverse transform
+    if np.isinf(u[0]) and not inverse:
+        warn('singular transform; consider changing the bias', stacklevel=3)
+        # fix coefficient to obtain (potentially correct) transform anyway
+        u = np.copy(u)
+        u[0] = 0
+    elif u[0] == 0 and inverse:
+        warn('singular inverse transform; consider changing the bias', stacklevel=3)
+        # fix coefficient to obtain (potentially correct) inverse anyway
+        u = np.copy(u)
+        u[0] = np.inf
+
+    return u
+
+
+@xp_capabilities(out_of_scope=True)
+def fhtoffset(dln, mu, initial=0.0, bias=0.0):
+    """Return optimal offset for a fast Hankel transform.
+
+    Returns an offset close to `initial` that fulfils the low-ringing
+    condition of [1]_ for the fast Hankel transform `fht` with logarithmic
+    spacing `dln`, order `mu` and bias `bias`.
+
+    Parameters
+    ----------
+    dln : float
+        Uniform logarithmic spacing of the transform.
+    mu : float
+        Order of the Hankel transform, any positive or negative real number.
+    initial : float, optional
+        Initial value for the offset. Returns the closest value that fulfils
+        the low-ringing condition.
+    bias : float, optional
+        Exponent of power law bias, any positive or negative real number.
+
+    Returns
+    -------
+    offset : float
+        Optimal offset of the uniform logarithmic spacing of the transform that
+        fulfils a low-ringing condition.
+
+    Examples
+    --------
+    >>> from scipy.fft import fhtoffset
+    >>> dln = 0.1
+    >>> mu = 2.0
+    >>> initial = 0.5
+    >>> bias = 0.0
+    >>> offset = fhtoffset(dln, mu, initial, bias)
+    >>> offset
+    0.5454581477676637
+
+    See Also
+    --------
+    fht : Definition of the fast Hankel transform.
+
+    References
+    ----------
+    .. [1] Hamilton A. J. S., 2000, MNRAS, 312, 257 (astro-ph/9905191)
+
+    """
+
+    lnkr, q = initial, bias
+
+    xp = (mu+1+q)/2
+    xm = (mu+1-q)/2
+    y = np.pi/(2*dln)
+    zp = loggamma(xp + 1j*y)
+    zm = loggamma(xm + 1j*y)
+    arg = (LN_2 - lnkr)/dln + (zp.imag + zm.imag)/np.pi
+    return lnkr + (arg - np.round(arg))*dln
+
+
+def _fhtq(a, u, inverse=False, *, xp=None):
+    """Compute the biased fast Hankel transform.
+
+    This is the basic FFTLog routine.
+    """
+    if xp is None:
+        xp = np
+
+    # size of transform
+    n = a.shape[-1]
+
+    # biased fast Hankel transform via real FFT
+    A = rfft(a, axis=-1)
+    if not inverse:
+        # forward transform
+        A *= u
+    else:
+        # backward transform
+        A /= xp.conj(u)
+    A = irfft(A, n, axis=-1)
+    A = xp.flip(A, axis=-1)
+
+    return A
diff --git a/.venv/lib/python3.12/site-packages/scipy/fft/_helper.py b/.venv/lib/python3.12/site-packages/scipy/fft/_helper.py
new file mode 100644
index 0000000000000000000000000000000000000000..c8aa29880e9155e69d380aba4ce7e3aca80468ed
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/fft/_helper.py
@@ -0,0 +1,355 @@
+from functools import update_wrapper, lru_cache
+import inspect
+
+from ._duccfft import helper as _helper
+
+import numpy as np
+from scipy._lib._array_api import array_namespace
+from scipy._lib._array_api import xp_capabilities
+
+
+_init_nd_shape_and_axes = _helper._init_nd_shape_and_axes
+
+
+def next_fast_len(target, real=False):
+    """Find the next fast size of input data to ``fft``, for zero-padding, etc.
+
+    SciPy's FFT algorithms gain their speed by a recursive divide and conquer
+    strategy. This relies on efficient functions for small prime factors of the
+    input length. Thus, the transforms are fastest when using composites of the
+    prime factors handled by the fft implementation. If there are efficient
+    functions for all radices <= `n`, then the result will be a number `x`
+    >= ``target`` with only prime factors < `n`. (Also known as `n`-smooth
+    numbers)
+
+    Parameters
+    ----------
+    target : int
+        Length to start searching from. Must be a positive integer.
+    real : bool, optional
+        True if the FFT involves real input or output (e.g., `rfft` or `hfft`
+        but not `fft`). Defaults to False.
+
+    Returns
+    -------
+    out : int
+        The smallest fast length greater than or equal to ``target``.
+
+    Notes
+    -----
+    The result of this function may change in future as performance
+    considerations change, for example, if new prime factors are added.
+
+    Calling `fft` or `ifft` with real input data performs an ``'R2C'``
+    transform internally.
+
+    Examples
+    --------
+    On a particular machine, an FFT of prime length takes 11.4 ms:
+
+    >>> from scipy import fft
+    >>> import numpy as np
+    >>> rng = np.random.default_rng()
+    >>> min_len = 93059  # prime length is worst case for speed
+    >>> a = rng.standard_normal(min_len)
+    >>> b = fft.fft(a)
+
+    Zero-padding to the next regular length reduces computation time to
+    1.6 ms, a speedup of 7.3 times:
+
+    >>> fft.next_fast_len(min_len, real=True)
+    93312
+    >>> b = fft.fft(a, 93312)
+
+    Rounding up to the next power of 2 is not optimal, taking 3.0 ms to
+    compute; 1.9 times longer than the size given by ``next_fast_len``:
+
+    >>> b = fft.fft(a, 131072)
+
+    """
+    pass
+
+
+# Directly wrap the c-function good_size but take the docstring etc., from the
+# next_fast_len function above
+_sig = inspect.signature(next_fast_len)
+next_fast_len = update_wrapper(lru_cache(_helper.good_size), next_fast_len)
+next_fast_len = xp_capabilities(out_of_scope=True)(next_fast_len)
+next_fast_len.__wrapped__ = _helper.good_size
+next_fast_len.__signature__ = _sig
+
+
+def prev_fast_len(target, real=False):
+    """Find the previous fast size of input data to ``fft``.
+    Useful for discarding a minimal number of samples before FFT.
+
+    SciPy's FFT algorithms gain their speed by a recursive divide and conquer
+    strategy. This relies on efficient functions for small prime factors of the
+    input length. Thus, the transforms are fastest when using composites of the
+    prime factors handled by the fft implementation. If there are efficient
+    functions for all radices <= `n`, then the result will be a number `x`
+    <= ``target`` with only prime factors <= `n`. (Also known as `n`-smooth
+    numbers)
+
+    Parameters
+    ----------
+    target : int
+        Maximum length to search until. Must be a positive integer.
+    real : bool, optional
+        True if the FFT involves real input or output (e.g., `rfft` or `hfft`
+        but not `fft`). Defaults to False.
+
+    Returns
+    -------
+    out : int
+        The largest fast length less than or equal to ``target``.
+
+    Notes
+    -----
+    The result of this function may change in future as performance
+    considerations change, for example, if new prime factors are added.
+
+    Calling `fft` or `ifft` with real input data performs an ``'R2C'``
+    transform internally.
+
+    In the current implementation, prev_fast_len assumes radices of
+    2,3,5,7,11 for complex FFT and 2,3,5 for real FFT.
+
+    Examples
+    --------
+    On a particular machine, an FFT of prime length takes 16.2 ms:
+
+    >>> from scipy import fft
+    >>> import numpy as np
+    >>> rng = np.random.default_rng()
+    >>> max_len = 93059  # prime length is worst case for speed
+    >>> a = rng.standard_normal(max_len)
+    >>> b = fft.fft(a)
+
+    Performing FFT on the maximum fast length less than max_len
+    reduces the computation time to 1.5 ms, a speedup of 10.5 times:
+
+    >>> fft.prev_fast_len(max_len, real=True)
+    92160
+    >>> c = fft.fft(a[:92160]) # discard last 899 samples
+
+    """
+    pass
+
+
+# Directly wrap the c-function prev_good_size but take the docstring etc.,
+# from the prev_fast_len function above
+_sig_prev_fast_len = inspect.signature(prev_fast_len)
+prev_fast_len = update_wrapper(lru_cache()(_helper.prev_good_size), prev_fast_len)
+prev_fast_len = xp_capabilities(out_of_scope=True)(prev_fast_len)
+prev_fast_len.__wrapped__ = _helper.prev_good_size
+prev_fast_len.__signature__ = _sig_prev_fast_len
+
+
+@xp_capabilities()
+def fftfreq(n, d=1.0, *, xp=None, device=None):
+    """Return the Discrete Fourier Transform sample frequencies.
+
+    The returned float array `f` contains the frequency bin centers in cycles
+    per unit of the sample spacing (with zero at the start).  For instance, if
+    the sample spacing is in seconds, then the frequency unit is cycles/second.
+
+    Given a window length `n` and a sample spacing `d`::
+
+      f = [0, 1, ...,   n/2-1,     -n/2, ..., -1] / (d*n)   if n is even
+      f = [0, 1, ..., (n-1)/2, -(n-1)/2, ..., -1] / (d*n)   if n is odd
+
+    Parameters
+    ----------
+    n : int
+        Window length.
+    d : scalar, optional
+        Sample spacing (inverse of the sampling rate). Defaults to 1.
+    xp : array_namespace, optional
+        The namespace for the return array. Default is None, where NumPy is used.
+    device : device, optional
+        The device for the return array.
+        Only valid when `xp.fft.fftfreq` implements the device parameter.
+
+    Returns
+    -------
+    f : ndarray
+        Array of length `n` containing the sample frequencies.
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> import scipy.fft
+    >>> signal = np.array([-2, 8, 6, 4, 1, 0, 3, 5], dtype=float)
+    >>> fourier = scipy.fft.fft(signal)
+    >>> n = signal.size
+    >>> timestep = 0.1
+    >>> freq = scipy.fft.fftfreq(n, d=timestep)
+    >>> freq
+    array([ 0.  ,  1.25,  2.5 , ..., -3.75, -2.5 , -1.25])
+
+    """
+    xp = np if xp is None else xp
+    # numpy does not yet support the `device` keyword
+    # `xp.__name__ != 'numpy'` should be removed when numpy is compatible
+    if hasattr(xp, 'fft') and xp.__name__ != 'numpy':
+        return xp.fft.fftfreq(n, d=d, device=device)
+    if device is not None:
+        raise ValueError('device parameter is not supported for input array type')
+    return np.fft.fftfreq(n, d=d)
+
+
+@xp_capabilities()
+def rfftfreq(n, d=1.0, *, xp=None, device=None):
+    """Return the Discrete Fourier Transform sample frequencies
+    (for usage with rfft, irfft).
+
+    The returned float array `f` contains the frequency bin centers in cycles
+    per unit of the sample spacing (with zero at the start).  For instance, if
+    the sample spacing is in seconds, then the frequency unit is cycles/second.
+
+    Given a window length `n` and a sample spacing `d`::
+
+      f = [0, 1, ...,     n/2-1,     n/2] / (d*n)   if n is even
+      f = [0, 1, ..., (n-1)/2-1, (n-1)/2] / (d*n)   if n is odd
+
+    Unlike `fftfreq` (but like `scipy.fftpack.rfftfreq`)
+    the Nyquist frequency component is considered to be positive.
+
+    Parameters
+    ----------
+    n : int
+        Window length.
+    d : scalar, optional
+        Sample spacing (inverse of the sampling rate). Defaults to 1.
+    xp : array_namespace, optional
+        The namespace for the return array. Default is None, where NumPy is used.
+    device : device, optional
+        The device for the return array.
+        Only valid when `xp.fft.rfftfreq` implements the device parameter.
+
+    Returns
+    -------
+    f : ndarray
+        Array of length ``n//2 + 1`` containing the sample frequencies.
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> import scipy.fft
+    >>> signal = np.array([-2, 8, 6, 4, 1, 0, 3, 5, -3, 4], dtype=float)
+    >>> fourier = scipy.fft.rfft(signal)
+    >>> n = signal.size
+    >>> sample_rate = 100
+    >>> freq = scipy.fft.fftfreq(n, d=1./sample_rate)
+    >>> freq
+    array([  0.,  10.,  20., ..., -30., -20., -10.])
+    >>> freq = scipy.fft.rfftfreq(n, d=1./sample_rate)
+    >>> freq
+    array([  0.,  10.,  20.,  30.,  40.,  50.])
+
+    """
+    xp = np if xp is None else xp
+    # numpy does not yet support the `device` keyword
+    # `xp.__name__ != 'numpy'` should be removed when numpy is compatible
+    if hasattr(xp, 'fft') and xp.__name__ != 'numpy':
+        return xp.fft.rfftfreq(n, d=d, device=device)
+    if device is not None:
+        raise ValueError('device parameter is not supported for input array type')
+    return np.fft.rfftfreq(n, d=d)
+
+
+@xp_capabilities()
+def fftshift(x, axes=None):
+    """Shift the zero-frequency component to the center of the spectrum.
+
+    This function swaps half-spaces for all axes listed (defaults to all).
+    Note that ``y[0]`` is the Nyquist component only if ``len(x)`` is even.
+
+    Parameters
+    ----------
+    x : array_like
+        Input array.
+    axes : int or shape tuple, optional
+        Axes over which to shift.  Default is None, which shifts all axes.
+
+    Returns
+    -------
+    y : ndarray
+        The shifted array.
+
+    See Also
+    --------
+    ifftshift : The inverse of `fftshift`.
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> freqs = np.fft.fftfreq(10, 0.1)
+    >>> freqs
+    array([ 0.,  1.,  2., ..., -3., -2., -1.])
+    >>> np.fft.fftshift(freqs)
+    array([-5., -4., -3., -2., -1.,  0.,  1.,  2.,  3.,  4.])
+
+    Shift the zero-frequency component only along the second axis:
+
+    >>> freqs = np.fft.fftfreq(9, d=1./9).reshape(3, 3)
+    >>> freqs
+    array([[ 0.,  1.,  2.],
+           [ 3.,  4., -4.],
+           [-3., -2., -1.]])
+    >>> np.fft.fftshift(freqs, axes=(1,))
+    array([[ 2.,  0.,  1.],
+           [-4.,  3.,  4.],
+           [-1., -3., -2.]])
+
+    """
+    xp = array_namespace(x)
+    if hasattr(xp, 'fft'):
+        return xp.fft.fftshift(x, axes=axes)
+    x = np.asarray(x)
+    y = np.fft.fftshift(x, axes=axes)
+    return xp.asarray(y)
+
+
+@xp_capabilities()
+def ifftshift(x, axes=None):
+    """The inverse of `fftshift`. Although identical for even-length `x`, the
+    functions differ by one sample for odd-length `x`.
+
+    Parameters
+    ----------
+    x : array_like
+        Input array.
+    axes : int or shape tuple, optional
+        Axes over which to calculate.  Defaults to None, which shifts all axes.
+
+    Returns
+    -------
+    y : ndarray
+        The shifted array.
+
+    See Also
+    --------
+    fftshift : Shift zero-frequency component to the center of the spectrum.
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> freqs = np.fft.fftfreq(9, d=1./9).reshape(3, 3)
+    >>> freqs
+    array([[ 0.,  1.,  2.],
+           [ 3.,  4., -4.],
+           [-3., -2., -1.]])
+    >>> np.fft.ifftshift(np.fft.fftshift(freqs))
+    array([[ 0.,  1.,  2.],
+           [ 3.,  4., -4.],
+           [-3., -2., -1.]])
+
+    """
+    xp = array_namespace(x)
+    if hasattr(xp, 'fft'):
+        return xp.fft.ifftshift(x, axes=axes)
+    x = np.asarray(x)
+    y = np.fft.ifftshift(x, axes=axes)
+    return xp.asarray(y)
diff --git a/.venv/lib/python3.12/site-packages/scipy/fft/_realtransforms.py b/.venv/lib/python3.12/site-packages/scipy/fft/_realtransforms.py
new file mode 100644
index 0000000000000000000000000000000000000000..c67c3c91441c1851d354b238b2e36529b533683a
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/fft/_realtransforms.py
@@ -0,0 +1,759 @@
+from ._basic import _dispatch
+from scipy._lib.uarray import Dispatchable
+from scipy._lib._array_api import xp_capabilities
+import numpy as np
+
+__all__ = ['dct', 'idct', 'dst', 'idst', 'dctn', 'idctn', 'dstn', 'idstn']
+
+
+@xp_capabilities(cpu_only=True, allow_dask_compute=True)
+@_dispatch
+def dctn(x, type=2, s=None, axes=None, norm=None, overwrite_x=False,
+         workers=None, *, orthogonalize=None):
+    """
+    Return multidimensional Discrete Cosine Transform along the specified axes.
+
+    Parameters
+    ----------
+    x : array_like
+        The input array.
+    type : {1, 2, 3, 4}, optional
+        Type of the DCT (see Notes). Default type is 2.
+    s : int or array_like of ints or None, optional
+        The shape of the result. If both `s` and `axes` (see below) are None,
+        `s` is ``x.shape``; if `s` is None but `axes` is not None, then `s` is
+        ``numpy.take(x.shape, axes, axis=0)``.
+        If ``s[i] > x.shape[i]``, the ith dimension of the input is padded with zeros.
+        If ``s[i] < x.shape[i]``, the ith dimension of the input is truncated to length
+        ``s[i]``.
+        If any element of `s` is -1, the size of the corresponding dimension of
+        `x` is used.
+    axes : int or array_like of ints or None, optional
+        Axes over which the DCT is computed. If not given, the last ``len(s)``
+        axes are used, or all axes if `s` is also not specified.
+    norm : {"backward", "ortho", "forward"}, optional
+        Normalization mode (see Notes). Default is "backward".
+    overwrite_x : bool, optional
+        If True, the contents of `x` can be destroyed; the default is False.
+    workers : int, optional
+        Maximum number of workers to use for parallel computation. If negative,
+        the value wraps around from ``os.cpu_count()``.
+        See :func:`~scipy.fft.fft` for more details.
+    orthogonalize : bool, optional
+        Whether to use the orthogonalized DCT variant (see Notes).
+        Defaults to ``True`` when ``norm="ortho"`` and ``False`` otherwise.
+
+        .. versionadded:: 1.8.0
+
+    Returns
+    -------
+    y : ndarray of real
+        The transformed input array.
+
+    See Also
+    --------
+    idctn : Inverse multidimensional DCT
+
+    Notes
+    -----
+    For full details of the DCT types and normalization modes, as well as
+    references, see `dct`.
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy.fft import dctn, idctn
+    >>> rng = np.random.default_rng()
+    >>> y = rng.standard_normal((16, 16))
+    >>> np.allclose(y, idctn(dctn(y)))
+    True
+
+    """
+    return (Dispatchable(x, np.ndarray),)
+
+
+@xp_capabilities(cpu_only=True, allow_dask_compute=True)
+@_dispatch
+def idctn(x, type=2, s=None, axes=None, norm=None, overwrite_x=False,
+          workers=None, orthogonalize=None):
+    """
+    Return multidimensional Inverse Discrete Cosine Transform along the specified axes.
+
+    Parameters
+    ----------
+    x : array_like
+        The input array.
+    type : {1, 2, 3, 4}, optional
+        Type of the DCT (see Notes). Default type is 2.
+    s : int or array_like of ints or None, optional
+        The shape of the result.  If both `s` and `axes` (see below) are
+        None, `s` is ``x.shape``; if `s` is None but `axes` is
+        not None, then `s` is ``numpy.take(x.shape, axes, axis=0)``.
+        If ``s[i] > x.shape[i]``, the ith dimension of the input is padded with zeros.
+        If ``s[i] < x.shape[i]``, the ith dimension of the input is truncated to length
+        ``s[i]``.
+        If any element of `s` is -1, the size of the corresponding dimension of
+        `x` is used.
+    axes : int or array_like of ints or None, optional
+        Axes over which the IDCT is computed. If not given, the last ``len(s)``
+        axes are used, or all axes if `s` is also not specified.
+    norm : {"backward", "ortho", "forward"}, optional
+        Normalization mode (see Notes). Default is "backward".
+    overwrite_x : bool, optional
+        If True, the contents of `x` can be destroyed; the default is False.
+    workers : int, optional
+        Maximum number of workers to use for parallel computation. If negative,
+        the value wraps around from ``os.cpu_count()``.
+        See :func:`~scipy.fft.fft` for more details.
+    orthogonalize : bool, optional
+        Whether to use the orthogonalized IDCT variant (see Notes).
+        Defaults to ``True`` when ``norm="ortho"`` and ``False`` otherwise.
+
+        .. versionadded:: 1.8.0
+
+    Returns
+    -------
+    y : ndarray of real
+        The transformed input array.
+
+    See Also
+    --------
+    dctn : multidimensional DCT
+
+    Notes
+    -----
+    For full details of the IDCT types and normalization modes, as well as
+    references, see `idct`.
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy.fft import dctn, idctn
+    >>> rng = np.random.default_rng()
+    >>> y = rng.standard_normal((16, 16))
+    >>> np.allclose(y, idctn(dctn(y)))
+    True
+
+    """
+    return (Dispatchable(x, np.ndarray),)
+
+
+@xp_capabilities(cpu_only=True, allow_dask_compute=True)
+@_dispatch
+def dstn(x, type=2, s=None, axes=None, norm=None, overwrite_x=False,
+         workers=None, orthogonalize=None):
+    """
+    Return multidimensional Discrete Sine Transform along the specified axes.
+
+    Parameters
+    ----------
+    x : array_like
+        The input array.
+    type : {1, 2, 3, 4}, optional
+        Type of the DST (see Notes). Default type is 2.
+    s : int or array_like of ints or None, optional
+        The shape of the result.  If both `s` and `axes` (see below) are None,
+        `s` is ``x.shape``; if `s` is None but `axes` is not None, then `s` is
+        ``numpy.take(x.shape, axes, axis=0)``.
+        If ``s[i] > x.shape[i]``, the ith dimension of the input is padded with zeros.
+        If ``s[i] < x.shape[i]``, the ith dimension of the input is truncated to length
+        ``s[i]``.
+        If any element of `shape` is -1, the size of the corresponding dimension
+        of `x` is used.
+    axes : int or array_like of ints or None, optional
+        Axes over which the DST is computed. If not given, the last ``len(s)``
+        axes are used, or all axes if `s` is also not specified.
+    norm : {"backward", "ortho", "forward"}, optional
+        Normalization mode (see Notes). Default is "backward".
+    overwrite_x : bool, optional
+        If True, the contents of `x` can be destroyed; the default is False.
+    workers : int, optional
+        Maximum number of workers to use for parallel computation. If negative,
+        the value wraps around from ``os.cpu_count()``.
+        See :func:`~scipy.fft.fft` for more details.
+    orthogonalize : bool, optional
+        Whether to use the orthogonalized DST variant (see Notes).
+        Defaults to ``True`` when ``norm="ortho"`` and ``False`` otherwise.
+
+        .. versionadded:: 1.8.0
+
+    Returns
+    -------
+    y : ndarray of real
+        The transformed input array.
+
+    See Also
+    --------
+    idstn : Inverse multidimensional DST
+
+    Notes
+    -----
+    For full details of the DST types and normalization modes, as well as
+    references, see `dst`.
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy.fft import dstn, idstn
+    >>> rng = np.random.default_rng()
+    >>> y = rng.standard_normal((16, 16))
+    >>> np.allclose(y, idstn(dstn(y)))
+    True
+
+    """
+    return (Dispatchable(x, np.ndarray),)
+
+
+@xp_capabilities(cpu_only=True, allow_dask_compute=True)
+@_dispatch
+def idstn(x, type=2, s=None, axes=None, norm=None, overwrite_x=False,
+          workers=None, orthogonalize=None):
+    """
+    Return multidimensional Inverse Discrete Sine Transform along the specified axes.
+
+    Parameters
+    ----------
+    x : array_like
+        The input array.
+    type : {1, 2, 3, 4}, optional
+        Type of the DST (see Notes). Default type is 2.
+    s : int or array_like of ints or None, optional
+        The shape of the result.  If both `s` and `axes` (see below) are None,
+        `s` is ``x.shape``; if `s` is None but `axes` is not None, then `s` is
+        ``numpy.take(x.shape, axes, axis=0)``.
+        If ``s[i] > x.shape[i]``, the ith dimension of the input is padded with zeros.
+        If ``s[i] < x.shape[i]``, the ith dimension of the input is truncated to length
+        ``s[i]``.
+        If any element of `s` is -1, the size of the corresponding dimension of
+        `x` is used.
+    axes : int or array_like of ints or None, optional
+        Axes over which the IDST is computed. If not given, the last ``len(s)``
+        axes are used, or all axes if `s` is also not specified.
+    norm : {"backward", "ortho", "forward"}, optional
+        Normalization mode (see Notes). Default is "backward".
+    overwrite_x : bool, optional
+        If True, the contents of `x` can be destroyed; the default is False.
+    workers : int, optional
+        Maximum number of workers to use for parallel computation. If negative,
+        the value wraps around from ``os.cpu_count()``.
+        See :func:`~scipy.fft.fft` for more details.
+    orthogonalize : bool, optional
+        Whether to use the orthogonalized IDST variant (see Notes).
+        Defaults to ``True`` when ``norm="ortho"`` and ``False`` otherwise.
+
+        .. versionadded:: 1.8.0
+
+    Returns
+    -------
+    y : ndarray of real
+        The transformed input array.
+
+    See Also
+    --------
+    dstn : multidimensional DST
+
+    Notes
+    -----
+    For full details of the IDST types and normalization modes, as well as
+    references, see `idst`.
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy.fft import dstn, idstn
+    >>> rng = np.random.default_rng()
+    >>> y = rng.standard_normal((16, 16))
+    >>> np.allclose(y, idstn(dstn(y)))
+    True
+
+    """
+    return (Dispatchable(x, np.ndarray),)
+
+
+@xp_capabilities(cpu_only=True, allow_dask_compute=True,
+                 skip_backends=[('jax.numpy', 'XXX large tolerance violations')])
+@_dispatch
+def dct(x, type=2, n=None, axis=-1, norm=None, overwrite_x=False, workers=None,
+        orthogonalize=None):
+    r"""Return the Discrete Cosine Transform of arbitrary type sequence x.
+
+    Parameters
+    ----------
+    x : array_like
+        The input array.
+    type : {1, 2, 3, 4}, optional
+        Type of the DCT (see Notes). Default type is 2.
+    n : int, optional
+        Length of the transform.  If ``n < x.shape[axis]``, `x` is
+        truncated.  If ``n > x.shape[axis]``, `x` is zero-padded. The
+        default results in ``n = x.shape[axis]``.
+    axis : int, optional
+        Axis along which the dct is computed; the default is over the
+        last axis (i.e., ``axis=-1``).
+    norm : {"backward", "ortho", "forward"}, optional
+        Normalization mode (see Notes). Default is "backward".
+    overwrite_x : bool, optional
+        If True, the contents of `x` can be destroyed; the default is False.
+    workers : int, optional
+        Maximum number of workers to use for parallel computation. If negative,
+        the value wraps around from ``os.cpu_count()``.
+        See :func:`~scipy.fft.fft` for more details.
+    orthogonalize : bool, optional
+        Whether to use the orthogonalized DCT variant (see Notes).
+        Defaults to ``True`` when ``norm="ortho"`` and ``False`` otherwise.
+
+        .. versionadded:: 1.8.0
+
+    Returns
+    -------
+    y : ndarray of real
+        The transformed input array.
+
+    See Also
+    --------
+    idct : Inverse DCT
+
+    Notes
+    -----
+    For a single dimension array ``x``, ``dct(x, norm='ortho')`` is equal to
+    MATLAB ``dct(x)``.
+
+    .. warning:: For ``type in {1, 2, 3}``, ``norm="ortho"`` breaks the direct
+                 correspondence with the direct Fourier transform. To recover
+                 it you must specify ``orthogonalize=False``.
+
+    For ``norm="ortho"`` both the `dct` and `idct` are scaled by the same
+    overall factor in both directions. By default, the transform is also
+    orthogonalized which for types 1, 2 and 3 means the transform definition is
+    modified to give orthogonality of the DCT matrix (see below).
+
+    For ``norm="backward"``, there is no scaling on `dct` and the `idct` is
+    scaled by ``1/N`` where ``N`` is the "logical" size of the DCT. For
+    ``norm="forward"`` the ``1/N`` normalization is applied to the forward
+    `dct` instead and the `idct` is unnormalized.
+
+    There are, theoretically, 8 types of the DCT, only the first 4 types are
+    implemented in SciPy.'The' DCT generally refers to DCT type 2, and 'the'
+    Inverse DCT generally refers to DCT type 3.
+
+    **Type I**
+
+    There are several definitions of the DCT-I; we use the following
+    (for ``norm="backward"``)
+
+    .. math::
+
+       y_k = x_0 + (-1)^k x_{N-1} + 2 \sum_{n=1}^{N-2} x_n \cos\left(
+       \frac{\pi k n}{N-1} \right)
+
+    If ``orthogonalize=True``, ``x[0]`` and ``x[N-1]`` are multiplied by a
+    scaling factor of :math:`\sqrt{2}`, and ``y[0]`` and ``y[N-1]`` are divided
+    by :math:`\sqrt{2}`. When combined with ``norm="ortho"``, this makes the
+    corresponding matrix of coefficients orthonormal (``O @ O.T = np.eye(N)``).
+
+    .. note::
+       The DCT-I is only supported for input size > 1.
+
+    **Type II**
+
+    There are several definitions of the DCT-II; we use the following
+    (for ``norm="backward"``)
+
+    .. math::
+
+       y_k = 2 \sum_{n=0}^{N-1} x_n \cos\left(\frac{\pi k(2n+1)}{2N} \right)
+
+    If ``orthogonalize=True``, ``y[0]`` is divided by :math:`\sqrt{2}` which,
+    when combined with ``norm="ortho"``, makes the corresponding matrix of
+    coefficients orthonormal (``O @ O.T = np.eye(N)``).
+
+    **Type III**
+
+    There are several definitions, we use the following (for
+    ``norm="backward"``)
+
+    .. math::
+
+       y_k = x_0 + 2 \sum_{n=1}^{N-1} x_n \cos\left(\frac{\pi(2k+1)n}{2N}\right)
+
+    If ``orthogonalize=True``, ``x[0]`` terms are multiplied by
+    :math:`\sqrt{2}` which, when combined with ``norm="ortho"``, makes the
+    corresponding matrix of coefficients orthonormal (``O @ O.T = np.eye(N)``).
+
+    The (unnormalized) DCT-III is the inverse of the (unnormalized) DCT-II, up
+    to a factor `2N`. The orthonormalized DCT-III is exactly the inverse of
+    the orthonormalized DCT-II.
+
+    **Type IV**
+
+    There are several definitions of the DCT-IV; we use the following
+    (for ``norm="backward"``)
+
+    .. math::
+
+       y_k = 2 \sum_{n=0}^{N-1} x_n \cos\left(\frac{\pi(2k+1)(2n+1)}{4N} \right)
+
+    ``orthogonalize`` has no effect here, as the DCT-IV matrix is already
+    orthogonal up to a scale factor of ``2N``.
+
+    References
+    ----------
+    .. [1] 'A Fast Cosine Transform in One and Two Dimensions', by J.
+           Makhoul, `IEEE Transactions on acoustics, speech and signal
+           processing` vol. 28(1), pp. 27-34,
+           :doi:`10.1109/TASSP.1980.1163351` (1980).
+    .. [2] Wikipedia, "Discrete cosine transform",
+           https://en.wikipedia.org/wiki/Discrete_cosine_transform
+
+    Examples
+    --------
+    The Type 1 DCT is equivalent to the FFT (though faster) for real,
+    even-symmetrical inputs. The output is also real and even-symmetrical.
+    Half of the FFT input is used to generate half of the FFT output:
+
+    >>> from scipy.fft import fft, dct
+    >>> import numpy as np
+    >>> fft(np.array([4., 3., 5., 10., 5., 3.])).real
+    array([ 30.,  -8.,   6.,  -2.,   6.,  -8.])
+    >>> dct(np.array([4., 3., 5., 10.]), 1)
+    array([ 30.,  -8.,   6.,  -2.])
+
+    """
+    return (Dispatchable(x, np.ndarray),)
+
+
+@xp_capabilities(cpu_only=True, allow_dask_compute=True)
+@_dispatch
+def idct(x, type=2, n=None, axis=-1, norm=None, overwrite_x=False,
+         workers=None, orthogonalize=None):
+    """
+    Return the Inverse Discrete Cosine Transform of an arbitrary type sequence.
+
+    Parameters
+    ----------
+    x : array_like
+        The input array.
+    type : {1, 2, 3, 4}, optional
+        Type of the DCT (see Notes). Default type is 2.
+    n : int, optional
+        Length of the transform.  If ``n < x.shape[axis]``, `x` is
+        truncated.  If ``n > x.shape[axis]``, `x` is zero-padded. The
+        default results in ``n = x.shape[axis]``.
+    axis : int, optional
+        Axis along which the idct is computed; the default is over the
+        last axis (i.e., ``axis=-1``).
+    norm : {"backward", "ortho", "forward"}, optional
+        Normalization mode (see Notes). Default is "backward".
+    overwrite_x : bool, optional
+        If True, the contents of `x` can be destroyed; the default is False.
+    workers : int, optional
+        Maximum number of workers to use for parallel computation. If negative,
+        the value wraps around from ``os.cpu_count()``.
+        See :func:`~scipy.fft.fft` for more details.
+    orthogonalize : bool, optional
+        Whether to use the orthogonalized IDCT variant (see Notes).
+        Defaults to ``True`` when ``norm="ortho"`` and ``False`` otherwise.
+
+        .. versionadded:: 1.8.0
+
+    Returns
+    -------
+    idct : ndarray of real
+        The transformed input array.
+
+    See Also
+    --------
+    dct : Forward DCT
+
+    Notes
+    -----
+    For a single dimension array `x`, ``idct(x, norm='ortho')`` is equal to
+    MATLAB ``idct(x)``.
+
+    .. warning:: For ``type in {1, 2, 3}``, ``norm="ortho"`` breaks the direct
+                 correspondence with the inverse direct Fourier transform. To
+                 recover it you must specify ``orthogonalize=False``.
+
+    For ``norm="ortho"`` both the `dct` and `idct` are scaled by the same
+    overall factor in both directions. By default, the transform is also
+    orthogonalized which for types 1, 2 and 3 means the transform definition is
+    modified to give orthogonality of the IDCT matrix (see `dct` for the full
+    definitions).
+
+    'The' IDCT is the IDCT-II, which is the same as the normalized DCT-III.
+
+    The IDCT is equivalent to a normal DCT except for the normalization and
+    type. DCT type 1 and 4 are their own inverse and DCTs 2 and 3 are each
+    other's inverses.
+
+    Examples
+    --------
+    The Type 1 DCT is equivalent to the DFT for real, even-symmetrical
+    inputs. The output is also real and even-symmetrical. Half of the IFFT
+    input is used to generate half of the IFFT output:
+
+    >>> from scipy.fft import ifft, idct
+    >>> import numpy as np
+    >>> ifft(np.array([ 30.,  -8.,   6.,  -2.,   6.,  -8.])).real
+    array([  4.,   3.,   5.,  10.,   5.,   3.])
+    >>> idct(np.array([ 30.,  -8.,   6.,  -2.]), 1)
+    array([  4.,   3.,   5.,  10.])
+
+    """
+    return (Dispatchable(x, np.ndarray),)
+
+
+@xp_capabilities(cpu_only=True, allow_dask_compute=True,
+                 skip_backends=[('jax.numpy', 'XXX large tolerance violations')])
+@_dispatch
+def dst(x, type=2, n=None, axis=-1, norm=None, overwrite_x=False, workers=None,
+        orthogonalize=None):
+    r"""
+    Return the Discrete Sine Transform of arbitrary type sequence x.
+
+    Parameters
+    ----------
+    x : array_like
+        The input array.
+    type : {1, 2, 3, 4}, optional
+        Type of the DST (see Notes). Default type is 2.
+    n : int, optional
+        Length of the transform. If ``n < x.shape[axis]``, `x` is
+        truncated.  If ``n > x.shape[axis]``, `x` is zero-padded. The
+        default results in ``n = x.shape[axis]``.
+    axis : int, optional
+        Axis along which the dst is computed; the default is over the
+        last axis (i.e., ``axis=-1``).
+    norm : {"backward", "ortho", "forward"}, optional
+        Normalization mode (see Notes). Default is "backward".
+    overwrite_x : bool, optional
+        If True, the contents of `x` can be destroyed; the default is False.
+    workers : int, optional
+        Maximum number of workers to use for parallel computation. If negative,
+        the value wraps around from ``os.cpu_count()``.
+        See :func:`~scipy.fft.fft` for more details.
+    orthogonalize : bool, optional
+        Whether to use the orthogonalized DST variant (see Notes).
+        Defaults to ``True`` when ``norm="ortho"`` and ``False`` otherwise.
+
+        .. versionadded:: 1.8.0
+
+    Returns
+    -------
+    dst : ndarray of reals
+        The transformed input array.
+
+    See Also
+    --------
+    idst : Inverse DST
+
+    Notes
+    -----
+    .. warning:: For ``type in {2, 3}``, ``norm="ortho"`` breaks the direct
+                 correspondence with the direct Fourier transform. To recover
+                 it you must specify ``orthogonalize=False``.
+
+    For ``norm="ortho"`` both the `dst` and `idst` are scaled by the same
+    overall factor in both directions. By default, the transform is also
+    orthogonalized which for types 2 and 3 means the transform definition is
+    modified to give orthogonality of the DST matrix (see below).
+
+    For ``norm="backward"``, there is no scaling on the `dst` and the `idst` is
+    scaled by ``1/N`` where ``N`` is the "logical" size of the DST.
+
+    There are, theoretically, 8 types of the DST for different combinations of
+    even/odd boundary conditions and boundary off sets [1]_, only the first
+    4 types are implemented in SciPy.
+
+    **Type I**
+
+    There are several definitions of the DST-I; we use the following for
+    ``norm="backward"``. DST-I assumes the input is odd around :math:`n=-1` and
+    :math:`n=N`.
+
+    .. math::
+
+        y_k = 2 \sum_{n=0}^{N-1} x_n \sin\left(\frac{\pi(k+1)(n+1)}{N+1}\right)
+
+    Note that the DST-I is only supported for input size > 1.
+    The (unnormalized) DST-I is its own inverse, up to a factor :math:`2(N+1)`.
+    The orthonormalized DST-I is exactly its own inverse.
+
+    ``orthogonalize`` has no effect here, as the DST-I matrix is already
+    orthogonal up to a scale factor of ``2N``.
+
+    **Type II**
+
+    There are several definitions of the DST-II; we use the following for
+    ``norm="backward"``. DST-II assumes the input is odd around :math:`n=-1/2` and
+    :math:`n=N-1/2`; the output is odd around :math:`k=-1` and even around :math:`k=N-1`
+
+    .. math::
+
+        y_k = 2 \sum_{n=0}^{N-1} x_n \sin\left(\frac{\pi(k+1)(2n+1)}{2N}\right)
+
+    If ``orthogonalize=True``, ``y[-1]`` is divided :math:`\sqrt{2}` which, when
+    combined with ``norm="ortho"``, makes the corresponding matrix of
+    coefficients orthonormal (``O @ O.T = np.eye(N)``).
+
+    **Type III**
+
+    There are several definitions of the DST-III, we use the following (for
+    ``norm="backward"``). DST-III assumes the input is odd around :math:`n=-1` and
+    even around :math:`n=N-1`
+
+    .. math::
+
+        y_k = (-1)^k x_{N-1} + 2 \sum_{n=0}^{N-2} x_n \sin\left(
+        \frac{\pi(2k+1)(n+1)}{2N}\right)
+
+    If ``orthogonalize=True``, ``x[-1]`` is multiplied by :math:`\sqrt{2}`
+    which, when combined with ``norm="ortho"``, makes the corresponding matrix
+    of coefficients orthonormal (``O @ O.T = np.eye(N)``).
+
+    The (unnormalized) DST-III is the inverse of the (unnormalized) DST-II, up
+    to a factor :math:`2N`. The orthonormalized DST-III is exactly the inverse of the
+    orthonormalized DST-II.
+
+    **Type IV**
+
+    There are several definitions of the DST-IV, we use the following (for
+    ``norm="backward"``). DST-IV assumes the input is odd around :math:`n=-1/2` and
+    even around :math:`n=N-1/2`
+
+    .. math::
+
+        y_k = 2 \sum_{n=0}^{N-1} x_n \sin\left(\frac{\pi(2k+1)(2n+1)}{4N}\right)
+
+    ``orthogonalize`` has no effect here, as the DST-IV matrix is already
+    orthogonal up to a scale factor of ``2N``.
+
+    The (unnormalized) DST-IV is its own inverse, up to a factor :math:`2N`. The
+    orthonormalized DST-IV is exactly its own inverse.
+
+    Examples
+    --------
+    Compute the DST of a simple 1D array:
+
+    >>> import numpy as np
+    >>> from scipy.fft import dst
+    >>> x = np.array([1, -1, 1, -1])
+    >>> dst(x, type=2)
+    array([0., 0., 0., 8.])
+
+    This computes the Discrete Sine Transform (DST) of type-II for the input array.
+    The output contains the transformed values corresponding to the given input sequence
+
+    References
+    ----------
+    .. [1] Wikipedia, "Discrete sine transform",
+           https://en.wikipedia.org/wiki/Discrete_sine_transform
+
+    """
+    return (Dispatchable(x, np.ndarray),)
+
+
+@xp_capabilities(cpu_only=True, allow_dask_compute=True)
+@_dispatch
+def idst(x, type=2, n=None, axis=-1, norm=None, overwrite_x=False,
+         workers=None, orthogonalize=None):
+    """
+    Return the Inverse Discrete Sine Transform of an arbitrary type sequence.
+
+    Parameters
+    ----------
+    x : array_like
+        The input array.
+    type : {1, 2, 3, 4}, optional
+        Type of the DST (see Notes). Default type is 2.
+    n : int, optional
+        Length of the transform. If ``n < x.shape[axis]``, `x` is
+        truncated.  If ``n > x.shape[axis]``, `x` is zero-padded. The
+        default results in ``n = x.shape[axis]``.
+    axis : int, optional
+        Axis along which the idst is computed; the default is over the
+        last axis (i.e., ``axis=-1``).
+    norm : {"backward", "ortho", "forward"}, optional
+        Normalization mode (see Notes). Default is "backward".
+    overwrite_x : bool, optional
+        If True, the contents of `x` can be destroyed; the default is False.
+    workers : int, optional
+        Maximum number of workers to use for parallel computation. If negative,
+        the value wraps around from ``os.cpu_count()``.
+        See :func:`~scipy.fft.fft` for more details.
+    orthogonalize : bool, optional
+        Whether to use the orthogonalized IDST variant (see Notes).
+        Defaults to ``True`` when ``norm="ortho"`` and ``False`` otherwise.
+
+        .. versionadded:: 1.8.0
+
+    Returns
+    -------
+    idst : ndarray of real
+        The transformed input array.
+
+    See Also
+    --------
+    dst : Forward DST
+    irfft : Inverse FFT for real input
+
+    Notes
+    -----
+    .. warning:: For ``type in {2, 3}``, ``norm="ortho"`` breaks the direct
+                 correspondence with the inverse direct Fourier transform.
+
+    For ``norm="ortho"`` both the `dst` and `idst` are scaled by the same
+    overall factor in both directions. By default, the transform is also
+    orthogonalized which for types 2 and 3 means the transform definition is
+    modified to give orthogonality of the DST matrix (see `dst` for the full
+    definitions).
+
+    'The' IDST is the IDST-II, which is the same as the normalized DST-III.
+
+    The IDST is equivalent to a normal DST except for the normalization and
+    type. DST type 1 and 4 are their own inverse and DSTs 2 and 3 are each
+    other's inverses. For an example that demonstrates the relation between
+    the DST and ISDT, consult the :ref:`DST and IDST `
+    section of the :ref:`user_guide`.
+
+    Examples
+    --------
+    The following example calculates the signal from a spectrum `X` where only the first
+    bin has a non-zero value. The signal for all four DST types is plotted:
+
+    >>> import numpy as np
+    >>> import matplotlib.pyplot as plt
+    >>> from scipy.fft import idst
+    ...
+    >>> N = 15
+    >>> X = np.array([0, N])  # the last `N-2` bin zero-valued bins are not needed
+    ...
+    >>> _, ax = plt.subplots()
+    >>> ax.set(title=f"Inverse of one component DST ({N} samples)",
+    ...        xlim=(0, N), xlabel="k", ylabel="x[k]")
+    >>> for t_ in range(1, 5):
+    ...     x = idst(X, type=t_, n=N)  # parameter `n` pads `X` to length `N`.
+    ...     ax.plot(x, '.-', alpha=0.5, label=f"Type {t_}")
+    >>> ax.grid(True)
+    >>> ax.legend()
+    >>> plt.show()
+
+    The resulting signals are sines with their period and their phase determined by the
+    used DST type. The following table shows those, with `N` being the number of signal
+    samples and `n` is the index of the non-zero bin (here: ``N, n = 15, 1``):
+
+    +------+------------------------------+------------------------+
+    | Type | period in samples            | phase shift in samples |
+    +======+==============================+========================+
+    |  1   | :math:`2 (N+1) / (n+1) = 16` | :math:`-1`             |
+    +------+------------------------------+------------------------+
+    |  2   | :math:`2 N / (n+1) = 15`     | :math:`-1/2`           |
+    +------+------------------------------+------------------------+
+    |  3   | :math:`2 N / (n+1/2) = 20`   | :math:`-1`             |
+    +------+------------------------------+------------------------+
+    |  4   | :math:`2 N / (n+1/2) = 20`   | :math:`-1/2`           |
+    +------+------------------------------+------------------------+
+
+    """
+    return (Dispatchable(x, np.ndarray),)
+
diff --git a/.venv/lib/python3.12/site-packages/scipy/fft/_realtransforms_backend.py b/.venv/lib/python3.12/site-packages/scipy/fft/_realtransforms_backend.py
new file mode 100644
index 0000000000000000000000000000000000000000..533c5f9b9917350c75978f6b941d8d31d78a1969
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/fft/_realtransforms_backend.py
@@ -0,0 +1,63 @@
+from scipy._lib._array_api import array_namespace
+import numpy as np
+from . import _duccfft
+
+__all__ = ['dct', 'idct', 'dst', 'idst', 'dctn', 'idctn', 'dstn', 'idstn']
+
+
+def _execute(duccfft_func, x, type, s, axes, norm, 
+             overwrite_x, workers, orthogonalize):
+    xp = array_namespace(x)
+    x = np.asarray(x)
+    y = duccfft_func(x, type, s, axes, norm,
+                       overwrite_x=overwrite_x, workers=workers,
+                       orthogonalize=orthogonalize)
+    return xp.asarray(y)
+
+
+def dctn(x, type=2, s=None, axes=None, norm=None,
+         overwrite_x=False, workers=None, *, orthogonalize=None):
+    return _execute(_duccfft.dctn, x, type, s, axes, norm, 
+                    overwrite_x, workers, orthogonalize)
+
+
+def idctn(x, type=2, s=None, axes=None, norm=None,
+          overwrite_x=False, workers=None, *, orthogonalize=None):
+    return _execute(_duccfft.idctn, x, type, s, axes, norm, 
+                    overwrite_x, workers, orthogonalize)
+
+
+def dstn(x, type=2, s=None, axes=None, norm=None,
+         overwrite_x=False, workers=None, orthogonalize=None):
+    return _execute(_duccfft.dstn, x, type, s, axes, norm, 
+                    overwrite_x, workers, orthogonalize)
+
+
+def idstn(x, type=2, s=None, axes=None, norm=None,
+          overwrite_x=False, workers=None, *, orthogonalize=None):
+    return _execute(_duccfft.idstn, x, type, s, axes, norm, 
+                    overwrite_x, workers, orthogonalize)
+
+
+def dct(x, type=2, n=None, axis=-1, norm=None,
+        overwrite_x=False, workers=None, orthogonalize=None):
+    return _execute(_duccfft.dct, x, type, n, axis, norm, 
+                    overwrite_x, workers, orthogonalize)
+
+
+def idct(x, type=2, n=None, axis=-1, norm=None,
+         overwrite_x=False, workers=None, orthogonalize=None):
+    return _execute(_duccfft.idct, x, type, n, axis, norm, 
+                    overwrite_x, workers, orthogonalize)
+
+
+def dst(x, type=2, n=None, axis=-1, norm=None,
+        overwrite_x=False, workers=None, orthogonalize=None):
+    return _execute(_duccfft.dst, x, type, n, axis, norm, 
+                    overwrite_x, workers, orthogonalize)
+
+
+def idst(x, type=2, n=None, axis=-1, norm=None,
+         overwrite_x=False, workers=None, orthogonalize=None):
+    return _execute(_duccfft.idst, x, type, n, axis, norm, 
+                    overwrite_x, workers, orthogonalize)
diff --git a/.venv/lib/python3.12/site-packages/scipy/fft/tests/__init__.py b/.venv/lib/python3.12/site-packages/scipy/fft/tests/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/.venv/lib/python3.12/site-packages/scipy/fft/tests/mock_backend.py b/.venv/lib/python3.12/site-packages/scipy/fft/tests/mock_backend.py
new file mode 100644
index 0000000000000000000000000000000000000000..48a7d2b3b50501b84f7c18e366ad2e66782b4ab6
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/fft/tests/mock_backend.py
@@ -0,0 +1,96 @@
+import numpy as np
+import scipy.fft
+import threading
+
+class _MockFunction:
+    def __init__(self, return_value = None):
+        self.number_calls = threading.local()
+        self.return_value = return_value
+        self.last_args = threading.local()
+
+    def __call__(self, *args, **kwargs):
+        if not hasattr(self.number_calls, 'c'):
+            self.number_calls.c = 0
+
+        self.number_calls.c += 1
+        self.last_args.l = (args, kwargs)
+        return self.return_value
+
+
+fft = _MockFunction(np.random.random(10))
+fft2 = _MockFunction(np.random.random(10))
+fftn = _MockFunction(np.random.random(10))
+
+ifft = _MockFunction(np.random.random(10))
+ifft2 = _MockFunction(np.random.random(10))
+ifftn = _MockFunction(np.random.random(10))
+
+rfft = _MockFunction(np.random.random(10))
+rfft2 = _MockFunction(np.random.random(10))
+rfftn = _MockFunction(np.random.random(10))
+
+irfft = _MockFunction(np.random.random(10))
+irfft2 = _MockFunction(np.random.random(10))
+irfftn = _MockFunction(np.random.random(10))
+
+hfft = _MockFunction(np.random.random(10))
+hfft2 = _MockFunction(np.random.random(10))
+hfftn = _MockFunction(np.random.random(10))
+
+ihfft = _MockFunction(np.random.random(10))
+ihfft2 = _MockFunction(np.random.random(10))
+ihfftn = _MockFunction(np.random.random(10))
+
+dct = _MockFunction(np.random.random(10))
+idct = _MockFunction(np.random.random(10))
+dctn = _MockFunction(np.random.random(10))
+idctn = _MockFunction(np.random.random(10))
+
+dst = _MockFunction(np.random.random(10))
+idst = _MockFunction(np.random.random(10))
+dstn = _MockFunction(np.random.random(10))
+idstn = _MockFunction(np.random.random(10))
+
+fht = _MockFunction(np.random.random(10))
+ifht = _MockFunction(np.random.random(10))
+
+
+__ua_domain__ = "numpy.scipy.fft"
+
+
+_implements = {
+    scipy.fft.fft: fft,
+    scipy.fft.fft2: fft2,
+    scipy.fft.fftn: fftn,
+    scipy.fft.ifft: ifft,
+    scipy.fft.ifft2: ifft2,
+    scipy.fft.ifftn: ifftn,
+    scipy.fft.rfft: rfft,
+    scipy.fft.rfft2: rfft2,
+    scipy.fft.rfftn: rfftn,
+    scipy.fft.irfft: irfft,
+    scipy.fft.irfft2: irfft2,
+    scipy.fft.irfftn: irfftn,
+    scipy.fft.hfft: hfft,
+    scipy.fft.hfft2: hfft2,
+    scipy.fft.hfftn: hfftn,
+    scipy.fft.ihfft: ihfft,
+    scipy.fft.ihfft2: ihfft2,
+    scipy.fft.ihfftn: ihfftn,
+    scipy.fft.dct: dct,
+    scipy.fft.idct: idct,
+    scipy.fft.dctn: dctn,
+    scipy.fft.idctn: idctn,
+    scipy.fft.dst: dst,
+    scipy.fft.idst: idst,
+    scipy.fft.dstn: dstn,
+    scipy.fft.idstn: idstn,
+    scipy.fft.fht: fht,
+    scipy.fft.ifht: ifht
+}
+
+
+def __ua_function__(method, args, kwargs):
+    fn = _implements.get(method)
+    return (fn(*args, **kwargs) if fn is not None
+            else NotImplemented)
diff --git a/.venv/lib/python3.12/site-packages/scipy/fft/tests/test_backend.py b/.venv/lib/python3.12/site-packages/scipy/fft/tests/test_backend.py
new file mode 100644
index 0000000000000000000000000000000000000000..8df1a0cec1b2973f2d0e778155a1d88bb456a9c2
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/fft/tests/test_backend.py
@@ -0,0 +1,98 @@
+from functools import partial
+
+import numpy as np
+import scipy.fft
+from scipy.fft import _fftlog, _duccfft, set_backend
+from scipy.fft.tests import mock_backend
+
+from numpy.testing import assert_allclose, assert_equal
+import pytest
+
+fnames = ('fft', 'fft2', 'fftn',
+          'ifft', 'ifft2', 'ifftn',
+          'rfft', 'rfft2', 'rfftn',
+          'irfft', 'irfft2', 'irfftn',
+          'dct', 'idct', 'dctn', 'idctn',
+          'dst', 'idst', 'dstn', 'idstn',
+          'fht', 'ifht')
+
+np_funcs = (np.fft.fft, np.fft.fft2, np.fft.fftn,
+            np.fft.ifft, np.fft.ifft2, np.fft.ifftn,
+            np.fft.rfft, np.fft.rfft2, np.fft.rfftn,
+            np.fft.irfft, np.fft.irfft2, np.fft.irfftn,
+            np.fft.hfft, _duccfft.hfft2, _duccfft.hfftn,  # np has no hfftn
+            np.fft.ihfft, _duccfft.ihfft2, _duccfft.ihfftn,
+            _duccfft.dct, _duccfft.idct, _duccfft.dctn, _duccfft.idctn,
+            _duccfft.dst, _duccfft.idst, _duccfft.dstn, _duccfft.idstn,
+            # must provide required kwargs for fht, ifht
+            partial(_fftlog.fht, dln=2, mu=0.5),
+            partial(_fftlog.ifht, dln=2, mu=0.5))
+
+funcs = (scipy.fft.fft, scipy.fft.fft2, scipy.fft.fftn,
+         scipy.fft.ifft, scipy.fft.ifft2, scipy.fft.ifftn,
+         scipy.fft.rfft, scipy.fft.rfft2, scipy.fft.rfftn,
+         scipy.fft.irfft, scipy.fft.irfft2, scipy.fft.irfftn,
+         scipy.fft.hfft, scipy.fft.hfft2, scipy.fft.hfftn,
+         scipy.fft.ihfft, scipy.fft.ihfft2, scipy.fft.ihfftn,
+         scipy.fft.dct, scipy.fft.idct, scipy.fft.dctn, scipy.fft.idctn,
+         scipy.fft.dst, scipy.fft.idst, scipy.fft.dstn, scipy.fft.idstn,
+         # must provide required kwargs for fht, ifht
+         partial(scipy.fft.fht, dln=2, mu=0.5),
+         partial(scipy.fft.ifht, dln=2, mu=0.5))
+
+mocks = (mock_backend.fft, mock_backend.fft2, mock_backend.fftn,
+         mock_backend.ifft, mock_backend.ifft2, mock_backend.ifftn,
+         mock_backend.rfft, mock_backend.rfft2, mock_backend.rfftn,
+         mock_backend.irfft, mock_backend.irfft2, mock_backend.irfftn,
+         mock_backend.hfft, mock_backend.hfft2, mock_backend.hfftn,
+         mock_backend.ihfft, mock_backend.ihfft2, mock_backend.ihfftn,
+         mock_backend.dct, mock_backend.idct,
+         mock_backend.dctn, mock_backend.idctn,
+         mock_backend.dst, mock_backend.idst,
+         mock_backend.dstn, mock_backend.idstn,
+         mock_backend.fht, mock_backend.ifht)
+
+
+@pytest.mark.parametrize("func, np_func, mock", list(zip(funcs, np_funcs, mocks)))
+def test_backend_call(func, np_func, mock):
+    x = np.arange(20).reshape((10,2))
+    answer = np_func(x.astype(np.float64))
+    assert_allclose(func(x), answer, atol=1e-10)
+
+    with set_backend(mock_backend, only=True):
+        mock.number_calls.c = 0
+        y = func(x)
+        assert_equal(y, mock.return_value)
+        assert_equal(mock.number_calls.c, 1)
+
+    assert_allclose(func(x), answer, atol=1e-10)
+
+
+plan_funcs = (scipy.fft.fft, scipy.fft.fft2, scipy.fft.fftn,
+              scipy.fft.ifft, scipy.fft.ifft2, scipy.fft.ifftn,
+              scipy.fft.rfft, scipy.fft.rfft2, scipy.fft.rfftn,
+              scipy.fft.irfft, scipy.fft.irfft2, scipy.fft.irfftn,
+              scipy.fft.hfft, scipy.fft.hfft2, scipy.fft.hfftn,
+              scipy.fft.ihfft, scipy.fft.ihfft2, scipy.fft.ihfftn)
+
+plan_mocks = (mock_backend.fft, mock_backend.fft2, mock_backend.fftn,
+              mock_backend.ifft, mock_backend.ifft2, mock_backend.ifftn,
+              mock_backend.rfft, mock_backend.rfft2, mock_backend.rfftn,
+              mock_backend.irfft, mock_backend.irfft2, mock_backend.irfftn,
+              mock_backend.hfft, mock_backend.hfft2, mock_backend.hfftn,
+              mock_backend.ihfft, mock_backend.ihfft2, mock_backend.ihfftn)
+
+
+@pytest.mark.parametrize("func, mock", list(zip(plan_funcs, plan_mocks)))
+def test_backend_plan(func, mock):
+    x = np.arange(20).reshape((10, 2))
+
+    with pytest.raises(NotImplementedError, match='precomputed plan'):
+        func(x, plan='foo')
+
+    with set_backend(mock_backend, only=True):
+        mock.number_calls.c = 0
+        y = func(x, plan='foo')
+        assert_equal(y, mock.return_value)
+        assert_equal(mock.number_calls.c, 1)
+        assert_equal(mock.last_args.l[1]['plan'], 'foo')
diff --git a/.venv/lib/python3.12/site-packages/scipy/fft/tests/test_basic.py b/.venv/lib/python3.12/site-packages/scipy/fft/tests/test_basic.py
new file mode 100644
index 0000000000000000000000000000000000000000..27355db3f16b08d64bd6e2fe17c71f1e5de6dda7
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/fft/tests/test_basic.py
@@ -0,0 +1,551 @@
+import queue
+import threading
+import multiprocessing
+import numpy as np
+import pytest
+from numpy.random import random
+from numpy.testing import assert_array_almost_equal, assert_allclose
+from pytest import raises as assert_raises
+import scipy.fft as fft
+from scipy._lib._array_api import (
+    is_numpy, xp_size, xp_assert_close, xp_assert_equal, make_xp_test_case,
+    make_xp_pytest_param
+)
+
+lazy_xp_modules = [fft]
+skip_xp_backends = pytest.mark.skip_xp_backends
+
+
+# Expected input dtypes. Note that `scipy.fft` is more flexible for numpy,
+# but for C2C transforms like `fft.fft`, the array API standard only mandates
+# that complex dtypes should work, float32/float64 aren't guaranteed to.
+def get_expected_input_dtype(func, xp):
+    # use __name__ so that `lazy_xp_function` doesn't break things
+    if func.__name__ in ["fft", "fftn", "fft2", "ifft", "ifftn", "ifft2", "hfft",
+                         "hfftn", "hfft2", "irfft", "irfftn", "irfft2"]:
+        dtype = xp.complex128
+    elif func.__name__ in ["rfft", "rfftn", "rfft2", "ihfft", "ihfftn", "ihfft2"]:
+        dtype = xp.float64
+    else:
+        raise ValueError(f'Unknown FFT function: {func}')
+
+    return dtype
+
+
+def fft1(x):
+    L = len(x)
+    phase = -2j*np.pi*(np.arange(L)/float(L))
+    phase = np.arange(L).reshape(-1, 1) * phase
+    return np.sum(x*np.exp(phase), axis=1)
+
+
+class TestFFT:
+    @make_xp_test_case(fft.ifft, fft.fft, fft.rfft, fft.irfft)
+    def test_identity(self, xp):
+        maxlen = 512
+        x = xp.asarray(random(maxlen) + 1j*random(maxlen))
+        xr = xp.asarray(random(maxlen))
+        # Check some powers of 2 and some primes
+        for i in [1, 2, 16, 128, 512, 53, 149, 281, 397]:
+            xp_assert_close(fft.ifft(fft.fft(x[0:i])), x[0:i])
+            xp_assert_close(fft.irfft(fft.rfft(xr[0:i]), i), xr[0:i])
+
+    @skip_xp_backends(np_only=True, reason='significant overhead for some backends')
+    @make_xp_test_case(fft.ifft, fft.fft, fft.rfft, fft.irfft)
+    def test_identity_extensive(self, xp):
+        maxlen = 512
+        x = xp.asarray(random(maxlen) + 1j*random(maxlen))
+        xr = xp.asarray(random(maxlen))
+        for i in range(1, maxlen):
+            xp_assert_close(fft.ifft(fft.fft(x[0:i])), x[0:i])
+            xp_assert_close(fft.irfft(fft.rfft(xr[0:i]), i), xr[0:i])
+
+    @make_xp_test_case(fft.fft)
+    def test_fft(self, xp):
+        x = random(30) + 1j*random(30)
+        expect = xp.asarray(fft1(x))
+        x = xp.asarray(x)
+        xp_assert_close(fft.fft(x), expect)
+        xp_assert_close(fft.fft(x, norm="backward"), expect)
+        xp_assert_close(fft.fft(x, norm="ortho"),
+                        expect / xp.sqrt(xp.asarray(30, dtype=xp.float64)),)
+        xp_assert_close(fft.fft(x, norm="forward"), expect / 30)
+
+    @skip_xp_backends(np_only=True, reason='some backends allow `n=0`')
+    @make_xp_test_case(fft.fft)
+    def test_fft_n(self, xp):
+        x = xp.asarray([1, 2, 3], dtype=xp.complex128)
+        assert_raises(ValueError, fft.fft, x, 0)
+
+    @make_xp_test_case(fft.fft, fft.ifft)
+    def test_ifft(self, xp):
+        x = xp.asarray(random(30) + 1j*random(30))
+        xp_assert_close(fft.ifft(fft.fft(x)), x)
+        for norm in ["backward", "ortho", "forward"]:
+            xp_assert_close(fft.ifft(fft.fft(x, norm=norm), norm=norm), x)
+
+    @make_xp_test_case(fft.fft, fft.fft2)
+    def test_fft2(self, xp):
+        x = xp.asarray(random((30, 20)) + 1j*random((30, 20)))
+        expect = fft.fft(fft.fft(x, axis=1), axis=0)
+        xp_assert_close(fft.fft2(x), expect)
+        xp_assert_close(fft.fft2(x, norm="backward"), expect)
+        xp_assert_close(fft.fft2(x, norm="ortho"),
+                        expect / xp.sqrt(xp.asarray(30 * 20, dtype=xp.float64)))
+        xp_assert_close(fft.fft2(x, norm="forward"), expect / (30 * 20))
+
+    @make_xp_test_case(fft.ifft, fft.ifft2)
+    def test_ifft2(self, xp):
+        x = xp.asarray(random((30, 20)) + 1j*random((30, 20)))
+        expect = fft.ifft(fft.ifft(x, axis=1), axis=0)
+        xp_assert_close(fft.ifft2(x), expect)
+        xp_assert_close(fft.ifft2(x, norm="backward"), expect)
+        xp_assert_close(fft.ifft2(x, norm="ortho"),
+                        expect * xp.sqrt(xp.asarray(30 * 20, dtype=xp.float64)))
+        xp_assert_close(fft.ifft2(x, norm="forward"), expect * (30 * 20))
+
+    @make_xp_test_case(fft.fft, fft.fftn)
+    def test_fftn(self, xp):
+        x = xp.asarray(random((30, 20, 10)) + 1j*random((30, 20, 10)))
+        expect = fft.fft(fft.fft(fft.fft(x, axis=2), axis=1), axis=0)
+        xp_assert_close(fft.fftn(x), expect)
+        xp_assert_close(fft.fftn(x, norm="backward"), expect)
+        xp_assert_close(fft.fftn(x, norm="ortho"),
+                        expect / xp.sqrt(xp.asarray(30 * 20 * 10, dtype=xp.float64)))
+        xp_assert_close(fft.fftn(x, norm="forward"), expect / (30 * 20 * 10))
+
+    @make_xp_test_case(fft.ifft, fft.ifftn)
+    def test_ifftn(self, xp):
+        x = xp.asarray(random((30, 20, 10)) + 1j*random((30, 20, 10)))
+        expect = fft.ifft(fft.ifft(fft.ifft(x, axis=2), axis=1), axis=0)
+        xp_assert_close(fft.ifftn(x), expect, rtol=1e-7)
+        xp_assert_close(fft.ifftn(x, norm="backward"), expect, rtol=1e-7)
+        xp_assert_close(
+            fft.ifftn(x, norm="ortho"),
+            fft.ifftn(x) * xp.sqrt(xp.asarray(30 * 20 * 10, dtype=xp.float64))
+        )
+        xp_assert_close(fft.ifftn(x, norm="forward"),
+                        expect * (30 * 20 * 10),
+                        rtol=1e-7)
+
+    @make_xp_test_case(fft.fft, fft.rfft)
+    def test_rfft(self, xp):
+        x = xp.asarray(random(29), dtype=xp.float64)
+        for n in [xp_size(x), 2*xp_size(x)]:
+            for norm in [None, "backward", "ortho", "forward"]:
+                xp_assert_close(fft.rfft(x, n=n, norm=norm),
+                                fft.fft(xp.asarray(x, dtype=xp.complex128),
+                                        n=n, norm=norm)[:(n//2 + 1)])
+            xp_assert_close(
+                fft.rfft(x, n=n, norm="ortho"),
+                fft.rfft(x, n=n) / xp.sqrt(xp.asarray(n, dtype=xp.float64))
+            )
+
+    @make_xp_test_case(fft.irfft, fft.rfft)
+    def test_irfft(self, xp):
+        x = xp.asarray(random(30))
+        xp_assert_close(fft.irfft(fft.rfft(x)), x)
+        for norm in ["backward", "ortho", "forward"]:
+            xp_assert_close(fft.irfft(fft.rfft(x, norm=norm), norm=norm), x)
+
+    @make_xp_test_case(fft.rfft2)
+    def test_rfft2(self, xp):
+        x = xp.asarray(random((30, 20)), dtype=xp.float64)
+        expect = fft.fft2(xp.asarray(x, dtype=xp.complex128))[:, :11]
+        xp_assert_close(fft.rfft2(x), expect)
+        xp_assert_close(fft.rfft2(x, norm="backward"), expect)
+        xp_assert_close(fft.rfft2(x, norm="ortho"),
+                        expect / xp.sqrt(xp.asarray(30 * 20, dtype=xp.float64)))
+        xp_assert_close(fft.rfft2(x, norm="forward"), expect / (30 * 20))
+
+    @make_xp_test_case(fft.rfft2, fft.irfft2)
+    def test_irfft2(self, xp):
+        x = xp.asarray(random((30, 20)))
+        xp_assert_close(fft.irfft2(fft.rfft2(x)), x)
+        for norm in ["backward", "ortho", "forward"]:
+            xp_assert_close(fft.irfft2(fft.rfft2(x, norm=norm), norm=norm), x)
+
+    @make_xp_test_case(fft.fftn, fft.rfftn)
+    def test_rfftn(self, xp):
+        x = xp.asarray(random((30, 20, 10)), dtype=xp.float64)
+        expect = fft.fftn(xp.asarray(x, dtype=xp.complex128))[:, :, :6]
+        xp_assert_close(fft.rfftn(x), expect)
+        xp_assert_close(fft.rfftn(x, norm="backward"), expect)
+        xp_assert_close(fft.rfftn(x, norm="ortho"),
+                        expect / xp.sqrt(xp.asarray(30 * 20 * 10, dtype=xp.float64)))
+        xp_assert_close(fft.rfftn(x, norm="forward"), expect / (30 * 20 * 10))
+
+    @make_xp_test_case(fft.irfftn, fft.rfftn)
+    def test_irfftn(self, xp):
+        x = xp.asarray(random((30, 20, 10)))
+        xp_assert_close(fft.irfftn(fft.rfftn(x)), x)
+        for norm in ["backward", "ortho", "forward"]:
+            xp_assert_close(fft.irfftn(fft.rfftn(x, norm=norm), norm=norm), x)
+
+    @make_xp_test_case(fft.hfft, fft.fft)
+    def test_hfft(self, xp):
+        x = random(14) + 1j*random(14)
+        x_herm = np.concatenate((random(1), x, random(1)))
+        x = np.concatenate((x_herm, x[::-1].conj()))
+        x = xp.asarray(x)
+        x_herm = xp.asarray(x_herm)
+        expect = xp.real(fft.fft(x))
+        xp_assert_close(fft.hfft(x_herm), expect)
+        xp_assert_close(fft.hfft(x_herm, norm="backward"), expect)
+        xp_assert_close(fft.hfft(x_herm, norm="ortho"),
+                        expect / xp.sqrt(xp.asarray(30, dtype=xp.float64)))
+        xp_assert_close(fft.hfft(x_herm, norm="forward"), expect / 30)
+
+    @make_xp_test_case(fft.hfft, fft.ihfft)
+    def test_ihfft(self, xp):
+        x = random(14) + 1j*random(14)
+        x_herm = np.concatenate((random(1), x, random(1)))
+        x = np.concatenate((x_herm, x[::-1].conj()))
+        x = xp.asarray(x)
+        x_herm = xp.asarray(x_herm)
+        xp_assert_close(fft.ihfft(fft.hfft(x_herm)), x_herm)
+        for norm in ["backward", "ortho", "forward"]:
+            xp_assert_close(fft.ihfft(fft.hfft(x_herm, norm=norm), norm=norm), x_herm)
+
+    @make_xp_test_case(fft.hfft2, fft.ihfft2)
+    def test_hfft2(self, xp):
+        x = xp.asarray(random((30, 20)))
+        xp_assert_close(fft.hfft2(fft.ihfft2(x)), x)
+        for norm in ["backward", "ortho", "forward"]:
+            xp_assert_close(fft.hfft2(fft.ihfft2(x, norm=norm), norm=norm), x)
+
+    @make_xp_test_case(fft.ifft2)
+    def test_ihfft2(self, xp):
+        x = xp.asarray(random((30, 20)), dtype=xp.float64)
+        expect = fft.ifft2(xp.asarray(x, dtype=xp.complex128))[:, :11]
+        xp_assert_close(fft.ihfft2(x), expect)
+        xp_assert_close(fft.ihfft2(x, norm="backward"), expect)
+        xp_assert_close(
+            fft.ihfft2(x, norm="ortho"),
+            expect * xp.sqrt(xp.asarray(30 * 20, dtype=xp.float64))
+        )
+        xp_assert_close(fft.ihfft2(x, norm="forward"), expect * (30 * 20))
+
+    @make_xp_test_case(fft.hfftn, fft.ihfftn)
+    def test_hfftn(self, xp):
+        x = xp.asarray(random((30, 20, 10)))
+        xp_assert_close(fft.hfftn(fft.ihfftn(x)), x)
+        for norm in ["backward", "ortho", "forward"]:
+            xp_assert_close(fft.hfftn(fft.ihfftn(x, norm=norm), norm=norm), x)
+
+    @make_xp_test_case(fft.ifftn, fft.ihfftn)
+    def test_ihfftn(self, xp):
+        x = xp.asarray(random((30, 20, 10)), dtype=xp.float64)
+        expect = fft.ifftn(xp.asarray(x, dtype=xp.complex128))[:, :, :6]
+        xp_assert_close(expect, fft.ihfftn(x))
+        xp_assert_close(expect, fft.ihfftn(x, norm="backward"))
+        xp_assert_close(
+            fft.ihfftn(x, norm="ortho"),
+            expect * xp.sqrt(xp.asarray(30 * 20 * 10, dtype=xp.float64))
+        )
+        xp_assert_close(fft.ihfftn(x, norm="forward"), expect * (30 * 20 * 10))
+
+    def _check_axes(self, op, xp):
+        dtype = get_expected_input_dtype(op, xp)
+        x = xp.asarray(random((30, 20, 10)), dtype=dtype)
+        axes = [(0, 1, 2), (0, 2, 1), (1, 0, 2), (1, 2, 0), (2, 0, 1), (2, 1, 0)]
+
+        for a in axes:
+            op_tr = op(xp.permute_dims(x, axes=a))
+            tr_op = xp.permute_dims(op(x, axes=a), axes=a)
+            xp_assert_close(op_tr, tr_op)
+
+    @pytest.mark.parametrize("op", [make_xp_pytest_param(fft.fftn),
+                                    make_xp_pytest_param(fft.ifftn),
+                                    make_xp_pytest_param(fft.rfftn),
+                                    make_xp_pytest_param(fft.irfftn)])
+    def test_axes_standard(self, op, xp):
+        self._check_axes(op, xp)
+
+    @pytest.mark.parametrize("op", [make_xp_pytest_param(fft.hfftn),
+                                    make_xp_pytest_param(fft.ihfftn)])
+    def test_axes_non_standard(self, op, xp):
+        self._check_axes(op, xp)
+
+    @pytest.mark.parametrize("op", [make_xp_pytest_param(fft.fftn),
+                                    make_xp_pytest_param(fft.ifftn),
+                                    make_xp_pytest_param(fft.rfftn),
+                                    make_xp_pytest_param(fft.irfftn)])
+    def test_axes_subset_with_shape_standard(self, op, xp):
+        dtype = get_expected_input_dtype(op, xp)
+        x = xp.asarray(random((16, 8, 4)), dtype=dtype)
+        axes = [(0, 1, 2), (0, 2, 1), (1, 2, 0)]
+
+        for a in axes:
+            # different shape on the first two axes
+            shape = tuple([2*x.shape[ax] if ax in a[:2] else x.shape[ax]
+                           for ax in range(x.ndim)])
+            # transform only the first two axes
+            op_tr = op(xp.permute_dims(x, axes=a),
+                       s=shape[:2], axes=(0, 1))
+            tr_op = xp.permute_dims(op(x, s=shape[:2], axes=a[:2]),
+                                         axes=a)
+            xp_assert_close(op_tr, tr_op)
+
+    @pytest.mark.parametrize("op", [make_xp_pytest_param(fft.fft2),
+                                    make_xp_pytest_param(fft.ifft2),
+                                    make_xp_pytest_param(fft.rfft2),
+                                    make_xp_pytest_param(fft.irfft2),
+                                    make_xp_pytest_param(fft.hfft2),
+                                    make_xp_pytest_param(fft.ihfft2),
+                                    make_xp_pytest_param(fft.hfftn),
+                                    make_xp_pytest_param(fft.ihfftn)])
+    def test_axes_subset_with_shape_non_standard(self, op, xp):
+        dtype = get_expected_input_dtype(op, xp)
+        x = xp.asarray(random((16, 8, 4)), dtype=dtype)
+        axes = [(0, 1, 2), (0, 2, 1), (1, 2, 0)]
+
+        for a in axes:
+            # different shape on the first two axes
+            shape = tuple([2*x.shape[ax] if ax in a[:2] else x.shape[ax]
+                           for ax in range(x.ndim)])
+            # transform only the first two axes
+            op_tr = op(xp.permute_dims(x, axes=a), s=shape[:2], axes=(0, 1))
+            tr_op = xp.permute_dims(op(x, s=shape[:2], axes=a[:2]), axes=a)
+            xp_assert_close(op_tr, tr_op)
+
+    @make_xp_test_case(fft.rfft, fft.irfft, fft.ihfft, fft.hfft, fft.fft, fft.ifft)
+    def test_all_1d_norm_preserving(self, xp):
+        # verify that round-trip transforms are norm-preserving
+        x = xp.asarray(random(30), dtype=xp.float64)
+
+        x_norm = xp.linalg.vector_norm(x)
+        n = xp_size(x) * 2
+        func_pairs = [(fft.rfft, fft.irfft),
+                      # hfft: order so the first function takes x.size samples
+                      #       (necessary for comparison to x_norm above)
+                      (fft.ihfft, fft.hfft),
+                      # functions that expect complex dtypes at the end
+                      (fft.fft, fft.ifft),
+                      ]
+        for forw, back in func_pairs:
+            if forw == fft.fft:
+                x = xp.asarray(x, dtype=xp.complex128)
+                x_norm = xp.linalg.vector_norm(x)
+            for n in [xp_size(x), 2*xp_size(x)]:
+                for norm in ['backward', 'ortho', 'forward']:
+                    tmp = forw(x, n=n, norm=norm)
+                    tmp = back(tmp, n=n, norm=norm)
+                    xp_assert_close(xp.linalg.vector_norm(tmp), x_norm)
+
+    @pytest.mark.parametrize("dtype", [np.float16, np.longdouble])
+    def test_dtypes_nonstandard(self, dtype):
+        x = random(30).astype(dtype)
+        out_dtypes = {np.float16: np.complex64, np.longdouble: np.clongdouble}
+        x_complex = x.astype(out_dtypes[dtype])
+
+        res_fft = fft.ifft(fft.fft(x))
+        res_rfft = fft.irfft(fft.rfft(x))
+        res_hfft = fft.hfft(fft.ihfft(x), x.shape[0])
+        # Check both numerical results and exact dtype matches
+        assert_array_almost_equal(res_fft, x_complex)
+        assert_array_almost_equal(res_rfft, x)
+        assert_array_almost_equal(res_hfft, x)
+        assert res_fft.dtype == x_complex.dtype
+        assert res_rfft.dtype == np.result_type(np.float32, x.dtype)
+        assert res_hfft.dtype == np.result_type(np.float32, x.dtype)
+
+    @make_xp_test_case(fft.irfft, fft.rfft)
+    @pytest.mark.parametrize("dtype", ["float32", "float64"])
+    def test_dtypes_real(self, dtype, xp):
+        x = xp.asarray(random(30), dtype=getattr(xp, dtype))
+
+        res_rfft = fft.irfft(fft.rfft(x))
+        res_hfft = fft.hfft(fft.ihfft(x), x.shape[0])
+        # Check both numerical results and exact dtype matches
+        xp_assert_close(res_rfft, x)
+        xp_assert_close(res_hfft, x)
+
+    @make_xp_test_case(fft.fft, fft.ifft)
+    @pytest.mark.parametrize("dtype", ["complex64", "complex128"])
+    def test_dtypes_complex(self, dtype, xp):
+        rng = np.random.default_rng(1234)
+        x = xp.asarray(rng.random(30), dtype=getattr(xp, dtype))
+
+        res_fft = fft.ifft(fft.fft(x))
+        # Check both numerical results and exact dtype matches
+        xp_assert_close(res_fft, x)
+
+    @pytest.mark.parametrize("op", [fft.fft, fft.ifft,
+                                    fft.fft2, fft.ifft2,
+                                    fft.fftn, fft.ifftn,
+                                    fft.rfft, fft.irfft,
+                                    fft.rfft2, fft.irfft2,
+                                    fft.rfftn, fft.irfftn,
+                                    fft.hfft, fft.ihfft,
+                                    fft.hfft2, fft.ihfft2,
+                                    fft.hfftn, fft.ihfftn,])
+    def test_array_like(self, op):
+        x = [[[1.0, 1.0], [1.0, 1.0]],
+             [[1.0, 1.0], [1.0, 1.0]],
+             [[1.0, 1.0], [1.0, 1.0]]]
+        xp_assert_close(op(x), op(np.asarray(x)))
+
+
+@pytest.mark.parametrize(
+        "dtype",
+        [np.float32, np.float64, np.longdouble,
+         np.complex64, np.complex128, np.clongdouble])
+@pytest.mark.parametrize("order", ["F", 'non-contiguous'])
+@pytest.mark.parametrize(
+        "fft",
+        [fft.fft, fft.fft2, fft.fftn, fft.ifft, fft.ifft2, fft.ifftn])
+def test_fft_with_order(dtype, order, fft):
+    # Check that FFT/IFFT produces identical results for C, Fortran and
+    # non contiguous arrays
+    rng = np.random.RandomState(42)
+    X = rng.rand(8, 7, 13).astype(dtype, copy=False)
+    if order == 'F':
+        Y = np.asfortranarray(X)
+    else:
+        # Make a non contiguous array
+        Y = X[::-1]
+        X = np.ascontiguousarray(X[::-1])
+
+    if fft.__name__.endswith('fft'):
+        for axis in range(3):
+            X_res = fft(X, axis=axis)
+            Y_res = fft(Y, axis=axis)
+            assert_array_almost_equal(X_res, Y_res)
+    elif fft.__name__.endswith(('fft2', 'fftn')):
+        axes = [(0, 1), (1, 2), (0, 2)]
+        if fft.__name__.endswith('fftn'):
+            axes.extend([(0,), (1,), (2,), None])
+        for ax in axes:
+            X_res = fft(X, axes=ax)
+            Y_res = fft(Y, axes=ax)
+            assert_allclose(X_res, Y_res, rtol=3e-6, atol=3e-6)
+    else:
+        raise ValueError
+
+
+@skip_xp_backends(cpu_only=True)
+class TestFFTThreadSafe:
+    threads = 16
+    input_shape = (800, 200)
+
+    def _test_mtsame(self, func, *args, xp=None):
+        def worker(args, q):
+            q.put(func(*args))
+
+        q = queue.Queue()
+        expected = func(*args)
+
+        # Spin off a bunch of threads to call the same function simultaneously
+        t = [threading.Thread(target=worker, args=(args, q))
+             for i in range(self.threads)]
+        [x.start() for x in t]
+
+        [x.join() for x in t]
+
+        # Make sure all threads returned the correct value
+        for i in range(self.threads):
+            xp_assert_equal(
+                q.get(timeout=5), expected,
+                err_msg='Function returned wrong value in multithreaded context'
+            )
+
+    @make_xp_test_case(fft.fft)
+    def test_fft(self, xp):
+        a = xp.ones(self.input_shape, dtype=xp.complex128)
+        self._test_mtsame(fft.fft, a, xp=xp)
+
+    @make_xp_test_case(fft.ifft)
+    def test_ifft(self, xp):
+        a = xp.full(self.input_shape, 1+0j)
+        self._test_mtsame(fft.ifft, a, xp=xp)
+
+    @make_xp_test_case(fft.rfft)
+    def test_rfft(self, xp):
+        a = xp.ones(self.input_shape)
+        self._test_mtsame(fft.rfft, a, xp=xp)
+
+    @make_xp_test_case(fft.irfft)
+    def test_irfft(self, xp):
+        a = xp.full(self.input_shape, 1+0j)
+        self._test_mtsame(fft.irfft, a, xp=xp)
+
+    @make_xp_test_case(fft.hfft)
+    def test_hfft(self, xp):
+        a = xp.ones(self.input_shape, dtype=xp.complex64)
+        self._test_mtsame(fft.hfft, a, xp=xp)
+
+    @make_xp_test_case(fft.ihfft)
+    def test_ihfft(self, xp):
+        a = xp.ones(self.input_shape)
+        self._test_mtsame(fft.ihfft, a, xp=xp)
+
+
+@pytest.mark.parametrize("func", [fft.fft, fft.ifft, fft.rfft, fft.irfft])
+def test_multiprocess(func):
+    # Test that fft still works after fork (gh-10422)
+
+    with multiprocessing.Pool(2) as p:
+        res = p.map(func, [np.ones(100) for _ in range(4)])
+
+    expect = func(np.ones(100))
+    for x in res:
+        assert_allclose(x, expect)
+
+
+@make_xp_test_case(fft.irfftn)
+class TestIRFFTN:
+
+    def test_not_last_axis_success(self, xp):
+        ar, ai = np.random.random((2, 16, 8, 32))
+        a = ar + 1j*ai
+        a = xp.asarray(a)
+
+        axes = (-2,)
+
+        # Should not raise error
+        fft.irfftn(a, axes=axes)
+
+
+@pytest.mark.parametrize("func", [make_xp_pytest_param(fft.fft),
+                                  make_xp_pytest_param(fft.ifft),
+                                  make_xp_pytest_param(fft.rfft),
+                                  make_xp_pytest_param(fft.irfft),
+                                  make_xp_pytest_param(fft.fftn),
+                                  make_xp_pytest_param(fft.ifftn),
+                                  make_xp_pytest_param(fft.rfftn),
+                                  make_xp_pytest_param(fft.irfftn),
+                                  make_xp_pytest_param(fft.hfft),
+                                  make_xp_pytest_param(fft.ihfft)])
+def test_non_standard_params(func, xp):
+    # use __name__ so that `lazy_xp_function` doesn't break things
+    if func.__name__ in ["rfft", "rfftn", "ihfft"]:
+        dtype = xp.float64
+    else:
+        dtype = xp.complex128
+
+    x = xp.asarray([1, 2, 3], dtype=dtype)
+    # func(x) should not raise an exception
+    func(x)
+
+    if is_numpy(xp):
+        func(x, workers=2)
+    else:
+        assert_raises(ValueError, func, x, workers=2)
+
+    # `plan` param is not tested since SciPy does not use it currently
+    # but should be tested if it comes into use
+
+
+@pytest.mark.parametrize("dtype", ['float32', 'float64'])
+@pytest.mark.parametrize("func", [make_xp_pytest_param(fft.fft),
+                                  make_xp_pytest_param(fft.ifft),
+                                  make_xp_pytest_param(fft.irfft),
+                                  make_xp_pytest_param(fft.fftn),
+                                  make_xp_pytest_param(fft.ifftn),
+                                  make_xp_pytest_param(fft.irfftn),
+                                  make_xp_pytest_param(fft.hfft)])
+def test_real_input(func, dtype, xp):
+    x = xp.asarray([1, 2, 3], dtype=getattr(xp, dtype))
+    # func(x) should not raise an exception
+    func(x)
diff --git a/.venv/lib/python3.12/site-packages/scipy/fft/tests/test_fftlog.py b/.venv/lib/python3.12/site-packages/scipy/fft/tests/test_fftlog.py
new file mode 100644
index 0000000000000000000000000000000000000000..27de68b08baf726641a031e79e830ae2fce7be9b
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/fft/tests/test_fftlog.py
@@ -0,0 +1,221 @@
+import warnings
+import math
+
+import numpy as np
+import pytest
+
+from scipy.fft._fftlog import fht, ifht, fhtoffset
+from scipy.special import poch
+
+from scipy._lib._array_api import (
+    xp_assert_close, xp_assert_less, make_xp_test_case, make_xp_pytest_param
+)
+
+skip_xp_backends = pytest.mark.skip_xp_backends
+
+
+@make_xp_test_case(fht, fhtoffset)
+def test_fht_agrees_with_fftlog(xp):
+    # check that fht numerically agrees with the output from Fortran FFTLog,
+    # the results were generated with the provided `fftlogtest` program,
+    # after fixing how the k array is generated (divide range by n-1, not n)
+
+    # test function, analytical Hankel transform is of the same form
+    def f(r, mu):
+        return r**(mu+1)*np.exp(-r**2/2)
+
+    r = np.logspace(-4, 4, 16)
+
+    dln = math.log(r[1]/r[0])
+    mu = 0.3
+    offset = 0.0
+    bias = 0.0
+
+    a = xp.asarray(f(r, mu))
+
+    # test 1: compute as given
+    ours = fht(a, dln, mu, offset=offset, bias=bias)
+    theirs = [-0.1159922613593045E-02, +0.1625822618458832E-02,
+              -0.1949518286432330E-02, +0.3789220182554077E-02,
+              +0.5093959119952945E-03, +0.2785387803618774E-01,
+              +0.9944952700848897E-01, +0.4599202164586588E+00,
+              +0.3157462160881342E+00, -0.8201236844404755E-03,
+              -0.7834031308271878E-03, +0.3931444945110708E-03,
+              -0.2697710625194777E-03, +0.3568398050238820E-03,
+              -0.5554454827797206E-03, +0.8286331026468585E-03]
+    theirs = xp.asarray(theirs, dtype=xp.float64)
+    xp_assert_close(ours, theirs)
+
+    # test 2: change to optimal offset
+    offset = fhtoffset(dln, mu, bias=bias)
+    ours = fht(a, dln, mu, offset=offset, bias=bias)
+    theirs = [+0.4353768523152057E-04, -0.9197045663594285E-05,
+              +0.3150140927838524E-03, +0.9149121960963704E-03,
+              +0.5808089753959363E-02, +0.2548065256377240E-01,
+              +0.1339477692089897E+00, +0.4821530509479356E+00,
+              +0.2659899781579785E+00, -0.1116475278448113E-01,
+              +0.1791441617592385E-02, -0.4181810476548056E-03,
+              +0.1314963536765343E-03, -0.5422057743066297E-04,
+              +0.3208681804170443E-04, -0.2696849476008234E-04]
+    theirs = xp.asarray(theirs, dtype=xp.float64)
+    xp_assert_close(ours, theirs)
+
+    # test 3: positive bias
+    bias = 0.8
+    offset = fhtoffset(dln, mu, bias=bias)
+    # offset is a np.float64, which array-api-strict disallows
+    # even if it's technically a subclass of float
+    offset = float(offset)
+
+    ours = fht(a, dln, mu, offset=offset, bias=bias)
+    theirs = [-7.3436673558316850E+00, +0.1710271207817100E+00,
+              +0.1065374386206564E+00, -0.5121739602708132E-01,
+              +0.2636649319269470E-01, +0.1697209218849693E-01,
+              +0.1250215614723183E+00, +0.4739583261486729E+00,
+              +0.2841149874912028E+00, -0.8312764741645729E-02,
+              +0.1024233505508988E-02, -0.1644902767389120E-03,
+              +0.3305775476926270E-04, -0.7786993194882709E-05,
+              +0.1962258449520547E-05, -0.8977895734909250E-06]
+    theirs = xp.asarray(theirs, dtype=xp.float64)
+    xp_assert_close(ours, theirs)
+
+    # test 4: negative bias
+    bias = -0.8
+    offset = fhtoffset(dln, mu, bias=bias)
+    offset = float(offset)
+
+    ours = fht(a, dln, mu, offset=offset, bias=bias)
+    theirs = [+0.8985777068568745E-05, +0.4074898209936099E-04,
+              +0.2123969254700955E-03, +0.1009558244834628E-02,
+              +0.5131386375222176E-02, +0.2461678673516286E-01,
+              +0.1235812845384476E+00, +0.4719570096404403E+00,
+              +0.2893487490631317E+00, -0.1686570611318716E-01,
+              +0.2231398155172505E-01, -0.1480742256379873E-01,
+              +0.1692387813500801E+00, +0.3097490354365797E+00,
+              +2.7593607182401860E+00, 10.5251075070045800E+00]
+    theirs = xp.asarray(theirs, dtype=xp.float64)
+    xp_assert_close(ours, theirs)
+
+
+@pytest.mark.parametrize('optimal', [True, False])
+@pytest.mark.parametrize('offset', [0.0, 1.0, -1.0])
+@pytest.mark.parametrize('bias', [0, 0.1, -0.1])
+@pytest.mark.parametrize('n', [64, 63])
+@make_xp_test_case(fhtoffset, fht, ifht)
+def test_fht_identity(n, bias, offset, optimal, xp):
+    rng = np.random.RandomState(3491349965)
+
+    a = xp.asarray(rng.standard_normal(n))
+    dln = rng.uniform(-1, 1)
+    mu = rng.uniform(-2, 2)
+
+    if optimal:
+        offset = fhtoffset(dln, mu, initial=offset, bias=bias)
+        # offset is a np.float64, which array-api-strict disallows
+        # even if it's technically a subclass of float
+        offset = float(offset)
+
+    A = fht(a, dln, mu, offset=offset, bias=bias)
+    a_ = ifht(A, dln, mu, offset=offset, bias=bias)
+
+    xp_assert_close(a_, a, rtol=1.5e-7)
+
+
+@make_xp_test_case(fht, ifht)
+def test_fht_special_cases(xp):
+    rng = np.random.RandomState(3491349965)
+
+    a = xp.asarray(rng.standard_normal(64))
+    dln = rng.uniform(-1, 1)
+
+    # let x = (mu+1+q)/2, y = (mu+1-q)/2, M = {0, -1, -2, ...}
+
+    # case 1: x in M, y in M => well-defined transform
+    mu, bias = -4.0, 1.0
+    with warnings.catch_warnings(record=True) as record:
+        fht(a, dln, mu, bias=bias)
+        assert not record, 'fht warned about a well-defined transform'
+
+    # case 2: x not in M, y in M => well-defined transform
+    mu, bias = -2.5, 0.5
+    with warnings.catch_warnings(record=True) as record:
+        fht(a, dln, mu, bias=bias)
+        assert not record, 'fht warned about a well-defined transform'
+
+    # with fht_lock:
+    # case 3: x in M, y not in M => singular transform
+    mu, bias = -3.5, 0.5
+    with pytest.warns(Warning) as record:
+        fht(a, dln, mu, bias=bias)
+        assert record, 'fht did not warn about a singular transform'
+
+    # with fht_lock:
+    # case 4: x not in M, y in M => singular inverse transform
+    mu, bias = -2.5, 0.5
+    with pytest.warns(Warning) as record:
+        ifht(a, dln, mu, bias=bias)
+        assert record, 'ifht did not warn about a singular transform'
+
+
+@pytest.mark.parametrize('n', [64, 63])
+@make_xp_test_case(fht)
+def test_fht_exact(n, xp):
+    rng = np.random.RandomState(3491349965)
+
+    # for a(r) a power law r^\gamma, the fast Hankel transform produces the
+    # exact continuous Hankel transform if biased with q = \gamma
+
+    mu = rng.uniform(0, 3)
+
+    # convergence of HT: -1-mu < gamma < 1/2
+    gamma = rng.uniform(-1-mu, 1/2)
+
+    r = np.logspace(-2, 2, n)
+    a = xp.asarray(r**gamma)
+
+    dln = math.log(r[1]/r[0])
+
+    offset = fhtoffset(dln, mu, initial=0.0, bias=gamma)
+    # offset is a np.float64, which array-api-strict disallows
+    # even if it's technically a subclass of float
+    offset = float(offset)
+
+    A = fht(a, dln, mu, offset=offset, bias=gamma)
+
+    k = np.exp(offset)/r[::-1]
+
+    # analytical result
+    At = xp.asarray((2/k)**gamma * poch((mu+1-gamma)/2, gamma))
+
+    xp_assert_close(A, At)
+
+@skip_xp_backends(np_only=True,
+                  reason='array-likes only supported for NumPy backend')
+@pytest.mark.parametrize(
+    "op", [make_xp_pytest_param(fht), make_xp_pytest_param(ifht)]
+)
+def test_array_like(xp, op):
+    x = [[[1.0, 1.0], [1.0, 1.0]],
+         [[1.0, 1.0], [1.0, 1.0]],
+         [[1.0, 1.0], [1.0, 1.0]]]
+    xp_assert_close(op(x, 1.0, 2.0), op(xp.asarray(x), 1.0, 2.0))
+
+@pytest.mark.parametrize('n', [128, 129])
+@make_xp_test_case(fhtoffset, fht)
+def test_gh_21661(xp, n):
+    one = xp.asarray(1.0)
+    mu = 0.0
+    r = np.logspace(-7, 1, n)
+    dln = math.log(r[1] / r[0])
+    offset = fhtoffset(dln, initial=-6 * np.log(10), mu=mu)
+    r = xp.asarray(r, dtype=one.dtype)
+    k = math.exp(offset) / xp.flip(r, axis=-1)
+
+    def f(x, mu):
+        return x**(mu + 1)*xp.exp(-x**2/2)
+
+    a_r = f(r, mu)
+    fht_val = fht(a_r, dln, mu=mu, offset=offset)
+    a_k = f(k, mu)
+    rel_err = xp.max(xp.abs((fht_val - a_k) / a_k))
+    xp_assert_less(rel_err, xp.asarray(7.28e+16)[()])
diff --git a/.venv/lib/python3.12/site-packages/scipy/fft/tests/test_helper.py b/.venv/lib/python3.12/site-packages/scipy/fft/tests/test_helper.py
new file mode 100644
index 0000000000000000000000000000000000000000..4f8e41992c195808b7d90239ba4673e13df3a1dc
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/fft/tests/test_helper.py
@@ -0,0 +1,560 @@
+"""Includes test functions for fftpack.helper module
+
+Copied from fftpack.helper by Pearu Peterson, October 2005
+Modified for Array API, 2023
+
+"""
+from scipy.fft._helper import next_fast_len, prev_fast_len, _init_nd_shape_and_axes
+from numpy.testing import assert_equal
+from pytest import raises as assert_raises
+import pytest
+import numpy as np
+import sys
+from scipy._lib._array_api import xp_assert_close, xp_device, make_xp_test_case
+from scipy import fft
+
+skip_xp_backends = pytest.mark.skip_xp_backends
+lazy_xp_modules = [fft]
+
+_5_smooth_numbers = [
+    2, 3, 4, 5, 6, 8, 9, 10,
+    2 * 3 * 5,
+    2**3 * 3**5,
+    2**3 * 3**3 * 5**2,
+]
+
+
+def test_next_fast_len():
+    for n in _5_smooth_numbers:
+        assert_equal(next_fast_len(n), n)
+
+
+def _assert_n_smooth(x, n):
+    x_orig = x
+    if n < 2:
+        assert False
+
+    while True:
+        q, r = divmod(x, 2)
+        if r != 0:
+            break
+        x = q
+
+    for d in range(3, n+1, 2):
+        while True:
+            q, r = divmod(x, d)
+            if r != 0:
+                break
+            x = q
+
+    assert x == 1, \
+           f'x={x_orig} is not {n}-smooth, remainder={x}'
+
+
+class TestNextFastLen:
+
+    def test_next_fast_len(self):
+        np.random.seed(1234)
+
+        def nums():
+            yield from range(1, 1000)
+            yield 2**5 * 3**5 * 4**5 + 1
+
+        for n in nums():
+            m = next_fast_len(n)
+            _assert_n_smooth(m, 11)
+            assert m == next_fast_len(n, False)
+
+            m = next_fast_len(n, True)
+            _assert_n_smooth(m, 5)
+
+    def test_np_integers(self):
+        ITYPES = [np.int16, np.int32, np.int64, np.uint16, np.uint32, np.uint64]
+        for ityp in ITYPES:
+            x = ityp(12345)
+            testN = next_fast_len(x)
+            assert_equal(testN, next_fast_len(int(x)))
+
+    def testnext_fast_len_small(self):
+        hams = {
+            1: 1, 2: 2, 3: 3, 4: 4, 5: 5, 6: 6, 7: 8, 8: 8, 14: 15, 15: 15,
+            16: 16, 17: 18, 1021: 1024, 1536: 1536, 51200000: 51200000
+        }
+        for x, y in hams.items():
+            assert_equal(next_fast_len(x, True), y)
+
+    @pytest.mark.xfail(sys.maxsize < 2**32,
+                       reason="Hamming Numbers too large for 32-bit",
+                       raises=ValueError, strict=True)
+    def testnext_fast_len_big(self):
+        hams = {
+            510183360: 510183360, 510183360 + 1: 512000000,
+            511000000: 512000000,
+            854296875: 854296875, 854296875 + 1: 859963392,
+            196608000000: 196608000000, 196608000000 + 1: 196830000000,
+            8789062500000: 8789062500000, 8789062500000 + 1: 8796093022208,
+            206391214080000: 206391214080000,
+            206391214080000 + 1: 206624260800000,
+            470184984576000: 470184984576000,
+            470184984576000 + 1: 470715894135000,
+            7222041363087360: 7222041363087360,
+            7222041363087360 + 1: 7230196133913600,
+            # power of 5    5**23
+            11920928955078125: 11920928955078125,
+            11920928955078125 - 1: 11920928955078125,
+            # power of 3    3**34
+            16677181699666569: 16677181699666569,
+            16677181699666569 - 1: 16677181699666569,
+            # power of 2   2**54
+            18014398509481984: 18014398509481984,
+            18014398509481984 - 1: 18014398509481984,
+            # above this, int(ceil(n)) == int(ceil(n+1))
+            19200000000000000: 19200000000000000,
+            19200000000000000 + 1: 19221679687500000,
+            288230376151711744: 288230376151711744,
+            288230376151711744 + 1: 288325195312500000,
+            288325195312500000 - 1: 288325195312500000,
+            288325195312500000: 288325195312500000,
+            288325195312500000 + 1: 288555831593533440,
+        }
+        for x, y in hams.items():
+            assert_equal(next_fast_len(x, True), y)
+
+    def test_keyword_args(self):
+        assert next_fast_len(11, real=True) == 12
+        assert next_fast_len(target=7, real=False) == 7
+
+
+class TestPrevFastLen:
+
+    def test_prev_fast_len(self):
+        np.random.seed(1234)
+
+        def nums():
+            yield from range(1, 1000)
+            yield 2**5 * 3**5 * 4**5 + 1
+
+        for n in nums():
+            m = prev_fast_len(n)
+            _assert_n_smooth(m, 11)
+            assert m == prev_fast_len(n, False)
+
+            m = prev_fast_len(n, True)
+            _assert_n_smooth(m, 5)
+
+    def test_np_integers(self):
+        ITYPES = [np.int16, np.int32, np.int64, np.uint16, np.uint32,
+                    np.uint64]
+        for ityp in ITYPES:
+            x = ityp(12345)
+            testN = prev_fast_len(x)
+            assert_equal(testN, prev_fast_len(int(x)))
+
+            testN = prev_fast_len(x, real=True)
+            assert_equal(testN, prev_fast_len(int(x), real=True))
+
+    def testprev_fast_len_small(self):
+        hams = {
+            1: 1, 2: 2, 3: 3, 4: 4, 5: 5, 6: 6, 7: 6, 8: 8, 14: 12, 15: 15,
+            16: 16, 17: 16, 1021: 1000, 1536: 1536, 51200000: 51200000
+        }
+        for x, y in hams.items():
+            assert_equal(prev_fast_len(x, True), y)
+
+        hams = {
+            1: 1, 2: 2, 3: 3, 4: 4, 5: 5, 6: 6, 7: 7, 8: 8, 9: 9, 10: 10,
+            11: 11, 12: 12, 13: 12, 14: 14, 15: 15, 16: 16, 17: 16, 18: 18,
+            19: 18, 20: 20, 21: 21, 22: 22, 120: 120, 121: 121, 122: 121,
+            1021: 1008, 1536: 1536, 51200000: 51200000
+        }
+        for x, y in hams.items():
+            assert_equal(prev_fast_len(x, False), y)
+
+    @pytest.mark.xfail(sys.maxsize < 2**32,
+                       reason="Hamming Numbers too large for 32-bit",
+                       raises=ValueError, strict=True)
+    def testprev_fast_len_big(self):
+        hams = {
+            # 2**6 * 3**13 * 5**1
+            510183360: 510183360,
+            510183360 + 1: 510183360,
+            510183360 - 1: 509607936,  # 2**21 * 3**5
+            # 2**6 * 5**6 * 7**1 * 73**1
+            511000000: 510183360,
+            511000000 + 1: 510183360,
+            511000000 - 1: 510183360,  # 2**6 * 3**13 * 5**1
+            # 3**7 * 5**8
+            854296875: 854296875,
+            854296875 + 1: 854296875,
+            854296875 - 1: 850305600,  # 2**6 * 3**12 * 5**2
+            # 2**22 * 3**1 * 5**6
+            196608000000: 196608000000,
+            196608000000 + 1: 196608000000,
+            196608000000 - 1: 195910410240,  # 2**13 * 3**14 * 5**1
+            # 2**5 * 3**2 * 5**15
+            8789062500000: 8789062500000,
+            8789062500000 + 1: 8789062500000,
+            8789062500000 - 1: 8748000000000,  # 2**11 * 3**7 * 5**9
+            # 2**24 * 3**9 * 5**4
+            206391214080000: 206391214080000,
+            206391214080000 + 1: 206391214080000,
+            206391214080000 - 1: 206158430208000,  # 2**39 * 3**1 * 5**3
+            # 2**18 * 3**15 * 5**3
+            470184984576000: 470184984576000,
+            470184984576000 + 1: 470184984576000,
+            470184984576000 - 1: 469654673817600,  # 2**33 * 3**7 **5**2
+            # 2**25 * 3**16 * 5**1
+            7222041363087360: 7222041363087360,
+            7222041363087360 + 1: 7222041363087360,
+            7222041363087360 - 1: 7213895789838336,  # 2**40 * 3**8
+            # power of 5    5**23
+            11920928955078125: 11920928955078125,
+            11920928955078125 + 1: 11920928955078125,
+            11920928955078125 - 1: 11901557422080000,  # 2**14 * 3**19 * 5**4
+            # power of 3    3**34
+            16677181699666569: 16677181699666569,
+            16677181699666569 + 1: 16677181699666569,
+            16677181699666569 - 1: 16607531250000000,  # 2**7 * 3**12 * 5**12
+            # power of 2   2**54
+            18014398509481984: 18014398509481984,
+            18014398509481984 + 1: 18014398509481984,
+            18014398509481984 - 1: 18000000000000000,  # 2**16 * 3**2 * 5**15
+            # 2**20 * 3**1 * 5**14
+            19200000000000000: 19200000000000000,
+            19200000000000000 + 1: 19200000000000000,
+            19200000000000000 - 1: 19131876000000000,  # 2**11 * 3**14 * 5**9
+            # 2**58
+            288230376151711744: 288230376151711744,
+            288230376151711744 + 1: 288230376151711744,
+            288230376151711744 - 1: 288000000000000000,  # 2**20 * 3**2 * 5**15
+            # 2**5 * 3**10 * 5**16
+            288325195312500000: 288325195312500000,
+            288325195312500000 + 1: 288325195312500000,
+            288325195312500000 - 1: 288230376151711744,  # 2**58
+        }
+        for x, y in hams.items():
+            assert_equal(prev_fast_len(x, True), y)
+
+    def test_keyword_args(self):
+        assert prev_fast_len(11, real=True) == 10
+        assert prev_fast_len(target=7, real=False) == 7
+
+
+@skip_xp_backends(cpu_only=True)
+@pytest.mark.uses_xp_capabilities(False, reason="private")
+class Test_init_nd_shape_and_axes:
+
+    def test_py_0d_defaults(self, xp):
+        x = xp.asarray(4)
+        shape = None
+        axes = None
+
+        shape_expected = ()
+        axes_expected = []
+
+        shape_res, axes_res = _init_nd_shape_and_axes(x, shape, axes)
+
+        assert shape_res == shape_expected
+        assert axes_res == axes_expected
+
+    def test_xp_0d_defaults(self, xp):
+        x = xp.asarray(7.)
+        shape = None
+        axes = None
+
+        shape_expected = ()
+        axes_expected = []
+
+        shape_res, axes_res = _init_nd_shape_and_axes(x, shape, axes)
+
+        assert shape_res == shape_expected
+        assert axes_res == axes_expected
+
+    def test_py_1d_defaults(self, xp):
+        x = xp.asarray([1, 2, 3])
+        shape = None
+        axes = None
+
+        shape_expected = (3,)
+        axes_expected = [0]
+
+        shape_res, axes_res = _init_nd_shape_and_axes(x, shape, axes)
+
+        assert shape_res == shape_expected
+        assert axes_res == axes_expected
+
+    def test_xp_1d_defaults(self, xp):
+        x = xp.arange(0, 1, .1)
+        shape = None
+        axes = None
+
+        shape_expected = (10,)
+        axes_expected = [0]
+
+        shape_res, axes_res = _init_nd_shape_and_axes(x, shape, axes)
+
+        assert shape_res == shape_expected
+        assert axes_res == axes_expected
+
+    def test_py_2d_defaults(self, xp):
+        x = xp.asarray([[1, 2, 3, 4],
+                        [5, 6, 7, 8]])
+        shape = None
+        axes = None
+
+        shape_expected = (2, 4)
+        axes_expected = [0, 1]
+
+        shape_res, axes_res = _init_nd_shape_and_axes(x, shape, axes)
+
+        assert shape_res == shape_expected
+        assert axes_res == axes_expected
+
+    def test_xp_2d_defaults(self, xp):
+        x = xp.arange(0, 1, .1)
+        x = xp.reshape(x, (5, 2))
+        shape = None
+        axes = None
+
+        shape_expected = (5, 2)
+        axes_expected = [0, 1]
+
+        shape_res, axes_res = _init_nd_shape_and_axes(x, shape, axes)
+
+        assert shape_res == shape_expected
+        assert axes_res == axes_expected
+
+    def test_xp_5d_defaults(self, xp):
+        x = xp.zeros([6, 2, 5, 3, 4])
+        shape = None
+        axes = None
+
+        shape_expected = (6, 2, 5, 3, 4)
+        axes_expected = [0, 1, 2, 3, 4]
+
+        shape_res, axes_res = _init_nd_shape_and_axes(x, shape, axes)
+
+        assert shape_res == shape_expected
+        assert axes_res == axes_expected
+
+    def test_xp_5d_set_shape(self, xp):
+        x = xp.zeros([6, 2, 5, 3, 4])
+        shape = [10, -1, -1, 1, 4]
+        axes = None
+
+        shape_expected = (10, 2, 5, 1, 4)
+        axes_expected = [0, 1, 2, 3, 4]
+
+        shape_res, axes_res = _init_nd_shape_and_axes(x, shape, axes)
+
+        assert shape_res == shape_expected
+        assert axes_res == axes_expected
+
+    def test_xp_5d_set_axes(self, xp):
+        x = xp.zeros([6, 2, 5, 3, 4])
+        shape = None
+        axes = [4, 1, 2]
+
+        shape_expected = (4, 2, 5)
+        axes_expected = [4, 1, 2]
+
+        shape_res, axes_res = _init_nd_shape_and_axes(x, shape, axes)
+
+        assert shape_res == shape_expected
+        assert axes_res == axes_expected
+
+    def test_xp_5d_set_shape_axes(self, xp):
+        x = xp.zeros([6, 2, 5, 3, 4])
+        shape = [10, -1, 2]
+        axes = [1, 0, 3]
+
+        shape_expected = (10, 6, 2)
+        axes_expected = [1, 0, 3]
+
+        shape_res, axes_res = _init_nd_shape_and_axes(x, shape, axes)
+
+        assert shape_res == shape_expected
+        assert axes_res == axes_expected
+
+    def test_shape_axes_subset(self, xp):
+        x = xp.zeros((2, 3, 4, 5))
+        shape, axes = _init_nd_shape_and_axes(x, shape=(5, 5, 5), axes=None)
+
+        assert shape == (5, 5, 5)
+        assert axes == [1, 2, 3]
+
+    def test_errors(self, xp):
+        x = xp.zeros(1)
+        with assert_raises(ValueError, match="axes must be a scalar or "
+                           "iterable of integers"):
+            _init_nd_shape_and_axes(x, shape=None, axes=[[1, 2], [3, 4]])
+
+        with assert_raises(ValueError, match="axes must be a scalar or "
+                           "iterable of integers"):
+            _init_nd_shape_and_axes(x, shape=None, axes=[1., 2., 3., 4.])
+
+        with assert_raises(ValueError,
+                           match="axes exceeds dimensionality of input"):
+            _init_nd_shape_and_axes(x, shape=None, axes=[1])
+
+        with assert_raises(ValueError,
+                           match="axes exceeds dimensionality of input"):
+            _init_nd_shape_and_axes(x, shape=None, axes=[-2])
+
+        with assert_raises(ValueError,
+                           match="all axes must be unique"):
+            _init_nd_shape_and_axes(x, shape=None, axes=[0, 0])
+
+        with assert_raises(ValueError, match="shape must be a scalar or "
+                           "iterable of integers"):
+            _init_nd_shape_and_axes(x, shape=[[1, 2], [3, 4]], axes=None)
+
+        with assert_raises(ValueError, match="shape must be a scalar or "
+                           "iterable of integers"):
+            _init_nd_shape_and_axes(x, shape=[1., 2., 3., 4.], axes=None)
+
+        with assert_raises(ValueError,
+                           match="when given, axes and shape arguments"
+                           " have to be of the same length"):
+            _init_nd_shape_and_axes(xp.zeros([1, 1, 1, 1]),
+                                    shape=[1, 2, 3], axes=[1])
+
+        with assert_raises(ValueError,
+                           match="invalid number of data points"
+                           r" \(\[0\]\) specified"):
+            _init_nd_shape_and_axes(x, shape=[0], axes=None)
+
+        with assert_raises(ValueError,
+                           match="invalid number of data points"
+                           r" \(\[-2\]\) specified"):
+            _init_nd_shape_and_axes(x, shape=-2, axes=None)
+
+
+@make_xp_test_case(fft.fftshift, fft.ifftshift)
+class TestFFTShift:
+
+    def test_definition(self, xp):
+        x = xp.asarray([0., 1, 2, 3, 4, -4, -3, -2, -1])
+        y = xp.asarray([-4., -3, -2, -1, 0, 1, 2, 3, 4])
+        xp_assert_close(fft.fftshift(x), y)
+        xp_assert_close(fft.ifftshift(y), x)
+        x = xp.asarray([0., 1, 2, 3, 4, -5, -4, -3, -2, -1])
+        y = xp.asarray([-5., -4, -3, -2, -1, 0, 1, 2, 3, 4])
+        xp_assert_close(fft.fftshift(x), y)
+        xp_assert_close(fft.ifftshift(y), x)
+
+    def test_inverse(self, xp):
+        for n in [1, 4, 9, 100, 211]:
+            x = xp.asarray(np.random.random((n,)))
+            xp_assert_close(fft.ifftshift(fft.fftshift(x)), x)
+
+    def test_axes_keyword(self, xp):
+        freqs = xp.asarray([[0., 1, 2], [3, 4, -4], [-3, -2, -1]])
+        shifted = xp.asarray([[-1., -3, -2], [2, 0, 1], [-4, 3, 4]])
+        xp_assert_close(fft.fftshift(freqs, axes=(0, 1)), shifted)
+        xp_assert_close(fft.fftshift(freqs, axes=0), fft.fftshift(freqs, axes=(0,)))
+        xp_assert_close(fft.ifftshift(shifted, axes=(0, 1)), freqs)
+        xp_assert_close(fft.ifftshift(shifted, axes=0),
+                        fft.ifftshift(shifted, axes=(0,)))
+        xp_assert_close(fft.fftshift(freqs), shifted)
+        xp_assert_close(fft.ifftshift(shifted), freqs)
+
+    def test_uneven_dims(self, xp):
+        """ Test 2D input, which has uneven dimension sizes """
+        freqs = xp.asarray([
+            [0, 1],
+            [2, 3],
+            [4, 5]
+        ], dtype=xp.float64)
+
+        # shift in dimension 0
+        shift_dim0 = xp.asarray([
+            [4, 5],
+            [0, 1],
+            [2, 3]
+        ], dtype=xp.float64)
+        xp_assert_close(fft.fftshift(freqs, axes=0), shift_dim0)
+        xp_assert_close(fft.ifftshift(shift_dim0, axes=0), freqs)
+        xp_assert_close(fft.fftshift(freqs, axes=(0,)), shift_dim0)
+        xp_assert_close(fft.ifftshift(shift_dim0, axes=[0]), freqs)
+
+        # shift in dimension 1
+        shift_dim1 = xp.asarray([
+            [1, 0],
+            [3, 2],
+            [5, 4]
+        ], dtype=xp.float64)
+        xp_assert_close(fft.fftshift(freqs, axes=1), shift_dim1)
+        xp_assert_close(fft.ifftshift(shift_dim1, axes=1), freqs)
+
+        # shift in both dimensions
+        shift_dim_both = xp.asarray([
+            [5, 4],
+            [1, 0],
+            [3, 2]
+        ], dtype=xp.float64)
+        xp_assert_close(fft.fftshift(freqs, axes=(0, 1)), shift_dim_both)
+        xp_assert_close(fft.ifftshift(shift_dim_both, axes=(0, 1)), freqs)
+        xp_assert_close(fft.fftshift(freqs, axes=[0, 1]), shift_dim_both)
+        xp_assert_close(fft.ifftshift(shift_dim_both, axes=[0, 1]), freqs)
+
+        # axes=None (default) shift in all dimensions
+        xp_assert_close(fft.fftshift(freqs, axes=None), shift_dim_both)
+        xp_assert_close(fft.ifftshift(shift_dim_both, axes=None), freqs)
+        xp_assert_close(fft.fftshift(freqs), shift_dim_both)
+        xp_assert_close(fft.ifftshift(shift_dim_both), freqs)
+
+
+@make_xp_test_case(fft.fftfreq)
+class TestFFTFreq:
+    def test_definition(self, xp):
+        x = xp.asarray([0, 1, 2, 3, 4, -4, -3, -2, -1], dtype=xp.float64)
+        x2 = xp.asarray([0, 1, 2, 3, 4, -5, -4, -3, -2, -1], dtype=xp.float64)
+
+        # default dtype varies across backends
+
+        y = 9 * fft.fftfreq(9, xp=xp)
+        xp_assert_close(y, x, check_dtype=False, check_namespace=True)
+
+        y = 9 * xp.pi * fft.fftfreq(9, xp.pi, xp=xp)
+        xp_assert_close(y, x, check_dtype=False)
+
+        y = 10 * fft.fftfreq(10, xp=xp)
+        xp_assert_close(y, x2, check_dtype=False)
+
+        y = 10 * xp.pi * fft.fftfreq(10, xp.pi, xp=xp)
+        xp_assert_close(y, x2, check_dtype=False)
+
+    def test_device(self, xp, devices):
+        for d in devices:
+            y = fft.fftfreq(9, xp=xp, device=d)
+            x = xp.empty(0, device=d)
+            assert xp_device(y) == xp_device(x)
+
+
+@make_xp_test_case(fft.rfftfreq)
+class TestRFFTFreq:
+
+    def test_definition(self, xp):
+        x = xp.asarray([0, 1, 2, 3, 4], dtype=xp.float64)
+        x2 = xp.asarray([0, 1, 2, 3, 4, 5], dtype=xp.float64)
+
+        # default dtype varies across backends
+
+        y = 9 * fft.rfftfreq(9, xp=xp)
+        xp_assert_close(y, x, check_dtype=False, check_namespace=True)
+
+        y = 9 * xp.pi * fft.rfftfreq(9, xp.pi, xp=xp)
+        xp_assert_close(y, x, check_dtype=False)
+
+        y = 10 * fft.rfftfreq(10, xp=xp)
+        xp_assert_close(y, x2, check_dtype=False)
+
+        y = 10 * xp.pi * fft.rfftfreq(10, xp.pi, xp=xp)
+        xp_assert_close(y, x2, check_dtype=False)
+
+    def test_device(self, xp, devices):
+        for d in devices:
+            y = fft.rfftfreq(9, xp=xp, device=d)
+            x = xp.empty(0, device=d)
+            assert xp_device(y) == xp_device(x)
diff --git a/.venv/lib/python3.12/site-packages/scipy/fft/tests/test_multithreading.py b/.venv/lib/python3.12/site-packages/scipy/fft/tests/test_multithreading.py
new file mode 100644
index 0000000000000000000000000000000000000000..1a6b71b830211f8bcbe56e97ff71098be75021c8
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/fft/tests/test_multithreading.py
@@ -0,0 +1,84 @@
+from scipy import fft
+import numpy as np
+import pytest
+from numpy.testing import assert_allclose
+import multiprocessing
+import os
+
+
+@pytest.fixture(scope='module')
+def x():
+    return np.random.randn(512, 128)  # Must be large enough to qualify for mt
+
+
+@pytest.mark.parametrize("func", [
+    fft.fft, fft.ifft, fft.fft2, fft.ifft2, fft.fftn, fft.ifftn,
+    fft.rfft, fft.irfft, fft.rfft2, fft.irfft2, fft.rfftn, fft.irfftn,
+    fft.hfft, fft.ihfft, fft.hfft2, fft.ihfft2, fft.hfftn, fft.ihfftn,
+    fft.dct, fft.idct, fft.dctn, fft.idctn,
+    fft.dst, fft.idst, fft.dstn, fft.idstn,
+])
+@pytest.mark.parametrize("workers", [2, -1])
+def test_threaded_same(x, func, workers):
+    expected = func(x, workers=1)
+    actual = func(x, workers=workers)
+    assert_allclose(actual, expected)
+
+
+def _mt_fft(x):
+    return fft.fft(x, workers=2)
+
+
+@pytest.mark.slow
+def test_mixed_threads_processes(x):
+    # Test that the fft threadpool is safe to use before & after fork
+
+    expect = fft.fft(x, workers=2)
+
+    with multiprocessing.Pool(2) as p:
+        res = p.map(_mt_fft, [x for _ in range(4)])
+
+    for r in res:
+        assert_allclose(r, expect)
+
+    fft.fft(x, workers=2)
+
+
+def test_invalid_workers(x):
+    cpus = os.cpu_count()
+
+    fft.ifft([1], workers=-cpus)
+
+    with pytest.raises(ValueError, match='workers must not be zero'):
+        fft.fft(x, workers=0)
+
+    with pytest.raises(ValueError, match='workers value out of range'):
+        fft.ifft(x, workers=-cpus-1)
+
+
+def test_set_get_workers():
+    cpus = os.cpu_count()
+    assert fft.get_workers() == 1
+    with fft.set_workers(4):
+        assert fft.get_workers() == 4
+
+        with fft.set_workers(-1):
+            assert fft.get_workers() == cpus
+
+        assert fft.get_workers() == 4
+
+    assert fft.get_workers() == 1
+
+    with fft.set_workers(-cpus):
+        assert fft.get_workers() == 1
+
+
+def test_set_workers_invalid():
+
+    with pytest.raises(ValueError, match='workers must not be zero'):
+        with fft.set_workers(0):
+            pass
+
+    with pytest.raises(ValueError, match='workers value out of range'):
+        with fft.set_workers(-os.cpu_count()-1):
+            pass
diff --git a/.venv/lib/python3.12/site-packages/scipy/fft/tests/test_real_transforms.py b/.venv/lib/python3.12/site-packages/scipy/fft/tests/test_real_transforms.py
new file mode 100644
index 0000000000000000000000000000000000000000..7e4549d4135a9af6d9372ad6658fe76c18bce48d
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/fft/tests/test_real_transforms.py
@@ -0,0 +1,243 @@
+import numpy as np
+from numpy.testing import assert_allclose, assert_array_equal
+import pytest
+import math
+
+from scipy.fft import dct, idct, dctn, idctn, dst, idst, dstn, idstn
+import scipy.fft as fft
+from scipy import fftpack
+from scipy._lib._array_api import (xp_copy, xp_assert_close, make_xp_test_case,
+                                   make_xp_pytest_param)
+import scipy._external.array_api_extra as xpx
+
+skip_xp_backends = pytest.mark.skip_xp_backends
+
+SQRT_2 = math.sqrt(2)
+
+# scipy.fft wraps the fftpack versions but with normalized inverse transforms.
+# So, the forward transforms and definitions are already thoroughly tested in
+# fftpack/test_real_transforms.py
+
+
+@make_xp_test_case(dct, idct, dst, idst)
+@pytest.mark.parametrize("forward, backward", [(dct, idct), (dst, idst)])
+@pytest.mark.parametrize("type", [1, 2, 3, 4])
+@pytest.mark.parametrize("n", [2, 3, 4, 5, 10, 16])
+@pytest.mark.parametrize("axis", [0, 1])
+@pytest.mark.parametrize("norm", [None, 'backward', 'ortho', 'forward'])
+@pytest.mark.parametrize("orthogonalize", [False, True])
+def test_identity_1d(forward, backward, type, n, axis, norm, orthogonalize, xp):
+    # Test the identity f^-1(f(x)) == x
+    x = xp.asarray(np.random.rand(n, n))
+
+    y = forward(x, type, axis=axis, norm=norm, orthogonalize=orthogonalize)
+    z = backward(y, type, axis=axis, norm=norm, orthogonalize=orthogonalize)
+    xp_assert_close(z, x)
+
+    pad = [(0, 0)] * 2
+    pad[axis] = (0, 4)
+
+    y2 = xp.asarray(np.pad(np.asarray(y), pad, mode='edge'))
+    z2 = backward(y2, type, n, axis, norm, orthogonalize=orthogonalize)
+    xp_assert_close(z2, x)
+
+
+@pytest.mark.parametrize("forward, backward", [[dct, idct], [dst, idst]])
+@pytest.mark.parametrize("type", [1, 2, 3, 4])
+@pytest.mark.parametrize("dtype", [np.float16, np.float32, np.float64,
+                                   np.complex64, np.complex128])
+@pytest.mark.parametrize("axis", [0, 1])
+@pytest.mark.parametrize("norm", [None, 'backward', 'ortho', 'forward'])
+@pytest.mark.parametrize("overwrite_x", [True, False])
+def test_identity_1d_overwrite(forward, backward, type, dtype, axis, norm,
+                               overwrite_x):
+    # Test the identity f^-1(f(x)) == x
+    x = np.random.rand(7, 8).astype(dtype)
+    x_orig = x.copy()
+
+    y = forward(x, type, axis=axis, norm=norm, overwrite_x=overwrite_x)
+    y_orig = y.copy()
+    z = backward(y, type, axis=axis, norm=norm, overwrite_x=overwrite_x)
+    if not overwrite_x:
+        assert_allclose(z, x, rtol=1e-6, atol=1e-6)
+        assert_array_equal(x, x_orig)
+        assert_array_equal(y, y_orig)
+    else:
+        assert_allclose(z, x_orig, rtol=1e-6, atol=1e-6)
+
+
+@make_xp_test_case(dctn, idctn, dstn, idstn)
+@pytest.mark.parametrize("forward, backward", [(dctn, idctn), (dstn, idstn)])
+@pytest.mark.parametrize("type", [1, 2, 3, 4])
+@pytest.mark.parametrize("shape, axes",
+                         [
+                             ((4, 4), 0),
+                             ((4, 4), 1),
+                             ((4, 4), None),
+                             ((4, 4), (0, 1)),
+                             ((10, 12), None),
+                             ((10, 12), (0, 1)),
+                             ((4, 5, 6), None),
+                             ((4, 5, 6), 1),
+                             ((4, 5, 6), (0, 2)),
+                         ])
+@pytest.mark.parametrize("norm", [None, 'backward', 'ortho', 'forward'])
+@pytest.mark.parametrize("orthogonalize", [False, True])
+def test_identity_nd(forward, backward, type, shape, axes, norm,
+                     orthogonalize, xp):
+    # Test the identity f^-1(f(x)) == x
+
+    x = xp.asarray(np.random.random(shape))
+
+    if axes is not None:
+        shape = np.take(shape, axes)
+
+    y = forward(x, type, axes=axes, norm=norm, orthogonalize=orthogonalize)
+    z = backward(y, type, axes=axes, norm=norm, orthogonalize=orthogonalize)
+    xp_assert_close(z, x)
+
+    if axes is None:
+        pad = [(0, 4)] * x.ndim
+    elif isinstance(axes, int):
+        pad = [(0, 0)] * x.ndim
+        pad[axes] = (0, 4)
+    else:
+        pad = [(0, 0)] * x.ndim
+
+        for a in axes:
+            pad[a] = (0, 4)
+
+    # TODO write an array-agnostic pad
+    y2 = xp.asarray(np.pad(np.asarray(y), pad, mode='edge'))
+    z2 = backward(y2, type, shape, axes, norm, orthogonalize=orthogonalize)
+    xp_assert_close(z2, x)
+
+
+@pytest.mark.parametrize("forward, backward", [[dctn, idctn], [dstn, idstn]])
+@pytest.mark.parametrize("type", [1, 2, 3, 4])
+@pytest.mark.parametrize("shape, axes",
+                         [
+                             ((4, 5), 0),
+                             ((4, 5), 1),
+                             ((4, 5), None),
+                         ])
+@pytest.mark.parametrize("dtype", [np.float16, np.float32, np.float64,
+                                   np.complex64, np.complex128])
+@pytest.mark.parametrize("norm", [None, 'backward', 'ortho', 'forward'])
+@pytest.mark.parametrize("overwrite_x", [False, True])
+def test_identity_nd_overwrite(forward, backward, type, shape, axes, dtype,
+                               norm, overwrite_x):
+    # Test the identity f^-1(f(x)) == x
+
+    x = np.random.random(shape).astype(dtype)
+    x_orig = x.copy()
+
+    if axes is not None:
+        shape = np.take(shape, axes)
+
+    y = forward(x, type, axes=axes, norm=norm)
+    y_orig = y.copy()
+    z = backward(y, type, axes=axes, norm=norm)
+    if overwrite_x:
+        assert_allclose(z, x_orig, rtol=1e-6, atol=1e-6)
+    else:
+        assert_allclose(z, x, rtol=1e-6, atol=1e-6)
+        assert_array_equal(x, x_orig)
+        assert_array_equal(y, y_orig)
+
+
+@pytest.mark.parametrize("func", [make_xp_pytest_param(dct),
+                                  make_xp_pytest_param(dst),
+                                  make_xp_pytest_param(dctn),
+                                  make_xp_pytest_param(dstn)])
+@pytest.mark.parametrize("type", [1, 2, 3, 4])
+@pytest.mark.parametrize("norm", [None, 'backward', 'ortho', 'forward'])
+def test_fftpack_equivalience(func, type, norm, xp):
+    x = np.random.rand(8, 16)
+    fftpack_res = xp.asarray(getattr(fftpack, func.__name__)(x, type, norm=norm))
+    x = xp.asarray(x)
+    fft_res = getattr(fft, func.__name__)(x, type, norm=norm)
+
+    xp_assert_close(fft_res, fftpack_res)
+
+
+@pytest.mark.parametrize("func", [make_xp_pytest_param(dct),
+                                  make_xp_pytest_param(dst),
+                                  make_xp_pytest_param(dctn),
+                                  make_xp_pytest_param(dstn)])
+@pytest.mark.parametrize("type", [1, 2, 3, 4])
+def test_orthogonalize_default(func, type, xp):
+    # Test orthogonalize is the default when norm="ortho", but not otherwise
+    x = xp.asarray(np.random.rand(100))
+
+    for norm, ortho in [
+            ("forward", False),
+            ("backward", False),
+            ("ortho", True),
+    ]:
+        a = func(x, type=type, norm=norm, orthogonalize=ortho)
+        b = func(x, type=type, norm=norm)
+        xp_assert_close(a, b)
+
+
+@pytest.mark.parametrize("norm", ["backward", "ortho", "forward"])
+@pytest.mark.parametrize("func, type", [make_xp_pytest_param(dct, 4),
+                                        make_xp_pytest_param(dst, 1),
+                                        make_xp_pytest_param(dst, 4)])
+def test_orthogonalize_noop(func, type, norm, xp):
+    # Transforms where orthogonalize is a no-op
+    x = xp.asarray(np.random.rand(100))
+    y1 = func(x, type=type, norm=norm, orthogonalize=True)
+    y2 = func(x, type=type, norm=norm, orthogonalize=False)
+    xp_assert_close(y1, y2)
+
+
+@make_xp_test_case(dct)
+@pytest.mark.parametrize("norm", ["backward", "ortho", "forward"])
+def test_orthogonalize_dct1(norm, xp):
+    x = xp.asarray(np.random.rand(100))
+
+    x2 = xp_copy(x, xp=xp)
+    xpx.at(x2, 0).multiply(SQRT_2)
+    xpx.at(x2, -1).multiply(SQRT_2)
+
+    y1 = dct(x, type=1, norm=norm, orthogonalize=True)
+    y2 = dct(x2, type=1, norm=norm, orthogonalize=False)
+
+    xpx.at(y2, 0).divide(SQRT_2)
+    xpx.at(y2, -1).divide(SQRT_2)
+    xp_assert_close(y1, y2)
+
+
+
+@pytest.mark.parametrize("norm", ["backward", "ortho", "forward"])
+@pytest.mark.parametrize("func", [make_xp_pytest_param(dct),
+                                  make_xp_pytest_param(dst)])
+def test_orthogonalize_dcst2(func, norm, xp):
+    x = xp.asarray(np.random.rand(100))
+    y1 = func(x, type=2, norm=norm, orthogonalize=True)
+    y2 = func(x, type=2, norm=norm, orthogonalize=False)
+
+    xpx.at(y2, 0 if func.__name__ == "dct" else -1).divide(SQRT_2)
+    xp_assert_close(y1, y2)
+
+
+@pytest.mark.parametrize("norm", ["backward", "ortho", "forward"])
+@pytest.mark.parametrize("func", [make_xp_pytest_param(dct),
+                                  make_xp_pytest_param(dst)])
+def test_orthogonalize_dcst3(func, norm, xp):
+    x = xp.asarray(np.random.rand(100))
+    x2 = xp_copy(x, xp=xp)
+    xpx.at(x2, 0 if func.__name__ == "dct" else -1).multiply(SQRT_2)
+
+    y1 = func(x, type=3, norm=norm, orthogonalize=True)
+    y2 = func(x2, type=3, norm=norm, orthogonalize=False)
+    xp_assert_close(y1, y2)
+
+
+@pytest.mark.parametrize("func", [dct, idct, dctn, idctn, dst, idst, dstn, idstn])
+def test_array_like(func):
+    x = [[[1.0, 1.0], [1.0, 1.0]],
+         [[1.0, 1.0], [1.0, 1.0]],
+         [[1.0, 1.0], [1.0, 1.0]]]
+    xp_assert_close(func(x), func(np.asarray(x)))
diff --git a/.venv/lib/python3.12/site-packages/scipy/fftpack/__init__.py b/.venv/lib/python3.12/site-packages/scipy/fftpack/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..10f4b39e48e2d6c0b042582ca65f572bde6ba575
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/fftpack/__init__.py
@@ -0,0 +1,103 @@
+"""
+=========================================================
+Legacy discrete Fourier transforms (:mod:`scipy.fftpack`)
+=========================================================
+
+.. legacy::
+
+   New code should use :mod:`scipy.fft`.
+
+Fast Fourier Transforms (FFTs)
+==============================
+
+.. autosummary::
+   :toctree: generated/
+
+   fft - Fast (discrete) Fourier Transform (FFT)
+   ifft - Inverse FFT
+   fft2 - 2-D FFT
+   ifft2 - 2-D inverse FFT
+   fftn - N-D FFT
+   ifftn - N-D inverse FFT
+   rfft - FFT of strictly real-valued sequence
+   irfft - Inverse of rfft
+   dct - Discrete cosine transform
+   idct - Inverse discrete cosine transform
+   dctn - N-D Discrete cosine transform
+   idctn - N-D Inverse discrete cosine transform
+   dst - Discrete sine transform
+   idst - Inverse discrete sine transform
+   dstn - N-D Discrete sine transform
+   idstn - N-D Inverse discrete sine transform
+
+Differential and pseudo-differential operators
+==============================================
+
+.. autosummary::
+   :toctree: generated/
+
+   diff - Differentiation and integration of periodic sequences
+   tilbert - Tilbert transform:         cs_diff(x,h,h)
+   itilbert - Inverse Tilbert transform: sc_diff(x,h,h)
+   hilbert - Hilbert transform:         cs_diff(x,inf,inf)
+   ihilbert - Inverse Hilbert transform: sc_diff(x,inf,inf)
+   cs_diff - cosh/sinh pseudo-derivative of periodic sequences
+   sc_diff - sinh/cosh pseudo-derivative of periodic sequences
+   ss_diff - sinh/sinh pseudo-derivative of periodic sequences
+   cc_diff - cosh/cosh pseudo-derivative of periodic sequences
+   shift - Shift periodic sequences
+
+Helper functions
+================
+
+.. autosummary::
+   :toctree: generated/
+
+   fftshift - Shift the zero-frequency component to the center of the spectrum
+   ifftshift - The inverse of `fftshift`
+   fftfreq - Return the Discrete Fourier Transform sample frequencies
+   rfftfreq - DFT sample frequencies (for usage with rfft, irfft)
+   next_fast_len - Find the optimal length to zero-pad an FFT for speed
+
+Note that ``fftshift``, ``ifftshift`` and ``fftfreq`` are numpy functions
+exposed by ``fftpack``; importing them from ``numpy`` should be preferred.
+
+Convolutions (:mod:`scipy.fftpack.convolve`)
+============================================
+
+.. module:: scipy.fftpack.convolve
+
+.. autosummary::
+   :toctree: generated/
+
+   convolve
+   convolve_z
+   init_convolution_kernel
+   destroy_convolve_cache
+
+"""
+
+
+__all__ = ['fft','ifft','fftn','ifftn','rfft','irfft',
+           'fft2','ifft2',
+           'diff',
+           'tilbert','itilbert','hilbert','ihilbert',
+           'sc_diff','cs_diff','cc_diff','ss_diff',
+           'shift',
+           'fftfreq', 'rfftfreq',
+           'fftshift', 'ifftshift',
+           'next_fast_len',
+           'dct', 'idct', 'dst', 'idst', 'dctn', 'idctn', 'dstn', 'idstn'
+           ]
+
+from ._basic import *
+from ._pseudo_diffs import *
+from ._helper import *
+from ._realtransforms import *
+
+# Deprecated namespaces, to be removed in v2.0.0
+from . import basic, helper, pseudo_diffs, realtransforms
+
+from scipy._lib._testutils import PytestTester
+test = PytestTester(__name__)
+del PytestTester
diff --git a/.venv/lib/python3.12/site-packages/scipy/fftpack/__pycache__/__init__.cpython-312.pyc b/.venv/lib/python3.12/site-packages/scipy/fftpack/__pycache__/__init__.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..542b1fd898a32aa624752cfe96084ecb2923ae25
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/scipy/fftpack/__pycache__/__init__.cpython-312.pyc differ
diff --git a/.venv/lib/python3.12/site-packages/scipy/fftpack/__pycache__/_basic.cpython-312.pyc b/.venv/lib/python3.12/site-packages/scipy/fftpack/__pycache__/_basic.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..add7abc6d11ea1c92c3daf4fdfa37d0781657ee5
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/scipy/fftpack/__pycache__/_basic.cpython-312.pyc differ
diff --git a/.venv/lib/python3.12/site-packages/scipy/fftpack/__pycache__/_helper.cpython-312.pyc b/.venv/lib/python3.12/site-packages/scipy/fftpack/__pycache__/_helper.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..7f19c0f3c10f9b50b7ea71549383ac1ffb777136
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/scipy/fftpack/__pycache__/_helper.cpython-312.pyc differ
diff --git a/.venv/lib/python3.12/site-packages/scipy/fftpack/__pycache__/_pseudo_diffs.cpython-312.pyc b/.venv/lib/python3.12/site-packages/scipy/fftpack/__pycache__/_pseudo_diffs.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..060585148679e960d56684e614a83308a8442443
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/scipy/fftpack/__pycache__/_pseudo_diffs.cpython-312.pyc differ
diff --git a/.venv/lib/python3.12/site-packages/scipy/fftpack/__pycache__/_realtransforms.cpython-312.pyc b/.venv/lib/python3.12/site-packages/scipy/fftpack/__pycache__/_realtransforms.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..0548b68cf46d30c0abb68cf3edebfc1720094397
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/scipy/fftpack/__pycache__/_realtransforms.cpython-312.pyc differ
diff --git a/.venv/lib/python3.12/site-packages/scipy/fftpack/__pycache__/basic.cpython-312.pyc b/.venv/lib/python3.12/site-packages/scipy/fftpack/__pycache__/basic.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..3818e763256dd8a9744d73ca94826681647b358e
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/scipy/fftpack/__pycache__/basic.cpython-312.pyc differ
diff --git a/.venv/lib/python3.12/site-packages/scipy/fftpack/__pycache__/helper.cpython-312.pyc b/.venv/lib/python3.12/site-packages/scipy/fftpack/__pycache__/helper.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..3908b98c1486fc644a5b1793db935ed35f0dc098
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/scipy/fftpack/__pycache__/helper.cpython-312.pyc differ
diff --git a/.venv/lib/python3.12/site-packages/scipy/fftpack/__pycache__/pseudo_diffs.cpython-312.pyc b/.venv/lib/python3.12/site-packages/scipy/fftpack/__pycache__/pseudo_diffs.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..2cbceb3814522819d1832e0a4756218a0674a895
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/scipy/fftpack/__pycache__/pseudo_diffs.cpython-312.pyc differ
diff --git a/.venv/lib/python3.12/site-packages/scipy/fftpack/__pycache__/realtransforms.cpython-312.pyc b/.venv/lib/python3.12/site-packages/scipy/fftpack/__pycache__/realtransforms.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..d6670f2026b1744d7174be6e2408140b46346281
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/scipy/fftpack/__pycache__/realtransforms.cpython-312.pyc differ
diff --git a/.venv/lib/python3.12/site-packages/scipy/fftpack/_basic.py b/.venv/lib/python3.12/site-packages/scipy/fftpack/_basic.py
new file mode 100644
index 0000000000000000000000000000000000000000..d3a512a9c0361d2f65a4173d416d44c97a212cc5
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/fftpack/_basic.py
@@ -0,0 +1,428 @@
+"""
+Discrete Fourier Transforms - _basic.py
+"""
+# Created by Pearu Peterson, August,September 2002
+__all__ = ['fft','ifft','fftn','ifftn','rfft','irfft',
+           'fft2','ifft2']
+
+from scipy.fft import _duccfft
+from ._helper import _good_shape
+
+
+def fft(x, n=None, axis=-1, overwrite_x=False):
+    """
+    Return discrete Fourier transform of real or complex sequence.
+
+    The returned complex array contains ``y(0), y(1),..., y(n-1)``, where
+
+    ``y(j) = (x * exp(-2*pi*sqrt(-1)*j*np.arange(n)/n)).sum()``.
+
+    Parameters
+    ----------
+    x : array_like
+        Array to Fourier transform.
+    n : int, optional
+        Length of the Fourier transform. If ``n < x.shape[axis]``, `x` is
+        truncated. If ``n > x.shape[axis]``, `x` is zero-padded. The
+        default results in ``n = x.shape[axis]``.
+    axis : int, optional
+        Axis along which the fft's are computed; the default is over the
+        last axis (i.e., ``axis=-1``).
+    overwrite_x : bool, optional
+        If True, the contents of `x` can be destroyed; the default is False.
+
+    Returns
+    -------
+    z : complex ndarray
+        with the elements::
+
+            [y(0),y(1),..,y(n/2),y(1-n/2),...,y(-1)]        if n is even
+            [y(0),y(1),..,y((n-1)/2),y(-(n-1)/2),...,y(-1)]  if n is odd
+
+        where::
+
+            y(j) = sum[k=0..n-1] x[k] * exp(-sqrt(-1)*j*k* 2*pi/n), j = 0..n-1
+
+    See Also
+    --------
+    ifft : Inverse FFT
+    rfft : FFT of a real sequence
+
+    Notes
+    -----
+    The packing of the result is "standard": If ``A = fft(a, n)``, then
+    ``A[0]`` contains the zero-frequency term, ``A[1:n/2]`` contains the
+    positive-frequency terms, and ``A[n/2:]`` contains the negative-frequency
+    terms, in order of decreasingly negative frequency. So ,for an 8-point
+    transform, the frequencies of the result are [0, 1, 2, 3, -4, -3, -2, -1].
+    To rearrange the fft output so that the zero-frequency component is
+    centered, like [-4, -3, -2, -1,  0,  1,  2,  3], use `fftshift`.
+
+    Both single and double precision routines are implemented. Half precision
+    inputs will be converted to single precision. Non-floating-point inputs
+    will be converted to double precision. Long-double precision inputs are
+    not supported.
+
+    This function is most efficient when `n` is a power of two, and least
+    efficient when `n` is prime.
+
+    Note that if ``x`` is real-valued, then ``A[j] == A[n-j].conjugate()``.
+    If ``x`` is real-valued and ``n`` is even, then ``A[n/2]`` is real.
+
+    If the data type of `x` is real, a "real FFT" algorithm is automatically
+    used, which roughly halves the computation time. To increase efficiency
+    a little further, use `rfft`, which does the same calculation, but only
+    outputs half of the symmetrical spectrum. If the data is both real and
+    symmetrical, the `dct` can again double the efficiency by generating
+    half of the spectrum from half of the signal.
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy.fftpack import fft, ifft
+    >>> x = np.arange(5)
+    >>> np.allclose(fft(ifft(x)), x, atol=1e-15)  # within numerical accuracy.
+    True
+
+    """
+    return _duccfft.fft(x, n, axis, None, overwrite_x)
+
+
+def ifft(x, n=None, axis=-1, overwrite_x=False):
+    """
+    Return discrete inverse Fourier transform of real or complex sequence.
+
+    The returned complex array contains ``y(0), y(1),..., y(n-1)``, where
+
+    ``y(j) = (x * exp(2*pi*sqrt(-1)*j*np.arange(n)/n)).mean()``.
+
+    Parameters
+    ----------
+    x : array_like
+        Transformed data to invert.
+    n : int, optional
+        Length of the inverse Fourier transform.  If ``n < x.shape[axis]``,
+        `x` is truncated. If ``n > x.shape[axis]``, `x` is zero-padded.
+        The default results in ``n = x.shape[axis]``.
+    axis : int, optional
+        Axis along which the ifft's are computed; the default is over the
+        last axis (i.e., ``axis=-1``).
+    overwrite_x : bool, optional
+        If True, the contents of `x` can be destroyed; the default is False.
+
+    Returns
+    -------
+    ifft : ndarray of floats
+        The inverse discrete Fourier transform.
+
+    See Also
+    --------
+    fft : Forward FFT
+
+    Notes
+    -----
+    Both single and double precision routines are implemented. Half precision
+    inputs will be converted to single precision. Non-floating-point inputs
+    will be converted to double precision. Long-double precision inputs are
+    not supported.
+
+    This function is most efficient when `n` is a power of two, and least
+    efficient when `n` is prime.
+
+    If the data type of `x` is real, a "real IFFT" algorithm is automatically
+    used, which roughly halves the computation time.
+
+    Examples
+    --------
+    >>> from scipy.fftpack import fft, ifft
+    >>> import numpy as np
+    >>> x = np.arange(5)
+    >>> np.allclose(ifft(fft(x)), x, atol=1e-15)  # within numerical accuracy.
+    True
+
+    """
+    return _duccfft.ifft(x, n, axis, None, overwrite_x)
+
+
+def rfft(x, n=None, axis=-1, overwrite_x=False):
+    """
+    Discrete Fourier transform of a real sequence.
+
+    Parameters
+    ----------
+    x : array_like, real-valued
+        The data to transform.
+    n : int, optional
+        Defines the length of the Fourier transform. If `n` is not specified
+        (the default) then ``n = x.shape[axis]``. If ``n < x.shape[axis]``,
+        `x` is truncated, if ``n > x.shape[axis]``, `x` is zero-padded.
+    axis : int, optional
+        The axis along which the transform is applied. The default is the
+        last axis.
+    overwrite_x : bool, optional
+        If set to true, the contents of `x` can be overwritten. Default is
+        False.
+
+    Returns
+    -------
+    z : real ndarray
+        The returned real array contains::
+
+          [y(0),Re(y(1)),Im(y(1)),...,Re(y(n/2))]              if n is even
+          [y(0),Re(y(1)),Im(y(1)),...,Re(y(n/2)),Im(y(n/2))]   if n is odd
+
+        where::
+
+          y(j) = sum[k=0..n-1] x[k] * exp(-sqrt(-1)*j*k*2*pi/n)
+          j = 0..n-1
+
+    See Also
+    --------
+    fft, irfft, scipy.fft.rfft
+
+    Notes
+    -----
+    Within numerical accuracy, ``y == rfft(irfft(y))``.
+
+    Both single and double precision routines are implemented. Half precision
+    inputs will be converted to single precision. Non-floating-point inputs
+    will be converted to double precision. Long-double precision inputs are
+    not supported.
+
+    To get an output with a complex datatype, consider using the newer
+    function `scipy.fft.rfft`.
+
+    Examples
+    --------
+    >>> from scipy.fftpack import fft, rfft
+    >>> a = [9, -9, 1, 3]
+    >>> fft(a)
+    array([  4. +0.j,   8.+12.j,  16. +0.j,   8.-12.j])
+    >>> rfft(a)
+    array([  4.,   8.,  12.,  16.])
+
+    """
+    return _duccfft.rfft_fftpack(x, n, axis, None, overwrite_x)
+
+
+def irfft(x, n=None, axis=-1, overwrite_x=False):
+    """
+    Return inverse discrete Fourier transform of real sequence x.
+
+    The contents of `x` are interpreted as the output of the `rfft`
+    function.
+
+    Parameters
+    ----------
+    x : array_like
+        Transformed data to invert.
+    n : int, optional
+        Length of the inverse Fourier transform.
+        If n < x.shape[axis], x is truncated.
+        If n > x.shape[axis], x is zero-padded.
+        The default results in n = x.shape[axis].
+    axis : int, optional
+        Axis along which the ifft's are computed; the default is over
+        the last axis (i.e., axis=-1).
+    overwrite_x : bool, optional
+        If True, the contents of `x` can be destroyed; the default is False.
+
+    Returns
+    -------
+    irfft : ndarray of floats
+        The inverse discrete Fourier transform.
+
+    See Also
+    --------
+    rfft, ifft, scipy.fft.irfft
+
+    Notes
+    -----
+    The returned real array contains::
+
+        [y(0),y(1),...,y(n-1)]
+
+    where for n is even::
+
+        y(j) = 1/n (sum[k=1..n/2-1] (x[2*k-1]+sqrt(-1)*x[2*k])
+                                     * exp(sqrt(-1)*j*k* 2*pi/n)
+                    + c.c. + x[0] + (-1)**(j) x[n-1])
+
+    and for n is odd::
+
+        y(j) = 1/n (sum[k=1..(n-1)/2] (x[2*k-1]+sqrt(-1)*x[2*k])
+                                     * exp(sqrt(-1)*j*k* 2*pi/n)
+                    + c.c. + x[0])
+
+    c.c. denotes complex conjugate of preceding expression.
+
+    For details on input parameters, see `rfft`.
+
+    To process (conjugate-symmetric) frequency-domain data with a complex
+    datatype, consider using the newer function `scipy.fft.irfft`.
+
+    Examples
+    --------
+    >>> from scipy.fftpack import rfft, irfft
+    >>> a = [1.0, 2.0, 3.0, 4.0, 5.0]
+    >>> irfft(a)
+    array([ 2.6       , -3.16405192,  1.24398433, -1.14955713,  1.46962473])
+    >>> irfft(rfft(a))
+    array([1., 2., 3., 4., 5.])
+
+    """
+    return _duccfft.irfft_fftpack(x, n, axis, None, overwrite_x)
+
+
+def fftn(x, shape=None, axes=None, overwrite_x=False):
+    """
+    Return multidimensional discrete Fourier transform.
+
+    The returned array contains::
+
+      y[j_1,..,j_d] = sum[k_1=0..n_1-1, ..., k_d=0..n_d-1]
+         x[k_1,..,k_d] * prod[i=1..d] exp(-sqrt(-1)*2*pi/n_i * j_i * k_i)
+
+    where d = len(x.shape) and n = x.shape.
+
+    Parameters
+    ----------
+    x : array_like
+        The (N-D) array to transform.
+    shape : int or array_like of ints or None, optional
+        The shape of the result. If both `shape` and `axes` (see below) are
+        None, `shape` is ``x.shape``; if `shape` is None but `axes` is
+        not None, then `shape` is ``numpy.take(x.shape, axes, axis=0)``.
+        If ``shape[i] > x.shape[i]``, the ith dimension is padded with zeros.
+        If ``shape[i] < x.shape[i]``, the ith dimension is truncated to
+        length ``shape[i]``.
+        If any element of `shape` is -1, the size of the corresponding
+        dimension of `x` is used.
+    axes : int or array_like of ints or None, optional
+        The axes of `x` (`y` if `shape` is not None) along which the
+        transform is applied.
+        The default is over all axes.
+    overwrite_x : bool, optional
+        If True, the contents of `x` can be destroyed. Default is False.
+
+    Returns
+    -------
+    y : complex-valued N-D NumPy array
+        The (N-D) DFT of the input array.
+
+    See Also
+    --------
+    ifftn
+
+    Notes
+    -----
+    If ``x`` is real-valued, then
+    ``y[..., j_i, ...] == y[..., n_i-j_i, ...].conjugate()``.
+
+    Both single and double precision routines are implemented. Half precision
+    inputs will be converted to single precision. Non-floating-point inputs
+    will be converted to double precision. Long-double precision inputs are
+    not supported.
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy.fftpack import fftn, ifftn
+    >>> y = (-np.arange(16), 8 - np.arange(16), np.arange(16))
+    >>> np.allclose(y, fftn(ifftn(y)))
+    True
+
+    """
+    shape = _good_shape(x, shape, axes)
+    return _duccfft.fftn(x, shape, axes, None, overwrite_x)
+
+
+def ifftn(x, shape=None, axes=None, overwrite_x=False):
+    """
+    Return inverse multidimensional discrete Fourier transform.
+
+    The sequence can be of an arbitrary type.
+
+    The returned array contains::
+
+      y[j_1,..,j_d] = 1/p * sum[k_1=0..n_1-1, ..., k_d=0..n_d-1]
+         x[k_1,..,k_d] * prod[i=1..d] exp(sqrt(-1)*2*pi/n_i * j_i * k_i)
+
+    where ``d = len(x.shape)``, ``n = x.shape``, and ``p = prod[i=1..d] n_i``.
+
+    For description of parameters see `fftn`.
+
+    See Also
+    --------
+    fftn : for detailed information.
+
+    Examples
+    --------
+    >>> from scipy.fftpack import fftn, ifftn
+    >>> import numpy as np
+    >>> y = (-np.arange(16), 8 - np.arange(16), np.arange(16))
+    >>> np.allclose(y, ifftn(fftn(y)))
+    True
+
+    """  # numpydoc ignore=RT01
+    shape = _good_shape(x, shape, axes)
+    return _duccfft.ifftn(x, shape, axes, None, overwrite_x)
+
+
+def fft2(x, shape=None, axes=(-2,-1), overwrite_x=False):
+    """
+    2-D discrete Fourier transform.
+
+    Return the 2-D discrete Fourier transform of the 2-D argument
+    `x`.
+
+    See Also
+    --------
+    fftn : for detailed information.
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy.fftpack import fft2, ifft2
+    >>> y = np.mgrid[:5, :5][0]
+    >>> y
+    array([[0, 0, 0, 0, 0],
+           [1, 1, 1, 1, 1],
+           [2, 2, 2, 2, 2],
+           [3, 3, 3, 3, 3],
+           [4, 4, 4, 4, 4]])
+    >>> np.allclose(y, ifft2(fft2(y)))
+    True
+    """  # numpydoc ignore=RT01
+    return fftn(x,shape,axes,overwrite_x)
+
+
+def ifft2(x, shape=None, axes=(-2,-1), overwrite_x=False):
+    """
+    2-D discrete inverse Fourier transform of real or complex sequence.
+
+    Return inverse 2-D discrete Fourier transform of
+    arbitrary type sequence x.
+
+    See `ifft` for more information.
+
+    See Also
+    --------
+    fft2, ifft
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy.fftpack import fft2, ifft2
+    >>> y = np.mgrid[:5, :5][0]
+    >>> y
+    array([[0, 0, 0, 0, 0],
+           [1, 1, 1, 1, 1],
+           [2, 2, 2, 2, 2],
+           [3, 3, 3, 3, 3],
+           [4, 4, 4, 4, 4]])
+    >>> np.allclose(y, fft2(ifft2(y)))
+    True
+
+    """  # numpydoc ignore=RT01
+    return ifftn(x,shape,axes,overwrite_x)
diff --git a/.venv/lib/python3.12/site-packages/scipy/fftpack/_helper.py b/.venv/lib/python3.12/site-packages/scipy/fftpack/_helper.py
new file mode 100644
index 0000000000000000000000000000000000000000..1aff14a67f376fe98f7dba9ce306ab3628db71eb
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/fftpack/_helper.py
@@ -0,0 +1,115 @@
+import operator
+
+import numpy as np
+from numpy.fft import fftshift, ifftshift, fftfreq
+
+import scipy.fft._duccfft.helper as _helper
+
+__all__ = ['fftshift', 'ifftshift', 'fftfreq', 'rfftfreq', 'next_fast_len']
+
+
+def rfftfreq(n, d=1.0):
+    """DFT sample frequencies (for usage with rfft, irfft).
+
+    The returned float array contains the frequency bins in
+    cycles/unit (with zero at the start) given a window length `n` and a
+    sample spacing `d`::
+
+      f = [0,1,1,2,2,...,n/2-1,n/2-1,n/2]/(d*n)   if n is even
+      f = [0,1,1,2,2,...,n/2-1,n/2-1,n/2,n/2]/(d*n)   if n is odd
+
+    Parameters
+    ----------
+    n : int
+        Window length.
+    d : scalar, optional
+        Sample spacing. Default is 1.
+
+    Returns
+    -------
+    out : ndarray
+        The array of length `n`, containing the sample frequencies.
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy import fftpack
+    >>> sig = np.array([-2, 8, 6, 4, 1, 0, 3, 5], dtype=float)
+    >>> sig_fft = fftpack.rfft(sig)
+    >>> n = sig_fft.size
+    >>> timestep = 0.1
+    >>> freq = fftpack.rfftfreq(n, d=timestep)
+    >>> freq
+    array([ 0.  ,  1.25,  1.25,  2.5 ,  2.5 ,  3.75,  3.75,  5.  ])
+
+    """
+    n = operator.index(n)
+    if n < 0:
+        raise ValueError(f"n = {n} is not valid. "
+                         "n must be a nonnegative integer.")
+
+    return (np.arange(1, n + 1, dtype=int) // 2) / float(n * d)
+
+
+def next_fast_len(target):
+    """
+    Find the next fast size of input data to `fft`, for zero-padding, etc.
+
+    SciPy's FFTPACK has efficient functions for radix {2, 3, 4, 5}, so this
+    returns the next composite of the prime factors 2, 3, and 5 which is
+    greater than or equal to `target`. (These are also known as 5-smooth
+    numbers, regular numbers, or Hamming numbers.)
+
+    Parameters
+    ----------
+    target : int
+        Length to start searching from. Must be a positive integer.
+
+    Returns
+    -------
+    out : int
+        The first 5-smooth number greater than or equal to `target`.
+
+    Notes
+    -----
+    .. versionadded:: 0.18.0
+
+    Examples
+    --------
+    On a particular machine, an FFT of prime length takes 133 ms:
+
+    >>> from scipy import fftpack
+    >>> import numpy as np
+    >>> rng = np.random.default_rng()
+    >>> min_len = 10007  # prime length is worst case for speed
+    >>> a = rng.standard_normal(min_len)
+    >>> b = fftpack.fft(a)
+
+    Zero-padding to the next 5-smooth length reduces computation time to
+    211 us, a speedup of 630 times:
+
+    >>> fftpack.next_fast_len(min_len)
+    10125
+    >>> b = fftpack.fft(a, 10125)
+
+    Rounding up to the next power of 2 is not optimal, taking 367 us to
+    compute, 1.7 times as long as the 5-smooth size:
+
+    >>> b = fftpack.fft(a, 16384)
+
+    """
+    # Real transforms use regular sizes so this is backwards compatible
+    return _helper.good_size(target, True)
+
+
+def _good_shape(x, shape, axes):
+    """Ensure that shape argument is valid for scipy.fftpack
+
+    scipy.fftpack does not support len(shape) < x.ndim when axes is not given.
+    """
+    if shape is not None and axes is None:
+        shape = _helper._iterable_of_int(shape, 'shape')
+        if len(shape) != np.ndim(x):
+            raise ValueError("when given, axes and shape arguments"
+                             " have to be of the same length")
+    return shape
diff --git a/.venv/lib/python3.12/site-packages/scipy/fftpack/_pseudo_diffs.py b/.venv/lib/python3.12/site-packages/scipy/fftpack/_pseudo_diffs.py
new file mode 100644
index 0000000000000000000000000000000000000000..126f001e1124f1265adc5b9e6d9040d1a82124d7
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/fftpack/_pseudo_diffs.py
@@ -0,0 +1,554 @@
+"""
+Differential and pseudo-differential operators.
+"""
+# Created by Pearu Peterson, September 2002
+
+__all__ = ['diff',
+           'tilbert','itilbert','hilbert','ihilbert',
+           'cs_diff','cc_diff','sc_diff','ss_diff',
+           'shift']
+
+import threading
+
+from numpy import pi, asarray, sin, cos, sinh, cosh, tanh, iscomplexobj
+from . import convolve
+
+from scipy.fft._duccfft.helper import _datacopied
+
+
+_cache = threading.local()
+
+
+def diff(x,order=1,period=None, _cache=_cache):
+    """
+    Return kth derivative (or integral) of a periodic sequence x.
+
+    If x_j and y_j are Fourier coefficients of periodic functions x
+    and y, respectively, then::
+
+      y_j = pow(sqrt(-1)*j*2*pi/period, order) * x_j
+      y_0 = 0 if order is not 0.
+
+    Parameters
+    ----------
+    x : array_like
+        Input array.
+    order : int, optional
+        The order of differentiation. Default order is 1. If order is
+        negative, then integration is carried out under the assumption
+        that ``x_0 == 0``.
+    period : float, optional
+        The assumed period of the sequence. Default is ``2*pi``.
+
+    Notes
+    -----
+    If ``sum(x, axis=0) = 0`` then ``diff(diff(x, k), -k) == x`` (within
+    numerical accuracy).
+
+    For odd order and even ``len(x)``, the Nyquist mode is taken zero.
+
+    """  # numpydoc ignore=RT01
+    if isinstance(_cache, threading.local):
+        if not hasattr(_cache, 'diff_cache'):
+            _cache.diff_cache = {}
+        _cache = _cache.diff_cache
+
+    tmp = asarray(x)
+    if order == 0:
+        return tmp
+    if iscomplexobj(tmp):
+        return diff(tmp.real, order, period, _cache)+1j*diff(
+            tmp.imag, order, period, _cache)
+    if period is not None:
+        c = 2*pi/period
+    else:
+        c = 1.0
+    n = len(x)
+    omega = _cache.get((n,order,c))
+    if omega is None:
+        if len(_cache) > 20:
+            while _cache:
+                _cache.popitem()
+
+        def kernel(k,order=order,c=c):
+            if k:
+                return pow(c*k,order)
+            return 0
+        omega = convolve.init_convolution_kernel(n,kernel,d=order,
+                                                 zero_nyquist=1)
+        _cache[(n,order,c)] = omega
+    overwrite_x = _datacopied(tmp, x)
+    return convolve.convolve(tmp,omega,swap_real_imag=order % 2,
+                             overwrite_x=overwrite_x)
+
+
+def tilbert(x, h, period=None, _cache=_cache):
+    """
+    Return h-Tilbert transform of a periodic sequence x.
+
+    If x_j and y_j are Fourier coefficients of periodic functions x
+    and y, respectively, then::
+
+        y_j = sqrt(-1)*coth(j*h*2*pi/period) * x_j
+        y_0 = 0
+
+    Parameters
+    ----------
+    x : array_like
+        The input array to transform.
+    h : float
+        Defines the parameter of the Tilbert transform.
+    period : float, optional
+        The assumed period of the sequence. Default period is ``2*pi``.
+
+    Returns
+    -------
+    tilbert : ndarray
+        The result of the transform.
+
+    Notes
+    -----
+    If ``sum(x, axis=0) == 0`` and ``n = len(x)`` is odd, then
+    ``tilbert(itilbert(x)) == x``.
+
+    If ``2 * pi * h / period`` is approximately 10 or larger, then
+    numerically ``tilbert == hilbert``
+    (theoretically oo-Tilbert == Hilbert).
+
+    For even ``len(x)``, the Nyquist mode of ``x`` is taken zero.
+
+    """
+    if isinstance(_cache, threading.local):
+        if not hasattr(_cache, 'tilbert_cache'):
+            _cache.tilbert_cache = {}
+        _cache = _cache.tilbert_cache
+
+    tmp = asarray(x)
+    if iscomplexobj(tmp):
+        return tilbert(tmp.real, h, period, _cache) + \
+               1j * tilbert(tmp.imag, h, period, _cache)
+
+    if period is not None:
+        h = h * 2 * pi / period
+
+    n = len(x)
+    omega = _cache.get((n, h))
+    if omega is None:
+        if len(_cache) > 20:
+            while _cache:
+                _cache.popitem()
+
+        def kernel(k, h=h):
+            if k:
+                return 1.0/tanh(h*k)
+
+            return 0
+
+        omega = convolve.init_convolution_kernel(n, kernel, d=1)
+        _cache[(n,h)] = omega
+
+    overwrite_x = _datacopied(tmp, x)
+    return convolve.convolve(tmp,omega,swap_real_imag=1,overwrite_x=overwrite_x)
+
+
+def itilbert(x,h,period=None, _cache=_cache):
+    """
+    Return inverse h-Tilbert transform of a periodic sequence x.
+
+    If ``x_j`` and ``y_j`` are Fourier coefficients of periodic functions x
+    and y, respectively, then::
+
+      y_j = -sqrt(-1)*tanh(j*h*2*pi/period) * x_j
+      y_0 = 0
+
+    For more details, see `tilbert`.
+
+    """  # numpydoc ignore=RT01
+    if isinstance(_cache, threading.local):
+        if not hasattr(_cache, 'itilbert_cache'):
+            _cache.itilbert_cache = {}
+        _cache = _cache.itilbert_cache
+
+    tmp = asarray(x)
+    if iscomplexobj(tmp):
+        return itilbert(tmp.real, h, period, _cache) + \
+               1j*itilbert(tmp.imag, h, period, _cache)
+    if period is not None:
+        h = h*2*pi/period
+    n = len(x)
+    omega = _cache.get((n,h))
+    if omega is None:
+        if len(_cache) > 20:
+            while _cache:
+                _cache.popitem()
+
+        def kernel(k,h=h):
+            if k:
+                return -tanh(h*k)
+            return 0
+        omega = convolve.init_convolution_kernel(n,kernel,d=1)
+        _cache[(n,h)] = omega
+    overwrite_x = _datacopied(tmp, x)
+    return convolve.convolve(tmp,omega,swap_real_imag=1,overwrite_x=overwrite_x)
+
+
+def hilbert(x, _cache=_cache):
+    """
+    Return Hilbert transform of a periodic sequence x.
+
+    If x_j and y_j are Fourier coefficients of periodic functions x
+    and y, respectively, then::
+
+      y_j = sqrt(-1)*sign(j) * x_j
+      y_0 = 0
+
+    Parameters
+    ----------
+    x : array_like
+        The input array, should be periodic.
+    _cache : dict, optional
+        Dictionary that contains the kernel used to do a convolution with.
+
+    Returns
+    -------
+    y : ndarray
+        The transformed input.
+
+    See Also
+    --------
+    scipy.signal.hilbert : Compute the analytic signal, using the Hilbert
+                           transform.
+
+    Notes
+    -----
+    If ``sum(x, axis=0) == 0`` then ``hilbert(ihilbert(x)) == x``.
+
+    For even len(x), the Nyquist mode of x is taken zero.
+
+    The sign of the returned transform does not have a factor -1 that is more
+    often than not found in the definition of the Hilbert transform. Note also
+    that `scipy.signal.hilbert` does have an extra -1 factor compared to this
+    function.
+
+    """
+    if isinstance(_cache, threading.local):
+        if not hasattr(_cache, 'hilbert_cache'):
+            _cache.hilbert_cache = {}
+        _cache = _cache.hilbert_cache
+
+    tmp = asarray(x)
+    if iscomplexobj(tmp):
+        return hilbert(tmp.real, _cache) + 1j * hilbert(tmp.imag, _cache)
+    n = len(x)
+    omega = _cache.get(n)
+    if omega is None:
+        if len(_cache) > 20:
+            while _cache:
+                _cache.popitem()
+
+        def kernel(k):
+            if k > 0:
+                return 1.0
+            elif k < 0:
+                return -1.0
+            return 0.0
+        omega = convolve.init_convolution_kernel(n,kernel,d=1)
+        _cache[n] = omega
+    overwrite_x = _datacopied(tmp, x)
+    return convolve.convolve(tmp,omega,swap_real_imag=1,overwrite_x=overwrite_x)
+
+
+def ihilbert(x, _cache=_cache):
+    """
+    Return inverse Hilbert transform of a periodic sequence x.
+
+    If ``x_j`` and ``y_j`` are Fourier coefficients of periodic functions x
+    and y, respectively, then::
+
+      y_j = -sqrt(-1)*sign(j) * x_j
+      y_0 = 0
+
+    """  # numpydoc ignore=RT01
+    if isinstance(_cache, threading.local):
+        if not hasattr(_cache, 'ihilbert_cache'):
+            _cache.ihilbert_cache = {}
+        _cache = _cache.ihilbert_cache
+    return -hilbert(x, _cache)
+
+
+def cs_diff(x, a, b, period=None, _cache=_cache):
+    """
+    Return (a,b)-cosh/sinh pseudo-derivative of a periodic sequence.
+
+    If ``x_j`` and ``y_j`` are Fourier coefficients of periodic functions x
+    and y, respectively, then::
+
+      y_j = -sqrt(-1)*cosh(j*a*2*pi/period)/sinh(j*b*2*pi/period) * x_j
+      y_0 = 0
+
+    Parameters
+    ----------
+    x : array_like
+        The array to take the pseudo-derivative from.
+    a, b : float
+        Defines the parameters of the cosh/sinh pseudo-differential
+        operator.
+    period : float, optional
+        The period of the sequence. Default period is ``2*pi``.
+
+    Returns
+    -------
+    cs_diff : ndarray
+        Pseudo-derivative of periodic sequence `x`.
+
+    Notes
+    -----
+    For even len(`x`), the Nyquist mode of `x` is taken as zero.
+
+    """
+    if isinstance(_cache, threading.local):
+        if not hasattr(_cache, 'cs_diff_cache'):
+            _cache.cs_diff_cache = {}
+        _cache = _cache.cs_diff_cache
+
+    tmp = asarray(x)
+    if iscomplexobj(tmp):
+        return cs_diff(tmp.real, a, b, period, _cache) + \
+               1j*cs_diff(tmp.imag, a, b, period, _cache)
+    if period is not None:
+        a = a*2*pi/period
+        b = b*2*pi/period
+    n = len(x)
+    omega = _cache.get((n,a,b))
+    if omega is None:
+        if len(_cache) > 20:
+            while _cache:
+                _cache.popitem()
+
+        def kernel(k,a=a,b=b):
+            if k:
+                return -cosh(a*k)/sinh(b*k)
+            return 0
+        omega = convolve.init_convolution_kernel(n,kernel,d=1)
+        _cache[(n,a,b)] = omega
+    overwrite_x = _datacopied(tmp, x)
+    return convolve.convolve(tmp,omega,swap_real_imag=1,overwrite_x=overwrite_x)
+
+
+def sc_diff(x, a, b, period=None, _cache=_cache):
+    """
+    Return (a,b)-sinh/cosh pseudo-derivative of a periodic sequence x.
+
+    If x_j and y_j are Fourier coefficients of periodic functions x
+    and y, respectively, then::
+
+      y_j = sqrt(-1)*sinh(j*a*2*pi/period)/cosh(j*b*2*pi/period) * x_j
+      y_0 = 0
+
+    Parameters
+    ----------
+    x : array_like
+        Input array.
+    a, b : float
+        Defines the parameters of the sinh/cosh pseudo-differential
+        operator.
+    period : float, optional
+        The period of the sequence x. Default is 2*pi.
+
+    Notes
+    -----
+    ``sc_diff(cs_diff(x,a,b),b,a) == x``
+    For even ``len(x)``, the Nyquist mode of x is taken as zero.
+
+    """  # numpydoc ignore=RT01
+    if isinstance(_cache, threading.local):
+        if not hasattr(_cache, 'sc_diff_cache'):
+            _cache.sc_diff_cache = {}
+        _cache = _cache.sc_diff_cache
+
+    tmp = asarray(x)
+    if iscomplexobj(tmp):
+        return sc_diff(tmp.real, a, b, period, _cache) + \
+               1j * sc_diff(tmp.imag, a, b, period, _cache)
+    if period is not None:
+        a = a*2*pi/period
+        b = b*2*pi/period
+    n = len(x)
+    omega = _cache.get((n,a,b))
+    if omega is None:
+        if len(_cache) > 20:
+            while _cache:
+                _cache.popitem()
+
+        def kernel(k,a=a,b=b):
+            if k:
+                return sinh(a*k)/cosh(b*k)
+            return 0
+        omega = convolve.init_convolution_kernel(n,kernel,d=1)
+        _cache[(n,a,b)] = omega
+    overwrite_x = _datacopied(tmp, x)
+    return convolve.convolve(tmp,omega,swap_real_imag=1,overwrite_x=overwrite_x)
+
+
+def ss_diff(x, a, b, period=None, _cache=_cache):
+    """
+    Return (a,b)-sinh/sinh pseudo-derivative of a periodic sequence x.
+
+    If x_j and y_j are Fourier coefficients of periodic functions x
+    and y, respectively, then::
+
+      y_j = sinh(j*a*2*pi/period)/sinh(j*b*2*pi/period) * x_j
+      y_0 = a/b * x_0
+
+    Parameters
+    ----------
+    x : array_like
+        The array to take the pseudo-derivative from.
+    a, b
+        Defines the parameters of the sinh/sinh pseudo-differential
+        operator.
+    period : float, optional
+        The period of the sequence x. Default is ``2*pi``.
+
+    Notes
+    -----
+    ``ss_diff(ss_diff(x,a,b),b,a) == x``
+
+    """  # numpydoc ignore=RT01
+    if isinstance(_cache, threading.local):
+        if not hasattr(_cache, 'ss_diff_cache'):
+            _cache.ss_diff_cache = {}
+        _cache = _cache.ss_diff_cache
+
+    tmp = asarray(x)
+    if iscomplexobj(tmp):
+        return ss_diff(tmp.real, a, b, period, _cache) + \
+               1j*ss_diff(tmp.imag, a, b, period, _cache)
+    if period is not None:
+        a = a*2*pi/period
+        b = b*2*pi/period
+    n = len(x)
+    omega = _cache.get((n,a,b))
+    if omega is None:
+        if len(_cache) > 20:
+            while _cache:
+                _cache.popitem()
+
+        def kernel(k,a=a,b=b):
+            if k:
+                return sinh(a*k)/sinh(b*k)
+            return float(a)/b
+        omega = convolve.init_convolution_kernel(n,kernel)
+        _cache[(n,a,b)] = omega
+    overwrite_x = _datacopied(tmp, x)
+    return convolve.convolve(tmp,omega,overwrite_x=overwrite_x)
+
+
+def cc_diff(x, a, b, period=None, _cache=_cache):
+    """
+    Return (a,b)-cosh/cosh pseudo-derivative of a periodic sequence.
+
+    If x_j and y_j are Fourier coefficients of periodic functions x
+    and y, respectively, then::
+
+      y_j = cosh(j*a*2*pi/period)/cosh(j*b*2*pi/period) * x_j
+
+    Parameters
+    ----------
+    x : array_like
+        The array to take the pseudo-derivative from.
+    a, b : float
+        Defines the parameters of the sinh/sinh pseudo-differential
+        operator.
+    period : float, optional
+        The period of the sequence x. Default is ``2*pi``.
+
+    Returns
+    -------
+    cc_diff : ndarray
+        Pseudo-derivative of periodic sequence `x`.
+
+    Notes
+    -----
+    ``cc_diff(cc_diff(x,a,b),b,a) == x``
+
+    """
+    if isinstance(_cache, threading.local):
+        if not hasattr(_cache, 'cc_diff_cache'):
+            _cache.cc_diff_cache = {}
+        _cache = _cache.cc_diff_cache
+
+    tmp = asarray(x)
+    if iscomplexobj(tmp):
+        return cc_diff(tmp.real, a, b, period, _cache) + \
+               1j * cc_diff(tmp.imag, a, b, period, _cache)
+    if period is not None:
+        a = a*2*pi/period
+        b = b*2*pi/period
+    n = len(x)
+    omega = _cache.get((n,a,b))
+    if omega is None:
+        if len(_cache) > 20:
+            while _cache:
+                _cache.popitem()
+
+        def kernel(k,a=a,b=b):
+            return cosh(a*k)/cosh(b*k)
+        omega = convolve.init_convolution_kernel(n,kernel)
+        _cache[(n,a,b)] = omega
+    overwrite_x = _datacopied(tmp, x)
+    return convolve.convolve(tmp,omega,overwrite_x=overwrite_x)
+
+
+def shift(x, a, period=None, _cache=_cache):
+    """
+    Shift periodic sequence x by a: y(u) = x(u+a).
+
+    If x_j and y_j are Fourier coefficients of periodic functions x
+    and y, respectively, then::
+
+          y_j = exp(j*a*2*pi/period*sqrt(-1)) * x_f
+
+    Parameters
+    ----------
+    x : array_like
+        The array to take the pseudo-derivative from.
+    a : float
+        Defines the parameters of the sinh/sinh pseudo-differential
+    period : float, optional
+        The period of the sequences x and y. Default period is ``2*pi``.
+    """  # numpydoc ignore=RT01
+    if isinstance(_cache, threading.local):
+        if not hasattr(_cache, 'shift_cache'):
+            _cache.shift_cache = {}
+        _cache = _cache.shift_cache
+
+    tmp = asarray(x)
+    if iscomplexobj(tmp):
+        return shift(tmp.real, a, period, _cache) + 1j * shift(
+            tmp.imag, a, period, _cache)
+    if period is not None:
+        a = a*2*pi/period
+    n = len(x)
+    omega = _cache.get((n,a))
+    if omega is None:
+        if len(_cache) > 20:
+            while _cache:
+                _cache.popitem()
+
+        def kernel_real(k,a=a):
+            return cos(a*k)
+
+        def kernel_imag(k,a=a):
+            return sin(a*k)
+        omega_real = convolve.init_convolution_kernel(n,kernel_real,d=0,
+                                                      zero_nyquist=0)
+        omega_imag = convolve.init_convolution_kernel(n,kernel_imag,d=1,
+                                                      zero_nyquist=0)
+        _cache[(n,a)] = omega_real,omega_imag
+    else:
+        omega_real,omega_imag = omega
+    overwrite_x = _datacopied(tmp, x)
+    return convolve.convolve_z(tmp,omega_real,omega_imag,
+                               overwrite_x=overwrite_x)
+
diff --git a/.venv/lib/python3.12/site-packages/scipy/fftpack/_realtransforms.py b/.venv/lib/python3.12/site-packages/scipy/fftpack/_realtransforms.py
new file mode 100644
index 0000000000000000000000000000000000000000..fcb90ebb3747374f0116e8670c9e3d3b327267da
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/fftpack/_realtransforms.py
@@ -0,0 +1,598 @@
+"""
+Real spectrum transforms (DCT, DST, MDCT)
+"""
+
+__all__ = ['dct', 'idct', 'dst', 'idst', 'dctn', 'idctn', 'dstn', 'idstn']
+
+from scipy.fft import _duccfft
+from ._helper import _good_shape
+
+_inverse_typemap = {1: 1, 2: 3, 3: 2, 4: 4}
+
+
+def dctn(x, type=2, shape=None, axes=None, norm=None, overwrite_x=False):
+    """
+    Return multidimensional Discrete Cosine Transform along the specified axes.
+
+    Parameters
+    ----------
+    x : array_like
+        The input array.
+    type : {1, 2, 3, 4}, optional
+        Type of the DCT (see Notes). Default type is 2.
+    shape : int or array_like of ints or None, optional
+        The shape of the result. If both `shape` and `axes` (see below) are
+        None, `shape` is ``x.shape``; if `shape` is None but `axes` is
+        not None, then `shape` is ``numpy.take(x.shape, axes, axis=0)``.
+        If ``shape[i] > x.shape[i]``, the ith dimension is padded with zeros.
+        If ``shape[i] < x.shape[i]``, the ith dimension is truncated to
+        length ``shape[i]``.
+        If any element of `shape` is -1, the size of the corresponding
+        dimension of `x` is used.
+    axes : int or array_like of ints or None, optional
+        Axes along which the DCT is computed.
+        The default is over all axes.
+    norm : {None, 'ortho'}, optional
+        Normalization mode (see Notes). Default is None.
+    overwrite_x : bool, optional
+        If True, the contents of `x` can be destroyed; the default is False.
+
+    Returns
+    -------
+    y : ndarray of real
+        The transformed input array.
+
+    See Also
+    --------
+    idctn : Inverse multidimensional DCT
+
+    Notes
+    -----
+    For full details of the DCT types and normalization modes, as well as
+    references, see `dct`.
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy.fftpack import dctn, idctn
+    >>> rng = np.random.default_rng()
+    >>> y = rng.standard_normal((16, 16))
+    >>> np.allclose(y, idctn(dctn(y, norm='ortho'), norm='ortho'))
+    True
+
+    """
+    shape = _good_shape(x, shape, axes)
+    return _duccfft.dctn(x, type, shape, axes, norm, overwrite_x)
+
+
+def idctn(x, type=2, shape=None, axes=None, norm=None, overwrite_x=False):
+    """
+    Return multidimensional Discrete Cosine Transform along the specified axes.
+
+    Parameters
+    ----------
+    x : array_like
+        The input array.
+    type : {1, 2, 3, 4}, optional
+        Type of the DCT (see Notes). Default type is 2.
+    shape : int or array_like of ints or None, optional
+        The shape of the result.  If both `shape` and `axes` (see below) are
+        None, `shape` is ``x.shape``; if `shape` is None but `axes` is
+        not None, then `shape` is ``numpy.take(x.shape, axes, axis=0)``.
+        If ``shape[i] > x.shape[i]``, the ith dimension is padded with zeros.
+        If ``shape[i] < x.shape[i]``, the ith dimension is truncated to
+        length ``shape[i]``.
+        If any element of `shape` is -1, the size of the corresponding
+        dimension of `x` is used.
+    axes : int or array_like of ints or None, optional
+        Axes along which the IDCT is computed.
+        The default is over all axes.
+    norm : {None, 'ortho'}, optional
+        Normalization mode (see Notes). Default is None.
+    overwrite_x : bool, optional
+        If True, the contents of `x` can be destroyed; the default is False.
+
+    Returns
+    -------
+    y : ndarray of real
+        The transformed input array.
+
+    See Also
+    --------
+    dctn : multidimensional DCT
+
+    Notes
+    -----
+    For full details of the IDCT types and normalization modes, as well as
+    references, see `idct`.
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy.fftpack import dctn, idctn
+    >>> rng = np.random.default_rng()
+    >>> y = rng.standard_normal((16, 16))
+    >>> np.allclose(y, idctn(dctn(y, norm='ortho'), norm='ortho'))
+    True
+
+    """
+    type = _inverse_typemap[type]
+    shape = _good_shape(x, shape, axes)
+    return _duccfft.dctn(x, type, shape, axes, norm, overwrite_x)
+
+
+def dstn(x, type=2, shape=None, axes=None, norm=None, overwrite_x=False):
+    """
+    Return multidimensional Discrete Sine Transform along the specified axes.
+
+    Parameters
+    ----------
+    x : array_like
+        The input array.
+    type : {1, 2, 3, 4}, optional
+        Type of the DST (see Notes). Default type is 2.
+    shape : int or array_like of ints or None, optional
+        The shape of the result.  If both `shape` and `axes` (see below) are
+        None, `shape` is ``x.shape``; if `shape` is None but `axes` is
+        not None, then `shape` is ``numpy.take(x.shape, axes, axis=0)``.
+        If ``shape[i] > x.shape[i]``, the ith dimension is padded with zeros.
+        If ``shape[i] < x.shape[i]``, the ith dimension is truncated to
+        length ``shape[i]``.
+        If any element of `shape` is -1, the size of the corresponding
+        dimension of `x` is used.
+    axes : int or array_like of ints or None, optional
+        Axes along which the DCT is computed.
+        The default is over all axes.
+    norm : {None, 'ortho'}, optional
+        Normalization mode (see Notes). Default is None.
+    overwrite_x : bool, optional
+        If True, the contents of `x` can be destroyed; the default is False.
+
+    Returns
+    -------
+    y : ndarray of real
+        The transformed input array.
+
+    See Also
+    --------
+    idstn : Inverse multidimensional DST
+
+    Notes
+    -----
+    For full details of the DST types and normalization modes, as well as
+    references, see `dst`.
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy.fftpack import dstn, idstn
+    >>> rng = np.random.default_rng()
+    >>> y = rng.standard_normal((16, 16))
+    >>> np.allclose(y, idstn(dstn(y, norm='ortho'), norm='ortho'))
+    True
+
+    """
+    shape = _good_shape(x, shape, axes)
+    return _duccfft.dstn(x, type, shape, axes, norm, overwrite_x)
+
+
+def idstn(x, type=2, shape=None, axes=None, norm=None, overwrite_x=False):
+    """
+    Return multidimensional Discrete Sine Transform along the specified axes.
+
+    Parameters
+    ----------
+    x : array_like
+        The input array.
+    type : {1, 2, 3, 4}, optional
+        Type of the DST (see Notes). Default type is 2.
+    shape : int or array_like of ints or None, optional
+        The shape of the result.  If both `shape` and `axes` (see below) are
+        None, `shape` is ``x.shape``; if `shape` is None but `axes` is
+        not None, then `shape` is ``numpy.take(x.shape, axes, axis=0)``.
+        If ``shape[i] > x.shape[i]``, the ith dimension is padded with zeros.
+        If ``shape[i] < x.shape[i]``, the ith dimension is truncated to
+        length ``shape[i]``.
+        If any element of `shape` is -1, the size of the corresponding
+        dimension of `x` is used.
+    axes : int or array_like of ints or None, optional
+        Axes along which the IDST is computed.
+        The default is over all axes.
+    norm : {None, 'ortho'}, optional
+        Normalization mode (see Notes). Default is None.
+    overwrite_x : bool, optional
+        If True, the contents of `x` can be destroyed; the default is False.
+
+    Returns
+    -------
+    y : ndarray of real
+        The transformed input array.
+
+    See Also
+    --------
+    dstn : multidimensional DST
+
+    Notes
+    -----
+    For full details of the IDST types and normalization modes, as well as
+    references, see `idst`.
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy.fftpack import dstn, idstn
+    >>> rng = np.random.default_rng()
+    >>> y = rng.standard_normal((16, 16))
+    >>> np.allclose(y, idstn(dstn(y, norm='ortho'), norm='ortho'))
+    True
+
+    """
+    type = _inverse_typemap[type]
+    shape = _good_shape(x, shape, axes)
+    return _duccfft.dstn(x, type, shape, axes, norm, overwrite_x)
+
+
+def dct(x, type=2, n=None, axis=-1, norm=None, overwrite_x=False):
+    r"""
+    Return the Discrete Cosine Transform of arbitrary type sequence x.
+
+    Parameters
+    ----------
+    x : array_like
+        The input array.
+    type : {1, 2, 3, 4}, optional
+        Type of the DCT (see Notes). Default type is 2.
+    n : int, optional
+        Length of the transform.  If ``n < x.shape[axis]``, `x` is
+        truncated.  If ``n > x.shape[axis]``, `x` is zero-padded. The
+        default results in ``n = x.shape[axis]``.
+    axis : int, optional
+        Axis along which the dct is computed; the default is over the
+        last axis (i.e., ``axis=-1``).
+    norm : {None, 'ortho'}, optional
+        Normalization mode (see Notes). Default is None.
+    overwrite_x : bool, optional
+        If True, the contents of `x` can be destroyed; the default is False.
+
+    Returns
+    -------
+    y : ndarray of real
+        The transformed input array.
+
+    See Also
+    --------
+    idct : Inverse DCT
+
+    Notes
+    -----
+    For a single dimension array ``x``, ``dct(x, norm='ortho')`` is equal to
+    MATLAB ``dct(x)``.
+
+    There are, theoretically, 8 types of the DCT, only the first 4 types are
+    implemented in scipy. 'The' DCT generally refers to DCT type 2, and 'the'
+    Inverse DCT generally refers to DCT type 3.
+
+    **Type I**
+
+    There are several definitions of the DCT-I; we use the following
+    (for ``norm=None``)
+
+    .. math::
+
+       y_k = x_0 + (-1)^k x_{N-1} + 2 \sum_{n=1}^{N-2} x_n \cos\left(
+       \frac{\pi k n}{N-1} \right)
+
+    If ``norm='ortho'``, ``x[0]`` and ``x[N-1]`` are multiplied by a scaling
+    factor of :math:`\sqrt{2}`, and ``y[k]`` is multiplied by a scaling factor
+    ``f``
+
+    .. math::
+
+        f = \begin{cases}
+         \frac{1}{2}\sqrt{\frac{1}{N-1}} & \text{if }k=0\text{ or }N-1, \\
+         \frac{1}{2}\sqrt{\frac{2}{N-1}} & \text{otherwise} \end{cases}
+
+    .. versionadded:: 1.2.0
+       Orthonormalization in DCT-I.
+
+    .. note::
+       The DCT-I is only supported for input size > 1.
+
+    **Type II**
+
+    There are several definitions of the DCT-II; we use the following
+    (for ``norm=None``)
+
+    .. math::
+
+       y_k = 2 \sum_{n=0}^{N-1} x_n \cos\left(\frac{\pi k(2n+1)}{2N} \right)
+
+    If ``norm='ortho'``, ``y[k]`` is multiplied by a scaling factor ``f``
+
+    .. math::
+       f = \begin{cases}
+       \sqrt{\frac{1}{4N}} & \text{if }k=0, \\
+       \sqrt{\frac{1}{2N}} & \text{otherwise} \end{cases}
+
+    which makes the corresponding matrix of coefficients orthonormal
+    (``O @ O.T = np.eye(N)``).
+
+    **Type III**
+
+    There are several definitions, we use the following (for ``norm=None``)
+
+    .. math::
+
+       y_k = x_0 + 2 \sum_{n=1}^{N-1} x_n \cos\left(\frac{\pi(2k+1)n}{2N}\right)
+
+    or, for ``norm='ortho'``
+
+    .. math::
+
+       y_k = \frac{x_0}{\sqrt{N}} + \sqrt{\frac{2}{N}} \sum_{n=1}^{N-1} x_n
+       \cos\left(\frac{\pi(2k+1)n}{2N}\right)
+
+    The (unnormalized) DCT-III is the inverse of the (unnormalized) DCT-II, up
+    to a factor ``2N``. The orthonormalized DCT-III is exactly the inverse of
+    the orthonormalized DCT-II.
+
+    **Type IV**
+
+    There are several definitions of the DCT-IV; we use the following
+    (for ``norm=None``)
+
+    .. math::
+
+       y_k = 2 \sum_{n=0}^{N-1} x_n \cos\left(\frac{\pi(2k+1)(2n+1)}{4N} \right)
+
+    If ``norm='ortho'``, ``y[k]`` is multiplied by a scaling factor ``f``
+
+    .. math::
+
+        f = \frac{1}{\sqrt{2N}}
+
+    .. versionadded:: 1.2.0
+       Support for DCT-IV.
+
+    References
+    ----------
+    .. [1] 'A Fast Cosine Transform in One and Two Dimensions', by J.
+           Makhoul, `IEEE Transactions on acoustics, speech and signal
+           processing` vol. 28(1), pp. 27-34,
+           :doi:`10.1109/TASSP.1980.1163351` (1980).
+    .. [2] Wikipedia, "Discrete cosine transform",
+           https://en.wikipedia.org/wiki/Discrete_cosine_transform
+
+    Examples
+    --------
+    The Type 1 DCT is equivalent to the FFT (though faster) for real,
+    even-symmetrical inputs. The output is also real and even-symmetrical.
+    Half of the FFT input is used to generate half of the FFT output:
+
+    >>> from scipy.fftpack import fft, dct
+    >>> import numpy as np
+    >>> fft(np.array([4., 3., 5., 10., 5., 3.])).real
+    array([ 30.,  -8.,   6.,  -2.,   6.,  -8.])
+    >>> dct(np.array([4., 3., 5., 10.]), 1)
+    array([ 30.,  -8.,   6.,  -2.])
+
+    """
+    return _duccfft.dct(x, type, n, axis, norm, overwrite_x)
+
+
+def idct(x, type=2, n=None, axis=-1, norm=None, overwrite_x=False):
+    """
+    Return the Inverse Discrete Cosine Transform of an arbitrary type sequence.
+
+    Parameters
+    ----------
+    x : array_like
+        The input array.
+    type : {1, 2, 3, 4}, optional
+        Type of the DCT (see Notes). Default type is 2.
+    n : int, optional
+        Length of the transform.  If ``n < x.shape[axis]``, `x` is
+        truncated.  If ``n > x.shape[axis]``, `x` is zero-padded. The
+        default results in ``n = x.shape[axis]``.
+    axis : int, optional
+        Axis along which the idct is computed; the default is over the
+        last axis (i.e., ``axis=-1``).
+    norm : {None, 'ortho'}, optional
+        Normalization mode (see Notes). Default is None.
+    overwrite_x : bool, optional
+        If True, the contents of `x` can be destroyed; the default is False.
+
+    Returns
+    -------
+    idct : ndarray of real
+        The transformed input array.
+
+    See Also
+    --------
+    dct : Forward DCT
+
+    Notes
+    -----
+    For a single dimension array `x`, ``idct(x, norm='ortho')`` is equal to
+    MATLAB ``idct(x)``.
+
+    'The' IDCT is the IDCT of type 2, which is the same as DCT of type 3.
+
+    IDCT of type 1 is the DCT of type 1, IDCT of type 2 is the DCT of type
+    3, and IDCT of type 3 is the DCT of type 2. IDCT of type 4 is the DCT
+    of type 4. For the definition of these types, see `dct`.
+
+    Examples
+    --------
+    The Type 1 DCT is equivalent to the DFT for real, even-symmetrical
+    inputs. The output is also real and even-symmetrical. Half of the IFFT
+    input is used to generate half of the IFFT output:
+
+    >>> from scipy.fftpack import ifft, idct
+    >>> import numpy as np
+    >>> ifft(np.array([ 30.,  -8.,   6.,  -2.,   6.,  -8.])).real
+    array([  4.,   3.,   5.,  10.,   5.,   3.])
+    >>> idct(np.array([ 30.,  -8.,   6.,  -2.]), 1) / 6
+    array([  4.,   3.,   5.,  10.])
+
+    """
+    type = _inverse_typemap[type]
+    return _duccfft.dct(x, type, n, axis, norm, overwrite_x)
+
+
+def dst(x, type=2, n=None, axis=-1, norm=None, overwrite_x=False):
+    r"""
+    Return the Discrete Sine Transform of arbitrary type sequence x.
+
+    Parameters
+    ----------
+    x : array_like
+        The input array.
+    type : {1, 2, 3, 4}, optional
+        Type of the DST (see Notes). Default type is 2.
+    n : int, optional
+        Length of the transform.  If ``n < x.shape[axis]``, `x` is
+        truncated.  If ``n > x.shape[axis]``, `x` is zero-padded. The
+        default results in ``n = x.shape[axis]``.
+    axis : int, optional
+        Axis along which the dst is computed; the default is over the
+        last axis (i.e., ``axis=-1``).
+    norm : {None, 'ortho'}, optional
+        Normalization mode (see Notes). Default is None.
+    overwrite_x : bool, optional
+        If True, the contents of `x` can be destroyed; the default is False.
+
+    Returns
+    -------
+    dst : ndarray of reals
+        The transformed input array.
+
+    See Also
+    --------
+    idst : Inverse DST
+
+    Notes
+    -----
+    For a single dimension array ``x``.
+
+    There are, theoretically, 8 types of the DST for different combinations of
+    even/odd boundary conditions and boundary off sets [1]_, only the first
+    4 types are implemented in scipy.
+
+    **Type I**
+
+    There are several definitions of the DST-I; we use the following
+    for ``norm=None``. DST-I assumes the input is odd around `n=-1` and `n=N`.
+
+    .. math::
+
+        y_k = 2 \sum_{n=0}^{N-1} x_n \sin\left(\frac{\pi(k+1)(n+1)}{N+1}\right)
+
+    Note that the DST-I is only supported for input size > 1.
+    The (unnormalized) DST-I is its own inverse, up to a factor ``2(N+1)``.
+    The orthonormalized DST-I is exactly its own inverse.
+
+    **Type II**
+
+    There are several definitions of the DST-II; we use the following for
+    ``norm=None``. DST-II assumes the input is odd around `n=-1/2` and
+    `n=N-1/2`; the output is odd around :math:`k=-1` and even around `k=N-1`
+
+    .. math::
+
+        y_k = 2 \sum_{n=0}^{N-1} x_n \sin\left(\frac{\pi(k+1)(2n+1)}{2N}\right)
+
+    if ``norm='ortho'``, ``y[k]`` is multiplied by a scaling factor ``f``
+
+    .. math::
+
+        f = \begin{cases}
+        \sqrt{\frac{1}{4N}} & \text{if }k = 0, \\
+        \sqrt{\frac{1}{2N}} & \text{otherwise} \end{cases}
+
+    **Type III**
+
+    There are several definitions of the DST-III, we use the following (for
+    ``norm=None``). DST-III assumes the input is odd around `n=-1` and even
+    around `n=N-1`
+
+    .. math::
+
+        y_k = (-1)^k x_{N-1} + 2 \sum_{n=0}^{N-2} x_n \sin\left(
+        \frac{\pi(2k+1)(n+1)}{2N}\right)
+
+    The (unnormalized) DST-III is the inverse of the (unnormalized) DST-II, up
+    to a factor ``2N``. The orthonormalized DST-III is exactly the inverse of the
+    orthonormalized DST-II.
+
+    .. versionadded:: 0.11.0
+
+    **Type IV**
+
+    There are several definitions of the DST-IV, we use the following (for
+    ``norm=None``). DST-IV assumes the input is odd around `n=-0.5` and even
+    around `n=N-0.5`
+
+    .. math::
+
+        y_k = 2 \sum_{n=0}^{N-1} x_n \sin\left(\frac{\pi(2k+1)(2n+1)}{4N}\right)
+
+    The (unnormalized) DST-IV is its own inverse, up to a factor ``2N``. The
+    orthonormalized DST-IV is exactly its own inverse.
+
+    .. versionadded:: 1.2.0
+       Support for DST-IV.
+
+    References
+    ----------
+    .. [1] Wikipedia, "Discrete sine transform",
+           https://en.wikipedia.org/wiki/Discrete_sine_transform
+
+    """
+    return _duccfft.dst(x, type, n, axis, norm, overwrite_x)
+
+
+def idst(x, type=2, n=None, axis=-1, norm=None, overwrite_x=False):
+    """
+    Return the Inverse Discrete Sine Transform of an arbitrary type sequence.
+
+    Parameters
+    ----------
+    x : array_like
+        The input array.
+    type : {1, 2, 3, 4}, optional
+        Type of the DST (see Notes). Default type is 2.
+    n : int, optional
+        Length of the transform.  If ``n < x.shape[axis]``, `x` is
+        truncated. If ``n > x.shape[axis]``, `x` is zero-padded. The
+        default results in ``n = x.shape[axis]``.
+    axis : int, optional
+        Axis along which the idst is computed; the default is over the
+        last axis (i.e., ``axis=-1``).
+    norm : {None, 'ortho'}, optional
+        Normalization mode (see Notes). Default is None.
+    overwrite_x : bool, optional
+        If True, the contents of `x` can be destroyed; the default is False.
+
+    Returns
+    -------
+    idst : ndarray of real
+        The transformed input array.
+
+    See Also
+    --------
+    dst : Forward DST
+
+    Notes
+    -----
+    'The' IDST is the IDST of type 2, which is the same as DST of type 3.
+
+    IDST of type 1 is the DST of type 1, IDST of type 2 is the DST of type
+    3, and IDST of type 3 is the DST of type 2. For the definition of these
+    types, see `dst`.
+
+    .. versionadded:: 0.11.0
+
+    """
+    type = _inverse_typemap[type]
+    return _duccfft.dst(x, type, n, axis, norm, overwrite_x)
diff --git a/.venv/lib/python3.12/site-packages/scipy/fftpack/basic.py b/.venv/lib/python3.12/site-packages/scipy/fftpack/basic.py
new file mode 100644
index 0000000000000000000000000000000000000000..553f456fe1561c28928ecc4ebe2238459cc60443
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/fftpack/basic.py
@@ -0,0 +1,20 @@
+# This file is not meant for public use and will be removed in SciPy v2.0.0.
+# Use the `scipy.fftpack` namespace for importing the functions
+# included below.
+
+from scipy._lib.deprecation import _sub_module_deprecation
+
+__all__ = [  # noqa: F822
+    'fft','ifft','fftn','ifftn','rfft','irfft',
+    'fft2','ifft2'
+]
+
+
+def __dir__():
+    return __all__
+
+
+def __getattr__(name):
+    return _sub_module_deprecation(sub_package="fftpack", module="basic",
+                                   private_modules=["_basic"], all=__all__,
+                                   attribute=name)
diff --git a/.venv/lib/python3.12/site-packages/scipy/fftpack/convolve.cpython-312-x86_64-linux-gnu.so b/.venv/lib/python3.12/site-packages/scipy/fftpack/convolve.cpython-312-x86_64-linux-gnu.so
new file mode 100644
index 0000000000000000000000000000000000000000..87aecb5ccdc86e2c66f8e2b3b2efb928fc316904
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/fftpack/convolve.cpython-312-x86_64-linux-gnu.so
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:5b28e0f1444e647494ed8ac89cf2d4448450922b461c6d00b81e292f4ff85fc0
+size 129784
diff --git a/.venv/lib/python3.12/site-packages/scipy/fftpack/helper.py b/.venv/lib/python3.12/site-packages/scipy/fftpack/helper.py
new file mode 100644
index 0000000000000000000000000000000000000000..fcc7000c215f8a7605a2a59b5767b27b2fcd969d
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/fftpack/helper.py
@@ -0,0 +1,19 @@
+# This file is not meant for public use and will be removed in SciPy v2.0.0.
+# Use the `scipy.fftpack` namespace for importing the functions
+# included below.
+
+from scipy._lib.deprecation import _sub_module_deprecation
+
+__all__ = [  # noqa: F822
+    'fftshift', 'ifftshift', 'fftfreq', 'rfftfreq', 'next_fast_len'
+]
+
+
+def __dir__():
+    return __all__
+
+
+def __getattr__(name):
+    return _sub_module_deprecation(sub_package="fftpack", module="helper",
+                                   private_modules=["_helper"], all=__all__,
+                                   attribute=name)
diff --git a/.venv/lib/python3.12/site-packages/scipy/fftpack/pseudo_diffs.py b/.venv/lib/python3.12/site-packages/scipy/fftpack/pseudo_diffs.py
new file mode 100644
index 0000000000000000000000000000000000000000..ecf71ad3256d48d2131c8058072da724cb001af9
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/fftpack/pseudo_diffs.py
@@ -0,0 +1,22 @@
+# This file is not meant for public use and will be removed in SciPy v2.0.0.
+# Use the `scipy.fftpack` namespace for importing the functions
+# included below.
+
+from scipy._lib.deprecation import _sub_module_deprecation
+
+__all__ = [  # noqa: F822
+    'diff',
+    'tilbert', 'itilbert', 'hilbert', 'ihilbert',
+    'cs_diff', 'cc_diff', 'sc_diff', 'ss_diff',
+    'shift', 'convolve'
+]
+
+
+def __dir__():
+    return __all__
+
+
+def __getattr__(name):
+    return _sub_module_deprecation(sub_package="fftpack", module="pseudo_diffs",
+                                   private_modules=["_pseudo_diffs"], all=__all__,
+                                   attribute=name)
diff --git a/.venv/lib/python3.12/site-packages/scipy/fftpack/realtransforms.py b/.venv/lib/python3.12/site-packages/scipy/fftpack/realtransforms.py
new file mode 100644
index 0000000000000000000000000000000000000000..9a392198fccf213bc988a79058bd69515e39f510
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/fftpack/realtransforms.py
@@ -0,0 +1,19 @@
+# This file is not meant for public use and will be removed in SciPy v2.0.0.
+# Use the `scipy.fftpack` namespace for importing the functions
+# included below.
+
+from scipy._lib.deprecation import _sub_module_deprecation
+
+__all__ = [  # noqa: F822
+    'dct', 'idct', 'dst', 'idst', 'dctn', 'idctn', 'dstn', 'idstn'
+]
+
+
+def __dir__():
+    return __all__
+
+
+def __getattr__(name):
+    return _sub_module_deprecation(sub_package="fftpack", module="realtransforms",
+                                   private_modules=["_realtransforms"], all=__all__,
+                                   attribute=name)
diff --git a/.venv/lib/python3.12/site-packages/scipy/fftpack/tests/__init__.py b/.venv/lib/python3.12/site-packages/scipy/fftpack/tests/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/.venv/lib/python3.12/site-packages/scipy/fftpack/tests/fftw_double_ref.npz b/.venv/lib/python3.12/site-packages/scipy/fftpack/tests/fftw_double_ref.npz
new file mode 100644
index 0000000000000000000000000000000000000000..e1e3d620400746177b560b9193efce03c2841e99
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/fftpack/tests/fftw_double_ref.npz
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:a60c649415b645223924d8342ccc5c097801c86901287a369e53fc9259f5ec4e
+size 162120
diff --git a/.venv/lib/python3.12/site-packages/scipy/fftpack/tests/fftw_longdouble_ref.npz b/.venv/lib/python3.12/site-packages/scipy/fftpack/tests/fftw_longdouble_ref.npz
new file mode 100644
index 0000000000000000000000000000000000000000..b1a646889c9889541e8d368c8c2d96520d183dc4
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/fftpack/tests/fftw_longdouble_ref.npz
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:a406cbd4dad04d0c59dd38f54416fb49424c82229c1a074b6a44ec0cde2000e3
+size 296072
diff --git a/.venv/lib/python3.12/site-packages/scipy/fftpack/tests/fftw_single_ref.npz b/.venv/lib/python3.12/site-packages/scipy/fftpack/tests/fftw_single_ref.npz
new file mode 100644
index 0000000000000000000000000000000000000000..a42748dba14b7ff0d2f53ce4cd5a86a4f08e5d93
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/fftpack/tests/fftw_single_ref.npz
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:276a9141318e6fc36e4ab6ff54a61b64054ef8849b660f17359e5f541b43c526
+size 95144
diff --git a/.venv/lib/python3.12/site-packages/scipy/fftpack/tests/test.npz b/.venv/lib/python3.12/site-packages/scipy/fftpack/tests/test.npz
new file mode 100644
index 0000000000000000000000000000000000000000..1e5a4e06615c6bcc58f0feff20f73e83439a937d
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/fftpack/tests/test.npz
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:36de804a22d8fdea054590ce49ddf3c859838b7d89193c56b3bcb660cbf43797
+size 11968
diff --git a/.venv/lib/python3.12/site-packages/scipy/fftpack/tests/test_basic.py b/.venv/lib/python3.12/site-packages/scipy/fftpack/tests/test_basic.py
new file mode 100644
index 0000000000000000000000000000000000000000..b7c3523b18b69f5363fa015869b2445cb4494c3a
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/fftpack/tests/test_basic.py
@@ -0,0 +1,877 @@
+# Created by Pearu Peterson, September 2002
+
+from numpy.testing import (assert_, assert_equal, assert_array_almost_equal,
+                           assert_array_almost_equal_nulp, assert_array_less)
+import pytest
+from pytest import raises as assert_raises
+from scipy.fftpack import ifft, fft, fftn, ifftn, rfft, irfft, fft2
+
+from numpy import (arange, array, asarray, zeros, dot, exp, pi,
+                   swapaxes, double, cdouble)
+import numpy as np
+import numpy.fft
+from numpy.random import rand
+
+# "large" composite numbers supported by FFTPACK
+LARGE_COMPOSITE_SIZES = [
+    2**13,
+    2**5 * 3**5,
+    2**3 * 3**3 * 5**2,
+]
+SMALL_COMPOSITE_SIZES = [
+    2,
+    2*3*5,
+    2*2*3*3,
+]
+# prime
+LARGE_PRIME_SIZES = [
+    2011
+]
+SMALL_PRIME_SIZES = [
+    29
+]
+
+
+def _assert_close_in_norm(x, y, rtol, size, rdt):
+    # helper function for testing
+    err_msg = f"size: {size}  rdt: {rdt}"
+    assert_array_less(np.linalg.norm(x - y), rtol*np.linalg.norm(x), err_msg)
+
+
+def random(size):
+    return rand(*size)
+
+
+def direct_dft(x):
+    x = asarray(x)
+    n = len(x)
+    y = zeros(n, dtype=cdouble)
+    w = -arange(n)*(2j*pi/n)
+    for i in range(n):
+        y[i] = dot(exp(i*w), x)
+    return y
+
+
+def direct_idft(x):
+    x = asarray(x)
+    n = len(x)
+    y = zeros(n, dtype=cdouble)
+    w = arange(n)*(2j*pi/n)
+    for i in range(n):
+        y[i] = dot(exp(i*w), x)/n
+    return y
+
+
+def direct_dftn(x):
+    x = asarray(x)
+    for axis in range(len(x.shape)):
+        x = fft(x, axis=axis)
+    return x
+
+
+def direct_idftn(x):
+    x = asarray(x)
+    for axis in range(len(x.shape)):
+        x = ifft(x, axis=axis)
+    return x
+
+
+def direct_rdft(x):
+    x = asarray(x)
+    n = len(x)
+    w = -arange(n)*(2j*pi/n)
+    r = zeros(n, dtype=double)
+    for i in range(n//2+1):
+        y = dot(exp(i*w), x)
+        if i:
+            r[2*i-1] = y.real
+            if 2*i < n:
+                r[2*i] = y.imag
+        else:
+            r[0] = y.real
+    return r
+
+
+def direct_irdft(x):
+    x = asarray(x)
+    n = len(x)
+    x1 = zeros(n, dtype=cdouble)
+    for i in range(n//2+1):
+        if i:
+            if 2*i < n:
+                x1[i] = x[2*i-1] + 1j*x[2*i]
+                x1[n-i] = x[2*i-1] - 1j*x[2*i]
+            else:
+                x1[i] = x[2*i-1]
+        else:
+            x1[0] = x[0]
+    return direct_idft(x1).real
+
+
+class _TestFFTBase:
+    def setup_method(self):
+        self.cdt = None
+        self.rdt = None
+        np.random.seed(1234)
+
+    def test_definition(self):
+        x = np.array([1,2,3,4+1j,1,2,3,4+2j], dtype=self.cdt)
+        y = fft(x)
+        assert_equal(y.dtype, self.cdt)
+        y1 = direct_dft(x)
+        assert_array_almost_equal(y,y1)
+        x = np.array([1,2,3,4+0j,5], dtype=self.cdt)
+        assert_array_almost_equal(fft(x),direct_dft(x))
+
+    def test_n_argument_real(self):
+        x1 = np.array([1,2,3,4], dtype=self.rdt)
+        x2 = np.array([1,2,3,4], dtype=self.rdt)
+        y = fft([x1,x2],n=4)
+        assert_equal(y.dtype, self.cdt)
+        assert_equal(y.shape,(2,4))
+        assert_array_almost_equal(y[0],direct_dft(x1))
+        assert_array_almost_equal(y[1],direct_dft(x2))
+
+    def _test_n_argument_complex(self):
+        x1 = np.array([1,2,3,4+1j], dtype=self.cdt)
+        x2 = np.array([1,2,3,4+1j], dtype=self.cdt)
+        y = fft([x1,x2],n=4)
+        assert_equal(y.dtype, self.cdt)
+        assert_equal(y.shape,(2,4))
+        assert_array_almost_equal(y[0],direct_dft(x1))
+        assert_array_almost_equal(y[1],direct_dft(x2))
+
+    def test_invalid_sizes(self):
+        assert_raises(ValueError, fft, [])
+        assert_raises(ValueError, fft, [[1,1],[2,2]], -5)
+
+
+class TestDoubleFFT(_TestFFTBase):
+    def setup_method(self):
+        self.cdt = np.complex128
+        self.rdt = np.float64
+
+
+class TestSingleFFT(_TestFFTBase):
+    def setup_method(self):
+        self.cdt = np.complex64
+        self.rdt = np.float32
+
+    reason = ("single-precision FFT implementation is partially disabled, "
+              "until accuracy issues with large prime powers are resolved")
+
+    @pytest.mark.xfail(run=False, reason=reason)
+    def test_notice(self):
+        pass
+
+
+class TestFloat16FFT:
+
+    def test_1_argument_real(self):
+        x1 = np.array([1, 2, 3, 4], dtype=np.float16)
+        y = fft(x1, n=4)
+        assert_equal(y.dtype, np.complex64)
+        assert_equal(y.shape, (4, ))
+        assert_array_almost_equal(y, direct_dft(x1.astype(np.float32)))
+
+    def test_n_argument_real(self):
+        x1 = np.array([1, 2, 3, 4], dtype=np.float16)
+        x2 = np.array([1, 2, 3, 4], dtype=np.float16)
+        y = fft([x1, x2], n=4)
+        assert_equal(y.dtype, np.complex64)
+        assert_equal(y.shape, (2, 4))
+        assert_array_almost_equal(y[0], direct_dft(x1.astype(np.float32)))
+        assert_array_almost_equal(y[1], direct_dft(x2.astype(np.float32)))
+
+
+class _TestIFFTBase:
+    def setup_method(self):
+        np.random.seed(1234)
+
+    def test_definition(self):
+        x = np.array([1,2,3,4+1j,1,2,3,4+2j], self.cdt)
+        y = ifft(x)
+        y1 = direct_idft(x)
+        assert_equal(y.dtype, self.cdt)
+        assert_array_almost_equal(y,y1)
+
+        x = np.array([1,2,3,4+0j,5], self.cdt)
+        assert_array_almost_equal(ifft(x),direct_idft(x))
+
+    def test_definition_real(self):
+        x = np.array([1,2,3,4,1,2,3,4], self.rdt)
+        y = ifft(x)
+        assert_equal(y.dtype, self.cdt)
+        y1 = direct_idft(x)
+        assert_array_almost_equal(y,y1)
+
+        x = np.array([1,2,3,4,5], dtype=self.rdt)
+        assert_equal(y.dtype, self.cdt)
+        assert_array_almost_equal(ifft(x),direct_idft(x))
+
+    def test_random_complex(self):
+        for size in [1,51,111,100,200,64,128,256,1024]:
+            x = random([size]).astype(self.cdt)
+            x = random([size]).astype(self.cdt) + 1j*x
+            y1 = ifft(fft(x))
+            y2 = fft(ifft(x))
+            assert_equal(y1.dtype, self.cdt)
+            assert_equal(y2.dtype, self.cdt)
+            assert_array_almost_equal(y1, x)
+            assert_array_almost_equal(y2, x)
+
+    def test_random_real(self):
+        for size in [1,51,111,100,200,64,128,256,1024]:
+            x = random([size]).astype(self.rdt)
+            y1 = ifft(fft(x))
+            y2 = fft(ifft(x))
+            assert_equal(y1.dtype, self.cdt)
+            assert_equal(y2.dtype, self.cdt)
+            assert_array_almost_equal(y1, x)
+            assert_array_almost_equal(y2, x)
+
+    def test_size_accuracy(self):
+        # Sanity check for the accuracy for prime and non-prime sized inputs
+        if self.rdt == np.float32:
+            rtol = 1e-5
+        elif self.rdt == np.float64:
+            rtol = 1e-10
+
+        for size in LARGE_COMPOSITE_SIZES + LARGE_PRIME_SIZES:
+            np.random.seed(1234)
+            x = np.random.rand(size).astype(self.rdt)
+            y = ifft(fft(x))
+            _assert_close_in_norm(x, y, rtol, size, self.rdt)
+            y = fft(ifft(x))
+            _assert_close_in_norm(x, y, rtol, size, self.rdt)
+
+            x = (x + 1j*np.random.rand(size)).astype(self.cdt)
+            y = ifft(fft(x))
+            _assert_close_in_norm(x, y, rtol, size, self.rdt)
+            y = fft(ifft(x))
+            _assert_close_in_norm(x, y, rtol, size, self.rdt)
+
+    def test_invalid_sizes(self):
+        assert_raises(ValueError, ifft, [])
+        assert_raises(ValueError, ifft, [[1,1],[2,2]], -5)
+
+
+class TestDoubleIFFT(_TestIFFTBase):
+    def setup_method(self):
+        self.cdt = np.complex128
+        self.rdt = np.float64
+
+
+class TestSingleIFFT(_TestIFFTBase):
+    def setup_method(self):
+        self.cdt = np.complex64
+        self.rdt = np.float32
+
+
+class _TestRFFTBase:
+    def setup_method(self):
+        np.random.seed(1234)
+
+    def test_definition(self):
+        for t in [[1, 2, 3, 4, 1, 2, 3, 4], [1, 2, 3, 4, 1, 2, 3, 4, 5]]:
+            x = np.array(t, dtype=self.rdt)
+            y = rfft(x)
+            y1 = direct_rdft(x)
+            assert_array_almost_equal(y,y1)
+            assert_equal(y.dtype, self.rdt)
+
+    def test_invalid_sizes(self):
+        assert_raises(ValueError, rfft, [])
+        assert_raises(ValueError, rfft, [[1,1],[2,2]], -5)
+
+    # See gh-5790
+    class MockSeries:
+        def __init__(self, data):
+            self.data = np.asarray(data)
+
+        def __getattr__(self, item):
+            try:
+                return getattr(self.data, item)
+            except AttributeError as e:
+                raise AttributeError("'MockSeries' object "
+                                      f"has no attribute '{item}'") from e
+
+    def test_non_ndarray_with_dtype(self):
+        x = np.array([1., 2., 3., 4., 5.])
+        xs = _TestRFFTBase.MockSeries(x)
+
+        expected = [1, 2, 3, 4, 5]
+        rfft(xs)
+
+        # Data should not have been overwritten
+        assert_equal(x, expected)
+        assert_equal(xs.data, expected)
+
+    def test_complex_input(self):
+        assert_raises(TypeError, rfft, np.arange(4, dtype=np.complex64))
+
+
+class TestRFFTDouble(_TestRFFTBase):
+    def setup_method(self):
+        self.cdt = np.complex128
+        self.rdt = np.float64
+
+
+class TestRFFTSingle(_TestRFFTBase):
+    def setup_method(self):
+        self.cdt = np.complex64
+        self.rdt = np.float32
+
+
+class _TestIRFFTBase:
+    def setup_method(self):
+        np.random.seed(1234)
+
+    def test_definition(self):
+        x1 = [1,2,3,4,1,2,3,4]
+        x1_1 = [1,2+3j,4+1j,2+3j,4,2-3j,4-1j,2-3j]
+        x2 = [1,2,3,4,1,2,3,4,5]
+        x2_1 = [1,2+3j,4+1j,2+3j,4+5j,4-5j,2-3j,4-1j,2-3j]
+
+        def _test(x, xr):
+            y = irfft(np.array(x, dtype=self.rdt))
+            y1 = direct_irdft(x)
+            assert_equal(y.dtype, self.rdt)
+            assert_array_almost_equal(y,y1, decimal=self.ndec)
+            assert_array_almost_equal(y,ifft(xr), decimal=self.ndec)
+
+        _test(x1, x1_1)
+        _test(x2, x2_1)
+
+    def test_random_real(self):
+        for size in [1,51,111,100,200,64,128,256,1024]:
+            x = random([size]).astype(self.rdt)
+            y1 = irfft(rfft(x))
+            y2 = rfft(irfft(x))
+            assert_equal(y1.dtype, self.rdt)
+            assert_equal(y2.dtype, self.rdt)
+            assert_array_almost_equal(y1, x, decimal=self.ndec, err_msg=f"size={size}")
+            assert_array_almost_equal(y2, x, decimal=self.ndec, err_msg=f"size={size}")
+
+    def test_size_accuracy(self):
+        # Sanity check for the accuracy for prime and non-prime sized inputs
+        if self.rdt == np.float32:
+            rtol = 1e-5
+        elif self.rdt == np.float64:
+            rtol = 1e-10
+
+        for size in LARGE_COMPOSITE_SIZES + LARGE_PRIME_SIZES:
+            np.random.seed(1234)
+            x = np.random.rand(size).astype(self.rdt)
+            y = irfft(rfft(x))
+            _assert_close_in_norm(x, y, rtol, size, self.rdt)
+            y = rfft(irfft(x))
+            _assert_close_in_norm(x, y, rtol, size, self.rdt)
+
+    def test_invalid_sizes(self):
+        assert_raises(ValueError, irfft, [])
+        assert_raises(ValueError, irfft, [[1,1],[2,2]], -5)
+
+    def test_complex_input(self):
+        assert_raises(TypeError, irfft, np.arange(4, dtype=np.complex64))
+
+
+# self.ndec is bogus; we should have a assert_array_approx_equal for number of
+# significant digits
+
+class TestIRFFTDouble(_TestIRFFTBase):
+    def setup_method(self):
+        self.cdt = np.complex128
+        self.rdt = np.float64
+        self.ndec = 14
+
+
+class TestIRFFTSingle(_TestIRFFTBase):
+    def setup_method(self):
+        self.cdt = np.complex64
+        self.rdt = np.float32
+        self.ndec = 5
+
+
+class Testfft2:
+    def setup_method(self):
+        np.random.seed(1234)
+
+    def test_regression_244(self):
+        """FFT returns wrong result with axes parameter."""
+        # fftn (and hence fft2) used to break when both axes and shape were
+        # used
+        x = numpy.ones((4, 4, 2))
+        y = fft2(x, shape=(8, 8), axes=(-3, -2))
+        y_r = numpy.fft.fftn(x, s=(8, 8), axes=(-3, -2))
+        assert_array_almost_equal(y, y_r)
+
+    def test_invalid_sizes(self):
+        assert_raises(ValueError, fft2, [[]])
+        assert_raises(ValueError, fft2, [[1, 1], [2, 2]], (4, -3))
+
+
+class TestFftnSingle:
+    def setup_method(self):
+        np.random.seed(1234)
+
+    def test_definition(self):
+        x = [[1, 2, 3],
+             [4, 5, 6],
+             [7, 8, 9]]
+        y = fftn(np.array(x, np.float32))
+        assert_(y.dtype == np.complex64,
+                msg="double precision output with single precision")
+
+        y_r = np.array(fftn(x), np.complex64)
+        assert_array_almost_equal_nulp(y, y_r)
+
+    @pytest.mark.parametrize('size', SMALL_COMPOSITE_SIZES + SMALL_PRIME_SIZES)
+    def test_size_accuracy_small(self, size):
+        rng = np.random.default_rng(1234)
+        x = rng.random((size, size)) + 1j*rng.random((size, size))
+        y1 = fftn(x.real.astype(np.float32))
+        y2 = fftn(x.real.astype(np.float64)).astype(np.complex64)
+
+        assert_equal(y1.dtype, np.complex64)
+        assert_array_almost_equal_nulp(y1, y2, 2000)
+
+    @pytest.mark.parametrize('size', LARGE_COMPOSITE_SIZES + LARGE_PRIME_SIZES)
+    def test_size_accuracy_large(self, size):
+        rand = np.random.default_rng(1234)
+        x = rand.random((size, 3)) + 1j*rand.random((size, 3))
+        y1 = fftn(x.real.astype(np.float32))
+        y2 = fftn(x.real.astype(np.float64)).astype(np.complex64)
+
+        assert_equal(y1.dtype, np.complex64)
+        assert_array_almost_equal_nulp(y1, y2, 2000)
+
+    def test_definition_float16(self):
+        x = [[1, 2, 3],
+             [4, 5, 6],
+             [7, 8, 9]]
+        y = fftn(np.array(x, np.float16))
+        assert_equal(y.dtype, np.complex64)
+        y_r = np.array(fftn(x), np.complex64)
+        assert_array_almost_equal_nulp(y, y_r)
+
+    @pytest.mark.parametrize('size', SMALL_COMPOSITE_SIZES + SMALL_PRIME_SIZES)
+    def test_float16_input_small(self, size):
+        rng = np.random.default_rng(1234)
+        x = rng.random((size, size)) + 1j * rng.random((size, size))
+        y1 = fftn(x.real.astype(np.float16))
+        y2 = fftn(x.real.astype(np.float64)).astype(np.complex64)
+
+        assert_equal(y1.dtype, np.complex64)
+        assert_array_almost_equal_nulp(y1, y2, 5e5)
+
+    @pytest.mark.parametrize('size', LARGE_COMPOSITE_SIZES + LARGE_PRIME_SIZES)
+    def test_float16_input_large(self, size):
+        rng = np.random.default_rng(1234)
+        x = rng.random((size, 3)) + 1j*rng.random((size, 3))
+        y1 = fftn(x.real.astype(np.float16))
+        y2 = fftn(x.real.astype(np.float64)).astype(np.complex64)
+
+        assert_equal(y1.dtype, np.complex64)
+        assert_array_almost_equal_nulp(y1, y2, 2e6)
+
+
+class TestFftn:
+    def setup_method(self):
+        np.random.seed(1234)
+
+    def test_definition(self):
+        x = [[1, 2, 3],
+             [4, 5, 6],
+             [7, 8, 9]]
+        y = fftn(x)
+        assert_array_almost_equal(y, direct_dftn(x))
+
+        x = random((20, 26))
+        assert_array_almost_equal(fftn(x), direct_dftn(x))
+
+        x = random((5, 4, 3, 20))
+        assert_array_almost_equal(fftn(x), direct_dftn(x))
+
+    def test_axes_argument(self):
+        # plane == ji_plane, x== kji_space
+        plane1 = [[1, 2, 3],
+                  [4, 5, 6],
+                  [7, 8, 9]]
+        plane2 = [[10, 11, 12],
+                  [13, 14, 15],
+                  [16, 17, 18]]
+        plane3 = [[19, 20, 21],
+                  [22, 23, 24],
+                  [25, 26, 27]]
+        ki_plane1 = [[1, 2, 3],
+                     [10, 11, 12],
+                     [19, 20, 21]]
+        ki_plane2 = [[4, 5, 6],
+                     [13, 14, 15],
+                     [22, 23, 24]]
+        ki_plane3 = [[7, 8, 9],
+                     [16, 17, 18],
+                     [25, 26, 27]]
+        jk_plane1 = [[1, 10, 19],
+                     [4, 13, 22],
+                     [7, 16, 25]]
+        jk_plane2 = [[2, 11, 20],
+                     [5, 14, 23],
+                     [8, 17, 26]]
+        jk_plane3 = [[3, 12, 21],
+                     [6, 15, 24],
+                     [9, 18, 27]]
+        kj_plane1 = [[1, 4, 7],
+                     [10, 13, 16], [19, 22, 25]]
+        kj_plane2 = [[2, 5, 8],
+                     [11, 14, 17], [20, 23, 26]]
+        kj_plane3 = [[3, 6, 9],
+                     [12, 15, 18], [21, 24, 27]]
+        ij_plane1 = [[1, 4, 7],
+                     [2, 5, 8],
+                     [3, 6, 9]]
+        ij_plane2 = [[10, 13, 16],
+                     [11, 14, 17],
+                     [12, 15, 18]]
+        ij_plane3 = [[19, 22, 25],
+                     [20, 23, 26],
+                     [21, 24, 27]]
+        ik_plane1 = [[1, 10, 19],
+                     [2, 11, 20],
+                     [3, 12, 21]]
+        ik_plane2 = [[4, 13, 22],
+                     [5, 14, 23],
+                     [6, 15, 24]]
+        ik_plane3 = [[7, 16, 25],
+                     [8, 17, 26],
+                     [9, 18, 27]]
+        ijk_space = [jk_plane1, jk_plane2, jk_plane3]
+        ikj_space = [kj_plane1, kj_plane2, kj_plane3]
+        jik_space = [ik_plane1, ik_plane2, ik_plane3]
+        jki_space = [ki_plane1, ki_plane2, ki_plane3]
+        kij_space = [ij_plane1, ij_plane2, ij_plane3]
+        x = array([plane1, plane2, plane3])
+
+        assert_array_almost_equal(fftn(x),
+                                  fftn(x, axes=(-3, -2, -1)))  # kji_space
+        assert_array_almost_equal(fftn(x), fftn(x, axes=(0, 1, 2)))
+        assert_array_almost_equal(fftn(x, axes=(0, 2)), fftn(x, axes=(0, -1)))
+        y = fftn(x, axes=(2, 1, 0))  # ijk_space
+        assert_array_almost_equal(swapaxes(y, -1, -3), fftn(ijk_space))
+        y = fftn(x, axes=(2, 0, 1))  # ikj_space
+        assert_array_almost_equal(swapaxes(swapaxes(y, -1, -3), -1, -2),
+                                  fftn(ikj_space))
+        y = fftn(x, axes=(1, 2, 0))  # jik_space
+        assert_array_almost_equal(swapaxes(swapaxes(y, -1, -3), -3, -2),
+                                  fftn(jik_space))
+        y = fftn(x, axes=(1, 0, 2))  # jki_space
+        assert_array_almost_equal(swapaxes(y, -2, -3), fftn(jki_space))
+        y = fftn(x, axes=(0, 2, 1))  # kij_space
+        assert_array_almost_equal(swapaxes(y, -2, -1), fftn(kij_space))
+
+        y = fftn(x, axes=(-2, -1))  # ji_plane
+        assert_array_almost_equal(fftn(plane1), y[0])
+        assert_array_almost_equal(fftn(plane2), y[1])
+        assert_array_almost_equal(fftn(plane3), y[2])
+
+        y = fftn(x, axes=(1, 2))  # ji_plane
+        assert_array_almost_equal(fftn(plane1), y[0])
+        assert_array_almost_equal(fftn(plane2), y[1])
+        assert_array_almost_equal(fftn(plane3), y[2])
+
+        y = fftn(x, axes=(-3, -2))  # kj_plane
+        assert_array_almost_equal(fftn(x[:, :, 0]), y[:, :, 0])
+        assert_array_almost_equal(fftn(x[:, :, 1]), y[:, :, 1])
+        assert_array_almost_equal(fftn(x[:, :, 2]), y[:, :, 2])
+
+        y = fftn(x, axes=(-3, -1))  # ki_plane
+        assert_array_almost_equal(fftn(x[:, 0, :]), y[:, 0, :])
+        assert_array_almost_equal(fftn(x[:, 1, :]), y[:, 1, :])
+        assert_array_almost_equal(fftn(x[:, 2, :]), y[:, 2, :])
+
+        y = fftn(x, axes=(-1, -2))  # ij_plane
+        assert_array_almost_equal(fftn(ij_plane1), swapaxes(y[0], -2, -1))
+        assert_array_almost_equal(fftn(ij_plane2), swapaxes(y[1], -2, -1))
+        assert_array_almost_equal(fftn(ij_plane3), swapaxes(y[2], -2, -1))
+
+        y = fftn(x, axes=(-1, -3))  # ik_plane
+        assert_array_almost_equal(fftn(ik_plane1),
+                                  swapaxes(y[:, 0, :], -1, -2))
+        assert_array_almost_equal(fftn(ik_plane2),
+                                  swapaxes(y[:, 1, :], -1, -2))
+        assert_array_almost_equal(fftn(ik_plane3),
+                                  swapaxes(y[:, 2, :], -1, -2))
+
+        y = fftn(x, axes=(-2, -3))  # jk_plane
+        assert_array_almost_equal(fftn(jk_plane1),
+                                  swapaxes(y[:, :, 0], -1, -2))
+        assert_array_almost_equal(fftn(jk_plane2),
+                                  swapaxes(y[:, :, 1], -1, -2))
+        assert_array_almost_equal(fftn(jk_plane3),
+                                  swapaxes(y[:, :, 2], -1, -2))
+
+        y = fftn(x, axes=(-1,))  # i_line
+        for i in range(3):
+            for j in range(3):
+                assert_array_almost_equal(fft(x[i, j, :]), y[i, j, :])
+        y = fftn(x, axes=(-2,))  # j_line
+        for i in range(3):
+            for j in range(3):
+                assert_array_almost_equal(fft(x[i, :, j]), y[i, :, j])
+        y = fftn(x, axes=(0,))  # k_line
+        for i in range(3):
+            for j in range(3):
+                assert_array_almost_equal(fft(x[:, i, j]), y[:, i, j])
+
+        y = fftn(x, axes=())  # point
+        assert_array_almost_equal(y, x)
+
+    def test_shape_argument(self):
+        small_x = [[1, 2, 3],
+                   [4, 5, 6]]
+        large_x1 = [[1, 2, 3, 0],
+                    [4, 5, 6, 0],
+                    [0, 0, 0, 0],
+                    [0, 0, 0, 0]]
+
+        y = fftn(small_x, shape=(4, 4))
+        assert_array_almost_equal(y, fftn(large_x1))
+
+        y = fftn(small_x, shape=(3, 4))
+        assert_array_almost_equal(y, fftn(large_x1[:-1]))
+
+    def test_shape_axes_argument(self):
+        small_x = [[1, 2, 3],
+                   [4, 5, 6],
+                   [7, 8, 9]]
+        large_x1 = array([[1, 2, 3, 0],
+                          [4, 5, 6, 0],
+                          [7, 8, 9, 0],
+                          [0, 0, 0, 0]])
+        y = fftn(small_x, shape=(4, 4), axes=(-2, -1))
+        assert_array_almost_equal(y, fftn(large_x1))
+        y = fftn(small_x, shape=(4, 4), axes=(-1, -2))
+
+        assert_array_almost_equal(y, swapaxes(
+            fftn(swapaxes(large_x1, -1, -2)), -1, -2))
+
+    def test_shape_axes_argument2(self):
+        # Change shape of the last axis
+        x = numpy.random.random((10, 5, 3, 7))
+        y = fftn(x, axes=(-1,), shape=(8,))
+        assert_array_almost_equal(y, fft(x, axis=-1, n=8))
+
+        # Change shape of an arbitrary axis which is not the last one
+        x = numpy.random.random((10, 5, 3, 7))
+        y = fftn(x, axes=(-2,), shape=(8,))
+        assert_array_almost_equal(y, fft(x, axis=-2, n=8))
+
+        # Change shape of axes: cf #244, where shape and axes were mixed up
+        x = numpy.random.random((4, 4, 2))
+        y = fftn(x, axes=(-3, -2), shape=(8, 8))
+        assert_array_almost_equal(y,
+                                  numpy.fft.fftn(x, axes=(-3, -2), s=(8, 8)))
+
+    def test_shape_argument_more(self):
+        x = zeros((4, 4, 2))
+        with assert_raises(ValueError,
+                           match="when given, axes and shape arguments"
+                           " have to be of the same length"):
+            fftn(x, shape=(8, 8, 2, 1))
+
+    def test_invalid_sizes(self):
+        with assert_raises(ValueError,
+                           match="invalid number of data points"
+                           r" \(\[1, 0\]\) specified"):
+            fftn([[]])
+
+        with assert_raises(ValueError,
+                           match="invalid number of data points"
+                           r" \(\[4, -3\]\) specified"):
+            fftn([[1, 1], [2, 2]], (4, -3))
+
+
+class TestIfftn:
+    dtype = None
+    cdtype = None
+
+    def setup_method(self):
+        np.random.seed(1234)
+
+    @pytest.mark.parametrize('dtype,cdtype,maxnlp',
+                             [(np.float64, np.complex128, 2000),
+                              (np.float32, np.complex64, 3500)])
+    def test_definition(self, dtype, cdtype, maxnlp):
+        rng = np.random.default_rng(1234)
+        x = np.array([[1, 2, 3],
+                      [4, 5, 6],
+                      [7, 8, 9]], dtype=dtype)
+        y = ifftn(x)
+        assert_equal(y.dtype, cdtype)
+        assert_array_almost_equal_nulp(y, direct_idftn(x), maxnlp)
+
+        x = rng.random((20, 26))
+        assert_array_almost_equal_nulp(ifftn(x), direct_idftn(x), maxnlp)
+
+        x = rng.random((5, 4, 3, 20))
+        assert_array_almost_equal_nulp(ifftn(x), direct_idftn(x), maxnlp)
+
+    @pytest.mark.parametrize('maxnlp', [2000, 3500])
+    @pytest.mark.parametrize('size', [1, 2, 51, 32, 64, 92])
+    def test_random_complex(self, maxnlp, size):
+        rng = np.random.default_rng(1234)
+        x = rng.random([size, size]) + 1j * rng.random([size, size])
+        assert_array_almost_equal_nulp(ifftn(fftn(x)), x, maxnlp)
+        assert_array_almost_equal_nulp(fftn(ifftn(x)), x, maxnlp)
+
+    def test_invalid_sizes(self):
+        with assert_raises(ValueError,
+                           match="invalid number of data points"
+                           r" \(\[1, 0\]\) specified"):
+            ifftn([[]])
+
+        with assert_raises(ValueError,
+                           match="invalid number of data points"
+                           r" \(\[4, -3\]\) specified"):
+            ifftn([[1, 1], [2, 2]], (4, -3))
+
+
+class FakeArray:
+    def __init__(self, data):
+        self._data = data
+        self.__array_interface__ = data.__array_interface__
+
+
+class FakeArray2:
+    def __init__(self, data):
+        self._data = data
+
+    def __array__(self, dtype=None, copy=None):
+        return self._data
+
+
+class TestOverwrite:
+    """Check input overwrite behavior of the FFT functions."""
+
+    real_dtypes = (np.float32, np.float64)
+    dtypes = real_dtypes + (np.complex64, np.complex128)
+    fftsizes = [8, 16, 32]
+
+    def _check(self, x, routine, fftsize, axis, overwrite_x):
+        x2 = x.copy()
+        for fake in [lambda x: x, FakeArray, FakeArray2]:
+            routine(fake(x2), fftsize, axis, overwrite_x=overwrite_x)
+
+            sig = (f"{routine.__name__}({x.dtype}{x.shape!r}, {fftsize!r}, "
+                   f"axis={axis!r}, overwrite_x={overwrite_x!r})")
+            if not overwrite_x:
+                assert_equal(x2, x, err_msg=f"spurious overwrite in {sig}")
+
+    def _check_1d(self, routine, dtype, shape, axis, overwritable_dtypes,
+                  fftsize, overwrite_x):
+        np.random.seed(1234)
+        if np.issubdtype(dtype, np.complexfloating):
+            data = np.random.randn(*shape) + 1j*np.random.randn(*shape)
+        else:
+            data = np.random.randn(*shape)
+        data = data.astype(dtype)
+
+        self._check(data, routine, fftsize, axis,
+                    overwrite_x=overwrite_x)
+
+    @pytest.mark.parametrize('dtype', dtypes)
+    @pytest.mark.parametrize('fftsize', fftsizes)
+    @pytest.mark.parametrize('overwrite_x', [True, False])
+    @pytest.mark.parametrize('shape,axes', [((16,), -1),
+                                            ((16, 2), 0),
+                                            ((2, 16), 1)])
+    def test_fft_ifft(self, dtype, fftsize, overwrite_x, shape, axes):
+        overwritable = (np.complex128, np.complex64)
+        self._check_1d(fft, dtype, shape, axes, overwritable,
+                       fftsize, overwrite_x)
+        self._check_1d(ifft, dtype, shape, axes, overwritable,
+                       fftsize, overwrite_x)
+
+    @pytest.mark.parametrize('dtype', real_dtypes)
+    @pytest.mark.parametrize('fftsize', fftsizes)
+    @pytest.mark.parametrize('overwrite_x', [True, False])
+    @pytest.mark.parametrize('shape,axes', [((16,), -1),
+                                            ((16, 2), 0),
+                                            ((2, 16), 1)])
+    def test_rfft_irfft(self, dtype, fftsize, overwrite_x, shape, axes):
+        overwritable = self.real_dtypes
+        self._check_1d(irfft, dtype, shape, axes, overwritable,
+                       fftsize, overwrite_x)
+        self._check_1d(rfft, dtype, shape, axes, overwritable,
+                       fftsize, overwrite_x)
+
+    def _check_nd_one(self, routine, dtype, shape, axes, overwritable_dtypes,
+                      overwrite_x):
+        np.random.seed(1234)
+        if np.issubdtype(dtype, np.complexfloating):
+            data = np.random.randn(*shape) + 1j*np.random.randn(*shape)
+        else:
+            data = np.random.randn(*shape)
+        data = data.astype(dtype)
+
+        def fftshape_iter(shp):
+            if len(shp) <= 0:
+                yield ()
+            else:
+                for j in (shp[0]//2, shp[0], shp[0]*2):
+                    for rest in fftshape_iter(shp[1:]):
+                        yield (j,) + rest
+
+        if axes is None:
+            part_shape = shape
+        else:
+            part_shape = tuple(np.take(shape, axes))
+
+        for fftshape in fftshape_iter(part_shape):
+            self._check(data, routine, fftshape, axes,
+                        overwrite_x=overwrite_x)
+            if data.ndim > 1:
+                self._check(data.T, routine, fftshape, axes,
+                            overwrite_x=overwrite_x)
+
+    @pytest.mark.parametrize('dtype', dtypes)
+    @pytest.mark.parametrize('overwrite_x', [True, False])
+    @pytest.mark.parametrize('shape,axes', [((16,), None),
+                                            ((16,), (0,)),
+                                            ((16, 2), (0,)),
+                                            ((2, 16), (1,)),
+                                            ((8, 16), None),
+                                            ((8, 16), (0, 1)),
+                                            ((8, 16, 2), (0, 1)),
+                                            ((8, 16, 2), (1, 2)),
+                                            ((8, 16, 2), (0,)),
+                                            ((8, 16, 2), (1,)),
+                                            ((8, 16, 2), (2,)),
+                                            ((8, 16, 2), None),
+                                            ((8, 16, 2), (0, 1, 2))])
+    def test_fftn_ifftn(self, dtype, overwrite_x, shape, axes):
+        overwritable = (np.complex128, np.complex64)
+        self._check_nd_one(fftn, dtype, shape, axes, overwritable,
+                           overwrite_x)
+        self._check_nd_one(ifftn, dtype, shape, axes, overwritable,
+                           overwrite_x)
+
+
+@pytest.mark.parametrize('func', [fftn, ifftn, fft2])
+def test_shape_axes_ndarray(func):
+    # Test fftn and ifftn work with NumPy arrays for shape and axes arguments
+    # Regression test for gh-13342
+    a = np.random.rand(10, 10)
+
+    expect = func(a, shape=(5, 5))
+    actual = func(a, shape=np.array([5, 5]))
+    assert_equal(expect, actual)
+
+    expect = func(a, axes=(-1,))
+    actual = func(a, axes=np.array([-1,]))
+    assert_equal(expect, actual)
+
+    expect = func(a, shape=(4, 7), axes=(1, 0))
+    actual = func(a, shape=np.array([4, 7]), axes=np.array([1, 0]))
+    assert_equal(expect, actual)
diff --git a/.venv/lib/python3.12/site-packages/scipy/fftpack/tests/test_helper.py b/.venv/lib/python3.12/site-packages/scipy/fftpack/tests/test_helper.py
new file mode 100644
index 0000000000000000000000000000000000000000..5e7be04f3c0291502b50b101db82d299aadc7772
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/fftpack/tests/test_helper.py
@@ -0,0 +1,54 @@
+# Created by Pearu Peterson, September 2002
+
+__usage__ = """
+Build fftpack:
+  python setup_fftpack.py build
+Run tests if scipy is installed:
+  python -c 'import scipy;scipy.fftpack.test()'
+Run tests if fftpack is not installed:
+  python tests/test_helper.py []
+"""
+
+from numpy.testing import assert_array_almost_equal
+from scipy.fftpack import fftshift, ifftshift, fftfreq, rfftfreq
+
+from numpy import pi, random
+
+class TestFFTShift:
+
+    def test_definition(self):
+        x = [0,1,2,3,4,-4,-3,-2,-1]
+        y = [-4,-3,-2,-1,0,1,2,3,4]
+        assert_array_almost_equal(fftshift(x),y)
+        assert_array_almost_equal(ifftshift(y),x)
+        x = [0,1,2,3,4,-5,-4,-3,-2,-1]
+        y = [-5,-4,-3,-2,-1,0,1,2,3,4]
+        assert_array_almost_equal(fftshift(x),y)
+        assert_array_almost_equal(ifftshift(y),x)
+
+    def test_inverse(self):
+        for n in [1,4,9,100,211]:
+            x = random.random((n,))
+            assert_array_almost_equal(ifftshift(fftshift(x)),x)
+
+
+class TestFFTFreq:
+
+    def test_definition(self):
+        x = [0,1,2,3,4,-4,-3,-2,-1]
+        assert_array_almost_equal(9*fftfreq(9),x)
+        assert_array_almost_equal(9*pi*fftfreq(9,pi),x)
+        x = [0,1,2,3,4,-5,-4,-3,-2,-1]
+        assert_array_almost_equal(10*fftfreq(10),x)
+        assert_array_almost_equal(10*pi*fftfreq(10,pi),x)
+
+
+class TestRFFTFreq:
+
+    def test_definition(self):
+        x = [0,1,1,2,2,3,3,4,4]
+        assert_array_almost_equal(9*rfftfreq(9),x)
+        assert_array_almost_equal(9*pi*rfftfreq(9,pi),x)
+        x = [0,1,1,2,2,3,3,4,4,5]
+        assert_array_almost_equal(10*rfftfreq(10),x)
+        assert_array_almost_equal(10*pi*rfftfreq(10,pi),x)
diff --git a/.venv/lib/python3.12/site-packages/scipy/fftpack/tests/test_import.py b/.venv/lib/python3.12/site-packages/scipy/fftpack/tests/test_import.py
new file mode 100644
index 0000000000000000000000000000000000000000..e71aec9bd07cd4ef486b7e74b9589b6f1634d629
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/fftpack/tests/test_import.py
@@ -0,0 +1,33 @@
+"""Test possibility of patching fftpack with pyfftw.
+
+No module source outside of scipy.fftpack should contain an import of
+the form `from scipy.fftpack import ...`, so that a simple replacement
+of scipy.fftpack by the corresponding fftw interface completely swaps
+the two FFT implementations.
+
+Because this simply inspects source files, we only need to run the test
+on one version of Python.
+"""
+
+
+from pathlib import Path
+import re
+import tokenize
+import pytest
+from numpy.testing import assert_
+import scipy
+
+class TestFFTPackImport:
+    @pytest.mark.slow
+    def test_fftpack_import(self):
+        base = Path(scipy.__file__).parent
+        regexp = r"\s*from.+\.fftpack import .*\n"
+        for path in base.rglob("*.py"):
+            if base / "fftpack" in path.parents:
+                continue
+            # use tokenize to auto-detect encoding on systems where no
+            # default encoding is defined (e.g., LANG='C')
+            with tokenize.open(str(path)) as file:
+                assert_(all(not re.fullmatch(regexp, line)
+                            for line in file),
+                        f"{path} contains an import from fftpack")
diff --git a/.venv/lib/python3.12/site-packages/scipy/fftpack/tests/test_pseudo_diffs.py b/.venv/lib/python3.12/site-packages/scipy/fftpack/tests/test_pseudo_diffs.py
new file mode 100644
index 0000000000000000000000000000000000000000..0a92729626a280c12aa3197e99b0d58ce00812d9
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/fftpack/tests/test_pseudo_diffs.py
@@ -0,0 +1,388 @@
+# Created by Pearu Peterson, September 2002
+
+__usage__ = """
+Build fftpack:
+  python setup_fftpack.py build
+Run tests if scipy is installed:
+  python -c 'import scipy;scipy.fftpack.test()'
+Run tests if fftpack is not installed:
+  python tests/test_pseudo_diffs.py []
+"""
+
+from numpy.testing import (assert_equal, assert_almost_equal,
+                           assert_array_almost_equal)
+from scipy.fftpack import (diff, fft, ifft, tilbert, itilbert, hilbert,
+                           ihilbert, shift, fftfreq, cs_diff, sc_diff,
+                           ss_diff, cc_diff)
+
+import numpy as np
+from numpy import arange, sin, cos, pi, exp, tanh, sum, sign
+from numpy.random import random
+
+
+def direct_diff(x,k=1,period=None):
+    fx = fft(x)
+    n = len(fx)
+    if period is None:
+        period = 2*pi
+    w = fftfreq(n)*2j*pi/period*n
+    if k < 0:
+        w = 1 / w**k
+        w[0] = 0.0
+    else:
+        w = w**k
+    if n > 2000:
+        w[250:n-250] = 0.0
+    return ifft(w*fx).real
+
+
+def direct_tilbert(x,h=1,period=None):
+    fx = fft(x)
+    n = len(fx)
+    if period is None:
+        period = 2*pi
+    w = fftfreq(n)*h*2*pi/period*n
+    w[0] = 1
+    w = 1j/tanh(w)
+    w[0] = 0j
+    return ifft(w*fx)
+
+
+def direct_itilbert(x,h=1,period=None):
+    fx = fft(x)
+    n = len(fx)
+    if period is None:
+        period = 2*pi
+    w = fftfreq(n)*h*2*pi/period*n
+    w = -1j*tanh(w)
+    return ifft(w*fx)
+
+
+def direct_hilbert(x):
+    fx = fft(x)
+    n = len(fx)
+    w = fftfreq(n)*n
+    w = 1j*sign(w)
+    return ifft(w*fx)
+
+
+def direct_ihilbert(x):
+    return -direct_hilbert(x)
+
+
+def direct_shift(x,a,period=None):
+    n = len(x)
+    if period is None:
+        k = fftfreq(n)*1j*n
+    else:
+        k = fftfreq(n)*2j*pi/period*n
+    return ifft(fft(x)*exp(k*a)).real
+
+
+class TestDiff:
+
+    def test_definition(self):
+        for n in [16,17,64,127,32]:
+            x = arange(n)*2*pi/n
+            assert_array_almost_equal(diff(sin(x)),direct_diff(sin(x)))
+            assert_array_almost_equal(diff(sin(x),2),direct_diff(sin(x),2))
+            assert_array_almost_equal(diff(sin(x),3),direct_diff(sin(x),3))
+            assert_array_almost_equal(diff(sin(x),4),direct_diff(sin(x),4))
+            assert_array_almost_equal(diff(sin(x),5),direct_diff(sin(x),5))
+            assert_array_almost_equal(diff(sin(2*x),3),direct_diff(sin(2*x),3))
+            assert_array_almost_equal(diff(sin(2*x),4),direct_diff(sin(2*x),4))
+            assert_array_almost_equal(diff(cos(x)),direct_diff(cos(x)))
+            assert_array_almost_equal(diff(cos(x),2),direct_diff(cos(x),2))
+            assert_array_almost_equal(diff(cos(x),3),direct_diff(cos(x),3))
+            assert_array_almost_equal(diff(cos(x),4),direct_diff(cos(x),4))
+            assert_array_almost_equal(diff(cos(2*x)),direct_diff(cos(2*x)))
+            assert_array_almost_equal(diff(sin(x*n/8)),direct_diff(sin(x*n/8)))
+            assert_array_almost_equal(diff(cos(x*n/8)),direct_diff(cos(x*n/8)))
+            for k in range(5):
+                assert_array_almost_equal(diff(sin(4*x),k),direct_diff(sin(4*x),k))
+                assert_array_almost_equal(diff(cos(4*x),k),direct_diff(cos(4*x),k))
+
+    def test_period(self):
+        for n in [17,64]:
+            x = arange(n)/float(n)
+            assert_array_almost_equal(diff(sin(2*pi*x),period=1),
+                                      2*pi*cos(2*pi*x))
+            assert_array_almost_equal(diff(sin(2*pi*x),3,period=1),
+                                      -(2*pi)**3*cos(2*pi*x))
+
+    def test_sin(self):
+        for n in [32,64,77]:
+            x = arange(n)*2*pi/n
+            assert_array_almost_equal(diff(sin(x)),cos(x))
+            assert_array_almost_equal(diff(cos(x)),-sin(x))
+            assert_array_almost_equal(diff(sin(x),2),-sin(x))
+            assert_array_almost_equal(diff(sin(x),4),sin(x))
+            assert_array_almost_equal(diff(sin(4*x)),4*cos(4*x))
+            assert_array_almost_equal(diff(sin(sin(x))),cos(x)*cos(sin(x)))
+
+    def test_expr(self):
+        for n in [64,77,100,128,256,512,1024,2048,4096,8192][:5]:
+            x = arange(n)*2*pi/n
+            f = sin(x)*cos(4*x)+exp(sin(3*x))
+            df = cos(x)*cos(4*x)-4*sin(x)*sin(4*x)+3*cos(3*x)*exp(sin(3*x))
+            ddf = -17*sin(x)*cos(4*x)-8*cos(x)*sin(4*x)\
+                 - 9*sin(3*x)*exp(sin(3*x))+9*cos(3*x)**2*exp(sin(3*x))
+            d1 = diff(f)
+            assert_array_almost_equal(d1,df)
+            assert_array_almost_equal(diff(df),ddf)
+            assert_array_almost_equal(diff(f,2),ddf)
+            assert_array_almost_equal(diff(ddf,-1),df)
+
+    def test_expr_large(self):
+        for n in [2048,4096]:
+            x = arange(n)*2*pi/n
+            f = sin(x)*cos(4*x)+exp(sin(3*x))
+            df = cos(x)*cos(4*x)-4*sin(x)*sin(4*x)+3*cos(3*x)*exp(sin(3*x))
+            ddf = -17*sin(x)*cos(4*x)-8*cos(x)*sin(4*x)\
+                 - 9*sin(3*x)*exp(sin(3*x))+9*cos(3*x)**2*exp(sin(3*x))
+            assert_array_almost_equal(diff(f),df)
+            assert_array_almost_equal(diff(df),ddf)
+            assert_array_almost_equal(diff(ddf,-1),df)
+            assert_array_almost_equal(diff(f,2),ddf)
+
+    def test_int(self):
+        n = 64
+        x = arange(n)*2*pi/n
+        assert_array_almost_equal(diff(sin(x),-1),-cos(x))
+        assert_array_almost_equal(diff(sin(x),-2),-sin(x))
+        assert_array_almost_equal(diff(sin(x),-4),sin(x))
+        assert_array_almost_equal(diff(2*cos(2*x),-1),sin(2*x))
+
+    def test_random_even(self):
+        rng = np.random.default_rng(1234)
+        for k in [0,2,4,6]:
+            for n in [60,32,64,56,55]:
+                f = rng.random((n,))
+                af = sum(f,axis=0)/n
+                f = f-af
+                # zeroing Nyquist mode:
+                f = diff(diff(f,1),-1)
+                assert_almost_equal(sum(f,axis=0),0.0)
+                assert_array_almost_equal(diff(diff(f,k),-k),f)
+                assert_array_almost_equal(diff(diff(f,-k),k),f)
+
+    def test_random_odd(self):
+        rng = np.random.default_rng(1234)
+        for k in [0,1,2,3,4,5,6]:
+            for n in [33,65,55]:
+                f = rng.random((n,))
+                af = sum(f,axis=0)/n
+                f = f-af
+                assert_almost_equal(sum(f,axis=0),0.0)
+                assert_array_almost_equal(diff(diff(f,k),-k),f)
+                assert_array_almost_equal(diff(diff(f,-k),k),f)
+
+    def test_zero_nyquist(self):
+        rng = np.random.default_rng(1234)
+        for k in [0,1,2,3,4,5,6]:
+            for n in [32,33,64,56,55]:
+                f = rng.random((n,))
+                af = sum(f,axis=0)/n
+                f = f-af
+                # zeroing Nyquist mode:
+                f = diff(diff(f,1),-1)
+                assert_almost_equal(sum(f,axis=0),0.0)
+                assert_array_almost_equal(diff(diff(f,k),-k),f)
+                assert_array_almost_equal(diff(diff(f,-k),k),f)
+
+
+class TestTilbert:
+
+    def test_definition(self):
+        for h in [0.1,0.5,1,5.5,10]:
+            for n in [16,17,64,127]:
+                x = arange(n)*2*pi/n
+                y = tilbert(sin(x),h)
+                y1 = direct_tilbert(sin(x),h)
+                assert_array_almost_equal(y,y1)
+                assert_array_almost_equal(tilbert(sin(x),h),
+                                          direct_tilbert(sin(x),h))
+                assert_array_almost_equal(tilbert(sin(2*x),h),
+                                          direct_tilbert(sin(2*x),h))
+
+    def test_random_even(self):
+        for h in [0.1,0.5,1,5.5,10]:
+            for n in [32,64,56]:
+                f = random((n,))
+                af = sum(f,axis=0)/n
+                f = f-af
+                assert_almost_equal(sum(f,axis=0),0.0)
+                assert_array_almost_equal(direct_tilbert(direct_itilbert(f,h),h),f)
+
+    def test_random_odd(self):
+        rng = np.random.default_rng(1234)
+        for h in [0.1,0.5,1,5.5,10]:
+            for n in [33,65,55]:
+                f = rng.random((n,))
+                af = sum(f,axis=0)/n
+                f = f-af
+                assert_almost_equal(sum(f,axis=0),0.0)
+                assert_array_almost_equal(itilbert(tilbert(f,h),h),f)
+                assert_array_almost_equal(tilbert(itilbert(f,h),h),f)
+
+
+class TestITilbert:
+
+    def test_definition(self):
+        for h in [0.1,0.5,1,5.5,10]:
+            for n in [16,17,64,127]:
+                x = arange(n)*2*pi/n
+                y = itilbert(sin(x),h)
+                y1 = direct_itilbert(sin(x),h)
+                assert_array_almost_equal(y,y1)
+                assert_array_almost_equal(itilbert(sin(x),h),
+                                          direct_itilbert(sin(x),h))
+                assert_array_almost_equal(itilbert(sin(2*x),h),
+                                          direct_itilbert(sin(2*x),h))
+
+
+class TestHilbert:
+
+    def test_definition(self):
+        for n in [16,17,64,127]:
+            x = arange(n)*2*pi/n
+            y = hilbert(sin(x))
+            y1 = direct_hilbert(sin(x))
+            assert_array_almost_equal(y,y1)
+            assert_array_almost_equal(hilbert(sin(2*x)),
+                                      direct_hilbert(sin(2*x)))
+
+    def test_tilbert_relation(self):
+        for n in [16,17,64,127]:
+            x = arange(n)*2*pi/n
+            f = sin(x)+cos(2*x)*sin(x)
+            y = hilbert(f)
+            y1 = direct_hilbert(f)
+            assert_array_almost_equal(y,y1)
+            y2 = tilbert(f,h=10)
+            assert_array_almost_equal(y,y2)
+
+    def test_random_odd(self):
+        rng = np.random.default_rng(1234)
+        for n in [33,65,55]:
+            f = rng.random((n,))
+            af = sum(f,axis=0)/n
+            f = f-af
+            assert_almost_equal(sum(f,axis=0),0.0)
+            assert_array_almost_equal(ihilbert(hilbert(f)),f)
+            assert_array_almost_equal(hilbert(ihilbert(f)),f)
+
+    def test_random_even(self):
+        rng = np.random.default_rng(1234)
+        for n in [32,64,56]:
+            f = rng.random((n,))
+            af = sum(f,axis=0)/n
+            f = f-af
+            # zeroing Nyquist mode:
+            f = diff(diff(f,1),-1)
+            assert_almost_equal(sum(f,axis=0),0.0)
+            assert_array_almost_equal(direct_hilbert(direct_ihilbert(f)),f)
+            assert_array_almost_equal(hilbert(ihilbert(f)),f)
+
+
+class TestIHilbert:
+
+    def test_definition(self):
+        for n in [16,17,64,127]:
+            x = arange(n)*2*pi/n
+            y = ihilbert(sin(x))
+            y1 = direct_ihilbert(sin(x))
+            assert_array_almost_equal(y,y1)
+            assert_array_almost_equal(ihilbert(sin(2*x)),
+                                      direct_ihilbert(sin(2*x)))
+
+    def test_itilbert_relation(self):
+        for n in [16,17,64,127]:
+            x = arange(n)*2*pi/n
+            f = sin(x)+cos(2*x)*sin(x)
+            y = ihilbert(f)
+            y1 = direct_ihilbert(f)
+            assert_array_almost_equal(y,y1)
+            y2 = itilbert(f,h=10)
+            assert_array_almost_equal(y,y2)
+
+
+class TestShift:
+
+    def test_definition(self):
+        for n in [18,17,64,127,32,2048,256]:
+            x = arange(n)*2*pi/n
+            for a in [0.1,3]:
+                assert_array_almost_equal(shift(sin(x),a),direct_shift(sin(x),a))
+                assert_array_almost_equal(shift(sin(x),a),sin(x+a))
+                assert_array_almost_equal(shift(cos(x),a),cos(x+a))
+                assert_array_almost_equal(shift(cos(2*x)+sin(x),a),
+                                          cos(2*(x+a))+sin(x+a))
+                assert_array_almost_equal(shift(exp(sin(x)),a),exp(sin(x+a)))
+            assert_array_almost_equal(shift(sin(x),2*pi),sin(x))
+            assert_array_almost_equal(shift(sin(x),pi),-sin(x))
+            assert_array_almost_equal(shift(sin(x),pi/2),cos(x))
+
+
+class TestOverwrite:
+    """Check input overwrite behavior """
+
+    real_dtypes = (np.float32, np.float64)
+    dtypes = real_dtypes + (np.complex64, np.complex128)
+
+    def _check(self, x, routine, *args, **kwargs):
+        x2 = x.copy()
+        routine(x2, *args, **kwargs)
+        sig = routine.__name__
+        if args:
+            sig += repr(args)
+        if kwargs:
+            sig += repr(kwargs)
+        assert_equal(x2, x, err_msg=f"spurious overwrite in {sig}")
+
+    def _check_1d(self, routine, dtype, shape, *args, **kwargs):
+        # rng = np.random.default_rng(1234)
+        rng = np.random.RandomState(1234)
+        # np.random.seed(1234)
+        if np.issubdtype(dtype, np.complexfloating):
+            data = rng.randn(*shape) + 1j*rng.randn(*shape)
+        else:
+            data = rng.randn(*shape)
+        data = data.astype(dtype)
+        self._check(data, routine, *args, **kwargs)
+
+    def test_diff(self):
+        for dtype in self.dtypes:
+            self._check_1d(diff, dtype, (16,))
+
+    def test_tilbert(self):
+        for dtype in self.dtypes:
+            self._check_1d(tilbert, dtype, (16,), 1.6)
+
+    def test_itilbert(self):
+        for dtype in self.dtypes:
+            self._check_1d(itilbert, dtype, (16,), 1.6)
+
+    def test_hilbert(self):
+        for dtype in self.dtypes:
+            self._check_1d(hilbert, dtype, (16,))
+
+    def test_cs_diff(self):
+        for dtype in self.dtypes:
+            self._check_1d(cs_diff, dtype, (16,), 1.0, 4.0)
+
+    def test_sc_diff(self):
+        for dtype in self.dtypes:
+            self._check_1d(sc_diff, dtype, (16,), 1.0, 4.0)
+
+    def test_ss_diff(self):
+        for dtype in self.dtypes:
+            self._check_1d(ss_diff, dtype, (16,), 1.0, 4.0)
+
+    def test_cc_diff(self):
+        for dtype in self.dtypes:
+            self._check_1d(cc_diff, dtype, (16,), 1.0, 4.0)
+
+    def test_shift(self):
+        for dtype in self.dtypes:
+            self._check_1d(shift, dtype, (16,), 1.0)
diff --git a/.venv/lib/python3.12/site-packages/scipy/fftpack/tests/test_real_transforms.py b/.venv/lib/python3.12/site-packages/scipy/fftpack/tests/test_real_transforms.py
new file mode 100644
index 0000000000000000000000000000000000000000..fc8d657a7fe36f28de3f94fa8f933bf6855499ab
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/fftpack/tests/test_real_transforms.py
@@ -0,0 +1,836 @@
+from os.path import join, dirname
+import threading
+
+import numpy as np
+from numpy.testing import assert_array_almost_equal, assert_equal
+import pytest
+from pytest import raises as assert_raises
+
+from scipy.fftpack._realtransforms import (
+    dct, idct, dst, idst, dctn, idctn, dstn, idstn)
+
+# Matlab reference data
+MDATA = np.load(join(dirname(__file__), 'test.npz'))
+X = [MDATA[f'x{i}'] for i in range(8)]
+Y = [MDATA[f'y{i}'] for i in range(8)]
+
+# FFTW reference data: the data are organized as follows:
+#    * SIZES is an array containing all available sizes
+#    * for every type (1, 2, 3, 4) and every size, the array dct_type_size
+#    contains the output of the DCT applied to the input np.linspace(0, size-1,
+#    size)
+FFTWDATA_DOUBLE = np.load(join(dirname(__file__), 'fftw_double_ref.npz'))
+FFTWDATA_SINGLE = np.load(join(dirname(__file__), 'fftw_single_ref.npz'))
+FFTWDATA_SIZES = FFTWDATA_DOUBLE['sizes']
+
+
+def fftw_dct_ref(type, size, dt):
+    x = np.linspace(0, size-1, size).astype(dt)
+    dt = np.result_type(np.float32, dt)
+    if dt == np.float64:
+        data = FFTWDATA_DOUBLE
+    elif dt == np.float32:
+        data = FFTWDATA_SINGLE
+    else:
+        raise ValueError()
+    y = (data[f'dct_{type}_{size}']).astype(dt)
+    return x, y, dt
+
+
+def fftw_dst_ref(type, size, dt):
+    x = np.linspace(0, size-1, size).astype(dt)
+    dt = np.result_type(np.float32, dt)
+    if dt == np.float64:
+        data = FFTWDATA_DOUBLE
+    elif dt == np.float32:
+        data = FFTWDATA_SINGLE
+    else:
+        raise ValueError()
+    y = (data[f'dst_{type}_{size}']).astype(dt)
+    return x, y, dt
+
+
+def dct_2d_ref(x, **kwargs):
+    """Calculate reference values for testing dct2."""
+    x = np.array(x, copy=True)
+    for row in range(x.shape[0]):
+        x[row, :] = dct(x[row, :], **kwargs)
+    for col in range(x.shape[1]):
+        x[:, col] = dct(x[:, col], **kwargs)
+    return x
+
+
+def idct_2d_ref(x, **kwargs):
+    """Calculate reference values for testing idct2."""
+    x = np.array(x, copy=True)
+    for row in range(x.shape[0]):
+        x[row, :] = idct(x[row, :], **kwargs)
+    for col in range(x.shape[1]):
+        x[:, col] = idct(x[:, col], **kwargs)
+    return x
+
+
+def dst_2d_ref(x, **kwargs):
+    """Calculate reference values for testing dst2."""
+    x = np.array(x, copy=True)
+    for row in range(x.shape[0]):
+        x[row, :] = dst(x[row, :], **kwargs)
+    for col in range(x.shape[1]):
+        x[:, col] = dst(x[:, col], **kwargs)
+    return x
+
+
+def idst_2d_ref(x, **kwargs):
+    """Calculate reference values for testing idst2."""
+    x = np.array(x, copy=True)
+    for row in range(x.shape[0]):
+        x[row, :] = idst(x[row, :], **kwargs)
+    for col in range(x.shape[1]):
+        x[:, col] = idst(x[:, col], **kwargs)
+    return x
+
+
+def naive_dct1(x, norm=None):
+    """Calculate textbook definition version of DCT-I."""
+    x = np.array(x, copy=True)
+    N = len(x)
+    M = N-1
+    y = np.zeros(N)
+    m0, m = 1, 2
+    if norm == 'ortho':
+        m0 = np.sqrt(1.0/M)
+        m = np.sqrt(2.0/M)
+    for k in range(N):
+        for n in range(1, N-1):
+            y[k] += m*x[n]*np.cos(np.pi*n*k/M)
+        y[k] += m0 * x[0]
+        y[k] += m0 * x[N-1] * (1 if k % 2 == 0 else -1)
+    if norm == 'ortho':
+        y[0] *= 1/np.sqrt(2)
+        y[N-1] *= 1/np.sqrt(2)
+    return y
+
+
+def naive_dst1(x, norm=None):
+    """Calculate textbook definition version  of DST-I."""
+    x = np.array(x, copy=True)
+    N = len(x)
+    M = N+1
+    y = np.zeros(N)
+    for k in range(N):
+        for n in range(N):
+            y[k] += 2*x[n]*np.sin(np.pi*(n+1.0)*(k+1.0)/M)
+    if norm == 'ortho':
+        y *= np.sqrt(0.5/M)
+    return y
+
+
+def naive_dct4(x, norm=None):
+    """Calculate textbook definition version of DCT-IV."""
+    x = np.array(x, copy=True)
+    N = len(x)
+    y = np.zeros(N)
+    for k in range(N):
+        for n in range(N):
+            y[k] += x[n]*np.cos(np.pi*(n+0.5)*(k+0.5)/(N))
+    if norm == 'ortho':
+        y *= np.sqrt(2.0/N)
+    else:
+        y *= 2
+    return y
+
+
+def naive_dst4(x, norm=None):
+    """Calculate textbook definition version of DST-IV."""
+    x = np.array(x, copy=True)
+    N = len(x)
+    y = np.zeros(N)
+    for k in range(N):
+        for n in range(N):
+            y[k] += x[n]*np.sin(np.pi*(n+0.5)*(k+0.5)/(N))
+    if norm == 'ortho':
+        y *= np.sqrt(2.0/N)
+    else:
+        y *= 2
+    return y
+
+
+class TestComplex:
+    def test_dct_complex64(self):
+        y = dct(1j*np.arange(5, dtype=np.complex64))
+        x = 1j*dct(np.arange(5))
+        assert_array_almost_equal(x, y)
+
+    def test_dct_complex(self):
+        y = dct(np.arange(5)*1j)
+        x = 1j*dct(np.arange(5))
+        assert_array_almost_equal(x, y)
+
+    def test_idct_complex(self):
+        y = idct(np.arange(5)*1j)
+        x = 1j*idct(np.arange(5))
+        assert_array_almost_equal(x, y)
+
+    def test_dst_complex64(self):
+        y = dst(np.arange(5, dtype=np.complex64)*1j)
+        x = 1j*dst(np.arange(5))
+        assert_array_almost_equal(x, y)
+
+    def test_dst_complex(self):
+        y = dst(np.arange(5)*1j)
+        x = 1j*dst(np.arange(5))
+        assert_array_almost_equal(x, y)
+
+    def test_idst_complex(self):
+        y = idst(np.arange(5)*1j)
+        x = 1j*idst(np.arange(5))
+        assert_array_almost_equal(x, y)
+
+
+class _TestDCTBase:
+    def setup_method(self):
+        self.rdt = None
+        self.dec = 14
+        self.type = None
+
+    @pytest.fixture
+    def dct_lock(self):
+        return threading.Lock()
+
+    def test_definition(self, dct_lock):
+        for i in FFTWDATA_SIZES:
+            with dct_lock:
+                x, yr, dt = fftw_dct_ref(self.type, i, self.rdt)
+            y = dct(x, type=self.type)
+            assert_equal(y.dtype, dt)
+            # XXX: we divide by np.max(y) because the tests fail otherwise. We
+            # should really use something like assert_array_approx_equal. The
+            # difference is due to fftw using a better algorithm w.r.t error
+            # propagation compared to the ones from fftpack.
+            assert_array_almost_equal(y / np.max(y), yr / np.max(y), decimal=self.dec,
+                    err_msg=f"Size {i} failed")
+
+    def test_axis(self):
+        nt = 2
+        rng = np.random.RandomState(1234)
+        for i in [7, 8, 9, 16, 32, 64]:
+            x = rng.randn(nt, i)
+            y = dct(x, type=self.type)
+            for j in range(nt):
+                assert_array_almost_equal(y[j], dct(x[j], type=self.type),
+                        decimal=self.dec)
+
+            x = x.T
+            y = dct(x, axis=0, type=self.type)
+            for j in range(nt):
+                assert_array_almost_equal(y[:,j], dct(x[:,j], type=self.type),
+                        decimal=self.dec)
+
+
+class _TestDCTIBase(_TestDCTBase):
+    def test_definition_ortho(self):
+        # Test orthornomal mode.
+        dt = np.result_type(np.float32, self.rdt)
+        for xr in X:
+            x = np.array(xr, dtype=self.rdt)
+            y = dct(x, norm='ortho', type=1)
+            y2 = naive_dct1(x, norm='ortho')
+            assert_equal(y.dtype, dt)
+            assert_array_almost_equal(y / np.max(y), y2 / np.max(y), decimal=self.dec)
+
+class _TestDCTIIBase(_TestDCTBase):
+    def test_definition_matlab(self):
+        # Test correspondence with MATLAB (orthornomal mode).
+        dt = np.result_type(np.float32, self.rdt)
+        for xr, yr in zip(X, Y):
+            x = np.array(xr, dtype=dt)
+            y = dct(x, norm="ortho", type=2)
+            assert_equal(y.dtype, dt)
+            assert_array_almost_equal(y, yr, decimal=self.dec)
+
+
+class _TestDCTIIIBase(_TestDCTBase):
+    def test_definition_ortho(self):
+        # Test orthornomal mode.
+        dt = np.result_type(np.float32, self.rdt)
+        for xr in X:
+            x = np.array(xr, dtype=self.rdt)
+            y = dct(x, norm='ortho', type=2)
+            xi = dct(y, norm="ortho", type=3)
+            assert_equal(xi.dtype, dt)
+            assert_array_almost_equal(xi, x, decimal=self.dec)
+
+class _TestDCTIVBase(_TestDCTBase):
+    def test_definition_ortho(self):
+        # Test orthornomal mode.
+        dt = np.result_type(np.float32, self.rdt)
+        for xr in X:
+            x = np.array(xr, dtype=self.rdt)
+            y = dct(x, norm='ortho', type=4)
+            y2 = naive_dct4(x, norm='ortho')
+            assert_equal(y.dtype, dt)
+            assert_array_almost_equal(y / np.max(y), y2 / np.max(y), decimal=self.dec)
+
+
+class TestDCTIDouble(_TestDCTIBase):
+    def setup_method(self):
+        self.rdt = np.float64
+        self.dec = 10
+        self.type = 1
+
+
+class TestDCTIFloat(_TestDCTIBase):
+    def setup_method(self):
+        self.rdt = np.float32
+        self.dec = 4
+        self.type = 1
+
+
+class TestDCTIInt(_TestDCTIBase):
+    def setup_method(self):
+        self.rdt = int
+        self.dec = 5
+        self.type = 1
+
+
+class TestDCTIIDouble(_TestDCTIIBase):
+    def setup_method(self):
+        self.rdt = np.float64
+        self.dec = 10
+        self.type = 2
+
+
+class TestDCTIIFloat(_TestDCTIIBase):
+    def setup_method(self):
+        self.rdt = np.float32
+        self.dec = 5
+        self.type = 2
+
+
+class TestDCTIIInt(_TestDCTIIBase):
+    def setup_method(self):
+        self.rdt = int
+        self.dec = 5
+        self.type = 2
+
+
+class TestDCTIIIDouble(_TestDCTIIIBase):
+    def setup_method(self):
+        self.rdt = np.float64
+        self.dec = 14
+        self.type = 3
+
+
+class TestDCTIIIFloat(_TestDCTIIIBase):
+    def setup_method(self):
+        self.rdt = np.float32
+        self.dec = 5
+        self.type = 3
+
+
+class TestDCTIIIInt(_TestDCTIIIBase):
+    def setup_method(self):
+        self.rdt = int
+        self.dec = 5
+        self.type = 3
+
+
+class TestDCTIVDouble(_TestDCTIVBase):
+    def setup_method(self):
+        self.rdt = np.float64
+        self.dec = 12
+        self.type = 3
+
+
+class TestDCTIVFloat(_TestDCTIVBase):
+    def setup_method(self):
+        self.rdt = np.float32
+        self.dec = 5
+        self.type = 3
+
+
+class TestDCTIVInt(_TestDCTIVBase):
+    def setup_method(self):
+        self.rdt = int
+        self.dec = 5
+        self.type = 3
+
+
+class _TestIDCTBase:
+    def setup_method(self):
+        self.rdt = None
+        self.dec = 14
+        self.type = None
+
+    @pytest.fixture
+    def idct_lock(self):
+        return threading.Lock()
+
+    def test_definition(self, idct_lock):
+        for i in FFTWDATA_SIZES:
+            with idct_lock:
+                xr, yr, dt = fftw_dct_ref(self.type, i, self.rdt)
+            x = idct(yr, type=self.type)
+            if self.type == 1:
+                x /= 2 * (i-1)
+            else:
+                x /= 2 * i
+            assert_equal(x.dtype, dt)
+            # XXX: we divide by np.max(y) because the tests fail otherwise. We
+            # should really use something like assert_array_approx_equal. The
+            # difference is due to fftw using a better algorithm w.r.t error
+            # propagation compared to the ones from fftpack.
+            assert_array_almost_equal(x / np.max(x), xr / np.max(x), decimal=self.dec,
+                    err_msg=f"Size {i} failed")
+
+class TestIDCTIDouble(_TestIDCTBase):
+    def setup_method(self):
+        self.rdt = np.float64
+        self.dec = 10
+        self.type = 1
+
+
+class TestIDCTIFloat(_TestIDCTBase):
+    def setup_method(self):
+        self.rdt = np.float32
+        self.dec = 4
+        self.type = 1
+
+
+class TestIDCTIInt(_TestIDCTBase):
+    def setup_method(self):
+        self.rdt = int
+        self.dec = 4
+        self.type = 1
+
+
+class TestIDCTIIDouble(_TestIDCTBase):
+    def setup_method(self):
+        self.rdt = np.float64
+        self.dec = 10
+        self.type = 2
+
+
+class TestIDCTIIFloat(_TestIDCTBase):
+    def setup_method(self):
+        self.rdt = np.float32
+        self.dec = 5
+        self.type = 2
+
+
+class TestIDCTIIInt(_TestIDCTBase):
+    def setup_method(self):
+        self.rdt = int
+        self.dec = 5
+        self.type = 2
+
+
+class TestIDCTIIIDouble(_TestIDCTBase):
+    def setup_method(self):
+        self.rdt = np.float64
+        self.dec = 14
+        self.type = 3
+
+
+class TestIDCTIIIFloat(_TestIDCTBase):
+    def setup_method(self):
+        self.rdt = np.float32
+        self.dec = 5
+        self.type = 3
+
+
+class TestIDCTIIIInt(_TestIDCTBase):
+    def setup_method(self):
+        self.rdt = int
+        self.dec = 5
+        self.type = 3
+
+class TestIDCTIVDouble(_TestIDCTBase):
+    def setup_method(self):
+        self.rdt = np.float64
+        self.dec = 12
+        self.type = 4
+
+
+class TestIDCTIVFloat(_TestIDCTBase):
+    def setup_method(self):
+        self.rdt = np.float32
+        self.dec = 5
+        self.type = 4
+
+
+class TestIDCTIVInt(_TestIDCTBase):
+    def setup_method(self):
+        self.rdt = int
+        self.dec = 5
+        self.type = 4
+
+class _TestDSTBase:
+    def setup_method(self):
+        self.rdt = None  # dtype
+        self.dec = None  # number of decimals to match
+        self.type = None  # dst type
+
+    @pytest.fixture
+    def dst_lock(self):
+        return threading.Lock()
+
+    def test_definition(self, dst_lock):
+        for i in FFTWDATA_SIZES:
+            with dst_lock:
+                xr, yr, dt = fftw_dst_ref(self.type, i, self.rdt)
+            y = dst(xr, type=self.type)
+            assert_equal(y.dtype, dt)
+            # XXX: we divide by np.max(y) because the tests fail otherwise. We
+            # should really use something like assert_array_approx_equal. The
+            # difference is due to fftw using a better algorithm w.r.t error
+            # propagation compared to the ones from fftpack.
+            assert_array_almost_equal(y / np.max(y), yr / np.max(y), decimal=self.dec,
+                    err_msg=f"Size {i} failed")
+
+
+class _TestDSTIBase(_TestDSTBase):
+    def test_definition_ortho(self):
+        # Test orthornomal mode.
+        dt = np.result_type(np.float32, self.rdt)
+        for xr in X:
+            x = np.array(xr, dtype=self.rdt)
+            y = dst(x, norm='ortho', type=1)
+            y2 = naive_dst1(x, norm='ortho')
+            assert_equal(y.dtype, dt)
+            assert_array_almost_equal(y / np.max(y), y2 / np.max(y), decimal=self.dec)
+
+class _TestDSTIVBase(_TestDSTBase):
+    def test_definition_ortho(self):
+        # Test orthornomal mode.
+        dt = np.result_type(np.float32, self.rdt)
+        for xr in X:
+            x = np.array(xr, dtype=self.rdt)
+            y = dst(x, norm='ortho', type=4)
+            y2 = naive_dst4(x, norm='ortho')
+            assert_equal(y.dtype, dt)
+            assert_array_almost_equal(y, y2, decimal=self.dec)
+
+class TestDSTIDouble(_TestDSTIBase):
+    def setup_method(self):
+        self.rdt = np.float64
+        self.dec = 12
+        self.type = 1
+
+
+class TestDSTIFloat(_TestDSTIBase):
+    def setup_method(self):
+        self.rdt = np.float32
+        self.dec = 4
+        self.type = 1
+
+
+class TestDSTIInt(_TestDSTIBase):
+    def setup_method(self):
+        self.rdt = int
+        self.dec = 5
+        self.type = 1
+
+
+class TestDSTIIDouble(_TestDSTBase):
+    def setup_method(self):
+        self.rdt = np.float64
+        self.dec = 14
+        self.type = 2
+
+
+class TestDSTIIFloat(_TestDSTBase):
+    def setup_method(self):
+        self.rdt = np.float32
+        self.dec = 6
+        self.type = 2
+
+
+class TestDSTIIInt(_TestDSTBase):
+    def setup_method(self):
+        self.rdt = int
+        self.dec = 6
+        self.type = 2
+
+
+class TestDSTIIIDouble(_TestDSTBase):
+    def setup_method(self):
+        self.rdt = np.float64
+        self.dec = 14
+        self.type = 3
+
+
+class TestDSTIIIFloat(_TestDSTBase):
+    def setup_method(self):
+        self.rdt = np.float32
+        self.dec = 7
+        self.type = 3
+
+
+class TestDSTIIIInt(_TestDSTBase):
+    def setup_method(self):
+        self.rdt = int
+        self.dec = 7
+        self.type = 3
+
+
+class TestDSTIVDouble(_TestDSTIVBase):
+    def setup_method(self):
+        self.rdt = np.float64
+        self.dec = 12
+        self.type = 4
+
+
+class TestDSTIVFloat(_TestDSTIVBase):
+    def setup_method(self):
+        self.rdt = np.float32
+        self.dec = 4
+        self.type = 4
+
+
+class TestDSTIVInt(_TestDSTIVBase):
+    def setup_method(self):
+        self.rdt = int
+        self.dec = 5
+        self.type = 4
+
+
+class _TestIDSTBase:
+    def setup_method(self):
+        self.rdt = None
+        self.dec = None
+        self.type = None
+
+    @pytest.fixture
+    def idst_lock(self):
+        return threading.Lock()
+
+    def test_definition(self, idst_lock):
+        for i in FFTWDATA_SIZES:
+            with idst_lock:
+                xr, yr, dt = fftw_dst_ref(self.type, i, self.rdt)
+            x = idst(yr, type=self.type)
+            if self.type == 1:
+                x /= 2 * (i+1)
+            else:
+                x /= 2 * i
+            assert_equal(x.dtype, dt)
+            # XXX: we divide by np.max(x) because the tests fail otherwise. We
+            # should really use something like assert_array_approx_equal. The
+            # difference is due to fftw using a better algorithm w.r.t error
+            # propagation compared to the ones from fftpack.
+            assert_array_almost_equal(x / np.max(x), xr / np.max(x), decimal=self.dec,
+                    err_msg=f"Size {i} failed")
+
+
+class TestIDSTIDouble(_TestIDSTBase):
+    def setup_method(self):
+        self.rdt = np.float64
+        self.dec = 12
+        self.type = 1
+
+
+class TestIDSTIFloat(_TestIDSTBase):
+    def setup_method(self):
+        self.rdt = np.float32
+        self.dec = 4
+        self.type = 1
+
+
+class TestIDSTIInt(_TestIDSTBase):
+    def setup_method(self):
+        self.rdt = int
+        self.dec = 4
+        self.type = 1
+
+
+class TestIDSTIIDouble(_TestIDSTBase):
+    def setup_method(self):
+        self.rdt = np.float64
+        self.dec = 14
+        self.type = 2
+
+
+class TestIDSTIIFloat(_TestIDSTBase):
+    def setup_method(self):
+        self.rdt = np.float32
+        self.dec = 6
+        self.type = 2
+
+
+class TestIDSTIIInt(_TestIDSTBase):
+    def setup_method(self):
+        self.rdt = int
+        self.dec = 6
+        self.type = 2
+
+
+class TestIDSTIIIDouble(_TestIDSTBase):
+    def setup_method(self):
+        self.rdt = np.float64
+        self.dec = 14
+        self.type = 3
+
+
+class TestIDSTIIIFloat(_TestIDSTBase):
+    def setup_method(self):
+        self.rdt = np.float32
+        self.dec = 6
+        self.type = 3
+
+
+class TestIDSTIIIInt(_TestIDSTBase):
+    def setup_method(self):
+        self.rdt = int
+        self.dec = 6
+        self.type = 3
+
+
+class TestIDSTIVDouble(_TestIDSTBase):
+    def setup_method(self):
+        self.rdt = np.float64
+        self.dec = 12
+        self.type = 4
+
+
+class TestIDSTIVFloat(_TestIDSTBase):
+    def setup_method(self):
+        self.rdt = np.float32
+        self.dec = 6
+        self.type = 4
+
+
+class TestIDSTIVnt(_TestIDSTBase):
+    def setup_method(self):
+        self.rdt = int
+        self.dec = 6
+        self.type = 4
+
+
+class TestOverwrite:
+    """Check input overwrite behavior."""
+
+    real_dtypes = [np.float32, np.float64]
+
+    def _check(self, x, routine, type, fftsize, axis, norm, overwrite_x, **kw):
+        x2 = x.copy()
+        routine(x2, type, fftsize, axis, norm, overwrite_x=overwrite_x)
+
+        sig = (f"{routine.__name__}({x.dtype}{x.shape!r}, {fftsize!r}, "
+               f"axis={axis!r}, overwrite_x={overwrite_x!r})")
+        if not overwrite_x:
+            assert_equal(x2, x, err_msg=f"spurious overwrite in {sig}")
+
+    def _check_1d(self, routine, dtype, shape, axis):
+        rng = np.random.RandomState(1234)
+        if np.issubdtype(dtype, np.complexfloating):
+            data = rng.randn(*shape) + 1j*rng.randn(*shape)
+        else:
+            data = rng.randn(*shape)
+        data = data.astype(dtype)
+
+        for type in [1, 2, 3, 4]:
+            for overwrite_x in [True, False]:
+                for norm in [None, 'ortho']:
+                    self._check(data, routine, type, None, axis, norm,
+                                overwrite_x)
+
+    def test_dct(self):
+        for dtype in self.real_dtypes:
+            self._check_1d(dct, dtype, (16,), -1)
+            self._check_1d(dct, dtype, (16, 2), 0)
+            self._check_1d(dct, dtype, (2, 16), 1)
+
+    def test_idct(self):
+        for dtype in self.real_dtypes:
+            self._check_1d(idct, dtype, (16,), -1)
+            self._check_1d(idct, dtype, (16, 2), 0)
+            self._check_1d(idct, dtype, (2, 16), 1)
+
+    def test_dst(self):
+        for dtype in self.real_dtypes:
+            self._check_1d(dst, dtype, (16,), -1)
+            self._check_1d(dst, dtype, (16, 2), 0)
+            self._check_1d(dst, dtype, (2, 16), 1)
+
+    def test_idst(self):
+        for dtype in self.real_dtypes:
+            self._check_1d(idst, dtype, (16,), -1)
+            self._check_1d(idst, dtype, (16, 2), 0)
+            self._check_1d(idst, dtype, (2, 16), 1)
+
+
+class Test_DCTN_IDCTN:
+    dec = 14
+    dct_type = [1, 2, 3, 4]
+    norms = [None, 'ortho']
+    rstate = np.random.RandomState(1234)
+    shape = (32, 16)
+    data = rstate.randn(*shape)
+
+    @pytest.mark.parametrize('fforward,finverse', [(dctn, idctn),
+                                                   (dstn, idstn)])
+    @pytest.mark.parametrize('axes', [None,
+                                      1, (1,), [1],
+                                      0, (0,), [0],
+                                      (0, 1), [0, 1],
+                                      (-2, -1), [-2, -1]])
+    @pytest.mark.parametrize('dct_type', dct_type)
+    @pytest.mark.parametrize('norm', ['ortho'])
+    def test_axes_round_trip(self, fforward, finverse, axes, dct_type, norm):
+        tmp = fforward(self.data, type=dct_type, axes=axes, norm=norm)
+        tmp = finverse(tmp, type=dct_type, axes=axes, norm=norm)
+        assert_array_almost_equal(self.data, tmp, decimal=12)
+
+    @pytest.mark.parametrize('fforward,fforward_ref', [(dctn, dct_2d_ref),
+                                                       (dstn, dst_2d_ref)])
+    @pytest.mark.parametrize('dct_type', dct_type)
+    @pytest.mark.parametrize('norm', norms)
+    def test_dctn_vs_2d_reference(self, fforward, fforward_ref,
+                                  dct_type, norm):
+        y1 = fforward(self.data, type=dct_type, axes=None, norm=norm)
+        y2 = fforward_ref(self.data, type=dct_type, norm=norm)
+        assert_array_almost_equal(y1, y2, decimal=11)
+
+    @pytest.mark.parametrize('finverse,finverse_ref', [(idctn, idct_2d_ref),
+                                                       (idstn, idst_2d_ref)])
+    @pytest.mark.parametrize('dct_type', dct_type)
+    @pytest.mark.parametrize('norm', [None, 'ortho'])
+    def test_idctn_vs_2d_reference(self, finverse, finverse_ref,
+                                   dct_type, norm):
+        fdata = dctn(self.data, type=dct_type, norm=norm)
+        y1 = finverse(fdata, type=dct_type, norm=norm)
+        y2 = finverse_ref(fdata, type=dct_type, norm=norm)
+        assert_array_almost_equal(y1, y2, decimal=11)
+
+    @pytest.mark.parametrize('fforward,finverse', [(dctn, idctn),
+                                                   (dstn, idstn)])
+    def test_axes_and_shape(self, fforward, finverse):
+        with assert_raises(ValueError,
+                           match="when given, axes and shape arguments"
+                           " have to be of the same length"):
+            fforward(self.data, shape=self.data.shape[0], axes=(0, 1))
+
+        with assert_raises(ValueError,
+                           match="when given, axes and shape arguments"
+                           " have to be of the same length"):
+            fforward(self.data, shape=self.data.shape[0], axes=None)
+
+        with assert_raises(ValueError,
+                           match="when given, axes and shape arguments"
+                           " have to be of the same length"):
+            fforward(self.data, shape=self.data.shape, axes=0)
+
+    @pytest.mark.parametrize('fforward', [dctn, dstn])
+    def test_shape(self, fforward):
+        tmp = fforward(self.data, shape=(128, 128), axes=None)
+        assert_equal(tmp.shape, (128, 128))
+
+    @pytest.mark.parametrize('fforward,finverse', [(dctn, idctn),
+                                                   (dstn, idstn)])
+    @pytest.mark.parametrize('axes', [1, (1,), [1],
+                                      0, (0,), [0]])
+    def test_shape_is_none_with_axes(self, fforward, finverse, axes):
+        tmp = fforward(self.data, shape=None, axes=axes, norm='ortho')
+        tmp = finverse(tmp, shape=None, axes=axes, norm='ortho')
+        assert_array_almost_equal(self.data, tmp, decimal=self.dec)
diff --git a/.venv/lib/python3.12/site-packages/scipy/integrate/LICENSE_DOP b/.venv/lib/python3.12/site-packages/scipy/integrate/LICENSE_DOP
new file mode 100644
index 0000000000000000000000000000000000000000..25058a7ef423593c505720032a99a5bb19503bfd
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/integrate/LICENSE_DOP
@@ -0,0 +1,76 @@
+Copyright (C) 2025 SciPy developers
+
+Redistribution and use in source and binary forms, with or without
+modification, are permitted provided that the following conditions are met:
+
+    a. Redistributions of source code must retain the above copyright notice,
+       this list of conditions and the following disclaimer.
+    b. Redistributions in binary form must reproduce the above copyright
+       notice, this list of conditions and the following disclaimer in the
+       documentation and/or other materials provided with the distribution.
+    c. Names of the SciPy Developers may not 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.
+
+
+DOP library consisting Dormand-Prince (4)5 and 8(5,3) integrators, is a
+C translation of the Fortran code written by Ernst Hairer, and Gerhard
+Wanner with the original descriptions below.
+
+* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
+* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
+    NUMERICAL SOLUTION OF A SYSTEM OF FIRST 0RDER
+    ORDINARY DIFFERENTIAL EQUATIONS  Y'=F(X,Y).
+    THIS IS AN EXPLICIT RUNGE-KUTTA METHOD OF ORDER 8(5,3)
+    DUE TO DORMAND & PRINCE (WITH STEPSIZE CONTROL AND
+    DENSE OUTPUT)
+
+    AUTHORS: E. HAIRER AND G. WANNER
+             UNIVERSITE DE GENEVE, DEPT. DE MATHEMATIQUES
+             CH-1211 GENEVE 24, SWITZERLAND
+             E-MAIL:  Ernst.Hairer@math.unige.ch
+                      Gerhard.Wanner@math.unige.ch
+
+    THIS CODE IS DESCRIBED IN:
+        E. HAIRER, S.P. NORSETT AND G. WANNER, SOLVING ORDINARY
+        DIFFERENTIAL EQUATIONS I. NONSTIFF PROBLEMS. 2ND EDITION.
+        SPRINGER SERIES IN COMPUTATIONAL MATHEMATICS,
+        SPRINGER-VERLAG (1993)
+
+    VERSION OF APRIL 25, 1996
+    (latest correction of a small bug: August 8, 2005)
+
+* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
+    NUMERICAL SOLUTION OF A SYSTEM OF FIRST 0RDER
+    ORDINARY DIFFERENTIAL EQUATIONS  Y'=F(X,Y).
+    THIS IS AN EXPLICIT RUNGE-KUTTA METHOD OF ORDER (4)5
+    DUE TO DORMAND & PRINCE (WITH STEPSIZE CONTROL AND
+    DENSE OUTPUT).
+
+    AUTHORS: E. HAIRER AND G. WANNER
+             UNIVERSITE DE GENEVE, DEPT. DE MATHEMATIQUES
+             CH-1211 GENEVE 24, SWITZERLAND
+             E-MAIL:  Ernst.Hairer@math.unige.ch
+                      Gerhard.Wanner@math.unige.ch
+
+    THIS CODE IS DESCRIBED IN:
+        E. HAIRER, S.P. NORSETT AND G. WANNER, SOLVING ORDINARY
+        DIFFERENTIAL EQUATIONS I. NONSTIFF PROBLEMS. 2ND EDITION.
+        SPRINGER SERIES IN COMPUTATIONAL MATHEMATICS,
+        SPRINGER-VERLAG (1993)
+
+    VERSION OF APRIL 25, 1996
+* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
+* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
diff --git a/.venv/lib/python3.12/site-packages/scipy/integrate/__init__.py b/.venv/lib/python3.12/site-packages/scipy/integrate/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..1533b5c60b695fce0abf08e2163dfba3bdd4fb17
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/integrate/__init__.py
@@ -0,0 +1,122 @@
+"""
+=============================================
+Integration and ODEs (:mod:`scipy.integrate`)
+=============================================
+
+.. currentmodule:: scipy.integrate
+
+Integrating functions, given function object
+============================================
+
+.. autosummary::
+   :toctree: generated/
+
+   quad          -- General purpose integration
+   quad_vec      -- General purpose integration of vector-valued functions
+   cubature      -- General purpose multi-dimensional integration of array-valued functions
+   dblquad       -- General purpose double integration
+   tplquad       -- General purpose triple integration
+   nquad         -- General purpose N-D integration
+   tanhsinh      -- General purpose elementwise integration
+   fixed_quad    -- Integrate func(x) using Gaussian quadrature of order n
+   newton_cotes  -- Weights and error coefficient for Newton-Cotes integration
+   lebedev_rule
+   qmc_quad      -- N-D integration using Quasi-Monte Carlo quadrature
+   IntegrationWarning -- Warning on issues during integration
+
+
+Integrating functions, given fixed samples
+==========================================
+
+.. autosummary::
+   :toctree: generated/
+
+   trapezoid            -- Use trapezoidal rule to compute integral.
+   cumulative_trapezoid -- Use trapezoidal rule to cumulatively compute integral.
+   simpson              -- Use Simpson's rule to compute integral from samples.
+   cumulative_simpson   -- Use Simpson's rule to cumulatively compute integral from samples.
+   romb                 -- Use Romberg Integration to compute integral from
+                        -- (2**k + 1) evenly-spaced samples.
+
+.. seealso::
+
+   :mod:`scipy.special` for orthogonal polynomials (special) for Gaussian
+   quadrature roots and weights for other weighting factors and regions.
+
+Summation
+=========
+
+.. autosummary::
+   :toctree: generated/
+
+   nsum
+
+Solving initial value problems for ODE systems
+==============================================
+
+The solvers are implemented as individual classes, which can be used directly
+(low-level usage) or through a convenience function.
+
+.. autosummary::
+   :toctree: generated/
+
+   solve_ivp     -- Convenient function for ODE integration.
+   RK23          -- Explicit Runge-Kutta solver of order 3(2).
+   RK45          -- Explicit Runge-Kutta solver of order 5(4).
+   DOP853        -- Explicit Runge-Kutta solver of order 8.
+   Radau         -- Implicit Runge-Kutta solver of order 5.
+   BDF           -- Implicit multi-step variable order (1 to 5) solver.
+   LSODA         -- LSODA solver from ODEPACK Fortran package.
+   OdeSolver     -- Base class for ODE solvers.
+   DenseOutput   -- Local interpolant for computing a dense output.
+   OdeSolution   -- Class which represents a continuous ODE solution.
+
+
+Old API
+-------
+
+These are the routines developed earlier for SciPy. They wrap older solvers
+implemented in Fortran (mostly ODEPACK). While the interface to them is not
+particularly convenient and certain features are missing compared to the new
+API, the solvers themselves are of good quality and work fast as compiled
+Fortran code. In some cases, it might be worth using this old API.
+
+.. autosummary::
+   :toctree: generated/
+
+   odeint        -- General integration of ordinary differential equations.
+   ode           -- Integrate ODE using VODE and ZVODE routines.
+   complex_ode   -- Convert a complex-valued ODE to real-valued and integrate.
+   ODEintWarning -- Warning raised during the execution of `odeint`.
+
+
+Solving boundary value problems for ODE systems
+===============================================
+
+.. autosummary::
+   :toctree: generated/
+
+   solve_bvp     -- Solve a boundary value problem for a system of ODEs.
+"""  # noqa: E501
+
+
+from ._quadrature import *
+from ._odepack_py import *
+from ._quadpack_py import *
+from ._ode import *
+from ._bvp import solve_bvp
+from ._ivp import (solve_ivp, OdeSolution, DenseOutput,
+                   OdeSolver, RK23, RK45, DOP853, Radau, BDF, LSODA)
+from ._quad_vec import quad_vec
+from ._tanhsinh import nsum, tanhsinh
+from ._cubature import cubature
+from ._lebedev import lebedev_rule
+
+# Deprecated namespaces, to be removed in v2.0.0
+from . import dop, lsoda, vode, odepack, quadpack
+
+__all__ = [s for s in dir() if not s.startswith('_')]
+
+from scipy._lib._testutils import PytestTester
+test = PytestTester(__name__)
+del PytestTester
diff --git a/.venv/lib/python3.12/site-packages/scipy/integrate/_bvp.py b/.venv/lib/python3.12/site-packages/scipy/integrate/_bvp.py
new file mode 100644
index 0000000000000000000000000000000000000000..396d991de2a62a53979c769d7cab528197386595
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/integrate/_bvp.py
@@ -0,0 +1,1164 @@
+"""Boundary value problem solver."""
+from warnings import warn
+
+import numpy as np
+from numpy.linalg import pinv
+
+from scipy.sparse import csc_array
+from scipy.sparse.linalg import splu
+from scipy.optimize import OptimizeResult
+from scipy._lib._array_api import xp_capabilities
+
+
+EPS = np.finfo(float).eps
+
+
+def estimate_fun_jac(fun, x, y, p, f0=None):
+    """Estimate derivatives of an ODE system rhs with forward differences.
+
+    Returns
+    -------
+    df_dy : ndarray, shape (n, n, m)
+        Derivatives with respect to y. An element (i, j, q) corresponds to
+        d f_i(x_q, y_q) / d (y_q)_j.
+    df_dp : ndarray with shape (n, k, m) or None
+        Derivatives with respect to p. An element (i, j, q) corresponds to
+        d f_i(x_q, y_q, p) / d p_j. If `p` is empty, None is returned.
+    """
+    n, m = y.shape
+    if f0 is None:
+        f0 = fun(x, y, p)
+
+    dtype = y.dtype
+
+    df_dy = np.empty((n, n, m), dtype=dtype)
+    h = EPS**0.5 * (1 + np.abs(y))
+    for i in range(n):
+        y_new = y.copy()
+        y_new[i] += h[i]
+        hi = y_new[i] - y[i]
+        f_new = fun(x, y_new, p)
+        df_dy[:, i, :] = (f_new - f0) / hi
+
+    k = p.shape[0]
+    if k == 0:
+        df_dp = None
+    else:
+        df_dp = np.empty((n, k, m), dtype=dtype)
+        h = EPS**0.5 * (1 + np.abs(p))
+        for i in range(k):
+            p_new = p.copy()
+            p_new[i] += h[i]
+            hi = p_new[i] - p[i]
+            f_new = fun(x, y, p_new)
+            df_dp[:, i, :] = (f_new - f0) / hi
+
+    return df_dy, df_dp
+
+
+def estimate_bc_jac(bc, ya, yb, p, bc0=None):
+    """Estimate derivatives of boundary conditions with forward differences.
+
+    Returns
+    -------
+    dbc_dya : ndarray, shape (n + k, n)
+        Derivatives with respect to ya. An element (i, j) corresponds to
+        d bc_i / d ya_j.
+    dbc_dyb : ndarray, shape (n + k, n)
+        Derivatives with respect to yb. An element (i, j) corresponds to
+        d bc_i / d ya_j.
+    dbc_dp : ndarray with shape (n + k, k) or None
+        Derivatives with respect to p. An element (i, j) corresponds to
+        d bc_i / d p_j. If `p` is empty, None is returned.
+    """
+    n = ya.shape[0]
+    k = p.shape[0]
+
+    if bc0 is None:
+        bc0 = bc(ya, yb, p)
+
+    dtype = ya.dtype
+
+    dbc_dya = np.empty((n, n + k), dtype=dtype)
+    h = EPS**0.5 * (1 + np.abs(ya))
+    for i in range(n):
+        ya_new = ya.copy()
+        ya_new[i] += h[i]
+        hi = ya_new[i] - ya[i]
+        bc_new = bc(ya_new, yb, p)
+        dbc_dya[i] = (bc_new - bc0) / hi
+    dbc_dya = dbc_dya.T
+
+    h = EPS**0.5 * (1 + np.abs(yb))
+    dbc_dyb = np.empty((n, n + k), dtype=dtype)
+    for i in range(n):
+        yb_new = yb.copy()
+        yb_new[i] += h[i]
+        hi = yb_new[i] - yb[i]
+        bc_new = bc(ya, yb_new, p)
+        dbc_dyb[i] = (bc_new - bc0) / hi
+    dbc_dyb = dbc_dyb.T
+
+    if k == 0:
+        dbc_dp = None
+    else:
+        h = EPS**0.5 * (1 + np.abs(p))
+        dbc_dp = np.empty((k, n + k), dtype=dtype)
+        for i in range(k):
+            p_new = p.copy()
+            p_new[i] += h[i]
+            hi = p_new[i] - p[i]
+            bc_new = bc(ya, yb, p_new)
+            dbc_dp[i] = (bc_new - bc0) / hi
+        dbc_dp = dbc_dp.T
+
+    return dbc_dya, dbc_dyb, dbc_dp
+
+
+def compute_jac_indices(n, m, k):
+    """Compute indices for the collocation system Jacobian construction.
+
+    See `construct_global_jac` for the explanation.
+    """
+    i_col = np.repeat(np.arange((m - 1) * n), n)
+    j_col = (np.tile(np.arange(n), n * (m - 1)) +
+             np.repeat(np.arange(m - 1) * n, n**2))
+
+    i_bc = np.repeat(np.arange((m - 1) * n, m * n + k), n)
+    j_bc = np.tile(np.arange(n), n + k)
+
+    i_p_col = np.repeat(np.arange((m - 1) * n), k)
+    j_p_col = np.tile(np.arange(m * n, m * n + k), (m - 1) * n)
+
+    i_p_bc = np.repeat(np.arange((m - 1) * n, m * n + k), k)
+    j_p_bc = np.tile(np.arange(m * n, m * n + k), n + k)
+
+    i = np.hstack((i_col, i_col, i_bc, i_bc, i_p_col, i_p_bc))
+    j = np.hstack((j_col, j_col + n,
+                   j_bc, j_bc + (m - 1) * n,
+                   j_p_col, j_p_bc))
+
+    return i, j
+
+
+def stacked_matmul(a, b):
+    """Stacked matrix multiply: out[i,:,:] = np.dot(a[i,:,:], b[i,:,:]).
+
+    Empirical optimization. Use outer Python loop and BLAS for large
+    matrices, otherwise use a single einsum call.
+    """
+    if a.shape[1] > 50:
+        out = np.empty((a.shape[0], a.shape[1], b.shape[2]))
+        for i in range(a.shape[0]):
+            out[i] = np.dot(a[i], b[i])
+        return out
+    else:
+        return np.einsum('...ij,...jk->...ik', a, b)
+
+
+def construct_global_jac(n, m, k, i_jac, j_jac, h, df_dy, df_dy_middle, df_dp,
+                         df_dp_middle, dbc_dya, dbc_dyb, dbc_dp):
+    """Construct the Jacobian of the collocation system.
+
+    There are n * m + k functions: m - 1 collocations residuals, each
+    containing n components, followed by n + k boundary condition residuals.
+
+    There are n * m + k variables: m vectors of y, each containing n
+    components, followed by k values of vector p.
+
+    For example, let m = 4, n = 2 and k = 1, then the Jacobian will have
+    the following sparsity structure:
+
+        1 1 2 2 0 0 0 0  5
+        1 1 2 2 0 0 0 0  5
+        0 0 1 1 2 2 0 0  5
+        0 0 1 1 2 2 0 0  5
+        0 0 0 0 1 1 2 2  5
+        0 0 0 0 1 1 2 2  5
+
+        3 3 0 0 0 0 4 4  6
+        3 3 0 0 0 0 4 4  6
+        3 3 0 0 0 0 4 4  6
+
+    Zeros denote identically zero values, other values denote different kinds
+    of blocks in the matrix (see below). The blank row indicates the separation
+    of collocation residuals from boundary conditions. And the blank column
+    indicates the separation of y values from p values.
+
+    Refer to [1]_  (p. 306) for the formula of n x n blocks for derivatives
+    of collocation residuals with respect to y.
+
+    Parameters
+    ----------
+    n : int
+        Number of equations in the ODE system.
+    m : int
+        Number of nodes in the mesh.
+    k : int
+        Number of the unknown parameters.
+    i_jac, j_jac : ndarray
+        Row and column indices returned by `compute_jac_indices`. They
+        represent different blocks in the Jacobian matrix in the following
+        order (see the scheme above):
+
+            * 1: m - 1 diagonal n x n blocks for the collocation residuals.
+            * 2: m - 1 off-diagonal n x n blocks for the collocation residuals.
+            * 3 : (n + k) x n block for the dependency of the boundary
+              conditions on ya.
+            * 4: (n + k) x n block for the dependency of the boundary
+              conditions on yb.
+            * 5: (m - 1) * n x k block for the dependency of the collocation
+              residuals on p.
+            * 6: (n + k) x k block for the dependency of the boundary
+              conditions on p.
+
+    df_dy : ndarray, shape (n, n, m)
+        Jacobian of f with respect to y computed at the mesh nodes.
+    df_dy_middle : ndarray, shape (n, n, m - 1)
+        Jacobian of f with respect to y computed at the middle between the
+        mesh nodes.
+    df_dp : ndarray with shape (n, k, m) or None
+        Jacobian of f with respect to p computed at the mesh nodes.
+    df_dp_middle : ndarray with shape (n, k, m - 1) or None
+        Jacobian of f with respect to p computed at the middle between the
+        mesh nodes.
+    dbc_dya, dbc_dyb : ndarray, shape (n, n)
+        Jacobian of bc with respect to ya and yb.
+    dbc_dp : ndarray with shape (n, k) or None
+        Jacobian of bc with respect to p.
+
+    Returns
+    -------
+    J : csc_array, shape (n * m + k, n * m + k)
+        Jacobian of the collocation system in a sparse form.
+
+    References
+    ----------
+    .. [1] J. Kierzenka, L. F. Shampine, "A BVP Solver Based on Residual
+       Control and the Maltab PSE", ACM Trans. Math. Softw., Vol. 27,
+       Number 3, pp. 299-316, 2001.
+    """
+    df_dy = np.transpose(df_dy, (2, 0, 1))
+    df_dy_middle = np.transpose(df_dy_middle, (2, 0, 1))
+
+    h = h[:, np.newaxis, np.newaxis]
+
+    dtype = df_dy.dtype
+
+    # Computing diagonal n x n blocks.
+    dPhi_dy_0 = np.empty((m - 1, n, n), dtype=dtype)
+    dPhi_dy_0[:] = -np.identity(n)
+    dPhi_dy_0 -= h / 6 * (df_dy[:-1] + 2 * df_dy_middle)
+    T = stacked_matmul(df_dy_middle, df_dy[:-1])
+    dPhi_dy_0 -= h**2 / 12 * T
+
+    # Computing off-diagonal n x n blocks.
+    dPhi_dy_1 = np.empty((m - 1, n, n), dtype=dtype)
+    dPhi_dy_1[:] = np.identity(n)
+    dPhi_dy_1 -= h / 6 * (df_dy[1:] + 2 * df_dy_middle)
+    T = stacked_matmul(df_dy_middle, df_dy[1:])
+    dPhi_dy_1 += h**2 / 12 * T
+
+    values = np.hstack((dPhi_dy_0.ravel(), dPhi_dy_1.ravel(), dbc_dya.ravel(),
+                        dbc_dyb.ravel()))
+
+    if k > 0:
+        df_dp = np.transpose(df_dp, (2, 0, 1))
+        df_dp_middle = np.transpose(df_dp_middle, (2, 0, 1))
+        T = stacked_matmul(df_dy_middle, df_dp[:-1] - df_dp[1:])
+        df_dp_middle += 0.125 * h * T
+        dPhi_dp = -h/6 * (df_dp[:-1] + df_dp[1:] + 4 * df_dp_middle)
+        values = np.hstack((values, dPhi_dp.ravel(), dbc_dp.ravel()))
+
+    return csc_array((values, (i_jac, j_jac)))
+
+
+def collocation_fun(fun, y, p, x, h):
+    """Evaluate collocation residuals.
+
+    This function lies in the core of the method. The solution is sought
+    as a cubic C1 continuous spline with derivatives matching the ODE rhs
+    at given nodes `x`. Collocation conditions are formed from the equality
+    of the spline derivatives and rhs of the ODE system in the middle points
+    between nodes.
+
+    Such method is classified to Lobbato IIIA family in ODE literature.
+    Refer to [1]_ for the formula and some discussion.
+
+    Returns
+    -------
+    col_res : ndarray, shape (n, m - 1)
+        Collocation residuals at the middle points of the mesh intervals.
+    y_middle : ndarray, shape (n, m - 1)
+        Values of the cubic spline evaluated at the middle points of the mesh
+        intervals.
+    f : ndarray, shape (n, m)
+        RHS of the ODE system evaluated at the mesh nodes.
+    f_middle : ndarray, shape (n, m - 1)
+        RHS of the ODE system evaluated at the middle points of the mesh
+        intervals (and using `y_middle`).
+
+    References
+    ----------
+    .. [1] J. Kierzenka, L. F. Shampine, "A BVP Solver Based on Residual
+           Control and the Maltab PSE", ACM Trans. Math. Softw., Vol. 27,
+           Number 3, pp. 299-316, 2001.
+    """
+    f = fun(x, y, p)
+    y_middle = (0.5 * (y[:, 1:] + y[:, :-1]) -
+                0.125 * h * (f[:, 1:] - f[:, :-1]))
+    f_middle = fun(x[:-1] + 0.5 * h, y_middle, p)
+    col_res = y[:, 1:] - y[:, :-1] - h / 6 * (f[:, :-1] + f[:, 1:] +
+                                              4 * f_middle)
+
+    return col_res, y_middle, f, f_middle
+
+
+def prepare_sys(n, m, k, fun, bc, fun_jac, bc_jac, x, h):
+    """Create the function and the Jacobian for the collocation system."""
+    x_middle = x[:-1] + 0.5 * h
+    i_jac, j_jac = compute_jac_indices(n, m, k)
+
+    def col_fun(y, p):
+        return collocation_fun(fun, y, p, x, h)
+
+    def sys_jac(y, p, y_middle, f, f_middle, bc0):
+        if fun_jac is None:
+            df_dy, df_dp = estimate_fun_jac(fun, x, y, p, f)
+            df_dy_middle, df_dp_middle = estimate_fun_jac(
+                fun, x_middle, y_middle, p, f_middle)
+        else:
+            df_dy, df_dp = fun_jac(x, y, p)
+            df_dy_middle, df_dp_middle = fun_jac(x_middle, y_middle, p)
+
+        if bc_jac is None:
+            dbc_dya, dbc_dyb, dbc_dp = estimate_bc_jac(bc, y[:, 0], y[:, -1],
+                                                       p, bc0)
+        else:
+            dbc_dya, dbc_dyb, dbc_dp = bc_jac(y[:, 0], y[:, -1], p)
+
+        return construct_global_jac(n, m, k, i_jac, j_jac, h, df_dy,
+                                    df_dy_middle, df_dp, df_dp_middle, dbc_dya,
+                                    dbc_dyb, dbc_dp)
+
+    return col_fun, sys_jac
+
+
+def solve_newton(n, m, h, col_fun, bc, jac, y, p, B, bvp_tol, bc_tol):
+    """Solve the nonlinear collocation system by a Newton method.
+
+    This is a simple Newton method with a backtracking line search. As
+    advised in [1]_, an affine-invariant criterion function F = ||J^-1 r||^2
+    is used, where J is the Jacobian matrix at the current iteration and r is
+    the vector or collocation residuals (values of the system lhs).
+
+    The method alters between full Newton iterations and the fixed-Jacobian
+    iterations based
+
+    There are other tricks proposed in [1]_, but they are not used as they
+    don't seem to improve anything significantly, and even break the
+    convergence on some test problems I tried.
+
+    All important parameters of the algorithm are defined inside the function.
+
+    Parameters
+    ----------
+    n : int
+        Number of equations in the ODE system.
+    m : int
+        Number of nodes in the mesh.
+    h : ndarray, shape (m-1,)
+        Mesh intervals.
+    col_fun : callable
+        Function computing collocation residuals.
+    bc : callable
+        Function computing boundary condition residuals.
+    jac : callable
+        Function computing the Jacobian of the whole system (including
+        collocation and boundary condition residuals). It must return
+        scipy.sparse in CSC format ready for use with `scipy.sparse.linalg.splu`.
+    y : ndarray, shape (n, m)
+        Initial guess for the function values at the mesh nodes.
+    p : ndarray, shape (k,)
+        Initial guess for the unknown parameters.
+    B : ndarray with shape (n, n) or None
+        Matrix to force the S y(a) = 0 condition for a problems with the
+        singular term. If None, the singular term is assumed to be absent.
+    bvp_tol : float
+        Tolerance to which we want to solve a BVP.
+    bc_tol : float
+        Tolerance to which we want to satisfy the boundary conditions.
+
+    Returns
+    -------
+    y : ndarray, shape (n, m)
+        Final iterate for the function values at the mesh nodes.
+    p : ndarray, shape (k,)
+        Final iterate for the unknown parameters.
+    singular : bool
+        True, if the LU decomposition failed because Jacobian turned out
+        to be singular.
+
+    References
+    ----------
+    .. [1]  U. Ascher, R. Mattheij and R. Russell "Numerical Solution of
+       Boundary Value Problems for Ordinary Differential Equations",
+       Philidelphia, PA: Society for Industrial and Applied Mathematics,
+       1995.
+    """
+    # We know that the solution residuals at the middle points of the mesh
+    # are connected with collocation residuals  r_middle = 1.5 * col_res / h.
+    # As our BVP solver tries to decrease relative residuals below a certain
+    # tolerance, it seems reasonable to terminated Newton iterations by
+    # comparison of r_middle / (1 + np.abs(f_middle)) with a certain threshold,
+    # which we choose to be 1.5 orders lower than the BVP tolerance. We rewrite
+    # the condition as col_res < tol_r * (1 + np.abs(f_middle)), then tol_r
+    # should be computed as follows:
+    tol_r = 2/3 * h * 5e-2 * bvp_tol
+
+    # Maximum allowed number of Jacobian evaluation and factorization, in
+    # other words, the maximum number of full Newton iterations. A small value
+    # is recommended in the literature.
+    max_njev = 4
+
+    # Maximum number of iterations, considering that some of them can be
+    # performed with the fixed Jacobian. In theory, such iterations are cheap,
+    # but it's not that simple in Python.
+    max_iter = 8
+
+    # Minimum relative improvement of the criterion function to accept the
+    # step (Armijo constant).
+    sigma = 0.2
+
+    # Step size decrease factor for backtracking.
+    tau = 0.5
+
+    # Maximum number of backtracking steps, the minimum step is then
+    # tau ** n_trial.
+    n_trial = 4
+
+    col_res, y_middle, f, f_middle = col_fun(y, p)
+    bc_res = bc(y[:, 0], y[:, -1], p)
+    res = np.hstack((col_res.ravel(order='F'), bc_res))
+
+    njev = 0
+    singular = False
+    recompute_jac = True
+    for iteration in range(max_iter):
+        if recompute_jac:
+            J = jac(y, p, y_middle, f, f_middle, bc_res)
+            njev += 1
+            try:
+                LU = splu(J)
+            except RuntimeError:
+                singular = True
+                break
+
+            step = LU.solve(res)
+            cost = np.dot(step, step)
+
+        y_step = step[:m * n].reshape((n, m), order='F')
+        p_step = step[m * n:]
+
+        alpha = 1
+        for trial in range(n_trial + 1):
+            y_new = y - alpha * y_step
+            if B is not None:
+                y_new[:, 0] = np.dot(B, y_new[:, 0])
+            p_new = p - alpha * p_step
+
+            col_res, y_middle, f, f_middle = col_fun(y_new, p_new)
+            bc_res = bc(y_new[:, 0], y_new[:, -1], p_new)
+            res = np.hstack((col_res.ravel(order='F'), bc_res))
+
+            step_new = LU.solve(res)
+            cost_new = np.dot(step_new, step_new)
+            if cost_new < (1 - 2 * alpha * sigma) * cost:
+                break
+
+            if trial < n_trial:
+                alpha *= tau
+
+        y = y_new
+        p = p_new
+
+        if njev == max_njev:
+            break
+
+        if (np.all(np.abs(col_res) < tol_r * (1 + np.abs(f_middle))) and
+                np.all(np.abs(bc_res) < bc_tol)):
+            break
+
+        # If the full step was taken, then we are going to continue with
+        # the same Jacobian. This is the approach of BVP_SOLVER.
+        if alpha == 1:
+            step = step_new
+            cost = cost_new
+            recompute_jac = False
+        else:
+            recompute_jac = True
+
+    return y, p, singular
+
+
+def print_iteration_header():
+    print(f"{'Iteration':^15}{'Max residual':^15}{'Max BC residual':^15}"
+          f"{'Total nodes':^15}{'Nodes added':^15}")
+
+
+def print_iteration_progress(iteration, residual, bc_residual, total_nodes,
+                             nodes_added):
+    print(f"{iteration:^15}{residual:^15.2e}{bc_residual:^15.2e}"
+          f"{total_nodes:^15}{nodes_added:^15}")
+
+
+class BVPResult(OptimizeResult):
+    pass
+
+
+TERMINATION_MESSAGES = {
+    0: "The algorithm converged to the desired accuracy.",
+    1: "The maximum number of mesh nodes is exceeded.",
+    2: "A singular Jacobian encountered when solving the collocation system.",
+    3: "The solver was unable to satisfy boundary conditions tolerance on iteration 10."
+}
+
+
+def estimate_rms_residuals(fun, sol, x, h, p, r_middle, f_middle):
+    """Estimate rms values of collocation residuals using Lobatto quadrature.
+
+    The residuals are defined as the difference between the derivatives of
+    our solution and rhs of the ODE system. We use relative residuals, i.e.,
+    normalized by 1 + np.abs(f). RMS values are computed as sqrt from the
+    normalized integrals of the squared relative residuals over each interval.
+    Integrals are estimated using 5-point Lobatto quadrature [1]_, we use the
+    fact that residuals at the mesh nodes are identically zero.
+
+    In [2] they don't normalize integrals by interval lengths, which gives
+    a higher rate of convergence of the residuals by the factor of h**0.5.
+    I chose to do such normalization for an ease of interpretation of return
+    values as RMS estimates.
+
+    Returns
+    -------
+    rms_res : ndarray, shape (m - 1,)
+        Estimated rms values of the relative residuals over each interval.
+
+    References
+    ----------
+    .. [1] http://mathworld.wolfram.com/LobattoQuadrature.html
+    .. [2] J. Kierzenka, L. F. Shampine, "A BVP Solver Based on Residual
+       Control and the Maltab PSE", ACM Trans. Math. Softw., Vol. 27,
+       Number 3, pp. 299-316, 2001.
+    """
+    x_middle = x[:-1] + 0.5 * h
+    s = 0.5 * h * (3/7)**0.5
+    x1 = x_middle + s
+    x2 = x_middle - s
+    y1 = sol(x1)
+    y2 = sol(x2)
+    y1_prime = sol(x1, 1)
+    y2_prime = sol(x2, 1)
+    f1 = fun(x1, y1, p)
+    f2 = fun(x2, y2, p)
+    r1 = y1_prime - f1
+    r2 = y2_prime - f2
+
+    r_middle /= 1 + np.abs(f_middle)
+    r1 /= 1 + np.abs(f1)
+    r2 /= 1 + np.abs(f2)
+
+    r1 = np.sum(np.real(r1 * np.conj(r1)), axis=0)
+    r2 = np.sum(np.real(r2 * np.conj(r2)), axis=0)
+    r_middle = np.sum(np.real(r_middle * np.conj(r_middle)), axis=0)
+
+    return (0.5 * (32 / 45 * r_middle + 49 / 90 * (r1 + r2))) ** 0.5
+
+
+def create_spline(y, yp, x, h):
+    """Create a cubic spline given values and derivatives.
+
+    Formulas for the coefficients are taken from interpolate.CubicSpline.
+
+    Returns
+    -------
+    sol : PPoly
+        Constructed spline as a PPoly instance.
+    """
+    from scipy.interpolate import PPoly
+
+    n, m = y.shape
+    c = np.empty((4, n, m - 1), dtype=y.dtype)
+    slope = (y[:, 1:] - y[:, :-1]) / h
+    t = (yp[:, :-1] + yp[:, 1:] - 2 * slope) / h
+    c[0] = t / h
+    c[1] = (slope - yp[:, :-1]) / h - t
+    c[2] = yp[:, :-1]
+    c[3] = y[:, :-1]
+    c = np.moveaxis(c, 1, 0)
+
+    return PPoly(c, x, extrapolate=True, axis=1)
+
+
+def modify_mesh(x, insert_1, insert_2):
+    """Insert nodes into a mesh.
+
+    Nodes removal logic is not established, its impact on the solver is
+    presumably negligible. So, only insertion is done in this function.
+
+    Parameters
+    ----------
+    x : ndarray, shape (m,)
+        Mesh nodes.
+    insert_1 : ndarray
+        Intervals to each insert 1 new node in the middle.
+    insert_2 : ndarray
+        Intervals to each insert 2 new nodes, such that divide an interval
+        into 3 equal parts.
+
+    Returns
+    -------
+    x_new : ndarray
+        New mesh nodes.
+
+    Notes
+    -----
+    `insert_1` and `insert_2` should not have common values.
+    """
+    # Because np.insert implementation apparently varies with a version of
+    # NumPy, we use a simple and reliable approach with sorting.
+    return np.sort(np.hstack((
+        x,
+        0.5 * (x[insert_1] + x[insert_1 + 1]),
+        (2 * x[insert_2] + x[insert_2 + 1]) / 3,
+        (x[insert_2] + 2 * x[insert_2 + 1]) / 3
+    )))
+
+
+def wrap_functions(fun, bc, fun_jac, bc_jac, k, a, S, D, dtype):
+    """Wrap functions for unified usage in the solver."""
+    if fun_jac is None:
+        fun_jac_wrapped = None
+
+    if bc_jac is None:
+        bc_jac_wrapped = None
+
+    if k == 0:
+        def fun_p(x, y, _):
+            return np.asarray(fun(x, y), dtype)
+
+        def bc_wrapped(ya, yb, _):
+            return np.asarray(bc(ya, yb), dtype)
+
+        if fun_jac is not None:
+            def fun_jac_p(x, y, _):
+                return np.asarray(fun_jac(x, y), dtype), None
+
+        if bc_jac is not None:
+            def bc_jac_wrapped(ya, yb, _):
+                dbc_dya, dbc_dyb = bc_jac(ya, yb)
+                return (np.asarray(dbc_dya, dtype),
+                        np.asarray(dbc_dyb, dtype), None)
+    else:
+        def fun_p(x, y, p):
+            return np.asarray(fun(x, y, p), dtype)
+
+        def bc_wrapped(x, y, p):
+            return np.asarray(bc(x, y, p), dtype)
+
+        if fun_jac is not None:
+            def fun_jac_p(x, y, p):
+                df_dy, df_dp = fun_jac(x, y, p)
+                return np.asarray(df_dy, dtype), np.asarray(df_dp, dtype)
+
+        if bc_jac is not None:
+            def bc_jac_wrapped(ya, yb, p):
+                dbc_dya, dbc_dyb, dbc_dp = bc_jac(ya, yb, p)
+                return (np.asarray(dbc_dya, dtype), np.asarray(dbc_dyb, dtype),
+                        np.asarray(dbc_dp, dtype))
+
+    if S is None:
+        fun_wrapped = fun_p
+    else:
+        def fun_wrapped(x, y, p):
+            f = fun_p(x, y, p)
+            if x[0] == a:
+                f[:, 0] = np.dot(D, f[:, 0])
+                f[:, 1:] += np.dot(S, y[:, 1:]) / (x[1:] - a)
+            else:
+                f += np.dot(S, y) / (x - a)
+            return f
+
+    if fun_jac is not None:
+        if S is None:
+            fun_jac_wrapped = fun_jac_p
+        else:
+            Sr = S[:, :, np.newaxis]
+
+            def fun_jac_wrapped(x, y, p):
+                df_dy, df_dp = fun_jac_p(x, y, p)
+                if x[0] == a:
+                    df_dy[:, :, 0] = np.dot(D, df_dy[:, :, 0])
+                    df_dy[:, :, 1:] += Sr / (x[1:] - a)
+                else:
+                    df_dy += Sr / (x - a)
+
+                return df_dy, df_dp
+
+    return fun_wrapped, bc_wrapped, fun_jac_wrapped, bc_jac_wrapped
+
+
+@xp_capabilities(np_only=True)
+def solve_bvp(fun, bc, x, y, p=None, S=None, fun_jac=None, bc_jac=None,
+              tol=1e-3, max_nodes=1000, verbose=0, bc_tol=None):
+    """Solve a boundary value problem for a system of ODEs.
+
+    This function numerically solves a first order system of ODEs subject to
+    two-point boundary conditions::
+
+        dy / dx = f(x, y, p) + S * y / (x - a), a <= x <= b
+        bc(y(a), y(b), p) = 0
+
+    Here x is a 1-D independent variable, y(x) is an n-D
+    vector-valued function and p is a k-D vector of unknown
+    parameters which is to be found along with y(x). For the problem to be
+    determined, there must be n + k boundary conditions, i.e., bc must be an
+    (n + k)-D function.
+
+    The last singular term on the right-hand side of the system is optional.
+    It is defined by an n-by-n matrix S, such that the solution must satisfy
+    S y(a) = 0. This condition will be forced during iterations, so it must not
+    contradict boundary conditions. See [2]_ for the explanation how this term
+    is handled when solving BVPs numerically.
+
+    Problems in a complex domain can be solved as well. In this case, y and p
+    are considered to be complex, and f and bc are assumed to be complex-valued
+    functions, but x stays real. Note that f and bc must be complex
+    differentiable (satisfy Cauchy-Riemann equations [4]_), otherwise you
+    should rewrite your problem for real and imaginary parts separately. To
+    solve a problem in a complex domain, pass an initial guess for y with a
+    complex data type (see below).
+
+    Parameters
+    ----------
+    fun : callable
+        Right-hand side of the system. The calling signature is ``fun(x, y)``,
+        or ``fun(x, y, p)`` if parameters are present. All arguments are
+        ndarray: ``x`` with shape (m,), ``y`` with shape (n, m), meaning that
+        ``y[:, i]`` corresponds to ``x[i]``, and ``p`` with shape (k,). The
+        return value must be an array with shape (n, m) and with the same
+        layout as ``y``.
+    bc : callable
+        Function evaluating residuals of the boundary conditions. The calling
+        signature is ``bc(ya, yb)``, or ``bc(ya, yb, p)`` if parameters are
+        present. All arguments are ndarray: ``ya`` and ``yb`` with shape (n,),
+        and ``p`` with shape (k,). The return value must be an array with
+        shape (n + k,).
+        The order of the returned residuals does not matter, as `solve_bvp`
+        attempts to drive all residuals to zero.
+    x : array_like, shape (m,)
+        Initial mesh. Must be a strictly increasing sequence of real numbers
+        with ``x[0]=a`` and ``x[-1]=b``.
+    y : array_like, shape (n, m)
+        Initial guess for the function values at the mesh nodes, ith column
+        corresponds to ``x[i]``. For problems in a complex domain pass `y`
+        with a complex data type (even if the initial guess is purely real).
+    p : array_like with shape (k,) or None, optional
+        Initial guess for the unknown parameters. If None (default), it is
+        assumed that the problem doesn't depend on any parameters.
+    S : array_like with shape (n, n) or None
+        Matrix defining the singular term. If None (default), the problem is
+        solved without the singular term.
+    fun_jac : callable or None, optional
+        Function computing derivatives of f with respect to y and p. The
+        calling signature is ``fun_jac(x, y)``, or ``fun_jac(x, y, p)`` if
+        parameters are present. The return must contain 1 or 2 elements in the
+        following order:
+
+        * df_dy : array_like with shape ``(n, n, m)``, where an element
+          ``(i, j, q)`` equals to ``d f_i(x_q, y_q, p) / d (y_q)_j``.
+        * df_dp : array_like with shape ``(n, k, m)``, where an element
+          ``(i, j, q)`` equals to ``d f_i(x_q, y_q, p) / d p_j``.
+
+        Here q numbers nodes at which x and y are defined, whereas i and j
+        number vector components. If the problem is solved without unknown
+        parameters, df_dp should not be returned.
+
+        If `fun_jac` is None (default), the derivatives will be estimated
+        by the forward finite differences.
+    bc_jac : callable or None, optional
+        Function computing derivatives of bc with respect to ya, yb, and p.
+        The calling signature is ``bc_jac(ya, yb)``, or ``bc_jac(ya, yb, p)``
+        if parameters are present. The return must contain 2 or 3 elements in
+        the following order:
+
+        * ``dbc_dya`` : array_like with shape ``(n, n)``, where an element ``(i, j)``
+          equals to ``d bc_i(ya, yb, p) / d ya_j``.
+        * ``dbc_dyb`` : array_like with shape ``(n, n)``, where an element ``(i, j)``
+          equals to ``d bc_i(ya, yb, p) / d yb_j``.
+        * ``dbc_dp`` : array_like with shape ``(n, k)``, where an element ``(i, j)``
+          equals to ``d bc_i(ya, yb, p) / d p_j``.
+
+        If the problem is solved without unknown parameters, dbc_dp should not
+        be returned.
+
+        If `bc_jac` is None (default), the derivatives will be estimated by
+        the forward finite differences.
+    tol : float, optional
+        Desired tolerance of the solution. If we define ``r = y' - f(x, y)``,
+        where y is the found solution, then the solver tries to achieve on each
+        mesh interval ``norm(r / (1 + abs(f)) < tol``, where ``norm`` is
+        estimated in a root mean squared sense (using a numerical quadrature
+        formula). Default is 1e-3.
+    max_nodes : int, optional
+        Maximum allowed number of the mesh nodes. If exceeded, the algorithm
+        terminates. Default is 1000.
+    verbose : {0, 1, 2}, optional
+        Level of algorithm's verbosity:
+
+        * 0 (default) : work silently.
+        * 1 : display a termination report.
+        * 2 : display progress during iterations.
+    bc_tol : float, optional
+        Desired absolute tolerance for the boundary condition residuals: `bc`
+        value should satisfy ``abs(bc) < bc_tol`` component-wise.
+        Equals to `tol` by default. Up to 10 iterations are allowed to achieve this
+        tolerance.
+
+    Returns
+    -------
+    result : BVPResult
+        Bunch object with the following fields defined:
+
+        sol : PPoly
+            Found solution for y as `scipy.interpolate.PPoly` instance, a C1
+            continuous cubic spline.
+        p : ndarray or None, shape (k,)
+            Found parameters. None, if the parameters were not present in the
+            problem.
+        x : ndarray, shape (m,)
+            Nodes of the final mesh.
+        y : ndarray, shape (n, m)
+            Solution values at the mesh nodes.
+        yp : ndarray, shape (n, m)
+            Solution derivatives at the mesh nodes.
+        rms_residuals : ndarray, shape (m - 1,)
+            RMS values of the relative residuals over each mesh interval (see the
+            description of `tol` parameter).
+        niter : int
+            Number of completed iterations.
+        status : int
+            Reason for algorithm termination:
+
+            * 0: The algorithm converged to the desired accuracy.
+            * 1: The maximum number of mesh nodes is exceeded.
+            * 2: A singular Jacobian encountered when solving the collocation system.
+
+        message : str
+            Verbal description of the termination reason.
+        success : bool
+            True if the algorithm converged to the desired accuracy (``status=0``).
+
+    Notes
+    -----
+    This function implements a 4th order collocation algorithm with the
+    control of residuals similar to [1]_. A collocation system is solved
+    by a damped Newton method with an affine-invariant criterion function as
+    described in [3]_.
+
+    Note that in [1]_  integral residuals are defined without normalization
+    by interval lengths. So, their definition is different by a multiplier of
+    h**0.5 (h is an interval length) from the definition used here.
+
+    .. versionadded:: 0.18.0
+
+    References
+    ----------
+    .. [1] J. Kierzenka, L. F. Shampine, "A BVP Solver Based on Residual
+           Control and the Maltab PSE", ACM Trans. Math. Softw., Vol. 27,
+           Number 3, pp. 299-316, 2001.
+    .. [2] L.F. Shampine, P. H. Muir and H. Xu, "A User-Friendly Fortran BVP
+           Solver", J. Numer. Anal., Ind. Appl. Math. (JNAIAM), Vol. 1, 
+           Number 2, pp. 201-217, 2006.
+    .. [3] U. Ascher, R. Mattheij and R. Russell "Numerical Solution of
+           Boundary Value Problems for Ordinary Differential Equations",
+           Philidelphia, PA: Society for Industrial and Applied Mathematics,
+           1995.
+           :doi:`10.1137/1.9781611971231`
+    .. [4] `Cauchy-Riemann equations
+            `_ on
+            Wikipedia.
+
+    Examples
+    --------
+    In the first example, we solve Bratu's problem::
+
+        y'' + k * exp(y) = 0
+        y(0) = y(1) = 0
+
+    for k = 1.
+
+    We rewrite the equation as a first-order system and implement its
+    right-hand side evaluation::
+
+        y1' = y2
+        y2' = -exp(y1)
+
+    >>> import numpy as np
+    >>> def fun(x, y):
+    ...     return np.vstack((y[1], -np.exp(y[0])))
+
+    Implement evaluation of the boundary condition residuals:
+
+    >>> def bc(ya, yb):
+    ...     return np.array([ya[0], yb[0]])
+
+    Define the initial mesh with 5 nodes:
+
+    >>> x = np.linspace(0, 1, 5)
+
+    This problem is known to have two solutions. To obtain both of them, we
+    use two different initial guesses for y. We denote them by subscripts
+    a and b.
+
+    >>> y_a = np.zeros((2, x.size))
+    >>> y_b = np.zeros((2, x.size))
+    >>> y_b[0] = 3
+
+    Now we are ready to run the solver.
+
+    >>> from scipy.integrate import solve_bvp
+    >>> res_a = solve_bvp(fun, bc, x, y_a)
+    >>> res_b = solve_bvp(fun, bc, x, y_b)
+
+    Let's plot the two found solutions. We take an advantage of having the
+    solution in a spline form to produce a smooth plot.
+
+    >>> x_plot = np.linspace(0, 1, 100)
+    >>> y_plot_a = res_a.sol(x_plot)[0]
+    >>> y_plot_b = res_b.sol(x_plot)[0]
+    >>> import matplotlib.pyplot as plt
+    >>> plt.plot(x_plot, y_plot_a, label='y_a')
+    >>> plt.plot(x_plot, y_plot_b, label='y_b')
+    >>> plt.legend()
+    >>> plt.xlabel("x")
+    >>> plt.ylabel("y")
+    >>> plt.show()
+
+    We see that the two solutions have similar shape, but differ in scale
+    significantly.
+
+    In the second example, we solve a simple Sturm-Liouville problem::
+
+        y'' + k**2 * y = 0
+        y(0) = y(1) = 0
+
+    It is known that a non-trivial solution y = A * sin(k * x) is possible for
+    k = pi * n, where n is an integer. To establish the normalization constant
+    A = 1 we add a boundary condition::
+
+        y'(0) = k
+
+    Again, we rewrite our equation as a first-order system and implement its
+    right-hand side evaluation::
+
+        y1' = y2
+        y2' = -k**2 * y1
+
+    >>> def fun(x, y, p):
+    ...     k = p[0]
+    ...     return np.vstack((y[1], -k**2 * y[0]))
+
+    Note that parameters p are passed as a vector (with one element in our
+    case).
+
+    Implement the boundary conditions:
+
+    >>> def bc(ya, yb, p):
+    ...     k = p[0]
+    ...     return np.array([ya[0], yb[0], ya[1] - k])
+
+    Set up the initial mesh and guess for y. We aim to find the solution for
+    k = 2 * pi, to achieve that we set values of y to approximately follow
+    sin(2 * pi * x):
+
+    >>> x = np.linspace(0, 1, 5)
+    >>> y = np.zeros((2, x.size))
+    >>> y[0, 1] = 1
+    >>> y[0, 3] = -1
+
+    Run the solver with 6 as an initial guess for k.
+
+    >>> sol = solve_bvp(fun, bc, x, y, p=[6])
+
+    We see that the found k is approximately correct:
+
+    >>> sol.p[0]
+    6.28329460046
+
+    And, finally, plot the solution to see the anticipated sinusoid:
+
+    >>> x_plot = np.linspace(0, 1, 100)
+    >>> y_plot = sol.sol(x_plot)[0]
+    >>> plt.plot(x_plot, y_plot)
+    >>> plt.xlabel("x")
+    >>> plt.ylabel("y")
+    >>> plt.show()
+    """
+    x = np.asarray(x, dtype=float)
+    if x.ndim != 1:
+        raise ValueError("`x` must be 1 dimensional.")
+    h = np.diff(x)
+    if np.any(h <= 0):
+        raise ValueError("`x` must be strictly increasing.")
+    a = x[0]
+
+    y = np.asarray(y)
+    if np.issubdtype(y.dtype, np.complexfloating):
+        dtype = complex
+    else:
+        dtype = float
+    y = y.astype(dtype, copy=False)
+
+    if y.ndim != 2:
+        raise ValueError("`y` must be 2 dimensional.")
+    if y.shape[1] != x.shape[0]:
+        raise ValueError(f"`y` is expected to have {x.shape[0]} columns, but actually "
+                         f"has {y.shape[1]}.")
+
+    if p is None:
+        p = np.array([])
+    else:
+        p = np.asarray(p, dtype=dtype)
+    if p.ndim != 1:
+        raise ValueError("`p` must be 1 dimensional.")
+
+    if tol < 100 * EPS:
+        warn(f"`tol` is too low, setting to {100 * EPS:.2e}", stacklevel=2)
+        tol = 100 * EPS
+
+    if verbose not in [0, 1, 2]:
+        raise ValueError("`verbose` must be in [0, 1, 2].")
+
+    n = y.shape[0]
+    k = p.shape[0]
+
+    if S is not None:
+        S = np.asarray(S, dtype=dtype)
+        if S.shape != (n, n):
+            raise ValueError(f"`S` is expected to have shape {(n, n)}, "
+                             f"but actually has {S.shape}")
+
+        # Compute I - S^+ S to impose necessary boundary conditions.
+        B = np.identity(n) - np.dot(pinv(S), S)
+
+        y[:, 0] = np.dot(B, y[:, 0])
+
+        # Compute (I - S)^+ to correct derivatives at x=a.
+        D = pinv(np.identity(n) - S)
+    else:
+        B = None
+        D = None
+
+    if bc_tol is None:
+        bc_tol = tol
+
+    # Maximum number of iterations
+    max_iteration = 10
+
+    fun_wrapped, bc_wrapped, fun_jac_wrapped, bc_jac_wrapped = wrap_functions(
+        fun, bc, fun_jac, bc_jac, k, a, S, D, dtype)
+
+    f = fun_wrapped(x, y, p)
+    if f.shape != y.shape:
+        raise ValueError(f"`fun` return is expected to have shape {y.shape}, "
+                         f"but actually has {f.shape}.")
+
+    bc_res = bc_wrapped(y[:, 0], y[:, -1], p)
+    if bc_res.shape != (n + k,):
+        raise ValueError(f"`bc` return is expected to have shape {(n + k,)}, "
+                         f"but actually has {bc_res.shape}.")
+
+    status = 0
+    iteration = 0
+    if verbose == 2:
+        print_iteration_header()
+
+    while True:
+        m = x.shape[0]
+
+        col_fun, jac_sys = prepare_sys(n, m, k, fun_wrapped, bc_wrapped,
+                                       fun_jac_wrapped, bc_jac_wrapped, x, h)
+        y, p, singular = solve_newton(n, m, h, col_fun, bc_wrapped, jac_sys,
+                                      y, p, B, tol, bc_tol)
+        iteration += 1
+
+        col_res, y_middle, f, f_middle = collocation_fun(fun_wrapped, y,
+                                                         p, x, h)
+        bc_res = bc_wrapped(y[:, 0], y[:, -1], p)
+        max_bc_res = np.max(abs(bc_res))
+
+        # This relation is not trivial, but can be verified.
+        r_middle = 1.5 * col_res / h
+        sol = create_spline(y, f, x, h)
+        rms_res = estimate_rms_residuals(fun_wrapped, sol, x, h, p,
+                                         r_middle, f_middle)
+        max_rms_res = np.max(rms_res)
+
+        if singular:
+            status = 2
+            break
+
+        insert_1, = np.nonzero((rms_res > tol) & (rms_res < 100 * tol))
+        insert_2, = np.nonzero(rms_res >= 100 * tol)
+        nodes_added = insert_1.shape[0] + 2 * insert_2.shape[0]
+
+        if m + nodes_added > max_nodes:
+            status = 1
+            if verbose == 2:
+                nodes_added = f"({nodes_added})"
+                print_iteration_progress(iteration, max_rms_res, max_bc_res,
+                                         m, nodes_added)
+            break
+
+        if verbose == 2:
+            print_iteration_progress(iteration, max_rms_res, max_bc_res, m,
+                                     nodes_added)
+
+        if nodes_added > 0:
+            x = modify_mesh(x, insert_1, insert_2)
+            h = np.diff(x)
+            y = sol(x)
+        elif max_bc_res <= bc_tol:
+            status = 0
+            break
+        elif iteration >= max_iteration:
+            status = 3
+            break
+
+    if verbose > 0:
+        if status == 0:
+            print(f"Solved in {iteration} iterations, number of nodes {x.shape[0]}. \n"
+                  f"Maximum relative residual: {max_rms_res:.2e} \n"
+                  f"Maximum boundary residual: {max_bc_res:.2e}")
+        elif status == 1:
+            print(f"Number of nodes is exceeded after iteration {iteration}. \n"
+                  f"Maximum relative residual: {max_rms_res:.2e} \n"
+                  f"Maximum boundary residual: {max_bc_res:.2e}")
+        elif status == 2:
+            print("Singular Jacobian encountered when solving the collocation "
+                  f"system on iteration {iteration}. \n"
+                  f"Maximum relative residual: {max_rms_res:.2e} \n"
+                  f"Maximum boundary residual: {max_bc_res:.2e}")
+        elif status == 3:
+            print("The solver was unable to satisfy boundary conditions "
+                  f"tolerance on iteration {iteration}. \n"
+                  f"Maximum relative residual: {max_rms_res:.2e} \n"
+                  f"Maximum boundary residual: {max_bc_res:.2e}")
+
+    if p.size == 0:
+        p = None
+
+    return BVPResult(sol=sol, p=p, x=x, y=y, yp=f, rms_residuals=rms_res,
+                     niter=iteration, status=status,
+                     message=TERMINATION_MESSAGES[status], success=status == 0)
diff --git a/.venv/lib/python3.12/site-packages/scipy/integrate/_cubature.py b/.venv/lib/python3.12/site-packages/scipy/integrate/_cubature.py
new file mode 100644
index 0000000000000000000000000000000000000000..3ad4a11e4aff0d58a0bf56eedeefca1478c537af
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/integrate/_cubature.py
@@ -0,0 +1,731 @@
+import math
+import heapq
+import itertools
+
+from dataclasses import dataclass, field
+from types import ModuleType
+from typing import Any
+
+from scipy._lib._array_api import (
+    array_namespace,
+    xp_size,
+    xp_copy,
+    xp_promote,
+    xp_capabilities
+)
+from scipy._lib._util import MapWrapper
+
+from scipy.integrate._rules import (
+    ProductNestedFixed,
+    GaussKronrodQuadrature,
+    GenzMalikCubature,
+)
+from scipy.integrate._rules._base import _split_subregion
+
+__all__ = ['cubature']
+
+type Array = Any  # To be changed to an array-api-typing Protocol later
+
+
+@dataclass
+class CubatureRegion:
+    estimate: Array
+    error: Array
+    a: Array
+    b: Array
+    _xp: ModuleType = field(repr=False)
+
+    def __lt__(self, other):
+        # Consider regions with higher error estimates as being "less than" regions with
+        # lower order estimates, so that regions with high error estimates are placed at
+        # the top of the heap.
+
+        this_err = self._xp.max(self._xp.abs(self.error))
+        other_err = self._xp.max(self._xp.abs(other.error))
+
+        return this_err > other_err
+
+
+@dataclass
+class CubatureResult:
+    estimate: Array
+    error: Array
+    status: str
+    regions: list[CubatureRegion]
+    subdivisions: int
+    atol: float
+    rtol: float
+
+
+@xp_capabilities(allow_dask_compute=True, jax_jit=False)
+def cubature(f, a, b, *, rule="gk21", rtol=1e-8, atol=0, max_subdivisions=10000,
+             args=(), workers=1, points=None):
+    r"""
+    Adaptive cubature of multidimensional array-valued function.
+
+    Given an arbitrary integration rule, this function returns an estimate of the
+    integral to the requested tolerance over the region defined by the arrays `a` and
+    `b` specifying the corners of a hypercube.
+
+    Convergence is not guaranteed for all integrals.
+
+    Parameters
+    ----------
+    f : callable
+        Function to integrate. `f` must have the signature::
+
+            f(x : ndarray, *args) -> ndarray
+
+        `f` should accept arrays ``x`` of shape::
+
+            (npoints, ndim)
+
+        and output arrays of shape::
+
+            (npoints, output_dim_1, ..., output_dim_n)
+
+        In this case, `cubature` will return arrays of shape::
+
+            (output_dim_1, ..., output_dim_n)
+    a, b : array_like
+        Lower and upper limits of integration as 1D arrays specifying the left and right
+        endpoints of the intervals being integrated over. Limits can be infinite.
+    rule : str, optional
+        Rule used to estimate the integral. If passing a string, the options are
+        "gauss-kronrod" (21 node), or "genz-malik" (degree 7). If a rule like
+        "gauss-kronrod" is specified for an ``n``-dim integrand, the corresponding
+        Cartesian product rule is used. "gk21", "gk15" are also supported for
+        compatibility with `quad_vec`. See Notes.
+    rtol, atol : float, optional
+        Relative and absolute tolerances. Iterations are performed until the error is
+        estimated to be less than ``atol + rtol * abs(est)``. Here `rtol` controls
+        relative accuracy (number of correct digits), while `atol` controls absolute
+        accuracy (number of correct decimal places). To achieve the desired `rtol`, set
+        `atol` to be smaller than the smallest value that can be expected from
+        ``rtol * abs(y)`` so that `rtol` dominates the allowable error. If `atol` is
+        larger than ``rtol * abs(y)`` the number of correct digits is not guaranteed.
+        Conversely, to achieve the desired `atol`, set `rtol` such that
+        ``rtol * abs(y)`` is always smaller than `atol`. Default values are 1e-8 for
+        `rtol` and 0 for `atol`.
+    max_subdivisions : int, optional
+        Upper bound on the number of subdivisions to perform. Default is 10,000.
+    args : tuple, optional
+        Additional positional args passed to `f`, if any.
+    workers : int or map-like callable, optional
+        If `workers` is an integer, part of the computation is done in parallel
+        subdivided to this many tasks (using :class:`python:multiprocessing.pool.Pool`).
+        Supply `-1` to use all cores available to the Process. Alternatively, supply a
+        map-like callable, such as :meth:`python:multiprocessing.pool.Pool.map` for
+        evaluating the population in parallel. This evaluation is carried out as
+        ``workers(func, iterable)``.
+    points : list of array_like, optional
+        List of points to avoid evaluating `f` at, under the condition that the rule
+        being used does not evaluate `f` on the boundary of a region (which is the
+        case for all Genz-Malik and Gauss-Kronrod rules). This can be useful if `f` has
+        a singularity at the specified point. This should be a list of array-likes where
+        each element has length ``ndim``. Default is empty. See Examples.
+
+    Returns
+    -------
+    res : object
+        Object containing the results of the estimation. It has the following
+        attributes:
+
+        estimate : ndarray
+            Estimate of the value of the integral over the overall region specified.
+        error : ndarray
+            Estimate of the error of the approximation over the overall region
+            specified.
+        status : str
+            Whether the estimation was successful. Can be either: "converged",
+            "not_converged".
+        subdivisions : int
+            Number of subdivisions performed.
+        atol, rtol : float
+            Requested tolerances for the approximation.
+        regions: list of object
+            List of objects containing the estimates of the integral over smaller
+            regions of the domain.
+
+        Each object in ``regions`` has the following attributes:
+
+        a, b : ndarray
+            Points describing the corners of the region. If the original integral
+            contained infinite limits or was over a region described by `region`,
+            then `a` and `b` are in the transformed coordinates.
+        estimate : ndarray
+            Estimate of the value of the integral over this region.
+        error : ndarray
+            Estimate of the error of the approximation over this region.
+
+    Notes
+    -----
+    The algorithm uses a similar algorithm to `quad_vec`, which itself is based on the
+    implementation of QUADPACK's DQAG* algorithms, implementing global error control and
+    adaptive subdivision.
+
+    The source of the nodes and weights used for Gauss-Kronrod quadrature can be found
+    in [1]_, and the algorithm for calculating the nodes and weights in Genz-Malik
+    cubature can be found in [2]_.
+
+    The rules currently supported via the `rule` argument are:
+
+    - ``"gauss-kronrod"``, 21-node Gauss-Kronrod
+    - ``"genz-malik"``, n-node Genz-Malik
+
+    If using Gauss-Kronrod for an ``n``-dim integrand where ``n > 2``, then the
+    corresponding Cartesian product rule will be found by taking the Cartesian product
+    of the nodes in the 1D case. This means that the number of nodes scales
+    exponentially as ``21^n`` in the Gauss-Kronrod case, which may be problematic in a
+    moderate number of dimensions.
+
+    Genz-Malik is typically less accurate than Gauss-Kronrod but has much fewer nodes,
+    so in this situation using "genz-malik" might be preferable.
+
+    Infinite limits are handled with an appropriate variable transformation. Assuming
+    ``a = [a_1, ..., a_n]`` and ``b = [b_1, ..., b_n]``:
+
+    If :math:`a_i = -\infty` and :math:`b_i = \infty`, the i-th integration variable
+    will use the transformation :math:`x = \frac{1-|t|}{t}` and :math:`t \in (-1, 1)`.
+
+    If :math:`a_i \ne \pm\infty` and :math:`b_i = \infty`, the i-th integration variable
+    will use the transformation :math:`x = a_i + \frac{1-t}{t}` and
+    :math:`t \in (0, 1)`.
+
+    If :math:`a_i = -\infty` and :math:`b_i \ne \pm\infty`, the i-th integration
+    variable will use the transformation :math:`x = b_i - \frac{1-t}{t}` and
+    :math:`t \in (0, 1)`.
+
+    References
+    ----------
+    .. [1] R. Piessens, E. de Doncker, Quadpack: A Subroutine Package for Automatic
+        Integration, files: dqk21.f, dqk15.f (1983).
+
+    .. [2] A.C. Genz, A.A. Malik, Remarks on algorithm 006: An adaptive algorithm for
+        numerical integration over an N-dimensional rectangular region, Journal of
+        Computational and Applied Mathematics, Volume 6, Issue 4, 1980, Pages 295-302,
+        ISSN 0377-0427
+        :doi:`10.1016/0771-050X(80)90039-X`
+
+    Examples
+    --------
+    **1D integral with vector output**:
+
+    .. math::
+
+        \int^1_0 \mathbf f(x) \text dx
+
+    Where ``f(x) = x^n`` and ``n = np.arange(10)`` is a vector. Since no rule is
+    specified, the default "gk21" is used, which corresponds to Gauss-Kronrod
+    integration with 21 nodes.
+
+    >>> import numpy as np
+    >>> from scipy.integrate import cubature
+    >>> def f(x, n):
+    ...    # Make sure x and n are broadcastable
+    ...    return x[:, np.newaxis]**n[np.newaxis, :]
+    >>> res = cubature(
+    ...     f,
+    ...     a=[0],
+    ...     b=[1],
+    ...     args=(np.arange(10),),
+    ... )
+    >>> res.estimate
+     array([1.        , 0.5       , 0.33333333, 0.25      , 0.2       ,
+            0.16666667, 0.14285714, 0.125     , 0.11111111, 0.1       ])
+
+    **7D integral with arbitrary-shaped array output**::
+
+        f(x) = cos(2*pi*r + alphas @ x)
+
+    for some ``r`` and ``alphas``, and the integral is performed over the unit
+    hybercube, :math:`[0, 1]^7`. Since the integral is in a moderate number of
+    dimensions, "genz-malik" is used rather than the default "gauss-kronrod" to
+    avoid constructing a product rule with :math:`21^7 \approx 2 \times 10^9` nodes.
+
+    >>> import numpy as np
+    >>> from scipy.integrate import cubature
+    >>> def f(x, r, alphas):
+    ...     # f(x) = cos(2*pi*r + alphas @ x)
+    ...     # Need to allow r and alphas to be arbitrary shape
+    ...     npoints, ndim = x.shape[0], x.shape[-1]
+    ...     alphas = alphas[np.newaxis, ...]
+    ...     x = x.reshape(npoints, *([1]*(len(alphas.shape) - 1)), ndim)
+    ...     return np.cos(2*np.pi*r + np.sum(alphas * x, axis=-1))
+    >>> rng = np.random.default_rng()
+    >>> r, alphas = rng.random((2, 3)), rng.random((2, 3, 7))
+    >>> res = cubature(
+    ...     f=f,
+    ...     a=np.array([0, 0, 0, 0, 0, 0, 0]),
+    ...     b=np.array([1, 1, 1, 1, 1, 1, 1]),
+    ...     rtol=1e-5,
+    ...     rule="genz-malik",
+    ...     args=(r, alphas),
+    ... )
+    >>> res.estimate
+     array([[-0.79812452,  0.35246913, -0.52273628],
+            [ 0.88392779,  0.59139899,  0.41895111]])
+
+    **Parallel computation with** `workers`:
+
+    >>> from concurrent.futures import ThreadPoolExecutor
+    >>> with ThreadPoolExecutor() as executor:
+    ...     res = cubature(
+    ...         f=f,
+    ...         a=np.array([0, 0, 0, 0, 0, 0, 0]),
+    ...         b=np.array([1, 1, 1, 1, 1, 1, 1]),
+    ...         rtol=1e-5,
+    ...         rule="genz-malik",
+    ...         args=(r, alphas),
+    ...         workers=executor.map,
+    ...      )
+    >>> res.estimate
+     array([[-0.79812452,  0.35246913, -0.52273628],
+            [ 0.88392779,  0.59139899,  0.41895111]])
+
+    **2D integral with infinite limits**:
+
+    .. math::
+
+        \int^{ \infty }_{ -\infty }
+        \int^{ \infty }_{ -\infty }
+            e^{-x^2-y^2}
+        \text dy
+        \text dx
+
+    >>> def gaussian(x):
+    ...     return np.exp(-np.sum(x**2, axis=-1))
+    >>> res = cubature(gaussian, [-np.inf, -np.inf], [np.inf, np.inf])
+    >>> res.estimate
+     3.1415926
+
+    **1D integral with singularities avoided using** `points`:
+
+    .. math::
+
+        \int^{ 1 }_{ -1 }
+          \frac{\sin(x)}{x}
+        \text dx
+
+    It is necessary to use the `points` parameter to avoid evaluating `f` at the origin.
+
+    >>> def sinc(x):
+    ...     return np.sin(x)/x
+    >>> res = cubature(sinc, [-1], [1], points=[[0]])
+    >>> res.estimate
+     1.8921661
+    """
+
+    # It is also possible to use a custom rule, but this is not yet part of the public
+    # API. An example of this can be found in the class scipy.integrate._rules.Rule.
+
+    xp = array_namespace(a, b)
+    max_subdivisions = float("inf") if max_subdivisions is None else max_subdivisions
+    points = [] if points is None else points
+
+    # Convert a and b to arrays and convert each point in points to an array, promoting
+    # each to a common floating dtype.
+    a, b, *points = xp_promote(a, b, *points, broadcast=True, force_floating=True,
+                               xp=xp)
+    result_dtype = a.dtype
+
+    if xp_size(a) == 0 or xp_size(b) == 0:
+        raise ValueError("`a` and `b` must be nonempty")
+
+    if a.ndim != 1 or b.ndim != 1:
+        raise ValueError("`a` and `b` must be 1D arrays")
+
+    # If the rule is a string, convert to a corresponding product rule
+    if isinstance(rule, str):
+        ndim = xp_size(a)
+
+        if rule == "genz-malik":
+            rule = GenzMalikCubature(ndim, xp=xp)
+        else:
+            quadratues = {
+                "gauss-kronrod": GaussKronrodQuadrature(21, xp=xp),
+
+                # Also allow names quad_vec uses:
+                "gk21": GaussKronrodQuadrature(21, xp=xp),
+                "gk15": GaussKronrodQuadrature(15, xp=xp),
+            }
+
+            base_rule = quadratues.get(rule)
+
+            if base_rule is None:
+                raise ValueError(f"unknown rule {rule}")
+
+            rule = ProductNestedFixed([base_rule] * ndim)
+
+    # If any of limits are the wrong way around (a > b), flip them and keep track of
+    # the sign.
+    sign = (-1) ** xp.sum(xp.astype(a > b, xp.int8), dtype=result_dtype)
+
+    a_flipped = xp.min(xp.stack([a, b]), axis=0)
+    b_flipped = xp.max(xp.stack([a, b]), axis=0)
+
+    a, b = a_flipped, b_flipped
+
+    # If any of the limits are infinite, apply a transformation
+    if xp.any(xp.isinf(a)) or xp.any(xp.isinf(b)):
+        f = _InfiniteLimitsTransform(f, a, b, xp=xp)
+        a, b = f.transformed_limits
+
+        # Map points from the original coordinates to the new transformed coordinates.
+        #
+        # `points` is a list of arrays of shape (ndim,), but transformations are applied
+        # to arrays of shape (npoints, ndim).
+        #
+        # It is not possible to combine all the points into one array and then apply
+        # f.inv to all of them at once since `points` needs to remain iterable.
+        # Instead, each point is reshaped to an array of shape (1, ndim), `f.inv` is
+        # applied, and then each is reshaped back to (ndim,).
+        points = [xp.reshape(point, (1, -1)) for point in points]
+        points = [f.inv(point) for point in points]
+        points = [xp.reshape(point, (-1,)) for point in points]
+
+        # Include any problematic points introduced by the transformation
+        points.extend(f.points)
+
+    # If any problematic points are specified, divide the initial region so that these
+    # points lie on the edge of a subregion.
+    #
+    # This means ``f`` won't be evaluated there if the rule being used has no evaluation
+    # points on the boundary.
+    if len(points) == 0:
+        initial_regions = [(a, b)]
+    else:
+        initial_regions = _split_region_at_points(a, b, points, xp)
+
+    regions = []
+    est = 0.0
+    err = 0.0
+
+    for a_k, b_k in initial_regions:
+        est_k = rule.estimate(f, a_k, b_k, args)
+        err_k = rule.estimate_error(f, a_k, b_k, args)
+        regions.append(CubatureRegion(est_k, err_k, a_k, b_k, xp))
+
+        est += est_k
+        err += err_k
+
+    subdivisions = 0
+    success = True
+
+    with MapWrapper(workers) as mapwrapper:
+        while xp.any(err > atol + rtol * xp.abs(est)):
+            # region_k is the region with highest estimated error
+            region_k = heapq.heappop(regions)
+
+            est_k = region_k.estimate
+            err_k = region_k.error
+
+            a_k, b_k = region_k.a, region_k.b
+
+            # Subtract the estimate of the integral and its error over this region from
+            # the current global estimates, since these will be refined in the loop over
+            # all subregions.
+            est -= est_k
+            err -= err_k
+
+            # Find all 2^ndim subregions formed by splitting region_k along each axis,
+            # e.g. for 1D integrals this splits an estimate over an interval into an
+            # estimate over two subintervals, for 3D integrals this splits an estimate
+            # over a cube into 8 subcubes.
+            #
+            # For each of the new subregions, calculate an estimate for the integral and
+            # the error there, and push these regions onto the heap for potential
+            # further subdividing.
+
+            executor_args = zip(
+                itertools.repeat(f),
+                itertools.repeat(rule),
+                itertools.repeat(args),
+                _split_subregion(a_k, b_k, xp),
+            )
+
+            for subdivision_result in mapwrapper(_process_subregion, executor_args):
+                a_k_sub, b_k_sub, est_sub, err_sub = subdivision_result
+
+                est += est_sub
+                err += err_sub
+
+                new_region = CubatureRegion(est_sub, err_sub, a_k_sub, b_k_sub, xp)
+
+                heapq.heappush(regions, new_region)
+
+            subdivisions += 1
+
+            if subdivisions >= max_subdivisions:
+                success = False
+                break
+
+        status = "converged" if success else "not_converged"
+
+        # Apply sign change to handle any limits which were initially flipped.
+        est = sign * est
+
+        return CubatureResult(
+            estimate=est,
+            error=err,
+            status=status,
+            subdivisions=subdivisions,
+            regions=regions,
+            atol=atol,
+            rtol=rtol,
+        )
+
+
+def _process_subregion(data):
+    f, rule, args, coord = data
+    a_k_sub, b_k_sub = coord
+
+    est_sub = rule.estimate(f, a_k_sub, b_k_sub, args)
+    err_sub = rule.estimate_error(f, a_k_sub, b_k_sub, args)
+
+    return a_k_sub, b_k_sub, est_sub, err_sub
+
+
+def _is_strictly_in_region(a, b, point, xp):
+    if xp.all(point == a) or xp.all(point == b):
+        return False
+
+    return xp.all(a <= point) and xp.all(point <= b)
+
+
+def _split_region_at_points(a, b, points, xp):
+    """
+    Given the integration limits `a` and `b` describing a rectangular region and a list
+    of `points`, find the list of ``[(a_1, b_1), ..., (a_l, b_l)]`` which breaks up the
+    initial region into smaller subregion such that no `points` lie strictly inside
+    any of the subregions.
+    """
+
+    regions = [(a, b)]
+
+    for point in points:
+        if xp.any(xp.isinf(point)):
+            # If a point is specified at infinity, ignore.
+            #
+            # This case occurs when points are given by the user to avoid, but after
+            # applying a transformation, they are removed.
+            continue
+
+        new_subregions = []
+
+        for a_k, b_k in regions:
+            if _is_strictly_in_region(a_k, b_k, point, xp):
+                subregions = _split_subregion(a_k, b_k, xp, point)
+
+                for left, right in subregions:
+                    # Skip any zero-width regions.
+                    if xp.any(left == right):
+                        continue
+                    else:
+                        new_subregions.append((left, right))
+
+                new_subregions.extend(subregions)
+
+            else:
+                new_subregions.append((a_k, b_k))
+
+        regions = new_subregions
+
+    return regions
+
+
+class _VariableTransform:
+    """
+    A transformation that can be applied to an integral.
+    """
+
+    @property
+    def transformed_limits(self):
+        """
+        New limits of integration after applying the transformation.
+        """
+
+        raise NotImplementedError
+
+    @property
+    def points(self):
+        """
+        Any problematic points introduced by the transformation.
+
+        These should be specified as points where ``_VariableTransform(f)(self, point)``
+        would be problematic.
+
+        For example, if the transformation ``x = 1/((1-t)(1+t))`` is applied to a
+        univariate integral, then points should return ``[ [1], [-1] ]``.
+        """
+
+        return []
+
+    def inv(self, x):
+        """
+        Map points ``x`` to ``t`` such that if ``f`` is the original function and ``g``
+        is the function after the transformation is applied, then::
+
+            f(x) = g(self.inv(x))
+        """
+
+        raise NotImplementedError
+
+    def __call__(self, t, *args, **kwargs):
+        """
+        Apply the transformation to ``f`` and multiply by the Jacobian determinant.
+        This should be the new integrand after the transformation has been applied so
+        that the following is satisfied::
+
+            f_transformed = _VariableTransform(f)
+
+            cubature(f, a, b) == cubature(
+                f_transformed,
+                *f_transformed.transformed_limits(a, b),
+            )
+        """
+
+        raise NotImplementedError
+
+
+class _InfiniteLimitsTransform(_VariableTransform):
+    r"""
+    Transformation for handling infinite limits.
+
+    Assuming ``a = [a_1, ..., a_n]`` and ``b = [b_1, ..., b_n]``:
+
+    If :math:`a_i = -\infty` and :math:`b_i = \infty`, the i-th integration variable
+    will use the transformation :math:`x = \frac{1-|t|}{t}` and :math:`t \in (-1, 1)`.
+
+    If :math:`a_i \ne \pm\infty` and :math:`b_i = \infty`, the i-th integration variable
+    will use the transformation :math:`x = a_i + \frac{1-t}{t}` and
+    :math:`t \in (0, 1)`.
+
+    If :math:`a_i = -\infty` and :math:`b_i \ne \pm\infty`, the i-th integration
+    variable will use the transformation :math:`x = b_i - \frac{1-t}{t}` and
+    :math:`t \in (0, 1)`.
+    """
+
+    def __init__(self, f, a, b, xp):
+        self._xp = xp
+
+        self._f = f
+        self._orig_a = a
+        self._orig_b = b
+
+        # (-oo, oo) will be mapped to (-1, 1).
+        self._double_inf_pos = (a == -math.inf) & (b == math.inf)
+
+        # (start, oo) will be mapped to (0, 1).
+        start_inf_mask = (a != -math.inf) & (b == math.inf)
+
+        # (-oo, end) will be mapped to (0, 1).
+        inf_end_mask = (a == -math.inf) & (b != math.inf)
+
+        # This is handled by making the transformation t = -x and reducing it to
+        # the other semi-infinite case.
+        self._semi_inf_pos = start_inf_mask | inf_end_mask
+
+        # Since we flip the limits, we don't need to separately multiply the
+        # integrand by -1.
+        self._orig_a[inf_end_mask] = -b[inf_end_mask]
+        self._orig_b[inf_end_mask] = -a[inf_end_mask]
+
+        self._num_inf = self._xp.sum(
+            self._xp.astype(self._double_inf_pos | self._semi_inf_pos, self._xp.int64),
+        ).__int__()
+
+    @property
+    def transformed_limits(self):
+        a = xp_copy(self._orig_a)
+        b = xp_copy(self._orig_b)
+
+        a[self._double_inf_pos] = -1
+        b[self._double_inf_pos] = 1
+
+        a[self._semi_inf_pos] = 0
+        b[self._semi_inf_pos] = 1
+
+        return a, b
+
+    @property
+    def points(self):
+        # If there are infinite limits, then the origin becomes a problematic point
+        # due to a division by zero there.
+
+        # If the function using this class only wraps f when a and b contain infinite
+        # limits, this condition will always be met (as is the case with cubature).
+        #
+        # If a and b do not contain infinite limits but f is still wrapped with this
+        # class, then without this condition the initial region of integration will
+        # be split around the origin unnecessarily.
+        if self._num_inf != 0:
+            return [self._xp.zeros(self._orig_a.shape)]
+        else:
+            return []
+
+    def inv(self, x):
+        t = xp_copy(x)
+        npoints = x.shape[0]
+
+        double_inf_mask = self._xp.tile(
+            self._double_inf_pos[self._xp.newaxis, :],
+            (npoints, 1),
+        )
+
+        semi_inf_mask = self._xp.tile(
+            self._semi_inf_pos[self._xp.newaxis, :],
+            (npoints, 1),
+        )
+
+        # If any components of x are 0, then this component will be mapped to infinity
+        # under the transformation used for doubly-infinite limits.
+        #
+        # Handle the zero values and non-zero values separately to avoid division by
+        # zero.
+        zero_mask = x[double_inf_mask] == 0
+        non_zero_mask = double_inf_mask & ~zero_mask
+        t[zero_mask] = math.inf
+        t[non_zero_mask] = 1/(x[non_zero_mask] + self._xp.sign(x[non_zero_mask]))
+
+        start = self._xp.tile(self._orig_a[self._semi_inf_pos], (npoints,))
+        t[semi_inf_mask] = 1/(x[semi_inf_mask] - start + 1)
+
+        return t
+
+    def __call__(self, t, *args, **kwargs):
+        x = xp_copy(t)
+        npoints = t.shape[0]
+
+        double_inf_mask = self._xp.tile(
+            self._double_inf_pos[self._xp.newaxis, :],
+            (npoints, 1),
+        )
+
+        semi_inf_mask = self._xp.tile(
+            self._semi_inf_pos[self._xp.newaxis, :],
+            (npoints, 1),
+        )
+
+        # For (-oo, oo) -> (-1, 1), use the transformation x = (1-|t|)/t.
+        x[double_inf_mask] = (
+            (1 - self._xp.abs(t[double_inf_mask])) / t[double_inf_mask]
+        )
+
+        start = self._xp.tile(self._orig_a[self._semi_inf_pos], (npoints,))
+
+        # For (start, oo) -> (0, 1), use the transformation x = start + (1-t)/t.
+        x[semi_inf_mask] = start + (1 - t[semi_inf_mask]) / t[semi_inf_mask]
+
+        jacobian_det = 1/self._xp.prod(
+            self._xp.reshape(
+                t[semi_inf_mask | double_inf_mask]**2,
+                (-1, self._num_inf),
+            ),
+            axis=-1,
+        )
+
+        f_x = self._f(x, *args, **kwargs)
+        jacobian_det = self._xp.reshape(jacobian_det, (-1, *([1]*(len(f_x.shape) - 1))))
+
+        return f_x * jacobian_det
diff --git a/.venv/lib/python3.12/site-packages/scipy/integrate/_dop.cpython-312-x86_64-linux-gnu.so b/.venv/lib/python3.12/site-packages/scipy/integrate/_dop.cpython-312-x86_64-linux-gnu.so
new file mode 100644
index 0000000000000000000000000000000000000000..12837c99bfbc02e8d4fa1f86f61f1d7bb9e9ed8e
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/scipy/integrate/_dop.cpython-312-x86_64-linux-gnu.so differ
diff --git a/.venv/lib/python3.12/site-packages/scipy/integrate/_ivp/__init__.py b/.venv/lib/python3.12/site-packages/scipy/integrate/_ivp/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..f3c8aaa36588651ae5e48b58fbb1d443bc71fc77
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/integrate/_ivp/__init__.py
@@ -0,0 +1,8 @@
+"""Suite of ODE solvers implemented in Python."""
+from .ivp import solve_ivp
+from .rk import RK23, RK45, DOP853
+from .radau import Radau
+from .bdf import BDF
+from .lsoda import LSODA
+from .common import OdeSolution
+from .base import DenseOutput, OdeSolver
diff --git a/.venv/lib/python3.12/site-packages/scipy/integrate/_ivp/base.py b/.venv/lib/python3.12/site-packages/scipy/integrate/_ivp/base.py
new file mode 100644
index 0000000000000000000000000000000000000000..f1e630f714e44a0e70431b675fc1522addb57fa8
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/integrate/_ivp/base.py
@@ -0,0 +1,305 @@
+from types import GenericAlias
+import numpy as np
+
+
+def check_arguments(fun, y0, support_complex):
+    """Helper function for checking arguments common to all solvers."""
+    y0 = np.asarray(y0)
+    if np.issubdtype(y0.dtype, np.complexfloating):
+        if not support_complex:
+            raise ValueError("`y0` is complex, but the chosen solver does "
+                             "not support integration in a complex domain.")
+        dtype = complex
+    else:
+        dtype = float
+    y0 = y0.astype(dtype, copy=False)
+
+    if y0.ndim != 1:
+        raise ValueError("`y0` must be 1-dimensional.")
+
+    if not np.isfinite(y0).all():
+        raise ValueError("All components of the initial state `y0` must be finite.")
+
+    def fun_wrapped(t, y):
+        return np.asarray(fun(t, y), dtype=dtype)
+
+    return fun_wrapped, y0
+
+
+class OdeSolver:
+    """Base class for ODE solvers.
+
+    In order to implement a new solver you need to follow the guidelines:
+
+    1. A constructor must accept parameters presented in the base class
+       (listed below) along with any other parameters specific to a solver.
+    2. A constructor must accept arbitrary extraneous arguments
+       ``**extraneous``, but warn that these arguments are irrelevant
+       using `common.warn_extraneous` function. Do not pass these
+       arguments to the base class.
+    3. A solver must implement a private method ``_step_impl(self)`` which
+       propagates a solver one step further. It must return tuple
+       ``(success, message)``, where ``success`` is a boolean indicating
+       whether a step was successful, and ``message`` is a string
+       containing description of a failure if a step failed or None
+       otherwise.
+    4. A solver must implement a private method ``_dense_output_impl(self)``,
+       which returns a `DenseOutput` object covering the last successful
+       step.
+    5. A solver must have attributes listed below in Attributes section.
+       Note that ``t_old`` and ``step_size`` are updated automatically.
+    6. Use ``fun(self, t, y)`` method for the system rhs evaluation, this
+       way the number of function evaluations (`nfev`) will be tracked
+       automatically.
+    7. For convenience, a base class provides ``fun_single(self, t, y)`` and
+       ``fun_vectorized(self, t, y)`` for evaluating the rhs in
+       non-vectorized and vectorized fashions respectively (regardless of
+       how `fun` from the constructor is implemented). These calls don't
+       increment `nfev`.
+    8. If a solver uses a Jacobian matrix and LU decompositions, it should
+       track the number of Jacobian evaluations (`njev`) and the number of
+       LU decompositions (`nlu`).
+    9. By convention, the function evaluations used to compute a finite
+       difference approximation of the Jacobian should not be counted in
+       `nfev`, thus use ``fun_single(self, t, y)`` or
+       ``fun_vectorized(self, t, y)`` when computing a finite difference
+       approximation of the Jacobian.
+
+    Parameters
+    ----------
+    fun : callable
+        Right-hand side of the system: the time derivative of the state ``y``
+        at time ``t``. The calling signature is ``fun(t, y)``, where ``t`` is a
+        scalar and ``y`` is an ndarray with ``len(y) = len(y0)``. ``fun`` must
+        return an array of the same shape as ``y``. See `vectorized` for more
+        information.
+    t0 : float
+        Initial time.
+    y0 : array_like, shape (n,)
+        Initial state.
+    t_bound : float
+        Boundary time --- the integration won't continue beyond it. It also
+        determines the direction of the integration.
+    vectorized : bool
+        Whether `fun` can be called in a vectorized fashion. Default is False.
+
+        If ``vectorized`` is False, `fun` will always be called with ``y`` of
+        shape ``(n,)``, where ``n = len(y0)``.
+
+        If ``vectorized`` is True, `fun` may be called with ``y`` of shape
+        ``(n, k)``, where ``k`` is an integer. In this case, `fun` must behave
+        such that ``fun(t, y)[:, i] == fun(t, y[:, i])`` (i.e. each column of
+        the returned array is the time derivative of the state corresponding
+        with a column of ``y``).
+
+        Setting ``vectorized=True`` allows for faster finite difference
+        approximation of the Jacobian by methods 'Radau' and 'BDF', but
+        will result in slower execution for other methods. It can also
+        result in slower overall execution for 'Radau' and 'BDF' in some
+        circumstances (e.g. small ``len(y0)``).
+    support_complex : bool, optional
+        Whether integration in a complex domain should be supported.
+        Generally determined by a derived solver class capabilities.
+        Default is False.
+
+    Attributes
+    ----------
+    n : int
+        Number of equations.
+    status : str
+        Current status of the solver: 'running', 'finished' or 'failed'.
+    t_bound : float
+        Boundary time.
+    direction : float
+        Integration direction: +1 or -1.
+    t : float
+        Current time.
+    y : ndarray
+        Current state.
+    t_old : float
+        Previous time. None if no steps were made yet.
+    step_size : float
+        Size of the last successful step. None if no steps were made yet.
+    nfev : int
+        Number of the system's rhs evaluations.
+    njev : int
+        Number of the Jacobian evaluations.
+    nlu : int
+        Number of LU decompositions.
+    """
+    TOO_SMALL_STEP = "Required step size is less than spacing between numbers."
+
+    # generic type compatibility with scipy-stubs
+    __class_getitem__: classmethod = classmethod(GenericAlias)
+
+    def __init__(self, fun, t0, y0, t_bound, vectorized,
+                 support_complex=False):
+        self.t_old = None
+        self.t = t0
+        self._fun, self.y = check_arguments(fun, y0, support_complex)
+        self.t_bound = t_bound
+        self.vectorized = vectorized
+
+        if vectorized:
+            def fun_single(t, y):
+                return self._fun(t, y[:, None]).ravel()
+            fun_vectorized = self._fun
+        else:
+            fun_single = self._fun
+
+            def fun_vectorized(t, y):
+                f = np.empty_like(y)
+                for i, yi in enumerate(y.T):
+                    f[:, i] = self._fun(t, yi)
+                return f
+
+        def fun(t, y):
+            self.nfev += 1
+            return self.fun_single(t, y)
+
+        self.fun = fun
+        self.fun_single = fun_single
+        self.fun_vectorized = fun_vectorized
+
+        self.direction = np.sign(t_bound - t0) if t_bound != t0 else 1
+        self.n = self.y.size
+        self.status = 'running'
+
+        self.nfev = 0
+        self.njev = 0
+        self.nlu = 0
+
+    @property
+    def step_size(self):
+        if self.t_old is None:
+            return None
+        else:
+            return np.abs(self.t - self.t_old)
+
+    def step(self):
+        """Perform one integration step.
+
+        Returns
+        -------
+        message : str or None
+            Report from the solver. Typically a reason for a failure if
+            `self.status` is 'failed' after the step was taken or None
+            otherwise.
+        """
+        if self.status != 'running':
+            raise RuntimeError("Attempt to step on a failed or finished "
+                               "solver.")
+
+        if self.n == 0 or self.t == self.t_bound:
+            # Handle corner cases of empty solver or no integration.
+            self.t_old = self.t
+            self.t = self.t_bound
+            message = None
+            self.status = 'finished'
+        else:
+            t = self.t
+            success, message = self._step_impl()
+
+            if not success:
+                self.status = 'failed'
+            else:
+                self.t_old = t
+                if self.direction * (self.t - self.t_bound) >= 0:
+                    self.status = 'finished'
+
+        return message
+
+    def dense_output(self):
+        """Compute a local interpolant over the last successful step.
+
+        Returns
+        -------
+        sol : `DenseOutput`
+            Local interpolant over the last successful step.
+        """
+        if self.t_old is None:
+            raise RuntimeError("Dense output is available after a successful "
+                               "step was made.")
+
+        if self.n == 0 or self.t == self.t_old:
+            # Handle corner cases of empty solver and no integration.
+            return ConstantDenseOutput(self.t_old, self.t, self.y)
+        else:
+            return self._dense_output_impl()
+
+    def _step_impl(self):
+        raise NotImplementedError
+
+    def _dense_output_impl(self):
+        raise NotImplementedError
+
+
+class DenseOutput:
+    """Base class for local interpolant over step made by an ODE solver.
+
+    It interpolates between `t_min` and `t_max` (see Attributes below).
+    Evaluation outside this interval is not forbidden, but the accuracy is not
+    guaranteed.
+
+    Parameters
+    ----------
+    t_old : float
+        Previous time.
+    t : float
+        Current time.
+
+    Attributes
+    ----------
+    t_min, t_max : float
+        Time range of the interpolation.
+    """
+
+    # generic type compatibility with scipy-stubs
+    __class_getitem__: classmethod = classmethod(GenericAlias)
+
+    def __init__(self, t_old, t):
+        self.t_old = t_old
+        self.t = t
+        self.t_min = min(t, t_old)
+        self.t_max = max(t, t_old)
+
+    def __call__(self, t):
+        """Evaluate the interpolant.
+
+        Parameters
+        ----------
+        t : float or array_like with shape (n_points,)
+            Points to evaluate the solution at.
+
+        Returns
+        -------
+        y : ndarray, shape (n,) or (n, n_points)
+            Computed values. Shape depends on whether `t` was a scalar or a
+            1-D array.
+        """
+        t = np.asarray(t)
+        if t.ndim > 1:
+            raise ValueError("`t` must be a float or a 1-D array.")
+        return self._call_impl(t)
+
+    def _call_impl(self, t):
+        raise NotImplementedError
+
+
+class ConstantDenseOutput(DenseOutput):
+    """Constant value interpolator.
+
+    This class used for degenerate integration cases: equal integration limits
+    or a system with 0 equations.
+    """
+    def __init__(self, t_old, t, value):
+        super().__init__(t_old, t)
+        self.value = value
+
+    def _call_impl(self, t):
+        if t.ndim == 0:
+            return self.value
+        else:
+            ret = np.empty((self.value.shape[0], t.shape[0]))
+            ret[:] = self.value[:, None]
+            return ret
diff --git a/.venv/lib/python3.12/site-packages/scipy/integrate/_ivp/bdf.py b/.venv/lib/python3.12/site-packages/scipy/integrate/_ivp/bdf.py
new file mode 100644
index 0000000000000000000000000000000000000000..75a5063fb88e0715e076d8e6ff6a5df239f10359
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/integrate/_ivp/bdf.py
@@ -0,0 +1,484 @@
+import numpy as np
+from scipy.linalg import lu_factor, lu_solve
+from scipy.sparse import issparse, eye_array, safely_cast_index_arrays
+from scipy.sparse.linalg import splu
+from scipy.optimize._numdiff import group_columns
+from .common import (validate_max_step, validate_tol, select_initial_step,
+                     norm, EPS, num_jac, validate_first_step,
+                     warn_extraneous)
+from .base import OdeSolver, DenseOutput
+
+
+MAX_ORDER = 5
+NEWTON_MAXITER = 4
+MIN_FACTOR = 0.2
+MAX_FACTOR = 10
+
+
+def compute_R(order, factor):
+    """Compute the matrix for changing the differences array."""
+    I = np.arange(1, order + 1)[:, None]
+    J = np.arange(1, order + 1)
+    M = np.zeros((order + 1, order + 1))
+    M[1:, 1:] = (I - 1 - factor * J) / I
+    M[0] = 1
+    return np.cumprod(M, axis=0)
+
+
+def change_D(D, order, factor):
+    """Change differences array in-place when step size is changed."""
+    R = compute_R(order, factor)
+    U = compute_R(order, 1)
+    RU = R.dot(U)
+    D[:order + 1] = np.dot(RU.T, D[:order + 1])
+
+
+def solve_bdf_system(fun, t_new, y_predict, c, psi, LU, solve_lu, scale, tol):
+    """Solve the algebraic system resulting from BDF method."""
+    d = 0
+    y = y_predict.copy()
+    dy_norm_old = None
+    converged = False
+    for k in range(NEWTON_MAXITER):
+        f = fun(t_new, y)
+        if not np.all(np.isfinite(f)):
+            break
+
+        dy = solve_lu(LU, c * f - psi - d)
+        dy_norm = norm(dy / scale)
+
+        if dy_norm_old is None:
+            rate = None
+        else:
+            rate = dy_norm / dy_norm_old
+
+        if (rate is not None and (rate >= 1 or
+                rate ** (NEWTON_MAXITER - k) / (1 - rate) * dy_norm > tol)):
+            break
+
+        y += dy
+        d += dy
+
+        if (dy_norm == 0 or
+                rate is not None and rate / (1 - rate) * dy_norm < tol):
+            converged = True
+            break
+
+        dy_norm_old = dy_norm
+
+    return converged, k + 1, y, d
+
+
+class BDF(OdeSolver):
+    """Implicit method based on backward-differentiation formulas.
+
+    This is a variable order method with the order varying automatically from
+    1 to 5. The general framework of the BDF algorithm is described in [1]_.
+    This class implements a quasi-constant step size as explained in [2]_.
+    The error estimation strategy for the constant-step BDF is derived in [3]_.
+    An accuracy enhancement using modified formulas (NDF) [2]_ is also implemented.
+
+    Can be applied in the complex domain.
+
+    Parameters
+    ----------
+    fun : callable
+        Right-hand side of the system: the time derivative of the state ``y``
+        at time ``t``. The calling signature is ``fun(t, y)``, where ``t`` is a
+        scalar and ``y`` is an ndarray with ``len(y) = len(y0)``. ``fun`` must
+        return an array of the same shape as ``y``. See `vectorized` for more
+        information.
+    t0 : float
+        Initial time.
+    y0 : array_like, shape (n,)
+        Initial state.
+    t_bound : float
+        Boundary time - the integration won't continue beyond it. It also
+        determines the direction of the integration.
+    max_step : float, optional
+        Maximum allowed step size. Default is np.inf, i.e., the step size is not
+        bounded and determined solely by the solver.
+    rtol, atol : float and array_like, optional
+        Relative and absolute tolerances. The solver keeps the local error
+        estimates less than ``atol + rtol * abs(y)``. Here `rtol` controls a
+        relative accuracy (number of correct digits), while `atol` controls
+        absolute accuracy (number of correct decimal places). To achieve the
+        desired `rtol`, set `atol` to be smaller than the smallest value that
+        can be expected from ``rtol * abs(y)`` so that `rtol` dominates the
+        allowable error. If `atol` is larger than ``rtol * abs(y)`` the
+        number of correct digits is not guaranteed. Conversely, to achieve the
+        desired `atol` set `rtol` such that ``rtol * abs(y)`` is always smaller
+        than `atol`. If components of y have different scales, it might be
+        beneficial to set different `atol` values for different components by
+        passing array_like with shape (n,) for `atol`. Default values are
+        1e-3 for `rtol` and 1e-6 for `atol`.
+    jac : {None, array_like, sparse array or matrix, callable}, optional
+        Jacobian matrix of the right-hand side of the system with respect to y,
+        required by this method. The Jacobian matrix has shape (n, n) and its
+        element (i, j) is equal to ``d f_i / d y_j``.
+        There are three ways to define the Jacobian:
+
+        * If array_like or sparse, the Jacobian is assumed to be constant.
+        * If callable, the Jacobian is assumed to depend on both
+          t and y; it will be called as ``jac(t, y)`` as necessary.
+          For the 'Radau' and 'BDF' methods, it can return dense or sparse.
+        * If None (default), the Jacobian will be approximated by
+          finite differences.
+
+        It is generally recommended to provide the Jacobian rather than
+        relying on a finite-difference approximation.
+    jac_sparsity : {None, array_like, sparse array or matrix}, optional
+        Defines a sparsity structure of the Jacobian matrix for a
+        finite-difference approximation. Its shape must be (n, n). This argument
+        is ignored if `jac` is not `None`. If the Jacobian has only few non-zero
+        elements in *each* row, providing the sparsity structure will greatly
+        speed up the computations [4]_. A zero entry means that a corresponding
+        element in the Jacobian is always zero. If None (default), the Jacobian
+        is assumed to be dense.
+    vectorized : bool, optional
+        Whether `fun` can be called in a vectorized fashion. Default is False.
+
+        If ``vectorized`` is False, `fun` will always be called with ``y`` of
+        shape ``(n,)``, where ``n = len(y0)``.
+
+        If ``vectorized`` is True, `fun` may be called with ``y`` of shape
+        ``(n, k)``, where ``k`` is an integer. In this case, `fun` must behave
+        such that ``fun(t, y)[:, i] == fun(t, y[:, i])`` (i.e. each column of
+        the returned array is the time derivative of the state corresponding
+        with a column of ``y``).
+
+        Setting ``vectorized=True`` allows for faster finite difference
+        approximation of the Jacobian by this method, but may result in slower
+        execution overall in some circumstances (e.g. small ``len(y0)``).
+    first_step : float or None, optional
+        Initial step size. Default is ``None`` which means that the algorithm
+        should choose.
+    **extraneous
+        Any additional keyword arguments will be ignored.
+
+    Attributes
+    ----------
+    n : int
+        Number of equations.
+    status : str
+        Current status of the solver: 'running', 'finished' or 'failed'.
+    t_bound : float
+        Boundary time.
+    direction : float
+        Integration direction: +1 or -1.
+    t : float
+        Current time.
+    y : ndarray
+        Current state.
+    t_old : float
+        Previous time. None if no steps were made yet.
+    step_size : float
+        Size of the last successful step. None if no steps were made yet.
+    nfev : int
+        Number of evaluations of the right-hand side.
+    njev : int
+        Number of evaluations of the Jacobian.
+    nlu : int
+        Number of LU decompositions.
+
+    References
+    ----------
+    .. [1] G. D. Byrne, A. C. Hindmarsh, "A Polyalgorithm for the Numerical
+           Solution of Ordinary Differential Equations", ACM Transactions on
+           Mathematical Software, Vol. 1, No. 1, pp. 71-96, March 1975.
+    .. [2] L. F. Shampine, M. W. Reichelt, "THE MATLAB ODE SUITE", SIAM J. SCI.
+           COMPUTE., Vol. 18, No. 1, pp. 1-22, January 1997.
+    .. [3] E. Hairer, G. Wanner, "Solving Ordinary Differential Equations I:
+           Nonstiff Problems", Sec. III.2.
+    .. [4] A. Curtis, M. J. D. Powell, and J. Reid, "On the estimation of
+           sparse Jacobian matrices", Journal of the Institute of Mathematics
+           and its Applications, 13, pp. 117-120, 1974.
+    """
+
+    def __init__(self, fun, t0, y0, t_bound, max_step=np.inf,
+                 rtol=1e-3, atol=1e-6, jac=None, jac_sparsity=None,
+                 vectorized=False, first_step=None, **extraneous):
+        warn_extraneous(extraneous)
+        super().__init__(fun, t0, y0, t_bound, vectorized,
+                         support_complex=True)
+        self.max_step = validate_max_step(max_step)
+        self.rtol, self.atol = validate_tol(rtol, atol, self.n)
+        f = self.fun(self.t, self.y)
+        if first_step is None:
+            self.h_abs = select_initial_step(self.fun, self.t, self.y,
+                                             t_bound, max_step, f,
+                                             self.direction, 1,
+                                             self.rtol, self.atol)
+        else:
+            self.h_abs = validate_first_step(first_step, t0, t_bound)
+        self.h_abs_old = None
+        self.error_norm_old = None
+
+        self.newton_tol = max(10 * EPS / rtol, min(0.03, rtol ** 0.5))
+
+        self.jac_factor = None
+        self.jac, self.J = self._validate_jac(jac, jac_sparsity)
+        if issparse(self.J):
+            def lu(A):
+                self.nlu += 1
+                return splu(A)
+
+            def solve_lu(LU, b):
+                return LU.solve(b)
+
+            I = eye_array(self.n, format='csc', dtype=self.y.dtype)
+        else:
+            def lu(A):
+                self.nlu += 1
+                return lu_factor(A, overwrite_a=True)
+
+            def solve_lu(LU, b):
+                return lu_solve(LU, b, overwrite_b=True)
+
+            I = np.identity(self.n, dtype=self.y.dtype)
+
+        self.lu = lu
+        self.solve_lu = solve_lu
+        self.I = I
+
+        kappa = np.array([0, -0.1850, -1/9, -0.0823, -0.0415, 0])
+        self.gamma = np.hstack((0, np.cumsum(1 / np.arange(1, MAX_ORDER + 1))))
+        self.alpha = (1 - kappa) * self.gamma
+        self.error_const = kappa * self.gamma + 1 / np.arange(1, MAX_ORDER + 2)
+
+        D = np.empty((MAX_ORDER + 3, self.n), dtype=self.y.dtype)
+        D[0] = self.y
+        D[1] = f * self.h_abs * self.direction
+        self.D = D
+
+        self.order = 1
+        self.n_equal_steps = 0
+        self.LU = None
+
+    def _validate_jac(self, jac, sparsity):
+        t0 = self.t
+        y0 = self.y
+
+        if jac is None:
+            if sparsity is not None:
+                if issparse(sparsity):
+                    sparsity = sparsity.tocsc()
+                    # this restricts self.n to fit in int32 for group_columns
+                    indices, indptr = safely_cast_index_arrays(sparsity)
+                    sparsity.indices, sparsity.indptr = indices, indptr
+                groups = group_columns(sparsity)
+                sparsity = (sparsity, groups)
+
+            def jac_wrapped(t, y):
+                self.njev += 1
+                f = self.fun_single(t, y)
+                J, self.jac_factor = num_jac(self.fun_vectorized, t, y, f,
+                                             self.atol, self.jac_factor,
+                                             sparsity)
+                return J
+            J = jac_wrapped(t0, y0)
+        elif callable(jac):
+            J = jac(t0, y0)
+            self.njev += 1
+            if issparse(J):
+                J = J.tocsc().astype(y0.dtype, copy=False)
+                csc_constructor = J.__class__
+
+                def jac_wrapped(t, y):
+                    self.njev += 1
+                    # TODO: switch to csc_array after spmatrix is removed
+                    return csc_constructor(jac(t, y), dtype=y0.dtype)
+            else:
+                J = np.asarray(J, dtype=y0.dtype)
+
+                def jac_wrapped(t, y):
+                    self.njev += 1
+                    return np.asarray(jac(t, y), dtype=y0.dtype)
+
+            if J.shape != (self.n, self.n):
+                raise ValueError(f"`jac` is expected to have shape {(self.n, self.n)},"
+                                 f" but actually has {J.shape}.")
+        else:
+            if issparse(jac):
+                J = jac.tocsc().astype(y0.dtype, copy=False)
+            else:
+                J = np.asarray(jac, dtype=y0.dtype)
+
+            if J.shape != (self.n, self.n):
+                raise ValueError(f"`jac` is expected to have shape {(self.n, self.n)},"
+                                 f" but actually has {J.shape}.")
+            jac_wrapped = None
+
+        return jac_wrapped, J
+
+    def _step_impl(self):
+        t = self.t
+        D = self.D
+
+        max_step = self.max_step
+        min_step = 10 * np.abs(np.nextafter(t, self.direction * np.inf) - t)
+        if self.h_abs > max_step:
+            h_abs = max_step
+            change_D(D, self.order, max_step / self.h_abs)
+            self.n_equal_steps = 0
+        elif self.h_abs < min_step:
+            h_abs = min_step
+            change_D(D, self.order, min_step / self.h_abs)
+            self.n_equal_steps = 0
+        else:
+            h_abs = self.h_abs
+
+        atol = self.atol
+        rtol = self.rtol
+        order = self.order
+
+        alpha = self.alpha
+        gamma = self.gamma
+        error_const = self.error_const
+
+        J = self.J
+        LU = self.LU
+        current_jac = self.jac is None
+
+        step_accepted = False
+        while not step_accepted:
+            if h_abs < min_step:
+                return False, self.TOO_SMALL_STEP
+
+            h = h_abs * self.direction
+            t_new = t + h
+
+            if self.direction * (t_new - self.t_bound) > 0:
+                t_new = self.t_bound
+                change_D(D, order, np.abs(t_new - t) / h_abs)
+                self.n_equal_steps = 0
+                LU = None
+
+            h = t_new - t
+            h_abs = np.abs(h)
+
+            y_predict = np.sum(D[:order + 1], axis=0)
+
+            scale = atol + rtol * np.abs(y_predict)
+            psi = np.dot(D[1: order + 1].T, gamma[1: order + 1]) / alpha[order]
+
+            converged = False
+            c = h / alpha[order]
+            while not converged:
+                if LU is None:
+                    LU = self.lu(self.I - c * J)
+
+                converged, n_iter, y_new, d = solve_bdf_system(
+                    self.fun, t_new, y_predict, c, psi, LU, self.solve_lu,
+                    scale, self.newton_tol)
+
+                if not converged:
+                    if current_jac:
+                        break
+                    J = self.jac(t_new, y_predict)
+                    LU = None
+                    current_jac = True
+
+            if not converged:
+                factor = 0.5
+                h_abs *= factor
+                change_D(D, order, factor)
+                self.n_equal_steps = 0
+                LU = None
+                continue
+
+            safety = 0.9 * (2 * NEWTON_MAXITER + 1) / (2 * NEWTON_MAXITER
+                                                       + n_iter)
+
+            scale = atol + rtol * np.abs(y_new)
+            error = error_const[order] * d
+            error_norm = norm(error / scale)
+
+            if error_norm > 1:
+                factor = max(MIN_FACTOR,
+                             safety * error_norm ** (-1 / (order + 1)))
+                h_abs *= factor
+                change_D(D, order, factor)
+                self.n_equal_steps = 0
+                # As we didn't have problems with convergence, we don't
+                # reset LU here.
+            else:
+                step_accepted = True
+
+        self.n_equal_steps += 1
+
+        self.t = t_new
+        self.y = y_new
+
+        self.h_abs = h_abs
+        self.J = J
+        self.LU = LU
+
+        # Update differences. The principal relation here is
+        # D^{j + 1} y_n = D^{j} y_n - D^{j} y_{n - 1}. Keep in mind that D
+        # contained difference for previous interpolating polynomial and
+        # d = D^{k + 1} y_n. Thus this elegant code follows.
+        D[order + 2] = d - D[order + 1]
+        D[order + 1] = d
+        for i in reversed(range(order + 1)):
+            D[i] += D[i + 1]
+
+        if self.n_equal_steps < order + 1:
+            return True, None
+
+        if order > 1:
+            error_m = error_const[order - 1] * D[order]
+            error_m_norm = norm(error_m / scale)
+        else:
+            error_m_norm = np.inf
+
+        if order < MAX_ORDER:
+            error_p = error_const[order + 1] * D[order + 2]
+            error_p_norm = norm(error_p / scale)
+        else:
+            error_p_norm = np.inf
+
+        error_norms = np.array([error_m_norm, error_norm, error_p_norm])
+        with np.errstate(divide='ignore'):
+            factors = error_norms ** (-1 / np.arange(order, order + 3))
+
+        delta_order = np.argmax(factors) - 1
+        order += delta_order
+        self.order = order
+
+        factor = min(MAX_FACTOR, safety * np.max(factors))
+        self.h_abs *= factor
+        change_D(D, order, factor)
+        self.n_equal_steps = 0
+        self.LU = None
+
+        return True, None
+
+    def _dense_output_impl(self):
+        return BdfDenseOutput(self.t_old, self.t, self.h_abs * self.direction,
+                              self.order, self.D[:self.order + 1].copy())
+
+
+class BdfDenseOutput(DenseOutput):
+    def __init__(self, t_old, t, h, order, D):
+        super().__init__(t_old, t)
+        self.order = order
+        self.t_shift = self.t - h * np.arange(self.order)
+        self.denom = h * (1 + np.arange(self.order))
+        self.D = D
+
+    def _call_impl(self, t):
+        if t.ndim == 0:
+            x = (t - self.t_shift) / self.denom
+            p = np.cumprod(x)
+        else:
+            x = (t - self.t_shift[:, None]) / self.denom[:, None]
+            p = np.cumprod(x, axis=0)
+
+        y = np.dot(self.D[1:].T, p)
+        if y.ndim == 1:
+            y += self.D[0]
+        else:
+            y += self.D[0, :, None]
+
+        return y
diff --git a/.venv/lib/python3.12/site-packages/scipy/integrate/_ivp/common.py b/.venv/lib/python3.12/site-packages/scipy/integrate/_ivp/common.py
new file mode 100644
index 0000000000000000000000000000000000000000..1a9c4871b87a3d9c6afe3f3ce02d69f16300776c
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/integrate/_ivp/common.py
@@ -0,0 +1,454 @@
+from itertools import groupby
+from warnings import warn
+import numpy as np
+from scipy.sparse import find, csc_array, isspmatrix, csc_matrix
+
+
+EPS = np.finfo(float).eps
+
+
+def validate_first_step(first_step, t0, t_bound):
+    """Assert that first_step is valid and return it."""
+    if first_step <= 0:
+        raise ValueError("`first_step` must be positive.")
+    if first_step > np.abs(t_bound - t0):
+        raise ValueError("`first_step` exceeds bounds.")
+    return first_step
+
+
+def validate_max_step(max_step):
+    """Assert that max_Step is valid and return it."""
+    if max_step <= 0:
+        raise ValueError("`max_step` must be positive.")
+    return max_step
+
+
+def warn_extraneous(extraneous):
+    """Display a warning for extraneous keyword arguments.
+
+    The initializer of each solver class is expected to collect keyword
+    arguments that it doesn't understand and warn about them. This function
+    prints a warning for each key in the supplied dictionary.
+
+    Parameters
+    ----------
+    extraneous : dict
+        Extraneous keyword arguments
+    """
+    if extraneous:
+        warn("The following arguments have no effect for a chosen solver: "
+             f"{', '.join(f'`{x}`' for x in extraneous)}.",
+             stacklevel=3)
+
+
+def validate_tol(rtol, atol, n):
+    """Validate tolerance values."""
+
+    if np.any(rtol < 100 * EPS):
+        warn("At least one element of `rtol` is too small. "
+             f"Setting `rtol = np.maximum(rtol, {100 * EPS})`.",
+             stacklevel=3)
+        rtol = np.maximum(rtol, 100 * EPS)
+
+    atol = np.asarray(atol)
+    if atol.ndim > 0 and atol.shape != (n,):
+        raise ValueError("`atol` has wrong shape.")
+
+    if np.any(atol < 0):
+        raise ValueError("`atol` must be positive.")
+
+    return rtol, atol
+
+
+def norm(x):
+    """Compute RMS norm."""
+    return np.linalg.norm(x) / x.size ** 0.5
+
+
+def select_initial_step(fun, t0, y0, t_bound,
+                        max_step, f0, direction, order, rtol, atol):
+    """Empirically select a good initial step.
+
+    The algorithm is described in [1]_.
+
+    Parameters
+    ----------
+    fun : callable
+        Right-hand side of the system.
+    t0 : float
+        Initial value of the independent variable.
+    y0 : ndarray, shape (n,)
+        Initial value of the dependent variable.
+    t_bound : float
+        End-point of integration interval; used to ensure that t0+step<=tbound
+        and that fun is only evaluated in the interval [t0,tbound]
+    max_step : float
+        Maximum allowable step size.
+    f0 : ndarray, shape (n,)
+        Initial value of the derivative, i.e., ``fun(t0, y0)``.
+    direction : float
+        Integration direction.
+    order : float
+        Error estimator order. It means that the error controlled by the
+        algorithm is proportional to ``step_size ** (order + 1)`.
+    rtol : float
+        Desired relative tolerance.
+    atol : float
+        Desired absolute tolerance.
+
+    Returns
+    -------
+    h_abs : float
+        Absolute value of the suggested initial step.
+
+    References
+    ----------
+    .. [1] E. Hairer, S. P. Norsett G. Wanner, "Solving Ordinary Differential
+           Equations I: Nonstiff Problems", Sec. II.4.
+    """
+    if y0.size == 0:
+        return np.inf
+
+    interval_length = abs(t_bound - t0)
+    if interval_length == 0.0:
+        return 0.0
+
+    scale = atol + np.abs(y0) * rtol
+    d0 = norm(y0 / scale)
+    d1 = norm(f0 / scale)
+    if d0 < 1e-5 or d1 < 1e-5:
+        h0 = 1e-6
+    else:
+        h0 = 0.01 * d0 / d1
+    # Check t0+h0*direction doesn't take us beyond t_bound
+    h0 = min(h0, interval_length)
+    y1 = y0 + h0 * direction * f0
+    f1 = fun(t0 + h0 * direction, y1)
+    d2 = norm((f1 - f0) / scale) / h0
+
+    if d1 <= 1e-15 and d2 <= 1e-15:
+        h1 = max(1e-6, h0 * 1e-3)
+    else:
+        h1 = (0.01 / max(d1, d2)) ** (1 / (order + 1))
+
+    return min(100 * h0, h1, interval_length, max_step)
+
+
+class OdeSolution:
+    """Continuous ODE solution.
+
+    It is organized as a collection of `DenseOutput` objects which represent
+    local interpolants. It provides an algorithm to select a right interpolant
+    for each given point.
+
+    The interpolants cover the range between `t_min` and `t_max` (see
+    Attributes below). Evaluation outside this interval is not forbidden, but
+    the accuracy is not guaranteed.
+
+    When evaluating at a breakpoint (one of the values in `ts`) a segment with
+    the lower index is selected.
+
+    Parameters
+    ----------
+    ts : array_like, shape (n_segments + 1,)
+        Time instants between which local interpolants are defined. Must
+        be strictly increasing or decreasing (zero segment with two points is
+        also allowed).
+    interpolants : list of DenseOutput with n_segments elements
+        Local interpolants. An i-th interpolant is assumed to be defined
+        between ``ts[i]`` and ``ts[i + 1]``.
+    alt_segment : bool
+        Requests the alternative interpolant segment selection scheme. At each
+        solver integration point, two interpolant segments are available. The
+        default (False) and alternative (True) behaviours select the segment
+        for which the requested time corresponded to ``t`` and ``t_old``,
+        respectively. This functionality is only relevant for testing the
+        interpolants' accuracy: different integrators use different
+        construction strategies.
+
+    Attributes
+    ----------
+    t_min, t_max : float
+        Time range of the interpolation.
+    """
+    def __init__(self, ts, interpolants, alt_segment=False):
+        ts = np.asarray(ts)
+        d = np.diff(ts)
+        # The first case covers integration on zero segment.
+        if not ((ts.size == 2 and ts[0] == ts[-1])
+                or np.all(d > 0) or np.all(d < 0)):
+            raise ValueError("`ts` must be strictly increasing or decreasing.")
+
+        self.n_segments = len(interpolants)
+        if ts.shape != (self.n_segments + 1,):
+            raise ValueError("Numbers of time stamps and interpolants "
+                             "don't match.")
+
+        self.ts = ts
+        self.interpolants = interpolants
+        if ts[-1] >= ts[0]:
+            self.t_min = ts[0]
+            self.t_max = ts[-1]
+            self.ascending = True
+            self.side = "right" if alt_segment else "left"
+            self.ts_sorted = ts
+        else:
+            self.t_min = ts[-1]
+            self.t_max = ts[0]
+            self.ascending = False
+            self.side = "left" if alt_segment else "right"
+            self.ts_sorted = ts[::-1]
+
+    def _call_single(self, t):
+        # Here we preserve a certain symmetry that when t is in self.ts,
+        # if alt_segment=False, then we prioritize a segment with a lower
+        # index.
+        ind = np.searchsorted(self.ts_sorted, t, side=self.side)
+
+        segment = min(max(ind - 1, 0), self.n_segments - 1)
+        if not self.ascending:
+            segment = self.n_segments - 1 - segment
+
+        return self.interpolants[segment](t)
+
+    def __call__(self, t):
+        """Evaluate the solution.
+
+        Parameters
+        ----------
+        t : float or array_like with shape (n_points,)
+            Points to evaluate at.
+
+        Returns
+        -------
+        y : ndarray, shape (n_states,) or (n_states, n_points)
+            Computed values. Shape depends on whether `t` is a scalar or a
+            1-D array.
+        """
+        t = np.asarray(t)
+
+        if t.ndim == 0:
+            return self._call_single(t)
+
+        order = np.argsort(t)
+        reverse = np.empty_like(order)
+        reverse[order] = np.arange(order.shape[0])
+        t_sorted = t[order]
+
+        # See comment in self._call_single.
+        segments = np.searchsorted(self.ts_sorted, t_sorted, side=self.side)
+        segments -= 1
+        segments[segments < 0] = 0
+        segments[segments > self.n_segments - 1] = self.n_segments - 1
+        if not self.ascending:
+            segments = self.n_segments - 1 - segments
+
+        ys = []
+        group_start = 0
+        for segment, group in groupby(segments):
+            group_end = group_start + len(list(group))
+            y = self.interpolants[segment](t_sorted[group_start:group_end])
+            ys.append(y)
+            group_start = group_end
+
+        ys = np.hstack(ys)
+        ys = ys[:, reverse]
+
+        return ys
+
+
+NUM_JAC_DIFF_REJECT = EPS ** 0.875
+NUM_JAC_DIFF_SMALL = EPS ** 0.75
+NUM_JAC_DIFF_BIG = EPS ** 0.25
+NUM_JAC_MIN_FACTOR = 1e3 * EPS
+NUM_JAC_FACTOR_INCREASE = 10
+NUM_JAC_FACTOR_DECREASE = 0.1
+
+
+def num_jac(fun, t, y, f, threshold, factor, sparsity=None):
+    """Finite differences Jacobian approximation tailored for ODE solvers.
+
+    This function computes finite difference approximation to the Jacobian
+    matrix of `fun` with respect to `y` using forward differences.
+    The Jacobian matrix has shape (n, n) and its element (i, j) is equal to
+    ``d f_i / d y_j``.
+
+    A special feature of this function is the ability to correct the step
+    size from iteration to iteration. The main idea is to keep the finite
+    difference significantly separated from its round-off error which
+    approximately equals ``EPS * np.abs(f)``. It reduces a possibility of a
+    huge error and assures that the estimated derivative are reasonably close
+    to the true values (i.e., the finite difference approximation is at least
+    qualitatively reflects the structure of the true Jacobian).
+
+    Parameters
+    ----------
+    fun : callable
+        Right-hand side of the system implemented in a vectorized fashion.
+    t : float
+        Current time.
+    y : ndarray, shape (n,)
+        Current state.
+    f : ndarray, shape (n,)
+        Value of the right hand side at (t, y).
+    threshold : float
+        Threshold for `y` value used for computing the step size as
+        ``factor * np.maximum(np.abs(y), threshold)``. Typically, the value of
+        absolute tolerance (atol) for a solver should be passed as `threshold`.
+    factor : ndarray with shape (n,) or None
+        Factor to use for computing the step size. Pass None for the very
+        evaluation, then use the value returned from this function.
+    sparsity : tuple (structure, groups) or None
+        Sparsity structure of the Jacobian. To get dense Jacobian use `None`.
+
+    Returns
+    -------
+    J : ndarray or csc_array or csc_matrix, shape (n, n)
+        Jacobian matrix.
+    factor : ndarray, shape (n,)
+        Suggested `factor` for the next evaluation.
+    """
+    y = np.asarray(y)
+    n = y.shape[0]
+    if n == 0:
+        return np.empty((0, 0)), factor
+
+    if factor is None:
+        factor = np.full(n, EPS ** 0.5)
+    else:
+        factor = factor.copy()
+
+    # Direct the step as ODE dictates, hoping that such a step won't lead to
+    # a problematic region. For complex ODEs it makes sense to use the real
+    # part of f as we use steps along real axis.
+    f_sign = 2 * (np.real(f) >= 0).astype(float) - 1
+    y_scale = f_sign * np.maximum(threshold, np.abs(y))
+    h = (y + factor * y_scale) - y
+
+    # Make sure that the step is not 0 to start with. Not likely it will be
+    # executed often.
+    for i in np.nonzero(h == 0)[0]:
+        while h[i] == 0:
+            factor[i] *= 10
+            h[i] = (y[i] + factor[i] * y_scale[i]) - y[i]
+
+    if sparsity is None:
+        return _dense_num_jac(fun, t, y, f, h, factor, y_scale)
+    else:
+        structure, groups = sparsity
+        return _sparse_num_jac(fun, t, y, f, h, factor, y_scale,
+                               structure, groups)
+
+
+def _dense_num_jac(fun, t, y, f, h, factor, y_scale):
+    n = y.shape[0]
+    h_vecs = np.diag(h)
+    f_new = fun(t, y[:, None] + h_vecs)
+    diff = f_new - f[:, None]
+    max_ind = np.argmax(np.abs(diff), axis=0)
+    r = np.arange(n)
+    max_diff = np.abs(diff[max_ind, r])
+    scale = np.maximum(np.abs(f[max_ind]), np.abs(f_new[max_ind, r]))
+
+    diff_too_small = max_diff < NUM_JAC_DIFF_REJECT * scale
+    if np.any(diff_too_small):
+        ind, = np.nonzero(diff_too_small)
+        new_factor = NUM_JAC_FACTOR_INCREASE * factor[ind]
+        h_new = (y[ind] + new_factor * y_scale[ind]) - y[ind]
+        h_vecs[ind, ind] = h_new
+        f_new = fun(t, y[:, None] + h_vecs[:, ind])
+        diff_new = f_new - f[:, None]
+        max_ind = np.argmax(np.abs(diff_new), axis=0)
+        r = np.arange(ind.shape[0])
+        max_diff_new = np.abs(diff_new[max_ind, r])
+        scale_new = np.maximum(np.abs(f[max_ind]), np.abs(f_new[max_ind, r]))
+
+        update = max_diff[ind] * scale_new < max_diff_new * scale[ind]
+        if np.any(update):
+            update, = np.nonzero(update)
+            update_ind = ind[update]
+            factor[update_ind] = new_factor[update]
+            h[update_ind] = h_new[update]
+            diff[:, update_ind] = diff_new[:, update]
+            scale[update_ind] = scale_new[update]
+            max_diff[update_ind] = max_diff_new[update]
+
+    diff /= h
+
+    factor[max_diff < NUM_JAC_DIFF_SMALL * scale] *= NUM_JAC_FACTOR_INCREASE
+    factor[max_diff > NUM_JAC_DIFF_BIG * scale] *= NUM_JAC_FACTOR_DECREASE
+    factor = np.maximum(factor, NUM_JAC_MIN_FACTOR)
+
+    return diff, factor
+
+
+def _sparse_num_jac(fun, t, y, f, h, factor, y_scale, structure, groups):
+    n = y.shape[0]
+    n_groups = np.max(groups) + 1
+    h_vecs = np.empty((n_groups, n), dtype=h.dtype)
+    for group in range(n_groups):
+        e = np.equal(group, groups)
+        h_vecs[group] = h * e
+    h_vecs = h_vecs.T
+
+    f_new = fun(t, y[:, None] + h_vecs)
+    df = f_new - f[:, None]
+
+    i, j, _ = find(structure)
+    diff = csc_array((df[i, groups[j]], (i, j)), shape=(n, n))
+    max_ind = np.array(abs(diff).argmax(axis=0)).ravel()
+    r = np.arange(n)
+    max_diff = np.asarray(np.abs(diff[max_ind, r])).ravel()
+    scale = np.maximum(np.abs(f[max_ind]),
+                       np.abs(f_new[max_ind, groups[r]]))
+
+    diff_too_small = max_diff < NUM_JAC_DIFF_REJECT * scale
+    if np.any(diff_too_small):
+        ind, = np.nonzero(diff_too_small)
+        new_factor = NUM_JAC_FACTOR_INCREASE * factor[ind]
+        h_new = (y[ind] + new_factor * y_scale[ind]) - y[ind]
+        h_new_all = np.zeros(n, dtype=h.dtype)
+        h_new_all[ind] = h_new
+
+        groups_unique = np.unique(groups[ind])
+        groups_map = np.empty(n_groups, dtype=int)
+        h_vecs = np.empty((groups_unique.shape[0], n), dtype=h.dtype)
+        for k, group in enumerate(groups_unique):
+            e = np.equal(group, groups)
+            h_vecs[k] = h_new_all * e
+            groups_map[group] = k
+        h_vecs = h_vecs.T
+
+        f_new = fun(t, y[:, None] + h_vecs)
+        df = f_new - f[:, None]
+        i, j, _ = find(structure[:, ind])
+        diff_new = csc_array((df[i, groups_map[groups[ind[j]]]], (i, j)),
+                             shape=(n, ind.shape[0]))
+
+        max_ind_new = np.array(abs(diff_new).argmax(axis=0)).ravel()
+        r = np.arange(ind.shape[0])
+        max_diff_new = np.asarray(np.abs(diff_new[max_ind_new, r])).ravel()
+        scale_new = np.maximum(
+            np.abs(f[max_ind_new]),
+            np.abs(f_new[max_ind_new, groups_map[groups[ind]]]))
+
+        update = max_diff[ind] * scale_new < max_diff_new * scale[ind]
+        if np.any(update):
+            update, = np.nonzero(update)
+            update_ind = ind[update]
+            factor[update_ind] = new_factor[update]
+            h[update_ind] = h_new[update]
+            diff[:, update_ind] = diff_new[:, update]
+            scale[update_ind] = scale_new[update]
+            max_diff[update_ind] = max_diff_new[update]
+
+    diff.data /= np.repeat(h, np.diff(diff.indptr))
+
+    factor[max_diff < NUM_JAC_DIFF_SMALL * scale] *= NUM_JAC_FACTOR_INCREASE
+    factor[max_diff > NUM_JAC_DIFF_BIG * scale] *= NUM_JAC_FACTOR_DECREASE
+    factor = np.maximum(factor, NUM_JAC_MIN_FACTOR)
+
+    # return spmatrix if structure is spmatrix
+    if isspmatrix(structure):
+        diff = csc_matrix(diff)
+    return diff, factor
diff --git a/.venv/lib/python3.12/site-packages/scipy/integrate/_ivp/dop853_coefficients.py b/.venv/lib/python3.12/site-packages/scipy/integrate/_ivp/dop853_coefficients.py
new file mode 100644
index 0000000000000000000000000000000000000000..f39f2f3650d321e2c475d4e220f9769139118a5e
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/integrate/_ivp/dop853_coefficients.py
@@ -0,0 +1,193 @@
+import numpy as np
+
+N_STAGES = 12
+N_STAGES_EXTENDED = 16
+INTERPOLATOR_POWER = 7
+
+C = np.array([0.0,
+              0.526001519587677318785587544488e-01,
+              0.789002279381515978178381316732e-01,
+              0.118350341907227396726757197510,
+              0.281649658092772603273242802490,
+              0.333333333333333333333333333333,
+              0.25,
+              0.307692307692307692307692307692,
+              0.651282051282051282051282051282,
+              0.6,
+              0.857142857142857142857142857142,
+              1.0,
+              1.0,
+              0.1,
+              0.2,
+              0.777777777777777777777777777778])
+
+A = np.zeros((N_STAGES_EXTENDED, N_STAGES_EXTENDED))
+A[1, 0] = 5.26001519587677318785587544488e-2
+
+A[2, 0] = 1.97250569845378994544595329183e-2
+A[2, 1] = 5.91751709536136983633785987549e-2
+
+A[3, 0] = 2.95875854768068491816892993775e-2
+A[3, 2] = 8.87627564304205475450678981324e-2
+
+A[4, 0] = 2.41365134159266685502369798665e-1
+A[4, 2] = -8.84549479328286085344864962717e-1
+A[4, 3] = 9.24834003261792003115737966543e-1
+
+A[5, 0] = 3.7037037037037037037037037037e-2
+A[5, 3] = 1.70828608729473871279604482173e-1
+A[5, 4] = 1.25467687566822425016691814123e-1
+
+A[6, 0] = 3.7109375e-2
+A[6, 3] = 1.70252211019544039314978060272e-1
+A[6, 4] = 6.02165389804559606850219397283e-2
+A[6, 5] = -1.7578125e-2
+
+A[7, 0] = 3.70920001185047927108779319836e-2
+A[7, 3] = 1.70383925712239993810214054705e-1
+A[7, 4] = 1.07262030446373284651809199168e-1
+A[7, 5] = -1.53194377486244017527936158236e-2
+A[7, 6] = 8.27378916381402288758473766002e-3
+
+A[8, 0] = 6.24110958716075717114429577812e-1
+A[8, 3] = -3.36089262944694129406857109825
+A[8, 4] = -8.68219346841726006818189891453e-1
+A[8, 5] = 2.75920996994467083049415600797e1
+A[8, 6] = 2.01540675504778934086186788979e1
+A[8, 7] = -4.34898841810699588477366255144e1
+
+A[9, 0] = 4.77662536438264365890433908527e-1
+A[9, 3] = -2.48811461997166764192642586468
+A[9, 4] = -5.90290826836842996371446475743e-1
+A[9, 5] = 2.12300514481811942347288949897e1
+A[9, 6] = 1.52792336328824235832596922938e1
+A[9, 7] = -3.32882109689848629194453265587e1
+A[9, 8] = -2.03312017085086261358222928593e-2
+
+A[10, 0] = -9.3714243008598732571704021658e-1
+A[10, 3] = 5.18637242884406370830023853209
+A[10, 4] = 1.09143734899672957818500254654
+A[10, 5] = -8.14978701074692612513997267357
+A[10, 6] = -1.85200656599969598641566180701e1
+A[10, 7] = 2.27394870993505042818970056734e1
+A[10, 8] = 2.49360555267965238987089396762
+A[10, 9] = -3.0467644718982195003823669022
+
+A[11, 0] = 2.27331014751653820792359768449
+A[11, 3] = -1.05344954667372501984066689879e1
+A[11, 4] = -2.00087205822486249909675718444
+A[11, 5] = -1.79589318631187989172765950534e1
+A[11, 6] = 2.79488845294199600508499808837e1
+A[11, 7] = -2.85899827713502369474065508674
+A[11, 8] = -8.87285693353062954433549289258
+A[11, 9] = 1.23605671757943030647266201528e1
+A[11, 10] = 6.43392746015763530355970484046e-1
+
+A[12, 0] = 5.42937341165687622380535766363e-2
+A[12, 5] = 4.45031289275240888144113950566
+A[12, 6] = 1.89151789931450038304281599044
+A[12, 7] = -5.8012039600105847814672114227
+A[12, 8] = 3.1116436695781989440891606237e-1
+A[12, 9] = -1.52160949662516078556178806805e-1
+A[12, 10] = 2.01365400804030348374776537501e-1
+A[12, 11] = 4.47106157277725905176885569043e-2
+
+A[13, 0] = 5.61675022830479523392909219681e-2
+A[13, 6] = 2.53500210216624811088794765333e-1
+A[13, 7] = -2.46239037470802489917441475441e-1
+A[13, 8] = -1.24191423263816360469010140626e-1
+A[13, 9] = 1.5329179827876569731206322685e-1
+A[13, 10] = 8.20105229563468988491666602057e-3
+A[13, 11] = 7.56789766054569976138603589584e-3
+A[13, 12] = -8.298e-3
+
+A[14, 0] = 3.18346481635021405060768473261e-2
+A[14, 5] = 2.83009096723667755288322961402e-2
+A[14, 6] = 5.35419883074385676223797384372e-2
+A[14, 7] = -5.49237485713909884646569340306e-2
+A[14, 10] = -1.08347328697249322858509316994e-4
+A[14, 11] = 3.82571090835658412954920192323e-4
+A[14, 12] = -3.40465008687404560802977114492e-4
+A[14, 13] = 1.41312443674632500278074618366e-1
+
+A[15, 0] = -4.28896301583791923408573538692e-1
+A[15, 5] = -4.69762141536116384314449447206
+A[15, 6] = 7.68342119606259904184240953878
+A[15, 7] = 4.06898981839711007970213554331
+A[15, 8] = 3.56727187455281109270669543021e-1
+A[15, 12] = -1.39902416515901462129418009734e-3
+A[15, 13] = 2.9475147891527723389556272149
+A[15, 14] = -9.15095847217987001081870187138
+
+
+B = A[N_STAGES, :N_STAGES]
+
+E3 = np.zeros(N_STAGES + 1)
+E3[:-1] = B.copy()
+E3[0] -= 0.244094488188976377952755905512
+E3[8] -= 0.733846688281611857341361741547
+E3[11] -= 0.220588235294117647058823529412e-1
+
+E5 = np.zeros(N_STAGES + 1)
+E5[0] = 0.1312004499419488073250102996e-1
+E5[5] = -0.1225156446376204440720569753e+1
+E5[6] = -0.4957589496572501915214079952
+E5[7] = 0.1664377182454986536961530415e+1
+E5[8] = -0.3503288487499736816886487290
+E5[9] = 0.3341791187130174790297318841
+E5[10] = 0.8192320648511571246570742613e-1
+E5[11] = -0.2235530786388629525884427845e-1
+
+# First 3 coefficients are computed separately.
+D = np.zeros((INTERPOLATOR_POWER - 3, N_STAGES_EXTENDED))
+D[0, 0] = -0.84289382761090128651353491142e+1
+D[0, 5] = 0.56671495351937776962531783590
+D[0, 6] = -0.30689499459498916912797304727e+1
+D[0, 7] = 0.23846676565120698287728149680e+1
+D[0, 8] = 0.21170345824450282767155149946e+1
+D[0, 9] = -0.87139158377797299206789907490
+D[0, 10] = 0.22404374302607882758541771650e+1
+D[0, 11] = 0.63157877876946881815570249290
+D[0, 12] = -0.88990336451333310820698117400e-1
+D[0, 13] = 0.18148505520854727256656404962e+2
+D[0, 14] = -0.91946323924783554000451984436e+1
+D[0, 15] = -0.44360363875948939664310572000e+1
+
+D[1, 0] = 0.10427508642579134603413151009e+2
+D[1, 5] = 0.24228349177525818288430175319e+3
+D[1, 6] = 0.16520045171727028198505394887e+3
+D[1, 7] = -0.37454675472269020279518312152e+3
+D[1, 8] = -0.22113666853125306036270938578e+2
+D[1, 9] = 0.77334326684722638389603898808e+1
+D[1, 10] = -0.30674084731089398182061213626e+2
+D[1, 11] = -0.93321305264302278729567221706e+1
+D[1, 12] = 0.15697238121770843886131091075e+2
+D[1, 13] = -0.31139403219565177677282850411e+2
+D[1, 14] = -0.93529243588444783865713862664e+1
+D[1, 15] = 0.35816841486394083752465898540e+2
+
+D[2, 0] = 0.19985053242002433820987653617e+2
+D[2, 5] = -0.38703730874935176555105901742e+3
+D[2, 6] = -0.18917813819516756882830838328e+3
+D[2, 7] = 0.52780815920542364900561016686e+3
+D[2, 8] = -0.11573902539959630126141871134e+2
+D[2, 9] = 0.68812326946963000169666922661e+1
+D[2, 10] = -0.10006050966910838403183860980e+1
+D[2, 11] = 0.77771377980534432092869265740
+D[2, 12] = -0.27782057523535084065932004339e+1
+D[2, 13] = -0.60196695231264120758267380846e+2
+D[2, 14] = 0.84320405506677161018159903784e+2
+D[2, 15] = 0.11992291136182789328035130030e+2
+
+D[3, 0] = -0.25693933462703749003312586129e+2
+D[3, 5] = -0.15418974869023643374053993627e+3
+D[3, 6] = -0.23152937917604549567536039109e+3
+D[3, 7] = 0.35763911791061412378285349910e+3
+D[3, 8] = 0.93405324183624310003907691704e+2
+D[3, 9] = -0.37458323136451633156875139351e+2
+D[3, 10] = 0.10409964950896230045147246184e+3
+D[3, 11] = 0.29840293426660503123344363579e+2
+D[3, 12] = -0.43533456590011143754432175058e+2
+D[3, 13] = 0.96324553959188282948394950600e+2
+D[3, 14] = -0.39177261675615439165231486172e+2
+D[3, 15] = -0.14972683625798562581422125276e+3
diff --git a/.venv/lib/python3.12/site-packages/scipy/integrate/_ivp/ivp.py b/.venv/lib/python3.12/site-packages/scipy/integrate/_ivp/ivp.py
new file mode 100644
index 0000000000000000000000000000000000000000..fee56ef5eca8e395946e29ad74de57514f47349f
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/integrate/_ivp/ivp.py
@@ -0,0 +1,760 @@
+import inspect
+import numpy as np
+from .bdf import BDF
+from .radau import Radau
+from .rk import RK23, RK45, DOP853
+from .lsoda import LSODA
+from scipy.optimize import OptimizeResult
+from .common import EPS, OdeSolution
+from .base import OdeSolver
+from scipy._lib._array_api import xp_capabilities
+
+
+METHODS = {'RK23': RK23,
+           'RK45': RK45,
+           'DOP853': DOP853,
+           'Radau': Radau,
+           'BDF': BDF,
+           'LSODA': LSODA}
+
+
+MESSAGES = {0: "The solver successfully reached the end of the integration interval.",
+            1: "A termination event occurred."}
+
+
+class OdeResult(OptimizeResult):
+    pass
+
+
+def prepare_events(events):
+    """Standardize event functions and extract attributes."""
+    if callable(events):
+        events = (events,)
+
+    max_events = np.empty(len(events))
+    direction = np.empty(len(events))
+    for i, event in enumerate(events):
+        terminal = getattr(event, 'terminal', None)
+        direction[i] = getattr(event, 'direction', 0)
+
+        message = ('The `terminal` attribute of each event '
+                   'must be a boolean or positive integer.')
+        if terminal is None or terminal == 0:
+            max_events[i] = np.inf
+        elif int(terminal) == terminal and terminal > 0:
+            max_events[i] = terminal
+        else:
+            raise ValueError(message)
+
+    return events, max_events, direction
+
+
+def solve_event_equation(event, sol, t_old, t):
+    """Solve an equation corresponding to an ODE event.
+
+    The equation is ``event(t, y(t)) = 0``, here ``y(t)`` is known from an
+    ODE solver using some sort of interpolation. It is solved by
+    `scipy.optimize.brentq` with xtol=atol=4*EPS.
+
+    Parameters
+    ----------
+    event : callable
+        Function ``event(t, y)``.
+    sol : callable
+        Function ``sol(t)`` which evaluates an ODE solution between `t_old`
+        and  `t`.
+    t_old, t : float
+        Previous and new values of time. They will be used as a bracketing
+        interval.
+
+    Returns
+    -------
+    root : float
+        Found solution.
+    """
+    from scipy.optimize import brentq
+    return brentq(lambda t: event(t, sol(t)), t_old, t,
+                  xtol=4 * EPS, rtol=4 * EPS)
+
+
+def handle_events(sol, events, active_events, event_count, max_events,
+                  t_old, t):
+    """Helper function to handle events.
+
+    Parameters
+    ----------
+    sol : DenseOutput
+        Function ``sol(t)`` which evaluates an ODE solution between `t_old`
+        and  `t`.
+    events : list of callables, length n_events
+        Event functions with signatures ``event(t, y)``.
+    active_events : ndarray
+        Indices of events which occurred.
+    event_count : ndarray
+        Current number of occurrences for each event.
+    max_events : ndarray, shape (n_events,)
+        Number of occurrences allowed for each event before integration
+        termination is issued.
+    t_old, t : float
+        Previous and new values of time.
+
+    Returns
+    -------
+    root_indices : ndarray
+        Indices of events which take zero between `t_old` and `t` and before
+        a possible termination.
+    roots : ndarray
+        Values of t at which events occurred.
+    terminate : bool
+        Whether a terminal event occurred.
+    """
+    roots = [solve_event_equation(events[event_index], sol, t_old, t)
+             for event_index in active_events]
+
+    roots = np.asarray(roots)
+
+    if np.any(event_count[active_events] >= max_events[active_events]):
+        if t > t_old:
+            order = np.argsort(roots)
+        else:
+            order = np.argsort(-roots)
+        active_events = active_events[order]
+        roots = roots[order]
+        t = np.nonzero(event_count[active_events]
+                       >= max_events[active_events])[0][0]
+        active_events = active_events[:t + 1]
+        roots = roots[:t + 1]
+        terminate = True
+    else:
+        terminate = False
+
+    return active_events, roots, terminate
+
+
+def find_active_events(g, g_new, direction):
+    """Find which event occurred during an integration step.
+
+    Parameters
+    ----------
+    g, g_new : array_like, shape (n_events,)
+        Values of event functions at a current and next points.
+    direction : ndarray, shape (n_events,)
+        Event "direction" according to the definition in `solve_ivp`.
+
+    Returns
+    -------
+    active_events : ndarray
+        Indices of events which occurred during the step.
+    """
+    g, g_new = np.asarray(g), np.asarray(g_new)
+    up = (g <= 0) & (g_new >= 0)
+    down = (g >= 0) & (g_new <= 0)
+    either = up | down
+    mask = (up & (direction > 0) |
+            down & (direction < 0) |
+            either & (direction == 0))
+
+    return np.nonzero(mask)[0]
+
+
+@xp_capabilities(np_only=True)
+def solve_ivp(fun, t_span, y0, method='RK45', t_eval=None, dense_output=False,
+              events=None, vectorized=False, args=None, **options):
+    """Solve an initial value problem for a system of ODEs.
+
+    This function numerically integrates a system of ordinary differential
+    equations given an initial value::
+
+        dy / dt = f(t, y)
+        y(t0) = y0
+
+    Here t is a 1-D independent variable (time), y(t) is an
+    N-D vector-valued function (state), and an N-D
+    vector-valued function f(t, y) determines the differential equations.
+    The goal is to find y(t) approximately satisfying the differential
+    equations, given an initial value y(t0)=y0.
+
+    Some of the solvers support integration in the complex domain, but note
+    that for stiff ODE solvers, the right-hand side must be
+    complex-differentiable (satisfy Cauchy-Riemann equations [11]_).
+    To solve a problem in the complex domain, pass y0 with a complex data type.
+    Another option always available is to rewrite your problem for real and
+    imaginary parts separately.
+
+    Parameters
+    ----------
+    fun : callable
+        Right-hand side of the system: the time derivative of the state ``y``
+        at time ``t``. The calling signature is ``fun(t, y)``, where ``t`` is a
+        scalar and ``y`` is an ndarray with ``len(y) = len(y0)``. Additional
+        arguments need to be passed if ``args`` is used (see documentation of
+        ``args`` argument). ``fun`` must return an array of the same shape as
+        ``y``. See `vectorized` for more information.
+    t_span : 2-member sequence
+        Interval of integration (t0, tf). The solver starts with t=t0 and
+        integrates until it reaches t=tf. Both t0 and tf must be floats
+        or values interpretable by the float conversion function.
+    y0 : array_like, shape (n,)
+        Initial state. For problems in the complex domain, pass `y0` with a
+        complex data type (even if the initial value is purely real).
+    method : str or `OdeSolver`, optional
+        Integration method to use:
+
+        * **'RK45' (default)**: Explicit Runge-Kutta method of order 5(4) [1]_.
+          The error is controlled assuming accuracy of the fourth-order
+          method, but steps are taken using the fifth-order accurate
+          formula (local extrapolation is done). A quartic interpolation
+          polynomial is used for the dense output [2]_. Can be applied in
+          the complex domain.
+        * **'RK23'**: Explicit Runge-Kutta method of order 3(2) [3]_. The error
+          is controlled assuming accuracy of the second-order method, but
+          steps are taken using the third-order accurate formula (local
+          extrapolation is done). A cubic Hermite polynomial is used for the
+          dense output. Can be applied in the complex domain.
+        * **'DOP853'**: Explicit Runge-Kutta method of order 8 [13]_.
+          Python implementation of the "DOP853" algorithm originally
+          written in Fortran [14]_. A 7-th order interpolation polynomial
+          accurate to 7-th order is used for the dense output.
+          Can be applied in the complex domain.
+        * **'Radau'**: Implicit Runge-Kutta method of the Radau IIA family of
+          order 5 [4]_. The error is controlled with a third-order accurate
+          embedded formula. A cubic polynomial which satisfies the
+          collocation conditions is used for the dense output.
+        * **'BDF'**: Implicit multi-step variable-order (1 to 5) method based
+          on a backward differentiation formula for the derivative
+          approximation [5]_. The implementation follows the one described
+          in [6]_. A quasi-constant step scheme is used and accuracy is
+          enhanced using the NDF modification. Can be applied in the
+          complex domain.
+        * **'LSODA'**: Adams/BDF method with automatic stiffness detection and
+          switching [7]_, [8]_. This is a wrapper of the Fortran solver
+          from ODEPACK.
+
+        Explicit Runge-Kutta methods ('RK23', 'RK45', 'DOP853') should be used
+        for non-stiff problems and implicit methods ('Radau', 'BDF') for
+        stiff problems [9]_. Among Runge-Kutta methods, 'DOP853' is recommended
+        for solving with high precision (low values of `rtol` and `atol`).
+
+        If not sure, first try to run 'RK45'. If it makes unusually many
+        iterations, diverges, or fails, your problem is likely to be stiff and
+        you should use 'Radau' or 'BDF'. 'LSODA' can also be a good universal
+        choice, but it might be somewhat less convenient to work with as it
+        wraps old Fortran code.
+
+        You can also pass an arbitrary class derived from `OdeSolver` which
+        implements the solver.
+    t_eval : array_like or None, optional
+        Times at which to store the computed solution, must be sorted and lie
+        within `t_span`. If None (default), use points selected by the solver.
+    dense_output : bool, optional
+        Whether to compute a continuous solution. Default is False.
+    events : callable, or list of callables, optional
+        Events to track. If None (default), no events will be tracked.
+        Each event occurs at the zeros of a continuous function of time and
+        state. Each function must have the signature ``event(t, y)`` where
+        additional argument have to be passed if ``args`` is used (see
+        documentation of ``args`` argument). Each function must return a
+        float. The solver will find an accurate value of `t` at which
+        ``event(t, y(t)) = 0`` using a root-finding algorithm. By default,
+        all zeros will be found. The solver looks for a sign change over
+        each step, so if multiple zero crossings occur within one step,
+        events may be missed. Additionally each `event` function might
+        have the following attributes:
+
+        terminal: bool or int, optional
+            When boolean, whether to terminate integration if this event occurs.
+            When integral, termination occurs after the specified the number of
+            occurrences of this event.
+            Implicitly False if not assigned.
+        direction: float, optional
+            Direction of a zero crossing. If `direction` is positive,
+            `event` will only trigger when going from negative to positive,
+            and vice versa if `direction` is negative. If 0, then either
+            direction will trigger event. Implicitly 0 if not assigned.
+
+        You can assign attributes like ``event.terminal = True`` to any
+        function in Python.
+    vectorized : bool, optional
+        Whether `fun` can be called in a vectorized fashion. Default is False.
+
+        If ``vectorized`` is False, `fun` will always be called with ``y`` of
+        shape ``(n,)``, where ``n = len(y0)``.
+
+        If ``vectorized`` is True, `fun` may be called with ``y`` of shape
+        ``(n, k)``, where ``k`` is an integer. In this case, `fun` must behave
+        such that ``fun(t, y)[:, i] == fun(t, y[:, i])`` (i.e. each column of
+        the returned array is the time derivative of the state corresponding
+        with a column of ``y``).
+
+        Setting ``vectorized=True`` allows for faster finite difference
+        approximation of the Jacobian by methods 'Radau' and 'BDF', but
+        will result in slower execution for other methods and for 'Radau' and
+        'BDF' in some circumstances (e.g. small ``len(y0)``).
+    args : tuple, optional
+        Additional arguments to pass to the user-defined functions.  If given,
+        the additional arguments are passed to all user-defined functions.
+        So if, for example, `fun` has the signature ``fun(t, y, a, b, c)``,
+        then `jac` (if given) and any event functions must have the same
+        signature, and `args` must be a tuple of length 3.
+    **options
+        Options passed to a chosen solver. All options available for already
+        implemented solvers are listed below.
+
+        first_step : float or None, optional
+            Initial step size. Default is `None` which means that the algorithm
+            should choose.
+        max_step : float, optional
+            Maximum allowed step size. Default is np.inf, i.e., the step size is not
+            bounded and determined solely by the solver.
+        rtol, atol : float or array_like, optional
+            Relative and absolute tolerances. The solver keeps the local error
+            estimates less than ``atol + rtol * abs(y)``. Here `rtol` controls a
+            relative accuracy (number of correct digits), while `atol` controls
+            absolute accuracy (number of correct decimal places). To achieve the
+            desired `rtol`, set `atol` to be smaller than the smallest value that
+            can be expected from ``rtol * abs(y)`` so that `rtol` dominates the
+            allowable error. If `atol` is larger than ``rtol * abs(y)`` the
+            number of correct digits is not guaranteed. Conversely, to achieve the
+            desired `atol` set `rtol` such that ``rtol * abs(y)`` is always smaller
+            than `atol`. If components of y have different scales, it might be
+            beneficial to set different `atol` values for different components by
+            passing array_like with shape (n,) for `atol`. Default values are
+            1e-3 for `rtol` and 1e-6 for `atol`.
+        jac : array_like, sparse_matrix, callable or None, optional
+            Jacobian matrix of the right-hand side of the system with respect
+            to y, required by the 'Radau', 'BDF' and 'LSODA' method. The
+            Jacobian matrix has shape (n, n) and its element (i, j) is equal to
+            ``d f_i / d y_j``.  There are three ways to define the Jacobian:
+
+            * If array_like or sparse_matrix, the Jacobian is assumed to
+              be constant. Not supported by 'LSODA'.
+            * If callable, the Jacobian is assumed to depend on both
+              t and y; it will be called as ``jac(t, y)``, as necessary.
+              Additional arguments have to be passed if ``args`` is
+              used (see documentation of ``args`` argument).
+              For 'Radau' and 'BDF' methods, the return value might be a
+              sparse matrix.
+            * If None (default), the Jacobian will be approximated by
+              finite differences.
+
+            It is generally recommended to provide the Jacobian rather than
+            relying on a finite-difference approximation.
+        jac_sparsity : array_like, sparse matrix or None, optional
+            Defines a sparsity structure of the Jacobian matrix for a finite-
+            difference approximation. Its shape must be (n, n). This argument
+            is ignored if `jac` is not `None`. If the Jacobian has only few
+            non-zero elements in *each* row, providing the sparsity structure
+            will greatly speed up the computations [10]_. A zero entry means that
+            a corresponding element in the Jacobian is always zero. If None
+            (default), the Jacobian is assumed to be dense.
+            Not supported by 'LSODA', see `lband` and `uband` instead.
+        lband, uband : int or None, optional
+            Parameters defining the bandwidth of the Jacobian for the 'LSODA'
+            method, i.e., ``jac[i, j] != 0 only for i - lband <= j <= i + uband``.
+            Default is None. Setting these requires your jac routine to return the
+            Jacobian in the packed format: the returned array must have ``n``
+            columns and ``uband + lband + 1`` rows in which Jacobian diagonals are
+            written. Specifically ``jac_packed[uband + i - j , j] = jac[i, j]``.
+            The same format is used in `scipy.linalg.solve_banded` (check for an
+            illustration).  These parameters can be also used with ``jac=None`` to
+            reduce the number of Jacobian elements estimated by finite differences.
+        min_step : float, optional
+            The minimum allowed step size for 'LSODA' method.
+            By default `min_step` is zero.
+
+    Returns
+    -------
+    result : OdeResult
+        Bunch object with the following fields defined:
+
+        t : ndarray, shape (n_points,)
+            Time points.
+        y : ndarray, shape (n, n_points)
+            Values of the solution at `t`.
+        sol : `OdeSolution` or None
+            Found solution as `OdeSolution` instance; None if `dense_output` was
+            set to False.
+        t_events : list of ndarray or None
+            Contains for each event type a list of arrays at which an event of
+            that type event was detected. None if `events` was None.
+        y_events : list of ndarray or None
+            For each value of `t_events`, the corresponding value of the solution.
+            None if `events` was None.
+        nfev : int
+            Number of evaluations of the right-hand side.
+        njev : int
+            Number of evaluations of the Jacobian.
+        nlu : int
+            Number of LU decompositions.
+        status : int
+            Reason for algorithm termination:
+
+            * -1: Integration step failed.
+            *  0: The solver successfully reached the end of `tspan`.
+            *  1: A termination event occurred.
+
+        message : str
+            Human-readable description of the termination reason.
+        success : bool
+            True if the solver reached the interval end or a termination event
+            occurred (``status >= 0``).
+
+    References
+    ----------
+    .. [1] J. R. Dormand, P. J. Prince, "A family of embedded Runge-Kutta
+           formulae", Journal of Computational and Applied Mathematics, Vol. 6,
+           No. 1, pp. 19-26, 1980.
+    .. [2] L. W. Shampine, "Some Practical Runge-Kutta Formulas", Mathematics
+           of Computation,, Vol. 46, No. 173, pp. 135-150, 1986.
+    .. [3] P. Bogacki, L.F. Shampine, "A 3(2) Pair of Runge-Kutta Formulas",
+           Appl. Math. Lett. Vol. 2, No. 4. pp. 321-325, 1989.
+    .. [4] E. Hairer, G. Wanner, "Solving Ordinary Differential Equations II:
+           Stiff and Differential-Algebraic Problems", Sec. IV.8.
+    .. [5] `Backward Differentiation Formula
+            `_
+            on Wikipedia.
+    .. [6] L. F. Shampine, M. W. Reichelt, "THE MATLAB ODE SUITE", SIAM J. SCI.
+           COMPUTE., Vol. 18, No. 1, pp. 1-22, January 1997.
+    .. [7] A. C. Hindmarsh, "ODEPACK, A Systematized Collection of ODE
+           Solvers," IMACS Transactions on Scientific Computation, Vol 1.,
+           pp. 55-64, 1983.
+    .. [8] L. Petzold, "Automatic selection of methods for solving stiff and
+           nonstiff systems of ordinary differential equations", SIAM Journal
+           on Scientific and Statistical Computing, Vol. 4, No. 1, pp. 136-148,
+           1983.
+    .. [9] `Stiff equation `_ on
+           Wikipedia.
+    .. [10] A. Curtis, M. J. D. Powell, and J. Reid, "On the estimation of
+            sparse Jacobian matrices", Journal of the Institute of Mathematics
+            and its Applications, 13, pp. 117-120, 1974.
+    .. [11] `Cauchy-Riemann equations
+             `_ on
+             Wikipedia.
+    .. [12] `Lotka-Volterra equations
+            `_
+            on Wikipedia.
+    .. [13] E. Hairer, S. P. Norsett G. Wanner, "Solving Ordinary Differential
+            Equations I: Nonstiff Problems", Sec. II.
+    .. [14] `Page with original Fortran code of DOP853
+            `_.
+
+    Examples
+    --------
+    Basic exponential decay showing automatically chosen time points.
+
+    >>> import numpy as np
+    >>> from scipy.integrate import solve_ivp
+    >>> def exponential_decay(t, y): return -0.5 * y
+    >>> sol = solve_ivp(exponential_decay, [0, 10], [2, 4, 8])
+    >>> print(sol.t)
+    [ 0.          0.11487653  1.26364188  3.06061781  4.81611105  6.57445806
+      8.33328988 10.        ]
+    >>> print(sol.y)
+    [[2.         1.88836035 1.06327177 0.43319312 0.18017253 0.07483045
+      0.03107158 0.01350781]
+     [4.         3.7767207  2.12654355 0.86638624 0.36034507 0.14966091
+      0.06214316 0.02701561]
+     [8.         7.5534414  4.25308709 1.73277247 0.72069014 0.29932181
+      0.12428631 0.05403123]]
+
+    Specifying points where the solution is desired.
+
+    >>> sol = solve_ivp(exponential_decay, [0, 10], [2, 4, 8],
+    ...                 t_eval=[0, 1, 2, 4, 10])
+    >>> print(sol.t)
+    [ 0  1  2  4 10]
+    >>> print(sol.y)
+    [[2.         1.21305369 0.73534021 0.27066736 0.01350938]
+     [4.         2.42610739 1.47068043 0.54133472 0.02701876]
+     [8.         4.85221478 2.94136085 1.08266944 0.05403753]]
+
+    Cannon fired upward with terminal event upon impact. The ``terminal`` and
+    ``direction`` fields of an event are applied by monkey patching a function.
+    Here ``y[0]`` is position and ``y[1]`` is velocity. The projectile starts
+    at position 0 with velocity +10. Note that the integration never reaches
+    t=100 because the event is terminal.
+
+    >>> def upward_cannon(t, y): return [y[1], -0.5]
+    >>> def hit_ground(t, y): return y[0]
+    >>> hit_ground.terminal = True
+    >>> hit_ground.direction = -1
+    >>> sol = solve_ivp(upward_cannon, [0, 100], [0, 10], events=hit_ground)
+    >>> print(sol.t_events)
+    [array([40.])]
+    >>> print(sol.t)
+    [0.00000000e+00 9.99900010e-05 1.09989001e-03 1.10988901e-02
+     1.11088891e-01 1.11098890e+00 1.11099890e+01 4.00000000e+01]
+
+    Use `dense_output` and `events` to find position, which is 100, at the apex
+    of the cannonball's trajectory. Apex is not defined as terminal, so both
+    apex and hit_ground are found. There is no information at t=20, so the sol
+    attribute is used to evaluate the solution. The sol attribute is returned
+    by setting ``dense_output=True``. Alternatively, the `y_events` attribute
+    can be used to access the solution at the time of the event.
+
+    >>> def apex(t, y): return y[1]
+    >>> sol = solve_ivp(upward_cannon, [0, 100], [0, 10],
+    ...                 events=(hit_ground, apex), dense_output=True)
+    >>> print(sol.t_events)
+    [array([40.]), array([20.])]
+    >>> print(sol.t)
+    [0.00000000e+00 9.99900010e-05 1.09989001e-03 1.10988901e-02
+     1.11088891e-01 1.11098890e+00 1.11099890e+01 4.00000000e+01]
+    >>> print(sol.sol(sol.t_events[1][0]))
+    [100.   0.]
+    >>> print(sol.y_events)
+    [array([[-5.68434189e-14, -1.00000000e+01]]),
+     array([[1.00000000e+02, 1.77635684e-15]])]
+
+    As an example of a system with additional parameters, we'll implement
+    the Lotka-Volterra equations [12]_.
+
+    >>> def lotkavolterra(t, z, a, b, c, d):
+    ...     x, y = z
+    ...     return [a*x - b*x*y, -c*y + d*x*y]
+    ...
+
+    We pass in the parameter values a=1.5, b=1, c=3 and d=1 with the `args`
+    argument.
+
+    >>> sol = solve_ivp(lotkavolterra, [0, 15], [10, 5], args=(1.5, 1, 3, 1),
+    ...                 dense_output=True)
+
+    Compute a dense solution and plot it.
+
+    >>> t = np.linspace(0, 15, 300)
+    >>> z = sol.sol(t)
+    >>> import matplotlib.pyplot as plt
+    >>> plt.plot(t, z.T)
+    >>> plt.xlabel('t')
+    >>> plt.legend(['x', 'y'], shadow=True)
+    >>> plt.title('Lotka-Volterra System')
+    >>> plt.show()
+
+    A couple examples of using solve_ivp to solve the differential
+    equation ``y' = Ay`` with complex matrix ``A``.
+
+    >>> A = np.array([[-0.25 + 0.14j, 0, 0.33 + 0.44j],
+    ...               [0.25 + 0.58j, -0.2 + 0.14j, 0],
+    ...               [0, 0.2 + 0.4j, -0.1 + 0.97j]])
+
+    Solving an IVP with ``A`` from above and ``y`` as 3x1 vector:
+
+    >>> def deriv_vec(t, y):
+    ...     return A @ y
+    >>> result = solve_ivp(deriv_vec, [0, 25],
+    ...                    np.array([10 + 0j, 20 + 0j, 30 + 0j]),
+    ...                    t_eval=np.linspace(0, 25, 101))
+    >>> print(result.y[:, 0])
+    [10.+0.j 20.+0.j 30.+0.j]
+    >>> print(result.y[:, -1])
+    [18.46291039+45.25653651j 10.01569306+36.23293216j
+     -4.98662741+80.07360388j]
+
+    Solving an IVP with ``A`` from above with ``y`` as 3x3 matrix :
+
+    >>> def deriv_mat(t, y):
+    ...     return (A @ y.reshape(3, 3)).flatten()
+    >>> y0 = np.array([[2 + 0j, 3 + 0j, 4 + 0j],
+    ...                [5 + 0j, 6 + 0j, 7 + 0j],
+    ...                [9 + 0j, 34 + 0j, 78 + 0j]])
+
+    >>> result = solve_ivp(deriv_mat, [0, 25], y0.flatten(),
+    ...                    t_eval=np.linspace(0, 25, 101))
+    >>> print(result.y[:, 0].reshape(3, 3))
+    [[ 2.+0.j  3.+0.j  4.+0.j]
+     [ 5.+0.j  6.+0.j  7.+0.j]
+     [ 9.+0.j 34.+0.j 78.+0.j]]
+    >>> print(result.y[:, -1].reshape(3, 3))
+    [[  5.67451179 +12.07938445j  17.2888073  +31.03278837j
+        37.83405768 +63.25138759j]
+     [  3.39949503 +11.82123994j  21.32530996 +44.88668871j
+        53.17531184+103.80400411j]
+     [ -2.26105874 +22.19277664j -15.1255713  +70.19616341j
+       -38.34616845+153.29039931j]]
+
+
+    """
+    if method not in METHODS and not (
+            inspect.isclass(method) and issubclass(method, OdeSolver)):
+        raise ValueError(f"`method` must be one of {METHODS} or OdeSolver class.")
+
+    t0, tf = map(float, t_span)
+
+    if args is not None:
+        # Wrap the user's fun (and jac, if given) in lambdas to hide the
+        # additional parameters.  Pass in the original fun as a keyword
+        # argument to keep it in the scope of the lambda.
+        try:
+            _ = [*(args)]
+        except TypeError as exp:
+            suggestion_tuple = (
+                "Supplied 'args' cannot be unpacked. Please supply `args`"
+                f" as a tuple (e.g. `args=({args},)`)"
+            )
+            raise TypeError(suggestion_tuple) from exp
+
+        def fun(t, x, fun=fun):
+            return fun(t, x, *args)
+        jac = options.get('jac')
+        if callable(jac):
+            options['jac'] = lambda t, x: jac(t, x, *args)
+
+    if t_eval is not None:
+        t_eval = np.asarray(t_eval)
+        if t_eval.ndim != 1:
+            raise ValueError("`t_eval` must be 1-dimensional.")
+
+        if np.any(t_eval < min(t0, tf)) or np.any(t_eval > max(t0, tf)):
+            raise ValueError("Values in `t_eval` are not within `t_span`.")
+
+        d = np.diff(t_eval)
+        if tf > t0 and np.any(d <= 0) or tf < t0 and np.any(d >= 0):
+            raise ValueError("Values in `t_eval` are not properly sorted.")
+
+        if tf > t0:
+            t_eval_i = 0
+        else:
+            # Make order of t_eval decreasing to use np.searchsorted.
+            t_eval = t_eval[::-1]
+            # This will be an upper bound for slices.
+            t_eval_i = t_eval.shape[0]
+
+    if method in METHODS:
+        method = METHODS[method]
+
+    solver = method(fun, t0, y0, tf, vectorized=vectorized, **options)
+
+    if t_eval is None:
+        ts = [t0]
+        ys = [y0]
+    elif t_eval is not None and dense_output:
+        ts = []
+        ti = [t0]
+        ys = []
+    else:
+        ts = []
+        ys = []
+
+    interpolants = []
+
+    if events is not None:
+        events, max_events, event_dir = prepare_events(events)
+        event_count = np.zeros(len(events))
+        if args is not None:
+            # Wrap user functions in lambdas to hide the additional parameters.
+            # The original event function is passed as a keyword argument to the
+            # lambda to keep the original function in scope (i.e., avoid the
+            # late binding closure "gotcha").
+            events = [lambda t, x, event=event: event(t, x, *args)
+                      for event in events]
+        g = [event(t0, y0) for event in events]
+        t_events = [[] for _ in range(len(events))]
+        y_events = [[] for _ in range(len(events))]
+    else:
+        t_events = None
+        y_events = None
+
+    status = None
+    while status is None:
+        message = solver.step()
+
+        if solver.status == 'finished':
+            status = 0
+        elif solver.status == 'failed':
+            status = -1
+            break
+
+        t_old = solver.t_old
+        t = solver.t
+        y = solver.y
+
+        if dense_output:
+            sol = solver.dense_output()
+            interpolants.append(sol)
+        else:
+            sol = None
+
+        if events is not None:
+            g_new = [event(t, y) for event in events]
+            active_events = find_active_events(g, g_new, event_dir)
+            if active_events.size > 0:
+                if sol is None:
+                    sol = solver.dense_output()
+
+                event_count[active_events] += 1
+                root_indices, roots, terminate = handle_events(
+                    sol, events, active_events, event_count, max_events,
+                    t_old, t)
+
+                for e, te in zip(root_indices, roots):
+                    t_events[e].append(te)
+                    y_events[e].append(sol(te))
+
+                if terminate:
+                    status = 1
+                    t = roots[-1]
+                    y = sol(t)
+
+            g = g_new
+
+        if t_eval is None:
+            donot_append = (len(ts) > 1 and
+                            ts[-1] == t and
+                            dense_output)
+            if not donot_append:
+                ts.append(t)
+                ys.append(y)
+            else:
+                if len(interpolants) > 0:
+                    interpolants.pop()
+        else:
+            # The value in t_eval equal to t will be included.
+            if solver.direction > 0:
+                t_eval_i_new = np.searchsorted(t_eval, t, side='right')
+                t_eval_step = t_eval[t_eval_i:t_eval_i_new]
+            else:
+                t_eval_i_new = np.searchsorted(t_eval, t, side='left')
+                # It has to be done with two slice operations, because
+                # you can't slice to 0th element inclusive using backward
+                # slicing.
+                t_eval_step = t_eval[t_eval_i_new:t_eval_i][::-1]
+
+            if t_eval_step.size > 0:
+                if sol is None:
+                    sol = solver.dense_output()
+                ts.append(t_eval_step)
+                ys.append(sol(t_eval_step))
+                t_eval_i = t_eval_i_new
+
+        if t_eval is not None and dense_output:
+            ti.append(t)
+
+    message = MESSAGES.get(status, message)
+
+    if t_events is not None:
+        t_events = [np.asarray(te) for te in t_events]
+        y_events = [np.asarray(ye) for ye in y_events]
+
+    if t_eval is None:
+        ts = np.array(ts)
+        ys = np.vstack(ys).T
+    elif ts:
+        ts = np.hstack(ts)
+        ys = np.hstack(ys)
+
+    if dense_output:
+        if t_eval is None:
+            sol = OdeSolution(
+                ts, interpolants, alt_segment=True if method in [BDF, LSODA] else False
+            )
+        else:
+            sol = OdeSolution(
+                ti, interpolants, alt_segment=True if method in [BDF, LSODA] else False
+            )
+    else:
+        sol = None
+
+    return OdeResult(t=ts, y=ys, sol=sol, t_events=t_events, y_events=y_events,
+                     nfev=solver.nfev, njev=solver.njev, nlu=solver.nlu,
+                     status=status, message=message, success=status >= 0)
diff --git a/.venv/lib/python3.12/site-packages/scipy/integrate/_ivp/lsoda.py b/.venv/lib/python3.12/site-packages/scipy/integrate/_ivp/lsoda.py
new file mode 100644
index 0000000000000000000000000000000000000000..40d6001cf239fc8230dcf389a1514e85a239211d
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/integrate/_ivp/lsoda.py
@@ -0,0 +1,229 @@
+import numpy as np
+from scipy.integrate import ode
+from .common import validate_tol, validate_first_step, warn_extraneous
+from .base import OdeSolver, DenseOutput
+
+
+class LSODA(OdeSolver):
+    """Adams/BDF method with automatic stiffness detection and switching.
+
+    This is a wrapper to the Fortran solver from ODEPACK [1]_. It switches
+    automatically between the nonstiff Adams method and the stiff BDF method.
+    The method was originally detailed in [2]_.
+
+    Parameters
+    ----------
+    fun : callable
+        Right-hand side of the system: the time derivative of the state ``y``
+        at time ``t``. The calling signature is ``fun(t, y)``, where ``t`` is a
+        scalar and ``y`` is an ndarray with ``len(y) = len(y0)``. ``fun`` must
+        return an array of the same shape as ``y``. See `vectorized` for more
+        information.
+    t0 : float
+        Initial time.
+    y0 : array_like, shape (n,)
+        Initial state.
+    t_bound : float
+        Boundary time - the integration won't continue beyond it. It also
+        determines the direction of the integration.
+    first_step : float or None, optional
+        Initial step size. Default is ``None`` which means that the algorithm
+        should choose.
+    min_step : float, optional
+        Minimum allowed step size. Default is 0.0, i.e., the step size is not
+        bounded and determined solely by the solver.
+    max_step : float, optional
+        Maximum allowed step size. Default is np.inf, i.e., the step size is not
+        bounded and determined solely by the solver.
+    rtol, atol : float and array_like, optional
+        Relative and absolute tolerances. The solver keeps the local error
+        estimates less than ``atol + rtol * abs(y)``. Here `rtol` controls a
+        relative accuracy (number of correct digits), while `atol` controls
+        absolute accuracy (number of correct decimal places). To achieve the
+        desired `rtol`, set `atol` to be smaller than the smallest value that
+        can be expected from ``rtol * abs(y)`` so that `rtol` dominates the
+        allowable error. If `atol` is larger than ``rtol * abs(y)`` the
+        number of correct digits is not guaranteed. Conversely, to achieve the
+        desired `atol` set `rtol` such that ``rtol * abs(y)`` is always smaller
+        than `atol`. If components of y have different scales, it might be
+        beneficial to set different `atol` values for different components by
+        passing array_like with shape (n,) for `atol`. Default values are
+        1e-3 for `rtol` and 1e-6 for `atol`.
+    jac : None or callable, optional
+        Jacobian matrix of the right-hand side of the system with respect to
+        ``y``. The Jacobian matrix has shape (n, n) and its element (i, j) is
+        equal to ``d f_i / d y_j``. The function will be called as
+        ``jac(t, y)``. If None (default), the Jacobian will be
+        approximated by finite differences. It is generally recommended to
+        provide the Jacobian rather than relying on a finite-difference
+        approximation.
+    lband, uband : int or None
+        Parameters defining the bandwidth of the Jacobian,
+        i.e., ``jac[i, j] != 0 only for i - lband <= j <= i + uband``. Setting
+        these requires your jac routine to return the Jacobian in the packed format:
+        the returned array must have ``n`` columns and ``uband + lband + 1``
+        rows in which Jacobian diagonals are written. Specifically
+        ``jac_packed[uband + i - j , j] = jac[i, j]``. The same format is used
+        in `scipy.linalg.solve_banded` (check for an illustration).
+        These parameters can be also used with ``jac=None`` to reduce the
+        number of Jacobian elements estimated by finite differences.
+    vectorized : bool, optional
+        Whether `fun` may be called in a vectorized fashion. False (default)
+        is recommended for this solver.
+
+        If ``vectorized`` is False, `fun` will always be called with ``y`` of
+        shape ``(n,)``, where ``n = len(y0)``.
+
+        If ``vectorized`` is True, `fun` may be called with ``y`` of shape
+        ``(n, k)``, where ``k`` is an integer. In this case, `fun` must behave
+        such that ``fun(t, y)[:, i] == fun(t, y[:, i])`` (i.e. each column of
+        the returned array is the time derivative of the state corresponding
+        with a column of ``y``).
+
+        Setting ``vectorized=True`` allows for faster finite difference
+        approximation of the Jacobian by methods 'Radau' and 'BDF', but
+        will result in slower execution for this solver.
+    **extraneous
+        Any additional keyword arguments will be ignored.
+
+    Attributes
+    ----------
+    n : int
+        Number of equations.
+    status : str
+        Current status of the solver: 'running', 'finished' or 'failed'.
+    t_bound : float
+        Boundary time.
+    direction : float
+        Integration direction: +1 or -1.
+    t : float
+        Current time.
+    y : ndarray
+        Current state.
+    t_old : float
+        Previous time. None if no steps were made yet.
+    nfev : int
+        Number of evaluations of the right-hand side.
+    njev : int
+        Number of evaluations of the Jacobian.
+
+    References
+    ----------
+    .. [1] A. C. Hindmarsh, "ODEPACK, A Systematized Collection of ODE
+           Solvers," IMACS Transactions on Scientific Computation, Vol 1.,
+           pp. 55-64, 1983.
+    .. [2] L. Petzold, "Automatic selection of methods for solving stiff and
+           nonstiff systems of ordinary differential equations", SIAM Journal
+           on Scientific and Statistical Computing, Vol. 4, No. 1, pp. 136-148,
+           1983.
+    """
+    def __init__(self, fun, t0, y0, t_bound, first_step=None, min_step=0.0,
+                 max_step=np.inf, rtol=1e-3, atol=1e-6, jac=None, lband=None,
+                 uband=None, vectorized=False, **extraneous):
+        warn_extraneous(extraneous)
+        super().__init__(fun, t0, y0, t_bound, vectorized)
+
+        if first_step is None:
+            first_step = 0  # LSODA value for automatic selection.
+        else:
+            first_step = validate_first_step(first_step, t0, t_bound)
+
+        first_step *= self.direction
+
+        if max_step == np.inf:
+            max_step = 0  # LSODA value for infinity.
+        elif max_step <= 0:
+            raise ValueError("`max_step` must be positive.")
+
+        if min_step < 0:
+            raise ValueError("`min_step` must be nonnegative.")
+
+        rtol, atol = validate_tol(rtol, atol, self.n)
+
+        solver = ode(self.fun, jac)
+        solver.set_integrator('lsoda', rtol=rtol, atol=atol, max_step=max_step,
+                              min_step=min_step, first_step=first_step,
+                              lband=lband, uband=uband)
+        solver.set_initial_value(y0, t0)
+
+        # Inject t_bound into rwork array as needed for itask=5.
+        solver._integrator.rwork[0] = self.t_bound
+        solver._integrator.call_args[4] = solver._integrator.rwork
+
+        self._lsoda_solver = solver
+
+    def _step_impl(self):
+        solver = self._lsoda_solver
+        integrator = solver._integrator
+
+        # From lsoda.step and lsoda.integrate itask=5 means take a single
+        # step and do not go past t_bound.
+        itask = integrator.call_args[2]
+        integrator.call_args[2] = 5
+        solver._y, solver.t = integrator.run(
+            solver.f, solver.jac or (lambda: None), solver._y, solver.t,
+            self.t_bound, solver.f_params, solver.jac_params)
+        integrator.call_args[2] = itask
+
+        if solver.successful():
+            self.t = solver.t
+            # IMPORTANT: Must copy solver._y because the C code reuses the same
+            # array object across calls (for in-place modification). Without copy,
+            # solve_ivp would store references to the same array.
+            self.y = solver._y.copy()
+            # From LSODA Fortran source njev is equal to nlu.
+            self.njev = integrator.iwork[12]
+            self.nlu = integrator.iwork[12]
+            return True, None
+        else:
+            return False, 'Unexpected istate in LSODA.'
+
+    def _dense_output_impl(self):
+        iwork = self._lsoda_solver._integrator.iwork
+        rwork = self._lsoda_solver._integrator.rwork
+
+        # We want to produce the Nordsieck history array, yh, up to the order
+        # used in the last successful iteration. The step size is unimportant
+        # because it will be scaled out in LsodaDenseOutput. Some additional
+        # work may be required because ODEPACK's LSODA implementation produces
+        # the Nordsieck history in the state needed for the next iteration.
+
+        # iwork[13] contains order from last successful iteration, while
+        # iwork[14] contains order to be attempted next.
+        order = iwork[13]
+
+        # rwork[11] contains the step size to be attempted next, while
+        # rwork[10] contains step size from last successful iteration.
+        h = rwork[11]
+
+        # rwork[20:20 + (iwork[14] + 1) * self.n] contains entries of the
+        # Nordsieck array in state needed for next iteration. We want
+        # the entries up to order for the last successful step so use the
+        # following.
+        yh = np.reshape(rwork[20:20 + (order + 1) * self.n],
+                        (self.n, order + 1), order='F').copy()
+        if iwork[14] < order:
+            # If the order is set to decrease then the final column of yh
+            # has not been updated within ODEPACK's LSODA
+            # implementation because this column will not be used in the
+            # next iteration. We must rescale this column to make the
+            # associated step size consistent with the other columns.
+            yh[:, -1] *= (h / rwork[10]) ** order
+
+        return LsodaDenseOutput(self.t_old, self.t, h, order, yh)
+
+
+class LsodaDenseOutput(DenseOutput):
+    def __init__(self, t_old, t, h, order, yh):
+        super().__init__(t_old, t)
+        self.h = h
+        self.yh = yh
+        self.p = np.arange(order + 1)
+
+    def _call_impl(self, t):
+        if t.ndim == 0:
+            x = ((t - self.t) / self.h) ** self.p
+        else:
+            x = ((t - self.t) / self.h) ** self.p[:, None]
+
+        return np.dot(self.yh, x)
diff --git a/.venv/lib/python3.12/site-packages/scipy/integrate/_ivp/radau.py b/.venv/lib/python3.12/site-packages/scipy/integrate/_ivp/radau.py
new file mode 100644
index 0000000000000000000000000000000000000000..036b9b477fc4b4f4f9c767e1f53662e9d3f6bee3
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/integrate/_ivp/radau.py
@@ -0,0 +1,578 @@
+import numpy as np
+from scipy.linalg import lu_factor, lu_solve
+from scipy.sparse import issparse, eye_array, safely_cast_index_arrays
+from scipy.sparse.linalg import splu
+from scipy.optimize._numdiff import group_columns
+from .common import (validate_max_step, validate_tol, select_initial_step,
+                     norm, num_jac, EPS, warn_extraneous,
+                     validate_first_step)
+from .base import OdeSolver, DenseOutput
+
+S6 = 6 ** 0.5
+
+# Butcher tableau. A is not used directly, see below.
+C = np.array([(4 - S6) / 10, (4 + S6) / 10, 1])
+E = np.array([-13 - 7 * S6, -13 + 7 * S6, -1]) / 3
+
+# Eigendecomposition of A is done: A = T L T**-1. There is 1 real eigenvalue
+# and a complex conjugate pair. They are written below.
+MU_REAL = 3 + 3 ** (2 / 3) - 3 ** (1 / 3)
+MU_COMPLEX = (3 + 0.5 * (3 ** (1 / 3) - 3 ** (2 / 3))
+              - 0.5j * (3 ** (5 / 6) + 3 ** (7 / 6)))
+
+# These are transformation matrices.
+T = np.array([
+    [0.09443876248897524, -0.14125529502095421, 0.03002919410514742],
+    [0.25021312296533332, 0.20412935229379994, -0.38294211275726192],
+    [1, 1, 0]])
+TI = np.array([
+    [4.17871859155190428, 0.32768282076106237, 0.52337644549944951],
+    [-4.17871859155190428, -0.32768282076106237, 0.47662355450055044],
+    [0.50287263494578682, -2.57192694985560522, 0.59603920482822492]])
+# These linear combinations are used in the algorithm.
+TI_REAL = TI[0]
+TI_COMPLEX = TI[1] + 1j * TI[2]
+
+# Interpolator coefficients.
+P = np.array([
+    [13/3 + 7*S6/3, -23/3 - 22*S6/3, 10/3 + 5 * S6],
+    [13/3 - 7*S6/3, -23/3 + 22*S6/3, 10/3 - 5 * S6],
+    [1/3, -8/3, 10/3]])
+
+
+NEWTON_MAXITER = 6  # Maximum number of Newton iterations.
+MIN_FACTOR = 0.2  # Minimum allowed decrease in a step size.
+MAX_FACTOR = 10  # Maximum allowed increase in a step size.
+
+
+def solve_collocation_system(fun, t, y, h, Z0, scale, tol,
+                             LU_real, LU_complex, solve_lu):
+    """Solve the collocation system.
+
+    Parameters
+    ----------
+    fun : callable
+        Right-hand side of the system.
+    t : float
+        Current time.
+    y : ndarray, shape (n,)
+        Current state.
+    h : float
+        Step to try.
+    Z0 : ndarray, shape (3, n)
+        Initial guess for the solution. It determines new values of `y` at
+        ``t + h * C`` as ``y + Z0``, where ``C`` is the Radau method constants.
+    scale : ndarray, shape (n)
+        Problem tolerance scale, i.e. ``rtol * abs(y) + atol``.
+    tol : float
+        Tolerance to which solve the system. This value is compared with
+        the normalized by `scale` error.
+    LU_real, LU_complex
+        LU decompositions of the system Jacobians.
+    solve_lu : callable
+        Callable which solves a linear system given a LU decomposition. The
+        signature is ``solve_lu(LU, b)``.
+
+    Returns
+    -------
+    converged : bool
+        Whether iterations converged.
+    n_iter : int
+        Number of completed iterations.
+    Z : ndarray, shape (3, n)
+        Found solution.
+    rate : float
+        The rate of convergence.
+    """
+    n = y.shape[0]
+    M_real = MU_REAL / h
+    M_complex = MU_COMPLEX / h
+
+    W = TI.dot(Z0)
+    Z = Z0
+
+    F = np.empty((3, n))
+    ch = h * C
+
+    dW_norm_old = None
+    dW = np.empty_like(W)
+    converged = False
+    rate = None
+    for k in range(NEWTON_MAXITER):
+        for i in range(3):
+            F[i] = fun(t + ch[i], y + Z[i])
+
+        if not np.all(np.isfinite(F)):
+            break
+
+        f_real = F.T.dot(TI_REAL) - M_real * W[0]
+        f_complex = F.T.dot(TI_COMPLEX) - M_complex * (W[1] + 1j * W[2])
+
+        dW_real = solve_lu(LU_real, f_real)
+        dW_complex = solve_lu(LU_complex, f_complex)
+
+        dW[0] = dW_real
+        dW[1] = dW_complex.real
+        dW[2] = dW_complex.imag
+
+        dW_norm = norm(dW / scale)
+        if dW_norm_old is not None:
+            rate = dW_norm / dW_norm_old
+
+        if (rate is not None and (rate >= 1 or
+                rate ** (NEWTON_MAXITER - k) / (1 - rate) * dW_norm > tol)):
+            break
+
+        W += dW
+        Z = T.dot(W)
+
+        if (dW_norm == 0 or
+                rate is not None and rate / (1 - rate) * dW_norm < tol):
+            converged = True
+            break
+
+        dW_norm_old = dW_norm
+
+    return converged, k + 1, Z, rate
+
+
+def predict_factor(h_abs, h_abs_old, error_norm, error_norm_old):
+    """Predict by which factor to increase/decrease the step size.
+
+    The algorithm is described in [1]_.
+
+    Parameters
+    ----------
+    h_abs, h_abs_old : float
+        Current and previous values of the step size, `h_abs_old` can be None
+        (see Notes).
+    error_norm, error_norm_old : float
+        Current and previous values of the error norm, `error_norm_old` can
+        be None (see Notes).
+
+    Returns
+    -------
+    factor : float
+        Predicted factor.
+
+    Notes
+    -----
+    If `h_abs_old` and `error_norm_old` are both not None then a two-step
+    algorithm is used, otherwise a one-step algorithm is used.
+
+    References
+    ----------
+    .. [1] E. Hairer, S. P. Norsett G. Wanner, "Solving Ordinary Differential
+           Equations II: Stiff and Differential-Algebraic Problems", Sec. IV.8.
+    """
+    if error_norm_old is None or h_abs_old is None or error_norm == 0:
+        multiplier = 1
+    else:
+        multiplier = h_abs / h_abs_old * (error_norm_old / error_norm) ** 0.25
+
+    with np.errstate(divide='ignore'):
+        factor = min(1, multiplier) * error_norm ** -0.25
+
+    return factor
+
+
+class Radau(OdeSolver):
+    """Implicit Runge-Kutta method of Radau IIA family of order 5.
+
+    The implementation follows [1]_. The error is controlled with a
+    third-order accurate embedded formula. A cubic polynomial which satisfies
+    the collocation conditions is used for the dense output.
+
+    Parameters
+    ----------
+    fun : callable
+        Right-hand side of the system: the time derivative of the state ``y``
+        at time ``t``. The calling signature is ``fun(t, y)``, where ``t`` is a
+        scalar and ``y`` is an ndarray with ``len(y) = len(y0)``. ``fun`` must
+        return an array of the same shape as ``y``. See `vectorized` for more
+        information.
+    t0 : float
+        Initial time.
+    y0 : array_like, shape (n,)
+        Initial state.
+    t_bound : float
+        Boundary time - the integration won't continue beyond it. It also
+        determines the direction of the integration.
+    max_step : float, optional
+        Maximum allowed step size. Default is np.inf, i.e., the step size is not
+        bounded and determined solely by the solver.
+    rtol, atol : float and array_like, optional
+        Relative and absolute tolerances. The solver keeps the local error
+        estimates less than ``atol + rtol * abs(y)``. HHere `rtol` controls a
+        relative accuracy (number of correct digits), while `atol` controls
+        absolute accuracy (number of correct decimal places). To achieve the
+        desired `rtol`, set `atol` to be smaller than the smallest value that
+        can be expected from ``rtol * abs(y)`` so that `rtol` dominates the
+        allowable error. If `atol` is larger than ``rtol * abs(y)`` the
+        number of correct digits is not guaranteed. Conversely, to achieve the
+        desired `atol` set `rtol` such that ``rtol * abs(y)`` is always smaller
+        than `atol`. If components of y have different scales, it might be
+        beneficial to set different `atol` values for different components by
+        passing array_like with shape (n,) for `atol`. Default values are
+        1e-3 for `rtol` and 1e-6 for `atol`.
+    jac : {None, array_like, sparse array or matrix, callable}, optional
+        Jacobian matrix of the right-hand side of the system with respect to
+        y, required by this method. The Jacobian matrix has shape (n, n) and
+        its element (i, j) is equal to ``d f_i / d y_j``.
+        There are three ways to define the Jacobian:
+
+        * If array_like or sparse, the Jacobian is assumed to be constant.
+        * If callable, the Jacobian is assumed to depend on both
+          t and y; it will be called as ``jac(t, y)`` as necessary.
+          For the 'Radau' and 'BDF' methods, it can return dense or sparse.
+        * If None (default), the Jacobian will be approximated by
+          finite differences.
+
+        It is generally recommended to provide the Jacobian rather than
+        relying on a finite-difference approximation.
+    jac_sparsity : {None, array_like, sparse array or matrix}, optional
+        Defines a sparsity structure of the Jacobian matrix for a
+        finite-difference approximation. Its shape must be (n, n). This argument
+        is ignored if `jac` is not `None`. If the Jacobian has only few non-zero
+        elements in *each* row, providing the sparsity structure will greatly
+        speed up the computations [2]_. A zero entry means that a corresponding
+        element in the Jacobian is always zero. If None (default), the Jacobian
+        is assumed to be dense.
+    vectorized : bool, optional
+        Whether `fun` can be called in a vectorized fashion. Default is False.
+
+        If ``vectorized`` is False, `fun` will always be called with ``y`` of
+        shape ``(n,)``, where ``n = len(y0)``.
+
+        If ``vectorized`` is True, `fun` may be called with ``y`` of shape
+        ``(n, k)``, where ``k`` is an integer. In this case, `fun` must behave
+        such that ``fun(t, y)[:, i] == fun(t, y[:, i])`` (i.e. each column of
+        the returned array is the time derivative of the state corresponding
+        with a column of ``y``).
+
+        Setting ``vectorized=True`` allows for faster finite difference
+        approximation of the Jacobian by this method, but may result in slower
+        execution overall in some circumstances (e.g. small ``len(y0)``).
+    first_step : float or None, optional
+        Initial step size. Default is ``None`` which means that the algorithm
+        should choose.
+    **extraneous
+        Any additional keyword arguments will be ignored.
+
+    Attributes
+    ----------
+    n : int
+        Number of equations.
+    status : str
+        Current status of the solver: 'running', 'finished' or 'failed'.
+    t_bound : float
+        Boundary time.
+    direction : float
+        Integration direction: +1 or -1.
+    t : float
+        Current time.
+    y : ndarray
+        Current state.
+    t_old : float
+        Previous time. None if no steps were made yet.
+    step_size : float
+        Size of the last successful step. None if no steps were made yet.
+    nfev : int
+        Number of evaluations of the right-hand side.
+    njev : int
+        Number of evaluations of the Jacobian.
+    nlu : int
+        Number of LU decompositions.
+
+    References
+    ----------
+    .. [1] E. Hairer, G. Wanner, "Solving Ordinary Differential Equations II:
+           Stiff and Differential-Algebraic Problems", Sec. IV.8.
+    .. [2] A. Curtis, M. J. D. Powell, and J. Reid, "On the estimation of
+           sparse Jacobian matrices", Journal of the Institute of Mathematics
+           and its Applications, 13, pp. 117-120, 1974.
+    """
+    def __init__(self, fun, t0, y0, t_bound, max_step=np.inf,
+                 rtol=1e-3, atol=1e-6, jac=None, jac_sparsity=None,
+                 vectorized=False, first_step=None, **extraneous):
+        warn_extraneous(extraneous)
+        super().__init__(fun, t0, y0, t_bound, vectorized)
+        self.y_old = None
+        self.max_step = validate_max_step(max_step)
+        self.rtol, self.atol = validate_tol(rtol, atol, self.n)
+        self.f = self.fun(self.t, self.y)
+        # Select initial step assuming the same order which is used to control
+        # the error.
+        if first_step is None:
+            self.h_abs = select_initial_step(
+                self.fun, self.t, self.y, t_bound, max_step, self.f, self.direction,
+                3, self.rtol, self.atol)
+        else:
+            self.h_abs = validate_first_step(first_step, t0, t_bound)
+        self.h_abs_old = None
+        self.error_norm_old = None
+
+        self.newton_tol = max(10 * EPS / rtol, min(0.03, rtol ** 0.5))
+        self.sol = None
+
+        self.jac_factor = None
+        self.jac, self.J = self._validate_jac(jac, jac_sparsity)
+        if issparse(self.J):
+            def lu(A):
+                self.nlu += 1
+                return splu(A)
+
+            def solve_lu(LU, b):
+                return LU.solve(b)
+
+            # TODO: use I = eye_array(self.n, format="csc") after spmatrix removed
+            I = self.J.__class__(eye_array(self.n)).tocsc()
+        else:
+            def lu(A):
+                self.nlu += 1
+                return lu_factor(A, overwrite_a=True)
+
+            def solve_lu(LU, b):
+                return lu_solve(LU, b, overwrite_b=True)
+
+            I = np.identity(self.n)
+
+        self.lu = lu
+        self.solve_lu = solve_lu
+        self.I = I
+
+        self.current_jac = True
+        self.LU_real = None
+        self.LU_complex = None
+        self.Z = None
+
+    def _validate_jac(self, jac, sparsity):
+        t0 = self.t
+        y0 = self.y
+
+        if jac is None:
+            if sparsity is not None:
+                if issparse(sparsity):
+                    sparsity = sparsity.tocsc()
+                    # this restricts self.n to fit in int32 for group_columns
+                    indices, indptr = safely_cast_index_arrays(sparsity)
+                    sparsity.indices, sparsity.indptr = indices, indptr
+                groups = group_columns(sparsity)
+                sparsity = (sparsity, groups)
+
+            def jac_wrapped(t, y, f):
+                self.njev += 1
+                J, self.jac_factor = num_jac(self.fun_vectorized, t, y, f,
+                                             self.atol, self.jac_factor,
+                                             sparsity)
+                return J
+            J = jac_wrapped(t0, y0, self.f)
+        elif callable(jac):
+            J = jac(t0, y0)
+            self.njev = 1
+            if issparse(J):
+                J = J.tocsc()
+                csc_constructor = J.__class__
+
+                def jac_wrapped(t, y, _=None):
+                    self.njev += 1
+                    # TODO: Use csc_array after spmatrix removed
+                    return csc_constructor(jac(t, y), dtype=float)
+
+            else:
+                J = np.asarray(J, dtype=float)
+
+                def jac_wrapped(t, y, _=None):
+                    self.njev += 1
+                    return np.asarray(jac(t, y), dtype=float)
+
+            if J.shape != (self.n, self.n):
+                raise ValueError(f"`jac` is expected to have shape {(self.n, self.n)},"
+                                 f" but actually has {J.shape}.")
+        else:
+            if issparse(jac):
+                J = jac.tocsc()
+            else:
+                J = np.asarray(jac, dtype=float)
+
+            if J.shape != (self.n, self.n):
+                raise ValueError(f"`jac` is expected to have shape {(self.n, self.n)},"
+                                 f" but actually has {J.shape}.")
+            jac_wrapped = None
+
+        return jac_wrapped, J
+
+    def _step_impl(self):
+        t = self.t
+        y = self.y
+        f = self.f
+
+        max_step = self.max_step
+        atol = self.atol
+        rtol = self.rtol
+
+        min_step = 10 * np.abs(np.nextafter(t, self.direction * np.inf) - t)
+        if self.h_abs > max_step:
+            h_abs = max_step
+            h_abs_old = None
+            error_norm_old = None
+        elif self.h_abs < min_step:
+            h_abs = min_step
+            h_abs_old = None
+            error_norm_old = None
+        else:
+            h_abs = self.h_abs
+            h_abs_old = self.h_abs_old
+            error_norm_old = self.error_norm_old
+
+        J = self.J
+        LU_real = self.LU_real
+        LU_complex = self.LU_complex
+
+        current_jac = self.current_jac
+        jac = self.jac
+
+        rejected = False
+        step_accepted = False
+        message = None
+        while not step_accepted:
+            if h_abs < min_step:
+                return False, self.TOO_SMALL_STEP
+
+            h = h_abs * self.direction
+            t_new = t + h
+
+            if self.direction * (t_new - self.t_bound) > 0:
+                t_new = self.t_bound
+
+            h = t_new - t
+            h_abs = np.abs(h)
+
+            if self.sol is None:
+                Z0 = np.zeros((3, y.shape[0]))
+            else:
+                Z0 = self.sol(t + h * C).T - y
+
+            scale = atol + np.abs(y) * rtol
+
+            converged = False
+            while not converged:
+                if LU_real is None or LU_complex is None:
+                    LU_real = self.lu(MU_REAL / h * self.I - J)
+                    LU_complex = self.lu(MU_COMPLEX / h * self.I - J)
+
+                converged, n_iter, Z, rate = solve_collocation_system(
+                    self.fun, t, y, h, Z0, scale, self.newton_tol,
+                    LU_real, LU_complex, self.solve_lu)
+
+                if not converged:
+                    if current_jac:
+                        break
+
+                    J = self.jac(t, y, f)
+                    current_jac = True
+                    LU_real = None
+                    LU_complex = None
+
+            if not converged:
+                h_abs *= 0.5
+                LU_real = None
+                LU_complex = None
+                continue
+
+            y_new = y + Z[-1]
+            ZE = Z.T.dot(E) / h
+            error = self.solve_lu(LU_real, f + ZE)
+            scale = atol + np.maximum(np.abs(y), np.abs(y_new)) * rtol
+            error_norm = norm(error / scale)
+            safety = 0.9 * (2 * NEWTON_MAXITER + 1) / (2 * NEWTON_MAXITER
+                                                       + n_iter)
+
+            if rejected and error_norm > 1:
+                error = self.solve_lu(LU_real, self.fun(t, y + error) + ZE)
+                error_norm = norm(error / scale)
+
+            if error_norm > 1:
+                factor = predict_factor(h_abs, h_abs_old,
+                                        error_norm, error_norm_old)
+                h_abs *= max(MIN_FACTOR, safety * factor)
+
+                LU_real = None
+                LU_complex = None
+                rejected = True
+            else:
+                step_accepted = True
+
+        recompute_jac = jac is not None and n_iter > 2 and rate > 1e-3
+
+        factor = predict_factor(h_abs, h_abs_old, error_norm, error_norm_old)
+        factor = min(MAX_FACTOR, safety * factor)
+
+        if not recompute_jac and factor < 1.2:
+            factor = 1
+        else:
+            LU_real = None
+            LU_complex = None
+
+        f_new = self.fun(t_new, y_new)
+        if recompute_jac:
+            J = jac(t_new, y_new, f_new)
+            current_jac = True
+        elif jac is not None:
+            current_jac = False
+
+        self.h_abs_old = self.h_abs
+        self.error_norm_old = error_norm
+
+        self.h_abs = h_abs * factor
+
+        self.y_old = y
+
+        self.t = t_new
+        self.y = y_new
+        self.f = f_new
+
+        self.Z = Z
+
+        self.LU_real = LU_real
+        self.LU_complex = LU_complex
+        self.current_jac = current_jac
+        self.J = J
+
+        self.t_old = t
+        self.sol = self._compute_dense_output()
+
+        return step_accepted, message
+
+    def _compute_dense_output(self):
+        Q = np.dot(self.Z.T, P)
+        return RadauDenseOutput(self.t_old, self.t, self.y_old, Q)
+
+    def _dense_output_impl(self):
+        return self.sol
+
+
+class RadauDenseOutput(DenseOutput):
+    def __init__(self, t_old, t, y_old, Q):
+        super().__init__(t_old, t)
+        self.h = t - t_old
+        self.Q = Q
+        self.order = Q.shape[1] - 1
+        self.y_old = y_old
+
+    def _call_impl(self, t):
+        x = (t - self.t_old) / self.h
+        if t.ndim == 0:
+            p = np.tile(x, self.order + 1)
+            p = np.cumprod(p)
+        else:
+            p = np.tile(x, (self.order + 1, 1))
+            p = np.cumprod(p, axis=0)
+        # Here we don't multiply by h, not a mistake.
+        y = np.dot(self.Q, p)
+        if y.ndim == 2:
+            y += self.y_old[:, None]
+        else:
+            y += self.y_old
+
+        return y
diff --git a/.venv/lib/python3.12/site-packages/scipy/integrate/_ivp/rk.py b/.venv/lib/python3.12/site-packages/scipy/integrate/_ivp/rk.py
new file mode 100644
index 0000000000000000000000000000000000000000..df71a7e63179e3d2f76ba8b0b3db81a8726b7256
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/integrate/_ivp/rk.py
@@ -0,0 +1,764 @@
+import numpy as np
+from .base import OdeSolver, DenseOutput
+from .common import (validate_max_step, validate_tol, select_initial_step,
+                     norm, warn_extraneous, validate_first_step)
+from . import dop853_coefficients
+
+# Multiply steps computed from asymptotic behaviour of errors by this.
+SAFETY = 0.9
+
+MIN_FACTOR = 0.2  # Minimum allowed decrease in a step size.
+MAX_FACTOR = 10  # Maximum allowed increase in a step size.
+
+
+def rk_step(fun, t, y, f, h, A, B, C, K):
+    """Perform a single Runge-Kutta step.
+
+    This function computes a prediction of an explicit Runge-Kutta method and
+    also estimates the error of a less accurate method.
+
+    Notation for Butcher tableau is as in [1]_.
+
+    Parameters
+    ----------
+    fun : callable
+        Right-hand side of the system.
+    t : float
+        Current time.
+    y : ndarray, shape (n,)
+        Current state.
+    f : ndarray, shape (n,)
+        Current value of the derivative, i.e., ``fun(x, y)``.
+    h : float
+        Step to use.
+    A : ndarray, shape (n_stages, n_stages)
+        Coefficients for combining previous RK stages to compute the next
+        stage. For explicit methods the coefficients at and above the main
+        diagonal are zeros.
+    B : ndarray, shape (n_stages,)
+        Coefficients for combining RK stages for computing the final
+        prediction.
+    C : ndarray, shape (n_stages,)
+        Coefficients for incrementing time for consecutive RK stages.
+        The value for the first stage is always zero.
+    K : ndarray, shape (n_stages + 1, n)
+        Storage array for putting RK stages here. Stages are stored in rows.
+        The last row is a linear combination of the previous rows with
+        coefficients
+
+    Returns
+    -------
+    y_new : ndarray, shape (n,)
+        Solution at t + h computed with a higher accuracy.
+    f_new : ndarray, shape (n,)
+        Derivative ``fun(t + h, y_new)``.
+
+    References
+    ----------
+    .. [1] E. Hairer, S. P. Norsett G. Wanner, "Solving Ordinary Differential
+           Equations I: Nonstiff Problems", Sec. II.4.
+    """
+    K[0] = f
+    for s, (a, c) in enumerate(zip(A[1:], C[1:]), start=1):
+        dy = np.dot(K[:s].T, a[:s]) * h
+        K[s] = fun(t + c * h, y + dy)
+
+    y_new = y + h * np.dot(K[:-1].T, B)
+    f_new = fun(t + h, y_new)
+
+    K[-1] = f_new
+
+    return y_new, f_new
+
+
+class RungeKutta(OdeSolver):
+    """Base class for explicit Runge-Kutta methods."""
+    C: np.ndarray = NotImplemented
+    A: np.ndarray = NotImplemented
+    B: np.ndarray = NotImplemented
+    E: np.ndarray = NotImplemented
+    P: np.ndarray = NotImplemented
+    order: int = NotImplemented
+    error_estimator_order: int = NotImplemented
+    n_stages: int = NotImplemented
+
+    def __init__(self, fun, t0, y0, t_bound, max_step=np.inf,
+                 rtol=1e-3, atol=1e-6, vectorized=False,
+                 first_step=None, **extraneous):
+        warn_extraneous(extraneous)
+        super().__init__(fun, t0, y0, t_bound, vectorized,
+                         support_complex=True)
+        self.y_old = None
+        self.max_step = validate_max_step(max_step)
+        self.rtol, self.atol = validate_tol(rtol, atol, self.n)
+        self.f = self.fun(self.t, self.y)
+        if first_step is None:
+            self.h_abs = select_initial_step(
+                self.fun, self.t, self.y, t_bound, max_step, self.f, self.direction,
+                self.error_estimator_order, self.rtol, self.atol)
+        else:
+            self.h_abs = validate_first_step(first_step, t0, t_bound)
+        self.K = np.empty((self.n_stages + 1, self.n), dtype=self.y.dtype)
+        self.error_exponent = -1 / (self.error_estimator_order + 1)
+        self.h_previous = None
+
+    def _estimate_error(self, K, h):
+        return np.dot(K.T, self.E) * h
+
+    def _estimate_error_norm(self, K, h, scale):
+        return norm(self._estimate_error(K, h) / scale)
+
+    def _step_impl(self):
+        t = self.t
+        y = self.y
+
+        max_step = self.max_step
+        rtol = self.rtol
+        atol = self.atol
+
+        min_step = 10 * np.abs(np.nextafter(t, self.direction * np.inf) - t)
+
+        if self.h_abs > max_step:
+            h_abs = max_step
+        elif self.h_abs < min_step:
+            h_abs = min_step
+        else:
+            h_abs = self.h_abs
+
+        step_accepted = False
+        step_rejected = False
+
+        while not step_accepted:
+            if h_abs < min_step:
+                return False, self.TOO_SMALL_STEP
+
+            h = h_abs * self.direction
+            t_new = t + h
+
+            if self.direction * (t_new - self.t_bound) > 0:
+                t_new = self.t_bound
+
+            h = t_new - t
+            h_abs = np.abs(h)
+
+            y_new, f_new = rk_step(self.fun, t, y, self.f, h, self.A,
+                                   self.B, self.C, self.K)
+            scale = atol + np.maximum(np.abs(y), np.abs(y_new)) * rtol
+            error_norm = self._estimate_error_norm(self.K, h, scale)
+
+            if error_norm < 1:
+                if error_norm == 0:
+                    factor = MAX_FACTOR
+                else:
+                    factor = min(MAX_FACTOR,
+                                 SAFETY * error_norm ** self.error_exponent)
+
+                if step_rejected:
+                    factor = min(1, factor)
+
+                h_abs *= factor
+
+                step_accepted = True
+            else:
+                h_abs *= max(MIN_FACTOR,
+                             SAFETY * error_norm ** self.error_exponent)
+                step_rejected = True
+
+        self.h_previous = h
+        self.y_old = y
+
+        self.t = t_new
+        self.y = y_new
+
+        self.h_abs = h_abs
+        self.f = f_new
+
+        return True, None
+
+    def _dense_output_impl(self):
+        Q = self.K.T.dot(self.P)
+        return RkDenseOutput(self.t_old, self.t, self.y_old, Q)
+
+
+class RK23(RungeKutta):
+    """Explicit Runge-Kutta method of order 3(2).
+
+    This uses the Bogacki-Shampine pair of formulas [1]_. The error is controlled
+    assuming accuracy of the second-order method, but steps are taken using the
+    third-order accurate formula (local extrapolation is done). A cubic Hermite
+    polynomial is used for the dense output.
+
+    Can be applied in the complex domain.
+
+    Parameters
+    ----------
+    fun : callable
+        Right-hand side of the system: the time derivative of the state ``y``
+        at time ``t``. The calling signature is ``fun(t, y)``, where ``t`` is a
+        scalar and ``y`` is an ndarray with ``len(y) = len(y0)``. ``fun`` must
+        return an array of the same shape as ``y``. See `vectorized` for more
+        information.
+    t0 : float
+        Initial time.
+    y0 : array_like, shape (n,)
+        Initial state.
+    t_bound : float
+        Boundary time - the integration won't continue beyond it. It also
+        determines the direction of the integration.
+    max_step : float, optional
+        Maximum allowed step size. Default is np.inf, i.e., the step size is not
+        bounded and determined solely by the solver.
+    rtol, atol : float and array_like, optional
+        Relative and absolute tolerances. The solver keeps the local error
+        estimates less than ``atol + rtol * abs(y)``. Here `rtol` controls a
+        relative accuracy (number of correct digits), while `atol` controls
+        absolute accuracy (number of correct decimal places). To achieve the
+        desired `rtol`, set `atol` to be smaller than the smallest value that
+        can be expected from ``rtol * abs(y)`` so that `rtol` dominates the
+        allowable error. If `atol` is larger than ``rtol * abs(y)`` the
+        number of correct digits is not guaranteed. Conversely, to achieve the
+        desired `atol` set `rtol` such that ``rtol * abs(y)`` is always smaller
+        than `atol`. If components of y have different scales, it might be
+        beneficial to set different `atol` values for different components by
+        passing array_like with shape (n,) for `atol`. Default values are
+        1e-3 for `rtol` and 1e-6 for `atol`.
+    vectorized : bool, optional
+        Whether `fun` may be called in a vectorized fashion. False (default)
+        is recommended for this solver.
+
+        If ``vectorized`` is False, `fun` will always be called with ``y`` of
+        shape ``(n,)``, where ``n = len(y0)``.
+
+        If ``vectorized`` is True, `fun` may be called with ``y`` of shape
+        ``(n, k)``, where ``k`` is an integer. In this case, `fun` must behave
+        such that ``fun(t, y)[:, i] == fun(t, y[:, i])`` (i.e. each column of
+        the returned array is the time derivative of the state corresponding
+        with a column of ``y``).
+
+        Setting ``vectorized=True`` allows for faster finite difference
+        approximation of the Jacobian by methods 'Radau' and 'BDF', but
+        will result in slower execution for this solver.
+    first_step : float or None, optional
+        Initial step size. Default is ``None`` which means that the algorithm
+        should choose.
+    **extraneous
+        Any additional keyword arguments will be ignored.
+
+    Attributes
+    ----------
+    n : int
+        Number of equations.
+    status : str
+        Current status of the solver: 'running', 'finished' or 'failed'.
+    t_bound : float
+        Boundary time.
+    direction : float
+        Integration direction: +1 or -1.
+    t : float
+        Current time.
+    y : ndarray
+        Current state.
+    t_old : float
+        Previous time. None if no steps were made yet.
+    step_size : float
+        Size of the last successful step. None if no steps were made yet.
+    nfev : int
+        Number evaluations of the system's right-hand side.
+    njev : int
+        Number of evaluations of the Jacobian.
+        Is always 0 for this solver as it does not use the Jacobian.
+    nlu : int
+        Number of LU decompositions. Is always 0 for this solver.
+
+    References
+    ----------
+    .. [1] P. Bogacki, L.F. Shampine, "A 3(2) Pair of Runge-Kutta Formulas",
+           Appl. Math. Lett. Vol. 2, No. 4. pp. 321-325, 1989.
+
+    Examples
+    --------
+    This example demonstrates how to compute one period of a periodic
+    orbit in a two-dimensional dynamical system.
+
+    >>> import numpy as np
+    >>> import scipy.integrate as itg
+    >>> import matplotlib.pylab as plt
+
+    Define a function that returns the right-hand side of a dynamical
+    system with a stable periodic orbit.
+
+    >>> def dynam_sys(t, x):
+    ...     dx1_dt = 5*(1-x[1]**2)*x[0] - x[1]
+    ...     dx2_dt = x[0]
+    ...     return [dx1_dt, dx2_dt]
+
+    The system has an equilibrium at the origin. Create a solver
+    object with an initial state slightly away from the
+    equilibrium.
+
+    >>> solver = itg.RK45(dynam_sys, 0, [0.25,0.25], 1E200, max_step=0.05)
+
+    Create an array in which to store the estimated solution.
+    To allow for concatenation of future states, initialize the array
+    by reshaping the initial state.
+
+    >>> soly = solver.y.reshape(1, 2)
+
+    To find a point on the periodic orbit, run the solver
+    for ``2000`` integration steps. Store the estimated states in
+    ``soly``.
+
+    >>> for i in range(2000):
+    ...     solver.step()
+    ...     solyn = solver.y.reshape(1, 2)
+    ...     soly = np.concatenate((soly, solyn))
+
+    Plot ``soly`` with its first element in green and its final
+    element in magenta.
+
+    >>> plt.plot(soly[:,0], soly[:,1])
+    >>> plt.plot(soly[0,0], soly[0,1], "go")
+    >>> plt.plot(soly[-1,0], soly[-1,1], "mo")
+    >>> plt.show()
+
+    The plot shows that the last element in ``soly`` is located on a
+    segment of the periodic orbit where there is relatively little
+    variation in the estimated states. Create another solver and
+    initialize it with the last element in ``soly``.
+
+    >>> init = np.array([soly[-1,0], soly[-1,1]])
+    >>> POsolver = itg.RK23(dynam_sys, 0, init, 5000, max_step=0.05)
+
+    Create a variable that tracks the distance of the current
+    estimated state from the initial state. Run ``POsolver`` until
+    the current estimated state is within ``0.005`` units of the last
+    estimated state.
+
+    >>> dist_init = 1
+    >>> POsoly = POsolver.y.reshape(1, 2)
+    >>> while dist_init > 0.005:
+    ...     POsolver.step()
+    ...     POsolyn = POsolver.y.reshape(1, 2)
+    ...     POsoly = np.concatenate((POsoly, POsolyn))
+    ...     dist_init = np.linalg.norm(init-POsolyn)
+
+    Plot ``POsoly`` with its initial element in green and its final
+    element in magenta.
+
+    >>> plt.plot(POsoly[:,0], POsoly[:,1])
+    >>> plt.plot(POsoly[0,0], POsoly[0,1], "go")
+    >>> plt.plot(POsoly[-1,0], POsoly[-1,1], "mo")
+    >>> plt.show()
+
+    The plot shows approximately one period of the orbit.
+    The final and initial states are so close that the final
+    state marker obscures the initial state marker.
+    """
+    order = 3
+    error_estimator_order = 2
+    n_stages = 3
+    C = np.array([0, 1/2, 3/4])
+    A = np.array([
+        [0, 0, 0],
+        [1/2, 0, 0],
+        [0, 3/4, 0]
+    ])
+    B = np.array([2/9, 1/3, 4/9])
+    E = np.array([5/72, -1/12, -1/9, 1/8])
+    P = np.array([[1, -4 / 3, 5 / 9],
+                  [0, 1, -2/3],
+                  [0, 4/3, -8/9],
+                  [0, -1, 1]])
+
+
+class RK45(RungeKutta):
+    """Explicit Runge-Kutta method of order 5(4).
+
+    This uses the Dormand-Prince pair of formulas [1]_. The error is controlled
+    assuming accuracy of the fourth-order method accuracy, but steps are taken
+    using the fifth-order accurate formula (local extrapolation is done).
+    A quartic interpolation polynomial is used for the dense output [2]_.
+
+    Can be applied in the complex domain.
+
+    Parameters
+    ----------
+    fun : callable
+        Right-hand side of the system. The calling signature is ``fun(t, y)``.
+        Here ``t`` is a scalar, and there are two options for the ndarray ``y``:
+        It can either have shape (n,); then ``fun`` must return array_like with
+        shape (n,). Alternatively it can have shape (n, k); then ``fun``
+        must return an array_like with shape (n, k), i.e., each column
+        corresponds to a single column in ``y``. The choice between the two
+        options is determined by `vectorized` argument (see below).
+    t0 : float
+        Initial time.
+    y0 : array_like, shape (n,)
+        Initial state.
+    t_bound : float
+        Boundary time - the integration won't continue beyond it. It also
+        determines the direction of the integration.
+    max_step : float, optional
+        Maximum allowed step size. Default is np.inf, i.e., the step size is not
+        bounded and determined solely by the solver.
+    rtol, atol : float and array_like, optional
+        Relative and absolute tolerances. The solver keeps the local error
+        estimates less than ``atol + rtol * abs(y)``. Here `rtol` controls a
+        relative accuracy (number of correct digits), while `atol` controls
+        absolute accuracy (number of correct decimal places). To achieve the
+        desired `rtol`, set `atol` to be smaller than the smallest value that
+        can be expected from ``rtol * abs(y)`` so that `rtol` dominates the
+        allowable error. If `atol` is larger than ``rtol * abs(y)`` the
+        number of correct digits is not guaranteed. Conversely, to achieve the
+        desired `atol` set `rtol` such that ``rtol * abs(y)`` is always smaller
+        than `atol`. If components of y have different scales, it might be
+        beneficial to set different `atol` values for different components by
+        passing array_like with shape (n,) for `atol`. Default values are
+        1e-3 for `rtol` and 1e-6 for `atol`.
+    vectorized : bool, optional
+        Whether `fun` is implemented in a vectorized fashion. Default is False.
+    first_step : float or None, optional
+        Initial step size. Default is ``None`` which means that the algorithm
+        should choose.
+    **extraneous
+        Any additional keyword arguments will be ignored.
+
+    Attributes
+    ----------
+    n : int
+        Number of equations.
+    status : str
+        Current status of the solver: 'running', 'finished' or 'failed'.
+    t_bound : float
+        Boundary time.
+    direction : float
+        Integration direction: +1 or -1.
+    t : float
+        Current time.
+    y : ndarray
+        Current state.
+    t_old : float
+        Previous time. None if no steps were made yet.
+    step_size : float
+        Size of the last successful step. None if no steps were made yet.
+    nfev : int
+        Number evaluations of the system's right-hand side.
+    njev : int
+        Number of evaluations of the Jacobian.
+        Is always 0 for this solver as it does not use the Jacobian.
+    nlu : int
+        Number of LU decompositions. Is always 0 for this solver.
+
+    References
+    ----------
+    .. [1] J. R. Dormand, P. J. Prince, "A family of embedded Runge-Kutta
+           formulae", Journal of Computational and Applied Mathematics, Vol. 6,
+           No. 1, pp. 19-26, 1980.
+    .. [2] L. W. Shampine, "Some Practical Runge-Kutta Formulas", Mathematics
+           of Computation,, Vol. 46, No. 173, pp. 135-150, 1986.
+
+    Examples
+    --------
+    This example demonstrates how to compute one period of a periodic
+    orbit in a two-dimensional dynamical system.
+
+    >>> import numpy as np
+    >>> import scipy.integrate as itg
+    >>> import matplotlib.pylab as plt
+
+    Define a function that returns the right-hand side of a dynamical
+    system with a stable periodic orbit.
+
+    >>> def dynam_sys(t, x):
+    ...     dx1_dt = 5*(1-x[1]**2)*x[0] - x[1]
+    ...     dx2_dt = x[0]
+    ...     return [dx1_dt, dx2_dt]
+
+    The system has an equilibrium at the origin. Create a solver
+    object with an initial state slightly away from the
+    equilibrium.
+
+    >>> solver = itg.RK45(dynam_sys, 0, [0.25,0.25], 5000, max_step=0.05)
+
+    Create an array in which to store the estimated solution.
+    To allow for concatenation of future states, initialize the array
+    by reshaping the initial state.
+
+    >>> soly = solver.y.reshape(1, 2)
+
+    To find a point on the periodic orbit, run the solver for
+    ``2000`` integration steps. Store the estimated states in ``soly``.
+
+    >>> for i in range(2000):
+    ...     solver.step()
+    ...     solyn = solver.y.reshape(1, 2)
+    ...     soly = np.concatenate((soly, solyn))
+
+    Plot ``soly`` with its first element in green and its final
+    element in magenta.
+
+    >>> plt.plot(soly[:,0], soly[:,1])
+    >>> plt.plot(soly[0,0], soly[0,1], "go")
+    >>> plt.plot(soly[-1,0], soly[-1,1], "mo")
+    >>> plt.show()
+
+    The plot shows that the last element in ``soly`` is located on a
+    segment of the periodic orbit where there is relatively little
+    variation in the estimated states. Create another solver and
+    initialize it with the last element in ``soly``.
+
+    >>> init = np.array([soly[-1,0], soly[-1,1]])
+    >>> POsolver = itg.RK45(dynam_sys, 0, init, 5000, max_step=0.05)
+
+    Create a variable that tracks the distance of the current
+    estimated state from the initial state. Run ``POsolver`` until
+    the current estimated state is within ``0.01`` units of the last
+    estimated state.
+
+    >>> dist_init = 1
+    >>> POsoly = POsolver.y.reshape(1, 2)
+    >>> while dist_init > 0.01:
+    ...     POsolver.step()
+    ...     POsolyn = POsolver.y.reshape(1, 2)
+    ...     POsoly = np.concatenate((POsoly, POsolyn))
+    ...     dist_init = np.linalg.norm(init-POsolyn)
+
+    Plot ``POsoly`` with its initial element in green and its final
+    element in magenta.
+
+    >>> plt.plot(POsoly[:,0], POsoly[:,1])
+    >>> plt.plot(POsoly[0,0], POsoly[0,1], "go")
+    >>> plt.plot(POsoly[-1,0], POsoly[-1,1], "mo")
+    >>> plt.show()
+
+    The plot shows approximately one period of the orbit.
+    The final and initial states are so close that the final
+    state marker obscures the initial state marker.
+    """
+    order = 5
+    error_estimator_order = 4
+    n_stages = 6
+    C = np.array([0, 1/5, 3/10, 4/5, 8/9, 1])
+    A = np.array([
+        [0, 0, 0, 0, 0],
+        [1/5, 0, 0, 0, 0],
+        [3/40, 9/40, 0, 0, 0],
+        [44/45, -56/15, 32/9, 0, 0],
+        [19372/6561, -25360/2187, 64448/6561, -212/729, 0],
+        [9017/3168, -355/33, 46732/5247, 49/176, -5103/18656]
+    ])
+    B = np.array([35/384, 0, 500/1113, 125/192, -2187/6784, 11/84])
+    E = np.array([-71/57600, 0, 71/16695, -71/1920, 17253/339200, -22/525,
+                  1/40])
+    # Corresponds to the optimum value of c_6 from [2]_.
+    P = np.array([
+        [1, -8048581381/2820520608, 8663915743/2820520608,
+         -12715105075/11282082432],
+        [0, 0, 0, 0],
+        [0, 131558114200/32700410799, -68118460800/10900136933,
+         87487479700/32700410799],
+        [0, -1754552775/470086768, 14199869525/1410260304,
+         -10690763975/1880347072],
+        [0, 127303824393/49829197408, -318862633887/49829197408,
+         701980252875 / 199316789632],
+        [0, -282668133/205662961, 2019193451/616988883, -1453857185/822651844],
+        [0, 40617522/29380423, -110615467/29380423, 69997945/29380423]])
+
+
+class DOP853(RungeKutta):
+    """Explicit Runge-Kutta method of order 8.
+
+    This is a Python implementation of "DOP853" algorithm originally written
+    in Fortran [1]_, [2]_. Note that this is not a literal translation, but
+    the algorithmic core and coefficients are the same.
+
+    Can be applied in the complex domain.
+
+    Parameters
+    ----------
+    fun : callable
+        Right-hand side of the system. The calling signature is ``fun(t, y)``.
+        Here, ``t`` is a scalar, and there are two options for the ndarray ``y``:
+        It can either have shape (n,); then ``fun`` must return array_like with
+        shape (n,). Alternatively it can have shape (n, k); then ``fun``
+        must return an array_like with shape (n, k), i.e. each column
+        corresponds to a single column in ``y``. The choice between the two
+        options is determined by `vectorized` argument (see below).
+    t0 : float
+        Initial time.
+    y0 : array_like, shape (n,)
+        Initial state.
+    t_bound : float
+        Boundary time - the integration won't continue beyond it. It also
+        determines the direction of the integration.
+    max_step : float, optional
+        Maximum allowed step size. Default is np.inf, i.e. the step size is not
+        bounded and determined solely by the solver.
+    rtol, atol : float and array_like, optional
+        Relative and absolute tolerances. The solver keeps the local error
+        estimates less than ``atol + rtol * abs(y)``. Here `rtol` controls a
+        relative accuracy (number of correct digits), while `atol` controls
+        absolute accuracy (number of correct decimal places). To achieve the
+        desired `rtol`, set `atol` to be smaller than the smallest value that
+        can be expected from ``rtol * abs(y)`` so that `rtol` dominates the
+        allowable error. If `atol` is larger than ``rtol * abs(y)`` the
+        number of correct digits is not guaranteed. Conversely, to achieve the
+        desired `atol` set `rtol` such that ``rtol * abs(y)`` is always smaller
+        than `atol`. If components of y have different scales, it might be
+        beneficial to set different `atol` values for different components by
+        passing array_like with shape (n,) for `atol`. Default values are
+        1e-3 for `rtol` and 1e-6 for `atol`.
+    vectorized : bool, optional
+        Whether `fun` is implemented in a vectorized fashion. Default is False.
+    first_step : float or None, optional
+        Initial step size. Default is ``None`` which means that the algorithm
+        should choose.
+    **extraneous
+        Any additional keyword arguments will be ignored.
+
+    Attributes
+    ----------
+    n : int
+        Number of equations.
+    status : str
+        Current status of the solver: 'running', 'finished' or 'failed'.
+    t_bound : float
+        Boundary time.
+    direction : float
+        Integration direction: +1 or -1.
+    t : float
+        Current time.
+    y : ndarray
+        Current state.
+    t_old : float
+        Previous time. None if no steps were made yet.
+    step_size : float
+        Size of the last successful step. None if no steps were made yet.
+    nfev : int
+        Number evaluations of the system's right-hand side.
+    njev : int
+        Number of evaluations of the Jacobian. Is always 0 for this solver
+        as it does not use the Jacobian.
+    nlu : int
+        Number of LU decompositions. Is always 0 for this solver.
+
+    References
+    ----------
+    .. [1] E. Hairer, S. P. Norsett G. Wanner, "Solving Ordinary Differential
+           Equations I: Nonstiff Problems", Sec. II.
+    .. [2] `Page with original Fortran code of DOP853
+            `_.
+    """
+    n_stages = dop853_coefficients.N_STAGES
+    order = 8
+    error_estimator_order = 7
+    A = dop853_coefficients.A[:n_stages, :n_stages]
+    B = dop853_coefficients.B
+    C = dop853_coefficients.C[:n_stages]
+    E3 = dop853_coefficients.E3
+    E5 = dop853_coefficients.E5
+    D = dop853_coefficients.D
+
+    A_EXTRA = dop853_coefficients.A[n_stages + 1:]
+    C_EXTRA = dop853_coefficients.C[n_stages + 1:]
+
+    def __init__(self, fun, t0, y0, t_bound, max_step=np.inf,
+                 rtol=1e-3, atol=1e-6, vectorized=False,
+                 first_step=None, **extraneous):
+        super().__init__(fun, t0, y0, t_bound, max_step, rtol, atol,
+                         vectorized, first_step, **extraneous)
+        self.K_extended = np.empty((dop853_coefficients.N_STAGES_EXTENDED,
+                                    self.n), dtype=self.y.dtype)
+        self.K = self.K_extended[:self.n_stages + 1]
+
+    def _estimate_error(self, K, h):  # Left for testing purposes.
+        err5 = np.dot(K.T, self.E5)
+        err3 = np.dot(K.T, self.E3)
+        denom = np.hypot(np.abs(err5), 0.1 * np.abs(err3))
+        correction_factor = np.ones_like(err5)
+        mask = denom > 0
+        correction_factor[mask] = np.abs(err5[mask]) / denom[mask]
+        return h * err5 * correction_factor
+
+    def _estimate_error_norm(self, K, h, scale):
+        err5 = np.dot(K.T, self.E5) / scale
+        err3 = np.dot(K.T, self.E3) / scale
+        err5_norm_2 = np.linalg.norm(err5)**2
+        err3_norm_2 = np.linalg.norm(err3)**2
+        if err5_norm_2 == 0 and err3_norm_2 == 0:
+            return 0.0
+        denom = err5_norm_2 + 0.01 * err3_norm_2
+        return np.abs(h) * err5_norm_2 / np.sqrt(denom * len(scale))
+
+    def _dense_output_impl(self):
+        K = self.K_extended
+        h = self.h_previous
+        for s, (a, c) in enumerate(zip(self.A_EXTRA, self.C_EXTRA),
+                                   start=self.n_stages + 1):
+            dy = np.dot(K[:s].T, a[:s]) * h
+            K[s] = self.fun(self.t_old + c * h, self.y_old + dy)
+
+        F = np.empty((dop853_coefficients.INTERPOLATOR_POWER, self.n),
+                     dtype=self.y_old.dtype)
+
+        f_old = K[0]
+        delta_y = self.y - self.y_old
+
+        F[0] = delta_y
+        F[1] = h * f_old - delta_y
+        F[2] = 2 * delta_y - h * (self.f + f_old)
+        F[3:] = h * np.dot(self.D, K)
+
+        return Dop853DenseOutput(self.t_old, self.t, self.y_old, F)
+
+
+class RkDenseOutput(DenseOutput):
+    def __init__(self, t_old, t, y_old, Q):
+        super().__init__(t_old, t)
+        self.h = t - t_old
+        self.Q = Q
+        self.order = Q.shape[1] - 1
+        self.y_old = y_old
+
+    def _call_impl(self, t):
+        x = (t - self.t_old) / self.h
+        if t.ndim == 0:
+            p = np.tile(x, self.order + 1)
+            p = np.cumprod(p)
+        else:
+            p = np.tile(x, (self.order + 1, 1))
+            p = np.cumprod(p, axis=0)
+        y = self.h * np.dot(self.Q, p)
+        if y.ndim == 2:
+            y += self.y_old[:, None]
+        else:
+            y += self.y_old
+
+        return y
+
+
+class Dop853DenseOutput(DenseOutput):
+    def __init__(self, t_old, t, y_old, F):
+        super().__init__(t_old, t)
+        self.h = t - t_old
+        self.F = F
+        self.y_old = y_old
+
+    def _call_impl(self, t):
+        x = (t - self.t_old) / self.h
+
+        if t.ndim == 0:
+            y = np.zeros_like(self.y_old)
+        else:
+            x = x[:, None]
+            y = np.zeros((len(x), len(self.y_old)), dtype=self.y_old.dtype)
+
+        for i, f in enumerate(reversed(self.F)):
+            y += f
+            if i % 2 == 0:
+                y *= x
+            else:
+                y *= 1 - x
+        y += self.y_old
+
+        return y.T
diff --git a/.venv/lib/python3.12/site-packages/scipy/integrate/_ivp/tests/__init__.py b/.venv/lib/python3.12/site-packages/scipy/integrate/_ivp/tests/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/.venv/lib/python3.12/site-packages/scipy/integrate/_ivp/tests/test_ivp.py b/.venv/lib/python3.12/site-packages/scipy/integrate/_ivp/tests/test_ivp.py
new file mode 100644
index 0000000000000000000000000000000000000000..35dc3c03732dc0c30f224be9872c3aa97023d9e8
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/integrate/_ivp/tests/test_ivp.py
@@ -0,0 +1,1310 @@
+import warnings
+
+from itertools import product
+
+from numpy.testing import (assert_, assert_allclose, assert_array_less,
+                           assert_equal, assert_no_warnings)
+import pytest
+from pytest import raises as assert_raises
+import numpy as np
+from scipy.optimize._numdiff import group_columns
+from scipy.integrate import solve_ivp, RK23, RK45, DOP853, Radau, BDF, LSODA
+from scipy.integrate import OdeSolution
+from scipy.integrate._ivp.common import num_jac, select_initial_step
+from scipy.integrate._ivp.base import ConstantDenseOutput
+from scipy.sparse import csc_array, coo_array, csc_matrix
+
+
+def fun_zero(t, y):
+    return np.zeros_like(y)
+
+
+def fun_linear(t, y):
+    return np.array([-y[0] - 5 * y[1], y[0] + y[1]])
+
+
+def jac_linear():
+    return np.array([[-1, -5], [1, 1]])
+
+
+def sol_linear(t):
+    return np.vstack((-5 * np.sin(2 * t),
+                      2 * np.cos(2 * t) + np.sin(2 * t)))
+
+
+def fun_rational(t, y):
+    return np.array([y[1] / t,
+                     y[1] * (y[0] + 2 * y[1] - 1) / (t * (y[0] - 1))])
+
+
+def fun_rational_vectorized(t, y):
+    return np.vstack((y[1] / t,
+                      y[1] * (y[0] + 2 * y[1] - 1) / (t * (y[0] - 1))))
+
+
+def jac_rational(t, y):
+    return np.array([
+        [0, 1 / t],
+        [-2 * y[1] ** 2 / (t * (y[0] - 1) ** 2),
+         (y[0] + 4 * y[1] - 1) / (t * (y[0] - 1))]
+    ])
+
+
+def jac_rational_sparse(t, y):
+    return csc_array([
+        [0, 1 / t],
+        [-2 * y[1] ** 2 / (t * (y[0] - 1) ** 2),
+         (y[0] + 4 * y[1] - 1) / (t * (y[0] - 1))]
+    ])
+
+
+def sol_rational(t):
+    return np.asarray((t / (t + 10), 10 * t / (t + 10) ** 2))
+
+
+def fun_medazko(t, y):
+    n = y.shape[0] // 2
+    k = 100
+    c = 4
+
+    phi = 2 if t <= 5 else 0
+    y = np.hstack((phi, 0, y, y[-2]))
+
+    d = 1 / n
+    j = np.arange(n) + 1
+    alpha = 2 * (j * d - 1) ** 3 / c ** 2
+    beta = (j * d - 1) ** 4 / c ** 2
+
+    j_2_p1 = 2 * j + 2
+    j_2_m3 = 2 * j - 2
+    j_2_m1 = 2 * j
+    j_2 = 2 * j + 1
+
+    f = np.empty(2 * n)
+    f[::2] = (alpha * (y[j_2_p1] - y[j_2_m3]) / (2 * d) +
+              beta * (y[j_2_m3] - 2 * y[j_2_m1] + y[j_2_p1]) / d ** 2 -
+              k * y[j_2_m1] * y[j_2])
+    f[1::2] = -k * y[j_2] * y[j_2_m1]
+
+    return f
+
+
+def medazko_sparsity(n):
+    cols = []
+    rows = []
+
+    i = np.arange(n) * 2
+
+    cols.append(i[1:])
+    rows.append(i[1:] - 2)
+
+    cols.append(i)
+    rows.append(i)
+
+    cols.append(i)
+    rows.append(i + 1)
+
+    cols.append(i[:-1])
+    rows.append(i[:-1] + 2)
+
+    i = np.arange(n) * 2 + 1
+
+    cols.append(i)
+    rows.append(i)
+
+    cols.append(i)
+    rows.append(i - 1)
+
+    cols = np.hstack(cols)
+    rows = np.hstack(rows)
+
+    return coo_array((np.ones_like(cols), (cols, rows)))
+
+
+def fun_complex(t, y):
+    return -y
+
+
+def jac_complex(t, y):
+    return -np.eye(y.shape[0])
+
+
+def jac_complex_sparse(t, y):
+    return csc_array(jac_complex(t, y))
+
+
+def sol_complex(t):
+    y = (0.5 + 1j) * np.exp(-t)
+    return y.reshape((1, -1))
+
+
+def fun_event_dense_output_LSODA(t, y):
+    return y * (t - 2)
+
+
+def jac_event_dense_output_LSODA(t, y):
+    return t - 2
+
+
+def sol_event_dense_output_LSODA(t):
+    return np.exp(t ** 2 / 2 - 2 * t + np.log(0.05) - 6)
+
+
+def compute_error(y, y_true, rtol, atol):
+    e = (y - y_true) / (atol + rtol * np.abs(y_true))
+    return np.linalg.norm(e, axis=0) / np.sqrt(e.shape[0])
+
+def test_duplicate_timestamps():
+    def upward_cannon(t, y):
+        return [y[1], -9.80665]
+
+    def hit_ground(t, y):
+        return y[0]
+
+    hit_ground.terminal = True
+    hit_ground.direction = -1
+
+    sol = solve_ivp(upward_cannon, [0, np.inf], [0, 0.01],
+                    max_step=0.05 * 0.001 / 9.80665,
+                    events=hit_ground, dense_output=True)
+    assert_allclose(sol.sol(0.01), np.asarray([-0.00039033, -0.08806632]),
+                    rtol=1e-5, atol=1e-8)
+    assert_allclose(sol.t_events, np.asarray([[0.00203943]]), rtol=1e-5, atol=1e-8)
+    assert_allclose(sol.y_events, [np.asarray([[ 0.0, -0.01 ]])], atol=1e-9)
+    assert sol.success
+    assert_equal(sol.status, 1)
+
+
+def test_integration():
+    rtol = 1e-3
+    atol = 1e-6
+    y0 = [1/3, 2/9]
+
+    for vectorized, method, t_span, jac in product(
+            [False, True],
+            ['RK23', 'RK45', 'DOP853', 'Radau', 'BDF', 'LSODA'],
+            [[5, 9], [5, 1]],
+            [None, jac_rational, jac_rational_sparse]):
+
+        if vectorized:
+            fun = fun_rational_vectorized
+        else:
+            fun = fun_rational
+
+        with warnings.catch_warnings():
+            warnings.filterwarnings(
+                "ignore",
+                "The following arguments have no effect for a chosen solver: `jac`",
+                UserWarning,
+            )
+            res = solve_ivp(fun, t_span, y0, rtol=rtol,
+                            atol=atol, method=method, dense_output=True,
+                            jac=jac, vectorized=vectorized)
+        assert_equal(res.t[0], t_span[0])
+        assert_(res.t_events is None)
+        assert_(res.y_events is None)
+        assert_(res.success)
+        assert_equal(res.status, 0)
+
+        if method == 'DOP853':
+            # DOP853 spends more functions evaluation because it doesn't
+            # have enough time to develop big enough step size.
+            assert_(res.nfev < 50)
+        else:
+            assert_(res.nfev < 40)
+
+        if method in ['RK23', 'RK45', 'DOP853', 'LSODA']:
+            assert_equal(res.njev, 0)
+            assert_equal(res.nlu, 0)
+        else:
+            assert_(0 < res.njev < 3)
+            assert_(0 < res.nlu < 10)
+
+        y_true = sol_rational(res.t)
+        e = compute_error(res.y, y_true, rtol, atol)
+        assert_(np.all(e < 5))
+
+        tc = np.linspace(*t_span)
+        yc_true = sol_rational(tc)
+        yc = res.sol(tc)
+
+        e = compute_error(yc, yc_true, rtol, atol)
+        assert_(np.all(e < 5))
+
+        tc = (t_span[0] + t_span[-1]) / 2
+        yc_true = sol_rational(tc)
+        yc = res.sol(tc)
+
+        e = compute_error(yc, yc_true, rtol, atol)
+        assert_(np.all(e < 5))
+
+        assert_allclose(res.sol(res.t), res.y, rtol=1e-15, atol=1e-15)
+
+
+def test_integration_complex():
+    rtol = 1e-3
+    atol = 1e-6
+    y0 = [0.5 + 1j]
+    t_span = [0, 1]
+    tc = np.linspace(t_span[0], t_span[1])
+    for method, jac in product(['RK23', 'RK45', 'DOP853', 'BDF'],
+                               [None, jac_complex, jac_complex_sparse]):
+        with warnings.catch_warnings():
+            warnings.filterwarnings(
+                "ignore",
+                "The following arguments have no effect for a chosen solver: `jac`",
+                UserWarning,
+            )
+            res = solve_ivp(fun_complex, t_span, y0, method=method,
+                            dense_output=True, rtol=rtol, atol=atol, jac=jac)
+
+        assert_equal(res.t[0], t_span[0])
+        assert_(res.t_events is None)
+        assert_(res.y_events is None)
+        assert_(res.success)
+        assert_equal(res.status, 0)
+
+        if method == 'DOP853':
+            assert res.nfev < 35
+        else:
+            assert res.nfev < 25
+
+        if method == 'BDF':
+            assert_equal(res.njev, 1)
+            assert res.nlu < 6
+        else:
+            assert res.njev == 0
+            assert res.nlu == 0
+
+        y_true = sol_complex(res.t)
+        e = compute_error(res.y, y_true, rtol, atol)
+        assert np.all(e < 5)
+
+        yc_true = sol_complex(tc)
+        yc = res.sol(tc)
+        e = compute_error(yc, yc_true, rtol, atol)
+
+        assert np.all(e < 5)
+
+
+def test_integration_complex_sparse():
+    # Regression test for gh-24671: solve_ivp with a complex ODE and
+    # jac_sparsity should not emit ComplexWarning.
+    rtol = 1e-3
+    atol = 1e-6
+    y0 = [0.5 + 1j]
+    t_span = [0, 1]
+    sparsity = csc_array(np.ones((1, 1)))
+    res = solve_ivp(fun_complex, t_span, y0, method='BDF',
+                    rtol=rtol, atol=atol, jac_sparsity=sparsity)
+    assert res.success
+    y_true = sol_complex(res.t)
+    e = compute_error(res.y, y_true, rtol, atol)
+    assert np.all(e < 5)
+
+
+@pytest.mark.fail_slow(5)
+def test_integration_sparse_difference():
+    n = 200
+    t_span = [0, 20]
+    y0 = np.zeros(2 * n)
+    y0[1::2] = 1
+    sparsity = medazko_sparsity(n)
+
+    for method in ['BDF', 'Radau']:
+        res = solve_ivp(fun_medazko, t_span, y0, method=method,
+                        jac_sparsity=sparsity)
+
+        assert_equal(res.t[0], t_span[0])
+        assert_(res.t_events is None)
+        assert_(res.y_events is None)
+        assert_(res.success)
+        assert_equal(res.status, 0)
+
+        assert_allclose(res.y[78, -1], 0.233994e-3, rtol=1e-2)
+        assert_allclose(res.y[79, -1], 0, atol=1e-3)
+        assert_allclose(res.y[148, -1], 0.359561e-3, rtol=1e-2)
+        assert_allclose(res.y[149, -1], 0, atol=1e-3)
+        assert_allclose(res.y[198, -1], 0.117374129e-3, rtol=1e-2)
+        assert_allclose(res.y[199, -1], 0.6190807e-5, atol=1e-3)
+        assert_allclose(res.y[238, -1], 0, atol=1e-3)
+        assert_allclose(res.y[239, -1], 0.9999997, rtol=1e-2)
+
+
+def test_integration_const_jac():
+    rtol = 1e-3
+    atol = 1e-6
+    y0 = [0, 2]
+    t_span = [0, 2]
+    J = jac_linear()
+    J_sparse = csc_array(J)
+
+    for method, jac in product(['Radau', 'BDF'], [J, J_sparse]):
+        res = solve_ivp(fun_linear, t_span, y0, rtol=rtol, atol=atol,
+                        method=method, dense_output=True, jac=jac)
+        assert_equal(res.t[0], t_span[0])
+        assert_(res.t_events is None)
+        assert_(res.y_events is None)
+        assert_(res.success)
+        assert_equal(res.status, 0)
+
+        assert_(res.nfev < 100)
+        assert_equal(res.njev, 0)
+        assert_(0 < res.nlu < 15)
+
+        y_true = sol_linear(res.t)
+        e = compute_error(res.y, y_true, rtol, atol)
+        assert_(np.all(e < 10))
+
+        tc = np.linspace(*t_span)
+        yc_true = sol_linear(tc)
+        yc = res.sol(tc)
+
+        e = compute_error(yc, yc_true, rtol, atol)
+        assert_(np.all(e < 15))
+
+        assert_allclose(res.sol(res.t), res.y, rtol=1e-14, atol=1e-14)
+
+
+@pytest.mark.slow
+@pytest.mark.parametrize('method', ['Radau', 'BDF', 'LSODA'])
+def test_integration_stiff(method, num_parallel_threads):
+    rtol = 1e-6
+    atol = 1e-6
+    y0 = [1e4, 0, 0]
+    tspan = [0, 1e8]
+
+    if method == 'LSODA' and num_parallel_threads > 1:
+        pytest.skip(reason='LSODA does not allow for concurrent calls')
+
+    def fun_robertson(t, state):
+        x, y, z = state
+        return [
+            -0.04 * x + 1e4 * y * z,
+            0.04 * x - 1e4 * y * z - 3e7 * y * y,
+            3e7 * y * y,
+        ]
+
+    res = solve_ivp(fun_robertson, tspan, y0, rtol=rtol,
+                    atol=atol, method=method)
+
+    # If the stiff mode is not activated correctly, these numbers will be much bigger
+    assert res.nfev < 5000
+    assert res.njev < 200
+
+
+def test_events(num_parallel_threads):
+    def event_rational_1(t, y):
+        return y[0] - y[1] ** 0.7
+
+    def event_rational_2(t, y):
+        return y[1] ** 0.6 - y[0]
+
+    def event_rational_3(t, y):
+        return t - 7.4
+
+    event_rational_3.terminal = True
+
+    for method in ['RK23', 'RK45', 'DOP853', 'Radau', 'BDF', 'LSODA']:
+        if method == 'LSODA' and num_parallel_threads > 1:
+            continue
+
+        res = solve_ivp(fun_rational, [5, 8], [1/3, 2/9], method=method,
+                        events=(event_rational_1, event_rational_2))
+        assert_equal(res.status, 0)
+        assert_equal(res.t_events[0].size, 1)
+        assert_equal(res.t_events[1].size, 1)
+        assert_(5.3 < res.t_events[0][0] < 5.7)
+        assert_(7.3 < res.t_events[1][0] < 7.7)
+
+        assert_equal(res.y_events[0].shape, (1, 2))
+        assert_equal(res.y_events[1].shape, (1, 2))
+        assert np.isclose(
+            event_rational_1(res.t_events[0][0], res.y_events[0][0]), 0)
+        assert np.isclose(
+            event_rational_2(res.t_events[1][0], res.y_events[1][0]), 0)
+
+        event_rational_1.direction = 1
+        event_rational_2.direction = 1
+        res = solve_ivp(fun_rational, [5, 8], [1 / 3, 2 / 9], method=method,
+                        events=(event_rational_1, event_rational_2))
+        assert_equal(res.status, 0)
+        assert_equal(res.t_events[0].size, 1)
+        assert_equal(res.t_events[1].size, 0)
+        assert_(5.3 < res.t_events[0][0] < 5.7)
+        assert_equal(res.y_events[0].shape, (1, 2))
+        assert_equal(res.y_events[1].shape, (0,))
+        assert np.isclose(
+            event_rational_1(res.t_events[0][0], res.y_events[0][0]), 0)
+
+        event_rational_1.direction = -1
+        event_rational_2.direction = -1
+        res = solve_ivp(fun_rational, [5, 8], [1 / 3, 2 / 9], method=method,
+                        events=(event_rational_1, event_rational_2))
+        assert_equal(res.status, 0)
+        assert_equal(res.t_events[0].size, 0)
+        assert_equal(res.t_events[1].size, 1)
+        assert_(7.3 < res.t_events[1][0] < 7.7)
+        assert_equal(res.y_events[0].shape, (0,))
+        assert_equal(res.y_events[1].shape, (1, 2))
+        assert np.isclose(
+            event_rational_2(res.t_events[1][0], res.y_events[1][0]), 0)
+
+        event_rational_1.direction = 0
+        event_rational_2.direction = 0
+
+        res = solve_ivp(fun_rational, [5, 8], [1 / 3, 2 / 9], method=method,
+                        events=(event_rational_1, event_rational_2,
+                                event_rational_3), dense_output=True)
+        assert_equal(res.status, 1)
+        assert_equal(res.t_events[0].size, 1)
+        assert_equal(res.t_events[1].size, 0)
+        assert_equal(res.t_events[2].size, 1)
+        assert_(5.3 < res.t_events[0][0] < 5.7)
+        assert_(7.3 < res.t_events[2][0] < 7.5)
+        assert_equal(res.y_events[0].shape, (1, 2))
+        assert_equal(res.y_events[1].shape, (0,))
+        assert_equal(res.y_events[2].shape, (1, 2))
+        assert np.isclose(
+            event_rational_1(res.t_events[0][0], res.y_events[0][0]), 0)
+        assert np.isclose(
+            event_rational_3(res.t_events[2][0], res.y_events[2][0]), 0)
+
+        res = solve_ivp(fun_rational, [5, 8], [1 / 3, 2 / 9], method=method,
+                        events=event_rational_1, dense_output=True)
+        assert_equal(res.status, 0)
+        assert_equal(res.t_events[0].size, 1)
+        assert_(5.3 < res.t_events[0][0] < 5.7)
+
+        assert_equal(res.y_events[0].shape, (1, 2))
+        assert np.isclose(
+            event_rational_1(res.t_events[0][0], res.y_events[0][0]), 0)
+
+        # Also test that termination by event doesn't break interpolants.
+        tc = np.linspace(res.t[0], res.t[-1])
+        yc_true = sol_rational(tc)
+        yc = res.sol(tc)
+        e = compute_error(yc, yc_true, 1e-3, 1e-6)
+        assert_(np.all(e < 5))
+
+        # Test that the y_event matches solution
+        assert np.allclose(sol_rational(res.t_events[0][0]), res.y_events[0][0],
+                           rtol=1e-3, atol=1e-6)
+
+    # Test in backward direction.
+    event_rational_1.direction = 0
+    event_rational_2.direction = 0
+    for method in ['RK23', 'RK45', 'DOP853', 'Radau', 'BDF', 'LSODA']:
+        if method == 'LSODA' and num_parallel_threads > 1:
+            continue
+
+        res = solve_ivp(fun_rational, [8, 5], [4/9, 20/81], method=method,
+                        events=(event_rational_1, event_rational_2))
+        assert_equal(res.status, 0)
+        assert_equal(res.t_events[0].size, 1)
+        assert_equal(res.t_events[1].size, 1)
+        assert_(5.3 < res.t_events[0][0] < 5.7)
+        assert_(7.3 < res.t_events[1][0] < 7.7)
+
+        assert_equal(res.y_events[0].shape, (1, 2))
+        assert_equal(res.y_events[1].shape, (1, 2))
+        assert np.isclose(
+            event_rational_1(res.t_events[0][0], res.y_events[0][0]), 0)
+        assert np.isclose(
+            event_rational_2(res.t_events[1][0], res.y_events[1][0]), 0)
+
+        event_rational_1.direction = -1
+        event_rational_2.direction = -1
+        res = solve_ivp(fun_rational, [8, 5], [4/9, 20/81], method=method,
+                        events=(event_rational_1, event_rational_2))
+        assert_equal(res.status, 0)
+        assert_equal(res.t_events[0].size, 1)
+        assert_equal(res.t_events[1].size, 0)
+        assert_(5.3 < res.t_events[0][0] < 5.7)
+
+        assert_equal(res.y_events[0].shape, (1, 2))
+        assert_equal(res.y_events[1].shape, (0,))
+        assert np.isclose(
+            event_rational_1(res.t_events[0][0], res.y_events[0][0]), 0)
+
+        event_rational_1.direction = 1
+        event_rational_2.direction = 1
+        res = solve_ivp(fun_rational, [8, 5], [4/9, 20/81], method=method,
+                        events=(event_rational_1, event_rational_2))
+        assert_equal(res.status, 0)
+        assert_equal(res.t_events[0].size, 0)
+        assert_equal(res.t_events[1].size, 1)
+        assert_(7.3 < res.t_events[1][0] < 7.7)
+
+        assert_equal(res.y_events[0].shape, (0,))
+        assert_equal(res.y_events[1].shape, (1, 2))
+        assert np.isclose(
+            event_rational_2(res.t_events[1][0], res.y_events[1][0]), 0)
+
+        event_rational_1.direction = 0
+        event_rational_2.direction = 0
+
+        res = solve_ivp(fun_rational, [8, 5], [4/9, 20/81], method=method,
+                        events=(event_rational_1, event_rational_2,
+                                event_rational_3), dense_output=True)
+        assert_equal(res.status, 1)
+        assert_equal(res.t_events[0].size, 0)
+        assert_equal(res.t_events[1].size, 1)
+        assert_equal(res.t_events[2].size, 1)
+        assert_(7.3 < res.t_events[1][0] < 7.7)
+        assert_(7.3 < res.t_events[2][0] < 7.5)
+
+        assert_equal(res.y_events[0].shape, (0,))
+        assert_equal(res.y_events[1].shape, (1, 2))
+        assert_equal(res.y_events[2].shape, (1, 2))
+        assert np.isclose(
+            event_rational_2(res.t_events[1][0], res.y_events[1][0]), 0)
+        assert np.isclose(
+            event_rational_3(res.t_events[2][0], res.y_events[2][0]), 0)
+
+        # Also test that termination by event doesn't break interpolants.
+        tc = np.linspace(res.t[-1], res.t[0])
+        yc_true = sol_rational(tc)
+        yc = res.sol(tc)
+        e = compute_error(yc, yc_true, 1e-3, 1e-6)
+        assert_(np.all(e < 5))
+
+        assert np.allclose(sol_rational(res.t_events[1][0]), res.y_events[1][0],
+                           rtol=1e-3, atol=1e-6)
+        assert np.allclose(sol_rational(res.t_events[2][0]), res.y_events[2][0],
+                           rtol=1e-3, atol=1e-6)
+
+
+def _get_harmonic_oscillator():
+    def f(t, y):
+        return [y[1], -y[0]]
+
+    def event(t, y):
+        return y[0]
+
+    return f, event
+
+
+@pytest.mark.parametrize('n_events', [3, 4])
+def test_event_terminal_integer(n_events):
+    f, event = _get_harmonic_oscillator()
+    event.terminal = n_events
+    res = solve_ivp(f, (0, 100), [1, 0], events=event)
+    assert len(res.t_events[0]) == n_events
+    assert len(res.y_events[0]) == n_events
+    assert_allclose(res.y_events[0][:, 0], 0, atol=1e-14)
+
+
+def test_event_terminal_iv():
+    f, event = _get_harmonic_oscillator()
+    args = (f, (0, 100), [1, 0])
+
+    event.terminal = None
+    res = solve_ivp(*args, events=event)
+    event.terminal = 0
+    ref = solve_ivp(*args, events=event)
+    assert_allclose(res.t_events, ref.t_events)
+
+    message = "The `terminal` attribute..."
+    event.terminal = -1
+    with pytest.raises(ValueError, match=message):
+        solve_ivp(*args, events=event)
+    event.terminal = 3.5
+    with pytest.raises(ValueError, match=message):
+        solve_ivp(*args, events=event)
+
+
+def test_max_step(num_parallel_threads):
+    rtol = 1e-3
+    atol = 1e-6
+    y0 = [1/3, 2/9]
+    for method in [RK23, RK45, DOP853, Radau, BDF, LSODA]:
+        if method is LSODA and num_parallel_threads > 1:
+            continue
+        for t_span in ([5, 9], [5, 1]):
+            res = solve_ivp(fun_rational, t_span, y0, rtol=rtol,
+                            max_step=0.5, atol=atol, method=method,
+                            dense_output=True)
+            assert_equal(res.t[0], t_span[0])
+            assert_equal(res.t[-1], t_span[-1])
+            assert_(np.all(np.abs(np.diff(res.t)) <= 0.5 + 1e-15))
+            assert_(res.t_events is None)
+            assert_(res.success)
+            assert_equal(res.status, 0)
+
+            y_true = sol_rational(res.t)
+            e = compute_error(res.y, y_true, rtol, atol)
+            assert_(np.all(e < 5))
+
+            tc = np.linspace(*t_span)
+            yc_true = sol_rational(tc)
+            yc = res.sol(tc)
+
+            e = compute_error(yc, yc_true, rtol, atol)
+            assert_(np.all(e < 5))
+
+            assert_allclose(res.sol(res.t), res.y, rtol=1e-15, atol=1e-15)
+
+            assert_raises(ValueError, method, fun_rational, t_span[0], y0,
+                          t_span[1], max_step=-1)
+
+            if method is not LSODA:
+                solver = method(fun_rational, t_span[0], y0, t_span[1],
+                                rtol=rtol, atol=atol, max_step=1e-20)
+                message = solver.step()
+                message = solver.step()  # First step succeeds but second step fails.
+                assert_equal(solver.status, 'failed')
+                assert_("step size is less" in message)
+                assert_raises(RuntimeError, solver.step)
+
+
+def test_first_step(num_parallel_threads):
+    rtol = 1e-3
+    atol = 1e-6
+    y0 = [1/3, 2/9]
+    first_step = 0.1
+    for method in [RK23, RK45, DOP853, Radau, BDF, LSODA]:
+        if method is LSODA and num_parallel_threads > 1:
+            continue
+        for t_span in ([5, 9], [5, 1]):
+            res = solve_ivp(fun_rational, t_span, y0, rtol=rtol,
+                            max_step=0.5, atol=atol, method=method,
+                            dense_output=True, first_step=first_step)
+
+            assert_equal(res.t[0], t_span[0])
+            assert_equal(res.t[-1], t_span[-1])
+            assert_allclose(first_step, np.abs(res.t[1] - 5))
+            assert_(res.t_events is None)
+            assert_(res.success)
+            assert_equal(res.status, 0)
+
+            y_true = sol_rational(res.t)
+            e = compute_error(res.y, y_true, rtol, atol)
+            assert_(np.all(e < 5))
+
+            tc = np.linspace(*t_span)
+            yc_true = sol_rational(tc)
+            yc = res.sol(tc)
+
+            e = compute_error(yc, yc_true, rtol, atol)
+            assert_(np.all(e < 5))
+
+            assert_allclose(res.sol(res.t), res.y, rtol=1e-15, atol=1e-15)
+
+            assert_raises(ValueError, method, fun_rational, t_span[0], y0,
+                          t_span[1], first_step=-1)
+            assert_raises(ValueError, method, fun_rational, t_span[0], y0,
+                          t_span[1], first_step=5)
+
+
+def test_t_eval():
+    rtol = 1e-3
+    atol = 1e-6
+    y0 = [1/3, 2/9]
+    for t_span in ([5, 9], [5, 1]):
+        t_eval = np.linspace(t_span[0], t_span[1], 10)
+        res = solve_ivp(fun_rational, t_span, y0, rtol=rtol, atol=atol,
+                        t_eval=t_eval)
+        assert_equal(res.t, t_eval)
+        assert_(res.t_events is None)
+        assert_(res.success)
+        assert_equal(res.status, 0)
+
+        y_true = sol_rational(res.t)
+        e = compute_error(res.y, y_true, rtol, atol)
+        assert_(np.all(e < 5))
+
+    t_eval = [5, 5.01, 7, 8, 8.01, 9]
+    res = solve_ivp(fun_rational, [5, 9], y0, rtol=rtol, atol=atol,
+                    t_eval=t_eval)
+    assert_equal(res.t, t_eval)
+    assert_(res.t_events is None)
+    assert_(res.success)
+    assert_equal(res.status, 0)
+
+    y_true = sol_rational(res.t)
+    e = compute_error(res.y, y_true, rtol, atol)
+    assert_(np.all(e < 5))
+
+    t_eval = [5, 4.99, 3, 1.5, 1.1, 1.01, 1]
+    res = solve_ivp(fun_rational, [5, 1], y0, rtol=rtol, atol=atol,
+                    t_eval=t_eval)
+    assert_equal(res.t, t_eval)
+    assert_(res.t_events is None)
+    assert_(res.success)
+    assert_equal(res.status, 0)
+
+    t_eval = [5.01, 7, 8, 8.01]
+    res = solve_ivp(fun_rational, [5, 9], y0, rtol=rtol, atol=atol,
+                    t_eval=t_eval)
+    assert_equal(res.t, t_eval)
+    assert_(res.t_events is None)
+    assert_(res.success)
+    assert_equal(res.status, 0)
+
+    y_true = sol_rational(res.t)
+    e = compute_error(res.y, y_true, rtol, atol)
+    assert_(np.all(e < 5))
+
+    t_eval = [4.99, 3, 1.5, 1.1, 1.01]
+    res = solve_ivp(fun_rational, [5, 1], y0, rtol=rtol, atol=atol,
+                    t_eval=t_eval)
+    assert_equal(res.t, t_eval)
+    assert_(res.t_events is None)
+    assert_(res.success)
+    assert_equal(res.status, 0)
+
+    t_eval = [4, 6]
+    assert_raises(ValueError, solve_ivp, fun_rational, [5, 9], y0,
+                  rtol=rtol, atol=atol, t_eval=t_eval)
+
+
+def test_t_eval_dense_output():
+    rtol = 1e-3
+    atol = 1e-6
+    y0 = [1/3, 2/9]
+    t_span = [5, 9]
+    t_eval = np.linspace(t_span[0], t_span[1], 10)
+    res = solve_ivp(fun_rational, t_span, y0, rtol=rtol, atol=atol,
+                    t_eval=t_eval)
+    res_d = solve_ivp(fun_rational, t_span, y0, rtol=rtol, atol=atol,
+                      t_eval=t_eval, dense_output=True)
+    assert_equal(res.t, t_eval)
+    assert_(res.t_events is None)
+    assert_(res.success)
+    assert_equal(res.status, 0)
+
+    assert_equal(res.t, res_d.t)
+    assert_equal(res.y, res_d.y)
+    assert_(res_d.t_events is None)
+    assert_(res_d.success)
+    assert_equal(res_d.status, 0)
+
+    # if t and y are equal only test values for one case
+    y_true = sol_rational(res.t)
+    e = compute_error(res.y, y_true, rtol, atol)
+    assert_(np.all(e < 5))
+
+
+def test_t_eval_early_event():
+    def early_event(t, y):
+        return t - 7
+
+    early_event.terminal = True
+
+    rtol = 1e-3
+    atol = 1e-6
+    y0 = [1/3, 2/9]
+    t_span = [5, 9]
+    t_eval = np.linspace(7.5, 9, 16)
+    for method in ['RK23', 'RK45', 'DOP853', 'Radau', 'BDF', 'LSODA']:
+        with warnings.catch_warnings():
+            warnings.filterwarnings(
+                "ignore",
+                "The following arguments have no effect for a chosen solver: `jac`",
+                UserWarning,
+            )
+            res = solve_ivp(fun_rational, t_span, y0, rtol=rtol, atol=atol,
+                            method=method, t_eval=t_eval, events=early_event,
+                            jac=jac_rational)
+        assert res.success
+        assert res.message == 'A termination event occurred.'
+        assert res.status == 1
+        assert not res.t and not res.y
+        assert len(res.t_events) == 1
+        assert res.t_events[0].size == 1
+        assert res.t_events[0][0] == 7
+
+
+def test_event_dense_output_LSODA(num_parallel_threads):
+    if num_parallel_threads > 1:
+        pytest.skip('LSODA does not allow for concurrent execution')
+
+    def event_lsoda(t, y):
+        return y[0] - 2.02e-5
+
+    rtol = 1e-3
+    atol = 1e-6
+    y0 = [0.05]
+    t_span = [-2, 2]
+    first_step = 1e-3
+    res = solve_ivp(
+        fun_event_dense_output_LSODA,
+        t_span,
+        y0,
+        method="LSODA",
+        dense_output=True,
+        events=event_lsoda,
+        first_step=first_step,
+        max_step=1,
+        rtol=rtol,
+        atol=atol,
+        jac=jac_event_dense_output_LSODA,
+    )
+
+    assert_equal(res.t[0], t_span[0])
+    assert_equal(res.t[-1], t_span[-1])
+    assert_allclose(first_step, np.abs(res.t[1] - t_span[0]))
+    assert res.success
+    assert_equal(res.status, 0)
+
+    y_true = sol_event_dense_output_LSODA(res.t)
+    e = compute_error(res.y, y_true, rtol, atol)
+    assert_array_less(e, 5)
+
+    tc = np.linspace(*t_span)
+    yc_true = sol_event_dense_output_LSODA(tc)
+    yc = res.sol(tc)
+    e = compute_error(yc, yc_true, rtol, atol)
+    assert_array_less(e, 5)
+
+    assert_allclose(res.sol(res.t), res.y, rtol=1e-15, atol=1e-15)
+
+
+def test_no_integration():
+    for method in ['RK23', 'RK45', 'DOP853', 'Radau', 'BDF', 'LSODA']:
+        sol = solve_ivp(lambda t, y: -y, [4, 4], [2, 3],
+                        method=method, dense_output=True)
+        assert_equal(sol.sol(4), [2, 3])
+        assert_equal(sol.sol([4, 5, 6]), [[2, 2, 2], [3, 3, 3]])
+
+
+def test_no_integration_class():
+    for method in [RK23, RK45, DOP853, Radau, BDF, LSODA]:
+        solver = method(lambda t, y: -y, 0.0, [10.0, 0.0], 0.0)
+        solver.step()
+        assert_equal(solver.status, 'finished')
+        sol = solver.dense_output()
+        assert_equal(sol(0.0), [10.0, 0.0])
+        assert_equal(sol([0, 1, 2]), [[10, 10, 10], [0, 0, 0]])
+
+        solver = method(lambda t, y: -y, 0.0, [], np.inf)
+        solver.step()
+        assert_equal(solver.status, 'finished')
+        sol = solver.dense_output()
+        assert_equal(sol(100.0), [])
+        assert_equal(sol([0, 1, 2]), np.empty((0, 3)))
+
+
+def test_empty():
+    def fun(t, y):
+        return np.zeros((0,))
+
+    y0 = np.zeros((0,))
+
+    for method in ['RK23', 'RK45', 'DOP853', 'Radau', 'BDF', 'LSODA']:
+        sol = assert_no_warnings(solve_ivp, fun, [0, 10], y0,
+                                 method=method, dense_output=True)
+        assert_equal(sol.sol(10), np.zeros((0,)))
+        assert_equal(sol.sol([1, 2, 3]), np.zeros((0, 3)))
+
+    for method in ['RK23', 'RK45', 'DOP853', 'Radau', 'BDF', 'LSODA']:
+        sol = assert_no_warnings(solve_ivp, fun, [0, np.inf], y0,
+                                 method=method, dense_output=True)
+        assert_equal(sol.sol(10), np.zeros((0,)))
+        assert_equal(sol.sol([1, 2, 3]), np.zeros((0, 3)))
+
+
+def test_ConstantDenseOutput():
+    sol = ConstantDenseOutput(0, 1, np.array([1, 2]))
+    assert_allclose(sol(1.5), [1, 2])
+    assert_allclose(sol([1, 1.5, 2]), [[1, 1, 1], [2, 2, 2]])
+
+    sol = ConstantDenseOutput(0, 1, np.array([]))
+    assert_allclose(sol(1.5), np.empty(0))
+    assert_allclose(sol([1, 1.5, 2]), np.empty((0, 3)))
+
+
+def test_classes():
+    y0 = [1 / 3, 2 / 9]
+    for cls in [RK23, RK45, DOP853, Radau, BDF, LSODA]:
+        solver = cls(fun_rational, 5, y0, np.inf)
+        assert_equal(solver.n, 2)
+        assert_equal(solver.status, 'running')
+        assert_equal(solver.t_bound, np.inf)
+        assert_equal(solver.direction, 1)
+        assert_equal(solver.t, 5)
+        assert_equal(solver.y, y0)
+        assert_(solver.step_size is None)
+        if cls is not LSODA:
+            assert_(solver.nfev > 0)
+            assert_(solver.njev >= 0)
+            assert_equal(solver.nlu, 0)
+        else:
+            assert_equal(solver.nfev, 0)
+            assert_equal(solver.njev, 0)
+            assert_equal(solver.nlu, 0)
+
+        assert_raises(RuntimeError, solver.dense_output)
+
+        message = solver.step()
+        assert_equal(solver.status, 'running')
+        assert_equal(message, None)
+        assert_equal(solver.n, 2)
+        assert_equal(solver.t_bound, np.inf)
+        assert_equal(solver.direction, 1)
+        assert_(solver.t > 5)
+        assert_(not np.all(np.equal(solver.y, y0)))
+        assert_(solver.step_size > 0)
+        assert_(solver.nfev > 0)
+        assert_(solver.njev >= 0)
+        assert_(solver.nlu >= 0)
+        sol = solver.dense_output()
+        assert_allclose(sol(5), y0, rtol=1e-15, atol=0)
+
+
+def test_OdeSolution():
+    ts = np.array([0, 2, 5], dtype=float)
+    s1 = ConstantDenseOutput(ts[0], ts[1], np.array([-1]))
+    s2 = ConstantDenseOutput(ts[1], ts[2], np.array([1]))
+
+    sol = OdeSolution(ts, [s1, s2])
+
+    assert_equal(sol(-1), [-1])
+    assert_equal(sol(1), [-1])
+    assert_equal(sol(2), [-1])
+    assert_equal(sol(3), [1])
+    assert_equal(sol(5), [1])
+    assert_equal(sol(6), [1])
+
+    assert_equal(sol([0, 6, -2, 1.5, 4.5, 2.5, 5, 5.5, 2]),
+                 np.array([[-1, 1, -1, -1, 1, 1, 1, 1, -1]]))
+
+    ts = np.array([10, 4, -3])
+    s1 = ConstantDenseOutput(ts[0], ts[1], np.array([-1]))
+    s2 = ConstantDenseOutput(ts[1], ts[2], np.array([1]))
+
+    sol = OdeSolution(ts, [s1, s2])
+    assert_equal(sol(11), [-1])
+    assert_equal(sol(10), [-1])
+    assert_equal(sol(5), [-1])
+    assert_equal(sol(4), [-1])
+    assert_equal(sol(0), [1])
+    assert_equal(sol(-3), [1])
+    assert_equal(sol(-4), [1])
+
+    assert_equal(sol([12, -5, 10, -3, 6, 1, 4]),
+                 np.array([[-1, 1, -1, 1, -1, 1, -1]]))
+
+    ts = np.array([1, 1])
+    s = ConstantDenseOutput(1, 1, np.array([10]))
+    sol = OdeSolution(ts, [s])
+    assert_equal(sol(0), [10])
+    assert_equal(sol(1), [10])
+    assert_equal(sol(2), [10])
+
+    assert_equal(sol([2, 1, 0]), np.array([[10, 10, 10]]))
+
+
+def test_num_jac():
+    def fun(t, y):
+        return np.vstack([
+            -0.04 * y[0] + 1e4 * y[1] * y[2],
+            0.04 * y[0] - 1e4 * y[1] * y[2] - 3e7 * y[1] ** 2,
+            3e7 * y[1] ** 2
+        ])
+
+    def jac(t, y):
+        return np.array([
+            [-0.04, 1e4 * y[2], 1e4 * y[1]],
+            [0.04, -1e4 * y[2] - 6e7 * y[1], -1e4 * y[1]],
+            [0, 6e7 * y[1], 0]
+        ])
+
+    t = 1
+    y = np.array([1, 0, 0])
+    J_true = jac(t, y)
+    threshold = 1e-5
+    f = fun(t, y).ravel()
+
+    J_num, factor = num_jac(fun, t, y, f, threshold, None)
+    assert_allclose(J_num, J_true, rtol=1e-5, atol=1e-5)
+
+    J_num, factor = num_jac(fun, t, y, f, threshold, factor)
+    assert_allclose(J_num, J_true, rtol=1e-5, atol=1e-5)
+
+
+@pytest.mark.parametrize("structure_type", [csc_array, csc_matrix, np.array])
+def test_num_jac_sparse(structure_type):
+    def fun(t, y):
+        e = y[1:]**3 - y[:-1]**2
+        z = np.zeros(y.shape[1])
+        return np.vstack((z, 3 * e)) + np.vstack((2 * e, z))
+
+    def structure(n):
+        A = np.zeros((n, n), dtype=int)
+        A[0, 0] = 1
+        A[0, 1] = 1
+        for i in range(1, n - 1):
+            A[i, i - 1: i + 2] = 1
+        A[-1, -1] = 1
+        A[-1, -2] = 1
+
+        return structure_type(A)
+
+    np.random.seed(0)
+    n = 20
+    y = np.random.randn(n)
+    A = structure(n)
+    groups = group_columns(A)
+
+    f = fun(0, y[:, None]).ravel()
+
+    # Compare dense and sparse results, assuming that dense implementation
+    # is correct (as it is straightforward).
+    J_num_sparse, factor_sparse = num_jac(fun, 0, y.ravel(), f, 1e-8, None,
+                                          sparsity=(A, groups))
+    J_num_dense, factor_dense = num_jac(fun, 0, y.ravel(), f, 1e-8, None)
+    assert_allclose(J_num_dense, J_num_sparse.toarray(),
+                    rtol=1e-12, atol=1e-14)
+    assert_allclose(factor_dense, factor_sparse, rtol=1e-12, atol=1e-14)
+
+    # Take small factors to trigger their recomputing inside.
+    factor = np.random.uniform(0, 1e-12, size=n)
+    J_num_sparse, factor_sparse = num_jac(fun, 0, y.ravel(), f, 1e-8, factor,
+                                          sparsity=(A, groups))
+    J_num_dense, factor_dense = num_jac(fun, 0, y.ravel(), f, 1e-8, factor)
+
+    assert_allclose(J_num_dense, J_num_sparse.toarray(),
+                    rtol=1e-12, atol=1e-14)
+    assert_allclose(factor_dense, factor_sparse, rtol=1e-12, atol=1e-14)
+
+
+def test_args():
+
+    # sys3 is actually two decoupled systems. (x, y) form a
+    # linear oscillator, while z is a nonlinear first order
+    # system with equilibria at z=0 and z=1. If k > 0, z=1
+    # is stable and z=0 is unstable.
+
+    def sys3(t, w, omega, k, zfinal):
+        x, y, z = w
+        return [-omega*y, omega*x, k*z*(1 - z)]
+
+    def sys3_jac(t, w, omega, k, zfinal):
+        x, y, z = w
+        J = np.array([[0, -omega, 0],
+                      [omega, 0, 0],
+                      [0, 0, k*(1 - 2*z)]])
+        return J
+
+    def sys3_x0decreasing(t, w, omega, k, zfinal):
+        x, y, z = w
+        return x
+
+    def sys3_y0increasing(t, w, omega, k, zfinal):
+        x, y, z = w
+        return y
+
+    def sys3_zfinal(t, w, omega, k, zfinal):
+        x, y, z = w
+        return z - zfinal
+
+    # Set the event flags for the event functions.
+    sys3_x0decreasing.direction = -1
+    sys3_y0increasing.direction = 1
+    sys3_zfinal.terminal = True
+
+    omega = 2
+    k = 4
+
+    tfinal = 5
+    zfinal = 0.99
+    # Find z0 such that when z(0) = z0, z(tfinal) = zfinal.
+    # The condition z(tfinal) = zfinal is the terminal event.
+    z0 = np.exp(-k*tfinal)/((1 - zfinal)/zfinal + np.exp(-k*tfinal))
+
+    w0 = [0, -1, z0]
+
+    # Provide the jac argument and use the Radau method to ensure that the use
+    # of the Jacobian function is exercised.
+    # If event handling is working, the solution will stop at tfinal, not tend.
+    tend = 2*tfinal
+    sol = solve_ivp(sys3, [0, tend], w0,
+                    events=[sys3_x0decreasing, sys3_y0increasing, sys3_zfinal],
+                    dense_output=True, args=(omega, k, zfinal),
+                    method='Radau', jac=sys3_jac,
+                    rtol=1e-10, atol=1e-13)
+
+    # Check that we got the expected events at the expected times.
+    x0events_t = sol.t_events[0]
+    y0events_t = sol.t_events[1]
+    zfinalevents_t = sol.t_events[2]
+    assert_allclose(x0events_t, [0.5*np.pi, 1.5*np.pi])
+    assert_allclose(y0events_t, [0.25*np.pi, 1.25*np.pi])
+    assert_allclose(zfinalevents_t, [tfinal])
+
+    # Check that the solution agrees with the known exact solution.
+    t = np.linspace(0, zfinalevents_t[0], 250)
+    w = sol.sol(t)
+    assert_allclose(w[0], np.sin(omega*t), rtol=1e-9, atol=1e-12)
+    assert_allclose(w[1], -np.cos(omega*t), rtol=1e-9, atol=1e-12)
+    assert_allclose(w[2], 1/(((1 - z0)/z0)*np.exp(-k*t) + 1),
+                    rtol=1e-9, atol=1e-12)
+
+    # Check that the state variables have the expected values at the events.
+    x0events = sol.sol(x0events_t)
+    y0events = sol.sol(y0events_t)
+    zfinalevents = sol.sol(zfinalevents_t)
+    assert_allclose(x0events[0], np.zeros_like(x0events[0]), atol=5e-14)
+    assert_allclose(x0events[1], np.ones_like(x0events[1]))
+    assert_allclose(y0events[0], np.ones_like(y0events[0]))
+    assert_allclose(y0events[1], np.zeros_like(y0events[1]), atol=5e-14)
+    assert_allclose(zfinalevents[2], [zfinal])
+
+
+def test_array_rtol():
+    # solve_ivp had a bug with array_like `rtol`; see gh-15482
+    # check that it's fixed
+    def f(t, y):
+        return y[0], y[1]
+
+    # no warning (or error) when `rtol` is array_like
+    sol = solve_ivp(f, (0, 1), [1., 1.], rtol=[1e-1, 1e-1])
+    err1 = np.abs(np.linalg.norm(sol.y[:, -1] - np.exp(1)))
+
+    # warning when an element of `rtol` is too small
+    with pytest.warns(UserWarning, match="At least one element..."):
+        sol = solve_ivp(f, (0, 1), [1., 1.], rtol=[1e-1, 1e-16])
+        err2 = np.abs(np.linalg.norm(sol.y[:, -1] - np.exp(1)))
+
+    # tighter rtol improves the error
+    assert err2 < err1
+
+
+@pytest.mark.parametrize('method', ['RK23', 'RK45', 'DOP853', 'Radau', 'BDF', 'LSODA'])
+def test_integration_zero_rhs(method, num_parallel_threads):
+    if method == 'LSODA' and num_parallel_threads > 1:
+        pytest.skip(reason='LSODA does not allow for concurrent execution')
+
+    result = solve_ivp(fun_zero, [0, 10], np.ones(3), method=method)
+    assert_(result.success)
+    assert_equal(result.status, 0)
+    assert_allclose(result.y, 1.0, rtol=1e-15)
+
+
+def test_args_single_value():
+    def fun_with_arg(t, y, a):
+        return a*y
+
+    message = "Supplied 'args' cannot be unpacked."
+    with pytest.raises(TypeError, match=message):
+        solve_ivp(fun_with_arg, (0, 0.1), [1], args=-1)
+
+    sol = solve_ivp(fun_with_arg, (0, 0.1), [1], args=(-1,))
+    assert_allclose(sol.y[0, -1], np.exp(-0.1))
+
+
+@pytest.mark.parametrize("f0_fill", [np.nan, np.inf])
+def test_initial_state_finiteness(f0_fill):
+    # regression test for gh-17846
+    msg = "All components of the initial state `y0` must be finite."
+    with pytest.raises(ValueError, match=msg):
+        solve_ivp(fun_zero, [0, 10], np.full(3, f0_fill))
+
+
+@pytest.mark.parametrize('method', ['RK23', 'RK45', 'DOP853', 'Radau', 'BDF'])
+def test_zero_interval(method):
+    # Case where upper and lower limits of integration are the same
+    # Result of integration should match initial state.
+    # f[y(t)] = 2y(t)
+    def f(t, y):
+        return 2 * y
+    res = solve_ivp(f, (0.0, 0.0), np.array([1.0]), method=method)
+    assert res.success
+    assert_allclose(res.y[0, -1], 1.0)
+
+
+@pytest.mark.parametrize('method', ['RK23', 'RK45', 'DOP853', 'Radau', 'BDF'])
+def test_tbound_respected_small_interval(method):
+    """Regression test for gh-17341"""
+    SMALL = 1e-4
+
+    # f[y(t)] = 2y(t) on t in [0,SMALL]
+    #           undefined otherwise
+    def f(t, y):
+        if t > SMALL:
+            raise ValueError("Function was evaluated outside interval")
+        return 2 * y
+    res = solve_ivp(f, (0.0, SMALL), np.array([1]), method=method)
+    assert res.success
+
+
+@pytest.mark.parametrize('method', ['RK23', 'RK45', 'DOP853', 'Radau', 'BDF'])
+def test_tbound_respected_larger_interval(method):
+    """Regression test for gh-8848"""
+    def V(r):
+        return -11/r + 10 * r / (0.05 + r**2)
+
+    def func(t, p):
+        if t < -17 or t > 2:
+            raise ValueError("Function was evaluated outside interval")
+        P = p[0]
+        Q = p[1]
+        r = np.exp(t)
+        dPdr = r * Q
+        dQdr = -2.0 * r * ((-0.2 - V(r)) * P + 1 / r * Q)
+        return np.array([dPdr, dQdr])
+
+    result = solve_ivp(func,
+                       (-17, 2),
+                       y0=np.array([1, -11]),
+                       max_step=0.03,
+                       vectorized=False,
+                       t_eval=None,
+                       atol=1e-8,
+                       rtol=1e-5)
+    assert result.success
+
+
+@pytest.mark.parametrize('method', ['RK23', 'RK45', 'DOP853', 'Radau', 'BDF'])
+def test_tbound_respected_oscillator(method):
+    "Regression test for gh-9198"
+    def reactions_func(t, y):
+        if (t > 205):
+            raise ValueError("Called outside interval")
+        yprime = np.array([1.73307544e-02,
+                           6.49376470e-06,
+                           0.00000000e+00,
+                           0.00000000e+00])
+        return yprime
+
+    def run_sim2(t_end, n_timepoints=10, shortest_delay_line=10000000):
+        init_state = np.array([134.08298555, 138.82348612, 100., 0.])
+        t0 = 100.0
+        t1 = 200.0
+        return solve_ivp(reactions_func,
+                         (t0, t1),
+                         init_state.copy(),
+                         dense_output=True,
+                         max_step=t1 - t0)
+    result = run_sim2(1000, 100, 100)
+    assert result.success
+
+
+def test_inital_maxstep():
+    """Verify that select_inital_step respects max_step"""
+    rtol = 1e-3
+    atol = 1e-6
+    y0 = np.array([1/3, 2/9])
+    for (t0, t_bound) in ((5, 9), (5, 1)):
+        for method_order in [RK23.error_estimator_order,
+                            RK45.error_estimator_order,
+                            DOP853.error_estimator_order,
+                            3, #RADAU
+                            1 #BDF
+                            ]:
+            step_no_max = select_initial_step(fun_rational, t0, y0, t_bound,
+                                            np.inf,
+                                            fun_rational(t0,y0),
+                                            np.sign(t_bound - t0),
+                                            method_order,
+                                            rtol, atol)
+            max_step = step_no_max/2
+            step_with_max = select_initial_step(fun_rational, t0, y0, t_bound,
+                                            max_step,
+                                            fun_rational(t0, y0),
+                                            np.sign(t_bound - t0),
+                                            method_order,
+                                            rtol, atol)
+            assert_equal(max_step, step_with_max)
diff --git a/.venv/lib/python3.12/site-packages/scipy/integrate/_ivp/tests/test_rk.py b/.venv/lib/python3.12/site-packages/scipy/integrate/_ivp/tests/test_rk.py
new file mode 100644
index 0000000000000000000000000000000000000000..33cb27d0323d037c0937ab94b4de8f63b46be3d7
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/integrate/_ivp/tests/test_rk.py
@@ -0,0 +1,37 @@
+import pytest
+from numpy.testing import assert_allclose, assert_
+import numpy as np
+from scipy.integrate import RK23, RK45, DOP853
+from scipy.integrate._ivp import dop853_coefficients
+
+
+@pytest.mark.parametrize("solver", [RK23, RK45, DOP853])
+def test_coefficient_properties(solver):
+    assert_allclose(np.sum(solver.B), 1, rtol=1e-15)
+    assert_allclose(np.sum(solver.A, axis=1), solver.C, rtol=1e-14)
+
+
+def test_coefficient_properties_dop853():
+    assert_allclose(np.sum(dop853_coefficients.B), 1, rtol=1e-15)
+    assert_allclose(np.sum(dop853_coefficients.A, axis=1),
+                    dop853_coefficients.C,
+                    rtol=1e-14)
+
+
+@pytest.mark.parametrize("solver_class", [RK23, RK45, DOP853])
+def test_error_estimation(solver_class):
+    step = 0.2
+    solver = solver_class(lambda t, y: y, 0, [1], 1, first_step=step)
+    solver.step()
+    error_estimate = solver._estimate_error(solver.K, step)
+    error = solver.y - np.exp([step])
+    assert_(np.abs(error) < np.abs(error_estimate))
+
+
+@pytest.mark.parametrize("solver_class", [RK23, RK45, DOP853])
+def test_error_estimation_complex(solver_class):
+    h = 0.2
+    solver = solver_class(lambda t, y: 1j * y, 0, [1j], 1, first_step=h)
+    solver.step()
+    err_norm = solver._estimate_error_norm(solver.K, h, scale=[1])
+    assert np.isrealobj(err_norm)
diff --git a/.venv/lib/python3.12/site-packages/scipy/integrate/_lebedev.py b/.venv/lib/python3.12/site-packages/scipy/integrate/_lebedev.py
new file mode 100644
index 0000000000000000000000000000000000000000..6e45d40e7950780c724523809a7c18fc957fa576
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/integrate/_lebedev.py
@@ -0,0 +1,5453 @@
+# getLebedevSphere
+# Copyright (c) 2010, Robert Parrish
+# 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
+#
+# 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.
+#
+# Brainlessly translated to Python
+
+import numpy as np
+from numpy import pi, zeros, sqrt
+
+from scipy._lib._array_api import xp_capabilities
+
+
+__all__ = ['lebedev_rule']
+
+
+def get_lebedev_sphere(degree):
+    # getLebedevSphere
+    # @author Rob Parrish, The Sherrill Group, CCMST Georgia Tech
+    # @email robparrish@gmail.com
+    # @date 03/24/2010
+    #
+    # @description - function to compute normalized points and weights
+    # for Lebedev quadratures on the surface of the unit sphere at double precision.
+    # **********Relative error is generally expected to be ~2.0E-14 [1]********
+    # Lebedev quadratures are superbly accurate and efficient quadrature rules for
+    # approximating integrals of the form $v = \iint_{4\pi}  f(\Omega) \ \ud
+    # \Omega$, where $\Omega is the solid angle on the surface of the unit
+    # sphere. Lebedev quadratures integrate all spherical harmonics up to $l =
+    # order$, where $degree \approx order(order+1)/3$. These grids may be easily
+    # combined with radial quadratures to provide robust cubature formulae. For
+    # example, see 'A. Becke, 1988c, J. Chem. Phys., 88(4), pp. 2547' (The first
+    # paper on tractable molecular Density Functional Theory methods, of which
+    # Lebedev grids and numerical cubature are an intrinsic part).
+    #
+    # @param degree - positive integer specifying number of points in the
+    # requested quadrature. Allowed values are (degree -> order):
+    # degree: { 6, 14, 26, 38, 50, 74, 86, 110, 146, 170, 194, 230, 266, 302,
+    #   350, 434, 590, 770, 974, 1202, 1454, 1730, 2030, 2354, 2702, 3074,
+    #   3470, 3890, 4334, 4802, 5294, 5810 }
+    # order: {3,5,7,9,11,13,15,17,19,21,23,25,27,29,31,35,41,47,53,59,65,71,77,
+    #   83,89,95,101,107,113,119,125,131}
+    #
+    #
+    # @return leb_tmp - struct containing fields:
+    #   x - x values of quadrature, constrained to unit sphere
+    #   y - y values of quadrature, constrained to unit sphere
+    #   z - z values of quadrature, constrained to unit sphere
+    #   w - quadrature weights, normalized to $4\pi$.
+    #
+    # @example: $\int_S x^2+y^2-z^2 \ud \Omega = 4.188790204786399$
+    #   f = @(x,y,z) x.^2+y.^2-z.^2
+    #   leb = getLebedevSphere(590)
+    #   v = f(leb.x,leb.y,leb.z)
+    #   int = sum(v.*leb.w)
+    #
+    # @citation - Translated from a Fortran code kindly provided by Christoph van
+    # Wuellen (Ruhr-Universitaet, Bochum, Germany), which in turn came from the
+    # original C routines coded by Dmitri Laikov (Moscow State University,
+    # Moscow, Russia). The MATLAB implementation of this code is designed for
+    # benchmarking of new DFT integration techniques to be implemented in the
+    # open source Psi4 ab initio quantum chemistry program.
+    #
+    # As per Professor Wuellen's request, any papers published using this code
+    # or its derivatives are requested to include the following citation:
+    #
+    # [1] V.I. Lebedev, and D.N. Laikov
+    #    "A quadrature formula for the sphere of the 131st
+    #     algebraic order of accuracy"
+    #    Doklady Mathematics, Vol. 59, No. 3, 1999, pp. 477-481.
+
+    class Leb:
+        x, y, z, w = None, None, None, None
+
+    leb_tmp = Leb()
+
+    leb_tmp.x = zeros(degree)
+    leb_tmp.y = zeros(degree)
+    leb_tmp.z = zeros(degree)
+    leb_tmp.w = zeros(degree)
+
+    start = 0
+    a = 0.0
+    b = 0.0
+
+    match degree:
+
+        case 6:
+
+            v = 0.1666666666666667E+0
+            leb_tmp, start = get_lebedev_recurrence_points(1, start, a, b, v, leb_tmp)
+
+        case 14:
+
+            v = 0.6666666666666667E-1
+            leb_tmp, start = get_lebedev_recurrence_points(1, start, a, b, v, leb_tmp)
+            v = 0.7500000000000000E-1
+            leb_tmp, start = get_lebedev_recurrence_points(3, start, a, b, v, leb_tmp)
+
+        case 26:
+
+            v = 0.4761904761904762E-1
+            leb_tmp, start = get_lebedev_recurrence_points(1, start, a, b, v, leb_tmp)
+            v = 0.3809523809523810E-1
+            leb_tmp, start = get_lebedev_recurrence_points(2, start, a, b, v, leb_tmp)
+            v = 0.3214285714285714E-1
+            leb_tmp, start = get_lebedev_recurrence_points(3, start, a, b, v, leb_tmp)
+
+        case 38:
+
+            v = 0.9523809523809524E-2
+            leb_tmp, start = get_lebedev_recurrence_points(1, start, a, b, v, leb_tmp)
+            v = 0.3214285714285714E-1
+            leb_tmp, start = get_lebedev_recurrence_points(3, start, a, b, v, leb_tmp)
+            a = 0.4597008433809831E+0
+            v = 0.2857142857142857E-1
+            leb_tmp, start = get_lebedev_recurrence_points(5, start, a, b, v, leb_tmp)
+
+        case 50:
+
+            v = 0.1269841269841270E-1
+            leb_tmp, start = get_lebedev_recurrence_points(1, start, a, b, v, leb_tmp)
+            v = 0.2257495590828924E-1
+            leb_tmp, start = get_lebedev_recurrence_points(2, start, a, b, v, leb_tmp)
+            v = 0.2109375000000000E-1
+            leb_tmp, start = get_lebedev_recurrence_points(3, start, a, b, v, leb_tmp)
+            a = 0.3015113445777636E+0
+            v = 0.2017333553791887E-1
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+
+        case 74:
+
+            v = 0.5130671797338464E-3
+            leb_tmp, start = get_lebedev_recurrence_points(1, start, a, b, v, leb_tmp)
+            v = 0.1660406956574204E-1
+            leb_tmp, start = get_lebedev_recurrence_points(2, start, a, b, v, leb_tmp)
+            v = -0.2958603896103896E-1
+            leb_tmp, start = get_lebedev_recurrence_points(3, start, a, b, v, leb_tmp)
+            a = 0.4803844614152614E+0
+            v = 0.2657620708215946E-1
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.3207726489807764E+0
+            v = 0.1652217099371571E-1
+            leb_tmp, start = get_lebedev_recurrence_points(5, start, a, b, v, leb_tmp)
+
+        case 86:
+
+            v = 0.1154401154401154E-1
+            leb_tmp, start = get_lebedev_recurrence_points(1, start, a, b, v, leb_tmp)
+            v = 0.1194390908585628E-1
+            leb_tmp, start = get_lebedev_recurrence_points(3, start, a, b, v, leb_tmp)
+            a = 0.3696028464541502E+0
+            v = 0.1111055571060340E-1
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.6943540066026664E+0
+            v = 0.1187650129453714E-1
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.3742430390903412E+0
+            v = 0.1181230374690448E-1
+            leb_tmp, start = get_lebedev_recurrence_points(5, start, a, b, v, leb_tmp)
+
+        case 110:
+
+            v = 0.3828270494937162E-2
+            leb_tmp, start = get_lebedev_recurrence_points(1, start, a, b, v, leb_tmp)
+            v = 0.9793737512487512E-2
+            leb_tmp, start = get_lebedev_recurrence_points(3, start, a, b, v, leb_tmp)
+            a = 0.1851156353447362E+0
+            v = 0.8211737283191111E-2
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.6904210483822922E+0
+            v = 0.9942814891178103E-2
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.3956894730559419E+0
+            v = 0.9595471336070963E-2
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.4783690288121502E+0
+            v = 0.9694996361663028E-2
+            leb_tmp, start = get_lebedev_recurrence_points(5, start, a, b, v, leb_tmp)
+
+        case 146:
+
+            v = 0.5996313688621381E-3
+            leb_tmp, start = get_lebedev_recurrence_points(1, start, a, b, v, leb_tmp)
+            v = 0.7372999718620756E-2
+            leb_tmp, start = get_lebedev_recurrence_points(2, start, a, b, v, leb_tmp)
+            v = 0.7210515360144488E-2
+            leb_tmp, start = get_lebedev_recurrence_points(3, start, a, b, v, leb_tmp)
+            a = 0.6764410400114264E+0
+            v = 0.7116355493117555E-2
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.4174961227965453E+0
+            v = 0.6753829486314477E-2
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.1574676672039082E+0
+            v = 0.7574394159054034E-2
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.1403553811713183E+0
+            b = 0.4493328323269557E+0
+            v = 0.6991087353303262E-2
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+
+        case 170:
+
+            v = 0.5544842902037365E-2
+            leb_tmp, start = get_lebedev_recurrence_points(1, start, a, b, v, leb_tmp)
+            v = 0.6071332770670752E-2
+            leb_tmp, start = get_lebedev_recurrence_points(2, start, a, b, v, leb_tmp)
+            v = 0.6383674773515093E-2
+            leb_tmp, start = get_lebedev_recurrence_points(3, start, a, b, v, leb_tmp)
+            a = 0.2551252621114134E+0
+            v = 0.5183387587747790E-2
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.6743601460362766E+0
+            v = 0.6317929009813725E-2
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.4318910696719410E+0
+            v = 0.6201670006589077E-2
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.2613931360335988E+0
+            v = 0.5477143385137348E-2
+            leb_tmp, start = get_lebedev_recurrence_points(5, start, a, b, v, leb_tmp)
+            a = 0.4990453161796037E+0
+            b = 0.1446630744325115E+0
+            v = 0.5968383987681156E-2
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+
+        case 194:
+
+            v = 0.1782340447244611E-2
+            leb_tmp, start = get_lebedev_recurrence_points(1, start, a, b, v, leb_tmp)
+            v = 0.5716905949977102E-2
+            leb_tmp, start = get_lebedev_recurrence_points(2, start, a, b, v, leb_tmp)
+            v = 0.5573383178848738E-2
+            leb_tmp, start = get_lebedev_recurrence_points(3, start, a, b, v, leb_tmp)
+            a = 0.6712973442695226E+0
+            v = 0.5608704082587997E-2
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.2892465627575439E+0
+            v = 0.5158237711805383E-2
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.4446933178717437E+0
+            v = 0.5518771467273614E-2
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.1299335447650067E+0
+            v = 0.4106777028169394E-2
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.3457702197611283E+0
+            v = 0.5051846064614808E-2
+            leb_tmp, start = get_lebedev_recurrence_points(5, start, a, b, v, leb_tmp)
+            a = 0.1590417105383530E+0
+            b = 0.8360360154824589E+0
+            v = 0.5530248916233094E-2
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+
+        case 230:
+
+            v = -0.5522639919727325E-1
+            leb_tmp, start = get_lebedev_recurrence_points(1, start, a, b, v, leb_tmp)
+            v = 0.4450274607445226E-2
+            leb_tmp, start = get_lebedev_recurrence_points(3, start, a, b, v, leb_tmp)
+            a = 0.4492044687397611E+0
+            v = 0.4496841067921404E-2
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.2520419490210201E+0
+            v = 0.5049153450478750E-2
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.6981906658447242E+0
+            v = 0.3976408018051883E-2
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.6587405243460960E+0
+            v = 0.4401400650381014E-2
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.4038544050097660E-1
+            v = 0.1724544350544401E-1
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.5823842309715585E+0
+            v = 0.4231083095357343E-2
+            leb_tmp, start = get_lebedev_recurrence_points(5, start, a, b, v, leb_tmp)
+            a = 0.3545877390518688E+0
+            v = 0.5198069864064399E-2
+            leb_tmp, start = get_lebedev_recurrence_points(5, start, a, b, v, leb_tmp)
+            a = 0.2272181808998187E+0
+            b = 0.4864661535886647E+0
+            v = 0.4695720972568883E-2
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+
+        case 266:
+
+            v = -0.1313769127326952E-2
+            leb_tmp, start = get_lebedev_recurrence_points(1, start, a, b, v, leb_tmp)
+            v = -0.2522728704859336E-2
+            leb_tmp, start = get_lebedev_recurrence_points(2, start, a, b, v, leb_tmp)
+            v = 0.4186853881700583E-2
+            leb_tmp, start = get_lebedev_recurrence_points(3, start, a, b, v, leb_tmp)
+            a = 0.7039373391585475E+0
+            v = 0.5315167977810885E-2
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.1012526248572414E+0
+            v = 0.4047142377086219E-2
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.4647448726420539E+0
+            v = 0.4112482394406990E-2
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.3277420654971629E+0
+            v = 0.3595584899758782E-2
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.6620338663699974E+0
+            v = 0.4256131351428158E-2
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.8506508083520399E+0
+            v = 0.4229582700647240E-2
+            leb_tmp, start = get_lebedev_recurrence_points(5, start, a, b, v, leb_tmp)
+            a = 0.3233484542692899E+0
+            b = 0.1153112011009701E+0
+            v = 0.4080914225780505E-2
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.2314790158712601E+0
+            b = 0.5244939240922365E+0
+            v = 0.4071467593830964E-2
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+
+        case 302:
+
+            v = 0.8545911725128148E-3
+            leb_tmp, start = get_lebedev_recurrence_points(1, start, a, b, v, leb_tmp)
+            v = 0.3599119285025571E-2
+            leb_tmp, start = get_lebedev_recurrence_points(3, start, a, b, v, leb_tmp)
+            a = 0.3515640345570105E+0
+            v = 0.3449788424305883E-2
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.6566329410219612E+0
+            v = 0.3604822601419882E-2
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.4729054132581005E+0
+            v = 0.3576729661743367E-2
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.9618308522614784E-1
+            v = 0.2352101413689164E-2
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.2219645236294178E+0
+            v = 0.3108953122413675E-2
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.7011766416089545E+0
+            v = 0.3650045807677255E-2
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.2644152887060663E+0
+            v = 0.2982344963171804E-2
+            leb_tmp, start = get_lebedev_recurrence_points(5, start, a, b, v, leb_tmp)
+            a = 0.5718955891878961E+0
+            v = 0.3600820932216460E-2
+            leb_tmp, start = get_lebedev_recurrence_points(5, start, a, b, v, leb_tmp)
+            a = 0.2510034751770465E+0
+            b = 0.8000727494073952E+0
+            v = 0.3571540554273387E-2
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.1233548532583327E+0
+            b = 0.4127724083168531E+0
+            v = 0.3392312205006170E-2
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+
+        case 350:
+
+            v = 0.3006796749453936E-2
+            leb_tmp, start = get_lebedev_recurrence_points(1, start, a, b, v, leb_tmp)
+            v = 0.3050627745650771E-2
+            leb_tmp, start = get_lebedev_recurrence_points(3, start, a, b, v, leb_tmp)
+            a = 0.7068965463912316E+0
+            v = 0.1621104600288991E-2
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.4794682625712025E+0
+            v = 0.3005701484901752E-2
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.1927533154878019E+0
+            v = 0.2990992529653774E-2
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.6930357961327123E+0
+            v = 0.2982170644107595E-2
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.3608302115520091E+0
+            v = 0.2721564237310992E-2
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.6498486161496169E+0
+            v = 0.3033513795811141E-2
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.1932945013230339E+0
+            v = 0.3007949555218533E-2
+            leb_tmp, start = get_lebedev_recurrence_points(5, start, a, b, v, leb_tmp)
+            a = 0.3800494919899303E+0
+            v = 0.2881964603055307E-2
+            leb_tmp, start = get_lebedev_recurrence_points(5, start, a, b, v, leb_tmp)
+            a = 0.2899558825499574E+0
+            b = 0.7934537856582316E+0
+            v = 0.2958357626535696E-2
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.9684121455103957E-1
+            b = 0.8280801506686862E+0
+            v = 0.3036020026407088E-2
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.1833434647041659E+0
+            b = 0.9074658265305127E+0
+            v = 0.2832187403926303E-2
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+
+        case 434:
+
+            v = 0.5265897968224436E-3
+            leb_tmp, start = get_lebedev_recurrence_points(1, start, a, b, v, leb_tmp)
+            v = 0.2548219972002607E-2
+            leb_tmp, start = get_lebedev_recurrence_points(2, start, a, b, v, leb_tmp)
+            v = 0.2512317418927307E-2
+            leb_tmp, start = get_lebedev_recurrence_points(3, start, a, b, v, leb_tmp)
+            a = 0.6909346307509111E+0
+            v = 0.2530403801186355E-2
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.1774836054609158E+0
+            v = 0.2014279020918528E-2
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.4914342637784746E+0
+            v = 0.2501725168402936E-2
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.6456664707424256E+0
+            v = 0.2513267174597564E-2
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.2861289010307638E+0
+            v = 0.2302694782227416E-2
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.7568084367178018E-1
+            v = 0.1462495621594614E-2
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.3927259763368002E+0
+            v = 0.2445373437312980E-2
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.8818132877794288E+0
+            v = 0.2417442375638981E-2
+            leb_tmp, start = get_lebedev_recurrence_points(5, start, a, b, v, leb_tmp)
+            a = 0.9776428111182649E+0
+            v = 0.1910951282179532E-2
+            leb_tmp, start = get_lebedev_recurrence_points(5, start, a, b, v, leb_tmp)
+            a = 0.2054823696403044E+0
+            b = 0.8689460322872412E+0
+            v = 0.2416930044324775E-2
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5905157048925271E+0
+            b = 0.7999278543857286E+0
+            v = 0.2512236854563495E-2
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5550152361076807E+0
+            b = 0.7717462626915901E+0
+            v = 0.2496644054553086E-2
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.9371809858553722E+0
+            b = 0.3344363145343455E+0
+            v = 0.2236607760437849E-2
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+
+        case 590:
+
+            v = 0.3095121295306187E-3
+            leb_tmp, start = get_lebedev_recurrence_points(1, start, a, b, v, leb_tmp)
+            v = 0.1852379698597489E-2
+            leb_tmp, start = get_lebedev_recurrence_points(3, start, a, b, v, leb_tmp)
+            a = 0.7040954938227469E+0
+            v = 0.1871790639277744E-2
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.6807744066455243E+0
+            v = 0.1858812585438317E-2
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.6372546939258752E+0
+            v = 0.1852028828296213E-2
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.5044419707800358E+0
+            v = 0.1846715956151242E-2
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.4215761784010967E+0
+            v = 0.1818471778162769E-2
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.3317920736472123E+0
+            v = 0.1749564657281154E-2
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.2384736701421887E+0
+            v = 0.1617210647254411E-2
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.1459036449157763E+0
+            v = 0.1384737234851692E-2
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.6095034115507196E-1
+            v = 0.9764331165051050E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.6116843442009876E+0
+            v = 0.1857161196774078E-2
+            leb_tmp, start = get_lebedev_recurrence_points(5, start, a, b, v, leb_tmp)
+            a = 0.3964755348199858E+0
+            v = 0.1705153996395864E-2
+            leb_tmp, start = get_lebedev_recurrence_points(5, start, a, b, v, leb_tmp)
+            a = 0.1724782009907724E+0
+            v = 0.1300321685886048E-2
+            leb_tmp, start = get_lebedev_recurrence_points(5, start, a, b, v, leb_tmp)
+            a = 0.5610263808622060E+0
+            b = 0.3518280927733519E+0
+            v = 0.1842866472905286E-2
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4742392842551980E+0
+            b = 0.2634716655937950E+0
+            v = 0.1802658934377451E-2
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5984126497885380E+0
+            b = 0.1816640840360209E+0
+            v = 0.1849830560443660E-2
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.3791035407695563E+0
+            b = 0.1720795225656878E+0
+            v = 0.1713904507106709E-2
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.2778673190586244E+0
+            b = 0.8213021581932511E-1
+            v = 0.1555213603396808E-2
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5033564271075117E+0
+            b = 0.8999205842074875E-1
+            v = 0.1802239128008525E-2
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+
+        case 770:
+
+            v = 0.2192942088181184E-3
+            leb_tmp, start = get_lebedev_recurrence_points(1, start, a, b, v, leb_tmp)
+            v = 0.1436433617319080E-2
+            leb_tmp, start = get_lebedev_recurrence_points(2, start, a, b, v, leb_tmp)
+            v = 0.1421940344335877E-2
+            leb_tmp, start = get_lebedev_recurrence_points(3, start, a, b, v, leb_tmp)
+            a = 0.5087204410502360E-1
+            v = 0.6798123511050502E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.1228198790178831E+0
+            v = 0.9913184235294912E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.2026890814408786E+0
+            v = 0.1180207833238949E-2
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.2847745156464294E+0
+            v = 0.1296599602080921E-2
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.3656719078978026E+0
+            v = 0.1365871427428316E-2
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.4428264886713469E+0
+            v = 0.1402988604775325E-2
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.5140619627249735E+0
+            v = 0.1418645563595609E-2
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.6306401219166803E+0
+            v = 0.1421376741851662E-2
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.6716883332022612E+0
+            v = 0.1423996475490962E-2
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.6979792685336881E+0
+            v = 0.1431554042178567E-2
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.1446865674195309E+0
+            v = 0.9254401499865368E-3
+            leb_tmp, start = get_lebedev_recurrence_points(5, start, a, b, v, leb_tmp)
+            a = 0.3390263475411216E+0
+            v = 0.1250239995053509E-2
+            leb_tmp, start = get_lebedev_recurrence_points(5, start, a, b, v, leb_tmp)
+            a = 0.5335804651263506E+0
+            v = 0.1394365843329230E-2
+            leb_tmp, start = get_lebedev_recurrence_points(5, start, a, b, v, leb_tmp)
+            a = 0.6944024393349413E-1
+            b = 0.2355187894242326E+0
+            v = 0.1127089094671749E-2
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.2269004109529460E+0
+            b = 0.4102182474045730E+0
+            v = 0.1345753760910670E-2
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.8025574607775339E-1
+            b = 0.6214302417481605E+0
+            v = 0.1424957283316783E-2
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.1467999527896572E+0
+            b = 0.3245284345717394E+0
+            v = 0.1261523341237750E-2
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.1571507769824727E+0
+            b = 0.5224482189696630E+0
+            v = 0.1392547106052696E-2
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.2365702993157246E+0
+            b = 0.6017546634089558E+0
+            v = 0.1418761677877656E-2
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.7714815866765732E-1
+            b = 0.4346575516141163E+0
+            v = 0.1338366684479554E-2
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.3062936666210730E+0
+            b = 0.4908826589037616E+0
+            v = 0.1393700862676131E-2
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.3822477379524787E+0
+            b = 0.5648768149099500E+0
+            v = 0.1415914757466932E-2
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+
+        case 974:
+
+            v = 0.1438294190527431E-3
+            leb_tmp, start = get_lebedev_recurrence_points(1, start, a, b, v, leb_tmp)
+            v = 0.1125772288287004E-2
+            leb_tmp, start = get_lebedev_recurrence_points(3, start, a, b, v, leb_tmp)
+            a = 0.4292963545341347E-1
+            v = 0.4948029341949241E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.1051426854086404E+0
+            v = 0.7357990109125470E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.1750024867623087E+0
+            v = 0.8889132771304384E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.2477653379650257E+0
+            v = 0.9888347838921435E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.3206567123955957E+0
+            v = 0.1053299681709471E-2
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.3916520749849983E+0
+            v = 0.1092778807014578E-2
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.4590825874187624E+0
+            v = 0.1114389394063227E-2
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.5214563888415861E+0
+            v = 0.1123724788051555E-2
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.6253170244654199E+0
+            v = 0.1125239325243814E-2
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.6637926744523170E+0
+            v = 0.1126153271815905E-2
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.6910410398498301E+0
+            v = 0.1130286931123841E-2
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.7052907007457760E+0
+            v = 0.1134986534363955E-2
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.1236686762657990E+0
+            v = 0.6823367927109931E-3
+            leb_tmp, start = get_lebedev_recurrence_points(5, start, a, b, v, leb_tmp)
+            a = 0.2940777114468387E+0
+            v = 0.9454158160447096E-3
+            leb_tmp, start = get_lebedev_recurrence_points(5, start, a, b, v, leb_tmp)
+            a = 0.4697753849207649E+0
+            v = 0.1074429975385679E-2
+            leb_tmp, start = get_lebedev_recurrence_points(5, start, a, b, v, leb_tmp)
+            a = 0.6334563241139567E+0
+            v = 0.1129300086569132E-2
+            leb_tmp, start = get_lebedev_recurrence_points(5, start, a, b, v, leb_tmp)
+            a = 0.5974048614181342E-1
+            b = 0.2029128752777523E+0
+            v = 0.8436884500901954E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.1375760408473636E+0
+            b = 0.4602621942484054E+0
+            v = 0.1075255720448885E-2
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.3391016526336286E+0
+            b = 0.5030673999662036E+0
+            v = 0.1108577236864462E-2
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.1271675191439820E+0
+            b = 0.2817606422442134E+0
+            v = 0.9566475323783357E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.2693120740413512E+0
+            b = 0.4331561291720157E+0
+            v = 0.1080663250717391E-2
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.1419786452601918E+0
+            b = 0.6256167358580814E+0
+            v = 0.1126797131196295E-2
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.6709284600738255E-1
+            b = 0.3798395216859157E+0
+            v = 0.1022568715358061E-2
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.7057738183256172E-1
+            b = 0.5517505421423520E+0
+            v = 0.1108960267713108E-2
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.2783888477882155E+0
+            b = 0.6029619156159187E+0
+            v = 0.1122790653435766E-2
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.1979578938917407E+0
+            b = 0.3589606329589096E+0
+            v = 0.1032401847117460E-2
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.2087307061103274E+0
+            b = 0.5348666438135476E+0
+            v = 0.1107249382283854E-2
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4055122137872836E+0
+            b = 0.5674997546074373E+0
+            v = 0.1121780048519972E-2
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+
+        case 1202:
+
+            v = 0.1105189233267572E-3
+            leb_tmp, start = get_lebedev_recurrence_points(1, start, a, b, v, leb_tmp)
+            v = 0.9205232738090741E-3
+            leb_tmp, start = get_lebedev_recurrence_points(2, start, a, b, v, leb_tmp)
+            v = 0.9133159786443561E-3
+            leb_tmp, start = get_lebedev_recurrence_points(3, start, a, b, v, leb_tmp)
+            a = 0.3712636449657089E-1
+            v = 0.3690421898017899E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.9140060412262223E-1
+            v = 0.5603990928680660E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.1531077852469906E+0
+            v = 0.6865297629282609E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.2180928891660612E+0
+            v = 0.7720338551145630E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.2839874532200175E+0
+            v = 0.8301545958894795E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.3491177600963764E+0
+            v = 0.8686692550179628E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.4121431461444309E+0
+            v = 0.8927076285846890E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.4718993627149127E+0
+            v = 0.9060820238568219E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.5273145452842337E+0
+            v = 0.9119777254940867E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.6209475332444019E+0
+            v = 0.9128720138604181E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.6569722711857291E+0
+            v = 0.9130714935691735E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.6841788309070143E+0
+            v = 0.9152873784554116E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.7012604330123631E+0
+            v = 0.9187436274321654E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.1072382215478166E+0
+            v = 0.5176977312965694E-3
+            leb_tmp, start = get_lebedev_recurrence_points(5, start, a, b, v, leb_tmp)
+            a = 0.2582068959496968E+0
+            v = 0.7331143682101417E-3
+            leb_tmp, start = get_lebedev_recurrence_points(5, start, a, b, v, leb_tmp)
+            a = 0.4172752955306717E+0
+            v = 0.8463232836379928E-3
+            leb_tmp, start = get_lebedev_recurrence_points(5, start, a, b, v, leb_tmp)
+            a = 0.5700366911792503E+0
+            v = 0.9031122694253992E-3
+            leb_tmp, start = get_lebedev_recurrence_points(5, start, a, b, v, leb_tmp)
+            a = 0.9827986018263947E+0
+            b = 0.1771774022615325E+0
+            v = 0.6485778453163257E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.9624249230326228E+0
+            b = 0.2475716463426288E+0
+            v = 0.7435030910982369E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.9402007994128811E+0
+            b = 0.3354616289066489E+0
+            v = 0.7998527891839054E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.9320822040143202E+0
+            b = 0.3173615246611977E+0
+            v = 0.8101731497468018E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.9043674199393299E+0
+            b = 0.4090268427085357E+0
+            v = 0.8483389574594331E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.8912407560074747E+0
+            b = 0.3854291150669224E+0
+            v = 0.8556299257311812E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.8676435628462708E+0
+            b = 0.4932221184851285E+0
+            v = 0.8803208679738260E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.8581979986041619E+0
+            b = 0.4785320675922435E+0
+            v = 0.8811048182425720E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.8396753624049856E+0
+            b = 0.4507422593157064E+0
+            v = 0.8850282341265444E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.8165288564022188E+0
+            b = 0.5632123020762100E+0
+            v = 0.9021342299040653E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.8015469370783529E+0
+            b = 0.5434303569693900E+0
+            v = 0.9010091677105086E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.7773563069070351E+0
+            b = 0.5123518486419871E+0
+            v = 0.9022692938426915E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.7661621213900394E+0
+            b = 0.6394279634749102E+0
+            v = 0.9158016174693465E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.7553584143533510E+0
+            b = 0.6269805509024392E+0
+            v = 0.9131578003189435E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.7344305757559503E+0
+            b = 0.6031161693096310E+0
+            v = 0.9107813579482705E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.7043837184021765E+0
+            b = 0.5693702498468441E+0
+            v = 0.9105760258970126E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+
+        case 1454:
+
+            v = 0.7777160743261247E-4
+            leb_tmp, start = get_lebedev_recurrence_points(1, start, a, b, v, leb_tmp)
+            v = 0.7557646413004701E-3
+            leb_tmp, start = get_lebedev_recurrence_points(3, start, a, b, v, leb_tmp)
+            a = 0.3229290663413854E-1
+            v = 0.2841633806090617E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.8036733271462222E-1
+            v = 0.4374419127053555E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.1354289960531653E+0
+            v = 0.5417174740872172E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.1938963861114426E+0
+            v = 0.6148000891358593E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.2537343715011275E+0
+            v = 0.6664394485800705E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.3135251434752570E+0
+            v = 0.7025039356923220E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.3721558339375338E+0
+            v = 0.7268511789249627E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.4286809575195696E+0
+            v = 0.7422637534208629E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.4822510128282994E+0
+            v = 0.7509545035841214E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.5320679333566263E+0
+            v = 0.7548535057718401E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.6172998195394274E+0
+            v = 0.7554088969774001E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.6510679849127481E+0
+            v = 0.7553147174442808E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.6777315251687360E+0
+            v = 0.7564767653292297E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.6963109410648741E+0
+            v = 0.7587991808518730E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.7058935009831749E+0
+            v = 0.7608261832033027E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.9955546194091857E+0
+            v = 0.4021680447874916E-3
+            leb_tmp, start = get_lebedev_recurrence_points(5, start, a, b, v, leb_tmp)
+            a = 0.9734115901794209E+0
+            v = 0.5804871793945964E-3
+            leb_tmp, start = get_lebedev_recurrence_points(5, start, a, b, v, leb_tmp)
+            a = 0.9275693732388626E+0
+            v = 0.6792151955945159E-3
+            leb_tmp, start = get_lebedev_recurrence_points(5, start, a, b, v, leb_tmp)
+            a = 0.8568022422795103E+0
+            v = 0.7336741211286294E-3
+            leb_tmp, start = get_lebedev_recurrence_points(5, start, a, b, v, leb_tmp)
+            a = 0.7623495553719372E+0
+            v = 0.7581866300989608E-3
+            leb_tmp, start = get_lebedev_recurrence_points(5, start, a, b, v, leb_tmp)
+            a = 0.5707522908892223E+0
+            b = 0.4387028039889501E+0
+            v = 0.7538257859800743E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5196463388403083E+0
+            b = 0.3858908414762617E+0
+            v = 0.7483517247053123E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4646337531215351E+0
+            b = 0.3301937372343854E+0
+            v = 0.7371763661112059E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4063901697557691E+0
+            b = 0.2725423573563777E+0
+            v = 0.7183448895756934E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.3456329466643087E+0
+            b = 0.2139510237495250E+0
+            v = 0.6895815529822191E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.2831395121050332E+0
+            b = 0.1555922309786647E+0
+            v = 0.6480105801792886E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.2197682022925330E+0
+            b = 0.9892878979686097E-1
+            v = 0.5897558896594636E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.1564696098650355E+0
+            b = 0.4598642910675510E-1
+            v = 0.5095708849247346E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.6027356673721295E+0
+            b = 0.3376625140173426E+0
+            v = 0.7536906428909755E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5496032320255096E+0
+            b = 0.2822301309727988E+0
+            v = 0.7472505965575118E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4921707755234567E+0
+            b = 0.2248632342592540E+0
+            v = 0.7343017132279698E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4309422998598483E+0
+            b = 0.1666224723456479E+0
+            v = 0.7130871582177445E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.3664108182313672E+0
+            b = 0.1086964901822169E+0
+            v = 0.6817022032112776E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.2990189057758436E+0
+            b = 0.5251989784120085E-1
+            v = 0.6380941145604121E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.6268724013144998E+0
+            b = 0.2297523657550023E+0
+            v = 0.7550381377920310E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5707324144834607E+0
+            b = 0.1723080607093800E+0
+            v = 0.7478646640144802E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5096360901960365E+0
+            b = 0.1140238465390513E+0
+            v = 0.7335918720601220E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4438729938312456E+0
+            b = 0.5611522095882537E-1
+            v = 0.7110120527658118E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.6419978471082389E+0
+            b = 0.1164174423140873E+0
+            v = 0.7571363978689501E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5817218061802611E+0
+            b = 0.5797589531445219E-1
+            v = 0.7489908329079234E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+
+        case 1730:
+
+            v = 0.6309049437420976E-4
+            leb_tmp, start = get_lebedev_recurrence_points(1, start, a, b, v, leb_tmp)
+            v = 0.6398287705571748E-3
+            leb_tmp, start = get_lebedev_recurrence_points(2, start, a, b, v, leb_tmp)
+            v = 0.6357185073530720E-3
+            leb_tmp, start = get_lebedev_recurrence_points(3, start, a, b, v, leb_tmp)
+            a = 0.2860923126194662E-1
+            v = 0.2221207162188168E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.7142556767711522E-1
+            v = 0.3475784022286848E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.1209199540995559E+0
+            v = 0.4350742443589804E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.1738673106594379E+0
+            v = 0.4978569136522127E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.2284645438467734E+0
+            v = 0.5435036221998053E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.2834807671701512E+0
+            v = 0.5765913388219542E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.3379680145467339E+0
+            v = 0.6001200359226003E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.3911355454819537E+0
+            v = 0.6162178172717512E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.4422860353001403E+0
+            v = 0.6265218152438485E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.4907781568726057E+0
+            v = 0.6323987160974212E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.5360006153211468E+0
+            v = 0.6350767851540569E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.6142105973596603E+0
+            v = 0.6354362775297107E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.6459300387977504E+0
+            v = 0.6352302462706235E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.6718056125089225E+0
+            v = 0.6358117881417972E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.6910888533186254E+0
+            v = 0.6373101590310117E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.7030467416823252E+0
+            v = 0.6390428961368665E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.8354951166354646E-1
+            v = 0.3186913449946576E-3
+            leb_tmp, start = get_lebedev_recurrence_points(5, start, a, b, v, leb_tmp)
+            a = 0.2050143009099486E+0
+            v = 0.4678028558591711E-3
+            leb_tmp, start = get_lebedev_recurrence_points(5, start, a, b, v, leb_tmp)
+            a = 0.3370208290706637E+0
+            v = 0.5538829697598626E-3
+            leb_tmp, start = get_lebedev_recurrence_points(5, start, a, b, v, leb_tmp)
+            a = 0.4689051484233963E+0
+            v = 0.6044475907190476E-3
+            leb_tmp, start = get_lebedev_recurrence_points(5, start, a, b, v, leb_tmp)
+            a = 0.5939400424557334E+0
+            v = 0.6313575103509012E-3
+            leb_tmp, start = get_lebedev_recurrence_points(5, start, a, b, v, leb_tmp)
+            a = 0.1394983311832261E+0
+            b = 0.4097581162050343E-1
+            v = 0.4078626431855630E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.1967999180485014E+0
+            b = 0.8851987391293348E-1
+            v = 0.4759933057812725E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.2546183732548967E+0
+            b = 0.1397680182969819E+0
+            v = 0.5268151186413440E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.3121281074713875E+0
+            b = 0.1929452542226526E+0
+            v = 0.5643048560507316E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.3685981078502492E+0
+            b = 0.2467898337061562E+0
+            v = 0.5914501076613073E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4233760321547856E+0
+            b = 0.3003104124785409E+0
+            v = 0.6104561257874195E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4758671236059246E+0
+            b = 0.3526684328175033E+0
+            v = 0.6230252860707806E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5255178579796463E+0
+            b = 0.4031134861145713E+0
+            v = 0.6305618761760796E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5718025633734589E+0
+            b = 0.4509426448342351E+0
+            v = 0.6343092767597889E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.2686927772723415E+0
+            b = 0.4711322502423248E-1
+            v = 0.5176268945737826E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.3306006819904809E+0
+            b = 0.9784487303942695E-1
+            v = 0.5564840313313692E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.3904906850594983E+0
+            b = 0.1505395810025273E+0
+            v = 0.5856426671038980E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4479957951904390E+0
+            b = 0.2039728156296050E+0
+            v = 0.6066386925777091E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5027076848919780E+0
+            b = 0.2571529941121107E+0
+            v = 0.6208824962234458E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5542087392260217E+0
+            b = 0.3092191375815670E+0
+            v = 0.6296314297822907E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.6020850887375187E+0
+            b = 0.3593807506130276E+0
+            v = 0.6340423756791859E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4019851409179594E+0
+            b = 0.5063389934378671E-1
+            v = 0.5829627677107342E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4635614567449800E+0
+            b = 0.1032422269160612E+0
+            v = 0.6048693376081110E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5215860931591575E+0
+            b = 0.1566322094006254E+0
+            v = 0.6202362317732461E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5758202499099271E+0
+            b = 0.2098082827491099E+0
+            v = 0.6299005328403779E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.6259893683876795E+0
+            b = 0.2618824114553391E+0
+            v = 0.6347722390609353E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5313795124811891E+0
+            b = 0.5263245019338556E-1
+            v = 0.6203778981238834E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5893317955931995E+0
+            b = 0.1061059730982005E+0
+            v = 0.6308414671239979E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.6426246321215801E+0
+            b = 0.1594171564034221E+0
+            v = 0.6362706466959498E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.6511904367376113E+0
+            b = 0.5354789536565540E-1
+            v = 0.6375414170333233E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+
+        case 2030:
+
+            v = 0.4656031899197431E-4
+            leb_tmp, start = get_lebedev_recurrence_points(1, start, a, b, v, leb_tmp)
+            v = 0.5421549195295507E-3
+            leb_tmp, start = get_lebedev_recurrence_points(3, start, a, b, v, leb_tmp)
+            a = 0.2540835336814348E-1
+            v = 0.1778522133346553E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.6399322800504915E-1
+            v = 0.2811325405682796E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.1088269469804125E+0
+            v = 0.3548896312631459E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.1570670798818287E+0
+            v = 0.4090310897173364E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.2071163932282514E+0
+            v = 0.4493286134169965E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.2578914044450844E+0
+            v = 0.4793728447962723E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.3085687558169623E+0
+            v = 0.5015415319164265E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.3584719706267024E+0
+            v = 0.5175127372677937E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.4070135594428709E+0
+            v = 0.5285522262081019E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.4536618626222638E+0
+            v = 0.5356832703713962E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.4979195686463577E+0
+            v = 0.5397914736175170E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.5393075111126999E+0
+            v = 0.5416899441599930E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.6115617676843916E+0
+            v = 0.5419308476889938E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.6414308435160159E+0
+            v = 0.5416936902030596E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.6664099412721607E+0
+            v = 0.5419544338703164E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.6859161771214913E+0
+            v = 0.5428983656630975E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.6993625593503890E+0
+            v = 0.5442286500098193E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.7062393387719380E+0
+            v = 0.5452250345057301E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.7479028168349763E-1
+            v = 0.2568002497728530E-3
+            leb_tmp, start = get_lebedev_recurrence_points(5, start, a, b, v, leb_tmp)
+            a = 0.1848951153969366E+0
+            v = 0.3827211700292145E-3
+            leb_tmp, start = get_lebedev_recurrence_points(5, start, a, b, v, leb_tmp)
+            a = 0.3059529066581305E+0
+            v = 0.4579491561917824E-3
+            leb_tmp, start = get_lebedev_recurrence_points(5, start, a, b, v, leb_tmp)
+            a = 0.4285556101021362E+0
+            v = 0.5042003969083574E-3
+            leb_tmp, start = get_lebedev_recurrence_points(5, start, a, b, v, leb_tmp)
+            a = 0.5468758653496526E+0
+            v = 0.5312708889976025E-3
+            leb_tmp, start = get_lebedev_recurrence_points(5, start, a, b, v, leb_tmp)
+            a = 0.6565821978343439E+0
+            v = 0.5438401790747117E-3
+            leb_tmp, start = get_lebedev_recurrence_points(5, start, a, b, v, leb_tmp)
+            a = 0.1253901572367117E+0
+            b = 0.3681917226439641E-1
+            v = 0.3316041873197344E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.1775721510383941E+0
+            b = 0.7982487607213301E-1
+            v = 0.3899113567153771E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.2305693358216114E+0
+            b = 0.1264640966592335E+0
+            v = 0.4343343327201309E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.2836502845992063E+0
+            b = 0.1751585683418957E+0
+            v = 0.4679415262318919E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.3361794746232590E+0
+            b = 0.2247995907632670E+0
+            v = 0.4930847981631031E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.3875979172264824E+0
+            b = 0.2745299257422246E+0
+            v = 0.5115031867540091E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4374019316999074E+0
+            b = 0.3236373482441118E+0
+            v = 0.5245217148457367E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4851275843340022E+0
+            b = 0.3714967859436741E+0
+            v = 0.5332041499895321E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5303391803806868E+0
+            b = 0.4175353646321745E+0
+            v = 0.5384583126021542E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5726197380596287E+0
+            b = 0.4612084406355461E+0
+            v = 0.5411067210798852E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.2431520732564863E+0
+            b = 0.4258040133043952E-1
+            v = 0.4259797391468714E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.3002096800895869E+0
+            b = 0.8869424306722721E-1
+            v = 0.4604931368460021E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.3558554457457432E+0
+            b = 0.1368811706510655E+0
+            v = 0.4871814878255202E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4097782537048887E+0
+            b = 0.1860739985015033E+0
+            v = 0.5072242910074885E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4616337666067458E+0
+            b = 0.2354235077395853E+0
+            v = 0.5217069845235350E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5110707008417874E+0
+            b = 0.2842074921347011E+0
+            v = 0.5315785966280310E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5577415286163795E+0
+            b = 0.3317784414984102E+0
+            v = 0.5376833708758905E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.6013060431366950E+0
+            b = 0.3775299002040700E+0
+            v = 0.5408032092069521E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.3661596767261781E+0
+            b = 0.4599367887164592E-1
+            v = 0.4842744917904866E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4237633153506581E+0
+            b = 0.9404893773654421E-1
+            v = 0.5048926076188130E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4786328454658452E+0
+            b = 0.1431377109091971E+0
+            v = 0.5202607980478373E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5305702076789774E+0
+            b = 0.1924186388843570E+0
+            v = 0.5309932388325743E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5793436224231788E+0
+            b = 0.2411590944775190E+0
+            v = 0.5377419770895208E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.6247069017094747E+0
+            b = 0.2886871491583605E+0
+            v = 0.5411696331677717E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4874315552535204E+0
+            b = 0.4804978774953206E-1
+            v = 0.5197996293282420E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5427337322059053E+0
+            b = 0.9716857199366665E-1
+            v = 0.5311120836622945E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5943493747246700E+0
+            b = 0.1465205839795055E+0
+            v = 0.5384309319956951E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.6421314033564943E+0
+            b = 0.1953579449803574E+0
+            v = 0.5421859504051886E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.6020628374713980E+0
+            b = 0.4916375015738108E-1
+            v = 0.5390948355046314E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.6529222529856881E+0
+            b = 0.9861621540127005E-1
+            v = 0.5433312705027845E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+
+        case 2354:
+
+            v = 0.3922616270665292E-4
+            leb_tmp, start = get_lebedev_recurrence_points(1, start, a, b, v, leb_tmp)
+            v = 0.4703831750854424E-3
+            leb_tmp, start = get_lebedev_recurrence_points(2, start, a, b, v, leb_tmp)
+            v = 0.4678202801282136E-3
+            leb_tmp, start = get_lebedev_recurrence_points(3, start, a, b, v, leb_tmp)
+            a = 0.2290024646530589E-1
+            v = 0.1437832228979900E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.5779086652271284E-1
+            v = 0.2303572493577644E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.9863103576375984E-1
+            v = 0.2933110752447454E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.1428155792982185E+0
+            v = 0.3402905998359838E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.1888978116601463E+0
+            v = 0.3759138466870372E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.2359091682970210E+0
+            v = 0.4030638447899798E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.2831228833706171E+0
+            v = 0.4236591432242211E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.3299495857966693E+0
+            v = 0.4390522656946746E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.3758840802660796E+0
+            v = 0.4502523466626247E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.4204751831009480E+0
+            v = 0.4580577727783541E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.4633068518751051E+0
+            v = 0.4631391616615899E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.5039849474507313E+0
+            v = 0.4660928953698676E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.5421265793440747E+0
+            v = 0.4674751807936953E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.6092660230557310E+0
+            v = 0.4676414903932920E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.6374654204984869E+0
+            v = 0.4674086492347870E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.6615136472609892E+0
+            v = 0.4674928539483207E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.6809487285958127E+0
+            v = 0.4680748979686447E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.6952980021665196E+0
+            v = 0.4690449806389040E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.7041245497695400E+0
+            v = 0.4699877075860818E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.6744033088306065E-1
+            v = 0.2099942281069176E-3
+            leb_tmp, start = get_lebedev_recurrence_points(5, start, a, b, v, leb_tmp)
+            a = 0.1678684485334166E+0
+            v = 0.3172269150712804E-3
+            leb_tmp, start = get_lebedev_recurrence_points(5, start, a, b, v, leb_tmp)
+            a = 0.2793559049539613E+0
+            v = 0.3832051358546523E-3
+            leb_tmp, start = get_lebedev_recurrence_points(5, start, a, b, v, leb_tmp)
+            a = 0.3935264218057639E+0
+            v = 0.4252193818146985E-3
+            leb_tmp, start = get_lebedev_recurrence_points(5, start, a, b, v, leb_tmp)
+            a = 0.5052629268232558E+0
+            v = 0.4513807963755000E-3
+            leb_tmp, start = get_lebedev_recurrence_points(5, start, a, b, v, leb_tmp)
+            a = 0.6107905315437531E+0
+            v = 0.4657797469114178E-3
+            leb_tmp, start = get_lebedev_recurrence_points(5, start, a, b, v, leb_tmp)
+            a = 0.1135081039843524E+0
+            b = 0.3331954884662588E-1
+            v = 0.2733362800522836E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.1612866626099378E+0
+            b = 0.7247167465436538E-1
+            v = 0.3235485368463559E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.2100786550168205E+0
+            b = 0.1151539110849745E+0
+            v = 0.3624908726013453E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.2592282009459942E+0
+            b = 0.1599491097143677E+0
+            v = 0.3925540070712828E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.3081740561320203E+0
+            b = 0.2058699956028027E+0
+            v = 0.4156129781116235E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.3564289781578164E+0
+            b = 0.2521624953502911E+0
+            v = 0.4330644984623263E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4035587288240703E+0
+            b = 0.2982090785797674E+0
+            v = 0.4459677725921312E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4491671196373903E+0
+            b = 0.3434762087235733E+0
+            v = 0.4551593004456795E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4928854782917489E+0
+            b = 0.3874831357203437E+0
+            v = 0.4613341462749918E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5343646791958988E+0
+            b = 0.4297814821746926E+0
+            v = 0.4651019618269806E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5732683216530990E+0
+            b = 0.4699402260943537E+0
+            v = 0.4670249536100625E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.2214131583218986E+0
+            b = 0.3873602040643895E-1
+            v = 0.3549555576441708E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.2741796504750071E+0
+            b = 0.8089496256902013E-1
+            v = 0.3856108245249010E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.3259797439149485E+0
+            b = 0.1251732177620872E+0
+            v = 0.4098622845756882E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.3765441148826891E+0
+            b = 0.1706260286403185E+0
+            v = 0.4286328604268950E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4255773574530558E+0
+            b = 0.2165115147300408E+0
+            v = 0.4427802198993945E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4727795117058430E+0
+            b = 0.2622089812225259E+0
+            v = 0.4530473511488561E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5178546895819012E+0
+            b = 0.3071721431296201E+0
+            v = 0.4600805475703138E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5605141192097460E+0
+            b = 0.3508998998801138E+0
+            v = 0.4644599059958017E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.6004763319352512E+0
+            b = 0.3929160876166931E+0
+            v = 0.4667274455712508E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.3352842634946949E+0
+            b = 0.4202563457288019E-1
+            v = 0.4069360518020356E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.3891971629814670E+0
+            b = 0.8614309758870850E-1
+            v = 0.4260442819919195E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4409875565542281E+0
+            b = 0.1314500879380001E+0
+            v = 0.4408678508029063E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4904893058592484E+0
+            b = 0.1772189657383859E+0
+            v = 0.4518748115548597E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5375056138769549E+0
+            b = 0.2228277110050294E+0
+            v = 0.4595564875375116E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5818255708669969E+0
+            b = 0.2677179935014386E+0
+            v = 0.4643988774315846E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.6232334858144959E+0
+            b = 0.3113675035544165E+0
+            v = 0.4668827491646946E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4489485354492058E+0
+            b = 0.4409162378368174E-1
+            v = 0.4400541823741973E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5015136875933150E+0
+            b = 0.8939009917748489E-1
+            v = 0.4514512890193797E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5511300550512623E+0
+            b = 0.1351806029383365E+0
+            v = 0.4596198627347549E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5976720409858000E+0
+            b = 0.1808370355053196E+0
+            v = 0.4648659016801781E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.6409956378989354E+0
+            b = 0.2257852192301602E+0
+            v = 0.4675502017157673E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5581222330827514E+0
+            b = 0.4532173421637160E-1
+            v = 0.4598494476455523E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.6074705984161695E+0
+            b = 0.9117488031840314E-1
+            v = 0.4654916955152048E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.6532272537379033E+0
+            b = 0.1369294213140155E+0
+            v = 0.4684709779505137E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.6594761494500487E+0
+            b = 0.4589901487275583E-1
+            v = 0.4691445539106986E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+
+        case 2702:
+
+            v = 0.2998675149888161E-4
+            leb_tmp, start = get_lebedev_recurrence_points(1, start, a, b, v, leb_tmp)
+            v = 0.4077860529495355E-3
+            leb_tmp, start = get_lebedev_recurrence_points(3, start, a, b, v, leb_tmp)
+            a = 0.2065562538818703E-1
+            v = 0.1185349192520667E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.5250918173022379E-1
+            v = 0.1913408643425751E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.8993480082038376E-1
+            v = 0.2452886577209897E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.1306023924436019E+0
+            v = 0.2862408183288702E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.1732060388531418E+0
+            v = 0.3178032258257357E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.2168727084820249E+0
+            v = 0.3422945667633690E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.2609528309173586E+0
+            v = 0.3612790520235922E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.3049252927938952E+0
+            v = 0.3758638229818521E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.3483484138084404E+0
+            v = 0.3868711798859953E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.3908321549106406E+0
+            v = 0.3949429933189938E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.4320210071894814E+0
+            v = 0.4006068107541156E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.4715824795890053E+0
+            v = 0.4043192149672723E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.5091984794078453E+0
+            v = 0.4064947495808078E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.5445580145650803E+0
+            v = 0.4075245619813152E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.6072575796841768E+0
+            v = 0.4076423540893566E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.6339484505755803E+0
+            v = 0.4074280862251555E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.6570718257486958E+0
+            v = 0.4074163756012244E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.6762557330090709E+0
+            v = 0.4077647795071246E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.6911161696923790E+0
+            v = 0.4084517552782530E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.7012841911659961E+0
+            v = 0.4092468459224052E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.7064559272410020E+0
+            v = 0.4097872687240906E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.6123554989894765E-1
+            v = 0.1738986811745028E-3
+            leb_tmp, start = get_lebedev_recurrence_points(5, start, a, b, v, leb_tmp)
+            a = 0.1533070348312393E+0
+            v = 0.2659616045280191E-3
+            leb_tmp, start = get_lebedev_recurrence_points(5, start, a, b, v, leb_tmp)
+            a = 0.2563902605244206E+0
+            v = 0.3240596008171533E-3
+            leb_tmp, start = get_lebedev_recurrence_points(5, start, a, b, v, leb_tmp)
+            a = 0.3629346991663361E+0
+            v = 0.3621195964432943E-3
+            leb_tmp, start = get_lebedev_recurrence_points(5, start, a, b, v, leb_tmp)
+            a = 0.4683949968987538E+0
+            v = 0.3868838330760539E-3
+            leb_tmp, start = get_lebedev_recurrence_points(5, start, a, b, v, leb_tmp)
+            a = 0.5694479240657952E+0
+            v = 0.4018911532693111E-3
+            leb_tmp, start = get_lebedev_recurrence_points(5, start, a, b, v, leb_tmp)
+            a = 0.6634465430993955E+0
+            v = 0.4089929432983252E-3
+            leb_tmp, start = get_lebedev_recurrence_points(5, start, a, b, v, leb_tmp)
+            a = 0.1033958573552305E+0
+            b = 0.3034544009063584E-1
+            v = 0.2279907527706409E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.1473521412414395E+0
+            b = 0.6618803044247135E-1
+            v = 0.2715205490578897E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.1924552158705967E+0
+            b = 0.1054431128987715E+0
+            v = 0.3057917896703976E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.2381094362890328E+0
+            b = 0.1468263551238858E+0
+            v = 0.3326913052452555E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.2838121707936760E+0
+            b = 0.1894486108187886E+0
+            v = 0.3537334711890037E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.3291323133373415E+0
+            b = 0.2326374238761579E+0
+            v = 0.3700567500783129E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.3736896978741460E+0
+            b = 0.2758485808485768E+0
+            v = 0.3825245372589122E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4171406040760013E+0
+            b = 0.3186179331996921E+0
+            v = 0.3918125171518296E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4591677985256915E+0
+            b = 0.3605329796303794E+0
+            v = 0.3984720419937579E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4994733831718418E+0
+            b = 0.4012147253586509E+0
+            v = 0.4029746003338211E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5377731830445096E+0
+            b = 0.4403050025570692E+0
+            v = 0.4057428632156627E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5737917830001331E+0
+            b = 0.4774565904277483E+0
+            v = 0.4071719274114857E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.2027323586271389E+0
+            b = 0.3544122504976147E-1
+            v = 0.2990236950664119E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.2516942375187273E+0
+            b = 0.7418304388646328E-1
+            v = 0.3262951734212878E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.3000227995257181E+0
+            b = 0.1150502745727186E+0
+            v = 0.3482634608242413E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.3474806691046342E+0
+            b = 0.1571963371209364E+0
+            v = 0.3656596681700892E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.3938103180359209E+0
+            b = 0.1999631877247100E+0
+            v = 0.3791740467794218E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4387519590455703E+0
+            b = 0.2428073457846535E+0
+            v = 0.3894034450156905E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4820503960077787E+0
+            b = 0.2852575132906155E+0
+            v = 0.3968600245508371E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5234573778475101E+0
+            b = 0.3268884208674639E+0
+            v = 0.4019931351420050E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5627318647235282E+0
+            b = 0.3673033321675939E+0
+            v = 0.4052108801278599E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5996390607156954E+0
+            b = 0.4061211551830290E+0
+            v = 0.4068978613940934E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.3084780753791947E+0
+            b = 0.3860125523100059E-1
+            v = 0.3454275351319704E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.3589988275920223E+0
+            b = 0.7928938987104867E-1
+            v = 0.3629963537007920E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4078628415881973E+0
+            b = 0.1212614643030087E+0
+            v = 0.3770187233889873E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4549287258889735E+0
+            b = 0.1638770827382693E+0
+            v = 0.3878608613694378E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5000278512957279E+0
+            b = 0.2065965798260176E+0
+            v = 0.3959065270221274E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5429785044928199E+0
+            b = 0.2489436378852235E+0
+            v = 0.4015286975463570E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5835939850491711E+0
+            b = 0.2904811368946891E+0
+            v = 0.4050866785614717E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.6216870353444856E+0
+            b = 0.3307941957666609E+0
+            v = 0.4069320185051913E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4151104662709091E+0
+            b = 0.4064829146052554E-1
+            v = 0.3760120964062763E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4649804275009218E+0
+            b = 0.8258424547294755E-1
+            v = 0.3870969564418064E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5124695757009662E+0
+            b = 0.1251841962027289E+0
+            v = 0.3955287790534055E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5574711100606224E+0
+            b = 0.1679107505976331E+0
+            v = 0.4015361911302668E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5998597333287227E+0
+            b = 0.2102805057358715E+0
+            v = 0.4053836986719548E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.6395007148516600E+0
+            b = 0.2518418087774107E+0
+            v = 0.4073578673299117E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5188456224746252E+0
+            b = 0.4194321676077518E-1
+            v = 0.3954628379231406E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5664190707942778E+0
+            b = 0.8457661551921499E-1
+            v = 0.4017645508847530E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.6110464353283153E+0
+            b = 0.1273652932519396E+0
+            v = 0.4059030348651293E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.6526430302051563E+0
+            b = 0.1698173239076354E+0
+            v = 0.4080565809484880E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.6167551880377548E+0
+            b = 0.4266398851548864E-1
+            v = 0.4063018753664651E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.6607195418355383E+0
+            b = 0.8551925814238349E-1
+            v = 0.4087191292799671E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+
+        case 3074:
+
+            v = 0.2599095953754734E-4
+            leb_tmp, start = get_lebedev_recurrence_points(1, start, a, b, v, leb_tmp)
+            v = 0.3603134089687541E-3
+            leb_tmp, start = get_lebedev_recurrence_points(2, start, a, b, v, leb_tmp)
+            v = 0.3586067974412447E-3
+            leb_tmp, start = get_lebedev_recurrence_points(3, start, a, b, v, leb_tmp)
+            a = 0.1886108518723392E-1
+            v = 0.9831528474385880E-4
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.4800217244625303E-1
+            v = 0.1605023107954450E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.8244922058397242E-1
+            v = 0.2072200131464099E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.1200408362484023E+0
+            v = 0.2431297618814187E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.1595773530809965E+0
+            v = 0.2711819064496707E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.2002635973434064E+0
+            v = 0.2932762038321116E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.2415127590139982E+0
+            v = 0.3107032514197368E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.2828584158458477E+0
+            v = 0.3243808058921213E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.3239091015338138E+0
+            v = 0.3349899091374030E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.3643225097962194E+0
+            v = 0.3430580688505218E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.4037897083691802E+0
+            v = 0.3490124109290343E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.4420247515194127E+0
+            v = 0.3532148948561955E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.4787572538464938E+0
+            v = 0.3559862669062833E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.5137265251275234E+0
+            v = 0.3576224317551411E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.5466764056654611E+0
+            v = 0.3584050533086076E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.6054859420813535E+0
+            v = 0.3584903581373224E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.6308106701764562E+0
+            v = 0.3582991879040586E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.6530369230179584E+0
+            v = 0.3582371187963125E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.6718609524611158E+0
+            v = 0.3584353631122350E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.6869676499894013E+0
+            v = 0.3589120166517785E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.6980467077240748E+0
+            v = 0.3595445704531601E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.7048241721250522E+0
+            v = 0.3600943557111074E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.5591105222058232E-1
+            v = 0.1456447096742039E-3
+            leb_tmp, start = get_lebedev_recurrence_points(5, start, a, b, v, leb_tmp)
+            a = 0.1407384078513916E+0
+            v = 0.2252370188283782E-3
+            leb_tmp, start = get_lebedev_recurrence_points(5, start, a, b, v, leb_tmp)
+            a = 0.2364035438976309E+0
+            v = 0.2766135443474897E-3
+            leb_tmp, start = get_lebedev_recurrence_points(5, start, a, b, v, leb_tmp)
+            a = 0.3360602737818170E+0
+            v = 0.3110729491500851E-3
+            leb_tmp, start = get_lebedev_recurrence_points(5, start, a, b, v, leb_tmp)
+            a = 0.4356292630054665E+0
+            v = 0.3342506712303391E-3
+            leb_tmp, start = get_lebedev_recurrence_points(5, start, a, b, v, leb_tmp)
+            a = 0.5321569415256174E+0
+            v = 0.3491981834026860E-3
+            leb_tmp, start = get_lebedev_recurrence_points(5, start, a, b, v, leb_tmp)
+            a = 0.6232956305040554E+0
+            v = 0.3576003604348932E-3
+            leb_tmp, start = get_lebedev_recurrence_points(5, start, a, b, v, leb_tmp)
+            a = 0.9469870086838469E-1
+            b = 0.2778748387309470E-1
+            v = 0.1921921305788564E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.1353170300568141E+0
+            b = 0.6076569878628364E-1
+            v = 0.2301458216495632E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.1771679481726077E+0
+            b = 0.9703072762711040E-1
+            v = 0.2604248549522893E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.2197066664231751E+0
+            b = 0.1354112458524762E+0
+            v = 0.2845275425870697E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.2624783557374927E+0
+            b = 0.1750996479744100E+0
+            v = 0.3036870897974840E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.3050969521214442E+0
+            b = 0.2154896907449802E+0
+            v = 0.3188414832298066E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.3472252637196021E+0
+            b = 0.2560954625740152E+0
+            v = 0.3307046414722089E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.3885610219026360E+0
+            b = 0.2965070050624096E+0
+            v = 0.3398330969031360E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4288273776062765E+0
+            b = 0.3363641488734497E+0
+            v = 0.3466757899705373E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4677662471302948E+0
+            b = 0.3753400029836788E+0
+            v = 0.3516095923230054E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5051333589553359E+0
+            b = 0.4131297522144286E+0
+            v = 0.3549645184048486E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5406942145810492E+0
+            b = 0.4494423776081795E+0
+            v = 0.3570415969441392E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5742204122576457E+0
+            b = 0.4839938958841502E+0
+            v = 0.3581251798496118E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.1865407027225188E+0
+            b = 0.3259144851070796E-1
+            v = 0.2543491329913348E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.2321186453689432E+0
+            b = 0.6835679505297343E-1
+            v = 0.2786711051330776E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.2773159142523882E+0
+            b = 0.1062284864451989E+0
+            v = 0.2985552361083679E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.3219200192237254E+0
+            b = 0.1454404409323047E+0
+            v = 0.3145867929154039E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.3657032593944029E+0
+            b = 0.1854018282582510E+0
+            v = 0.3273290662067609E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4084376778363622E+0
+            b = 0.2256297412014750E+0
+            v = 0.3372705511943501E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4499004945751427E+0
+            b = 0.2657104425000896E+0
+            v = 0.3448274437851510E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4898758141326335E+0
+            b = 0.3052755487631557E+0
+            v = 0.3503592783048583E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5281547442266309E+0
+            b = 0.3439863920645423E+0
+            v = 0.3541854792663162E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5645346989813992E+0
+            b = 0.3815229456121914E+0
+            v = 0.3565995517909428E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5988181252159848E+0
+            b = 0.4175752420966734E+0
+            v = 0.3578802078302898E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.2850425424471603E+0
+            b = 0.3562149509862536E-1
+            v = 0.2958644592860982E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.3324619433027876E+0
+            b = 0.7330318886871096E-1
+            v = 0.3119548129116835E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.3785848333076282E+0
+            b = 0.1123226296008472E+0
+            v = 0.3250745225005984E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4232891028562115E+0
+            b = 0.1521084193337708E+0
+            v = 0.3355153415935208E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4664287050829722E+0
+            b = 0.1921844459223610E+0
+            v = 0.3435847568549328E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5078458493735726E+0
+            b = 0.2321360989678303E+0
+            v = 0.3495786831622488E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5473779816204180E+0
+            b = 0.2715886486360520E+0
+            v = 0.3537767805534621E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5848617133811376E+0
+            b = 0.3101924707571355E+0
+            v = 0.3564459815421428E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.6201348281584888E+0
+            b = 0.3476121052890973E+0
+            v = 0.3578464061225468E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.3852191185387871E+0
+            b = 0.3763224880035108E-1
+            v = 0.3239748762836212E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4325025061073423E+0
+            b = 0.7659581935637135E-1
+            v = 0.3345491784174287E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4778486229734490E+0
+            b = 0.1163381306083900E+0
+            v = 0.3429126177301782E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5211663693009000E+0
+            b = 0.1563890598752899E+0
+            v = 0.3492420343097421E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5623469504853703E+0
+            b = 0.1963320810149200E+0
+            v = 0.3537399050235257E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.6012718188659246E+0
+            b = 0.2357847407258738E+0
+            v = 0.3566209152659172E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.6378179206390117E+0
+            b = 0.2743846121244060E+0
+            v = 0.3581084321919782E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4836936460214534E+0
+            b = 0.3895902610739024E-1
+            v = 0.3426522117591512E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5293792562683797E+0
+            b = 0.7871246819312640E-1
+            v = 0.3491848770121379E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5726281253100033E+0
+            b = 0.1187963808202981E+0
+            v = 0.3539318235231476E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.6133658776169068E+0
+            b = 0.1587914708061787E+0
+            v = 0.3570231438458694E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.6515085491865307E+0
+            b = 0.1983058575227646E+0
+            v = 0.3586207335051714E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5778692716064976E+0
+            b = 0.3977209689791542E-1
+            v = 0.3541196205164025E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.6207904288086192E+0
+            b = 0.7990157592981152E-1
+            v = 0.3574296911573953E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.6608688171046802E+0
+            b = 0.1199671308754309E+0
+            v = 0.3591993279818963E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.6656263089489130E+0
+            b = 0.4015955957805969E-1
+            v = 0.3595855034661997E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+
+        case 3470:
+
+            v = 0.2040382730826330E-4
+            leb_tmp, start = get_lebedev_recurrence_points(1, start, a, b, v, leb_tmp)
+            v = 0.3178149703889544E-3
+            leb_tmp, start = get_lebedev_recurrence_points(3, start, a, b, v, leb_tmp)
+            a = 0.1721420832906233E-1
+            v = 0.8288115128076110E-4
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.4408875374981770E-1
+            v = 0.1360883192522954E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.7594680813878681E-1
+            v = 0.1766854454542662E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.1108335359204799E+0
+            v = 0.2083153161230153E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.1476517054388567E+0
+            v = 0.2333279544657158E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.1856731870860615E+0
+            v = 0.2532809539930247E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.2243634099428821E+0
+            v = 0.2692472184211158E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.2633006881662727E+0
+            v = 0.2819949946811885E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.3021340904916283E+0
+            v = 0.2920953593973030E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.3405594048030089E+0
+            v = 0.2999889782948352E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.3783044434007372E+0
+            v = 0.3060292120496902E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.4151194767407910E+0
+            v = 0.3105109167522192E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.4507705766443257E+0
+            v = 0.3136902387550312E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.4850346056573187E+0
+            v = 0.3157984652454632E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.5176950817792470E+0
+            v = 0.3170516518425422E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.5485384240820989E+0
+            v = 0.3176568425633755E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.6039117238943308E+0
+            v = 0.3177198411207062E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.6279956655573113E+0
+            v = 0.3175519492394733E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.6493636169568952E+0
+            v = 0.3174654952634756E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.6677644117704504E+0
+            v = 0.3175676415467654E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.6829368572115624E+0
+            v = 0.3178923417835410E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.6946195818184121E+0
+            v = 0.3183788287531909E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.7025711542057026E+0
+            v = 0.3188755151918807E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.7066004767140119E+0
+            v = 0.3191916889313849E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.5132537689946062E-1
+            v = 0.1231779611744508E-3
+            leb_tmp, start = get_lebedev_recurrence_points(5, start, a, b, v, leb_tmp)
+            a = 0.1297994661331225E+0
+            v = 0.1924661373839880E-3
+            leb_tmp, start = get_lebedev_recurrence_points(5, start, a, b, v, leb_tmp)
+            a = 0.2188852049401307E+0
+            v = 0.2380881867403424E-3
+            leb_tmp, start = get_lebedev_recurrence_points(5, start, a, b, v, leb_tmp)
+            a = 0.3123174824903457E+0
+            v = 0.2693100663037885E-3
+            leb_tmp, start = get_lebedev_recurrence_points(5, start, a, b, v, leb_tmp)
+            a = 0.4064037620738195E+0
+            v = 0.2908673382834366E-3
+            leb_tmp, start = get_lebedev_recurrence_points(5, start, a, b, v, leb_tmp)
+            a = 0.4984958396944782E+0
+            v = 0.3053914619381535E-3
+            leb_tmp, start = get_lebedev_recurrence_points(5, start, a, b, v, leb_tmp)
+            a = 0.5864975046021365E+0
+            v = 0.3143916684147777E-3
+            leb_tmp, start = get_lebedev_recurrence_points(5, start, a, b, v, leb_tmp)
+            a = 0.6686711634580175E+0
+            v = 0.3187042244055363E-3
+            leb_tmp, start = get_lebedev_recurrence_points(5, start, a, b, v, leb_tmp)
+            a = 0.8715738780835950E-1
+            b = 0.2557175233367578E-1
+            v = 0.1635219535869790E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.1248383123134007E+0
+            b = 0.5604823383376681E-1
+            v = 0.1968109917696070E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.1638062693383378E+0
+            b = 0.8968568601900765E-1
+            v = 0.2236754342249974E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.2035586203373176E+0
+            b = 0.1254086651976279E+0
+            v = 0.2453186687017181E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.2436798975293774E+0
+            b = 0.1624780150162012E+0
+            v = 0.2627551791580541E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.2838207507773806E+0
+            b = 0.2003422342683208E+0
+            v = 0.2767654860152220E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.3236787502217692E+0
+            b = 0.2385628026255263E+0
+            v = 0.2879467027765895E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.3629849554840691E+0
+            b = 0.2767731148783578E+0
+            v = 0.2967639918918702E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4014948081992087E+0
+            b = 0.3146542308245309E+0
+            v = 0.3035900684660351E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4389818379260225E+0
+            b = 0.3519196415895088E+0
+            v = 0.3087338237298308E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4752331143674377E+0
+            b = 0.3883050984023654E+0
+            v = 0.3124608838860167E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5100457318374018E+0
+            b = 0.4235613423908649E+0
+            v = 0.3150084294226743E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5432238388954868E+0
+            b = 0.4574484717196220E+0
+            v = 0.3165958398598402E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5745758685072442E+0
+            b = 0.4897311639255524E+0
+            v = 0.3174320440957372E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.1723981437592809E+0
+            b = 0.3010630597881105E-1
+            v = 0.2182188909812599E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.2149553257844597E+0
+            b = 0.6326031554204694E-1
+            v = 0.2399727933921445E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.2573256081247422E+0
+            b = 0.9848566980258631E-1
+            v = 0.2579796133514652E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.2993163751238106E+0
+            b = 0.1350835952384266E+0
+            v = 0.2727114052623535E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.3407238005148000E+0
+            b = 0.1725184055442181E+0
+            v = 0.2846327656281355E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.3813454978483264E+0
+            b = 0.2103559279730725E+0
+            v = 0.2941491102051334E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4209848104423343E+0
+            b = 0.2482278774554860E+0
+            v = 0.3016049492136107E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4594519699996300E+0
+            b = 0.2858099509982883E+0
+            v = 0.3072949726175648E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4965640166185930E+0
+            b = 0.3228075659915428E+0
+            v = 0.3114768142886460E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5321441655571562E+0
+            b = 0.3589459907204151E+0
+            v = 0.3143823673666223E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5660208438582166E+0
+            b = 0.3939630088864310E+0
+            v = 0.3162269764661535E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5980264315964364E+0
+            b = 0.4276029922949089E+0
+            v = 0.3172164663759821E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.2644215852350733E+0
+            b = 0.3300939429072552E-1
+            v = 0.2554575398967435E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.3090113743443063E+0
+            b = 0.6803887650078501E-1
+            v = 0.2701704069135677E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.3525871079197808E+0
+            b = 0.1044326136206709E+0
+            v = 0.2823693413468940E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.3950418005354029E+0
+            b = 0.1416751597517679E+0
+            v = 0.2922898463214289E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4362475663430163E+0
+            b = 0.1793408610504821E+0
+            v = 0.3001829062162428E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4760661812145854E+0
+            b = 0.2170630750175722E+0
+            v = 0.3062890864542953E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5143551042512103E+0
+            b = 0.2545145157815807E+0
+            v = 0.3108328279264746E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5509709026935597E+0
+            b = 0.2913940101706601E+0
+            v = 0.3140243146201245E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5857711030329428E+0
+            b = 0.3274169910910705E+0
+            v = 0.3160638030977130E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.6186149917404392E+0
+            b = 0.3623081329317265E+0
+            v = 0.3171462882206275E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.3586894569557064E+0
+            b = 0.3497354386450040E-1
+            v = 0.2812388416031796E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4035266610019441E+0
+            b = 0.7129736739757095E-1
+            v = 0.2912137500288045E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4467775312332510E+0
+            b = 0.1084758620193165E+0
+            v = 0.2993241256502206E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4883638346608543E+0
+            b = 0.1460915689241772E+0
+            v = 0.3057101738983822E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5281908348434601E+0
+            b = 0.1837790832369980E+0
+            v = 0.3105319326251432E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5661542687149311E+0
+            b = 0.2212075390874021E+0
+            v = 0.3139565514428167E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.6021450102031452E+0
+            b = 0.2580682841160985E+0
+            v = 0.3161543006806366E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.6360520783610050E+0
+            b = 0.2940656362094121E+0
+            v = 0.3172985960613294E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4521611065087196E+0
+            b = 0.3631055365867002E-1
+            v = 0.2989400336901431E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4959365651560963E+0
+            b = 0.7348318468484350E-1
+            v = 0.3054555883947677E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5376815804038283E+0
+            b = 0.1111087643812648E+0
+            v = 0.3104764960807702E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5773314480243768E+0
+            b = 0.1488226085145408E+0
+            v = 0.3141015825977616E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.6148113245575056E+0
+            b = 0.1862892274135151E+0
+            v = 0.3164520621159896E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.6500407462842380E+0
+            b = 0.2231909701714456E+0
+            v = 0.3176652305912204E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5425151448707213E+0
+            b = 0.3718201306118944E-1
+            v = 0.3105097161023939E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5841860556907931E+0
+            b = 0.7483616335067346E-1
+            v = 0.3143014117890550E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.6234632186851500E+0
+            b = 0.1125990834266120E+0
+            v = 0.3168172866287200E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.6602934551848843E+0
+            b = 0.1501303813157619E+0
+            v = 0.3181401865570968E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.6278573968375105E+0
+            b = 0.3767559930245720E-1
+            v = 0.3170663659156037E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.6665611711264577E+0
+            b = 0.7548443301360158E-1
+            v = 0.3185447944625510E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+
+        case 3890:
+
+            v = 0.1807395252196920E-4
+            leb_tmp, start = get_lebedev_recurrence_points(1, start, a, b, v, leb_tmp)
+            v = 0.2848008782238827E-3
+            leb_tmp, start = get_lebedev_recurrence_points(2, start, a, b, v, leb_tmp)
+            v = 0.2836065837530581E-3
+            leb_tmp, start = get_lebedev_recurrence_points(3, start, a, b, v, leb_tmp)
+            a = 0.1587876419858352E-1
+            v = 0.7013149266673816E-4
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.4069193593751206E-1
+            v = 0.1162798021956766E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.7025888115257997E-1
+            v = 0.1518728583972105E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.1027495450028704E+0
+            v = 0.1798796108216934E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.1371457730893426E+0
+            v = 0.2022593385972785E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.1727758532671953E+0
+            v = 0.2203093105575464E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.2091492038929037E+0
+            v = 0.2349294234299855E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.2458813281751915E+0
+            v = 0.2467682058747003E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.2826545859450066E+0
+            v = 0.2563092683572224E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.3191957291799622E+0
+            v = 0.2639253896763318E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.3552621469299578E+0
+            v = 0.2699137479265108E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.3906329503406230E+0
+            v = 0.2745196420166739E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.4251028614093031E+0
+            v = 0.2779529197397593E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.4584777520111870E+0
+            v = 0.2803996086684265E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.4905711358710193E+0
+            v = 0.2820302356715842E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.5212011669847385E+0
+            v = 0.2830056747491068E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.5501878488737995E+0
+            v = 0.2834808950776839E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.6025037877479342E+0
+            v = 0.2835282339078929E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.6254572689549016E+0
+            v = 0.2833819267065800E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.6460107179528248E+0
+            v = 0.2832858336906784E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.6639541138154251E+0
+            v = 0.2833268235451244E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.6790688515667495E+0
+            v = 0.2835432677029253E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.6911338580371512E+0
+            v = 0.2839091722743049E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.6999385956126490E+0
+            v = 0.2843308178875841E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.7053037748656896E+0
+            v = 0.2846703550533846E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.4732224387180115E-1
+            v = 0.1051193406971900E-3
+            leb_tmp, start = get_lebedev_recurrence_points(5, start, a, b, v, leb_tmp)
+            a = 0.1202100529326803E+0
+            v = 0.1657871838796974E-3
+            leb_tmp, start = get_lebedev_recurrence_points(5, start, a, b, v, leb_tmp)
+            a = 0.2034304820664855E+0
+            v = 0.2064648113714232E-3
+            leb_tmp, start = get_lebedev_recurrence_points(5, start, a, b, v, leb_tmp)
+            a = 0.2912285643573002E+0
+            v = 0.2347942745819741E-3
+            leb_tmp, start = get_lebedev_recurrence_points(5, start, a, b, v, leb_tmp)
+            a = 0.3802361792726768E+0
+            v = 0.2547775326597726E-3
+            leb_tmp, start = get_lebedev_recurrence_points(5, start, a, b, v, leb_tmp)
+            a = 0.4680598511056146E+0
+            v = 0.2686876684847025E-3
+            leb_tmp, start = get_lebedev_recurrence_points(5, start, a, b, v, leb_tmp)
+            a = 0.5528151052155599E+0
+            v = 0.2778665755515867E-3
+            leb_tmp, start = get_lebedev_recurrence_points(5, start, a, b, v, leb_tmp)
+            a = 0.6329386307803041E+0
+            v = 0.2830996616782929E-3
+            leb_tmp, start = get_lebedev_recurrence_points(5, start, a, b, v, leb_tmp)
+            a = 0.8056516651369069E-1
+            b = 0.2363454684003124E-1
+            v = 0.1403063340168372E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.1156476077139389E+0
+            b = 0.5191291632545936E-1
+            v = 0.1696504125939477E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.1520473382760421E+0
+            b = 0.8322715736994519E-1
+            v = 0.1935787242745390E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.1892986699745931E+0
+            b = 0.1165855667993712E+0
+            v = 0.2130614510521968E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.2270194446777792E+0
+            b = 0.1513077167409504E+0
+            v = 0.2289381265931048E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.2648908185093273E+0
+            b = 0.1868882025807859E+0
+            v = 0.2418630292816186E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.3026389259574136E+0
+            b = 0.2229277629776224E+0
+            v = 0.2523400495631193E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.3400220296151384E+0
+            b = 0.2590951840746235E+0
+            v = 0.2607623973449605E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.3768217953335510E+0
+            b = 0.2951047291750847E+0
+            v = 0.2674441032689209E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4128372900921884E+0
+            b = 0.3307019714169930E+0
+            v = 0.2726432360343356E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4478807131815630E+0
+            b = 0.3656544101087634E+0
+            v = 0.2765787685924545E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4817742034089257E+0
+            b = 0.3997448951939695E+0
+            v = 0.2794428690642224E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5143472814653344E+0
+            b = 0.4327667110812024E+0
+            v = 0.2814099002062895E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5454346213905650E+0
+            b = 0.4645196123532293E+0
+            v = 0.2826429531578994E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5748739313170252E+0
+            b = 0.4948063555703345E+0
+            v = 0.2832983542550884E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.1599598738286342E+0
+            b = 0.2792357590048985E-1
+            v = 0.1886695565284976E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.1998097412500951E+0
+            b = 0.5877141038139065E-1
+            v = 0.2081867882748234E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.2396228952566202E+0
+            b = 0.9164573914691377E-1
+            v = 0.2245148680600796E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.2792228341097746E+0
+            b = 0.1259049641962687E+0
+            v = 0.2380370491511872E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.3184251107546741E+0
+            b = 0.1610594823400863E+0
+            v = 0.2491398041852455E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.3570481164426244E+0
+            b = 0.1967151653460898E+0
+            v = 0.2581632405881230E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.3949164710492144E+0
+            b = 0.2325404606175168E+0
+            v = 0.2653965506227417E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4318617293970503E+0
+            b = 0.2682461141151439E+0
+            v = 0.2710857216747087E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4677221009931678E+0
+            b = 0.3035720116011973E+0
+            v = 0.2754434093903659E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5023417939270955E+0
+            b = 0.3382781859197439E+0
+            v = 0.2786579932519380E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5355701836636128E+0
+            b = 0.3721383065625942E+0
+            v = 0.2809011080679474E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5672608451328771E+0
+            b = 0.4049346360466055E+0
+            v = 0.2823336184560987E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5972704202540162E+0
+            b = 0.4364538098633802E+0
+            v = 0.2831101175806309E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.2461687022333596E+0
+            b = 0.3070423166833368E-1
+            v = 0.2221679970354546E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.2881774566286831E+0
+            b = 0.6338034669281885E-1
+            v = 0.2356185734270703E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.3293963604116978E+0
+            b = 0.9742862487067941E-1
+            v = 0.2469228344805590E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.3697303822241377E+0
+            b = 0.1323799532282290E+0
+            v = 0.2562726348642046E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4090663023135127E+0
+            b = 0.1678497018129336E+0
+            v = 0.2638756726753028E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4472819355411712E+0
+            b = 0.2035095105326114E+0
+            v = 0.2699311157390862E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4842513377231437E+0
+            b = 0.2390692566672091E+0
+            v = 0.2746233268403837E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5198477629962928E+0
+            b = 0.2742649818076149E+0
+            v = 0.2781225674454771E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5539453011883145E+0
+            b = 0.3088503806580094E+0
+            v = 0.2805881254045684E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5864196762401251E+0
+            b = 0.3425904245906614E+0
+            v = 0.2821719877004913E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.6171484466668390E+0
+            b = 0.3752562294789468E+0
+            v = 0.2830222502333124E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.3350337830565727E+0
+            b = 0.3261589934634747E-1
+            v = 0.2457995956744870E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.3775773224758284E+0
+            b = 0.6658438928081572E-1
+            v = 0.2551474407503706E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4188155229848973E+0
+            b = 0.1014565797157954E+0
+            v = 0.2629065335195311E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4586805892009344E+0
+            b = 0.1368573320843822E+0
+            v = 0.2691900449925075E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4970895714224235E+0
+            b = 0.1724614851951608E+0
+            v = 0.2741275485754276E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5339505133960747E+0
+            b = 0.2079779381416412E+0
+            v = 0.2778530970122595E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5691665792531440E+0
+            b = 0.2431385788322288E+0
+            v = 0.2805010567646741E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.6026387682680377E+0
+            b = 0.2776901883049853E+0
+            v = 0.2822055834031040E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.6342676150163307E+0
+            b = 0.3113881356386632E+0
+            v = 0.2831016901243473E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4237951119537067E+0
+            b = 0.3394877848664351E-1
+            v = 0.2624474901131803E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4656918683234929E+0
+            b = 0.6880219556291447E-1
+            v = 0.2688034163039377E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5058857069185980E+0
+            b = 0.1041946859721635E+0
+            v = 0.2738932751287636E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5443204666713996E+0
+            b = 0.1398039738736393E+0
+            v = 0.2777944791242523E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5809298813759742E+0
+            b = 0.1753373381196155E+0
+            v = 0.2806011661660987E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.6156416039447128E+0
+            b = 0.2105215793514010E+0
+            v = 0.2824181456597460E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.6483801351066604E+0
+            b = 0.2450953312157051E+0
+            v = 0.2833585216577828E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5103616577251688E+0
+            b = 0.3485560643800719E-1
+            v = 0.2738165236962878E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5506738792580681E+0
+            b = 0.7026308631512033E-1
+            v = 0.2778365208203180E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5889573040995292E+0
+            b = 0.1059035061296403E+0
+            v = 0.2807852940418966E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.6251641589516930E+0
+            b = 0.1414823925236026E+0
+            v = 0.2827245949674705E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.6592414921570178E+0
+            b = 0.1767207908214530E+0
+            v = 0.2837342344829828E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5930314017533384E+0
+            b = 0.3542189339561672E-1
+            v = 0.2809233907610981E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.6309812253390175E+0
+            b = 0.7109574040369549E-1
+            v = 0.2829930809742694E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.6666296011353230E+0
+            b = 0.1067259792282730E+0
+            v = 0.2841097874111479E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.6703715271049922E+0
+            b = 0.3569455268820809E-1
+            v = 0.2843455206008783E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+
+        case 4334:
+
+            v = 0.1449063022537883E-4
+            leb_tmp, start = get_lebedev_recurrence_points(1, start, a, b, v, leb_tmp)
+            v = 0.2546377329828424E-3
+            leb_tmp, start = get_lebedev_recurrence_points(3, start, a, b, v, leb_tmp)
+            a = 0.1462896151831013E-1
+            v = 0.6018432961087496E-4
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.3769840812493139E-1
+            v = 0.1002286583263673E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.6524701904096891E-1
+            v = 0.1315222931028093E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.9560543416134648E-1
+            v = 0.1564213746876724E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.1278335898929198E+0
+            v = 0.1765118841507736E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.1613096104466031E+0
+            v = 0.1928737099311080E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.1955806225745371E+0
+            v = 0.2062658534263270E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.2302935218498028E+0
+            v = 0.2172395445953787E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.2651584344113027E+0
+            v = 0.2262076188876047E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.2999276825183209E+0
+            v = 0.2334885699462397E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.3343828669718798E+0
+            v = 0.2393355273179203E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.3683265013750518E+0
+            v = 0.2439559200468863E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.4015763206518108E+0
+            v = 0.2475251866060002E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.4339612026399770E+0
+            v = 0.2501965558158773E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.4653180651114582E+0
+            v = 0.2521081407925925E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.4954893331080803E+0
+            v = 0.2533881002388081E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.5243207068924930E+0
+            v = 0.2541582900848261E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.5516590479041704E+0
+            v = 0.2545365737525860E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.6012371927804176E+0
+            v = 0.2545726993066799E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.6231574466449819E+0
+            v = 0.2544456197465555E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.6429416514181271E+0
+            v = 0.2543481596881064E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.6604124272943595E+0
+            v = 0.2543506451429194E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.6753851470408250E+0
+            v = 0.2544905675493763E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.6876717970626160E+0
+            v = 0.2547611407344429E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.6970895061319234E+0
+            v = 0.2551060375448869E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.7034746912553310E+0
+            v = 0.2554291933816039E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.7067017217542295E+0
+            v = 0.2556255710686343E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.4382223501131123E-1
+            v = 0.9041339695118195E-4
+            leb_tmp, start = get_lebedev_recurrence_points(5, start, a, b, v, leb_tmp)
+            a = 0.1117474077400006E+0
+            v = 0.1438426330079022E-3
+            leb_tmp, start = get_lebedev_recurrence_points(5, start, a, b, v, leb_tmp)
+            a = 0.1897153252911440E+0
+            v = 0.1802523089820518E-3
+            leb_tmp, start = get_lebedev_recurrence_points(5, start, a, b, v, leb_tmp)
+            a = 0.2724023009910331E+0
+            v = 0.2060052290565496E-3
+            leb_tmp, start = get_lebedev_recurrence_points(5, start, a, b, v, leb_tmp)
+            a = 0.3567163308709902E+0
+            v = 0.2245002248967466E-3
+            leb_tmp, start = get_lebedev_recurrence_points(5, start, a, b, v, leb_tmp)
+            a = 0.4404784483028087E+0
+            v = 0.2377059847731150E-3
+            leb_tmp, start = get_lebedev_recurrence_points(5, start, a, b, v, leb_tmp)
+            a = 0.5219833154161411E+0
+            v = 0.2468118955882525E-3
+            leb_tmp, start = get_lebedev_recurrence_points(5, start, a, b, v, leb_tmp)
+            a = 0.5998179868977553E+0
+            v = 0.2525410872966528E-3
+            leb_tmp, start = get_lebedev_recurrence_points(5, start, a, b, v, leb_tmp)
+            a = 0.6727803154548222E+0
+            v = 0.2553101409933397E-3
+            leb_tmp, start = get_lebedev_recurrence_points(5, start, a, b, v, leb_tmp)
+            a = 0.7476563943166086E-1
+            b = 0.2193168509461185E-1
+            v = 0.1212879733668632E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.1075341482001416E+0
+            b = 0.4826419281533887E-1
+            v = 0.1472872881270931E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.1416344885203259E+0
+            b = 0.7751191883575742E-1
+            v = 0.1686846601010828E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.1766325315388586E+0
+            b = 0.1087558139247680E+0
+            v = 0.1862698414660208E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.2121744174481514E+0
+            b = 0.1413661374253096E+0
+            v = 0.2007430956991861E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.2479669443408145E+0
+            b = 0.1748768214258880E+0
+            v = 0.2126568125394796E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.2837600452294113E+0
+            b = 0.2089216406612073E+0
+            v = 0.2224394603372113E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.3193344933193984E+0
+            b = 0.2431987685545972E+0
+            v = 0.2304264522673135E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.3544935442438745E+0
+            b = 0.2774497054377770E+0
+            v = 0.2368854288424087E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.3890571932288154E+0
+            b = 0.3114460356156915E+0
+            v = 0.2420352089461772E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4228581214259090E+0
+            b = 0.3449806851913012E+0
+            v = 0.2460597113081295E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4557387211304052E+0
+            b = 0.3778618641248256E+0
+            v = 0.2491181912257687E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4875487950541643E+0
+            b = 0.4099086391698978E+0
+            v = 0.2513528194205857E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5181436529962997E+0
+            b = 0.4409474925853973E+0
+            v = 0.2528943096693220E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5473824095600661E+0
+            b = 0.4708094517711291E+0
+            v = 0.2538660368488136E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5751263398976174E+0
+            b = 0.4993275140354637E+0
+            v = 0.2543868648299022E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.1489515746840028E+0
+            b = 0.2599381993267017E-1
+            v = 0.1642595537825183E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.1863656444351767E+0
+            b = 0.5479286532462190E-1
+            v = 0.1818246659849308E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.2238602880356348E+0
+            b = 0.8556763251425254E-1
+            v = 0.1966565649492420E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.2612723375728160E+0
+            b = 0.1177257802267011E+0
+            v = 0.2090677905657991E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.2984332990206190E+0
+            b = 0.1508168456192700E+0
+            v = 0.2193820409510504E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.3351786584663333E+0
+            b = 0.1844801892177727E+0
+            v = 0.2278870827661928E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.3713505522209120E+0
+            b = 0.2184145236087598E+0
+            v = 0.2348283192282090E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4067981098954663E+0
+            b = 0.2523590641486229E+0
+            v = 0.2404139755581477E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4413769993687534E+0
+            b = 0.2860812976901373E+0
+            v = 0.2448227407760734E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4749487182516394E+0
+            b = 0.3193686757808996E+0
+            v = 0.2482110455592573E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5073798105075426E+0
+            b = 0.3520226949547602E+0
+            v = 0.2507192397774103E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5385410448878654E+0
+            b = 0.3838544395667890E+0
+            v = 0.2524765968534880E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5683065353670530E+0
+            b = 0.4146810037640963E+0
+            v = 0.2536052388539425E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5965527620663510E+0
+            b = 0.4443224094681121E+0
+            v = 0.2542230588033068E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.2299227700856157E+0
+            b = 0.2865757664057584E-1
+            v = 0.1944817013047896E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.2695752998553267E+0
+            b = 0.5923421684485993E-1
+            v = 0.2067862362746635E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.3086178716611389E+0
+            b = 0.9117817776057715E-1
+            v = 0.2172440734649114E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.3469649871659077E+0
+            b = 0.1240593814082605E+0
+            v = 0.2260125991723423E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.3845153566319655E+0
+            b = 0.1575272058259175E+0
+            v = 0.2332655008689523E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4211600033403215E+0
+            b = 0.1912845163525413E+0
+            v = 0.2391699681532458E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4567867834329882E+0
+            b = 0.2250710177858171E+0
+            v = 0.2438801528273928E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4912829319232061E+0
+            b = 0.2586521303440910E+0
+            v = 0.2475370504260665E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5245364793303812E+0
+            b = 0.2918112242865407E+0
+            v = 0.2502707235640574E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5564369788915756E+0
+            b = 0.3243439239067890E+0
+            v = 0.2522031701054241E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5868757697775287E+0
+            b = 0.3560536787835351E+0
+            v = 0.2534511269978784E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.6157458853519617E+0
+            b = 0.3867480821242581E+0
+            v = 0.2541284914955151E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.3138461110672113E+0
+            b = 0.3051374637507278E-1
+            v = 0.2161509250688394E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.3542495872050569E+0
+            b = 0.6237111233730755E-1
+            v = 0.2248778513437852E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.3935751553120181E+0
+            b = 0.9516223952401907E-1
+            v = 0.2322388803404617E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4317634668111147E+0
+            b = 0.1285467341508517E+0
+            v = 0.2383265471001355E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4687413842250821E+0
+            b = 0.1622318931656033E+0
+            v = 0.2432476675019525E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5044274237060283E+0
+            b = 0.1959581153836453E+0
+            v = 0.2471122223750674E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5387354077925727E+0
+            b = 0.2294888081183837E+0
+            v = 0.2500291752486870E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5715768898356105E+0
+            b = 0.2626031152713945E+0
+            v = 0.2521055942764682E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.6028627200136111E+0
+            b = 0.2950904075286713E+0
+            v = 0.2534472785575503E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.6325039812653463E+0
+            b = 0.3267458451113286E+0
+            v = 0.2541599713080121E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.3981986708423407E+0
+            b = 0.3183291458749821E-1
+            v = 0.2317380975862936E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4382791182133300E+0
+            b = 0.6459548193880908E-1
+            v = 0.2378550733719775E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4769233057218166E+0
+            b = 0.9795757037087952E-1
+            v = 0.2428884456739118E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5140823911194238E+0
+            b = 0.1316307235126655E+0
+            v = 0.2469002655757292E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5496977833862983E+0
+            b = 0.1653556486358704E+0
+            v = 0.2499657574265851E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5837047306512727E+0
+            b = 0.1988931724126510E+0
+            v = 0.2521676168486082E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.6160349566926879E+0
+            b = 0.2320174581438950E+0
+            v = 0.2535935662645334E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.6466185353209440E+0
+            b = 0.2645106562168662E+0
+            v = 0.2543356743363214E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4810835158795404E+0
+            b = 0.3275917807743992E-1
+            v = 0.2427353285201535E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5199925041324341E+0
+            b = 0.6612546183967181E-1
+            v = 0.2468258039744386E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5571717692207494E+0
+            b = 0.9981498331474143E-1
+            v = 0.2500060956440310E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5925789250836378E+0
+            b = 0.1335687001410374E+0
+            v = 0.2523238365420979E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.6261658523859670E+0
+            b = 0.1671444402896463E+0
+            v = 0.2538399260252846E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.6578811126669331E+0
+            b = 0.2003106382156076E+0
+            v = 0.2546255927268069E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5609624612998100E+0
+            b = 0.3337500940231335E-1
+            v = 0.2500583360048449E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5979959659984670E+0
+            b = 0.6708750335901803E-1
+            v = 0.2524777638260203E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.6330523711054002E+0
+            b = 0.1008792126424850E+0
+            v = 0.2540951193860656E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.6660960998103972E+0
+            b = 0.1345050343171794E+0
+            v = 0.2549524085027472E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.6365384364585819E+0
+            b = 0.3372799460737052E-1
+            v = 0.2542569507009158E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.6710994302899275E+0
+            b = 0.6755249309678028E-1
+            v = 0.2552114127580376E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+
+        case 4802:
+
+            v = 0.9687521879420705E-4
+            leb_tmp, start = get_lebedev_recurrence_points(1, start, a, b, v, leb_tmp)
+            v = 0.2307897895367918E-3
+            leb_tmp, start = get_lebedev_recurrence_points(2, start, a, b, v, leb_tmp)
+            v = 0.2297310852498558E-3
+            leb_tmp, start = get_lebedev_recurrence_points(3, start, a, b, v, leb_tmp)
+            a = 0.2335728608887064E-1
+            v = 0.7386265944001919E-4
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.4352987836550653E-1
+            v = 0.8257977698542210E-4
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.6439200521088801E-1
+            v = 0.9706044762057630E-4
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.9003943631993181E-1
+            v = 0.1302393847117003E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.1196706615548473E+0
+            v = 0.1541957004600968E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.1511715412838134E+0
+            v = 0.1704459770092199E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.1835982828503801E+0
+            v = 0.1827374890942906E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.2165081259155405E+0
+            v = 0.1926360817436107E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.2496208720417563E+0
+            v = 0.2008010239494833E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.2827200673567900E+0
+            v = 0.2075635983209175E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.3156190823994346E+0
+            v = 0.2131306638690909E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.3481476793749115E+0
+            v = 0.2176562329937335E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.3801466086947226E+0
+            v = 0.2212682262991018E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.4114652119634011E+0
+            v = 0.2240799515668565E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.4419598786519751E+0
+            v = 0.2261959816187525E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.4714925949329543E+0
+            v = 0.2277156368808855E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.4999293972879466E+0
+            v = 0.2287351772128336E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.5271387221431248E+0
+            v = 0.2293490814084085E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.5529896780837761E+0
+            v = 0.2296505312376273E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.6000856099481712E+0
+            v = 0.2296793832318756E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.6210562192785175E+0
+            v = 0.2295785443842974E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.6401165879934240E+0
+            v = 0.2295017931529102E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.6571144029244334E+0
+            v = 0.2295059638184868E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.6718910821718863E+0
+            v = 0.2296232343237362E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.6842845591099010E+0
+            v = 0.2298530178740771E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.6941353476269816E+0
+            v = 0.2301579790280501E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.7012965242212991E+0
+            v = 0.2304690404996513E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.7056471428242644E+0
+            v = 0.2307027995907102E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.4595557643585895E-1
+            v = 0.9312274696671092E-4
+            leb_tmp, start = get_lebedev_recurrence_points(5, start, a, b, v, leb_tmp)
+            a = 0.1049316742435023E+0
+            v = 0.1199919385876926E-3
+            leb_tmp, start = get_lebedev_recurrence_points(5, start, a, b, v, leb_tmp)
+            a = 0.1773548879549274E+0
+            v = 0.1598039138877690E-3
+            leb_tmp, start = get_lebedev_recurrence_points(5, start, a, b, v, leb_tmp)
+            a = 0.2559071411236127E+0
+            v = 0.1822253763574900E-3
+            leb_tmp, start = get_lebedev_recurrence_points(5, start, a, b, v, leb_tmp)
+            a = 0.3358156837985898E+0
+            v = 0.1988579593655040E-3
+            leb_tmp, start = get_lebedev_recurrence_points(5, start, a, b, v, leb_tmp)
+            a = 0.4155835743763893E+0
+            v = 0.2112620102533307E-3
+            leb_tmp, start = get_lebedev_recurrence_points(5, start, a, b, v, leb_tmp)
+            a = 0.4937894296167472E+0
+            v = 0.2201594887699007E-3
+            leb_tmp, start = get_lebedev_recurrence_points(5, start, a, b, v, leb_tmp)
+            a = 0.5691569694793316E+0
+            v = 0.2261622590895036E-3
+            leb_tmp, start = get_lebedev_recurrence_points(5, start, a, b, v, leb_tmp)
+            a = 0.6405840854894251E+0
+            v = 0.2296458453435705E-3
+            leb_tmp, start = get_lebedev_recurrence_points(5, start, a, b, v, leb_tmp)
+            a = 0.7345133894143348E-1
+            b = 0.2177844081486067E-1
+            v = 0.1006006990267000E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.1009859834044931E+0
+            b = 0.4590362185775188E-1
+            v = 0.1227676689635876E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.1324289619748758E+0
+            b = 0.7255063095690877E-1
+            v = 0.1467864280270117E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.1654272109607127E+0
+            b = 0.1017825451960684E+0
+            v = 0.1644178912101232E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.1990767186776461E+0
+            b = 0.1325652320980364E+0
+            v = 0.1777664890718961E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.2330125945523278E+0
+            b = 0.1642765374496765E+0
+            v = 0.1884825664516690E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.2670080611108287E+0
+            b = 0.1965360374337889E+0
+            v = 0.1973269246453848E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.3008753376294316E+0
+            b = 0.2290726770542238E+0
+            v = 0.2046767775855328E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.3344475596167860E+0
+            b = 0.2616645495370823E+0
+            v = 0.2107600125918040E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.3675709724070786E+0
+            b = 0.2941150728843141E+0
+            v = 0.2157416362266829E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4001000887587812E+0
+            b = 0.3262440400919066E+0
+            v = 0.2197557816920721E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4318956350436028E+0
+            b = 0.3578835350611916E+0
+            v = 0.2229192611835437E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4628239056795531E+0
+            b = 0.3888751854043678E+0
+            v = 0.2253385110212775E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4927563229773636E+0
+            b = 0.4190678003222840E+0
+            v = 0.2271137107548774E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5215687136707969E+0
+            b = 0.4483151836883852E+0
+            v = 0.2283414092917525E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5491402346984905E+0
+            b = 0.4764740676087880E+0
+            v = 0.2291161673130077E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5753520160126075E+0
+            b = 0.5034021310998277E+0
+            v = 0.2295313908576598E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.1388326356417754E+0
+            b = 0.2435436510372806E-1
+            v = 0.1438204721359031E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.1743686900537244E+0
+            b = 0.5118897057342652E-1
+            v = 0.1607738025495257E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.2099737037950268E+0
+            b = 0.8014695048539634E-1
+            v = 0.1741483853528379E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.2454492590908548E+0
+            b = 0.1105117874155699E+0
+            v = 0.1851918467519151E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.2807219257864278E+0
+            b = 0.1417950531570966E+0
+            v = 0.1944628638070613E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.3156842271975842E+0
+            b = 0.1736604945719597E+0
+            v = 0.2022495446275152E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.3502090945177752E+0
+            b = 0.2058466324693981E+0
+            v = 0.2087462382438514E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.3841684849519686E+0
+            b = 0.2381284261195919E+0
+            v = 0.2141074754818308E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4174372367906016E+0
+            b = 0.2703031270422569E+0
+            v = 0.2184640913748162E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4498926465011892E+0
+            b = 0.3021845683091309E+0
+            v = 0.2219309165220329E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4814146229807701E+0
+            b = 0.3335993355165720E+0
+            v = 0.2246123118340624E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5118863625734701E+0
+            b = 0.3643833735518232E+0
+            v = 0.2266062766915125E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5411947455119144E+0
+            b = 0.3943789541958179E+0
+            v = 0.2280072952230796E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5692301500357246E+0
+            b = 0.4234320144403542E+0
+            v = 0.2289082025202583E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5958857204139576E+0
+            b = 0.4513897947419260E+0
+            v = 0.2294012695120025E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.2156270284785766E+0
+            b = 0.2681225755444491E-1
+            v = 0.1722434488736947E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.2532385054909710E+0
+            b = 0.5557495747805614E-1
+            v = 0.1830237421455091E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.2902564617771537E+0
+            b = 0.8569368062950249E-1
+            v = 0.1923855349997633E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.3266979823143256E+0
+            b = 0.1167367450324135E+0
+            v = 0.2004067861936271E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.3625039627493614E+0
+            b = 0.1483861994003304E+0
+            v = 0.2071817297354263E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.3975838937548699E+0
+            b = 0.1803821503011405E+0
+            v = 0.2128250834102103E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4318396099009774E+0
+            b = 0.2124962965666424E+0
+            v = 0.2174513719440102E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4651706555732742E+0
+            b = 0.2445221837805913E+0
+            v = 0.2211661839150214E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4974752649620969E+0
+            b = 0.2762701224322987E+0
+            v = 0.2240665257813102E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5286517579627517E+0
+            b = 0.3075627775211328E+0
+            v = 0.2262439516632620E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5586001195731895E+0
+            b = 0.3382311089826877E+0
+            v = 0.2277874557231869E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5872229902021319E+0
+            b = 0.3681108834741399E+0
+            v = 0.2287854314454994E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.6144258616235123E+0
+            b = 0.3970397446872839E+0
+            v = 0.2293268499615575E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.2951676508064861E+0
+            b = 0.2867499538750441E-1
+            v = 0.1912628201529828E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.3335085485472725E+0
+            b = 0.5867879341903510E-1
+            v = 0.1992499672238701E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.3709561760636381E+0
+            b = 0.8961099205022284E-1
+            v = 0.2061275533454027E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4074722861667498E+0
+            b = 0.1211627927626297E+0
+            v = 0.2119318215968572E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4429923648839117E+0
+            b = 0.1530748903554898E+0
+            v = 0.2167416581882652E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4774428052721736E+0
+            b = 0.1851176436721877E+0
+            v = 0.2206430730516600E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5107446539535904E+0
+            b = 0.2170829107658179E+0
+            v = 0.2237186938699523E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5428151370542935E+0
+            b = 0.2487786689026271E+0
+            v = 0.2260480075032884E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5735699292556964E+0
+            b = 0.2800239952795016E+0
+            v = 0.2277098884558542E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.6029253794562866E+0
+            b = 0.3106445702878119E+0
+            v = 0.2287845715109671E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.6307998987073145E+0
+            b = 0.3404689500841194E+0
+            v = 0.2293547268236294E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.3752652273692719E+0
+            b = 0.2997145098184479E-1
+            v = 0.2056073839852528E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4135383879344028E+0
+            b = 0.6086725898678011E-1
+            v = 0.2114235865831876E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4506113885153907E+0
+            b = 0.9238849548435643E-1
+            v = 0.2163175629770551E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4864401554606072E+0
+            b = 0.1242786603851851E+0
+            v = 0.2203392158111650E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5209708076611709E+0
+            b = 0.1563086731483386E+0
+            v = 0.2235473176847839E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5541422135830122E+0
+            b = 0.1882696509388506E+0
+            v = 0.2260024141501235E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5858880915113817E+0
+            b = 0.2199672979126059E+0
+            v = 0.2277675929329182E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.6161399390603444E+0
+            b = 0.2512165482924867E+0
+            v = 0.2289102112284834E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.6448296482255090E+0
+            b = 0.2818368701871888E+0
+            v = 0.2295027954625118E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4544796274917948E+0
+            b = 0.3088970405060312E-1
+            v = 0.2161281589879992E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4919389072146628E+0
+            b = 0.6240947677636835E-1
+            v = 0.2201980477395102E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5279313026985183E+0
+            b = 0.9430706144280313E-1
+            v = 0.2234952066593166E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5624169925571135E+0
+            b = 0.1263547818770374E+0
+            v = 0.2260540098520838E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5953484627093287E+0
+            b = 0.1583430788822594E+0
+            v = 0.2279157981899988E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.6266730715339185E+0
+            b = 0.1900748462555988E+0
+            v = 0.2291296918565571E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.6563363204278871E+0
+            b = 0.2213599519592567E+0
+            v = 0.2297533752536649E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5314574716585696E+0
+            b = 0.3152508811515374E-1
+            v = 0.2234927356465995E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5674614932298185E+0
+            b = 0.6343865291465561E-1
+            v = 0.2261288012985219E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.6017706004970264E+0
+            b = 0.9551503504223951E-1
+            v = 0.2280818160923688E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.6343471270264178E+0
+            b = 0.1275440099801196E+0
+            v = 0.2293773295180159E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.6651494599127802E+0
+            b = 0.1593252037671960E+0
+            v = 0.2300528767338634E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.6050184986005704E+0
+            b = 0.3192538338496105E-1
+            v = 0.2281893855065666E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.6390163550880400E+0
+            b = 0.6402824353962306E-1
+            v = 0.2295720444840727E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.6711199107088448E+0
+            b = 0.9609805077002909E-1
+            v = 0.2303227649026753E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.6741354429572275E+0
+            b = 0.3211853196273233E-1
+            v = 0.2304831913227114E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+
+        case 5294:
+
+            v = 0.9080510764308163E-4
+            leb_tmp, start = get_lebedev_recurrence_points(1, start, a, b, v, leb_tmp)
+            v = 0.2084824361987793E-3
+            leb_tmp, start = get_lebedev_recurrence_points(3, start, a, b, v, leb_tmp)
+            a = 0.2303261686261450E-1
+            v = 0.5011105657239616E-4
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.3757208620162394E-1
+            v = 0.5942520409683854E-4
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.5821912033821852E-1
+            v = 0.9564394826109721E-4
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.8403127529194872E-1
+            v = 0.1185530657126338E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.1122927798060578E+0
+            v = 0.1364510114230331E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.1420125319192987E+0
+            v = 0.1505828825605415E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.1726396437341978E+0
+            v = 0.1619298749867023E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.2038170058115696E+0
+            v = 0.1712450504267789E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.2352849892876508E+0
+            v = 0.1789891098164999E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.2668363354312461E+0
+            v = 0.1854474955629795E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.2982941279900452E+0
+            v = 0.1908148636673661E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.3295002922087076E+0
+            v = 0.1952377405281833E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.3603094918363593E+0
+            v = 0.1988349254282232E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.3905857895173920E+0
+            v = 0.2017079807160050E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.4202005758160837E+0
+            v = 0.2039473082709094E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.4490310061597227E+0
+            v = 0.2056360279288953E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.4769586160311491E+0
+            v = 0.2068525823066865E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.5038679887049750E+0
+            v = 0.2076724877534488E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.5296454286519961E+0
+            v = 0.2081694278237885E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.5541776207164850E+0
+            v = 0.2084157631219326E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.5990467321921213E+0
+            v = 0.2084381531128593E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.6191467096294587E+0
+            v = 0.2083476277129307E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.6375251212901849E+0
+            v = 0.2082686194459732E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.6540514381131168E+0
+            v = 0.2082475686112415E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.6685899064391510E+0
+            v = 0.2083139860289915E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.6810013009681648E+0
+            v = 0.2084745561831237E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.6911469578730340E+0
+            v = 0.2087091313375890E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.6988956915141736E+0
+            v = 0.2089718413297697E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.7041335794868720E+0
+            v = 0.2092003303479793E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.7067754398018567E+0
+            v = 0.2093336148263241E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.3840368707853623E-1
+            v = 0.7591708117365267E-4
+            leb_tmp, start = get_lebedev_recurrence_points(5, start, a, b, v, leb_tmp)
+            a = 0.9835485954117399E-1
+            v = 0.1083383968169186E-3
+            leb_tmp, start = get_lebedev_recurrence_points(5, start, a, b, v, leb_tmp)
+            a = 0.1665774947612998E+0
+            v = 0.1403019395292510E-3
+            leb_tmp, start = get_lebedev_recurrence_points(5, start, a, b, v, leb_tmp)
+            a = 0.2405702335362910E+0
+            v = 0.1615970179286436E-3
+            leb_tmp, start = get_lebedev_recurrence_points(5, start, a, b, v, leb_tmp)
+            a = 0.3165270770189046E+0
+            v = 0.1771144187504911E-3
+            leb_tmp, start = get_lebedev_recurrence_points(5, start, a, b, v, leb_tmp)
+            a = 0.3927386145645443E+0
+            v = 0.1887760022988168E-3
+            leb_tmp, start = get_lebedev_recurrence_points(5, start, a, b, v, leb_tmp)
+            a = 0.4678825918374656E+0
+            v = 0.1973474670768214E-3
+            leb_tmp, start = get_lebedev_recurrence_points(5, start, a, b, v, leb_tmp)
+            a = 0.5408022024266935E+0
+            v = 0.2033787661234659E-3
+            leb_tmp, start = get_lebedev_recurrence_points(5, start, a, b, v, leb_tmp)
+            a = 0.6104967445752438E+0
+            v = 0.2072343626517331E-3
+            leb_tmp, start = get_lebedev_recurrence_points(5, start, a, b, v, leb_tmp)
+            a = 0.6760910702685738E+0
+            v = 0.2091177834226918E-3
+            leb_tmp, start = get_lebedev_recurrence_points(5, start, a, b, v, leb_tmp)
+            a = 0.6655644120217392E-1
+            b = 0.1936508874588424E-1
+            v = 0.9316684484675566E-4
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.9446246161270182E-1
+            b = 0.4252442002115869E-1
+            v = 0.1116193688682976E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.1242651925452509E+0
+            b = 0.6806529315354374E-1
+            v = 0.1298623551559414E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.1553438064846751E+0
+            b = 0.9560957491205369E-1
+            v = 0.1450236832456426E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.1871137110542670E+0
+            b = 0.1245931657452888E+0
+            v = 0.1572719958149914E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.2192612628836257E+0
+            b = 0.1545385828778978E+0
+            v = 0.1673234785867195E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.2515682807206955E+0
+            b = 0.1851004249723368E+0
+            v = 0.1756860118725188E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.2838535866287290E+0
+            b = 0.2160182608272384E+0
+            v = 0.1826776290439367E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.3159578817528521E+0
+            b = 0.2470799012277111E+0
+            v = 0.1885116347992865E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.3477370882791392E+0
+            b = 0.2781014208986402E+0
+            v = 0.1933457860170574E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.3790576960890540E+0
+            b = 0.3089172523515731E+0
+            v = 0.1973060671902064E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4097938317810200E+0
+            b = 0.3393750055472244E+0
+            v = 0.2004987099616311E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4398256572859637E+0
+            b = 0.3693322470987730E+0
+            v = 0.2030170909281499E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4690384114718480E+0
+            b = 0.3986541005609877E+0
+            v = 0.2049461460119080E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4973216048301053E+0
+            b = 0.4272112491408562E+0
+            v = 0.2063653565200186E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5245681526132446E+0
+            b = 0.4548781735309936E+0
+            v = 0.2073507927381027E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5506733911803888E+0
+            b = 0.4815315355023251E+0
+            v = 0.2079764593256122E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5755339829522475E+0
+            b = 0.5070486445801855E+0
+            v = 0.2083150534968778E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.1305472386056362E+0
+            b = 0.2284970375722366E-1
+            v = 0.1262715121590664E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.1637327908216477E+0
+            b = 0.4812254338288384E-1
+            v = 0.1414386128545972E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.1972734634149637E+0
+            b = 0.7531734457511935E-1
+            v = 0.1538740401313898E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.2308694653110130E+0
+            b = 0.1039043639882017E+0
+            v = 0.1642434942331432E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.2643899218338160E+0
+            b = 0.1334526587117626E+0
+            v = 0.1729790609237496E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.2977171599622171E+0
+            b = 0.1636414868936382E+0
+            v = 0.1803505190260828E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.3307293903032310E+0
+            b = 0.1942195406166568E+0
+            v = 0.1865475350079657E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.3633069198219073E+0
+            b = 0.2249752879943753E+0
+            v = 0.1917182669679069E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.3953346955922727E+0
+            b = 0.2557218821820032E+0
+            v = 0.1959851709034382E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4267018394184914E+0
+            b = 0.2862897925213193E+0
+            v = 0.1994529548117882E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4573009622571704E+0
+            b = 0.3165224536636518E+0
+            v = 0.2022138911146548E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4870279559856109E+0
+            b = 0.3462730221636496E+0
+            v = 0.2043518024208592E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5157819581450322E+0
+            b = 0.3754016870282835E+0
+            v = 0.2059450313018110E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5434651666465393E+0
+            b = 0.4037733784993613E+0
+            v = 0.2070685715318472E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5699823887764627E+0
+            b = 0.4312557784139123E+0
+            v = 0.2077955310694373E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5952403350947741E+0
+            b = 0.4577175367122110E+0
+            v = 0.2081980387824712E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.2025152599210369E+0
+            b = 0.2520253617719557E-1
+            v = 0.1521318610377956E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.2381066653274425E+0
+            b = 0.5223254506119000E-1
+            v = 0.1622772720185755E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.2732823383651612E+0
+            b = 0.8060669688588620E-1
+            v = 0.1710498139420709E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.3080137692611118E+0
+            b = 0.1099335754081255E+0
+            v = 0.1785911149448736E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.3422405614587601E+0
+            b = 0.1399120955959857E+0
+            v = 0.1850125313687736E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.3758808773890420E+0
+            b = 0.1702977801651705E+0
+            v = 0.1904229703933298E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4088458383438932E+0
+            b = 0.2008799256601680E+0
+            v = 0.1949259956121987E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4410450550841152E+0
+            b = 0.2314703052180836E+0
+            v = 0.1986161545363960E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4723879420561312E+0
+            b = 0.2618972111375892E+0
+            v = 0.2015790585641370E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5027843561874343E+0
+            b = 0.2920013195600270E+0
+            v = 0.2038934198707418E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5321453674452458E+0
+            b = 0.3216322555190551E+0
+            v = 0.2056334060538251E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5603839113834030E+0
+            b = 0.3506456615934198E+0
+            v = 0.2068705959462289E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5874150706875146E+0
+            b = 0.3789007181306267E+0
+            v = 0.2076753906106002E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.6131559381660038E+0
+            b = 0.4062580170572782E+0
+            v = 0.2081179391734803E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.2778497016394506E+0
+            b = 0.2696271276876226E-1
+            v = 0.1700345216228943E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.3143733562261912E+0
+            b = 0.5523469316960465E-1
+            v = 0.1774906779990410E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.3501485810261827E+0
+            b = 0.8445193201626464E-1
+            v = 0.1839659377002642E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.3851430322303653E+0
+            b = 0.1143263119336083E+0
+            v = 0.1894987462975169E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4193013979470415E+0
+            b = 0.1446177898344475E+0
+            v = 0.1941548809452595E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4525585960458567E+0
+            b = 0.1751165438438091E+0
+            v = 0.1980078427252384E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4848447779622947E+0
+            b = 0.2056338306745660E+0
+            v = 0.2011296284744488E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5160871208276894E+0
+            b = 0.2359965487229226E+0
+            v = 0.2035888456966776E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5462112185696926E+0
+            b = 0.2660430223139146E+0
+            v = 0.2054516325352142E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5751425068101757E+0
+            b = 0.2956193664498032E+0
+            v = 0.2067831033092635E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.6028073872853596E+0
+            b = 0.3245763905312779E+0
+            v = 0.2076485320284876E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.6291338275278409E+0
+            b = 0.3527670026206972E+0
+            v = 0.2081141439525255E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.3541797528439391E+0
+            b = 0.2823853479435550E-1
+            v = 0.1834383015469222E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.3908234972074657E+0
+            b = 0.5741296374713106E-1
+            v = 0.1889540591777677E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4264408450107590E+0
+            b = 0.8724646633650199E-1
+            v = 0.1936677023597375E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4609949666553286E+0
+            b = 0.1175034422915616E+0
+            v = 0.1976176495066504E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4944389496536006E+0
+            b = 0.1479755652628428E+0
+            v = 0.2008536004560983E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5267194884346086E+0
+            b = 0.1784740659484352E+0
+            v = 0.2034280351712291E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5577787810220990E+0
+            b = 0.2088245700431244E+0
+            v = 0.2053944466027758E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5875563763536670E+0
+            b = 0.2388628136570763E+0
+            v = 0.2068077642882360E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.6159910016391269E+0
+            b = 0.2684308928769185E+0
+            v = 0.2077250949661599E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.6430219602956268E+0
+            b = 0.2973740761960252E+0
+            v = 0.2082062440705320E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4300647036213646E+0
+            b = 0.2916399920493977E-1
+            v = 0.1934374486546626E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4661486308935531E+0
+            b = 0.5898803024755659E-1
+            v = 0.1974107010484300E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5009658555287261E+0
+            b = 0.8924162698525409E-1
+            v = 0.2007129290388658E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5344824270447704E+0
+            b = 0.1197185199637321E+0
+            v = 0.2033736947471293E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5666575997416371E+0
+            b = 0.1502300756161382E+0
+            v = 0.2054287125902493E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5974457471404752E+0
+            b = 0.1806004191913564E+0
+            v = 0.2069184936818894E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.6267984444116886E+0
+            b = 0.2106621764786252E+0
+            v = 0.2078883689808782E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.6546664713575417E+0
+            b = 0.2402526932671914E+0
+            v = 0.2083886366116359E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5042711004437253E+0
+            b = 0.2982529203607657E-1
+            v = 0.2006593275470817E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5392127456774380E+0
+            b = 0.6008728062339922E-1
+            v = 0.2033728426135397E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5726819437668618E+0
+            b = 0.9058227674571398E-1
+            v = 0.2055008781377608E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.6046469254207278E+0
+            b = 0.1211219235803400E+0
+            v = 0.2070651783518502E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.6350716157434952E+0
+            b = 0.1515286404791580E+0
+            v = 0.2080953335094320E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.6639177679185454E+0
+            b = 0.1816314681255552E+0
+            v = 0.2086284998988521E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5757276040972253E+0
+            b = 0.3026991752575440E-1
+            v = 0.2055549387644668E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.6090265823139755E+0
+            b = 0.6078402297870770E-1
+            v = 0.2071871850267654E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.6406735344387661E+0
+            b = 0.9135459984176636E-1
+            v = 0.2082856600431965E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.6706397927793709E+0
+            b = 0.1218024155966590E+0
+            v = 0.2088705858819358E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.6435019674426665E+0
+            b = 0.3052608357660639E-1
+            v = 0.2083995867536322E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.6747218676375681E+0
+            b = 0.6112185773983089E-1
+            v = 0.2090509712889637E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+
+        case 5810:
+
+            v = 0.9735347946175486E-5
+            leb_tmp, start = get_lebedev_recurrence_points(1, start, a, b, v, leb_tmp)
+            v = 0.1907581241803167E-3
+            leb_tmp, start = get_lebedev_recurrence_points(2, start, a, b, v, leb_tmp)
+            v = 0.1901059546737578E-3
+            leb_tmp, start = get_lebedev_recurrence_points(3, start, a, b, v, leb_tmp)
+            a = 0.1182361662400277E-1
+            v = 0.3926424538919212E-4
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.3062145009138958E-1
+            v = 0.6667905467294382E-4
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.5329794036834243E-1
+            v = 0.8868891315019135E-4
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.7848165532862220E-1
+            v = 0.1066306000958872E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.1054038157636201E+0
+            v = 0.1214506743336128E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.1335577797766211E+0
+            v = 0.1338054681640871E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.1625769955502252E+0
+            v = 0.1441677023628504E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.1921787193412792E+0
+            v = 0.1528880200826557E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.2221340534690548E+0
+            v = 0.1602330623773609E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.2522504912791132E+0
+            v = 0.1664102653445244E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.2823610860679697E+0
+            v = 0.1715845854011323E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.3123173966267560E+0
+            v = 0.1758901000133069E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.3419847036953789E+0
+            v = 0.1794382485256736E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.3712386456999758E+0
+            v = 0.1823238106757407E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.3999627649876828E+0
+            v = 0.1846293252959976E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.4280466458648093E+0
+            v = 0.1864284079323098E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.4553844360185711E+0
+            v = 0.1877882694626914E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.4818736094437834E+0
+            v = 0.1887716321852025E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.5074138709260629E+0
+            v = 0.1894381638175673E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.5319061304570707E+0
+            v = 0.1898454899533629E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.5552514978677286E+0
+            v = 0.1900497929577815E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.5981009025246183E+0
+            v = 0.1900671501924092E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.6173990192228116E+0
+            v = 0.1899837555533510E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.6351365239411131E+0
+            v = 0.1899014113156229E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.6512010228227200E+0
+            v = 0.1898581257705106E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.6654758363948120E+0
+            v = 0.1898804756095753E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.6778410414853370E+0
+            v = 0.1899793610426402E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.6881760887484110E+0
+            v = 0.1901464554844117E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.6963645267094598E+0
+            v = 0.1903533246259542E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.7023010617153579E+0
+            v = 0.1905556158463228E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.7059004636628753E+0
+            v = 0.1907037155663528E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.3552470312472575E-1
+            v = 0.5992997844249967E-4
+            leb_tmp, start = get_lebedev_recurrence_points(5, start, a, b, v, leb_tmp)
+            a = 0.9151176620841283E-1
+            v = 0.9749059382456978E-4
+            leb_tmp, start = get_lebedev_recurrence_points(5, start, a, b, v, leb_tmp)
+            a = 0.1566197930068980E+0
+            v = 0.1241680804599158E-3
+            leb_tmp, start = get_lebedev_recurrence_points(5, start, a, b, v, leb_tmp)
+            a = 0.2265467599271907E+0
+            v = 0.1437626154299360E-3
+            leb_tmp, start = get_lebedev_recurrence_points(5, start, a, b, v, leb_tmp)
+            a = 0.2988242318581361E+0
+            v = 0.1584200054793902E-3
+            leb_tmp, start = get_lebedev_recurrence_points(5, start, a, b, v, leb_tmp)
+            a = 0.3717482419703886E+0
+            v = 0.1694436550982744E-3
+            leb_tmp, start = get_lebedev_recurrence_points(5, start, a, b, v, leb_tmp)
+            a = 0.4440094491758889E+0
+            v = 0.1776617014018108E-3
+            leb_tmp, start = get_lebedev_recurrence_points(5, start, a, b, v, leb_tmp)
+            a = 0.5145337096756642E+0
+            v = 0.1836132434440077E-3
+            leb_tmp, start = get_lebedev_recurrence_points(5, start, a, b, v, leb_tmp)
+            a = 0.5824053672860230E+0
+            v = 0.1876494727075983E-3
+            leb_tmp, start = get_lebedev_recurrence_points(5, start, a, b, v, leb_tmp)
+            a = 0.6468283961043370E+0
+            v = 0.1899906535336482E-3
+            leb_tmp, start = get_lebedev_recurrence_points(5, start, a, b, v, leb_tmp)
+            a = 0.6095964259104373E-1
+            b = 0.1787828275342931E-1
+            v = 0.8143252820767350E-4
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.8811962270959388E-1
+            b = 0.3953888740792096E-1
+            v = 0.9998859890887728E-4
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.1165936722428831E+0
+            b = 0.6378121797722990E-1
+            v = 0.1156199403068359E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.1460232857031785E+0
+            b = 0.8985890813745037E-1
+            v = 0.1287632092635513E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.1761197110181755E+0
+            b = 0.1172606510576162E+0
+            v = 0.1398378643365139E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.2066471190463718E+0
+            b = 0.1456102876970995E+0
+            v = 0.1491876468417391E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.2374076026328152E+0
+            b = 0.1746153823011775E+0
+            v = 0.1570855679175456E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.2682305474337051E+0
+            b = 0.2040383070295584E+0
+            v = 0.1637483948103775E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.2989653312142369E+0
+            b = 0.2336788634003698E+0
+            v = 0.1693500566632843E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.3294762752772209E+0
+            b = 0.2633632752654219E+0
+            v = 0.1740322769393633E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.3596390887276086E+0
+            b = 0.2929369098051601E+0
+            v = 0.1779126637278296E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.3893383046398812E+0
+            b = 0.3222592785275512E+0
+            v = 0.1810908108835412E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4184653789358347E+0
+            b = 0.3512004791195743E+0
+            v = 0.1836529132600190E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4469172319076166E+0
+            b = 0.3796385677684537E+0
+            v = 0.1856752841777379E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4745950813276976E+0
+            b = 0.4074575378263879E+0
+            v = 0.1872270566606832E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5014034601410262E+0
+            b = 0.4345456906027828E+0
+            v = 0.1883722645591307E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5272493404551239E+0
+            b = 0.4607942515205134E+0
+            v = 0.1891714324525297E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5520413051846366E+0
+            b = 0.4860961284181720E+0
+            v = 0.1896827480450146E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5756887237503077E+0
+            b = 0.5103447395342790E+0
+            v = 0.1899628417059528E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.1225039430588352E+0
+            b = 0.2136455922655793E-1
+            v = 0.1123301829001669E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.1539113217321372E+0
+            b = 0.4520926166137188E-1
+            v = 0.1253698826711277E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.1856213098637712E+0
+            b = 0.7086468177864818E-1
+            v = 0.1366266117678531E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.2174998728035131E+0
+            b = 0.9785239488772918E-1
+            v = 0.1462736856106918E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.2494128336938330E+0
+            b = 0.1258106396267210E+0
+            v = 0.1545076466685412E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.2812321562143480E+0
+            b = 0.1544529125047001E+0
+            v = 0.1615096280814007E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.3128372276456111E+0
+            b = 0.1835433512202753E+0
+            v = 0.1674366639741759E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.3441145160177973E+0
+            b = 0.2128813258619585E+0
+            v = 0.1724225002437900E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.3749567714853510E+0
+            b = 0.2422913734880829E+0
+            v = 0.1765810822987288E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4052621732015610E+0
+            b = 0.2716163748391453E+0
+            v = 0.1800104126010751E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4349335453522385E+0
+            b = 0.3007127671240280E+0
+            v = 0.1827960437331284E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4638776641524965E+0
+            b = 0.3294470677216479E+0
+            v = 0.1850140300716308E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4920046410462687E+0
+            b = 0.3576932543699155E+0
+            v = 0.1867333507394938E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5192273554861704E+0
+            b = 0.3853307059757764E+0
+            v = 0.1880178688638289E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5454609081136522E+0
+            b = 0.4122425044452694E+0
+            v = 0.1889278925654758E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5706220661424140E+0
+            b = 0.4383139587781027E+0
+            v = 0.1895213832507346E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5946286755181518E+0
+            b = 0.4634312536300553E+0
+            v = 0.1898548277397420E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.1905370790924295E+0
+            b = 0.2371311537781979E-1
+            v = 0.1349105935937341E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.2242518717748009E+0
+            b = 0.4917878059254806E-1
+            v = 0.1444060068369326E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.2577190808025936E+0
+            b = 0.7595498960495142E-1
+            v = 0.1526797390930008E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.2908724534927187E+0
+            b = 0.1036991083191100E+0
+            v = 0.1598208771406474E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.3236354020056219E+0
+            b = 0.1321348584450234E+0
+            v = 0.1659354368615331E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.3559267359304543E+0
+            b = 0.1610316571314789E+0
+            v = 0.1711279910946440E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.3876637123676956E+0
+            b = 0.1901912080395707E+0
+            v = 0.1754952725601440E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4187636705218842E+0
+            b = 0.2194384950137950E+0
+            v = 0.1791247850802529E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4491449019883107E+0
+            b = 0.2486155334763858E+0
+            v = 0.1820954300877716E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4787270932425445E+0
+            b = 0.2775768931812335E+0
+            v = 0.1844788524548449E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5074315153055574E+0
+            b = 0.3061863786591120E+0
+            v = 0.1863409481706220E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5351810507738336E+0
+            b = 0.3343144718152556E+0
+            v = 0.1877433008795068E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5619001025975381E+0
+            b = 0.3618362729028427E+0
+            v = 0.1887444543705232E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5875144035268046E+0
+            b = 0.3886297583620408E+0
+            v = 0.1894009829375006E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.6119507308734495E+0
+            b = 0.4145742277792031E+0
+            v = 0.1897683345035198E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.2619733870119463E+0
+            b = 0.2540047186389353E-1
+            v = 0.1517327037467653E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.2968149743237949E+0
+            b = 0.5208107018543989E-1
+            v = 0.1587740557483543E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.3310451504860488E+0
+            b = 0.7971828470885599E-1
+            v = 0.1649093382274097E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.3646215567376676E+0
+            b = 0.1080465999177927E+0
+            v = 0.1701915216193265E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.3974916785279360E+0
+            b = 0.1368413849366629E+0
+            v = 0.1746847753144065E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4295967403772029E+0
+            b = 0.1659073184763559E+0
+            v = 0.1784555512007570E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4608742854473447E+0
+            b = 0.1950703730454614E+0
+            v = 0.1815687562112174E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4912598858949903E+0
+            b = 0.2241721144376724E+0
+            v = 0.1840864370663302E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5206882758945558E+0
+            b = 0.2530655255406489E+0
+            v = 0.1860676785390006E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5490940914019819E+0
+            b = 0.2816118409731066E+0
+            v = 0.1875690583743703E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5764123302025542E+0
+            b = 0.3096780504593238E+0
+            v = 0.1886453236347225E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.6025786004213506E+0
+            b = 0.3371348366394987E+0
+            v = 0.1893501123329645E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.6275291964794956E+0
+            b = 0.3638547827694396E+0
+            v = 0.1897366184519868E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.3348189479861771E+0
+            b = 0.2664841935537443E-1
+            v = 0.1643908815152736E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.3699515545855295E+0
+            b = 0.5424000066843495E-1
+            v = 0.1696300350907768E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4042003071474669E+0
+            b = 0.8251992715430854E-1
+            v = 0.1741553103844483E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4375320100182624E+0
+            b = 0.1112695182483710E+0
+            v = 0.1780015282386092E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4699054490335947E+0
+            b = 0.1402964116467816E+0
+            v = 0.1812116787077125E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5012739879431952E+0
+            b = 0.1694275117584291E+0
+            v = 0.1838323158085421E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5315874883754966E+0
+            b = 0.1985038235312689E+0
+            v = 0.1859113119837737E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5607937109622117E+0
+            b = 0.2273765660020893E+0
+            v = 0.1874969220221698E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5888393223495521E+0
+            b = 0.2559041492849764E+0
+            v = 0.1886375612681076E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.6156705979160163E+0
+            b = 0.2839497251976899E+0
+            v = 0.1893819575809276E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.6412338809078123E+0
+            b = 0.3113791060500690E+0
+            v = 0.1897794748256767E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4076051259257167E+0
+            b = 0.2757792290858463E-1
+            v = 0.1738963926584846E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4423788125791520E+0
+            b = 0.5584136834984293E-1
+            v = 0.1777442359873466E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4760480917328258E+0
+            b = 0.8457772087727143E-1
+            v = 0.1810010815068719E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5085838725946297E+0
+            b = 0.1135975846359248E+0
+            v = 0.1836920318248129E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5399513637391218E+0
+            b = 0.1427286904765053E+0
+            v = 0.1858489473214328E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5701118433636380E+0
+            b = 0.1718112740057635E+0
+            v = 0.1875079342496592E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5990240530606021E+0
+            b = 0.2006944855985351E+0
+            v = 0.1887080239102310E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.6266452685139695E+0
+            b = 0.2292335090598907E+0
+            v = 0.1894905752176822E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.6529320971415942E+0
+            b = 0.2572871512353714E+0
+            v = 0.1898991061200695E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4791583834610126E+0
+            b = 0.2826094197735932E-1
+            v = 0.1809065016458791E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5130373952796940E+0
+            b = 0.5699871359683649E-1
+            v = 0.1836297121596799E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5456252429628476E+0
+            b = 0.8602712528554394E-1
+            v = 0.1858426916241869E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5768956329682385E+0
+            b = 0.1151748137221281E+0
+            v = 0.1875654101134641E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.6068186944699046E+0
+            b = 0.1442811654136362E+0
+            v = 0.1888240751833503E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.6353622248024907E+0
+            b = 0.1731930321657680E+0
+            v = 0.1896497383866979E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.6624927035731797E+0
+            b = 0.2017619958756061E+0
+            v = 0.1900775530219121E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5484933508028488E+0
+            b = 0.2874219755907391E-1
+            v = 0.1858525041478814E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5810207682142106E+0
+            b = 0.5778312123713695E-1
+            v = 0.1876248690077947E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.6120955197181352E+0
+            b = 0.8695262371439526E-1
+            v = 0.1889404439064607E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.6416944284294319E+0
+            b = 0.1160893767057166E+0
+            v = 0.1898168539265290E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.6697926391731260E+0
+            b = 0.1450378826743251E+0
+            v = 0.1902779940661772E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.6147594390585488E+0
+            b = 0.2904957622341456E-1
+            v = 0.1890125641731815E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.6455390026356783E+0
+            b = 0.5823809152617197E-1
+            v = 0.1899434637795751E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.6747258588365477E+0
+            b = 0.8740384899884715E-1
+            v = 0.1904520856831751E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.6772135750395347E+0
+            b = 0.2919946135808105E-1
+            v = 0.1905534498734563E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+
+        case _:
+            raise Exception('Angular grid unrecognized, choices are 6, 14, 26, 38, 50, 74, 86, 110, 146, 170, 194, 230, 266, 302, 350, 434, 590, 770, 974, 1202, 1454, 1730, 2030, 2354, 2702, 3074, 3470, 3890, 4334, 4802, 5294, 5810')  # noqa: E501
+
+    leb_tmp.n = degree
+    return leb_tmp
+
+
+def get_lebedev_recurrence_points(type_, start, a, b, v, leb):
+    c = 0.0
+
+    match type_:
+
+        case 1:
+            a = 1.0
+
+            leb.x[start] = a
+            leb.y[start] = 0.0
+            leb.z[start] = 0.0
+            leb.w[start] = 4.0 * pi * v
+
+            leb.x[start + 1] = -a
+            leb.y[start + 1] = 0.0
+            leb.z[start + 1] = 0.0
+            leb.w[start + 1] = 4.0 * pi * v
+
+            leb.x[start + 2] = 0.0
+            leb.y[start + 2] = a
+            leb.z[start + 2] = 0.0
+            leb.w[start + 2] = 4.0 * pi * v
+
+            leb.x[start + 3] = 0.0
+            leb.y[start + 3] = -a
+            leb.z[start + 3] = 0.0
+            leb.w[start + 3] = 4.0 * pi * v
+
+            leb.x[start + 4] = 0.0
+            leb.y[start + 4] = 0.0
+            leb.z[start + 4] = a
+            leb.w[start + 4] = 4.0 * pi * v
+
+            leb.x[start + 5] = 0.0
+            leb.y[start + 5] = 0.0
+            leb.z[start + 5] = -a
+            leb.w[start + 5] = 4.0 * pi * v
+            start = start + 6
+
+        case 2:
+            a = sqrt(0.5)
+            leb.x[start] = 0.0
+            leb.y[start] = a
+            leb.z[start] = a
+            leb.w[start] = 4.0 * pi * v
+
+            leb.x[start + 1] = 0.0
+            leb.y[start + 1] = -a
+            leb.z[start + 1] = a
+            leb.w[start + 1] = 4.0 * pi * v
+
+            leb.x[start + 2] = 0.0
+            leb.y[start + 2] = a
+            leb.z[start + 2] = -a
+            leb.w[start + 2] = 4.0 * pi * v
+
+            leb.x[start + 3] = 0.0
+            leb.y[start + 3] = -a
+            leb.z[start + 3] = -a
+            leb.w[start + 3] = 4.0 * pi * v
+
+            leb.x[start + 4] = a
+            leb.y[start + 4] = 0.0
+            leb.z[start + 4] = a
+            leb.w[start + 4] = 4.0 * pi * v
+
+            leb.x[start + 5] = a
+            leb.y[start + 5] = 0.0
+            leb.z[start + 5] = -a
+            leb.w[start + 5] = 4.0 * pi * v
+
+            leb.x[start + 6] = -a
+            leb.y[start + 6] = 0.0
+            leb.z[start + 6] = a
+            leb.w[start + 6] = 4.0 * pi * v
+
+            leb.x[start + 7] = -a
+            leb.y[start + 7] = 0.0
+            leb.z[start + 7] = -a
+            leb.w[start + 7] = 4.0 * pi * v
+
+            leb.x[start + 8] = a
+            leb.y[start + 8] = a
+            leb.z[start + 8] = 0.0
+            leb.w[start + 8] = 4.0 * pi * v
+
+            leb.x[start + 9] = -a
+            leb.y[start + 9] = a
+            leb.z[start + 9] = 0.0
+            leb.w[start + 9] = 4.0 * pi * v
+
+            leb.x[start + 10] = a
+            leb.y[start + 10] = -a
+            leb.z[start + 10] = 0.0
+            leb.w[start + 10] = 4.0 * pi * v
+
+            leb.x[start + 11] = -a
+            leb.y[start + 11] = -a
+            leb.z[start + 11] = 0.0
+            leb.w[start + 11] = 4.0 * pi * v
+            start = start + 12
+
+        case 3:
+            a = sqrt(1.0 / 3.0)
+            leb.x[start] = a
+            leb.y[start] = a
+            leb.z[start] = a
+            leb.w[start] = 4.0 * pi * v
+
+            leb.x[start + 1] = -a
+            leb.y[start + 1] = a
+            leb.z[start + 1] = a
+            leb.w[start + 1] = 4.0 * pi * v
+
+            leb.x[start + 2] = a
+            leb.y[start + 2] = -a
+            leb.z[start + 2] = a
+            leb.w[start + 2] = 4.0 * pi * v
+
+            leb.x[start + 3] = a
+            leb.y[start + 3] = a
+            leb.z[start + 3] = -a
+            leb.w[start + 3] = 4.0 * pi * v
+
+            leb.x[start + 4] = -a
+            leb.y[start + 4] = -a
+            leb.z[start + 4] = a
+            leb.w[start + 4] = 4.0 * pi * v
+
+            leb.x[start + 5] = a
+            leb.y[start + 5] = -a
+            leb.z[start + 5] = -a
+            leb.w[start + 5] = 4.0 * pi * v
+
+            leb.x[start + 6] = -a
+            leb.y[start + 6] = a
+            leb.z[start + 6] = -a
+            leb.w[start + 6] = 4.0 * pi * v
+
+            leb.x[start + 7] = -a
+            leb.y[start + 7] = -a
+            leb.z[start + 7] = -a
+            leb.w[start + 7] = 4.0 * pi * v
+            start = start + 8
+
+        case 4:
+            # /* In this case A is inputed */
+            b = sqrt(1.0 - 2.0 * a * a)
+            leb.x[start] = a
+            leb.y[start] = a
+            leb.z[start] = b
+            leb.w[start] = 4.0 * pi * v
+
+            leb.x[start + 1] = -a
+            leb.y[start + 1] = a
+            leb.z[start + 1] = b
+            leb.w[start + 1] = 4.0 * pi * v
+
+            leb.x[start + 2] = a
+            leb.y[start + 2] = -a
+            leb.z[start + 2] = b
+            leb.w[start + 2] = 4.0 * pi * v
+
+            leb.x[start + 3] = a
+            leb.y[start + 3] = a
+            leb.z[start + 3] = -b
+            leb.w[start + 3] = 4.0 * pi * v
+
+            leb.x[start + 4] = -a
+            leb.y[start + 4] = -a
+            leb.z[start + 4] = b
+            leb.w[start + 4] = 4.0 * pi * v
+
+            leb.x[start + 5] = -a
+            leb.y[start + 5] = a
+            leb.z[start + 5] = -b
+            leb.w[start + 5] = 4.0 * pi * v
+
+            leb.x[start + 6] = a
+            leb.y[start + 6] = -a
+            leb.z[start + 6] = -b
+            leb.w[start + 6] = 4.0 * pi * v
+
+            leb.x[start + 7] = -a
+            leb.y[start + 7] = -a
+            leb.z[start + 7] = -b
+            leb.w[start + 7] = 4.0 * pi * v
+
+            leb.x[start + 8] = -a
+            leb.y[start + 8] = b
+            leb.z[start + 8] = a
+            leb.w[start + 8] = 4.0 * pi * v
+
+            leb.x[start + 9] = a
+            leb.y[start + 9] = -b
+            leb.z[start + 9] = a
+            leb.w[start + 9] = 4.0 * pi * v
+
+            leb.x[start + 10] = a
+            leb.y[start + 10] = b
+            leb.z[start + 10] = -a
+            leb.w[start + 10] = 4.0 * pi * v
+
+            leb.x[start + 11] = -a
+            leb.y[start + 11] = -b
+            leb.z[start + 11] = a
+            leb.w[start + 11] = 4.0 * pi * v
+
+            leb.x[start + 12] = -a
+            leb.y[start + 12] = b
+            leb.z[start + 12] = -a
+            leb.w[start + 12] = 4.0 * pi * v
+
+            leb.x[start + 13] = a
+            leb.y[start + 13] = -b
+            leb.z[start + 13] = -a
+            leb.w[start + 13] = 4.0 * pi * v
+
+            leb.x[start + 14] = -a
+            leb.y[start + 14] = -b
+            leb.z[start + 14] = -a
+            leb.w[start + 14] = 4.0 * pi * v
+
+            leb.x[start + 15] = a
+            leb.y[start + 15] = b
+            leb.z[start + 15] = a
+            leb.w[start + 15] = 4.0 * pi * v
+
+            leb.x[start + 16] = b
+            leb.y[start + 16] = a
+            leb.z[start + 16] = a
+            leb.w[start + 16] = 4.0 * pi * v
+
+            leb.x[start + 17] = -b
+            leb.y[start + 17] = a
+            leb.z[start + 17] = a
+            leb.w[start + 17] = 4.0 * pi * v
+
+            leb.x[start + 18] = b
+            leb.y[start + 18] = -a
+            leb.z[start + 18] = a
+            leb.w[start + 18] = 4.0 * pi * v
+
+            leb.x[start + 19] = b
+            leb.y[start + 19] = a
+            leb.z[start + 19] = -a
+            leb.w[start + 19] = 4.0 * pi * v
+
+            leb.x[start + 20] = -b
+            leb.y[start + 20] = -a
+            leb.z[start + 20] = a
+            leb.w[start + 20] = 4.0 * pi * v
+
+            leb.x[start + 21] = -b
+            leb.y[start + 21] = a
+            leb.z[start + 21] = -a
+            leb.w[start + 21] = 4.0 * pi * v
+
+            leb.x[start + 22] = b
+            leb.y[start + 22] = -a
+            leb.z[start + 22] = -a
+            leb.w[start + 22] = 4.0 * pi * v
+
+            leb.x[start + 23] = -b
+            leb.y[start + 23] = -a
+            leb.z[start + 23] = -a
+            leb.w[start + 23] = 4.0 * pi * v
+            start = start + 24
+
+        case 5:
+            # /* A is inputed in this case as well*/
+            b = sqrt(1 - a * a)
+            leb.x[start] = a
+            leb.y[start] = b
+            leb.z[start] = 0.0
+            leb.w[start] = 4.0 * pi * v
+
+            leb.x[start + 1] = -a
+            leb.y[start + 1] = b
+            leb.z[start + 1] = 0.0
+            leb.w[start + 1] = 4.0 * pi * v
+
+            leb.x[start + 2] = a
+            leb.y[start + 2] = -b
+            leb.z[start + 2] = 0.0
+            leb.w[start + 2] = 4.0 * pi * v
+
+            leb.x[start + 3] = -a
+            leb.y[start + 3] = -b
+            leb.z[start + 3] = 0.0
+            leb.w[start + 3] = 4.0 * pi * v
+
+            leb.x[start + 4] = b
+            leb.y[start + 4] = a
+            leb.z[start + 4] = 0.0
+            leb.w[start + 4] = 4.0 * pi * v
+
+            leb.x[start + 5] = -b
+            leb.y[start + 5] = a
+            leb.z[start + 5] = 0.0
+            leb.w[start + 5] = 4.0 * pi * v
+
+            leb.x[start + 6] = b
+            leb.y[start + 6] = -a
+            leb.z[start + 6] = 0.0
+            leb.w[start + 6] = 4.0 * pi * v
+
+            leb.x[start + 7] = -b
+            leb.y[start + 7] = -a
+            leb.z[start + 7] = 0.0
+            leb.w[start + 7] = 4.0 * pi * v
+
+            leb.x[start + 8] = a
+            leb.y[start + 8] = 0.0
+            leb.z[start + 8] = b
+            leb.w[start + 8] = 4.0 * pi * v
+
+            leb.x[start + 9] = -a
+            leb.y[start + 9] = 0.0
+            leb.z[start + 9] = b
+            leb.w[start + 9] = 4.0 * pi * v
+
+            leb.x[start + 10] = a
+            leb.y[start + 10] = 0.0
+            leb.z[start + 10] = -b
+            leb.w[start + 10] = 4.0 * pi * v
+
+            leb.x[start + 11] = -a
+            leb.y[start + 11] = 0.0
+            leb.z[start + 11] = -b
+            leb.w[start + 11] = 4.0 * pi * v
+
+            leb.x[start + 12] = b
+            leb.y[start + 12] = 0.0
+            leb.z[start + 12] = a
+            leb.w[start + 12] = 4.0 * pi * v
+
+            leb.x[start + 13] = -b
+            leb.y[start + 13] = 0.0
+            leb.z[start + 13] = a
+            leb.w[start + 13] = 4.0 * pi * v
+
+            leb.x[start + 14] = b
+            leb.y[start + 14] = 0.0
+            leb.z[start + 14] = -a
+            leb.w[start + 14] = 4.0 * pi * v
+
+            leb.x[start + 15] = -b
+            leb.y[start + 15] = 0.0
+            leb.z[start + 15] = -a
+            leb.w[start + 15] = 4.0 * pi * v
+
+            leb.x[start + 16] = 0.0
+            leb.y[start + 16] = a
+            leb.z[start + 16] = b
+            leb.w[start + 16] = 4.0 * pi * v
+
+            leb.x[start + 17] = 0.0
+            leb.y[start + 17] = -a
+            leb.z[start + 17] = b
+            leb.w[start + 17] = 4.0 * pi * v
+
+            leb.x[start + 18] = 0.0
+            leb.y[start + 18] = a
+            leb.z[start + 18] = -b
+            leb.w[start + 18] = 4.0 * pi * v
+
+            leb.x[start + 19] = 0.0
+            leb.y[start + 19] = -a
+            leb.z[start + 19] = -b
+            leb.w[start + 19] = 4.0 * pi * v
+
+            leb.x[start + 20] = 0.0
+            leb.y[start + 20] = b
+            leb.z[start + 20] = a
+            leb.w[start + 20] = 4.0 * pi * v
+
+            leb.x[start + 21] = 0.0
+            leb.y[start + 21] = -b
+            leb.z[start + 21] = a
+            leb.w[start + 21] = 4.0 * pi * v
+
+            leb.x[start + 22] = 0.0
+            leb.y[start + 22] = b
+            leb.z[start + 22] = -a
+            leb.w[start + 22] = 4.0 * pi * v
+
+            leb.x[start + 23] = 0.0
+            leb.y[start + 23] = -b
+            leb.z[start + 23] = -a
+            leb.w[start + 23] = 4.0 * pi * v
+            start = start + 24
+
+        case 6:
+            # /* both A and B are inputed in this case */
+            c = sqrt(1.0 - a * a - b * b)
+            leb.x[start] = a
+            leb.y[start] = b
+            leb.z[start] = c
+            leb.w[start] = 4.0 * pi * v
+
+            leb.x[start + 1] = -a
+            leb.y[start + 1] = b
+            leb.z[start + 1] = c
+            leb.w[start + 1] = 4.0 * pi * v
+
+            leb.x[start + 2] = a
+            leb.y[start + 2] = -b
+            leb.z[start + 2] = c
+            leb.w[start + 2] = 4.0 * pi * v
+
+            leb.x[start + 3] = a
+            leb.y[start + 3] = b
+            leb.z[start + 3] = -c
+            leb.w[start + 3] = 4.0 * pi * v
+
+            leb.x[start + 4] = -a
+            leb.y[start + 4] = -b
+            leb.z[start + 4] = c
+            leb.w[start + 4] = 4.0 * pi * v
+
+            leb.x[start + 5] = a
+            leb.y[start + 5] = -b
+            leb.z[start + 5] = -c
+            leb.w[start + 5] = 4.0 * pi * v
+
+            leb.x[start + 6] = -a
+            leb.y[start + 6] = b
+            leb.z[start + 6] = -c
+            leb.w[start + 6] = 4.0 * pi * v
+
+            leb.x[start + 7] = -a
+            leb.y[start + 7] = -b
+            leb.z[start + 7] = -c
+            leb.w[start + 7] = 4.0 * pi * v
+
+            leb.x[start + 8] = b
+            leb.y[start + 8] = a
+            leb.z[start + 8] = c
+            leb.w[start + 8] = 4.0 * pi * v
+
+            leb.x[start + 9] = -b
+            leb.y[start + 9] = a
+            leb.z[start + 9] = c
+            leb.w[start + 9] = 4.0 * pi * v
+
+            leb.x[start + 10] = b
+            leb.y[start + 10] = -a
+            leb.z[start + 10] = c
+            leb.w[start + 10] = 4.0 * pi * v
+
+            leb.x[start + 11] = b
+            leb.y[start + 11] = a
+            leb.z[start + 11] = -c
+            leb.w[start + 11] = 4.0 * pi * v
+
+            leb.x[start + 12] = -b
+            leb.y[start + 12] = -a
+            leb.z[start + 12] = c
+            leb.w[start + 12] = 4.0 * pi * v
+
+            leb.x[start + 13] = b
+            leb.y[start + 13] = -a
+            leb.z[start + 13] = -c
+            leb.w[start + 13] = 4.0 * pi * v
+
+            leb.x[start + 14] = -b
+            leb.y[start + 14] = a
+            leb.z[start + 14] = -c
+            leb.w[start + 14] = 4.0 * pi * v
+
+            leb.x[start + 15] = -b
+            leb.y[start + 15] = -a
+            leb.z[start + 15] = -c
+            leb.w[start + 15] = 4.0 * pi * v
+
+            leb.x[start + 16] = c
+            leb.y[start + 16] = a
+            leb.z[start + 16] = b
+            leb.w[start + 16] = 4.0 * pi * v
+
+            leb.x[start + 17] = -c
+            leb.y[start + 17] = a
+            leb.z[start + 17] = b
+            leb.w[start + 17] = 4.0 * pi * v
+
+            leb.x[start + 18] = c
+            leb.y[start + 18] = -a
+            leb.z[start + 18] = b
+            leb.w[start + 18] = 4.0 * pi * v
+
+            leb.x[start + 19] = c
+            leb.y[start + 19] = a
+            leb.z[start + 19] = -b
+            leb.w[start + 19] = 4.0 * pi * v
+
+            leb.x[start + 20] = -c
+            leb.y[start + 20] = -a
+            leb.z[start + 20] = b
+            leb.w[start + 20] = 4.0 * pi * v
+
+            leb.x[start + 21] = c
+            leb.y[start + 21] = -a
+            leb.z[start + 21] = -b
+            leb.w[start + 21] = 4.0 * pi * v
+
+            leb.x[start + 22] = -c
+            leb.y[start + 22] = a
+            leb.z[start + 22] = -b
+            leb.w[start + 22] = 4.0 * pi * v
+
+            leb.x[start + 23] = -c
+            leb.y[start + 23] = -a
+            leb.z[start + 23] = -b
+            leb.w[start + 23] = 4.0 * pi * v
+
+            leb.x[start + 24] = c
+            leb.y[start + 24] = b
+            leb.z[start + 24] = a
+            leb.w[start + 24] = 4.0 * pi * v
+
+            leb.x[start + 25] = -c
+            leb.y[start + 25] = b
+            leb.z[start + 25] = a
+            leb.w[start + 25] = 4.0 * pi * v
+
+            leb.x[start + 26] = c
+            leb.y[start + 26] = -b
+            leb.z[start + 26] = a
+            leb.w[start + 26] = 4.0 * pi * v
+
+            leb.x[start + 27] = c
+            leb.y[start + 27] = b
+            leb.z[start + 27] = -a
+            leb.w[start + 27] = 4.0 * pi * v
+
+            leb.x[start + 28] = -c
+            leb.y[start + 28] = -b
+            leb.z[start + 28] = a
+            leb.w[start + 28] = 4.0 * pi * v
+
+            leb.x[start + 29] = c
+            leb.y[start + 29] = -b
+            leb.z[start + 29] = -a
+            leb.w[start + 29] = 4.0 * pi * v
+
+            leb.x[start + 30] = -c
+            leb.y[start + 30] = b
+            leb.z[start + 30] = -a
+            leb.w[start + 30] = 4.0 * pi * v
+
+            leb.x[start + 31] = -c
+            leb.y[start + 31] = -b
+            leb.z[start + 31] = -a
+            leb.w[start + 31] = 4.0 * pi * v
+
+            leb.x[start + 32] = a
+            leb.y[start + 32] = c
+            leb.z[start + 32] = b
+            leb.w[start + 32] = 4.0 * pi * v
+
+            leb.x[start + 33] = -a
+            leb.y[start + 33] = c
+            leb.z[start + 33] = b
+            leb.w[start + 33] = 4.0 * pi * v
+
+            leb.x[start + 34] = a
+            leb.y[start + 34] = -c
+            leb.z[start + 34] = b
+            leb.w[start + 34] = 4.0 * pi * v
+
+            leb.x[start + 35] = a
+            leb.y[start + 35] = c
+            leb.z[start + 35] = -b
+            leb.w[start + 35] = 4.0 * pi * v
+
+            leb.x[start + 36] = -a
+            leb.y[start + 36] = -c
+            leb.z[start + 36] = b
+            leb.w[start + 36] = 4.0 * pi * v
+
+            leb.x[start + 37] = a
+            leb.y[start + 37] = -c
+            leb.z[start + 37] = -b
+            leb.w[start + 37] = 4.0 * pi * v
+
+            leb.x[start + 38] = -a
+            leb.y[start + 38] = c
+            leb.z[start + 38] = -b
+            leb.w[start + 38] = 4.0 * pi * v
+
+            leb.x[start + 39] = -a
+            leb.y[start + 39] = -c
+            leb.z[start + 39] = -b
+            leb.w[start + 39] = 4.0 * pi * v
+
+            leb.x[start + 40] = b
+            leb.y[start + 40] = c
+            leb.z[start + 40] = a
+            leb.w[start + 40] = 4.0 * pi * v
+
+            leb.x[start + 41] = -b
+            leb.y[start + 41] = c
+            leb.z[start + 41] = a
+            leb.w[start + 41] = 4.0 * pi * v
+
+            leb.x[start + 42] = b
+            leb.y[start + 42] = -c
+            leb.z[start + 42] = a
+            leb.w[start + 42] = 4.0 * pi * v
+
+            leb.x[start + 43] = b
+            leb.y[start + 43] = c
+            leb.z[start + 43] = -a
+            leb.w[start + 43] = 4.0 * pi * v
+
+            leb.x[start + 44] = -b
+            leb.y[start + 44] = -c
+            leb.z[start + 44] = a
+            leb.w[start + 44] = 4.0 * pi * v
+
+            leb.x[start + 45] = b
+            leb.y[start + 45] = -c
+            leb.z[start + 45] = -a
+            leb.w[start + 45] = 4.0 * pi * v
+
+            leb.x[start + 46] = -b
+            leb.y[start + 46] = c
+            leb.z[start + 46] = -a
+            leb.w[start + 46] = 4.0 * pi * v
+
+            leb.x[start + 47] = -b
+            leb.y[start + 47] = -c
+            leb.z[start + 47] = -a
+            leb.w[start + 47] = 4.0 * pi * v
+            start = start + 48
+
+        case _:
+            raise Exception('Bad grid order')
+
+    return leb, start
+
+
+@xp_capabilities(np_only=True)
+def lebedev_rule(n):
+    r"""Lebedev quadrature.
+
+    Compute the sample points and weights for Lebedev quadrature [1]_
+    for integration of a function over the surface of a unit sphere.
+
+    Parameters
+    ----------
+    n : int
+        Quadrature order. See Notes for supported values.
+
+    Returns
+    -------
+    x : ndarray of shape ``(3, m)``
+        Sample points on the unit sphere in Cartesian coordinates.
+        ``m`` is the "degree" corresponding with the specified order; see Notes.
+    w : ndarray of shape ``(m,)``
+        Weights
+
+    Notes
+    -----
+    Implemented by translating the Matlab code of [2]_ to Python.
+
+    The available orders (argument `n`) are::
+
+        3, 5, 7, 9, 11, 13, 15, 17,
+        19, 21, 23, 25, 27, 29, 31, 35,
+        41, 47, 53, 59, 65, 71, 77, 83,
+        89, 95, 101, 107, 113, 119, 125, 131
+
+    The corresponding degrees ``m`` are::
+
+        6, 14, 26, 38, 50, 74, 86, 110,
+        146, 170, 194, 230, 266, 302, 350, 434,
+        590, 770, 974, 1202, 1454, 1730, 2030, 2354,
+        2702, 3074, 3470, 3890, 4334, 4802, 5294, 5810
+
+    References
+    ----------
+    .. [1] V.I. Lebedev, and D.N. Laikov. "A quadrature formula for the sphere of
+           the 131st algebraic order of accuracy". Doklady Mathematics, Vol. 59,
+           No. 3, 1999, pp. 477-481.
+    .. [2] R. Parrish. ``getLebedevSphere``. Matlab Central File Exchange.
+           https://www.mathworks.com/matlabcentral/fileexchange/27097-getlebedevsphere.
+    .. [3] Bellet, Jean-Baptiste, Matthieu Brachet, and Jean-Pierre Croisille.
+           "Quadrature and symmetry on the Cubed Sphere." Journal of Computational and
+           Applied Mathematics 409 (2022): 114142. :doi:`10.1016/j.cam.2022.114142`.
+
+    Examples
+    --------
+    An example given in [3]_ is integration of :math:`f(x, y, z) = \exp(x)` over a
+    sphere of radius :math:`1`; the reference there is ``14.7680137457653``.
+    Show the convergence to the expected result as the order increases:
+
+    >>> import matplotlib.pyplot as plt
+    >>> import numpy as np
+    >>> from scipy.integrate import lebedev_rule
+    >>>
+    >>> def f(x):
+    ...     return np.exp(x[0])
+    >>>
+    >>> res = []
+    >>> orders = np.arange(3, 20, 2)
+    >>> for n in orders:
+    ...     x, w = lebedev_rule(n)
+    ...     res.append(w @ f(x))
+    >>>
+    >>> ref = np.full_like(res, 14.7680137457653)
+    >>> err = abs(res - ref)/abs(ref)
+    >>> plt.semilogy(orders, err)
+    >>> plt.xlabel('order $n$')
+    >>> plt.ylabel('relative error')
+    >>> plt.title(r'Convergence for $f(x, y, z) = \exp(x)$')
+    >>> plt.show()
+
+    """
+    degree = [6, 14, 26, 38, 50, 74, 86, 110, 146, 170, 194, 230, 266, 302, 350,
+              434, 590, 770, 974, 1202, 1454, 1730, 2030, 2354, 2702, 3074, 3470,
+              3890, 4334, 4802, 5294, 5810]
+    order = [3, 5, 7, 9, 11, 13, 15, 17, 19, 21, 23, 25, 27, 29, 31, 35, 41, 47,
+             53, 59, 65, 71, 77, 83, 89, 95, 101, 107, 113, 119, 125, 131]
+    order_degree_map = dict(zip(order, degree))
+
+    if n not in order_degree_map:
+        message = f"Order {n=} not available. Available orders are {order}."
+        raise NotImplementedError(message)
+
+    degree = order_degree_map[n]
+    res = get_lebedev_sphere(degree)
+    x = np.stack((res.x, res.y, res.z))
+    w = res.w
+
+    return x, w
diff --git a/.venv/lib/python3.12/site-packages/scipy/integrate/_ode.py b/.venv/lib/python3.12/site-packages/scipy/integrate/_ode.py
new file mode 100644
index 0000000000000000000000000000000000000000..ff2f367fbceb98ba37490bc6c7930b66d760abce
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/integrate/_ode.py
@@ -0,0 +1,1411 @@
+# Authors: Pearu Peterson, Pauli Virtanen, John Travers
+"""
+First-order ODE integrators.
+
+User-friendly interface to various numerical integrators for solving a
+system of first order ODEs with prescribed initial conditions::
+
+    d y(t)[i]
+    ---------  = f(t,y(t))[i],
+       d t
+
+    y(t=0)[i] = y0[i],
+
+where::
+
+    i = 0, ..., len(y0) - 1
+
+class ode
+---------
+
+A generic interface class to numeric integrators. It has the following
+methods::
+
+    integrator = ode(f, jac=None)
+    integrator = integrator.set_integrator(name, **params)
+    integrator = integrator.set_initial_value(y0, t0=0.0)
+    integrator = integrator.set_f_params(*args)
+    integrator = integrator.set_jac_params(*args)
+    y1 = integrator.integrate(t1, step=False, relax=False)
+    flag = integrator.successful()
+
+class complex_ode
+-----------------
+
+This class has the same generic interface as ode, except it can handle complex
+f, y and Jacobians by transparently translating them into the equivalent
+real-valued system. It supports the real-valued solvers (i.e., not zvode) and is
+an alternative to ode with the zvode solver, sometimes performing better.
+"""
+# XXX: Integrators must have:
+# ===========================
+# cvode - C version of vode and vodpk with many improvements.
+#   Get it from http://www.netlib.org/ode/cvode.tar.gz.
+#   To wrap cvode to Python, one must write the extension module by
+#   hand. Its interface is too much 'advanced C' that using f2py
+#   would be too complicated (or impossible).
+#
+# How to define a new integrator:
+# ===============================
+#
+# class myodeint(IntegratorBase):
+#
+#     runner =  or None
+#
+#     def __init__(self,...):                           # required
+#         
+#
+#     def reset(self,n,has_jac):                        # optional
+#         # n - the size of the problem (number of equations)
+#         # has_jac - whether user has supplied its own routine for Jacobian
+#         
+#
+#     def run(self,f,jac,y0,t0,t1,f_params,jac_params): # required
+#         # this method is called to integrate from t=t0 to t=t1
+#         # with initial condition y0. f and jac are user-supplied functions
+#         # that define the problem. f_params,jac_params are additional
+#         # arguments
+#         # to these functions.
+#         
+#         if :
+#             self.success = 0
+#         return t1,y1
+#
+#     # In addition, one can define step() and run_relax() methods (they
+#     # take the same arguments as run()) if the integrator can support
+#     # these features (see IntegratorBase doc strings).
+#
+# if myodeint.runner:
+#     IntegratorBase.integrator_classes.append(myodeint)
+
+__all__ = ['ode', 'complex_ode']
+
+import re
+import types
+import warnings
+
+import numpy as np
+from numpy import asarray, array, zeros, isscalar, real, imag
+
+from scipy.linalg.blas import HAS_ILP64
+
+from . import _vode
+from . import _dop
+from ._odepack import lsoda as lsoda_step
+
+_iwork_dtype = np.int64 if HAS_ILP64 else np.int32
+
+# ------------------------------------------------------------------------------
+# User interface
+# ------------------------------------------------------------------------------
+
+
+class ode:
+    """
+    A generic interface class to numeric integrators.
+
+    Solve an equation system :math:`y'(t) = f(t,y)` with (optional) ``jac = df/dy``.
+
+    *Note*: The first two arguments of ``f(t, y, ...)`` are in the
+    opposite order of the arguments in the system definition function used
+    by `scipy.integrate.odeint`.
+
+    Parameters
+    ----------
+    f : callable ``f(t, y, *f_args)``
+        Right-hand side of the differential equation. t is a scalar,
+        ``y.shape == (n,)``.
+        ``f_args`` is set by calling ``set_f_params(*args)``.
+        `f` should return a scalar, array or list (not a tuple).
+    jac : callable ``jac(t, y, *jac_args)``, optional
+        Jacobian of the right-hand side, ``jac[i,j] = d f[i] / d y[j]``.
+        ``jac_args`` is set by calling ``set_jac_params(*args)``.
+
+    Attributes
+    ----------
+    t : float
+        Current time.
+    y : ndarray
+        Current variable values.
+
+    See Also
+    --------
+    odeint : an integrator with a simpler interface based on lsoda from ODEPACK
+    quad : for finding the area under a curve
+
+    Notes
+    -----
+    Available integrators are listed below. They can be selected using
+    the `set_integrator` method.
+
+    "vode"
+
+        Real-valued Variable-coefficient Ordinary Differential Equation
+        solver, with fixed-leading-coefficient implementation. It provides
+        implicit Adams method (for non-stiff problems) and a method based on
+        backward differentiation formulas (BDF) (for stiff problems).
+
+        Source: http://www.netlib.org/ode/vode.f
+
+        This integrator accepts the following parameters in `set_integrator`
+        method of the `ode` class:
+
+        - atol : float or sequence
+          absolute tolerance for solution
+        - rtol : float or sequence
+          relative tolerance for solution
+        - lband : None or int
+        - uband : None or int
+          Jacobian band width, jac[i,j] != 0 for i-lband <= j <= i+uband.
+          Setting these requires your jac routine to return the jacobian
+          in packed format, jac_packed[i-j+uband, j] = jac[i,j]. The
+          dimension of the matrix must be (lband+uband+1, len(y)).
+        - method: 'adams' or 'bdf'
+          Which solver to use, Adams (non-stiff) or BDF (stiff)
+        - with_jacobian : bool
+          This option is only considered when the user has not supplied a
+          Jacobian function and has not indicated (by setting either band)
+          that the Jacobian is banded. In this case, `with_jacobian` specifies
+          whether the iteration method of the ODE solver's correction step is
+          chord iteration with an internally generated full Jacobian or
+          functional iteration with no Jacobian.
+        - nsteps : int
+          Maximum number of (internally defined) steps allowed during one
+          call to the solver.
+        - first_step : float
+        - min_step : float
+        - max_step : float
+          Limits for the step sizes used by the integrator.
+        - order : int
+          Maximum order used by the integrator,
+          order <= 12 for Adams, <= 5 for BDF.
+
+    "zvode"
+
+        Complex-valued Variable-coefficient Ordinary Differential Equation
+        solver, with fixed-leading-coefficient implementation. It provides
+        implicit Adams method (for non-stiff problems) and a method based on
+        backward differentiation formulas (BDF) (for stiff problems).
+
+        Source: http://www.netlib.org/ode/zvode.f
+
+        This integrator accepts the same parameters in `set_integrator`
+        as the "vode" solver.
+
+        .. note::
+
+            When using ZVODE for a stiff system, it should only be used for
+            the case in which the function f is analytic, that is, when each f(i)
+            is an analytic function of each y(j). Analyticity means that the
+            partial derivative df(i)/dy(j) is a unique complex number, and this
+            fact is critical in the way ZVODE solves the dense or banded linear
+            systems that arise in the stiff case. For a complex stiff ODE system
+            in which f is not analytic, ZVODE is likely to have convergence
+            failures, and for this problem one should instead use DVODE on the
+            equivalent real system (in the real and imaginary parts of y).
+
+    "lsoda"
+
+        Real-valued Variable-coefficient Ordinary Differential Equation
+        solver, with fixed-leading-coefficient implementation. It provides
+        automatic method switching between implicit Adams method (for non-stiff
+        problems) and a method based on backward differentiation formulas (BDF)
+        (for stiff problems).
+
+        This integrator uses the C translation of the original Fortran 77 ODEPACK
+        library, which can be found at http://www.netlib.org/odepack
+
+        This integrator accepts the following parameters in `set_integrator`
+        method of the `ode` class:
+
+        - atol : float or sequence
+          absolute tolerance for solution
+        - rtol : float or sequence
+          relative tolerance for solution
+        - lband : None or int
+        - uband : None or int
+          Jacobian band width, jac[i,j] != 0 for i-lband <= j <= i+uband.
+          Setting these requires your jac routine to return the jacobian
+          in packed format, jac_packed[i-j+uband, j] = jac[i,j].
+        - with_jacobian : bool
+          *Not used.*
+        - nsteps : int
+          Maximum number of (internally defined) steps allowed during one
+          call to the solver.
+        - first_step : float
+        - min_step : float
+        - max_step : float
+          Limits for the step sizes used by the integrator.
+        - max_order_ns : int
+          Maximum order used in the nonstiff case (default 12).
+        - max_order_s : int
+          Maximum order used in the stiff case (default 5).
+        - max_hnil : int
+          Maximum number of messages reporting too small step size (t + h = t)
+          (default 0)
+        - ixpr : int
+          Whether to generate extra printing at method switches (default False).
+
+    "dopri5"
+
+        This is an explicit runge-kutta method of order (4)5 due to Dormand &
+        Prince (with stepsize control and dense output).
+
+        Authors:
+
+            E. Hairer and G. Wanner
+            Universite de Geneve, Dept. de Mathematiques
+            CH-1211 Geneve 24, Switzerland
+            e-mail:  ernst.hairer@math.unige.ch, gerhard.wanner@math.unige.ch
+
+        This code is described in [HNW93]_.
+
+        This integrator accepts the following parameters in set_integrator()
+        method of the ode class:
+
+        - atol : float or sequence
+          absolute tolerance for solution
+        - rtol : float or sequence
+          relative tolerance for solution
+        - nsteps : int
+          Maximum number of (internally defined) steps allowed during one
+          call to the solver.
+        - first_step : float
+        - max_step : float
+        - safety : float
+          Safety factor on new step selection (default 0.9)
+        - ifactor : float
+        - dfactor : float
+          Maximum factor to increase/decrease step size by in one step
+        - beta : float
+          Beta parameter for stabilised step size control.
+        - verbosity : int
+          Switch for printing messages (< 0 for no messages).
+
+    "dop853"
+
+        This is an explicit runge-kutta method of order 8(5,3) due to Dormand
+        & Prince (with stepsize control and dense output).
+
+        Options and references the same as "dopri5".
+
+    References
+    ----------
+    .. [HNW93] E. Hairer, S.P. Norsett and G. Wanner, Solving Ordinary
+        Differential Equations i. Nonstiff Problems. 2nd edition.
+        Springer Series in Computational Mathematics,
+        Springer-Verlag (1993)
+
+    Examples
+    --------
+
+    A problem to integrate and the corresponding jacobian:
+
+    >>> from scipy.integrate import ode
+    >>>
+    >>> y0, t0 = [1.0j, 2.0], 0
+    >>>
+    >>> def f(t, y, arg1):
+    ...     return [1j*arg1*y[0] + y[1], -arg1*y[1]**2]
+    >>> def jac(t, y, arg1):
+    ...     return [[1j*arg1, 1], [0, -arg1*2*y[1]]]
+
+    The integration:
+
+    >>> r = ode(f, jac).set_integrator('zvode', method='bdf')
+    >>> r.set_initial_value(y0, t0).set_f_params(2.0).set_jac_params(2.0)
+    >>> t1 = 10
+    >>> dt = 1
+    >>> while r.successful() and r.t < t1:
+    ...     print(r.t+dt, r.integrate(r.t+dt))
+    1 [-0.71038232+0.23749653j  0.40000271+0.j        ]
+    2.0 [0.19098503-0.52359246j 0.22222356+0.j        ]
+    3.0 [0.47153208+0.52701229j 0.15384681+0.j        ]
+    4.0 [-0.61905937+0.30726255j  0.11764744+0.j        ]
+    5.0 [0.02340997-0.61418799j 0.09523835+0.j        ]
+    6.0 [0.58643071+0.339819j 0.08000018+0.j      ]
+    7.0 [-0.52070105+0.44525141j  0.06896565+0.j        ]
+    8.0 [-0.15986733-0.61234476j  0.06060616+0.j        ]
+    9.0 [0.64850462+0.15048982j 0.05405414+0.j        ]
+    10.0 [-0.38404699+0.56382299j  0.04878055+0.j        ]
+    """
+
+    # generic type compatibility with scipy-stubs
+    __class_getitem__: classmethod = classmethod(types.GenericAlias)
+
+    def __init__(self, f, jac=None):
+        self.stiff = 0
+        self.f = f
+        self.jac = jac
+        self.f_params = ()
+        self.jac_params = ()
+        self._y = []
+
+    @property
+    def y(self):
+        return self._y
+
+    def set_initial_value(self, y, t=0.0):
+        """Set initial conditions y(t) = y."""
+        if isscalar(y):
+            y = [y]
+        n_prev = len(self._y)
+        if not n_prev:
+            self.set_integrator('')  # find first available integrator
+        # NOTE: The C code modifies y in place, hence the copy.
+        self._y = asarray(y, self._integrator.scalar).copy()
+        self.t = t
+        self._integrator.reset(len(self._y), self.jac is not None)
+        return self
+
+    def set_integrator(self, name, **integrator_params):
+        """
+        Set integrator by name.
+
+        Parameters
+        ----------
+        name : str
+            Name of the integrator.
+        **integrator_params
+            Additional parameters for the integrator.
+        """
+        integrator = find_integrator(name)
+        if integrator is None:
+            # FIXME: this really should be raise an exception. Will that break
+            # any code?
+            message = f'No integrator name match with {name!r} or is not available.'
+            warnings.warn(message, stacklevel=2)
+        else:
+            self._integrator = integrator(**integrator_params)
+            if not len(self._y):
+                self.t = 0.0
+                self._y = array([0.0], self._integrator.scalar)
+            self._integrator.reset(len(self._y), self.jac is not None)
+        return self
+
+    def integrate(self, t, step=False, relax=False):
+        """Find y=y(t), set y as an initial condition, and return y.
+
+        Parameters
+        ----------
+        t : float
+            The endpoint of the integration step.
+        step : bool
+            If True, and if the integrator supports the step method,
+            then perform a single integration step and return.
+            This parameter is provided in order to expose internals of
+            the implementation, and should not be changed from its default
+            value in most cases.
+        relax : bool
+            If True and if the integrator supports the run_relax method,
+            then integrate until t_1 >= t and return. ``relax`` is not
+            referenced if ``step=True``.
+            This parameter is provided in order to expose internals of
+            the implementation, and should not be changed from its default
+            value in most cases.
+
+        Returns
+        -------
+        y : float
+            The integrated value at t
+        """
+        if step and self._integrator.supports_step:
+            mth = self._integrator.step
+        elif relax and self._integrator.supports_run_relax:
+            mth = self._integrator.run_relax
+        else:
+            mth = self._integrator.run
+
+        try:
+            self._y, self.t = mth(self.f, self.jac or (lambda: None),
+                                  self._y, self.t, t,
+                                  self.f_params, self.jac_params)
+        except SystemError as e:
+            # f2py issue with tuple returns, see ticket 1187.
+            raise ValueError(
+                'Function to integrate must not return a tuple.'
+            ) from e
+
+        return self._y
+
+    def successful(self):
+        """Check if integration was successful."""
+        try:
+            self._integrator
+        except AttributeError:
+            self.set_integrator('')
+        return self._integrator.success == 1
+
+    def get_return_code(self):
+        """Extracts the return code for the integration to enable better control
+        if the integration fails.
+
+        In general, a return code > 0 implies success, while a return code < 0
+        implies failure.
+
+        Notes
+        -----
+        This section describes possible return codes and their meaning, for available
+        integrators that can be selected by `set_integrator` method.
+
+        "vode"
+
+        ===========  =======
+        Return Code  Message
+        ===========  =======
+        2            Integration successful.
+        -1           Excess work done on this call. (Perhaps wrong MF.)
+        -2           Excess accuracy requested. (Tolerances too small.)
+        -3           Illegal input detected. (See printed message.)
+        -4           Repeated error test failures. (Check all input.)
+        -5           Repeated convergence failures. (Perhaps bad Jacobian
+                     supplied or wrong choice of MF or tolerances.)
+        -6           Error weight became zero during problem. (Solution
+                     component i vanished, and ATOL or ATOL(i) = 0.)
+        ===========  =======
+
+        "zvode"
+
+        ===========  =======
+        Return Code  Message
+        ===========  =======
+        2            Integration successful.
+        -1           Excess work done on this call. (Perhaps wrong MF.)
+        -2           Excess accuracy requested. (Tolerances too small.)
+        -3           Illegal input detected. (See printed message.)
+        -4           Repeated error test failures. (Check all input.)
+        -5           Repeated convergence failures. (Perhaps bad Jacobian
+                     supplied or wrong choice of MF or tolerances.)
+        -6           Error weight became zero during problem. (Solution
+                     component i vanished, and ATOL or ATOL(i) = 0.)
+        ===========  =======
+
+        "dopri5"
+
+        ===========  =======
+        Return Code  Message
+        ===========  =======
+        1            Integration successful.
+        2            Integration successful (interrupted by solout).
+        -1           Input is not consistent.
+        -2           Larger nsteps is needed.
+        -3           Step size becomes too small.
+        -4           Problem is probably stiff (interrupted).
+        ===========  =======
+
+        "dop853"
+
+        ===========  =======
+        Return Code  Message
+        ===========  =======
+        1            Integration successful.
+        2            Integration successful (interrupted by solout).
+        -1           Input is not consistent.
+        -2           Larger nsteps is needed.
+        -3           Step size becomes too small.
+        -4           Problem is probably stiff (interrupted).
+        ===========  =======
+
+        "lsoda"
+
+        ===========  =======
+        Return Code  Message
+        ===========  =======
+        2            Integration successful.
+        -1           Excess work done on this call (perhaps wrong Dfun type).
+        -2           Excess accuracy requested (tolerances too small).
+        -3           Illegal input detected (internal error).
+        -4           Repeated error test failures (internal error).
+        -5           Repeated convergence failures (perhaps bad Jacobian or tolerances).
+        -6           Error weight became zero during problem.
+        -7           Internal workspace insufficient to finish (internal error).
+        ===========  =======
+        """
+        try:
+            self._integrator
+        except AttributeError:
+            self.set_integrator('')
+        return self._integrator.istate
+
+    def set_f_params(self, *args):
+        """Set extra parameters for user-supplied function f."""
+        self.f_params = args
+        return self
+
+    def set_jac_params(self, *args):
+        """Set extra parameters for user-supplied function jac."""
+        self.jac_params = args
+        return self
+
+    def set_solout(self, solout):
+        """
+        Set callable to be called at every successful integration step.
+
+        Parameters
+        ----------
+        solout : callable
+            ``solout(t, y)`` is called at each internal integrator step,
+            t is a scalar providing the current independent position
+            y is the current solution ``y.shape == (n,)``
+            solout should return -1 to stop integration
+            otherwise it should return None or 0
+
+        """
+        if self._integrator.supports_solout:
+            self._integrator.set_solout(solout)
+            if self._y is not None:
+                self._integrator.reset(len(self._y), self.jac is not None)
+        else:
+            raise ValueError("selected integrator does not support solout,"
+                             " choose another one")
+
+
+def _transform_banded_jac(bjac):
+    """
+    Convert a real matrix of the form (for example)
+
+        [0 0 A B]        [0 0 0 B]
+        [0 0 C D]        [0 0 A D]
+        [E F G H]   to   [0 F C H]
+        [I J K L]        [E J G L]
+                         [I 0 K 0]
+
+    That is, every other column is shifted up one.
+    """
+    # Shift every other column.
+    newjac = zeros((bjac.shape[0] + 1, bjac.shape[1]))
+    newjac[1:, ::2] = bjac[:, ::2]
+    newjac[:-1, 1::2] = bjac[:, 1::2]
+    return newjac
+
+
+class complex_ode(ode):
+    """
+    A wrapper of ode for complex systems.
+
+    This functions similarly as `ode`, but re-maps a complex-valued
+    equation system to a real-valued one before using the integrators.
+
+    Parameters
+    ----------
+    f : callable ``f(t, y, *f_args)``
+        Rhs of the equation. t is a scalar, ``y.shape == (n,)``.
+        ``f_args`` is set by calling ``set_f_params(*args)``.
+    jac : callable ``jac(t, y, *jac_args)``
+        Jacobian of the rhs, ``jac[i,j] = d f[i] / d y[j]``.
+        ``jac_args`` is set by calling ``set_f_params(*args)``.
+
+    Attributes
+    ----------
+    t : float
+        Current time.
+    y : ndarray
+        Current variable values.
+
+    Examples
+    --------
+    For usage examples, see `ode`.
+
+    """
+
+    def __init__(self, f, jac=None):
+        self.cf = f
+        self.cjac = jac
+        self.tmp_derivative = None  # Work array for derivatives in _wrap
+        if jac is None:
+            ode.__init__(self, self._wrap, None)
+        else:
+            ode.__init__(self, self._wrap, self._wrap_jac)
+
+    def _wrap(self, t, y, *f_args):
+        f = self.cf(*((t, y[::2] + 1j * y[1::2]) + f_args))
+        # self.tmp_derivative is a real-valued array containing the interleaved
+        # real and imaginary parts of f (the derivative).
+        # IMPORTANT: Must NOT use self.tmp here, as it may alias with y!
+        self.tmp_derivative[::2] = real(f)
+        self.tmp_derivative[1::2] = imag(f)
+        return self.tmp_derivative
+
+    def _wrap_jac(self, t, y, *jac_args):
+        # jac is the complex Jacobian computed by the user-defined function.
+        jac = self.cjac(*((t, y[::2] + 1j * y[1::2]) + jac_args))
+
+        # jac_tmp is the real version of the complex Jacobian.  Each complex
+        # entry in jac, say 2+3j, becomes a 2x2 block of the form
+        #     [2 -3]
+        #     [3  2]
+        jac_tmp = zeros((2 * jac.shape[0], 2 * jac.shape[1]))
+        jac_tmp[1::2, 1::2] = jac_tmp[::2, ::2] = real(jac)
+        jac_tmp[1::2, ::2] = imag(jac)
+        jac_tmp[::2, 1::2] = -jac_tmp[1::2, ::2]
+
+        ml = getattr(self._integrator, 'ml', None)
+        mu = getattr(self._integrator, 'mu', None)
+        if ml is not None or mu is not None:
+            # Jacobian is banded.  The user's Jacobian function has computed
+            # the complex Jacobian in packed format.  The corresponding
+            # real-valued version has every other column shifted up.
+            jac_tmp = _transform_banded_jac(jac_tmp)
+
+        return jac_tmp
+
+    @property
+    def y(self):
+        return self._y[::2] + 1j * self._y[1::2]
+
+    def set_integrator(self, name, **integrator_params):
+        """
+        Set integrator by name.
+
+        Parameters
+        ----------
+        name : str
+            Name of the integrator
+        **integrator_params
+            Additional parameters for the integrator.
+        """
+        if name == 'zvode':
+            raise ValueError("zvode must be used with ode, not complex_ode")
+
+        lband = integrator_params.get('lband')
+        uband = integrator_params.get('uband')
+        if lband is not None or uband is not None:
+            # The Jacobian is banded.  Override the user-supplied bandwidths
+            # (which are for the complex Jacobian) with the bandwidths of
+            # the corresponding real-valued Jacobian wrapper of the complex
+            # Jacobian.
+            integrator_params['lband'] = 2 * (lband or 0) + 1
+            integrator_params['uband'] = 2 * (uband or 0) + 1
+
+        return ode.set_integrator(self, name, **integrator_params)
+
+    def set_initial_value(self, y, t=0.0):
+        """Set initial conditions y(t) = y."""
+        y = asarray(y)
+        self.tmp = zeros(y.size * 2, 'float')
+        self.tmp[::2] = real(y)
+        self.tmp[1::2] = imag(y)
+        # Create separate work array for derivatives to avoid aliasing issues
+        self.tmp_derivative = zeros(y.size * 2, 'float')
+        return ode.set_initial_value(self, self.tmp, t)
+
+    def integrate(self, t, step=False, relax=False):
+        """Find y=y(t), set y as an initial condition, and return y.
+
+        Parameters
+        ----------
+        t : float
+            The endpoint of the integration step.
+        step : bool
+            If True, and if the integrator supports the step method,
+            then perform a single integration step and return.
+            This parameter is provided in order to expose internals of
+            the implementation, and should not be changed from its default
+            value in most cases.
+        relax : bool
+            If True and if the integrator supports the run_relax method,
+            then integrate until t_1 >= t and return. ``relax`` is not
+            referenced if ``step=True``.
+            This parameter is provided in order to expose internals of
+            the implementation, and should not be changed from its default
+            value in most cases.
+
+        Returns
+        -------
+        y : float
+            The integrated value at t
+        """
+        y = ode.integrate(self, t, step, relax)
+        return y[::2] + 1j * y[1::2]
+
+    def set_solout(self, solout):
+        """
+        Set callable to be called at every successful integration step.
+
+        Parameters
+        ----------
+        solout : callable
+            ``solout(t, y)`` is called at each internal integrator step,
+            t is a scalar providing the current independent position
+            y is the current solution ``y.shape == (n,)``
+            solout should return -1 to stop integration
+            otherwise it should return None or 0
+
+        """
+        if self._integrator.supports_solout:
+            self._integrator.set_solout(solout, complex=True)
+        else:
+            raise TypeError("selected integrator does not support solouta, "
+                            "choose another one")
+
+
+# ------------------------------------------------------------------------------
+# ODE integrators
+# ------------------------------------------------------------------------------
+
+def find_integrator(name):
+    for cl in IntegratorBase.integrator_classes:
+        if re.match(name, cl.__name__, re.I):
+            return cl
+    return None
+
+
+class IntegratorConcurrencyError(RuntimeError):
+    """
+    Failure due to concurrent usage of an integrator that can be used
+    only for a single problem at a time.
+
+    """
+
+    def __init__(self, name):
+        msg = (f"Integrator `{name}` can be used to solve only a single problem "
+                "at a time. If you want to integrate multiple problems, "
+                "consider using a different integrator (see `ode.set_integrator`)")
+        RuntimeError.__init__(self, msg)
+
+
+class IntegratorBase:
+    runner = None  # runner is None => integrator is not available
+    success = None  # success==1 if integrator was called successfully
+    istate = None  # istate > 0 means success, istate < 0 means failure
+    supports_run_relax = None
+    supports_step = None
+    supports_solout = False
+    integrator_classes = []
+    scalar = float
+
+    # generic type compatibility with scipy-stubs
+    __class_getitem__: classmethod = classmethod(types.GenericAlias)
+
+    def acquire_new_handle(self):
+        # Some of the integrators have internal state (ancient
+        # Fortran...), and so only one instance can use them at a time.
+        # We keep track of this, and fail when concurrent usage is tried.
+        self.__class__.active_global_handle += 1
+        self.handle = self.__class__.active_global_handle
+
+    def check_handle(self):
+        if self.handle is not self.__class__.active_global_handle:
+            raise IntegratorConcurrencyError(self.__class__.__name__)
+
+    def reset(self, n, has_jac):
+        """Prepare integrator for call: allocate memory, set flags, etc.
+        n - number of equations.
+        has_jac - if user has supplied function for evaluating Jacobian.
+        """
+
+    def run(self, f, jac, y0, t0, t1, f_params, jac_params):
+        """Integrate from t=t0 to t=t1 using y0 as an initial condition.
+        Return 2-tuple (y1,t1) where y1 is the result and t=t1
+        defines the stoppage coordinate of the result.
+        """
+        raise NotImplementedError('all integrators must define '
+                                  'run(f, jac, t0, t1, y0, f_params, jac_params)')
+
+    def step(self, f, jac, y0, t0, t1, f_params, jac_params, /):
+        """Make one integration step and return (y1,t1)."""
+        raise NotImplementedError(f'{self.__class__.__name__} '
+                                  'does not support step() method')
+
+    def run_relax(self, f, jac, y0, t0, t1, f_params, jac_params, /):
+        """Integrate from t=t0 to t>=t1 and return (y1,t)."""
+        raise NotImplementedError(f'{self.__class__.__name__} '
+                                  'does not support run_relax() method')
+
+    # XXX: __str__ method for getting visual state of the integrator
+
+
+class vode(IntegratorBase):
+    runner = getattr(_vode, 'dvode', None)
+
+    messages = {-1: 'Excess work done on this call. (Perhaps wrong MF.)',
+                -2: 'Excess accuracy requested. (Tolerances too small.)',
+                -3: 'Illegal input detected. (See printed message.)',
+                -4: 'Repeated error test failures. (Check all input.)',
+                -5: 'Repeated convergence failures. (Perhaps bad'
+                    ' Jacobian supplied or wrong choice of MF or tolerances.)',
+                -6: 'Error weight became zero during problem. (Solution'
+                    ' component i vanished, and ATOL or ATOL(i) = 0.)'
+                }
+    supports_run_relax = 1
+    supports_step = 1
+
+    def __init__(self,
+                 method='adams',
+                 with_jacobian=False,
+                 rtol=1e-6, atol=1e-12,
+                 lband=None, uband=None,
+                 order=12,
+                 nsteps=500,
+                 max_step=0.0,  # corresponds to infinite
+                 min_step=0.0,
+                 first_step=0.0,  # determined by solver
+                 ):
+
+        if re.match(method, r'adams', re.I):
+            self.meth = 1
+        elif re.match(method, r'bdf', re.I):
+            self.meth = 2
+        else:
+            raise ValueError(f'Unknown integration method {method}')
+        self.with_jacobian = with_jacobian
+        self.rtol = rtol
+        self.atol = atol
+        self.mu = uband
+        self.ml = lband
+
+        self.order = order
+        self.nsteps = nsteps
+        self.max_step = max_step
+        self.min_step = min_step
+        self.first_step = first_step
+        self.success = 1
+
+        # State persistence arrays for VODE internal state
+        # These retain the solver state between calls
+        self.state_doubles = zeros(51, dtype=np.float64)  # VODE_STATE_DOUBLE_SIZE
+        self.state_ints = zeros(41, dtype=np.int32)        # VODE_STATE_INT_SIZE
+
+    def _determine_mf_and_set_bands(self, has_jac):
+        """
+        Determine the `MF` parameter (Method Flag) for the Fortran subroutine `dvode`.
+
+        In the Fortran code, the legal values of `MF` are:
+            10, 11, 12, 13, 14, 15, 20, 21, 22, 23, 24, 25,
+            -11, -12, -14, -15, -21, -22, -24, -25
+        but this Python wrapper does not use negative values.
+
+        Returns
+
+            mf  = 10*self.meth + miter
+
+        self.meth is the linear multistep method:
+            self.meth == 1:  method="adams"
+            self.meth == 2:  method="bdf"
+
+        miter is the correction iteration method:
+            miter == 0:  Functional iteration; no Jacobian involved.
+            miter == 1:  Chord iteration with user-supplied full Jacobian.
+            miter == 2:  Chord iteration with internally computed full Jacobian.
+            miter == 3:  Chord iteration with internally computed diagonal Jacobian.
+            miter == 4:  Chord iteration with user-supplied banded Jacobian.
+            miter == 5:  Chord iteration with internally computed banded Jacobian.
+
+        Side effects: If either self.mu or self.ml is not None and the other is None,
+        then the one that is None is set to 0.
+        """
+
+        jac_is_banded = self.mu is not None or self.ml is not None
+        if jac_is_banded:
+            if self.mu is None:
+                self.mu = 0
+            if self.ml is None:
+                self.ml = 0
+
+        # has_jac is True if the user provided a Jacobian function.
+        if has_jac:
+            if jac_is_banded:
+                miter = 4
+            else:
+                miter = 1
+        else:
+            if jac_is_banded:
+                if self.ml == self.mu == 0:
+                    miter = 3  # Chord iteration with internal diagonal Jacobian.
+                else:
+                    miter = 5  # Chord iteration with internal banded Jacobian.
+            else:
+                # self.with_jacobian is set by the user in
+                # the call to ode.set_integrator.
+                if self.with_jacobian:
+                    miter = 2  # Chord iteration with internal full Jacobian.
+                else:
+                    miter = 0  # Functional iteration; no Jacobian involved.
+
+        mf = 10 * self.meth + miter
+        return mf
+
+    def reset(self, n, has_jac):
+        mf = self._determine_mf_and_set_bands(has_jac)
+
+        if mf == 10:
+            lrw = 20 + 16 * n
+        elif mf in [11, 12]:
+            lrw = 22 + 16 * n + 2 * n * n
+        elif mf == 13:
+            lrw = 22 + 17 * n
+        elif mf in [14, 15]:
+            lrw = 22 + 18 * n + (3 * self.ml + 2 * self.mu) * n
+        elif mf == 20:
+            lrw = 20 + 9 * n
+        elif mf in [21, 22]:
+            lrw = 22 + 9 * n + 2 * n * n
+        elif mf == 23:
+            lrw = 22 + 10 * n
+        elif mf in [24, 25]:
+            lrw = 22 + 11 * n + (3 * self.ml + 2 * self.mu) * n
+        else:
+            raise ValueError(f'Unexpected mf={mf}')
+
+        if mf % 10 in [0, 3]:
+            liw = 30
+        else:
+            liw = 30 + n
+
+        rwork = zeros((lrw,), float)
+        rwork[4] = self.first_step
+        rwork[5] = self.max_step
+        rwork[6] = self.min_step
+        self.rwork = rwork
+
+        iwork = zeros((liw,), dtype=_iwork_dtype)
+        if self.ml is not None:
+            iwork[0] = self.ml
+        if self.mu is not None:
+            iwork[1] = self.mu
+        iwork[4] = self.order
+        iwork[5] = self.nsteps
+        iwork[6] = 2  # mxhnil
+        self.iwork = iwork
+
+        self.call_args = [self.rtol, self.atol, 1, 1,
+                          self.rwork, self.iwork, mf]
+        self.success = 1
+        self.initialized = False
+
+        # Zero state arrays on reset to avoid contamination from previous problems.
+        # State persistence works within a single integration (istate=2), but between
+        # different problems (different n etc.), state needs to be cleared.
+        self.state_doubles.fill(0.0)
+        self.state_ints.fill(0)
+
+
+    def run(self, f, jac, y0, t0, t1, f_params, jac_params):
+        # Note: For banded Jacobians, the user provides the compressed format
+        # (ml + mu + 1, n), and the C code handles padding to the expanded
+        # format (ml + 2*mu + 1, n) internally. No Python wrapper needed.
+
+        # VODE C wrapper signature:
+        # dvode(f, jac, y0, t0, t1, rtol, atol, itask, istate, rwork, iwork, mf,
+        #       f_params, jac_params, state_doubles, state_ints)
+        args = ((f, jac, y0, t0, t1) + tuple(self.call_args) +
+                (f_params, jac_params, self.state_doubles, self.state_ints))
+
+        y1, t, istate = self.runner(*args)
+
+        self.istate = istate
+        if istate < 0:
+            unexpected_istate_msg = f'Unexpected istate={istate:d}'
+            warnings.warn(f'{self.__class__.__name__:s}: '
+                          f'{self.messages.get(istate, unexpected_istate_msg):s}',
+                          stacklevel=2)
+            self.success = 0
+        else:
+            self.call_args[3] = 2  # upgrade istate from 1 to 2
+            self.istate = 2
+        return y1, t
+
+    def step(self, *args):
+        itask = self.call_args[2]
+        self.call_args[2] = 2
+        r = self.run(*args)
+        self.call_args[2] = itask
+        return r
+
+    def run_relax(self, *args):
+        itask = self.call_args[2]
+        self.call_args[2] = 3
+        r = self.run(*args)
+        self.call_args[2] = itask
+        return r
+
+
+if vode.runner is not None:
+    IntegratorBase.integrator_classes.append(vode)
+
+
+class zvode(vode):
+    runner = getattr(_vode, 'zvode', None)
+
+    supports_run_relax = 1
+    supports_step = 1
+    scalar = complex
+
+    __class_getitem__ = None  # type:ignore[assignment]
+
+    def __init__(self, *args, **kwargs):
+        super().__init__(*args, **kwargs)
+        # Override state array sizes for ZVODE (53 doubles vs 51 for VODE)
+        self.state_doubles = zeros(53, dtype=np.float64)  # ZVODE_STATE_DOUBLE_SIZE
+        self.state_ints = zeros(41, dtype=np.int32)        # ZVODE_STATE_INT_SIZE
+
+    def reset(self, n, has_jac):
+        mf = self._determine_mf_and_set_bands(has_jac)
+
+        if mf in (10,):
+            lzw = 15 * n
+        elif mf in (11, 12):
+            lzw = 15 * n + 2 * n ** 2
+        elif mf in (-11, -12):
+            lzw = 15 * n + n ** 2
+        elif mf in (13,):
+            lzw = 16 * n
+        elif mf in (14, 15):
+            lzw = 17 * n + (3 * self.ml + 2 * self.mu) * n
+        elif mf in (-14, -15):
+            lzw = 16 * n + (2 * self.ml + self.mu) * n
+        elif mf in (20,):
+            lzw = 8 * n
+        elif mf in (21, 22):
+            lzw = 8 * n + 2 * n ** 2
+        elif mf in (-21, -22):
+            lzw = 8 * n + n ** 2
+        elif mf in (23,):
+            lzw = 9 * n
+        elif mf in (24, 25):
+            lzw = 10 * n + (3 * self.ml + 2 * self.mu) * n
+        elif mf in (-24, -25):
+            lzw = 9 * n + (2 * self.ml + self.mu) * n
+
+        lrw = 20 + n
+
+        if mf % 10 in (0, 3):
+            liw = 30
+        else:
+            liw = 30 + n
+
+        zwork = zeros((lzw,), complex)
+        self.zwork = zwork
+
+        rwork = zeros((lrw,), float)
+        rwork[4] = self.first_step
+        rwork[5] = self.max_step
+        rwork[6] = self.min_step
+        self.rwork = rwork
+
+        iwork = zeros((liw,), _iwork_dtype)
+        if self.ml is not None:
+            iwork[0] = self.ml
+        if self.mu is not None:
+            iwork[1] = self.mu
+        iwork[4] = self.order
+        iwork[5] = self.nsteps
+        iwork[6] = 2  # mxhnil
+        self.iwork = iwork
+
+        self.call_args = [self.rtol, self.atol, 1, 1,
+                          self.zwork, self.rwork, self.iwork, mf]
+        self.success = 1
+        self.initialized = False
+
+        # Zero state arrays on reset to avoid contamination from previous problems.
+        # State persistence works within a single integration (istate=2), but between
+        # different problems (different n etc.), state needs to be cleared.
+        self.state_doubles.fill(0.0)
+        self.state_ints.fill(0)
+
+
+if zvode.runner is not None:
+    IntegratorBase.integrator_classes.append(zvode)
+
+
+class dopri5(IntegratorBase):
+    runner = getattr(_dop, 'dopri5', None)
+    name = 'dopri5'
+    supports_solout = True
+
+    messages = {1: 'computation successful',
+                2: 'computation successful (interrupted by solout)',
+                -1: 'input is not consistent',
+                -2: 'larger nsteps is needed',
+                -3: 'step size becomes too small',
+                -4: 'problem is probably stiff (interrupted)',
+                }
+
+    __class_getitem__ = None  # type:ignore[assignment]
+
+    def __init__(self,
+                 rtol=1e-6, atol=1e-12,
+                 nsteps=500,
+                 max_step=0.0,
+                 first_step=0.0,  # determined by solver
+                 safety=0.9,
+                 ifactor=10.0,
+                 dfactor=0.2,
+                 beta=0.0,
+                 method=None,
+                 verbosity=-1,  # no messages if negative
+                 ):
+        self.rtol = rtol
+        self.atol = atol
+        self.nsteps = nsteps
+        self.max_step = max_step
+        self.first_step = first_step
+        self.safety = safety
+        self.ifactor = ifactor
+        self.dfactor = dfactor
+        self.beta = beta
+        self.verbosity = verbosity
+        self.success = 1
+        self.set_solout(None)
+
+    def set_solout(self, solout, complex=False):
+        self.solout = solout
+        self.solout_cmplx = complex
+        if solout is None:
+            self.iout = 0
+        else:
+            self.iout = 1
+
+    def reset(self, n, has_jac):
+        work = zeros((8 * n + 21,), float)
+        work[1] = self.safety
+        work[2] = self.dfactor
+        work[3] = self.ifactor
+        work[4] = self.beta
+        work[5] = self.max_step
+        work[6] = self.first_step
+        self.work = work
+        self.iwork = zeros((21,), dtype=np.int32)
+        self.call_args = [self.rtol, self.atol, self._solout,
+                          self.iout, self.work, self.iwork,
+                          self.nsteps, self.verbosity]
+        self.success = 1
+
+    def run(self, f, jac, y0, t0, t1, f_params, jac_params):
+        x, y, istate = self.runner(*((f, t0, y0, t1) +
+                                   tuple(self.call_args) + (f_params,)))
+        self.istate = istate
+        if istate < 0:
+            unexpected_istate_msg = f'Unexpected istate={istate:d}'
+            warnings.warn(f'{self.__class__.__name__:s}: '
+                          f'{self.messages.get(istate, unexpected_istate_msg):s}',
+                          stacklevel=2)
+            self.success = 0
+        return y, x
+
+    def _solout(self, x, y):
+        if self.solout is not None:
+            if self.solout_cmplx:
+                y = y[::2] + 1j * y[1::2]
+            return self.solout(x, y)
+        else:
+            return 1
+
+
+if dopri5.runner is not None:
+    IntegratorBase.integrator_classes.append(dopri5)
+
+
+class dop853(dopri5):
+    runner = getattr(_dop, 'dopri853', None)
+    name = 'dop853'
+
+    def __init__(self,
+                 rtol=1e-6, atol=1e-12,
+                 nsteps=500,
+                 max_step=0.0,
+                 first_step=0.0,  # determined by solver
+                 safety=0.9,
+                 ifactor=6.0,
+                 dfactor=0.3,
+                 beta=0.0,
+                 method=None,
+                 verbosity=-1,  # no messages if negative
+                 ):
+        super().__init__(rtol, atol, nsteps, max_step, first_step, safety,
+                         ifactor, dfactor, beta, method, verbosity)
+
+    def reset(self, n, has_jac):
+        work = zeros((11 * n + 21,), float)
+        work[1] = self.safety
+        work[2] = self.dfactor
+        work[3] = self.ifactor
+        work[4] = self.beta
+        work[5] = self.max_step
+        work[6] = self.first_step
+        self.work = work
+        self.iwork = zeros((21,), dtype=np.int32)
+        self.call_args = [self.rtol, self.atol, self._solout,
+                          self.iout, self.work, self.iwork,
+                          self.nsteps, self.verbosity]
+        self.success = 1
+
+
+if dop853.runner is not None:
+    IntegratorBase.integrator_classes.append(dop853)
+
+
+class lsoda(IntegratorBase):
+    runner = lsoda_step  # Use low-level lsoda wrapper
+
+    messages = {
+        2: "Integration successful.",
+        -1: "Excess work done on this call (perhaps wrong Dfun type).",
+        -2: "Excess accuracy requested (tolerances too small).",
+        -3: "Illegal input detected (internal error).",
+        -4: "Repeated error test failures (internal error).",
+        -5: "Repeated convergence failures (perhaps bad Jacobian or tolerances).",
+        -6: "Error weight became zero during problem.",
+        -7: "Internal workspace insufficient to finish (internal error)."
+    }
+
+    __class_getitem__ = None  # type:ignore[assignment]
+
+    def __init__(self,
+                 with_jacobian=False,
+                 rtol=1e-6, atol=1e-12,
+                 lband=None, uband=None,
+                 nsteps=500,
+                 max_step=0.0,  # corresponds to infinite
+                 min_step=0.0,
+                 first_step=0.0,  # determined by solver
+                 ixpr=0,
+                 max_hnil=0,
+                 max_order_ns=12,
+                 max_order_s=5,
+                 method=None
+                 ):
+
+        self.with_jacobian = with_jacobian
+        self.rtol = rtol
+        self.atol = atol
+        self.mu = uband
+        self.ml = lband
+
+        self.max_order_ns = max_order_ns
+        self.max_order_s = max_order_s
+        self.nsteps = nsteps
+        self.max_step = max_step
+        self.min_step = min_step
+        self.first_step = first_step
+        self.ixpr = ixpr
+        self.max_hnil = max_hnil
+        self.success = 1
+
+        self.initialized = False
+
+        # State persistence arrays for LSODA internal state
+        # These retain the solver state between calls
+        self.state_doubles = zeros(240, dtype=np.float64)  # LSODA_STATE_DOUBLE_SIZE
+        self.state_ints = zeros(48, dtype=np.int32)        # LSODA_STATE_INT_SIZE
+
+    def reset(self, n, has_jac):
+        # Zero state arrays on reset to avoid contamination from previous steps.
+        # State persistence works within a single integration (istate=2), but between
+        # different problems (different n etc.), state needs to be cleared.
+        self.state_doubles.fill(0.0)
+        self.state_ints.fill(0)
+
+        # Calculate parameters for lsoda subroutine.
+        # jt values: 1=user full, 2=FD full, 4=user banded, 5=FD banded (3=invalid)
+        if has_jac:
+            if self.mu is None and self.ml is None:
+                jt = 1  # User-supplied full Jacobian
+            else:
+                if self.mu is None:
+                    self.mu = 0
+                if self.ml is None:
+                    self.ml = 0
+                jt = 4  # User-supplied banded Jacobian
+        else:
+            if self.mu is None and self.ml is None:
+                jt = 2  # Internally generated full Jacobian (finite differences)
+            else:
+                if self.mu is None:
+                    self.mu = 0
+                if self.ml is None:
+                    self.ml = 0
+                jt = 5  # Internally generated banded Jacobian (finite differences)
+
+        # Calculate work array sizes
+        lrn = 20 + (self.max_order_ns + 4) * n
+        if jt in [1, 2]:
+            lrs = 22 + (self.max_order_s + 4) * n + n * n
+        elif jt in [4, 5]:
+            lrs = 22 + (self.max_order_s + 5 + 2 * self.ml + self.mu) * n
+        else:
+            raise ValueError(f'Unexpected jt={jt}')
+        lrw = max(lrn, lrs)
+        liw = 20 + n
+
+        # Create and initialize work arrays
+        rwork = zeros((lrw,), float)
+        rwork[4] = self.first_step
+        rwork[5] = self.max_step
+        rwork[6] = self.min_step
+        self.rwork = rwork
+
+        iwork = zeros((liw,), dtype=_iwork_dtype)
+        if self.ml is not None:
+            iwork[0] = self.ml
+        if self.mu is not None:
+            iwork[1] = self.mu
+        iwork[4] = self.ixpr
+        iwork[5] = self.nsteps
+        iwork[6] = self.max_hnil
+        iwork[7] = self.max_order_ns
+        iwork[8] = self.max_order_s
+        self.iwork = iwork
+
+        self.call_args = [self.rtol, self.atol, 1, 1,
+                          self.rwork, self.iwork, jt]
+        self.success = 1
+
+    def run(self, f, jac, y0, t0, t1, f_params, jac_params):
+        # Prepare arguments for low-level lsoda wrapper
+        rtol = self.call_args[0]
+        atol = self.call_args[1]
+        itask = self.call_args[2]
+        istate = self.call_args[3]
+        rwork = self.call_args[4]
+        iwork = self.call_args[5]
+        jt = self.call_args[6]
+
+        # Note: For banded Jacobians, the user provides the compressed format
+        # (ml + mu + 1, n), and the C code handles padding to the expanded
+        # format (2*ml + mu + 1, n) internally. No Python wrapper needed.
+
+        # Signature:
+        #
+        #    lsoda(fun, y0, t, tout, rtol, atol, itask, istate, rwork, iwork,
+        #          jac, jt, f_params, tfirst, jac_params, state_doubles, state_ints)
+        #
+        # "state_doubles" and "state_ints" are arrays for passing internal
+        # state between Python-C code.
+        y1, t, istate = self.runner(
+            f, y0, t0, t1, rtol, atol, itask, istate, rwork, iwork,
+            jac, jt, f_params, 1, jac_params,  # tfirst=1 for (t, y) signature
+            self.state_doubles, self.state_ints
+        )
+
+        self.istate = istate
+        if istate < 0:
+            unexpected_istate_msg = f'Unexpected istate={istate:d}'
+            warnings.warn(f'{self.__class__.__name__:s}: '
+                          f'{self.messages.get(istate, unexpected_istate_msg):s}',
+                          stacklevel=2)
+            self.success = 0
+        else:
+            self.call_args[3] = 2  # upgrade istate from 1 to 2
+            self.istate = 2
+            self.success = 1
+        return y1, t
+
+    def step(self, *args):
+        itask = self.call_args[2]
+        self.call_args[2] = 2
+        r = self.run(*args)
+        self.call_args[2] = itask
+        return r
+
+    def run_relax(self, *args):
+        itask = self.call_args[2]
+        self.call_args[2] = 3
+        r = self.run(*args)
+        self.call_args[2] = itask
+        return r
+
+
+if lsoda.runner:
+    IntegratorBase.integrator_classes.append(lsoda)
diff --git a/.venv/lib/python3.12/site-packages/scipy/integrate/_odepack.cpython-312-x86_64-linux-gnu.so b/.venv/lib/python3.12/site-packages/scipy/integrate/_odepack.cpython-312-x86_64-linux-gnu.so
new file mode 100644
index 0000000000000000000000000000000000000000..e06624d78e9f1fd3373e1819d3370011ca7ab2f6
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/scipy/integrate/_odepack.cpython-312-x86_64-linux-gnu.so differ
diff --git a/.venv/lib/python3.12/site-packages/scipy/integrate/_odepack_py.py b/.venv/lib/python3.12/site-packages/scipy/integrate/_odepack_py.py
new file mode 100644
index 0000000000000000000000000000000000000000..11acc97446daf90936ca2cbb55ab06d68719ae8d
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/integrate/_odepack_py.py
@@ -0,0 +1,271 @@
+# Author: Travis Oliphant
+
+__all__ = ['odeint', 'ODEintWarning']
+
+import numpy as np
+from . import _odepack
+from copy import copy
+import warnings
+
+from scipy._lib._array_api import xp_capabilities
+
+
+class ODEintWarning(Warning):
+    """Warning raised during the execution of `odeint`."""
+    pass
+
+
+_msgs = {2: "Integration successful.",
+         1: "Nothing was done; the integration time was 0.",
+         -1: "Excess work done on this call (perhaps wrong Dfun type).",
+         -2: "Excess accuracy requested (tolerances too small).",
+         -3: "Illegal input detected (internal error).",
+         -4: "Repeated error test failures (internal error).",
+         -5: "Repeated convergence failures (perhaps bad Jacobian or tolerances).",
+         -6: "Error weight became zero during problem.",
+         -7: "Internal workspace insufficient to finish (internal error).",
+         -8: "Run terminated (internal error)."
+         }
+
+
+@xp_capabilities(out_of_scope=True)
+def odeint(func, y0, t, args=(), Dfun=None, col_deriv=0, full_output=0,
+           ml=None, mu=None, rtol=None, atol=None, tcrit=None, h0=0.0,
+           hmax=0.0, hmin=0.0, ixpr=0, mxstep=0, mxhnil=0, mxordn=12,
+           mxords=5, printmessg=0, tfirst=False):
+    """
+    Integrate a system of ordinary differential equations.
+
+    .. note:: For new code, use `scipy.integrate.solve_ivp` to solve a
+              differential equation.
+
+    Solve a system of ordinary differential equations using lsoda from the
+    FORTRAN library odepack.
+
+    Solves the initial value problem for stiff or non-stiff systems
+    of first order ode-s::
+
+        dy/dt = func(y, t, ...)  [or func(t, y, ...)]
+
+    where y can be a vector.
+
+    .. note:: By default, the required order of the first two arguments of
+              `func` are in the opposite order of the arguments in the system
+              definition function used by the `scipy.integrate.ode` class and
+              the function `scipy.integrate.solve_ivp`. To use a function with
+              the signature ``func(t, y, ...)``, the argument `tfirst` must be
+              set to ``True``.
+
+    Parameters
+    ----------
+    func : callable(y, t, ...) or callable(t, y, ...)
+        Computes the derivative of y at t.
+        If the signature is ``callable(t, y, ...)``, then the argument
+        `tfirst` must be set ``True``.
+        `func` must not modify the data in `y`, as it is a
+        view of the data used internally by the ODE solver.
+    y0 : array
+        Initial condition on y (can be a vector).
+    t : array
+        A sequence of time points for which to solve for y. The initial
+        value point should be the first element of this sequence.
+        This sequence must be monotonically increasing or monotonically
+        decreasing; repeated values are allowed.
+    args : tuple, optional
+        Extra arguments to pass to function.
+    Dfun : callable(y, t, ...) or callable(t, y, ...)
+        Gradient (Jacobian) of `func`.
+        If the signature is ``callable(t, y, ...)``, then the argument
+        `tfirst` must be set ``True``.
+        `Dfun` must not modify the data in `y`, as it is a
+        view of the data used internally by the ODE solver.
+    col_deriv : bool, optional
+        True if `Dfun` defines derivatives down columns (faster),
+        otherwise `Dfun` should define derivatives across rows.
+    full_output : bool, optional
+        True if to return a dictionary of optional outputs as the second output
+    printmessg : bool, optional
+        Whether to print the convergence message
+    tfirst : bool, optional
+        If True, the first two arguments of `func` (and `Dfun`, if given)
+        must ``t, y`` instead of the default ``y, t``.
+
+        .. versionadded:: 1.1.0
+
+    Returns
+    -------
+    y : array, shape (len(t), len(y0))
+        Array containing the value of y for each desired time in t,
+        with the initial value `y0` in the first row.
+    infodict : dict, only returned if full_output == True
+        Dictionary containing additional output information
+
+        =======  ============================================================
+        key      meaning
+        =======  ============================================================
+        'hu'     vector of step sizes successfully used for each time step
+        'tcur'   vector with the value of t reached for each time step
+                 (will always be at least as large as the input times)
+        'tolsf'  vector of tolerance scale factors, greater than 1.0,
+                 computed when a request for too much accuracy was detected
+        'tsw'    value of t at the time of the last method switch
+                 (given for each time step)
+        'nst'    cumulative number of time steps
+        'nfe'    cumulative number of function evaluations for each time step
+        'nje'    cumulative number of jacobian evaluations for each time step
+        'nqu'    a vector of method orders for each successful step
+        'imxer'  index of the component of largest magnitude in the
+                 weighted local error vector (e / ewt) on an error return, -1
+                 otherwise
+        'lenrw'  the length of the double work array required
+        'leniw'  the length of integer work array required
+        'mused'  a vector of method indicators for each successful time step:
+                 1: adams (nonstiff), 2: bdf (stiff)
+        =======  ============================================================
+
+    Other Parameters
+    ----------------
+    ml, mu : int, optional
+        If either of these are not None or non-negative, then the
+        Jacobian is assumed to be banded. These give the number of
+        lower and upper non-zero diagonals in this banded matrix.
+        For the banded case, `Dfun` should return a matrix whose
+        rows contain the non-zero bands (starting with the lowest diagonal).
+        Thus, the return matrix `jac` from `Dfun` should have shape
+        ``(ml + mu + 1, len(y0))`` when ``ml >=0`` or ``mu >=0``.
+        The data in `jac` must be stored such that ``jac[i - j + mu, j]``
+        holds the derivative of the ``i``\\ th equation with respect to the
+        ``j``\\ th state variable.  If `col_deriv` is True, the transpose of
+        this `jac` must be returned.
+    rtol, atol : float, optional
+        The input parameters `rtol` and `atol` determine the error
+        control performed by the solver.  The solver will control the
+        vector, e, of estimated local errors in y, according to an
+        inequality of the form ``max-norm of (e / ewt) <= 1``,
+        where ewt is a vector of positive error weights computed as
+        ``ewt = rtol * abs(y) + atol``.
+        rtol and atol can be either vectors the same length as y or scalars.
+        Defaults to 1.49012e-8.
+    tcrit : ndarray, optional
+        Vector of critical points (e.g., singularities) where integration
+        care should be taken.
+    h0 : float, (0: solver-determined), optional
+        The step size to be attempted on the first step.
+    hmax : float, (0: solver-determined), optional
+        The maximum absolute step size allowed.
+    hmin : float, (0: solver-determined), optional
+        The minimum absolute step size allowed.
+    ixpr : bool, optional
+        Whether to generate extra printing at method switches.
+    mxstep : int, (0: solver-determined), optional
+        Maximum number of (internally defined) steps allowed for each
+        integration point in t.
+    mxhnil : int, (0: solver-determined), optional
+        Maximum number of messages printed.
+    mxordn : int, (0: solver-determined), optional
+        Maximum order to be allowed for the non-stiff (Adams) method.
+    mxords : int, (0: solver-determined), optional
+        Maximum order to be allowed for the stiff (BDF) method.
+
+    See Also
+    --------
+    solve_ivp : solve an initial value problem for a system of ODEs
+    ode : a more object-oriented integrator based on VODE
+    quad : for finding the area under a curve
+
+    Examples
+    --------
+    The second order differential equation for the angle `theta` of a
+    pendulum acted on by gravity with friction can be written::
+
+        theta''(t) + b*theta'(t) + c*sin(theta(t)) = 0
+
+    where `b` and `c` are positive constants, and a prime (') denotes a
+    derivative. To solve this equation with `odeint`, we must first convert
+    it to a system of first order equations. By defining the angular
+    velocity ``omega(t) = theta'(t)``, we obtain the system::
+
+        theta'(t) = omega(t)
+        omega'(t) = -b*omega(t) - c*sin(theta(t))
+
+    Let `y` be the vector [`theta`, `omega`]. We implement this system
+    in Python as:
+
+    >>> import numpy as np
+    >>> def pend(y, t, b, c):
+    ...     theta, omega = y
+    ...     dydt = [omega, -b*omega - c*np.sin(theta)]
+    ...     return dydt
+    ...
+
+    We assume the constants are `b` = 0.25 and `c` = 5.0:
+
+    >>> b = 0.25
+    >>> c = 5.0
+
+    For initial conditions, we assume the pendulum is nearly vertical
+    with `theta(0)` = `pi` - 0.1, and is initially at rest, so
+    `omega(0)` = 0.  Then the vector of initial conditions is
+
+    >>> y0 = [np.pi - 0.1, 0.0]
+
+    We will generate a solution at 101 evenly spaced samples in the interval
+    0 <= `t` <= 10.  So our array of times is:
+
+    >>> t = np.linspace(0, 10, 101)
+
+    Call `odeint` to generate the solution. To pass the parameters
+    `b` and `c` to `pend`, we give them to `odeint` using the `args`
+    argument.
+
+    >>> from scipy.integrate import odeint
+    >>> sol = odeint(pend, y0, t, args=(b, c))
+
+    The solution is an array with shape (101, 2). The first column
+    is `theta(t)`, and the second is `omega(t)`. The following code
+    plots both components.
+
+    >>> import matplotlib.pyplot as plt
+    >>> plt.plot(t, sol[:, 0], 'b', label='theta(t)')
+    >>> plt.plot(t, sol[:, 1], 'g', label='omega(t)')
+    >>> plt.legend(loc='best')
+    >>> plt.xlabel('t')
+    >>> plt.grid()
+    >>> plt.show()
+    """
+
+    if ml is None:
+        ml = -1  # changed to zero inside function call
+    if mu is None:
+        mu = -1  # changed to zero inside function call
+
+    dt = np.diff(t)
+    if not ((dt >= 0).all() or (dt <= 0).all()):
+        raise ValueError("The values in t must be monotonically increasing "
+                         "or monotonically decreasing; repeated values are "
+                         "allowed.")
+
+    t = copy(t)
+    y0 = copy(y0)
+
+
+    output = _odepack.odeint(func, y0, t, args, Dfun, col_deriv, ml, mu,
+                            full_output, rtol, atol, tcrit, h0, hmax, hmin,
+                            ixpr, mxstep, mxhnil, mxordn, mxords,
+                            int(bool(tfirst)))
+    if output[-1] < 0:
+        warning_msg = (f"{_msgs[output[-1]]} Run with full_output = 1 to "
+                       f"get quantitative information.")
+        warnings.warn(warning_msg, ODEintWarning, stacklevel=2)
+    elif printmessg:
+        warning_msg = _msgs[output[-1]]
+        warnings.warn(warning_msg, ODEintWarning, stacklevel=2)
+
+    if full_output:
+        output[1]['message'] = _msgs[output[-1]]
+
+    output = output[:-1]
+    if len(output) == 1:
+        return output[0]
+    else:
+        return output
diff --git a/.venv/lib/python3.12/site-packages/scipy/integrate/_quad_vec.py b/.venv/lib/python3.12/site-packages/scipy/integrate/_quad_vec.py
new file mode 100644
index 0000000000000000000000000000000000000000..fdc076dfcb80146a5670643fba57e77dc44304d5
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/integrate/_quad_vec.py
@@ -0,0 +1,666 @@
+import sys
+import copy
+import heapq
+import collections
+import functools
+
+import numpy as np
+
+from scipy._lib._util import MapWrapper, _FunctionWrapper
+from scipy._lib._array_api import xp_capabilities
+
+
+class LRUDict(collections.OrderedDict):
+    def __init__(self, max_size):
+        self.__max_size = max_size
+
+    def __setitem__(self, key, value):
+        existing_key = (key in self)
+        super().__setitem__(key, value)
+        if existing_key:
+            self.move_to_end(key)
+        elif len(self) > self.__max_size:
+            self.popitem(last=False)
+
+    def update(self, other, /, **kwargs):
+        # Not needed below
+        raise NotImplementedError()
+
+
+class SemiInfiniteFunc:
+    """
+    Argument transform from (start, +-oo) to (0, 1)
+    """
+    def __init__(self, func, start, infty):
+        self._func = func
+        self._start = start
+        self._sgn = -1 if infty < 0 else 1
+
+        # Overflow threshold for the 1/t**2 factor
+        self._tmin = sys.float_info.min**0.5
+
+    def get_t(self, x):
+        z = self._sgn * (x - self._start) + 1
+        if z == 0:
+            # Can happen only if point not in range
+            return np.inf
+        return 1 / z
+
+    def __call__(self, t):
+        if t < self._tmin:
+            return 0.0
+        else:
+            x = self._start + self._sgn * (1 - t) / t
+            f = self._func(x)
+            return self._sgn * (f / t) / t
+
+
+class DoubleInfiniteFunc:
+    """
+    Argument transform from (-oo, oo) to (-1, 1)
+    """
+    def __init__(self, func):
+        self._func = func
+
+        # Overflow threshold for the 1/t**2 factor
+        self._tmin = sys.float_info.min**0.5
+
+    def get_t(self, x):
+        s = -1 if x < 0 else 1
+        return s / (abs(x) + 1)
+
+    def __call__(self, t):
+        if abs(t) < self._tmin:
+            return 0.0
+        else:
+            x = (1 - abs(t)) / t
+            f = self._func(x)
+            return (f / t) / t
+
+
+def _max_norm(x):
+    return np.amax(abs(x))
+
+
+class _Bunch:
+    def __init__(self, **kwargs):
+        self.__keys = kwargs.keys()
+        self.__dict__.update(**kwargs)
+
+    def __repr__(self):
+        key_value_pairs = ', '.join(
+            f'{k}={repr(self.__dict__[k])}' for k in self.__keys
+        )
+        return f"_Bunch({key_value_pairs})"
+
+
+@xp_capabilities(np_only=True)
+def quad_vec(f, a, b, epsabs=1e-200, epsrel=1e-8, norm='2', cache_size=100e6,
+             limit=10000, workers=1, points=None, quadrature=None, full_output=False,
+             *, args=()):
+    r"""Adaptive integration of a vector-valued function.
+
+    Parameters
+    ----------
+    f : callable
+        Vector-valued function f(x) to integrate.
+    a : float
+        Initial point.
+    b : float
+        Final point.
+    epsabs : float, optional
+        Absolute tolerance.
+    epsrel : float, optional
+        Relative tolerance.
+    norm : {'max', '2'}, optional
+        Vector norm to use for error estimation.
+    cache_size : int, optional
+        Number of bytes to use for memoization.
+    limit : float or int, optional
+        An upper bound on the number of subintervals used in the adaptive
+        algorithm.
+    workers : int or map-like callable, optional
+        If `workers` is an integer, part of the computation is done in
+        parallel subdivided to this many tasks (using
+        :class:`python:multiprocessing.pool.Pool`).
+        Supply `-1` to use all cores available to the Process.
+        Alternatively, supply a map-like callable, such as
+        :meth:`python:multiprocessing.pool.Pool.map` for evaluating the
+        population in parallel.
+        This evaluation is carried out as ``workers(func, iterable)``.
+    points : list, optional
+        List of additional breakpoints.
+    quadrature : {'gk21', 'gk15', 'trapezoid'}, optional
+        Quadrature rule to use on subintervals.
+        Options: 'gk21' (Gauss-Kronrod 21-point rule),
+        'gk15' (Gauss-Kronrod 15-point rule),
+        'trapezoid' (composite trapezoid rule).
+        Default: 'gk21' for finite intervals and 'gk15' for (semi-)infinite.
+    full_output : bool, optional
+        Return an additional ``info`` object.
+    args : tuple, optional
+        Extra arguments to pass to function, if any.
+
+        .. versionadded:: 1.8.0
+
+    Returns
+    -------
+    res : {float, array-like}
+        Estimate for the result
+    err : float
+        Error estimate for the result in the given norm
+    info : object
+        Returned only when ``full_output=True``.
+        Result object with the attributes:
+
+        success : bool
+            Whether integration reached target precision.
+        status : int
+            Indicator for convergence, success (0),
+            failure (1), and failure due to rounding error (2).
+        neval : int
+            Number of function evaluations.
+        intervals : ndarray, shape (num_intervals, 2)
+            Start and end points of subdivision intervals.
+        integrals : ndarray, shape (num_intervals, ...)
+            Integral for each interval.
+            Note that at most ``cache_size`` values are recorded,
+            and the array may contains *nan* for missing items.
+        errors : ndarray, shape (num_intervals,)
+            Estimated integration error for each interval.
+
+    Notes
+    -----
+    The algorithm mainly follows the implementation of QUADPACK's
+    DQAG* algorithms, implementing global error control and adaptive
+    subdivision.
+
+    The algorithm here has some differences to the QUADPACK approach:
+
+    Instead of subdividing one interval at a time, the algorithm
+    subdivides N intervals with largest errors at once. This enables
+    (partial) parallelization of the integration.
+
+    The logic of subdividing "next largest" intervals first is then
+    not implemented, and we rely on the above extension to avoid
+    concentrating on "small" intervals only.
+
+    The Wynn epsilon table extrapolation is not used (QUADPACK uses it
+    for infinite intervals). This is because the algorithm here is
+    supposed to work on vector-valued functions, in an user-specified
+    norm, and the extension of the epsilon algorithm to this case does
+    not appear to be widely agreed. For max-norm, using elementwise
+    Wynn epsilon could be possible, but we do not do this here with
+    the hope that the epsilon extrapolation is mainly useful in
+    special cases.
+
+    References
+    ----------
+    [1] R. Piessens, E. de Doncker, QUADPACK (1983).
+
+    Examples
+    --------
+    We can compute integrations of a vector-valued function:
+
+    >>> from scipy.integrate import quad_vec
+    >>> import numpy as np
+    >>> import matplotlib.pyplot as plt
+    >>> alpha = np.linspace(0.0, 2.0, num=30)
+    >>> f = lambda x: x**alpha
+    >>> x0, x1 = 0, 2
+    >>> y, err = quad_vec(f, x0, x1)
+    >>> plt.plot(alpha, y)
+    >>> plt.xlabel(r"$\alpha$")
+    >>> plt.ylabel(r"$\int_{0}^{2} x^\alpha dx$")
+    >>> plt.show()
+
+    When using the argument `workers`, one should ensure
+    that the main module is import-safe, for instance
+    by rewriting the example above as:
+
+    .. code-block:: python
+
+        from scipy.integrate import quad_vec
+        import numpy as np
+        import matplotlib.pyplot as plt
+
+        alpha = np.linspace(0.0, 2.0, num=30)
+        x0, x1 = 0, 2
+        def f(x):
+            return x**alpha
+
+        if __name__ == "__main__":
+            y, err = quad_vec(f, x0, x1, workers=2)
+    """
+    a = float(a)
+    b = float(b)
+
+    if args:
+        if not isinstance(args, tuple):
+            args = (args,)
+
+        # create a wrapped function to allow the use of map and Pool.map
+        f = _FunctionWrapper(f, args)
+
+    # Use simple transformations to deal with integrals over infinite
+    # intervals.
+    kwargs = dict(epsabs=epsabs,
+                  epsrel=epsrel,
+                  norm=norm,
+                  cache_size=cache_size,
+                  limit=limit,
+                  workers=workers,
+                  points=points,
+                  quadrature='gk15' if quadrature is None else quadrature,
+                  full_output=full_output)
+    if np.isfinite(a) and np.isinf(b):
+        f2 = SemiInfiniteFunc(f, start=a, infty=b)
+        if points is not None:
+            kwargs['points'] = tuple(f2.get_t(xp) for xp in points)
+        return quad_vec(f2, 0, 1, **kwargs)
+    elif np.isfinite(b) and np.isinf(a):
+        f2 = SemiInfiniteFunc(f, start=b, infty=a)
+        if points is not None:
+            kwargs['points'] = tuple(f2.get_t(xp) for xp in points)
+        res = quad_vec(f2, 0, 1, **kwargs)
+        return (-res[0],) + res[1:]
+    elif np.isinf(a) and np.isinf(b):
+        sgn = -1 if b < a else 1
+
+        # NB. explicitly split integral at t=0, which separates
+        # the positive and negative sides
+        f2 = DoubleInfiniteFunc(f)
+        if points is not None:
+            kwargs['points'] = (0,) + tuple(f2.get_t(xp) for xp in points)
+        else:
+            kwargs['points'] = (0,)
+
+        if a != b:
+            res = quad_vec(f2, -1, 1, **kwargs)
+        else:
+            res = quad_vec(f2, 1, 1, **kwargs)
+
+        return (res[0]*sgn,) + res[1:]
+    elif not (np.isfinite(a) and np.isfinite(b)):
+        raise ValueError(f"invalid integration bounds a={a}, b={b}")
+
+    norm_funcs = {
+        None: _max_norm,
+        'max': _max_norm,
+        '2': np.linalg.norm
+    }
+    if callable(norm):
+        norm_func = norm
+    else:
+        norm_func = norm_funcs[norm]
+
+    parallel_count = 128
+    min_intervals = 2
+
+    try:
+        _quadrature = {None: _quadrature_gk21,
+                       'gk21': _quadrature_gk21,
+                       'gk15': _quadrature_gk15,
+                       'trapezoid': _quadrature_trapezoid}[quadrature]
+    except KeyError as e:
+        raise ValueError(f"unknown quadrature {quadrature!r}") from e
+
+    # Initial interval set
+    if points is None:
+        initial_intervals = [(a, b)]
+    else:
+        prev = a
+        initial_intervals = []
+        for p in sorted(points):
+            p = float(p)
+            if not (a < p < b) or p == prev:
+                continue
+            initial_intervals.append((prev, p))
+            prev = p
+        initial_intervals.append((prev, b))
+
+    global_integral = None
+    global_error = None
+    rounding_error = None
+    interval_cache = None
+    intervals = []
+    neval = 0
+
+    for x1, x2 in initial_intervals:
+        ig, err, rnd = _quadrature(x1, x2, f, norm_func)
+        neval += _quadrature.num_eval
+
+        if global_integral is None:
+            if isinstance(ig, float | complex):
+                # Specialize for scalars
+                if norm_func in (_max_norm, np.linalg.norm):
+                    norm_func = abs
+
+            global_integral = ig
+            global_error = float(err)
+            rounding_error = float(rnd)
+
+            cache_count = cache_size // sys.getsizeof(ig)
+            interval_cache = LRUDict(cache_count)
+        else:
+            global_integral += ig
+            global_error += err
+            rounding_error += rnd
+
+        interval_cache[(x1, x2)] = copy.copy(ig)
+        intervals.append((-err, x1, x2))
+
+    heapq.heapify(intervals)
+
+    CONVERGED = 0
+    NOT_CONVERGED = 1
+    ROUNDING_ERROR = 2
+    NOT_A_NUMBER = 3
+
+    status_msg = {
+        CONVERGED: "Target precision reached.",
+        NOT_CONVERGED: "Target precision not reached.",
+        ROUNDING_ERROR: "Target precision could not be reached due to rounding error.",
+        NOT_A_NUMBER: "Non-finite values encountered."
+    }
+
+    # Process intervals
+    with MapWrapper(workers) as mapwrapper:
+        ier = NOT_CONVERGED
+
+        while intervals and len(intervals) < limit:
+            # Select intervals with largest errors for subdivision
+            tol = max(epsabs, epsrel*norm_func(global_integral))
+
+            to_process = []
+            err_sum = 0
+
+            for j in range(parallel_count):
+                if not intervals:
+                    break
+
+                if j > 0 and err_sum > global_error - tol/8:
+                    # avoid unnecessary parallel splitting
+                    break
+
+                interval = heapq.heappop(intervals)
+
+                neg_old_err, a, b = interval
+                old_int = interval_cache.pop((a, b), None)
+                to_process.append(
+                    ((-neg_old_err, a, b, old_int), f, norm_func, _quadrature)
+                )
+                err_sum += -neg_old_err
+
+            # Subdivide intervals
+            for parts in mapwrapper(_subdivide_interval, to_process):
+                dint, derr, dround_err, subint, dneval = parts
+                neval += dneval
+                global_integral += dint
+                global_error += derr
+                rounding_error += dround_err
+                for x in subint:
+                    x1, x2, ig, err = x
+                    interval_cache[(x1, x2)] = ig
+                    heapq.heappush(intervals, (-err, x1, x2))
+
+            # Termination check
+            if len(intervals) >= min_intervals:
+                tol = max(epsabs, epsrel*norm_func(global_integral))
+                if global_error < tol/8:
+                    ier = CONVERGED
+                    break
+                if global_error < rounding_error:
+                    ier = ROUNDING_ERROR
+                    break
+
+            if not (np.isfinite(global_error) and np.isfinite(rounding_error)):
+                ier = NOT_A_NUMBER
+                break
+
+    res = global_integral
+    err = global_error + rounding_error
+
+    if full_output:
+        res_arr = np.asarray(res)
+        dummy = np.full(res_arr.shape, np.nan, dtype=res_arr.dtype)
+        integrals = np.array([interval_cache.get((z[1], z[2]), dummy)
+                                      for z in intervals], dtype=res_arr.dtype)
+        errors = np.array([-z[0] for z in intervals])
+        intervals = np.array([[z[1], z[2]] for z in intervals])
+
+        info = _Bunch(neval=neval,
+                      success=(ier == CONVERGED),
+                      status=ier,
+                      message=status_msg[ier],
+                      intervals=intervals,
+                      integrals=integrals,
+                      errors=errors)
+        return (res, err, info)
+    else:
+        return (res, err)
+
+
+def _subdivide_interval(args):
+    interval, f, norm_func, _quadrature = args
+    old_err, a, b, old_int = interval
+
+    c = 0.5 * (a + b)
+
+    # Left-hand side
+    if getattr(_quadrature, 'cache_size', 0) > 0:
+        f = functools.lru_cache(_quadrature.cache_size)(f)
+
+    s1, err1, round1 = _quadrature(a, c, f, norm_func)
+    dneval = _quadrature.num_eval
+    s2, err2, round2 = _quadrature(c, b, f, norm_func)
+    dneval += _quadrature.num_eval
+    if old_int is None:
+        old_int, _, _ = _quadrature(a, b, f, norm_func)
+        dneval += _quadrature.num_eval
+
+    if getattr(_quadrature, 'cache_size', 0) > 0:
+        dneval = f.cache_info().misses
+
+    dint = s1 + s2 - old_int
+    derr = err1 + err2 - old_err
+    dround_err = round1 + round2
+
+    subintervals = ((a, c, s1, err1), (c, b, s2, err2))
+    return dint, derr, dround_err, subintervals, dneval
+
+
+def _quadrature_trapezoid(x1, x2, f, norm_func):
+    """
+    Composite trapezoid quadrature
+    """
+    x3 = 0.5*(x1 + x2)
+    f1 = f(x1)
+    f2 = f(x2)
+    f3 = f(x3)
+
+    s2 = 0.25 * (x2 - x1) * (f1 + 2*f3 + f2)
+
+    round_err = 0.25 * abs(x2 - x1) * (float(norm_func(f1))
+                                       + 2*float(norm_func(f3))
+                                       + float(norm_func(f2))) * 2e-16
+
+    s1 = 0.5 * (x2 - x1) * (f1 + f2)
+    err = 1/3 * float(norm_func(s1 - s2))
+    return s2, err, round_err
+
+
+_quadrature_trapezoid.cache_size = 3 * 3  # pyrefly:ignore[missing-attribute]
+_quadrature_trapezoid.num_eval = 3  # pyrefly:ignore[missing-attribute]
+
+
+def _quadrature_gk(a, b, f, norm_func, x, w, v):
+    """
+    Generic Gauss-Kronrod quadrature
+    """
+
+    fv = [0.0]*len(x)
+
+    c = 0.5 * (a + b)
+    h = 0.5 * (b - a)
+
+    # Gauss-Kronrod
+    s_k = 0.0
+    s_k_abs = 0.0
+    for i in range(len(x)):
+        ff = f(c + h*x[i])
+        fv[i] = ff
+
+        vv = v[i]
+
+        # \int f(x)
+        s_k += vv * ff
+        # \int |f(x)|
+        s_k_abs += vv * abs(ff)
+
+    # Gauss
+    s_g = 0.0
+    for i in range(len(w)):
+        s_g += w[i] * fv[2*i + 1]
+
+    # Quadrature of abs-deviation from average
+    s_k_dabs = 0.0
+    y0 = s_k / 2.0
+    for i in range(len(x)):
+        # \int |f(x) - y0|
+        s_k_dabs += v[i] * abs(fv[i] - y0)
+
+    # Use similar error estimation as quadpack
+    err = float(norm_func((s_k - s_g) * h))
+    dabs = float(norm_func(s_k_dabs * h))
+    if dabs != 0 and err != 0:
+        err = dabs * min(1.0, (200 * err / dabs)**1.5)
+
+    eps = sys.float_info.epsilon
+    round_err = float(norm_func(50 * eps * h * s_k_abs))
+
+    if round_err > sys.float_info.min:
+        err = max(err, round_err)
+
+    return h * s_k, err, round_err
+
+
+def _quadrature_gk21(a, b, f, norm_func):
+    """
+    Gauss-Kronrod 21 quadrature with error estimate
+    """
+    # Gauss-Kronrod points
+    x = (0.995657163025808080735527280689003,
+         0.973906528517171720077964012084452,
+         0.930157491355708226001207180059508,
+         0.865063366688984510732096688423493,
+         0.780817726586416897063717578345042,
+         0.679409568299024406234327365114874,
+         0.562757134668604683339000099272694,
+         0.433395394129247190799265943165784,
+         0.294392862701460198131126603103866,
+         0.148874338981631210884826001129720,
+         0,
+         -0.148874338981631210884826001129720,
+         -0.294392862701460198131126603103866,
+         -0.433395394129247190799265943165784,
+         -0.562757134668604683339000099272694,
+         -0.679409568299024406234327365114874,
+         -0.780817726586416897063717578345042,
+         -0.865063366688984510732096688423493,
+         -0.930157491355708226001207180059508,
+         -0.973906528517171720077964012084452,
+         -0.995657163025808080735527280689003)
+
+    # 10-point weights
+    w = (0.066671344308688137593568809893332,
+         0.149451349150580593145776339657697,
+         0.219086362515982043995534934228163,
+         0.269266719309996355091226921569469,
+         0.295524224714752870173892994651338,
+         0.295524224714752870173892994651338,
+         0.269266719309996355091226921569469,
+         0.219086362515982043995534934228163,
+         0.149451349150580593145776339657697,
+         0.066671344308688137593568809893332)
+
+    # 21-point weights
+    v = (0.011694638867371874278064396062192,
+         0.032558162307964727478818972459390,
+         0.054755896574351996031381300244580,
+         0.075039674810919952767043140916190,
+         0.093125454583697605535065465083366,
+         0.109387158802297641899210590325805,
+         0.123491976262065851077958109831074,
+         0.134709217311473325928054001771707,
+         0.142775938577060080797094273138717,
+         0.147739104901338491374841515972068,
+         0.149445554002916905664936468389821,
+         0.147739104901338491374841515972068,
+         0.142775938577060080797094273138717,
+         0.134709217311473325928054001771707,
+         0.123491976262065851077958109831074,
+         0.109387158802297641899210590325805,
+         0.093125454583697605535065465083366,
+         0.075039674810919952767043140916190,
+         0.054755896574351996031381300244580,
+         0.032558162307964727478818972459390,
+         0.011694638867371874278064396062192)
+
+    return _quadrature_gk(a, b, f, norm_func, x, w, v)
+
+
+_quadrature_gk21.num_eval = 21  # pyrefly:ignore[missing-attribute]
+
+
+def _quadrature_gk15(a, b, f, norm_func):
+    """
+    Gauss-Kronrod 15 quadrature with error estimate
+    """
+    # Gauss-Kronrod points
+    x = (0.991455371120812639206854697526329,
+         0.949107912342758524526189684047851,
+         0.864864423359769072789712788640926,
+         0.741531185599394439863864773280788,
+         0.586087235467691130294144838258730,
+         0.405845151377397166906606412076961,
+         0.207784955007898467600689403773245,
+         0.000000000000000000000000000000000,
+         -0.207784955007898467600689403773245,
+         -0.405845151377397166906606412076961,
+         -0.586087235467691130294144838258730,
+         -0.741531185599394439863864773280788,
+         -0.864864423359769072789712788640926,
+         -0.949107912342758524526189684047851,
+         -0.991455371120812639206854697526329)
+
+    # 7-point weights
+    w = (0.129484966168869693270611432679082,
+         0.279705391489276667901467771423780,
+         0.381830050505118944950369775488975,
+         0.417959183673469387755102040816327,
+         0.381830050505118944950369775488975,
+         0.279705391489276667901467771423780,
+         0.129484966168869693270611432679082)
+
+    # 15-point weights
+    v = (0.022935322010529224963732008058970,
+         0.063092092629978553290700663189204,
+         0.104790010322250183839876322541518,
+         0.140653259715525918745189590510238,
+         0.169004726639267902826583426598550,
+         0.190350578064785409913256402421014,
+         0.204432940075298892414161999234649,
+         0.209482141084727828012999174891714,
+         0.204432940075298892414161999234649,
+         0.190350578064785409913256402421014,
+         0.169004726639267902826583426598550,
+         0.140653259715525918745189590510238,
+         0.104790010322250183839876322541518,
+         0.063092092629978553290700663189204,
+         0.022935322010529224963732008058970)
+
+    return _quadrature_gk(a, b, f, norm_func, x, w, v)
+
+
+_quadrature_gk15.num_eval = 15  # pyrefly:ignore[missing-attribute]
diff --git a/.venv/lib/python3.12/site-packages/scipy/integrate/_quadpack.cpython-312-x86_64-linux-gnu.so b/.venv/lib/python3.12/site-packages/scipy/integrate/_quadpack.cpython-312-x86_64-linux-gnu.so
new file mode 100644
index 0000000000000000000000000000000000000000..72e2a4541858e8453b0b89107297982c85d195c4
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/integrate/_quadpack.cpython-312-x86_64-linux-gnu.so
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:df03afae0c0121e722aa8b41643fc17ecd4e6cdf667dc1526cff04bd1db81e67
+size 119920
diff --git a/.venv/lib/python3.12/site-packages/scipy/integrate/_quadpack_py.py b/.venv/lib/python3.12/site-packages/scipy/integrate/_quadpack_py.py
new file mode 100644
index 0000000000000000000000000000000000000000..9f9efb402870afba80c829ae006fed30a765d1cc
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/integrate/_quadpack_py.py
@@ -0,0 +1,1305 @@
+# Author: Travis Oliphant 2001
+# Author: Nathan Woods 2013 (nquad &c)
+import sys
+import warnings
+from functools import partial
+
+from . import _quadpack
+import numpy as np
+
+from scipy._lib._array_api import xp_capabilities
+
+__all__ = ["quad", "dblquad", "tplquad", "nquad", "IntegrationWarning"]
+
+
+class IntegrationWarning(UserWarning):
+    """
+    Warning on issues during integration.
+    """
+    pass
+
+
+@xp_capabilities(np_only=True)
+def quad(func, a, b, args=(), full_output=0, epsabs=1.49e-8, epsrel=1.49e-8,
+         limit=50, points=None, weight=None, wvar=None, wopts=None, maxp1=50,
+         limlst=50, complex_func=False):
+    """
+    Compute a definite integral.
+
+    Integrate func from `a` to `b` (possibly infinite interval) using a
+    technique from the Fortran library QUADPACK.
+
+    Parameters
+    ----------
+    func : {function, scipy.LowLevelCallable}
+        A Python function or method to integrate. If `func` takes many
+        arguments, it is integrated along the axis corresponding to the
+        first argument.
+
+        If the user desires improved integration performance, then `f` may
+        be a `scipy.LowLevelCallable` with one of the signatures::
+
+            double func(double x)
+            double func(double x, void *user_data)
+            double func(int n, double *xx)
+            double func(int n, double *xx, void *user_data)
+
+        The ``user_data`` is the data contained in the `scipy.LowLevelCallable`.
+        In the call forms with ``xx``,  ``n`` is the length of the ``xx``
+        array which contains ``xx[0] == x`` and the rest of the items are
+        numbers contained in the ``args`` argument of quad.
+
+        In addition, certain ctypes call signatures are supported for
+        backward compatibility, but those should not be used in new code.
+    a : float
+        Lower limit of integration (use -numpy.inf for -infinity).
+    b : float
+        Upper limit of integration (use numpy.inf for +infinity).
+    args : tuple, optional
+        Extra arguments to pass to `func`.
+    full_output : int, optional
+        Non-zero to return a dictionary of integration information.
+        If non-zero, warning messages are also suppressed and the
+        message is appended to the output tuple.
+
+    Returns
+    -------
+    y : float
+        The integral of func from `a` to `b`.
+    abserr : float
+        An estimate of the absolute error in the result.
+    infodict : dict
+        A dictionary containing additional information.
+    message
+        A convergence message.
+    explain
+        Appended only with 'cos' or 'sin' weighting and infinite
+        integration limits, it contains an explanation of the codes in
+        infodict['ierlst']
+
+    Other Parameters
+    ----------------
+    epsabs : float or int, optional
+        Absolute error tolerance. Default is 1.49e-8. `quad` tries to obtain
+        an accuracy of ``abs(i-result) <= max(epsabs, epsrel*abs(i))``
+        where ``i`` = integral of `func` from `a` to `b`, and ``result`` is the
+        numerical approximation. See `epsrel` below.
+    epsrel : float or int, optional
+        Relative error tolerance. Default is 1.49e-8.
+        If ``epsabs <= 0``, `epsrel` must be greater than both 5e-29
+        and ``50 * (machine epsilon)``. See `epsabs` above.
+    limit : float or int, optional
+        An upper bound on the number of subintervals used in the adaptive
+        algorithm.
+    points : (sequence of floats,ints), optional
+        A sequence of break points in the bounded integration interval
+        where local difficulties of the integrand may occur (e.g.,
+        singularities, discontinuities). The sequence does not have
+        to be sorted. Note that this option cannot be used in conjunction
+        with ``weight``.
+    weight : float or int, optional
+        String indicating weighting function. Full explanation for this
+        and the remaining arguments can be found below.
+    wvar : optional
+        Variables for use with weighting functions.
+    wopts : optional
+        Optional input for reusing Chebyshev moments.
+    maxp1 : float or int, optional
+        An upper bound on the number of Chebyshev moments.
+    limlst : int, optional
+        Upper bound on the number of cycles (>=3) for use with a sinusoidal
+        weighting and an infinite end-point.
+    complex_func : bool, optional
+        Indicate if the function's (`func`) return type is real
+        (``complex_func=False``: default) or complex (``complex_func=True``).
+        In both cases, the function's argument is real.
+        If full_output is also non-zero, the `infodict`, `message`, and
+        `explain` for the real and complex components are returned in
+        a dictionary with keys "real output" and "imag output".
+
+    See Also
+    --------
+    dblquad : double integral
+    tplquad : triple integral
+    nquad : n-dimensional integrals (uses `quad` recursively)
+    fixed_quad : fixed-order Gaussian quadrature
+    simpson : integrator for sampled data
+    romb : integrator for sampled data
+    scipy.special : for coefficients and roots of orthogonal polynomials
+
+    Notes
+    -----
+    For valid results, the integral must converge; behavior for divergent
+    integrals is not guaranteed.
+
+    **Extra information for quad() inputs and outputs**
+
+    If full_output is non-zero, then the third output argument
+    (infodict) is a dictionary with entries as tabulated below. For
+    infinite limits, the range is transformed to (0,1) and the
+    optional outputs are given with respect to this transformed range.
+    Let M be the input argument limit and let K be infodict['last'].
+    The entries are:
+
+    'neval'
+        The number of function evaluations.
+    'last'
+        The number, K, of subintervals produced in the subdivision process.
+    'alist'
+        A rank-1 array of length M, the first K elements of which are the
+        left end points of the subintervals in the partition of the
+        integration range.
+    'blist'
+        A rank-1 array of length M, the first K elements of which are the
+        right end points of the subintervals.
+    'rlist'
+        A rank-1 array of length M, the first K elements of which are the
+        integral approximations on the subintervals.
+    'elist'
+        A rank-1 array of length M, the first K elements of which are the
+        moduli of the absolute error estimates on the subintervals.
+    'iord'
+        A rank-1 integer array of length M, the first L elements of
+        which are pointers to the error estimates over the subintervals
+        with ``L=K`` if ``K<=M/2+2`` or ``L=M+1-K`` otherwise. Let I be the
+        sequence ``infodict['iord']`` and let E be the sequence
+        ``infodict['elist']``.  Then ``E[I[1]], ..., E[I[L]]`` forms a
+        decreasing sequence.
+
+    If the input argument points is provided (i.e., it is not None),
+    the following additional outputs are placed in the output
+    dictionary. Assume the points sequence is of length P.
+
+    'pts'
+        A rank-1 array of length P+2 containing the integration limits
+        and the break points of the intervals in ascending order.
+        This is an array giving the subintervals over which integration
+        will occur.
+    'level'
+        A rank-1 integer array of length M (=limit), containing the
+        subdivision levels of the subintervals, i.e., if (aa,bb) is a
+        subinterval of ``(pts[1], pts[2])`` where ``pts[0]`` and ``pts[2]``
+        are adjacent elements of ``infodict['pts']``, then (aa,bb) has level l
+        if ``|bb-aa| = |pts[2]-pts[1]| * 2**(-l)``.
+    'ndin'
+        A rank-1 integer array of length P+2. After the first integration
+        over the intervals (pts[1], pts[2]), the error estimates over some
+        of the intervals may have been increased artificially in order to
+        put their subdivision forward. This array has ones in slots
+        corresponding to the subintervals for which this happens.
+
+    **Weighting the integrand**
+
+    The input variables, *weight* and *wvar*, are used to weight the
+    integrand by a select list of functions. Different integration
+    methods are used to compute the integral with these weighting
+    functions, and these do not support specifying break points. The
+    possible values of weight and the corresponding weighting functions are.
+
+    ==========  ===================================   =====================
+    ``weight``  Weight function used                  ``wvar``
+    ==========  ===================================   =====================
+    'cos'       cos(w*x)                              wvar = w
+    'sin'       sin(w*x)                              wvar = w
+    'alg'       g(x) = ((x-a)**alpha)*((b-x)**beta)   wvar = (alpha, beta)
+    'alg-loga'  g(x)*log(x-a)                         wvar = (alpha, beta)
+    'alg-logb'  g(x)*log(b-x)                         wvar = (alpha, beta)
+    'alg-log'   g(x)*log(x-a)*log(b-x)                wvar = (alpha, beta)
+    'cauchy'    1/(x-c)                               wvar = c
+    ==========  ===================================   =====================
+
+    wvar holds the parameter w, (alpha, beta), or c depending on the weight
+    selected. In these expressions, a and b are the integration limits.
+
+    For the 'cos' and 'sin' weighting, additional inputs and outputs are
+    available.
+
+    For weighted integrals with finite integration limits, the integration
+    is performed using a Clenshaw-Curtis method, which uses Chebyshev moments.
+    For repeated calculations, these moments are saved in the output dictionary:
+
+    'momcom'
+        The maximum level of Chebyshev moments that have been computed,
+        i.e., if ``M_c`` is ``infodict['momcom']`` then the moments have been
+        computed for intervals of length ``|b-a| * 2**(-l)``,
+        ``l=0,1,...,M_c``.
+    'nnlog'
+        A rank-1 integer array of length M(=limit), containing the
+        subdivision levels of the subintervals, i.e., an element of this
+        array is equal to l if the corresponding subinterval is
+        ``|b-a|* 2**(-l)``.
+    'chebmo'
+        A rank-2 array of shape (25, maxp1) containing the computed
+        Chebyshev moments. These can be passed on to an integration
+        over the same interval by passing this array as the second
+        element of the sequence wopts and passing infodict['momcom'] as
+        the first element.
+
+    If one of the integration limits is infinite, then a Fourier integral is
+    computed (assuming w neq 0). If full_output is 1 and a numerical error
+    is encountered, besides the error message attached to the output tuple,
+    a dictionary is also appended to the output tuple which translates the
+    error codes in the array ``info['ierlst']`` to English messages. The
+    output information dictionary contains the following entries instead of
+    'last', 'alist', 'blist', 'rlist', and 'elist':
+
+    'lst'
+        The number of subintervals needed for the integration (call it ``K_f``).
+    'rslst'
+        A rank-1 array of length M_f=limlst, whose first ``K_f`` elements
+        contain the integral contribution over the interval
+        ``(a+(k-1)c, a+kc)`` where ``c = (2*floor(|w|) + 1) * pi / |w|``
+        and ``k=1,2,...,K_f``.
+    'erlst'
+        A rank-1 array of length ``M_f`` containing the error estimate
+        corresponding to the interval in the same position in
+        ``infodict['rslist']``.
+    'ierlst'
+        A rank-1 integer array of length ``M_f`` containing an error flag
+        corresponding to the interval in the same position in
+        ``infodict['rslist']``.  See the explanation dictionary (last entry
+        in the output tuple) for the meaning of the codes.
+
+
+    **Details of QUADPACK level routines**
+
+    `quad` calls routines from the FORTRAN library QUADPACK. This section
+    provides details on the conditions for each routine to be called and a
+    short description of each routine. The routine called depends on
+    `weight`, `points` and the integration limits `a` and `b`.
+
+    ================  ==============  ==========  =====================
+    QUADPACK routine  `weight`        `points`    infinite bounds
+    ================  ==============  ==========  =====================
+    qagse             None            No          No
+    qagie             None            No          Yes
+    qagpe             None            Yes         No
+    qawoe             'sin', 'cos'    No          No
+    qawfe             'sin', 'cos'    No          either `a` or `b`
+    qawse             'alg*'          No          No
+    qawce             'cauchy'        No          No
+    ================  ==============  ==========  =====================
+
+    The following provides a short description from [1]_ for each
+    routine.
+
+    qagse
+        is an integrator based on globally adaptive interval
+        subdivision in connection with extrapolation, which will
+        eliminate the effects of integrand singularities of
+        several types. The integration is performed using a 21-point Gauss-Kronrod 
+        quadrature within each subinterval.
+    qagie
+        handles integration over infinite intervals. The infinite range is
+        mapped onto a finite interval and subsequently the same strategy as
+        in ``QAGS`` is applied.
+    qagpe
+        serves the same purposes as QAGS, but also allows the
+        user to provide explicit information about the location
+        and type of trouble-spots i.e. the abscissae of internal
+        singularities, discontinuities and other difficulties of
+        the integrand function.
+    qawoe
+        is an integrator for the evaluation of
+        :math:`\\int^b_a \\cos(\\omega x)f(x)dx` or
+        :math:`\\int^b_a \\sin(\\omega x)f(x)dx`
+        over a finite interval [a,b], where :math:`\\omega` and :math:`f`
+        are specified by the user. The rule evaluation component is based
+        on the modified Clenshaw-Curtis technique
+
+        An adaptive subdivision scheme is used in connection
+        with an extrapolation procedure, which is a modification
+        of that in ``QAGS`` and allows the algorithm to deal with
+        singularities in :math:`f(x)`.
+    qawfe
+        calculates the Fourier transform
+        :math:`\\int^\\infty_a \\cos(\\omega x)f(x)dx` or
+        :math:`\\int^\\infty_a \\sin(\\omega x)f(x)dx`
+        for user-provided :math:`\\omega` and :math:`f`. The procedure of
+        ``QAWO`` is applied on successive finite intervals, and convergence
+        acceleration by means of the :math:`\\varepsilon`-algorithm is applied
+        to the series of integral approximations.
+    qawse
+        approximate :math:`\\int^b_a w(x)f(x)dx`, with :math:`a < b` where
+        :math:`w(x) = (x-a)^{\\alpha}(b-x)^{\\beta}v(x)` with
+        :math:`\\alpha,\\beta > -1`, where :math:`v(x)` may be one of the
+        following functions: :math:`1`, :math:`\\log(x-a)`, :math:`\\log(b-x)`,
+        :math:`\\log(x-a)\\log(b-x)`.
+
+        The user specifies :math:`\\alpha`, :math:`\\beta` and the type of the
+        function :math:`v`. A globally adaptive subdivision strategy is
+        applied, with modified Clenshaw-Curtis integration on those
+        subintervals which contain `a` or `b`.
+    qawce
+        compute :math:`\\int^b_a f(x) / (x-c)dx` where the integral must be
+        interpreted as a Cauchy principal value integral, for user specified
+        :math:`c` and :math:`f`. The strategy is globally adaptive. Modified
+        Clenshaw-Curtis integration is used on those intervals containing the
+        point :math:`x = c`.
+
+    **Integration of Complex Function of a Real Variable**
+
+    A complex valued function, :math:`f`, of a real variable can be written as
+    :math:`f = g + ih`.  Similarly, the integral of :math:`f` can be
+    written as
+
+    .. math::
+        \\int_a^b f(x) dx = \\int_a^b g(x) dx + i\\int_a^b h(x) dx
+
+    assuming that the integrals of :math:`g` and :math:`h` exist
+    over the interval :math:`[a,b]` [2]_. Therefore, ``quad`` integrates
+    complex-valued functions by integrating the real and imaginary components
+    separately.
+
+
+    References
+    ----------
+
+    .. [1] Piessens, Robert; de Doncker-Kapenga, Elise;
+           Überhuber, Christoph W.; Kahaner, David (1983).
+           QUADPACK: A subroutine package for automatic integration.
+           Springer-Verlag.
+           ISBN 978-3-540-12553-2.
+
+    .. [2] McCullough, Thomas; Phillips, Keith (1973).
+           Foundations of Analysis in the Complex Plane.
+           Holt Rinehart Winston.
+           ISBN 0-03-086370-8
+
+    Examples
+    --------
+    Calculate :math:`\\int^4_0 x^2 dx` and compare with an analytic result
+
+    >>> from scipy import integrate
+    >>> import numpy as np
+    >>> x2 = lambda x: x**2
+    >>> integrate.quad(x2, 0, 4)
+    (21.333333333333332, 2.3684757858670003e-13)
+    >>> print(4**3 / 3.)  # analytical result
+    21.3333333333
+
+    Calculate :math:`\\int^\\infty_0 e^{-x} dx`
+
+    >>> invexp = lambda x: np.exp(-x)
+    >>> integrate.quad(invexp, 0, np.inf)
+    (1.0, 5.842605999138044e-11)
+
+    Calculate :math:`\\int^1_0 a x \\,dx` for :math:`a = 1, 3`
+
+    >>> f = lambda x, a: a*x
+    >>> y, err = integrate.quad(f, 0, 1, args=(1,))
+    >>> y
+    0.5
+    >>> y, err = integrate.quad(f, 0, 1, args=(3,))
+    >>> y
+    1.5
+
+    Calculate :math:`\\int^1_0 x^2 + y^2 dx` with ctypes, holding
+    y parameter as 1::
+
+        testlib.c =>
+            double func(int n, double args[n]){
+                return args[0]*args[0] + args[1]*args[1];}
+        compile to library testlib.*
+
+    ::
+
+       from scipy import integrate
+       import ctypes
+       lib = ctypes.CDLL('/home/.../testlib.*') #use absolute path
+       lib.func.restype = ctypes.c_double
+       lib.func.argtypes = (ctypes.c_int,ctypes.c_double)
+       integrate.quad(lib.func,0,1,(1))
+       #(1.3333333333333333, 1.4802973661668752e-14)
+       print((1.0**3/3.0 + 1.0) - (0.0**3/3.0 + 0.0)) #Analytic result
+       # 1.3333333333333333
+
+    Be aware that pulse shapes and other sharp features as compared to the
+    size of the integration interval may not be integrated correctly using
+    this method. A simplified example of this limitation is integrating a
+    y-axis reflected step function with many zero values within the integrals
+    bounds.
+
+    >>> y = lambda x: 1 if x<=0 else 0
+    >>> integrate.quad(y, -1, 1)
+    (1.0, 1.1102230246251565e-14)
+    >>> integrate.quad(y, -1, 100)
+    (1.0000000002199108, 1.0189464580163188e-08)
+    >>> integrate.quad(y, -1, 10000)
+    (0.0, 0.0)
+
+    """
+    if not isinstance(args, tuple):
+        args = (args,)
+
+    # Shortcut for empty interval, also works for improper integrals.
+    if a == b:
+        if full_output == 0:
+            return (0., 0.)
+        else:
+            infodict = {"neval": 0, "last": 0,
+                        "alist": np.full(limit, np.nan, dtype=np.float64),
+                        "blist": np.full(limit, np.nan, dtype=np.float64),
+                        "rlist": np.zeros(limit, dtype=np.float64),
+                        "elist": np.zeros(limit, dtype=np.float64),
+                        "iord" : np.zeros(limit, dtype=np.int32)}
+            if complex_func:
+                return (0.+0.j, 0.+0.j, {"real": infodict, "imag": infodict})
+            else:
+                return (0., 0., infodict)
+
+    # check the limits of integration: \int_a^b, expect a < b
+    flip, a, b = b < a, min(a, b), max(a, b)
+
+    if complex_func:
+        def imfunc(x, *args):
+            return func(x, *args).imag
+
+        def refunc(x, *args):
+            return func(x, *args).real
+
+        re_retval = quad(refunc, a, b, args, full_output, epsabs,
+                         epsrel, limit, points, weight, wvar, wopts,
+                         maxp1, limlst, complex_func=False)
+        im_retval = quad(imfunc, a, b, args, full_output, epsabs,
+                         epsrel, limit, points, weight, wvar, wopts,
+                         maxp1, limlst, complex_func=False)
+        integral = re_retval[0] + 1j*im_retval[0]
+        error_estimate = re_retval[1] + 1j*im_retval[1]
+        retval = integral, error_estimate
+        if full_output:
+            msgexp = {}
+            msgexp["real"] = re_retval[2:]
+            msgexp["imag"] = im_retval[2:]
+            retval = retval + (msgexp,)
+
+        return retval
+
+    if weight is None:
+        retval = _quad(func, a, b, args, full_output, epsabs, epsrel, limit,
+                       points)
+    else:
+        if points is not None:
+            msg = ("Break points cannot be specified when using weighted integrand.\n"
+                   "Continuing, ignoring specified points.")
+            warnings.warn(msg, IntegrationWarning, stacklevel=2)
+        retval = _quad_weight(func, a, b, args, full_output, epsabs, epsrel,
+                              limlst, limit, maxp1, weight, wvar, wopts)
+
+    if flip:
+        retval = (-retval[0],) + retval[1:]
+
+    ier = retval[-1]
+    if ier == 0:
+        return retval[:-1]
+
+    msgs = {80: "A Python error occurred possibly while calling the function.",
+             1: f"The maximum number of subdivisions ({limit}) has been achieved.\n  "
+                f"If increasing the limit yields no improvement it is advised to "
+                f"analyze \n  the integrand in order to determine the difficulties.  "
+                f"If the position of a \n  local difficulty can be determined "
+                f"(singularity, discontinuity) one will \n  probably gain from "
+                f"splitting up the interval and calling the integrator \n  on the "
+                f"subranges.  Perhaps a special-purpose integrator should be used.",
+             2: "The occurrence of roundoff error is detected, which prevents \n  "
+                "the requested tolerance from being achieved.  "
+                "The error may be \n  underestimated.",
+             3: "Extremely bad integrand behavior occurs at some points of the\n  "
+                "integration interval.",
+             4: "The algorithm does not converge.  Roundoff error is detected\n  "
+                "in the extrapolation table.  It is assumed that the requested "
+                "tolerance\n  cannot be achieved, and that the returned result "
+                "(if full_output = 1) is \n  the best which can be obtained.",
+             5: "The integral is probably divergent, or slowly convergent.",
+             6: "The input is invalid.",
+             7: "Abnormal termination of the routine.  The estimates for result\n  "
+                "and error are less reliable.  It is assumed that the requested "
+                "accuracy\n  has not been achieved.",
+            'unknown': "Unknown error."}
+
+    if weight in ['cos','sin'] and (b == np.inf or a == -np.inf):
+        msgs[1] = (
+            "The maximum number of cycles allowed has been achieved., e.e.\n  of "
+            "subintervals (a+(k-1)c, a+kc) where c = (2*int(abs(omega)+1))\n  "
+            "*pi/abs(omega), for k = 1, 2, ..., lst.  "
+            "One can allow more cycles by increasing the value of limlst.  "
+            "Look at info['ierlst'] with full_output=1."
+        )
+        msgs[4] = (
+            "The extrapolation table constructed for convergence acceleration\n  of "
+            "the series formed by the integral contributions over the cycles, \n  does "
+            "not converge to within the requested accuracy.  "
+            "Look at \n  info['ierlst'] with full_output=1."
+        )
+        msgs[7] = (
+            "Bad integrand behavior occurs within one or more of the cycles.\n  "
+            "Location and type of the difficulty involved can be determined from \n  "
+            "the vector info['ierlist'] obtained with full_output=1."
+        )
+        explain = {1: "The maximum number of subdivisions (= limit) has been \n  "
+                      "achieved on this cycle.",
+                   2: "The occurrence of roundoff error is detected and prevents\n  "
+                      "the tolerance imposed on this cycle from being achieved.",
+                   3: "Extremely bad integrand behavior occurs at some points of\n  "
+                      "this cycle.",
+                   4: "The integral over this cycle does not converge (to within the "
+                      "required accuracy) due to roundoff in the extrapolation "
+                      "procedure invoked on this cycle.  It is assumed that the result "
+                      "on this interval is the best which can be obtained.",
+                   5: "The integral over this cycle is probably divergent or "
+                      "slowly convergent."}
+
+    try:
+        msg = msgs[ier]
+    except KeyError:
+        msg = msgs['unknown']
+
+    if ier in [1,2,3,4,5,7]:
+        if full_output:
+            if weight in ['cos', 'sin'] and (b == np.inf or a == -np.inf):
+                return retval[:-1] + (msg, explain)
+            else:
+                return retval[:-1] + (msg,)
+        else:
+            warnings.warn(msg, IntegrationWarning, stacklevel=2)
+            return retval[:-1]
+
+    elif ier == 6:  # Forensic decision tree when QUADPACK throws ier=6
+        if epsabs <= 0:  # Small error tolerance - applies to all methods
+            if epsrel < max(50 * sys.float_info.epsilon, 5e-29):
+                msg = ("If 'epsabs'<=0, 'epsrel' must be greater than both"
+                       " 5e-29 and 50*(machine epsilon).")
+            elif weight in ['sin', 'cos'] and (abs(a) + abs(b) == np.inf):
+                msg = ("Sine or cosine weighted integrals with infinite domain"
+                       " must have 'epsabs'>0.")
+
+        elif weight is None:
+            if points is None:  # QAGSE/QAGIE
+                msg = ("Invalid 'limit' argument. There must be"
+                       " at least one subinterval")
+            else:  # QAGPE
+                if not (min(a, b) <= min(points) <= max(points) <= max(a, b)):
+                    msg = ("All break points in 'points' must lie within the"
+                           " integration limits.")
+                elif len(points) >= limit:
+                    msg = (f"Number of break points ({len(points):d}) "
+                           f"must be less than subinterval limit ({limit:d})")
+
+        else:
+            if maxp1 < 1:
+                msg = "Chebyshev moment limit maxp1 must be >=1."
+
+            elif weight in ('cos', 'sin') and abs(a+b) == np.inf:  # QAWFE
+                msg = "Cycle limit limlst must be >=3."
+
+            elif weight.startswith('alg'):  # QAWSE
+                if min(wvar) < -1:
+                    msg = "wvar parameters (alpha, beta) must both be >= -1."
+                if b < a:
+                    msg = "Integration limits a, b must satistfy a>> import numpy as np
+    >>> from scipy import integrate
+    >>> f = lambda y, x: x*y**2
+    >>> integrate.dblquad(f, 0, 2, 0, 1)
+        (0.6666666666666667, 7.401486830834377e-15)
+
+    Calculate :math:`\\int^{x=\\pi/4}_{x=0} \\int^{y=\\cos(x)}_{y=\\sin(x)} 1
+    \\,dy \\,dx`.
+
+    >>> f = lambda y, x: 1
+    >>> integrate.dblquad(f, 0, np.pi/4, np.sin, np.cos)
+        (0.41421356237309503, 1.1083280054755938e-14)
+
+    Calculate :math:`\\int^{x=1}_{x=0} \\int^{y=2-x}_{y=x} a x y \\,dy \\,dx`
+    for :math:`a=1, 3`.
+
+    >>> f = lambda y, x, a: a*x*y
+    >>> integrate.dblquad(f, 0, 1, lambda x: x, lambda x: 2-x, args=(1,))
+        (0.33333333333333337, 5.551115123125783e-15)
+    >>> integrate.dblquad(f, 0, 1, lambda x: x, lambda x: 2-x, args=(3,))
+        (0.9999999999999999, 1.6653345369377348e-14)
+
+    Compute the two-dimensional Gaussian Integral, which is the integral of the
+    Gaussian function :math:`f(x,y) = e^{-(x^{2} + y^{2})}`, over
+    :math:`(-\\infty,+\\infty)`. That is, compute the integral
+    :math:`\\iint^{+\\infty}_{-\\infty} e^{-(x^{2} + y^{2})} \\,dy\\,dx`.
+
+    >>> f = lambda x, y: np.exp(-(x ** 2 + y ** 2))
+    >>> integrate.dblquad(f, -np.inf, np.inf, -np.inf, np.inf)
+        (3.141592653589777, 2.5173086737433208e-08)
+
+    """
+
+    def temp_ranges(*args):
+        return [gfun(args[0]) if callable(gfun) else gfun,
+                hfun(args[0]) if callable(hfun) else hfun]
+
+    return nquad(func, [temp_ranges, [a, b]], args=args,
+            opts={"epsabs": epsabs, "epsrel": epsrel})
+
+
+@xp_capabilities(np_only=True)
+def tplquad(func, a, b, gfun, hfun, qfun, rfun, args=(), epsabs=1.49e-8,
+            epsrel=1.49e-8):
+    """
+    Compute a triple (definite) integral.
+
+    Return the triple integral of ``func(z, y, x)`` from ``x = a..b``,
+    ``y = gfun(x)..hfun(x)``, and ``z = qfun(x,y)..rfun(x,y)``.
+
+    Parameters
+    ----------
+    func : function
+        A Python function or method of at least three variables in the
+        order (z, y, x).
+    a, b : float
+        The limits of integration in x: `a` < `b`
+    gfun : function or float
+        The lower boundary curve in y which is a function taking a single
+        floating point argument (x) and returning a floating point result
+        or a float indicating a constant boundary curve.
+    hfun : function or float
+        The upper boundary curve in y (same requirements as `gfun`).
+    qfun : function or float
+        The lower boundary surface in z.  It must be a function that takes
+        two floats in the order (x, y) and returns a float or a float
+        indicating a constant boundary surface.
+    rfun : function or float
+        The upper boundary surface in z. (Same requirements as `qfun`.)
+    args : tuple, optional
+        Extra arguments to pass to `func`.
+    epsabs : float, optional
+        Absolute tolerance passed directly to the innermost 1-D quadrature
+        integration. Default is 1.49e-8.
+    epsrel : float, optional
+        Relative tolerance of the innermost 1-D integrals. Default is 1.49e-8.
+
+    Returns
+    -------
+    y : float
+        The resultant integral.
+    abserr : float
+        An estimate of the error.
+
+    See Also
+    --------
+    quad : Adaptive quadrature using QUADPACK
+    fixed_quad : Fixed-order Gaussian quadrature
+    dblquad : Double integrals
+    nquad : N-dimensional integrals
+    romb : Integrators for sampled data
+    simpson : Integrators for sampled data
+    scipy.special : For coefficients and roots of orthogonal polynomials
+
+    Notes
+    -----
+    For valid results, the integral must converge; behavior for divergent
+    integrals is not guaranteed.
+
+    **Details of QUADPACK level routines**
+
+    `quad` calls routines from the FORTRAN library QUADPACK. This section
+    provides details on the conditions for each routine to be called and a
+    short description of each routine. For each level of integration, ``qagse``
+    is used for finite limits or ``qagie`` is used, if either limit (or both!)
+    are infinite. The following provides a short description from [1]_ for each
+    routine.
+
+    qagse
+        is an integrator based on globally adaptive interval
+        subdivision in connection with extrapolation, which will
+        eliminate the effects of integrand singularities of
+        several types. The integration is is performed using a 21-point Gauss-Kronrod 
+        quadrature within each subinterval.
+    qagie
+        handles integration over infinite intervals. The infinite range is
+        mapped onto a finite interval and subsequently the same strategy as
+        in ``QAGS`` is applied.
+
+    References
+    ----------
+
+    .. [1] Piessens, Robert; de Doncker-Kapenga, Elise;
+           Überhuber, Christoph W.; Kahaner, David (1983).
+           QUADPACK: A subroutine package for automatic integration.
+           Springer-Verlag.
+           ISBN 978-3-540-12553-2.
+
+    Examples
+    --------
+    Compute the triple integral of ``x * y * z``, over ``x`` ranging
+    from 1 to 2, ``y`` ranging from 2 to 3, ``z`` ranging from 0 to 1.
+    That is, :math:`\\int^{x=2}_{x=1} \\int^{y=3}_{y=2} \\int^{z=1}_{z=0} x y z
+    \\,dz \\,dy \\,dx`.
+
+    >>> import numpy as np
+    >>> from scipy import integrate
+    >>> f = lambda z, y, x: x*y*z
+    >>> integrate.tplquad(f, 1, 2, 2, 3, 0, 1)
+    (1.8749999999999998, 3.3246447942574074e-14)
+
+    Calculate :math:`\\int^{x=1}_{x=0} \\int^{y=1-2x}_{y=0}
+    \\int^{z=1-x-2y}_{z=0} x y z \\,dz \\,dy \\,dx`.
+    Note: `qfun`/`rfun` takes arguments in the order (x, y), even though ``f``
+    takes arguments in the order (z, y, x).
+
+    >>> f = lambda z, y, x: x*y*z
+    >>> integrate.tplquad(f, 0, 1, 0, lambda x: 1-2*x, 0, lambda x, y: 1-x-2*y)
+    (0.05416666666666668, 2.1774196738157757e-14)
+
+    Calculate :math:`\\int^{x=1}_{x=0} \\int^{y=1}_{y=0} \\int^{z=1}_{z=0}
+    a x y z \\,dz \\,dy \\,dx` for :math:`a=1, 3`.
+
+    >>> f = lambda z, y, x, a: a*x*y*z
+    >>> integrate.tplquad(f, 0, 1, 0, 1, 0, 1, args=(1,))
+        (0.125, 5.527033708952211e-15)
+    >>> integrate.tplquad(f, 0, 1, 0, 1, 0, 1, args=(3,))
+        (0.375, 1.6581101126856635e-14)
+
+    Compute the three-dimensional Gaussian Integral, which is the integral of
+    the Gaussian function :math:`f(x,y,z) = e^{-(x^{2} + y^{2} + z^{2})}`, over
+    :math:`(-\\infty,+\\infty)`. That is, compute the integral
+    :math:`\\iiint^{+\\infty}_{-\\infty} e^{-(x^{2} + y^{2} + z^{2})} \\,dz
+    \\,dy\\,dx`.
+
+    >>> f = lambda x, y, z: np.exp(-(x ** 2 + y ** 2 + z ** 2))
+    >>> integrate.tplquad(f, -np.inf, np.inf, -np.inf, np.inf, -np.inf, np.inf)
+        (5.568327996830833, 4.4619078828029765e-08)
+
+    """
+    # f(z, y, x)
+    # qfun/rfun(x, y)
+    # gfun/hfun(x)
+    # nquad will hand (y, x, t0, ...) to ranges0
+    # nquad will hand (x, t0, ...) to ranges1
+    # Only qfun / rfun is different API...
+
+    def ranges0(*args):
+        return [qfun(args[1], args[0]) if callable(qfun) else qfun,
+                rfun(args[1], args[0]) if callable(rfun) else rfun]
+
+    def ranges1(*args):
+        return [gfun(args[0]) if callable(gfun) else gfun,
+                hfun(args[0]) if callable(hfun) else hfun]
+
+    ranges = [ranges0, ranges1, [a, b]]
+    return nquad(func, ranges, args=args,
+            opts={"epsabs": epsabs, "epsrel": epsrel})
+
+
+@xp_capabilities(np_only=True)
+def nquad(func, ranges, args=None, opts=None, full_output=False):
+    r"""
+    Integration over multiple variables.
+
+    Wraps `quad` to enable integration over multiple variables.
+    Various options allow improved integration of discontinuous functions, as
+    well as the use of weighted integration, and generally finer control of the
+    integration process.
+
+    Parameters
+    ----------
+    func : {callable, scipy.LowLevelCallable}
+        The function to be integrated. Has arguments of ``x0, ..., xn``,
+        ``t0, ..., tm``, where integration is carried out over ``x0, ..., xn``,
+        which must be floats.  Where ``t0, ..., tm`` are extra arguments
+        passed in args.
+        Function signature should be ``func(x0, x1, ..., xn, t0, t1, ..., tm)``.
+        Integration is carried out in order.  That is, integration over ``x0``
+        is the innermost integral, and ``xn`` is the outermost.
+
+        If the user desires improved integration performance, then `f` may
+        be a `scipy.LowLevelCallable` with one of the signatures::
+
+            double func(int n, double *xx)
+            double func(int n, double *xx, void *user_data)
+
+        where ``n`` is the number of variables and args.  The ``xx`` array
+        contains the coordinates and extra arguments. ``user_data`` is the data
+        contained in the `scipy.LowLevelCallable`.
+    ranges : iterable object
+        Each element of ranges may be either a sequence  of 2 numbers, or else
+        a callable that returns such a sequence. ``ranges[0]`` corresponds to
+        integration over x0, and so on. If an element of ranges is a callable,
+        then it will be called with all of the integration arguments available,
+        as well as any parametric arguments. e.g., if
+        ``func = f(x0, x1, x2, t0, t1)``, then ``ranges[0]`` may be defined as
+        either ``(a, b)`` or else as ``(a, b) = range0(x1, x2, t0, t1)``.
+    args : iterable object, optional
+        Additional arguments ``t0, ..., tn``, required by ``func``, ``ranges``,
+        and ``opts``.
+    opts : iterable object or dict, optional
+        Options to be passed to `quad`. May be empty, a dict, or
+        a sequence of dicts or functions that return a dict. If empty, the
+        default options from scipy.integrate.quad are used. If a dict, the same
+        options are used for all levels of integraion. If a sequence, then each
+        element of the sequence corresponds to a particular integration. e.g.,
+        ``opts[0]`` corresponds to integration over ``x0``, and so on. If a
+        callable, the signature must be the same as for ``ranges``. The
+        available options together with their default values are:
+
+        - ``epsabs = 1.49e-08``
+        - ``epsrel = 1.49e-08``
+        - ``limit  = 50``
+        - ``points = None``
+        - ``weight = None``
+        - ``wvar   = None``
+        - ``wopts  = None``
+
+        For more information on these options, see `quad`.
+
+    full_output : bool, optional
+        Partial implementation of ``full_output`` from scipy.integrate.quad.
+        The number of integrand function evaluations ``neval`` can be obtained
+        by setting ``full_output=True`` when calling nquad.
+
+    Returns
+    -------
+    result : float
+        The result of the integration.
+    abserr : float
+        The maximum of the estimates of the absolute error in the various
+        integration results.
+    out_dict : dict, optional
+        A dict containing additional information on the integration.
+
+    See Also
+    --------
+    quad : 1-D numerical integration
+    dblquad, tplquad : double and triple integrals
+    fixed_quad : fixed-order Gaussian quadrature
+
+    Notes
+    -----
+    For valid results, the integral must converge; behavior for divergent
+    integrals is not guaranteed.
+
+    **Details of QUADPACK level routines**
+
+    `nquad` calls routines from the FORTRAN library QUADPACK. This section
+    provides details on the conditions for each routine to be called and a
+    short description of each routine. The routine called depends on
+    `weight`, `points` and the integration limits `a` and `b`.
+
+    ================  ==============  ==========  =====================
+    QUADPACK routine  `weight`        `points`    infinite bounds
+    ================  ==============  ==========  =====================
+    qagse             None            No          No
+    qagie             None            No          Yes
+    qagpe             None            Yes         No
+    qawoe             'sin', 'cos'    No          No
+    qawfe             'sin', 'cos'    No          either `a` or `b`
+    qawse             'alg*'          No          No
+    qawce             'cauchy'        No          No
+    ================  ==============  ==========  =====================
+
+    The following provides a short description from [1]_ for each
+    routine.
+
+    qagse
+        is an integrator based on globally adaptive interval
+        subdivision in connection with extrapolation, which will
+        eliminate the effects of integrand singularities of
+        several types. The integration is is performed using a 21-point Gauss-Kronrod
+        quadrature within each subinterval.
+    qagie
+        handles integration over infinite intervals. The infinite range is
+        mapped onto a finite interval and subsequently the same strategy as
+        in ``QAGS`` is applied.
+    qagpe
+        serves the same purposes as QAGS, but also allows the
+        user to provide explicit information about the location
+        and type of trouble-spots i.e. the abscissae of internal
+        singularities, discontinuities and other difficulties of
+        the integrand function.
+    qawoe
+        is an integrator for the evaluation of
+        :math:`\int^b_a \cos(\omega x)f(x)dx` or
+        :math:`\int^b_a \sin(\omega x)f(x)dx`
+        over a finite interval [a,b], where :math:`\omega` and :math:`f`
+        are specified by the user. The rule evaluation component is based
+        on the modified Clenshaw-Curtis technique
+
+        An adaptive subdivision scheme is used in connection
+        with an extrapolation procedure, which is a modification
+        of that in ``QAGS`` and allows the algorithm to deal with
+        singularities in :math:`f(x)`.
+    qawfe
+        calculates the Fourier transform
+        :math:`\int^\infty_a \cos(\omega x)f(x)dx` or
+        :math:`\int^\infty_a \sin(\omega x)f(x)dx`
+        for user-provided :math:`\omega` and :math:`f`. The procedure of
+        ``QAWO`` is applied on successive finite intervals, and convergence
+        acceleration by means of the :math:`\varepsilon`-algorithm is applied
+        to the series of integral approximations.
+    qawse
+        approximate :math:`\int^b_a w(x)f(x)dx`, with :math:`a < b` where
+        :math:`w(x) = (x-a)^{\alpha}(b-x)^{\beta}v(x)` with
+        :math:`\alpha,\beta > -1`, where :math:`v(x)` may be one of the
+        following functions: :math:`1`, :math:`\log(x-a)`, :math:`\log(b-x)`,
+        :math:`\log(x-a)\log(b-x)`.
+
+        The user specifies :math:`\alpha`, :math:`\beta` and the type of the
+        function :math:`v`. A globally adaptive subdivision strategy is
+        applied, with modified Clenshaw-Curtis integration on those
+        subintervals which contain `a` or `b`.
+    qawce
+        compute :math:`\int^b_a f(x) / (x-c)dx` where the integral must be
+        interpreted as a Cauchy principal value integral, for user specified
+        :math:`c` and :math:`f`. The strategy is globally adaptive. Modified
+        Clenshaw-Curtis integration is used on those intervals containing the
+        point :math:`x = c`.
+
+    References
+    ----------
+
+    .. [1] Piessens, Robert; de Doncker-Kapenga, Elise;
+           Überhuber, Christoph W.; Kahaner, David (1983).
+           QUADPACK: A subroutine package for automatic integration.
+           Springer-Verlag.
+           ISBN 978-3-540-12553-2.
+
+    Examples
+    --------
+    Calculate
+
+    .. math::
+
+        \int^{1}_{-0.15} \int^{0.8}_{0.13} \int^{1}_{-1} \int^{1}_{0}
+        f(x_0, x_1, x_2, x_3) \,dx_0 \,dx_1 \,dx_2 \,dx_3 ,
+
+    where
+
+    .. math::
+
+        f(x_0, x_1, x_2, x_3) = \begin{cases}
+          x_0^2+x_1 x_2-x_3^3+ \sin{x_0}+1 & (x_0-0.2 x_3-0.5-0.25 x_1 > 0) \\
+          x_0^2+x_1 x_2-x_3^3+ \sin{x_0}+0 & (x_0-0.2 x_3-0.5-0.25 x_1 \leq 0)
+        \end{cases} .
+
+    >>> import numpy as np
+    >>> from scipy import integrate
+    >>> func = lambda x0,x1,x2,x3 : x0**2 + x1*x2 - x3**3 + np.sin(x0) + (
+    ...                                 1 if (x0-.2*x3-.5-.25*x1>0) else 0)
+    >>> def opts0(*args, **kwargs):
+    ...     return {'points':[0.2*args[2] + 0.5 + 0.25*args[0]]}
+    >>> integrate.nquad(func, [[0,1], [-1,1], [.13,.8], [-.15,1]],
+    ...                 opts=[opts0,{},{},{}], full_output=True)
+    (1.5267454070738633, 2.9437360001402324e-14, {'neval': 388962})
+
+    Calculate
+
+    .. math::
+
+        \int^{t_0+t_1+1}_{t_0+t_1-1}
+        \int^{x_2+t_0^2 t_1^3+1}_{x_2+t_0^2 t_1^3-1}
+        \int^{t_0 x_1+t_1 x_2+1}_{t_0 x_1+t_1 x_2-1}
+        f(x_0,x_1, x_2,t_0,t_1)
+        \,dx_0 \,dx_1 \,dx_2,
+
+    where
+
+    .. math::
+
+        f(x_0, x_1, x_2, t_0, t_1) = \begin{cases}
+          x_0 x_2^2 + \sin{x_1}+2 & (x_0+t_1 x_1-t_0 > 0) \\
+          x_0 x_2^2 +\sin{x_1}+1 & (x_0+t_1 x_1-t_0 \leq 0)
+        \end{cases}
+
+    and :math:`(t_0, t_1) = (0, 1)` .
+
+    >>> def func2(x0, x1, x2, t0, t1):
+    ...     return x0*x2**2 + np.sin(x1) + 1 + (1 if x0+t1*x1-t0>0 else 0)
+    >>> def lim0(x1, x2, t0, t1):
+    ...     return [t0*x1 + t1*x2 - 1, t0*x1 + t1*x2 + 1]
+    >>> def lim1(x2, t0, t1):
+    ...     return [x2 + t0**2*t1**3 - 1, x2 + t0**2*t1**3 + 1]
+    >>> def lim2(t0, t1):
+    ...     return [t0 + t1 - 1, t0 + t1 + 1]
+    >>> def opts0(x1, x2, t0, t1):
+    ...     return {'points' : [t0 - t1*x1]}
+    >>> def opts1(x2, t0, t1):
+    ...     return {}
+    >>> def opts2(t0, t1):
+    ...     return {}
+    >>> integrate.nquad(func2, [lim0, lim1, lim2], args=(0,1),
+    ...                 opts=[opts0, opts1, opts2])
+    (36.099919226771625, 1.8546948553373528e-07)
+
+    """
+    depth = len(ranges)
+    ranges = [rng if callable(rng) else _RangeFunc(rng) for rng in ranges]
+    if args is None:
+        args = ()
+    if opts is None:
+        opts = [dict([])] * depth
+
+    if isinstance(opts, dict):
+        opts = [_OptFunc(opts)] * depth
+    else:
+        opts = [opt if callable(opt) else _OptFunc(opt) for opt in opts]
+    return _NQuad(func, ranges, opts, full_output).integrate(*args)
+
+
+class _RangeFunc:
+    def __init__(self, range_):
+        self.range_ = range_
+
+    def __call__(self, *args):
+        """Return stored value.
+
+        *args needed because range_ can be float or func, and is called with
+        variable number of parameters.
+        """
+        return self.range_
+
+
+class _OptFunc:
+    def __init__(self, opt):
+        self.opt = opt
+
+    def __call__(self, *args):
+        """Return stored dict."""
+        return self.opt
+
+
+class _NQuad:
+    def __init__(self, func, ranges, opts, full_output):
+        self.abserr = 0
+        self.func = func
+        self.ranges = ranges
+        self.opts = opts
+        self.maxdepth = len(ranges)
+        self.full_output = full_output
+        if self.full_output:
+            self.out_dict = {'neval': 0}
+
+    def integrate(self, *args, **kwargs):
+        depth = kwargs.pop('depth', 0)
+        if kwargs:
+            raise ValueError('unexpected kwargs')
+
+        # Get the integration range and options for this depth.
+        ind = -(depth + 1)
+        fn_range = self.ranges[ind]
+        low, high = fn_range(*args)
+        fn_opt = self.opts[ind]
+        opt = dict(fn_opt(*args))
+
+        if 'points' in opt:
+            opt['points'] = [x for x in opt['points'] if low <= x <= high]
+        if depth + 1 == self.maxdepth:
+            f = self.func
+        else:
+            f = partial(self.integrate, depth=depth+1)
+        quad_r = quad(f, low, high, args=args, full_output=self.full_output,
+                      **opt)
+        value = quad_r[0]
+        abserr = quad_r[1]
+        if self.full_output:
+            infodict = quad_r[2]
+            # The 'neval' parameter in full_output returns the total
+            # number of times the integrand function was evaluated.
+            # Therefore, only the innermost integration loop counts.
+            if depth + 1 == self.maxdepth:
+                self.out_dict['neval'] += infodict['neval']
+        self.abserr = max(self.abserr, abserr)
+        if depth > 0:
+            return value
+        else:
+            # Final result of N-D integration with error
+            if self.full_output:
+                return value, self.abserr, self.out_dict
+            else:
+                return value, self.abserr
diff --git a/.venv/lib/python3.12/site-packages/scipy/integrate/_quadrature.py b/.venv/lib/python3.12/site-packages/scipy/integrate/_quadrature.py
new file mode 100644
index 0000000000000000000000000000000000000000..352cf1375ad13a048618800b105cc88648d92b0a
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/integrate/_quadrature.py
@@ -0,0 +1,1350 @@
+import numpy as np
+import math
+import warnings
+from collections import namedtuple
+from collections.abc import Callable
+
+from scipy.special import roots_legendre
+from scipy.special import gammaln, logsumexp
+from scipy._lib._util import _rng_spawn
+from scipy._lib._array_api import (_asarray, array_namespace, xp_result_type, xp_copy,
+                                   xp_capabilities, xp_promote, xp_swapaxes, is_numpy,
+                                   xp_size,
+                                   is_lazy_array)
+import scipy._external.array_api_extra as xpx
+
+
+__all__ = ['fixed_quad', 'romb',
+           'trapezoid', 'simpson',
+           'cumulative_trapezoid', 'newton_cotes',
+           'qmc_quad', 'cumulative_simpson']
+
+
+@xp_capabilities(skip_backends=[('jax.numpy',
+                                 "JAX arrays do not support item assignment")])
+def trapezoid(y, x=None, dx=1.0, axis=-1):
+    r"""
+    Integrate along the given axis using the composite trapezoidal rule.
+
+    If `x` is provided, the integration happens in sequence along its
+    elements - they are not sorted.
+
+    Integrate `y` (`x`) along each 1d slice on the given axis, compute
+    :math:`\int y(x) dx`.
+    When `x` is specified, this integrates along the parametric curve,
+    computing :math:`\int_t y(t) dt =
+    \int_t y(t) \left.\frac{dx}{dt}\right|_{x=x(t)} dt`.
+
+    Parameters
+    ----------
+    y : array_like
+        Input array to integrate.
+    x : array_like, optional
+        The sample points corresponding to the `y` values. If `x` is None,
+        the sample points are assumed to be evenly spaced `dx` apart. The
+        default is None.
+    dx : scalar, optional
+        The spacing between sample points when `x` is None. The default is 1.
+    axis : int, optional
+        The axis along which to integrate. The default is the last axis.
+
+    Returns
+    -------
+    trapezoid : float or ndarray
+        Definite integral of `y` = n-dimensional array as approximated along
+        a single axis by the trapezoidal rule. If `y` is a 1-dimensional array,
+        then the result is a float. If `n` is greater than 1, then the result
+        is an `n`-1 dimensional array.
+
+    See Also
+    --------
+    cumulative_trapezoid, simpson, romb
+
+    Notes
+    -----
+    Image [2]_ illustrates trapezoidal rule -- y-axis locations of points
+    will be taken from `y` array, by default x-axis distances between
+    points will be 1.0, alternatively they can be provided with `x` array
+    or with `dx` scalar.  Return value will be equal to combined area under
+    the red lines.
+
+    References
+    ----------
+    .. [1] Wikipedia page: https://en.wikipedia.org/wiki/Trapezoidal_rule
+
+    .. [2] Illustration image:
+           https://en.wikipedia.org/wiki/File:Composite_trapezoidal_rule_illustration.png
+
+    Examples
+    --------
+    Use the trapezoidal rule on evenly spaced points:
+
+    >>> import numpy as np
+    >>> from scipy import integrate
+    >>> integrate.trapezoid([1, 2, 3])
+    4.0
+
+    The spacing between sample points can be selected by either the
+    ``x`` or ``dx`` arguments:
+
+    >>> integrate.trapezoid([1, 2, 3], x=[4, 6, 8])
+    8.0
+    >>> integrate.trapezoid([1, 2, 3], dx=2)
+    8.0
+
+    Using a decreasing ``x`` corresponds to integrating in reverse:
+
+    >>> integrate.trapezoid([1, 2, 3], x=[8, 6, 4])
+    -8.0
+
+    More generally ``x`` is used to integrate along a parametric curve. We can
+    estimate the integral :math:`\int_0^1 x^2 = 1/3` using:
+
+    >>> x = np.linspace(0, 1, num=50)
+    >>> y = x**2
+    >>> integrate.trapezoid(y, x)
+    0.33340274885464394
+
+    Or estimate the area of a circle, noting we repeat the sample which closes
+    the curve:
+
+    >>> theta = np.linspace(0, 2 * np.pi, num=1000, endpoint=True)
+    >>> integrate.trapezoid(np.cos(theta), x=np.sin(theta))
+    3.141571941375841
+
+    ``trapezoid`` can be applied along a specified axis to do multiple
+    computations in one call:
+
+    >>> a = np.arange(6).reshape(2, 3)
+    >>> a
+    array([[0, 1, 2],
+           [3, 4, 5]])
+    >>> integrate.trapezoid(a, axis=0)
+    array([1.5, 2.5, 3.5])
+    >>> integrate.trapezoid(a, axis=1)
+    array([2.,  8.])
+    """
+    xp = array_namespace(y)
+    y = _asarray(y, xp=xp, subok=True)
+    # Cannot just use the broadcasted arrays that are returned
+    # because trapezoid does not follow normal broadcasting rules
+    # cf. https://github.com/scipy/scipy/pull/21524#issuecomment-2354105942
+    result_dtype = xp_result_type(y, force_floating=True, xp=xp)
+    nd = y.ndim
+    slice1 = [slice(None)]*nd
+    slice2 = [slice(None)]*nd
+    slice1[axis] = slice(1, None)
+    slice2[axis] = slice(None, -1)
+    if x is None:
+        d = dx
+    else:
+        x = _asarray(x, xp=xp, subok=True)
+        if x.ndim == 1:
+            d = x[1:] - x[:-1]
+            # make d broadcastable to y
+            slice3 = [None] * nd
+            slice3[axis] = slice(None)
+            d = d[tuple(slice3)]
+        else:
+            # if x is n-D it should be broadcastable to y
+            x = xp.broadcast_to(x, y.shape)
+            d = x[tuple(slice1)] - x[tuple(slice2)]
+    try:
+        ret = xp.sum(
+            d * (y[tuple(slice1)] + y[tuple(slice2)]) / 2.0,
+            axis=axis, dtype=result_dtype
+        )
+    except ValueError:
+        # Operations didn't work, cast to ndarray
+        d = xp.asarray(d)
+        y = xp.asarray(y)
+        ret = xp.sum(
+            d * (y[tuple(slice1)] + y[tuple(slice2)]) / 2.0,
+            axis=axis, dtype=result_dtype
+        )
+    return ret
+
+
+def _cached_roots_legendre(n):
+    """
+    Cache roots_legendre results to speed up calls of the fixed_quad
+    function.
+    """
+    if n in _cached_roots_legendre.cache:
+        return _cached_roots_legendre.cache[n]
+
+    _cached_roots_legendre.cache[n] = roots_legendre(n)
+    return _cached_roots_legendre.cache[n]
+
+
+_cached_roots_legendre.cache = dict()  # pyrefly:ignore[missing-attribute]
+
+
+@xp_capabilities()
+def fixed_quad(func, a, b, args=(), n=5):
+    """
+    Compute a definite integral using fixed-order Gaussian quadrature.
+
+    Integrate `func` from `a` to `b` using Gaussian quadrature of
+    order `n`.
+
+    Parameters
+    ----------
+    func : callable
+        A Python function or method to integrate (must accept vector inputs).
+        If integrating a vector-valued function, the returned array must have
+        shape ``(..., len(x))``.
+    a : float
+        Lower limit of integration.
+    b : float
+        Upper limit of integration.
+    args : tuple, optional
+        Extra arguments to pass to function, if any.
+    n : int, optional
+        Order of quadrature integration. Default is 5.
+
+    Returns
+    -------
+    val : float
+        Gaussian quadrature approximation to the integral
+    none : None
+        Statically returned value of None
+
+    See Also
+    --------
+    quad : adaptive quadrature using QUADPACK
+    dblquad : double integrals
+    tplquad : triple integrals
+    romb : integrators for sampled data
+    simpson : integrators for sampled data
+    cumulative_trapezoid : cumulative integration for sampled data
+
+    Examples
+    --------
+    >>> from scipy import integrate
+    >>> import numpy as np
+    >>> f = lambda x: x**8
+    >>> integrate.fixed_quad(f, 0.0, 1.0, n=4)
+    (0.1110884353741496, None)
+    >>> integrate.fixed_quad(f, 0.0, 1.0, n=5)
+    (0.11111111111111102, None)
+    >>> print(1/9.0)  # analytical result
+    0.1111111111111111
+
+    >>> integrate.fixed_quad(np.cos, 0.0, np.pi/2, n=4)
+    (0.9999999771971152, None)
+    >>> integrate.fixed_quad(np.cos, 0.0, np.pi/2, n=5)
+    (1.000000000039565, None)
+    >>> np.sin(np.pi/2)-np.sin(0)  # analytical result
+    1.0
+
+    """
+    # `args` not necessarily numeric arrays, so don't pass to array_namespace/xp_promote
+    xp = array_namespace(a, b)
+    a, b = xp_promote(a, b, force_floating=True, xp=xp)
+    x, w = _cached_roots_legendre(n)
+    x, w = xp.asarray(x, dtype=a.dtype), xp.asarray(w, dtype=a.dtype)
+    x = xp.real(x)
+    if not is_lazy_array(a) and (xp.isinf(a) or xp.isinf(b)):
+        raise ValueError("Gaussian quadrature is only available for "
+                         "finite limits.")
+    y = (b-a)*(x+1)/2.0 + a
+    return (b-a)/2.0 * xp.sum(w*func(y, *args), axis=-1), None
+
+
+def tupleset(t, i, value):
+    l = list(t)
+    l[i] = value
+    return tuple(l)
+
+
+@xp_capabilities()
+def cumulative_trapezoid(y, x=None, dx=1.0, axis=-1, initial=None):
+    """
+    Cumulatively integrate y(x) using the composite trapezoidal rule.
+
+    Parameters
+    ----------
+    y : array_like
+        Values to integrate.
+    x : array_like, optional
+        The coordinate to integrate along. If None (default), use spacing `dx`
+        between consecutive elements in `y`.
+    dx : float, optional
+        Spacing between elements of `y`. Only used if `x` is None.
+    axis : int, optional
+        Specifies the axis to cumulate. Default is -1 (last axis).
+    initial : scalar, optional
+        If given, insert this value at the beginning of the returned result.
+        0 or None are the only values accepted. Default is None, which means
+        `res` has one element less than `y` along the axis of integration.
+
+    Returns
+    -------
+    res : ndarray
+        The result of cumulative integration of `y` along `axis`.
+        If `initial` is None, the shape is such that the axis of integration
+        has one less value than `y`. If `initial` is given, the shape is equal
+        to that of `y`.
+
+    See Also
+    --------
+    numpy.cumsum, numpy.cumprod
+    cumulative_simpson : cumulative integration using Simpson's 1/3 rule
+    quad : adaptive quadrature using QUADPACK
+    fixed_quad : fixed-order Gaussian quadrature
+    dblquad : double integrals
+    tplquad : triple integrals
+    romb : integrators for sampled data
+
+    Examples
+    --------
+    >>> from scipy import integrate
+    >>> import numpy as np
+    >>> import matplotlib.pyplot as plt
+
+    >>> x = np.linspace(-2, 2, num=20)
+    >>> y = x
+    >>> y_int = integrate.cumulative_trapezoid(y, x, initial=0)
+    >>> plt.plot(x, y_int, 'ro', x, y[0] + 0.5 * x**2, 'b-')
+    >>> plt.show()
+
+    """
+    xp = array_namespace(y)
+    y = xp.asarray(y)
+
+    if y.shape[axis] == 0:
+        raise ValueError("At least one point is required along `axis`.")
+
+    if x is None:
+        d = dx
+    else:
+        x = xp.asarray(x)
+        if x.ndim == 1:
+            d = xp.diff(x)
+            # reshape to correct shape
+            shape = [1] * y.ndim
+            shape[axis] = -1
+            d = xp.reshape(d, tuple(shape))
+        elif len(x.shape) != len(y.shape):
+            raise ValueError("If given, shape of x must be 1-D or the "
+                             "same as y.")
+        else:
+            d = xp.diff(x, axis=axis)
+
+        if d.shape[axis] != y.shape[axis] - 1:
+            raise ValueError("If given, length of x along axis must be the "
+                             "same as y.")
+
+    nd = len(y.shape)
+    slice1 = tupleset((slice(None),)*nd, axis, slice(1, None))
+    slice2 = tupleset((slice(None),)*nd, axis, slice(None, -1))
+    res = xp.cumulative_sum(d * (y[slice1] + y[slice2]) / 2.0, axis=axis)
+
+    if initial is not None:
+        if initial != 0:
+            raise ValueError("`initial` must be `None` or `0`.")
+        if not np.isscalar(initial):
+            raise ValueError("`initial` parameter should be a scalar.")
+
+        shape = list(res.shape)
+        shape[axis] = 1
+        res = xp.concat((xp.full(tuple(shape), initial, dtype=res.dtype), res),
+                        axis=axis)
+
+    return res
+
+
+def _basic_simpson(y, start, stop, x, dx, axis, *, xp):
+    nd = y.ndim
+    if start is None:
+        start = 0
+    step = 2
+    slice_all = (slice(None),)*nd
+    slice0 = tupleset(slice_all, axis, slice(start, stop, step))
+    slice1 = tupleset(slice_all, axis, slice(start+1, stop+1, step))
+    slice2 = tupleset(slice_all, axis, slice(start+2, stop+2, step))
+
+    if x is None:  # Even-spaced Simpson's rule.
+        result = dx / 3.0 * xp.sum(y[slice0] + 4.0*y[slice1] + y[slice2], axis=axis)
+    else:
+        # Account for possibly different spacings.
+        #    Simpson's rule changes a bit.
+        h = xp.diff(x, axis=axis)
+        sl0 = tupleset(slice_all, axis, slice(start, stop, step))
+        sl1 = tupleset(slice_all, axis, slice(start+1, stop+1, step))
+        h0 = h[sl0] if xp_size(h) else h
+        h1 = h[sl1] if xp_size(h) else h
+        hsum = h0 + h1
+        hprod = h0 * h1
+        h0divh1 = xpx.apply_where(h1 != 0, (h0, h1), xp.divide, fill_value=0.)
+        tmp = hsum/6.0 * (y[slice0] *
+            (2.0 - xpx.apply_where(h0divh1 != 0, (xp.ones_like(h0divh1), h0divh1,),
+                                   xp.divide, fill_value=0.))
+            + y[slice1] * (hsum * xpx.apply_where(hprod != 0, (hsum, hprod,),
+                                                  xp.divide, fill_value=0.))
+            + (y[slice2] if xp_size(y) > 1 else y[0:0, ...]) * (2.0 - h0divh1))
+        result = xp.sum(tmp, axis=axis)
+    return result
+
+
+@xp_capabilities()
+def simpson(y, x=None, *, dx=1.0, axis=-1):
+    """
+    Integrate y(x) using samples along the given axis and the composite
+    Simpson's rule. If x is None, spacing of dx is assumed.
+
+    Parameters
+    ----------
+    y : array_like
+        Array to be integrated.
+    x : array_like, optional
+        If given, the points at which `y` is sampled.
+    dx : float, optional
+        Spacing of integration points along axis of `x`. Only used when
+        `x` is None. Default is 1.
+    axis : int, optional
+        Axis along which to integrate. Default is the last axis.
+
+    Returns
+    -------
+    float
+        The estimated integral computed with the composite Simpson's rule.
+
+    See Also
+    --------
+    quad : adaptive quadrature using QUADPACK
+    fixed_quad : fixed-order Gaussian quadrature
+    dblquad : double integrals
+    tplquad : triple integrals
+    romb : integrators for sampled data
+    cumulative_trapezoid : cumulative integration for sampled data
+    cumulative_simpson : cumulative integration using Simpson's 1/3 rule
+
+    Notes
+    -----
+    For an odd number of samples that are equally spaced the result is
+    exact if the function is a polynomial of order 3 or less. If
+    the samples are not equally spaced, then the result is exact only
+    if the function is a polynomial of order 2 or less.
+
+    References
+    ----------
+    .. [1] Cartwright, Kenneth V. Simpson's Rule Cumulative Integration with
+           MS Excel and Irregularly-spaced Data. Journal of Mathematical
+           Sciences and Mathematics Education. 12 (2): 1-9
+
+    Examples
+    --------
+    >>> from scipy import integrate
+    >>> import numpy as np
+    >>> x = np.arange(0, 10)
+    >>> y = np.arange(0, 10)
+
+    >>> integrate.simpson(y, x=x)
+    40.5
+
+    >>> y = np.power(x, 3)
+    >>> integrate.simpson(y, x=x)
+    1640.5
+    >>> integrate.quad(lambda x: x**3, 0, 9)[0]
+    1640.25
+
+    """
+    xp = array_namespace(y, x, dx)
+    y, x, dx = xp_promote(y, x, dx, xp=xp)
+    nd = y.ndim
+    N = y.shape[axis]
+    last_dx = dx
+    if x is not None:
+        if x.ndim == 1:
+            shapex = [1] * nd
+            shapex[axis] = x.shape[0]
+            x = xp.reshape(x, tuple(shapex))
+        elif x.ndim != y.ndim:
+            raise ValueError("If given, shape of x must be 1-D or the same as y.")
+        if x.shape[axis] != N:
+            raise ValueError("If given, length of x along axis must be the same as y.")
+
+    if N % 2 == 0:
+        val = 0.0
+        result = 0.0
+        slice_all = (slice(None),) * nd
+
+        if N == 2:
+            # need at least 3 points in integration axis to form parabolic
+            # segment. If there are two points then any of 'avg', 'first',
+            # 'last' should give the same result.
+            slice1 = tupleset(slice_all, axis, -1)
+            slice2 = tupleset(slice_all, axis, -2)
+            if x is not None:
+                last_dx = x[slice1] - x[slice2]
+            val = 0.5 * last_dx * (y[slice1] + y[slice2])
+        else:
+            # use Simpson's rule on first intervals
+            result = _basic_simpson(y, 0, N-3, x, dx, axis, xp=xp)
+
+            slice1 = tupleset(slice_all, axis, -1)
+            slice2 = tupleset(slice_all, axis, -2)
+            slice3 = tupleset(slice_all, axis, -3)
+
+            h = xp.stack([dx, dx])
+            if x is not None:
+                # grab the last two spacings from the appropriate axis
+                hm2 = tupleset(slice_all, axis, slice(-2, -1, 1))
+                hm1 = tupleset(slice_all, axis, slice(-1, None, 1))
+
+                diffs = xp.diff(x, axis=axis)
+                h = [xp.squeeze(diffs[hm2], axis=axis),
+                     xp.squeeze(diffs[hm1], axis=axis)]
+
+            # This is the correction for the last interval according to
+            # Cartwright.
+            # However, I used the equations given at
+            # https://en.wikipedia.org/wiki/Simpson%27s_rule#Composite_Simpson's_rule_for_irregularly_spaced_data
+            # A footnote on Wikipedia says:
+            # Cartwright 2017, Equation 8. The equation in Cartwright is
+            # calculating the first interval whereas the equations in the
+            # Wikipedia article are adjusting for the last integral. If the
+            # proper algebraic substitutions are made, the equation results in
+            # the values shown.
+            num = 2 * h[1] ** 2 + 3 * h[0] * h[1]
+            den = 6 * (h[1] + h[0])
+            alpha = xpx.apply_where(den != 0, (num, den), xp.divide, fill_value=0.)
+
+            num = h[1] ** 2 + 3.0 * h[0] * h[1]
+            den = 6 * h[0]
+            beta = xpx.apply_where(den != 0, (num, den), xp.divide, fill_value=0.)
+
+            num = 1 * h[1] ** 3
+            den = 6 * h[0] * (h[0] + h[1])
+            eta = xpx.apply_where(den != 0, (num, den), xp.divide, fill_value=0.)
+
+            result += alpha*y[slice1] + beta*y[slice2] - eta*y[slice3]
+
+        result += val
+    else:
+        result = _basic_simpson(y, 0, N-2, x, dx, axis, xp=xp)
+    return result
+
+
+def _cumulatively_sum_simpson_integrals(
+    y: np.ndarray,
+    dx: np.ndarray,
+    integration_func: Callable[[np.ndarray, np.ndarray], np.ndarray],
+    xp
+) -> np.ndarray:
+    """Calculate cumulative sum of Simpson integrals.
+    Takes as input the integration function to be used.
+    The integration_func is assumed to return the cumulative sum using
+    composite Simpson's rule. Assumes the axis of summation is -1.
+    """
+    sub_integrals_h1 = integration_func(y, dx)
+    sub_integrals_h2 = xp.flip(
+        integration_func(xp.flip(y, axis=-1), xp.flip(dx, axis=-1)),
+        axis=-1
+    )
+
+    shape = list(sub_integrals_h1.shape)
+    shape[-1] += 1
+    sub_integrals = xp.empty(shape, dtype=xp.result_type(y, dx))
+    sub_integrals[..., :-1:2] = sub_integrals_h1[..., ::2]
+    sub_integrals[..., 1::2] = sub_integrals_h2[..., ::2]
+    # Integral over last subinterval can only be calculated from
+    # formula for h2
+    sub_integrals[..., -1] = sub_integrals_h2[..., -1]
+    res = xp.cumulative_sum(sub_integrals, axis=-1)
+    return res
+
+
+def _cumulative_simpson_equal_intervals(y: np.ndarray, dx: np.ndarray) -> np.ndarray:
+    """Calculate the Simpson integrals for all h1 intervals assuming equal interval
+    widths. The function can also be used to calculate the integral for all
+    h2 intervals by reversing the inputs, `y` and `dx`.
+    """
+    d = dx[..., :-1]
+    f1 = y[..., :-2]
+    f2 = y[..., 1:-1]
+    f3 = y[..., 2:]
+
+    # Calculate integral over the subintervals (eqn (10) of Reference [2])
+    return d / 3 * (5 * f1 / 4 + 2 * f2 - f3 / 4)
+
+
+def _cumulative_simpson_unequal_intervals(y: np.ndarray, dx: np.ndarray) -> np.ndarray:
+    """Calculate the Simpson integrals for all h1 intervals assuming unequal interval
+    widths. The function can also be used to calculate the integral for all
+    h2 intervals by reversing the inputs, `y` and `dx`.
+    """
+    x21 = dx[..., :-1]
+    x32 = dx[..., 1:]
+    f1 = y[..., :-2]
+    f2 = y[..., 1:-1]
+    f3 = y[..., 2:]
+
+    x31 = x21 + x32
+    x21_x31 = x21/x31
+    x21_x32 = x21/x32
+    x21x21_x31x32 = x21_x31 * x21_x32
+
+    # Calculate integral over the subintervals (eqn (8) of Reference [2])
+    coeff1 = 3 - x21_x31
+    coeff2 = 3 + x21x21_x31x32 + x21_x31
+    coeff3 = -x21x21_x31x32
+
+    return x21/6 * (coeff1*f1 + coeff2*f2 + coeff3*f3)
+
+
+@xp_capabilities(allow_dask_compute=1,
+                 skip_backends=[("jax.numpy", "item assignment")])
+def cumulative_simpson(y, *, x=None, dx=1.0, axis=-1, initial=None):
+    r"""
+    Cumulatively integrate y(x) using the composite Simpson's 1/3 rule.
+    The integral of the samples at every point is calculated by assuming a
+    quadratic relationship between each point and the two adjacent points.
+
+    Parameters
+    ----------
+    y : array_like
+        Values to integrate. Requires at least one point along `axis`. If two or fewer
+        points are provided along `axis`, Simpson's integration is not possible and the
+        result is calculated with `cumulative_trapezoid`.
+    x : array_like, optional
+        The coordinate to integrate along. Must have the same shape as `y` or
+        must be 1D with the same length as `y` along `axis`. `x` must also be
+        strictly increasing along `axis`.
+        If `x` is None (default), integration is performed using spacing `dx`
+        between consecutive elements in `y`.
+    dx : scalar or array_like, optional
+        Spacing between elements of `y`. Only used if `x` is None. Can either
+        be a float, or an array with the same shape as `y`, but of length one along
+        `axis`. Default is 1.0.
+    axis : int, optional
+        Specifies the axis to integrate along. Default is -1 (last axis).
+    initial : scalar or array_like, optional
+        If given, insert this value at the beginning of the returned result,
+        and add it to the rest of the result. Default is None, which means no
+        value at ``x[0]`` is returned and `res` has one element less than `y`
+        along the axis of integration. Can either be a float, or an array with
+        the same shape as `y`, but of length one along `axis`.
+
+    Returns
+    -------
+    res : ndarray
+        The result of cumulative integration of `y` along `axis`.
+        If `initial` is None, the shape is such that the axis of integration
+        has one less value than `y`. If `initial` is given, the shape is equal
+        to that of `y`.
+
+    See Also
+    --------
+    numpy.cumsum
+    cumulative_trapezoid : cumulative integration using the composite
+        trapezoidal rule
+    simpson : integrator for sampled data using the Composite Simpson's Rule
+
+    Notes
+    -----
+
+    .. versionadded:: 1.12.0
+
+    The composite Simpson's 1/3 method can be used to approximate the definite
+    integral of a sampled input function :math:`y(x)` [1]_. The method assumes
+    a quadratic relationship over the interval containing any three consecutive
+    sampled points.
+
+    Consider three consecutive points:
+    :math:`(x_1, y_1), (x_2, y_2), (x_3, y_3)`.
+
+    Assuming a quadratic relationship over the three points, the integral over
+    the subinterval between :math:`x_1` and :math:`x_2` is given by formula
+    (8) of [2]_:
+
+    .. math::
+        \int_{x_1}^{x_2} y(x) dx\ &= \frac{x_2-x_1}{6}\left[\
+        \left\{3-\frac{x_2-x_1}{x_3-x_1}\right\} y_1 + \
+        \left\{3 + \frac{(x_2-x_1)^2}{(x_3-x_2)(x_3-x_1)} + \
+        \frac{x_2-x_1}{x_3-x_1}\right\} y_2\\
+        - \frac{(x_2-x_1)^2}{(x_3-x_2)(x_3-x_1)} y_3\right]
+
+    The integral between :math:`x_2` and :math:`x_3` is given by swapping
+    appearances of :math:`x_1` and :math:`x_3`. The integral is estimated
+    separately for each subinterval and then cumulatively summed to obtain
+    the final result.
+
+    For samples that are equally spaced, the result is exact if the function
+    is a polynomial of order three or less [1]_ and the number of subintervals
+    is even. Otherwise, the integral is exact for polynomials of order two or
+    less.
+
+    References
+    ----------
+    .. [1] Wikipedia page: https://en.wikipedia.org/wiki/Simpson's_rule
+    .. [2] Cartwright, Kenneth V. Simpson's Rule Cumulative Integration with
+            MS Excel and Irregularly-spaced Data. Journal of Mathematical
+            Sciences and Mathematics Education. 12 (2): 1-9
+
+    Examples
+    --------
+    >>> from scipy import integrate
+    >>> import numpy as np
+    >>> import matplotlib.pyplot as plt
+    >>> x = np.linspace(-2, 2, num=20)
+    >>> y = x**2
+    >>> y_int = integrate.cumulative_simpson(y, x=x, initial=0)
+    >>> fig, ax = plt.subplots()
+    >>> ax.plot(x, y_int, 'ro', x, x**3/3 - (x[0])**3/3, 'b-')
+    >>> ax.grid()
+    >>> plt.show()
+
+    The output of `cumulative_simpson` is similar to that of iteratively
+    calling `simpson` with successively higher upper limits of integration, but
+    not identical.
+
+    >>> def cumulative_simpson_reference(y, x):
+    ...     return np.asarray([integrate.simpson(y[:i], x=x[:i])
+    ...                        for i in range(2, len(y) + 1)])
+    >>>
+    >>> rng = np.random.default_rng(354673834679465)
+    >>> x, y = rng.random(size=(2, 10))
+    >>> x.sort()
+    >>>
+    >>> res = integrate.cumulative_simpson(y, x=x)
+    >>> ref = cumulative_simpson_reference(y, x)
+    >>> equal = np.abs(res - ref) < 1e-15
+    >>> equal  # not equal when `simpson` has even number of subintervals
+    array([False,  True, False,  True, False,  True, False,  True,  True])
+
+    This is expected: because `cumulative_simpson` has access to more
+    information than `simpson`, it can typically produce more accurate
+    estimates of the underlying integral over subintervals.
+
+    """
+    xp = array_namespace(y)
+    y = xp_promote(y, force_floating=True, xp=xp)
+
+    # validate `axis` and standardize to work along the last axis
+    original_y = y
+    original_shape = y.shape
+    try:
+        y = xp_swapaxes(y, axis, -1, xp)
+    except IndexError as e:
+        message = f"`axis={axis}` is not valid for `y` with `y.ndim={y.ndim}`."
+        raise ValueError(message) from e
+    if y.shape[-1] < 3:
+        res = cumulative_trapezoid(original_y, x, dx=dx, axis=axis, initial=None)
+        res = xp_swapaxes(res, axis, -1, xp)
+
+    elif x is not None:
+        x = xp_promote(x, force_floating=True, xp=xp)
+        message = ("If given, shape of `x` must be the same as `y` or 1-D with "
+                   "the same length as `y` along `axis`.")
+        if not (x.shape == original_shape
+                or (x.ndim == 1 and x.shape[0] == original_shape[axis])):
+            raise ValueError(message)
+
+        x = xp.broadcast_to(x, y.shape) if x.ndim == 1 else xp_swapaxes(x, axis, -1, xp)
+        dx = xp.diff(x, axis=-1)
+        if xp.any(dx <= 0):
+            raise ValueError("Input x must be strictly increasing.")
+        res = _cumulatively_sum_simpson_integrals(
+            y, dx, _cumulative_simpson_unequal_intervals, xp
+        )
+
+    else:
+        dx = xp_promote(xp.asarray(dx), force_floating=True, xp=xp)
+        final_dx_shape = tupleset(original_shape, axis, original_shape[axis] - 1)
+        alt_input_dx_shape = tupleset(original_shape, axis, 1)
+        message = ("If provided, `dx` must either be a scalar or have the same "
+                   "shape as `y` but with only 1 point along `axis`.")
+        if not (dx.ndim == 0 or dx.shape == alt_input_dx_shape):
+            raise ValueError(message)
+        dx = xp.broadcast_to(dx, final_dx_shape)
+        dx = xp_swapaxes(dx, axis, -1, xp)
+        res = _cumulatively_sum_simpson_integrals(
+            y, dx, _cumulative_simpson_equal_intervals, xp
+        )
+
+    if initial is not None:
+        initial = xp_promote(initial, force_floating=True, xp=xp)
+        alt_initial_input_shape = tupleset(original_shape, axis, 1)
+        message = ("If provided, `initial` must either be a scalar or have the "
+                   "same shape as `y` but with only 1 point along `axis`.")
+        if not (initial.ndim == 0 or initial.shape == alt_initial_input_shape):
+            raise ValueError(message)
+        initial = xp.broadcast_to(initial, alt_initial_input_shape)
+        initial = xp_swapaxes(initial, axis, -1, xp)
+
+        res += initial
+        res = xp.concat((initial, res), axis=-1)
+
+    res = xp_swapaxes(res, -1, axis, xp)
+    return res
+
+
+@xp_capabilities()
+def romb(y, dx=1.0, axis=-1, show=False):
+    """
+    Romberg integration using samples of a function.
+
+    Parameters
+    ----------
+    y : array_like
+        A vector of ``2**k + 1`` equally-spaced samples of a function.
+    dx : float, optional
+        The sample spacing. Default is 1.
+    axis : int, optional
+        The axis along which to integrate. Default is -1 (last axis).
+    show : bool, optional
+        When `y` is a single 1-D array, then if this argument is True
+        print the table showing Richardson extrapolation from the
+        samples. Default is False.
+
+    Returns
+    -------
+    romb : ndarray
+        The integrated result for `axis`.
+
+    See Also
+    --------
+    quad : adaptive quadrature using QUADPACK
+    fixed_quad : fixed-order Gaussian quadrature
+    dblquad : double integrals
+    tplquad : triple integrals
+    simpson : integrators for sampled data
+    cumulative_trapezoid : cumulative integration for sampled data
+
+    Examples
+    --------
+    >>> from scipy import integrate
+    >>> import numpy as np
+    >>> x = np.arange(10, 14.25, 0.25)
+    >>> y = np.arange(3, 12)
+
+    >>> integrate.romb(y)
+    56.0
+
+    >>> y = np.sin(np.power(x, 2.5))
+    >>> integrate.romb(y)
+    -0.742561336672229
+
+    >>> integrate.romb(y, show=True)
+    Richardson Extrapolation Table for Romberg Integration
+    ======================================================
+    -0.81576
+     4.63862  6.45674
+    -1.10581 -3.02062 -3.65245
+    -2.57379 -3.06311 -3.06595 -3.05664
+    -1.34093 -0.92997 -0.78776 -0.75160 -0.74256
+    ======================================================
+    -0.742561336672229  # may vary
+
+    >>> integrate.romb([[1, 2, 3], [4, 5, 6]], show=True)
+    *** Printing table only supported for integrals of a single data set.
+    array([ 4., 10.])
+    """
+    xp = array_namespace(y)
+    y = xp.asarray(y)
+    nd = len(y.shape)
+    Nsamps = y.shape[axis]
+    Ninterv = Nsamps-1
+    n = 1
+    k = 0
+    while n < Ninterv:
+        n <<= 1
+        k += 1
+    if n != Ninterv:
+        raise ValueError("Number of samples must be one plus a "
+                         "non-negative power of 2.")
+
+    R = {}
+    slice_all = (slice(None),) * nd
+    slice0 = tupleset(slice_all, axis, 0)
+    slicem1 = tupleset(slice_all, axis, -1)
+    h = Ninterv * xp.asarray(dx, dtype=xp.float64)
+    R[(0, 0)] = (y[slice0] + y[slicem1])/2.0*h
+    slice_R = slice_all
+    start = stop = step = Ninterv
+    for i in range(1, k+1):
+        start >>= 1
+        slice_R = tupleset(slice_R, axis, slice(start, stop, step))
+        step >>= 1
+        R[(i, 0)] = 0.5*(R[(i-1, 0)] + h*xp.sum(y[slice_R], axis=axis))
+        for j in range(1, i+1):
+            prev = R[(i, j-1)]
+            R[(i, j)] = prev + (prev-R[(i-1, j-1)]) / ((1 << (2*j))-1)
+        h /= 2.0
+
+    if show:
+        if not np.isscalar(R[(0, 0)]):
+            print("*** Printing table only supported for integrals" +
+                  " of a single data set.")
+        else:
+            try:
+                precis = show[0]
+            except (TypeError, IndexError):
+                precis = 5
+            try:
+                width = show[1]
+            except (TypeError, IndexError):
+                width = 8
+            formstr = f"%{width}.{precis}f"
+
+            title = "Richardson Extrapolation Table for Romberg Integration"
+            print(title, "=" * len(title), sep="\n", end="\n")
+            for i in range(k+1):
+                for j in range(i+1):
+                    print(formstr % R[(i, j)], end=" ")
+                print()
+            print("=" * len(title))
+
+    return R[(k, k)]
+
+
+# Coefficients for Newton-Cotes quadrature
+#
+# These are the points being used
+#  to construct the local interpolating polynomial
+#  a are the weights for Newton-Cotes integration
+#  B is the error coefficient.
+#  error in these coefficients grows as N gets larger.
+#  or as samples are closer and closer together
+
+# You can use maxima to find these rational coefficients
+#  for equally spaced data using the commands
+#  a(i,N) := (integrate(product(r-j,j,0,i-1) * product(r-j,j,i+1,N),r,0,N)
+#             / ((N-i)! * i!) * (-1)^(N-i));
+#  Be(N) := N^(N+2)/(N+2)! * (N/(N+3) - sum((i/N)^(N+2)*a(i,N),i,0,N));
+#  Bo(N) := N^(N+1)/(N+1)! * (N/(N+2) - sum((i/N)^(N+1)*a(i,N),i,0,N));
+#  B(N) := (if (mod(N,2)=0) then Be(N) else Bo(N));
+#
+# pre-computed for equally-spaced weights
+#
+# num_a, den_a, int_a, num_B, den_B = _builtincoeffs[N]
+#
+#  a = num_a*array(int_a)/den_a
+#  B = num_B*1.0 / den_B
+#
+#  integrate(f(x),x,x_0,x_N) = dx*sum(a*f(x_i)) + B*(dx)^(2k+3) f^(2k+2)(x*)
+#    where k = N // 2
+#
+_builtincoeffs = {
+    1: (1,2,[1,1],-1,12),
+    2: (1,3,[1,4,1],-1,90),
+    3: (3,8,[1,3,3,1],-3,80),
+    4: (2,45,[7,32,12,32,7],-8,945),
+    5: (5,288,[19,75,50,50,75,19],-275,12096),
+    6: (1,140,[41,216,27,272,27,216,41],-9,1400),
+    7: (7,17280,[751,3577,1323,2989,2989,1323,3577,751],-8183,518400),
+    8: (4,14175,[989,5888,-928,10496,-4540,10496,-928,5888,989],
+        -2368,467775),
+    9: (9,89600,[2857,15741,1080,19344,5778,5778,19344,1080,
+                 15741,2857], -4671, 394240),
+    10: (5,299376,[16067,106300,-48525,272400,-260550,427368,
+                   -260550,272400,-48525,106300,16067],
+         -673175, 163459296),
+    11: (11,87091200,[2171465,13486539,-3237113, 25226685,-9595542,
+                      15493566,15493566,-9595542,25226685,-3237113,
+                      13486539,2171465], -2224234463, 237758976000),
+    12: (1, 5255250, [1364651,9903168,-7587864,35725120,-51491295,
+                      87516288,-87797136,87516288,-51491295,35725120,
+                      -7587864,9903168,1364651], -3012, 875875),
+    13: (13, 402361344000,[8181904909, 56280729661, -31268252574,
+                           156074417954,-151659573325,206683437987,
+                           -43111992612,-43111992612,206683437987,
+                           -151659573325,156074417954,-31268252574,
+                           56280729661,8181904909], -2639651053,
+         344881152000),
+    14: (7, 2501928000, [90241897,710986864,-770720657,3501442784,
+                         -6625093363,12630121616,-16802270373,19534438464,
+                         -16802270373,12630121616,-6625093363,3501442784,
+                         -770720657,710986864,90241897], -3740727473,
+         1275983280000)
+    }
+
+
+@xp_capabilities(np_only=True)
+def newton_cotes(rn, equal=0):
+    r"""
+    Return weights and error coefficient for Newton-Cotes integration.
+
+    Suppose we have :math:`(N+1)` samples of :math:`f` at the positions
+    :math:`x_0, x_1, ..., x_N`. Then an :math:`N`-point Newton-Cotes formula
+    for the integral between :math:`x_0` and :math:`x_N` is:
+
+    :math:`\int_{x_0}^{x_N} f(x)dx = \Delta x \sum_{i=0}^{N} a_i f(x_i)
+    + B_N (\Delta x)^{N+2} f^{N+1} (\xi)`
+
+    where :math:`\xi \in [x_0,x_N]`
+    and :math:`\Delta x = \frac{x_N-x_0}{N}` is the average samples spacing.
+
+    If the samples are equally-spaced and N is even, then the error
+    term is :math:`B_N (\Delta x)^{N+3} f^{N+2}(\xi)`.
+
+    Parameters
+    ----------
+    rn : int
+        The integer order for equally-spaced data or the relative positions of
+        the samples with the first sample at 0 and the last at N, where N+1 is
+        the length of `rn`. N is the order of the Newton-Cotes integration.
+    equal : int, optional
+        Set to 1 to enforce equally spaced data.
+
+    Returns
+    -------
+    an : ndarray
+        1-D array of weights to apply to the function at the provided sample
+        positions.
+    B : float
+        Error coefficient.
+
+    Notes
+    -----
+    Normally, the Newton-Cotes rules are used on smaller integration
+    regions and a composite rule is used to return the total integral.
+
+    Examples
+    --------
+    Compute the integral of sin(x) in [0, :math:`\pi`]:
+
+    >>> from scipy.integrate import newton_cotes
+    >>> import numpy as np
+    >>> def f(x):
+    ...     return np.sin(x)
+    >>> a = 0
+    >>> b = np.pi
+    >>> exact = 2
+    >>> for N in [2, 4, 6, 8, 10]:
+    ...     x = np.linspace(a, b, N + 1)
+    ...     an, B = newton_cotes(N, 1)
+    ...     dx = (b - a) / N
+    ...     quad = dx * np.sum(an * f(x))
+    ...     error = abs(quad - exact)
+    ...     print('{:2d}  {:10.9f}  {:.5e}'.format(N, quad, error))
+    ...
+     2   2.094395102   9.43951e-02
+     4   1.998570732   1.42927e-03
+     6   2.000017814   1.78136e-05
+     8   1.999999835   1.64725e-07
+    10   2.000000001   1.14677e-09
+
+    """
+    try:
+        N = len(rn)-1
+        if equal:
+            rn = np.arange(N+1)
+        elif np.all(np.diff(rn) == 1):
+            equal = 1
+    except Exception:
+        N = rn
+        rn = np.arange(N+1)
+        equal = 1
+
+    if equal and N in _builtincoeffs:
+        na, da, vi, nb, db = _builtincoeffs[N]
+        an = na * np.array(vi, dtype=float) / da
+        return an, float(nb)/db
+
+    if (rn[0] != 0) or (rn[-1] != N):
+        raise ValueError("The sample positions must start at 0"
+                         " and end at N")
+    yi = rn / float(N)
+    ti = 2 * yi - 1
+    nvec = np.arange(N+1)
+    C = ti ** nvec[:, np.newaxis]
+    Cinv = np.linalg.inv(C)
+    # improve precision of result
+    for i in range(2):
+        Cinv = 2*Cinv - Cinv.dot(C).dot(Cinv)
+    vec = 2.0 / (nvec[::2]+1)
+    ai = Cinv[:, ::2].dot(vec) * (N / 2.)
+
+    if (N % 2 == 0) and equal:
+        BN = N/(N+3.)
+        power = N+2
+    else:
+        BN = N/(N+2.)
+        power = N+1
+
+    BN = BN - np.dot(yi**power, ai)
+    p1 = power+1
+    fac = power*math.log(N) - gammaln(p1)
+    fac = math.exp(fac)
+    return ai, BN*fac
+
+
+def _qmc_quad_iv(func, a, b, n_points, n_estimates, qrng, log, xp):
+    # lazy import to avoid issues with partially-initialized submodule
+    if not hasattr(qmc_quad, 'qmc'):
+        from scipy import stats
+        qmc_quad.stats = stats
+    else:
+        stats = qmc_quad.stats
+
+    if not callable(func):
+        message = "`func` must be callable."
+        raise TypeError(message)
+
+    # a, b will be modified, so copy. Oh well if it's copied twice.
+    a, b = xp_promote(a, b, broadcast=True, force_floating=True, xp=xp)
+    a = xpx.atleast_nd(a, ndim=1, xp=xp)
+    b = xpx.atleast_nd(b, ndim=1, xp=xp)
+    a, b = xp.broadcast_arrays(a, b)
+    a, b = xp_copy(a), xp_copy(b)
+    dim = a.shape[0]
+
+    try:
+        func((a + b) / 2)
+    except Exception as e:
+        message = ("`func` must evaluate the integrand at points within "
+                   "the integration range; e.g. `func( (a + b) / 2)` "
+                   "must return the integrand at the centroid of the "
+                   "integration volume.")
+        raise ValueError(message) from e
+
+    try:
+        func(xp.stack([a, b]).T)
+        vfunc = func
+    except Exception as e:
+        if not is_numpy(xp):
+            message = ("Exception encountered when attempting vectorized call to "
+                       f"`func`: {e}. When using array library {xp}, `func` must "
+                       "accept two-dimensional array `x` with shape `(a.shape[0], "
+                       "n_points)` and return an array of the integrand value at "
+                       "each of the `n_points`.")
+            raise ValueError(message)
+
+        message = ("Exception encountered when attempting vectorized call to "
+                   f"`func`: {e}. For better performance, `func` should "
+                   "accept two-dimensional array `x` with shape `(len(a), "
+                   "n_points)` and return an array of the integrand value at "
+                   "each of the `n_points`.")
+        warnings.warn(message, stacklevel=3)
+
+        def vfunc(x):
+            return np.apply_along_axis(func, axis=-1, arr=x)
+
+    n_points_int = int(n_points)
+    if n_points != n_points_int:
+        message = "`n_points` must be an integer."
+        raise TypeError(message)
+
+    n_estimates_int = int(n_estimates)
+    if n_estimates != n_estimates_int:
+        message = "`n_estimates` must be an integer."
+        raise TypeError(message)
+
+    if qrng is None:
+        qrng = stats.qmc.Halton(dim)
+    elif not isinstance(qrng, stats.qmc.QMCEngine):
+        message = "`qrng` must be an instance of scipy.stats.qmc.QMCEngine."
+        raise TypeError(message)
+
+    if qrng.d != a.shape[0]:
+        message = ("`qrng` must be initialized with dimensionality equal to "
+                   "the number of variables in `a`, i.e., "
+                   "`qrng.random().shape[-1]` must equal `a.shape[0]`.")
+        raise ValueError(message)
+
+    rng_seed = getattr(qrng, 'rng_seed', None)
+    rng = stats._qmc.check_random_state(rng_seed)
+
+    if log not in {True, False}:
+        message = "`log` must be boolean (`True` or `False`)."
+        raise TypeError(message)
+
+    return (vfunc, a, b, n_points_int, n_estimates_int, qrng, rng, log, stats)
+
+
+QMCQuadResult = namedtuple('QMCQuadResult', ['integral', 'standard_error'])
+
+
+@xp_capabilities(skip_backends=[("dask.array",
+                                 "Dask arrays are confused about their shape")],
+                 jax_jit=False)
+def qmc_quad(func, a, b, *, n_estimates=8, n_points=1024, qrng=None,
+             log=False):
+    """
+    Compute an integral in N-dimensions using Quasi-Monte Carlo quadrature.
+
+    Parameters
+    ----------
+    func : callable
+        The integrand. Must accept a single argument ``x``, an array which
+        specifies the point(s) at which to evaluate the scalar-valued
+        integrand, and return the value(s) of the integrand.
+        For efficiency, the function should be vectorized to accept an array of
+        shape ``(d, n_points)``, where ``d`` is the number of variables (i.e.
+        the dimensionality of the function domain) and `n_points` is the number
+        of quadrature points, and return an array of shape ``(n_points,)``,
+        the integrand at each quadrature point.
+    a, b : scalar or 1-d array-like
+        One-dimensional arrays specifying the lower and upper integration
+        limits, respectively, of each of the ``d`` variables.
+    n_estimates, n_points : int, optional
+        `n_estimates` (default: 8) statistically independent QMC samples, each
+        of `n_points` (default: 1024) points, will be generated by `qrng`.
+        The total number of points at which the integrand `func` will be
+        evaluated is ``n_points * n_estimates``. See Notes for details.
+    qrng : `~scipy.stats.qmc.QMCEngine`, optional
+        An instance of the QMCEngine from which to sample QMC points.
+        The QMCEngine must be initialized to a number of dimensions ``d``
+        corresponding with the number of variables ``x1, ..., xd`` passed to
+        `func`.
+        The provided QMCEngine is used to produce the first integral estimate.
+        If `n_estimates` is greater than one, additional QMCEngines are
+        spawned from the first (with scrambling enabled, if it is an option.)
+        If a QMCEngine is not provided, the default `scipy.stats.qmc.Halton`
+        will be initialized with the number of dimensions determine from
+        the length of `a`.
+    log : bool, default: False
+        When set to True, `func` returns the log of the integrand, and
+        the result object contains the log of the integral.
+
+    Returns
+    -------
+    result : object
+        A result object with attributes:
+
+        integral : float
+            The estimate of the integral.
+        standard_error :
+            The error estimate. See Notes for interpretation.
+
+    Notes
+    -----
+    Values of the integrand at each of the `n_points` points of a QMC sample
+    are used to produce an estimate of the integral. This estimate is drawn
+    from a population of possible estimates of the integral, the value of
+    which we obtain depends on the particular points at which the integral
+    was evaluated. We perform this process `n_estimates` times, each time
+    evaluating the integrand at different scrambled QMC points, effectively
+    drawing i.i.d. random samples from the population of integral estimates.
+    The sample mean :math:`m` of these integral estimates is an
+    unbiased estimator of the true value of the integral, and the standard
+    error of the mean :math:`s` of these estimates may be used to generate
+    confidence intervals using the t distribution with ``n_estimates - 1``
+    degrees of freedom. Perhaps counter-intuitively, increasing `n_points`
+    while keeping the total number of function evaluation points
+    ``n_points * n_estimates`` fixed tends to reduce the actual error, whereas
+    increasing `n_estimates` tends to decrease the error estimate.
+
+    Examples
+    --------
+    QMC quadrature is particularly useful for computing integrals in higher
+    dimensions. An example integrand is the probability density function
+    of a multivariate normal distribution.
+
+    >>> import numpy as np
+    >>> from scipy import stats
+    >>> dim = 8
+    >>> mean = np.zeros(dim)
+    >>> cov = np.eye(dim)
+    >>> def func(x):
+    ...     # `multivariate_normal` expects the _last_ axis to correspond with
+    ...     # the dimensionality of the space, so `x` must be transposed
+    ...     return stats.multivariate_normal.pdf(x.T, mean, cov)
+
+    To compute the integral over the unit hypercube:
+
+    >>> from scipy.integrate import qmc_quad
+    >>> a = np.zeros(dim)
+    >>> b = np.ones(dim)
+    >>> rng = np.random.default_rng()
+    >>> qrng = stats.qmc.Halton(d=dim, seed=rng)
+    >>> n_estimates = 8
+    >>> res = qmc_quad(func, a, b, n_estimates=n_estimates, qrng=qrng)
+    >>> res.integral, res.standard_error
+    (0.00018429555666024108, 1.0389431116001344e-07)
+
+    A two-sided, 99% confidence interval for the integral may be estimated
+    as:
+
+    >>> t = stats.t(df=n_estimates-1, loc=res.integral,
+    ...             scale=res.standard_error)
+    >>> t.interval(0.99)
+    (0.0001839319802536469, 0.00018465913306683527)
+
+    Indeed, the value reported by `scipy.stats.multivariate_normal` is
+    within this range.
+
+    >>> stats.multivariate_normal.cdf(b, mean, cov, lower_limit=a)
+    0.00018430867675187443
+
+    """
+    xp = array_namespace(a, b)
+    args = _qmc_quad_iv(func, a, b, n_points, n_estimates, qrng, log, xp)
+    func, a, b, n_points, n_estimates, qrng, rng, log, stats = args
+
+    def sum_product(integrands, dA, log=False):
+        if log:
+            return logsumexp(integrands) + math.log(dA)
+        else:
+            return xp.sum(integrands * dA)
+
+    def mean(estimates, log=False):
+        if log:
+            return logsumexp(estimates) - math.log(n_estimates)
+        else:
+            return xp.mean(estimates)
+
+    def std(estimates, m=None, ddof=0, log=False):
+        m = m or mean(estimates, log)
+        if log:
+            estimates, m = xp.broadcast_arrays(estimates, m)
+            temp = xp.stack((estimates, m + xp.pi * 1j))
+            diff = logsumexp(temp, axis=0)
+            return xp.real(0.5 * (logsumexp(2 * diff)
+                                  - math.log(n_estimates - ddof)))
+        else:
+            return xp.std(estimates, correction=ddof)
+
+    def sem(estimates, m=None, s=None, log=False):
+        m = m or mean(estimates, log)
+        s = s or std(estimates, m, ddof=1, log=log)
+        if log:
+            return s - 0.5*math.log(n_estimates)
+        else:
+            return s / math.sqrt(n_estimates)
+
+    # The sign of the integral depends on the order of the limits. Fix this by
+    # ensuring that lower bounds are indeed lower and setting sign of resulting
+    # integral manually
+    if xp.any(a == b):
+        message = ("A lower limit was equal to an upper limit, so the value "
+                   "of the integral is zero by definition.")
+        warnings.warn(message, stacklevel=2)
+        zero = xp.asarray(-xp.inf if log else 0, dtype=a.dtype)
+        return QMCQuadResult(zero, xp.asarray(0., dtype=a.dtype))
+
+    i_swap = b < a
+    sign = (-1)**(xp.count_nonzero(i_swap, axis=-1))  # odd # of swaps -> negative
+    sign = xp.astype(sign, a.dtype)
+    # a[i_swap], b[i_swap] = b[i_swap], a[i_swap]
+    a_iswap = a[i_swap]
+    b_iswap = b[i_swap]
+    a = xpx.at(a)[i_swap].set(b_iswap)
+    b = xpx.at(b)[i_swap].set(a_iswap)
+
+    A = xp.prod(b - a)
+    dA = A / n_points
+
+    estimates = xp.zeros(n_estimates, dtype=a.dtype)
+    rngs = _rng_spawn(qrng.rng, n_estimates)
+    for i in range(n_estimates):
+        # Generate integral estimate
+        sample = xp.asarray(qrng.random(n_points), dtype=a.dtype)
+        # The rationale for transposing is that this allows users to easily
+        # unpack `x` into separate variables, if desired. This is consistent
+        # with the `xx` array passed into the `scipy.integrate.nquad` `func`.
+        x = (sample * (b - a) + a).T  # (n_dim, n_points)
+        integrands = func(x)
+        estimates = xpx.at(estimates)[i].set(sum_product(integrands, dA, log))
+
+        # Get a new, independently-scrambled QRNG for next time
+        qrng = type(qrng)(seed=rngs[i], **qrng._init_quad)
+
+    integral = mean(estimates, log)
+    standard_error = sem(estimates, m=integral, log=log)
+    integral = integral + xp.pi*1j if (log and sign < 0) else integral*sign
+    return QMCQuadResult(integral, standard_error)
diff --git a/.venv/lib/python3.12/site-packages/scipy/integrate/_rules/__init__.py b/.venv/lib/python3.12/site-packages/scipy/integrate/_rules/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..4c91aa324478d49a8723f05618801f9b256d07af
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/integrate/_rules/__init__.py
@@ -0,0 +1,12 @@
+"""Numerical cubature algorithms"""
+
+from ._base import (
+    Rule, FixedRule,
+    NestedFixedRule,
+    ProductNestedFixed,
+)
+from ._genz_malik import GenzMalikCubature
+from ._gauss_kronrod import GaussKronrodQuadrature
+from ._gauss_legendre import GaussLegendreQuadrature
+
+__all__ = [s for s in dir() if not s.startswith('_')]
diff --git a/.venv/lib/python3.12/site-packages/scipy/integrate/_rules/_base.py b/.venv/lib/python3.12/site-packages/scipy/integrate/_rules/_base.py
new file mode 100644
index 0000000000000000000000000000000000000000..724c07c58080fb31efa4ed926b12f3496b54836b
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/integrate/_rules/_base.py
@@ -0,0 +1,518 @@
+from scipy._lib._array_api import array_namespace, xp_size
+
+from functools import cached_property
+
+
+class Rule:
+    """
+    Base class for numerical integration algorithms (cubatures).
+
+    Finds an estimate for the integral of ``f`` over the region described by two arrays
+    ``a`` and ``b`` via `estimate`, and find an estimate for the error of this
+    approximation via `estimate_error`.
+
+    If a subclass does not implement its own `estimate_error`, then it will use a
+    default error estimate based on the difference between the estimate over the whole
+    region and the sum of estimates over that region divided into ``2^ndim`` subregions.
+
+    See Also
+    --------
+    FixedRule
+
+    Examples
+    --------
+    In the following, a custom rule is created which uses 3D Genz-Malik cubature for
+    the estimate of the integral, and the difference between this estimate and a less
+    accurate estimate using 5-node Gauss-Legendre quadrature as an estimate for the
+    error.
+
+    >>> import numpy as np
+    >>> from scipy.integrate import cubature
+    >>> from scipy.integrate._rules import (
+    ...     Rule, ProductNestedFixed, GenzMalikCubature, GaussLegendreQuadrature
+    ... )
+    >>> def f(x, r, alphas):
+    ...     # f(x) = cos(2*pi*r + alpha @ x)
+    ...     # Need to allow r and alphas to be arbitrary shape
+    ...     npoints, ndim = x.shape[0], x.shape[-1]
+    ...     alphas_reshaped = alphas[np.newaxis, :]
+    ...     x_reshaped = x.reshape(npoints, *([1]*(len(alphas.shape) - 1)), ndim)
+    ...     return np.cos(2*np.pi*r + np.sum(alphas_reshaped * x_reshaped, axis=-1))
+    >>> genz = GenzMalikCubature(ndim=3)
+    >>> gauss = GaussKronrodQuadrature(npoints=21)
+    >>> # Gauss-Kronrod is 1D, so we find the 3D product rule:
+    >>> gauss_3d = ProductNestedFixed([gauss, gauss, gauss])
+    >>> class CustomRule(Rule):
+    ...     def estimate(self, f, a, b, args=()):
+    ...         return genz.estimate(f, a, b, args)
+    ...     def estimate_error(self, f, a, b, args=()):
+    ...         return np.abs(
+    ...             genz.estimate(f, a, b, args)
+    ...             - gauss_3d.estimate(f, a, b, args)
+    ...         )
+    >>> rng = np.random.default_rng()
+    >>> res = cubature(
+    ...     f=f,
+    ...     a=np.array([0, 0, 0]),
+    ...     b=np.array([1, 1, 1]),
+    ...     rule=CustomRule(),
+    ...     args=(rng.random((2,)), rng.random((3, 2, 3)))
+    ... )
+    >>> res.estimate
+     array([[-0.95179502,  0.12444608],
+            [-0.96247411,  0.60866385],
+            [-0.97360014,  0.25515587]])
+    """
+
+    def estimate(self, f, a, b, args=()):
+        r"""
+        Calculate estimate of integral of `f` in rectangular region described by
+        corners `a` and ``b``.
+
+        Parameters
+        ----------
+        f : callable
+            Function to integrate. `f` must have the signature::
+                f(x : ndarray, \*args) -> ndarray
+
+            `f` should accept arrays ``x`` of shape::
+                (npoints, ndim)
+
+            and output arrays of shape::
+                (npoints, output_dim_1, ..., output_dim_n)
+
+            In this case, `estimate` will return arrays of shape::
+                (output_dim_1, ..., output_dim_n)
+        a, b : ndarray
+            Lower and upper limits of integration as rank-1 arrays specifying the left
+            and right endpoints of the intervals being integrated over. Infinite limits
+            are currently not supported.
+        args : tuple, optional
+            Additional positional args passed to ``f``, if any.
+
+        Returns
+        -------
+        est : ndarray
+            Result of estimation. If `f` returns arrays of shape ``(npoints,
+            output_dim_1, ..., output_dim_n)``, then `est` will be of shape
+            ``(output_dim_1, ..., output_dim_n)``.
+        """
+        raise NotImplementedError
+
+    def estimate_error(self, f, a, b, args=()):
+        r"""
+        Estimate the error of the approximation for the integral of `f` in rectangular
+        region described by corners `a` and `b`.
+
+        If a subclass does not override this method, then a default error estimator is
+        used. This estimates the error as ``|est - refined_est|`` where ``est`` is
+        ``estimate(f, a, b)`` and ``refined_est`` is the sum of
+        ``estimate(f, a_k, b_k)`` where ``a_k, b_k`` are the coordinates of each
+        subregion of the region described by ``a`` and ``b``. In the 1D case, this
+        is equivalent to comparing the integral over an entire interval ``[a, b]`` to
+        the sum of the integrals over the left and right subintervals, ``[a, (a+b)/2]``
+        and ``[(a+b)/2, b]``.
+
+        Parameters
+        ----------
+        f : callable
+            Function to estimate error for. `f` must have the signature::
+                f(x : ndarray, \*args) -> ndarray
+
+            `f` should accept arrays `x` of shape::
+                (npoints, ndim)
+
+            and output arrays of shape::
+                (npoints, output_dim_1, ..., output_dim_n)
+
+            In this case, `estimate` will return arrays of shape::
+                (output_dim_1, ..., output_dim_n)
+        a, b : ndarray
+            Lower and upper limits of integration as rank-1 arrays specifying the left
+            and right endpoints of the intervals being integrated over. Infinite limits
+            are currently not supported.
+        args : tuple, optional
+            Additional positional args passed to `f`, if any.
+
+        Returns
+        -------
+        err_est : ndarray
+            Result of error estimation. If `f` returns arrays of shape
+            ``(npoints, output_dim_1, ..., output_dim_n)``, then `est` will be
+            of shape ``(output_dim_1, ..., output_dim_n)``.
+        """
+
+        est = self.estimate(f, a, b, args)
+        refined_est = 0
+
+        for a_k, b_k in _split_subregion(a, b):
+            refined_est += self.estimate(f, a_k, b_k, args)
+
+        return self.xp.abs(est - refined_est)
+
+
+class FixedRule(Rule):
+    """
+    A rule implemented as the weighted sum of function evaluations at fixed nodes.
+
+    Attributes
+    ----------
+    nodes_and_weights : (ndarray, ndarray)
+        A tuple ``(nodes, weights)`` of nodes at which to evaluate ``f`` and the
+        corresponding weights. ``nodes`` should be of shape ``(num_nodes,)`` for 1D
+        cubature rules (quadratures) and more generally for N-D cubature rules, it
+        should be of shape ``(num_nodes, ndim)``. ``weights`` should be of shape
+        ``(num_nodes,)``. The nodes and weights should be for integrals over
+        :math:`[-1, 1]^n`.
+
+    See Also
+    --------
+    GaussLegendreQuadrature, GaussKronrodQuadrature, GenzMalikCubature
+
+    Examples
+    --------
+
+    Implementing Simpson's 1/3 rule:
+
+    >>> import numpy as np
+    >>> from scipy.integrate._rules import FixedRule
+    >>> class SimpsonsQuad(FixedRule):
+    ...     @property
+    ...     def nodes_and_weights(self):
+    ...         nodes = np.array([-1, 0, 1])
+    ...         weights = np.array([1/3, 4/3, 1/3])
+    ...         return (nodes, weights)
+    >>> rule = SimpsonsQuad()
+    >>> rule.estimate(
+    ...     f=lambda x: x**2,
+    ...     a=np.array([0]),
+    ...     b=np.array([1]),
+    ... )
+     [0.3333333]
+    """
+
+    def __init__(self):
+        self.xp = None
+
+    @property
+    def nodes_and_weights(self):
+        raise NotImplementedError
+
+    def estimate(self, f, a, b, args=()):
+        r"""
+        Calculate estimate of integral of `f` in rectangular region described by
+        corners `a` and `b` as ``sum(weights * f(nodes))``.
+
+        Nodes and weights will automatically be adjusted from calculating integrals over
+        :math:`[-1, 1]^n` to :math:`[a, b]^n`.
+
+        Parameters
+        ----------
+        f : callable
+            Function to integrate. `f` must have the signature::
+                f(x : ndarray, \*args) -> ndarray
+
+            `f` should accept arrays `x` of shape::
+                (npoints, ndim)
+
+            and output arrays of shape::
+                (npoints, output_dim_1, ..., output_dim_n)
+
+            In this case, `estimate` will return arrays of shape::
+                (output_dim_1, ..., output_dim_n)
+        a, b : ndarray
+            Lower and upper limits of integration as rank-1 arrays specifying the left
+            and right endpoints of the intervals being integrated over. Infinite limits
+            are currently not supported.
+        args : tuple, optional
+            Additional positional args passed to `f`, if any.
+
+        Returns
+        -------
+        est : ndarray
+            Result of estimation. If `f` returns arrays of shape ``(npoints,
+            output_dim_1, ..., output_dim_n)``, then `est` will be of shape
+            ``(output_dim_1, ..., output_dim_n)``.
+        """
+        nodes, weights = self.nodes_and_weights
+
+        if self.xp is None:
+            self.xp = array_namespace(nodes)
+
+        return _apply_fixed_rule(f, a, b, nodes, weights, args, self.xp)
+
+
+class NestedFixedRule(FixedRule):
+    r"""
+    A cubature rule with error estimate given by the difference between two underlying
+    fixed rules.
+
+    If constructed as ``NestedFixedRule(higher, lower)``, this will use::
+
+        estimate(f, a, b) := higher.estimate(f, a, b)
+        estimate_error(f, a, b) := \|higher.estimate(f, a, b) - lower.estimate(f, a, b)|
+
+    (where the absolute value is taken elementwise).
+
+    Attributes
+    ----------
+    higher : Rule
+        Higher accuracy rule.
+
+    lower : Rule
+        Lower accuracy rule.
+
+    See Also
+    --------
+    GaussKronrodQuadrature
+
+    Examples
+    --------
+
+    >>> from scipy.integrate import cubature
+    >>> from scipy.integrate._rules import (
+    ...     GaussLegendreQuadrature, NestedFixedRule, ProductNestedFixed
+    ... )
+    >>> higher = GaussLegendreQuadrature(10)
+    >>> lower = GaussLegendreQuadrature(5)
+    >>> rule = NestedFixedRule(
+    ...     higher,
+    ...     lower
+    ... )
+    >>> rule_2d = ProductNestedFixed([rule, rule])
+    """
+
+    def __init__(self, higher, lower):
+        self.higher = higher
+        self.lower = lower
+        self.xp = None
+
+    @property
+    def nodes_and_weights(self):
+        if self.higher is not None:
+            return self.higher.nodes_and_weights
+        else:
+            raise NotImplementedError
+
+    @property
+    def lower_nodes_and_weights(self):
+        if self.lower is not None:
+            return self.lower.nodes_and_weights
+        else:
+            raise NotImplementedError
+
+    def estimate_error(self, f, a, b, args=()):
+        r"""
+        Estimate the error of the approximation for the integral of `f` in rectangular
+        region described by corners `a` and `b`.
+
+        Parameters
+        ----------
+        f : callable
+            Function to estimate error for. `f` must have the signature::
+                f(x : ndarray, \*args) -> ndarray
+
+            `f` should accept arrays `x` of shape::
+                (npoints, ndim)
+
+            and output arrays of shape::
+                (npoints, output_dim_1, ..., output_dim_n)
+
+            In this case, `estimate` will return arrays of shape::
+                (output_dim_1, ..., output_dim_n)
+        a, b : ndarray
+            Lower and upper limits of integration as rank-1 arrays specifying the left
+            and right endpoints of the intervals being integrated over. Infinite limits
+            are currently not supported.
+        args : tuple, optional
+            Additional positional args passed to `f`, if any.
+
+        Returns
+        -------
+        err_est : ndarray
+            Result of error estimation. If `f` returns arrays of shape
+            ``(npoints, output_dim_1, ..., output_dim_n)``, then `est` will be
+            of shape ``(output_dim_1, ..., output_dim_n)``.
+        """
+
+        nodes, weights = self.nodes_and_weights
+        lower_nodes, lower_weights = self.lower_nodes_and_weights
+
+        if self.xp is None:
+            self.xp = array_namespace(nodes)
+
+        error_nodes = self.xp.concat([nodes, lower_nodes], axis=0)
+        error_weights = self.xp.concat([weights, -lower_weights], axis=0)
+
+        return self.xp.abs(
+            _apply_fixed_rule(f, a, b, error_nodes, error_weights, args, self.xp)
+        )
+
+
+class ProductNestedFixed(NestedFixedRule):
+    """
+    Find the n-dimensional cubature rule constructed from the Cartesian product of 1-D
+    `NestedFixedRule` quadrature rules.
+
+    Given a list of N 1-dimensional quadrature rules which support error estimation
+    using NestedFixedRule, this will find the N-dimensional cubature rule obtained by
+    taking the Cartesian product of their nodes, and estimating the error by taking the
+    difference with a lower-accuracy N-dimensional cubature rule obtained using the
+    ``.lower_nodes_and_weights`` rule in each of the base 1-dimensional rules.
+
+    Parameters
+    ----------
+    base_rules : list of NestedFixedRule
+        List of base 1-dimensional `NestedFixedRule` quadrature rules.
+
+    Attributes
+    ----------
+    base_rules : list of NestedFixedRule
+        List of base 1-dimensional `NestedFixedRule` qudarature rules.
+
+    Examples
+    --------
+
+    Evaluate a 2D integral by taking the product of two 1D rules:
+
+    >>> import numpy as np
+    >>> from scipy.integrate import cubature
+    >>> from scipy.integrate._rules import (
+    ...  ProductNestedFixed, GaussKronrodQuadrature
+    ... )
+    >>> def f(x):
+    ...     # f(x) = cos(x_1) + cos(x_2)
+    ...     return np.sum(np.cos(x), axis=-1)
+    >>> rule = ProductNestedFixed(
+    ...     [GaussKronrodQuadrature(15), GaussKronrodQuadrature(15)]
+    ... ) # Use 15-point Gauss-Kronrod, which implements NestedFixedRule
+    >>> a, b = np.array([0, 0]), np.array([1, 1])
+    >>> rule.estimate(f, a, b) # True value 2*sin(1), approximately 1.6829
+     np.float64(1.682941969615793)
+    >>> rule.estimate_error(f, a, b)
+     np.float64(2.220446049250313e-16)
+    """
+
+    def __init__(self, base_rules):
+        for rule in base_rules:
+            if not isinstance(rule, NestedFixedRule):
+                raise ValueError("base rules for product need to be instance of"
+                                 "NestedFixedRule")
+
+        self.base_rules = base_rules
+        self.xp = None
+
+    @cached_property
+    def nodes_and_weights(self):
+        nodes = _cartesian_product(
+            [rule.nodes_and_weights[0] for rule in self.base_rules]
+        )
+
+        if self.xp is None:
+            self.xp = array_namespace(nodes)
+
+        weights = self.xp.prod(
+            _cartesian_product(
+                [rule.nodes_and_weights[1] for rule in self.base_rules]
+            ),
+            axis=-1,
+        )
+
+        return nodes, weights
+
+    @cached_property
+    def lower_nodes_and_weights(self):
+        nodes = _cartesian_product(
+            [cubature.lower_nodes_and_weights[0] for cubature in self.base_rules]
+        )
+
+        if self.xp is None:
+            self.xp = array_namespace(nodes)
+
+        weights = self.xp.prod(
+            _cartesian_product(
+                [cubature.lower_nodes_and_weights[1] for cubature in self.base_rules]
+            ),
+            axis=-1,
+        )
+
+        return nodes, weights
+
+
+def _cartesian_product(arrays):
+    xp = array_namespace(*arrays)
+
+    arrays_ix = xp.meshgrid(*arrays, indexing='ij')
+    result = xp.reshape(xp.stack(arrays_ix, axis=-1), (-1, len(arrays)))
+
+    return result
+
+
+def _split_subregion(a, b, xp, split_at=None):
+    """
+    Given the coordinates of a region like a=[0, 0] and b=[1, 1], yield the coordinates
+    of all subregions, which in this case would be::
+
+        ([0, 0], [1/2, 1/2]),
+        ([0, 1/2], [1/2, 1]),
+        ([1/2, 0], [1, 1/2]),
+        ([1/2, 1/2], [1, 1])
+    """
+    xp = array_namespace(a, b)
+
+    if split_at is None:
+        split_at = (a + b) / 2
+
+    left = [xp.stack((a[i], split_at[i])) for i in range(a.shape[0])]
+    right = [xp.stack((split_at[i], b[i])) for i in range(b.shape[0])]
+
+    a_sub = _cartesian_product(left)
+    b_sub = _cartesian_product(right)
+
+    for i in range(a_sub.shape[0]):
+        yield a_sub[i, ...], b_sub[i, ...]
+
+
+def _apply_fixed_rule(f, a, b, orig_nodes, orig_weights, args, xp):
+    # Downcast nodes and weights to common dtype of a and b
+    result_dtype = a.dtype
+    orig_nodes = xp.astype(orig_nodes, result_dtype)
+    orig_weights = xp.astype(orig_weights, result_dtype)
+
+    # Ensure orig_nodes are at least 2D, since 1D cubature methods can return arrays of
+    # shape (npoints,) rather than (npoints, 1)
+    if orig_nodes.ndim == 1:
+        orig_nodes = orig_nodes[:, None]
+
+    rule_ndim = orig_nodes.shape[-1]
+
+    a_ndim = xp_size(a)
+    b_ndim = xp_size(b)
+
+    if rule_ndim != a_ndim or rule_ndim != b_ndim:
+        raise ValueError(f"rule and function are of incompatible dimension, nodes have"
+                         f"ndim {rule_ndim}, while limit of integration has ndim"
+                         f"a_ndim={a_ndim}, b_ndim={b_ndim}")
+
+    lengths = b - a
+
+    # The underlying rule is for the hypercube [-1, 1]^n.
+    #
+    # To handle arbitrary regions of integration, it's necessary to apply a linear
+    # change of coordinates to map each interval [a[i], b[i]] to [-1, 1].
+    nodes = (orig_nodes + 1) * (lengths * 0.5) + a
+
+    # Also need to multiply the weights by a scale factor equal to the determinant
+    # of the Jacobian for this coordinate change.
+    weight_scale_factor = xp.prod(lengths, dtype=result_dtype) / 2**rule_ndim
+    weights = orig_weights * weight_scale_factor
+
+    f_nodes = f(nodes, *args)
+    weights_reshaped = xp.reshape(weights, (-1, *([1] * (f_nodes.ndim - 1))))
+
+    # f(nodes) will have shape (num_nodes, output_dim_1, ..., output_dim_n)
+    # Summing along the first axis means estimate will shape (output_dim_1, ...,
+    # output_dim_n)
+    est = xp.sum(weights_reshaped * f_nodes, axis=0, dtype=result_dtype)
+
+    return est
diff --git a/.venv/lib/python3.12/site-packages/scipy/integrate/_rules/_gauss_kronrod.py b/.venv/lib/python3.12/site-packages/scipy/integrate/_rules/_gauss_kronrod.py
new file mode 100644
index 0000000000000000000000000000000000000000..b2a3518c55cf49cd14c777d243ea7e93a489f86c
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/integrate/_rules/_gauss_kronrod.py
@@ -0,0 +1,202 @@
+from scipy._lib._array_api import np_compat, array_namespace
+
+from functools import cached_property
+
+from ._base import NestedFixedRule
+from ._gauss_legendre import GaussLegendreQuadrature
+
+
+class GaussKronrodQuadrature(NestedFixedRule):
+    """
+    Gauss-Kronrod quadrature.
+
+    Gauss-Kronrod rules consist of two quadrature rules, one higher-order and one
+    lower-order. The higher-order rule is used as the estimate of the integral and the
+    difference between them is used as an estimate for the error.
+
+    Gauss-Kronrod is a 1D rule. To use it for multidimensional integrals, it will be
+    necessary to use ProductNestedFixed and multiple Gauss-Kronrod rules. See Examples.
+
+    For n-node Gauss-Kronrod, the lower-order rule has ``n//2`` nodes, which are the
+    ordinary Gauss-Legendre nodes with corresponding weights. The higher-order rule has
+    ``n`` nodes, ``n//2`` of which are the same as the lower-order rule and the
+    remaining nodes are the Kronrod extension of those nodes.
+
+    Parameters
+    ----------
+    npoints : int
+        Number of nodes for the higher-order rule.
+
+    xp : array_namespace, optional
+        The namespace for the node and weight arrays. Default is None, where NumPy is
+        used.
+
+    Attributes
+    ----------
+    lower : Rule
+        Lower-order rule.
+
+    References
+    ----------
+    .. [1] R. Piessens, E. de Doncker, Quadpack: A Subroutine Package for Automatic
+        Integration, files: dqk21.f, dqk15.f (1983).
+
+    Examples
+    --------
+    Evaluate a 1D integral. Note in this example that ``f`` returns an array, so the
+    estimates will also be arrays, despite the fact that this is a 1D problem.
+
+    >>> import numpy as np
+    >>> from scipy.integrate import cubature
+    >>> from scipy.integrate._rules import GaussKronrodQuadrature
+    >>> def f(x):
+    ...     return np.cos(x)
+    >>> rule = GaussKronrodQuadrature(21) # Use 21-point GaussKronrod
+    >>> a, b = np.array([0]), np.array([1])
+    >>> rule.estimate(f, a, b) # True value sin(1), approximately 0.84147
+     array([0.84147098])
+    >>> rule.estimate_error(f, a, b)
+     array([1.11022302e-16])
+
+    Evaluate a 2D integral. Note that in this example ``f`` returns a float, so the
+    estimates will also be floats.
+
+    >>> import numpy as np
+    >>> from scipy.integrate import cubature
+    >>> from scipy.integrate._rules import (
+    ...     ProductNestedFixed, GaussKronrodQuadrature
+    ... )
+    >>> def f(x):
+    ...     # f(x) = cos(x_1) + cos(x_2)
+    ...     return np.sum(np.cos(x), axis=-1)
+    >>> rule = ProductNestedFixed(
+    ...     [GaussKronrodQuadrature(15), GaussKronrodQuadrature(15)]
+    ... ) # Use 15-point Gauss-Kronrod
+    >>> a, b = np.array([0, 0]), np.array([1, 1])
+    >>> rule.estimate(f, a, b) # True value 2*sin(1), approximately 1.6829
+     np.float64(1.682941969615793)
+    >>> rule.estimate_error(f, a, b)
+     np.float64(2.220446049250313e-16)
+    """
+
+    def __init__(self, npoints, xp=None):
+        # TODO: nodes and weights are currently hard-coded for values 15 and 21, but in
+        # the future it would be best to compute the Kronrod extension of the lower rule
+        if npoints != 15 and npoints != 21:
+            raise NotImplementedError("Gauss-Kronrod quadrature is currently only"
+                                      "supported for 15 or 21 nodes")
+
+        self.npoints = npoints
+
+        if xp is None:
+            xp = np_compat
+
+        self.xp = array_namespace(xp.empty(0))
+
+        self.gauss = GaussLegendreQuadrature(npoints//2, xp=self.xp)
+
+    @cached_property
+    def nodes_and_weights(self):
+        # These values are from QUADPACK's `dqk21.f` and `dqk15.f` (1983).
+        if self.npoints == 21:
+            nodes = self.xp.asarray(
+                [
+                    0.995657163025808080735527280689003,
+                    0.973906528517171720077964012084452,
+                    0.930157491355708226001207180059508,
+                    0.865063366688984510732096688423493,
+                    0.780817726586416897063717578345042,
+                    0.679409568299024406234327365114874,
+                    0.562757134668604683339000099272694,
+                    0.433395394129247190799265943165784,
+                    0.294392862701460198131126603103866,
+                    0.148874338981631210884826001129720,
+                    0,
+                    -0.148874338981631210884826001129720,
+                    -0.294392862701460198131126603103866,
+                    -0.433395394129247190799265943165784,
+                    -0.562757134668604683339000099272694,
+                    -0.679409568299024406234327365114874,
+                    -0.780817726586416897063717578345042,
+                    -0.865063366688984510732096688423493,
+                    -0.930157491355708226001207180059508,
+                    -0.973906528517171720077964012084452,
+                    -0.995657163025808080735527280689003,
+                ],
+                dtype=self.xp.float64,
+            )
+
+            weights = self.xp.asarray(
+                [
+                    0.011694638867371874278064396062192,
+                    0.032558162307964727478818972459390,
+                    0.054755896574351996031381300244580,
+                    0.075039674810919952767043140916190,
+                    0.093125454583697605535065465083366,
+                    0.109387158802297641899210590325805,
+                    0.123491976262065851077958109831074,
+                    0.134709217311473325928054001771707,
+                    0.142775938577060080797094273138717,
+                    0.147739104901338491374841515972068,
+                    0.149445554002916905664936468389821,
+                    0.147739104901338491374841515972068,
+                    0.142775938577060080797094273138717,
+                    0.134709217311473325928054001771707,
+                    0.123491976262065851077958109831074,
+                    0.109387158802297641899210590325805,
+                    0.093125454583697605535065465083366,
+                    0.075039674810919952767043140916190,
+                    0.054755896574351996031381300244580,
+                    0.032558162307964727478818972459390,
+                    0.011694638867371874278064396062192,
+                ],
+                dtype=self.xp.float64,
+            )
+        elif self.npoints == 15:
+            nodes = self.xp.asarray(
+                [
+                    0.991455371120812639206854697526329,
+                    0.949107912342758524526189684047851,
+                    0.864864423359769072789712788640926,
+                    0.741531185599394439863864773280788,
+                    0.586087235467691130294144838258730,
+                    0.405845151377397166906606412076961,
+                    0.207784955007898467600689403773245,
+                    0.000000000000000000000000000000000,
+                    -0.207784955007898467600689403773245,
+                    -0.405845151377397166906606412076961,
+                    -0.586087235467691130294144838258730,
+                    -0.741531185599394439863864773280788,
+                    -0.864864423359769072789712788640926,
+                    -0.949107912342758524526189684047851,
+                    -0.991455371120812639206854697526329,
+                ],
+                dtype=self.xp.float64,
+            )
+
+            weights = self.xp.asarray(
+                [
+                    0.022935322010529224963732008058970,
+                    0.063092092629978553290700663189204,
+                    0.104790010322250183839876322541518,
+                    0.140653259715525918745189590510238,
+                    0.169004726639267902826583426598550,
+                    0.190350578064785409913256402421014,
+                    0.204432940075298892414161999234649,
+                    0.209482141084727828012999174891714,
+                    0.204432940075298892414161999234649,
+                    0.190350578064785409913256402421014,
+                    0.169004726639267902826583426598550,
+                    0.140653259715525918745189590510238,
+                    0.104790010322250183839876322541518,
+                    0.063092092629978553290700663189204,
+                    0.022935322010529224963732008058970,
+                ],
+                dtype=self.xp.float64,
+            )
+
+        return nodes, weights
+
+    @property
+    def lower_nodes_and_weights(self):
+        return self.gauss.nodes_and_weights
diff --git a/.venv/lib/python3.12/site-packages/scipy/integrate/_rules/_gauss_legendre.py b/.venv/lib/python3.12/site-packages/scipy/integrate/_rules/_gauss_legendre.py
new file mode 100644
index 0000000000000000000000000000000000000000..1163aec5370fb93951402ab99ee2ae4b79158d52
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/integrate/_rules/_gauss_legendre.py
@@ -0,0 +1,62 @@
+from scipy._lib._array_api import array_namespace, np_compat
+
+from functools import cached_property
+
+from scipy.special import roots_legendre
+
+from ._base import FixedRule
+
+
+class GaussLegendreQuadrature(FixedRule):
+    """
+    Gauss-Legendre quadrature.
+
+    Parameters
+    ----------
+    npoints : int
+        Number of nodes for the higher-order rule.
+
+    xp : array_namespace, optional
+        The namespace for the node and weight arrays. Default is None, where NumPy is
+        used.
+
+    Examples
+    --------
+    Evaluate a 1D integral. Note in this example that ``f`` returns an array, so the
+    estimates will also be arrays.
+
+    >>> import numpy as np
+    >>> from scipy.integrate import cubature
+    >>> from scipy.integrate._rules import GaussLegendreQuadrature
+    >>> def f(x):
+    ...     return np.cos(x)
+    >>> rule = GaussLegendreQuadrature(21) # Use 21-point GaussLegendre
+    >>> a, b = np.array([0]), np.array([1])
+    >>> rule.estimate(f, a, b) # True value sin(1), approximately 0.84147
+     array([0.84147098])
+    >>> rule.estimate_error(f, a, b)
+     array([1.11022302e-16])
+    """
+
+    def __init__(self, npoints, xp=None):
+        if npoints < 2:
+            raise ValueError(
+                "At least 2 nodes required for Gauss-Legendre cubature"
+            )
+
+        self.npoints = npoints
+
+        if xp is None:
+            xp = np_compat
+
+        self.xp = array_namespace(xp.empty(0))
+
+    @cached_property
+    def nodes_and_weights(self):
+        # TODO: current converting to/from numpy
+        nodes, weights = roots_legendre(self.npoints)
+
+        return (
+            self.xp.asarray(nodes, dtype=self.xp.float64),
+            self.xp.asarray(weights, dtype=self.xp.float64)
+        )
diff --git a/.venv/lib/python3.12/site-packages/scipy/integrate/_rules/_genz_malik.py b/.venv/lib/python3.12/site-packages/scipy/integrate/_rules/_genz_malik.py
new file mode 100644
index 0000000000000000000000000000000000000000..fdf187a7a0aad3baa36d5ae303afebadade18884
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/integrate/_rules/_genz_malik.py
@@ -0,0 +1,210 @@
+import math
+import itertools
+
+from functools import cached_property
+
+from scipy._lib._array_api import array_namespace, np_compat
+
+from scipy.integrate._rules import NestedFixedRule
+
+
+class GenzMalikCubature(NestedFixedRule):
+    """
+    Genz-Malik cubature.
+
+    Genz-Malik is only defined for integrals of dimension >= 2.
+
+    Parameters
+    ----------
+    ndim : int
+        The spatial dimension of the integrand.
+
+    xp : array_namespace, optional
+        The namespace for the node and weight arrays. Default is None, where NumPy is
+        used.
+
+    Attributes
+    ----------
+    higher : Cubature
+        Higher-order rule.
+
+    lower : Cubature
+        Lower-order rule.
+
+    References
+    ----------
+    .. [1] A.C. Genz, A.A. Malik, Remarks on algorithm 006: An adaptive algorithm for
+        numerical integration over an N-dimensional rectangular region, Journal of
+        Computational and Applied Mathematics, Volume 6, Issue 4, 1980, Pages 295-302,
+        ISSN 0377-0427, :doi:`10.1016/0771-050X(80)90039-X`.
+
+    Examples
+    --------
+    Evaluate a 3D integral:
+
+    >>> import numpy as np
+    >>> from scipy.integrate import cubature
+    >>> from scipy.integrate._rules import GenzMalikCubature
+    >>> def f(x):
+    ...     # f(x) = cos(x_1) + cos(x_2) + cos(x_3)
+    ...     return np.sum(np.cos(x), axis=-1)
+    >>> rule = GenzMalikCubature(3) # Use 3D Genz-Malik
+    >>> a, b = np.array([0, 0, 0]), np.array([1, 1, 1])
+    >>> rule.estimate(f, a, b) # True value 3*sin(1), approximately 2.5244
+     np.float64(2.5244129547230862)
+    >>> rule.estimate_error(f, a, b)
+     np.float64(1.378269656626685e-06)
+    """
+
+    def __init__(self, ndim, degree=7, lower_degree=5, xp=None):
+        if ndim < 2:
+            raise ValueError("Genz-Malik cubature is only defined for ndim >= 2")
+
+        if degree != 7 or lower_degree != 5:
+            raise NotImplementedError("Genz-Malik cubature is currently only supported"
+                                      "for degree=7, lower_degree=5")
+
+        self.ndim = ndim
+        self.degree = degree
+        self.lower_degree = lower_degree
+
+        if xp is None:
+            xp = np_compat
+
+        self.xp = array_namespace(xp.empty(0))
+
+    @cached_property
+    def nodes_and_weights(self):
+        # TODO: Currently only support for degree 7 Genz-Malik cubature, should aim to
+        # support arbitrary degree
+        l_2 = math.sqrt(9/70)
+        l_3 = math.sqrt(9/10)
+        l_4 = math.sqrt(9/10)
+        l_5 = math.sqrt(9/19)
+
+        its = itertools.chain(
+            [(0,) * self.ndim],
+            _distinct_permutations((l_2,) + (0,) * (self.ndim - 1)),
+            _distinct_permutations((-l_2,) + (0,) * (self.ndim - 1)),
+            _distinct_permutations((l_3,) + (0,) * (self.ndim - 1)),
+            _distinct_permutations((-l_3,) + (0,) * (self.ndim - 1)),
+            _distinct_permutations((l_4, l_4) + (0,) * (self.ndim - 2)),
+            _distinct_permutations((l_4, -l_4) + (0,) * (self.ndim - 2)),
+            _distinct_permutations((-l_4, -l_4) + (0,) * (self.ndim - 2)),
+            itertools.product((l_5, -l_5), repeat=self.ndim),
+        )
+
+        nodes_size = 1 + (2 * (self.ndim + 1) * self.ndim) + 2**self.ndim
+
+        nodes = self.xp.asarray(
+            list(zip(*its)),
+            dtype=self.xp.float64,
+        )
+
+        nodes = self.xp.reshape(nodes, (self.ndim, nodes_size))
+
+        # It's convenient to generate the nodes as a sequence of evaluation points
+        # as an array of shape (npoints, ndim), but nodes needs to have shape
+        # (ndim, npoints)
+        nodes = nodes.T
+
+        w_1 = (
+            (2**self.ndim) * (12824 - 9120*self.ndim + (400 * self.ndim**2)) / 19683
+        )
+        w_2 = (2**self.ndim) * 980/6561
+        w_3 = (2**self.ndim) * (1820 - 400 * self.ndim) / 19683
+        w_4 = (2**self.ndim) * (200 / 19683)
+        w_5 = 6859 / 19683
+
+        weights = self.xp.concat([
+            self.xp.asarray([w_1] * 1, dtype=self.xp.float64),
+            self.xp.asarray([w_2] * (2 * self.ndim), dtype=self.xp.float64),
+            self.xp.asarray([w_3] * (2 * self.ndim), dtype=self.xp.float64),
+            self.xp.asarray(
+                [w_4] * (2 * (self.ndim - 1) * self.ndim),
+                dtype=self.xp.float64,
+            ),
+            self.xp.asarray([w_5] * (2**self.ndim), dtype=self.xp.float64),
+        ])
+
+        return nodes, weights
+
+    @cached_property
+    def lower_nodes_and_weights(self):
+        # TODO: Currently only support for the degree 5 lower rule, in the future it
+        # would be worth supporting arbitrary degree
+
+        # Nodes are almost the same as the full rule, but there are no nodes
+        # corresponding to l_5.
+        l_2 = math.sqrt(9/70)
+        l_3 = math.sqrt(9/10)
+        l_4 = math.sqrt(9/10)
+
+        its = itertools.chain(
+            [(0,) * self.ndim],
+            _distinct_permutations((l_2,) + (0,) * (self.ndim - 1)),
+            _distinct_permutations((-l_2,) + (0,) * (self.ndim - 1)),
+            _distinct_permutations((l_3,) + (0,) * (self.ndim - 1)),
+            _distinct_permutations((-l_3,) + (0,) * (self.ndim - 1)),
+            _distinct_permutations((l_4, l_4) + (0,) * (self.ndim - 2)),
+            _distinct_permutations((l_4, -l_4) + (0,) * (self.ndim - 2)),
+            _distinct_permutations((-l_4, -l_4) + (0,) * (self.ndim - 2)),
+        )
+
+        nodes_size = 1 + (2 * (self.ndim + 1) * self.ndim)
+
+        nodes = self.xp.asarray(list(zip(*its)), dtype=self.xp.float64)
+        nodes = self.xp.reshape(nodes, (self.ndim, nodes_size))
+        nodes = nodes.T
+
+        # Weights are different from those in the full rule.
+        w_1 = (2**self.ndim) * (729 - 950*self.ndim + 50*self.ndim**2) / 729
+        w_2 = (2**self.ndim) * (245 / 486)
+        w_3 = (2**self.ndim) * (265 - 100*self.ndim) / 1458
+        w_4 = (2**self.ndim) * (25 / 729)
+
+        weights = self.xp.concat([
+            self.xp.asarray([w_1] * 1, dtype=self.xp.float64),
+            self.xp.asarray([w_2] * (2 * self.ndim), dtype=self.xp.float64),
+            self.xp.asarray([w_3] * (2 * self.ndim), dtype=self.xp.float64),
+            self.xp.asarray(
+                [w_4] * (2 * (self.ndim - 1) * self.ndim),
+                dtype=self.xp.float64,
+            ),
+        ])
+
+        return nodes, weights
+
+
+def _distinct_permutations(iterable):
+    """
+    Find the number of distinct permutations of elements of `iterable`.
+    """
+
+    # Algorithm: https://w.wiki/Qai
+
+    items = sorted(iterable)
+    size = len(items)
+
+    while True:
+        # Yield the permutation we have
+        yield tuple(items)
+
+        # Find the largest index i such that A[i] < A[i + 1]
+        for i in range(size - 2, -1, -1):
+            if items[i] < items[i + 1]:
+                break
+
+        #  If no such index exists, this permutation is the last one
+        else:
+            return
+
+        # Find the largest index j greater than j such that A[i] < A[j]
+        for j in range(size - 1, i, -1):
+            if items[i] < items[j]:
+                break
+
+        # Swap the value of A[i] with that of A[j], then reverse the
+        # sequence from A[i + 1] to form the new permutation
+        items[i], items[j] = items[j], items[i]
+        items[i+1:] = items[:i-size:-1]  # A[i + 1:][::-1]
diff --git a/.venv/lib/python3.12/site-packages/scipy/integrate/_tanhsinh.py b/.venv/lib/python3.12/site-packages/scipy/integrate/_tanhsinh.py
new file mode 100644
index 0000000000000000000000000000000000000000..306974b4e70218837c2d5ff6646b2d5187260af1
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/integrate/_tanhsinh.py
@@ -0,0 +1,1391 @@
+# mypy: disable-error-code="attr-defined"
+import math
+import numpy as np
+from scipy import special
+import scipy._lib._elementwise_iterative_method as eim
+from scipy._lib._util import _RichResult
+from scipy._lib._array_api import (array_namespace, xp_copy, xp_ravel,
+                                   xp_promote, xp_capabilities)
+
+
+__all__ = ['nsum']
+
+
+# todo:
+#  figure out warning situation
+#  address https://github.com/scipy/scipy/pull/18650#discussion_r1233032521
+#  without `minweight`, we are also suppressing infinities within the interval.
+#    Is that OK? If so, we can probably get rid of `status=3`.
+#  support singularities? interval subdivision? this feature will be added
+#    eventually, but do we adjust the interface now?
+
+
+@xp_capabilities(skip_backends=[('array_api_strict', 'No fancy indexing.'),
+                                ('jax.numpy', 'No mutation.'),
+                                ('dask.array',
+                                 'Data-dependent shapes in boolean index assignment')])
+def tanhsinh(f, a, b, *, args=(), kwargs=None, log=False, maxlevel=None, minlevel=2,
+             atol=None, rtol=None, preserve_shape=False, callback=None):
+    """Evaluate a convergent integral numerically using tanh-sinh quadrature.
+
+    In practice, tanh-sinh quadrature achieves quadratic convergence for
+    many integrands: the number of accurate *digits* scales roughly linearly
+    with the number of function evaluations [1]_.
+
+    Either or both of the limits of integration may be infinite, and
+    singularities at the endpoints are acceptable. Divergent integrals and
+    integrands with non-finite derivatives or singularities within an interval
+    are out of scope, but the latter may be evaluated be calling `tanhsinh` on
+    each sub-interval separately.
+
+    Parameters
+    ----------
+    f : callable
+        The function to be integrated. The signature must be::
+
+            f(xi: ndarray, *argsi) -> ndarray
+
+        where each element of ``xi`` is a finite real number and ``argsi`` is a tuple,
+        which may contain an arbitrary number of arrays that are broadcastable
+        with ``xi``. `f` must be an elementwise function: see documentation of parameter
+        `preserve_shape` for details. It must not mutate the array ``xi`` or the arrays
+        in ``argsi``.
+        If ``f`` returns a value with complex dtype when evaluated at
+        either endpoint, subsequent arguments ``x`` will have complex dtype
+        (but zero imaginary part).
+    a, b : float array_like
+        Real lower and upper limits of integration. Must be broadcastable with one
+        another and with arrays in `args`. Elements may be infinite.
+    args : tuple of array_like, optional
+        Additional positional array arguments to be passed to `f`. Arrays
+        must be broadcastable with one another and the arrays of `a` and `b`.
+        If the callable for which the root is desired requires arguments that are
+        not broadcastable with `x`, wrap that callable with `f` such that `f`
+        accepts only `x` and broadcastable ``*args``.
+    kwargs : dict of str:array_like, optional
+        Additional keyword arguments to be passed to `f`. See `args`.
+    log : bool, default: False
+        Setting to True indicates that `f` returns the log of the integrand
+        and that `atol` and `rtol` are expressed as the logs of the absolute
+        and relative errors. In this case, the result object will contain the
+        log of the integral and error. This is useful for integrands for which
+        numerical underflow or overflow would lead to inaccuracies.
+        When ``log=True``, the integrand (the exponential of `f`) must be real,
+        but it may be negative, in which case the log of the integrand is a
+        complex number with an imaginary part that is an odd multiple of π.
+    maxlevel : int, default: 10
+        The maximum refinement level of the algorithm.
+
+        At the zeroth level, `f` is called once, performing 16 function
+        evaluations. At each subsequent level, `f` is called once more,
+        approximately doubling the number of function evaluations that have
+        been performed. Accordingly, for many integrands, each successive level
+        will double the number of accurate digits in the result (up to the
+        limits of floating point precision).
+
+        The algorithm will terminate after completing level `maxlevel` or after
+        another termination condition is satisfied, whichever comes first.
+    minlevel : int, default: 2
+        The level at which to begin iteration (default: 2). This does not
+        change the total number of function evaluations or the abscissae at
+        which the function is evaluated; it changes only the *number of times*
+        `f` is called. If ``minlevel=k``, then the integrand is evaluated at
+        all abscissae from levels ``0`` through ``k`` in a single call.
+        Note that if `minlevel` exceeds `maxlevel`, the provided `minlevel` is
+        ignored, and `minlevel` is set equal to `maxlevel`.
+    atol, rtol : float, optional
+        Absolute termination tolerance (default: 0) and relative termination
+        tolerance (default: ``eps**0.75``, where ``eps`` is the precision of
+        the result dtype), respectively. Must be non-negative and finite if
+        `log` is False, and must be expressed as the log of a non-negative and
+        finite number if `log` is True. Iteration will stop when
+        ``res.error < atol`` or  ``res.error < res.integral * rtol``.
+    preserve_shape : bool, default: False
+        In the following, "arguments of `f`" refers to the array ``xi`` and
+        any arrays within ``argsi``. Let ``shape`` be the broadcasted shape
+        of `a`, `b`, and all elements of `args` (which is conceptually
+        distinct from ``xi`` and ``argsi`` passed into `f`).
+
+        - When ``preserve_shape=False`` (default), `f` must accept arguments
+          of *any* broadcastable shapes.
+
+        - When ``preserve_shape=True``, `f` must accept arguments of shape
+          ``shape`` *or* ``shape + (n,)``, where ``(n,)`` is the number of
+          abscissae at which the function is being evaluated.
+
+        In either case, for each scalar element ``xi[j]`` within ``xi``, the array
+        returned by `f` must include the scalar ``f(xi[j])`` at the same index.
+        Consequently, the shape of the output is always the shape of the input
+        ``xi``.
+
+        See Examples.
+
+    callback : callable, optional
+        An optional user-supplied function to be called before the first
+        iteration and after each iteration.
+        Called as ``callback(res)``, where ``res`` is a ``_RichResult``
+        similar to that returned by `tanhsinh` (but containing the
+        current iterate's values of all variables). If `callback` raises a
+        ``StopIteration``, the algorithm will terminate immediately and
+        `tanhsinh` will return a result object. `callback` must not mutate
+        `res` or its attributes.
+
+    Returns
+    -------
+    res : _RichResult
+        An object similar to an instance of `scipy.optimize.OptimizeResult` with the
+        following attributes. (The descriptions are written as though the values will
+        be scalars; however, if `f` returns an array, the outputs will be
+        arrays of the same shape.)
+
+        success : bool array
+            ``True`` when the algorithm terminated successfully (status ``0``).
+            ``False`` otherwise.
+        status : int array
+            An integer representing the exit status of the algorithm.
+
+            - ``0`` : The algorithm converged to the specified tolerances.
+            - ``-1`` : (unused)
+            - ``-2`` : The maximum number of iterations was reached.
+            - ``-3`` : A non-finite value was encountered.
+            - ``-4`` : Iteration was terminated by `callback`.
+            - ``1`` : The algorithm is proceeding normally (in `callback` only).
+
+        integral : float array
+            An estimate of the integral.
+        error : float array
+            An estimate of the error. Only available if level two or higher
+            has been completed; otherwise NaN.
+        maxlevel : int array
+            The maximum refinement level used.
+        nfev : int array
+            The number of points at which `f` was evaluated.
+
+    See Also
+    --------
+    quad
+
+    Notes
+    -----
+    Implements the algorithm as described in [1]_ with minor adaptations for
+    finite-precision arithmetic, including some described by [2]_ and [3]_. The
+    tanh-sinh scheme was originally introduced in [4]_.
+
+    Two error estimation schemes are described in [1]_ Section 5: one attempts to
+    detect and exploit quadratic convergence; the other simply compares the integral
+    estimates at successive levels. While neither is theoretically rigorous or
+    conservative, both work well in practice. Our error estimate uses the minimum of
+    these two schemes with a lower bound of ``eps * res.integral``.
+
+    Due to floating-point error in the abscissae, the function may be evaluated
+    at the endpoints of the interval during iterations, but the values returned by
+    the function at the endpoints will be ignored.
+
+    References
+    ----------
+    .. [1] Bailey, David H., Karthik Jeyabalan, and Xiaoye S. Li. "A comparison of
+           three high-precision quadrature schemes." Experimental Mathematics 14.3
+           (2005): 317-329.
+    .. [2] Vanherck, Joren, Bart Sorée, and Wim Magnus. "Tanh-sinh quadrature for
+           single and multiple integration using floating-point arithmetic."
+           arXiv preprint arXiv:2007.15057 (2020).
+    .. [3] van Engelen, Robert A.  "Improving the Double Exponential Quadrature
+           Tanh-Sinh, Sinh-Sinh and Exp-Sinh Formulas."
+           https://www.genivia.com/files/qthsh.pdf
+    .. [4] Takahasi, Hidetosi, and Masatake Mori. "Double exponential formulas for
+           numerical integration." Publications of the Research Institute for
+           Mathematical Sciences 9.3 (1974): 721-741.
+
+    Examples
+    --------
+    Evaluate the Gaussian integral:
+
+    >>> import numpy as np
+    >>> from scipy.integrate import tanhsinh
+    >>> def f(x):
+    ...     return np.exp(-x**2)
+    >>> res = tanhsinh(f, -np.inf, np.inf)
+    >>> res.integral  # true value is np.sqrt(np.pi), 1.7724538509055159
+    1.7724538509055159
+    >>> res.error  # actual error is 0
+    4.0007963937534104e-16
+
+    The value of the Gaussian function (bell curve) is nearly zero for
+    arguments sufficiently far from zero, so the value of the integral
+    over a finite interval is nearly the same.
+
+    >>> tanhsinh(f, -20, 20).integral
+    1.772453850905518
+
+    However, with unfavorable integration limits, the integration scheme
+    may not be able to find the important region.
+
+    >>> tanhsinh(f, -np.inf, 1000).integral
+    4.500490856616431
+
+    In such cases, or when there are singularities within the interval,
+    break the integral into parts with endpoints at the important points.
+
+    >>> tanhsinh(f, -np.inf, 0).integral + tanhsinh(f, 0, 1000).integral
+    1.772453850905404
+
+    For integration involving very large or very small magnitudes, use
+    log-integration. (For illustrative purposes, the following example shows a
+    case in which both regular and log-integration work, but for more extreme
+    limits of integration, log-integration would avoid the underflow
+    experienced when evaluating the integral normally.)
+
+    >>> res = tanhsinh(f, 20, 30, rtol=1e-10)
+    >>> res.integral, res.error
+    (4.7819613911309014e-176, 4.670364401645202e-187)
+    >>> def log_f(x):
+    ...     return -x**2
+    >>> res = tanhsinh(log_f, 20, 30, log=True, rtol=np.log(1e-10))
+    >>> np.exp(res.integral), np.exp(res.error)
+    (4.7819613911306924e-176, 4.670364401645093e-187)
+
+    The limits of integration and elements of `args` may be broadcastable
+    arrays, and integration is performed elementwise.
+
+    >>> from scipy import stats
+    >>> dist = stats.gausshyper(13.8, 3.12, 2.51, 5.18)
+    >>> a, b = dist.support()
+    >>> x = np.linspace(a, b, 100)
+    >>> res = tanhsinh(dist.pdf, a, x)
+    >>> ref = dist.cdf(x)
+    >>> np.allclose(res.integral, ref)
+    True
+
+    By default, `preserve_shape` is False, and therefore the callable
+    `f` may be called with arrays of any broadcastable shapes.
+    For example:
+
+    >>> shapes = []
+    >>> def f(x, c):
+    ...    shape = np.broadcast_shapes(x.shape, c.shape)
+    ...    shapes.append(shape)
+    ...    return np.sin(c*x)
+    >>>
+    >>> c = [1, 10, 30, 100]
+    >>> res = tanhsinh(f, 0, 1, args=(c,), minlevel=1)
+    >>> shapes
+    [(4,), (4, 34), (4, 32), (3, 64), (2, 128), (1, 256)]
+
+    To understand where these shapes are coming from - and to better
+    understand how `tanhsinh` computes accurate results - note that
+    higher values of ``c`` correspond with higher frequency sinusoids.
+    The higher frequency sinusoids make the integrand more complicated,
+    so more function evaluations are required to achieve the target
+    accuracy:
+
+    >>> res.nfev
+    array([ 67, 131, 259, 515], dtype=int32)
+
+    The initial ``shape``, ``(4,)``, corresponds with evaluating the
+    integrand at a single abscissa and all four frequencies; this is used
+    for input validation and to determine the size and dtype of the arrays
+    that store results. The next shape corresponds with evaluating the
+    integrand at an initial grid of abscissae and all four frequencies.
+    Successive calls to the function double the total number of abscissae at
+    which the function has been evaluated. However, in later function
+    evaluations, the integrand is evaluated at fewer frequencies because
+    the corresponding integral has already converged to the required
+    tolerance. This saves function evaluations to improve performance, but
+    it requires the function to accept arguments of any shape.
+
+    "Vector-valued" integrands, such as those written for use with
+    `scipy.integrate.quad_vec`, are unlikely to satisfy this requirement.
+    For example, consider
+
+    >>> def f(x):
+    ...    return [x, np.sin(10*x), np.cos(30*x), x*np.sin(100*x)**2]
+
+    This integrand is not compatible with `tanhsinh` as written; for instance,
+    the shape of the output will not be the same as the shape of ``x``. Such a
+    function *could* be converted to a compatible form with the introduction of
+    additional parameters, but this would be inconvenient. In such cases,
+    a simpler solution would be to use `preserve_shape`.
+
+    >>> shapes = []
+    >>> def f(x):
+    ...     shapes.append(x.shape)
+    ...     x0, x1, x2, x3 = x
+    ...     return [x0, np.sin(10*x1), np.cos(30*x2), x3*np.sin(100*x3)]
+    >>>
+    >>> a = np.zeros(4)
+    >>> res = tanhsinh(f, a, 1, preserve_shape=True)
+    >>> shapes
+    [(4,), (4, 66), (4, 64), (4, 128), (4, 256)]
+
+    Here, the broadcasted shape of `a` and `b` is ``(4,)``. With
+    ``preserve_shape=True``, the function may be called with argument
+    ``x`` of shape ``(4,)`` or ``(4, n)``, and this is what we observe.
+
+    """
+    maxfun = None  # unused right now
+    (f, a, b, log, maxfun, maxlevel, minlevel,
+     atol, rtol, args, kwargs, preserve_shape, callback, xp) = _tanhsinh_iv(
+        f, a, b, log, maxfun, maxlevel, minlevel, atol,
+        rtol, args, kwargs, preserve_shape, callback)
+
+    # Initialization
+    # `eim._initialize` does several important jobs, including
+    # ensuring that limits, each of the `args`, and the output of `f`
+    # broadcast correctly and are of consistent types. To save a function
+    # evaluation, I pass the midpoint of the integration interval. This comes
+    # at a cost of some gymnastics to ensure that the midpoint has the right
+    # shape and dtype. Did you know that 0d and >0d arrays follow different
+    # type promotion rules?
+    with np.errstate(over='ignore', invalid='ignore', divide='ignore'):
+        c = xp.reshape((xp_ravel(a) + xp_ravel(b))/2, a.shape)
+        inf_a, inf_b = xp.isinf(a), xp.isinf(b)
+        c[inf_a] = b[inf_a] - 1.  # takes care of infinite a
+        c[inf_b] = a[inf_b] + 1.  # takes care of infinite b
+        c[inf_a & inf_b] = 0.  # takes care of infinite a and b
+        temp = eim._initialize(f, (c,), args, kwargs=kwargs, complex_ok=True,
+                               preserve_shape=preserve_shape, xp=xp)
+    f, xs, fs, args, shape, dtype, xp = temp
+    a = xp_ravel(xp.astype(xp.broadcast_to(a, shape), dtype))
+    b = xp_ravel(xp.astype(xp.broadcast_to(b, shape), dtype))
+
+    # Transform improper integrals
+    a, b, a0, negative, abinf, ainf, binf = _transform_integrals(a, b, xp)
+
+    # Define variables we'll need
+    nit, nfev = 0, 1  # one function evaluation performed above
+    zero = -xp.inf if log else 0
+    pi = xp.asarray(xp.pi, dtype=dtype)[()]
+    maxiter = maxlevel - minlevel + 1
+    eps = xp.finfo(dtype).eps
+    if rtol is None:
+        rtol = 0.75*math.log(eps) if log else eps**0.75
+
+    Sn = xp_ravel(xp.full(shape, zero, dtype=dtype))  # latest integral estimate
+    Sn[xp.isnan(a) | xp.isnan(b) | xp.isnan(fs[0])] = xp.nan
+    Sk = xp.reshape(xp.empty_like(Sn), (-1, 1))[:, 0:0]  # all integral estimates
+    aerr = xp_ravel(xp.full(shape, xp.nan, dtype=dtype))  # absolute error
+    status = xp_ravel(xp.full(shape, eim._EINPROGRESS, dtype=xp.int32))
+    h0 = _get_base_step(dtype, xp)
+    h0 = xp.real(h0) # base step
+
+    # For term `d4` of error estimate ([1] Section 5), we need to keep the
+    # most extreme abscissae and corresponding `fj`s, `wj`s in Euler-Maclaurin
+    # sum. Here, we initialize these variables.
+    xr0 = xp_ravel(xp.full(shape, -xp.inf, dtype=dtype))
+    fr0 = xp_ravel(xp.full(shape, xp.nan, dtype=dtype))
+    wr0 = xp_ravel(xp.zeros(shape, dtype=dtype))
+    xl0 = xp_ravel(xp.full(shape, xp.inf, dtype=dtype))
+    fl0 = xp_ravel(xp.full(shape, xp.nan, dtype=dtype))
+    wl0 = xp_ravel(xp.zeros(shape, dtype=dtype))
+    d4 = xp_ravel(xp.zeros(shape, dtype=dtype))
+
+    work = _RichResult(
+        Sn=Sn, Sk=Sk, aerr=aerr, h=h0, log=log, dtype=dtype, pi=pi, eps=eps,
+        a=xp.reshape(a, (-1, 1)), b=xp.reshape(b, (-1, 1)),  # integration limits
+        n=minlevel, nit=nit, nfev=nfev, status=status,  # iter/eval counts
+        xr0=xr0, fr0=fr0, wr0=wr0, xl0=xl0, fl0=fl0, wl0=wl0, d4=d4,  # err est
+        ainf=ainf, binf=binf, abinf=abinf, a0=xp.reshape(a0, (-1, 1)),  # transforms
+        # Store the xjc/wj pair cache in an object so they can't get compressed
+        # Using RichResult to allow dot notation, but a dictionary would suffice
+        pair_cache=_RichResult(xjc=None, wj=None, indices=[0], h0=None))  # pair cache
+
+    # Constant scalars don't need to be put in `work` unless they need to be
+    # passed outside `tanhsinh`. Examples: atol, rtol, h0, minlevel.
+
+    # Correspondence between terms in the `work` object and the result
+    res_work_pairs = [('status', 'status'), ('integral', 'Sn'),
+                      ('error', 'aerr'), ('nit', 'nit'), ('nfev', 'nfev')]
+
+    def pre_func_eval(work):
+        # Determine abscissae at which to evaluate `f`
+        work.h = h0 / 2**work.n
+        xjc, wj = _get_pairs(work.n, h0, dtype=work.dtype,
+                             inclusive=(work.n == minlevel), xp=xp, work=work)
+        work.xj, work.wj = _transform_to_limits(xjc, wj, work.a, work.b, xp)
+
+        # Perform abscissae substitutions for infinite limits of integration
+        xj = xp_copy(work.xj)
+        xj[work.abinf] = xj[work.abinf] / (1 - xp.real(xj[work.abinf])**2)
+        xj[work.binf] = 1/xj[work.binf] - 1 + work.a0[work.binf]
+        xj[work.ainf] *= -1
+        return xj
+
+    def post_func_eval(x, fj, work):
+        # Weight integrand as required by substitutions for infinite limits
+        if work.log:
+            fj[work.abinf] += (xp.log(1 + work.xj[work.abinf]**2)
+                               - 2*xp.log(1 - work.xj[work.abinf]**2))
+            fj[work.binf] -= 2 * xp.log(work.xj[work.binf])
+        else:
+            fj[work.abinf] *= ((1 + work.xj[work.abinf]**2) /
+                               (1 - work.xj[work.abinf]**2)**2)
+            fj[work.binf] *= work.xj[work.binf]**-2.
+
+        # Estimate integral with Euler-Maclaurin Sum
+        fjwj, Sn = _euler_maclaurin_sum(fj, work, xp)
+        if work.Sk.shape[-1]:
+            Snm1 = work.Sk[:, -1]
+            Sn = (special.logsumexp(xp.stack([Snm1 - math.log(2), Sn]), axis=0) if log
+                  else Snm1 / 2 + Sn)
+
+        work.fjwj = fjwj
+        work.Sn = Sn
+
+    def check_termination(work):
+        """Terminate due to convergence or encountering non-finite values"""
+        stop = xp.zeros(work.Sn.shape, dtype=bool)
+
+        # Terminate before first iteration if integration limits are equal
+        if work.nit == 0:
+            i = xp_ravel(work.a == work.b)  # ravel singleton dimension
+            zero = xp.asarray(-xp.inf if log else 0.)
+            zero = xp.full(work.Sn.shape, zero, dtype=Sn.dtype)
+            zero[xp.isnan(Sn)] = xp.nan
+            work.Sn[i] = zero[i]
+            work.aerr[i] = zero[i]
+            work.status[i] = eim._ECONVERGED
+            stop[i] = True
+        else:
+            # Terminate if convergence criterion is met
+            rerr, aerr = _estimate_error(work, xp)
+            i = (rerr < rtol) | (aerr < atol)
+            work.aerr =  xp.reshape(xp.astype(aerr, work.dtype), work.Sn.shape)
+            work.status[i] = eim._ECONVERGED
+            stop[i] = True
+
+        # Terminate if integral estimate becomes invalid
+        if log:
+            Sn_real = xp.real(work.Sn)
+            Sn_pos_inf = xp.isinf(Sn_real) & (Sn_real > 0)
+            i = (Sn_pos_inf | xp.isnan(work.Sn)) & ~stop
+        else:
+            i = ~xp.isfinite(work.Sn) & ~stop
+        work.status[i] = eim._EVALUEERR
+        stop[i] = True
+
+        return stop
+
+    def post_termination_check(work):
+        work.n += 1
+        work.Sk = xp.concat((work.Sk, work.Sn[:, xp.newaxis]), axis=-1)
+        return
+
+    def customize_result(res, shape):
+        # If the integration limits were such that b < a, we reversed them
+        # to perform the calculation, and the final result needs to be negated.
+        if log and xp.any(negative):
+            res['integral'] = res['integral'] + negative * xp.pi * 1.0j
+        else:
+            res['integral'][negative] *= -1
+
+        # For this algorithm, it seems more appropriate to report the maximum
+        # level rather than the number of iterations in which it was performed.
+        res['maxlevel'] = minlevel + res['nit'] - 1
+        res['maxlevel'][res['nit'] == 0] = -1
+        del res['nit']
+        return shape
+
+    # Suppress all warnings initially, since there are many places in the code
+    # for which this is expected behavior.
+    with np.errstate(over='ignore', invalid='ignore', divide='ignore'):
+        res = eim._loop(work, callback, shape, maxiter, f, args, dtype, pre_func_eval,
+                        post_func_eval, check_termination, post_termination_check,
+                        customize_result, res_work_pairs, xp, preserve_shape)
+    return res
+
+
+def _get_base_step(dtype, xp):
+    # Compute the base step length for the provided dtype. Theoretically, the
+    # Euler-Maclaurin sum is infinite, but it gets cut off when either the
+    # weights underflow or the abscissae cannot be distinguished from the
+    # limits of integration. The latter happens to occur first for float32 and
+    # float64, and it occurs when `xjc` (the abscissa complement)
+    # in `_compute_pair` underflows. We can solve for the argument `tmax` at
+    # which it will underflow using [2] Eq. 13.
+    fmin = 4*xp.finfo(dtype).smallest_normal  # stay a little away from the limit
+    tmax = math.asinh(math.log(2/fmin - 1) / xp.pi)
+
+    # Based on this, we can choose a base step size `h` for level 0.
+    # The number of function evaluations will be `2 + m*2^(k+1)`, where `k` is
+    # the level and `m` is an integer we get to choose. I choose
+    # m = _N_BASE_STEPS = `8` somewhat arbitrarily, but a rationale is that a
+    # power of 2 makes floating point arithmetic more predictable. It also
+    # results in a base step size close to `1`, which is what [1] uses (and I
+    # used here until I found [2] and these ideas settled).
+    h0 = tmax / _N_BASE_STEPS
+    return xp.asarray(h0, dtype=dtype)[()]
+
+
+_N_BASE_STEPS = 8
+
+
+def _compute_pair(k, h0, xp):
+    # Compute the abscissa-weight pairs for each level k. See [1] page 9.
+
+    # For now, we compute and store in 64-bit precision. If higher-precision
+    # data types become better supported, it would be good to compute these
+    # using the highest precision available. Or, once there is an Array API-
+    # compatible arbitrary precision array, we can compute at the required
+    # precision.
+
+    # "....each level k of abscissa-weight pairs uses h = 2 **-k"
+    # We adapt to floating point arithmetic using ideas of [2].
+    h = h0 / 2**k
+    max = _N_BASE_STEPS * 2**k
+
+    # For iterations after the first, "....the integrand function needs to be
+    # evaluated only at the odd-indexed abscissas at each level."
+    j = xp.arange(max+1) if k == 0 else xp.arange(1, max+1, 2)
+    jh = j * h
+
+    # "In this case... the weights wj = u1/cosh(u2)^2, where..."
+    pi_2 = xp.pi / 2
+    u1 = pi_2*xp.cosh(jh)
+    u2 = pi_2*xp.sinh(jh)
+    # Denominators get big here. Overflow then underflow doesn't need warning.
+    # with np.errstate(under='ignore', over='ignore'):
+    wj = u1 / xp.cosh(u2)**2
+    # "We actually store 1-xj = 1/(...)."
+    xjc = 1 / (xp.exp(u2) * xp.cosh(u2))  # complement of xj = xp.tanh(u2)
+
+    # When level k == 0, the zeroth xj corresponds with xj = 0. To simplify
+    # code, the function will be evaluated there twice; each gets half weight.
+    wj[0] = wj[0] / 2 if k == 0 else wj[0]
+
+    return xjc, wj  # store at full precision
+
+
+def _pair_cache(k, h0, xp, work):
+    # Cache the abscissa-weight pairs up to a specified level.
+    # Abscissae and weights of consecutive levels are concatenated.
+    # `index` records the indices that correspond with each level:
+    # `xjc[index[k]:index[k+1]` extracts the level `k` abscissae.
+    if not isinstance(h0, type(work.pair_cache.h0)) or h0 != work.pair_cache.h0:
+        work.pair_cache.xjc = xp.empty(0)
+        work.pair_cache.wj = xp.empty(0)
+        work.pair_cache.indices = [0]
+
+    xjcs = [work.pair_cache.xjc]
+    wjs = [work.pair_cache.wj]
+
+    for i in range(len(work.pair_cache.indices)-1, k + 1):
+        xjc, wj = _compute_pair(i, h0, xp)
+        xjcs.append(xjc)
+        wjs.append(wj)
+        work.pair_cache.indices.append(work.pair_cache.indices[-1] + xjc.shape[0])
+
+    work.pair_cache.xjc = xp.concat(xjcs)
+    work.pair_cache.wj = xp.concat(wjs)
+    work.pair_cache.h0 = h0
+
+
+def _get_pairs(k, h0, inclusive, dtype, xp, work):
+    # Retrieve the specified abscissa-weight pairs from the cache
+    # If `inclusive`, return all up to and including the specified level
+    if (len(work.pair_cache.indices) <= k+2
+        or not isinstance (h0, type(work.pair_cache.h0))
+        or h0 != work.pair_cache.h0):
+            _pair_cache(k, h0, xp, work)
+
+    xjc = work.pair_cache.xjc
+    wj = work.pair_cache.wj
+    indices = work.pair_cache.indices
+
+    start = 0 if inclusive else indices[k]
+    end = indices[k+1]
+
+    return xp.astype(xjc[start:end], dtype), xp.astype(wj[start:end], dtype)
+
+
+def _transform_to_limits(xjc, wj, a, b, xp):
+    # Transform integral according to user-specified limits. This is just
+    # math that follows from the fact that the standard limits are (-1, 1).
+    # Note: If we had stored xj instead of xjc, we would have
+    # xj = alpha * xj + beta, where beta = (a + b)/2
+    alpha = (b - a) / 2
+    xj = xp.concat((-alpha * xjc + b, alpha * xjc + a), axis=-1)
+    wj = wj*alpha  # arguments get broadcasted, so we can't use *=
+    wj = xp.concat((wj, wj), axis=-1)
+
+    # Points at the boundaries can be generated due to finite precision
+    # arithmetic, but these function values aren't supposed to be included in
+    # the Euler-Maclaurin sum. Ideally we wouldn't evaluate the function at
+    # these points; however, we can't easily filter out points since this
+    # function is vectorized. Instead, zero the weights.
+    # Note: values may have complex dtype, but have zero imaginary part
+    xj_real, a_real, b_real = xp.real(xj), xp.real(a), xp.real(b)
+    invalid = (xj_real <= a_real) | (xj_real >= b_real)
+    wj[invalid] = 0
+    return xj, wj
+
+
+def _euler_maclaurin_sum(fj, work, xp):
+    # Perform the Euler-Maclaurin Sum, [1] Section 4
+
+    # The error estimate needs to know the magnitude of the last term
+    # omitted from the Euler-Maclaurin sum. This is a bit involved because
+    # it may have been computed at a previous level. I sure hope it's worth
+    # all the trouble.
+    xr0, fr0, wr0 = work.xr0, work.fr0, work.wr0
+    xl0, fl0, wl0 = work.xl0, work.fl0, work.wl0
+
+    # It is much more convenient to work with the transposes of our work
+    # variables here.
+    xj, fj, wj = work.xj.T, fj.T, work.wj.T
+    n_x, n_active = xj.shape  # number of abscissae, number of active elements
+
+    # We'll work with the left and right sides separately
+    xr, xl = xp_copy(xp.reshape(xj, (2, n_x // 2, n_active)))  # this gets modified
+    fr, fl = xp.reshape(fj, (2, n_x // 2, n_active))
+    wr, wl = xp.reshape(wj, (2, n_x // 2, n_active))
+
+    invalid_r = ~xp.isfinite(fr) | (wr == 0)
+    invalid_l = ~xp.isfinite(fl) | (wl == 0)
+
+    # integer index of the maximum abscissa at this level
+    xr[invalid_r] = -xp.inf
+    ir = xp.argmax(xp.real(xr), axis=0, keepdims=True)
+    # abscissa, function value, and weight at this index
+    ### Not Array API Compatible... yet ###
+    xr_max = xp.take_along_axis(xr, ir, axis=0)[0]
+    fr_max = xp.take_along_axis(fr, ir, axis=0)[0]
+    wr_max = xp.take_along_axis(wr, ir, axis=0)[0]
+    # boolean indices at which maximum abscissa at this level exceeds
+    # the incumbent maximum abscissa (from all previous levels)
+    # note: abscissa may have complex dtype, but will have zero imaginary part
+    j = xp.real(xr_max) > xp.real(xr0)
+    # Update record of the incumbent abscissa, function value, and weight
+    xr0[j] = xr_max[j]
+    fr0[j] = fr_max[j]
+    wr0[j] = wr_max[j]
+
+    # integer index of the minimum abscissa at this level
+    xl[invalid_l] = xp.inf
+    il = xp.argmin(xp.real(xl), axis=0, keepdims=True)
+    # abscissa, function value, and weight at this index
+    xl_min = xp.take_along_axis(xl, il, axis=0)[0]
+    fl_min = xp.take_along_axis(fl, il, axis=0)[0]
+    wl_min = xp.take_along_axis(wl, il, axis=0)[0]
+    # boolean indices at which minimum abscissa at this level is less than
+    # the incumbent minimum abscissa (from all previous levels)
+    # note: abscissa may have complex dtype, but will have zero imaginary part
+    j = xp.real(xl_min) < xp.real(xl0)
+    # Update record of the incumbent abscissa, function value, and weight
+    xl0[j] = xl_min[j]
+    fl0[j] = fl_min[j]
+    wl0[j] = wl_min[j]
+    fj = fj.T
+
+    # Compute the error estimate `d4` - the magnitude of the leftmost or
+    # rightmost term, whichever is greater.
+    flwl0 = fl0 + xp.log(wl0) if work.log else fl0 * wl0  # leftmost term
+    frwr0 = fr0 + xp.log(wr0) if work.log else fr0 * wr0  # rightmost term
+    magnitude = xp.real if work.log else xp.abs
+    work.d4 = xp.maximum(magnitude(flwl0), magnitude(frwr0))
+
+    # There are two approaches to dealing with function values that are
+    # numerically infinite due to approaching a singularity - zero them, or
+    # replace them with the function value at the nearest non-infinite point.
+    # [3] pg. 22 suggests the latter, so let's do that given that we have the
+    # information.
+    fr0b = xp.broadcast_to(fr0[xp.newaxis, :], fr.shape)
+    fl0b = xp.broadcast_to(fl0[xp.newaxis, :], fl.shape)
+    fr[invalid_r] = fr0b[invalid_r]
+    fl[invalid_l] = fl0b[invalid_l]
+
+    # When wj is zero, log emits a warning
+    # with np.errstate(divide='ignore'):
+    fjwj = fj + xp.log(work.wj) if work.log else fj * work.wj
+
+    # update integral estimate
+    Sn = (special.logsumexp(fjwj + xp.log(work.h), axis=-1) if work.log
+          else xp.sum(fjwj, axis=-1) * work.h)
+
+    work.xr0, work.fr0, work.wr0 = xr0, fr0, wr0
+    work.xl0, work.fl0, work.wl0 = xl0, fl0, wl0
+
+    return fjwj, Sn
+
+
+def _estimate_error(work, xp):
+    # Estimate the error according to [1] Section 5
+
+    if work.n == 0 or work.nit == 0:
+        # The paper says to use "one" as the error before it can be calculated.
+        # NaN seems to be more appropriate.
+        nan = xp.full_like(work.Sn, xp.nan)
+        return nan, nan
+
+    indices = work.pair_cache.indices
+
+    n_active = work.Sn.shape[0]  # number of active elements
+    axis_kwargs = dict(axis=-1, keepdims=True)
+
+    # With a jump start (starting at level higher than 0), we haven't
+    # explicitly calculated the integral estimate at lower levels. But we have
+    # all the function value-weight products, so we can compute the
+    # lower-level estimates.
+    if work.Sk.shape[-1] == 0:
+        h = 2 * work.h  # step size at this level
+        n_x = indices[work.n]  # number of abscissa up to this level
+        # The right and left fjwj terms from all levels are concatenated along
+        # the last axis. Get out only the terms up to this level.
+        fjwj_rl = xp.reshape(work.fjwj, (n_active, 2, -1))
+        fjwj = xp.reshape(fjwj_rl[:, :, :n_x], (n_active, 2*n_x))
+        # Compute the Euler-Maclaurin sum at this level
+        Snm1 = (special.logsumexp(fjwj, **axis_kwargs) + xp.log(h) if work.log
+                else xp.sum(fjwj, **axis_kwargs) * h)
+        work.Sk = xp.concat((Snm1, work.Sk), axis=-1)
+
+    if work.n == 1:
+        nan = xp.full_like(work.Sn, xp.nan)
+        return nan, nan
+
+    # The paper says not to calculate the error for n<=2, but it's not clear
+    # about whether it starts at level 0 or level 1. We start at level 0, so
+    # why not compute the error beginning in level 2?
+    if work.Sk.shape[-1] < 2:
+        h = 4 * work.h  # step size at this level
+        n_x = indices[work.n-1]  # number of abscissa up to this level
+        # The right and left fjwj terms from all levels are concatenated along
+        # the last axis. Get out only the terms up to this level.
+        fjwj_rl = xp.reshape(work.fjwj, (work.Sn.shape[0], 2, -1))
+        fjwj = xp.reshape(fjwj_rl[..., :n_x], (n_active, 2*n_x))
+        # Compute the Euler-Maclaurin sum at this level
+        Snm2 = (special.logsumexp(fjwj, **axis_kwargs) + xp.log(h) if work.log
+                else xp.sum(fjwj, **axis_kwargs) * h)
+        work.Sk = xp.concat((Snm2, work.Sk), axis=-1)
+
+    Snm2 = work.Sk[..., -2]
+    Snm1 = work.Sk[..., -1]
+
+    e1 = xp.asarray(work.eps)[()]
+
+    if work.log:
+        log_e1 = xp.log(e1)
+        # Currently, only real integrals are supported in log-scale. All
+        # complex values have imaginary part in increments of pi*j, which just
+        # carries sign information of the original integral, so use of
+        # `xp.real` here is equivalent to absolute value in real scale.
+        d1 = xp.real(special.logsumexp(xp.stack([work.Sn, Snm1 + work.pi*1j]), axis=0))
+        d2 = xp.real(special.logsumexp(xp.stack([work.Sn, Snm2 + work.pi*1j]), axis=0))
+        d3 = log_e1 + xp.max(xp.real(work.fjwj), axis=-1)
+        d4 = work.d4
+        d5 = log_e1 + xp.real(work.Sn)
+        temp = xp.where(d1 > -xp.inf, d1 ** 2 / d2, -xp.inf)
+        ds = xp.stack([temp, 2 * d1, d3, d4])
+        aerr = xp.clip(xp.max(ds, axis=0), d5, d1)
+        rerr = aerr - xp.real(work.Sn)
+    else:
+        # Note: explicit computation of log10 of each of these is unnecessary.
+        d1 = xp.abs(work.Sn - Snm1)
+        d2 = xp.abs(work.Sn - Snm2)
+        d3 = e1 * xp.max(xp.abs(work.fjwj), axis=-1)
+        d4 = work.d4
+        d5 = e1 * xp.abs(work.Sn)
+        temp = xp.where(d1 > 0, d1**(xp.log(d1)/xp.log(d2)), 0)
+        ds = xp.stack([temp, d1**2, d3, d4])
+        aerr = xp.clip(xp.max(ds, axis=0), d5, d1)
+        rerr = aerr/xp.abs(work.Sn)
+
+    return rerr, aerr
+
+
+def _transform_integrals(a, b, xp):
+    # Transform integrals to a form with finite a <= b
+    # For b == a (even infinite), we ensure that the limits remain equal
+    # For b < a, we reverse the limits and will multiply the final result by -1
+    # For infinite limit on the right, we use the substitution x = 1/t - 1 + a
+    # For infinite limit on the left, we substitute x = -x and treat as above
+    # For infinite limits, we substitute x = t / (1-t**2)
+    ab_same = (a == b)
+    a[ab_same], b[ab_same] = 1, 1
+
+    # `a, b` may have complex dtype but have zero imaginary part
+    negative = xp.real(b) < xp.real(a)
+    a[negative], b[negative] = b[negative], a[negative]
+
+    abinf = xp.isinf(a) & xp.isinf(b)
+    a[abinf], b[abinf] = -1, 1
+
+    ainf = xp.isinf(a)
+    a[ainf], b[ainf] = -b[ainf], -a[ainf]
+
+    binf = xp.isinf(b)
+    a0 = xp_copy(a)
+    a[binf], b[binf] = 0, 1
+
+    return a, b, a0, negative, abinf, ainf, binf
+
+
+def _tanhsinh_iv(f, a, b, log, maxfun, maxlevel, minlevel,
+                 atol, rtol, args, kwargs, preserve_shape, callback):
+    # Input validation and standardization
+
+    xp = array_namespace(a, b)
+    a, b = xp_promote(a, b, broadcast=True, force_floating=True, xp=xp)
+
+    message = '`f` must be callable.'
+    if not callable(f):
+        raise ValueError(message)
+
+    message = 'All elements of `a` and `b` must be real numbers.'
+    if (xp.isdtype(a.dtype, 'complex floating')
+            or xp.isdtype(b.dtype, 'complex floating')):
+        raise ValueError(message)
+
+    message = '`log` must be True or False.'
+    if log not in {True, False}:
+        raise ValueError(message)
+    log = bool(log)
+
+    if atol is None:
+        atol = -xp.inf if log else 0
+
+    rtol_temp = rtol if rtol is not None else 0.
+
+    # using NumPy for convenience here; these are just floats, not arrays
+    params = np.asarray([atol, rtol_temp, 0.])
+    message = "`atol` and `rtol` must be real numbers."
+    if not np.issubdtype(params.dtype, np.floating):
+        raise ValueError(message)
+
+    if log:
+        message = '`atol` and `rtol` may not be positive infinity.'
+        if np.any(np.isposinf(params)):
+            raise ValueError(message)
+    else:
+        message = '`atol` and `rtol` must be non-negative and finite.'
+        if np.any(params < 0) or np.any(np.isinf(params)):
+            raise ValueError(message)
+    atol = params[0]
+    rtol = rtol if rtol is None else params[1]
+
+    BIGINT = float(2**62)
+    if maxfun is None and maxlevel is None:
+        maxlevel = 10
+
+    maxfun = BIGINT if maxfun is None else maxfun
+    maxlevel = BIGINT if maxlevel is None else maxlevel
+
+    message = '`maxfun`, `maxlevel`, and `minlevel` must be integers.'
+    params = np.asarray([maxfun, maxlevel, minlevel])
+    if not (np.issubdtype(params.dtype, np.number)
+            and np.all(np.isreal(params))
+            and np.all(params.astype(np.int64) == params)):
+        raise ValueError(message)
+    message = '`maxfun`, `maxlevel`, and `minlevel` must be non-negative.'
+    if np.any(params < 0):
+        raise ValueError(message)
+    maxfun, maxlevel, minlevel = params.astype(np.int64)
+    minlevel = min(minlevel, maxlevel)
+
+    if not np.iterable(args):
+        args = (args,)
+
+    message = '`preserve_shape` must be True or False.'
+    if preserve_shape not in {True, False}:
+        raise ValueError(message)
+
+    if callback is not None and not callable(callback):
+        raise ValueError('`callback` must be callable.')
+
+    return (f, a, b, log, maxfun, maxlevel, minlevel,
+            atol, rtol, args, kwargs, preserve_shape, callback, xp)
+
+
+def _nsum_iv(f, a, b, step, args, kwargs, log, maxterms, tolerances):
+    # Input validation and standardization
+
+    xp = array_namespace(a, b, step)
+    a, b, step = xp_promote(a, b, step, broadcast=True, force_floating=True, xp=xp)
+
+    message = '`f` must be callable.'
+    if not callable(f):
+        raise ValueError(message)
+
+    message = 'All elements of `a`, `b`, and `step` must be real numbers.'
+    if not xp.isdtype(a.dtype, ('integral', 'real floating')):
+        raise ValueError(message)
+
+    valid_b = b >= a  # NaNs will be False
+    valid_step = xp.isfinite(step) & (step > 0)
+    valid_abstep = valid_b & valid_step
+
+    message = '`log` must be True or False.'
+    if log not in {True, False}:
+        raise ValueError(message)
+
+    tolerances = {} if tolerances is None else tolerances
+
+    atol = tolerances.get('atol', None)
+    if atol is None:
+        atol = -xp.inf if log else 0
+
+    rtol = tolerances.get('rtol', None)
+    rtol_temp = rtol if rtol is not None else 0.
+
+    # using NumPy for convenience here; these are just floats, not arrays
+    params = np.asarray([atol, rtol_temp, 0.])
+    message = "`atol` and `rtol` must be real numbers."
+    if not np.issubdtype(params.dtype, np.floating):
+        raise ValueError(message)
+
+    if log:
+        message = '`atol`, `rtol` may not be positive infinity or NaN.'
+        if np.any(np.isposinf(params) | np.isnan(params)):
+            raise ValueError(message)
+    else:
+        message = '`atol`, and `rtol` must be non-negative and finite.'
+        if np.any((params < 0) | (~np.isfinite(params))):
+            raise ValueError(message)
+    atol = params[0]
+    rtol = rtol if rtol is None else params[1]
+
+    maxterms_int = int(maxterms)
+    if maxterms_int != maxterms or maxterms < 0:
+        message = "`maxterms` must be a non-negative integer."
+        raise ValueError(message)
+
+    if not np.iterable(args):
+        args = (args,)
+
+    return f, a, b, step, valid_abstep, args, kwargs, log, maxterms_int, atol, rtol, xp
+
+
+@xp_capabilities(skip_backends=[('torch', 'data-apis/array-api-compat#271'),
+                                ('array_api_strict', 'No fancy indexing.'),
+                                ('jax.numpy', 'No mutation.'),
+                                ('dask.array',
+                                 'Data-dependent shapes in boolean index assignment')])
+def nsum(f, a, b, *, step=1, args=(), kwargs=None,
+         log=False, maxterms=int(2**20), tolerances=None):
+    r"""Evaluate a convergent finite or infinite series.
+
+    For finite `a` and `b`, this evaluates::
+
+        f(a + np.arange(n)*step).sum()
+
+    where ``n = int((b - a) / step) + 1``, where `f` is smooth, positive, and
+    unimodal. The number of terms in the sum may be very large or infinite,
+    in which case a partial sum is evaluated directly and the remainder is
+    approximated using integration.
+
+    Parameters
+    ----------
+    f : callable
+        The function that evaluates terms to be summed. The signature must be::
+
+            f(x: ndarray, *args) -> ndarray
+
+        where each element of ``x`` is a finite real and ``args`` is a tuple,
+        which may contain an arbitrary number of arrays that are broadcastable
+        with ``x``.
+
+        `f` must be an elementwise function: each element ``f(x)[i]``
+        must equal ``f(x[i])`` for all indices ``i``. It must not mutate the
+        array ``x`` or the arrays in ``args``, and it must return NaN where
+        the argument is NaN.
+
+        `f` must represent a smooth, positive, unimodal function of `x` defined at
+        *all reals* between `a` and `b`.
+    a, b : float array_like
+        Real lower and upper limits of summed terms. Must be broadcastable.
+        Each element of `a` must be less than the corresponding element in `b`.
+    step : float array_like
+        Finite, positive, real step between summed terms. Must be broadcastable
+        with `a` and `b`. Note that the number of terms included in the sum will
+        be ``floor((b - a) / step)`` + 1; adjust `b` accordingly to ensure
+        that ``f(b)`` is included if intended.
+    args : tuple of array_like, optional
+        Additional positional arguments to be passed to `f`. Must be arrays
+        broadcastable with `a`, `b`, and `step`. If the callable to be summed
+        requires arguments that are not broadcastable with `a`, `b`, and `step`,
+        wrap that callable with `f` such that `f` accepts only `x` and
+        broadcastable ``*args``. See Examples.
+    kwargs : dict of str:array_like, optional
+        Additional keyword arguments to be passed to `f`. See `args`.
+    log : bool, default: False
+        Setting to True indicates that `f` returns the log of the terms
+        and that `atol` and `rtol` are expressed as the logs of the absolute
+        and relative errors. In this case, the result object will contain the
+        log of the sum and error. This is useful for summands for which
+        numerical underflow or overflow would lead to inaccuracies.
+    maxterms : int, default: 2**20
+        The maximum number of terms to evaluate for direct summation.
+        Additional function evaluations may be performed for input
+        validation and integral evaluation.
+    tolerances : dict, optional
+        Dictionary with recognized keys ``atol`` for absolute termination tolerance
+        (default: 0) and ``rtol`` for relative termination tolerance (default:
+        ``eps**0.5``, where ``eps`` is the precision of the result dtype), respectively.
+        Values must be non-negative and finite if `log` is False, and must be expressed
+        as the log of a non-negative and finite number if `log` is True.
+
+    Returns
+    -------
+    res : _RichResult
+        An object similar to an instance of `scipy.optimize.OptimizeResult` with the
+        following attributes. (The descriptions are written as though the values will
+        be scalars; however, if `f` returns an array, the outputs will be
+        arrays of the same shape.)
+
+        success : bool
+            ``True`` when the algorithm terminated successfully (status ``0``);
+            ``False`` otherwise.
+        status : int array
+            An integer representing the exit status of the algorithm.
+
+            - ``0`` : The algorithm converged to the specified tolerances.
+            - ``-1`` : Element(s) of `a`, `b`, or `step` are invalid
+            - ``-2`` : Numerical integration reached its iteration limit;
+              the sum may be divergent.
+            - ``-3`` : A non-finite value was encountered.
+            - ``-4`` : The magnitude of the last term of the partial sum exceeds
+              the tolerances, so the error estimate exceeds the tolerances.
+              Consider increasing `maxterms` or loosening `tolerances`.
+              Alternatively, the callable may not be unimodal, or the limits of
+              summation may be too far from the function maximum. Consider
+              increasing `maxterms` or breaking the sum into pieces.
+
+        sum : float array
+            An estimate of the sum.
+        error : float array
+            An estimate of the absolute error, assuming all terms are non-negative,
+            the function is computed exactly, and direct summation is accurate to
+            the precision of the result dtype.
+        nfev : int array
+            The number of points at which `f` was evaluated.
+
+    See Also
+    --------
+    mpmath.nsum
+
+    Notes
+    -----
+    The method implemented for infinite summation is related to the integral
+    test for convergence of an infinite series: assuming `step` size 1 for
+    simplicity of exposition, the sum of a monotone decreasing function is bounded by
+
+    .. math::
+
+        \int_u^\infty f(x) dx \leq \sum_{k=u}^\infty f(k) \leq \int_u^\infty f(x) dx + f(u)
+
+    Let :math:`a` represent  `a`, :math:`n` represent `maxterms`, :math:`\epsilon_a`
+    represent `atol`, and :math:`\epsilon_r` represent `rtol`.
+    The implementation first evaluates the integral :math:`S_l=\int_a^\infty f(x) dx`
+    as a lower bound of the infinite sum. Then, it seeks a value :math:`c > a` such
+    that :math:`f(c) < \epsilon_a + S_l \epsilon_r`, if it exists; otherwise,
+    let :math:`c = a + n`. Then the infinite sum is approximated as
+
+    .. math::
+
+        \sum_{k=a}^{c-1} f(k) + \int_c^\infty f(x) dx + f(c)/2
+
+    and the reported error is :math:`f(c)/2` plus the error estimate of
+    numerical integration. Note that the integral approximations may require
+    evaluation of the function at points besides those that appear in the sum,
+    so `f` must be a continuous and monotonically decreasing function defined
+    for all reals within the integration interval. However, due to the nature
+    of the integral approximation, the shape of the function between points
+    that appear in the sum has little effect. If there is not a natural
+    extension of the function to all reals, consider using linear interpolation,
+    which is easy to evaluate and preserves monotonicity.
+
+    The approach described above is generalized for non-unit
+    `step` and finite `b` that is too large for direct evaluation of the sum,
+    i.e. ``b - a + 1 > maxterms``. It is further generalized to unimodal
+    functions by directly summing terms surrounding the maximum.
+    This strategy may fail:
+
+    - If the left limit is finite and the maximum is far from it.
+    - If the right limit is finite and the maximum is far from it.
+    - If both limits are finite and the maximum is far from the origin.
+
+    In these cases, accuracy may be poor, and `nsum` may return status code ``4``.
+
+    Although the callable `f` must be non-negative and unimodal,
+    `nsum` can be used to evaluate more general forms of series. For instance, to
+    evaluate an alternating series, pass a callable that returns the difference
+    between pairs of adjacent terms, and adjust `step` accordingly. See Examples.
+
+    References
+    ----------
+    .. [1] Wikipedia. "Integral test for convergence."
+           https://en.wikipedia.org/wiki/Integral_test_for_convergence
+
+    Examples
+    --------
+    Compute the infinite sum of the reciprocals of squared integers.
+
+    >>> import numpy as np
+    >>> from scipy.integrate import nsum
+    >>> res = nsum(lambda k: 1/k**2, 1, np.inf)
+    >>> ref = np.pi**2/6  # true value
+    >>> res.error  # estimated error
+    np.float64(7.448762306416137e-09)
+    >>> (res.sum - ref)/ref  # true error
+    np.float64(-1.839871898894426e-13)
+    >>> res.nfev  # number of points at which callable was evaluated
+    np.int32(8561)
+
+    Compute the infinite sums of the reciprocals of integers raised to powers ``p``,
+    where ``p`` is an array.
+
+    >>> from scipy import special
+    >>> p = np.arange(3, 10)
+    >>> res = nsum(lambda k, p: 1/k**p, 1, np.inf, maxterms=1e3, args=(p,))
+    >>> ref = special.zeta(p, 1)
+    >>> np.allclose(res.sum, ref)
+    True
+
+    Evaluate the alternating harmonic series.
+
+    >>> res = nsum(lambda x: 1/x - 1/(x+1), 1, np.inf, step=2)
+    >>> res.sum, res.sum - np.log(2)  # result, difference vs analytical sum
+    (np.float64(0.6931471805598691), np.float64(-7.616129948928574e-14))
+
+    """ # noqa: E501
+    # Potential future work:
+    # - improve error estimate of `_direct` sum
+    # - add other methods for convergence acceleration (Richardson, epsilon)
+    # - support negative monotone increasing functions?
+    # - b < a / negative step?
+    # - complex-valued function?
+    # - check for violations of monotonicity?
+
+    # Function-specific input validation / standardization
+    tmp = _nsum_iv(f, a, b, step, args, kwargs, log, maxterms, tolerances)
+    f, a, b, step, valid_abstep, args, kwargs, log, maxterms, atol, rtol, xp = tmp
+
+    # Additional elementwise algorithm input validation / standardization
+    tmp = eim._initialize(f, (a,), args, kwargs=kwargs, complex_ok=False, xp=xp)
+    f, xs, fs, args, shape, dtype, xp = tmp
+
+    # Finish preparing `a`, `b`, and `step` arrays
+    a = xs[0]
+    b = xp.astype(xp_ravel(xp.broadcast_to(b, shape)), dtype)
+    step = xp.astype(xp_ravel(xp.broadcast_to(step, shape)), dtype)
+    valid_abstep = xp_ravel(xp.broadcast_to(valid_abstep, shape))
+    nterms = xp.floor((b - a) / step)
+    finite_terms = xp.isfinite(nterms)
+    b[finite_terms] = a[finite_terms] + nterms[finite_terms]*step[finite_terms]
+
+    # Define constants
+    eps = xp.finfo(dtype).eps
+    zero = xp.asarray(-xp.inf if log else 0, dtype=dtype)[()]
+    if rtol is None:
+        rtol = 0.5*math.log(eps) if log else eps**0.5
+    constants = (dtype, log, eps, zero, rtol, atol, maxterms)
+
+    # Prepare result arrays
+    S = xp.empty_like(a)
+    E = xp.empty_like(a)
+    status = xp.zeros(len(a), dtype=xp.int32)
+    nfev = xp.ones(len(a), dtype=xp.int32)  # one function evaluation above
+
+    # Branch for direct sum evaluation / integral approximation / invalid input
+    i0 = ~valid_abstep                     # invalid
+    i0b = b < a                            # zero
+    i1 = (nterms + 1 <= maxterms) & ~i0    # direct sum evaluation
+    i2 = xp.isfinite(a) & ~i1 & ~i0        # infinite sum to the right
+    i3 = xp.isfinite(b) & ~i2 & ~i1 & ~i0  # infinite sum to the left
+    i4 = ~i3 & ~i2 & ~i1 & ~i0             # infinite sum on both sides
+
+    if xp.any(i0):
+        S[i0], E[i0] = xp.nan, xp.nan
+        status[i0] = -1
+
+        S[i0b], E[i0b] = zero, zero
+        status[i0b] = 0
+
+    if xp.any(i1):
+        args_direct = [arg[i1] for arg in args]
+        tmp = _direct(f, a[i1], b[i1], step[i1], args_direct, constants, xp)
+        S[i1], E[i1] = tmp[:-1]
+        nfev[i1] += tmp[-1]
+        status[i1] = -3 * xp.asarray(~xp.isfinite(S[i1]), dtype=xp.int32)
+
+    if xp.any(i2):
+        args_indirect = [arg[i2] for arg in args]
+        tmp = _integral_bound(f, a[i2], b[i2], step[i2],
+                              args_indirect, constants, xp)
+        S[i2], E[i2], status[i2] = tmp[:-1]
+        nfev[i2] += tmp[-1]
+
+    if xp.any(i3):
+        args_indirect = [arg[i3] for arg in args]
+        def _f(x, *args): return f(-x, *args)
+        tmp = _integral_bound(_f, -b[i3], -a[i3], step[i3],
+                              args_indirect, constants, xp)
+        S[i3], E[i3], status[i3] = tmp[:-1]
+        nfev[i3] += tmp[-1]
+
+    if xp.any(i4):
+        args_indirect = [arg[i4] for arg in args]
+
+        # There are two obvious high-level strategies:
+        # - Do two separate half-infinite sums (e.g. from -inf to 0 and 1 to inf)
+        # - Make a callable that returns f(x) + f(-x) and do a single half-infinite sum
+        # I thought the latter would have about half the overhead, so I went that way.
+        # Then there are two ways of ensuring that f(0) doesn't get counted twice.
+        # - Evaluate the sum from 1 to inf and add f(0)
+        # - Evaluate the sum from 0 to inf and subtract f(0)
+        # - Evaluate the sum from 0 to inf, but apply a weight of 0.5 when `x = 0`
+        # The last option has more overhead, but is simpler to implement correctly
+        # (especially getting the status message right)
+        if log:
+            def _f(x, *args):
+                log_factor = xp.where(x==0, math.log(0.5), 0)
+                out = xp.stack([f(x, *args), f(-x, *args)], axis=0)
+                return special.logsumexp(out, axis=0) + log_factor
+
+        else:
+            def _f(x, *args):
+                factor = xp.where(x==0, 0.5, 1)
+                return (f(x, *args) + f(-x, *args)) * factor
+
+        zero = xp.zeros_like(a[i4])
+        tmp = _integral_bound(_f, zero, b[i4], step[i4], args_indirect, constants, xp)
+        S[i4], E[i4], status[i4] = tmp[:-1]
+        nfev[i4] += 2*tmp[-1]
+
+    # Return results
+    S, E = S.reshape(shape)[()], E.reshape(shape)[()]
+    status, nfev = status.reshape(shape)[()], nfev.reshape(shape)[()]
+    return _RichResult(sum=S, error=E, status=status, success=status == 0,
+                       nfev=nfev)
+
+
+def _direct(f, a, b, step, args, constants, xp, inclusive=True):
+    # Directly evaluate the sum.
+
+    # When used in the context of distributions, `args` would contain the
+    # distribution parameters. We have broadcasted for simplicity, but we could
+    # reduce function evaluations when distribution parameters are the same but
+    # sum limits differ. Roughly:
+    # - compute the function at all points between min(a) and max(b),
+    # - compute the cumulative sum,
+    # - take the difference between elements of the cumulative sum
+    #   corresponding with b and a.
+    # This is left to future enhancement
+
+    dtype, log, eps, zero, _, _, _ = constants
+
+    # To allow computation in a single vectorized call, find the maximum number
+    # of points (over all slices) at which the function needs to be evaluated.
+    # Note: if `inclusive` is `True`, then we want `1` more term in the sum.
+    # I didn't think it was great style to use `True` as `1` in Python, so I
+    # explicitly converted it to an `int` before using it.
+    inclusive_adjustment = int(inclusive)
+    steps = xp.round((b - a) / step) + inclusive_adjustment
+    # Equivalently, steps = xp.round((b - a) / step) + inclusive
+    max_steps = int(xp.max(steps))
+
+    # In each slice, the function will be evaluated at the same number of points,
+    # but excessive points (those beyond the right sum limit `b`) are replaced
+    # with NaN to (potentially) reduce the time of these unnecessary calculations.
+    # Use a new last axis for these calculations for consistency with other
+    # elementwise algorithms.
+    a2, b2, step2 = a[:, xp.newaxis], b[:, xp.newaxis], step[:, xp.newaxis]
+    args2 = [arg[:, xp.newaxis] for arg in args]
+    ks = a2 + xp.arange(max_steps, dtype=dtype) * step2
+    i_nan = ks >= (b2 + inclusive_adjustment*step2/2)
+    ks[i_nan] = xp.nan
+    fs = f(ks, *args2)
+
+    # The function evaluated at NaN is NaN, and NaNs are zeroed in the sum.
+    # In some cases it may be faster to loop over slices than to vectorize
+    # like this. This is an optimization that can be added later.
+    fs[i_nan] = zero
+    nfev = max_steps - i_nan.sum(axis=-1)
+    S = special.logsumexp(fs, axis=-1) if log else xp.sum(fs, axis=-1)
+    # Rough, non-conservative error estimate. See gh-19667 for improvement ideas.
+    E = xp.real(S) + math.log(eps) if log else eps * abs(S)
+    return S, E, nfev
+
+
+def _integral_bound(f, a, b, step, args, constants, xp):
+    # Estimate the sum with integral approximation
+    dtype, log, _, _, rtol, atol, maxterms = constants
+    log2 = xp.asarray(math.log(2), dtype=dtype)
+
+    # Get a lower bound on the sum and compute effective absolute tolerance
+    lb = tanhsinh(f, a, b, args=args, atol=atol, rtol=rtol, log=log)
+    tol = xp.broadcast_to(xp.asarray(atol), lb.integral.shape)
+    if log:
+        tol = special.logsumexp(xp.stack((tol, rtol + lb.integral)), axis=0)
+    else:
+        tol = tol + rtol*lb.integral
+    i_skip = lb.status == -3  # avoid unnecessary f_evals if integral is divergent
+    tol[i_skip] = xp.nan
+    status = lb.status
+
+    # As in `_direct`, we'll need a temporary new axis for points
+    # at which to evaluate the function. Append axis at the end for
+    # consistency with other elementwise algorithms.
+    a2 = a[..., xp.newaxis]
+    step2 = step[..., xp.newaxis]
+    args2 = [arg[..., xp.newaxis] for arg in args]
+
+    # Find the location of a term that is less than the tolerance (if possible)
+    log2maxterms = math.floor(math.log2(maxterms)) if maxterms else 0
+    n_steps = xp.concat((2**xp.arange(0, log2maxterms), xp.asarray([maxterms])))
+    n_steps = xp.astype(n_steps, dtype)
+    nfev = len(n_steps) * 2
+    ks = a2 + n_steps * step2
+    fks = f(ks, *args2)
+    fksp1 = f(ks + step2, *args2)  # check that the function is decreasing
+    fk_insufficient = (fks > tol[:, xp.newaxis]) | (fksp1 > fks)
+    n_fk_insufficient = xp.sum(fk_insufficient, axis=-1)
+    nt = xp.minimum(n_fk_insufficient, n_steps.shape[-1]-1)
+    n_steps = n_steps[nt]
+
+    # If `maxterms` is insufficient (i.e. either the magnitude of the last term of the
+    # partial sum exceeds the tolerance or the function is not decreasing), finish the
+    # calculation, but report nonzero status. (Improvement: separate the status codes
+    # for these two cases.)
+    i_fk_insufficient = (n_fk_insufficient == nfev//2)
+
+    # Directly evaluate the sum up to this term
+    k = a + n_steps * step
+    left, left_error, left_nfev = _direct(f, a, k, step, args,
+                                          constants, xp, inclusive=False)
+    left_is_pos_inf = xp.isinf(left) & (left > 0)
+    i_skip |= left_is_pos_inf  # if sum is infinite, no sense in continuing
+    status[left_is_pos_inf] = -3
+    k[i_skip] = xp.nan
+
+    # Use integration to estimate the remaining sum
+    # Possible optimization for future work: if there were no terms less than
+    # the tolerance, there is no need to compute the integral to better accuracy.
+    # Something like:
+    # atol = xp.maximum(atol, xp.minimum(fk/2 - fb/2))
+    # rtol = xp.maximum(rtol, xp.minimum((fk/2 - fb/2)/left))
+    # where `fk`/`fb` are currently calculated below.
+    right = tanhsinh(f, k, b, args=args, atol=atol, rtol=rtol, log=log)
+
+    # Calculate the full estimate and error from the pieces
+    fk = fks[xp.arange(len(fks)), nt]
+
+    # fb = f(b, *args), but some functions return NaN at infinity.
+    # instead of 0 like they must (for the sum to be convergent).
+    fb = xp.full_like(fk, -xp.inf) if log else xp.zeros_like(fk)
+    i = xp.isfinite(b)
+    if xp.any(i):  # better not call `f` with empty arrays
+        fb[i] = f(b[i], *[arg[i] for arg in args])
+    nfev = nfev + xp.asarray(i, dtype=left_nfev.dtype)
+
+    if log:
+        log_step = xp.log(step)
+        S_terms = (left, right.integral - log_step, fk - log2, fb - log2)
+        S = special.logsumexp(xp.stack(S_terms), axis=0)
+        E_terms = (left_error, right.error - log_step, fk-log2, fb-log2+xp.pi*1j)
+        E = xp.real(special.logsumexp(xp.stack(E_terms), axis=0))
+    else:
+        S = left + right.integral/step + fk/2 + fb/2
+        E = left_error + right.error/step + fk/2 - fb/2
+    status[~i_skip] = right.status[~i_skip]
+
+    status[(status == 0) & i_fk_insufficient] = -4
+    return S, E, status, left_nfev + right.nfev + nfev + lb.nfev
diff --git a/.venv/lib/python3.12/site-packages/scipy/integrate/_test_multivariate.cpython-312-x86_64-linux-gnu.so b/.venv/lib/python3.12/site-packages/scipy/integrate/_test_multivariate.cpython-312-x86_64-linux-gnu.so
new file mode 100644
index 0000000000000000000000000000000000000000..a57d6e4488fcc45770bd37d1a20edfa8d9390f9c
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/scipy/integrate/_test_multivariate.cpython-312-x86_64-linux-gnu.so differ
diff --git a/.venv/lib/python3.12/site-packages/scipy/integrate/_vode.cpython-312-x86_64-linux-gnu.so b/.venv/lib/python3.12/site-packages/scipy/integrate/_vode.cpython-312-x86_64-linux-gnu.so
new file mode 100644
index 0000000000000000000000000000000000000000..b9f6cf1128be712fdff61cc3041e5d65034245c9
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/integrate/_vode.cpython-312-x86_64-linux-gnu.so
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:7e0573704c049ea2a9b6d82fa4a6b4214ddbf902d1c2d171770430da6a4b6c99
+size 120369
diff --git a/.venv/lib/python3.12/site-packages/scipy/integrate/dop.py b/.venv/lib/python3.12/site-packages/scipy/integrate/dop.py
new file mode 100644
index 0000000000000000000000000000000000000000..bf67a9a35b7d2959c2617aadc5638b577a45b9b5
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/integrate/dop.py
@@ -0,0 +1,15 @@
+# This file is not meant for public use and will be removed in SciPy v2.0.0.
+
+from scipy._lib.deprecation import _sub_module_deprecation
+
+__all__: list[str] = []
+
+
+def __dir__():
+    return __all__
+
+
+def __getattr__(name):
+    return _sub_module_deprecation(sub_package="integrate", module="dop",
+                                   private_modules=["_dop"], all=__all__,
+                                   attribute=name)
diff --git a/.venv/lib/python3.12/site-packages/scipy/integrate/lsoda.py b/.venv/lib/python3.12/site-packages/scipy/integrate/lsoda.py
new file mode 100644
index 0000000000000000000000000000000000000000..719e50411af4c148409ffae757bffe3e38006c81
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/integrate/lsoda.py
@@ -0,0 +1,15 @@
+# This file is not meant for public use and will be removed in SciPy v2.0.0.
+
+from scipy._lib.deprecation import _sub_module_deprecation
+
+__all__ = ['lsoda']  # noqa: F822
+
+
+def __dir__():
+    return __all__
+
+
+def __getattr__(name):
+    return _sub_module_deprecation(sub_package="integrate", module="lsoda",
+                                   private_modules=["_odepack"], all=__all__,
+                                   attribute=name)
diff --git a/.venv/lib/python3.12/site-packages/scipy/integrate/odepack.py b/.venv/lib/python3.12/site-packages/scipy/integrate/odepack.py
new file mode 100644
index 0000000000000000000000000000000000000000..7bb4c1a8c9be375df855abe6e1b30ca9711f2607
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/integrate/odepack.py
@@ -0,0 +1,17 @@
+# This file is not meant for public use and will be removed in SciPy v2.0.0.
+# Use the `scipy.integrate` namespace for importing the functions
+# included below.
+
+from scipy._lib.deprecation import _sub_module_deprecation
+
+__all__ = ['odeint', 'ODEintWarning']  # noqa: F822
+
+
+def __dir__():
+    return __all__
+
+
+def __getattr__(name):
+    return _sub_module_deprecation(sub_package="integrate", module="odepack",
+                                   private_modules=["_odepack_py"], all=__all__,
+                                   attribute=name)
diff --git a/.venv/lib/python3.12/site-packages/scipy/integrate/quadpack.py b/.venv/lib/python3.12/site-packages/scipy/integrate/quadpack.py
new file mode 100644
index 0000000000000000000000000000000000000000..144584988095c8855da8c34253c045f1a3940572
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/integrate/quadpack.py
@@ -0,0 +1,23 @@
+# This file is not meant for public use and will be removed in SciPy v2.0.0.
+# Use the `scipy.integrate` namespace for importing the functions
+# included below.
+
+from scipy._lib.deprecation import _sub_module_deprecation
+
+__all__ = [  # noqa: F822
+    "quad",
+    "dblquad",
+    "tplquad",
+    "nquad",
+    "IntegrationWarning",
+]
+
+
+def __dir__():
+    return __all__
+
+
+def __getattr__(name):
+    return _sub_module_deprecation(sub_package="integrate", module="quadpack",
+                                   private_modules=["_quadpack_py"], all=__all__,
+                                   attribute=name)
diff --git a/.venv/lib/python3.12/site-packages/scipy/integrate/tests/__init__.py b/.venv/lib/python3.12/site-packages/scipy/integrate/tests/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/.venv/lib/python3.12/site-packages/scipy/integrate/tests/test__quad_vec.py b/.venv/lib/python3.12/site-packages/scipy/integrate/tests/test__quad_vec.py
new file mode 100644
index 0000000000000000000000000000000000000000..5ce8616c13ec2e1bb2f171fb0b6f7a6a5369d15a
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/integrate/tests/test__quad_vec.py
@@ -0,0 +1,212 @@
+import pytest
+
+import numpy as np
+from numpy.testing import assert_allclose
+
+from scipy.integrate import quad_vec
+from scipy._lib._array_api import make_xp_test_case
+
+from multiprocessing.dummy import Pool
+
+
+quadrature_params = pytest.mark.parametrize(
+    'quadrature', [None, "gk15", "gk21", "trapezoid"])
+
+def _lorenzian(x):
+    return 1 / (1 + x**2)
+
+def _func_with_args(x, a):
+    return x * (x + a) * np.arange(3)
+
+
+@make_xp_test_case(quad_vec)
+class TestQuadVec:
+    @quadrature_params
+    def test_quad_vec_simple(self, quadrature):
+        n = np.arange(10)
+        def f(x):
+            return x ** n
+        for epsabs in [0.1, 1e-3, 1e-6]:
+            if quadrature == 'trapezoid' and epsabs < 1e-4:
+                # slow: skip
+                continue
+
+            kwargs = dict(epsabs=epsabs, quadrature=quadrature)
+
+            exact = 2**(n+1)/(n + 1)
+
+            res, err = quad_vec(f, 0, 2, norm='max', **kwargs)
+            assert_allclose(res, exact, rtol=0, atol=epsabs)
+
+            res, err = quad_vec(f, 0, 2, norm='2', **kwargs)
+            assert np.linalg.norm(res - exact) < epsabs
+
+            res, err = quad_vec(f, 0, 2, norm='max', points=(0.5, 1.0), **kwargs)
+            assert_allclose(res, exact, rtol=0, atol=epsabs)
+
+            res, err, *rest = quad_vec(f, 0, 2, norm='max',
+                                    epsrel=1e-8,
+                                    full_output=True,
+                                    limit=10000,
+                                    **kwargs)
+            assert_allclose(res, exact, rtol=0, atol=epsabs)
+
+
+    @quadrature_params
+    def test_quad_vec_simple_inf(self, quadrature):
+        def f(x):
+            return 1 / (1 + np.float64(x) ** 2)
+
+        for epsabs in [0.1, 1e-3, 1e-6]:
+            if quadrature == 'trapezoid' and epsabs < 1e-4:
+                # slow: skip
+                continue
+
+            kwargs = dict(norm='max', epsabs=epsabs, quadrature=quadrature)
+
+            res, err = quad_vec(f, 0, np.inf, **kwargs)
+            assert_allclose(res, np.pi/2, rtol=0, atol=max(epsabs, err))
+
+            res, err = quad_vec(f, 0, -np.inf, **kwargs)
+            assert_allclose(res, -np.pi/2, rtol=0, atol=max(epsabs, err))
+
+            res, err = quad_vec(f, -np.inf, 0, **kwargs)
+            assert_allclose(res, np.pi/2, rtol=0, atol=max(epsabs, err))
+
+            res, err = quad_vec(f, np.inf, 0, **kwargs)
+            assert_allclose(res, -np.pi/2, rtol=0, atol=max(epsabs, err))
+
+            res, err = quad_vec(f, -np.inf, np.inf, **kwargs)
+            assert_allclose(res, np.pi, rtol=0, atol=max(epsabs, err))
+
+            res, err = quad_vec(f, np.inf, -np.inf, **kwargs)
+            assert_allclose(res, -np.pi, rtol=0, atol=max(epsabs, err))
+
+            res, err = quad_vec(f, np.inf, np.inf, **kwargs)
+            assert_allclose(res, 0, rtol=0, atol=max(epsabs, err))
+
+            res, err = quad_vec(f, -np.inf, -np.inf, **kwargs)
+            assert_allclose(res, 0, rtol=0, atol=max(epsabs, err))
+
+            res, err = quad_vec(f, 0, np.inf, points=(1.0, 2.0), **kwargs)
+            assert_allclose(res, np.pi/2, rtol=0, atol=max(epsabs, err))
+
+        def f(x):
+            return np.sin(x + 2) / (1 + x ** 2)
+        exact = np.pi / np.e * np.sin(2)
+        epsabs = 1e-5
+
+        res, err, info = quad_vec(f, -np.inf, np.inf, limit=1000, norm='max',
+                                  epsabs=epsabs, quadrature=quadrature,
+                                  full_output=True)
+        assert info.status == 1
+        assert_allclose(res, exact, rtol=0, atol=max(epsabs, 1.5 * err))
+
+
+    def test_quad_vec_args(self):
+        def f(x, a):
+            return x * (x + a) * np.arange(3)
+        a = 2
+        exact = np.array([0, 4/3, 8/3])
+
+        res, err = quad_vec(f, 0, 1, args=(a,))
+        assert_allclose(res, exact, rtol=0, atol=1e-4)
+
+    @pytest.mark.fail_slow(10)
+    def test_quad_vec_pool(self):
+        f = _lorenzian
+        res, err = quad_vec(f, -np.inf, np.inf, norm='max', epsabs=1e-4, workers=4)
+        assert_allclose(res, np.pi, rtol=0, atol=1e-4)
+
+        with Pool(10) as pool:
+            def f(x):
+                return 1 / (1 + x ** 2)
+            res, _ = quad_vec(f, -np.inf, np.inf, norm='max', epsabs=1e-4,
+                              workers=pool.map)
+            assert_allclose(res, np.pi, rtol=0, atol=1e-4)
+
+    @pytest.mark.fail_slow(10)
+    @pytest.mark.parametrize('extra_args', [2, (2,)])
+    @pytest.mark.parametrize(
+        'workers',
+        [1, pytest.param(10, marks=pytest.mark.parallel_threads_limit(4))]
+    )
+    def test_quad_vec_pool_args(self, extra_args, workers):
+        f = _func_with_args
+        exact = np.array([0, 4/3, 8/3])
+
+        res, err = quad_vec(f, 0, 1, args=extra_args, workers=workers)
+        assert_allclose(res, exact, rtol=0, atol=1e-4)
+
+        with Pool(workers) as pool:
+            res, err = quad_vec(f, 0, 1, args=extra_args, workers=pool.map)
+            assert_allclose(res, exact, rtol=0, atol=1e-4)
+
+    @quadrature_params
+    def test_num_eval(self, quadrature):
+        def f(x):
+            count[0] += 1
+            return x**5
+
+        count = [0]
+        res = quad_vec(f, 0, 1, norm='max', full_output=True, quadrature=quadrature)
+        assert res[2].neval == count[0]
+
+    def test_info(self):
+        def f(x):
+            return np.ones((3, 2, 1))
+
+        res, err, info = quad_vec(f, 0, 1, norm='max', full_output=True)
+
+        assert info.success is True
+        assert info.status == 0
+        assert info.message == 'Target precision reached.'
+        assert info.neval > 0
+        assert info.intervals.shape[1] == 2
+        assert info.integrals.shape == (info.intervals.shape[0], 3, 2, 1)
+        assert info.errors.shape == (info.intervals.shape[0],)
+
+    def test_nan_inf(self):
+        def f_nan(x):
+            return np.nan
+
+        def f_inf(x):
+            return np.inf if x < 0.1 else 1/x
+
+        res, err, info = quad_vec(f_nan, 0, 1, full_output=True)
+        assert info.status == 3
+
+        res, err, info = quad_vec(f_inf, 0, 1, full_output=True)
+        assert info.status == 3
+
+
+    @pytest.mark.parametrize('a,b', [(0, 1), (0, np.inf), (np.inf, 0),
+                                    (-np.inf, np.inf), (np.inf, -np.inf)])
+    def test_points(self, a, b):
+        # Check that initial interval splitting is done according to
+        # `points`, by checking that consecutive sets of 15 point (for
+        # gk15) function evaluations lie between `points`
+
+        points = (0, 0.25, 0.5, 0.75, 1.0)
+        points += tuple(-x for x in points)
+
+        quadrature_points = 15
+        interval_sets = []
+        count = 0
+
+        def f(x):
+            nonlocal count
+
+            if count % quadrature_points == 0:
+                interval_sets.append(set())
+
+            count += 1
+            interval_sets[-1].add(float(x))
+            return 0.0
+
+        quad_vec(f, a, b, points=points, quadrature='gk15', limit=0)
+
+        # Check that all point sets lie in a single `points` interval
+        for p in interval_sets:
+            j = np.searchsorted(sorted(points), tuple(p))
+            assert np.all(j == j[0])
diff --git a/.venv/lib/python3.12/site-packages/scipy/integrate/tests/test_banded_ode_solvers.py b/.venv/lib/python3.12/site-packages/scipy/integrate/tests/test_banded_ode_solvers.py
new file mode 100644
index 0000000000000000000000000000000000000000..5d81d386b1ddfbbfaf22f67a4df5067811fcee96
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/integrate/tests/test_banded_ode_solvers.py
@@ -0,0 +1,304 @@
+import itertools
+import numpy as np
+from numpy.testing import assert_allclose
+from scipy.integrate import ode
+
+
+def _band_count(a):
+    """Returns ml and mu, the lower and upper band sizes of a."""
+    nrows, ncols = a.shape
+    ml = 0
+    for k in range(-nrows+1, 0):
+        if np.diag(a, k).any():
+            ml = -k
+            break
+    mu = 0
+    for k in range(nrows-1, 0, -1):
+        if np.diag(a, k).any():
+            mu = k
+            break
+    return ml, mu
+
+
+def _linear_func(t, y, a):
+    """Linear system dy/dt = a * y"""
+    return a.dot(y)
+
+
+def _linear_jac(t, y, a):
+    """Jacobian of a * y is a."""
+    return a
+
+
+def _linear_banded_jac(t, y, a):
+    """Banded Jacobian."""
+    ml, mu = _band_count(a)
+    bjac = [np.r_[[0] * k, np.diag(a, k)] for k in range(mu, 0, -1)]
+    bjac.append(np.diag(a))
+    for k in range(-1, -ml-1, -1):
+        bjac.append(np.r_[np.diag(a, k), [0] * (-k)])
+    return bjac
+
+
+def _solve_linear_sys(a, y0, tend=1, dt=0.1,
+                      solver=None, method='bdf', use_jac=True,
+                      with_jacobian=False, banded=False):
+    """Use scipy.integrate.ode to solve a linear system of ODEs.
+
+    a : square ndarray
+        Matrix of the linear system to be solved.
+    y0 : ndarray
+        Initial condition
+    tend : float
+        Stop time.
+    dt : float
+        Step size of the output.
+    solver : str
+        If not None, this must be "vode", "lsoda" or "zvode".
+    method : str
+        Either "bdf" or "adams".
+    use_jac : bool
+        Determines if the jacobian function is passed to ode().
+    with_jacobian : bool
+        Passed to ode.set_integrator().
+    banded : bool
+        Determines whether a banded or full jacobian is used.
+        If `banded` is True, `lband` and `uband` are determined by the
+        values in `a`.
+    """
+    if banded:
+        lband, uband = _band_count(a)
+    else:
+        lband = None
+        uband = None
+
+    if use_jac:
+        if banded:
+            r = ode(_linear_func, _linear_banded_jac)
+        else:
+            r = ode(_linear_func, _linear_jac)
+    else:
+        r = ode(_linear_func)
+
+    if solver is None:
+        if np.iscomplexobj(a):
+            solver = "zvode"
+        else:
+            solver = "vode"
+
+    r.set_integrator(solver,
+                     with_jacobian=with_jacobian,
+                     method=method,
+                     lband=lband, uband=uband,
+                     rtol=1e-9, atol=1e-10,
+                     )
+    t0 = 0
+    r.set_initial_value(y0, t0)
+    r.set_f_params(a)
+    r.set_jac_params(a)
+
+    t = [t0]
+    y = [y0.copy()]
+    while r.successful() and r.t < tend:
+        r.integrate(r.t + dt)
+        t.append(r.t)
+        y.append(r.y.copy())
+
+    t = np.array(t)
+    y = np.array(y)
+    return t, y
+
+
+def _analytical_solution(a, y0, t):
+    """
+    Analytical solution to the linear differential equations dy/dt = a*y.
+
+    The solution is only valid if `a` is diagonalizable.
+
+    Returns a 2-D array with shape (len(t), len(y0)).
+    """
+    lam, v = np.linalg.eig(a)
+    c = np.linalg.solve(v, y0)
+    e = c * np.exp(lam * t.reshape(-1, 1))
+    sol = e.dot(v.T)
+    return sol
+
+
+def test_banded_ode_solvers():
+    # Test the "lsoda", "vode" and "zvode" solvers of the `ode` class
+    # with a system that has a banded Jacobian matrix.
+
+    # This test does not test the Jacobian evaluation (banded or not)
+    # of "lsoda" due to the nonstiff nature of the equations.
+
+    t_exact = np.linspace(0, 1.0, 5)
+
+    # --- Real arrays for testing the "lsoda" and "vode" solvers ---
+
+    # lband = 2, uband = 1:
+    a_real = np.array([[-0.6, 0.1, 0.0, 0.0, 0.0],
+                       [0.2, -0.5, 0.9, 0.0, 0.0],
+                       [0.1, 0.1, -0.4, 0.1, 0.0],
+                       [0.0, 0.3, -0.1, -0.9, -0.3],
+                       [0.0, 0.0, 0.1, 0.1, -0.7]])
+
+    # lband = 0, uband = 1:
+    a_real_upper = np.triu(a_real)
+
+    # lband = 2, uband = 0:
+    a_real_lower = np.tril(a_real)
+
+    # lband = 0, uband = 0:
+    a_real_diag = np.triu(a_real_lower)
+
+    real_matrices = [a_real, a_real_upper, a_real_lower, a_real_diag]
+    real_solutions = []
+
+    for a in real_matrices:
+        y0 = np.arange(1, a.shape[0] + 1)
+        y_exact = _analytical_solution(a, y0, t_exact)
+        real_solutions.append((y0, t_exact, y_exact))
+
+    def check_real(idx, solver, meth, use_jac, with_jac, banded):
+        a = real_matrices[idx]
+        y0, t_exact, y_exact = real_solutions[idx]
+        t, y = _solve_linear_sys(a, y0,
+                                 tend=t_exact[-1],
+                                 dt=t_exact[1] - t_exact[0],
+                                 solver=solver,
+                                 method=meth,
+                                 use_jac=use_jac,
+                                 with_jacobian=with_jac,
+                                 banded=banded)
+        assert_allclose(t, t_exact)
+        assert_allclose(y, y_exact)
+
+    for idx in range(len(real_matrices)):
+        p = [['vode', 'lsoda'],  # solver
+             ['bdf', 'adams'],   # method
+             [False, True],      # use_jac
+             [False, True],      # with_jacobian
+             [False, True]]      # banded
+        for solver, meth, use_jac, with_jac, banded in itertools.product(*p):
+            check_real(idx, solver, meth, use_jac, with_jac, banded)
+
+    # --- Complex arrays for testing the "zvode" solver ---
+
+    # complex, lband = 2, uband = 1:
+    a_complex = a_real - 0.5j * a_real
+
+    # complex, lband = 0, uband = 0:
+    a_complex_diag = np.diag(np.diag(a_complex))
+
+    complex_matrices = [a_complex, a_complex_diag]
+    complex_solutions = []
+
+    for a in complex_matrices:
+        y0 = np.arange(1, a.shape[0] + 1) + 1j
+        y_exact = _analytical_solution(a, y0, t_exact)
+        complex_solutions.append((y0, t_exact, y_exact))
+
+    def check_complex(idx, solver, meth, use_jac, with_jac, banded):
+        a = complex_matrices[idx]
+        y0, t_exact, y_exact = complex_solutions[idx]
+        t, y = _solve_linear_sys(a, y0,
+                                 tend=t_exact[-1],
+                                 dt=t_exact[1] - t_exact[0],
+                                 solver=solver,
+                                 method=meth,
+                                 use_jac=use_jac,
+                                 with_jacobian=with_jac,
+                                 banded=banded)
+        assert_allclose(t, t_exact)
+        assert_allclose(y, y_exact)
+
+    for idx in range(len(complex_matrices)):
+        p = [['bdf', 'adams'],   # method
+             [False, True],      # use_jac
+             [False, True],      # with_jacobian
+             [False, True]]      # banded
+        for meth, use_jac, with_jac, banded in itertools.product(*p):
+            check_complex(idx, "zvode", meth, use_jac, with_jac, banded)
+
+# lsoda requires a stiffer problem to switch to stiff solver
+# Use the Robertson equation with surrounding trivial equations to make banded
+
+def stiff_f(t, y):
+    return np.array([
+        y[0],
+        -0.04 * y[1] + 1e4 * y[2] * y[3],
+        0.04 * y[1] - 1e4 * y[2] * y[3] - 3e7 * y[2]**2,
+        3e7 * y[2]**2,
+        y[4]
+    ])
+
+def stiff_jac(t, y):
+    return np.array([
+        [1,     0,                            0,         0, 0],
+        [0, -0.04,                     1e4*y[3],  1e4*y[2], 0],
+        [0,  0.04, -1e4 * y[3] - 3e7 * 2 * y[2], -1e4*y[2], 0],
+        [0,     0,                   3e7*2*y[2],         0, 0],
+        [0,     0,                            0,         0, 1]
+    ])
+
+def banded_stiff_jac(t, y):
+    return np.array([
+        [0,     0,                    0,  1e4*y[2], 0],
+        [0,     0,             1e4*y[3], -1e4*y[2], 0],
+        [1, -0.04, -1e4*y[3]-3e7*2*y[2],         0, 1],
+        [0,  0.04,           3e7*2*y[2],         0, 0]
+    ])
+
+def test_banded_lsoda():
+    # expected solution is given by problem with full jacobian
+    tfull, yfull = _solve_robertson_lsoda(use_jac=True, banded=False)
+
+    for use_jac in [True, False]:
+        t, y = _solve_robertson_lsoda(use_jac, True)
+        assert_allclose(t, tfull)
+        # Small tolerance to account for legitimate floating-point differences
+        # After fixing tesco and banded Jacobian bugs, max relative error is ~1.5e-7
+        assert_allclose(y, yfull, rtol=2e-7)
+
+def _solve_robertson_lsoda(use_jac, banded):
+
+    if use_jac:
+        if banded:
+            jac = banded_stiff_jac
+        else:
+            jac = stiff_jac
+    else:
+        jac = None
+
+    if banded:
+        lband = 1
+        uband = 2
+    else:
+        lband = None
+        uband = None
+
+    r = ode(stiff_f, jac)
+    r.set_integrator('lsoda',
+                     lband=lband, uband=uband,
+                     rtol=1e-9, atol=1e-10,
+                     )
+    t0 = 0
+    dt = 1
+    tend = 10
+    y0 = np.array([1.0, 1.0, 0.0, 0.0, 1.0])
+    r.set_initial_value(y0, t0)
+
+    t = [t0]
+    y = [y0.copy()]
+    while r.successful() and r.t < tend:
+        r.integrate(r.t + dt)
+        t.append(r.t)
+        y.append(r.y.copy())
+
+    # Ensure that the Jacobian was evaluated
+    # iwork[12] has the number of Jacobian evaluations.
+    assert r._integrator.iwork[12] > 0
+
+    t = np.array(t)
+    y = np.array(y)
+    return t, y
diff --git a/.venv/lib/python3.12/site-packages/scipy/integrate/tests/test_bvp.py b/.venv/lib/python3.12/site-packages/scipy/integrate/tests/test_bvp.py
new file mode 100644
index 0000000000000000000000000000000000000000..3ed14780216a3bdd9f3b567239480291877b0a8c
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/integrate/tests/test_bvp.py
@@ -0,0 +1,710 @@
+import sys
+from io import StringIO
+
+import numpy as np
+from numpy.testing import (assert_, assert_array_equal, assert_allclose,
+                           assert_equal)
+from pytest import raises as assert_raises
+
+from scipy.sparse import coo_array
+from scipy.special import erf
+from scipy.integrate._bvp import (modify_mesh, estimate_fun_jac,
+                                  estimate_bc_jac, compute_jac_indices,
+                                  construct_global_jac, solve_bvp)
+
+import pytest
+
+
+def exp_fun(x, y):
+    return np.vstack((y[1], y[0]))
+
+
+def exp_fun_jac(x, y):
+    df_dy = np.empty((2, 2, x.shape[0]))
+    df_dy[0, 0] = 0
+    df_dy[0, 1] = 1
+    df_dy[1, 0] = 1
+    df_dy[1, 1] = 0
+    return df_dy
+
+
+def exp_bc(ya, yb):
+    return np.hstack((ya[0] - 1, yb[0]))
+
+
+def exp_bc_complex(ya, yb):
+    return np.hstack((ya[0] - 1 - 1j, yb[0]))
+
+
+def exp_bc_jac(ya, yb):
+    dbc_dya = np.array([
+        [1, 0],
+        [0, 0]
+    ])
+    dbc_dyb = np.array([
+        [0, 0],
+        [1, 0]
+    ])
+    return dbc_dya, dbc_dyb
+
+
+def exp_sol(x):
+    return (np.exp(-x) - np.exp(x - 2)) / (1 - np.exp(-2))
+
+
+def sl_fun(x, y, p):
+    return np.vstack((y[1], -p[0]**2 * y[0]))
+
+
+def sl_fun_jac(x, y, p):
+    n, m = y.shape
+    df_dy = np.empty((n, 2, m))
+    df_dy[0, 0] = 0
+    df_dy[0, 1] = 1
+    df_dy[1, 0] = -p[0]**2
+    df_dy[1, 1] = 0
+
+    df_dp = np.empty((n, 1, m))
+    df_dp[0, 0] = 0
+    df_dp[1, 0] = -2 * p[0] * y[0]
+
+    return df_dy, df_dp
+
+
+def sl_bc(ya, yb, p):
+    return np.hstack((ya[0], yb[0], ya[1] - p[0]))
+
+
+def sl_bc_jac(ya, yb, p):
+    dbc_dya = np.zeros((3, 2))
+    dbc_dya[0, 0] = 1
+    dbc_dya[2, 1] = 1
+
+    dbc_dyb = np.zeros((3, 2))
+    dbc_dyb[1, 0] = 1
+
+    dbc_dp = np.zeros((3, 1))
+    dbc_dp[2, 0] = -1
+
+    return dbc_dya, dbc_dyb, dbc_dp
+
+
+def sl_sol(x, p):
+    return np.sin(p[0] * x)
+
+
+def emden_fun(x, y):
+    return np.vstack((y[1], -y[0]**5))
+
+
+def emden_fun_jac(x, y):
+    df_dy = np.empty((2, 2, x.shape[0]))
+    df_dy[0, 0] = 0
+    df_dy[0, 1] = 1
+    df_dy[1, 0] = -5 * y[0]**4
+    df_dy[1, 1] = 0
+    return df_dy
+
+
+def emden_bc(ya, yb):
+    return np.array([ya[1], yb[0] - (3/4)**0.5])
+
+
+def emden_bc_jac(ya, yb):
+    dbc_dya = np.array([
+        [0, 1],
+        [0, 0]
+    ])
+    dbc_dyb = np.array([
+        [0, 0],
+        [1, 0]
+    ])
+    return dbc_dya, dbc_dyb
+
+
+def emden_sol(x):
+    return (1 + x**2/3)**-0.5
+
+
+def undefined_fun(x, y):
+    return np.zeros_like(y)
+
+
+def undefined_bc(ya, yb):
+    return np.array([ya[0], yb[0] - 1])
+
+
+def big_fun(x, y):
+    f = np.zeros_like(y)
+    f[::2] = y[1::2]
+    return f
+
+
+def big_bc(ya, yb):
+    return np.hstack((ya[::2], yb[::2] - 1))
+
+
+def big_sol(x, n):
+    y = np.ones((2 * n, x.size))
+    y[::2] = x
+    return x
+
+
+def big_fun_with_parameters(x, y, p):
+    """ Big version of sl_fun, with two parameters.
+
+    The two differential equations represented by sl_fun are broadcast to the
+    number of rows of y, rotating between the parameters p[0] and p[1].
+    Here are the differential equations:
+
+        dy[0]/dt = y[1]
+        dy[1]/dt = -p[0]**2 * y[0]
+        dy[2]/dt = y[3]
+        dy[3]/dt = -p[1]**2 * y[2]
+        dy[4]/dt = y[5]
+        dy[5]/dt = -p[0]**2 * y[4]
+        dy[6]/dt = y[7]
+        dy[7]/dt = -p[1]**2 * y[6]
+        .
+        .
+        .
+
+    """
+    f = np.zeros_like(y)
+    f[::2] = y[1::2]
+    f[1::4] = -p[0]**2 * y[::4]
+    f[3::4] = -p[1]**2 * y[2::4]
+    return f
+
+
+def big_fun_with_parameters_jac(x, y, p):
+    # big version of sl_fun_jac, with two parameters
+    n, m = y.shape
+    df_dy = np.zeros((n, n, m))
+    df_dy[range(0, n, 2), range(1, n, 2)] = 1
+    df_dy[range(1, n, 4), range(0, n, 4)] = -p[0]**2
+    df_dy[range(3, n, 4), range(2, n, 4)] = -p[1]**2
+
+    df_dp = np.zeros((n, 2, m))
+    df_dp[range(1, n, 4), 0] = -2 * p[0] * y[range(0, n, 4)]
+    df_dp[range(3, n, 4), 1] = -2 * p[1] * y[range(2, n, 4)]
+
+    return df_dy, df_dp
+
+
+def big_bc_with_parameters(ya, yb, p):
+    # big version of sl_bc, with two parameters
+    return np.hstack((ya[::2], yb[::2], ya[1] - p[0], ya[3] - p[1]))
+
+
+def big_bc_with_parameters_jac(ya, yb, p):
+    # big version of sl_bc_jac, with two parameters
+    n = ya.shape[0]
+    dbc_dya = np.zeros((n + 2, n))
+    dbc_dyb = np.zeros((n + 2, n))
+
+    dbc_dya[range(n // 2), range(0, n, 2)] = 1
+    dbc_dyb[range(n // 2, n), range(0, n, 2)] = 1
+
+    dbc_dp = np.zeros((n + 2, 2))
+    dbc_dp[n, 0] = -1
+    dbc_dya[n, 1] = 1
+    dbc_dp[n + 1, 1] = -1
+    dbc_dya[n + 1, 3] = 1
+
+    return dbc_dya, dbc_dyb, dbc_dp
+
+
+def big_sol_with_parameters(x, p):
+    # big version of sl_sol, with two parameters
+    return np.vstack((np.sin(p[0] * x), np.sin(p[1] * x)))
+
+
+def shock_fun(x, y):
+    eps = 1e-3
+    return np.vstack((
+        y[1],
+        -(x * y[1] + eps * np.pi**2 * np.cos(np.pi * x) +
+          np.pi * x * np.sin(np.pi * x)) / eps
+    ))
+
+
+def shock_bc(ya, yb):
+    return np.array([ya[0] + 2, yb[0]])
+
+
+def shock_sol(x):
+    eps = 1e-3
+    k = np.sqrt(2 * eps)
+    return np.cos(np.pi * x) + erf(x / k) / erf(1 / k)
+
+
+def nonlin_bc_fun(x, y):
+    # laplace eq.
+    return np.stack([y[1], np.zeros_like(x)])
+
+
+def nonlin_bc_bc(ya, yb):
+    phiA, phipA = ya
+    phiC, phipC = yb
+
+    kappa, ioA, ioC, V, f = 1.64, 0.01, 1.0e-4, 0.5, 38.9
+
+    # Butler-Volmer Kinetics at Anode
+    hA = 0.0-phiA-0.0
+    iA = ioA * (np.exp(f*hA) - np.exp(-f*hA))
+    res0 = iA + kappa * phipA
+
+    # Butler-Volmer Kinetics at Cathode
+    hC = V - phiC - 1.0
+    iC = ioC * (np.exp(f*hC) - np.exp(-f*hC))
+    res1 = iC - kappa*phipC
+
+    return np.array([res0, res1])
+
+
+def nonlin_bc_sol(x):
+    return -0.13426436116763119 - 1.1308709 * x
+
+
+def test_modify_mesh():
+    x = np.array([0, 1, 3, 9], dtype=float)
+    x_new = modify_mesh(x, np.array([0]), np.array([2]))
+    assert_array_equal(x_new, np.array([0, 0.5, 1, 3, 5, 7, 9]))
+
+    x = np.array([-6, -3, 0, 3, 6], dtype=float)
+    x_new = modify_mesh(x, np.array([1], dtype=int), np.array([0, 2, 3]))
+    assert_array_equal(x_new, [-6, -5, -4, -3, -1.5, 0, 1, 2, 3, 4, 5, 6])
+
+
+def test_compute_fun_jac():
+    x = np.linspace(0, 1, 5)
+    y = np.empty((2, x.shape[0]))
+    y[0] = 0.01
+    y[1] = 0.02
+    p = np.array([])
+    df_dy, df_dp = estimate_fun_jac(lambda x, y, p: exp_fun(x, y), x, y, p)
+    df_dy_an = exp_fun_jac(x, y)
+    assert_allclose(df_dy, df_dy_an)
+    assert_(df_dp is None)
+
+    x = np.linspace(0, np.pi, 5)
+    y = np.empty((2, x.shape[0]))
+    y[0] = np.sin(x)
+    y[1] = np.cos(x)
+    p = np.array([1.0])
+    df_dy, df_dp = estimate_fun_jac(sl_fun, x, y, p)
+    df_dy_an, df_dp_an = sl_fun_jac(x, y, p)
+    assert_allclose(df_dy, df_dy_an)
+    assert_allclose(df_dp, df_dp_an)
+
+    x = np.linspace(0, 1, 10)
+    y = np.empty((2, x.shape[0]))
+    y[0] = (3/4)**0.5
+    y[1] = 1e-4
+    p = np.array([])
+    df_dy, df_dp = estimate_fun_jac(lambda x, y, p: emden_fun(x, y), x, y, p)
+    df_dy_an = emden_fun_jac(x, y)
+    assert_allclose(df_dy, df_dy_an)
+    assert_(df_dp is None)
+
+
+def test_compute_bc_jac():
+    ya = np.array([-1.0, 2])
+    yb = np.array([0.5, 3])
+    p = np.array([])
+    dbc_dya, dbc_dyb, dbc_dp = estimate_bc_jac(
+        lambda ya, yb, p: exp_bc(ya, yb), ya, yb, p)
+    dbc_dya_an, dbc_dyb_an = exp_bc_jac(ya, yb)
+    assert_allclose(dbc_dya, dbc_dya_an)
+    assert_allclose(dbc_dyb, dbc_dyb_an)
+    assert_(dbc_dp is None)
+
+    ya = np.array([0.0, 1])
+    yb = np.array([0.0, -1])
+    p = np.array([0.5])
+    dbc_dya, dbc_dyb, dbc_dp = estimate_bc_jac(sl_bc, ya, yb, p)
+    dbc_dya_an, dbc_dyb_an, dbc_dp_an = sl_bc_jac(ya, yb, p)
+    assert_allclose(dbc_dya, dbc_dya_an)
+    assert_allclose(dbc_dyb, dbc_dyb_an)
+    assert_allclose(dbc_dp, dbc_dp_an)
+
+    ya = np.array([0.5, 100])
+    yb = np.array([-1000, 10.5])
+    p = np.array([])
+    dbc_dya, dbc_dyb, dbc_dp = estimate_bc_jac(
+        lambda ya, yb, p: emden_bc(ya, yb), ya, yb, p)
+    dbc_dya_an, dbc_dyb_an = emden_bc_jac(ya, yb)
+    assert_allclose(dbc_dya, dbc_dya_an)
+    assert_allclose(dbc_dyb, dbc_dyb_an)
+    assert_(dbc_dp is None)
+
+
+def test_compute_jac_indices():
+    n = 2
+    m = 4
+    k = 2
+    i, j = compute_jac_indices(n, m, k)
+    s = coo_array((np.ones_like(i), (i, j))).toarray()
+    s_true = np.array([
+        [1, 1, 1, 1, 0, 0, 0, 0, 1, 1],
+        [1, 1, 1, 1, 0, 0, 0, 0, 1, 1],
+        [0, 0, 1, 1, 1, 1, 0, 0, 1, 1],
+        [0, 0, 1, 1, 1, 1, 0, 0, 1, 1],
+        [0, 0, 0, 0, 1, 1, 1, 1, 1, 1],
+        [0, 0, 0, 0, 1, 1, 1, 1, 1, 1],
+        [1, 1, 0, 0, 0, 0, 1, 1, 1, 1],
+        [1, 1, 0, 0, 0, 0, 1, 1, 1, 1],
+        [1, 1, 0, 0, 0, 0, 1, 1, 1, 1],
+        [1, 1, 0, 0, 0, 0, 1, 1, 1, 1],
+    ])
+    assert_array_equal(s, s_true)
+
+
+def test_compute_global_jac():
+    n = 2
+    m = 5
+    k = 1
+    i_jac, j_jac = compute_jac_indices(2, 5, 1)
+    x = np.linspace(0, 1, 5)
+    h = np.diff(x)
+    y = np.vstack((np.sin(np.pi * x), np.pi * np.cos(np.pi * x)))
+    p = np.array([3.0])
+
+    f = sl_fun(x, y, p)
+
+    x_middle = x[:-1] + 0.5 * h
+    y_middle = 0.5 * (y[:, :-1] + y[:, 1:]) - h/8 * (f[:, 1:] - f[:, :-1])
+
+    df_dy, df_dp = sl_fun_jac(x, y, p)
+    df_dy_middle, df_dp_middle = sl_fun_jac(x_middle, y_middle, p)
+    dbc_dya, dbc_dyb, dbc_dp = sl_bc_jac(y[:, 0], y[:, -1], p)
+
+    J = construct_global_jac(n, m, k, i_jac, j_jac, h, df_dy, df_dy_middle,
+                             df_dp, df_dp_middle, dbc_dya, dbc_dyb, dbc_dp)
+    J = J.toarray()
+
+    def J_block(h, p):
+        return np.array([
+            [h**2*p**2/12 - 1, -0.5*h, -h**2*p**2/12 + 1, -0.5*h],
+            [0.5*h*p**2, h**2*p**2/12 - 1, 0.5*h*p**2, 1 - h**2*p**2/12]
+        ])
+
+    J_true = np.zeros((m * n + k, m * n + k))
+    for i in range(m - 1):
+        J_true[i * n: (i + 1) * n, i * n: (i + 2) * n] = J_block(h[i], p[0])
+
+    J_true[:(m - 1) * n:2, -1] = p * h**2/6 * (y[0, :-1] - y[0, 1:])
+    J_true[1:(m - 1) * n:2, -1] = p * (h * (y[0, :-1] + y[0, 1:]) +
+                                       h**2/6 * (y[1, :-1] - y[1, 1:]))
+
+    J_true[8, 0] = 1
+    J_true[9, 8] = 1
+    J_true[10, 1] = 1
+    J_true[10, 10] = -1
+
+    assert_allclose(J, J_true, rtol=1e-10)
+
+    df_dy, df_dp = estimate_fun_jac(sl_fun, x, y, p)
+    df_dy_middle, df_dp_middle = estimate_fun_jac(sl_fun, x_middle, y_middle, p)
+    dbc_dya, dbc_dyb, dbc_dp = estimate_bc_jac(sl_bc, y[:, 0], y[:, -1], p)
+    J = construct_global_jac(n, m, k, i_jac, j_jac, h, df_dy, df_dy_middle,
+                             df_dp, df_dp_middle, dbc_dya, dbc_dyb, dbc_dp)
+    J = J.toarray()
+    assert_allclose(J, J_true, rtol=2e-8, atol=2e-8)
+
+
+def test_parameter_validation():
+    x = [0, 1, 0.5]
+    y = np.zeros((2, 3))
+    assert_raises(ValueError, solve_bvp, exp_fun, exp_bc, x, y)
+
+    x = np.linspace(0, 1, 5)
+    y = np.zeros((2, 4))
+    assert_raises(ValueError, solve_bvp, exp_fun, exp_bc, x, y)
+
+    def fun(x, y, p):
+        return exp_fun(x, y)
+    def bc(ya, yb, p):
+        return exp_bc(ya, yb)
+
+    y = np.zeros((2, x.shape[0]))
+    assert_raises(ValueError, solve_bvp, fun, bc, x, y, p=[1])
+
+    def wrong_shape_fun(x, y):
+        return np.zeros(3)
+
+    assert_raises(ValueError, solve_bvp, wrong_shape_fun, bc, x, y)
+
+    S = np.array([[0, 0]])
+    assert_raises(ValueError, solve_bvp, exp_fun, exp_bc, x, y, S=S)
+
+
+def test_no_params():
+    x = np.linspace(0, 1, 5)
+    x_test = np.linspace(0, 1, 100)
+    y = np.zeros((2, x.shape[0]))
+    for fun_jac in [None, exp_fun_jac]:
+        for bc_jac in [None, exp_bc_jac]:
+            sol = solve_bvp(exp_fun, exp_bc, x, y, fun_jac=fun_jac,
+                            bc_jac=bc_jac)
+
+            assert_equal(sol.status, 0)
+            assert_(sol.success)
+
+            assert_equal(sol.x.size, 5)
+
+            sol_test = sol.sol(x_test)
+
+            assert_allclose(sol_test[0], exp_sol(x_test), atol=1e-5)
+
+            f_test = exp_fun(x_test, sol_test)
+            r = sol.sol(x_test, 1) - f_test
+            rel_res = r / (1 + np.abs(f_test))
+            norm_res = np.sum(rel_res**2, axis=0)**0.5
+            assert_(np.all(norm_res < 1e-3))
+
+            assert_(np.all(sol.rms_residuals < 1e-3))
+            assert_allclose(sol.sol(sol.x), sol.y, rtol=1e-10, atol=1e-10)
+            assert_allclose(sol.sol(sol.x, 1), sol.yp, rtol=1e-10, atol=1e-10)
+
+
+def test_with_params():
+    x = np.linspace(0, np.pi, 5)
+    x_test = np.linspace(0, np.pi, 100)
+    y = np.ones((2, x.shape[0]))
+
+    for fun_jac in [None, sl_fun_jac]:
+        for bc_jac in [None, sl_bc_jac]:
+            sol = solve_bvp(sl_fun, sl_bc, x, y, p=[0.5], fun_jac=fun_jac,
+                            bc_jac=bc_jac)
+
+            assert_equal(sol.status, 0)
+            assert_(sol.success)
+
+            assert_(sol.x.size < 10)
+
+            assert_allclose(sol.p, [1], rtol=1e-4)
+
+            sol_test = sol.sol(x_test)
+
+            assert_allclose(sol_test[0], sl_sol(x_test, [1]),
+                            rtol=1e-4, atol=1e-4)
+
+            f_test = sl_fun(x_test, sol_test, [1])
+            r = sol.sol(x_test, 1) - f_test
+            rel_res = r / (1 + np.abs(f_test))
+            norm_res = np.sum(rel_res ** 2, axis=0) ** 0.5
+            assert_(np.all(norm_res < 1e-3))
+
+            assert_(np.all(sol.rms_residuals < 1e-3))
+            assert_allclose(sol.sol(sol.x), sol.y, rtol=1e-10, atol=1e-10)
+            assert_allclose(sol.sol(sol.x, 1), sol.yp, rtol=1e-10, atol=1e-10)
+
+
+def test_singular_term():
+    x = np.linspace(0, 1, 10)
+    x_test = np.linspace(0.05, 1, 100)
+    y = np.empty((2, 10))
+    y[0] = (3/4)**0.5
+    y[1] = 1e-4
+    S = np.array([[0, 0], [0, -2]])
+
+    for fun_jac in [None, emden_fun_jac]:
+        for bc_jac in [None, emden_bc_jac]:
+            sol = solve_bvp(emden_fun, emden_bc, x, y, S=S, fun_jac=fun_jac,
+                            bc_jac=bc_jac)
+
+            assert_equal(sol.status, 0)
+            assert_(sol.success)
+
+            assert_equal(sol.x.size, 10)
+
+            sol_test = sol.sol(x_test)
+            assert_allclose(sol_test[0], emden_sol(x_test), atol=1e-5)
+
+            f_test = emden_fun(x_test, sol_test) + S.dot(sol_test) / x_test
+            r = sol.sol(x_test, 1) - f_test
+            rel_res = r / (1 + np.abs(f_test))
+            norm_res = np.sum(rel_res ** 2, axis=0) ** 0.5
+
+            assert_(np.all(norm_res < 1e-3))
+            assert_allclose(sol.sol(sol.x), sol.y, rtol=1e-10, atol=1e-10)
+            assert_allclose(sol.sol(sol.x, 1), sol.yp, rtol=1e-10, atol=1e-10)
+
+
+def test_complex():
+    # The test is essentially the same as test_no_params, but boundary
+    # conditions are turned into complex.
+    x = np.linspace(0, 1, 5)
+    x_test = np.linspace(0, 1, 100)
+    y = np.zeros((2, x.shape[0]), dtype=complex)
+    for fun_jac in [None, exp_fun_jac]:
+        for bc_jac in [None, exp_bc_jac]:
+            sol = solve_bvp(exp_fun, exp_bc_complex, x, y, fun_jac=fun_jac,
+                            bc_jac=bc_jac)
+
+            assert_equal(sol.status, 0)
+            assert_(sol.success)
+
+            sol_test = sol.sol(x_test)
+
+            assert_allclose(sol_test[0].real, exp_sol(x_test), atol=1e-5)
+            assert_allclose(sol_test[0].imag, exp_sol(x_test), atol=1e-5)
+
+            f_test = exp_fun(x_test, sol_test)
+            r = sol.sol(x_test, 1) - f_test
+            rel_res = r / (1 + np.abs(f_test))
+            norm_res = np.sum(np.real(rel_res * np.conj(rel_res)),
+                              axis=0) ** 0.5
+            assert_(np.all(norm_res < 1e-3))
+
+            assert_(np.all(sol.rms_residuals < 1e-3))
+            assert_allclose(sol.sol(sol.x), sol.y, rtol=1e-10, atol=1e-10)
+            assert_allclose(sol.sol(sol.x, 1), sol.yp, rtol=1e-10, atol=1e-10)
+
+
+def test_failures():
+    x = np.linspace(0, 1, 2)
+    y = np.zeros((2, x.size))
+    res = solve_bvp(exp_fun, exp_bc, x, y, tol=1e-5, max_nodes=5)
+    assert_equal(res.status, 1)
+    assert_(not res.success)
+
+    x = np.linspace(0, 1, 5)
+    y = np.zeros((2, x.size))
+    res = solve_bvp(undefined_fun, undefined_bc, x, y)
+    assert_equal(res.status, 2)
+    assert_(not res.success)
+
+
+def test_big_problem():
+    n = 30
+    x = np.linspace(0, 1, 5)
+    y = np.zeros((2 * n, x.size))
+    sol = solve_bvp(big_fun, big_bc, x, y)
+
+    assert_equal(sol.status, 0)
+    assert_(sol.success)
+
+    sol_test = sol.sol(x)
+
+    assert_allclose(sol_test[0], big_sol(x, n))
+
+    f_test = big_fun(x, sol_test)
+    r = sol.sol(x, 1) - f_test
+    rel_res = r / (1 + np.abs(f_test))
+    norm_res = np.sum(np.real(rel_res * np.conj(rel_res)), axis=0) ** 0.5
+    assert_(np.all(norm_res < 1e-3))
+
+    assert_(np.all(sol.rms_residuals < 1e-3))
+    assert_allclose(sol.sol(sol.x), sol.y, rtol=1e-10, atol=1e-10)
+    assert_allclose(sol.sol(sol.x, 1), sol.yp, rtol=1e-10, atol=1e-10)
+
+
+def test_big_problem_with_parameters():
+    n = 30
+    x = np.linspace(0, np.pi, 5)
+    x_test = np.linspace(0, np.pi, 100)
+    y = np.ones((2 * n, x.size))
+
+    for fun_jac in [None, big_fun_with_parameters_jac]:
+        for bc_jac in [None, big_bc_with_parameters_jac]:
+            sol = solve_bvp(big_fun_with_parameters, big_bc_with_parameters, x,
+                            y, p=[0.5, 0.5], fun_jac=fun_jac, bc_jac=bc_jac)
+
+            assert_equal(sol.status, 0)
+            assert_(sol.success)
+
+            assert_allclose(sol.p, [1, 1], rtol=1e-4)
+
+            sol_test = sol.sol(x_test)
+
+            for isol in range(0, n, 4):
+                assert_allclose(sol_test[isol],
+                                big_sol_with_parameters(x_test, [1, 1])[0],
+                                rtol=1e-4, atol=1e-4)
+                assert_allclose(sol_test[isol + 2],
+                                big_sol_with_parameters(x_test, [1, 1])[1],
+                                rtol=1e-4, atol=1e-4)
+
+            f_test = big_fun_with_parameters(x_test, sol_test, [1, 1])
+            r = sol.sol(x_test, 1) - f_test
+            rel_res = r / (1 + np.abs(f_test))
+            norm_res = np.sum(rel_res ** 2, axis=0) ** 0.5
+            assert_(np.all(norm_res < 1e-3))
+
+            assert_(np.all(sol.rms_residuals < 1e-3))
+            assert_allclose(sol.sol(sol.x), sol.y, rtol=1e-10, atol=1e-10)
+            assert_allclose(sol.sol(sol.x, 1), sol.yp, rtol=1e-10, atol=1e-10)
+
+
+def test_shock_layer():
+    x = np.linspace(-1, 1, 5)
+    x_test = np.linspace(-1, 1, 100)
+    y = np.zeros((2, x.size))
+    sol = solve_bvp(shock_fun, shock_bc, x, y)
+
+    assert_equal(sol.status, 0)
+    assert_(sol.success)
+
+    assert_(sol.x.size < 110)
+
+    sol_test = sol.sol(x_test)
+    assert_allclose(sol_test[0], shock_sol(x_test), rtol=1e-5, atol=1e-5)
+
+    f_test = shock_fun(x_test, sol_test)
+    r = sol.sol(x_test, 1) - f_test
+    rel_res = r / (1 + np.abs(f_test))
+    norm_res = np.sum(rel_res ** 2, axis=0) ** 0.5
+
+    assert_(np.all(norm_res < 1e-3))
+    assert_allclose(sol.sol(sol.x), sol.y, rtol=1e-10, atol=1e-10)
+    assert_allclose(sol.sol(sol.x, 1), sol.yp, rtol=1e-10, atol=1e-10)
+
+
+def test_nonlin_bc():
+    x = np.linspace(0, 0.1, 5)
+    x_test = x
+    y = np.zeros([2, x.size])
+    sol = solve_bvp(nonlin_bc_fun, nonlin_bc_bc, x, y)
+
+    assert_equal(sol.status, 0)
+    assert_(sol.success)
+
+    assert_(sol.x.size < 8)
+
+    sol_test = sol.sol(x_test)
+    assert_allclose(sol_test[0], nonlin_bc_sol(x_test), rtol=1e-5, atol=1e-5)
+
+    f_test = nonlin_bc_fun(x_test, sol_test)
+    r = sol.sol(x_test, 1) - f_test
+    rel_res = r / (1 + np.abs(f_test))
+    norm_res = np.sum(rel_res ** 2, axis=0) ** 0.5
+
+    assert_(np.all(norm_res < 1e-3))
+    assert_allclose(sol.sol(sol.x), sol.y, rtol=1e-10, atol=1e-10)
+    assert_allclose(sol.sol(sol.x, 1), sol.yp, rtol=1e-10, atol=1e-10)
+
+
+@pytest.mark.thread_unsafe(reason="multithreaded sys.stdout parsing is not thread-safe")
+def test_verbose():
+    # Smoke test that checks the printing does something and does not crash
+    x = np.linspace(0, 1, 5)
+    y = np.zeros((2, x.shape[0]))
+    for verbose in [0, 1, 2]:
+        old_stdout = sys.stdout
+        sys.stdout = StringIO()
+        try:
+            sol = solve_bvp(exp_fun, exp_bc, x, y, verbose=verbose)
+            text = sys.stdout.getvalue()
+        finally:
+            sys.stdout = old_stdout
+
+        assert_(sol.success)
+        if verbose == 0:
+            assert_(not text, text)
+        if verbose >= 1:
+            assert_("Solved in" in text, text)
+        if verbose >= 2:
+            assert_("Max residual" in text, text)
diff --git a/.venv/lib/python3.12/site-packages/scipy/integrate/tests/test_cubature.py b/.venv/lib/python3.12/site-packages/scipy/integrate/tests/test_cubature.py
new file mode 100644
index 0000000000000000000000000000000000000000..5d734e30ecd878c898325a819e7dbf47e20d9c05
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/integrate/tests/test_cubature.py
@@ -0,0 +1,1381 @@
+import math
+import scipy
+import itertools
+
+import pytest
+
+from scipy._lib._array_api import (
+    array_namespace,
+    xp_assert_close,
+    xp_size,
+    np_compat,
+    is_array_api_strict,
+    make_xp_test_case,
+)
+from scipy.integrate import cubature
+from scipy.integrate._cubature import _InfiniteLimitsTransform
+from scipy.integrate._rules import (
+    Rule, FixedRule,
+    NestedFixedRule,
+    GaussLegendreQuadrature, GaussKronrodQuadrature,
+    GenzMalikCubature,
+)
+
+skip_xp_backends = pytest.mark.skip_xp_backends
+boolean_index_skip_reason = 'JAX/Dask arrays do not support boolean assignment.'
+
+# The integrands ``genz_malik_1980_*`` come from the paper:
+#   A.C. Genz, A.A. Malik, Remarks on algorithm 006: An adaptive algorithm for
+#   numerical integration over an N-dimensional rectangular region, Journal of
+#   Computational and Applied Mathematics, Volume 6, Issue 4, 1980, Pages 295-302,
+#   ISSN 0377-0427, https://doi.org/10.1016/0771-050X(80)90039-X.
+
+
+def basic_1d_integrand(x, n, xp):
+    x_reshaped = xp.reshape(x, (-1, 1, 1))
+    n_reshaped = xp.reshape(n, (1, -1, 1))
+
+    return x_reshaped**n_reshaped
+
+
+def basic_1d_integrand_exact(n, xp):
+    # Exact only for integration over interval [0, 2].
+    return xp.reshape(2**(n+1)/(n+1), (-1, 1))
+
+
+def basic_nd_integrand(x, n, xp):
+    return xp.reshape(xp.sum(x, axis=-1), (-1, 1))**xp.reshape(n, (1, -1))
+
+
+def basic_nd_integrand_exact(n, xp):
+    # Exact only for integration over interval [0, 2].
+    return (-2**(3+n) + 4**(2+n))/((1+n)*(2+n))
+
+
+def genz_malik_1980_f_1(x, r, alphas, xp):
+    r"""
+    .. math:: f_1(\mathbf x) = \cos\left(2\pi r + \sum^n_{i = 1}\alpha_i x_i\right)
+
+    .. code-block:: mathematica
+
+        genzMalik1980f1[x_List, r_, alphas_List] := Cos[2*Pi*r + Total[x*alphas]]
+    """
+
+    npoints, ndim = x.shape[0], x.shape[-1]
+
+    alphas_reshaped = alphas[None, ...]
+    x_reshaped = xp.reshape(x, (npoints, *([1]*(len(alphas.shape) - 1)), ndim))
+
+    return xp.cos(2*math.pi*r + xp.sum(alphas_reshaped * x_reshaped, axis=-1))
+
+
+def genz_malik_1980_f_1_exact(a, b, r, alphas, xp):
+    ndim = xp_size(a)
+    a = xp.reshape(a, (*([1]*(len(alphas.shape) - 1)), ndim))
+    b = xp.reshape(b, (*([1]*(len(alphas.shape) - 1)), ndim))
+
+    return (
+        (-2)**ndim
+        * 1/xp.prod(alphas, axis=-1)
+        * xp.cos(2*math.pi*r + xp.sum(alphas * (a+b) * 0.5, axis=-1))
+        * xp.prod(xp.sin(alphas * (a-b)/2), axis=-1)
+    )
+
+
+def genz_malik_1980_f_1_random_args(rng, shape, xp):
+    r = xp.asarray(rng.random(shape[:-1]))
+    alphas = xp.asarray(rng.random(shape))
+
+    difficulty = 9
+    normalisation_factors = xp.sum(alphas, axis=-1)[..., None]
+    alphas = difficulty * alphas / normalisation_factors
+
+    return (r, alphas)
+
+
+def genz_malik_1980_f_2(x, alphas, betas, xp):
+    r"""
+    .. math:: f_2(\mathbf x) = \prod^n_{i = 1} (\alpha_i^2 + (x_i - \beta_i)^2)^{-1}
+
+    .. code-block:: mathematica
+
+        genzMalik1980f2[x_List, alphas_List, betas_List] :=
+            1/Times @@ ((alphas^2 + (x - betas)^2))
+    """
+    npoints, ndim = x.shape[0], x.shape[-1]
+
+    alphas_reshaped = alphas[None, ...]
+    betas_reshaped = betas[None, ...]
+
+    x_reshaped = xp.reshape(x, (npoints, *([1]*(len(alphas.shape) - 1)), ndim))
+
+    return 1/xp.prod(alphas_reshaped**2 + (x_reshaped-betas_reshaped)**2, axis=-1)
+
+
+def genz_malik_1980_f_2_exact(a, b, alphas, betas, xp):
+    ndim = xp_size(a)
+    a = xp.reshape(a, (*([1]*(len(alphas.shape) - 1)), ndim))
+    b = xp.reshape(b, (*([1]*(len(alphas.shape) - 1)), ndim))
+
+    return (
+        (-1)**ndim * 1/xp.prod(alphas, axis=-1)
+        * xp.prod(
+            xp.atan((a - betas)/alphas) - xp.atan((b - betas)/alphas),
+            axis=-1,
+        )
+    )
+
+
+def genz_malik_1980_f_2_random_args(rng, shape, xp):
+    ndim = shape[-1]
+    alphas = xp.asarray(rng.random(shape))
+    betas = xp.asarray(rng.random(shape))
+
+    difficulty = 25.0
+    products = xp.prod(alphas**xp.asarray(-2.0), axis=-1)
+    normalisation_factors = (products**xp.asarray(1 / (2*ndim)))[..., None]
+    alphas = alphas * normalisation_factors * math.pow(difficulty, 1 / (2*ndim))
+
+    # Adjust alphas from distribution used in Genz and Malik 1980 since denominator
+    # is very small for high dimensions.
+    alphas *= 10
+
+    return alphas, betas
+
+
+def genz_malik_1980_f_3(x, alphas, xp):
+    r"""
+    .. math:: f_3(\mathbf x) = \exp\left(\sum^n_{i = 1} \alpha_i x_i\right)
+
+    .. code-block:: mathematica
+
+        genzMalik1980f3[x_List, alphas_List] := Exp[Dot[x, alphas]]
+    """
+
+    npoints, ndim = x.shape[0], x.shape[-1]
+
+    alphas_reshaped = alphas[None, ...]
+    x_reshaped = xp.reshape(x, (npoints, *([1]*(len(alphas.shape) - 1)), ndim))
+
+    return xp.exp(xp.sum(alphas_reshaped * x_reshaped, axis=-1))
+
+
+def genz_malik_1980_f_3_exact(a, b, alphas, xp):
+    ndim = xp_size(a)
+    a = xp.reshape(a, (*([1]*(len(alphas.shape) - 1)), ndim))
+    b = xp.reshape(b, (*([1]*(len(alphas.shape) - 1)), ndim))
+
+    return (
+        (-1)**ndim * 1/xp.prod(alphas, axis=-1)
+        * xp.prod(xp.exp(alphas * a) - xp.exp(alphas * b), axis=-1)
+    )
+
+
+def genz_malik_1980_f_3_random_args(rng, shape, xp):
+    alphas = xp.asarray(rng.random(shape))
+    normalisation_factors = xp.sum(alphas, axis=-1)[..., None]
+    difficulty = 12.0
+    alphas = difficulty * alphas / normalisation_factors
+
+    return (alphas,)
+
+
+def genz_malik_1980_f_4(x, alphas, xp):
+    r"""
+    .. math:: f_4(\mathbf x) = \left(1 + \sum^n_{i = 1} \alpha_i x_i\right)^{-n-1}
+
+    .. code-block:: mathematica
+        genzMalik1980f4[x_List, alphas_List] :=
+            (1 + Dot[x, alphas])^(-Length[alphas] - 1)
+    """
+
+    npoints, ndim = x.shape[0], x.shape[-1]
+
+    alphas_reshaped = alphas[None, ...]
+    x_reshaped = xp.reshape(x, (npoints, *([1]*(len(alphas.shape) - 1)), ndim))
+
+    return (1 + xp.sum(alphas_reshaped * x_reshaped, axis=-1))**(-ndim-1)
+
+
+def genz_malik_1980_f_4_exact(a, b, alphas, xp):
+    ndim = xp_size(a)
+
+    def F(x):
+        x_reshaped = xp.reshape(x, (*([1]*(len(alphas.shape) - 1)), ndim))
+
+        return (
+            (-1)**ndim/xp.prod(alphas, axis=-1)
+            / math.factorial(ndim)
+            / (1 + xp.sum(alphas * x_reshaped, axis=-1))
+        )
+
+    return _eval_indefinite_integral(F, a, b, xp)
+
+
+def _eval_indefinite_integral(F, a, b, xp):
+    """
+    Calculates a definite integral from points `a` to `b` by summing up over the corners
+    of the corresponding hyperrectangle.
+    """
+
+    ndim = xp_size(a)
+    points = xp.stack([a, b], axis=0)
+
+    out = 0
+    for ind in itertools.product(range(2), repeat=ndim):
+        selected_points = xp.asarray(
+            [float(points[i, j]) for i, j in zip(ind, range(ndim))]
+        )
+        out += pow(-1, sum(ind) + ndim) * F(selected_points)
+
+    return out
+
+
+def genz_malik_1980_f_4_random_args(rng, shape, xp):
+    ndim = shape[-1]
+
+    alphas = xp.asarray(rng.random(shape))
+    normalisation_factors = xp.sum(alphas, axis=-1)[..., None]
+    difficulty = 14.0
+    alphas = (difficulty / ndim) * alphas / normalisation_factors
+
+    return (alphas,)
+
+
+def genz_malik_1980_f_5(x, alphas, betas, xp):
+    r"""
+    .. math::
+
+        f_5(\mathbf x) = \exp\left(-\sum^n_{i = 1} \alpha^2_i (x_i - \beta_i)^2\right)
+
+    .. code-block:: mathematica
+
+        genzMalik1980f5[x_List, alphas_List, betas_List] :=
+            Exp[-Total[alphas^2 * (x - betas)^2]]
+    """
+
+    npoints, ndim = x.shape[0], x.shape[-1]
+
+    alphas_reshaped = alphas[None, ...]
+    betas_reshaped = betas[None, ...]
+
+    x_reshaped = xp.reshape(x, (npoints, *([1]*(len(alphas.shape) - 1)), ndim))
+
+    return xp.exp(
+        -xp.sum(alphas_reshaped**2 * (x_reshaped - betas_reshaped)**2, axis=-1)
+    )
+
+
+def genz_malik_1980_f_5_exact(a, b, alphas, betas, xp):
+    ndim = xp_size(a)
+    a = xp.reshape(a, (*([1]*(len(alphas.shape) - 1)), ndim))
+    b = xp.reshape(b, (*([1]*(len(alphas.shape) - 1)), ndim))
+
+    return (
+        (1/2)**ndim
+        * 1/xp.prod(alphas, axis=-1)
+        * (math.pi**(ndim/2))
+        * xp.prod(
+            scipy.special.erf(alphas * (betas - a))
+            + scipy.special.erf(alphas * (b - betas)),
+            axis=-1,
+        )
+    )
+
+
+def genz_malik_1980_f_5_random_args(rng, shape, xp):
+    alphas = xp.asarray(rng.random(shape))
+    betas = xp.asarray(rng.random(shape))
+
+    difficulty = 21.0
+    normalisation_factors = xp.sqrt(xp.sum(alphas**xp.asarray(2.0), axis=-1))[..., None]
+    alphas = alphas / normalisation_factors * math.sqrt(difficulty)
+
+    return alphas, betas
+
+
+def f_gaussian(x, alphas, xp):
+    r"""
+    .. math::
+
+        f(\mathbf x) = \exp\left(-\sum^n_{i = 1} (\alpha_i x_i)^2 \right)
+    """
+    npoints, ndim = x.shape[0], x.shape[-1]
+    alphas_reshaped = alphas[None, ...]
+    x_reshaped = xp.reshape(x, (npoints, *([1]*(len(alphas.shape) - 1)), ndim))
+
+    return xp.exp(-xp.sum((alphas_reshaped * x_reshaped)**2, axis=-1))
+
+
+def f_gaussian_exact(a, b, alphas, xp):
+    # Exact only when `a` and `b` are one of:
+    #   (-oo, oo), or
+    #   (0, oo), or
+    #   (-oo, 0)
+    # `alphas` can be arbitrary.
+
+    ndim = xp_size(a)
+    double_infinite_count = 0
+    semi_infinite_count = 0
+
+    for i in range(ndim):
+        if xp.isinf(a[i]) and xp.isinf(b[i]):   # doubly-infinite
+            double_infinite_count += 1
+        elif xp.isinf(a[i]) != xp.isinf(b[i]):  # exclusive or, so semi-infinite
+            semi_infinite_count += 1
+
+    return (math.sqrt(math.pi) ** ndim) / (
+        2**semi_infinite_count * xp.prod(alphas, axis=-1)
+    )
+
+
+def f_gaussian_random_args(rng, shape, xp):
+    alphas = xp.asarray(rng.random(shape))
+
+    # If alphas are very close to 0 this makes the problem very difficult due to large
+    # values of ``f``.
+    alphas *= 100
+
+    return (alphas,)
+
+
+def f_modified_gaussian(x_arr, n, xp):
+    r"""
+    .. math::
+
+        f(x, y, z, w) = x^n \sqrt{y} \exp(-y-z^2-w^2)
+    """
+    x, y, z, w = x_arr[:, 0], x_arr[:, 1], x_arr[:, 2], x_arr[:, 3]
+    res = (x ** n[:, None]) * xp.sqrt(y) * xp.exp(-y-z**2-w**2)
+
+    return res.T
+
+
+def f_modified_gaussian_exact(a, b, n, xp):
+    # Exact only for the limits
+    #   a = (0, 0, -oo, -oo)
+    #   b = (1, oo, oo, oo)
+    # but defined here as a function to match the format of the other integrands.
+    return 1/(2 + 2*n) * math.pi ** (3/2)
+
+
+def f_with_problematic_points(x_arr, points, xp):
+    """
+    This emulates a function with a list of singularities given by `points`.
+
+    If no `x_arr` are one of the `points`, then this function returns 1.
+    """
+
+    for point in points:
+        if xp.any(x_arr == point):
+            raise ValueError("called with a problematic point")
+
+    return xp.ones(x_arr.shape[0])
+
+
+@make_xp_test_case(cubature)
+class TestCubature:
+    """
+    Tests related to the interface of `cubature`.
+    """
+
+    @pytest.mark.parametrize("rule_str", [
+        "gauss-kronrod",
+        "genz-malik",
+        "gk21",
+        "gk15",
+    ])
+    def test_pass_str(self, rule_str, xp):
+        n = xp.arange(5, dtype=xp.float64)
+        a = xp.asarray([0, 0], dtype=xp.float64)
+        b = xp.asarray([2, 2], dtype=xp.float64)
+
+        res = cubature(basic_nd_integrand, a, b, rule=rule_str, args=(n, xp))
+
+        xp_assert_close(
+            res.estimate,
+            basic_nd_integrand_exact(n, xp),
+            rtol=1e-8,
+            atol=0,
+        )
+
+    def test_pass_array_like_not_array(self):
+        n = np_compat.arange(5, dtype=np_compat.float64)
+        a = [0]
+        b = [2]
+
+        res = cubature(
+            basic_1d_integrand,
+            a,
+            b,
+            args=(n, np_compat)
+        )
+
+        xp_assert_close(
+            res.estimate,
+            basic_1d_integrand_exact(n, np_compat),
+            rtol=1e-8,
+            atol=0,
+        )
+
+    def test_stops_after_max_subdivisions(self, xp):
+        a = xp.asarray([0])
+        b = xp.asarray([1])
+        rule = BadErrorRule()
+
+        res = cubature(
+            basic_1d_integrand,  # Any function would suffice
+            a,
+            b,
+            rule=rule,
+            max_subdivisions=10,
+            args=(xp.arange(5, dtype=xp.float64), xp),
+        )
+
+        assert res.subdivisions == 10
+        assert res.status == "not_converged"
+
+    def test_a_and_b_must_be_1d(self, xp):
+        a = xp.asarray([[0]], dtype=xp.float64)
+        b = xp.asarray([[1]], dtype=xp.float64)
+
+        with pytest.raises(Exception, match="`a` and `b` must be 1D arrays"):
+            cubature(basic_1d_integrand, a, b, args=(xp,))
+
+    def test_a_and_b_must_be_nonempty(self, xp):
+        a = xp.asarray([])
+        b = xp.asarray([])
+
+        with pytest.raises(Exception, match="`a` and `b` must be nonempty"):
+            cubature(basic_1d_integrand, a, b, args=(xp,))
+
+    def test_zero_width_limits(self, xp):
+        n = xp.arange(5, dtype=xp.float64)
+
+        a = xp.asarray([0], dtype=xp.float64)
+        b = xp.asarray([0], dtype=xp.float64)
+
+        res = cubature(
+            basic_1d_integrand,
+            a,
+            b,
+            args=(n, xp),
+        )
+
+        xp_assert_close(
+            res.estimate,
+            xp.asarray([[0], [0], [0], [0], [0]], dtype=xp.float64),
+            rtol=1e-8,
+            atol=0,
+        )
+
+    def test_limits_other_way_around(self, xp):
+        n = xp.arange(5, dtype=xp.float64)
+
+        a = xp.asarray([2], dtype=xp.float64)
+        b = xp.asarray([0], dtype=xp.float64)
+
+        res = cubature(
+            basic_1d_integrand,
+            a,
+            b,
+            args=(n, xp),
+        )
+
+        xp_assert_close(
+            res.estimate,
+            -basic_1d_integrand_exact(n, xp),
+            rtol=1e-8,
+            atol=0,
+        )
+
+    def test_result_dtype_promoted_correctly(self, xp):
+        result_dtype = cubature(
+            basic_1d_integrand,
+            xp.asarray([0], dtype=xp.float64),
+            xp.asarray([1], dtype=xp.float64),
+            points=[],
+            args=(xp.asarray([1], dtype=xp.float64), xp),
+        ).estimate.dtype
+
+        assert result_dtype == xp.float64
+
+        result_dtype = cubature(
+            basic_1d_integrand,
+            xp.asarray([0], dtype=xp.float32),
+            xp.asarray([1], dtype=xp.float32),
+            rtol=1e-7,
+            points=[],
+            args=(xp.asarray([1], dtype=xp.float32), xp),
+        ).estimate.dtype
+
+        assert result_dtype == xp.float32
+
+        result_dtype = cubature(
+            basic_1d_integrand,
+            xp.asarray([0], dtype=xp.float32),
+            xp.asarray([1], dtype=xp.float64),
+            points=[],
+            args=(xp.asarray([1], dtype=xp.float32), xp),
+        ).estimate.dtype
+
+        assert result_dtype == xp.float64
+
+
+@make_xp_test_case(cubature)
+@pytest.mark.parametrize("rtol", [1e-4])
+@pytest.mark.parametrize("atol", [1e-5])
+@pytest.mark.parametrize("rule", [
+    "gk15",
+    "gk21",
+    "genz-malik",
+])
+class TestCubatureProblems:
+    """
+    Tests that `cubature` gives the correct answer.
+    """
+
+    @skip_xp_backends("dask.array",
+                      reason="Dask hangs/takes a long time for some test cases")
+    @pytest.mark.parametrize("problem", [
+        # -- f1 --
+        (
+            # Function to integrate, like `f(x, *args)`
+            genz_malik_1980_f_1,
+
+            # Exact solution, like `exact(a, b, *args)`
+            genz_malik_1980_f_1_exact,
+
+            # Coordinates of `a`
+            [0],
+
+            # Coordinates of `b`
+            [10],
+
+            # Arguments to pass to `f` and `exact`
+            (
+                1/4,
+                [5],
+            )
+        ),
+        (
+            genz_malik_1980_f_1,
+            genz_malik_1980_f_1_exact,
+            [0, 0],
+            [1, 1],
+            (
+                1/4,
+                [2, 4],
+            ),
+        ),
+        (
+            genz_malik_1980_f_1,
+            genz_malik_1980_f_1_exact,
+            [0, 0],
+            [5, 5],
+            (
+                1/2,
+                [2, 4],
+            )
+        ),
+        (
+            genz_malik_1980_f_1,
+            genz_malik_1980_f_1_exact,
+            [0, 0, 0],
+            [5, 5, 5],
+            (
+                1/2,
+                [1, 1, 1],
+            )
+        ),
+
+        # -- f2 --
+        (
+            genz_malik_1980_f_2,
+            genz_malik_1980_f_2_exact,
+            [-1],
+            [1],
+            (
+                [5],
+                [4],
+            )
+        ),
+        (
+            genz_malik_1980_f_2,
+            genz_malik_1980_f_2_exact,
+
+            [0, 0],
+            [10, 50],
+            (
+                [-3, 3],
+                [-2, 2],
+            ),
+        ),
+        (
+            genz_malik_1980_f_2,
+            genz_malik_1980_f_2_exact,
+            [0, 0, 0],
+            [1, 1, 1],
+            (
+                [1, 1, 1],
+                [1, 1, 1],
+            )
+        ),
+        (
+            genz_malik_1980_f_2,
+            genz_malik_1980_f_2_exact,
+            [0, 0, 0],
+            [1, 1, 1],
+            (
+                [2, 3, 4],
+                [2, 3, 4],
+            )
+        ),
+        (
+            genz_malik_1980_f_2,
+            genz_malik_1980_f_2_exact,
+            [-1, -1, -1],
+            [1, 1, 1],
+            (
+                [1, 1, 1],
+                [2, 2, 2],
+            )
+        ),
+        (
+            genz_malik_1980_f_2,
+            genz_malik_1980_f_2_exact,
+            [-1, -1, -1, -1],
+            [1, 1, 1, 1],
+            (
+                [1, 1, 1, 1],
+                [1, 1, 1, 1],
+            )
+        ),
+
+        # -- f3 --
+        (
+            genz_malik_1980_f_3,
+            genz_malik_1980_f_3_exact,
+            [-1],
+            [1],
+            (
+                [1/2],
+            ),
+        ),
+        (
+            genz_malik_1980_f_3,
+            genz_malik_1980_f_3_exact,
+            [0, -1],
+            [1, 1],
+            (
+                [5, 5],
+            ),
+        ),
+        (
+            genz_malik_1980_f_3,
+            genz_malik_1980_f_3_exact,
+            [-1, -1, -1],
+            [1, 1, 1],
+            (
+                [1, 1, 1],
+            ),
+        ),
+
+        # -- f4 --
+        (
+            genz_malik_1980_f_4,
+            genz_malik_1980_f_4_exact,
+            [0],
+            [2],
+            (
+                [1],
+            ),
+        ),
+        (
+            genz_malik_1980_f_4,
+            genz_malik_1980_f_4_exact,
+            [0, 0],
+            [2, 1],
+            ([1, 1],),
+        ),
+        (
+            genz_malik_1980_f_4,
+            genz_malik_1980_f_4_exact,
+            [0, 0, 0],
+            [1, 1, 1],
+            ([1, 1, 1],),
+        ),
+
+        # -- f5 --
+        (
+            genz_malik_1980_f_5,
+            genz_malik_1980_f_5_exact,
+            [-1],
+            [1],
+            (
+                [-2],
+                [2],
+            ),
+        ),
+        (
+            genz_malik_1980_f_5,
+            genz_malik_1980_f_5_exact,
+            [-1, -1],
+            [1, 1],
+            (
+                [2, 3],
+                [4, 5],
+            ),
+        ),
+        (
+            genz_malik_1980_f_5,
+            genz_malik_1980_f_5_exact,
+            [-1, -1],
+            [1, 1],
+            (
+                [-1, 1],
+                [0, 0],
+            ),
+        ),
+        (
+            genz_malik_1980_f_5,
+            genz_malik_1980_f_5_exact,
+            [-1, -1, -1],
+            [1, 1, 1],
+            (
+                [1, 1, 1],
+                [1, 1, 1],
+            ),
+        ),
+    ])
+    def test_scalar_output(self, problem, rule, rtol, atol, xp):
+        f, exact, a, b, args = problem
+
+        a = xp.asarray(a, dtype=xp.float64)
+        b = xp.asarray(b, dtype=xp.float64)
+        args = tuple(xp.asarray(arg, dtype=xp.float64) for arg in args)
+
+        ndim = xp_size(a)
+
+        if rule == "genz-malik" and ndim < 2:
+            pytest.skip("Genz-Malik cubature does not support 1D integrals")
+
+        res = cubature(
+            f,
+            a,
+            b,
+            rule=rule,
+            rtol=rtol,
+            atol=atol,
+            args=(*args, xp),
+        )
+
+        assert res.status == "converged"
+
+        est = res.estimate
+        exact_sol = exact(a, b, *args, xp)
+
+        xp_assert_close(
+            est,
+            exact_sol,
+            rtol=rtol,
+            atol=atol,
+            err_msg=f"estimate_error={res.error}, subdivisions={res.subdivisions}",
+        )
+
+    @skip_xp_backends("dask.array",
+                      reason="Dask hangs/takes a long time for some test cases")
+    @pytest.mark.parametrize("problem", [
+        (
+            # Function to integrate, like `f(x, *args)`
+            genz_malik_1980_f_1,
+
+            # Exact solution, like `exact(a, b, *args)`
+            genz_malik_1980_f_1_exact,
+
+            # Function that generates random args of a certain shape.
+            genz_malik_1980_f_1_random_args,
+        ),
+        (
+            genz_malik_1980_f_2,
+            genz_malik_1980_f_2_exact,
+            genz_malik_1980_f_2_random_args,
+        ),
+        (
+            genz_malik_1980_f_3,
+            genz_malik_1980_f_3_exact,
+            genz_malik_1980_f_3_random_args
+        ),
+        (
+            genz_malik_1980_f_4,
+            genz_malik_1980_f_4_exact,
+            genz_malik_1980_f_4_random_args
+        ),
+        (
+            genz_malik_1980_f_5,
+            genz_malik_1980_f_5_exact,
+            genz_malik_1980_f_5_random_args,
+        ),
+    ])
+    @pytest.mark.parametrize("shape", [
+        (2,),
+        (3,),
+        (4,),
+        (1, 2),
+        (1, 3),
+        (1, 4),
+        (3, 2),
+        (3, 4, 2),
+        (2, 1, 3),
+    ])
+    def test_array_output(self, problem, rule, shape, rtol, atol, xp):
+        rng = np_compat.random.default_rng(1)
+        ndim = shape[-1]
+
+        if rule == "genz-malik" and ndim < 2:
+            pytest.skip("Genz-Malik cubature does not support 1D integrals")
+
+        if rule == "genz-malik" and ndim >= 5:
+            pytest.mark.slow("Gauss-Kronrod is slow in >= 5 dim")
+
+        f, exact, random_args = problem
+        args = random_args(rng, shape, xp)
+
+        a = xp.asarray([0] * ndim, dtype=xp.float64)
+        b = xp.asarray([1] * ndim, dtype=xp.float64)
+
+        res = cubature(
+            f,
+            a,
+            b,
+            rule=rule,
+            rtol=rtol,
+            atol=atol,
+            args=(*args, xp),
+        )
+
+        est = res.estimate
+        exact_sol = exact(a, b, *args, xp)
+
+        xp_assert_close(
+            est,
+            exact_sol,
+            rtol=rtol,
+            atol=atol,
+            err_msg=f"estimate_error={res.error}, subdivisions={res.subdivisions}",
+        )
+
+        err_msg = (f"estimate_error={res.error}, "
+                   f"subdivisions= {res.subdivisions}, "
+                   f"true_error={xp.abs(res.estimate - exact_sol)}")
+        assert res.status == "converged", err_msg
+
+        assert res.estimate.shape == shape[:-1]
+
+    @pytest.mark.parametrize("problem", [
+        (
+            # Function to integrate
+            lambda x, xp: x,
+
+            # Exact value
+            [50.0],
+
+            # Coordinates of `a`
+            [0],
+
+            # Coordinates of `b`
+            [10],
+
+            # Points by which to split up the initial region
+            None,
+        ),
+        (
+            lambda x, xp: xp.sin(x)/x,
+            [2.551496047169878],  # si(1) + si(2),
+            [-1],
+            [2],
+            [
+                [0.0],
+            ],
+        ),
+        (
+            lambda x, xp: xp.ones((x.shape[0], 1)),
+            [1.0],
+            [0, 0, 0],
+            [1, 1, 1],
+            [
+                [0.5, 0.5, 0.5],
+            ],
+        ),
+        (
+            lambda x, xp: xp.ones((x.shape[0], 1)),
+            [1.0],
+            [0, 0, 0],
+            [1, 1, 1],
+            [
+                [0.25, 0.25, 0.25],
+                [0.5, 0.5, 0.5],
+            ],
+        ),
+        (
+            lambda x, xp: xp.ones((x.shape[0], 1)),
+            [1.0],
+            [0, 0, 0],
+            [1, 1, 1],
+            [
+                [0.1, 0.25, 0.5],
+                [0.25, 0.25, 0.25],
+                [0.5, 0.5, 0.5],
+            ],
+        )
+    ])
+    def test_break_points(self, problem, rule, rtol, atol, xp):
+        f, exact, a, b, points = problem
+
+        a = xp.asarray(a, dtype=xp.float64)
+        b = xp.asarray(b, dtype=xp.float64)
+        exact = xp.asarray(exact, dtype=xp.float64)
+
+        if points is not None:
+            points = [xp.asarray(point, dtype=xp.float64) for point in points]
+
+        ndim = xp_size(a)
+
+        if rule == "genz-malik" and ndim < 2:
+            pytest.skip("Genz-Malik cubature does not support 1D integrals")
+
+        if rule == "genz-malik" and ndim >= 5:
+            pytest.mark.slow("Gauss-Kronrod is slow in >= 5 dim")
+
+        res = cubature(
+            f,
+            a,
+            b,
+            rule=rule,
+            rtol=rtol,
+            atol=atol,
+            points=points,
+            args=(xp,),
+        )
+
+        xp_assert_close(
+            res.estimate,
+            exact,
+            rtol=rtol,
+            atol=atol,
+            err_msg=f"estimate_error={res.error}, subdivisions={res.subdivisions}",
+            check_dtype=False,
+        )
+
+        err_msg = (f"estimate_error={res.error}, "
+                   f"subdivisions= {res.subdivisions}, "
+                   f"true_error={xp.abs(res.estimate - exact)}")
+        assert res.status == "converged", err_msg
+
+    @pytest.mark.skip_xp_backends('jax.numpy', reason=boolean_index_skip_reason)
+    @pytest.mark.skip_xp_backends('dask.array', reason=boolean_index_skip_reason)
+    @pytest.mark.parametrize("problem", [
+        (
+            # Function to integrate
+            f_gaussian,
+
+            # Exact solution
+            f_gaussian_exact,
+
+            # Arguments passed to f
+            f_gaussian_random_args,
+            (1, 1),
+
+            # Limits, have to match the shape of the arguments
+            [-math.inf],  # a
+            [math.inf],   # b
+        ),
+        (
+            f_gaussian,
+            f_gaussian_exact,
+            f_gaussian_random_args,
+            (2, 2),
+            [-math.inf, -math.inf],
+            [math.inf, math.inf],
+        ),
+        (
+            f_gaussian,
+            f_gaussian_exact,
+            f_gaussian_random_args,
+            (1, 1),
+            [0],
+            [math.inf],
+        ),
+        (
+            f_gaussian,
+            f_gaussian_exact,
+            f_gaussian_random_args,
+            (1, 1),
+            [-math.inf],
+            [0],
+        ),
+        (
+            f_gaussian,
+            f_gaussian_exact,
+            f_gaussian_random_args,
+            (2, 2),
+            [0, 0],
+            [math.inf, math.inf],
+        ),
+        (
+            f_gaussian,
+            f_gaussian_exact,
+            f_gaussian_random_args,
+            (2, 2),
+            [0, -math.inf],
+            [math.inf, math.inf],
+        ),
+        (
+            f_gaussian,
+            f_gaussian_exact,
+            f_gaussian_random_args,
+            (1, 4),
+            [0, 0, -math.inf, -math.inf],
+            [math.inf, math.inf, math.inf, math.inf],
+        ),
+        (
+            f_gaussian,
+            f_gaussian_exact,
+            f_gaussian_random_args,
+            (1, 4),
+            [-math.inf, -math.inf, -math.inf, -math.inf],
+            [0, 0, math.inf, math.inf],
+        ),
+        (
+            lambda x, xp: 1/xp.prod(x, axis=-1)**2,
+
+            # Exact only for the below limits, not for general `a` and `b`.
+            lambda a, b, xp: xp.asarray(1/6, dtype=xp.float64),
+
+            # Arguments
+            lambda rng, shape, xp: tuple(),
+            tuple(),
+
+            [1, -math.inf, 3],
+            [math.inf, -2, math.inf],
+        ),
+
+        # This particular problem can be slow
+        pytest.param(
+            (
+                # f(x, y, z, w) = x^n * sqrt(y) * exp(-y-z**2-w**2) for n in [0,1,2,3]
+                f_modified_gaussian,
+
+                # This exact solution is for the below limits, not in general
+                f_modified_gaussian_exact,
+
+                # Constant arguments
+                lambda rng, shape, xp: (xp.asarray([0, 1, 2, 3, 4], dtype=xp.float64),),
+                tuple(),
+
+                [0, 0, -math.inf, -math.inf],
+                [1, math.inf, math.inf, math.inf]
+            ),
+
+            marks=pytest.mark.xslow,
+        ),
+    ])
+    def test_infinite_limits(self, problem, rule, rtol, atol, xp):
+        rng = np_compat.random.default_rng(1)
+        f, exact, random_args_func, random_args_shape, a, b = problem
+
+        a = xp.asarray(a, dtype=xp.float64)
+        b = xp.asarray(b, dtype=xp.float64)
+        args = random_args_func(rng, random_args_shape, xp)
+
+        ndim = xp_size(a)
+
+        if rule == "genz-malik" and ndim < 2:
+            pytest.skip("Genz-Malik cubature does not support 1D integrals")
+
+        if rule == "genz-malik" and ndim >= 4:
+            pytest.mark.slow("Genz-Malik is slow in >= 5 dim")
+
+        if rule == "genz-malik" and ndim >= 4 and is_array_api_strict(xp):
+            pytest.mark.xslow("Genz-Malik very slow for array_api_strict in >= 4 dim")
+
+        res = cubature(
+            f,
+            a,
+            b,
+            rule=rule,
+            rtol=rtol,
+            atol=atol,
+            args=(*args, xp),
+        )
+
+        assert res.status == "converged"
+
+        xp_assert_close(
+            res.estimate,
+            exact(a, b, *args, xp),
+            rtol=rtol,
+            atol=atol,
+            err_msg=f"error_estimate={res.error}, subdivisions={res.subdivisions}",
+            check_0d=False,
+        )
+
+    @pytest.mark.skip_xp_backends('jax.numpy', reason=boolean_index_skip_reason)
+    @pytest.mark.skip_xp_backends('dask.array', reason=boolean_index_skip_reason)
+    @pytest.mark.parametrize("problem", [
+        (
+            # Function to integrate
+            lambda x, xp: (xp.sin(x) / x)**8,
+
+            # Exact value
+            [151/315 * math.pi],
+
+            # Limits
+            [-math.inf],
+            [math.inf],
+
+            # Breakpoints
+            [[0]],
+
+        ),
+        (
+            # Function to integrate
+            lambda x, xp: (xp.sin(x[:, 0]) / x[:, 0])**8,
+
+            # Exact value
+            151/315 * math.pi,
+
+            # Limits
+            [-math.inf, 0],
+            [math.inf, 1],
+
+            # Breakpoints
+            [[0, 0.5]],
+
+        )
+    ])
+    def test_infinite_limits_and_break_points(self, problem, rule, rtol, atol, xp):
+        f, exact, a, b, points = problem
+
+        a = xp.asarray(a, dtype=xp.float64)
+        b = xp.asarray(b, dtype=xp.float64)
+        exact = xp.asarray(exact, dtype=xp.float64)
+
+        ndim = xp_size(a)
+
+        if rule == "genz-malik" and ndim < 2:
+            pytest.skip("Genz-Malik cubature does not support 1D integrals")
+
+        if points is not None:
+            points = [xp.asarray(point, dtype=xp.float64) for point in points]
+
+        res = cubature(
+            f,
+            a,
+            b,
+            rule=rule,
+            rtol=rtol,
+            atol=atol,
+            points=points,
+            args=(xp,),
+        )
+
+        assert res.status == "converged"
+
+        xp_assert_close(
+            res.estimate,
+            exact,
+            rtol=rtol,
+            atol=atol,
+            err_msg=f"error_estimate={res.error}, subdivisions={res.subdivisions}",
+            check_0d=False,
+        )
+
+
+@pytest.mark.uses_xp_capabilities(False, reason="private")
+class TestRules:
+    """
+    Tests related to the general Rule interface (currently private).
+    """
+
+    @pytest.mark.parametrize("problem", [
+        (
+            # 2D problem, 1D rule
+            [0, 0],
+            [1, 1],
+            GaussKronrodQuadrature,
+            (21,),
+        ),
+        (
+            # 1D problem, 2D rule
+            [0],
+            [1],
+            GenzMalikCubature,
+            (2,),
+        )
+    ])
+    def test_incompatible_dimension_raises_error(self, problem, xp):
+        a, b, quadrature, quadrature_args = problem
+        rule = quadrature(*quadrature_args, xp=xp)
+
+        a = xp.asarray(a, dtype=xp.float64)
+        b = xp.asarray(b, dtype=xp.float64)
+
+        with pytest.raises(Exception, match="incompatible dimension"):
+            rule.estimate(basic_1d_integrand, a, b, args=(xp,))
+
+    def test_estimate_with_base_classes_raise_error(self, xp):
+        a = xp.asarray([0])
+        b = xp.asarray([1])
+
+        for base_class in [Rule(), FixedRule()]:
+            with pytest.raises(Exception):
+                base_class.estimate(basic_1d_integrand, a, b, args=(xp,))
+
+
+@pytest.mark.uses_xp_capabilities(False, reason="private")
+class TestRulesQuadrature:
+    """
+    Tests underlying quadrature rules (ndim == 1).
+    """
+
+    @pytest.mark.parametrize(("rule", "rule_args"), [
+        (GaussLegendreQuadrature, (3,)),
+        (GaussLegendreQuadrature, (5,)),
+        (GaussLegendreQuadrature, (10,)),
+        (GaussKronrodQuadrature, (15,)),
+        (GaussKronrodQuadrature, (21,)),
+    ])
+    def test_base_1d_quadratures_simple(self, rule, rule_args, xp):
+        quadrature = rule(*rule_args, xp=xp)
+
+        n = xp.arange(5, dtype=xp.float64)
+
+        def f(x):
+            x_reshaped = xp.reshape(x, (-1, 1, 1))
+            n_reshaped = xp.reshape(n, (1, -1, 1))
+
+            return x_reshaped**n_reshaped
+
+        a = xp.asarray([0], dtype=xp.float64)
+        b = xp.asarray([2], dtype=xp.float64)
+
+        exact = xp.reshape(2**(n+1)/(n+1), (-1, 1))
+        estimate = quadrature.estimate(f, a, b)
+
+        xp_assert_close(
+            estimate,
+            exact,
+            rtol=1e-8,
+            atol=0,
+        )
+
+    @pytest.mark.parametrize(("rule_pair", "rule_pair_args"), [
+        ((GaussLegendreQuadrature, GaussLegendreQuadrature), (10, 5)),
+    ])
+    def test_base_1d_quadratures_error_from_difference(self, rule_pair, rule_pair_args,
+                                                       xp):
+        n = xp.arange(5, dtype=xp.float64)
+        a = xp.asarray([0], dtype=xp.float64)
+        b = xp.asarray([2], dtype=xp.float64)
+
+        higher = rule_pair[0](rule_pair_args[0], xp=xp)
+        lower = rule_pair[1](rule_pair_args[1], xp=xp)
+
+        rule = NestedFixedRule(higher, lower)
+        res = cubature(
+            basic_1d_integrand,
+            a, b,
+            rule=rule,
+            rtol=1e-8,
+            args=(n, xp),
+        )
+
+        xp_assert_close(
+            res.estimate,
+            basic_1d_integrand_exact(n, xp),
+            rtol=1e-8,
+            atol=0,
+        )
+
+    @pytest.mark.parametrize("quadrature", [
+        GaussLegendreQuadrature
+    ])
+    def test_one_point_fixed_quad_impossible(self, quadrature, xp):
+        with pytest.raises(Exception):
+            quadrature(1, xp=xp)
+
+
+@pytest.mark.uses_xp_capabilities(False, reason="private")
+class TestRulesCubature:
+    """
+    Tests underlying cubature rules (ndim >= 2).
+    """
+
+    @pytest.mark.parametrize("ndim", range(2, 11))
+    def test_genz_malik_func_evaluations(self, ndim, xp):
+        """
+        Tests that the number of function evaluations required for Genz-Malik cubature
+        matches the number in Genz and Malik 1980.
+        """
+
+        nodes, _ = GenzMalikCubature(ndim, xp=xp).nodes_and_weights
+
+        assert nodes.shape[0] == (2**ndim) + 2*ndim**2 + 2*ndim + 1
+
+    def test_genz_malik_1d_raises_error(self, xp):
+        with pytest.raises(Exception, match="only defined for ndim >= 2"):
+            GenzMalikCubature(1, xp=xp)
+
+
+@pytest.mark.skip_xp_backends('jax.numpy', reason=boolean_index_skip_reason)
+@pytest.mark.skip_xp_backends('dask.array', reason=boolean_index_skip_reason)
+@pytest.mark.uses_xp_capabilities(False, reason="private")
+class TestTransformations:
+    @pytest.mark.parametrize(("a", "b", "points"), [
+        (
+            [0, 1, -math.inf],
+            [1, math.inf, math.inf],
+            [
+                [1, 1, 1],
+                [0.5, 10, 10],
+            ]
+        )
+    ])
+    def test_infinite_limits_maintains_points(self, a, b, points, xp):
+        """
+        Test that break points are correctly mapped under the _InfiniteLimitsTransform
+        transformation.
+        """
+
+        points = [xp.asarray(p, dtype=xp.float64) for p in points]
+
+        f_transformed = _InfiniteLimitsTransform(
+            # Bind `points` and `xp` argument in f
+            lambda x: f_with_problematic_points(x, points, xp),
+            xp.asarray(a, dtype=xp.float64),
+            xp.asarray(b, dtype=xp.float64),
+            xp=xp,
+        )
+
+        for point in points:
+            transformed_point = f_transformed.inv(xp.reshape(point, (1, -1)))
+
+            with pytest.raises(Exception, match="called with a problematic point"):
+                f_transformed(transformed_point)
+
+
+class BadErrorRule(Rule):
+    """
+    A rule with fake high error so that cubature will keep on subdividing.
+    """
+
+    def estimate(self, f, a, b, args=()):
+        xp = array_namespace(a, b)
+        underlying = GaussLegendreQuadrature(10, xp=xp)
+
+        return underlying.estimate(f, a, b, args)
+
+    def estimate_error(self, f, a, b, args=()):
+        xp = array_namespace(a, b)
+        return xp.asarray(1e6, dtype=xp.float64)
diff --git a/.venv/lib/python3.12/site-packages/scipy/integrate/tests/test_integrate.py b/.venv/lib/python3.12/site-packages/scipy/integrate/tests/test_integrate.py
new file mode 100644
index 0000000000000000000000000000000000000000..00675c1ae8966f74fe50bc162af32e4c6d3076fb
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/integrate/tests/test_integrate.py
@@ -0,0 +1,865 @@
+# Authors: Nils Wagner, Ed Schofield, Pauli Virtanen, John Travers
+"""
+Tests for numerical integration.
+"""
+import numpy as np
+from numpy import (arange, zeros, array, dot, sqrt, cos, sin, eye, pi, exp,
+                   allclose)
+
+from numpy.testing import (
+    assert_, assert_array_almost_equal,
+    assert_allclose, assert_array_equal, assert_equal)
+import pytest
+from pytest import raises as assert_raises
+from scipy.integrate import odeint, ode, complex_ode
+
+#------------------------------------------------------------------------------
+# Test ODE integrators
+#------------------------------------------------------------------------------
+
+
+class TestOdeint:
+    # Check integrate.odeint
+
+    def _do_problem(self, problem):
+        t = arange(0.0, problem.stop_t, 0.05)
+
+        # Basic case
+        z, infodict = odeint(problem.f, problem.z0, t, full_output=True)
+        assert_(problem.verify(z, t))
+
+        # Use tfirst=True
+        z, infodict = odeint(lambda t, y: problem.f(y, t), problem.z0, t,
+                             full_output=True, tfirst=True)
+        assert_(problem.verify(z, t))
+
+        if hasattr(problem, 'jac'):
+            # Use Dfun
+            z, infodict = odeint(problem.f, problem.z0, t, Dfun=problem.jac,
+                                 full_output=True)
+            assert_(problem.verify(z, t))
+
+            # Use Dfun and tfirst=True
+            z, infodict = odeint(lambda t, y: problem.f(y, t), problem.z0, t,
+                                 Dfun=lambda t, y: problem.jac(y, t),
+                                 full_output=True, tfirst=True)
+            assert_(problem.verify(z, t))
+
+    def test_odeint(self):
+        for problem_cls in PROBLEMS:
+            problem = problem_cls()
+            if problem.cmplx:
+                continue
+            self._do_problem(problem)
+
+
+class TestODEClass:
+
+    ode_class = None   # Set in subclass.
+
+    def _do_problem(self, problem, integrator, method='adams'):
+
+        # ode has callback arguments in different order than odeint
+        def f(t, z):
+            return problem.f(z, t)
+        jac = None
+        if hasattr(problem, 'jac'):
+            def jac(t, z):
+                return problem.jac(z, t)
+
+        integrator_params = {}
+        if problem.lband is not None or problem.uband is not None:
+            integrator_params['uband'] = problem.uband
+            integrator_params['lband'] = problem.lband
+
+        ig = self.ode_class(f, jac)
+        ig.set_integrator(integrator,
+                          atol=problem.atol/10,
+                          rtol=problem.rtol/10,
+                          method=method,
+                          **integrator_params)
+
+        ig.set_initial_value(problem.z0, t=0.0)
+        z = ig.integrate(problem.stop_t)
+
+        assert_array_equal(z, ig.y)
+        assert_(ig.successful(), (problem, method))
+        assert_(ig.get_return_code() > 0, (problem, method))
+        assert_(problem.verify(array([z]), problem.stop_t), (problem, method))
+
+
+class TestOde(TestODEClass):
+
+    ode_class = ode
+
+    def test_vode(self):
+        # Check the vode solver
+        for problem_cls in PROBLEMS:
+            problem = problem_cls()
+            if problem.cmplx:
+                continue
+            if not problem.stiff:
+                self._do_problem(problem, 'vode', 'adams')
+            self._do_problem(problem, 'vode', 'bdf')
+
+    def test_zvode(self):
+        # Check the zvode solver
+        for problem_cls in PROBLEMS:
+            problem = problem_cls()
+            if not problem.stiff:
+                self._do_problem(problem, 'zvode', 'adams')
+            self._do_problem(problem, 'zvode', 'bdf')
+
+    def test_lsoda(self):
+        # Check the lsoda solver
+        for problem_cls in PROBLEMS:
+            problem = problem_cls()
+            if problem.cmplx:
+                continue
+            self._do_problem(problem, 'lsoda')
+
+    def test_dopri5(self):
+        # Check the dopri5 solver
+        for problem_cls in PROBLEMS:
+            problem = problem_cls()
+            if problem.cmplx:
+                continue
+            if problem.stiff:
+                continue
+            if hasattr(problem, 'jac'):
+                continue
+            self._do_problem(problem, 'dopri5')
+
+    def test_dop853(self):
+        # Check the dop853 solver
+        for problem_cls in PROBLEMS:
+            problem = problem_cls()
+            if problem.cmplx:
+                continue
+            if problem.stiff:
+                continue
+            if hasattr(problem, 'jac'):
+                continue
+            self._do_problem(problem, 'dop853')
+
+    def test_concurrent_fail(self):
+        # Test concurrent usage behavior for different solvers
+        # All solvers (vode, zvode, lsoda) now support concurrent usage
+        # with state persistence via explicit state parameters
+        for sol in ('vode', 'zvode', 'lsoda'):
+            def f(t, y):
+                return 1.0
+
+            r = ode(f).set_integrator(sol)
+            r.set_initial_value(0, 0)
+
+            r2 = ode(f).set_integrator(sol)
+            r2.set_initial_value(0, 0)
+
+            r.integrate(r.t + 0.1)
+            r2.integrate(r2.t + 0.1)
+
+            # With state persistence, r should still work correctly
+            r.integrate(r.t + 0.1)
+            assert r.successful()
+
+    def test_concurrent_ok(self, num_parallel_threads):
+        def f(t, y):
+            return 1.0
+
+        for k in range(3):
+            for sol in ('vode', 'zvode', 'lsoda', 'dopri5', 'dop853'):
+                if sol in {'vode', 'zvode', 'lsoda'} and num_parallel_threads > 1:
+                    continue
+                r = ode(f).set_integrator(sol)
+                r.set_initial_value(0, 0)
+
+                r2 = ode(f).set_integrator(sol)
+                r2.set_initial_value(0, 0)
+
+                r.integrate(r.t + 0.1)
+                r2.integrate(r2.t + 0.1)
+                r2.integrate(r2.t + 0.1)
+
+                assert_allclose(r.y, 0.1)
+                assert_allclose(r2.y, 0.2)
+
+            for sol in ('dopri5', 'dop853'):
+                r = ode(f).set_integrator(sol)
+                r.set_initial_value(0, 0)
+
+                r2 = ode(f).set_integrator(sol)
+                r2.set_initial_value(0, 0)
+
+                r.integrate(r.t + 0.1)
+                r.integrate(r.t + 0.1)
+                r2.integrate(r2.t + 0.1)
+                r.integrate(r.t + 0.1)
+                r2.integrate(r2.t + 0.1)
+
+                assert_allclose(r.y, 0.3)
+                assert_allclose(r2.y, 0.2)
+
+
+class TestComplexOde(TestODEClass):
+
+    ode_class = complex_ode
+
+    def test_vode(self):
+        # Check the vode solver
+        for problem_cls in PROBLEMS:
+            problem = problem_cls()
+            if not problem.stiff:
+                self._do_problem(problem, 'vode', 'adams')
+            else:
+                self._do_problem(problem, 'vode', 'bdf')
+
+    def test_lsoda(self):
+
+        # Check the lsoda solver
+        for problem_cls in PROBLEMS:
+            problem = problem_cls()
+            self._do_problem(problem, 'lsoda')
+
+    def test_dopri5(self):
+        # Check the dopri5 solver
+        for problem_cls in PROBLEMS:
+            problem = problem_cls()
+            if problem.stiff:
+                continue
+            if hasattr(problem, 'jac'):
+                continue
+            self._do_problem(problem, 'dopri5')
+
+    def test_dop853(self):
+        # Check the dop853 solver
+        for problem_cls in PROBLEMS:
+            problem = problem_cls()
+            if problem.stiff:
+                continue
+            if hasattr(problem, 'jac'):
+                continue
+            self._do_problem(problem, 'dop853')
+
+
+class TestSolout:
+    # Check integrate.ode correctly handles solout for dopri5 and dop853
+    def _run_solout_test(self, integrator):
+        # Check correct usage of solout
+        ts = []
+        ys = []
+        t0 = 0.0
+        tend = 10.0
+        y0 = [1.0, 2.0]
+
+        def solout(t, y):
+            ts.append(t)
+            ys.append(y.copy())
+
+        def rhs(t, y):
+            return [y[0] + y[1], -y[1]**2]
+
+        ig = ode(rhs).set_integrator(integrator)
+        ig.set_solout(solout)
+        ig.set_initial_value(y0, t0)
+        ret = ig.integrate(tend)
+        assert_array_equal(ys[0], y0)
+        assert_array_equal(ys[-1], ret)
+        assert_equal(ts[0], t0)
+        assert_equal(ts[-1], tend)
+
+    def test_solout(self):
+        for integrator in ('dopri5', 'dop853'):
+            self._run_solout_test(integrator)
+
+    def _run_solout_after_initial_test(self, integrator):
+        # Check if solout works even if it is set after the initial value.
+        ts = []
+        ys = []
+        t0 = 0.0
+        tend = 10.0
+        y0 = [1.0, 2.0]
+
+        def solout(t, y):
+            ts.append(t)
+            ys.append(y.copy())
+
+        def rhs(t, y):
+            return [y[0] + y[1], -y[1]**2]
+
+        ig = ode(rhs).set_integrator(integrator)
+        ig.set_initial_value(y0, t0)
+        ig.set_solout(solout)
+        ret = ig.integrate(tend)
+        assert_array_equal(ys[0], y0)
+        assert_array_equal(ys[-1], ret)
+        assert_equal(ts[0], t0)
+        assert_equal(ts[-1], tend)
+
+    def test_solout_after_initial(self):
+        for integrator in ('dopri5', 'dop853'):
+            self._run_solout_after_initial_test(integrator)
+
+    def _run_solout_break_test(self, integrator):
+        # Check correct usage of stopping via solout
+        ts = []
+        ys = []
+        t0 = 0.0
+        tend = 10.0
+        y0 = [1.0, 2.0]
+
+        def solout(t, y):
+            ts.append(t)
+            ys.append(y.copy())
+            if t > tend/2.0:
+                return -1
+
+        def rhs(t, y):
+            return [y[0] + y[1], -y[1]**2]
+
+        ig = ode(rhs).set_integrator(integrator)
+        ig.set_solout(solout)
+        ig.set_initial_value(y0, t0)
+        ret = ig.integrate(tend)
+        assert_array_equal(ys[0], y0)
+        assert_array_equal(ys[-1], ret)
+        assert_equal(ts[0], t0)
+        assert_(ts[-1] > tend/2.0)
+        assert_(ts[-1] < tend)
+
+    def test_solout_break(self):
+        for integrator in ('dopri5', 'dop853'):
+            self._run_solout_break_test(integrator)
+
+
+class TestComplexSolout:
+    # Check integrate.ode correctly handles solout for dopri5 and dop853
+    def _run_solout_test(self, integrator):
+        # Check correct usage of solout
+        ts = []
+        ys = []
+        t0 = 0.0
+        tend = 20.0
+        y0 = [0.0]
+
+        def solout(t, y):
+            ts.append(t)
+            ys.append(y.copy())
+
+        def rhs(t, y):
+            return [1.0/(t - 10.0 - 1j)]
+
+        ig = complex_ode(rhs).set_integrator(integrator)
+        ig.set_solout(solout)
+        ig.set_initial_value(y0, t0)
+        ret = ig.integrate(tend)
+        assert_array_equal(ys[0], y0)
+        assert_array_equal(ys[-1], ret)
+        assert_equal(ts[0], t0)
+        assert_equal(ts[-1], tend)
+
+    def test_solout(self):
+        for integrator in ('dopri5', 'dop853'):
+            self._run_solout_test(integrator)
+
+    def _run_solout_break_test(self, integrator):
+        # Check correct usage of stopping via solout
+        ts = []
+        ys = []
+        t0 = 0.0
+        tend = 20.0
+        y0 = [0.0]
+
+        def solout(t, y):
+            ts.append(t)
+            ys.append(y.copy())
+            if t > tend/2.0:
+                return -1
+
+        def rhs(t, y):
+            return [1.0/(t - 10.0 - 1j)]
+
+        ig = complex_ode(rhs).set_integrator(integrator)
+        ig.set_solout(solout)
+        ig.set_initial_value(y0, t0)
+        ret = ig.integrate(tend)
+        assert_array_equal(ys[0], y0)
+        assert_array_equal(ys[-1], ret)
+        assert_equal(ts[0], t0)
+        assert_(ts[-1] > tend/2.0)
+        assert_(ts[-1] < tend)
+
+    def test_solout_break(self):
+        for integrator in ('dopri5', 'dop853'):
+            self._run_solout_break_test(integrator)
+
+
+#------------------------------------------------------------------------------
+# Test problems
+#------------------------------------------------------------------------------
+
+
+class ODE:
+    """
+    ODE problem
+    """
+    stiff = False
+    cmplx = False
+    stop_t = 1
+    z0 = []
+
+    lband = None
+    uband = None
+
+    atol = 1e-6
+    rtol = 1e-5
+
+
+class SimpleOscillator(ODE):
+    r"""
+    Free vibration of a simple oscillator::
+        m \ddot{u} + k u = 0, u(0) = u_0 \dot{u}(0) \dot{u}_0
+    Solution::
+        u(t) = u_0*cos(sqrt(k/m)*t)+\dot{u}_0*sin(sqrt(k/m)*t)/sqrt(k/m)
+    """
+    stop_t = 1 + 0.09
+    z0 = array([1.0, 0.1], float)
+
+    k = 4.0
+    m = 1.0
+
+    def f(self, z, t):
+        tmp = zeros((2, 2), float)
+        tmp[0, 1] = 1.0
+        tmp[1, 0] = -self.k / self.m
+        return dot(tmp, z)
+
+    def verify(self, zs, t):
+        omega = sqrt(self.k / self.m)
+        u = self.z0[0]*cos(omega*t) + self.z0[1]*sin(omega*t)/omega
+        return allclose(u, zs[:, 0], atol=self.atol, rtol=self.rtol)
+
+
+class ComplexExp(ODE):
+    r"""The equation :lm:`\dot u = i u`"""
+    stop_t = 1.23*pi
+    z0 = exp([1j, 2j, 3j, 4j, 5j])
+    cmplx = True
+
+    def f(self, z, t):
+        return 1j*z
+
+    def jac(self, z, t):
+        return 1j*eye(5)
+
+    def verify(self, zs, t):
+        u = self.z0 * exp(1j*t)
+        return allclose(u, zs, atol=self.atol, rtol=self.rtol)
+
+
+class Pi(ODE):
+    r"""Integrate 1/(t + 1j) from t=-10 to t=10"""
+    stop_t = 20
+    z0 = [0]
+    cmplx = True
+
+    def f(self, z, t):
+        return array([1./(t - 10 + 1j)])
+
+    def verify(self, zs, t):
+        u = -2j * np.arctan(10)
+        return allclose(u, zs[-1, :], atol=self.atol, rtol=self.rtol)
+
+
+class CoupledDecay(ODE):
+    r"""
+    3 coupled decays suited for banded treatment
+    (banded mode makes it necessary when N>>3)
+    """
+
+    stiff = True
+    stop_t = 0.5
+    z0 = [5.0, 7.0, 13.0]
+    lband = 1
+    uband = 0
+
+    lmbd = [0.17, 0.23, 0.29]  # fictitious decay constants
+
+    def f(self, z, t):
+        lmbd = self.lmbd
+        return np.array([-lmbd[0]*z[0],
+                         -lmbd[1]*z[1] + lmbd[0]*z[0],
+                         -lmbd[2]*z[2] + lmbd[1]*z[1]])
+
+    def jac(self, z, t):
+        # The full Jacobian is
+        #
+        #    [-lmbd[0]      0         0   ]
+        #    [ lmbd[0]  -lmbd[1]      0   ]
+        #    [    0      lmbd[1]  -lmbd[2]]
+        #
+        # The lower and upper bandwidths are lband=1 and uband=0, resp.
+        # The representation of this array in packed format is
+        #
+        #    [-lmbd[0]  -lmbd[1]  -lmbd[2]]
+        #    [ lmbd[0]   lmbd[1]      0   ]
+
+        lmbd = self.lmbd
+        j = np.zeros((self.lband + self.uband + 1, 3), order='F')
+
+        def set_j(ri, ci, val):
+            j[self.uband + ri - ci, ci] = val
+        set_j(0, 0, -lmbd[0])
+        set_j(1, 0, lmbd[0])
+        set_j(1, 1, -lmbd[1])
+        set_j(2, 1, lmbd[1])
+        set_j(2, 2, -lmbd[2])
+        return j
+
+    def verify(self, zs, t):
+        # Formulae derived by hand
+        lmbd = np.array(self.lmbd)
+        d10 = lmbd[1] - lmbd[0]
+        d21 = lmbd[2] - lmbd[1]
+        d20 = lmbd[2] - lmbd[0]
+        e0 = np.exp(-lmbd[0] * t)
+        e1 = np.exp(-lmbd[1] * t)
+        e2 = np.exp(-lmbd[2] * t)
+        u = np.vstack((
+            self.z0[0] * e0,
+            self.z0[1] * e1 + self.z0[0] * lmbd[0] / d10 * (e0 - e1),
+            self.z0[2] * e2 + self.z0[1] * lmbd[1] / d21 * (e1 - e2) +
+            lmbd[1] * lmbd[0] * self.z0[0] / d10 *
+            (1 / d20 * (e0 - e2) - 1 / d21 * (e1 - e2)))).transpose()
+        return allclose(u, zs, atol=self.atol, rtol=self.rtol)
+
+
+PROBLEMS = [SimpleOscillator, ComplexExp, Pi, CoupledDecay]
+
+#------------------------------------------------------------------------------
+
+
+def f(t, x):
+    dxdt = [x[1], -x[0]]
+    return dxdt
+
+
+def jac(t, x):
+    j = array([[0.0, 1.0],
+               [-1.0, 0.0]])
+    return j
+
+
+def f1(t, x, omega):
+    dxdt = [omega*x[1], -omega*x[0]]
+    return dxdt
+
+
+def jac1(t, x, omega):
+    j = array([[0.0, omega],
+               [-omega, 0.0]])
+    return j
+
+
+def f2(t, x, omega1, omega2):
+    dxdt = [omega1*x[1], -omega2*x[0]]
+    return dxdt
+
+
+def jac2(t, x, omega1, omega2):
+    j = array([[0.0, omega1],
+               [-omega2, 0.0]])
+    return j
+
+
+def fv(t, x, omega):
+    dxdt = [omega[0]*x[1], -omega[1]*x[0]]
+    return dxdt
+
+
+def jacv(t, x, omega):
+    j = array([[0.0, omega[0]],
+               [-omega[1], 0.0]])
+    return j
+
+
+class ODECheckParameterUse:
+    """Call an ode-class solver with several cases of parameter use."""
+
+    # solver_name must be set before tests can be run with this class.
+
+    # Set these in subclasses.
+    solver_name = ''
+    solver_uses_jac = False
+
+    def _get_solver(self, f, jac):
+        solver = ode(f, jac)
+        if self.solver_uses_jac:
+            solver.set_integrator(self.solver_name, atol=1e-9, rtol=1e-7,
+                                  with_jacobian=self.solver_uses_jac)
+        else:
+            # XXX Shouldn't set_integrator *always* accept the keyword arg
+            # 'with_jacobian', and perhaps raise an exception if it is set
+            # to True if the solver can't actually use it?
+            solver.set_integrator(self.solver_name, atol=1e-9, rtol=1e-7)
+        return solver
+
+    def _check_solver(self, solver):
+        ic = [1.0, 0.0]
+        solver.set_initial_value(ic, 0.0)
+        solver.integrate(pi)
+        assert_array_almost_equal(solver.y, [-1.0, 0.0])
+
+    def test_no_params(self):
+        solver = self._get_solver(f, jac)
+        self._check_solver(solver)
+
+    def test_one_scalar_param(self):
+        solver = self._get_solver(f1, jac1)
+        omega = 1.0
+        solver.set_f_params(omega)
+        if self.solver_uses_jac:
+            solver.set_jac_params(omega)
+        self._check_solver(solver)
+
+    def test_two_scalar_params(self):
+        solver = self._get_solver(f2, jac2)
+        omega1 = 1.0
+        omega2 = 1.0
+        solver.set_f_params(omega1, omega2)
+        if self.solver_uses_jac:
+            solver.set_jac_params(omega1, omega2)
+        self._check_solver(solver)
+
+    def test_vector_param(self):
+        solver = self._get_solver(fv, jacv)
+        omega = [1.0, 1.0]
+        solver.set_f_params(omega)
+        if self.solver_uses_jac:
+            solver.set_jac_params(omega)
+        self._check_solver(solver)
+
+    def test_warns_on_failure(self):
+        # Set nsteps small to ensure failure
+        solver = self._get_solver(f, jac)
+        solver.set_integrator(self.solver_name, nsteps=1)
+        ic = [1.0, 0.0]
+        solver.set_initial_value(ic, 0.0)
+        with pytest.warns(UserWarning):
+            solver.integrate(pi)
+
+
+class TestDOPRI5CheckParameterUse(ODECheckParameterUse):
+    solver_name = 'dopri5'
+    solver_uses_jac = False
+
+
+class TestDOP853CheckParameterUse(ODECheckParameterUse):
+    solver_name = 'dop853'
+    solver_uses_jac = False
+
+
+class TestVODECheckParameterUse(ODECheckParameterUse):
+    solver_name = 'vode'
+    solver_uses_jac = True
+
+
+class TestZVODECheckParameterUse(ODECheckParameterUse):
+    solver_name = 'zvode'
+    solver_uses_jac = True
+
+
+class TestLSODACheckParameterUse(ODECheckParameterUse):
+    solver_name = 'lsoda'
+    solver_uses_jac = True
+
+
+def test_odeint_trivial_time():
+    # Test that odeint succeeds when given a single time point
+    # and full_output=True.  This is a regression test for gh-4282.
+    y0 = 1
+    t = [0]
+    y, info = odeint(lambda y, t: -y, y0, t, full_output=True)
+    assert_array_equal(y, np.array([[y0]]))
+
+
+def test_odeint_banded_jacobian():
+    # Test the use of the `Dfun`, `ml` and `mu` options of odeint.
+
+    def func(y, t, c):
+        return c.dot(y)
+
+    def jac(y, t, c):
+        return c
+
+    def jac_transpose(y, t, c):
+        return c.T.copy(order='C')
+
+    def bjac_rows(y, t, c):
+        jac = np.vstack((np.r_[0, np.diag(c, 1)],
+                            np.diag(c),
+                            np.r_[np.diag(c, -1), 0],
+                            np.r_[np.diag(c, -2), 0, 0]))
+        return jac
+
+    def bjac_cols(y, t, c):
+        return bjac_rows(y, t, c).T.copy(order='C')
+
+    c = array([[-205, 0.01, 0.00, 0.0],
+               [0.1, -2.50, 0.02, 0.0],
+               [1e-3, 0.01, -2.0, 0.01],
+               [0.00, 0.00, 0.1, -1.0]])
+
+    y0 = np.ones(4)
+    t = np.array([0, 5, 10, 100])
+
+    # Use the full Jacobian.
+    sol1, info1 = odeint(func, y0, t, args=(c,), full_output=True,
+                         atol=1e-13, rtol=1e-11, mxstep=10000,
+                         Dfun=jac)
+
+    # Use the transposed full Jacobian, with col_deriv=True.
+    sol2, info2 = odeint(func, y0, t, args=(c,), full_output=True,
+                         atol=1e-13, rtol=1e-11, mxstep=10000,
+                         Dfun=jac_transpose, col_deriv=True)
+
+    # Use the banded Jacobian.
+    sol3, info3 = odeint(func, y0, t, args=(c,), full_output=True,
+                         atol=1e-13, rtol=1e-11, mxstep=10000,
+                         Dfun=bjac_rows, ml=2, mu=1)
+
+    # Use the transposed banded Jacobian, with col_deriv=True.
+    sol4, info4 = odeint(func, y0, t, args=(c,), full_output=True,
+                         atol=1e-13, rtol=1e-11, mxstep=10000,
+                         Dfun=bjac_cols, ml=2, mu=1, col_deriv=True)
+
+    assert_allclose(sol1, sol2, err_msg="sol1 != sol2")
+    assert_allclose(sol1, sol3, atol=1e-12, err_msg="sol1 != sol3")
+    assert_allclose(sol3, sol4, err_msg="sol3 != sol4")
+
+    # Verify that the number of jacobian evaluations was the same for the
+    # calls of odeint with a full jacobian and with a banded jacobian. This is
+    # a regression test--there was a bug in the handling of banded jacobians
+    # that resulted in an incorrect jacobian matrix being passed to the LSODA
+    # code.  That would cause errors or excessive jacobian evaluations.
+    assert_array_equal(info1['nje'], info2['nje'])
+    assert_array_equal(info3['nje'], info4['nje'])
+
+    # Test the use of tfirst
+    sol1ty, info1ty = odeint(lambda t, y, c: func(y, t, c), y0, t, args=(c,),
+                             full_output=True, atol=1e-13, rtol=1e-11,
+                             mxstep=10000,
+                             Dfun=lambda t, y, c: jac(y, t, c), tfirst=True)
+    # The code should execute the exact same sequence of floating point
+    # calculations, so these should be exactly equal. We'll be safe and use
+    # a small tolerance.
+    assert_allclose(sol1, sol1ty, rtol=1e-12, err_msg="sol1 != sol1ty")
+
+
+def test_odeint_errors():
+    def sys1d(x, t):
+        return -100*x
+
+    def bad1(x, t):
+        return 1.0/0
+
+    def bad2(x, t):
+        return "foo"
+
+    def bad_jac1(x, t):
+        return 1.0/0
+
+    def bad_jac2(x, t):
+        return [["foo"]]
+
+    def sys2d(x, t):
+        return [-100*x[0], -0.1*x[1]]
+
+    def sys2d_bad_jac(x, t):
+        return [[1.0/0, 0], [0, -0.1]]
+
+    assert_raises(ZeroDivisionError, odeint, bad1, 1.0, [0, 1])
+    assert_raises(ValueError, odeint, bad2, 1.0, [0, 1])
+
+    assert_raises(ZeroDivisionError, odeint, sys1d, 1.0, [0, 1], Dfun=bad_jac1)
+    assert_raises(ValueError, odeint, sys1d, 1.0, [0, 1], Dfun=bad_jac2)
+
+    assert_raises(ZeroDivisionError, odeint, sys2d, [1.0, 1.0], [0, 1],
+                  Dfun=sys2d_bad_jac)
+
+
+def test_odeint_bad_shapes():
+    # Tests of some errors that can occur with odeint.
+
+    def badrhs(x, t):
+        return [1, -1]
+
+    def sys1(x, t):
+        return -100*x
+
+    def badjac(x, t):
+        return [[0, 0, 0]]
+
+    # y0 must be at most 1-d.
+    bad_y0 = [[0, 0], [0, 0]]
+    assert_raises(ValueError, odeint, sys1, bad_y0, [0, 1])
+
+    # t must be at most 1-d.
+    bad_t = [[0, 1], [2, 3]]
+    assert_raises(ValueError, odeint, sys1, [10.0], bad_t)
+
+    # y0 is 10, but badrhs(x, t) returns [1, -1].
+    assert_raises(RuntimeError, odeint, badrhs, 10, [0, 1])
+
+    # shape of array returned by badjac(x, t) is not correct.
+    assert_raises(RuntimeError, odeint, sys1, [10, 10], [0, 1], Dfun=badjac)
+
+
+def test_repeated_t_values():
+    """Regression test for gh-8217."""
+
+    def func(x, t):
+        return -0.25*x
+
+    t = np.zeros(10)
+    sol = odeint(func, [1.], t)
+    assert_array_equal(sol, np.ones((len(t), 1)))
+
+    tau = 4*np.log(2)
+    t = [0]*9 + [tau, 2*tau, 2*tau, 3*tau]
+    sol = odeint(func, [1, 2], t, rtol=1e-12, atol=1e-12)
+    expected_sol = np.array([[1.0, 2.0]]*9 +
+                            [[0.5, 1.0],
+                             [0.25, 0.5],
+                             [0.25, 0.5],
+                             [0.125, 0.25]])
+    assert_allclose(sol, expected_sol)
+
+    # Edge case: empty t sequence.
+    sol = odeint(func, [1.], [])
+    assert_array_equal(sol, np.array([], dtype=np.float64).reshape((0, 1)))
+
+    # t values are not monotonic.
+    assert_raises(ValueError, odeint, func, [1.], [0, 1, 0.5, 0])
+    assert_raises(ValueError, odeint, func, [1, 2, 3], [0, -1, -2, 3])
+
+
+def test_vode_jacobian_convention():
+    # Regression test for gh-24933: VODE Jacobian transposition bug.
+    def f(t, y):
+        return [-0.04*y[0] + 1e4*y[1]*y[2],
+                0.04*y[0] - 1e4*y[1]*y[2] - 3e7*y[1]**2,
+                3e7*y[1]**2]
+
+    def jac(t, y):
+        return np.array([[-0.04,              1e4*y[2],         1e4*y[1]],
+                         [0.04,  -1e4*y[2] - 6e7*y[1],        -1e4*y[1]],
+                         [0.0,               6e7*y[1],              0.0]])
+
+    y0 = [1.0, 0.0, 0.0]
+    # Correct Jac. needs ~124 steps; transposed (bug) needs ~2084. Cap at 150.
+    r = ode(f, jac).set_integrator('vode', method='bdf', rtol=1e-8,
+                                   atol=1e-10, nsteps=150)
+    r.set_initial_value(y0, 0.0)
+    r.integrate(1.0)
+    assert r.successful()
diff --git a/.venv/lib/python3.12/site-packages/scipy/integrate/tests/test_quadpack.py b/.venv/lib/python3.12/site-packages/scipy/integrate/tests/test_quadpack.py
new file mode 100644
index 0000000000000000000000000000000000000000..af55e1af7cea85dbd54302dc612017cff1abd7bb
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/integrate/tests/test_quadpack.py
@@ -0,0 +1,723 @@
+import sys
+import math
+import numpy as np
+from numpy import sqrt, cos, sin, arctan, exp, log, pi
+from numpy.testing import (assert_,
+        assert_allclose, assert_array_less, assert_almost_equal, assert_equal)
+import pytest
+
+from scipy.integrate import quad, dblquad, tplquad, nquad
+from scipy.special import erf, erfc
+from scipy._lib._ccallback import LowLevelCallable
+from scipy._lib._array_api import make_xp_test_case
+
+import ctypes
+import ctypes.util
+from scipy._lib._ccallback_c import sine_ctypes
+
+import scipy.integrate._test_multivariate as clib_test
+
+
+def assert_quad(value_and_err, tabled_value, error_tolerance=1.5e-8):
+    value, err = value_and_err
+    assert_allclose(value, tabled_value, atol=err, rtol=0)
+    if error_tolerance is not None:
+        assert_array_less(err, error_tolerance)
+
+
+def get_clib_test_routine(name, restype, *argtypes):
+    ptr = getattr(clib_test, name)
+    return ctypes.cast(ptr, ctypes.CFUNCTYPE(restype, *argtypes))
+
+
+@make_xp_test_case(quad)
+class TestCtypesQuad:
+    def setup_method(self):
+        if sys.platform == 'win32':
+            files = ['api-ms-win-crt-math-l1-1-0.dll']
+        elif sys.platform == 'darwin':
+            files = ['libm.dylib']
+        else:
+            files = ['libm.so', 'libm.so.6']
+
+        for file in files:
+            try:
+                self.lib = ctypes.CDLL(file)
+                break
+            except OSError:
+                pass
+        else:
+            # This test doesn't work on some Linux platforms (Fedora for
+            # example) that put an ld script in libm.so - see gh-5370
+            pytest.skip("Ctypes can't import libm.so")
+
+        restype = ctypes.c_double
+        argtypes = (ctypes.c_double,)
+        for name in ['sin', 'cos', 'tan']:
+            func = getattr(self.lib, name)
+            func.restype = restype
+            func.argtypes = argtypes
+
+    def test_typical(self):
+        assert_quad(quad(self.lib.sin, 0, 5), quad(math.sin, 0, 5)[0])
+        assert_quad(quad(self.lib.cos, 0, 5), quad(math.cos, 0, 5)[0])
+        assert_quad(quad(self.lib.tan, 0, 1), quad(math.tan, 0, 1)[0])
+
+    def test_ctypes_sine(self):
+        quad(LowLevelCallable(sine_ctypes), 0, 1)
+
+    def test_ctypes_variants(self):
+        sin_0 = get_clib_test_routine('_sin_0', ctypes.c_double,
+                                      ctypes.c_double, ctypes.c_void_p)
+
+        sin_1 = get_clib_test_routine('_sin_1', ctypes.c_double,
+                                      ctypes.c_int, ctypes.POINTER(ctypes.c_double),
+                                      ctypes.c_void_p)
+
+        sin_2 = get_clib_test_routine('_sin_2', ctypes.c_double,
+                                      ctypes.c_double)
+
+        sin_3 = get_clib_test_routine('_sin_3', ctypes.c_double,
+                                      ctypes.c_int, ctypes.POINTER(ctypes.c_double))
+
+        sin_4 = get_clib_test_routine('_sin_3', ctypes.c_double,
+                                      ctypes.c_int, ctypes.c_double)
+
+        all_sigs = [sin_0, sin_1, sin_2, sin_3, sin_4]
+        legacy_sigs = [sin_2, sin_4]
+        legacy_only_sigs = [sin_4]
+
+        # LowLevelCallables work for new signatures
+        for j, func in enumerate(all_sigs):
+            callback = LowLevelCallable(func)
+            if func in legacy_only_sigs:
+                pytest.raises(ValueError, quad, callback, 0, pi)
+            else:
+                assert_allclose(quad(callback, 0, pi)[0], 2.0)
+
+        # Plain ctypes items work only for legacy signatures
+        for j, func in enumerate(legacy_sigs):
+            if func in legacy_sigs:
+                assert_allclose(quad(func, 0, pi)[0], 2.0)
+            else:
+                pytest.raises(ValueError, quad, func, 0, pi)
+
+
+@make_xp_test_case(quad)
+class TestMultivariateCtypesQuad:
+    def setup_method(self):
+        restype = ctypes.c_double
+        argtypes = (ctypes.c_int, ctypes.c_double)
+        for name in ['_multivariate_typical', '_multivariate_indefinite',
+                     '_multivariate_sin']:
+            func = get_clib_test_routine(name, restype, *argtypes)
+            setattr(self, name, func)
+
+    def test_typical(self):
+        # 1) Typical function with two extra arguments:
+        assert_quad(quad(self._multivariate_typical, 0, pi, (2, 1.8)),
+                    0.30614353532540296487)
+
+    def test_indefinite(self):
+        # 2) Infinite integration limits --- Euler's constant
+        assert_quad(quad(self._multivariate_indefinite, 0, np.inf),
+                    0.577215664901532860606512)
+
+    def test_threadsafety(self):
+        # Ensure multivariate ctypes are threadsafe
+        def threadsafety(y):
+            return y + quad(self._multivariate_sin, 0, 1)[0]
+        assert_quad(quad(threadsafety, 0, 1), 0.9596976941318602)
+
+
+@make_xp_test_case(quad)
+class TestQuad:
+    def test_typical(self):
+        # 1) Typical function with two extra arguments:
+        def myfunc(x, n, z):       # Bessel function integrand
+            return cos(n*x-z*sin(x))/pi
+        assert_quad(quad(myfunc, 0, pi, (2, 1.8)), 0.30614353532540296487)
+
+    def test_indefinite(self):
+        # 2) Infinite integration limits --- Euler's constant
+        def myfunc(x):           # Euler's constant integrand
+            return -exp(-x)*log(x)
+        assert_quad(quad(myfunc, 0, np.inf), 0.577215664901532860606512)
+
+    def test_singular(self):
+        # 3) Singular points in region of integration.
+        def myfunc(x):
+            if 0 < x < 2.5:
+                return sin(x)
+            elif 2.5 <= x <= 5.0:
+                return exp(-x)
+            else:
+                return 0.0
+
+        assert_quad(quad(myfunc, 0, 10, points=[2.5, 5.0]),
+                    1 - cos(2.5) + exp(-2.5) - exp(-5.0))
+
+    def test_sine_weighted_finite(self):
+        # 4) Sine weighted integral (finite limits)
+        def myfunc(x, a):
+            return exp(a*(x-1))
+
+        ome = 2.0**3.4
+        assert_quad(quad(myfunc, 0, 1, args=20, weight='sin', wvar=ome),
+                    (20*sin(ome)-ome*cos(ome)+ome*exp(-20))/(20**2 + ome**2))
+
+    def test_sine_weighted_infinite(self):
+        # 5) Sine weighted integral (infinite limits)
+        def myfunc(x, a):
+            return exp(-x*a)
+
+        a = 4.0
+        ome = 3.0
+        assert_quad(quad(myfunc, 0, np.inf, args=a, weight='sin', wvar=ome),
+                    ome/(a**2 + ome**2))
+
+    def test_cosine_weighted_infinite(self):
+        # 6) Cosine weighted integral (negative infinite limits)
+        def myfunc(x, a):
+            return exp(x*a)
+
+        a = 2.5
+        ome = 2.3
+        assert_quad(quad(myfunc, -np.inf, 0, args=a, weight='cos', wvar=ome),
+                    a/(a**2 + ome**2))
+
+    def test_algebraic_log_weight(self):
+        # 6) Algebraic-logarithmic weight.
+        def myfunc(x, a):
+            return 1/(1+x+2**(-a))
+
+        a = 1.5
+        assert_quad(quad(myfunc, -1, 1, args=a, weight='alg',
+                         wvar=(-0.5, -0.5)),
+                    pi/sqrt((1+2**(-a))**2 - 1))
+
+    def test_cauchypv_weight(self):
+        # 7) Cauchy prinicpal value weighting w(x) = 1/(x-c)
+        def myfunc(x, a):
+            return 2.0**(-a)/((x-1)**2+4.0**(-a))
+
+        a = 0.4
+        tabledValue = ((2.0**(-0.4)*log(1.5) -
+                        2.0**(-1.4)*log((4.0**(-a)+16) / (4.0**(-a)+1)) -
+                        arctan(2.0**(a+2)) -
+                        arctan(2.0**a)) /
+                       (4.0**(-a) + 1))
+        assert_quad(quad(myfunc, 0, 5, args=0.4, weight='cauchy', wvar=2.0),
+                    tabledValue, error_tolerance=1.9e-8)
+
+    def test_b_less_than_a(self):
+        def f(x, p, q):
+            return p * np.exp(-q*x)
+
+        val_1, err_1 = quad(f, 0, np.inf, args=(2, 3))
+        val_2, err_2 = quad(f, np.inf, 0, args=(2, 3))
+        assert_allclose(val_1, -val_2, atol=max(err_1, err_2))
+
+    def test_b_less_than_a_2(self):
+        def f(x, s):
+            return np.exp(-x**2 / 2 / s) / np.sqrt(2.*s)
+
+        val_1, err_1 = quad(f, -np.inf, np.inf, args=(2,))
+        val_2, err_2 = quad(f, np.inf, -np.inf, args=(2,))
+        assert_allclose(val_1, -val_2, atol=max(err_1, err_2))
+
+    def test_b_less_than_a_3(self):
+        def f(x):
+            return 1.0
+
+        val_1, err_1 = quad(f, 0, 1, weight='alg', wvar=(0, 0))
+        val_2, err_2 = quad(f, 1, 0, weight='alg', wvar=(0, 0))
+        assert_allclose(val_1, -val_2, atol=max(err_1, err_2))
+
+    def test_b_less_than_a_full_output(self):
+        def f(x):
+            return 1.0
+
+        res_1 = quad(f, 0, 1, weight='alg', wvar=(0, 0), full_output=True)
+        res_2 = quad(f, 1, 0, weight='alg', wvar=(0, 0), full_output=True)
+        err = max(res_1[1], res_2[1])
+        assert_allclose(res_1[0], -res_2[0], atol=err)
+
+    @pytest.mark.parametrize("complex_func", [True, False])
+    def test_b_equals_a(self, complex_func):
+        def f(x):
+            return 1/x
+
+        upper = lower = 0.
+        limit = 50
+        expected_infodict = {"neval": 0, "last": 0,
+                             "alist": np.full(limit, np.nan, dtype=np.float64),
+                             "blist": np.full(limit, np.nan, dtype=np.float64),
+                             "rlist": np.zeros(limit, dtype=np.float64),
+                             "elist": np.zeros(limit, dtype=np.float64),
+                             "iord" : np.zeros(limit, dtype=np.int32)}
+
+        zero, err, infodict = quad(f, lower, upper, full_output=1,
+                                   complex_func=complex_func)
+        assert (zero, err) == (0., 0.)
+        if complex_func:
+            assert_equal(infodict, {"real": expected_infodict,
+                                    "imag": expected_infodict})
+        else:
+            assert_equal(infodict, expected_infodict)
+
+    def test_complex(self):
+        def tfunc(x):
+            return np.exp(1j*x)
+
+        assert np.allclose(
+                    quad(tfunc, 0, np.pi/2, complex_func=True)[0],
+                    1+1j)
+
+        # We consider a divergent case in order to force quadpack
+        # to return an error message.  The output is compared
+        # against what is returned by explicit integration
+        # of the parts.
+        kwargs = {'a': 0, 'b': np.inf, 'full_output': True,
+                  'weight': 'cos', 'wvar': 1}
+        res_c = quad(tfunc, complex_func=True, **kwargs)
+        res_r = quad(lambda x: np.real(np.exp(1j*x)),
+                     complex_func=False,
+                     **kwargs)
+        res_i = quad(lambda x: np.imag(np.exp(1j*x)),
+                     complex_func=False,
+                     **kwargs)
+
+        np.testing.assert_equal(res_c[0], res_r[0] + 1j*res_i[0])
+        np.testing.assert_equal(res_c[1], res_r[1] + 1j*res_i[1])
+
+        assert len(res_c[2]['real']) == len(res_r[2:]) == 3
+        assert res_c[2]['real'][2] == res_r[4]
+        assert res_c[2]['real'][1] == res_r[3]
+        assert res_c[2]['real'][0]['lst'] == res_r[2]['lst']
+
+        assert len(res_c[2]['imag']) == len(res_i[2:]) == 1
+        assert res_c[2]['imag'][0]['lst'] == res_i[2]['lst']
+
+
+@make_xp_test_case(dblquad)
+class TestDblquad:
+    def test_double_integral(self):
+        # 8) Double Integral test
+        def simpfunc(y, x):       # Note order of arguments.
+            return x+y
+
+        a, b = 1.0, 2.0
+        assert_quad(dblquad(simpfunc, a, b, lambda x: x, lambda x: 2*x),
+                    5/6.0 * (b**3.0-a**3.0))
+
+    def test_double_integral2(self):
+        def func(x0, x1, t0, t1):
+            return x0 + x1 + t0 + t1
+        def g(x):
+            return x
+        def h(x):
+            return 2 * x
+        args = 1, 2
+        assert_quad(dblquad(func, 1, 2, g, h, args=args),35./6 + 9*.5)
+
+    def test_double_integral3(self):
+        def func(x0, x1):
+            return x0 + x1 + 1 + 2
+        assert_quad(dblquad(func, 1, 2, 1, 2),6.)
+
+    @pytest.mark.parametrize(
+        "x_lower, x_upper, y_lower, y_upper, expected",
+        [
+            # Multiple integration of a function in n = 2 variables: f(x, y, z)
+            # over domain D = [-inf, 0] for all n.
+            (-np.inf, 0, -np.inf, 0, np.pi / 4),
+            # Multiple integration of a function in n = 2 variables: f(x, y, z)
+            # over domain D = [-inf, -1] for each n (one at a time).
+            (-np.inf, -1, -np.inf, 0, np.pi / 4 * erfc(1)),
+            (-np.inf, 0, -np.inf, -1, np.pi / 4 * erfc(1)),
+            # Multiple integration of a function in n = 2 variables: f(x, y, z)
+            # over domain D = [-inf, -1] for all n.
+            (-np.inf, -1, -np.inf, -1, np.pi / 4 * (erfc(1) ** 2)),
+            # Multiple integration of a function in n = 2 variables: f(x, y, z)
+            # over domain D = [-inf, 1] for each n (one at a time).
+            (-np.inf, 1, -np.inf, 0, np.pi / 4 * (erf(1) + 1)),
+            (-np.inf, 0, -np.inf, 1, np.pi / 4 * (erf(1) + 1)),
+            # Multiple integration of a function in n = 2 variables: f(x, y, z)
+            # over domain D = [-inf, 1] for all n.
+            (-np.inf, 1, -np.inf, 1, np.pi / 4 * ((erf(1) + 1) ** 2)),
+            # Multiple integration of a function in n = 2 variables: f(x, y, z)
+            # over domain Dx = [-inf, -1] and Dy = [-inf, 1].
+            (-np.inf, -1, -np.inf, 1, np.pi / 4 * ((erf(1) + 1) * erfc(1))),
+            # Multiple integration of a function in n = 2 variables: f(x, y, z)
+            # over domain Dx = [-inf, 1] and Dy = [-inf, -1].
+            (-np.inf, 1, -np.inf, -1, np.pi / 4 * ((erf(1) + 1) * erfc(1))),
+            # Multiple integration of a function in n = 2 variables: f(x, y, z)
+            # over domain D = [0, inf] for all n.
+            (0, np.inf, 0, np.inf, np.pi / 4),
+            # Multiple integration of a function in n = 2 variables: f(x, y, z)
+            # over domain D = [1, inf] for each n (one at a time).
+            (1, np.inf, 0, np.inf, np.pi / 4 * erfc(1)),
+            (0, np.inf, 1, np.inf, np.pi / 4 * erfc(1)),
+            # Multiple integration of a function in n = 2 variables: f(x, y, z)
+            # over domain D = [1, inf] for all n.
+            (1, np.inf, 1, np.inf, np.pi / 4 * (erfc(1) ** 2)),
+            # Multiple integration of a function in n = 2 variables: f(x, y, z)
+            # over domain D = [-1, inf] for each n (one at a time).
+            (-1, np.inf, 0, np.inf, np.pi / 4 * (erf(1) + 1)),
+            (0, np.inf, -1, np.inf, np.pi / 4 * (erf(1) + 1)),
+            # Multiple integration of a function in n = 2 variables: f(x, y, z)
+            # over domain D = [-1, inf] for all n.
+            (-1, np.inf, -1, np.inf, np.pi / 4 * ((erf(1) + 1) ** 2)),
+            # Multiple integration of a function in n = 2 variables: f(x, y, z)
+            # over domain Dx = [-1, inf] and Dy = [1, inf].
+            (-1, np.inf, 1, np.inf, np.pi / 4 * ((erf(1) + 1) * erfc(1))),
+            # Multiple integration of a function in n = 2 variables: f(x, y, z)
+            # over domain Dx = [1, inf] and Dy = [-1, inf].
+            (1, np.inf, -1, np.inf, np.pi / 4 * ((erf(1) + 1) * erfc(1))),
+            # Multiple integration of a function in n = 2 variables: f(x, y, z)
+            # over domain D = [-inf, inf] for all n.
+            (-np.inf, np.inf, -np.inf, np.inf, np.pi),
+            # Multiple integration of a function in n = 2 variables: f(x, y, z)
+            # over domain D = [0, 0] for each n (one at a time).
+            (0, 0, 0, np.inf, 0.),
+            (0, np.inf, 0, 0, 0.),
+        ]
+    )
+    def test_double_integral_improper(
+            self, x_lower, x_upper, y_lower, y_upper, expected
+    ):
+        # The Gaussian Integral.
+        def f(x, y):
+            return np.exp(-x ** 2 - y ** 2)
+
+        assert_quad(
+            dblquad(f, x_lower, x_upper, y_lower, y_upper),
+            expected,
+            error_tolerance=3e-8
+        )
+
+
+@make_xp_test_case(tplquad)
+class TestTplquad:
+    def test_triple_integral(self):
+        # 9) Triple Integral test
+        def simpfunc(z, y, x, t):      # Note order of arguments.
+            return (x+y+z)*t
+
+        a, b = 1.0, 2.0
+        assert_quad(tplquad(simpfunc, a, b,
+                            lambda x: x, lambda x: 2*x,
+                            lambda x, y: x - y, lambda x, y: x + y,
+                            (2.,)),
+                     2*8/3.0 * (b**4.0 - a**4.0))
+
+    @pytest.mark.xslow
+    @pytest.mark.parametrize(
+        "x_lower, x_upper, y_lower, y_upper, z_lower, z_upper, expected",
+        [
+            # Multiple integration of a function in n = 3 variables: f(x, y, z)
+            # over domain D = [-inf, 0] for all n.
+            (-np.inf, 0, -np.inf, 0, -np.inf, 0, (np.pi ** (3 / 2)) / 8),
+            # Multiple integration of a function in n = 3 variables: f(x, y, z)
+            # over domain D = [-inf, -1] for each n (one at a time).
+            (-np.inf, -1, -np.inf, 0, -np.inf, 0,
+             (np.pi ** (3 / 2)) / 8 * erfc(1)),
+            (-np.inf, 0, -np.inf, -1, -np.inf, 0,
+             (np.pi ** (3 / 2)) / 8 * erfc(1)),
+            (-np.inf, 0, -np.inf, 0, -np.inf, -1,
+             (np.pi ** (3 / 2)) / 8 * erfc(1)),
+            # Multiple integration of a function in n = 3 variables: f(x, y, z)
+            # over domain D = [-inf, -1] for each n (two at a time).
+            (-np.inf, -1, -np.inf, -1, -np.inf, 0,
+             (np.pi ** (3 / 2)) / 8 * (erfc(1) ** 2)),
+            (-np.inf, -1, -np.inf, 0, -np.inf, -1,
+             (np.pi ** (3 / 2)) / 8 * (erfc(1) ** 2)),
+            (-np.inf, 0, -np.inf, -1, -np.inf, -1,
+             (np.pi ** (3 / 2)) / 8 * (erfc(1) ** 2)),
+            # Multiple integration of a function in n = 3 variables: f(x, y, z)
+            # over domain D = [-inf, -1] for all n.
+            (-np.inf, -1, -np.inf, -1, -np.inf, -1,
+             (np.pi ** (3 / 2)) / 8 * (erfc(1) ** 3)),
+            # Multiple integration of a function in n = 3 variables: f(x, y, z)
+            # over domain Dx = [-inf, -1] and Dy = Dz = [-inf, 1].
+            (-np.inf, -1, -np.inf, 1, -np.inf, 1,
+             (np.pi ** (3 / 2)) / 8 * (((erf(1) + 1) ** 2) * erfc(1))),
+            # Multiple integration of a function in n = 3 variables: f(x, y, z)
+            # over domain Dx = Dy = [-inf, -1] and Dz = [-inf, 1].
+            (-np.inf, -1, -np.inf, -1, -np.inf, 1,
+             (np.pi ** (3 / 2)) / 8 * ((erf(1) + 1) * (erfc(1) ** 2))),
+            # Multiple integration of a function in n = 3 variables: f(x, y, z)
+            # over domain Dx = Dz = [-inf, -1] and Dy = [-inf, 1].
+            (-np.inf, -1, -np.inf, 1, -np.inf, -1,
+             (np.pi ** (3 / 2)) / 8 * ((erf(1) + 1) * (erfc(1) ** 2))),
+            # Multiple integration of a function in n = 3 variables: f(x, y, z)
+            # over domain Dx = [-inf, 1] and Dy = Dz = [-inf, -1].
+            (-np.inf, 1, -np.inf, -1, -np.inf, -1,
+             (np.pi ** (3 / 2)) / 8 * ((erf(1) + 1) * (erfc(1) ** 2))),
+            # Multiple integration of a function in n = 3 variables: f(x, y, z)
+            # over domain Dx = Dy = [-inf, 1] and Dz = [-inf, -1].
+            (-np.inf, 1, -np.inf, 1, -np.inf, -1,
+             (np.pi ** (3 / 2)) / 8 * (((erf(1) + 1) ** 2) * erfc(1))),
+            # Multiple integration of a function in n = 3 variables: f(x, y, z)
+            # over domain Dx = Dz = [-inf, 1] and Dy = [-inf, -1].
+            (-np.inf, 1, -np.inf, -1, -np.inf, 1,
+             (np.pi ** (3 / 2)) / 8 * (((erf(1) + 1) ** 2) * erfc(1))),
+            # Multiple integration of a function in n = 3 variables: f(x, y, z)
+            # over domain D = [-inf, 1] for each n (one at a time).
+            (-np.inf, 1, -np.inf, 0, -np.inf, 0,
+             (np.pi ** (3 / 2)) / 8 * (erf(1) + 1)),
+            (-np.inf, 0, -np.inf, 1, -np.inf, 0,
+             (np.pi ** (3 / 2)) / 8 * (erf(1) + 1)),
+            (-np.inf, 0, -np.inf, 0, -np.inf, 1,
+             (np.pi ** (3 / 2)) / 8 * (erf(1) + 1)),
+            # Multiple integration of a function in n = 3 variables: f(x, y, z)
+            # over domain D = [-inf, 1] for each n (two at a time).
+            (-np.inf, 1, -np.inf, 1, -np.inf, 0,
+             (np.pi ** (3 / 2)) / 8 * ((erf(1) + 1) ** 2)),
+            (-np.inf, 1, -np.inf, 0, -np.inf, 1,
+             (np.pi ** (3 / 2)) / 8 * ((erf(1) + 1) ** 2)),
+            (-np.inf, 0, -np.inf, 1, -np.inf, 1,
+             (np.pi ** (3 / 2)) / 8 * ((erf(1) + 1) ** 2)),
+            # Multiple integration of a function in n = 3 variables: f(x, y, z)
+            # over domain D = [-inf, 1] for all n.
+            (-np.inf, 1, -np.inf, 1, -np.inf, 1,
+             (np.pi ** (3 / 2)) / 8 * ((erf(1) + 1) ** 3)),
+            # Multiple integration of a function in n = 3 variables: f(x, y, z)
+            # over domain D = [0, inf] for all n.
+            (0, np.inf, 0, np.inf, 0, np.inf, (np.pi ** (3 / 2)) / 8),
+            # Multiple integration of a function in n = 3 variables: f(x, y, z)
+            # over domain D = [1, inf] for each n (one at a time).
+            (1, np.inf, 0, np.inf, 0, np.inf,
+             (np.pi ** (3 / 2)) / 8 * erfc(1)),
+            (0, np.inf, 1, np.inf, 0, np.inf,
+             (np.pi ** (3 / 2)) / 8 * erfc(1)),
+            (0, np.inf, 0, np.inf, 1, np.inf,
+             (np.pi ** (3 / 2)) / 8 * erfc(1)),
+            # Multiple integration of a function in n = 3 variables: f(x, y, z)
+            # over domain D = [1, inf] for each n (two at a time).
+            (1, np.inf, 1, np.inf, 0, np.inf,
+             (np.pi ** (3 / 2)) / 8 * (erfc(1) ** 2)),
+            (1, np.inf, 0, np.inf, 1, np.inf,
+             (np.pi ** (3 / 2)) / 8 * (erfc(1) ** 2)),
+            (0, np.inf, 1, np.inf, 1, np.inf,
+             (np.pi ** (3 / 2)) / 8 * (erfc(1) ** 2)),
+            # Multiple integration of a function in n = 3 variables: f(x, y, z)
+            # over domain D = [1, inf] for all n.
+            (1, np.inf, 1, np.inf, 1, np.inf,
+             (np.pi ** (3 / 2)) / 8 * (erfc(1) ** 3)),
+            # Multiple integration of a function in n = 3 variables: f(x, y, z)
+            # over domain D = [-1, inf] for each n (one at a time).
+            (-1, np.inf, 0, np.inf, 0, np.inf,
+             (np.pi ** (3 / 2)) / 8 * (erf(1) + 1)),
+            (0, np.inf, -1, np.inf, 0, np.inf,
+             (np.pi ** (3 / 2)) / 8 * (erf(1) + 1)),
+            (0, np.inf, 0, np.inf, -1, np.inf,
+             (np.pi ** (3 / 2)) / 8 * (erf(1) + 1)),
+            # Multiple integration of a function in n = 3 variables: f(x, y, z)
+            # over domain D = [-1, inf] for each n (two at a time).
+            (-1, np.inf, -1, np.inf, 0, np.inf,
+             (np.pi ** (3 / 2)) / 8 * ((erf(1) + 1) ** 2)),
+            (-1, np.inf, 0, np.inf, -1, np.inf,
+             (np.pi ** (3 / 2)) / 8 * ((erf(1) + 1) ** 2)),
+            (0, np.inf, -1, np.inf, -1, np.inf,
+             (np.pi ** (3 / 2)) / 8 * ((erf(1) + 1) ** 2)),
+            # Multiple integration of a function in n = 3 variables: f(x, y, z)
+            # over domain D = [-1, inf] for all n.
+            (-1, np.inf, -1, np.inf, -1, np.inf,
+             (np.pi ** (3 / 2)) / 8 * ((erf(1) + 1) ** 3)),
+            # Multiple integration of a function in n = 3 variables: f(x, y, z)
+            # over domain Dx = [1, inf] and Dy = Dz = [-1, inf].
+            (1, np.inf, -1, np.inf, -1, np.inf,
+             (np.pi ** (3 / 2)) / 8 * (((erf(1) + 1) ** 2) * erfc(1))),
+            # Multiple integration of a function in n = 3 variables: f(x, y, z)
+            # over domain Dx = Dy = [1, inf] and Dz = [-1, inf].
+            (1, np.inf, 1, np.inf, -1, np.inf,
+             (np.pi ** (3 / 2)) / 8 * ((erf(1) + 1) * (erfc(1) ** 2))),
+            # Multiple integration of a function in n = 3 variables: f(x, y, z)
+            # over domain Dx = Dz = [1, inf] and Dy = [-1, inf].
+            (1, np.inf, -1, np.inf, 1, np.inf,
+             (np.pi ** (3 / 2)) / 8 * ((erf(1) + 1) * (erfc(1) ** 2))),
+            # Multiple integration of a function in n = 3 variables: f(x, y, z)
+            # over domain Dx = [-1, inf] and Dy = Dz = [1, inf].
+            (-1, np.inf, 1, np.inf, 1, np.inf,
+             (np.pi ** (3 / 2)) / 8 * ((erf(1) + 1) * (erfc(1) ** 2))),
+            # Multiple integration of a function in n = 3 variables: f(x, y, z)
+            # over domain Dx = Dy = [-1, inf] and Dz = [1, inf].
+            (-1, np.inf, -1, np.inf, 1, np.inf,
+             (np.pi ** (3 / 2)) / 8 * (((erf(1) + 1) ** 2) * erfc(1))),
+            # Multiple integration of a function in n = 3 variables: f(x, y, z)
+            # over domain Dx = Dz = [-1, inf] and Dy = [1, inf].
+            (-1, np.inf, 1, np.inf, -1, np.inf,
+             (np.pi ** (3 / 2)) / 8 * (((erf(1) + 1) ** 2) * erfc(1))),
+            # Multiple integration of a function in n = 3 variables: f(x, y, z)
+            # over domain D = [-inf, inf] for all n.
+            (-np.inf, np.inf, -np.inf, np.inf, -np.inf, np.inf,
+             np.pi ** (3 / 2)),
+            # Multiple integration of a function in n = 3 variables: f(x, y, z)
+            # over domain D = [0, 0] for each n (one at a time).
+            (0, 0, 0, np.inf, 0, np.inf, 0),
+            (0, np.inf, 0, 0, 0, np.inf, 0),
+            (0, np.inf, 0, np.inf, 0, 0, 0),
+        ],
+    )
+    def test_triple_integral_improper(
+            self,
+            x_lower,
+            x_upper,
+            y_lower,
+            y_upper,
+            z_lower,
+            z_upper,
+            expected
+    ):
+        # The Gaussian Integral.
+        def f(x, y, z):
+            return np.exp(-x ** 2 - y ** 2 - z ** 2)
+
+        assert_quad(
+            tplquad(f, x_lower, x_upper, y_lower, y_upper, z_lower, z_upper),
+            expected,
+            error_tolerance=6e-8
+        )
+
+
+@make_xp_test_case(nquad)
+class TestNQuad:
+    @pytest.mark.fail_slow(5)
+    def test_fixed_limits(self):
+        def func1(x0, x1, x2, x3):
+            val = (x0**2 + x1*x2 - x3**3 + np.sin(x0) +
+                   (1 if (x0 - 0.2*x3 - 0.5 - 0.25*x1 > 0) else 0))
+            return val
+
+        def opts_basic(*args):
+            return {'points': [0.2*args[2] + 0.5 + 0.25*args[0]]}
+
+        res = nquad(func1, [[0, 1], [-1, 1], [.13, .8], [-.15, 1]],
+                    opts=[opts_basic, {}, {}, {}], full_output=True)
+        assert_quad(res[:-1], 1.5267454070738635)
+        assert_(res[-1]['neval'] > 0 and res[-1]['neval'] < 4e5)
+
+    @pytest.mark.fail_slow(5)
+    def test_variable_limits(self):
+        scale = .1
+
+        def func2(x0, x1, x2, x3, t0, t1):
+            val = (x0*x1*x3**2 + np.sin(x2) + 1 +
+                   (1 if x0 + t1*x1 - t0 > 0 else 0))
+            return val
+
+        def lim0(x1, x2, x3, t0, t1):
+            return [scale * (x1**2 + x2 + np.cos(x3)*t0*t1 + 1) - 1,
+                    scale * (x1**2 + x2 + np.cos(x3)*t0*t1 + 1) + 1]
+
+        def lim1(x2, x3, t0, t1):
+            return [scale * (t0*x2 + t1*x3) - 1,
+                    scale * (t0*x2 + t1*x3) + 1]
+
+        def lim2(x3, t0, t1):
+            return [scale * (x3 + t0**2*t1**3) - 1,
+                    scale * (x3 + t0**2*t1**3) + 1]
+
+        def lim3(t0, t1):
+            return [scale * (t0 + t1) - 1, scale * (t0 + t1) + 1]
+
+        def opts0(x1, x2, x3, t0, t1):
+            return {'points': [t0 - t1*x1]}
+
+        def opts1(x2, x3, t0, t1):
+            return {}
+
+        def opts2(x3, t0, t1):
+            return {}
+
+        def opts3(t0, t1):
+            return {}
+
+        res = nquad(func2, [lim0, lim1, lim2, lim3], args=(0, 0),
+                    opts=[opts0, opts1, opts2, opts3])
+        assert_quad(res, 25.066666666666663)
+
+    def test_square_separate_ranges_and_opts(self):
+        def f(y, x):
+            return 1.0
+
+        assert_quad(nquad(f, [[-1, 1], [-1, 1]], opts=[{}, {}]), 4.0)
+
+    def test_square_aliased_ranges_and_opts(self):
+        def f(y, x):
+            return 1.0
+
+        r = [-1, 1]
+        opt = {}
+        assert_quad(nquad(f, [r, r], opts=[opt, opt]), 4.0)
+
+    def test_square_separate_fn_ranges_and_opts(self):
+        def f(y, x):
+            return 1.0
+
+        def fn_range0(*args):
+            return (-1, 1)
+
+        def fn_range1(*args):
+            return (-1, 1)
+
+        def fn_opt0(*args):
+            return {}
+
+        def fn_opt1(*args):
+            return {}
+
+        ranges = [fn_range0, fn_range1]
+        opts = [fn_opt0, fn_opt1]
+        assert_quad(nquad(f, ranges, opts=opts), 4.0)
+
+    def test_square_aliased_fn_ranges_and_opts(self):
+        def f(y, x):
+            return 1.0
+
+        def fn_range(*args):
+            return (-1, 1)
+
+        def fn_opt(*args):
+            return {}
+
+        ranges = [fn_range, fn_range]
+        opts = [fn_opt, fn_opt]
+        assert_quad(nquad(f, ranges, opts=opts), 4.0)
+
+    def test_matching_quad(self):
+        def func(x):
+            return x**2 + 1
+
+        res, reserr = quad(func, 0, 4)
+        res2, reserr2 = nquad(func, ranges=[[0, 4]])
+        assert_almost_equal(res, res2)
+        assert_almost_equal(reserr, reserr2)
+
+    def test_matching_dblquad(self):
+        def func2d(x0, x1):
+            return x0**2 + x1**3 - x0 * x1 + 1
+
+        res, reserr = dblquad(func2d, -2, 2, lambda x: -3, lambda x: 3)
+        res2, reserr2 = nquad(func2d, [[-3, 3], (-2, 2)])
+        assert_almost_equal(res, res2)
+        assert_almost_equal(reserr, reserr2)
+
+    def test_matching_tplquad(self):
+        def func3d(x0, x1, x2, c0, c1):
+            return x0**2 + c0 * x1**3 - x0 * x1 + 1 + c1 * np.sin(x2)
+
+        res = tplquad(func3d, -1, 2, lambda x: -2, lambda x: 2,
+                      lambda x, y: -np.pi, lambda x, y: np.pi,
+                      args=(2, 3))
+        res2 = nquad(func3d, [[-np.pi, np.pi], [-2, 2], (-1, 2)], args=(2, 3))
+        assert_almost_equal(res, res2)
+
+    def test_dict_as_opts(self):
+        try:
+            nquad(lambda x, y: x * y, [[0, 1], [0, 1]], opts={'epsrel': 0.0001})
+        except TypeError:
+            assert False
+
diff --git a/.venv/lib/python3.12/site-packages/scipy/integrate/tests/test_quadrature.py b/.venv/lib/python3.12/site-packages/scipy/integrate/tests/test_quadrature.py
new file mode 100644
index 0000000000000000000000000000000000000000..1c7f4528292ec85141cea177c361feefa91ae11c
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/integrate/tests/test_quadrature.py
@@ -0,0 +1,790 @@
+# mypy: disable-error-code="attr-defined"
+import pytest
+import numpy as np
+from numpy.testing import assert_equal, assert_almost_equal, assert_allclose
+from hypothesis import given
+import hypothesis.strategies as st
+import hypothesis.extra.numpy as hyp_num
+
+from scipy.integrate import (romb, newton_cotes,
+                             cumulative_trapezoid, trapezoid,
+                             quad, simpson, fixed_quad,
+                             qmc_quad, cumulative_simpson)
+from scipy.integrate._quadrature import _cumulative_simpson_unequal_intervals
+
+from scipy import stats, special, integrate
+from scipy.conftest import skip_xp_invalid_arg
+from scipy._lib._array_api import make_xp_test_case, xp_default_dtype, is_numpy
+from scipy._lib._array_api_no_0d import xp_assert_close, xp_assert_equal
+from scipy._external import array_api_extra as xpx
+
+skip_xp_backends = pytest.mark.skip_xp_backends
+
+@make_xp_test_case(fixed_quad)
+class TestFixedQuad:
+    def test_scalar(self):
+        n = 4
+        expected = 1/(2*n)
+        got, _ = fixed_quad(lambda x: x**(2*n - 1), 0, 1, n=n)
+        # quadrature exact for this input
+        xp_assert_close(got, np.asarray(expected), rtol=1e-12)
+
+    def test_0d(self, xp):
+        n = 4
+        expected = 1/(2*n)
+        got, _ = fixed_quad(lambda x: x**(2*n - 1), xp.asarray(0.), xp.asarray(1.), n=n)
+        # quadrature exact for this input
+        xp_assert_close(got, xp.asarray(expected), rtol=1e-12)
+
+    @pytest.mark.parametrize('dtype', [None, 'float32', 'float64'])
+    def test_vector(self, dtype, xp):
+        dtype = dtype if dtype is None else getattr(xp, dtype)
+        n = 4
+        p = xp.arange(1., 2*n, dtype=dtype)
+        a, b = xp.asarray(0., dtype=dtype), xp.asarray(1., dtype=dtype)
+        expected = 1/(p + 1)
+        got, _ = fixed_quad(lambda x, p: x**p[:, xp.newaxis], a, b, args=(p,), n=n)
+        rtol = 1e-12 if dtype == xp.float64 else 2e-7
+        xp_assert_close(got, xp.asarray(expected), rtol=rtol)
+
+    @skip_xp_backends('jax.numpy', reason="lazy -> limited input validation")
+    @skip_xp_backends('dask.array', reason="lazy -> limited input validation")
+    def test_input_validation(self, xp):
+        n = 4
+        message = "Gaussian quadrature is only available for finite limits."
+        with pytest.raises(ValueError, match=message):
+            fixed_quad(lambda x: x**(2*n - 1), xp.asarray(-xp.inf), xp.asarray(1.), n=n)
+        with pytest.raises(ValueError, match=message):
+            fixed_quad(lambda x: x**(2*n - 1), xp.asarray(0.), xp.asarray(xp.inf), n=n)
+
+
+@make_xp_test_case(romb)
+class TestRomb:
+    def test_romb(self, xp):
+        xp_assert_equal(romb(xp.arange(17.0)), xp.asarray(128.0, dtype=xp.float64))
+
+    def test_romb_gh_3731(self, xp):
+        # Check that romb makes maximal use of data points
+        x = np.arange(2**4+1)
+        y = np.cos(0.2*x)
+        val = romb(xp.asarray(y))
+        expected, _ = quad(lambda x: np.cos(np.array(0.2*x)), np.min(x), np.max(x))
+        xp_assert_close(val, xp.asarray(expected, dtype=xp.float64), rtol=1e-8, atol=0)
+
+
+@make_xp_test_case(newton_cotes)
+class TestNewtonCotes:
+    def test_newton_cotes(self):
+        """Test the first few degrees, for evenly spaced points."""
+        n = 1
+        wts, errcoff = newton_cotes(n, 1)
+        assert_equal(wts, n*np.array([0.5, 0.5]))
+        assert_almost_equal(errcoff, -n**3/12.0)
+
+        n = 2
+        wts, errcoff = newton_cotes(n, 1)
+        assert_almost_equal(wts, n*np.array([1.0, 4.0, 1.0])/6.0)
+        assert_almost_equal(errcoff, -n**5/2880.0)
+
+        n = 3
+        wts, errcoff = newton_cotes(n, 1)
+        assert_almost_equal(wts, n*np.array([1.0, 3.0, 3.0, 1.0])/8.0)
+        assert_almost_equal(errcoff, -n**5/6480.0)
+
+        n = 4
+        wts, errcoff = newton_cotes(n, 1)
+        assert_almost_equal(wts, n*np.array([7.0, 32.0, 12.0, 32.0, 7.0])/90.0)
+        assert_almost_equal(errcoff, -n**7/1935360.0)
+
+    def test_newton_cotes2(self):
+        """Test newton_cotes with points that are not evenly spaced."""
+
+        x = np.array([0.0, 1.5, 2.0])
+        y = x**2
+        wts, errcoff = newton_cotes(x)
+        exact_integral = 8.0/3
+        numeric_integral = np.dot(wts, y)
+        assert_almost_equal(numeric_integral, exact_integral)
+
+        x = np.array([0.0, 1.4, 2.1, 3.0])
+        y = x**2
+        wts, errcoff = newton_cotes(x)
+        exact_integral = 9.0
+        numeric_integral = np.dot(wts, y)
+        assert_almost_equal(numeric_integral, exact_integral)
+
+
+@make_xp_test_case(simpson)
+class TestSimpson:
+
+    def test_simpson(self, xp):
+        y = xp.arange(17.)
+        xp_assert_equal(simpson(y), xp.asarray(128.))
+        xp_assert_equal(simpson(y, dx=0.5), xp.asarray(64.))
+        xp_assert_equal(simpson(y, x=xp.linspace(0., 4., 17)), xp.asarray(32.))
+
+        # integral should be exactly 21
+        x = xp.linspace(1., 4., 4)
+        def f(x):
+            return x**2
+
+        xp_assert_close(simpson(f(x), x=x), xp.asarray(21.0))
+
+        # integral should be exactly 114
+        x = xp.linspace(1., 7., 4)
+        xp_assert_close(simpson(f(x), dx=2.0), xp.asarray(114.))
+
+        # test multi-axis behaviour
+        a = np.arange(16.).reshape(4, 4)
+        x = xp.reshape(xp.arange(64.), (4, 4, 4))
+        y = f(x)
+        for i in range(3):
+            r = simpson(y, x=x, axis=i)
+            it = np.nditer(a, flags=['multi_index'])
+            for _ in it:
+                idx = list(it.multi_index)
+                idx.insert(i, slice(None))
+                integral = x[tuple(idx)][-1]**3 / 3 - x[tuple(idx)][0]**3 / 3
+                xp_assert_close(r[it.multi_index], xp.asarray(integral))
+
+        # test when integration axis only has two points
+        x = xp.reshape(xp.arange(16.), (8, 2))
+        y = f(x)
+        r = simpson(y, x=x, axis=-1)
+
+        integral = 0.5 * (y[:, 1] + y[:, 0]) * (x[:, 1] - x[:, 0])
+        xp_assert_close(r, xp.asarray(integral))
+
+        # odd points, test multi-axis behaviour
+        a = np.arange(25).reshape(5, 5)
+        x = xp.reshape(xp.arange(125.), (5, 5, 5))
+        y = f(x)
+        for i in range(3):
+            r = simpson(y, x=x, axis=i)
+            it = np.nditer(a, flags=['multi_index'])
+            for _ in it:
+                idx = list(it.multi_index)
+                idx.insert(i, slice(None))
+                integral = x[tuple(idx)][-1]**3 / 3 - x[tuple(idx)][0]**3 / 3
+                xp_assert_close(r[it.multi_index], xp.asarray(integral))
+
+        # Tests for checking base case
+        x = xp.asarray([3.])
+        y = x**2
+        xp_assert_close(simpson(y, x=x, axis=0), xp.asarray(0.0))
+        xp_assert_close(simpson(y, x=x, axis=-1), xp.asarray(0.0))
+
+        x = xp.asarray([3., 3., 3., 3.])
+        y = x**2
+        xp_assert_close(simpson(y, x=x, axis=0), xp.asarray(0.0))
+        xp_assert_close(simpson(y, x=x, axis=-1), xp.asarray(0.0))
+
+        x = xp.asarray([[1., 2., 4., 8.], [1., 2., 4., 8.], [1., 2., 4., 8.]])
+        y = x**2
+        zero_axis = xp.asarray([0.0, 0.0, 0.0, 0.0])
+        default_axis = xp.asarray([170 + 1/3] * 3)   # 8**3 / 3 - 1/3
+        xp_assert_close(simpson(y, x=x, axis=0), zero_axis)
+        # the following should be exact
+        xp_assert_close(simpson(y, x=x, axis=-1), default_axis)
+
+        x = xp.asarray([[1., 2., 4., 8.], [1., 2., 4., 8.], [1., 8., 16., 32.]])
+        y = x**2
+        zero_axis = xp.asarray([0.0, 136.0, 1088.0, 8704.0])
+        default_axis = xp.asarray([170 + 1/3, 170 + 1/3, 32**3 / 3 - 1/3])
+        xp_assert_close(simpson(y, x=x, axis=0), zero_axis)
+        xp_assert_close(simpson(y, x=x, axis=-1), default_axis)
+
+    @pytest.mark.skip_xp_backends('array_api_strict', reason="no int->float promotion")
+    @pytest.mark.parametrize('droplast', [False, True])
+    def test_simpson_2d_integer_no_x(self, droplast, xp):
+        # The inputs are 2d integer arrays.  The results should be
+        # identical to the results when the inputs are floating point.
+        y = xp.asarray([[2, 2, 4, 4, 8, 8, -4, 5],
+                        [4, 4, 2, -4, 10, 22, -2, 10]])
+        if droplast:
+            y = y[:, :-1]
+        result = simpson(y, axis=-1)
+        expected = simpson(xp.asarray(y, dtype=xp_default_dtype(xp)), axis=-1)
+        xp_assert_equal(result, expected)
+
+
+@make_xp_test_case(cumulative_trapezoid)
+class TestCumulative_trapezoid:
+    def test_1d(self, xp):
+        x = xp.linspace(-2, 2, num=5)
+        y = x
+        y_int = cumulative_trapezoid(y, x, initial=0)
+        y_expected = xp.asarray([0., -1.5, -2., -1.5, 0.])
+        xp_assert_close(y_int, y_expected)
+
+        y_int = cumulative_trapezoid(y, x, initial=None)
+        xp_assert_close(y_int, y_expected[1:])
+
+    def test_y_nd_x_nd(self, xp):
+        x = xp.reshape(xp.arange(3 * 2 * 4, dtype=xp_default_dtype(xp)), (3, 2, 4))
+        y = x
+        y_int = cumulative_trapezoid(y, x, initial=0)
+        y_expected = xp.asarray([[[0., 0.5, 2., 4.5],
+                                  [0., 4.5, 10., 16.5]],
+                                 [[0., 8.5, 18., 28.5],
+                                  [0., 12.5, 26., 40.5]],
+                                 [[0., 16.5, 34., 52.5],
+                                  [0., 20.5, 42., 64.5]]])
+
+        xp_assert_close(y_int, y_expected)
+
+        # Try with all axes
+        shapes = [(2, 2, 4), (3, 1, 4), (3, 2, 3)]
+        for axis, shape in zip([0, 1, 2], shapes):
+            y_int = cumulative_trapezoid(y, x, initial=0, axis=axis)
+            assert y_int.shape == (3, 2, 4)
+            y_int = cumulative_trapezoid(y, x, initial=None, axis=axis)
+            assert y_int.shape == shape
+
+    def test_y_nd_x_1d(self, xp):
+        y = xp.reshape(xp.arange(3 * 2 * 4, dtype=xp_default_dtype(xp)), (3, 2, 4))
+        x = xp.arange(4, dtype=xp_default_dtype(xp))**2
+        # Try with all axes
+        ys_expected = (
+            xp.asarray([[[4., 5., 6., 7.],
+                         [8., 9., 10., 11.]],
+                        [[40., 44., 48., 52.],
+                         [56., 60., 64., 68.]]]),
+            xp.asarray([[[2., 3., 4., 5.]],
+                        [[10., 11., 12., 13.]],
+                        [[18., 19., 20., 21.]]]),
+            xp.asarray([[[0.5, 5., 17.5],
+                         [4.5, 21., 53.5]],
+                        [[8.5, 37., 89.5],
+                         [12.5, 53., 125.5]],
+                        [[16.5, 69., 161.5],
+                         [20.5, 85., 197.5]]]))
+
+        for axis, y_expected in zip([0, 1, 2], ys_expected):
+            y_int = cumulative_trapezoid(y, x=x[:y.shape[axis]], axis=axis,
+                                         initial=None)
+            xp_assert_close(y_int, y_expected)
+
+    def test_x_none(self, xp):
+        y = xp.linspace(-2, 2, num=5)
+
+        y_int = cumulative_trapezoid(y)
+        y_expected = xp.asarray([-1.5, -2., -1.5, 0.])
+        xp_assert_close(y_int, y_expected)
+
+        y_int = cumulative_trapezoid(y, initial=0)
+        y_expected = xp.asarray([0, -1.5, -2., -1.5, 0.])
+        xp_assert_close(y_int, y_expected)
+
+        y_int = cumulative_trapezoid(y, dx=3)
+        y_expected = xp.asarray([-4.5, -6., -4.5, 0.])
+        xp_assert_close(y_int, y_expected)
+
+        y_int = cumulative_trapezoid(y, dx=3, initial=0)
+        y_expected = xp.asarray([0, -4.5, -6., -4.5, 0.])
+        xp_assert_close(y_int, y_expected)
+
+    @pytest.mark.parametrize(
+        "initial", [1, 0.5]
+    )
+    def test_initial_error(self, initial, xp):
+        """If initial is not None or 0, a ValueError is raised."""
+        y = xp.linspace(0, 10, num=10)
+        with pytest.raises(ValueError, match="`initial`"):
+            cumulative_trapezoid(y, initial=initial)
+
+    def test_zero_len_y(self, xp):
+        with pytest.raises(ValueError, match="At least one point is required"):
+            cumulative_trapezoid(y=xp.asarray([]))
+
+
+class CommonTrapezoidSimpsonTests:
+    def test_simple(self, xp):
+        x = xp.arange(-10, 10, .1)
+        r = self.quadrature_func(xp.exp(-.5 * x ** 2) / xp.sqrt(2 * xp.asarray(xp.pi)),
+                                 dx=0.1)
+        # check integral of normal equals 1
+        xp_assert_close(r, xp.asarray(1.0))
+
+    def test_ndim(self, xp):
+        x = xp.linspace(0, 1, 3)
+        y = xp.linspace(0, 2, 8)
+        z = xp.linspace(0, 3, 13)
+
+        wx = xp.ones_like(x) * (x[1] - x[0])
+        wx = xpx.at(wx)[0].divide(2)
+        wx = xpx.at(wx)[-1].divide(2)
+        wy = xp.ones_like(y) * (y[1] - y[0])
+        wy = xpx.at(wy)[0].divide(2)
+        wy = xpx.at(wy)[-1].divide(2)
+        wz = xp.ones_like(z) * (z[1] - z[0])
+        wz = xpx.at(wz)[0].divide(2)
+        wz = xpx.at(wz)[-1].divide(2)
+
+        q = x[:, None, None] + y[None,:, None] + z[None, None,:]
+
+        qx = xp.sum(q * wx[:, None, None], axis=0)
+        qy = xp.sum(q * wy[None, :, None], axis=1)
+        qz = xp.sum(q * wz[None, None, :], axis=2)
+
+        # n-d `x`
+        r = self.quadrature_func(q, x=x[:, None, None], axis=0)
+        xp_assert_close(r, qx)
+        r = self.quadrature_func(q, x=y[None,:, None], axis=1)
+        xp_assert_close(r, qy)
+        r = self.quadrature_func(q, x=z[None, None,:], axis=2)
+        xp_assert_close(r, qz)
+
+        # 1-d `x`
+        r = self.quadrature_func(q, x=x, axis=0)
+        xp_assert_close(r, qx)
+        r = self.quadrature_func(q, x=y, axis=1)
+        xp_assert_close(r, qy)
+        r = self.quadrature_func(q, x=z, axis=2)
+        xp_assert_close(r, qz)
+
+@make_xp_test_case(simpson)
+class TestSimpson2(CommonTrapezoidSimpsonTests):
+    # run additional tests without copying/moving classes around
+    def quadrature_func(self, *args, **kwargs):
+        return simpson(*args, **kwargs)
+
+@make_xp_test_case(trapezoid)
+class TestTrapezoid(CommonTrapezoidSimpsonTests):
+    def quadrature_func(self, *args, **kwargs):
+        return trapezoid(*args, **kwargs)
+
+    def test_gh21908(self, xp):
+        # extended testing for n-dim arrays
+        x = xp.reshape(xp.linspace(0, 29, 30), (3, 10))
+        y = xp.reshape(xp.linspace(0, 29, 30), (3, 10))
+
+        out0 = xp.linspace(200, 380, 10)
+        xp_assert_close(trapezoid(y, x=x, axis=0), out0)
+        xp_assert_close(trapezoid(y, x=xp.asarray([0, 10., 20.]), axis=0), out0)
+        # x needs to be broadcastable against y
+        xp_assert_close(
+            trapezoid(y, x=xp.asarray([0, 10., 20.])[:, None], axis=0),
+            out0
+        )
+        with pytest.raises(Exception):
+            # x is not broadcastable against y
+            trapezoid(y, x=xp.asarray([0, 10., 20.])[None, :], axis=0)
+
+        out1 = xp.asarray([ 40.5, 130.5, 220.5])
+        xp_assert_close(trapezoid(y, x=x, axis=1), out1)
+        xp_assert_close(
+            trapezoid(y, x=xp.linspace(0, 9, 10), axis=1),
+            out1
+        )
+
+    @skip_xp_invalid_arg
+    def test_masked(self, xp):
+        # Testing that masked arrays behave as if the function is 0 where
+        # masked
+        x = np.arange(5)
+        y = x * x
+        mask = x == 2
+        ym = np.ma.array(y, mask=mask)
+        r = 13.0  # sum(0.5 * (0 + 1) * 1.0 + 0.5 * (9 + 16))
+        assert_allclose(trapezoid(ym, x), r)
+
+        xm = np.ma.array(x, mask=mask)
+        assert_allclose(trapezoid(ym, xm), r)
+
+        xm = np.ma.array(x, mask=mask)
+        assert_allclose(trapezoid(y, xm), r)
+
+    def test_array_like(self):
+        x = list(range(5))
+        y = [t * t for t in x]
+        xarr = np.asarray(x, dtype=np.float64)
+        yarr = np.asarray(y, dtype=np.float64)
+        res = trapezoid(y, x)
+        resarr = trapezoid(yarr, xarr)
+        xp_assert_close(res, resarr)
+
+
+@make_xp_test_case(qmc_quad)
+class TestQMCQuad:
+    def test_input_validation(self, xp):
+        a = xp.asarray([0., 0.])
+        b = xp.asarray([1., 1.])
+
+        message = "`func` must be callable."
+        with pytest.raises(TypeError, match=message):
+            qmc_quad("a duck", a, b)
+
+        message = "`func` must evaluate the integrand at points..."
+        with pytest.raises(ValueError, match=message):
+            qmc_quad(lambda: 1, a, b)
+
+        def func(x):
+            assert x.ndim == 1
+            return xp.sum(x)
+        message = "Exception encountered when attempting vectorized call..."
+        if is_numpy(xp):
+            with pytest.warns(UserWarning, match=message):
+                qmc_quad(func, a, b)
+        else:
+            with pytest.raises(ValueError, match=message):
+                qmc_quad(func, a, b)
+
+        message = "`n_points` must be an integer."
+        with pytest.raises(TypeError, match=message):
+            qmc_quad(lambda x: 1, a, b, n_points=1024.5)
+
+        message = "`n_estimates` must be an integer."
+        with pytest.raises(TypeError, match=message):
+            qmc_quad(lambda x: 1, a, b, n_estimates=8.5)
+
+        message = "`qrng` must be an instance of scipy.stats.qmc.QMCEngine."
+        with pytest.raises(TypeError, match=message):
+            qmc_quad(lambda x: 1, a, b, qrng="a duck")
+
+        message = "`qrng` must be initialized with dimensionality equal to "
+        with pytest.raises(ValueError, match=message):
+            qmc_quad(lambda x: 1, a, b, qrng=stats.qmc.Sobol(1))
+
+        message = r"`log` must be boolean \(`True` or `False`\)."
+        with pytest.raises(TypeError, match=message):
+            qmc_quad(lambda x: 1, a, b, log=10)
+
+    def basic_test(self, n_points=2**8, n_estimates=8, signs=None, xp=None):
+        dtype = xp_default_dtype(xp)
+        if signs is None:
+            signs = np.ones(2)
+        ndim = 2
+        mean = np.zeros(ndim)
+        cov = np.eye(ndim)
+
+        def func(x):
+            # standard multivariate normal PDF in two dimensions
+            return xp.exp(-0.5 * xp.sum(x*x, axis=0)) / (2 * xp.pi)
+
+        rng = np.random.default_rng(2879434385674690281)
+        qrng = stats.qmc.Sobol(ndim, seed=rng)
+        a = np.zeros(ndim)
+        b = np.ones(ndim) * signs
+        res = qmc_quad(func, xp.asarray(a, dtype=dtype), xp.asarray(b, dtype=dtype),
+                       n_points=n_points, n_estimates=n_estimates, qrng=qrng)
+        ref = stats.multivariate_normal.cdf(b, mean, cov, lower_limit=a)
+        atol = special.stdtrit(n_estimates-1, 0.995) * res.standard_error  # 99% CI
+        xp_assert_close(res.integral, xp.asarray(ref, dtype=dtype), atol=atol)
+        assert np.prod(signs)*res.integral > 0
+
+        rng = np.random.default_rng(2879434385674690281)
+        qrng = stats.qmc.Sobol(ndim, seed=rng)
+        logres = qmc_quad(lambda *args: xp.log(func(*args)),
+                          xp.asarray(a, dtype=dtype), xp.asarray(b, dtype=dtype),
+                          n_points=n_points, n_estimates=n_estimates,
+                          log=True, qrng=qrng)
+        rtol = 1e-14 if res.integral.dtype == xp.float64 else 2e-6
+        xp_assert_close(xp.real(xp.exp(logres.integral)), res.integral, rtol=rtol)
+        assert xp.imag(logres.integral + 0j) == (xp.pi if np.prod(signs) < 0 else 0)
+        xp_assert_close(xp.exp(logres.standard_error),
+                        res.standard_error, rtol=rtol, atol=rtol/100)
+
+    @pytest.mark.parametrize("n_points", [2**8, 2**12])
+    @pytest.mark.parametrize("n_estimates", [8, 16])
+    def test_basic(self, n_points, n_estimates, xp):
+        self.basic_test(n_points, n_estimates, xp=xp)
+
+    @pytest.mark.parametrize("signs", [[1., 1.], [-1., -1.], [-1., 1.], [1., -1.]])
+    def test_sign(self, signs, xp):
+        self.basic_test(signs=signs, xp=xp)
+
+    @pytest.mark.parametrize("log", [False, True])
+    def test_zero(self, log, xp):
+        message = "A lower limit was equal to an upper limit, so"
+        with pytest.warns(UserWarning, match=message):
+            res = qmc_quad(lambda x: 1, xp.asarray([0, 0]), xp.asarray([0, 1]), log=log)
+        assert res.integral == (-xp.inf if log else 0)
+        assert res.standard_error == 0
+
+    def test_flexible_input(self):
+        # check that qrng is not required
+        # also checks that for 1d problems, a and b can be scalars
+        def func(x):
+            return stats.norm.pdf(x, scale=2)
+
+        res = qmc_quad(func, 0, 1)
+        ref = stats.norm.cdf(1, scale=2) - stats.norm.cdf(0, scale=2)
+        assert_allclose(res.integral, ref, 1e-2)
+
+
+def cumulative_simpson_nd_reference(y, *, x=None, dx=None, initial=None, axis=-1):
+    # Use cumulative_trapezoid if length of y < 3
+    if y.shape[axis] < 3:
+        if initial is None:
+            return cumulative_trapezoid(y, x=x, dx=dx, axis=axis, initial=None)
+        else:
+            return initial + cumulative_trapezoid(y, x=x, dx=dx, axis=axis, initial=0)
+
+    # Ensure that working axis is last axis
+    y = np.moveaxis(y, axis, -1)
+    x = np.moveaxis(x, axis, -1) if np.ndim(x) > 1 else x
+    dx = np.moveaxis(dx, axis, -1) if np.ndim(dx) > 1 else dx
+    initial = np.moveaxis(initial, axis, -1) if np.ndim(initial) > 1 else initial
+
+    # If `x` is not present, create it from `dx`
+    n = y.shape[-1]
+    x = dx * np.arange(n) if dx is not None else x
+    # Similarly, if `initial` is not present, set it to 0
+    initial_was_none = initial is None
+    initial = 0 if initial_was_none else initial
+
+    # `np.apply_along_axis` accepts only one array, so concatenate arguments
+    x = np.broadcast_to(x, y.shape)
+    initial = np.broadcast_to(initial, y.shape[:-1] + (1,))
+    z = np.concatenate((y, x, initial), axis=-1)
+
+    # Use `np.apply_along_axis` to compute result
+    def f(z):
+        return cumulative_simpson(z[:n], x=z[n:2*n], initial=z[2*n:])
+    res = np.apply_along_axis(f, -1, z)
+
+    # Remove `initial` and undo axis move as needed
+    res = res[..., 1:] if initial_was_none else res
+    res = np.moveaxis(res, -1, axis)
+    return res
+
+
+@make_xp_test_case(cumulative_simpson)
+class TestCumulativeSimpson:
+    x0 = np.arange(4)
+    y0 = x0**2
+
+    @pytest.mark.parametrize('use_dx', (False, True))
+    @pytest.mark.parametrize('use_initial', (False, True))
+    def test_1d(self, use_dx, use_initial, xp):
+        # Test for exact agreement with polynomial of highest
+        # possible order (3 if `dx` is constant, 2 otherwise).
+        rng = np.random.default_rng(82456839535679456794)
+        n = 10
+
+        # Generate random polynomials and ground truth
+        # integral of appropriate order
+        order = 3 if use_dx else 2
+        dx = xp.asarray(rng.random())
+        if order == 2:
+            x = xp.asarray(np.sort(rng.random(n)))
+        else:
+            x = xp.arange(n, dtype=xp.float64)*dx + xp.asarray(rng.random())
+        i = xp.arange(order + 1, dtype=xp.float64)[:, xp.newaxis]
+        c = xp.asarray(rng.random(order + 1))[:, xp.newaxis]
+        y = xp.sum(c*x**i, axis=0)
+        Y = xp.sum(c*x**(i + 1)/(i + 1), axis=0)
+        ref = Y if use_initial else (Y-Y[0])[1:]
+
+        # Integrate with `cumulative_simpson`
+        initial = Y[0] if use_initial else None
+        kwarg = {'dx': dx} if use_dx else {'x': x}
+        res = cumulative_simpson(y, **kwarg, initial=initial)
+
+        # Compare result against reference
+        if not use_dx:
+            xp_assert_close(res, ref, rtol=2e-15)
+        else:
+            i0 = 0 if use_initial else 1
+            # all terms are "close"
+            xp_assert_close(res, ref, rtol=0.0025)
+            # only even-interval terms are "exact"
+            xp_assert_close(res[i0::2], ref[i0::2], rtol=2e-15)
+
+    @skip_xp_backends(cpu_only=True)  # uses np.apply_along_axis
+    @pytest.mark.parametrize('axis', np.arange(-3, 3))
+    @pytest.mark.parametrize('x_ndim', (1, 3))
+    @pytest.mark.parametrize('x_len', (1, 2, 7))
+    @pytest.mark.parametrize('i_ndim', (None, 0, 3,))
+    @pytest.mark.parametrize('dx', (None, True))
+    def test_nd(self, axis, x_ndim, x_len, i_ndim, dx, xp):
+        # Test behavior of `cumulative_simpson` with N-D `y`
+        rng = np.random.default_rng(82456839535679456794)
+
+        # determine shapes
+        shape = [5, 6, x_len]
+        shape[axis], shape[-1] = shape[-1], shape[axis]
+        shape_len_1 = shape.copy()
+        shape_len_1[axis] = 1
+        i_shape = shape_len_1 if i_ndim == 3 else ()
+
+        # initialize arguments
+        y = xp.asarray(rng.random(size=shape))
+        x, dx = None, None
+        if dx:
+            dx = rng.random(size=shape_len_1) if x_ndim > 1 else rng.random()
+            dx = xp.asarray(dx)
+        else:
+            x = (np.sort(rng.random(size=shape), axis=axis) if x_ndim > 1
+                 else np.sort(rng.random(size=shape[axis])))
+            x = xp.asarray(x)
+        initial = None if i_ndim is None else xp.asarray(rng.random(size=i_shape))
+
+        # compare results
+        res = cumulative_simpson(y, x=x, dx=dx, initial=initial, axis=axis)
+        # use np to generate `ref` as `cumulative_simpson_nd_ref`
+        # uses `apply_along_axis`
+        ref = cumulative_simpson_nd_reference(
+            np.asarray(y), x=np.asarray(x), dx=None if dx is None else np.asarray(dx),
+            initial=None if initial is None else np.asarray(initial), axis=axis
+        )
+        xp_assert_close(res, xp.asarray(ref), rtol=1e-15)
+
+    @pytest.mark.parametrize(('message', 'kwarg_update'), [
+        ("x must be strictly increasing", dict(x=[2, 2, 3, 4])),
+        ("x must be strictly increasing", dict(x=[x0, [2, 2, 4, 8]], y=[y0, y0])),
+        ("x must be strictly increasing", dict(x=[x0, x0, x0], y=[y0, y0, y0], axis=0)),
+        ("At least one point is required", dict(x=[], y=[])),
+        ("`axis=4` is not valid for `y` with `y.ndim=1`", dict(axis=4)),
+        ("shape of `x` must be the same as `y` or 1-D", dict(x=np.arange(5))),
+        ("`initial` must either be a scalar or...", dict(initial=np.arange(5))),
+        ("`dx` must either be a scalar or...", dict(x=None, dx=np.arange(5))),
+    ])
+    def test_simpson_exceptions(self, message, kwarg_update, xp):
+        kwargs0 = dict(y=xp.asarray(self.y0), x=xp.asarray(self.x0), dx=None,
+                       initial=None, axis=-1)
+        kwarg_update = {k: xp.asarray(np.asarray(v)) if isinstance(v, list) else v
+                        for k, v in kwarg_update.items()}
+        with pytest.raises(ValueError, match=message):
+            cumulative_simpson(**dict(kwargs0, **kwarg_update))
+
+    def test_special_cases(self, xp):
+        # Test special cases not checked elsewhere
+        rng = np.random.default_rng(82456839535679456794)
+        y = xp.asarray(rng.random(size=10))
+        res = cumulative_simpson(y, dx=0.)
+        xp_assert_equal(res, xp.zeros(9, dtype=xp.float64))
+
+        # Should add tests of:
+        # - all elements of `x` identical
+        # These should work as they do for `simpson`
+
+    def _get_theoretical_diff_between_simps_and_cum_simps(self, y, x):
+        """`cumulative_simpson` and `simpson` can be tested against other to verify
+        they give consistent results. `simpson` will iteratively be called with
+        successively higher upper limits of integration. This function calculates
+        the theoretical correction required to `simpson` at even intervals to match
+        with `cumulative_simpson`.
+        """
+        d = np.diff(x, axis=-1)
+        sub_integrals_h1 = _cumulative_simpson_unequal_intervals(y, d)
+        sub_integrals_h2 = _cumulative_simpson_unequal_intervals(
+            y[..., ::-1], d[..., ::-1]
+        )[..., ::-1]
+
+        # Concatenate to build difference array
+        zeros_shape = (*y.shape[:-1], 1)
+        theoretical_difference = np.concatenate(
+            [
+                np.zeros(zeros_shape),
+                (sub_integrals_h1[..., 1:] - sub_integrals_h2[..., :-1]),
+                np.zeros(zeros_shape),
+            ],
+            axis=-1,
+        )
+        # Differences only expected at even intervals. Odd intervals will
+        # match exactly so there is no correction
+        theoretical_difference[..., 1::2] = 0.0
+        # Note: the first interval will not match from this correction as
+        # `simpson` uses the trapezoidal rule
+        return theoretical_difference
+
+    @pytest.mark.fail_slow(10)
+    @pytest.mark.slow
+    @given(
+        y=hyp_num.arrays(
+            np.float64,
+            hyp_num.array_shapes(max_dims=4, min_side=3, max_side=10),
+            elements=st.floats(-10, 10, allow_nan=False).filter(lambda x: abs(x) > 1e-7)
+        )
+    )
+    def test_cumulative_simpson_against_simpson_with_default_dx(
+        self, y, xp
+    ):
+        """Theoretically, the output of `cumulative_simpson` will be identical
+        to `simpson` at all even indices and in the last index. The first index
+        will not match as `simpson` uses the trapezoidal rule when there are only two
+        data points. Odd indices after the first index are shown to match with
+        a mathematically-derived correction."""
+        def simpson_reference(y):
+            return np.stack(
+                [simpson(y[..., :i], dx=1.0) for i in range(2, y.shape[-1]+1)], axis=-1,
+            )
+
+        res = cumulative_simpson(xp.asarray(y), dx=1.0)
+        ref = simpson_reference(y)
+        theoretical_difference = self._get_theoretical_diff_between_simps_and_cum_simps(
+            y, x=np.arange(y.shape[-1])
+        )
+        xp_assert_close(
+            res[..., 1:], xp.asarray(ref[..., 1:] + theoretical_difference[..., 1:]),
+            atol=1e-16
+        )
+
+    @pytest.mark.fail_slow(10)
+    @pytest.mark.slow
+    @given(
+        y=hyp_num.arrays(
+            np.float64,
+            hyp_num.array_shapes(max_dims=4, min_side=3, max_side=10),
+            elements=st.floats(-10, 10, allow_nan=False).filter(lambda x: abs(x) > 1e-7)
+        )
+    )
+    def test_cumulative_simpson_against_simpson(
+        self, y, xp
+    ):
+        """Theoretically, the output of `cumulative_simpson` will be identical
+        to `simpson` at all even indices and in the last index. The first index
+        will not match as `simpson` uses the trapezoidal rule when there are only two
+        data points. Odd indices after the first index are shown to match with
+        a mathematically-derived correction."""
+        interval = 10/(y.shape[-1] - 1)
+        x = np.linspace(0, 10, num=y.shape[-1])
+        x[1:] = x[1:] + 0.2*interval*np.random.uniform(-1, 1, len(x) - 1)
+
+        def simpson_reference(y, x):
+            return np.stack(
+                [simpson(y[..., :i], x=x[..., :i]) for i in range(2, y.shape[-1]+1)],
+                axis=-1,
+            )
+
+        res = cumulative_simpson(xp.asarray(y), x=xp.asarray(x))
+        ref = simpson_reference(y, x)
+        theoretical_difference = self._get_theoretical_diff_between_simps_and_cum_simps(
+            y, x
+        )
+        xp_assert_close(
+            res[..., 1:], xp.asarray(ref[..., 1:] + theoretical_difference[..., 1:])
+        )
+
+
+@make_xp_test_case(integrate.lebedev_rule)
+class TestLebedev:
+    def test_input_validation(self):
+        # only certain rules are available
+        message = "Order n=-1 not available..."
+        with pytest.raises(NotImplementedError, match=message):
+            integrate.lebedev_rule(-1)
+
+    def test_quadrature(self):
+        # Test points/weights to integrate an example function
+
+        def f(x):
+            return np.exp(x[0])
+
+        x, w = integrate.lebedev_rule(15)
+        res = w @ f(x)
+        ref = 14.7680137457653  # lebedev_rule reference [3]
+        assert_allclose(res, ref, rtol=1e-14)
+        assert_allclose(np.sum(w), 4 * np.pi)
+
+    @pytest.mark.parametrize('order', list(range(3, 32, 2)) + list(range(35, 132, 6)))
+    def test_properties(self, order):
+        x, w = integrate.lebedev_rule(order)
+        # dispersion should be maximal; no clear spherical mean
+        with np.errstate(divide='ignore', invalid='ignore'):
+            res = stats.directional_stats(x.T, axis=0)
+            assert_allclose(res.mean_resultant_length, 0, atol=1e-15)
+        # weights should sum to 4*pi (surface area of unit sphere)
+        assert_allclose(np.sum(w), 4*np.pi)
diff --git a/.venv/lib/python3.12/site-packages/scipy/integrate/tests/test_tanhsinh.py b/.venv/lib/python3.12/site-packages/scipy/integrate/tests/test_tanhsinh.py
new file mode 100644
index 0000000000000000000000000000000000000000..24c3bdfee0a2bd99e7da84931b63ff04369416c3
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/integrate/tests/test_tanhsinh.py
@@ -0,0 +1,1187 @@
+# mypy: disable-error-code="attr-defined"
+import os
+import pytest
+import math
+
+import numpy as np
+from numpy.testing import assert_allclose
+
+import scipy._lib._elementwise_iterative_method as eim
+from scipy._lib._array_api_no_0d import xp_assert_close, xp_assert_equal
+from scipy._lib._array_api import (array_namespace, xp_size, xp_ravel, xp_copy,
+                                   is_numpy, make_xp_test_case)
+from scipy import special, stats
+from scipy.integrate import quad_vec, nsum, tanhsinh as _tanhsinh
+from scipy.integrate._tanhsinh import _pair_cache
+from scipy.special._ufuncs import _gen_harmonic
+
+
+def norm_pdf(x, xp=None):
+    xp = array_namespace(x) if xp is None else xp
+    return 1/(2*xp.pi)**0.5 * xp.exp(-x**2/2)
+
+
+def norm_logpdf(x, xp=None):
+    xp = array_namespace(x) if xp is None else xp
+    return -0.5*math.log(2*xp.pi) - x**2/2
+
+
+def _vectorize(xp):
+    # xp-compatible version of np.vectorize
+    # assumes arguments are all arrays of the same shape
+    def decorator(f):
+        def wrapped(*arg_arrays):
+            shape = arg_arrays[0].shape
+            arg_arrays = [xp_ravel(arg_array) for arg_array in arg_arrays]
+            res = []
+            for i in range(math.prod(shape)):
+                arg_scalars = [arg_array[i] for arg_array in arg_arrays]
+                res.append(f(*arg_scalars))
+            return res
+
+        return wrapped
+
+    return decorator
+
+
+@make_xp_test_case(_tanhsinh)
+class TestTanhSinh:
+
+    # Test problems from [1] Section 6
+    def f1(self, t):
+        return t * np.log(1 + t)
+
+    f1.ref = 0.25
+    f1.b = 1
+
+    def f2(self, t):
+        return t ** 2 * np.arctan(t)
+
+    f2.ref = (np.pi - 2 + 2 * np.log(2)) / 12
+    f2.b = 1
+
+    def f3(self, t):
+        return np.exp(t) * np.cos(t)
+
+    f3.ref = (np.exp(np.pi / 2) - 1) / 2
+    f3.b = np.pi / 2
+
+    def f4(self, t):
+        a = np.sqrt(2 + t ** 2)
+        return np.arctan(a) / ((1 + t ** 2) * a)
+
+    f4.ref = 5 * np.pi ** 2 / 96
+    f4.b = 1
+
+    def f5(self, t):
+        return np.sqrt(t) * np.log(t)
+
+    f5.ref = -4 / 9
+    f5.b = 1
+
+    def f6(self, t):
+        return np.sqrt(1 - t ** 2)
+
+    f6.ref = np.pi / 4
+    f6.b = 1
+
+    def f7(self, t):
+        return np.sqrt(t) / np.sqrt(1 - t ** 2)
+
+    f7.ref = 2 * np.sqrt(np.pi) * special.gamma(3 / 4) / special.gamma(1 / 4)
+    f7.b = 1
+
+    def f8(self, t):
+        return np.log(t) ** 2
+
+    f8.ref = 2
+    f8.b = 1
+
+    def f9(self, t):
+        return np.log(np.cos(t))
+
+    f9.ref = -np.pi * np.log(2) / 2
+    f9.b = np.pi / 2
+
+    def f10(self, t):
+        return np.sqrt(np.tan(t))
+
+    f10.ref = np.pi * np.sqrt(2) / 2
+    f10.b = np.pi / 2
+
+    def f11(self, t):
+        return 1 / (1 + t ** 2)
+
+    f11.ref = np.pi / 2
+    f11.b = np.inf
+
+    def f12(self, t):
+        return np.exp(-t) / np.sqrt(t)
+
+    f12.ref = np.sqrt(np.pi)
+    f12.b = np.inf
+
+    def f13(self, t):
+        return np.exp(-t ** 2 / 2)
+
+    f13.ref = np.sqrt(np.pi / 2)
+    f13.b = np.inf
+
+    def f14(self, t):
+        return np.exp(-t) * np.cos(t)
+
+    f14.ref = 0.5
+    f14.b = np.inf
+
+    def f15(self, t):
+        return np.sin(t) / t
+
+    f15.ref = np.pi / 2
+    f15.b = np.inf
+
+    def error(self, res, ref, log=False, xp=None):
+        xp = array_namespace(res, ref) if xp is None else xp
+        err = abs(res - ref)
+
+        if not log:
+            return err
+
+        with np.errstate(divide='ignore'):
+            return xp.log10(err)
+
+    def test_input_validation(self, xp):
+        f = self.f1
+
+        zero = xp.asarray(0)
+        f_b = xp.asarray(f.b)
+
+        message = '`f` must be callable.'
+        with pytest.raises(ValueError, match=message):
+            _tanhsinh(42, zero, f_b)
+
+        message = '...must be True or False.'
+        with pytest.raises(ValueError, match=message):
+            _tanhsinh(f, zero, f_b, log=2)
+
+        message = '...must be real numbers.'
+        with pytest.raises(ValueError, match=message):
+            _tanhsinh(f, xp.asarray(1+1j), f_b)
+        with pytest.raises(ValueError, match=message):
+            _tanhsinh(f, zero, f_b, atol='ekki')
+        with pytest.raises(ValueError, match=message):
+            _tanhsinh(f, zero, f_b, rtol=pytest)
+
+        message = '...must be non-negative and finite.'
+        with pytest.raises(ValueError, match=message):
+            _tanhsinh(f, zero, f_b, rtol=-1)
+        with pytest.raises(ValueError, match=message):
+            _tanhsinh(f, zero, f_b, atol=xp.inf)
+
+        message = '...may not be positive infinity.'
+        with pytest.raises(ValueError, match=message):
+            _tanhsinh(f, zero, f_b, rtol=xp.inf, log=True)
+        with pytest.raises(ValueError, match=message):
+            _tanhsinh(f, zero, f_b, atol=xp.inf, log=True)
+
+        message = '...must be integers.'
+        with pytest.raises(ValueError, match=message):
+            _tanhsinh(f, zero, f_b, maxlevel=object())
+        # with pytest.raises(ValueError, match=message):  # unused for now
+        #     _tanhsinh(f, zero, f_b, maxfun=1+1j)
+        with pytest.raises(ValueError, match=message):
+            _tanhsinh(f, zero, f_b, minlevel="migratory coconut")
+
+        message = '...must be non-negative.'
+        with pytest.raises(ValueError, match=message):
+            _tanhsinh(f, zero, f_b, maxlevel=-1)
+        # with pytest.raises(ValueError, match=message):  # unused for now
+        #     _tanhsinh(f, zero, f_b, maxfun=-1)
+        with pytest.raises(ValueError, match=message):
+            _tanhsinh(f, zero, f_b, minlevel=-1)
+
+        message = '...must be True or False.'
+        with pytest.raises(ValueError, match=message):
+            _tanhsinh(f, zero, f_b, preserve_shape=2)
+
+        message = '...must be callable.'
+        with pytest.raises(ValueError, match=message):
+            _tanhsinh(f, zero, f_b, callback='elderberry')
+
+    @pytest.mark.parametrize("limits, ref", [
+        [(0, math.inf), 0.5],  # b infinite
+        [(-math.inf, 0), 0.5],  # a infinite
+        [(-math.inf, math.inf), 1.],  # a and b infinite
+        [(math.inf, -math.inf), -1.],  # flipped limits
+        [(1, -1), stats.norm.cdf(-1.) -  stats.norm.cdf(1.)],  # flipped limits
+    ])
+    def test_integral_transforms(self, limits, ref, xp):
+        # Check that the integral transforms are behaving for both normal and
+        # log integration
+        limits = [xp.asarray(limit) for limit in limits]
+        dtype = xp.asarray(float(limits[0])).dtype
+        ref = xp.asarray(ref, dtype=dtype)
+
+        res = _tanhsinh(norm_pdf, *limits)
+        xp_assert_close(res.integral, ref)
+
+        logres = _tanhsinh(norm_logpdf, *limits, log=True)
+        xp_assert_close(xp.exp(logres.integral), ref, check_dtype=False)
+        # Transformation should not make the result complex unnecessarily
+        assert (xp.isdtype(logres.integral.dtype, "real floating") if ref > 0
+                else xp.isdtype(logres.integral.dtype, "complex floating"))
+
+        atol = 2 * xp.finfo(res.error.dtype).eps
+        xp_assert_close(xp.exp(logres.error), res.error, atol=atol, check_dtype=False)
+
+    # 15 skipped intentionally; it's very difficult numerically
+    @pytest.mark.skip_xp_backends(np_only=True,
+                                  reason='Cumbersome to convert everything.')
+    @pytest.mark.parametrize('f_number', range(1, 15))
+    def test_basic(self, f_number, xp):
+        f = getattr(self, f"f{f_number}")
+        rtol = 2e-8
+        res = _tanhsinh(f, 0, f.b, rtol=rtol)
+        assert_allclose(res.integral, f.ref, rtol=rtol)
+        if f_number not in {7, 12, 14}:  # mildly underestimates error here
+            true_error = abs(self.error(res.integral, f.ref)/res.integral)
+            assert true_error < res.error
+
+        if f_number in {7, 10, 12}:  # succeeds, but doesn't know it
+            return
+
+        assert res.success
+        assert res.status == 0
+
+    @pytest.mark.skip_xp_backends(np_only=True,
+                                  reason="Distributions aren't xp-compatible.")
+    @pytest.mark.parametrize('ref', (0.5, [0.4, 0.6]))
+    @pytest.mark.parametrize('case', stats._distr_params.distcont)
+    def test_accuracy(self, ref, case, xp):
+        distname, params = case
+        if distname in {'dgamma', 'dweibull', 'laplace', 'kstwo'}:
+            # should split up interval at first-derivative discontinuity
+            pytest.skip('tanh-sinh is not great for non-smooth integrands')
+        if (distname in {'studentized_range', 'levy_stable'}
+                and not int(os.getenv('SCIPY_XSLOW', 0))):
+            pytest.skip('This case passes, but it is too slow.')
+        dist = getattr(stats, distname)(*params)
+        x = dist.interval(ref)
+        res = _tanhsinh(dist.pdf, *x)
+        assert_allclose(res.integral, ref)
+
+    @pytest.mark.parametrize('shape', [tuple(), (12,), (3, 4), (3, 2, 2)])
+    def test_vectorization(self, shape, xp):
+        # Test for correct functionality, output shapes, and dtypes for various
+        # input shapes.
+        rng = np.random.default_rng(82456839535679456794)
+        a = xp.asarray(rng.random(shape))
+        b = xp.asarray(rng.random(shape))
+        p = xp.asarray(rng.random(shape))
+        n = math.prod(shape)
+
+        def f(x, p):
+            f.ncall += 1
+            f.feval += 1 if (xp_size(x) == n or x.ndim <= 1) else x.shape[-1]
+            return x**p
+        f.ncall = 0
+        f.feval = 0
+
+        @_vectorize(xp)
+        def _tanhsinh_single(a, b, p):
+            return _tanhsinh(lambda x: x**p, a, b)
+
+        res = _tanhsinh(f, a, b, args=(p,))
+        refs = _tanhsinh_single(a, b, p)
+
+        attrs = ['integral', 'error', 'success', 'status', 'nfev', 'maxlevel']
+        for attr in attrs:
+            ref_attr = xp.stack([getattr(ref, attr) for ref in refs])
+            res_attr = xp_ravel(getattr(res, attr))
+            xp_assert_close(res_attr, ref_attr, rtol=1e-15)
+            assert getattr(res, attr).shape == shape
+
+        assert xp.isdtype(res.success.dtype, 'bool')
+        assert xp.isdtype(res.status.dtype, 'integral')
+        assert xp.isdtype(res.nfev.dtype, 'integral')
+        assert xp.isdtype(res.maxlevel.dtype, 'integral')
+        assert xp.max(res.nfev) == f.feval
+        # maxlevel = 2 -> 3 function calls (2 initialization, 1 work)
+        assert xp.max(res.maxlevel) >= 2
+        assert xp.max(res.maxlevel) == f.ncall
+
+    def test_flags(self, xp):
+        # Test cases that should produce different status flags; show that all
+        # can be produced simultaneously.
+        def f(xs, js):
+            f.nit += 1
+            funcs = [lambda x: xp.exp(-x**2),  # converges
+                     lambda x: xp.exp(x),  # reaches maxiter due to order=2
+                     lambda x: xp.full_like(x, xp.nan)]  # stops due to NaN
+            res = []
+            for i in range(xp_size(js)):
+                x = xs[i, ...]
+                j = int(xp_ravel(js)[i])
+                res.append(funcs[j](x))
+            return xp.stack(res)
+        f.nit = 0
+
+        args = (xp.arange(3, dtype=xp.int64),)
+        a = xp.asarray([xp.inf]*3)
+        b = xp.asarray([-xp.inf] * 3)
+        res = _tanhsinh(f, a, b, maxlevel=5, args=args)
+        ref_flags = xp.asarray([0, -2, -3], dtype=xp.int32)
+        xp_assert_equal(res.status, ref_flags)
+
+    def test_flags_preserve_shape(self, xp):
+        # Same test as above but using `preserve_shape` option to simplify.
+        def f(x):
+            res = [xp.exp(-x[0]**2),  # converges
+                   xp.exp(x[1]),  # reaches maxiter due to order=2
+                   xp.full_like(x[2], xp.nan)]  # stops due to NaN
+            return xp.stack(res)
+
+        a = xp.asarray([xp.inf] * 3)
+        b = xp.asarray([-xp.inf] * 3)
+        res = _tanhsinh(f, a, b, maxlevel=5, preserve_shape=True)
+        ref_flags = xp.asarray([0, -2, -3], dtype=xp.int32)
+        xp_assert_equal(res.status, ref_flags)
+
+    def test_preserve_shape(self, xp):
+        # Test `preserve_shape` option
+        def f(x, xp):
+            return xp.stack([xp.stack([x, xp.sin(10 * x)]),
+                             xp.stack([xp.cos(30 * x), x * xp.sin(100 * x)])])
+
+        ref = quad_vec(lambda x: f(x, np), 0, 1)
+        res = _tanhsinh(lambda x: f(x, xp), xp.asarray(0), xp.asarray(1),
+                        preserve_shape=True)
+        dtype = xp.asarray(0.).dtype
+        xp_assert_close(res.integral, xp.asarray(ref[0], dtype=dtype))
+
+    def test_convergence(self, xp):
+        # demonstrate that number of accurate digits doubles each iteration
+        dtype = xp.float64  # this only works with good precision
+        def f(t):
+            return t * xp.log(1 + t)
+        ref = xp.asarray(0.25, dtype=dtype)
+        a, b = xp.asarray(0., dtype=dtype), xp.asarray(1., dtype=dtype)
+
+        last_logerr = 0
+        for i in range(4):
+            res = _tanhsinh(f, a, b, minlevel=0, maxlevel=i)
+            logerr = self.error(res.integral, ref, log=True, xp=xp)
+            assert (logerr < last_logerr * 2 or logerr < -15.5)
+            last_logerr = logerr
+
+    def test_options_and_result_attributes(self, xp):
+        # demonstrate that options are behaving as advertised and status
+        # messages are as intended
+        def f(x):
+            f.calls += 1
+            f.feval += xp_size(xp.asarray(x))
+            return x**2 * xp.atan(x)
+
+        f.ref = xp.asarray((math.pi - 2 + 2 * math.log(2)) / 12, dtype=xp.float64)
+
+        default_rtol = 1e-12
+        default_atol = f.ref * default_rtol  # effective default absolute tol
+
+        # Keep things simpler by leaving tolerances fixed rather than
+        # having to make them dtype-dependent
+        a = xp.asarray(0., dtype=xp.float64)
+        b = xp.asarray(1., dtype=xp.float64)
+
+        # Test default options
+        f.feval, f.calls = 0, 0
+        ref = _tanhsinh(f, a, b)
+        assert self.error(ref.integral, f.ref) < ref.error < default_atol
+        assert ref.nfev == f.feval
+        ref.calls = f.calls  # reference number of function calls
+        assert ref.success
+        assert ref.status == 0
+
+        # Test `maxlevel` equal to required max level
+        # We should get all the same results
+        f.feval, f.calls = 0, 0
+        maxlevel = int(ref.maxlevel)
+        res = _tanhsinh(f, a, b, maxlevel=maxlevel)
+        res.calls = f.calls
+        assert res == ref
+
+        # Now reduce the maximum level. We won't meet tolerances.
+        f.feval, f.calls = 0, 0
+        maxlevel -= 1
+        assert maxlevel >= 2  # can't compare errors otherwise
+        res = _tanhsinh(f, a, b, maxlevel=maxlevel)
+        assert self.error(res.integral, f.ref) < res.error > default_atol
+        assert res.nfev == f.feval < ref.nfev
+        assert f.calls == ref.calls - 1
+        assert not res.success
+        assert res.status == eim._ECONVERR
+
+        # `maxfun` is currently not enforced
+
+        # # Test `maxfun` equal to required number of function evaluations
+        # # We should get all the same results
+        # f.feval, f.calls = 0, 0
+        # maxfun = ref.nfev
+        # res = _tanhsinh(f, 0, f.b, maxfun = maxfun)
+        # assert res == ref
+        #
+        # # Now reduce `maxfun`. We won't meet tolerances.
+        # f.feval, f.calls = 0, 0
+        # maxfun -= 1
+        # res = _tanhsinh(f, 0, f.b, maxfun=maxfun)
+        # assert self.error(res.integral, f.ref) < res.error > default_atol
+        # assert res.nfev == f.feval < ref.nfev
+        # assert f.calls == ref.calls - 1
+        # assert not res.success
+        # assert res.status == 2
+
+        # Take this result to be the new reference
+        ref = res
+        ref.calls = f.calls
+
+        # Test `atol`
+        f.feval, f.calls = 0, 0
+        # With this tolerance, we should get the exact same result as ref
+        atol = np.nextafter(float(ref.error), np.inf)
+        res = _tanhsinh(f, a, b, rtol=0, atol=atol)
+        assert res.integral == ref.integral
+        assert res.error == ref.error
+        assert res.nfev == f.feval == ref.nfev
+        assert f.calls == ref.calls
+        # Except the result is considered to be successful
+        assert res.success
+        assert res.status == 0
+
+        f.feval, f.calls = 0, 0
+        # With a tighter tolerance, we should get a more accurate result
+        atol = np.nextafter(float(ref.error), -np.inf)
+        res = _tanhsinh(f, a, b, rtol=0, atol=atol)
+        assert self.error(res.integral, f.ref) < res.error < atol
+        assert res.nfev == f.feval > ref.nfev
+        assert f.calls > ref.calls
+        assert res.success
+        assert res.status == 0
+
+        # Test `rtol`
+        f.feval, f.calls = 0, 0
+        # With this tolerance, we should get the exact same result as ref
+        rtol = np.nextafter(float(ref.error/ref.integral), np.inf)
+        res = _tanhsinh(f, a, b, rtol=rtol)
+        assert res.integral == ref.integral
+        assert res.error == ref.error
+        assert res.nfev == f.feval == ref.nfev
+        assert f.calls == ref.calls
+        # Except the result is considered to be successful
+        assert res.success
+        assert res.status == 0
+
+        f.feval, f.calls = 0, 0
+        # With a tighter tolerance, we should get a more accurate result
+        rtol = np.nextafter(float(ref.error/ref.integral), -np.inf)
+        res = _tanhsinh(f, a, b, rtol=rtol)
+        assert self.error(res.integral, f.ref)/f.ref < res.error/res.integral < rtol
+        assert res.nfev == f.feval > ref.nfev
+        assert f.calls > ref.calls
+        assert res.success
+        assert res.status == 0
+
+    @pytest.mark.skip_xp_backends('torch', reason=
+            'https://github.com/scipy/scipy/pull/21149#issuecomment-2330477359',
+    )
+    @pytest.mark.parametrize('rtol', [1e-4, 1e-14])
+    def test_log(self, rtol, xp):
+        # Test equivalence of log-integration and regular integration
+        test_tols = dict(atol=1e-18, rtol=1e-15)
+
+        # Positive integrand (real log-integrand)
+        a = xp.asarray(-1., dtype=xp.float64)
+        b = xp.asarray(2., dtype=xp.float64)
+        res = _tanhsinh(norm_logpdf, a, b, log=True, rtol=math.log(rtol))
+        ref = _tanhsinh(norm_pdf, a, b, rtol=rtol)
+        xp_assert_close(xp.exp(res.integral), ref.integral, **test_tols)
+        xp_assert_close(xp.exp(res.error), ref.error, **test_tols)
+        assert res.nfev == ref.nfev
+
+        # Real integrand (complex log-integrand)
+        def f(x):
+            return -norm_logpdf(x)*norm_pdf(x)
+
+        def logf(x):
+            return xp.log(norm_logpdf(x) + 0j) + norm_logpdf(x) + xp.pi * 1j
+
+        a = xp.asarray(-xp.inf, dtype=xp.float64)
+        b = xp.asarray(xp.inf, dtype=xp.float64)
+        res = _tanhsinh(logf, a, b, log=True)
+        ref = _tanhsinh(f, a, b)
+        # In gh-19173, we saw `invalid` warnings on one CI platform.
+        # Silencing `all` because I can't reproduce locally and don't want
+        # to risk the need to run CI again.
+        with np.errstate(all='ignore'):
+            xp_assert_close(xp.exp(res.integral), ref.integral, **test_tols,
+                            check_dtype=False)
+            xp_assert_close(xp.exp(res.error), ref.error, **test_tols,
+                            check_dtype=False)
+        assert res.nfev == ref.nfev
+
+    def test_complex(self, xp):
+        # Test integration of complex integrand
+        # Finite limits
+        def f(x):
+            return xp.exp(1j * x)
+
+        a, b = xp.asarray(0.), xp.asarray(xp.pi/4)
+        res = _tanhsinh(f, a, b)
+        ref = math.sqrt(2)/2 + (1-math.sqrt(2)/2)*1j
+        xp_assert_close(res.integral, xp.asarray(ref))
+
+        # Infinite limits
+        def f(x):
+            return norm_pdf(x) + 1j/2*norm_pdf(x/2)
+
+        a, b = xp.asarray(xp.inf), xp.asarray(-xp.inf)
+        res = _tanhsinh(f, a, b)
+        xp_assert_close(res.integral, xp.asarray(-(1+1j)))
+
+    @pytest.mark.parametrize("maxlevel", range(4))
+    def test_minlevel(self, maxlevel, xp):
+        # Verify that minlevel does not change the values at which the
+        # integrand is evaluated or the integral/error estimates, only the
+        # number of function calls
+
+        def f(x):
+            f.calls += 1
+            f.feval += xp_size(xp.asarray(x))
+            f.x = xp.concat((f.x, xp_ravel(x)))
+            return x**2 * xp.atan(x)
+
+        f.feval, f.calls, f.x = 0, 0, xp.asarray([])
+
+        a = xp.asarray(0, dtype=xp.float64)
+        b = xp.asarray(1, dtype=xp.float64)
+        ref = _tanhsinh(f, a, b, minlevel=0, maxlevel=maxlevel)
+        ref_x = xp.sort(f.x)
+
+        for minlevel in range(0, maxlevel + 1):
+            f.feval, f.calls, f.x = 0, 0, xp.asarray([])
+            options = dict(minlevel=minlevel, maxlevel=maxlevel)
+            res = _tanhsinh(f, a, b, **options)
+            # Should be very close; all that has changed is the order of values
+            xp_assert_close(res.integral, ref.integral, rtol=4e-16)
+            # Difference in absolute errors << magnitude of integral
+            xp_assert_close(res.error, ref.error, atol=4e-16 * ref.integral)
+            assert res.nfev == f.feval == f.x.shape[0]
+            assert f.calls == maxlevel - minlevel + 1 + 1  # 1 validation call
+            assert res.status == ref.status
+            xp_assert_equal(ref_x, xp.sort(f.x))
+
+    def test_improper_integrals(self, xp):
+        # Test handling of infinite limits of integration (mixed with finite limits)
+        def f(x):
+            x[xp.isinf(x)] = xp.nan
+            return xp.exp(-x**2)
+        a = xp.asarray([-xp.inf, 0, -xp.inf, xp.inf, -20, -xp.inf, -20])
+        b = xp.asarray([xp.inf, xp.inf, 0, -xp.inf, 20, 20, xp.inf])
+        ref = math.sqrt(math.pi)
+        ref = xp.asarray([ref, ref/2, ref/2, -ref, ref, ref, ref])
+        res = _tanhsinh(f, a, b)
+        xp_assert_close(res.integral, ref)
+
+    @pytest.mark.parametrize("limits", ((0, 3), ([-math.inf, 0], [3, 3])))
+    @pytest.mark.parametrize("dtype", ('float32', 'float64'))
+    def test_dtype(self, limits, dtype, xp):
+        # Test that dtypes are preserved
+        dtype = getattr(xp, dtype)
+        a, b = xp.asarray(limits, dtype=dtype)
+
+        def f(x):
+            assert x.dtype == dtype
+            return xp.exp(x)
+
+        rtol = 1e-12 if dtype == xp.float64 else 1e-5
+        res = _tanhsinh(f, a, b, rtol=rtol)
+        assert res.integral.dtype == dtype
+        assert res.error.dtype == dtype
+        assert xp.all(res.success)
+        xp_assert_close(res.integral, xp.exp(b)-xp.exp(a))
+
+    def test_maxiter_callback(self, xp):
+        # Test behavior of `maxiter` parameter and `callback` interface
+        a, b = xp.asarray(-xp.inf), xp.asarray(xp.inf)
+        def f(x):
+            return xp.exp(-x*x)
+
+        minlevel, maxlevel = 0, 2
+        maxiter = maxlevel - minlevel + 1
+        kwargs = dict(minlevel=minlevel, maxlevel=maxlevel, rtol=1e-15)
+        res = _tanhsinh(f, a, b, **kwargs)
+        assert not res.success
+        assert res.maxlevel == maxlevel
+
+        def callback(res):
+            callback.iter += 1
+            callback.res = res
+            assert hasattr(res, 'integral')
+            assert res.status == 1
+            if callback.iter == maxiter:
+                raise StopIteration
+        callback.iter = -1  # callback called once before first iteration
+        callback.res = None
+
+        del kwargs['maxlevel']
+        res2 = _tanhsinh(f, a, b, **kwargs, callback=callback)
+        # terminating with callback is identical to terminating due to maxiter
+        # (except for `status`)
+        for key in res.keys():
+            if key == 'status':
+                assert res[key] == -2
+                assert res2[key] == -4
+            else:
+                assert res2[key] == callback.res[key] == res[key]
+
+    def test_jumpstart(self, xp):
+        # The intermediate results at each level i should be the same as the
+        # final results when jumpstarting at level i; i.e. minlevel=maxlevel=i
+        a = xp.asarray(-xp.inf, dtype=xp.float64)
+        b = xp.asarray(xp.inf, dtype=xp.float64)
+
+        def f(x):
+            return xp.exp(-x*x)
+
+        def callback(res):
+            callback.integrals.append(xp_copy(res.integral)[()])
+            callback.errors.append(xp_copy(res.error)[()])
+        callback.integrals = []
+        callback.errors = []
+
+        maxlevel = 4
+        _tanhsinh(f, a, b, minlevel=0, maxlevel=maxlevel, callback=callback)
+
+        for i in range(maxlevel + 1):
+            res = _tanhsinh(f, a, b, minlevel=i, maxlevel=i)
+            xp_assert_close(callback.integrals[1+i], res.integral, rtol=1e-15)
+            xp_assert_close(callback.errors[1+i], res.error, rtol=1e-15, atol=1e-16)
+
+    def test_special_cases(self, xp):
+        # Test edge cases and other special cases
+        a, b = xp.asarray(0), xp.asarray(1)
+
+        def f(x):
+            assert xp.isdtype(x.dtype, "real floating")
+            return x
+
+        res = _tanhsinh(f, a, b)
+        assert res.success
+        xp_assert_close(res.integral, xp.asarray(0.5))
+
+        # Test levels 0 and 1; error is NaN
+        res = _tanhsinh(f, a, b, maxlevel=0)
+        assert res.integral > 0
+        xp_assert_equal(res.error, xp.asarray(xp.nan))
+        res = _tanhsinh(f, a, b, maxlevel=1)
+        assert res.integral > 0
+        xp_assert_equal(res.error, xp.asarray(xp.nan))
+
+        # Test equal left and right integration limits
+        res = _tanhsinh(f, b, b)
+        assert res.success
+        assert res.maxlevel == -1
+        xp_assert_close(res.integral, xp.asarray(0.))
+
+        # Test scalar `args` (not in tuple)
+        def f(x, c):
+            return x**c
+
+        res = _tanhsinh(f, a, b, args=xp.asarray(29.))
+        xp_assert_close(res.integral, xp.asarray(1/30))
+
+        # Test NaNs
+        a = xp.asarray([xp.nan, 0, 0, 0])
+        b = xp.asarray([1, xp.nan, 1, 1])
+        c = xp.asarray([1, 1, xp.nan, 1])
+        res = _tanhsinh(f, a, b, args=(c,))
+        xp_assert_close(res.integral, xp.asarray([xp.nan, xp.nan, xp.nan, 0.5]))
+        xp_assert_equal(res.error[:3], xp.full((3,), xp.nan))
+        xp_assert_equal(res.status, xp.asarray([-3, -3, -3, 0], dtype=xp.int32))
+        xp_assert_equal(res.success, xp.asarray([False, False, False, True]))
+        xp_assert_equal(res.nfev[:3], xp.full((3,), 1, dtype=xp.int32))
+
+        # Test complex integral followed by real integral
+        # Previously, h0 was of the result dtype. If the `dtype` were complex,
+        # this could lead to complex cached abscissae/weights. If these get
+        # cast to real dtype for a subsequent real integral, we would get a
+        # ComplexWarning. Check that this is avoided.
+        _pair_cache.xjc = xp.empty(0)
+        _pair_cache.wj = xp.empty(0)
+        _pair_cache.indices = [0]
+        _pair_cache.h0 = None
+        a, b = xp.asarray(0), xp.asarray(1)
+        res = _tanhsinh(lambda x: xp.asarray(x*1j), a, b)
+        xp_assert_close(res.integral, xp.asarray(0.5*1j))
+        res = _tanhsinh(lambda x: x, a, b)
+        xp_assert_close(res.integral, xp.asarray(0.5))
+
+        # Test zero-size
+        shape = (0, 3)
+        res = _tanhsinh(lambda x: x, xp.asarray(0), xp.zeros(shape))
+        attrs = ['integral', 'error', 'success', 'status', 'nfev', 'maxlevel']
+        for attr in attrs:
+            assert res[attr].shape == shape
+
+    @pytest.mark.skip_xp_backends(np_only=True)
+    def test_compress_nodes_weights_gh21496(self, xp):
+        # See discussion in:
+        # https://github.com/scipy/scipy/pull/21496#discussion_r1878681049
+        # This would cause "ValueError: attempt to get argmax of an empty sequence"
+        # Check that this has been resolved.
+        x = np.full(65, 3)
+        x[-1] = 1000
+        _tanhsinh(np.sin, 1, x)
+
+    def test_gh_22681_finite_error(self, xp):
+        # gh-22681 noted a case in which the error was NaN on some platforms;
+        # check that this does in fact fail in CI.
+        c1 = complex(12, -10)
+        c2 = complex(12, 39)
+        def f(t):
+            return xp.sin(c1 * (1 - t) + c2 * t)
+        a, b = xp.asarray(0., dtype=xp.float64), xp.asarray(1., dtype=xp.float64)
+        ref = _tanhsinh(f, a, b, atol=0, rtol=0, maxlevel=10)
+        assert xp.isfinite(ref.error)
+        # Previously, tanhsinh would not detect convergence
+        res = _tanhsinh(f, a, b, rtol=1e-14)
+        assert res.success
+        assert res.maxlevel < 5
+        xp_assert_close(res.integral, ref.integral, rtol=1e-15)
+
+    @pytest.mark.parametrize('dtype', ['float32', 'float64'])
+    def test_kwargs(self, xp, dtype):
+        # test that `kwargs` is used, broadcasts correctly, and affects dtype
+        def f(x, c, *, p):
+            return x**p + c
+
+        a = xp.zeros((), dtype=xp.float32)
+        b = xp.ones((), dtype=xp.float32)
+        c = xp.asarray([1, 2, 3], dtype=xp.float32)
+        p = xp.asarray([2, 3, 4], dtype=getattr(xp, dtype))[:, xp.newaxis]
+        res = _tanhsinh(f, a, b, args=(c,), kwargs={'p': p})
+        ref = b**(p+1) / (p+1) + c
+        xp_assert_close(res.integral, ref)
+
+
+@make_xp_test_case(nsum)
+class TestNSum:
+    rng = np.random.default_rng(5895448232066142650)
+    p = rng.uniform(1, 10, size=10).tolist()
+
+    def f1(self, k):
+        # Integers are never passed to `f1`; if they were, we'd get
+        # integer to negative integer power error
+        return k**(-2)
+
+    f1.ref = np.pi**2/6
+    f1.a = 1
+    f1.b = np.inf
+    f1.args = tuple()
+
+    def f2(self, k, p):
+        return 1 / k**p
+
+    f2.ref = special.zeta(p, 1)
+    f2.a = 1.
+    f2.b = np.inf
+    f2.args = (p,)
+
+    def f3(self, k, p):
+        return 1 / k**p
+
+    f3.a = 1
+    f3.b = rng.integers(5, 15, size=(3, 1))
+    f3.ref = _gen_harmonic(f3.b, p)
+    f3.args = (p,)
+
+    def test_input_validation(self, xp):
+        f = self.f1
+        a, b = xp.asarray(f.a), xp.asarray(f.b)
+
+        message = '`f` must be callable.'
+        with pytest.raises(ValueError, match=message):
+            nsum(42, a, b)
+
+        message = '...must be True or False.'
+        with pytest.raises(ValueError, match=message):
+            nsum(f, a, b, log=2)
+
+        message = '...must be real numbers.'
+        with pytest.raises(ValueError, match=message):
+            nsum(f, xp.asarray(1+1j), b)
+        with pytest.raises(ValueError, match=message):
+            nsum(f, a, xp.asarray(1+1j))
+        with pytest.raises(ValueError, match=message):
+            nsum(f, a, b, step=xp.asarray(1+1j))
+        with pytest.raises(ValueError, match=message):
+            nsum(f, a, b, tolerances=dict(atol='ekki'))
+        with pytest.raises(ValueError, match=message):
+            nsum(f, a, b, tolerances=dict(rtol=pytest))
+
+        with (np.errstate(all='ignore')):
+            res = nsum(f, xp.asarray([np.nan, np.inf]), xp.asarray(1.))
+            assert (res.status[0] == -1) and not res.success[0]
+            assert xp.isnan(res.sum[0]) and xp.isnan(res.error[0])
+            assert (res.status[1] == 0) and res.success[1]
+            assert res.sum[1] == res.error[1]
+            assert xp.all(res.nfev[0] == 1)
+
+            res = nsum(f, xp.asarray(10.), xp.asarray([np.nan, 1]))
+            assert (res.status[0] == -1) and not res.success[0]
+            assert xp.isnan(res.sum[0]) and xp.isnan(res.error[0])
+            assert (res.status[1] == 0) and res.success[1]
+            assert res.sum[1] == res.error[1]
+            assert xp.all(res.nfev[0] == 1)
+
+            res = nsum(f, xp.asarray(1.), xp.asarray(10.),
+                       step=xp.asarray([xp.nan, -xp.inf, xp.inf, -1, 0]))
+            assert xp.all((res.status == -1) & xp.isnan(res.sum)
+                          & xp.isnan(res.error) & ~res.success & res.nfev == 1)
+
+        message = '...must be non-negative and finite.'
+        with pytest.raises(ValueError, match=message):
+            nsum(f, a, b, tolerances=dict(rtol=-1))
+        with pytest.raises(ValueError, match=message):
+            nsum(f, a, b, tolerances=dict(atol=np.inf))
+
+        message = '...may not be positive infinity.'
+        with pytest.raises(ValueError, match=message):
+            nsum(f, a, b, tolerances=dict(rtol=np.inf), log=True)
+        with pytest.raises(ValueError, match=message):
+            nsum(f, a, b, tolerances=dict(atol=np.inf), log=True)
+
+        message = '...must be a non-negative integer.'
+        with pytest.raises(ValueError, match=message):
+            nsum(f, a, b, maxterms=3.5)
+        with pytest.raises(ValueError, match=message):
+            nsum(f, a, b, maxterms=-2)
+
+    @pytest.mark.parametrize('f_number', range(1, 4))
+    def test_basic(self, f_number, xp):
+        dtype = xp.asarray(1.).dtype
+        f = getattr(self, f"f{f_number}")
+        a, b = xp.asarray(f.a), xp.asarray(f.b),
+        args = tuple(xp.asarray(arg) for arg in f.args)
+        ref = xp.asarray(f.ref, dtype=dtype)
+        res = nsum(f, a, b, args=args)
+        xp_assert_close(res.sum, ref)
+        xp_assert_equal(res.status, xp.zeros(ref.shape, dtype=xp.int32))
+        xp_assert_equal(res.success, xp.ones(ref.shape, dtype=xp.bool))
+
+        with np.errstate(divide='ignore'):
+            logres = nsum(lambda *args: xp.log(f(*args)),
+                           a, b, log=True, args=args)
+        xp_assert_close(xp.exp(logres.sum), res.sum)
+        xp_assert_close(xp.exp(logres.error), res.error, atol=1e-15)
+        xp_assert_equal(logres.status, res.status)
+        xp_assert_equal(logres.success, res.success)
+
+    @pytest.mark.parametrize('maxterms', [0, 1, 10, 20, 100])
+    def test_integral(self, maxterms, xp):
+        # test precise behavior of integral approximation
+        f = self.f1
+
+        def logf(x):
+            return -2*xp.log(x)
+
+        def F(x):
+            return -1 / x
+
+        a = xp.asarray([1, 5], dtype=xp.float64)[:, xp.newaxis]
+        b = xp.asarray([20, 100, xp.inf], dtype=xp.float64)[:, xp.newaxis, xp.newaxis]
+        step = xp.asarray([0.5, 1, 2], dtype=xp.float64).reshape((-1, 1, 1, 1))
+        nsteps = xp.floor((b - a)/step)
+        b_original = b
+        b = a + nsteps*step
+
+        k = a + maxterms*step
+        # partial sum
+        direct = xp.sum(f(a + xp.arange(maxterms)*step), axis=-1, keepdims=True)
+        integral = (F(b) - F(k))/step  # integral approximation of remainder
+        low = direct + integral + f(b)  # theoretical lower bound
+        high = direct + integral + f(k)  # theoretical upper bound
+        ref_sum = (low + high)/2  # nsum uses average of the two
+        ref_err = (high - low)/2  # error (assuming perfect quadrature)
+
+        # correct reference values where number of terms < maxterms
+        a, b, step = xp.broadcast_arrays(a, b, step)
+        for i in np.ndindex(a.shape):
+            ai, bi, stepi = float(a[i]), float(b[i]), float(step[i])
+            if (bi - ai)/stepi + 1 <= maxterms:
+                direct = xp.sum(f(xp.arange(ai, bi+stepi, stepi, dtype=xp.float64)))
+                ref_sum[i] = direct
+                ref_err[i] = direct * xp.finfo(direct.dtype).eps
+
+        rtol = 1e-12
+        res = nsum(f, a, b_original, step=step, maxterms=maxterms,
+                   tolerances=dict(rtol=rtol))
+        xp_assert_close(res.sum, ref_sum, rtol=10*rtol)
+        xp_assert_close(res.error, ref_err, rtol=100*rtol)
+
+        i = ((b_original - a)/step + 1 <= maxterms)
+        xp_assert_close(res.sum[i], ref_sum[i], rtol=1e-15)
+        xp_assert_close(res.error[i], ref_err[i], rtol=1e-15)
+
+        logres = nsum(logf, a, b_original, step=step, log=True,
+                      tolerances=dict(rtol=math.log(rtol)), maxterms=maxterms)
+        xp_assert_close(xp.exp(logres.sum), res.sum)
+        xp_assert_close(xp.exp(logres.error), res.error)
+
+    @pytest.mark.parametrize('shape', [tuple(), (12,), (3, 4), (3, 2, 2)])
+    def test_vectorization(self, shape, xp):
+        # Test for correct functionality, output shapes, and dtypes for various
+        # input shapes.
+        rng = np.random.default_rng(82456839535679456794)
+        a = rng.integers(1, 10, size=shape)
+        # when the sum can be computed directly or `maxterms` is large enough
+        # to meet `atol`, there are slight differences (for good reason)
+        # between vectorized call and looping.
+        b = np.inf
+        p = rng.random(shape) + 1
+        n = math.prod(shape)
+
+        def f(x, p):
+            f.feval += 1 if (x.size == n or x.ndim <= 1) else x.shape[-1]
+            return 1 / x ** p
+
+        f.feval = 0
+
+        @np.vectorize
+        def nsum_single(a, b, p, maxterms):
+            return nsum(lambda x: 1 / x**p, a, b, maxterms=maxterms)
+
+        res = nsum(f, xp.asarray(a), xp.asarray(b), maxterms=1000,
+                   args=(xp.asarray(p),))
+        refs = nsum_single(a, b, p, maxterms=1000).ravel()
+
+        attrs = ['sum', 'error', 'success', 'status', 'nfev']
+        for attr in attrs:
+            ref_attr = [xp.asarray(getattr(ref, attr)) for ref in refs]
+            res_attr = getattr(res, attr)
+            xp_assert_close(xp_ravel(res_attr), xp.asarray(ref_attr), rtol=1e-15)
+            assert res_attr.shape == shape
+
+        assert xp.isdtype(res.success.dtype, 'bool')
+        assert xp.isdtype(res.status.dtype, 'integral')
+        assert xp.isdtype(res.nfev.dtype, 'integral')
+        if is_numpy(xp):  # other libraries might have different number
+            assert int(xp.max(res.nfev)) == f.feval
+
+    def test_status(self, xp):
+        f = self.f2
+
+        p = [2, 2, 0.9, 1.1, 2, 2]
+        a = xp.asarray([0, 0, 1, 1, 1, np.nan], dtype=xp.float64)
+        b = xp.asarray([10, np.inf, np.inf, np.inf, np.inf, np.inf], dtype=xp.float64)
+        ref = special.zeta(p, 1)
+        p = xp.asarray(p, dtype=xp.float64)
+
+        with np.errstate(divide='ignore'):  # intentionally dividing by zero
+            res = nsum(f, a, b, args=(p,))
+
+        ref_success = xp.asarray([False, False, False, False, True, False])
+        ref_status = xp.asarray([-3, -3, -2, -4, 0, -1], dtype=xp.int32)
+        xp_assert_equal(res.success, ref_success)
+        xp_assert_equal(res.status, ref_status)
+        xp_assert_close(res.sum[res.success], xp.asarray(ref)[res.success])
+
+    def test_nfev(self, xp):
+        def f(x):
+            f.nfev += xp_size(x)
+            return 1 / x**2
+
+        f.nfev = 0
+        res = nsum(f, xp.asarray(1), xp.asarray(10))
+        assert res.nfev == f.nfev
+
+        f.nfev = 0
+        res = nsum(f, xp.asarray(1), xp.asarray(xp.inf), tolerances=dict(atol=1e-6))
+        assert res.nfev == f.nfev
+
+    def test_inclusive(self, xp):
+        # There was an edge case off-by one bug when `_direct` was called with
+        # `inclusive=True`. Check that this is resolved.
+        a = xp.asarray([1, 4])
+        b = xp.asarray(xp.inf)
+        res = nsum(lambda k: 1 / k ** 2, a, b,
+                   maxterms=500, tolerances=dict(atol=0.1))
+        ref = nsum(lambda k: 1 / k ** 2, a, b)
+        assert xp.all(res.sum > (ref.sum - res.error))
+        assert xp.all(res.sum < (ref.sum + res.error))
+
+    @pytest.mark.parametrize('log', [True, False])
+    def test_infinite_bounds(self, log, xp):
+        a = xp.asarray([1, -np.inf, -np.inf])
+        b = xp.asarray([np.inf, -1, np.inf])
+        c = xp.asarray([1, 2, 3])
+
+        def f(x, a):
+            return (xp.log(xp.tanh(a / 2)) - a*xp.abs(x) if log
+                    else xp.tanh(a/2) * xp.exp(-a*xp.abs(x)))
+
+        res = nsum(f, a, b, args=(c,), log=log)
+        ref = xp.asarray([stats.dlaplace.sf(0, 1), stats.dlaplace.sf(0, 2), 1])
+        ref = xp.log(ref) if log else ref
+        atol = (1e-10 if a.dtype==xp.float64 else 1e-5) if log else 0
+        xp_assert_close(res.sum, xp.asarray(ref, dtype=a.dtype), atol=atol)
+
+        # # Make sure the sign of `x` passed into `f` is correct.
+        def f(x, c):
+            return -3*xp.log(c*x) if log else 1 / (c*x)**3
+
+        a = xp.asarray([1, -np.inf])
+        b = xp.asarray([np.inf, -1])
+        arg = xp.asarray([1, -1])
+        res = nsum(f, a, b, args=(arg,), log=log)
+        ref = np.log(special.zeta(3)) if log else special.zeta(3)
+        xp_assert_close(res.sum, xp.full(a.shape, ref, dtype=a.dtype))
+
+    def test_decreasing_check(self, xp):
+        # Test accuracy when we start sum on an uphill slope.
+        # Without the decreasing check, the terms would look small enough to
+        # use the integral approximation. Because the function is not decreasing,
+        # the error is not bounded by the magnitude of the last term of the
+        # partial sum. In this case, the error would be  ~1e-4, causing the test
+        # to fail.
+        def f(x):
+            return xp.exp(-x ** 2)
+
+        a, b = xp.asarray(-25, dtype=xp.float64), xp.asarray(np.inf, dtype=xp.float64)
+        res = nsum(f, a, b)
+
+        # Reference computed with mpmath:
+        # from mpmath import mp
+        # mp.dps = 50
+        # def fmp(x): return mp.exp(-x**2)
+        # ref = mp.nsum(fmp, (-25, 0)) + mp.nsum(fmp, (1, mp.inf))
+        ref = xp.asarray(1.772637204826652, dtype=xp.float64)
+
+        xp_assert_close(res.sum, ref, rtol=1e-15)
+
+    def test_special_case(self, xp):
+        # test equal lower/upper limit
+        f = self.f1
+        a = b = xp.asarray(2)
+        res = nsum(f, a, b)
+        xp_assert_equal(res.sum, xp.asarray(f(2)))
+
+        # Test scalar `args` (not in tuple)
+        res = nsum(self.f2, xp.asarray(1), xp.asarray(np.inf), args=xp.asarray(2))
+        xp_assert_close(res.sum, xp.asarray(self.f1.ref))  # f1.ref is correct w/ args=2
+
+        # Test 0 size input
+        a = xp.empty((3, 1, 1))  # arbitrary broadcastable shapes
+        b = xp.empty((0, 1))  # could use Hypothesis
+        p = xp.empty(4)  # but it's overkill
+        shape = np.broadcast_shapes(a.shape, b.shape, p.shape)
+        res = nsum(self.f2, a, b, args=(p,))
+        assert res.sum.shape == shape
+        assert res.status.shape == shape
+        assert res.nfev.shape == shape
+
+        # Test maxterms=0
+        def f(x):
+            with np.errstate(divide='ignore'):
+                return 1 / x
+
+        res = nsum(f, xp.asarray(0), xp.asarray(10), maxterms=0)
+        assert xp.isinf(res.sum)
+        assert xp.isinf(res.error)
+        assert res.status == -2
+
+        res = nsum(f, xp.asarray(0), xp.asarray(10), maxterms=1)
+        assert xp.isnan(res.sum)
+        assert xp.isnan(res.error)
+        assert res.status == -3
+
+        # Test NaNs
+        # should skip both direct and integral methods if there are NaNs
+        a = xp.asarray([xp.nan, 1, 1, 1])
+        b = xp.asarray([xp.inf, xp.nan, xp.inf, xp.inf])
+        p = xp.asarray([2, 2, xp.nan, 2])
+        res = nsum(self.f2, a, b, args=(p,))
+        xp_assert_close(res.sum, xp.asarray([xp.nan, xp.nan, xp.nan, self.f1.ref]))
+        xp_assert_close(res.error[:3], xp.full((3,), xp.nan))
+        xp_assert_equal(res.status, xp.asarray([-1, -1, -3, 0], dtype=xp.int32))
+        xp_assert_equal(res.success, xp.asarray([False, False, False, True]))
+        # Ideally res.nfev[2] would be 1, but `tanhsinh` has some function evals
+        xp_assert_equal(res.nfev[:2], xp.full((2,), 1, dtype=xp.int32))
+
+    @pytest.mark.parametrize('dtype', ['float32', 'float64'])
+    def test_dtype(self, dtype, xp):
+        dtype = getattr(xp, dtype)
+
+        def f(k):
+            assert k.dtype == dtype
+            return 1 / k ** xp.asarray(2, dtype=dtype)
+
+        a = xp.asarray(1, dtype=dtype)
+        b = xp.asarray([10, xp.inf], dtype=dtype)
+        res = nsum(f, a, b)
+        assert res.sum.dtype == dtype
+        assert res.error.dtype == dtype
+
+        rtol = 1e-12 if dtype == xp.float64 else 1e-6
+        ref = [_gen_harmonic(10, 2), special.zeta(2, 1)]
+        xp_assert_close(res.sum, xp.asarray(ref, dtype=dtype), rtol=rtol)
+
+    @pytest.mark.parametrize('case', [(10, 100), (100, 10)])
+    def test_nondivisible_interval(self, case, xp):
+        # When the limits of the sum are such that (b - a)/step
+        # is not exactly integral, check that only floor((b - a)/step)
+        # terms are included.
+        n, maxterms = case
+
+        def f(k):
+            return 1 / k ** 2
+
+        a = np.e
+        step = 1 / 3
+        b0 = a + n * step
+        i = np.arange(-2, 3)
+        b = b0 + i * np.spacing(b0)
+        ns = np.floor((b - a) / step)
+        assert len(set(ns)) == 2
+
+        a, b = xp.asarray(a, dtype=xp.float64), xp.asarray(b, dtype=xp.float64)
+        step, ns = xp.asarray(step, dtype=xp.float64), xp.asarray(ns, dtype=xp.float64)
+        res = nsum(f, a, b, step=step, maxterms=maxterms)
+        xp_assert_equal(xp.diff(ns) > 0, xp.diff(res.sum) > 0)
+        xp_assert_close(res.sum[-1], res.sum[0] + f(b0))
+
+    @pytest.mark.skip_xp_backends(np_only=True, reason='Needs beta function.')
+    def test_logser_kurtosis_gh20648(self, xp):
+        # Some functions return NaN at infinity rather than 0 like they should.
+        # Check that this is accounted for.
+        ref = stats.yulesimon.moment(4, 5)
+        def f(x):
+            return stats.yulesimon._pmf(x, 5) * x**4
+
+        with np.errstate(invalid='ignore'):
+            assert np.isnan(f(np.inf))
+
+        res = nsum(f, 1, np.inf)
+        assert_allclose(res.sum, ref)
+
+    @pytest.mark.parametrize('dtype', ['float32', 'float64'])
+    def test_kwargs(self, xp, dtype):
+        # test that `kwargs` is used, broadcasts correctly, and affects dtype
+        def f(x, c, *, p):
+            return x**-p + c
+
+        a = xp.ones((), dtype=xp.float32)
+        b = xp.full((), 10, dtype=xp.float32)
+        c = xp.asarray([1, 2, 3], dtype=xp.float32)
+        p = xp.asarray([2, 3, 4], dtype=getattr(xp, dtype))[:, xp.newaxis]
+        res = nsum(f, a, b, args=(c,), kwargs={'p': p})
+        x = xp.arange(1, 11, dtype=xp.float32)
+        ref = xp.sum(f(x, c[..., xp.newaxis], p=p[..., xp.newaxis]), axis=-1)
+        xp_assert_close(res.sum, ref)
diff --git a/.venv/lib/python3.12/site-packages/scipy/integrate/vode.py b/.venv/lib/python3.12/site-packages/scipy/integrate/vode.py
new file mode 100644
index 0000000000000000000000000000000000000000..f92927901084ce33cdeb006057d85dd501b13aae
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/integrate/vode.py
@@ -0,0 +1,15 @@
+# This file is not meant for public use and will be removed in SciPy v2.0.0.
+
+from scipy._lib.deprecation import _sub_module_deprecation
+
+__all__: list[str] = []
+
+
+def __dir__():
+    return __all__
+
+
+def __getattr__(name):
+    return _sub_module_deprecation(sub_package="integrate", module="vode",
+                                   private_modules=["_vode"], all=__all__,
+                                   attribute=name)
diff --git a/.venv/lib/python3.12/site-packages/scipy/interpolate/__init__.py b/.venv/lib/python3.12/site-packages/scipy/interpolate/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..8be2d80bea342e3b6b3df7d13e17f969ef1f224b
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/interpolate/__init__.py
@@ -0,0 +1,228 @@
+"""
+========================================
+Interpolation (:mod:`scipy.interpolate`)
+========================================
+
+.. currentmodule:: scipy.interpolate
+
+Sub-package for functions and objects used in interpolation.
+
+See the :ref:`user guide ` for recommendations on choosing a
+routine, and other usage details.
+
+
+Univariate interpolation
+========================
+
+.. autosummary::
+   :toctree: generated/
+
+   make_interp_spline
+   CubicSpline
+   PchipInterpolator
+   Akima1DInterpolator
+   FloaterHormannInterpolator
+   BarycentricInterpolator
+   KroghInterpolator
+   CubicHermiteSpline
+
+**Low-level data structures for univariate interpolation:**
+
+.. autosummary::
+   :toctree: generated/
+
+   PPoly
+   BPoly
+   BSpline
+
+
+Multivariate interpolation
+==========================
+
+**Unstructured data**
+
+.. autosummary::
+   :toctree: generated/
+
+   LinearNDInterpolator
+   NearestNDInterpolator
+   CloughTocher2DInterpolator
+   RBFInterpolator
+
+**For data on a grid:**
+
+.. autosummary::
+   :toctree: generated/
+
+   RegularGridInterpolator
+
+.. seealso::
+
+    `scipy.ndimage.map_coordinates`,
+    :ref:`An example wrapper for map_coordinates `
+
+
+**Low-level data structures for tensor product polynomials and splines:**
+
+
+.. autosummary::
+   :toctree: generated/
+
+   NdPPoly
+   NdBSpline
+
+
+1-D spline smoothing and approximation
+======================================
+
+.. autosummary::
+   :toctree: generated/
+
+   make_lsq_spline
+   make_smoothing_spline
+   make_splrep
+   make_splprep
+   generate_knots
+
+Rational Approximation
+======================
+
+.. autosummary::
+   :toctree: generated/
+
+   AAA
+
+
+Interfaces to FITPACK routines for 1D and 2D spline fitting
+===========================================================
+
+This section lists wrappers for `FITPACK `__
+functionality for 1D and 2D smoothing splines. In most cases, users are better off
+using higher-level routines listed in previous sections.
+
+
+1D FITPACK splines
+------------------
+
+This package provides two sets of functionally equivalent wrappers: object-oriented and
+functional.
+
+**Functional FITPACK interface:**
+
+
+.. autosummary::
+   :toctree: generated/
+
+   splrep
+   splprep
+   splev
+   splint
+   sproot
+   spalde
+   splder
+   splantider
+   insert
+
+**Object-oriented FITPACK interface:**
+
+.. autosummary::
+   :toctree: generated/
+
+   UnivariateSpline
+   InterpolatedUnivariateSpline
+   LSQUnivariateSpline
+
+
+2D FITPACK splines
+------------------
+
+**For data on a grid:**
+
+.. autosummary::
+   :toctree: generated/
+
+   RectBivariateSpline
+   RectSphereBivariateSpline
+
+**For unstructured data (OOP interface):**
+
+.. autosummary::
+   :toctree: generated/
+
+   BivariateSpline
+   SmoothBivariateSpline
+   SmoothSphereBivariateSpline
+   LSQBivariateSpline
+   LSQSphereBivariateSpline
+
+**For unstructured data (functional interface):**
+
+.. autosummary::
+   :toctree: generated/
+
+   bisplrep
+   bisplev
+
+
+Additional tools
+================
+
+.. autosummary::
+   :toctree: generated/
+
+   lagrange
+   approximate_taylor_polynomial
+   pade
+
+   interpn
+   griddata
+   barycentric_interpolate
+   krogh_interpolate
+   pchip_interpolate
+   Rbf
+   interp1d
+   interp2d
+
+.. seealso::
+
+   `scipy.ndimage.map_coordinates`,
+   `scipy.ndimage.spline_filter`,
+
+"""  # noqa: E501
+from ._interpolate import *
+from ._fitpack_py import *
+
+from ._fitpack2 import *
+
+from ._rbf import Rbf
+
+from ._rbfinterp import *
+
+from ._polyint import *
+
+from ._cubic import *
+
+from ._ndgriddata import *
+
+from ._bsplines import *
+from ._fitpack_repro import generate_knots, make_splrep, make_splprep
+
+from ._pade import *
+
+from ._rgi import *
+
+from ._ndbspline import NdBSpline
+
+from ._bary_rational import *
+
+# Deprecated namespaces, to be removed in v2.0.0
+from . import fitpack, fitpack2, interpolate, ndgriddata, polyint, rbf, interpnd
+
+__all__ = [s for s in dir() if not s.startswith('_')]
+
+from scipy._lib._testutils import PytestTester
+test = PytestTester(__name__)
+del PytestTester
+
+# Backward compatibility
+pchip = PchipInterpolator
diff --git a/.venv/lib/python3.12/site-packages/scipy/interpolate/_bary_rational.py b/.venv/lib/python3.12/site-packages/scipy/interpolate/_bary_rational.py
new file mode 100644
index 0000000000000000000000000000000000000000..b23fcfbd1b8fa7bc2bd1d258c858ebd7bb626790
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/interpolate/_bary_rational.py
@@ -0,0 +1,752 @@
+# Copyright (c) 2017, The Chancellor, Masters and Scholars of the University
+# of Oxford, and the Chebfun Developers. 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 Oxford nor the names of its
+#       contributors may be used to endorse or promote products derived from
+#       this software without specific prior written permission.
+#
+# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
+# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
+# ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+# (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
+# ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
+# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+
+import warnings
+import operator
+from types import GenericAlias
+
+import numpy as np
+import scipy
+
+
+__all__ = ["AAA", "FloaterHormannInterpolator"]
+
+
+class _BarycentricRational:
+    """Base class for barycentric representation of a rational function."""
+
+    # generic type compatibility with scipy-stubs
+    __class_getitem__: classmethod = classmethod(GenericAlias)
+
+    def __init__(self, x, y, axis=0, **kwargs):
+        self._axis = axis
+
+        # input validation
+        z = np.asarray(x)
+        f = np.asarray(y)
+
+        self._input_validation(z, f, **kwargs)
+
+        f = np.moveaxis(f, self._axis, 0)
+
+        # Remove infinite or NaN function values and repeated entries
+        to_keep = np.logical_and.reduce(
+            ((np.isfinite(f)) & (~np.isnan(f))).reshape(f.shape[0], -1),
+            axis=-1
+        )
+        f = f[to_keep, ...]
+        z = z[to_keep]
+        z, uni = np.unique(z, return_index=True)
+        f = f[uni, ...]
+
+        self._shape = f.shape[1:]
+        self._support_points, self._support_values, self.weights = (
+            self._compute_weights(z, f, **kwargs)
+        )
+
+        # only compute once
+        self._poles = None
+        self._residues = None
+        self._roots = None
+
+    def _input_validation(self, x, y, **kwargs):
+        if x.ndim != 1:
+            raise ValueError("`x` must be 1-D.")
+
+        if not y.ndim >= 1:
+            raise ValueError("`y` must be at least 1-D.")
+
+        if x.size != y.shape[self._axis]:
+            msg = f"`x` be of size {y.shape[self._axis]} but got size {x.size}."
+            raise ValueError(msg)
+
+        if not np.all(np.isfinite(x)):
+            raise ValueError("`x` must be finite.")
+
+    def _compute_weights(self, z, f, **kwargs):
+        raise NotImplementedError
+
+    def __call__(self, z):
+        """Evaluate the rational approximation at given values.
+
+        Parameters
+        ----------
+        z : array_like
+            Input values.
+        """
+        # evaluate rational function in barycentric form.
+        z = np.asarray(z)
+        zv = np.ravel(z)
+
+        support_values = self._support_values.reshape(
+            (self._support_values.shape[0], -1)
+        )
+        weights = self.weights[..., np.newaxis]
+
+        # Cauchy matrix
+        # Ignore errors due to inf/inf at support points, these will be fixed later
+        with np.errstate(invalid="ignore", divide="ignore"):
+            CC = 1 / np.subtract.outer(zv, self._support_points)
+            # Vector of values
+            r = CC @ (weights * support_values) / (CC @ weights)
+
+        # Deal with input inf: `r(inf) = lim r(z) = sum(w*f) / sum(w)`
+        if np.any(np.isinf(zv)):
+            r[np.isinf(zv)] = (np.sum(weights * support_values)
+                               / np.sum(weights))
+
+        # Deal with NaN
+        ii = np.nonzero(np.isnan(r))[0]
+        for jj in ii:
+            if np.isnan(zv[jj]) or not np.any(zv[jj] == self._support_points):
+                # r(NaN) = NaN is fine.
+                # The second case may happen if `r(zv[ii]) = 0/0` at some point.
+                pass
+            else:
+                # Clean up values `NaN = inf/inf` at support points.
+                # Find the corresponding node and set entry to correct value:
+                r[jj] = support_values[zv[jj] == self._support_points].squeeze()
+
+        res = np.reshape(r, z.shape + self._shape)
+        return np.moveaxis(res, 0, self._axis) if z.ndim > 0 else res
+
+    def poles(self):
+        """Compute the poles of the rational approximation.
+
+        Returns
+        -------
+        poles : array
+            Poles of the approximation, repeated according to their multiplicity
+            but not in any specific order.
+        """
+        if self._poles is None:
+            # Compute poles via generalized eigenvalue problem
+            m = self.weights.size
+            B = np.eye(m + 1, dtype=self.weights.dtype)
+            B[0, 0] = 0
+
+            E = np.zeros_like(B, dtype=np.result_type(self.weights,
+                                                      self._support_points))
+            E[0, 1:] = self.weights
+            E[1:, 0] = 1
+            np.fill_diagonal(E[1:, 1:], self._support_points)
+
+            pol = scipy.linalg.eigvals(E, B)
+            self._poles = pol[np.isfinite(pol)]
+        return self._poles
+
+    def residues(self):
+        """Compute the residues of the poles of the approximation.
+
+        Returns
+        -------
+        residues : array
+            Residues associated with the `poles` of the approximation
+        """
+        if self._support_values.ndim > 1:
+            raise NotImplementedError("Residues not implemented for multi-dimensional"
+                                      " data.")
+        if self._residues is None:
+            # Compute residues via formula for res of quotient of analytic functions
+            with np.errstate(divide="ignore", invalid="ignore"):
+                N = (1/(np.subtract.outer(self.poles(), self._support_points))) @ (
+                    self._support_values * self.weights
+                )
+                Ddiff = (
+                    -((1/np.subtract.outer(self.poles(), self._support_points))**2)
+                    @ self.weights
+                )
+                self._residues = N / Ddiff
+        return self._residues
+
+    def roots(self):
+        """Compute the roots of the rational approximation.
+
+        Returns
+        -------
+        zeros : array
+            Zeros of the approximation, repeated according to their multiplicity
+            but not in any specific order.
+        """
+        if self._support_values.ndim > 1:
+            raise NotImplementedError("Roots not implemented for multi-dimensional"
+                                      " data.")
+        if self._roots is None:
+            # Compute zeros via generalized eigenvalue problem
+            m = self.weights.size
+            B = np.eye(m + 1, dtype=self.weights.dtype)
+            B[0, 0] = 0
+            E = np.zeros_like(B, dtype=np.result_type(self.weights,
+                                                      self._support_values,
+                                                      self._support_points))
+            E[0, 1:] = self.weights * self._support_values
+            E[1:, 0] = 1
+            np.fill_diagonal(E[1:, 1:], self._support_points)
+
+            zer = scipy.linalg.eigvals(E, B)
+            self._roots = zer[np.isfinite(zer)]
+        return self._roots
+
+
+class AAA(_BarycentricRational):
+    r"""
+    AAA real or complex rational approximation.
+
+    As described in [1]_, the AAA algorithm is a greedy algorithm for approximation by
+    rational functions on a real or complex set of points. The rational approximation is
+    represented in a barycentric form from which the roots (zeros), poles, and residues
+    can be computed.
+
+    Parameters
+    ----------
+    x : 1D array_like, shape (n,)
+        1-D array containing values of the independent variable. Values may be real or
+        complex but must be finite.
+    y : 1D array_like, shape (n,)
+        Function values ``f(x)``. Infinite and NaN values of `values` and
+        corresponding values of `points` will be discarded.
+    rtol : float, optional
+        Relative tolerance, defaults to ``eps**0.75``. If a small subset of the entries
+        in `values` are much larger than the rest the default tolerance may be too
+        loose. If the tolerance is too tight then the approximation may contain
+        Froissart doublets or the algorithm may fail to converge entirely.
+    max_terms : int, optional
+        Maximum number of terms in the barycentric representation, defaults to ``100``.
+        Must be greater than or equal to one.
+    clean_up : bool, optional
+        Automatic removal of Froissart doublets, defaults to ``True``. See notes for
+        more details.
+    clean_up_tol : float, optional
+        Poles with residues less than this number times the geometric mean
+        of `values` times the minimum distance to `points` are deemed spurious by the
+        cleanup procedure, defaults to 1e-13. See notes for more details.
+
+    Attributes
+    ----------
+    support_points : array
+        Support points of the approximation. These are a subset of the provided `x` at
+        which the approximation strictly interpolates `y`.
+        See notes for more details.
+    support_values : array
+        Value of the approximation at the `support_points`.
+    weights : array
+        Weights of the barycentric approximation.
+    errors : array
+        Error :math:`|f(z) - r(z)|_\infty` over `points` in the successive iterations
+        of AAA.
+
+    Warns
+    -----
+    RuntimeWarning
+        If `rtol` is not achieved in `max_terms` iterations.
+
+    See Also
+    --------
+    FloaterHormannInterpolator : Floater-Hormann barycentric rational interpolation.
+    pade : Padé approximation.
+
+    Notes
+    -----
+    At iteration :math:`m` (at which point there are :math:`m` terms in the both the
+    numerator and denominator of the approximation), the
+    rational approximation in the AAA algorithm takes the barycentric form
+
+    .. math::
+
+        r(z) = n(z)/d(z) =
+        \frac{\sum_{j=1}^m\ w_j f_j / (z - z_j)}{\sum_{j=1}^m w_j / (z - z_j)},
+
+    where :math:`z_1,\dots,z_m` are real or complex support points selected from
+    `x`, :math:`f_1,\dots,f_m` are the corresponding real or complex data values
+    from `y`, and :math:`w_1,\dots,w_m` are real or complex weights.
+
+    Each iteration of the algorithm has two parts: the greedy selection the next support
+    point and the computation of the weights. The first part of each iteration is to
+    select the next support point to be added :math:`z_{m+1}` from the remaining
+    unselected `x`, such that the nonlinear residual
+    :math:`|f(z_{m+1}) - n(z_{m+1})/d(z_{m+1})|` is maximised. The algorithm terminates
+    when this maximum is less than ``rtol * np.linalg.norm(f, ord=np.inf)``. This means
+    the interpolation property is only satisfied up to a tolerance, except at the
+    support points where approximation exactly interpolates the supplied data.
+
+    In the second part of each iteration, the weights :math:`w_j` are selected to solve
+    the least-squares problem
+
+    .. math::
+
+        \text{minimise}_{w_j}|fd - n| \quad \text{subject to} \quad
+        \sum_{j=1}^{m+1} w_j = 1,
+
+    over the unselected elements of `x`.
+
+    One of the challenges with working with rational approximations is the presence of
+    Froissart doublets, which are either poles with vanishingly small residues or
+    pole-zero pairs that are close enough together to nearly cancel, see [2]_. The
+    greedy nature of the AAA algorithm means Froissart doublets are rare. However, if
+    `rtol` is set too tight then the approximation will stagnate and many Froissart
+    doublets will appear. Froissart doublets can usually be removed by removing support
+    points and then resolving the least squares problem. The support point :math:`z_j`,
+    which is the closest support point to the pole :math:`a` with residue
+    :math:`\alpha`, is removed if the following is satisfied
+
+    .. math::
+
+        |\alpha| / |z_j - a| < \verb|clean_up_tol| \cdot \tilde{f},
+
+    where :math:`\tilde{f}` is the geometric mean of `support_values`.
+
+
+    References
+    ----------
+    .. [1] Y. Nakatsukasa, O. Sete, and L. N. Trefethen, "The AAA algorithm for
+            rational approximation", SIAM J. Sci. Comp. 40 (2018), A1494-A1522.
+            :doi:`10.1137/16M1106122`
+    .. [2] J. Gilewicz and M. Pindor, Pade approximants and noise: rational functions,
+           J. Comp. Appl. Math. 105 (1999), pp. 285-297.
+           :doi:`10.1016/S0377-0427(02)00674-X`
+
+    Examples
+    --------
+
+    Here we reproduce a number of the numerical examples from [1]_ as a demonstration
+    of the functionality offered by this method.
+
+    >>> import numpy as np
+    >>> import matplotlib.pyplot as plt
+    >>> from scipy.interpolate import AAA
+    >>> import warnings
+
+    For the first example we approximate the gamma function on ``[-3.5, 4.5]`` by
+    extrapolating from 100 samples in ``[-1.5, 1.5]``.
+
+    >>> from scipy.special import gamma
+    >>> sample_points = np.linspace(-1.5, 1.5, num=100)
+    >>> r = AAA(sample_points, gamma(sample_points))
+    >>> z = np.linspace(-3.5, 4.5, num=1000)
+    >>> fig, ax = plt.subplots()
+    >>> ax.plot(z, gamma(z), label="Gamma")
+    >>> ax.plot(sample_points, gamma(sample_points), label="Sample points")
+    >>> ax.plot(z, r(z).real, '--', label="AAA approximation")
+    >>> ax.set(xlabel="z", ylabel="r(z)", ylim=[-8, 8], xlim=[-3.5, 4.5])
+    >>> ax.legend()
+    >>> plt.show()
+
+    We can also view the poles of the rational approximation and their residues:
+
+    >>> order = np.argsort(r.poles())
+    >>> r.poles()[order]
+    array([-3.81591039e+00+0.j        , -3.00269049e+00+0.j        ,
+           -1.99999988e+00+0.j        , -1.00000000e+00+0.j        ,
+            5.85842812e-17+0.j        ,  4.77485458e+00-3.06919376j,
+            4.77485458e+00+3.06919376j,  5.29095868e+00-0.97373072j,
+            5.29095868e+00+0.97373072j])
+    >>> r.residues()[order]
+    array([ 0.03658074 +0.j        , -0.16915426 -0.j        ,
+            0.49999915 +0.j        , -1.         +0.j        ,
+            1.         +0.j        , -0.81132013 -2.30193429j,
+           -0.81132013 +2.30193429j,  0.87326839+10.70148546j,
+            0.87326839-10.70148546j])
+
+    For the second example, we call `AAA` with a spiral of 1000 points that wind 7.5
+    times around the origin in the complex plane.
+
+    >>> z = np.exp(np.linspace(-0.5, 0.5 + 15j*np.pi, 1000))
+    >>> r = AAA(z, np.tan(np.pi*z/2), rtol=1e-13)
+
+    We see that AAA takes 12 steps to converge with the following errors:
+
+    >>> r.errors.size
+    12
+    >>> r.errors
+    array([2.49261500e+01, 4.28045609e+01, 1.71346935e+01, 8.65055336e-02,
+           1.27106444e-02, 9.90889874e-04, 5.86910543e-05, 1.28735561e-06,
+           3.57007424e-08, 6.37007837e-10, 1.67103357e-11, 1.17112299e-13])
+
+    We can also plot the computed poles:
+
+    >>> fig, ax = plt.subplots()
+    >>> ax.plot(z.real, z.imag, '.', markersize=2, label="Sample points")
+    >>> ax.plot(r.poles().real, r.poles().imag, '.', markersize=5,
+    ...         label="Computed poles")
+    >>> ax.set(xlim=[-3.5, 3.5], ylim=[-3.5, 3.5], aspect="equal")
+    >>> ax.legend()
+    >>> plt.show()
+
+    We now demonstrate the removal of Froissart doublets using the `clean_up` method
+    using an example from [1]_. Here we approximate the function
+    :math:`f(z)=\log(2 + z^4)/(1 + 16z^4)` by sampling it at 1000 roots of unity. The
+    algorithm is run with ``rtol=0`` and ``clean_up=False`` to deliberately cause
+    Froissart doublets to appear.
+
+    >>> z = np.exp(1j*2*np.pi*np.linspace(0,1, num=1000))
+    >>> def f(z):
+    ...     return np.log(2 + z**4)/(1 - 16*z**4)
+    >>> with warnings.catch_warnings():  # filter convergence warning due to rtol=0
+    ...     warnings.simplefilter('ignore', RuntimeWarning)
+    ...     r = AAA(z, f(z), rtol=0, max_terms=50, clean_up=False)
+    >>> mask = np.abs(r.residues()) < 1e-13
+    >>> fig, axs = plt.subplots(ncols=2)
+    >>> axs[0].plot(r.poles().real[~mask], r.poles().imag[~mask], '.')
+    >>> axs[0].plot(r.poles().real[mask], r.poles().imag[mask], 'r.')
+
+    Now we call the `clean_up` method to remove Froissart doublets.
+
+    >>> with warnings.catch_warnings():
+    ...     warnings.simplefilter('ignore', RuntimeWarning)
+    ...     r.clean_up()
+    4  # may vary
+    >>> mask = np.abs(r.residues()) < 1e-13
+    >>> axs[1].plot(r.poles().real[~mask], r.poles().imag[~mask], '.')
+    >>> axs[1].plot(r.poles().real[mask], r.poles().imag[mask], 'r.')
+    >>> plt.show()
+
+    The left image shows the poles prior of the approximation ``clean_up=False`` with
+    poles with residue less than ``10^-13`` in absolute value shown in red. The right
+    image then shows the poles after the `clean_up` method has been called.
+    """
+    def __init__(self, x, y, *, rtol=None, max_terms=100, clean_up=True,
+                 clean_up_tol=1e-13):
+        super().__init__(x, y, rtol=rtol, max_terms=max_terms)
+
+        if clean_up:
+            self.clean_up(clean_up_tol)
+
+    # pyrefly:ignore[bad-override]
+    def _input_validation(self, x, y, rtol=None, max_terms=100, clean_up=True,
+                          clean_up_tol=1e-13):
+        max_terms = operator.index(max_terms)
+        if max_terms < 1:
+            raise ValueError("`max_terms` must be an integer value greater than or "
+                             "equal to one.")
+
+        if y.ndim != 1:
+            raise ValueError("`y` must be 1-D.")
+
+        super()._input_validation(x, y)
+
+    @property
+    def support_points(self):
+        return self._support_points
+
+    @property
+    def support_values(self):
+        return self._support_values
+
+    # pyrefly:ignore[bad-override]
+    def _compute_weights(self, z, f, rtol, max_terms):
+        # Initialization for AAA iteration
+        M = np.size(z)
+        mask = np.ones(M, dtype=np.bool_)
+        dtype = np.result_type(z, f, 1.0)
+        rtol = np.finfo(dtype).eps**0.75 if rtol is None else rtol
+        atol = rtol * np.linalg.norm(f, ord=np.inf)
+        zj = np.empty(max_terms, dtype=dtype)
+        fj = np.empty(max_terms, dtype=dtype)
+        # Cauchy matrix
+        C = np.empty((M, max_terms), dtype=dtype)
+        # Loewner matrix
+        A = np.empty((M, max_terms), dtype=dtype)
+        errors = np.empty(max_terms, dtype=A.real.dtype)
+        R = np.repeat(np.mean(f), M)
+        ill_conditioned = False
+        ill_conditioned_tol = 1/(3*np.finfo(dtype).eps)
+
+        # AAA iteration
+        for m in range(max_terms):
+            # Introduce next support point
+            # Select next support point
+            jj = np.argmax(np.abs(f[mask] - R[mask]))
+            # Update support points
+            zj[m] = z[mask][jj]
+            # Update data values
+            fj[m] = f[mask][jj]
+            # Next column of Cauchy matrix
+            # Ignore errors as we manually interpolate at support points
+            with np.errstate(divide="ignore", invalid="ignore"):
+                C[:, m] = 1 / (z - z[mask][jj])
+            # Update mask
+            mask[np.nonzero(mask)[0][jj]] = False
+            # Update Loewner matrix
+            # Ignore errors as inf values will be masked out in SVD call
+            with np.errstate(invalid="ignore"):
+                A[:, m] = (f - fj[m]) * C[:, m]
+
+            # Compute weights
+            rows = mask.sum()
+            if rows >= m + 1:
+                # The usual tall-skinny case
+                if not ill_conditioned:
+                    _, s, V = scipy.linalg.svd(
+                        A[mask, : m + 1], full_matrices=False, check_finite=False,
+                    )
+                    with np.errstate(invalid="ignore", divide="ignore"):
+                        if s[0]/s[-1] > ill_conditioned_tol:
+                            ill_conditioned = True
+                if ill_conditioned:
+                    col_norm = np.linalg.norm(A[mask, : m + 1], axis=0)
+                    _, s, V = scipy.linalg.svd(
+                        A[mask, : m + 1]/col_norm, full_matrices=False,
+                        check_finite=False,
+                    )
+                # Treat case of multiple min singular values
+                mm = s == np.min(s)
+                # Aim for non-sparse weight vector
+                wj = (V.conj()[mm, :].sum(axis=0) / np.sqrt(mm.sum())).astype(dtype)
+                if ill_conditioned:
+                    wj /= col_norm
+            else:
+                # Fewer rows than columns
+                V = scipy.linalg.null_space(A[mask, : m + 1], check_finite=False)
+                nm = V.shape[-1]
+                # Aim for non-sparse wt vector
+                wj = V.sum(axis=-1) / np.sqrt(nm)
+
+            # Compute rational approximant
+            # Omit columns with `wj == 0`
+            i0 = wj != 0
+            # Ignore errors as we manually interpolate at support points
+            with np.errstate(invalid="ignore"):
+                # Numerator
+                N = C[:, : m + 1][:, i0] @ (wj[i0] * fj[: m + 1][i0])
+                # Denominator
+                D = C[:, : m + 1][:, i0] @ wj[i0]
+            # Interpolate at support points with `wj !=0`
+            D_inf = np.isinf(D) | np.isnan(D)
+            D[D_inf] = 1
+            N[D_inf] = f[D_inf]
+            R = N / D
+
+            # Check if converged
+            max_error = np.linalg.norm(f - R, ord=np.inf)
+            errors[m] = max_error
+            if max_error <= atol:
+                break
+
+        if m == max_terms - 1:
+            warnings.warn(f"AAA failed to converge within {max_terms} iterations.",
+                          RuntimeWarning, stacklevel=2)
+
+        # Trim off unused array allocation
+        zj = zj[: m + 1]
+        fj = fj[: m + 1]
+
+        # Remove support points with zero weight
+        i_non_zero = wj != 0
+        self.errors = errors[: m + 1]
+        self._points = z
+        self._values = f
+        return zj[i_non_zero], fj[i_non_zero], wj[i_non_zero]
+
+    def clean_up(self, cleanup_tol=1e-13):
+        """Automatic removal of Froissart doublets.
+
+        Parameters
+        ----------
+        cleanup_tol : float, optional
+            Poles with residues less than this number times the geometric mean
+            of `values` times the minimum distance to `points` are deemed spurious by
+            the cleanup procedure, defaults to 1e-13.
+
+        Returns
+        -------
+        int
+            Number of Froissart doublets detected
+        """
+        # Find negligible residues
+        geom_mean_abs_f = scipy.stats.gmean(np.abs(self._values))
+
+        Z_distances = np.min(
+            np.abs(np.subtract.outer(self.poles(), self._points)), axis=1
+        )
+
+        with np.errstate(divide="ignore", invalid="ignore"):
+            ii = np.nonzero(
+                np.abs(self.residues()) / Z_distances < cleanup_tol * geom_mean_abs_f
+            )
+
+        ni = ii[0].size
+        if ni == 0:
+            return ni
+
+        warnings.warn(f"{ni} Froissart doublets detected.", RuntimeWarning,
+                        stacklevel=2)
+
+        # For each spurious pole find and remove closest support point
+        closest_spt_point = np.argmin(
+            np.abs(np.subtract.outer(self._support_points, self.poles()[ii])), axis=0
+        )
+        self._support_points = np.delete(self._support_points, closest_spt_point)
+        self._support_values = np.delete(self._support_values, closest_spt_point)
+
+        # Remove support points z from sample set
+        mask = np.logical_and.reduce(
+            np.not_equal.outer(self._points, self._support_points), axis=1
+        )
+        f = self._values[mask]
+        z = self._points[mask]
+
+        # recompute weights, we resolve the least squares problem for the remaining
+        # support points
+
+        m = self._support_points.size
+
+        # Cauchy matrix
+        C = 1 / np.subtract.outer(z, self._support_points)
+        # Loewner matrix
+        A = f[:, np.newaxis] * C - C * self._support_values
+
+        # Solve least-squares problem to obtain weights
+        _, _, V = scipy.linalg.svd(A, check_finite=False)
+        self.weights = np.conj(V[m - 1,:])
+
+        # reset roots, poles, residues as cached values will be wrong with new weights
+        self._poles = None
+        self._residues = None
+        self._roots = None
+
+        return ni
+
+
+class FloaterHormannInterpolator(_BarycentricRational):
+    r"""Floater-Hormann barycentric rational interpolator (C∞ smooth on real axis).
+
+    As described in [1]_, the method of Floater and Hormann computes weights for a
+    barycentric rational interpolant with no poles on the real axis.
+
+    Parameters
+    ----------
+    points : 1D array_like, shape (n,)
+        1-D array containing values of the independent variable. Values may be real or
+        complex but must be finite.
+    values : array_like, shape (n, ...)
+        Array containing values of the dependent variable. Infinite and NaN values
+        of `y` and corresponding values of `x` will be discarded.
+    d : int, default: 3
+        Integer satisfying ``0 <= d < n``. Floater-Hormann interpolation blends
+        ``n - d`` polynomials of degree `d` together; for ``d = n - 1``, this is
+        equivalent to polynomial interpolation.
+    axis : int, default: 0
+        Axis of `y` corresponding to `x`.
+
+    Attributes
+    ----------
+    weights : array
+        Weights of the barycentric approximation.
+
+    See Also
+    --------
+    AAA : Barycentric rational approximation of real and complex functions.
+    pade : Padé approximation.
+
+    Notes
+    -----
+    The Floater-Hormann interpolant is a rational function that interpolates the data
+    with approximation order :math:`O(h^{d+1})`. The rational function blends ``n - d``
+    polynomials of degree `d` together to produce a rational interpolant that contains
+    no poles on the real axis, unlike `AAA`. The interpolant is given
+    by
+
+    .. math::
+
+        r(x) = \frac{\sum_{i=0}^{n-d} \lambda_i(x) p_i(x)}
+        {\sum_{i=0}^{n-d} \lambda_i(x)},
+
+    where :math:`p_i(x)` is an interpolating polynomial of at most degree `d` through
+    the points :math:`(x_i,y_i),\dots,(x_{i+d},y_{i+d})`, and :math:`\lambda_i(z)` are
+    blending functions defined by
+
+    .. math::
+
+        \lambda_i(x) = \frac{(-1)^i}{(x - x_i)\cdots(x - x_{i+d})}.
+
+    When ``d = n - 1`` this reduces to polynomial interpolation.
+
+    Due to its stability, the following barycentric representation of the above equation
+    is used for computation
+
+    .. math::
+
+        r(z) = \frac{\sum_{k=1}^m\ w_k f_k / (x - x_k)}{\sum_{k=1}^m w_k / (x - x_k)},
+
+    where the weights :math:`w_j` are computed as
+
+    .. math::
+
+        w_k &= (-1)^{k - d} \sum_{i \in J_k} \prod_{j = i, j \neq k}^{i + d}
+        1/|x_k - x_j|, \\
+        J_k &= \{ i \in I: k - d \leq i \leq k\},\\
+        I &= \{0, 1, \dots, n - d\}.
+
+    References
+    ----------
+    .. [1] M.S. Floater and K. Hormann, "Barycentric rational interpolation with no
+           poles and high rates of approximation", Numer. Math. 107, 315 (2007).
+           :doi:`10.1007/s00211-007-0093-y`
+
+    Examples
+    --------
+
+    Here we compare the method against polynomial interpolation for an example where
+    the polynomial interpolation fails due to Runge's phenomenon.
+
+    >>> import numpy as np
+    >>> from scipy.interpolate import (FloaterHormannInterpolator,
+    ...                                BarycentricInterpolator)
+    >>> def f(x):
+    ...     return 1/(1 + x**2)
+    >>> x = np.linspace(-5, 5, num=15)
+    >>> r = FloaterHormannInterpolator(x, f(x))
+    >>> p = BarycentricInterpolator(x, f(x))
+    >>> xx = np.linspace(-5, 5, num=1000)
+    >>> import matplotlib.pyplot as plt
+    >>> fig, ax = plt.subplots()
+    >>> ax.plot(xx, f(xx), label="f(x)")
+    >>> ax.plot(xx, r(xx), "--", label="Floater-Hormann")
+    >>> ax.plot(xx, p(xx), "--", label="Polynomial")
+    >>> ax.legend()
+    >>> plt.show()
+    """
+    def __init__(self, points, values, *, d=3, axis=0):
+        super().__init__(points, values, d=d, axis=axis)
+
+    # pyrefly:ignore[bad-override]
+    def _input_validation(self, x, y, d):
+        d = operator.index(d)
+        if not (0 <= d < len(x)):
+            raise ValueError("`d` must satisfy 0 <= d < n")
+
+        super()._input_validation(x, y)
+
+    # pyrefly:ignore[bad-override]
+    def _compute_weights(self, z, f, d):
+        # Floater and Hormann 2007 Eqn. (18) 3 equations later
+        w = np.zeros_like(z, dtype=np.result_type(z, 1.0))
+        n = w.size
+        for k in range(n):
+            for i in range(max(k-d, 0), min(k+1, n-d)):
+                w[k] += 1/np.prod(np.abs(np.delete(z[k] - z[i : i + d + 1], k - i)))
+        w *= (-1.)**(np.arange(n) - d)
+
+        return z, f, w
diff --git a/.venv/lib/python3.12/site-packages/scipy/interpolate/_bsplines.py b/.venv/lib/python3.12/site-packages/scipy/interpolate/_bsplines.py
new file mode 100644
index 0000000000000000000000000000000000000000..3d958a0c6048c0891a188e08902bf9f77fdd5a7e
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/interpolate/_bsplines.py
@@ -0,0 +1,2835 @@
+import functools
+import operator
+from math import prod
+from types import GenericAlias
+
+import numpy as np
+from scipy._lib._util import normalize_axis_index
+from scipy.linalg import (get_lapack_funcs, LinAlgError,
+                          cholesky_banded, cho_solve_banded,
+                          solve, solve_banded)
+from scipy.optimize import minimize_scalar
+from . import _dierckx
+from . import _fitpack_impl
+from scipy.sparse import csr_array
+from scipy.special import poch
+from itertools import combinations
+
+from scipy._lib._array_api import (
+    array_namespace, concat_1d, xp_capabilities, scipy_namespace_for, is_numpy
+)
+
+__all__ = ["BSpline", "make_interp_spline", "make_lsq_spline",
+           "make_smoothing_spline"]
+
+
+def _get_dtype(dtype):
+    """Return np.complex128 for complex dtypes, np.float64 otherwise."""
+    if np.issubdtype(dtype, np.complexfloating):
+        return np.complex128
+    else:
+        return np.float64
+
+
+def _as_float_array(x, check_finite=False):
+    """Convert the input into a C contiguous float array.
+
+    NB: Upcasts half- and single-precision floats to double precision.
+    """
+    x = np.ascontiguousarray(x)
+    dtyp = _get_dtype(x.dtype)
+    x = x.astype(dtyp, copy=False)
+    if check_finite and not np.isfinite(x).all():
+        raise ValueError("Array must not contain infs or nans.")
+    return x
+
+
+def _dual_poly(j, k, t, y):
+    """
+    Dual polynomial of the B-spline B_{j,k,t} -
+    polynomial which is associated with B_{j,k,t}:
+    $p_{j,k}(y) = (y - t_{j+1})(y - t_{j+2})...(y - t_{j+k})$
+    """
+    if k == 0:
+        return 1
+    return np.prod([(y - t[j + i]) for i in range(1, k + 1)])
+
+
+def _diff_dual_poly(j, k, y, d, t):
+    """
+    d-th derivative of the dual polynomial $p_{j,k}(y)$
+    """
+    if d == 0:
+        return _dual_poly(j, k, t, y)
+    if d == k:
+        return poch(1, k)
+    comb = list(combinations(range(j + 1, j + k + 1), d))
+    res = 0
+    for i in range(len(comb) * len(comb[0])):
+        res += np.prod([(y - t[j + p]) for p in range(1, k + 1)
+                        if (j + p) not in comb[i//d]])
+    return res
+
+
+class _BSpline:
+    """NumPy Backend for BSpline.
+
+    The public BSpline class below is set up to delegate to bspline implementations
+    from differing backends. The ``derivative`` and ``antiderivative`` methods are
+    not including here because they are handled by an array-agnostic implementation
+    in the public class.
+    """
+    def __init__(self, t, c, k, extrapolate=True, axis=0):
+        self.k = operator.index(k)
+        self.c = np.asarray(c)
+        self.t = np.ascontiguousarray(t, dtype=np.float64)
+
+        if extrapolate == 'periodic':
+            self.extrapolate = extrapolate
+        else:
+            self.extrapolate = bool(extrapolate)
+
+        n = self.t.shape[0] - self.k - 1
+
+        axis = normalize_axis_index(axis, self.c.ndim)
+
+        # Note that the normalized axis is stored in the object.
+        self.axis = axis
+        if axis != 0:
+            # roll the interpolation axis to be the first one in self.c
+            # More specifically, the target shape for self.c is (n, ...),
+            # and axis !=0 means that we have c.shape (..., n, ...)
+            #                                               ^
+            #                                              axis
+            self.c = np.moveaxis(self.c, axis, 0)
+
+        if k < 0:
+            raise ValueError("Spline order cannot be negative.")
+        if self.t.ndim != 1:
+            raise ValueError("Knot vector must be one-dimensional.")
+        if n < self.k + 1:
+            raise ValueError(f"Need at least {2*k + 2} knots for degree {k}")
+        if (np.diff(self.t) < 0).any():
+            raise ValueError("Knots must be in a non-decreasing order.")
+        if len(np.unique(self.t[k:n+1])) < 2:
+            raise ValueError("Need at least two internal knots.")
+        if not np.isfinite(self.t).all():
+            raise ValueError("Knots should not have nans or infs.")
+        if self.c.ndim < 1:
+            raise ValueError("Coefficients must be at least 1-dimensional.")
+        if self.c.shape[0] < n:
+            raise ValueError("Knots, coefficients and degree are inconsistent.")
+
+        dt = _get_dtype(self.c.dtype)
+
+        self.c = np.ascontiguousarray(self.c, dtype=dt)
+
+    @classmethod
+    def construct_fast(cls, t, c, k, extrapolate=True, axis=0):
+        """Construct a spline without making checks.
+
+        Accepts same parameters as the regular constructor. Input arrays
+        `t` and `c` must of correct shape and dtype.
+        """
+        self = object.__new__(cls)
+        self.k = k
+        self.axis = axis
+        self.extrapolate = extrapolate
+
+        self._delegate_to = None
+        self.t, self.c = np.asarray(t), np.asarray(c)
+        return self
+
+    @classmethod
+    def basis_element(cls, t, extrapolate=True):
+        t = np.asarray(t)
+        k = t.shape[0] - 2
+
+        if k < 0:
+            raise ValueError("BSpline.basis_element requires at least 2 knots")
+
+        t = _as_float_array(t)
+        t = np.r_[(t[0]-1,) * k, t, (t[-1]+1,) * k]
+        c = np.zeros_like(t)
+        c[k] = 1.
+
+        return cls.construct_fast(t, c, k, extrapolate)
+
+    @classmethod
+    def design_matrix(cls, x, t, k, extrapolate=False):
+        x = _as_float_array(x, True)
+        t = _as_float_array(t, True)
+
+        if extrapolate != 'periodic':
+            extrapolate = bool(extrapolate)
+
+        if k < 0:
+            raise ValueError("Spline order cannot be negative.")
+        if t.ndim != 1 or np.any(t[1:] < t[:-1]):
+            raise ValueError(f"Expect t to be a 1-D sorted array_like, but "
+                             f"got t={t}.")
+        # There are `nt - k - 1` basis elements in a BSpline built on the
+        # vector of knots with length `nt`, so to have at least `k + 1` basis
+        # elements we need to have at least `2 * k + 2` elements in the vector
+        # of knots.
+        if len(t) < 2 * k + 2:
+            raise ValueError(f"Length t is not enough for k={k}.")
+
+        if extrapolate == 'periodic':
+            # With periodic extrapolation we map x to the segment
+            # [t[k], t[n]].
+            n = t.size - k - 1
+            x = t[k] + (x - t[k]) % (t[n] - t[k])
+            extrapolate = False
+        elif not extrapolate and (
+            (min(x) < t[k]) or (max(x) > t[t.shape[0] - k - 1])
+        ):
+            # Checks from `find_interval` function
+            raise ValueError(f'Out of bounds w/ x = {x}.')
+
+        # Compute number of non-zeros of final CSR array in order to determine
+        # the dtype of indices and indptr of the CSR array.
+        n = x.shape[0]
+        nnz = n * (k + 1)
+        if nnz < np.iinfo(np.int32).max:
+            int_dtype = np.int32
+        else:
+            int_dtype = np.int64
+
+        # Get the non-zero elements of the design matrix and per-row `offsets`:
+        # In row `i`, k+1 nonzero elements are consecutive, and start from `offset[i]`
+        data, offsets, _ = _dierckx.data_matrix(x, t, k, np.ones_like(x), extrapolate)
+        data = data.ravel()
+
+        if offsets.dtype != int_dtype:
+            offsets = offsets.astype(int_dtype)
+
+        # Convert from per-row offsets to the CSR indices/indptr format
+        indices = np.repeat(offsets, k+1).reshape(-1, k+1)
+        indices = indices + np.arange(k+1, dtype=int_dtype)
+        indices = indices.ravel()
+
+        indptr = np.arange(0, (n + 1) * (k + 1), k + 1, dtype=int_dtype)
+
+        return csr_array(
+            (data, indices, indptr),
+            shape=(x.shape[0], t.shape[0] - k - 1)
+        )
+
+    def __call__(self, x, nu=0, extrapolate=None):
+        if extrapolate is None:
+            extrapolate = self.extrapolate
+        x = np.asarray(x)
+        x_shape, x_ndim = x.shape, x.ndim
+        x = np.ascontiguousarray(x.ravel(), dtype=np.float64)
+
+        # With periodic extrapolation we map x to the segment
+        # [self.t[k], self.t[n]].
+        if extrapolate == 'periodic':
+            n = self.t.size - self.k - 1
+            x = self.t[self.k] + (x - self.t[self.k]) % (self.t[n] - self.t[self.k])
+            extrapolate = False
+
+        self._ensure_c_contiguous()
+
+        # if self.c is complex: the C code in _dierckxmodule.cc expects
+        # floats, so make a view---this expands the last axis, and
+        # the view is C contiguous if the original is.
+        # if c.dtype is complex of shape (n,), c.view(float).shape == (2*n,)
+        # if c.dtype is complex of shape (n, m), c.view(float).shape == (n, 2*m)
+
+        is_complex = self.c.dtype.kind == 'c'
+        if is_complex:
+            cc = self.c.view(float)
+            if self.c.ndim == 1:
+                cc = cc.reshape(self.c.shape[0], 2)
+        else:
+            cc = self.c
+
+        # flatten the trailing dims
+        cc = cc.reshape(cc.shape[0], -1)
+
+        # heavy lifting: actually perform the evaluations
+        out = _dierckx.evaluate_spline(self.t, cc, self.k, x, nu, extrapolate)
+
+        if is_complex:
+            out = out.view(complex)
+
+        out = out.reshape(x_shape + self.c.shape[1:])
+        if self.axis != 0:
+            # transpose to move the calculated values to the interpolation axis
+            l = list(range(out.ndim))
+            l = l[x_ndim:x_ndim+self.axis] + l[:x_ndim] + l[x_ndim+self.axis:]
+            out = out.transpose(l)
+        return out
+
+    def _ensure_c_contiguous(self):
+        """
+        c and t may be modified by the user. The Cython code expects
+        that they are C contiguous.
+
+        """
+        if not self.t.flags.c_contiguous:
+            self.t = self.t.copy()
+        if not self.c.flags.c_contiguous:
+            self.c = self.c.copy()
+
+    def integrate(self, a, b, extrapolate=None):
+        if extrapolate is None:
+            extrapolate = self.extrapolate
+
+        # Prepare self.t and self.c.
+        self._ensure_c_contiguous()
+
+        # Swap integration bounds if needed.
+        sign = 1
+        if b < a:
+            a, b = b, a
+            sign = -1
+        n = self.t.size - self.k - 1
+
+        if extrapolate != "periodic" and not extrapolate:
+            # Shrink the integration interval, if needed.
+            a = max(a, self.t[self.k])
+            b = min(b, self.t[n])
+
+            if self.c.ndim == 1:
+                # Fast path: use FITPACK's routine
+                # (cf _fitpack_impl.splint).
+                integral = _fitpack_impl.splint(a, b, (self.t, self.c, self.k))
+                return integral * sign
+
+        # Compute the antiderivative.
+        c = self.c
+        ct = len(self.t) - len(c)
+        if ct > 0:
+            c = np.r_[c, np.zeros((ct,) + c.shape[1:])]
+        ta, ca, ka = _fitpack_impl.splantider((self.t, c, self.k), 1)
+
+        if extrapolate == 'periodic':
+            # Split the integral into the part over period (can be several
+            # of them) and the remaining part.
+
+            ts, te = self.t[self.k], self.t[n]
+            period = te - ts
+            interval = b - a
+            n_periods, left = divmod(interval, period)
+
+            if n_periods > 0:
+                # Evaluate the difference of antiderivatives.
+                x = np.asarray([ts, te], dtype=np.float64)
+                out = _dierckx.evaluate_spline(ta, ca.reshape(ca.shape[0], -1),
+                                      ka, x, 0, False)
+                integral = out[1] - out[0]
+                integral *= n_periods
+            else:
+                integral = np.zeros((1, prod(self.c.shape[1:])),
+                                    dtype=self.c.dtype)
+
+            # Map a to [ts, te], b is always a + left.
+            a = ts + (a - ts) % period
+            b = a + left
+
+            # If b <= te then we need to integrate over [a, b], otherwise
+            # over [a, te] and from xs to what is remained.
+            if b <= te:
+                x = np.asarray([a, b], dtype=np.float64)
+                out = _dierckx.evaluate_spline(ta, ca.reshape(ca.shape[0], -1),
+                                      ka, x, 0, False)
+                integral += out[1] - out[0]
+            else:
+                x = np.asarray([a, te], dtype=np.float64)
+                out = _dierckx.evaluate_spline(ta, ca.reshape(ca.shape[0], -1),
+                                      ka, x, 0, False)
+                integral += out[1] - out[0]
+
+                x = np.asarray([ts, ts + b - te], dtype=np.float64)
+                out = _dierckx.evaluate_spline(ta, ca.reshape(ca.shape[0], -1),
+                                      ka, x, 0, False)
+                integral += out[1] - out[0]
+        else:
+            # Evaluate the difference of antiderivatives.
+            x = np.asarray([a, b], dtype=np.float64)
+            out = _dierckx.evaluate_spline(ta, ca.reshape(ca.shape[0], -1),
+                                  ka, x, 0, extrapolate)
+            integral = out[1] - out[0]
+
+        integral *= sign
+        return integral.reshape(ca.shape[1:])
+
+    @classmethod
+    def from_power_basis(cls, pp, bc_type='not-a-knot'):
+        from ._cubic import CubicSpline
+        if not isinstance(pp, CubicSpline):
+            raise NotImplementedError(f"Only CubicSpline objects are accepted "
+                                      f"for now. Got {type(pp)} instead.")
+        x = pp.x
+        coef = pp.c
+        k = pp.c.shape[0] - 1
+        n = x.shape[0]
+
+        if bc_type == 'not-a-knot':
+            t = _not_a_knot(x, k)
+        elif bc_type == 'natural' or bc_type == 'clamped':
+            t = _augknt(x, k)
+        elif bc_type == 'periodic':
+            t = _periodic_knots(x, k)
+        else:
+            raise TypeError(f'Unknown boundary condition: {bc_type}')
+
+        nod = t.shape[0] - (n + k + 1)  # number of derivatives at the ends
+        c = np.zeros(n + nod, dtype=pp.c.dtype)
+        for m in range(k + 1):
+            for i in range(n - 2):
+                c[i] += poch(k + 1, -m) * coef[m, i]\
+                        * np.power(-1, k - m)\
+                        * _diff_dual_poly(i, k, x[i], m, t)
+            for j in range(n - 2, n + nod):
+                c[j] += poch(k + 1, -m) * coef[m, n - 2]\
+                        * np.power(-1, k - m)\
+                        * _diff_dual_poly(j, k, x[n - 2], m, t)
+        return cls.construct_fast(t, c, k, pp.extrapolate, pp.axis)
+
+    def insert_knot(self, x, m=1):
+        x = float(x)
+
+        if x < self.t[self.k] or x > self.t[-self.k-1]:
+            raise ValueError(f"Cannot insert a knot at {x}.")
+        if m <= 0:
+            raise ValueError(f"`m` must be positive, got {m = }.")
+
+        tt = self.t.copy()
+        cc = self.c.copy()
+
+        for _ in range(m):
+            tt, cc = _insert(x, tt, cc, self.k, self.extrapolate == "periodic")
+        return self.construct_fast(tt, cc, self.k, self.extrapolate, self.axis)
+
+
+@functools.lru_cache(16)
+def _get_xp_bspline_cls(xp):
+    """Returns bspline class to delegate to for xp along with internal array namespace.
+
+    Parameters
+    ----------
+    xp : module
+
+    Returns
+    -------
+    cls : type
+        The bspline class to delegate to for namespace `xp`.
+    namespace : module
+        The internal namespace that calculations are performed with
+        (may differ from `xp`, e.g. numpy delegation for torch on CPU).
+    """
+    # A device kwarg could be added to give device dependent delegation
+    # e.g., delegating torch to numpy on CPU and cupy on GPU.
+    if is_numpy(xp):
+        return _BSpline, xp
+    spx = scipy_namespace_for(xp)
+    cls = getattr(getattr(spx, "interpolate", None), "BSpline", None)
+    if cls is not None:
+        return cls, xp
+    return _BSpline, np
+
+
+_bspline_extra_note = (
+    """The methods ``design_matrix`` and ``from_power_basis`` are currently
+    NumPy only. ``insert_knot`` is currently not supported with CuPy.
+
+    If the spline is called on an array ``x`` with namespace different from the
+    namespace ``xp`` of the knots ``t`` and coefficients ``c``, an attempt will
+    be made to coerce ``x`` to the ``xp`` namespace. Mixing namespaces in this
+    way is not recommended.
+
+    """
+)
+
+
+@xp_capabilities(
+    cpu_only=True, jax_jit=False,
+    exceptions=["cupy"],
+    method_capabilities={
+        "design_matrix": dict(np_only=True),
+        "from_power_basis": dict(np_only=True),
+        "insert_knot": dict(
+            cpu_only=True,
+            jax_jit=False,
+            skip_backends=[
+                ("dask.array", "https://github.com/scipy/scipy/issues/24205")
+            ]
+        ),
+    },
+    skip_backends=[
+        ("dask.array",
+         "https://github.com/scipy/scipy/issues/24205")
+    ],
+    extra_note=_bspline_extra_note,
+)
+class BSpline:
+    r"""Univariate spline in the B-spline basis.
+
+    .. math::
+
+        S(x) = \sum_{j=0}^{n-1} c_j  B_{j, k; t}(x)
+
+    where :math:`B_{j, k; t}` are B-spline basis functions of degree `k`
+    and knots `t`.
+
+    Parameters
+    ----------
+    t : ndarray, shape (n+k+1,)
+        knots
+    c : ndarray, shape (>=n, ...)
+        spline coefficients
+    k : int
+        B-spline degree
+    extrapolate : bool or 'periodic', optional
+        whether to extrapolate beyond the base interval, ``t[k] .. t[n]``,
+        or to return nans.
+        If True, extrapolates the first and last polynomial pieces of b-spline
+        functions active on the base interval.
+        If 'periodic', periodic extrapolation is used.
+        Default is True.
+    axis : int, optional
+        Interpolation axis. Default is zero.
+
+    Attributes
+    ----------
+    t : ndarray
+        knot vector
+    c : ndarray
+        spline coefficients
+    k : int
+        spline degree
+    extrapolate : bool
+        If True, extrapolates the first and last polynomial pieces of b-spline
+        functions active on the base interval.
+    axis : int
+        Interpolation axis.
+    tck : tuple
+        A read-only equivalent of ``(self.t, self.c, self.k)``
+
+    Methods
+    -------
+    __call__
+    basis_element
+    derivative
+    antiderivative
+    integrate
+    insert_knot
+    construct_fast
+    design_matrix
+    from_power_basis
+
+    Notes
+    -----
+    B-spline basis elements are defined via
+
+    .. math::
+
+        B_{i, 0}(x) = 1, \textrm{if $t_i \le x < t_{i+1}$, otherwise $0$,}
+
+        B_{i, k}(x) = \frac{x - t_i}{t_{i+k} - t_i} B_{i, k-1}(x)
+                 + \frac{t_{i+k+1} - x}{t_{i+k+1} - t_{i+1}} B_{i+1, k-1}(x)
+
+    **Implementation details**
+
+    - At least ``k+1`` coefficients are required for a spline of degree `k`,
+      so that ``n >= k+1``. Additional coefficients, ``c[j]`` with
+      ``j > n``, are ignored.
+
+    - B-spline basis elements of degree `k` form a partition of unity on the
+      *base interval*, ``t[k] <= x <= t[n]``.
+
+
+    Examples
+    --------
+    Translating the recursive definition of B-splines into Python code, we have:
+
+    >>> def B(x, k, i, t):
+    ...    if k == 0:
+    ...       return 1.0 if t[i] <= x < t[i+1] else 0.0
+    ...    if t[i+k] == t[i]:
+    ...       c1 = 0.0
+    ...    else:
+    ...       c1 = (x - t[i])/(t[i+k] - t[i]) * B(x, k-1, i, t)
+    ...    if t[i+k+1] == t[i+1]:
+    ...       c2 = 0.0
+    ...    else:
+    ...       c2 = (t[i+k+1] - x)/(t[i+k+1] - t[i+1]) * B(x, k-1, i+1, t)
+    ...    return c1 + c2
+
+    >>> def bspline(x, t, c, k):
+    ...    n = len(t) - k - 1
+    ...    assert (n >= k+1) and (len(c) >= n)
+    ...    return sum(c[i] * B(x, k, i, t) for i in range(n))
+
+    Note that this is an inefficient (if straightforward) way to
+    evaluate B-splines --- this spline class does it in an equivalent,
+    but much more efficient way.
+
+    Here we construct a quadratic spline function on the base interval
+    ``2 <= x <= 4`` and compare with the naive way of evaluating the spline:
+
+    >>> from scipy.interpolate import BSpline
+    >>> k = 2
+    >>> t = [0, 1, 2, 3, 4, 5, 6]
+    >>> c = [-1, 2, 0, -1]
+    >>> spl = BSpline(t, c, k)
+    >>> spl(2.5)
+    array(1.375)
+    >>> bspline(2.5, t, c, k)
+    1.375
+
+    Note that outside of the base interval results differ. This is because
+    `BSpline` extrapolates the first and last polynomial pieces of B-spline
+    functions active on the base interval.
+
+    >>> import matplotlib.pyplot as plt
+    >>> import numpy as np
+    >>> fig, ax = plt.subplots()
+    >>> xx = np.linspace(1.5, 4.5, 50)
+    >>> ax.plot(xx, [bspline(x, t, c ,k) for x in xx], 'r-', lw=3, label='naive')
+    >>> ax.plot(xx, spl(xx), 'b-', lw=4, alpha=0.7, label='BSpline')
+    >>> ax.grid(True)
+    >>> ax.legend(loc='best')
+    >>> plt.show()
+
+
+    References
+    ----------
+    .. [1] Michael Floater, An introduction to spline theory, 2025,
+        https://www.uio.no/studier/emner/matnat/math/MAT4170/v25/undervisningsmateriale/spline_notes.pdf
+    .. [2] Carl de Boor, A practical guide to splines, Springer, 2001.
+
+    """
+
+    # generic type compatibility with scipy-stubs
+    __class_getitem__: classmethod = classmethod(GenericAlias)
+
+
+    def __init__(self, t, c, k, extrapolate=True, axis=0):
+        super().__init__()
+
+        xp = array_namespace(t, c)
+        xp_bspline_cls, xp_internal = _get_xp_bspline_cls(xp)
+        if not is_numpy(xp):
+            # only convert t and c to internal namespace if it is not NumPy
+            # to preserve NumPy behavior with lists.
+            t, c = xp_internal.asarray(t), xp_internal.asarray(c)
+        self._delegate_to = xp_bspline_cls(
+            t, c, k, extrapolate=extrapolate, axis=axis
+        )
+        # The user facing namespace and the internal namespace used by
+        # ``self._delegate_to`` may differ.
+        # Track the user facing namespace in ``self._xp`` and the internal
+        # namespace used in the delegate in ``self._xp_internal`` for easy mapping.
+        # The internal namespace is also available as
+        # ``array_namespace(self._delegate_to.t)``
+        # but we cache it here to save on such lookups. Custom ``__getstate`` and
+        # ``__setstate__`` dunder methods are needed to allow for pickling while
+        # keeping modules in attributes like this.
+        self._xp = xp
+        self._xp_internal = xp_internal
+
+    @classmethod
+    def _construct_from_xp(cls, xp_bspline, *, xp_external):
+        self = object.__new__(cls)
+        self._delegate_to = xp_bspline
+        self._xp = xp_external
+        self._xp_internal = array_namespace(xp_bspline.t)
+        return self
+
+    @classmethod
+    def construct_fast(cls, t, c, k, extrapolate=True, axis=0):
+        """Construct a spline without making checks.
+
+        Accepts same parameters as the regular constructor. Input arrays
+        `t` and `c` must of correct shape and dtype.
+        """
+        xp = array_namespace(t, c)
+        xp_bspline_cls, xp_internal = _get_xp_bspline_cls(xp)
+        return cls._construct_from_xp(
+            xp_bspline_cls.construct_fast(
+                xp_internal.asarray(t),
+                xp_internal.asarray(c),
+                k,
+                extrapolate=extrapolate, axis=axis,
+            ),
+            xp_external=xp,
+        )
+
+    @property
+    def tck(self):
+        """Equivalent to ``(self.t, self.c, self.k)`` (read-only).
+        """
+        return self.t, self.c, self.k
+
+    @property
+    def t(self):
+        return self._xp.asarray(self._delegate_to.t)
+
+    @t.setter
+    def t(self, t):
+        # Preserves existing behavior to allow setting with a list when using
+        # the NumPy backend. Don't allow such conversions for other backends.
+        self._delegate_to.t = (
+            self._xp_internal.asarray(t) if is_numpy(self._xp_internal) else t
+        )
+
+    @property
+    def c(self):
+        return self._xp.asarray(self._delegate_to.c)
+
+    @c.setter
+    def c(self, c):
+        # Preserves existing behavior to allow setting with a list when using
+        # the NumPy backend. Don't allow such conversions for other backends.
+        self._delegate_to.c = (
+            self._xp_internal.asarray(c) if is_numpy(self._xp_internal) else c
+        )
+
+    @property
+    def k(self):
+        return self._delegate_to.k
+
+    @k.setter
+    def k(self, k):
+        self._delegate_to.k = k
+
+    @property
+    def extrapolate(self):
+        return self._delegate_to.extrapolate
+
+    @extrapolate.setter
+    def extrapolate(self, extrapolate):
+        self._delegate_to.extrapolate = extrapolate
+
+    @property
+    def axis(self):
+        return self._delegate_to.axis
+
+    @axis.setter
+    def axis(self, axis):
+        self._delegate_to.axis = axis
+
+    @classmethod
+    def basis_element(cls, t, extrapolate=True):
+        """Return a B-spline basis element ``B(x | t[0], ..., t[k+1])``.
+
+        Parameters
+        ----------
+        t : ndarray, shape (k+2,)
+            internal knots
+        extrapolate : bool or 'periodic', optional
+            whether to extrapolate beyond the base interval, ``t[0] .. t[k+1]``,
+            or to return nans.
+            If 'periodic', periodic extrapolation is used.
+            Default is True.
+
+        Returns
+        -------
+        basis_element : callable
+            A callable representing a B-spline basis element for the knot
+            vector `t`.
+
+        Notes
+        -----
+        The degree of the B-spline, `k`, is inferred from the length of `t` as
+        ``len(t)-2``. The knot vector is constructed by appending and prepending
+        ``k+1`` elements to internal knots `t`.
+
+        Examples
+        --------
+        Construct a cubic B-spline:
+
+        >>> import numpy as np
+        >>> from scipy.interpolate import BSpline
+        >>> b = BSpline.basis_element([0, 1, 2, 3, 4])
+        >>> k = b.k
+        >>> b.t[k:-k]
+        array([ 0.,  1.,  2.,  3.,  4.])
+        >>> k
+        3
+
+        Construct a quadratic B-spline on ``[0, 1, 1, 2]``, and compare
+        to its explicit form:
+
+        >>> t = [0, 1, 1, 2]
+        >>> b = BSpline.basis_element(t)
+        >>> def f(x):
+        ...     return np.where(x < 1, x*x, (2. - x)**2)
+
+        >>> import matplotlib.pyplot as plt
+        >>> fig, ax = plt.subplots()
+        >>> x = np.linspace(0, 2, 51)
+        >>> ax.plot(x, b(x), 'g', lw=3)
+        >>> ax.plot(x, f(x), 'r', lw=8, alpha=0.4)
+        >>> ax.grid(True)
+        >>> plt.show()
+
+        """
+        xp = array_namespace(t)
+        xp_bspline_cls, xp_internal = _get_xp_bspline_cls(xp)
+        return cls._construct_from_xp(
+            xp_bspline_cls.basis_element(
+                xp_internal.asarray(t), extrapolate=extrapolate,
+            ),
+            xp_external=xp,
+        )
+
+    @classmethod
+    def design_matrix(cls, x, t, k, extrapolate=False):
+        """
+        Returns a design matrix as a CSR format sparse array.
+
+        Parameters
+        ----------
+        x : array_like, shape (n,)
+            Points to evaluate the spline at.
+        t : array_like, shape (nt,)
+            Sorted 1D array of knots.
+        k : int
+            B-spline degree.
+        extrapolate : bool or 'periodic', optional
+            Whether to extrapolate based on the first and last intervals
+            or raise an error. If 'periodic', periodic extrapolation is used.
+            Default is False.
+
+            .. versionadded:: 1.10.0
+
+        Returns
+        -------
+        design_matrix : `csr_array` object
+            Sparse matrix in CSR format where each row contains all the basis
+            elements of the input row (first row = basis elements of x[0],
+            ..., last row = basis elements x[-1]).
+
+        Examples
+        --------
+        Construct a design matrix for a B-spline
+
+        >>> from scipy.interpolate import make_interp_spline, BSpline
+        >>> import numpy as np
+        >>> x = np.linspace(0, np.pi * 2, 4)
+        >>> y = np.sin(x)
+        >>> k = 3
+        >>> bspl = make_interp_spline(x, y, k=k)
+        >>> design_matrix = bspl.design_matrix(x, bspl.t, k)
+        >>> design_matrix.toarray()
+        [[1.        , 0.        , 0.        , 0.        ],
+        [0.2962963 , 0.44444444, 0.22222222, 0.03703704],
+        [0.03703704, 0.22222222, 0.44444444, 0.2962963 ],
+        [0.        , 0.        , 0.        , 1.        ]]
+
+        Construct a design matrix for some vector of knots
+
+        >>> k = 2
+        >>> t = [-1, 0, 1, 2, 3, 4, 5, 6]
+        >>> x = [1, 2, 3, 4]
+        >>> design_matrix = BSpline.design_matrix(x, t, k).toarray()
+        >>> design_matrix
+        [[0.5, 0.5, 0. , 0. , 0. ],
+        [0. , 0.5, 0.5, 0. , 0. ],
+        [0. , 0. , 0.5, 0.5, 0. ],
+        [0. , 0. , 0. , 0.5, 0.5]]
+
+        This result is equivalent to the one created in the sparse format
+
+        >>> c = np.eye(len(t) - k - 1)
+        >>> design_matrix_gh = BSpline(t, c, k)(x)
+        >>> np.allclose(design_matrix, design_matrix_gh, atol=1e-14)
+        True
+
+        Notes
+        -----
+        .. versionadded:: 1.8.0
+
+        In each row of the design matrix all the basis elements are evaluated
+        at the certain point (first row - x[0], ..., last row - x[-1]).
+
+        `nt` is a length of the vector of knots: as far as there are
+        `nt - k - 1` basis elements, `nt` should be not less than `2 * k + 2`
+        to have at least `k + 1` basis element.
+
+        Out of bounds `x` raises a ValueError.
+        """
+        xp = array_namespace(x, t)
+        xp_bspline_cls, xp_internal = _get_xp_bspline_cls(xp)
+        return xp_bspline_cls.design_matrix(
+            xp_internal.asarray(x), xp_internal.asarray(t), k, extrapolate=extrapolate
+        )
+
+    def __call__(self, x, nu=0, extrapolate=None):
+        """
+        Evaluate a spline function.
+
+        Parameters
+        ----------
+        x : array_like
+            points to evaluate the spline at.
+        nu : int, optional
+            derivative to evaluate (default is 0).
+        extrapolate : bool or 'periodic', optional
+            whether to extrapolate based on the first and last intervals
+            or return nans. If 'periodic', periodic extrapolation is used.
+            Default is `self.extrapolate`.
+
+        Returns
+        -------
+        y : array_like
+            Shape is determined by replacing the interpolation axis
+            in the coefficient array with the shape of `x`.
+
+        """
+        return self._xp.asarray(
+            self._delegate_to(
+                self._xp_internal.asarray(x), nu=nu, extrapolate=extrapolate
+            )
+        )
+
+    def derivative(self, nu=1):
+        """Return a B-spline representing the derivative.
+
+        Parameters
+        ----------
+        nu : int, optional
+            Derivative order.
+            Default is 1.
+
+        Returns
+        -------
+        b : `BSpline` object
+            A new instance representing the derivative.
+
+        See Also
+        --------
+        splder, splantider
+
+        """
+        if hasattr(self._delegate_to, "derivative"):
+            # NumPy backend class lacks derivative method because it relies on
+            # the array-agnostic codepath below.
+            return self._construct_from_xp(
+                self._delegate_to.derivative(nu=nu),
+                xp_external=self._xp,
+            )
+
+        ## Array-agnostic codepath
+        xp = self._xp
+        c = self._xp.asarray(self.c, copy=True)
+        t = self.t
+
+        # pad the c array if needed
+        ct = t.shape[0] - c.shape[0]
+        if ct > 0:
+            c = concat_1d(xp, c, xp.zeros((ct,) + c.shape[1:]))
+        tck = _fitpack_impl.splder((t, c, self.k), nu)
+        return self.construct_fast(*tck, extrapolate=self.extrapolate, axis=self.axis)
+
+    def antiderivative(self, nu=1):
+        """Return a B-spline representing the antiderivative.
+
+        Parameters
+        ----------
+        nu : int, optional
+            Antiderivative order. Default is 1.
+
+        Returns
+        -------
+        b : `BSpline` object
+            A new instance representing the antiderivative.
+
+        See Also
+        --------
+        splder, splantider
+
+        Notes
+        -----
+        If antiderivative is computed and ``self.extrapolate='periodic'``,
+        it will be set to False for the returned instance. This is done because
+        the antiderivative is no longer periodic and its correct evaluation
+        outside of the initially given x interval is difficult.
+
+        """
+        if hasattr(self._delegate_to, "antiderivative"):
+            # NumPy backend class lacks antiderivative method because it relies on the
+            # array-agnostic codepath below.
+            return self._construct_from_xp(
+                self._delegate_to.antiderivative(nu=nu),
+                xp_external=self._xp,
+            )
+
+        ## Array-agnostic codepath
+        xp = self._xp
+        c = self._xp.asarray(self.c, copy=True)
+        t = self.t
+
+        # pad the c array if needed
+        ct = t.shape[0] - c.shape[0]
+        if ct > 0:
+            c = concat_1d(xp, c, xp.zeros((ct,) + c.shape[1:]))
+        tck = _fitpack_impl.splantider((t, c, self.k), nu)
+
+        if self.extrapolate == 'periodic':
+            extrapolate = False
+        else:
+            extrapolate = self.extrapolate
+
+        return self.construct_fast(*tck, extrapolate=extrapolate, axis=self.axis)
+
+    def integrate(self, a, b, extrapolate=None):
+        """Compute a definite integral of the spline.
+
+        Parameters
+        ----------
+        a : float
+            Lower limit of integration.
+        b : float
+            Upper limit of integration.
+        extrapolate : bool or 'periodic', optional
+            whether to extrapolate beyond the base interval,
+            ``t[k] .. t[-k-1]``, or take the spline to be zero outside of the
+            base interval. If 'periodic', periodic extrapolation is used.
+            If None (default), use `self.extrapolate`.
+
+        Returns
+        -------
+        I : array_like
+            Definite integral of the spline over the interval ``[a, b]``.
+
+        Examples
+        --------
+        Construct the linear spline ``x if x < 1 else 2 - x`` on the base
+        interval :math:`[0, 2]`, and integrate it
+
+        >>> from scipy.interpolate import BSpline
+        >>> b = BSpline.basis_element([0, 1, 2])
+        >>> b.integrate(0, 1)
+        array(0.5)
+
+        If the integration limits are outside of the base interval, the result
+        is controlled by the `extrapolate` parameter
+
+        >>> b.integrate(-1, 1)
+        array(0.0)
+        >>> b.integrate(-1, 1, extrapolate=False)
+        array(0.5)
+
+        >>> import matplotlib.pyplot as plt
+        >>> fig, ax = plt.subplots()
+        >>> ax.grid(True)
+        >>> ax.axvline(0, c='r', lw=5, alpha=0.5)  # base interval
+        >>> ax.axvline(2, c='r', lw=5, alpha=0.5)
+        >>> xx = [-1, 1, 2]
+        >>> ax.plot(xx, b(xx))
+        >>> plt.show()
+
+        """
+        return self._xp.asarray(
+            self._delegate_to.integrate(a, b, extrapolate=extrapolate)
+        )
+
+    @classmethod
+    def from_power_basis(cls, pp, bc_type='not-a-knot'):
+        r"""
+        Construct a polynomial in the B-spline basis
+        from a piecewise polynomial in the power basis.
+
+        For now, accepts ``CubicSpline`` instances only.
+
+        Parameters
+        ----------
+        pp : CubicSpline
+            A piecewise polynomial in the power basis, as created
+            by ``CubicSpline``
+        bc_type : str, optional
+            Boundary condition type as in ``CubicSpline``: one of the
+            ``not-a-knot``, ``natural``, ``clamped``, or ``periodic``.
+            Necessary for construction an instance of ``BSpline`` class.
+            Default is ``not-a-knot``.
+
+        Returns
+        -------
+        b : `BSpline` object
+            A new instance representing the initial polynomial
+            in the B-spline basis.
+
+        Notes
+        -----
+        .. versionadded:: 1.8.0
+
+        Accepts only ``CubicSpline`` instances for now.
+
+        The algorithm follows from differentiation
+        the Marsden's identity [1]: each of coefficients of spline
+        interpolation function in the B-spline basis is computed as follows:
+
+        .. math::
+
+            c_j = \sum_{m=0}^{k} \frac{(k-m)!}{k!}
+                       c_{m,i} (-1)^{k-m} D^m p_{j,k}(x_i)
+
+        :math:`c_{m, i}` - a coefficient of CubicSpline,
+        :math:`D^m p_{j, k}(x_i)` - an m-th defivative of a dual polynomial
+        in :math:`x_i`.
+
+        ``k`` always equals 3 for now.
+
+        First ``n - 2`` coefficients are computed in :math:`x_i = x_j`, e.g.
+
+        .. math::
+
+            c_1 = \sum_{m=0}^{k} \frac{(k-1)!}{k!} c_{m,1} D^m p_{j,3}(x_1)
+
+        Last ``nod + 2`` coefficients are computed in ``x[-2]``,
+        ``nod`` - number of derivatives at the ends.
+
+        For example, consider :math:`x = [0, 1, 2, 3, 4]`,
+        :math:`y = [1, 1, 1, 1, 1]` and bc_type = ``natural``
+
+        The coefficients of CubicSpline in the power basis:
+
+        :math:`[[0, 0, 0, 0, 0], [0, 0, 0, 0, 0],
+        [0, 0, 0, 0, 0], [1, 1, 1, 1, 1]]`
+
+        The knot vector: :math:`t = [0, 0, 0, 0, 1, 2, 3, 4, 4, 4, 4]`
+
+        In this case
+
+        .. math::
+
+            c_j = \frac{0!}{k!} c_{3, i} k! = c_{3, i} = 1,~j = 0, ..., 6
+
+        References
+        ----------
+        .. [1] Michael Floater, An introduction to spline theory, 2025, Section 4.1
+            https://www.uio.no/studier/emner/matnat/math/MAT4170/v25/undervisningsmateriale/spline_notes.pdf
+
+        """
+        xp = array_namespace(pp.x, pp.c)
+        xp_bspline_cls, _ = _get_xp_bspline_cls(xp)
+        # from_power_basis isn't available in CuPy as of version 14 causing this to
+        # raise with an AttributeError when xp_internal is CuPy.
+        spl = xp_bspline_cls.from_power_basis(pp, bc_type=bc_type)
+        return cls._construct_from_xp(spl, xp_external=xp)
+
+    def insert_knot(self, x, m=1):
+        """Insert a new knot at `x` of multiplicity `m`.
+
+        Given the knots and coefficients of a B-spline representation, create a
+        new B-spline with a knot inserted `m` times at point `x`.
+
+        Parameters
+        ----------
+        x : float
+            The position of the new knot
+        m : int, optional
+            The number of times to insert the given knot (its multiplicity).
+            Default is 1.
+
+        Returns
+        -------
+        spl : `BSpline` object
+            A new `BSpline` object with the new knot inserted.
+
+        See Also
+        --------
+        scipy.interpolate.insert
+
+        Notes
+        -----
+        Based on algorithms from [1]_ and [2]_.
+
+        In case of a periodic spline (``self.extrapolate == "periodic"``)
+        there must be either at least k interior knots t(j) satisfying
+        ``t(k+1)>> import numpy as np
+        >>> from scipy.interpolate import BSpline, make_interp_spline
+        >>> x = np.linspace(0, 10, 5)
+        >>> y = np.sin(x)
+        >>> spl = make_interp_spline(x, y, k=3)
+        >>> spl.t
+        array([ 0.,  0.,  0.,  0.,  5., 10., 10., 10., 10.])
+
+        Insert a single knot
+
+        >>> spl_1 = spl.insert_knot(3)
+        >>> spl_1.t
+        array([ 0.,  0.,  0.,  0.,  3.,  5., 10., 10., 10., 10.])
+
+        Insert a multiple knot
+
+        >>> spl_2 = spl.insert_knot(8, m=3)
+        >>> spl_2.t
+        array([ 0.,  0.,  0.,  0.,  5.,  8.,  8.,  8., 10., 10., 10., 10.])
+
+        """
+        # insert_knot isn't available in CuPy as of version 14 causing this to
+        # raise with an AttributeError when xp_internal is CuPy.
+        return self._construct_from_xp(
+            self._delegate_to.insert_knot(x, m=m), xp_external=self._xp
+        )
+
+    def __getstate__(self):
+        # need custom __getstate__ and __setstate__ methods to allow pickling
+        # while holding onto namespaces.
+        return (self._delegate_to, self._xp.empty(0))
+
+    def __setstate__(self, state):
+        self._delegate_to, sentinel_array = state
+        self._xp_internal = array_namespace(self._delegate_to.t)
+        self._xp = array_namespace(sentinel_array)
+
+
+def _insert(xval, t, c, k, periodic=False):
+    """Insert a single knot at `xval`."""
+    #
+    # This is a port of the FORTRAN `insert` routine by P. Dierckx,
+    # https://github.com/scipy/scipy/blob/maintenance/1.11.x/scipy/interpolate/fitpack/insert.f
+    # which carries the following comment:
+    #
+    # subroutine insert inserts a new knot x into a spline function s(x)
+    # of degree k and calculates the b-spline representation of s(x) with
+    # respect to the new set of knots. in addition, if iopt.ne.0, s(x)
+    # will be considered as a periodic spline with period per=t(n-k)-t(k+1)
+    # satisfying the boundary constraints
+    #      t(i+n-2*k-1) = t(i)+per  ,i=1,2,...,2*k+1
+    #      c(i+n-2*k-1) = c(i)      ,i=1,2,...,k
+    # in that case, the knots and b-spline coefficients returned will also
+    # satisfy these boundary constraints, i.e.
+    #      tt(i+nn-2*k-1) = tt(i)+per  ,i=1,2,...,2*k+1
+    #      cc(i+nn-2*k-1) = cc(i)      ,i=1,2,...,k
+    interval = _dierckx.find_interval(t, k, float(xval), k, False)
+    if interval < 0:
+        # extrapolated values are guarded for in BSpline.insert_knot
+        raise ValueError(f"Cannot insert the knot at {xval}.")
+
+    # super edge case: a knot with multiplicity > k+1
+    # see https://github.com/scipy/scipy/commit/037204c3e91
+    if t[interval] == t[interval + k + 1]:
+        interval -= 1
+
+    if periodic:
+        if (interval + 1 <= 2*k) and (interval + 1 >= t.shape[0] - 2*k):
+            # in case of a periodic spline (iopt.ne.0) there must be
+            # either at least k interior knots t(j) satisfying t(k+1)= nk - k:
+            # adjust the left-hand boundary knots & coefs
+            tt[:k] = tt[nk - k:nk] - T
+            cc[:k, ...] = cc[n2k:n2k + k, ...]
+
+        if interval <= 2*k-1:
+            # adjust the right-hand boundary knots & coefs
+            tt[n-k:] = tt[k+1:k+1+k] + T
+            cc[n2k:n2k + k, ...] = cc[:k, ...]
+
+    return tt, cc
+
+
+#################################
+#  Interpolating spline helpers #
+#################################
+
+def _not_a_knot(x, k):
+    """Given data x, construct the knot vector w/ not-a-knot BC.
+    cf de Boor, XIII(12).
+
+    For even k, it's a bit ad hoc: Greville sites + omit 2nd and 2nd-to-last
+    data points, a la not-a-knot.
+    This seems to match what Dierckx does, too:
+    https://github.com/scipy/scipy/blob/maintenance/1.11.x/scipy/interpolate/fitpack/fpcurf.f#L63-L80
+    """
+    x = np.asarray(x)
+    if k % 2 == 1:
+        k2 = (k + 1) // 2
+        t = x.copy()
+    else:
+        k2 = k // 2
+        t = (x[1:] + x[:-1]) / 2
+
+    t = t[k2:-k2]
+    t = np.r_[(x[0],)*(k+1), t, (x[-1],)*(k+1)]
+    return t
+
+
+def _augknt(x, k):
+    """Construct a knot vector appropriate for the order-k interpolation."""
+    return np.r_[(x[0],)*k, x, (x[-1],)*k]
+
+
+def _convert_string_aliases(deriv, target_shape):
+    if isinstance(deriv, str):
+        if deriv == "clamped":
+            deriv = [(1, np.zeros(target_shape))]
+        elif deriv == "natural":
+            deriv = [(2, np.zeros(target_shape))]
+        else:
+            raise ValueError(f"Unknown boundary condition : {deriv}")
+    return deriv
+
+
+def _process_deriv_spec(deriv):
+    if deriv is not None:
+        try:
+            ords, vals = zip(*deriv)
+        except TypeError as e:
+            msg = ("Derivatives, `bc_type`, should be specified as a pair of "
+                   "iterables of pairs of (order, value).")
+            raise ValueError(msg) from e
+    else:
+        ords, vals = [], []
+    return np.atleast_1d(ords, vals)
+
+
+def _woodbury_algorithm(A, ur, ll, b, k):
+    '''
+    Solve a cyclic banded linear system with upper right
+    and lower blocks of size ``(k-1) / 2`` using
+    the Woodbury formula
+
+    Parameters
+    ----------
+    A : 2-D array, shape(k, n)
+        Matrix of diagonals of original matrix (see
+        ``solve_banded`` documentation).
+    ur : 2-D array, shape(bs, bs)
+        Upper right block matrix.
+    ll : 2-D array, shape(bs, bs)
+        Lower left block matrix.
+    b : 1-D array, shape(n,)
+        Vector of constant terms of the system of linear equations.
+    k : int
+        B-spline degree.
+
+    Returns
+    -------
+    c : 1-D array, shape(n,)
+        Solution of the original system of linear equations.
+
+    Notes
+    -----
+    This algorithm works only for systems with banded matrix A plus
+    a correction term U @ V.T, where the matrix U @ V.T gives upper right
+    and lower left block of A
+    The system is solved with the following steps:
+        1.  New systems of linear equations are constructed:
+            A @ z_i = u_i,
+            u_i - column vector of U,
+            i = 1, ..., k - 1
+        2.  Matrix Z is formed from vectors z_i:
+            Z = [ z_1 | z_2 | ... | z_{k - 1} ]
+        3.  Matrix H = (1 + V.T @ Z)^{-1}
+        4.  The system A' @ y = b is solved
+        5.  x = y - Z @ (H @ V.T @ y)
+    Also, ``n`` should be greater than ``k``, otherwise corner block
+    elements will intersect with diagonals.
+
+    Examples
+    --------
+    Consider the case of n = 8, k = 5 (size of blocks - 2 x 2).
+    The matrix of a system:       U:          V:
+      x  x  x  *  *  a  b         a b 0 0     0 0 1 0
+      x  x  x  x  *  *  c         0 c 0 0     0 0 0 1
+      x  x  x  x  x  *  *         0 0 0 0     0 0 0 0
+      *  x  x  x  x  x  *         0 0 0 0     0 0 0 0
+      *  *  x  x  x  x  x         0 0 0 0     0 0 0 0
+      d  *  *  x  x  x  x         0 0 d 0     1 0 0 0
+      e  f  *  *  x  x  x         0 0 e f     0 1 0 0
+
+    References
+    ----------
+    .. [1] William H. Press, Saul A. Teukolsky, William T. Vetterling
+           and Brian P. Flannery, Numerical Recipes, 2007, Section 2.7.3
+
+    '''
+    k_mod = k - k % 2
+    bs = int((k - 1) / 2) + (k + 1) % 2
+
+    n = A.shape[1] + 1
+    U = np.zeros((n - 1, k_mod))
+    VT = np.zeros((k_mod, n - 1))  # V transpose
+
+    # upper right block
+    U[:bs, :bs] = ur
+    VT[np.arange(bs), np.arange(bs) - bs] = 1
+
+    # lower left block
+    U[-bs:, -bs:] = ll
+    VT[np.arange(bs) - bs, np.arange(bs)] = 1
+
+    Z = solve_banded((bs, bs), A, U)
+
+    H = solve(np.identity(k_mod) + VT @ Z, np.identity(k_mod))
+
+    y = solve_banded((bs, bs), A, b)
+    c = y - Z @ (H @ (VT @ y))
+
+    return c
+
+
+def _periodic_knots(x, k):
+    '''
+    returns vector of nodes on circle
+    '''
+    xc = np.copy(x)
+    n = len(xc)
+    if k % 2 == 0:
+        dx = np.diff(xc)
+        xc[1: -1] -= dx[:-1] / 2
+    dx = np.diff(xc)
+    t = np.zeros(n + 2 * k)
+    t[k: -k] = xc
+    for i in range(0, k):
+        # filling first `k` elements in descending order
+        t[k - i - 1] = t[k - i] - dx[-(i % (n - 1)) - 1]
+        # filling last `k` elements in ascending order
+        t[-k + i] = t[-k + i - 1] + dx[i % (n - 1)]
+    return t
+
+
+def _make_interp_per_full_matr(x, y, t, k):
+    '''
+    Returns a solution of a system for B-spline interpolation with periodic
+    boundary conditions. First ``k - 1`` rows of matrix are conditions of
+    periodicity (continuity of ``k - 1`` derivatives at the boundary points).
+    Last ``n`` rows are interpolation conditions.
+    RHS is ``k - 1`` zeros and ``n`` ordinates in this case.
+
+    Parameters
+    ----------
+    x : 1-D array, shape (n,)
+        Values of x - coordinate of a given set of points.
+    y : 1-D array, shape (n,)
+        Values of y - coordinate of a given set of points.
+    t : 1-D array, shape(n+2*k,)
+        Vector of knots.
+    k : int
+        The maximum degree of spline
+
+    Returns
+    -------
+    c : 1-D array, shape (n+k-1,)
+        B-spline coefficients
+
+    Notes
+    -----
+    ``t`` is supposed to be taken on circle.
+
+    '''
+
+    x, y, t = map(np.asarray, (x, y, t))
+
+    n = x.size
+    # LHS: the colocation matrix + derivatives at edges
+    matr = np.zeros((n + k - 1, n + k - 1))
+
+    # derivatives at x[0] and x[-1]:
+    for i in range(k - 1):
+        bb = _dierckx.evaluate_all_bspl(t, k, x[0], k, i + 1)
+        matr[i, : k + 1] += bb
+        bb = _dierckx.evaluate_all_bspl(t, k, x[-1], n + k - 1, i + 1)[:-1]
+        matr[i, -k:] -= bb
+
+    # colocation matrix
+    for i in range(n):
+        xval = x[i]
+        # find interval
+        if xval == t[k]:
+            left = k
+        else:
+            left = np.searchsorted(t, xval) - 1
+
+        # fill a row
+        bb = _dierckx.evaluate_all_bspl(t, k, xval, left)
+        matr[i + k - 1, left-k:left+1] = bb
+
+    # RHS
+    b = np.r_[[0] * (k - 1), y]
+
+    c = solve(matr, b)
+    return c
+
+
+def _handle_lhs_derivatives(t, k, xval, ab, kl, ku, deriv_ords, offset=0):
+    """ Fill in the entries of the colocation matrix corresponding to known
+    derivatives at `xval`.
+
+    The colocation matrix is in the banded storage, as prepared by _coloc.
+    No error checking.
+
+    Parameters
+    ----------
+    t : ndarray, shape (nt + k + 1,)
+        knots
+    k : int
+        B-spline order
+    xval : float
+        The value at which to evaluate the derivatives at.
+    ab : ndarray, shape(2*kl + ku + 1, nt), Fortran order
+        B-spline colocation matrix.
+        This argument is modified *in-place*.
+    kl : int
+        Number of lower diagonals of ab.
+    ku : int
+        Number of upper diagonals of ab.
+    deriv_ords : 1D ndarray
+        Orders of derivatives known at xval
+    offset : int, optional
+        Skip this many rows of the matrix ab.
+
+    """
+    # find where `xval` is in the knot vector, `t`
+    left = _dierckx.find_interval(t, k, float(xval), k, False)
+
+    # compute and fill in the derivatives @ xval
+    for row in range(deriv_ords.shape[0]):
+        nu = deriv_ords[row]
+        wrk = _dierckx.evaluate_all_bspl(t, k, xval, left, nu)
+
+        # if A were a full matrix, it would be just
+        # ``A[row + offset, left-k:left+1] = bb``.
+        for a in range(k+1):
+            clmn = left - k + a
+            ab[kl + ku + offset + row - clmn, clmn] = wrk[a]
+
+
+def _make_periodic_spline(x, y, t, k, axis, *, xp):
+    '''
+    Compute the (coefficients of) interpolating B-spline with periodic
+    boundary conditions.
+
+    Parameters
+    ----------
+    x : array_like, shape (n,)
+        Abscissas.
+    y : array_like, shape (n,)
+        Ordinates.
+    k : int
+        B-spline degree.
+    t : array_like, shape (n + 2 * k,).
+        Knots taken on a circle, ``k`` on the left and ``k`` on the right
+        of the vector ``x``.
+
+    Returns
+    -------
+    b : `BSpline` object
+        A `BSpline` object of the degree ``k`` and with knots ``t``.
+
+    Notes
+    -----
+    The original system is formed by ``n + k - 1`` equations where the first
+    ``k - 1`` of them stand for the ``k - 1`` derivatives continuity on the
+    edges while the other equations correspond to an interpolating case
+    (matching all the input points). Due to a special form of knot vector, it
+    can be proved that in the original system the first and last ``k``
+    coefficients of a spline function are the same, respectively. It follows
+    from the fact that all ``k - 1`` derivatives are equal term by term at ends
+    and that the matrix of the original system of linear equations is
+    non-degenerate. So, we can reduce the number of equations to ``n - 1``
+    (first ``k - 1`` equations could be reduced). Another trick of this
+    implementation is cyclic shift of values of B-splines due to equality of
+    ``k`` unknown coefficients. With this we can receive matrix of the system
+    with upper right and lower left blocks, and ``k`` diagonals.  It allows
+    to use Woodbury formula to optimize the computations.
+
+    '''
+    n = y.shape[0]
+
+    extradim = prod(y.shape[1:])
+    y_new = y.reshape(n, extradim)
+    c = np.zeros((n + k - 1, extradim))
+
+    # n <= k case is solved with full matrix
+    if n <= k:
+        for i in range(extradim):
+            c[:, i] = _make_interp_per_full_matr(x, y_new[:, i], t, k)
+        c = np.ascontiguousarray(c.reshape((n + k - 1,) + y.shape[1:]))
+        t, c = xp.asarray(t), xp.asarray(c)
+        return BSpline.construct_fast(t, c, k, extrapolate='periodic', axis=axis)
+
+    nt = len(t) - k - 1
+
+    # size of block elements
+    kul = int(k / 2)
+
+    # kl = ku = k
+    ab = np.zeros((3 * k + 1, nt), dtype=np.float64, order='F')
+
+    # upper right and lower left blocks
+    ur = np.zeros((kul, kul))
+    ll = np.zeros_like(ur)
+
+    # `offset` is made to shift all the non-zero elements to the end of the
+    # matrix
+    # NB: 1. drop the last element of `x` because `x[0] = x[-1] + T` & `y[0] == y[-1]`
+    #     2. pass ab.T to _coloc to make it C-ordered; below it'll be fed to banded
+    #        LAPACK, which needs F-ordered arrays
+    _dierckx._coloc(x[:-1], t, k, ab.T, k)
+
+    # remove zeros before the matrix
+    ab = ab[-k - (k + 1) % 2:, :]
+
+    # The least elements in rows (except repetitions) are diagonals
+    # of block matrices. Upper right matrix is an upper triangular
+    # matrix while lower left is a lower triangular one.
+    for i in range(kul):
+        ur += np.diag(ab[-i - 1, i: kul], k=i)
+        ll += np.diag(ab[i, -kul - (k % 2): n - 1 + 2 * kul - i], k=-i)
+
+    # remove elements that occur in the last point
+    # (first and last points are equivalent)
+    A = ab[:, kul: -k + kul]
+
+    for i in range(extradim):
+        cc = _woodbury_algorithm(A, ur, ll, y_new[:, i][:-1], k)
+        c[:, i] = np.concatenate((cc[-kul:], cc, cc[:kul + k % 2]))
+    c = np.ascontiguousarray(c.reshape((n + k - 1,) + y.shape[1:]))
+    t, c = xp.asarray(t), xp.asarray(c)
+    return BSpline.construct_fast(t, c, k, extrapolate='periodic', axis=axis)
+
+
+@xp_capabilities(cpu_only=True, jax_jit=False, allow_dask_compute=True)
+def make_interp_spline(x, y, k=3, t=None, bc_type=None, axis=0,
+                       check_finite=True):
+    """Create an interpolating B-spline with specified degree and boundary conditions.
+
+    Parameters
+    ----------
+    x : array_like, shape (n,)
+        Abscissas.
+    y : array_like, shape (n, ...)
+        Ordinates.
+    k : int, optional
+        B-spline degree. Default is cubic, ``k = 3``.
+    t : array_like, shape (nt + k + 1,), optional
+        Knots.
+        The number of knots needs to agree with the number of data points and
+        the number of derivatives at the edges. Specifically, ``nt - n`` must
+        equal ``len(deriv_l) + len(deriv_r)``.
+    bc_type : 2-tuple or None
+        Boundary conditions.
+        Default is None, which means choosing the boundary conditions
+        automatically. Otherwise, it must be a length-two tuple where the first
+        element (``deriv_l``) sets the boundary conditions at ``x[0]`` and
+        the second element (``deriv_r``) sets the boundary conditions at
+        ``x[-1]``. Each of these must be an iterable of pairs
+        ``(order, value)`` which gives the values of derivatives of specified
+        orders at the given edge of the interpolation interval.
+        Alternatively, the following string aliases are recognized:
+
+        * ``"clamped"``: The first derivatives at the ends are zero. This is
+          equivalent to ``bc_type=([(1, 0.0)], [(1, 0.0)])``.
+        * ``"natural"``: The second derivatives at ends are zero. This is
+          equivalent to ``bc_type=([(2, 0.0)], [(2, 0.0)])``.
+        * ``"not-a-knot"`` (default): The first and second segments are the
+          same polynomial. This is equivalent to having ``bc_type=None``.
+        * ``"periodic"``: The values and the first ``k-1`` derivatives at the
+          ends are equivalent.
+
+    axis : int, optional
+        Interpolation axis. Default is 0.
+    check_finite : bool, optional
+        Whether to check that the input arrays contain only finite numbers.
+        Disabling may give a performance gain, but may result in problems
+        (crashes, non-termination) if the inputs do contain infinities or NaNs.
+        Default is True.
+
+    Returns
+    -------
+    b : `BSpline` object
+        A `BSpline` object of the degree ``k`` and with knots ``t``.
+
+    See Also
+    --------
+    BSpline : base class representing the B-spline objects
+    CubicSpline : a cubic spline in the polynomial basis
+    make_lsq_spline : a similar factory function for spline fitting
+    UnivariateSpline : a wrapper over FITPACK spline fitting routines
+    splrep : a wrapper over FITPACK spline fitting routines
+
+    Examples
+    --------
+    Use cubic interpolation on Chebyshev nodes:
+
+    >>> import numpy as np
+    >>> import matplotlib.pyplot as plt
+    >>> def cheb_nodes(N):
+    ...     jj = 2.*np.arange(N) + 1
+    ...     x = np.cos(np.pi * jj / 2 / N)[::-1]
+    ...     return x
+
+    >>> x = cheb_nodes(20)
+    >>> y = np.sqrt(1 - x**2)
+
+    >>> from scipy.interpolate import BSpline, make_interp_spline
+    >>> b = make_interp_spline(x, y)
+    >>> np.allclose(b(x), y)
+    True
+
+    Note that the default is a cubic spline with a not-a-knot boundary condition
+
+    >>> b.k
+    3
+
+    Here we use a 'natural' spline, with zero 2nd derivatives at edges:
+
+    >>> l, r = [(2, 0.0)], [(2, 0.0)]
+    >>> b_n = make_interp_spline(x, y, bc_type=(l, r))  # or, bc_type="natural"
+    >>> np.allclose(b_n(x), y)
+    True
+    >>> x0, x1 = x[0], x[-1]
+    >>> np.allclose([b_n(x0, 2), b_n(x1, 2)], [0, 0])
+    True
+
+    Interpolation of parametric curves is also supported. As an example, we
+    compute a discretization of a snail curve in polar coordinates
+
+    >>> phi = np.linspace(0, 2.*np.pi, 40)
+    >>> r = 0.3 + np.cos(phi)
+    >>> x, y = r*np.cos(phi), r*np.sin(phi)  # convert to Cartesian coordinates
+
+    Build an interpolating curve, parameterizing it by the angle
+
+    >>> spl = make_interp_spline(phi, np.c_[x, y])
+
+    Evaluate the interpolant on a finer grid (note that we transpose the result
+    to unpack it into a pair of x- and y-arrays)
+
+    >>> phi_new = np.linspace(0, 2.*np.pi, 100)
+    >>> x_new, y_new = spl(phi_new).T
+
+    Plot the result
+
+    >>> plt.plot(x, y, 'o')
+    >>> plt.plot(x_new, y_new, '-')
+    >>> plt.show()
+
+    Build a B-spline curve with 2 dimensional y
+
+    >>> x = np.linspace(0, 2*np.pi, 10)
+    >>> y = np.array([np.sin(x), np.cos(x)])
+
+    Periodic condition is satisfied because y coordinates of points on the ends
+    are equivalent
+
+    >>> ax = plt.axes(projection='3d')
+    >>> xx = np.linspace(0, 2*np.pi, 100)
+    >>> bspl = make_interp_spline(x, y, k=5, bc_type='periodic', axis=1)
+    >>> ax.plot3D(xx, *bspl(xx))
+    >>> ax.scatter3D(x, *y, color='red')
+    >>> plt.show()
+
+    """
+    # convert string aliases for the boundary conditions
+    if bc_type is None or bc_type == 'not-a-knot' or bc_type == 'periodic':
+        deriv_l, deriv_r = None, None
+    elif isinstance(bc_type, str):
+        deriv_l, deriv_r = bc_type, bc_type
+    else:
+        try:
+            deriv_l, deriv_r = bc_type
+        except TypeError as e:
+            raise ValueError(f"Unknown boundary condition: {bc_type}") from e
+
+    xp = array_namespace(x, y, t)
+    x = _as_float_array(x, check_finite)
+    y = _as_float_array(y, check_finite)
+
+    axis = normalize_axis_index(axis, y.ndim)
+    y = np.moveaxis(y, axis, 0)    # now internally interp axis is zero
+
+    # sanity check the input
+    if bc_type == 'periodic' and not np.allclose(y[0], y[-1], atol=1e-15):
+        raise ValueError("First and last points does not match while "
+                         "periodic case expected")
+    if x.size != y.shape[0]:
+        raise ValueError(f'Shapes of x {x.shape} and y {y.shape} are incompatible')
+    if np.any(x[1:] == x[:-1]):
+        raise ValueError("Expect x to not have duplicates")
+    if x.ndim != 1 or np.any(x[1:] < x[:-1]):
+        raise ValueError("Expect x to be a 1D strictly increasing sequence.")
+
+    # special-case k=0 right away
+    if k == 0:
+        if any(_ is not None for _ in (t, deriv_l, deriv_r)):
+            raise ValueError("Too much info for k=0: t and bc_type can only "
+                             "be None.")
+        t = np.r_[x, x[-1]]
+        c = np.asarray(y)
+        c = np.ascontiguousarray(c, dtype=_get_dtype(c.dtype))
+        t, c = xp.asarray(t), xp.asarray(c)
+        return BSpline.construct_fast(t, c, k, axis=axis)
+
+    # special-case k=1 (e.g., Lyche and Morken, Eq.(2.16))
+    if k == 1 and t is None:
+        if not (deriv_l is None and deriv_r is None):
+            raise ValueError("Too much info for k=1: bc_type can only be None.")
+        t = np.r_[x[0], x, x[-1]]
+        c = np.asarray(y)
+        c = np.ascontiguousarray(c, dtype=_get_dtype(c.dtype))
+        t, c = xp.asarray(t), xp.asarray(c)
+        return BSpline.construct_fast(t, c, k, axis=axis)
+
+    k = operator.index(k)
+
+    if bc_type == 'periodic' and t is not None:
+        raise NotImplementedError("For periodic case t is constructed "
+                                  "automatically and can not be passed "
+                                  "manually")
+
+    # come up with a sensible knot vector, if needed
+    if t is None:
+        if deriv_l is None and deriv_r is None:
+            if bc_type == 'periodic':
+                t = _periodic_knots(x, k)
+            else:
+                t = _not_a_knot(x, k)
+        else:
+            t = _augknt(x, k)
+
+    t = _as_float_array(t, check_finite)
+
+    if k < 0:
+        raise ValueError("Expect non-negative k.")
+    if t.ndim != 1 or np.any(t[1:] < t[:-1]):
+        raise ValueError("Expect t to be a 1-D sorted array_like.")
+    if t.size < x.size + k + 1:
+        raise ValueError(f"Got {t.size} knots, need at least {x.size + k + 1}.")
+    if (x[0] < t[k]) or (x[-1] > t[-k]):
+        raise ValueError(f'Out of bounds w/ x = {x}.')
+
+    if bc_type == 'periodic':
+        return _make_periodic_spline(x, y, t, k, axis, xp=xp)
+
+    # Here : deriv_l, r = [(nu, value), ...]
+    deriv_l = _convert_string_aliases(deriv_l, y.shape[1:])
+    deriv_l_ords, deriv_l_vals = _process_deriv_spec(deriv_l)
+    nleft = deriv_l_ords.shape[0]
+
+    deriv_r = _convert_string_aliases(deriv_r, y.shape[1:])
+    deriv_r_ords, deriv_r_vals = _process_deriv_spec(deriv_r)
+    nright = deriv_r_ords.shape[0]
+
+    if not all(0 <= i <= k for i in deriv_l_ords):
+        raise ValueError(f"Bad boundary conditions at {x[0]}.")
+
+    if not all(0 <= i <= k for i in deriv_r_ords):
+        raise ValueError(f"Bad boundary conditions at {x[-1]}.")
+
+    # have `n` conditions for `nt` coefficients; need nt-n derivatives
+    n = x.size
+    nt = t.size - k - 1
+
+    if nt - n != nleft + nright:
+        raise ValueError("The number of derivatives at boundaries does not "
+                         f"match: expected {nt-n}, got {nleft}+{nright}")
+
+    # bail out if the `y` array is zero-sized
+    if y.size == 0:
+        c = np.zeros((nt,) + y.shape[1:], dtype=float)
+        return BSpline.construct_fast(t, c, k, axis=axis)
+
+    # set up the LHS: the colocation matrix + derivatives at boundaries
+    # NB: ab is in F order for banded LAPACK; _coloc needs C-ordered arrays,
+    #     this pass ab.T into _coloc
+    kl = ku = k
+    ab = np.zeros((2*kl + ku + 1, nt), dtype=np.float64, order='F')
+    _dierckx._coloc(x, t, k, ab.T, nleft)
+    if nleft > 0:
+        _handle_lhs_derivatives(t, k, x[0], ab, kl, ku, deriv_l_ords)
+    if nright > 0:
+        _handle_lhs_derivatives(t, k, x[-1], ab, kl, ku, deriv_r_ords,
+                                offset=nt-nright)
+
+    # set up the RHS: values to interpolate (+ derivative values, if any)
+    extradim = prod(y.shape[1:])
+    rhs = np.empty((nt, extradim), dtype=y.dtype)
+    if nleft > 0:
+        rhs[:nleft] = deriv_l_vals.reshape(-1, extradim)
+    rhs[nleft:nt - nright] = y.reshape(-1, extradim)
+    if nright > 0:
+        rhs[nt - nright:] = deriv_r_vals.reshape(-1, extradim)
+
+    # solve Ab @ x = rhs; this is the relevant part of linalg.solve_banded
+    if check_finite:
+        ab, rhs = map(np.asarray_chkfinite, (ab, rhs))
+    gbsv, = get_lapack_funcs(('gbsv',), (ab, rhs))
+    lu, piv, c, info = gbsv(kl, ku, ab, rhs,
+                            overwrite_ab=True, overwrite_b=True)
+
+    if info > 0:
+        raise LinAlgError("Colocation matrix is singular.")
+    elif info < 0:
+        raise ValueError(f'illegal value in {-info}-th argument of internal gbsv')
+    c = np.ascontiguousarray(c.reshape((nt,) + y.shape[1:]))
+    t, c = xp.asarray(t), xp.asarray(c)
+    return BSpline.construct_fast(t, c, k, axis=axis)
+
+
+@xp_capabilities(cpu_only=True, jax_jit=False, allow_dask_compute=True)
+def make_lsq_spline(x, y, t, k=3, w=None, axis=0, check_finite=True, *, method="qr"):
+    r"""Create a smoothing B-spline satisfying the Least SQuares (LSQ) criterion.
+
+    The result is a linear combination
+
+    .. math::
+
+            S(x) = \sum_j c_j B_j(x; t)
+
+    of the B-spline basis elements, :math:`B_j(x; t)`, which minimizes
+
+    .. math::
+
+        \sum_{j} \left( w_j \times (S(x_j) - y_j) \right)^2
+
+    Parameters
+    ----------
+    x : array_like, shape (m,)
+        Abscissas.
+    y : array_like, shape (m, ...)
+        Ordinates.
+    t : array_like, shape (n + k + 1,)
+        Knots.
+        Knots and data points must satisfy Schoenberg-Whitney conditions.
+    k : int, optional
+        B-spline degree. Default is cubic, ``k = 3``.
+    w : array_like, shape (m,), optional
+        Weights for spline fitting. Must be positive. If ``None``,
+        then weights are all equal.
+        Default is ``None``.
+    axis : int, optional
+        Interpolation axis. Default is zero.
+    check_finite : bool, optional
+        Whether to check that the input arrays contain only finite numbers.
+        Disabling may give a performance gain, but may result in problems
+        (crashes, non-termination) if the inputs do contain infinities or NaNs.
+        Default is True.
+    method : str, optional
+        Method for solving the linear LSQ problem. Allowed values are "norm-eq"
+        (Explicitly construct and solve the normal system of equations), and
+        "qr" (Use the QR factorization of the design matrix).
+        Default is "qr".
+
+    Returns
+    -------
+    b : `BSpline` object
+        A `BSpline` object of the degree ``k`` with knots ``t``.
+
+    See Also
+    --------
+    BSpline : base class representing the B-spline objects
+    make_interp_spline : a similar factory function for interpolating splines
+    LSQUnivariateSpline : a FITPACK-based spline fitting routine
+    splrep : a FITPACK-based fitting routine
+
+    Notes
+    -----
+    The number of data points must be larger than the spline degree ``k``.
+
+    Knots ``t`` must satisfy the Schoenberg-Whitney conditions,
+    i.e., there must be a subset of data points ``x[j]`` such that
+    ``t[j] < x[j] < t[j+k+1]``, for ``j=0, 1,...,n-k-2``.
+
+    Examples
+    --------
+    Generate some noisy data:
+
+    >>> import numpy as np
+    >>> import matplotlib.pyplot as plt
+    >>> rng = np.random.default_rng()
+    >>> x = np.linspace(-3, 3, 50)
+    >>> y = np.exp(-x**2) + 0.1 * rng.standard_normal(50)
+
+    Now fit a smoothing cubic spline with a pre-defined internal knots.
+    Here we make the knot vector (k+1)-regular by adding boundary knots:
+
+    >>> from scipy.interpolate import make_lsq_spline, BSpline
+    >>> t = [-1, 0, 1]
+    >>> k = 3
+    >>> t = np.r_[(x[0],)*(k+1),
+    ...           t,
+    ...           (x[-1],)*(k+1)]
+    >>> spl = make_lsq_spline(x, y, t, k)
+
+    For comparison, we also construct an interpolating spline for the same
+    set of data:
+
+    >>> from scipy.interpolate import make_interp_spline
+    >>> spl_i = make_interp_spline(x, y)
+
+    Plot both:
+
+    >>> xs = np.linspace(-3, 3, 100)
+    >>> plt.plot(x, y, 'ro', ms=5)
+    >>> plt.plot(xs, spl(xs), 'g-', lw=3, label='LSQ spline')
+    >>> plt.plot(xs, spl_i(xs), 'b-', lw=3, alpha=0.7, label='interp spline')
+    >>> plt.legend(loc='best')
+    >>> plt.show()
+
+    **NaN handling**: If the input arrays contain ``nan`` values, the result is
+    not useful since the underlying spline fitting routines cannot deal with
+    ``nan``. A workaround is to use zero weights for not-a-number data points:
+
+    >>> y[8] = np.nan
+    >>> w = np.isnan(y)
+    >>> y[w] = 0.
+    >>> tck = make_lsq_spline(x, y, t, w=~w)
+
+    Notice the need to replace a ``nan`` by a numerical value (precise value
+    does not matter as long as the corresponding weight is zero.)
+
+    """
+    xp = array_namespace(x, y, t, w)
+
+    x = _as_float_array(x, check_finite)
+    y = _as_float_array(y, check_finite)
+    t = _as_float_array(t, check_finite)
+    if w is not None:
+        w = _as_float_array(w, check_finite)
+    else:
+        w = np.ones_like(x)
+    k = operator.index(k)
+
+    axis = normalize_axis_index(axis, y.ndim)
+
+    y = np.moveaxis(y, axis, 0)    # now internally interp axis is zero
+    if not y.flags.c_contiguous:
+        # C routines in _dierckx currently require C contiguity
+        y = y.copy(order='C')
+
+    if x.ndim != 1:
+        raise ValueError("Expect x to be a 1-D sequence.")
+    if x.shape[0] < k+1:
+        raise ValueError("Need more x points.")
+    if k < 0:
+        raise ValueError("Expect non-negative k.")
+    if t.ndim != 1 or np.any(t[1:] - t[:-1] < 0):
+        raise ValueError("Expect t to be a 1D strictly increasing sequence.")
+    if x.size != y.shape[0]:
+        raise ValueError(f'Shapes of x {x.shape} and y {y.shape} are incompatible')
+    if k > 0 and np.any((x < t[k]) | (x > t[-k])):
+        raise ValueError(f'Out of bounds w/ x = {x}.')
+    if x.size != w.size:
+        raise ValueError(f'Shapes of x {x.shape} and w {w.shape} are incompatible')
+    if method == "norm-eq" and np.any(x[1:] - x[:-1] <= 0):
+        raise ValueError("Expect x to be a 1D strictly increasing sequence.")
+    if method == "qr" and any(x[1:] - x[:-1] < 0):
+        raise ValueError("Expect x to be a 1D non-decreasing sequence.")
+
+    # number of coefficients
+    n = t.size - k - 1
+
+    # complex y: view as float, preserve the length
+    was_complex =  y.dtype.kind == 'c'
+    yy = y.view(float)
+    if was_complex and y.ndim == 1:
+        yy = yy.reshape(y.shape[0], 2)
+
+    # multiple r.h.s
+    extradim = prod(yy.shape[1:])
+    yy = yy.reshape(-1, extradim)
+
+    # complex y: view as float, preserve the length
+    was_complex =  y.dtype.kind == 'c'
+    yy = y.view(float)
+    if was_complex and y.ndim == 1:
+        yy = yy.reshape(y.shape[0], 2)
+
+    # multiple r.h.s
+    extradim = prod(yy.shape[1:])
+    yy = yy.reshape(-1, extradim)
+
+    if method == "norm-eq":
+        # construct A.T @ A and rhs with A the colocation matrix, and
+        # rhs = A.T @ y for solving the LSQ problem  ``A.T @ A @ c = A.T @ y``
+        lower = True
+        ab = np.zeros((k+1, n), dtype=np.float64, order='F')
+        rhs = np.zeros((n, extradim), dtype=np.float64)
+        _dierckx._norm_eq_lsq(x, t, k,
+                              yy,
+                              w,
+                              ab.T, rhs)
+
+        # undo complex -> float and flattening the trailing dims
+        if was_complex:
+            rhs = rhs.view(complex)
+
+        rhs = rhs.reshape((n,) + y.shape[1:])
+
+        # have observation matrix & rhs, can solve the LSQ problem
+        cho_decomp = cholesky_banded(ab, overwrite_ab=True, lower=lower,
+                                     check_finite=check_finite)
+        m = rhs.shape[0]
+        c = cho_solve_banded((cho_decomp, lower), rhs.reshape(m, -1), overwrite_b=True,
+                             check_finite=check_finite).reshape(rhs.shape)
+    elif method == "qr":
+        _, _, c, _, _ = _lsq_solve_qr(x, yy, t, k, w)
+
+        if was_complex:
+            c = c.view(complex)
+
+    else:
+        raise ValueError(f"Unknown {method =}.")
+
+
+    # restore the shape of `c` for both single and multiple r.h.s.
+    c = c.reshape((n,) + y.shape[1:])
+    c = np.ascontiguousarray(c)
+    t, c = xp.asarray(t), xp.asarray(c)
+    return BSpline.construct_fast(t, c, k, axis=axis)
+
+
+######################
+# LSQ spline helpers #
+######################
+
+def _lsq_solve_qr_for_root_rati_periodic(x, y, t, k, w):
+    """Solve for the LSQ spline coeffs given x, y and knots.
+
+    `y` is always 2D: for 1D data, the shape is ``(m, 1)``.
+    `w` is always 1D: one weight value per `x` value.
+
+    """
+    y_w = y * w[:, None]
+    # Ref: https://github.com/scipy/scipy/blob/maintenance/1.16.x/scipy/interpolate/fitpack/fpperi.f#L221-L238
+    R, H1, H2, offset, nc = _dierckx.data_matrix_periodic(x, t, k, w, False)
+    # Ref: https://github.com/scipy/scipy/blob/maintenance/1.16.x/scipy/interpolate/fitpack/fpperi.f#L239-L314
+    A1, A2, Z, p, _ = _dierckx.qr_reduce_periodic(
+        R, H1, H2, offset, nc, y_w, k,
+        len(t), True
+    )         # modifies arguments in-place
+    # Ref: https://github.com/scipy/scipy/blob/main/scipy/interpolate/fitpack/fpbacp.f
+    c, residuals, _ = _dierckx.fpbacp(A1, A2, Z, k, k, x, y, t, w)
+    return R, A1, A2, Z, y_w, c, p, residuals
+
+
+def _lsq_solve_qr(x, y, t, k, w, periodic=False):
+    """Solve for the LSQ spline coeffs given x, y and knots.
+
+    `y` is always 2D: for 1D data, the shape is ``(m, 1)``.
+    `w` is always 1D: one weight value per `x` value.
+
+    """
+    y_w = y * w[:, None]
+    if not periodic:
+        A, offset, nc = _dierckx.data_matrix(x, t, k, w)
+        _dierckx.qr_reduce(A, offset, nc, y_w)         # modifies arguments in-place
+        c, residuals, fp = _dierckx.fpback(A, nc, x, y, t, k, w, y_w)
+        return A, y_w, c, fp, residuals
+    else:
+        # Ref: https://github.com/scipy/scipy/blob/maintenance/1.16.x/scipy/interpolate/fitpack/fpperi.f#L221-L238
+        R, H1, H2, offset, nc = _dierckx.data_matrix_periodic(x, t, k, w, False)
+        # Ref: https://github.com/scipy/scipy/blob/maintenance/1.16.x/scipy/interpolate/fitpack/fpperi.f#L239-L314
+        A1, A2, Z, fp = _dierckx.qr_reduce_periodic(
+            R, H1, H2, offset, nc, y_w, k,
+            len(t), False)         # modifies arguments in-place
+        # Ref: https://github.com/scipy/scipy/blob/main/scipy/interpolate/fitpack/fpbacp.f
+        c, residuals, _ = _dierckx.fpbacp(A1, A2, Z, k, k, x, y, t, w)
+        return R, y_w, c, fp, residuals
+
+
+
+
+#############################
+#  Smoothing spline helpers #
+#############################
+
+def _compute_optimal_gcv_parameter(X, wE, y, w):
+    """
+    Returns an optimal regularization parameter from the GCV criteria [1].
+
+    Parameters
+    ----------
+    X : array, shape (5, n)
+        5 bands of the design matrix ``X`` stored in LAPACK banded storage.
+    wE : array, shape (5, n)
+        5 bands of the penalty matrix :math:`W^{-1} E` stored in LAPACK banded
+        storage.
+    y : array, shape (n,)
+        Ordinates.
+    w : array, shape (n,)
+        Vector of weights.
+
+    Returns
+    -------
+    lam : float
+        An optimal from the GCV criteria point of view regularization
+        parameter.
+
+    Notes
+    -----
+    No checks are performed.
+
+    References
+    ----------
+    .. [1] G. Wahba, "Estimating the smoothing parameter" in Spline models
+        for observational data, Philadelphia, Pennsylvania: Society for
+        Industrial and Applied Mathematics, 1990, pp. 45-65.
+        :doi:`10.1137/1.9781611970128`
+
+    """
+
+    def compute_banded_symmetric_XT_W_Y(X, w, Y):
+        """
+        Assuming that the product :math:`X^T W Y` is symmetric and both ``X``
+        and ``Y`` are 5-banded, compute the unique bands of the product.
+
+        Parameters
+        ----------
+        X : array, shape (5, n)
+            5 bands of the matrix ``X`` stored in LAPACK banded storage.
+        w : array, shape (n,)
+            Array of weights
+        Y : array, shape (5, n)
+            5 bands of the matrix ``Y`` stored in LAPACK banded storage.
+
+        Returns
+        -------
+        res : array, shape (4, n)
+            The result of the product :math:`X^T Y` stored in the banded way.
+
+        Notes
+        -----
+        As far as the matrices ``X`` and ``Y`` are 5-banded, their product
+        :math:`X^T W Y` is 7-banded. It is also symmetric, so we can store only
+        unique diagonals.
+
+        """
+        # compute W Y
+        W_Y = np.copy(Y)
+
+        W_Y[2] *= w
+        for i in range(2):
+            W_Y[i, 2 - i:] *= w[:-2 + i]
+            W_Y[3 + i, :-1 - i] *= w[1 + i:]
+
+        n = X.shape[1]
+        res = np.zeros((4, n))
+        for i in range(n):
+            for j in range(min(n-i, 4)):
+                res[-j-1, i + j] = sum(X[j:, i] * W_Y[:5-j, i + j])
+        return res
+
+    def compute_b_inv(A):
+        """
+        Inverse 3 central bands of matrix :math:`A=U^T D^{-1} U` assuming that
+        ``U`` is a unit upper triangular banded matrix using an algorithm
+        proposed in [1].
+
+        Parameters
+        ----------
+        A : array, shape (4, n)
+            Matrix to inverse, stored in LAPACK banded storage.
+
+        Returns
+        -------
+        B : array, shape (4, n)
+            3 unique bands of the symmetric matrix that is an inverse to ``A``.
+            The first row is filled with zeros.
+
+        Notes
+        -----
+        The algorithm is based on the cholesky decomposition and, therefore,
+        in case matrix ``A`` is close to not positive defined, the function
+        raises LinalgError.
+
+        Both matrices ``A`` and ``B`` are stored in LAPACK banded storage.
+
+        References
+        ----------
+        .. [1] M. F. Hutchinson and F. R. de Hoog, "Smoothing noisy data with
+            spline functions," Numerische Mathematik, vol. 47, no. 1,
+            pp. 99-106, 1985.
+            :doi:`10.1007/BF01389878`
+
+        """
+
+        def find_b_inv_elem(i, j, U, D, B):
+            rng = min(3, n - i - 1)
+            rng_sum = 0.
+            if j == 0:
+                # use 2-nd formula from [1]
+                for k in range(1, rng + 1):
+                    rng_sum -= U[-k - 1, i + k] * B[-k - 1, i + k]
+                rng_sum += D[i]
+                B[-1, i] = rng_sum
+            else:
+                # use 1-st formula from [1]
+                for k in range(1, rng + 1):
+                    diag = abs(k - j)
+                    ind = i + min(k, j)
+                    rng_sum -= U[-k - 1, i + k] * B[-diag - 1, ind + diag]
+                B[-j - 1, i + j] = rng_sum
+
+        U = cholesky_banded(A)
+        for i in range(2, 5):
+            U[-i, i-1:] /= U[-1, :-i+1]
+        D = 1. / (U[-1])**2
+        U[-1] /= U[-1]
+
+        n = U.shape[1]
+
+        B = np.zeros(shape=(4, n))
+        for i in range(n - 1, -1, -1):
+            for j in range(min(3, n - i - 1), -1, -1):
+                find_b_inv_elem(i, j, U, D, B)
+        # the first row contains garbage and should be removed
+        B[0] = [0.] * n
+        return B
+
+    def _gcv(lam, X, XtWX, wE, XtE, y):
+        r"""
+        Computes the generalized cross-validation criteria [1].
+
+        Parameters
+        ----------
+        lam : float, (:math:`\lambda \geq 0`)
+            Regularization parameter.
+        X : array, shape (5, n)
+            Matrix is stored in LAPACK banded storage.
+        XtWX : array, shape (4, n)
+            Product :math:`X^T W X` stored in LAPACK banded storage.
+        wE : array, shape (5, n)
+            Matrix :math:`W^{-1} E` stored in LAPACK banded storage.
+        XtE : array, shape (4, n)
+            Product :math:`X^T E` stored in LAPACK banded storage.
+
+        Returns
+        -------
+        res : float
+            Value of the GCV criteria with the regularization parameter
+            :math:`\lambda`.
+
+        Notes
+        -----
+        Criteria is computed from the formula (1.3.2) [3]:
+
+        .. math::
+
+            GCV(\lambda) = \dfrac{1}{n} \sum\limits_{k = 1}^{n} \dfrac{ \left(
+            y_k - f_{\lambda}(x_k) \right)^2}{\left( 1 - \Tr{A}/n\right)^2}
+
+        The criteria is discussed in section 1.3 [3].
+
+        The numerator is computed using (2.2.4) [3] and the denominator is
+        computed using an algorithm from [2] (see in the ``compute_b_inv``
+        function).
+
+        References
+        ----------
+        .. [1] G. Wahba, "Estimating the smoothing parameter" in Spline models
+            for observational data, Philadelphia, Pennsylvania: Society for
+            Industrial and Applied Mathematics, 1990, pp. 45-65.
+            :doi:`10.1137/1.9781611970128`
+        .. [2] M. F. Hutchinson and F. R. de Hoog, "Smoothing noisy data with
+            spline functions," Numerische Mathematik, vol. 47, no. 1,
+            pp. 99-106, 1985.
+            :doi:`10.1007/BF01389878`
+        .. [3] E. Zemlyanoy, "Generalized cross-validation smoothing splines",
+            BSc thesis, 2022. Might be available (in Russian)
+            `here `_
+
+        """
+        # Compute the numerator from (2.2.4) [3]
+        n = X.shape[1]
+        c = solve_banded((2, 2), X + lam * wE, y)
+        res = np.zeros(n)
+        # compute ``W^{-1} E c`` with respect to banded-storage of ``E``
+        tmp = wE * c
+        for i in range(n):
+            for j in range(max(0, i - n + 3), min(5, i + 3)):
+                res[i] += tmp[j, i + 2 - j]
+        numer = np.linalg.norm(lam * res)**2 / n
+
+        # compute the denominator
+        lhs = XtWX + lam * XtE
+        try:
+            b_banded = compute_b_inv(lhs)
+            # compute the trace of the product b_banded @ XtX
+            tr = b_banded * XtWX
+            tr[:-1] *= 2
+            # find the denominator
+            denom = (1 - sum(sum(tr)) / n)**2
+        except LinAlgError:
+            # cholesky decomposition cannot be performed
+            raise ValueError('Seems like the problem is ill-posed')
+
+        res = numer / denom
+
+        return res
+
+    n = X.shape[1]
+
+    XtWX = compute_banded_symmetric_XT_W_Y(X, w, X)
+    XtE = compute_banded_symmetric_XT_W_Y(X, w, wE)
+
+    if y.ndim == 1:
+        gcv_est = minimize_scalar(
+            _gcv, bounds=(0, n), method='Bounded', args=(X, XtWX, wE, XtE, y)
+        )
+        if gcv_est.success:
+            return gcv_est.x
+        raise ValueError(f"Unable to find minimum of the GCV "
+                         f"function: {gcv_est.message}")
+    elif y.ndim == 2:
+        gcv_est = np.empty(y.shape[1])
+        for i in range(y.shape[1]):
+            est = minimize_scalar(
+                _gcv, bounds=(0, n), method='Bounded', args=(X, XtWX, wE, XtE, y[:, i])
+            )
+            if est.success:
+               gcv_est[i] = est.x
+            else:
+                raise ValueError(f"Unable to find minimum of the GCV "
+                                 f"function: {gcv_est.message}")
+        return gcv_est
+    else:
+        # trailing dims must have been flattened already.
+        raise RuntimeError("Internal error. Please report it to scipy developers.")
+
+
+def _coeff_of_divided_diff(x):
+    """
+    Returns the coefficients of the divided difference.
+
+    Parameters
+    ----------
+    x : array, shape (n,)
+        Array which is used for the computation of divided difference.
+
+    Returns
+    -------
+    res : array_like, shape (n,)
+        Coefficients of the divided difference.
+
+    Notes
+    -----
+    Vector ``x`` should have unique elements, otherwise an error division by
+    zero might be raised.
+
+    No checks are performed.
+
+    """
+    n = x.shape[0]
+    res = np.zeros(n)
+    for i in range(n):
+        pp = 1.
+        for k in range(n):
+            if k != i:
+                pp *= (x[i] - x[k])
+        res[i] = 1. / pp
+    return res
+
+
+@xp_capabilities(cpu_only=True, jax_jit=False, allow_dask_compute=True)
+def make_smoothing_spline(x, y, w=None, lam=None, *, axis=0):
+    r"""
+    Create a smoothing B-spline satisfying the Generalized Cross Validation (GCV) criterion.
+
+    Compute the (coefficients of) smoothing cubic spline function using
+    ``lam`` to control the tradeoff between the amount of smoothness of the
+    curve and its proximity to the data. In case ``lam`` is None, using the
+    GCV criteria [1] to find it.
+
+    A smoothing spline is found as a solution to the regularized weighted
+    linear regression problem:
+
+    .. math::
+
+        \sum\limits_{i=1}^n w_i\lvert y_i - f(x_i) \rvert^2 +
+        \lambda\int\limits_{x_1}^{x_n} (f^{(2)}(u))^2 d u
+
+    where :math:`f` is a spline function, :math:`w` is a vector of weights and
+    :math:`\lambda` is a regularization parameter.
+
+    If ``lam`` is None, we use the GCV criteria to find an optimal
+    regularization parameter, otherwise we solve the regularized weighted
+    linear regression problem with given parameter. The parameter controls
+    the tradeoff in the following way: the larger the parameter becomes, the
+    smoother the function gets.
+
+    Parameters
+    ----------
+    x : array_like, shape (n,)
+        Abscissas. `n` must be at least 5.
+    y : array_like, shape (n, ...)
+        Ordinates. `n` must be at least 5.
+    w : array_like, shape (n,), optional
+        Vector of weights. Default is ``np.ones_like(x)``.
+    lam : float, (:math:`\lambda \geq 0`), optional
+        Regularization parameter. If ``lam`` is None, then it is found from
+        the GCV criteria. Default is None.
+    axis : int, optional
+        The data axis. Default is zero.
+        The assumption is that ``y.shape[axis] == n``, and all other axes of ``y``
+        are batching axes.
+
+    Returns
+    -------
+    func : `BSpline` object
+        An object representing a spline in the B-spline basis
+        as a solution of the problem of smoothing splines using
+        the GCV criteria [1] in case ``lam`` is None, otherwise using the
+        given parameter ``lam``.
+
+    Notes
+    -----
+    This algorithm is a clean room reimplementation of the algorithm
+    introduced by Woltring in FORTRAN [2]. The original version cannot be used
+    in SciPy source code because of the license issues. The details of the
+    reimplementation are discussed here (available only in Russian) [4].
+
+    If the vector of weights ``w`` is None, we assume that all the points are
+    equal in terms of weights, and vector of weights is vector of ones.
+
+    Note that in weighted residual sum of squares, weights are not squared:
+    :math:`\sum\limits_{i=1}^n w_i\lvert y_i - f(x_i) \rvert^2` while in
+    ``splrep`` the sum is built from the squared weights.
+
+    In cases when the initial problem is ill-posed (for example, the product
+    :math:`X^T W X` where :math:`X` is a design matrix is not a positive
+    defined matrix) a ValueError is raised.
+
+    References
+    ----------
+    .. [1] G. Wahba, "Estimating the smoothing parameter" in Spline models for
+        observational data, Philadelphia, Pennsylvania: Society for Industrial
+        and Applied Mathematics, 1990, pp. 45-65.
+        :doi:`10.1137/1.9781611970128`
+    .. [2] H. J. Woltring, A Fortran package for generalized, cross-validatory
+        spline smoothing and differentiation, Advances in Engineering
+        Software, vol. 8, no. 2, pp. 104-113, 1986.
+        :doi:`10.1016/0141-1195(86)90098-7`
+    .. [3] T. Hastie, J. Friedman, and R. Tisbshirani, "Smoothing Splines" in
+        The elements of Statistical Learning: Data Mining, Inference, and
+        prediction, New York: Springer, 2017, pp. 241-249.
+        :doi:`10.1007/978-0-387-84858-7`
+    .. [4] E. Zemlyanoy, "Generalized cross-validation smoothing splines",
+        BSc thesis, 2022.
+        ``_ (in
+        Russian)
+
+    Examples
+    --------
+    Generate some noisy data
+
+    >>> import numpy as np
+    >>> np.random.seed(1234)
+    >>> n = 200
+    >>> def func(x):
+    ...    return x**3 + x**2 * np.sin(4 * x)
+    >>> x = np.sort(np.random.random_sample(n) * 4 - 2)
+    >>> y = func(x) + np.random.normal(scale=1.5, size=n)
+
+    Make a smoothing spline function
+
+    >>> from scipy.interpolate import make_smoothing_spline
+    >>> spl = make_smoothing_spline(x, y)
+
+    Plot both
+
+    >>> import matplotlib.pyplot as plt
+    >>> grid = np.linspace(x[0], x[-1], 400)
+    >>> plt.plot(x, y, '.')
+    >>> plt.plot(grid, spl(grid), label='Spline')
+    >>> plt.plot(grid, func(grid), label='Original function')
+    >>> plt.legend(loc='best')
+    >>> plt.show()
+
+    """  # noqa:E501
+    xp = array_namespace(x, y)
+
+    x = np.ascontiguousarray(x, dtype=float)
+    y = np.ascontiguousarray(y, dtype=float)
+
+    if any(x[1:] - x[:-1] <= 0):
+        raise ValueError('``x`` should be an ascending array')
+
+    if x.ndim != 1 or x.shape[0] != y.shape[axis]:
+        raise ValueError(f'``x`` should be 1D and {x.shape = } == {y.shape = }')
+
+    if w is None:
+        w = np.ones(len(x))
+    else:
+        w = np.ascontiguousarray(w)
+        if any(w <= 0):
+            raise ValueError('Invalid vector of weights')
+
+    t = np.r_[[x[0]] * 3, x, [x[-1]] * 3]
+    n = x.shape[0]
+
+    if n <= 4:
+        raise ValueError('``x`` and ``y`` length must be at least 5')
+
+    # Internals assume that the data axis is the zero-th axis
+    axis = normalize_axis_index(axis, y.ndim)
+    y = np.moveaxis(y, axis, 0)
+
+    # flatten the trailing axes of y to simplify further manipulations
+    y_shape1 = y.shape[1:]
+    if y_shape1 != ():
+        y = y.reshape((n, -1))
+
+    # It is known that the solution to the stated minimization problem exists
+    # and is a natural cubic spline with vector of knots equal to the unique
+    # elements of ``x`` [3], so we will solve the problem in the basis of
+    # natural splines.
+
+    # create design matrix in the B-spline basis
+    X_bspl = BSpline.design_matrix(x, t, 3)
+    # move from B-spline basis to the basis of natural splines using equations
+    # (2.1.7) [4]
+    # central elements
+    X = np.zeros((5, n))
+    for i in range(1, 4):
+        X[i, 2: -2] = X_bspl[i: i - 4, 3: -3][np.diag_indices(n - 4)]
+
+    # first elements
+    X[1, 1] = X_bspl[0, 0]
+    X[2, :2] = ((x[2] + x[1] - 2 * x[0]) * X_bspl[0, 0],
+                X_bspl[1, 1] + X_bspl[1, 2])
+    X[3, :2] = ((x[2] - x[0]) * X_bspl[1, 1], X_bspl[2, 2])
+
+    # last elements
+    X[1, -2:] = (X_bspl[-3, -3], (x[-1] - x[-3]) * X_bspl[-2, -2])
+    X[2, -2:] = (X_bspl[-2, -3] + X_bspl[-2, -2],
+                 (2 * x[-1] - x[-2] - x[-3]) * X_bspl[-1, -1])
+    X[3, -2] = X_bspl[-1, -1]
+
+    # create penalty matrix and divide it by vector of weights: W^{-1} E
+    wE = np.zeros((5, n))
+    wE[2:, 0] = _coeff_of_divided_diff(x[:3]) / w[:3]
+    wE[1:, 1] = _coeff_of_divided_diff(x[:4]) / w[:4]
+    for j in range(2, n - 2):
+        wE[:, j] = (x[j+2] - x[j-2]) * _coeff_of_divided_diff(x[j-2:j+3])\
+                   / w[j-2: j+3]
+
+    wE[:-1, -2] = -_coeff_of_divided_diff(x[-4:]) / w[-4:]
+    wE[:-2, -1] = _coeff_of_divided_diff(x[-3:]) / w[-3:]
+    wE *= 6
+
+    if lam is None:
+        lam = _compute_optimal_gcv_parameter(X, wE, y, w)
+    elif lam < 0.:
+        raise ValueError('Regularization parameter should be non-negative')
+
+    # solve the initial problem in the basis of natural splines
+    if np.ndim(lam) == 0:
+        c = solve_banded((2, 2), X + lam * wE, y)
+    elif np.ndim(lam) == 1:
+        # XXX: solve_banded does not suppport batched `ab` matrices; loop manually
+        c = np.empty((n, lam.shape[0]))
+        for i in range(lam.shape[0]):
+            c[:, i] = solve_banded((2, 2), X + lam[i] * wE, y[:, i])
+    else:
+        # this should not happen, ever
+        raise RuntimeError("Internal error, please report it to SciPy developers.")
+    c = c.reshape((c.shape[0], *y_shape1))
+
+    # hack: these are c[0], c[1] etc, shape-compatible with np.r_ below
+    c0, c1 = c[0:1, ...], c[1:2, ...]     # c[0], c[1]
+    cm0, cm1 = c[-1:-2:-1, ...], c[-2:-3:-1, ...]    # c[-1], c[-2]
+
+    # move back to B-spline basis using equations (2.2.10) [4]
+    c_ = np.r_[c0 * (t[5] + t[4] - 2 * t[3]) + c1,
+               c0 * (t[5] - t[3]) + c1,
+               c[1: -1, ...],
+               cm0 * (t[-4] - t[-6]) + cm1,
+               cm0 * (2 * t[-4] - t[-5] - t[-6]) + cm1]
+
+    t, c_ = xp.asarray(t), xp.asarray(c_)
+    return BSpline.construct_fast(t, c_, 3, axis=axis)
+
+
+########################
+#  FITPACK look-alikes #
+########################
+
+def fpcheck(x, t, k, periodic=False):
+    """Check consistency of data vector `x` and knot vector `t`.
+
+    Parameters
+    ----------
+    x : array_like, shape (m,)
+        1D sorted array of data points.
+    t : array_like, shape (n,)
+        1D non-decreasing knot vector.
+    k : int
+        Degree of the spline.
+    periodic : bool, optional
+        Whether the spline is periodic. Default is False.
+
+    Raises
+    ------
+    ValueError
+        If the configuration of `x`, `t`, and `k` violates any required condition.
+    """
+    # This routine is a unified clone of the FITPACK Fortran routines `fpchec.f`
+    # and `fpchep.f`:
+    # - https://github.com/scipy/scipy/blob/main/scipy/interpolate/fitpack/fpchec.f
+    # - https://github.com/scipy/scipy/blob/main/scipy/interpolate/fitpack/fpchep.f
+    #
+    # These routines verify the number and position of the knots t(j), j=1,...,n,
+    # of a spline of degree k, relative to the number and distribution of data points
+    # x(i), i=1,...,m. If all of the following conditions are fulfilled,
+    # validation passes.
+    #
+    # For non-periodic splines:
+    #   1) k+1 <= n-k-1 <= m
+    #   2) t(1) <= t(2) <= ... <= t(k+1)
+    #      t(n-k) <= t(n-k+1) <= ... <= t(n)
+    #   3) t(k+1) < t(k+2) < ... < t(n-k)
+    #   4) t(k+1) <= x(i) <= t(n-k)
+    #   5) Schoenberg-Whitney conditions hold: there exists a subset y(j) such that
+    #        t(j) < y(j) < t(j+k+1), for j = 1, ..., n-k-1
+    #
+    # For periodic splines:
+    #   1) k+1 <= n-k-1 <= m + k - 1
+    #   2) Same boundary knot monotonicity as above
+    #   3) Same strict interior knot increase as above
+    #   4) t(k+1) <= x(i) <= t(n-k)
+    #   5) Schoenberg-Whitney conditions must hold for *some periodic shift*
+    #        of the data sequence; i.e. wrapped data points x(i) must satisfy
+    #        t(j) < y(j) < t(j+k+1), j = k+1, ..., n-k-1
+    x = np.asarray(x)
+    t = np.asarray(t)
+
+    if x.ndim != 1 or t.ndim != 1:
+        raise ValueError(f"Expect `x` and `t` be 1D sequences. Got {x = } and {t = }")
+
+    m = x.shape[0]
+    n = t.shape[0]
+    nk1 = n - k - 1
+
+    # check condition no 1
+    if periodic:
+        # c      1) k+1 <= nk1 <= m+k-1
+        if not (k + 1 <= nk1 <= m + k - 1):
+            raise ValueError(f"Need k+1 <= n-k-1 <= m+k-1. Got {m = }, {n = }, {k = }")
+    else:
+        # c      1) k+1 <= n-k-1 <= m
+        if not (k + 1 <= nk1 <= m):
+            raise ValueError(f"Need k+1 <= n-k-1 <= m. Got {m = }, {n = } and {k = }.")
+
+    # check condition no 2
+    # c      2) t(1) <= t(2) <= ... <= t(k+1)
+    # c         t(n-k) <= t(n-k+1) <= ... <= t(n)
+    if (t[:k+1] > t[1:k+2]).any():
+        raise ValueError(f"First k knots must be ordered; got {t = }.")
+
+    if (t[nk1:] < t[nk1-1:-1]).any():
+        raise ValueError(f"Last k knots must be ordered; got {t = }.")
+
+    # c  check condition no 3
+    # c      3) t(k+1) < t(k+2) < ... < t(n-k)
+    if (t[k+1:n-k] <= t[k:n-k-1]).any():
+        raise ValueError(f"Internal knots must be distinct. Got {t = }.")
+
+    # c  check condition no 4
+    # c      4) t(k+1) <= x(i) <= t(n-k)
+    # NB: FITPACK's fpchec only checks x[0] & x[-1], so we follow.
+    if (x[0] < t[k]) or (x[-1] > t[n-k-1]):
+        raise ValueError(f"Out of bounds: {x = } and {t = }.")
+
+    # c  check condition no 5
+    # c      5) the conditions specified by Schoenberg and Whitney must hold
+    # c         for at least one subset of data points y(j) such that
+    # c             t(j) < y(j) < t(j+k+1)
+    # c
+    # c         For non-periodic splines:
+    # c             j = 1, 2, ..., n-k-1 (i.e., j in [1, n-k-1])
+    # c             The data points must lie strictly inside some B-spline supports.
+    # c
+    # c         For periodic splines:
+    # c             j = k+1, ..., n-k-1
+    # c             The condition must hold for a wrapped subset of the data points,
+    # c             i.e., there exists a cyclic shift of the data such that
+    # c                 t(j) < x(i) < t(j+k+1)
+    # c             holds for all j in that range. The test must account for the
+    # c             periodic domain length: per = t(n-k) - t(k+1), and wrap around x(i)
+    # c             as x(i) + per if needed.
+    mesg = f"Schoenberg-Whitney condition is violated with {t = } and {x =}."
+
+    if periodic:
+        per = t[n - k - 1] - t[k]
+        m1 = m - 1
+        for shift in range(1, m):
+            for j in range(k, nk1):
+                tj = t[j]
+                tl = t[j + k + 1]
+                found = False
+                for i in range(shift, shift + m1 + 1):
+                    idx = i if i < m else i - m
+                    xi = x[idx] + (0 if i < m else per)
+                    if tj < xi < tl:
+                        found = True
+                        break
+                if not found:
+                    break
+            else:
+                return
+        raise ValueError(mesg)
+    else:
+        if (x[0] >= t[k+1]) or (x[-1] <= t[n-k-2]):
+            raise ValueError(mesg)
+
+        m = x.shape[0]
+        l = k+1
+        nk3 = n - k - 3
+        if nk3 < 2:
+            return
+        for j in range(1, nk3+1):
+            tj = t[j]
+            l += 1
+            tl = t[l]
+            i = np.argmax(x > tj)
+            if i >= m-1:
+                raise ValueError(mesg)
+            if x[i] >= tl:
+                raise ValueError(mesg)
+        return
diff --git a/.venv/lib/python3.12/site-packages/scipy/interpolate/_cubic.py b/.venv/lib/python3.12/site-packages/scipy/interpolate/_cubic.py
new file mode 100644
index 0000000000000000000000000000000000000000..c80cff7217c3f09eaced3690e4c549fbd1066720
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/interpolate/_cubic.py
@@ -0,0 +1,1034 @@
+"""Interpolation algorithms using piecewise cubic polynomials."""
+
+from typing import Literal
+
+import numpy as np
+
+from scipy.linalg import solve, solve_banded
+from scipy._lib._array_api import array_namespace, xp_size, xp_capabilities
+from scipy._external.array_api_compat import numpy as np_compat
+
+from . import PPoly
+from ._polyint import _isscalar
+
+__all__ = ["CubicHermiteSpline", "PchipInterpolator", "pchip_interpolate",
+           "Akima1DInterpolator", "CubicSpline"]
+
+
+def prepare_input(x, y, axis, dydx=None, xp=None):
+    """Prepare input for cubic spline interpolators.
+
+    All data are converted to numpy arrays and checked for correctness.
+    Axes equal to `axis` of arrays `y` and `dydx` are moved to be the 0th
+    axis. The value of `axis` is converted to lie in
+    [0, number of dimensions of `y`).
+    """
+
+    x, y = map(xp.asarray, (x, y))
+    if xp.isdtype(x.dtype, "complex floating"):
+        raise ValueError("`x` must contain real values.")
+    x = xp.astype(x, xp.float64)
+
+    if xp.isdtype(y.dtype, "complex floating"):
+        dtype = xp.complex128
+    else:
+        dtype = xp.float64
+
+    if dydx is not None:
+        dydx = xp.asarray(dydx)
+        if y.shape != dydx.shape:
+            raise ValueError("The shapes of `y` and `dydx` must be identical.")
+        if xp.isdtype(dydx.dtype, "complex floating"):
+            dtype = xp.complex128
+        dydx = xp.astype(dydx, dtype, copy=False)
+
+    y = xp.astype(y, dtype, copy=False)
+    axis = axis % y.ndim
+    if x.ndim != 1:
+        raise ValueError("`x` must be 1-dimensional.")
+    if x.shape[0] < 2:
+        raise ValueError("`x` must contain at least 2 elements.")
+    if x.shape[0] != y.shape[axis]:
+        raise ValueError(f"The length of `y` along `axis`={axis} doesn't "
+                         "match the length of `x`")
+
+    if not xp.all(xp.isfinite(x)):
+        raise ValueError("`x` must contain only finite values.")
+    if not xp.all(xp.isfinite(y)):
+        raise ValueError("`y` must contain only finite values.")
+
+    if dydx is not None and not xp.all(xp.isfinite(dydx)):
+        raise ValueError("`dydx` must contain only finite values.")
+
+    dx = xp.diff(x)
+    if xp.any(dx <= 0):
+        raise ValueError("`x` must be strictly increasing sequence.")
+
+    y = xp.moveaxis(y, axis, 0)
+    if dydx is not None:
+        dydx = xp.moveaxis(dydx, axis, 0)
+
+    return x, dx, y, axis, dydx
+
+
+@xp_capabilities(
+    cpu_only=True, jax_jit=False,
+    skip_backends=[
+        ("dask.array",
+         "https://github.com/data-apis/array-api-extra/issues/488")
+    ]
+)
+class CubicHermiteSpline(PPoly):
+    """Piecewise cubic interpolator to fit values and first derivatives (C1 smooth).
+
+    The result is represented as a `PPoly` instance.
+
+    Parameters
+    ----------
+    x : array_like, shape (n,)
+        1-D array containing values of the independent variable.
+        Values must be real, finite and in strictly increasing order.
+    y : array_like
+        Array containing values of the dependent variable. It can have
+        arbitrary number of dimensions, but the length along ``axis``
+        (see below) must match the length of ``x``. Values must be finite.
+    dydx : array_like
+        Array containing derivatives of the dependent variable. It can have
+        arbitrary number of dimensions, but the length along ``axis``
+        (see below) must match the length of ``x``. Values must be finite.
+    axis : int, optional
+        Axis along which `y` is assumed to be varying. Meaning that for
+        ``x[i]`` the corresponding values are ``np.take(y, i, axis=axis)``.
+        Default is 0.
+    extrapolate : {bool, 'periodic', None}, optional
+        If bool, determines whether to extrapolate to out-of-bounds points
+        based on first and last intervals, or to return NaNs. If 'periodic',
+        periodic extrapolation is used. If None (default), it is set to True.
+        See :ref:`tutorial-interpolate_out_of_bounds`.
+
+    Attributes
+    ----------
+    x : ndarray, shape (n,)
+        Breakpoints. The same ``x`` which was passed to the constructor.
+    c : ndarray, shape (4, n-1, ...)
+        Coefficients of the polynomials on each segment. The trailing
+        dimensions match the dimensions of `y`, excluding ``axis``.
+        For example, if `y` is 1-D, then ``c[k, i]`` is a coefficient for
+        ``(x-x[i])**(3-k)`` on the segment between ``x[i]`` and ``x[i+1]``.
+    axis : int
+        Interpolation axis. The same axis which was passed to the
+        constructor.
+
+    Methods
+    -------
+    __call__
+    derivative
+    antiderivative
+    integrate
+    solve
+    roots
+
+    See Also
+    --------
+    Akima1DInterpolator : Akima 1D interpolator.
+    PchipInterpolator : PCHIP 1-D monotonic cubic interpolator.
+    CubicSpline : Cubic spline data interpolator.
+    PPoly : Piecewise polynomial in terms of coefficients and breakpoints
+
+    Notes
+    -----
+    If you want to create a higher-order spline matching higher-order
+    derivatives, use `BPoly.from_derivatives`.
+
+    References
+    ----------
+    .. [1] `Cubic Hermite spline
+            `_
+            on Wikipedia.
+    """
+
+    def __init__(self, x, y, dydx, axis=0, extrapolate=None):
+        xp = array_namespace(x, y, dydx)
+
+        if extrapolate is None:
+            extrapolate = True
+
+        x, dx, y, axis, dydx = prepare_input(x, y, axis, dydx, xp=xp)
+
+        dxr = xp.reshape(dx, (dx.shape[0], ) + (1, ) * (y.ndim - 1))
+        slope = xp.diff(y, axis=0) / dxr
+        t = (dydx[:-1, ...] + dydx[1:, ...] - 2 * slope) / dxr
+
+        c = xp.stack((
+           t / dxr,
+           (slope - dydx[:-1, ...]) / dxr - t,
+           dydx[:-1, ...],
+           y[:-1, ...]
+        ))
+
+        super().__init__(c, x, extrapolate=extrapolate)
+        self.axis = axis
+
+
+# The commented out xp_capabilities below are probably right but since
+# this is untested, mark as np_only. TODO: convert the tests.
+#
+# @xp_capabilities(
+#     cpu_only=True, jax_jit=False,
+#     skip_backends=[
+#         ("dask.array",
+#          "https://github.com/data-apis/array-api-extra/issues/488")
+#     ]
+# )
+@xp_capabilities(np_only=True, reason="not tested")
+class PchipInterpolator(CubicHermiteSpline):
+    r"""PCHIP shape-preserving interpolator (C1 smooth).
+
+    ``x`` and ``y`` are arrays of values used to approximate some function f,
+    with ``y = f(x)``. The interpolant uses monotonic cubic splines
+    to find the value of new points. (PCHIP stands for Piecewise Cubic
+    Hermite Interpolating Polynomial).
+
+    Parameters
+    ----------
+    x : ndarray, shape (npoints, )
+        A 1-D array of monotonically increasing real values. ``x`` cannot
+        include duplicate values (otherwise f is overspecified)
+    y : ndarray, shape (..., npoints, ...)
+        An N-D array of real values. ``y``'s length along the interpolation
+        axis must be equal to the length of ``x``. Use the ``axis``
+        parameter to select the interpolation axis.
+    axis : int, optional
+        Axis in the ``y`` array corresponding to the x-coordinate values. Defaults
+        to ``axis=0``.
+    extrapolate : {bool, 'periodic', None}, optional
+        If bool, determines whether to extrapolate to out-of-bounds points
+        based on first and last intervals, or to return NaNs. If 'periodic',
+        periodic extrapolation is used. If None (default), it is set to True.
+        See :ref:`tutorial-interpolate_out_of_bounds`.
+
+    Methods
+    -------
+    __call__
+    derivative
+    antiderivative
+    integrate
+    solve
+    roots
+
+
+    See Also
+    --------
+    CubicHermiteSpline : Piecewise-cubic interpolator.
+    Akima1DInterpolator : Akima 1D interpolator.
+    CubicSpline : Cubic spline data interpolator.
+    PPoly : Piecewise polynomial in terms of coefficients and breakpoints.
+
+    Notes
+    -----
+    The interpolator preserves monotonicity in the interpolation data and does
+    not overshoot if the data is not smooth.
+
+    The first derivatives are guaranteed to be continuous, but the second
+    derivatives may jump at :math:`x_k`.
+
+    Determines the derivatives at the points :math:`x_k`, :math:`f'_k`,
+    by using PCHIP algorithm [1]_.
+
+    Let :math:`h_k = x_{k+1} - x_k`, and  :math:`d_k = (y_{k+1} - y_k) / h_k`
+    are the slopes at internal points :math:`x_k`.
+    If the signs of :math:`d_k` and :math:`d_{k-1}` are different or either of
+    them equals zero, then :math:`f'_k = 0`. Otherwise, it is given by the
+    weighted harmonic mean
+
+    .. math::
+
+        \frac{w_1 + w_2}{f'_k} = \frac{w_1}{d_{k-1}} + \frac{w_2}{d_k}
+
+    where :math:`w_1 = 2 h_k + h_{k-1}` and :math:`w_2 = h_k + 2 h_{k-1}`.
+
+    The end slopes are set using a one-sided scheme [2]_.
+
+
+    References
+    ----------
+    .. [1] F. N. Fritsch and J. Butland,
+           A method for constructing local
+           monotone piecewise cubic interpolants,
+           SIAM J. Sci. Comput., 5(2), 300-304 (1984).
+           :doi:`10.1137/0905021`.
+    .. [2] C. Moler, Numerical Computing with Matlab, 2004.
+           :doi:`10.1137/1.9780898717952`
+
+    """
+
+    def __init__(self, x, y, axis=0, extrapolate=None):
+        xp = array_namespace(x, y)
+        x, _, y, axis, _ = prepare_input(x, y, axis, xp=xp)
+        if xp.isdtype(y.dtype, "complex floating"):
+            msg = ("`PchipInterpolator` only works with real values for `y`. "
+                   "If you are trying to use the real components of the passed array, "
+                   "use `np.real` on the array before passing to `PchipInterpolator`.")
+            raise ValueError(msg)
+        xv = xp.reshape(x, (x.shape[0],) + (1,)*(y.ndim-1))
+        dk = self._find_derivatives(xv, y, xp=xp)
+        super().__init__(x, y, dk, axis=0, extrapolate=extrapolate)
+        self.axis = axis
+
+    @staticmethod
+    def _edge_case(h0, h1, m0, m1, xp):
+        # one-sided three-point estimate for the derivative
+        d = ((2*h0 + h1)*m0 - h0*m1) / (h0 + h1)
+
+        # try to preserve shape
+        mask = xp.sign(d) != xp.sign(m0)
+        mask2 = (xp.sign(m0) != xp.sign(m1)) & (xp.abs(d) > 3.*xp.abs(m0))
+        mmm = (~mask) & mask2
+
+        d[mask] = 0.
+        d[mmm] = 3.*m0[mmm]
+
+        return d
+
+    @staticmethod
+    def _find_derivatives(x, y, xp):
+        # Determine the derivatives at the points y_k, d_k, by using
+        #  PCHIP algorithm is:
+        # We choose the derivatives at the point x_k by
+        # Let m_k be the slope of the kth segment (between k and k+1)
+        # If m_k=0 or m_{k-1}=0 or sgn(m_k) != sgn(m_{k-1}) then d_k == 0
+        # else use weighted harmonic mean:
+        #   w_1 = 2h_k + h_{k-1}, w_2 = h_k + 2h_{k-1}
+        #   1/d_k = 1/(w_1 + w_2)*(w_1 / m_k + w_2 / m_{k-1})
+        #   where h_k is the spacing between x_k and x_{k+1}
+        y_shape = y.shape
+        if y.ndim == 1:
+            # So that _edge_case doesn't end up assigning to scalars
+            x = x[:, None]
+            y = y[:, None]
+
+        hk = x[1:] - x[:-1]
+        mk = (y[1:] - y[:-1]) / hk
+
+        if y.shape[0] == 2:
+            # edge case: only have two points, use linear interpolation
+            dk = xp.zeros_like(y)
+            dk[0] = mk
+            dk[1] = mk
+            return xp.reshape(dk, y_shape)
+
+        smk = xp.sign(mk)
+        condition = (smk[1:] != smk[:-1]) | (mk[1:] == 0) | (mk[:-1] == 0)
+
+        w1 = 2*hk[1:] + hk[:-1]
+        w2 = hk[1:] + 2*hk[:-1]
+
+        # values where division by zero occurs will be excluded
+        # by 'condition' afterwards
+        with np.errstate(divide='ignore', invalid='ignore'):
+            whmean = (w1/mk[:-1] + w2/mk[1:]) / (w1 + w2)
+
+        dk = np.zeros_like(y)
+        dk[1:-1][condition] = 0.0
+        dk[1:-1][~condition] = 1.0 / whmean[~condition]
+
+        # special case endpoints, as suggested in
+        # Cleve Moler, Numerical Computing with MATLAB, Chap 3.6 (pchiptx.m)
+        dk[0] = PchipInterpolator._edge_case(hk[0], hk[1], mk[0], mk[1], xp=xp)
+        dk[-1] = PchipInterpolator._edge_case(hk[-1], hk[-2], mk[-1], mk[-2], xp=xp)
+
+        return xp.reshape(dk, y_shape)
+
+
+def pchip_interpolate(xi, yi, x, der=0, axis=0):
+    """
+    Convenience function for pchip interpolation.
+
+    xi and yi are arrays of values used to approximate some function f,
+    with ``yi = f(xi)``. The interpolant uses monotonic cubic splines
+    to find the value of new points x and the derivatives there.
+
+    See `scipy.interpolate.PchipInterpolator` for details.
+
+    Parameters
+    ----------
+    xi : array_like
+        A sorted list of x-coordinates, of length N.
+    yi : array_like
+        A 1-D array of real values. `yi`'s length along the interpolation
+        axis must be equal to the length of `xi`. If N-D array, use axis
+        parameter to select correct axis.
+    x : scalar or array_like
+        Of length M.
+    der : int or list, optional
+        Derivatives to extract. The 0th derivative can be included to
+        return the function value.
+    axis : int, optional
+        Axis in the yi array corresponding to the x-coordinate values.
+
+    Returns
+    -------
+    y : scalar or array_like
+        The result, of length R or length M or M by R.
+
+    See Also
+    --------
+    PchipInterpolator : PCHIP 1-D monotonic cubic interpolator.
+
+    Examples
+    --------
+    We can interpolate 2D observed data using pchip interpolation:
+
+    >>> import numpy as np
+    >>> import matplotlib.pyplot as plt
+    >>> from scipy.interpolate import pchip_interpolate
+    >>> x_observed = np.linspace(0.0, 10.0, 11)
+    >>> y_observed = np.sin(x_observed)
+    >>> x = np.linspace(min(x_observed), max(x_observed), num=100)
+    >>> y = pchip_interpolate(x_observed, y_observed, x)
+    >>> plt.plot(x_observed, y_observed, "o", label="observation")
+    >>> plt.plot(x, y, label="pchip interpolation")
+    >>> plt.legend()
+    >>> plt.show()
+
+    """
+    P = PchipInterpolator(xi, yi, axis=axis)
+
+    if der == 0:
+        return P(x)
+    elif _isscalar(der):
+        return P.derivative(der)(x)
+    else:
+        return [P.derivative(nu)(x) for nu in der]
+
+
+@xp_capabilities(cpu_only=True, xfail_backends=[
+    ("dask.array", "lacks nd fancy indexing"),
+    ("jax.numpy", "immutable arrays"),
+    ("array_api_strict", "fancy indexing __setitem__"),
+])
+class Akima1DInterpolator(CubicHermiteSpline):
+    r"""Akima "visually pleasing" interpolator (C1 smooth).
+
+    Fit piecewise cubic polynomials, given vectors x and y. The interpolation
+    method by Akima uses a continuously differentiable sub-spline built from
+    piecewise cubic polynomials. The resultant curve passes through the given
+    data points and will appear smooth and natural.
+
+    Parameters
+    ----------
+    x : ndarray, shape (npoints, )
+        1-D array of monotonically increasing real values.
+    y : ndarray, shape (..., npoints, ...)
+        N-D array of real values. The length of ``y`` along the interpolation axis
+        must be equal to the length of ``x``. Use the ``axis`` parameter to
+        select the interpolation axis.
+    axis : int, optional
+        Axis in the ``y`` array corresponding to the x-coordinate values. Defaults
+        to ``axis=0``.
+    method : {'akima', 'makima'}, optional
+        If ``"makima"``, use the modified Akima interpolation [2]_.
+        Defaults to ``"akima"``, use the Akima interpolation [1]_.
+
+        .. versionadded:: 1.13.0
+
+    extrapolate : {bool, 'periodic', None}, optional
+        If bool, determines whether to extrapolate to out-of-bounds points
+        based on first and last intervals, or to return NaNs. If 'periodic',
+        periodic extrapolation is used. If None (default), it is set to False.
+        See :ref:`tutorial-interpolate_out_of_bounds`.
+
+    Methods
+    -------
+    __call__
+    derivative
+    antiderivative
+    integrate
+    solve
+    roots
+
+    See Also
+    --------
+    PchipInterpolator : PCHIP 1-D monotonic cubic interpolator.
+    CubicSpline : Cubic spline data interpolator.
+    PPoly : Piecewise polynomial in terms of coefficients and breakpoints
+
+    Notes
+    -----
+    .. versionadded:: 0.14
+
+    Use only for precise data, as the fitted curve passes through the given
+    points exactly. This routine is useful for plotting a pleasingly smooth
+    curve through a few given points for purposes of plotting.
+
+    Let :math:`\delta_i = (y_{i+1} - y_i) / (x_{i+1} - x_i)` be the slopes of
+    the interval :math:`\left[x_i, x_{i+1}\right)`. Akima's derivative at
+    :math:`x_i` is defined as:
+
+    .. math::
+
+        d_i = \frac{w_1}{w_1 + w_2}\delta_{i-1} + \frac{w_2}{w_1 + w_2}\delta_i
+
+    In the Akima interpolation [1]_ (``method="akima"``), the weights are:
+
+    .. math::
+
+        \begin{aligned}
+        w_1 &= |\delta_{i+1} - \delta_i| \\
+        w_2 &= |\delta_{i-1} - \delta_{i-2}|
+        \end{aligned}
+
+    In the modified Akima interpolation [2]_ (``method="makima"``),
+    to eliminate overshoot and avoid edge cases of both numerator and
+    denominator being equal to 0, the weights are modified as follows:
+
+    .. math::
+
+        \begin{align*}
+        w_1 &= |\delta_{i+1} - \delta_i| + |\delta_{i+1} + \delta_i| / 2 \\
+        w_2 &= |\delta_{i-1} - \delta_{i-2}| + |\delta_{i-1} + \delta_{i-2}| / 2
+        \end{align*}
+
+    Examples
+    --------
+    Comparison of ``method="akima"`` and ``method="makima"``:
+
+    >>> import numpy as np
+    >>> from scipy.interpolate import Akima1DInterpolator
+    >>> import matplotlib.pyplot as plt
+    >>> x = np.linspace(1, 7, 7)
+    >>> y = np.array([-1, -1, -1, 0, 1, 1, 1])
+    >>> xs = np.linspace(min(x), max(x), num=100)
+    >>> y_akima = Akima1DInterpolator(x, y, method="akima")(xs)
+    >>> y_makima = Akima1DInterpolator(x, y, method="makima")(xs)
+
+    >>> fig, ax = plt.subplots()
+    >>> ax.plot(x, y, "o", label="data")
+    >>> ax.plot(xs, y_akima, label="akima")
+    >>> ax.plot(xs, y_makima, label="makima")
+    >>> ax.legend()
+    >>> fig.show()
+
+    The overshoot that occurred in ``"akima"`` has been avoided in ``"makima"``.
+
+    References
+    ----------
+    .. [1] A new method of interpolation and smooth curve fitting based
+           on local procedures. Hiroshi Akima, J. ACM, October 1970, 17(4),
+           589-602. :doi:`10.1145/321607.321609`
+    .. [2] Makima Piecewise Cubic Interpolation. Cleve Moler and Cosmin Ionita, 2019.
+           https://blogs.mathworks.com/cleve/2019/04/29/makima-piecewise-cubic-interpolation/
+
+    """
+
+    def __init__(self, x, y, axis=0, *, method: Literal["akima", "makima"]="akima",
+                 extrapolate:bool | None = None):
+        if method not in {"akima", "makima"}:
+            raise NotImplementedError(f"`method`={method} is unsupported.")
+        # Original implementation in MATLAB by N. Shamsundar (BSD licensed), see
+        # https://www.mathworks.com/matlabcentral/fileexchange/1814-akima-interpolation
+
+        xp = array_namespace(x, y)
+        x, dx, y, axis, _ = prepare_input(x, y, axis, xp=xp)
+
+        if xp.isdtype(y.dtype, "complex floating"):
+            msg = ("`Akima1DInterpolator` only works with real values for `y`. "
+                   "If you are trying to use the real components of the passed array, "
+                   "use `np.real` on the array before passing to "
+                   "`Akima1DInterpolator`.")
+            raise ValueError(msg)
+
+        # Akima extrapolation historically False; parent class defaults to True.
+        extrapolate = False if extrapolate is None else extrapolate
+
+        if y.shape[0] == 2:
+            # edge case: only have two points, use linear interpolation
+            xv = xp.reshape(x, (x.shape[0],) + (1,)*(y.ndim-1))
+            hk = xv[1:, ...] - xv[:-1, ...]
+            mk = (y[1:, ...] - y[:-1, ...]) / hk
+            t = xp.zeros_like(y)
+            t[...] = mk
+        else:
+            # determine slopes between breakpoints
+            m = xp.empty((x.shape[0] + 3, ) + y.shape[1:])
+            dx = dx[(slice(None), ) + (None, ) * (y.ndim - 1)]
+            m[2:-2, ...] = xp.diff(y, axis=0) / dx
+
+            # add two additional points on the left ...
+            m[1, ...] = 2. * m[2, ...] - m[3, ...]
+            m[0, ...] = 2. * m[1, ...] - m[2, ...]
+            # ... and on the right
+            m[-2, ...] = 2. * m[-3, ...] - m[-4, ...]
+            m[-1, ...] = 2. * m[-2, ...] - m[-3, ...]
+
+            # if m1 == m2 != m3 == m4, the slope at the breakpoint is not
+            # defined. This is the fill value:
+            t = .5 * (m[3:, ...] + m[:-3, ...])
+            # get the denominator of the slope t
+            dm = xp.abs(xp.diff(m, axis=0))
+            if method == "makima":
+                pm = xp.abs(m[1:, ...] + m[:-1, ...])
+                f1 = dm[2:, ...] + 0.5 * pm[2:, ...]
+                f2 = dm[:-2, ...] + 0.5 * pm[:-2, ...]
+            else:
+                f1 = dm[2:, ...]
+                f2 = dm[:-2, ...]
+
+            # makima is more numerically stable for small f12,
+            # so a finite cutoff should not improve any behavior
+            # however, akima has a qualitative discontinuity near f12=0
+            # a finite cutoff moves it, but cannot remove it.
+            # the cutoff break_mult could be made a keyword argument
+            # method='akima' also benefits from a check for m2=m3
+            break_mult = 1.e-9
+
+            f12 = f1 + f2
+
+            # These are the mask of where the slope at breakpoint is defined:
+            mmax = xp.max(f12) if xp_size(f12) > 0 else -xp.inf
+            ind = xp.nonzero(f12 > break_mult * mmax)
+
+            x_ind, y_ind = ind[0], ind[1:]
+            # Set the slope at breakpoint
+            t[ind] = m[(x_ind + 1,) + y_ind] + (
+                (f2[ind] / f12[ind])
+                * (m[(x_ind + 2,) + y_ind] - m[(x_ind + 1,) + y_ind])
+            )
+
+        super().__init__(x, y, t, axis=0, extrapolate=extrapolate)
+        self.axis = axis
+
+    def extend(self, c, x, right=True):
+        """Extending a 1-D Akima interpolator is not yet implemented."""
+        # numpydoc ignore=PR01
+        raise NotImplementedError("Extending a 1-D Akima interpolator is not "
+                                  "yet implemented")
+
+    # These are inherited from PPoly, but they do not produce an Akima
+    # interpolator. Hence stub them out.
+    @classmethod
+    def from_spline(cls, tck, extrapolate=None):
+        raise NotImplementedError("This method does not make sense for "
+                                  "an Akima interpolator.")
+
+    @classmethod
+    def from_bernstein_basis(cls, bp, extrapolate=None):
+        raise NotImplementedError("This method does not make sense for "
+                                  "an Akima interpolator.")
+
+
+@xp_capabilities(
+    cpu_only=True, jax_jit=False,
+    skip_backends=[
+        ("dask.array",
+         "https://github.com/data-apis/array-api-extra/issues/488")
+    ]
+)
+class CubicSpline(CubicHermiteSpline):
+    """Piecewise cubic interpolator to fit values (C2 smooth).
+
+    Interpolate data with a piecewise cubic polynomial which is twice
+    continuously differentiable [1]_. The result is represented as a `PPoly`
+    instance with breakpoints matching the given data.
+
+    Parameters
+    ----------
+    x : array_like, shape (n,)
+        1-D array containing values of the independent variable.
+        Values must be real, finite and in strictly increasing order.
+    y : array_like
+        Array containing values of the dependent variable. It can have
+        arbitrary number of dimensions, but the length along ``axis``
+        (see below) must match the length of ``x``. Values must be finite.
+    axis : int, optional
+        Axis along which `y` is assumed to be varying. Meaning that for
+        ``x[i]`` the corresponding values are ``np.take(y, i, axis=axis)``.
+        Default is 0.
+    bc_type : str or 2-tuple, optional
+        Boundary condition type. Two additional equations, given by the
+        boundary conditions, are required to determine all coefficients of
+        polynomials on each segment [2]_.
+
+        If `bc_type` is a string, then the specified condition will be applied
+        at both ends of a spline. Available conditions are:
+
+        * 'not-a-knot' (default): The first and second segment at a curve end
+          are the same polynomial. It is a good default when there is no
+          information on boundary conditions.
+        * 'periodic': The interpolated functions is assumed to be periodic
+          of period ``x[-1] - x[0]``. The first and last value of `y` must be
+          identical: ``y[0] == y[-1]``. This boundary condition will result in
+          ``y'[0] == y'[-1]`` and ``y''[0] == y''[-1]``.
+        * 'clamped': The first derivative at curves ends are zero. Assuming
+          a 1D `y`, ``bc_type=((1, 0.0), (1, 0.0))`` is the same condition.
+        * 'natural': The second derivative at curve ends are zero. Assuming
+          a 1D `y`, ``bc_type=((2, 0.0), (2, 0.0))`` is the same condition.
+
+        If `bc_type` is a 2-tuple, the first and the second value will be
+        applied at the curve start and end respectively. The tuple values can
+        be one of the previously mentioned strings (except 'periodic') or a
+        tuple ``(order, deriv_values)`` allowing to specify arbitrary
+        derivatives at curve ends:
+
+        * `order`: the derivative order, 1 or 2.
+        * `deriv_value`: array_like containing derivative values, shape must
+          be the same as `y`, excluding ``axis`` dimension. For example, if
+          `y` is 1-D, then `deriv_value` must be a scalar. If `y` is 3-D with
+          the shape (n0, n1, n2) and axis=2, then `deriv_value` must be 2-D
+          and have the shape (n0, n1).
+    extrapolate : {bool, 'periodic', None}, optional
+        If bool, determines whether to extrapolate to out-of-bounds points
+        based on first and last intervals, or to return NaNs. If 'periodic',
+        periodic extrapolation is used. If None (default), ``extrapolate`` is
+        set to 'periodic' for ``bc_type='periodic'`` and to True otherwise.
+        See :ref:`tutorial-interpolate_out_of_bounds`.
+
+    Attributes
+    ----------
+    x : ndarray, shape (n,)
+        Breakpoints. The same ``x`` which was passed to the constructor.
+    c : ndarray, shape (4, n-1, ...)
+        Coefficients of the polynomials on each segment. The trailing
+        dimensions match the dimensions of `y`, excluding ``axis``.
+        For example, if `y` is 1-d, then ``c[k, i]`` is a coefficient for
+        ``(x-x[i])**(3-k)`` on the segment between ``x[i]`` and ``x[i+1]``.
+    axis : int
+        Interpolation axis. The same axis which was passed to the
+        constructor.
+
+    Methods
+    -------
+    __call__
+    derivative
+    antiderivative
+    integrate
+    solve
+    roots
+
+    See Also
+    --------
+    Akima1DInterpolator : Akima 1D interpolator.
+    PchipInterpolator : PCHIP 1-D monotonic cubic interpolator.
+    PPoly : Piecewise polynomial in terms of coefficients and breakpoints.
+
+    Notes
+    -----
+    Parameters `bc_type` and ``extrapolate`` work independently, i.e. the
+    former controls only construction of a spline, and the latter only
+    evaluation.
+
+    When a boundary condition is 'not-a-knot' and n = 2, it is replaced by
+    a condition that the first derivative is equal to the linear interpolant
+    slope. When both boundary conditions are 'not-a-knot' and n = 3, the
+    solution is sought as a parabola passing through given points.
+
+    When 'not-a-knot' boundary conditions is applied to both ends, the
+    resulting spline will be the same as returned by `splrep` (with ``s=0``)
+    and `InterpolatedUnivariateSpline`, but these two methods use a
+    representation in B-spline basis.
+
+    .. versionadded:: 0.18.0
+
+    Examples
+    --------
+    In this example the cubic spline is used to interpolate a sampled sinusoid.
+    You can see that the spline continuity property holds for the first and
+    second derivatives and violates only for the third derivative.
+
+    >>> import numpy as np
+    >>> from scipy.interpolate import CubicSpline
+    >>> import matplotlib.pyplot as plt
+    >>> x = np.arange(10)
+    >>> y = np.sin(x)
+    >>> cs = CubicSpline(x, y)
+    >>> xs = np.arange(-0.5, 9.6, 0.1)
+    >>> fig, ax = plt.subplots(figsize=(6.5, 4))
+    >>> ax.plot(x, y, 'o', label='data')
+    >>> ax.plot(xs, np.sin(xs), label='true')
+    >>> ax.plot(xs, cs(xs), label="S")
+    >>> ax.plot(xs, cs(xs, 1), label="S'")
+    >>> ax.plot(xs, cs(xs, 2), label="S''")
+    >>> ax.plot(xs, cs(xs, 3), label="S'''")
+    >>> ax.set_xlim(-0.5, 9.5)
+    >>> ax.legend(loc='lower left', ncol=2)
+    >>> plt.show()
+
+    In the second example, the unit circle is interpolated with a spline. A
+    periodic boundary condition is used. You can see that the first derivative
+    values, ds/dx=0, ds/dy=1 at the periodic point (1, 0) are correctly
+    computed. Note that a circle cannot be exactly represented by a cubic
+    spline. To increase precision, more breakpoints would be required.
+
+    >>> theta = 2 * np.pi * np.linspace(0, 1, 5)
+    >>> y = np.c_[np.cos(theta), np.sin(theta)]
+    >>> cs = CubicSpline(theta, y, bc_type='periodic')
+    >>> print("ds/dx={:.1f} ds/dy={:.1f}".format(cs(0, 1)[0], cs(0, 1)[1]))
+    ds/dx=0.0 ds/dy=1.0
+    >>> xs = 2 * np.pi * np.linspace(0, 1, 100)
+    >>> fig, ax = plt.subplots(figsize=(6.5, 4))
+    >>> ax.plot(y[:, 0], y[:, 1], 'o', label='data')
+    >>> ax.plot(np.cos(xs), np.sin(xs), label='true')
+    >>> ax.plot(cs(xs)[:, 0], cs(xs)[:, 1], label='spline')
+    >>> ax.axes.set_aspect('equal')
+    >>> ax.legend(loc='center')
+    >>> plt.show()
+
+    The third example is the interpolation of a polynomial y = x**3 on the
+    interval 0 <= x<= 1. A cubic spline can represent this function exactly.
+    To achieve that we need to specify values and first derivatives at
+    endpoints of the interval. Note that y' = 3 * x**2 and thus y'(0) = 0 and
+    y'(1) = 3.
+
+    >>> cs = CubicSpline([0, 1], [0, 1], bc_type=((1, 0), (1, 3)))
+    >>> x = np.linspace(0, 1)
+    >>> np.allclose(x**3, cs(x))
+    True
+
+    References
+    ----------
+    .. [1] `Cubic Spline Interpolation
+            `_
+            on Wikiversity.
+    .. [2] Carl de Boor, "A Practical Guide to Splines", Springer-Verlag, 1978.
+    """
+
+    def __init__(self, x, y, axis=0, bc_type='not-a-knot', extrapolate=None):
+        xp = array_namespace(x, y)
+        x, dx, y, axis, _ = prepare_input(x, y, axis, xp=np_compat)
+        n = len(x)
+
+        bc, y = self._validate_bc(bc_type, y, y.shape[1:], axis)
+
+        if extrapolate is None:
+            if bc[0] == 'periodic':
+                extrapolate = 'periodic'
+            else:
+                extrapolate = True
+
+        if y.size == 0:
+            # bail out early for zero-sized arrays
+            s = np.zeros_like(y)
+        else:
+            dxr = dx.reshape([dx.shape[0]] + [1] * (y.ndim - 1))
+            slope = np.diff(y, axis=0) / dxr
+
+            # If bc is 'not-a-knot' this change is just a convention.
+            # If bc is 'periodic' then we already checked that y[0] == y[-1],
+            # and the spline is just a constant, we handle this case in the
+            # same way by setting the first derivatives to slope, which is 0.
+            if n == 2:
+                if bc[0] in ['not-a-knot', 'periodic']:
+                    bc[0] = (1, slope[0])
+                if bc[1] in ['not-a-knot', 'periodic']:
+                    bc[1] = (1, slope[0])
+
+            # This is a special case, when both conditions are 'not-a-knot'
+            # and n == 3. In this case 'not-a-knot' can't be handled regularly
+            # as the both conditions are identical. We handle this case by
+            # constructing a parabola passing through given points.
+            if n == 3 and bc[0] == 'not-a-knot' and bc[1] == 'not-a-knot':
+                A = np.zeros((3, 3))  # This is a standard matrix.
+                b = np.empty((3,) + y.shape[1:], dtype=y.dtype)
+
+                A[0, 0] = 1
+                A[0, 1] = 1
+                A[1, 0] = dx[1]
+                A[1, 1] = 2 * (dx[0] + dx[1])
+                A[1, 2] = dx[0]
+                A[2, 1] = 1
+                A[2, 2] = 1
+
+                b[0] = 2 * slope[0]
+                b[1] = 3 * (dxr[0] * slope[1] + dxr[1] * slope[0])
+                b[2] = 2 * slope[1]
+
+                m = b.shape[0]
+                s = solve(A, b.reshape(m, -1), overwrite_a=True, overwrite_b=True,
+                          check_finite=False).reshape(b.shape)
+            elif n == 3 and bc[0] == 'periodic':
+                # In case when number of points is 3 we compute the derivatives
+                # manually
+                t = (slope / dxr).sum(0) / (1. / dxr).sum(0)
+                s = np.broadcast_to(t, (n,) + y.shape[1:])
+            else:
+                # Find derivative values at each x[i] by solving a tridiagonal
+                # system.
+                A = np.zeros((3, n))  # This is a banded matrix representation.
+                b = np.empty((n,) + y.shape[1:], dtype=y.dtype)
+
+                # Filling the system for i=1..n-2
+                #                         (x[i-1] - x[i]) * s[i-1] +\
+                # 2 * ((x[i] - x[i-1]) + (x[i+1] - x[i])) * s[i]   +\
+                #                         (x[i] - x[i-1]) * s[i+1] =\
+                #       3 * ((x[i+1] - x[i])*(y[i] - y[i-1])/(x[i] - x[i-1]) +\
+                #           (x[i] - x[i-1])*(y[i+1] - y[i])/(x[i+1] - x[i]))
+
+                A[1, 1:-1] = 2 * (dx[:-1] + dx[1:])  # The diagonal
+                A[0, 2:] = dx[:-1]                   # The upper diagonal
+                A[-1, :-2] = dx[1:]                  # The lower diagonal
+
+                b[1:-1] = 3 * (dxr[1:] * slope[:-1] + dxr[:-1] * slope[1:])
+
+                bc_start, bc_end = bc
+
+                if bc_start == 'periodic':
+                    # Due to the periodicity, and because y[-1] = y[0], the
+                    # linear system has (n-1) unknowns/equations instead of n:
+                    A = A[:, 0:-1]
+                    A[1, 0] = 2 * (dx[-1] + dx[0])
+                    A[0, 1] = dx[-1]
+
+                    b = b[:-1]
+
+                    # Also, due to the periodicity, the system is not tri-diagonal.
+                    # We need to compute a "condensed" matrix of shape (n-2, n-2).
+                    # See https://web.archive.org/web/20151220180652/http://www.cfm.brown.edu/people/gk/chap6/node14.html
+                    # for more explanations.
+                    # The condensed matrix is obtained by removing the last column
+                    # and last row of the (n-1, n-1) system matrix. The removed
+                    # values are saved in scalar variables with the (n-1, n-1)
+                    # system matrix indices forming their names:
+                    a_m1_0 = dx[-2]  # lower left corner value: A[-1, 0]
+                    a_m1_m2 = dx[-1]
+                    a_m1_m1 = 2 * (dx[-1] + dx[-2])
+                    a_m2_m1 = dx[-3]
+                    a_0_m1 = dx[0]
+
+                    b[0] = 3 * (dxr[0] * slope[-1] + dxr[-1] * slope[0])
+                    b[-1] = 3 * (dxr[-1] * slope[-2] + dxr[-2] * slope[-1])
+
+                    Ac = A[:, :-1]
+                    b1 = b[:-1]
+                    b2 = np.zeros_like(b1)
+                    b2[0] = -a_0_m1
+                    b2[-1] = -a_m2_m1
+
+                    # s1 and s2 are the solutions of (n-2, n-2) system
+                    m = b1.shape[0]
+                    s1 = solve_banded((1, 1), Ac, b1.reshape(m, -1), overwrite_ab=False,
+                                      overwrite_b=False, check_finite=False)
+                    s1 = s1.reshape(b1.shape)
+
+                    m = b2.shape[0]
+                    s2 = solve_banded((1, 1), Ac, b2.reshape(m, -1), overwrite_ab=False,
+                                      overwrite_b=False, check_finite=False)
+                    s2 = s2.reshape(b2.shape)
+
+                    # computing the s[n-2] solution:
+                    s_m1 = ((b[-1] - a_m1_0 * s1[0] - a_m1_m2 * s1[-1]) /
+                            (a_m1_m1 + a_m1_0 * s2[0] + a_m1_m2 * s2[-1]))
+
+                    # s is the solution of the (n, n) system:
+                    s = np.empty((n,) + y.shape[1:], dtype=y.dtype)
+                    s[:-2] = s1 + s_m1 * s2
+                    s[-2] = s_m1
+                    s[-1] = s[0]
+                else:
+                    if bc_start == 'not-a-knot':
+                        A[1, 0] = dx[1]
+                        A[0, 1] = x[2] - x[0]
+                        d = x[2] - x[0]
+                        b[0] = ((dxr[0] + 2*d) * dxr[1] * slope[0] +
+                                dxr[0]**2 * slope[1]) / d
+                    elif bc_start[0] == 1:
+                        A[1, 0] = 1
+                        A[0, 1] = 0
+                        b[0] = bc_start[1]
+                    elif bc_start[0] == 2:
+                        A[1, 0] = 2 * dx[0]
+                        A[0, 1] = dx[0]
+                        b[0] = -0.5 * bc_start[1] * dx[0]**2 + 3 * (y[1] - y[0])
+
+                    if bc_end == 'not-a-knot':
+                        A[1, -1] = dx[-2]
+                        A[-1, -2] = x[-1] - x[-3]
+                        d = x[-1] - x[-3]
+                        b[-1] = ((dxr[-1]**2*slope[-2] +
+                                 (2*d + dxr[-1])*dxr[-2]*slope[-1]) / d)
+                    elif bc_end[0] == 1:
+                        A[1, -1] = 1
+                        A[-1, -2] = 0
+                        b[-1] = bc_end[1]
+                    elif bc_end[0] == 2:
+                        A[1, -1] = 2 * dx[-1]
+                        A[-1, -2] = dx[-1]
+                        b[-1] = 0.5 * bc_end[1] * dx[-1]**2 + 3 * (y[-1] - y[-2])
+
+                    m = b.shape[0]
+                    s = solve_banded((1, 1), A, b.reshape(m, -1), overwrite_ab=True,
+                                     overwrite_b=True, check_finite=False)
+                    s = s.reshape(b.shape)
+
+        x, y, s = map(xp.asarray, (x, y, s))
+        super().__init__(x, y, s, axis=0, extrapolate=extrapolate)
+        self.axis = axis
+
+    @staticmethod
+    def _validate_bc(bc_type, y, expected_deriv_shape, axis):
+        """Validate and prepare boundary conditions.
+
+        Returns
+        -------
+        validated_bc : 2-tuple
+            Boundary conditions for a curve start and end.
+        y : ndarray
+            y casted to complex dtype if one of the boundary conditions has
+            complex dtype.
+        """
+        if isinstance(bc_type, str):
+            if bc_type == 'periodic':
+                if not np.allclose(y[0], y[-1], rtol=1e-15, atol=1e-15):
+                    raise ValueError(
+                        f"The first and last `y` point along axis {axis} must "
+                        "be identical (within machine precision) when "
+                        "bc_type='periodic'.")
+
+            bc_type = (bc_type, bc_type)
+
+        else:
+            if len(bc_type) != 2:
+                raise ValueError("`bc_type` must contain 2 elements to "
+                                 "specify start and end conditions.")
+
+            if 'periodic' in bc_type:
+                raise ValueError("'periodic' `bc_type` is defined for both "
+                                 "curve ends and cannot be used with other "
+                                 "boundary conditions.")
+
+        validated_bc = []
+        for bc in bc_type:
+            if isinstance(bc, str):
+                if bc == 'clamped':
+                    validated_bc.append((1, np.zeros(expected_deriv_shape)))
+                elif bc == 'natural':
+                    validated_bc.append((2, np.zeros(expected_deriv_shape)))
+                elif bc in ['not-a-knot', 'periodic']:
+                    validated_bc.append(bc)
+                else:
+                    raise ValueError(f"bc_type={bc} is not allowed.")
+            else:
+                try:
+                    deriv_order, deriv_value = bc
+                except Exception as e:
+                    raise ValueError(
+                        "A specified derivative value must be "
+                        "given in the form (order, value)."
+                    ) from e
+
+                if deriv_order not in [1, 2]:
+                    raise ValueError("The specified derivative order must "
+                                     "be 1 or 2.")
+
+                deriv_value = np.asarray(deriv_value)
+                if deriv_value.shape != expected_deriv_shape:
+                    raise ValueError(
+                        f"`deriv_value` shape {deriv_value.shape} is not "
+                        f"the expected one {expected_deriv_shape}."
+                    )
+
+                if np.issubdtype(deriv_value.dtype, np.complexfloating):
+                    y = y.astype(complex, copy=False)
+
+                validated_bc.append((deriv_order, deriv_value))
+
+        return validated_bc, y
diff --git a/.venv/lib/python3.12/site-packages/scipy/interpolate/_dierckx.cpython-312-x86_64-linux-gnu.so b/.venv/lib/python3.12/site-packages/scipy/interpolate/_dierckx.cpython-312-x86_64-linux-gnu.so
new file mode 100644
index 0000000000000000000000000000000000000000..5c0f98dccc623db817de826ed2dc7145b4c5f4d0
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/interpolate/_dierckx.cpython-312-x86_64-linux-gnu.so
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:d2d26df8de759f25eada97a6a47dbcb916991ba191e8b11964288499727de808
+size 129337
diff --git a/.venv/lib/python3.12/site-packages/scipy/interpolate/_fitpack.cpython-312-x86_64-linux-gnu.so b/.venv/lib/python3.12/site-packages/scipy/interpolate/_fitpack.cpython-312-x86_64-linux-gnu.so
new file mode 100644
index 0000000000000000000000000000000000000000..0bec96c39f4c1c41810a79ef8f8d00788f7d7467
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/interpolate/_fitpack.cpython-312-x86_64-linux-gnu.so
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:ef8f928f777cffbefdd22f053765224196b23736554595ae965885ba0a0bb396
+size 342504
diff --git a/.venv/lib/python3.12/site-packages/scipy/interpolate/_fitpack2.py b/.venv/lib/python3.12/site-packages/scipy/interpolate/_fitpack2.py
new file mode 100644
index 0000000000000000000000000000000000000000..dbc22dc9d6a881b7cb9c0865653737dee949b999
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/interpolate/_fitpack2.py
@@ -0,0 +1,2798 @@
+"""
+fitpack --- curve and surface fitting with splines
+
+fitpack is based on a collection of Fortran routines DIERCKX
+by P. Dierckx (see http://www.netlib.org/dierckx/) transformed
+to double routines by Pearu Peterson.
+"""
+# Created by Pearu Peterson, June,August 2003
+__all__ = [
+    'UnivariateSpline',
+    'InterpolatedUnivariateSpline',
+    'LSQUnivariateSpline',
+    'BivariateSpline',
+    'LSQBivariateSpline',
+    'SmoothBivariateSpline',
+    'LSQSphereBivariateSpline',
+    'SmoothSphereBivariateSpline',
+    'RectBivariateSpline',
+    'RectSphereBivariateSpline']
+
+
+import warnings
+
+from numpy import zeros, concatenate, ravel, diff, array
+import numpy as np
+
+from . import _fitpack_impl
+from . import _fitpack  # type:ignore[attr-defined]
+from scipy._lib._array_api import xp_capabilities
+
+
+# Helper functions for bbox calculation (matching f2py behavior)
+def _calc_b(data, knots):
+    """Calculate lower bbox bound for LSQ splines (mimics f2py calc_b)."""
+    val1 = np.min(data)
+    val2 = np.min(knots)
+    if val2 > val1:
+        return val1
+    val_max = np.max(knots)
+    return val2 - (val_max - val2) / len(knots)
+
+
+def _calc_e(data, knots):
+    """Calculate upper bbox bound for LSQ splines (mimics f2py calc_e)."""
+    val1 = np.max(data)
+    val2 = np.max(knots)
+    if val2 < val1:
+        return val1
+    val_min = np.min(knots)
+    return val2 + (val2 - val_min) / len(knots)
+
+
+def _curfit(x, y, k, w=None, xb=None, xe=None, s=None, nest=None, iopt=0,
+            t=None, c=None, n=None, fpint=None, nrdata=None):
+    """
+    Wrapper for curfit that provides a simpler interface.
+
+    iopt=0: find smoothing spline (initial call)
+    iopt=1: continue with current knots (refinement)
+    iopt=-1: least squares fit with fixed knots
+
+    Returns: n, t, c, fp, ier
+    For compatibility with old code, can be unpacked as:
+        _data = (x, y, w, xb, xe, k, s, n, t, c, fp, None, None, ier)
+    """
+    x = np.asarray(x, dtype=float, order='F').ravel('F')
+    y = np.asarray(y, dtype=float, order='F').ravel('F')
+    m = len(x)
+
+    if w is None:
+        w = np.ones(m, dtype=float)
+    else:
+        w = np.asarray(w, dtype=float, order='F').ravel('F')
+
+    if xb is None:
+        xb = float(x[0])
+    else:
+        xb = float(xb)
+    if xe is None:
+        xe = float(x[-1])
+    else:
+        xe = float(xe)
+    if s is None:
+        s = float(m)
+
+    # In iopt=1 mode, callers may pass preallocated/resized t/c; prefer that
+    # size as the working `nest` to keep workspace sizing consistent.
+    if nest is None and t is not None:
+        nest = len(t)
+
+    k1 = k + 1
+
+    if iopt == -1:
+        # Fixed knots mode: t is provided
+        if t is None:
+            raise ValueError("t must be provided for iopt=-1")
+        t = np.asarray(t, dtype=float, copy=True)
+        nest = len(t)
+        n = nest
+    else:
+        # Smoothing mode (iopt=0 or iopt=1)
+        if nest is None:
+            nest = (m + k + 1) if (s == 0.0) else (max(m // 2, 2 * k1))
+
+        if iopt == 0:
+            # Initial call: allocate new arrays
+            t = np.zeros(nest, dtype=float)
+        else:
+            # Continuation (iopt=1): use existing arrays
+            if t is None or c is None:
+                raise ValueError("t and c must be provided for iopt=1")
+            t = np.asarray(t, dtype=float, copy=True)
+            if n is None:
+                n = nest
+
+    # Workspace for curfit
+    lwrk = m * k1 + nest * (7 + 3 * k)
+    wrk = np.zeros(lwrk, dtype=float)
+    iwrk = np.zeros(nest, dtype=np.int32)
+
+    # Call curfit (nest is inferred from len(t) in C code)
+    n_out, t_out, c_out, fp, ier = _fitpack.curfit(iopt, x, y, w, xb, xe, k, s,
+                                                   t, wrk, iwrk)
+
+    # Return in old format for compatibility:
+    # x, y, w, xb, xe, k, s, n, t, c, fp, fpint, nrdata, ier
+    return x, y, w, xb, xe, k, s, n_out, t_out, c_out, fp, fpint, nrdata, ier
+
+
+def _surfit_smth(x, y, z, w, xb, xe, yb, ye, kx, ky, s, eps):
+    """
+    Wrapper for surfit with iopt=0 (smoothing spline).
+    Returns: nx, tx, ny, ty, c, fp, ier
+    """
+    # The C binding (_fitpack.surfit_smth) reads these buffers assuming
+    # C-contiguity; coerce strided views.
+    x = np.ascontiguousarray(x, dtype=np.float64)
+    y = np.ascontiguousarray(y, dtype=np.float64)
+    z = np.ascontiguousarray(z, dtype=np.float64)
+    m = len(x)
+
+    # Handle None w value (default equal weights)
+    if w is None:
+        w = np.ones(m, dtype=np.float64)
+    else:
+        w = np.asarray(w, dtype=np.float64, copy=True)
+
+    # Handle None bbox values (matching f2py behavior: xb=dmin(x,m), etc.)
+    if xb is None:
+        xb = np.min(x)
+    if xe is None:
+        xe = np.max(x)
+    if yb is None:
+        yb = np.min(y)
+    if ye is None:
+        ye = np.max(y)
+
+    # Estimate nxest and nyest
+    nxest = max(kx + 1 + int(np.sqrt(m / 2)), 2 * (kx + 1))
+    nyest = max(ky + 1 + int(np.sqrt(m / 2)), 2 * (ky + 1))
+    nmax = max(nxest, nyest)
+
+    # Handle None s value (default smoothing factor)
+    if s is None:
+        s = float(m)
+
+    # Call surfit with iopt=0
+    # Note: The C wrapper allocates tx, ty, and workspace arrays internally for iopt=1
+    # We just need to pass dummy wrk here
+    nx, tx, ny, ty, c, fp, ier = _fitpack.surfit_smth(
+        x, y, z, w, xb, xe, yb, ye, kx, ky, s, nxest, nyest, nmax, eps)
+
+    return nx, tx, ny, ty, c, fp, ier
+
+
+def _surfit_lsq(x, y, z, nx, tx, ny, ty, w, xb, xe, yb, ye, kx, ky, eps):
+    """
+    Wrapper for surfit with iopt=-1 (least squares fit with fixed knots).
+    Returns: tx, ty, c, fp, ier
+    """
+    # The C binding (_fitpack.surfit_lsq) reads these buffers assuming
+    # C-contiguity; coerce strided views.
+    x = np.ascontiguousarray(x, dtype=np.float64)
+    y = np.ascontiguousarray(y, dtype=np.float64)
+    z = np.ascontiguousarray(z, dtype=np.float64)
+    m = len(x)
+
+    if w is None:
+        w = np.ones(m, dtype=np.float64)
+    else:
+        w = np.asarray(w, dtype=np.float64, copy=True)
+
+    tx = np.asarray(tx, dtype=np.float64, copy=True)
+    ty = np.asarray(ty, dtype=np.float64, copy=True)
+
+    nxest = nx
+    nyest = ny
+    nmax = max(nx, ny)
+    if eps is None:
+        eps = 1e-16
+    else:
+        if not (0.0 < eps < 1.0):
+            raise ValueError("eps must be in the range (0.0, 1.0)")
+
+    # Call surfit with iopt=-1, tx/ty are modified in-place.
+    c, fp, ier = _fitpack.surfit_lsq(
+        x, y, z, w, xb, xe, yb, ye, kx, ky, 0.0, nxest, nyest, nmax, eps, tx, ty)
+
+    return tx, ty, c, fp, ier
+
+
+def _regrid_smth(x, y, z, xb, xe, yb, ye, kx, ky, s, maxit):
+    """
+    Wrapper for regrid with iopt=0 (smoothing spline on rectangular grid).
+    Returns: nx, tx, ny, ty, c, fp, ier
+    """
+    x = np.asarray(x, dtype=np.float64)
+    y = np.asarray(y, dtype=np.float64)
+    z = np.asarray(z, dtype=np.float64)
+    mx = len(x)
+    my = len(y)
+
+    # Handle None values for bbox
+    if xb is None:
+        xb = np.min(x)
+    if xe is None:
+        xe = np.max(x)
+    if yb is None:
+        yb = np.min(y)
+    if ye is None:
+        ye = np.max(y)
+
+    # Estimate nxest and nyest
+    nxest = mx + kx + 1
+    nyest = my + ky + 1
+
+    # Workspace
+    lwrk = 4 + mx + my + nxest * (my + 2 * kx + 5) \
+           + nyest * (2 * ky + 5) + mx * (kx + 1) \
+           + my * (ky + 1) + \
+           max((nxest - kx - 1) * (nyest - ky - 1), my)
+
+    wrk = np.zeros(lwrk, dtype=np.float64)
+    kwrk = 3 + mx + my + nxest + nyest
+    iwrk = np.zeros(kwrk, dtype=np.int32)
+
+    # Call regrid with iopt=0
+    nx, tx, ny, ty, c, fp, ier = _fitpack.regrid(
+        0, x, y, z, xb, xe, yb, ye, kx, ky, s, nxest, nyest, maxit, wrk, iwrk)
+
+    return nx, tx, ny, ty, c, fp, ier
+
+
+def _spherfit_smth(theta, phi, r, w, s, eps):
+    """
+    Wrapper for sphere with iopt=0 (smoothing spline on sphere).
+    Returns: nt, tt, np, tp, c, fp, ier
+    """
+    theta = np.asarray(theta, dtype=np.float64)
+    phi = np.asarray(phi, dtype=np.float64)
+    r = np.asarray(r, dtype=np.float64)
+    if w is None:
+        w = np.ones(len(theta), dtype=np.float64)
+    else:
+        w = np.asarray(w, dtype=np.float64)
+    m = len(theta)
+
+    # Estimate ntest and npest
+    ntest = 8 + int(np.sqrt(m / 2))
+    npest = 8 + int(np.sqrt(m / 2))
+
+    # Workspace
+    # lwrk1: 185+52*v+10*u+14*u*v+8*(u-1)*v**2+8*m
+    # lwrk2: 48+21*v+7*u*v+4*(u-1)*v**2
+    # where u = ntest - 7, v = npest - 7
+    u = ntest - 7
+    v = npest - 7
+    lwrk1 = 185 + 52*v + 10*u + 14*u*v + 8*(u-1)*v*v + 8*m
+    lwrk2 = 48 + 21*v + 7*u*v + 4*(u-1)*v*v
+    kwrk = m + (ntest - 7) * (npest - 7)
+    wrk1 = np.zeros(lwrk1, dtype=np.float64)
+    wrk2 = np.zeros(lwrk2, dtype=np.float64)
+    iwrk = np.zeros(kwrk, dtype=np.int32)
+
+    # Call sphere with iopt=0
+    nt, tt, np_, tp, c, fp, ier = _fitpack.sphere(
+        0, theta, phi, r, w, s, ntest, npest,
+        np.array([0.]), np.array([0.]),  # dummy input for tt and tp, ignored
+        eps, wrk1, wrk2, iwrk)
+
+    return nt, tt, np_, tp, c, fp, ier
+
+
+def _spherfit_lsq(theta, phi, r, nt, tt, np_, tp, w, eps):
+    """
+    Wrapper for sphere with iopt=-1 (least squares fit with fixed knots on sphere).
+    Returns: tt, tp, c, fp, ier
+    """
+    theta = np.asarray(theta, dtype=np.float64)
+    phi = np.asarray(phi, dtype=np.float64)
+    r = np.asarray(r, dtype=np.float64)
+    tt = np.asarray(tt, dtype=np.float64, copy=True)
+    tp = np.asarray(tp, dtype=np.float64, copy=True)
+    if w is None:
+        w = np.ones(len(theta), dtype=np.float64)
+    else:
+        w = np.asarray(w, dtype=np.float64)
+    m = len(theta)
+
+    ntest = nt
+    npest = np_
+
+    # Workspace
+    # lwrk1: 185+52*v+10*u+14*u*v+8*(u-1)*v**2+8*m
+    # lwrk2: 48+21*v+7*u*v+4*(u-1)*v**2
+    # where u = ntest - 7, v = npest - 7
+    u = ntest - 7
+    v = npest - 7
+    lwrk1 = 185 + 52*v + 10*u + 14*u*v + 8*(u-1)*v*v + 8*m
+    lwrk2 = 48 + 21*v + 7*u*v + 4*(u-1)*v*v
+    kwrk = m + (ntest - 7) * (npest - 7)
+    wrk1 = np.zeros(lwrk1, dtype=np.float64)
+    wrk2 = np.zeros(lwrk2, dtype=np.float64)
+    iwrk = np.zeros(kwrk, dtype=np.int32)
+
+    # Call sphere with iopt=-1
+    nt_out, tt_out, np_out, tp_out, c, fp, ier = _fitpack.sphere(
+        -1, theta, phi, r, w, 0.0, ntest, npest, tt, tp, eps, wrk1, wrk2, iwrk)
+
+    return tt_out, tp_out, c, fp, ier
+
+
+def _regrid_smth_spher(iopt, ider, u, v, r, r0, r1, s, nuest, nvest, eps):
+    """
+    Wrapper for spgrid (smoothing on spherical grid).
+    Returns: nu, tu, nv, tv, c, fp, ier
+
+    Note: eps parameter is not used by the C implementation but kept for
+    legacy API compatibility.
+    """
+    u = np.ascontiguousarray(u, dtype=np.float64)
+    v = np.ascontiguousarray(v, dtype=np.float64)
+    r = np.ascontiguousarray(r, dtype=np.float64)
+    iopt = np.ascontiguousarray(iopt, dtype=np.int32)
+    ider = np.ascontiguousarray(ider, dtype=np.int32)
+
+    # Handle None values for r0 and r1 (only used when ider indicates they should be)
+    if r0 is None:
+        r0 = 0.0
+    if r1 is None:
+        r1 = 0.0
+
+    # Call spgrid - workspace arrays are now allocated internally in C
+    nu, tu, nv, tv, c, fp, ier = _fitpack.spgrid(
+        iopt, ider, u, v, r, r0, r1, s, nuest, nvest)
+
+    return nu, tu, nv, tv, c, fp, ier
+
+
+# ############### Univariate spline ####################
+
+_curfit_messages = {1: """
+The required storage space exceeds the available storage space, as
+specified by the parameter nest: nest too small. If nest is already
+large (say nest > m/2), it may also indicate that s is too small.
+The approximation returned is the weighted least-squares spline
+according to the knots t[0],t[1],...,t[n-1]. (n=nest) the parameter fp
+gives the corresponding weighted sum of squared residuals (fp>s).
+""",
+                    2: """
+A theoretically impossible result was found during the iteration
+process for finding a smoothing spline with fp = s: s too small.
+There is an approximation returned but the corresponding weighted sum
+of squared residuals does not satisfy the condition abs(fp-s)/s < tol.""",
+                    3: """
+The maximal number of iterations maxit (set to 20 by the program)
+allowed for finding a smoothing spline with fp=s has been reached: s
+too small.
+There is an approximation returned but the corresponding weighted sum
+of squared residuals does not satisfy the condition abs(fp-s)/s < tol.""",
+                    10: """
+Error on entry, no approximation returned. The following conditions
+must hold:
+xb<=x[0]0, i=0..m-1
+if iopt=-1:
+  xb>> import numpy as np
+    >>> from scipy.interpolate import UnivariateSpline
+    >>> x, y = np.array([1, 2, 3, 4]), np.array([1, np.nan, 3, 4])
+    >>> w = np.isnan(y)
+    >>> y[w] = 0.
+    >>> spl = UnivariateSpline(x, y, w=~w)
+
+    Notice the need to replace a ``nan`` by a numerical value (precise value
+    does not matter as long as the corresponding weight is zero.)
+
+    References
+    ----------
+    Based on algorithms described in [1]_, [2]_, [3]_, and [4]_:
+
+    .. [1] P. Dierckx, "An algorithm for smoothing, differentiation and
+       integration of experimental data using spline functions",
+       J.Comp.Appl.Maths 1 (1975) 165-184.
+    .. [2] P. Dierckx, "A fast algorithm for smoothing data on a rectangular
+       grid while using spline functions", SIAM J.Numer.Anal. 19 (1982)
+       1286-1304.
+    .. [3] P. Dierckx, "An improved algorithm for curve fitting with spline
+       functions", report tw54, Dept. Computer Science,K.U. Leuven, 1981.
+    .. [4] P. Dierckx, "Curve and surface fitting with splines", Monographs on
+       Numerical Analysis, Oxford University Press, 1993.
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> import matplotlib.pyplot as plt
+    >>> from scipy.interpolate import UnivariateSpline
+    >>> rng = np.random.default_rng()
+    >>> x = np.linspace(-3, 3, 50)
+    >>> y = np.exp(-x**2) + 0.1 * rng.standard_normal(50)
+    >>> plt.plot(x, y, 'ro', ms=5)
+
+    Use the default value for the smoothing parameter:
+
+    >>> spl = UnivariateSpline(x, y)
+    >>> xs = np.linspace(-3, 3, 1000)
+    >>> plt.plot(xs, spl(xs), 'g', lw=3)
+
+    Manually change the amount of smoothing:
+
+    >>> spl.set_smoothing_factor(0.5)
+    >>> plt.plot(xs, spl(xs), 'b', lw=3)
+    >>> plt.show()
+
+    """
+
+    def __init__(self, x, y, w=None, bbox=[None]*2, k=3, s=None,
+                 ext=0, check_finite=False):
+
+        x, y, w, bbox, self.ext = self.validate_input(x, y, w, bbox, k, s, ext,
+                                                      check_finite)
+        # x, y, k, w, xb, xe, s, nest, iopt=0, t, c, n=None
+        # _data == x,y,w,xb,xe,k,s,n,t,c,fp,fpint,nrdata,ier
+        data = _curfit(x, y, k, w=w, xb=bbox[0], xe=bbox[1], s=s, iopt=0)
+        if data[-1] == 1:
+            # nest too small, setting to maximum bound
+            data = self._reset_nest(data)
+        self._data = data
+        self._reset_class()
+
+    @staticmethod
+    def validate_input(x, y, w, bbox, k, s, ext, check_finite):
+        x, y, bbox = np.asarray(x), np.asarray(y), np.asarray(bbox)
+        if w is not None:
+            w = np.asarray(w)
+        if check_finite:
+            w_finite = np.isfinite(w).all() if w is not None else True
+            if (not np.isfinite(x).all() or not np.isfinite(y).all() or
+                    not w_finite):
+                raise ValueError("x and y array must not contain "
+                                 "NaNs or infs.")
+        if s is None or s > 0:
+            if not np.all(diff(x) >= 0.0):
+                raise ValueError("x must be increasing if s > 0")
+        else:
+            if not np.all(diff(x) > 0.0):
+                raise ValueError("x must be strictly increasing if s = 0")
+        if x.size != y.size:
+            raise ValueError("x and y should have a same length")
+        elif w is not None and not x.size == y.size == w.size:
+            raise ValueError("x, y, and w should have a same length")
+        elif bbox.shape != (2,):
+            raise ValueError("bbox shape should be (2,)")
+        elif not (1 <= k <= 5):
+            raise ValueError("k should be 1 <= k <= 5")
+        elif s is not None and not s >= 0.0:
+            raise ValueError("s should be s >= 0.0")
+
+        try:
+            ext = _extrap_modes[ext]
+        except KeyError as e:
+            raise ValueError(f"Unknown extrapolation mode {ext}.") from e
+
+        return x, y, w, bbox, ext
+
+    @classmethod
+    def _from_tck(cls, tck, ext=0):
+        """Construct a spline object from given tck"""
+        self = cls.__new__(cls)
+        t, c, k = tck
+        self._eval_args = tck
+        # _data == x,y,w,xb,xe,k,s,n,t,c,fp,fpint,nrdata,ier
+        self._data = (None, None, None, None, None, k, None, len(t), t,
+                      c, None, None, None, None)
+        self.ext = ext
+        return self
+
+    def _reset_class(self):
+        data = self._data
+        n, t, c, k, ier = data[7], data[8], data[9], data[5], data[-1]
+        self._eval_args = t[:n], c[:n], k
+        if ier == 0:
+            # the spline returned has a residual sum of squares fp
+            # such that abs(fp-s)/s <= tol with tol a relative
+            # tolerance set to 0.001 by the program
+            pass
+        elif ier == -1:
+            # the spline returned is an interpolating spline
+            self._set_class(InterpolatedUnivariateSpline)
+        elif ier == -2:
+            # the spline returned is the weighted least-squares
+            # polynomial of degree k. In this extreme case fp gives
+            # the upper bound fp0 for the smoothing factor s.
+            self._set_class(LSQUnivariateSpline)
+        else:
+            # error
+            if ier == 1:
+                self._set_class(LSQUnivariateSpline)
+            message = _curfit_messages.get(ier, f'ier={ier}')
+            warnings.warn(message, stacklevel=3)
+
+    def _set_class(self, cls):
+        self._spline_class = cls
+        if self.__class__ in (UnivariateSpline, InterpolatedUnivariateSpline,
+                              LSQUnivariateSpline):
+            self.__class__ = cls
+        else:
+            # It's an unknown subclass -- don't change class. cf. #731
+            pass
+
+    def _reset_nest(self, data, nest=None):
+        n = data[7]
+        if nest is None:
+            k, m = data[5], len(data[0])
+            nest = m+k+1  # this is the maximum bound for nest
+        else:
+            if not n <= nest:
+                raise ValueError("`nest` can only be increased")
+        t, c, fpint, nrdata = (np.resize(data[j], nest) for j in
+                               [8, 9, 11, 12])
+
+        data = _curfit(
+            data[0],
+            data[1],
+            data[5],
+            w=data[2],
+            xb=data[3],
+            xe=data[4],
+            s=data[6],
+            nest=nest,
+            iopt=1,
+            t=t,
+            c=c,
+            n=n,
+            fpint=fpint,
+            nrdata=nrdata,
+        )
+        return data
+
+    def set_smoothing_factor(self, s):
+        """ Continue spline computation with the given smoothing
+        factor s and with the knots found at the last call.
+
+        This routine modifies the spline in place.
+
+        """
+        data = self._data
+        if data[6] == -1:
+            warnings.warn('smoothing factor unchanged for'
+                          'LSQ spline with fixed knots',
+                          stacklevel=2)
+            return
+
+        # data = x, y, w, xb, xe, k, s, n, t, c, fp, fpint, nrdata, ier
+        data = _curfit(
+            data[0],
+            data[1],
+            data[5],
+            w=data[2],
+            xb=data[3],
+            xe=data[4],
+            s=s,
+            nest=len(data[8]),
+            iopt=1,
+            t=data[8],
+            c=data[9],
+            n=data[7],
+            fpint=data[11],
+            nrdata=data[12],
+        )
+        if data[-1] == 1:
+            # nest too small, setting to maximum bound
+            data = self._reset_nest(data)
+        self._data = data
+        self._reset_class()
+
+    def __call__(self, x, nu=0, ext=None):
+        """
+        Evaluate spline (or its nu-th derivative) at positions x.
+
+        Parameters
+        ----------
+        x : array_like
+            A 1-D array of points at which to return the value of the smoothed
+            spline or its derivatives. Note: `x` can be unordered but the
+            evaluation is more efficient if `x` is (partially) ordered.
+        nu  : int
+            The order of derivative of the spline to compute.
+        ext : int
+            Controls the value returned for elements of `x` not in the
+            interval defined by the knot sequence.
+
+            * if ext=0 or 'extrapolate', return the extrapolated value.
+            * if ext=1 or 'zeros', return 0
+            * if ext=2 or 'raise', raise a ValueError
+            * if ext=3 or 'const', return the boundary value.
+
+            The default value is 0, passed from the initialization of
+            UnivariateSpline.
+
+        """
+        x = np.asarray(x)
+        # empty input yields empty output
+        if x.size == 0:
+            return array([])
+        if ext is None:
+            ext = self.ext
+        else:
+            try:
+                ext = _extrap_modes[ext]
+            except KeyError as e:
+                raise ValueError(f"Unknown extrapolation mode {ext}.") from e
+
+        return _fitpack_impl.splev(x, self._eval_args, der=nu, ext=ext)
+
+    def get_knots(self):
+        """ Return positions of interior knots of the spline.
+
+        Internally, the knot vector contains ``2*k`` additional boundary knots.
+        """
+        data = self._data
+        k, n = data[5], data[7]
+        return data[8][k:n-k]
+
+    def get_coeffs(self):
+        """Return spline coefficients."""
+        data = self._data
+        k, n = data[5], data[7]
+        return data[9][:n-k-1]
+
+    def get_residual(self):
+        """Return weighted sum of squared residuals of the spline approximation.
+
+           This is equivalent to::
+
+                sum((w[i] * (y[i]-spl(x[i])))**2, axis=0)
+
+        """
+        return self._data[10]
+
+    def integral(self, a, b):
+        """ Return definite integral of the spline between two given points.
+
+        Parameters
+        ----------
+        a : float
+            Lower limit of integration.
+        b : float
+            Upper limit of integration.
+
+        Returns
+        -------
+        integral : float
+            The value of the definite integral of the spline between limits.
+
+        Examples
+        --------
+        >>> import numpy as np
+        >>> from scipy.interpolate import UnivariateSpline
+        >>> x = np.linspace(0, 3, 11)
+        >>> y = x**2
+        >>> spl = UnivariateSpline(x, y)
+        >>> spl.integral(0, 3)
+        9.0
+
+        which agrees with :math:`\\int x^2 dx = x^3 / 3` between the limits
+        of 0 and 3.
+
+        A caveat is that this routine assumes the spline to be zero outside of
+        the data limits:
+
+        >>> spl.integral(-1, 4)
+        9.0
+        >>> spl.integral(-1, 0)
+        0.0
+
+        """
+        return _fitpack_impl.splint(a, b, self._eval_args)
+
+    def derivatives(self, x):
+        """ Return all derivatives of the spline at the point x.
+
+        Parameters
+        ----------
+        x : float
+            The point to evaluate the derivatives at.
+
+        Returns
+        -------
+        der : ndarray, shape(k+1,)
+            Derivatives of the orders 0 to k.
+
+        Examples
+        --------
+        >>> import numpy as np
+        >>> from scipy.interpolate import UnivariateSpline
+        >>> x = np.linspace(0, 3, 11)
+        >>> y = x**2
+        >>> spl = UnivariateSpline(x, y)
+        >>> spl.derivatives(1.5)
+        array([2.25, 3.0, 2.0, 0])
+
+        """
+        return _fitpack_impl.spalde(x, self._eval_args)
+
+    def roots(self):
+        """ Return the zeros of the spline.
+
+        Notes
+        -----
+        Restriction: only cubic splines are supported by FITPACK. For non-cubic
+        splines, use `PPoly.root` (see below for an example).
+
+        Examples
+        --------
+
+        For some data, this method may miss a root. This happens when one of
+        the spline knots (which FITPACK places automatically) happens to
+        coincide with the true root. A workaround is to convert to `PPoly`,
+        which uses a different root-finding algorithm.
+
+        For example,
+
+        >>> x = [1.96, 1.97, 1.98, 1.99, 2.00, 2.01, 2.02, 2.03, 2.04, 2.05]
+        >>> y = [-6.365470e-03, -4.790580e-03, -3.204320e-03, -1.607270e-03,
+        ...      4.440892e-16,  1.616930e-03,  3.243000e-03,  4.877670e-03,
+        ...      6.520430e-03,  8.170770e-03]
+        >>> from scipy.interpolate import UnivariateSpline
+        >>> spl = UnivariateSpline(x, y, s=0)
+        >>> spl.roots()
+        array([], dtype=float64)
+
+        Converting to a PPoly object does find the roots at `x=2`:
+
+        >>> from scipy.interpolate import splrep, PPoly
+        >>> tck = splrep(x, y, s=0)
+        >>> ppoly = PPoly.from_spline(tck)
+        >>> ppoly.roots(extrapolate=False)
+        array([2.])
+
+        See Also
+        --------
+        sproot
+        PPoly.roots
+
+        """
+        k = self._data[5]
+        if k == 3:
+            t = self._eval_args[0]
+            mest = 3 * (len(t) - 7)
+
+            return _fitpack_impl.sproot(self._eval_args, mest=mest)
+        raise NotImplementedError('finding roots unsupported for '
+                                  'non-cubic splines')
+
+    def derivative(self, n=1):
+        """
+        Construct a new spline representing the derivative of this spline.
+
+        Parameters
+        ----------
+        n : int, optional
+            Order of derivative to evaluate. Default: 1
+
+        Returns
+        -------
+        spline : UnivariateSpline
+            Spline of order k2=k-n representing the derivative of this
+            spline.
+
+        See Also
+        --------
+        splder, antiderivative
+
+        Notes
+        -----
+
+        .. versionadded:: 0.13.0
+
+        Examples
+        --------
+        This can be used for finding maxima of a curve:
+
+        >>> import numpy as np
+        >>> from scipy.interpolate import UnivariateSpline
+        >>> x = np.linspace(0, 10, 70)
+        >>> y = np.sin(x)
+        >>> spl = UnivariateSpline(x, y, k=4, s=0)
+
+        Now, differentiate the spline and find the zeros of the
+        derivative. (NB: `sproot` only works for order 3 splines, so we
+        fit an order 4 spline):
+
+        >>> spl.derivative().roots() / np.pi
+        array([ 0.50000001,  1.5       ,  2.49999998])
+
+        This agrees well with roots :math:`\\pi/2 + n\\pi` of
+        :math:`\\cos(x) = \\sin'(x)`.
+
+        """
+        tck = _fitpack_impl.splder(self._eval_args, n)
+        # if self.ext is 'const', derivative.ext will be 'zeros'
+        ext = 1 if self.ext == 3 else self.ext
+        return UnivariateSpline._from_tck(tck, ext=ext)
+
+    def antiderivative(self, n=1):
+        """
+        Construct a new spline representing the antiderivative of this spline.
+
+        Parameters
+        ----------
+        n : int, optional
+            Order of antiderivative to evaluate. Default: 1
+
+        Returns
+        -------
+        spline : UnivariateSpline
+            Spline of order k2=k+n representing the antiderivative of this
+            spline.
+
+        See Also
+        --------
+        splantider, derivative
+
+        Notes
+        -----
+
+        .. versionadded:: 0.13.0
+
+        Examples
+        --------
+        >>> import numpy as np
+        >>> from scipy.interpolate import UnivariateSpline
+        >>> x = np.linspace(0, np.pi/2, 70)
+        >>> y = 1 / np.sqrt(1 - 0.8*np.sin(x)**2)
+        >>> spl = UnivariateSpline(x, y, s=0)
+
+        The derivative is the inverse operation of the antiderivative,
+        although some floating point error accumulates:
+
+        >>> spl(1.7), spl.antiderivative().derivative()(1.7)
+        (array(2.1565429877197317), array(2.1565429877201865))
+
+        Antiderivative can be used to evaluate definite integrals:
+
+        >>> ispl = spl.antiderivative()
+        >>> ispl(np.pi/2) - ispl(0)
+        2.2572053588768486
+
+        This is indeed an approximation to the complete elliptic integral
+        :math:`K(m) = \\int_0^{\\pi/2} [1 - m\\sin^2 x]^{-1/2} dx`:
+
+        >>> from scipy.special import ellipk
+        >>> ellipk(0.8)
+        2.2572053268208538
+
+        """
+        tck = _fitpack_impl.splantider(self._eval_args, n)
+        return UnivariateSpline._from_tck(tck, self.ext)
+
+
+@xp_capabilities(out_of_scope=True)
+class InterpolatedUnivariateSpline(UnivariateSpline):
+    """
+    1-D interpolating spline for a given set of data points.
+
+    .. legacy:: class
+
+        Specifically, we recommend using `make_interp_spline` instead.
+
+    Fits a spline y = spl(x) of degree `k` to the provided `x`, `y` data.
+    Spline function passes through all provided points. Equivalent to
+    `UnivariateSpline` with  `s` = 0.
+
+    Parameters
+    ----------
+    x : (N,) array_like
+        Input dimension of data points -- must be strictly increasing
+    y : (N,) array_like
+        input dimension of data points
+    w : (N,) array_like, optional
+        Weights for spline fitting.  Must be positive.  If None (default),
+        weights are all 1.
+    bbox : (2,) array_like, optional
+        2-sequence specifying the boundary of the approximation interval. If
+        None (default), ``bbox=[x[0], x[-1]]``.
+    k : int, optional
+        Degree of the smoothing spline.  Must be ``1 <= k <= 5``. Default is
+        ``k = 3``, a cubic spline.
+    ext : int or str, optional
+        Controls the extrapolation mode for elements
+        not in the interval defined by the knot sequence.
+
+        * if ext=0 or 'extrapolate', return the extrapolated value.
+        * if ext=1 or 'zeros', return 0
+        * if ext=2 or 'raise', raise a ValueError
+        * if ext=3 of 'const', return the boundary value.
+
+        The default value is 0.
+
+    check_finite : bool, optional
+        Whether to check that the input arrays contain only finite numbers.
+        Disabling may give a performance gain, but may result in problems
+        (crashes, non-termination or non-sensical results) if the inputs
+        do contain infinities or NaNs.
+        Default is False.
+
+    See Also
+    --------
+    UnivariateSpline :
+        a smooth univariate spline to fit a given set of data points.
+    LSQUnivariateSpline :
+        a spline for which knots are user-selected
+    SmoothBivariateSpline :
+        a smoothing bivariate spline through the given points
+    LSQBivariateSpline :
+        a bivariate spline using weighted least-squares fitting
+    splrep :
+        a function to find the B-spline representation of a 1-D curve
+    splev :
+        a function to evaluate a B-spline or its derivatives
+    sproot :
+        a function to find the roots of a cubic B-spline
+    splint :
+        a function to evaluate the definite integral of a B-spline between two
+        given points
+    spalde :
+        a function to evaluate all derivatives of a B-spline
+
+    Notes
+    -----
+    The number of data points must be larger than the spline degree `k`.
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> import matplotlib.pyplot as plt
+    >>> from scipy.interpolate import InterpolatedUnivariateSpline
+    >>> rng = np.random.default_rng()
+    >>> x = np.linspace(-3, 3, 50)
+    >>> y = np.exp(-x**2) + 0.1 * rng.standard_normal(50)
+    >>> spl = InterpolatedUnivariateSpline(x, y)
+    >>> plt.plot(x, y, 'ro', ms=5)
+    >>> xs = np.linspace(-3, 3, 1000)
+    >>> plt.plot(xs, spl(xs), 'g', lw=3, alpha=0.7)
+    >>> plt.show()
+
+    Notice that the ``spl(x)`` interpolates `y`:
+
+    >>> spl.get_residual()
+    0.0
+
+    """
+
+    def __init__(self, x, y, w=None, bbox=[None]*2, k=3,
+                 ext=0, check_finite=False):
+
+        x, y, w, bbox, self.ext = self.validate_input(x, y, w, bbox, k, None,
+                                            ext, check_finite)
+        if not np.all(diff(x) > 0.0):
+            raise ValueError('x must be strictly increasing')
+
+        # _data == x,y,w,xb,xe,k,s,n,t,c,fp,fpint,nrdata,ier
+        self._data = _curfit(x, y, k, w=w, xb=bbox[0],
+                             xe=bbox[1], s=0, iopt=0)
+        self._reset_class()
+
+
+_fpchec_error_string = """The input parameters have been rejected by fpchec. \
+This means that at least one of the following conditions is violated:
+
+1) k+1 <= n-k-1 <= m
+2) t(1) <= t(2) <= ... <= t(k+1)
+   t(n-k) <= t(n-k+1) <= ... <= t(n)
+3) t(k+1) < t(k+2) < ... < t(n-k)
+4) t(k+1) <= x(i) <= t(n-k)
+5) The conditions specified by Schoenberg and Whitney must hold
+   for at least one subset of data points, i.e., there must be a
+   subset of data points y(j) such that
+       t(j) < y(j) < t(j+k+1), j=1,2,...,n-k-1
+"""
+
+
+@xp_capabilities(out_of_scope=True)
+class LSQUnivariateSpline(UnivariateSpline):
+    """
+    1-D spline with explicit internal knots.
+
+    .. legacy:: class
+
+        Specifically, we recommend using `make_lsq_spline` instead.
+
+
+    Fits a spline y = spl(x) of degree `k` to the provided `x`, `y` data.  `t`
+    specifies the internal knots of the spline
+
+    Parameters
+    ----------
+    x : (N,) array_like
+        Input dimension of data points -- must be increasing
+    y : (N,) array_like
+        Input dimension of data points
+    t : (M,) array_like
+        interior knots of the spline.  Must be in ascending order and::
+
+            bbox[0] < t[0] < ... < t[-1] < bbox[-1]
+
+    w : (N,) array_like, optional
+        weights for spline fitting. Must be positive. If None (default),
+        weights are all 1.
+    bbox : (2,) array_like, optional
+        2-sequence specifying the boundary of the approximation interval. If
+        None (default), ``bbox = [x[0], x[-1]]``.
+    k : int, optional
+        Degree of the smoothing spline.  Must be 1 <= `k` <= 5.
+        Default is `k` = 3, a cubic spline.
+    ext : int or str, optional
+        Controls the extrapolation mode for elements
+        not in the interval defined by the knot sequence.
+
+        * if ext=0 or 'extrapolate', return the extrapolated value.
+        * if ext=1 or 'zeros', return 0
+        * if ext=2 or 'raise', raise a ValueError
+        * if ext=3 of 'const', return the boundary value.
+
+        The default value is 0.
+
+    check_finite : bool, optional
+        Whether to check that the input arrays contain only finite numbers.
+        Disabling may give a performance gain, but may result in problems
+        (crashes, non-termination or non-sensical results) if the inputs
+        do contain infinities or NaNs.
+        Default is False.
+
+    Raises
+    ------
+    ValueError
+        If the interior knots do not satisfy the Schoenberg-Whitney conditions
+
+    See Also
+    --------
+    UnivariateSpline :
+        a smooth univariate spline to fit a given set of data points.
+    InterpolatedUnivariateSpline :
+        a interpolating univariate spline for a given set of data points.
+    splrep :
+        a function to find the B-spline representation of a 1-D curve
+    splev :
+        a function to evaluate a B-spline or its derivatives
+    sproot :
+        a function to find the roots of a cubic B-spline
+    splint :
+        a function to evaluate the definite integral of a B-spline between two
+        given points
+    spalde :
+        a function to evaluate all derivatives of a B-spline
+
+    Notes
+    -----
+    The number of data points must be larger than the spline degree `k`.
+
+    Knots `t` must satisfy the Schoenberg-Whitney conditions,
+    i.e., there must be a subset of data points ``x[j]`` such that
+    ``t[j] < x[j] < t[j+k+1]``, for ``j=0, 1,...,n-k-2``.
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy.interpolate import LSQUnivariateSpline, UnivariateSpline
+    >>> import matplotlib.pyplot as plt
+    >>> rng = np.random.default_rng()
+    >>> x = np.linspace(-3, 3, 50)
+    >>> y = np.exp(-x**2) + 0.1 * rng.standard_normal(50)
+
+    Fit a smoothing spline with a pre-defined internal knots:
+
+    >>> t = [-1, 0, 1]
+    >>> spl = LSQUnivariateSpline(x, y, t)
+
+    >>> xs = np.linspace(-3, 3, 1000)
+    >>> plt.plot(x, y, 'ro', ms=5)
+    >>> plt.plot(xs, spl(xs), 'g-', lw=3)
+    >>> plt.show()
+
+    Check the knot vector:
+
+    >>> spl.get_knots()
+    array([-3., -1., 0., 1., 3.])
+
+    Constructing lsq spline using the knots from another spline:
+
+    >>> x = np.arange(10)
+    >>> s = UnivariateSpline(x, x, s=0)
+    >>> s.get_knots()
+    array([ 0.,  2.,  3.,  4.,  5.,  6.,  7.,  9.])
+    >>> knt = s.get_knots()
+    >>> s1 = LSQUnivariateSpline(x, x, knt[1:-1])    # Chop 1st and last knot
+    >>> s1.get_knots()
+    array([ 0.,  2.,  3.,  4.,  5.,  6.,  7.,  9.])
+
+    """
+
+    def __init__(self, x, y, t, w=None, bbox=[None]*2, k=3,
+                 ext=0, check_finite=False):
+
+        x, y, w, bbox, self.ext = self.validate_input(x, y, w, bbox, k, None,
+                                                      ext, check_finite)
+        if not np.all(diff(x) >= 0.0):
+            raise ValueError('x must be increasing')
+
+        # _data == x,y,w,xb,xe,k,s,n,t,c,fp,fpint,nrdata,ier
+        xb = bbox[0]
+        xe = bbox[1]
+        if xb is None:
+            xb = x[0]
+        if xe is None:
+            xe = x[-1]
+        t = concatenate(([xb]*(k+1), t, [xe]*(k+1)))
+        n = len(t)
+        if not np.all(t[k+1:n-k]-t[k:n-k-1] > 0, axis=0):
+            raise ValueError('Interior knots t must satisfy '
+                             'Schoenberg-Whitney conditions')
+
+        ier = _fitpack.fpchec(x, t, k)
+        if not ier == 0:
+            raise ValueError(_fpchec_error_string)
+        data = _curfit(x, y, k, t=t, w=w, xb=xb, xe=xe, iopt=-1)
+        self._data = data[:-3] + (None, None, data[-1])
+        self._reset_class()
+
+
+# ############### Bivariate spline ####################
+
+class _BivariateSplineBase:
+    """ Base class for Bivariate spline s(x,y) interpolation on the rectangle
+    [xb,xe] x [yb, ye] calculated from a given set of data points
+    (x,y,z).
+
+    See Also
+    --------
+    bisplrep :
+        a function to find a bivariate B-spline representation of a surface
+    bisplev :
+        a function to evaluate a bivariate B-spline and its derivatives
+    BivariateSpline :
+        a base class for bivariate splines.
+    SphereBivariateSpline :
+        a bivariate spline on a spherical grid
+    """
+
+    @classmethod
+    def _from_tck(cls, tck):
+        """Construct a spline object from given tck and degree"""
+        self = cls.__new__(cls)
+        if len(tck) != 5:
+            raise ValueError("tck should be a 5 element tuple of tx,"
+                             " ty, c, kx, ky")
+        self.tck = tck[:3]
+        self.degrees = tck[3:]
+        return self
+
+    def get_residual(self):
+        """Return weighted sum of squared residuals of the spline approximation.
+
+        This is given by::
+
+            sum ((w[i]*(z[i]-s(x[i],y[i])))**2,axis=0)
+
+        Returns
+        -------
+        float
+            Weighted sum of squared residuals of the spline approximation.
+        """
+        return self.fp
+
+    def get_knots(self):
+        """ Return a tuple (tx,ty) where tx,ty contain knots positions
+        of the spline with respect to x-, y-variable, respectively.
+        The position of interior and additional knots are given as
+        t[k+1:-k-1] and t[:k+1]=b, t[-k-1:]=e, respectively.
+
+        Returns
+        -------
+        tuple of 1D arrays
+            Spline knots with respect to x- and y-variable.
+        """
+        return self.tck[:2]
+
+    def get_coeffs(self):
+        """ Return spline coefficients.
+
+        Returns
+        -------
+        1D array
+            Spline coefficients.
+        """
+        return self.tck[2]
+
+    def __call__(self, x, y, dx=0, dy=0, grid=True):
+        """
+        Evaluate the spline or its derivatives at given positions.
+
+        Parameters
+        ----------
+        x, y : array_like
+            Input coordinates.
+
+            If `grid` is False, evaluate the spline at points ``(x[i],
+            y[i]), i=0, ..., len(x)-1``.  Standard Numpy broadcasting
+            is obeyed.
+
+            If `grid` is True: evaluate spline at the grid points
+            defined by the coordinate arrays x, y. The arrays must be
+            sorted to increasing order.
+
+            The ordering of axes is consistent with
+            ``np.meshgrid(..., indexing="ij")`` and inconsistent with the
+            default ordering ``np.meshgrid(..., indexing="xy")``.
+        dx : int
+            Order of x-derivative
+
+            .. versionadded:: 0.14.0
+        dy : int
+            Order of y-derivative
+
+            .. versionadded:: 0.14.0
+        grid : bool
+            Whether to evaluate the results on a grid spanned by the
+            input arrays, or at points specified by the input arrays.
+
+            .. versionadded:: 0.14.0
+
+        Examples
+        --------
+        Suppose that we want to bilinearly interpolate an exponentially decaying
+        function in 2 dimensions.
+
+        >>> import numpy as np
+        >>> from scipy.interpolate import RectBivariateSpline
+
+        We sample the function on a coarse grid. Note that the default indexing="xy"
+        of meshgrid would result in an unexpected (transposed) result after
+        interpolation.
+
+        >>> xarr = np.linspace(-3, 3, 100)
+        >>> yarr = np.linspace(-3, 3, 100)
+        >>> xgrid, ygrid = np.meshgrid(xarr, yarr, indexing="ij")
+
+        The function to interpolate decays faster along one axis than the other.
+
+        >>> zdata = np.exp(-np.sqrt((xgrid / 2) ** 2 + ygrid**2))
+
+        Next we sample on a finer grid using interpolation (kx=ky=1 for bilinear).
+
+        >>> rbs = RectBivariateSpline(xarr, yarr, zdata, kx=1, ky=1)
+        >>> xarr_fine = np.linspace(-3, 3, 200)
+        >>> yarr_fine = np.linspace(-3, 3, 200)
+        >>> xgrid_fine, ygrid_fine = np.meshgrid(xarr_fine, yarr_fine, indexing="ij")
+        >>> zdata_interp = rbs(xgrid_fine, ygrid_fine, grid=False)
+
+        And check that the result agrees with the input by plotting both.
+
+        >>> import matplotlib.pyplot as plt
+        >>> fig = plt.figure()
+        >>> ax1 = fig.add_subplot(1, 2, 1, aspect="equal")
+        >>> ax2 = fig.add_subplot(1, 2, 2, aspect="equal")
+        >>> ax1.imshow(zdata)
+        >>> ax2.imshow(zdata_interp)
+        >>> plt.show()
+        """
+        x = np.asarray(x)
+        y = np.asarray(y)
+        # backwards compat, cf https://github.com/scipy/scipy/issues/25471
+        needs_squeeze = (x.ndim == 0) and (y.ndim == 0)
+
+        x = np.atleast_1d(x)
+        y = np.atleast_1d(y)
+
+        tx, ty, c = self.tck[:3]
+        kx, ky = self.degrees
+        if grid:
+            x = x.ravel()
+            y = y.ravel()
+            if x.size == 0 or y.size == 0:
+                return np.zeros((x.size, y.size), dtype=self.tck[2].dtype)
+
+            if (x.size >= 2) and (not np.all(np.diff(x) >= 0.0)):
+                raise ValueError("x must be strictly increasing when `grid` is True")
+            if (y.size >= 2) and (not np.all(np.diff(y) >= 0.0)):
+                raise ValueError("y must be strictly increasing when `grid` is True")
+
+            if dx or dy:
+                z, ier = _fitpack.parder(tx, ty, c, kx, ky, dx, dy, x, y)
+                if not ier == 0:
+                    raise ValueError(f"Error code returned by parder: {ier}")
+            else:
+                z, ier = _fitpack.bispev(tx, ty, c, kx, ky, x, y)
+                if not ier == 0:
+                    raise ValueError(f"Error code returned by bispev: {ier}")
+        else:
+            # standard Numpy broadcasting
+            if x.shape != y.shape:
+                x, y = np.broadcast_arrays(x, y)
+
+            shape = x.shape
+            x = x.ravel()
+            y = y.ravel()
+            if x.size == 0 or y.size == 0:
+                return np.zeros(shape, dtype=self.tck[2].dtype)
+
+            if dx or dy:
+                z, ier = _fitpack.pardeu(tx, ty, c, kx, ky, dx, dy, x, y)
+                if not ier == 0:
+                    raise ValueError(f"Error code returned by pardeu: {ier}")
+            else:
+                z, ier = _fitpack.bispeu(tx, ty, c, kx, ky, x, y)
+                if not ier == 0:
+                    raise ValueError(f"Error code returned by bispeu: {ier}")
+
+            z = z.reshape(shape)
+
+            if needs_squeeze:
+                z = z.squeeze()
+
+        return z
+
+    def partial_derivative(self, dx, dy):
+        """Construct a new spline representing a partial derivative of this
+        spline.
+
+        Parameters
+        ----------
+        dx, dy : int
+            Orders of the derivative in x and y respectively. They must be
+            non-negative integers and less than the respective degree of the
+            original spline (self) in that direction (``kx``, ``ky``).
+
+        Returns
+        -------
+        spline :
+            A new spline of degrees (``kx - dx``, ``ky - dy``) representing the
+            derivative of this spline.
+
+        Notes
+        -----
+
+        .. versionadded:: 1.9.0
+
+        """
+        if dx == 0 and dy == 0:
+            return self
+        else:
+            kx, ky = self.degrees
+            if not (dx >= 0 and dy >= 0):
+                raise ValueError("order of derivative must be positive or"
+                                 " zero")
+            if not (dx < kx and dy < ky):
+                raise ValueError("order of derivative must be less than"
+                                 " degree of spline")
+            tx, ty, c = self.tck[:3]
+            newc, ier = _fitpack.pardtc(tx, ty, c, kx, ky, dx, dy)
+            if ier != 0:
+                # This should not happen under normal conditions.
+                raise ValueError(f"Unexpected error code returned by pardtc: {ier}")
+            nx = len(tx)
+            ny = len(ty)
+            newtx = tx[dx:nx - dx]
+            newty = ty[dy:ny - dy]
+            newkx, newky = kx - dx, ky - dy
+            newclen = (nx - dx - kx - 1) * (ny - dy - ky - 1)
+            return _DerivedBivariateSpline._from_tck((newtx, newty,
+                                                      newc[:newclen],
+                                                      newkx, newky))
+
+
+_surfit_messages = {1: """
+The required storage space exceeds the available storage space: nxest
+or nyest too small, or s too small.
+The weighted least-squares spline corresponds to the current set of
+knots.""",
+                    2: """
+A theoretically impossible result was found during the iteration
+process for finding a smoothing spline with fp = s: s too small or
+badly chosen eps.
+Weighted sum of squared residuals does not satisfy abs(fp-s)/s < tol.""",
+                    3: """
+the maximal number of iterations maxit (set to 20 by the program)
+allowed for finding a smoothing spline with fp=s has been reached:
+s too small.
+Weighted sum of squared residuals does not satisfy abs(fp-s)/s < tol.
+Try increasing maxit by passing it as a keyword argument.""",
+                    4: """
+No more knots can be added because the number of b-spline coefficients
+(nx-kx-1)*(ny-ky-1) already exceeds the number of data points m:
+either s or m too small.
+The weighted least-squares spline corresponds to the current set of
+knots.""",
+                    5: """
+No more knots can be added because the additional knot would (quasi)
+coincide with an old one: s too small or too large a weight to an
+inaccurate data point.
+The weighted least-squares spline corresponds to the current set of
+knots.""",
+                    10: """
+Error on entry, no approximation returned. The following conditions
+must hold:
+xb<=x[i]<=xe, yb<=y[i]<=ye, w[i]>0, i=0..m-1
+If iopt==-1, then
+  xb>> import numpy as np
+        >>> from scipy.interpolate import RectBivariateSpline
+        >>> def f(x, y):
+        ...     return np.exp(-np.sqrt((x / 2) ** 2 + y**2))
+
+        We sample the function on a coarse grid and set up the interpolator. Note that
+        the default ``indexing="xy"`` of meshgrid would result in an unexpected
+        (transposed) result after interpolation.
+
+        >>> xarr = np.linspace(-3, 3, 21)
+        >>> yarr = np.linspace(-3, 3, 21)
+        >>> xgrid, ygrid = np.meshgrid(xarr, yarr, indexing="ij")
+        >>> zdata = f(xgrid, ygrid)
+        >>> rbs = RectBivariateSpline(xarr, yarr, zdata, kx=1, ky=1)
+
+        Next we sample the function along a diagonal slice through the coordinate space
+        on a finer grid using interpolation.
+
+        >>> xinterp = np.linspace(-3, 3, 201)
+        >>> yinterp = np.linspace(3, -3, 201)
+        >>> zinterp = rbs.ev(xinterp, yinterp)
+
+        And check that the interpolation passes through the function evaluations as a
+        function of the distance from the origin along the slice.
+
+        >>> import matplotlib.pyplot as plt
+        >>> fig = plt.figure()
+        >>> ax1 = fig.add_subplot(1, 1, 1)
+        >>> ax1.plot(np.sqrt(xarr**2 + yarr**2), np.diag(zdata), "or")
+        >>> ax1.plot(np.sqrt(xinterp**2 + yinterp**2), zinterp, "-b")
+        >>> plt.show()
+        """
+        return self.__call__(xi, yi, dx=dx, dy=dy, grid=False)
+
+    def integral(self, xa, xb, ya, yb):
+        """
+        Evaluate the integral of the spline over area [xa,xb] x [ya,yb].
+
+        Parameters
+        ----------
+        xa, xb : float
+            The end-points of the x integration interval.
+        ya, yb : float
+            The end-points of the y integration interval.
+
+        Returns
+        -------
+        integ : float
+            The value of the resulting integral.
+
+        """
+        tx, ty, c = self.tck[:3]
+        kx, ky = self.degrees
+        return _fitpack.dblint(tx, ty, c, kx, ky, xa, xb, ya, yb)
+
+    @staticmethod
+    def _validate_input(x, y, z, w, kx, ky, eps):
+        x, y, z = np.asarray(x), np.asarray(y), np.asarray(z)
+        if not x.size == y.size == z.size:
+            raise ValueError('x, y, and z should have a same length')
+
+        if w is not None:
+            w = np.asarray(w)
+            if x.size != w.size:
+                raise ValueError('x, y, z, and w should have a same length')
+            elif not np.all(w >= 0.0):
+                raise ValueError('w should be positive')
+        if (eps is not None) and (not 0.0 < eps < 1.0):
+            raise ValueError('eps should be between (0, 1)')
+        if not x.size >= (kx + 1) * (ky + 1):
+            raise ValueError('The length of x, y and z should be at least'
+                             ' (kx+1) * (ky+1)')
+        return x, y, z, w
+
+
+class _DerivedBivariateSpline(_BivariateSplineBase):
+    """Bivariate spline constructed from the coefficients and knots of another
+    spline.
+
+    Notes
+    -----
+    The class is not meant to be instantiated directly from the data to be
+    interpolated or smoothed. As a result, its ``fp`` attribute and
+    ``get_residual`` method are inherited but overridden; ``AttributeError`` is
+    raised when they are accessed.
+
+    The other inherited attributes can be used as usual.
+    """
+    _invalid_why = ("is unavailable, because _DerivedBivariateSpline"
+                    " instance is not constructed from data that are to be"
+                    " interpolated or smoothed, but derived from the"
+                    " underlying knots and coefficients of another spline"
+                    " object")
+
+    @property
+    def fp(self):
+        raise AttributeError(f"attribute \"fp\" {self._invalid_why}")
+
+    def get_residual(self):
+        raise AttributeError(f"method \"get_residual\" {self._invalid_why}")
+
+
+@xp_capabilities(out_of_scope=True)
+class SmoothBivariateSpline(BivariateSpline):
+    """
+    Smooth bivariate spline approximation.
+
+    Parameters
+    ----------
+    x, y, z : array_like
+        1-D sequences of data points (order is not important).
+    w : array_like, optional
+        Positive 1-D sequence of weights, of same length as `x`, `y` and `z`.
+    bbox : array_like, optional
+        Sequence of length 4 specifying the boundary of the rectangular
+        approximation domain.  By default,
+        ``bbox=[min(x), max(x), min(y), max(y)]``.
+    kx, ky : ints, optional
+        Degrees of the bivariate spline. Default is 3.
+    s : float, optional
+        Positive smoothing factor defined for estimation condition:
+        ``sum((w[i]*(z[i]-s(x[i], y[i])))**2, axis=0) <= s``
+        Default ``s=len(w)`` which should be a good value if ``1/w[i]`` is an
+        estimate of the standard deviation of ``z[i]``.
+    eps : float, optional
+        A threshold for determining the effective rank of an over-determined
+        linear system of equations. `eps` should have a value within the open
+        interval ``(0, 1)``, the default is 1e-16.
+
+    See Also
+    --------
+    BivariateSpline :
+        a base class for bivariate splines.
+    UnivariateSpline :
+        a smooth univariate spline to fit a given set of data points.
+    LSQBivariateSpline :
+        a bivariate spline using weighted least-squares fitting
+    RectSphereBivariateSpline :
+        a bivariate spline over a rectangular mesh on a sphere
+    SmoothSphereBivariateSpline :
+        a smoothing bivariate spline in spherical coordinates
+    LSQSphereBivariateSpline :
+        a bivariate spline in spherical coordinates using weighted
+        least-squares fitting
+    RectBivariateSpline :
+        a bivariate spline over a rectangular mesh
+    bisplrep :
+        a function to find a bivariate B-spline representation of a surface
+    bisplev :
+        a function to evaluate a bivariate B-spline and its derivatives
+
+    Notes
+    -----
+    The length of `x`, `y` and `z` should be at least ``(kx+1) * (ky+1)``.
+
+    If the input data is such that input dimensions have incommensurate
+    units and differ by many orders of magnitude, the interpolant may have
+    numerical artifacts. Consider rescaling the data before interpolating.
+
+    This routine constructs spline knot vectors automatically via the FITPACK
+    algorithm. The spline knots may be placed away from the data points. For
+    some data sets, this routine may fail to construct an interpolating spline,
+    even if one is requested via ``s=0`` parameter. In such situations, it is
+    recommended to use `bisplrep` / `bisplev` directly instead of this routine
+    and, if needed, increase the values of ``nxest`` and ``nyest`` parameters
+    of `bisplrep`.
+
+    For linear interpolation, `LinearNDInterpolator` is preferred.
+    Consult the :ref:`interp-transition-guide` for discussion.
+
+    """
+
+    def __init__(self, x, y, z, w=None, bbox=[None] * 4, kx=3, ky=3, s=None,
+                 eps=1e-16):
+
+        x, y, z, w = self._validate_input(x, y, z, w, kx, ky, eps)
+        bbox = ravel(bbox)
+        if not bbox.shape == (4,):
+            raise ValueError('bbox shape should be (4,)')
+        if s is not None and not s >= 0.0:
+            raise ValueError("s should be s >= 0.0")
+
+        xb, xe, yb, ye = bbox
+
+        nx, tx, ny, ty, c, fp, ier = _surfit_smth(
+            x, y, z, w, xb, xe, yb, ye, kx, ky, s, eps)
+
+        if ier in [0, -1, -2]:  # normal return
+            pass
+        else:
+            message = _surfit_messages.get(ier, f'ier={ier}')
+            warnings.warn(message, stacklevel=2)
+
+        self.fp = fp
+        self.tck = tx[:nx], ty[:ny], c[:(nx-kx-1)*(ny-ky-1)]
+        self.degrees = kx, ky
+
+
+@xp_capabilities(out_of_scope=True)
+class LSQBivariateSpline(BivariateSpline):
+    """
+    Weighted least-squares bivariate spline approximation.
+
+    Parameters
+    ----------
+    x, y, z : array_like
+        1-D sequences of data points (order is not important).
+    tx, ty : array_like
+        Strictly ordered 1-D sequences of knots coordinates.
+    w : array_like, optional
+        Positive 1-D array of weights, of the same length as `x`, `y` and `z`.
+    bbox : (4,) array_like, optional
+        Sequence of length 4 specifying the boundary of the rectangular
+        approximation domain.  By default,
+        ``bbox=[min(x,tx),max(x,tx), min(y,ty),max(y,ty)]``.
+    kx, ky : ints, optional
+        Degrees of the bivariate spline. Default is 3.
+    eps : float, optional
+        A threshold for determining the effective rank of an over-determined
+        linear system of equations. `eps` should have a value within the open
+        interval ``(0, 1)``, the default is 1e-16.
+
+    See Also
+    --------
+    BivariateSpline :
+        a base class for bivariate splines.
+    UnivariateSpline :
+        a smooth univariate spline to fit a given set of data points.
+    SmoothBivariateSpline :
+        a smoothing bivariate spline through the given points
+    RectSphereBivariateSpline :
+        a bivariate spline over a rectangular mesh on a sphere
+    SmoothSphereBivariateSpline :
+        a smoothing bivariate spline in spherical coordinates
+    LSQSphereBivariateSpline :
+        a bivariate spline in spherical coordinates using weighted
+        least-squares fitting
+    RectBivariateSpline :
+        a bivariate spline over a rectangular mesh.
+    bisplrep :
+        a function to find a bivariate B-spline representation of a surface
+    bisplev :
+        a function to evaluate a bivariate B-spline and its derivatives
+
+    Notes
+    -----
+    The length of `x`, `y` and `z` should be at least ``(kx+1) * (ky+1)``.
+
+    If the input data is such that input dimensions have incommensurate
+    units and differ by many orders of magnitude, the interpolant may have
+    numerical artifacts. Consider rescaling the data before interpolating.
+
+    """
+
+    def __init__(self, x, y, z, tx, ty, w=None, bbox=[None]*4, kx=3, ky=3,
+                 eps=None):
+
+        x, y, z, w = self._validate_input(x, y, z, w, kx, ky, eps)
+        bbox = ravel(bbox)
+        if not bbox.shape == (4,):
+            raise ValueError('bbox shape should be (4,)')
+
+        # Compute bbox defaults if needed (before setting up tx1/ty1)
+        xb, xe, yb, ye = bbox
+
+        nx = 2*kx+2+len(tx)
+        ny = 2*ky+2+len(ty)
+        # The Fortran subroutine "surfit" (called as _surfit_lsq)
+        # requires that the knot arrays passed as input should be "real
+        # array(s) of dimension nmax" where "nmax" refers to the greater of nx
+        # and ny. We pad the tx1/ty1 arrays here so that this is satisfied, and
+        # slice them to the desired sizes upon return.
+        nmax = max(nx, ny)
+        tx1 = zeros((nmax,), float)
+        ty1 = zeros((nmax,), float)
+        tx1[kx+1:nx-kx-1] = tx
+        ty1[ky+1:ny-ky-1] = ty
+
+        if xb is None:
+            xb = _calc_b(x, tx1)
+        if xe is None:
+            xe = _calc_e(x, tx1)
+        if yb is None:
+            yb = _calc_b(y, ty1)
+        if ye is None:
+            ye = _calc_e(y, ty1)
+
+        tx1, ty1, c, fp, ier = _surfit_lsq(x, y, z, nx, tx1, ny, ty1, w,
+                                           xb, xe, yb, ye, kx, ky, eps)
+
+        if ier in [0, -1, -2]:  # normal return
+            pass
+        else:
+            if ier < -2:
+                deficiency = (nx-kx-1)*(ny-ky-1)+ier
+                message = _surfit_messages.get(-3) % (deficiency)
+            else:
+                message = _surfit_messages.get(ier, f'ier={ier}')
+            warnings.warn(message, stacklevel=2)
+        self.fp = fp
+        self.tck = tx1[:nx], ty1[:ny], c
+        self.degrees = kx, ky
+
+
+@xp_capabilities(out_of_scope=True)
+class RectBivariateSpline(BivariateSpline):
+    """
+    Bivariate spline approximation over a rectangular mesh.
+
+    Can be used for both smoothing and interpolating data.
+
+    Parameters
+    ----------
+    x, y : array_like
+        1-D arrays of coordinates in strictly ascending order.
+        Evaluated points outside the data range will be extrapolated.
+    z : array_like
+        2-D array of data with shape (x.size,y.size).
+    bbox : array_like, optional
+        Sequence of length 4 specifying the boundary of the rectangular
+        approximation domain, which means the start and end spline knots of
+        each dimension are set by these values. By default,
+        ``bbox=[min(x), max(x), min(y), max(y)]``.
+    kx, ky : ints, optional
+        Degrees of the bivariate spline. Default is 3.
+    s : float, optional
+        Positive smoothing factor defined for estimation condition:
+        ``sum((z[i]-f(x[i], y[i]))**2, axis=0) <= s`` where f is a spline
+        function. Default is ``s=0``, which is for interpolation.
+    maxit : int, optional
+        The maximal number of iterations maxit allowed for finding a
+        smoothing spline with fp=s. Default is ``maxit=20``.
+
+    See Also
+    --------
+    BivariateSpline :
+        a base class for bivariate splines.
+    UnivariateSpline :
+        a smooth univariate spline to fit a given set of data points.
+    SmoothBivariateSpline :
+        a smoothing bivariate spline through the given points
+    LSQBivariateSpline :
+        a bivariate spline using weighted least-squares fitting
+    RectSphereBivariateSpline :
+        a bivariate spline over a rectangular mesh on a sphere
+    SmoothSphereBivariateSpline :
+        a smoothing bivariate spline in spherical coordinates
+    LSQSphereBivariateSpline :
+        a bivariate spline in spherical coordinates using weighted
+        least-squares fitting
+    bisplrep :
+        a function to find a bivariate B-spline representation of a surface
+    bisplev :
+        a function to evaluate a bivariate B-spline and its derivatives
+
+    Notes
+    -----
+
+    If the input data is such that input dimensions have incommensurate
+    units and differ by many orders of magnitude, the interpolant may have
+    numerical artifacts. Consider rescaling the data before interpolating.
+
+    """
+
+    def __init__(self, x, y, z, bbox=[None] * 4, kx=3, ky=3, s=0, maxit=20):
+        x, y, bbox = ravel(x), ravel(y), ravel(bbox)
+        z = np.asarray(z)
+        if not np.all(diff(x) > 0.0):
+            raise ValueError('x must be strictly increasing')
+        if not np.all(diff(y) > 0.0):
+            raise ValueError('y must be strictly increasing')
+        if not x.size == z.shape[0]:
+            raise ValueError('x dimension of z must have same number of '
+                             'elements as x')
+        if not y.size == z.shape[1]:
+            raise ValueError('y dimension of z must have same number of '
+                             'elements as y')
+        if not bbox.shape == (4,):
+            raise ValueError('bbox shape should be (4,)')
+        if s is not None and not s >= 0.0:
+            raise ValueError("s should be s >= 0.0")
+
+        z = ravel(z)
+        xb, xe, yb, ye = bbox
+        nx, tx, ny, ty, c, fp, ier = _regrid_smth(x, y, z, xb, xe, yb,
+                                                  ye, kx, ky, s, maxit)
+
+        if ier not in [0, -1, -2]:
+            msg = _surfit_messages.get(ier, f'ier={ier}')
+            raise ValueError(msg)
+
+        self.fp = fp
+        self.tck = tx[:nx], ty[:ny], c[:(nx - kx - 1) * (ny - ky - 1)]
+        self.degrees = kx, ky
+
+
+_spherefit_messages = _surfit_messages.copy()
+_spherefit_messages[10] = """
+ERROR. On entry, the input data are controlled on validity. The following
+       restrictions must be satisfied:
+            -1<=iopt<=1,  m>=2, ntest>=8 ,npest >=8, 00, i=1,...,m
+            lwrk1 >= 185+52*v+10*u+14*u*v+8*(u-1)*v**2+8*m
+            kwrk >= m+(ntest-7)*(npest-7)
+            if iopt=-1: 8<=nt<=ntest , 9<=np<=npest
+                        0=0: s>=0
+            if one of these conditions is found to be violated,control
+            is immediately repassed to the calling program. in that
+            case there is no approximation returned."""
+_spherefit_messages[-3] = """
+WARNING. The coefficients of the spline returned have been computed as the
+         minimal norm least-squares solution of a (numerically) rank
+         deficient system (deficiency=%i, rank=%i). Especially if the rank
+         deficiency, which is computed by 6+(nt-8)*(np-7)+ier, is large,
+         the results may be inaccurate. They could also seriously depend on
+         the value of eps."""
+
+
+@xp_capabilities(out_of_scope=True)
+class SphereBivariateSpline(_BivariateSplineBase):
+    """
+    Bivariate spline s(x,y) of degrees 3 on a sphere, calculated from a
+    given set of data points (theta,phi,r).
+
+    .. versionadded:: 0.11.0
+
+    See Also
+    --------
+    bisplrep :
+        a function to find a bivariate B-spline representation of a surface
+    bisplev :
+        a function to evaluate a bivariate B-spline and its derivatives
+    UnivariateSpline :
+        a smooth univariate spline to fit a given set of data points.
+    SmoothBivariateSpline :
+        a smoothing bivariate spline through the given points
+    LSQUnivariateSpline :
+        a univariate spline using weighted least-squares fitting
+    """
+
+    def __call__(self, theta, phi, dtheta=0, dphi=0, grid=True):
+        """
+        Evaluate the spline or its derivatives at given positions.
+
+        Parameters
+        ----------
+        theta, phi : array_like
+            Input coordinates.
+
+            If `grid` is False, evaluate the spline at points
+            ``(theta[i], phi[i]), i=0, ..., len(x)-1``.  Standard
+            Numpy broadcasting is obeyed.
+
+            If `grid` is True: evaluate spline at the grid points
+            defined by the coordinate arrays theta, phi. The arrays
+            must be sorted to increasing order.
+            The ordering of axes is consistent with
+            ``np.meshgrid(..., indexing="ij")`` and inconsistent with the
+            default ordering ``np.meshgrid(..., indexing="xy")``.
+        dtheta : int, optional
+            Order of theta-derivative
+
+            .. versionadded:: 0.14.0
+        dphi : int
+            Order of phi-derivative
+
+            .. versionadded:: 0.14.0
+        grid : bool
+            Whether to evaluate the results on a grid spanned by the
+            input arrays, or at points specified by the input arrays.
+
+            .. versionadded:: 0.14.0
+
+        Examples
+        --------
+
+        Suppose that we want to use splines to interpolate a bivariate function on a
+        sphere. The value of the function is known on a grid of longitudes and
+        colatitudes.
+
+        >>> import numpy as np
+        >>> from scipy.interpolate import RectSphereBivariateSpline
+        >>> def f(theta, phi):
+        ...     return np.sin(theta) * np.cos(phi)
+
+        We evaluate the function on the grid. Note that the default indexing="xy"
+        of meshgrid would result in an unexpected (transposed) result after
+        interpolation.
+
+        >>> thetaarr = np.linspace(0, np.pi, 22)[1:-1]
+        >>> phiarr = np.linspace(0, 2 * np.pi, 21)[:-1]
+        >>> thetagrid, phigrid = np.meshgrid(thetaarr, phiarr, indexing="ij")
+        >>> zdata = f(thetagrid, phigrid)
+
+        We next set up the interpolator and use it to evaluate the function
+        on a finer grid.
+
+        >>> rsbs = RectSphereBivariateSpline(thetaarr, phiarr, zdata)
+        >>> thetaarr_fine = np.linspace(0, np.pi, 200)
+        >>> phiarr_fine = np.linspace(0, 2 * np.pi, 200)
+        >>> zdata_fine = rsbs(thetaarr_fine, phiarr_fine)
+
+        Finally we plot the coarsly-sampled input data alongside the
+        finely-sampled interpolated data to check that they agree.
+
+        >>> import matplotlib.pyplot as plt
+        >>> fig = plt.figure()
+        >>> ax1 = fig.add_subplot(1, 2, 1)
+        >>> ax2 = fig.add_subplot(1, 2, 2)
+        >>> ax1.imshow(zdata)
+        >>> ax2.imshow(zdata_fine)
+        >>> plt.show()
+        """
+        theta = np.asarray(theta)
+        phi = np.asarray(phi)
+
+        if theta.size > 0 and (theta.min() < 0. or theta.max() > np.pi):
+            raise ValueError("requested theta out of bounds.")
+
+        return _BivariateSplineBase.__call__(self, theta, phi,
+                                             dx=dtheta, dy=dphi, grid=grid)
+
+    def ev(self, theta, phi, dtheta=0, dphi=0):
+        """
+        Evaluate the spline at points.
+
+        Returns the interpolated value at ``(theta[i], phi[i]),
+        i=0,...,len(theta)-1``.
+
+        Parameters
+        ----------
+        theta, phi : array_like
+            Input coordinates. Standard Numpy broadcasting is obeyed.
+            The ordering of axes is consistent with
+            np.meshgrid(..., indexing="ij") and inconsistent with the
+            default ordering np.meshgrid(..., indexing="xy").
+        dtheta : int, optional
+            Order of theta-derivative
+
+            .. versionadded:: 0.14.0
+        dphi : int, optional
+            Order of phi-derivative
+
+            .. versionadded:: 0.14.0
+
+        Returns
+        -------
+        z : ndarray
+            Evaluated values. Shape is the result of broadcasting `theta` and `phi`.
+
+        Examples
+        --------
+        Suppose that we want to use splines to interpolate a bivariate function on a
+        sphere. The value of the function is known on a grid of longitudes and
+        colatitudes.
+
+        >>> import numpy as np
+        >>> from scipy.interpolate import RectSphereBivariateSpline
+        >>> def f(theta, phi):
+        ...     return np.sin(theta) * np.cos(phi)
+
+        We evaluate the function on the grid. Note that the default indexing="xy"
+        of meshgrid would result in an unexpected (transposed) result after
+        interpolation.
+
+        >>> thetaarr = np.linspace(0, np.pi, 22)[1:-1]
+        >>> phiarr = np.linspace(0, 2 * np.pi, 21)[:-1]
+        >>> thetagrid, phigrid = np.meshgrid(thetaarr, phiarr, indexing="ij")
+        >>> zdata = f(thetagrid, phigrid)
+
+        We next set up the interpolator and use it to evaluate the function
+        at points not on the original grid.
+
+        >>> rsbs = RectSphereBivariateSpline(thetaarr, phiarr, zdata)
+        >>> thetainterp = np.linspace(thetaarr[0], thetaarr[-1], 200)
+        >>> phiinterp = np.linspace(phiarr[0], phiarr[-1], 200)
+        >>> zinterp = rsbs.ev(thetainterp, phiinterp)
+
+        Finally we plot the original data for a diagonal slice through the
+        initial grid, and the spline approximation along the same slice.
+
+        >>> import matplotlib.pyplot as plt
+        >>> fig = plt.figure()
+        >>> ax1 = fig.add_subplot(1, 1, 1)
+        >>> ax1.plot(np.sin(thetaarr) * np.sin(phiarr), np.diag(zdata), "or")
+        >>> ax1.plot(np.sin(thetainterp) * np.sin(phiinterp), zinterp, "-b")
+        >>> plt.show()
+        """
+        return self.__call__(theta, phi, dtheta=dtheta, dphi=dphi, grid=False)
+
+
+@xp_capabilities(out_of_scope=True)
+class SmoothSphereBivariateSpline(SphereBivariateSpline):
+    """
+    Smooth bivariate spline approximation in spherical coordinates.
+
+    .. versionadded:: 0.11.0
+
+    Parameters
+    ----------
+    theta, phi, r : array_like
+        1-D sequences of data points (order is not important). Coordinates
+        must be given in radians. Theta must lie within the interval
+        ``[0, pi]``, and phi must lie within the interval ``[0, 2pi]``.
+    w : array_like, optional
+        Positive 1-D sequence of weights.
+    s : float, optional
+        Positive smoothing factor defined for estimation condition:
+        ``sum((w(i)*(r(i) - s(theta(i), phi(i))))**2, axis=0) <= s``
+        Default ``s=len(w)`` which should be a good value if ``1/w[i]`` is an
+        estimate of the standard deviation of ``r[i]``.
+    eps : float, optional
+        A threshold for determining the effective rank of an over-determined
+        linear system of equations. `eps` should have a value within the open
+        interval ``(0, 1)``, the default is 1e-16.
+
+    See Also
+    --------
+    BivariateSpline :
+        a base class for bivariate splines.
+    UnivariateSpline :
+        a smooth univariate spline to fit a given set of data points.
+    SmoothBivariateSpline :
+        a smoothing bivariate spline through the given points
+    LSQBivariateSpline :
+        a bivariate spline using weighted least-squares fitting
+    RectSphereBivariateSpline :
+        a bivariate spline over a rectangular mesh on a sphere
+    LSQSphereBivariateSpline :
+        a bivariate spline in spherical coordinates using weighted
+        least-squares fitting
+    RectBivariateSpline :
+        a bivariate spline over a rectangular mesh.
+    bisplrep :
+        a function to find a bivariate B-spline representation of a surface
+    bisplev :
+        a function to evaluate a bivariate B-spline and its derivatives
+
+    Notes
+    -----
+    For more information, see the FITPACK_ site about this function.
+
+    .. _FITPACK: http://www.netlib.org/dierckx/sphere.f
+
+    Examples
+    --------
+    Suppose we have global data on a coarse grid (the input data does not
+    have to be on a grid):
+
+    >>> import numpy as np
+    >>> theta = np.linspace(0., np.pi, 7)
+    >>> phi = np.linspace(0., 2*np.pi, 9)
+    >>> data = np.empty((theta.shape[0], phi.shape[0]))
+    >>> data[:,0], data[0,:], data[-1,:] = 0., 0., 0.
+    >>> data[1:-1,1], data[1:-1,-1] = 1., 1.
+    >>> data[1,1:-1], data[-2,1:-1] = 1., 1.
+    >>> data[2:-2,2], data[2:-2,-2] = 2., 2.
+    >>> data[2,2:-2], data[-3,2:-2] = 2., 2.
+    >>> data[3,3:-2] = 3.
+    >>> data = np.roll(data, 4, 1)
+
+    We need to set up the interpolator object
+
+    >>> lats, lons = np.meshgrid(theta, phi)
+    >>> from scipy.interpolate import SmoothSphereBivariateSpline
+    >>> lut = SmoothSphereBivariateSpline(lats.ravel(), lons.ravel(),
+    ...                                   data.T.ravel(), s=3.5)
+
+    As a first test, we'll see what the algorithm returns when run on the
+    input coordinates
+
+    >>> data_orig = lut(theta, phi)
+
+    Finally we interpolate the data to a finer grid
+
+    >>> fine_lats = np.linspace(0., np.pi, 70)
+    >>> fine_lons = np.linspace(0., 2 * np.pi, 90)
+
+    >>> data_smth = lut(fine_lats, fine_lons)
+
+    >>> import matplotlib.pyplot as plt
+    >>> fig = plt.figure()
+    >>> ax1 = fig.add_subplot(131)
+    >>> ax1.imshow(data, interpolation='nearest')
+    >>> ax2 = fig.add_subplot(132)
+    >>> ax2.imshow(data_orig, interpolation='nearest')
+    >>> ax3 = fig.add_subplot(133)
+    >>> ax3.imshow(data_smth, interpolation='nearest')
+    >>> plt.show()
+
+    """
+
+    def __init__(self, theta, phi, r, w=None, s=0., eps=1E-16):
+
+        theta, phi, r = np.asarray(theta), np.asarray(phi), np.asarray(r)
+
+        # input validation
+        if not ((0.0 <= theta).all() and (theta <= np.pi).all()):
+            raise ValueError('theta should be between [0, pi]')
+        if not ((0.0 <= phi).all() and (phi <= 2.0 * np.pi).all()):
+            raise ValueError('phi should be between [0, 2pi]')
+        if w is not None:
+            w = np.asarray(w)
+            if not (w >= 0.0).all():
+                raise ValueError('w should be positive')
+        if not s >= 0.0:
+            raise ValueError('s should be positive')
+        if not 0.0 < eps < 1.0:
+            raise ValueError('eps should be between (0, 1)')
+
+        nt_, tt_, np_, tp_, c, fp, ier = _spherfit_smth(theta, phi, r, w, s, eps)
+        if ier not in [0, -1, -2]:
+            message = _spherefit_messages.get(ier, f'ier={ier}')
+            raise ValueError(message)
+
+        self.fp = fp
+        self.tck = tt_[:nt_], tp_[:np_], c[:(nt_ - 4) * (np_ - 4)]
+        self.degrees = (3, 3)
+
+    def __call__(self, theta, phi, dtheta=0, dphi=0, grid=True):
+
+        theta = np.asarray(theta)
+        phi = np.asarray(phi)
+
+        if phi.size > 0 and (phi.min() < 0. or phi.max() > 2. * np.pi):
+            raise ValueError("requested phi out of bounds.")
+
+        return SphereBivariateSpline.__call__(self, theta, phi, dtheta=dtheta,
+                                              dphi=dphi, grid=grid)
+
+
+@xp_capabilities(out_of_scope=True)
+class LSQSphereBivariateSpline(SphereBivariateSpline):
+    """
+    Weighted least-squares bivariate spline approximation in spherical
+    coordinates.
+
+    Determines a smoothing bicubic spline according to a given
+    set of knots in the `theta` and `phi` directions.
+
+    .. versionadded:: 0.11.0
+
+    Parameters
+    ----------
+    theta, phi, r : array_like
+        1-D sequences of data points (order is not important). Coordinates
+        must be given in radians. Theta must lie within the interval
+        ``[0, pi]``, and phi must lie within the interval ``[0, 2pi]``.
+    tt, tp : array_like
+        Strictly ordered 1-D sequences of knots coordinates.
+        Coordinates must satisfy ``0 < tt[i] < pi``, ``0 < tp[i] < 2*pi``.
+    w : array_like, optional
+        Positive 1-D sequence of weights, of the same length as `theta`, `phi`
+        and `r`.
+    eps : float, optional
+        A threshold for determining the effective rank of an over-determined
+        linear system of equations. `eps` should have a value within the
+        open interval ``(0, 1)``, the default is 1e-16.
+
+    See Also
+    --------
+    BivariateSpline :
+        a base class for bivariate splines.
+    UnivariateSpline :
+        a smooth univariate spline to fit a given set of data points.
+    SmoothBivariateSpline :
+        a smoothing bivariate spline through the given points
+    LSQBivariateSpline :
+        a bivariate spline using weighted least-squares fitting
+    RectSphereBivariateSpline :
+        a bivariate spline over a rectangular mesh on a sphere
+    SmoothSphereBivariateSpline :
+        a smoothing bivariate spline in spherical coordinates
+    RectBivariateSpline :
+        a bivariate spline over a rectangular mesh.
+    bisplrep :
+        a function to find a bivariate B-spline representation of a surface
+    bisplev :
+        a function to evaluate a bivariate B-spline and its derivatives
+
+    Notes
+    -----
+    For more information, see the FITPACK_ site about this function.
+
+    .. _FITPACK: http://www.netlib.org/dierckx/sphere.f
+
+    Examples
+    --------
+    Suppose we have global data on a coarse grid (the input data does not
+    have to be on a grid):
+
+    >>> from scipy.interpolate import LSQSphereBivariateSpline
+    >>> import numpy as np
+    >>> import matplotlib.pyplot as plt
+
+    >>> theta = np.linspace(0, np.pi, num=7)
+    >>> phi = np.linspace(0, 2*np.pi, num=9)
+    >>> data = np.empty((theta.shape[0], phi.shape[0]))
+    >>> data[:,0], data[0,:], data[-1,:] = 0., 0., 0.
+    >>> data[1:-1,1], data[1:-1,-1] = 1., 1.
+    >>> data[1,1:-1], data[-2,1:-1] = 1., 1.
+    >>> data[2:-2,2], data[2:-2,-2] = 2., 2.
+    >>> data[2,2:-2], data[-3,2:-2] = 2., 2.
+    >>> data[3,3:-2] = 3.
+    >>> data = np.roll(data, 4, 1)
+
+    We need to set up the interpolator object. Here, we must also specify the
+    coordinates of the knots to use.
+
+    >>> lats, lons = np.meshgrid(theta, phi)
+    >>> knotst, knotsp = theta.copy(), phi.copy()
+    >>> knotst[0] += .0001
+    >>> knotst[-1] -= .0001
+    >>> knotsp[0] += .0001
+    >>> knotsp[-1] -= .0001
+    >>> lut = LSQSphereBivariateSpline(lats.ravel(), lons.ravel(),
+    ...                                data.T.ravel(), knotst, knotsp)
+
+    As a first test, we'll see what the algorithm returns when run on the
+    input coordinates
+
+    >>> data_orig = lut(theta, phi)
+
+    Finally we interpolate the data to a finer grid
+
+    >>> fine_lats = np.linspace(0., np.pi, 70)
+    >>> fine_lons = np.linspace(0., 2*np.pi, 90)
+    >>> data_lsq = lut(fine_lats, fine_lons)
+
+    >>> fig = plt.figure()
+    >>> ax1 = fig.add_subplot(131)
+    >>> ax1.imshow(data, interpolation='nearest')
+    >>> ax2 = fig.add_subplot(132)
+    >>> ax2.imshow(data_orig, interpolation='nearest')
+    >>> ax3 = fig.add_subplot(133)
+    >>> ax3.imshow(data_lsq, interpolation='nearest')
+    >>> plt.show()
+
+    """
+
+    def __init__(self, theta, phi, r, tt, tp, w=None, eps=1E-16):
+
+        theta, phi, r = np.asarray(theta), np.asarray(phi), np.asarray(r)
+        tt, tp = np.asarray(tt), np.asarray(tp)
+
+        if not ((0.0 <= theta).all() and (theta <= np.pi).all()):
+            raise ValueError('theta should be between [0, pi]')
+        if not ((0.0 <= phi).all() and (phi <= 2*np.pi).all()):
+            raise ValueError('phi should be between [0, 2pi]')
+        if not ((0.0 < tt).all() and (tt < np.pi).all()):
+            raise ValueError('tt should be between (0, pi)')
+        if not ((0.0 < tp).all() and (tp < 2*np.pi).all()):
+            raise ValueError('tp should be between (0, 2pi)')
+        if w is not None:
+            w = np.asarray(w)
+            if not (w >= 0.0).all():
+                raise ValueError('w should be positive')
+        if not 0.0 < eps < 1.0:
+            raise ValueError('eps should be between (0, 1)')
+
+        nt_, np_ = 8 + len(tt), 8 + len(tp)
+        tt_, tp_ = zeros((nt_,), float), zeros((np_,), float)
+        tt_[4:-4], tp_[4:-4] = tt, tp
+        tt_[-4:], tp_[-4:] = np.pi, 2. * np.pi
+        tt_, tp_, c, fp, ier = _spherfit_lsq(theta, phi, r, nt_, tt_, np_, tp_, w, eps)
+        if ier > 0:
+            message = _spherefit_messages.get(ier, f'ier={ier}')
+            raise ValueError(message)
+
+        self.fp = fp
+        self.tck = tt_, tp_, c
+        self.degrees = (3, 3)
+
+    def __call__(self, theta, phi, dtheta=0, dphi=0, grid=True):
+
+        theta = np.asarray(theta)
+        phi = np.asarray(phi)
+
+        if phi.size > 0 and (phi.min() < 0. or phi.max() > 2. * np.pi):
+            raise ValueError("requested phi out of bounds.")
+
+        return SphereBivariateSpline.__call__(self, theta, phi, dtheta=dtheta,
+                                              dphi=dphi, grid=grid)
+
+
+_spfit_messages = _surfit_messages.copy()
+_spfit_messages[10] = """
+ERROR: on entry, the input data are controlled on validity
+       the following restrictions must be satisfied.
+          -1<=iopt(1)<=1, 0<=iopt(2)<=1, 0<=iopt(3)<=1,
+          -1<=ider(1)<=1, 0<=ider(2)<=1, ider(2)=0 if iopt(2)=0.
+          -1<=ider(3)<=1, 0<=ider(4)<=1, ider(4)=0 if iopt(3)=0.
+          mu >= mumin (see above), mv >= 4, nuest >=8, nvest >= 8,
+          kwrk>=5+mu+mv+nuest+nvest,
+          lwrk >= 12+nuest*(mv+nvest+3)+nvest*24+4*mu+8*mv+max(nuest,mv+nvest)
+          0< u(i-1)=0: s>=0
+          if s=0: nuest>=mu+6+iopt(2)+iopt(3), nvest>=mv+7
+       if one of these conditions is found to be violated,control is
+       immediately repassed to the calling program. in that case there is no
+       approximation returned."""
+
+
+@xp_capabilities(out_of_scope=True)
+class RectSphereBivariateSpline(SphereBivariateSpline):
+    """
+    Bivariate spline approximation over a rectangular mesh on a sphere.
+
+    Can be used for smoothing data.
+
+    .. versionadded:: 0.11.0
+
+    Parameters
+    ----------
+    u : array_like
+        1-D array of colatitude coordinates in strictly ascending order.
+        Coordinates must be given in radians and lie within the open interval
+        ``(0, pi)``.
+    v : array_like
+        1-D array of longitude coordinates in strictly ascending order.
+        Coordinates must be given in radians. First element (``v[0]``) must lie
+        within the interval ``[-pi, pi)``. Last element (``v[-1]``) must satisfy
+        ``v[-1] <= v[0] + 2*pi``.
+    r : array_like
+        2-D array of data with shape ``(u.size, v.size)``.
+    s : float, optional
+        Positive smoothing factor defined for estimation condition
+        (``s=0`` is for interpolation).
+    pole_continuity : bool or (bool, bool), optional
+        Order of continuity at the poles ``u=0`` (``pole_continuity[0]``) and
+        ``u=pi`` (``pole_continuity[1]``).  The order of continuity at the pole
+        will be 1 or 0 when this is True or False, respectively.
+        Defaults to False.
+    pole_values : float or (float, float), optional
+        Data values at the poles ``u=0`` and ``u=pi``.  Either the whole
+        parameter or each individual element can be None.  Defaults to None.
+    pole_exact : bool or (bool, bool), optional
+        Data value exactness at the poles ``u=0`` and ``u=pi``.  If True, the
+        value is considered to be the right function value, and it will be
+        fitted exactly. If False, the value will be considered to be a data
+        value just like the other data values.  Defaults to False.
+    pole_flat : bool or (bool, bool), optional
+        For the poles at ``u=0`` and ``u=pi``, specify whether or not the
+        approximation has vanishing derivatives.  Defaults to False.
+
+    See Also
+    --------
+    BivariateSpline :
+        a base class for bivariate splines.
+    UnivariateSpline :
+        a smooth univariate spline to fit a given set of data points.
+    SmoothBivariateSpline :
+        a smoothing bivariate spline through the given points
+    LSQBivariateSpline :
+        a bivariate spline using weighted least-squares fitting
+    SmoothSphereBivariateSpline :
+        a smoothing bivariate spline in spherical coordinates
+    LSQSphereBivariateSpline :
+        a bivariate spline in spherical coordinates using weighted
+        least-squares fitting
+    RectBivariateSpline :
+        a bivariate spline over a rectangular mesh.
+    bisplrep :
+        a function to find a bivariate B-spline representation of a surface
+    bisplev :
+        a function to evaluate a bivariate B-spline and its derivatives
+
+    Notes
+    -----
+    Currently, only the smoothing spline approximation (``iopt[0] = 0`` and
+    ``iopt[0] = 1`` in the FITPACK routine) is supported.  The exact
+    least-squares spline approximation is not implemented yet.
+
+    When actually performing the interpolation, the requested `v` values must
+    lie within the same length 2pi interval that the original `v` values were
+    chosen from.
+
+    For more information, see the FITPACK_ site about this function.
+
+    .. _FITPACK: http://www.netlib.org/dierckx/spgrid.f
+
+    Examples
+    --------
+    Suppose we have global data on a coarse grid
+
+    >>> import numpy as np
+    >>> lats = np.linspace(10, 170, 9) * np.pi / 180.
+    >>> lons = np.linspace(0, 350, 18) * np.pi / 180.
+    >>> data = np.dot(np.atleast_2d(90. - np.linspace(-80., 80., 18)).T,
+    ...               np.atleast_2d(180. - np.abs(np.linspace(0., 350., 9)))).T
+
+    We want to interpolate it to a global one-degree grid
+
+    >>> new_lats = np.linspace(1, 180, 180) * np.pi / 180
+    >>> new_lons = np.linspace(1, 360, 360) * np.pi / 180
+    >>> new_lats, new_lons = np.meshgrid(new_lats, new_lons)
+
+    We need to set up the interpolator object
+
+    >>> from scipy.interpolate import RectSphereBivariateSpline
+    >>> lut = RectSphereBivariateSpline(lats, lons, data)
+
+    Finally we interpolate the data.  The `RectSphereBivariateSpline` object
+    only takes 1-D arrays as input, therefore we need to do some reshaping.
+
+    >>> data_interp = lut.ev(new_lats.ravel(),
+    ...                      new_lons.ravel()).reshape((360, 180)).T
+
+    Looking at the original and the interpolated data, one can see that the
+    interpolant reproduces the original data very well:
+
+    >>> import matplotlib.pyplot as plt
+    >>> fig = plt.figure()
+    >>> ax1 = fig.add_subplot(211)
+    >>> ax1.imshow(data, interpolation='nearest')
+    >>> ax2 = fig.add_subplot(212)
+    >>> ax2.imshow(data_interp, interpolation='nearest')
+    >>> plt.show()
+
+    Choosing the optimal value of ``s`` can be a delicate task. Recommended
+    values for ``s`` depend on the accuracy of the data values.  If the user
+    has an idea of the statistical errors on the data, she can also find a
+    proper estimate for ``s``. By assuming that, if she specifies the
+    right ``s``, the interpolator will use a spline ``f(u,v)`` which exactly
+    reproduces the function underlying the data, she can evaluate
+    ``sum((r(i,j)-s(u(i),v(j)))**2)`` to find a good estimate for this ``s``.
+    For example, if she knows that the statistical errors on her
+    ``r(i,j)``-values are not greater than 0.1, she may expect that a good
+    ``s`` should have a value not larger than ``u.size * v.size * (0.1)**2``.
+
+    If nothing is known about the statistical error in ``r(i,j)``, ``s`` must
+    be determined by trial and error.  The best is then to start with a very
+    large value of ``s`` (to determine the least-squares polynomial and the
+    corresponding upper bound ``fp0`` for ``s``) and then to progressively
+    decrease the value of ``s`` (say by a factor 10 in the beginning, i.e.
+    ``s = fp0 / 10, fp0 / 100, ...``  and more carefully as the approximation
+    shows more detail) to obtain closer fits.
+
+    The interpolation results for different values of ``s`` give some insight
+    into this process:
+
+    >>> fig2 = plt.figure()
+    >>> s = [3e9, 2e9, 1e9, 1e8]
+    >>> for idx, sval in enumerate(s, 1):
+    ...     lut = RectSphereBivariateSpline(lats, lons, data, s=sval)
+    ...     data_interp = lut.ev(new_lats.ravel(),
+    ...                          new_lons.ravel()).reshape((360, 180)).T
+    ...     ax = fig2.add_subplot(2, 2, idx)
+    ...     ax.imshow(data_interp, interpolation='nearest')
+    ...     ax.set_title(f"s = {sval:g}")
+    >>> plt.show()
+
+    """
+
+    def __init__(self, u, v, r, s=0., pole_continuity=False, pole_values=None,
+                 pole_exact=False, pole_flat=False):
+        iopt = np.array([0, 0, 0], dtype=np.int32)
+        ider = np.array([-1, 0, -1, 0], dtype=np.int32)
+        if pole_values is None:
+            pole_values = (None, None)
+        elif isinstance(pole_values, float | np.float32 | np.float64):
+            pole_values = (pole_values, pole_values)
+        if isinstance(pole_continuity, bool):
+            pole_continuity = (pole_continuity, pole_continuity)
+        if isinstance(pole_exact, bool):
+            pole_exact = (pole_exact, pole_exact)
+        if isinstance(pole_flat, bool):
+            pole_flat = (pole_flat, pole_flat)
+
+        r0, r1 = pole_values
+        iopt[1:] = pole_continuity
+        if r0 is None:
+            ider[0] = -1
+        else:
+            ider[0] = pole_exact[0]
+
+        if r1 is None:
+            ider[2] = -1
+        else:
+            ider[2] = pole_exact[1]
+
+        ider[1], ider[3] = pole_flat
+
+        u, v = np.ravel(u), np.ravel(v)
+        r = np.asarray(r)
+
+        if not (0.0 < u[0] and u[-1] < np.pi):
+            raise ValueError('u should be between (0, pi)')
+        if not -np.pi <= v[0] < np.pi:
+            raise ValueError('v[0] should be between [-pi, pi)')
+        if not v[-1] <= v[0] + 2*np.pi:
+            raise ValueError('v[-1] should be v[0] + 2pi or less ')
+
+        if not np.all(np.diff(u) > 0.0):
+            raise ValueError('u must be strictly increasing')
+        if not np.all(np.diff(v) > 0.0):
+            raise ValueError('v must be strictly increasing')
+
+        if not u.size == r.shape[0]:
+            raise ValueError('u dimension of r must have same number of '
+                             'elements as u')
+        if not v.size == r.shape[1]:
+            raise ValueError('v dimension of r must have same number of '
+                             'elements as v')
+
+        if pole_continuity[1] is False and pole_flat[1] is True:
+            raise ValueError('if pole_continuity is False, so must be '
+                             'pole_flat')
+        if pole_continuity[0] is False and pole_flat[0] is True:
+            raise ValueError('if pole_continuity is False, so must be '
+                             'pole_flat')
+
+        if not s >= 0.0:
+            raise ValueError('s should be positive')
+
+        r = np.ravel(r)
+
+        # Default values for missing parameters
+        # For s=0 (interpolation), spgrid requires:
+        #   nuest >= mu + 6 + iopt[1] + iopt[2]  (0-based indexing)
+        #   nvest >= mv + 7
+        # For s>0 (smoothing), use heuristic
+        mu = len(u)
+        mv = len(v)
+        if s == 0.0:
+            nuest = mu + 6 + iopt[1] + iopt[2]
+            nvest = mv + 7
+        else:
+            nuest = max(mu + 6 + iopt[1] + iopt[2], 8 + int(np.sqrt(mu / 2)))
+            nvest = max(mv + 7, 8 + int(np.sqrt(mv / 2)))
+        eps = 1e-16
+
+        nu, tu, nv, tv, c, fp, ier = _regrid_smth_spher(iopt, ider,
+                                                        u.copy(),
+                                                        v.copy(),
+                                                        r.copy(),
+                                                        r0, r1, s,
+                                                        nuest, nvest, eps)
+
+        if ier not in [0, -1, -2]:
+            msg = _spfit_messages.get(ier, f'ier={ier}')
+            raise ValueError(msg)
+
+        self.fp = fp
+        self.tck = tu[:nu], tv[:nv], c[:(nu - 4) * (nv-4)]
+        self.degrees = (3, 3)
+        self.v0 = v[0]
+
+    def __call__(self, theta, phi, dtheta=0, dphi=0, grid=True):
+
+        theta = np.asarray(theta)
+        phi = np.asarray(phi)
+
+        return SphereBivariateSpline.__call__(self, theta, phi, dtheta=dtheta,
+                                              dphi=dphi, grid=grid)
diff --git a/.venv/lib/python3.12/site-packages/scipy/interpolate/_fitpack_impl.py b/.venv/lib/python3.12/site-packages/scipy/interpolate/_fitpack_impl.py
new file mode 100644
index 0000000000000000000000000000000000000000..7eb822d2d49ae60e4c83f8b6aa2274fb7a7fd381
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/interpolate/_fitpack_impl.py
@@ -0,0 +1,828 @@
+"""
+fitpack (dierckx in netlib) --- A Python-C wrapper to FITPACK (by P. Dierckx).
+        FITPACK is a collection of FORTRAN programs for curve and surface
+        fitting with splines and tensor product splines.
+
+See
+ https://web.archive.org/web/20010524124604/http://www.cs.kuleuven.ac.be:80/cwis/research/nalag/research/topics/fitpack.html
+or
+ http://www.netlib.org/dierckx/
+
+Copyright 2002 Pearu Peterson all rights reserved,
+Pearu Peterson 
+Permission to use, modify, and distribute this software is given under the
+terms of the SciPy (BSD style) license. See LICENSE.txt that came with
+this distribution for specifics.
+
+NO WARRANTY IS EXPRESSED OR IMPLIED.  USE AT YOUR OWN RISK.
+
+TODO: Make interfaces to the following fitpack functions:
+    For univariate splines: cocosp, concon, fourco, insert
+    For bivariate splines: profil, regrid, parsur, surev
+"""
+
+__all__ = ['splrep', 'splprep', 'splev', 'splint', 'sproot', 'spalde',
+           'bisplrep', 'bisplev', 'insert', 'splder', 'splantider']
+
+import warnings
+import numpy as np
+from . import _fitpack
+from numpy import (atleast_1d, array, ones, zeros, sqrt, ravel, empty, iinfo, asarray)
+
+from scipy._lib._array_api import array_namespace, concat_1d, xp_capabilities
+
+
+dfitpack_int = np.int32
+
+
+def _int_overflow(x, exception, msg=None):
+    """Cast the value to a dfitpack_int and raise an OverflowError if the value
+    cannot fit.
+    """
+    if x > iinfo(dfitpack_int).max:
+        if msg is None:
+            msg = f'{x!r} cannot fit into an {dfitpack_int!r}'
+        raise exception(msg)
+    return dfitpack_int(x)
+
+
+_iermess = {
+    0: ["The spline has a residual sum of squares fp such that "
+        "abs(fp-s)/s<=0.001", None],
+    -1: ["The spline is an interpolating spline (fp=0)", None],
+    -2: ["The spline is weighted least-squares polynomial of degree k.\n"
+         "fp gives the upper bound fp0 for the smoothing factor s", None],
+    1: ["The required storage space exceeds the available storage space.\n"
+        "Probable causes: data (x,y) size is too small or smoothing parameter"
+        "\ns is too small (fp>s).", ValueError],
+    2: ["A theoretically impossible result when finding a smoothing spline\n"
+        "with fp = s. Probable cause: s too small. (abs(fp-s)/s>0.001)",
+        ValueError],
+    3: ["The maximal number of iterations (20) allowed for finding smoothing\n"
+        "spline with fp=s has been reached. Probable cause: s too small.\n"
+        "(abs(fp-s)/s>0.001)", ValueError],
+    10: ["Error on input data", ValueError],
+    'unknown': ["An error occurred", TypeError]
+}
+
+_iermess2 = {
+    0: ["The spline has a residual sum of squares fp such that "
+        "abs(fp-s)/s<=0.001", None],
+    -1: ["The spline is an interpolating spline (fp=0)", None],
+    -2: ["The spline is weighted least-squares polynomial of degree kx and ky."
+         "\nfp gives the upper bound fp0 for the smoothing factor s", None],
+    -3: ["Warning. The coefficients of the spline have been computed as the\n"
+         "minimal norm least-squares solution of a rank deficient system.",
+         None],
+    1: ["The required storage space exceeds the available storage space.\n"
+        "Probable causes: nxest or nyest too small or s is too small. (fp>s)",
+        ValueError],
+    2: ["A theoretically impossible result when finding a smoothing spline\n"
+        "with fp = s. Probable causes: s too small or badly chosen eps.\n"
+        "(abs(fp-s)/s>0.001)", ValueError],
+    3: ["The maximal number of iterations (20) allowed for finding smoothing\n"
+        "spline with fp=s has been reached. Probable cause: s too small.\n"
+        "(abs(fp-s)/s>0.001)", ValueError],
+    4: ["No more knots can be added because the number of B-spline\n"
+        "coefficients already exceeds the number of data points m.\n"
+        "Probable causes: either s or m too small. (fp>s)", ValueError],
+    5: ["No more knots can be added because the additional knot would\n"
+        "coincide with an old one. Probable cause: s too small or too large\n"
+        "a weight to an inaccurate data point. (fp>s)", ValueError],
+    10: ["Error on input data", ValueError],
+    11: ["rwrk2 too small, i.e., there is not enough workspace for computing\n"
+         "the minimal least-squares solution of a rank deficient system of\n"
+         "linear equations.", ValueError],
+    'unknown': ["An error occurred", TypeError]
+}
+
+_parcur_cache = {'t': array([], float), 'wrk': array([], float),
+                 'iwrk': array([], np.int32), 'u': array([], float),
+                 'ub': 0, 'ue': 1}
+
+
+def splprep(x, w=None, u=None, ub=None, ue=None, k=3, task=0, s=None, t=None,
+            full_output=0, nest=None, per=0, quiet=1):
+    # see the docstring of `_fitpack_py/splprep`
+    if task <= 0:
+        _parcur_cache = {'t': array([], float), 'wrk': array([], float),
+                         'iwrk': array([], np.int32), 'u': array([], float),
+                         'ub': 0, 'ue': 1}
+    x = atleast_1d(x)
+    idim, m = x.shape
+    if per:
+        for i in range(idim):
+            if x[i][0] != x[i][-1]:
+                if not quiet:
+                    warnings.warn(
+                        RuntimeWarning(f'Setting x[{i}][{m}]=x[{i}][0]'),
+                        stacklevel=2
+                    )
+                x[i][-1] = x[i][0]
+    if not 0 < idim < 11:
+        raise TypeError('0 < idim < 11 must hold')
+    if w is None:
+        w = ones(m, float)
+    else:
+        w = atleast_1d(w)
+    ipar = (u is not None)
+    if ipar:
+        _parcur_cache['u'] = u
+        if ub is None:
+            _parcur_cache['ub'] = u[0]
+        else:
+            _parcur_cache['ub'] = ub
+        if ue is None:
+            _parcur_cache['ue'] = u[-1]
+        else:
+            _parcur_cache['ue'] = ue
+    else:
+        _parcur_cache['u'] = zeros(m, float)
+    if not (1 <= k <= 5):
+        raise TypeError(f'1 <= k= {k} <=5 must hold')
+    if not (-1 <= task <= 1):
+        raise TypeError('task must be -1, 0 or 1')
+    if (not len(w) == m) or (ipar == 1 and (not len(u) == m)):
+        raise TypeError('Mismatch of input dimensions')
+    if s is None:
+        s = m - sqrt(2*m)
+    if t is None and task == -1:
+        raise TypeError('Knots must be given for task=-1')
+    if t is not None:
+        _parcur_cache['t'] = atleast_1d(t)
+    n = len(_parcur_cache['t'])
+    if task == -1 and n < 2*k + 2:
+        raise TypeError('There must be at least 2*k+2 knots for task=-1')
+    if m <= k:
+        raise TypeError('m > k must hold')
+    if nest is None:
+        nest = m + 2*k
+
+    if (task >= 0 and s == 0) or (nest < 0):
+        if per:
+            nest = m + 2*k
+        else:
+            nest = m + k + 1
+    nest = max(nest, 2*k + 3)
+    u = _parcur_cache['u']
+    ub = _parcur_cache['ub']
+    ue = _parcur_cache['ue']
+    t = _parcur_cache['t']
+    wrk = _parcur_cache['wrk']
+    iwrk = _parcur_cache['iwrk']
+    t, c, o = _fitpack.parcur(ravel(x, 'F'), w, u, ub, ue, k, task, ipar, s,
+                              t, nest, wrk, iwrk, per)
+    _parcur_cache['u'] = o['u']
+    _parcur_cache['ub'] = o['ub']
+    _parcur_cache['ue'] = o['ue']
+    _parcur_cache['t'] = t
+    _parcur_cache['wrk'] = o['wrk']
+    _parcur_cache['iwrk'] = o['iwrk']
+    ier = o['ier']
+    fp = o['fp']
+    n = len(t)
+    u = o['u']
+    c = c.reshape((idim, n - k - 1))
+    tcku = [t, list(c), k], u
+    if ier <= 0 and not quiet:
+        warnings.warn(
+            RuntimeWarning(
+                _iermess[ier][0] + f"\tk={k} n={len(t)} m={m} fp={fp} s={s}"
+            ),
+            stacklevel=2
+        )
+    if ier > 0 and not full_output:
+        if ier in [1, 2, 3]:
+            warnings.warn(RuntimeWarning(_iermess[ier][0]), stacklevel=2)
+        else:
+            try:
+                raise _iermess[ier][1](_iermess[ier][0])
+            except KeyError as e:
+                raise _iermess['unknown'][1](_iermess['unknown'][0]) from e
+    if full_output:
+        try:
+            return tcku, fp, ier, _iermess[ier][0]
+        except KeyError:
+            return tcku, fp, ier, _iermess['unknown'][0]
+    else:
+        return tcku
+
+
+_curfit_cache = {'t': array([], float), 'wrk': array([], float),
+                 'iwrk': array([], np.int32)}
+
+
+def splrep(x, y, w=None, xb=None, xe=None, k=3, task=0, s=None, t=None,
+           full_output=0, per=0, quiet=1):
+    # see the docstring of `_fitpack_py/splrep`
+    if task <= 0:
+        _curfit_cache = {}
+    x, y = map(atleast_1d, [x, y])
+    m = len(x)
+    if w is None:
+        w = ones(m, float)
+        if s is None:
+            s = 0.0
+    else:
+        w = atleast_1d(w)
+        if s is None:
+            s = m - sqrt(2*m)
+    if not len(w) == m:
+        raise TypeError(f'len(w)={len(w)} is not equal to m={m}')
+    if (m != len(y)) or (m != len(w)):
+        raise TypeError('Lengths of the first three arguments (x,y,w) must '
+                        'be equal')
+    if not (1 <= k <= 5):
+        raise TypeError(
+            f'Given degree of the spline (k={k}) is not supported. (1<=k<=5)'
+        )
+    if m <= k:
+        raise TypeError('m > k must hold')
+    if xb is None:
+        xb = x[0]
+    if xe is None:
+        xe = x[-1]
+    if not (-1 <= task <= 1):
+        raise TypeError('task must be -1, 0 or 1')
+    if t is not None:
+        task = -1
+    if task == -1:
+        if t is None:
+            raise TypeError('Knots must be given for task=-1')
+        numknots = len(t)
+        _curfit_cache['t'] = empty((numknots + 2*k + 2,), float)
+        _curfit_cache['t'][k+1:-k-1] = t
+        nest = len(_curfit_cache['t'])
+    elif task == 0:
+        if per:
+            nest = max(m + 2*k, 2*k + 3)
+        else:
+            nest = max(m + k + 1, 2*k + 3)
+        t = empty((nest,), float)
+        _curfit_cache['t'] = t
+    if task <= 0:
+        if per:
+            _curfit_cache['wrk'] = empty((m*(k + 1) + nest*(8 + 5*k),), float)
+        else:
+            _curfit_cache['wrk'] = empty((m*(k + 1) + nest*(7 + 3*k),), float)
+        _curfit_cache['iwrk'] = empty((nest,), np.int32)
+    try:
+        t = _curfit_cache['t']
+        wrk = _curfit_cache['wrk']
+        iwrk = _curfit_cache['iwrk']
+    except KeyError as e:
+        raise TypeError("must call with task=1 only after"
+                        " call with task=0,-1") from e
+    if not per:
+        n, t, c, fp, ier = _fitpack.curfit(task, x, y, w, xb, xe, k, s,
+                                           t, wrk, iwrk)
+    else:
+        n, t, c, fp, ier = _fitpack.percur(task, x, y, w, k, s,
+                                           t, wrk, iwrk)
+
+    tck = (t[:n], c[:n], k)
+    if ier <= 0 and not quiet:
+        _mess = (_iermess[ier][0] + f"\tk={k} n={len(t)} m={m} fp={fp} s={s}")
+        warnings.warn(RuntimeWarning(_mess), stacklevel=2)
+    if ier > 0 and not full_output:
+        if ier in [1, 2, 3]:
+            warnings.warn(RuntimeWarning(_iermess[ier][0]), stacklevel=2)
+        else:
+            try:
+                raise _iermess[ier][1](_iermess[ier][0])
+            except KeyError as e:
+                raise _iermess['unknown'][1](_iermess['unknown'][0]) from e
+    if full_output:
+        try:
+            return tck, fp, ier, _iermess[ier][0]
+        except KeyError:
+            return tck, fp, ier, _iermess['unknown'][0]
+    else:
+        return tck
+
+
+def splev(x, tck, der=0, ext=0):
+    # see the docstring of `_fitpack_py/splev`
+    t, c, k = tck
+    try:
+        c[0][0]
+        parametric = True
+    except Exception:
+        parametric = False
+    if parametric:
+        return list(map(lambda c, x=x, t=t, k=k, der=der:
+                        splev(x, [t, c, k], der, ext), c))
+    else:
+        if not (0 <= der <= k):
+            raise ValueError(f"0<=der={der}<=k={k} must hold")
+        if ext not in (0, 1, 2, 3):
+            raise ValueError(f"ext = {ext} not in (0, 1, 2, 3) ")
+
+        x = asarray(x)
+        shape = x.shape
+        x = atleast_1d(x).ravel()
+        if der == 0:
+            y, ier = _fitpack.splev(t, c, k, x, ext)
+        else:
+            y, ier = _fitpack.splder(t, c, k, der, x, ext)
+
+        if ier == 10:
+            raise ValueError("Invalid input data")
+        if ier == 1:
+            raise ValueError("Found x value not in the domain")
+        if ier:
+            raise TypeError("An error occurred")
+
+        return y.reshape(shape)
+
+
+def splint(a, b, tck, full_output=0):
+    # see the docstring of `_fitpack_py/splint`
+    t, c, k = tck
+    try:
+        c[0][0]
+        parametric = True
+    except Exception:
+        parametric = False
+    if parametric:
+        return list(map(lambda c, a=a, b=b, t=t, k=k:
+                        splint(a, b, [t, c, k]), c))
+    else:
+        aint = _fitpack.splint(t, c, k, a, b)
+        if full_output:
+            return aint, None
+        else:
+            return aint
+
+
+def sproot(tck, mest=10):
+    # see the docstring of `_fitpack_py/sproot`
+    t, c, k = tck
+    if k != 3:
+        raise ValueError("sproot works only for cubic (k=3) splines")
+    try:
+        c[0][0]
+        parametric = True
+    except Exception:
+        parametric = False
+    if parametric:
+        return list(map(lambda c, t=t, k=k, mest=mest:
+                        sproot([t, c, k], mest), c))
+    else:
+        if len(t) < 8:
+            raise TypeError(f"The number of knots {len(t)}>=8")
+        z, m, ier = _fitpack.sproot(t, c, mest)
+        if ier == 10:
+            raise TypeError("Invalid input data. "
+                            "t1<=..<=t4 1:
+            return list(map(lambda x, tck=tck: spalde(x, tck), x))
+        d, ier = _fitpack.spalde(t, c, k+1, x[0])
+        if ier == 0:
+            return d
+        if ier == 10:
+            raise TypeError("Invalid input data. t(k)<=x<=t(n-k+1) must hold.")
+        raise TypeError("Unknown error")
+
+# def _curfit(x,y,w=None,xb=None,xe=None,k=3,task=0,s=None,t=None,
+#           full_output=0,nest=None,per=0,quiet=1):
+
+
+_surfit_cache = {'tx': array([], float), 'ty': array([], float),
+                 'wrk': array([], float), 'iwrk': array([], np.int32)}
+
+
+@xp_capabilities(out_of_scope=True)
+def bisplrep(x, y, z, w=None, xb=None, xe=None, yb=None, ye=None,
+             kx=3, ky=3, task=0, s=None, eps=1e-16, tx=None, ty=None,
+             full_output=0, nxest=None, nyest=None, quiet=1):
+    """
+    Find a bivariate B-spline representation of a surface.
+
+    Given a set of data points (x[i], y[i], z[i]) representing a surface
+    z=f(x,y), compute a B-spline representation of the surface. Based on
+    the routine SURFIT from FITPACK.
+
+    Parameters
+    ----------
+    x, y, z : ndarray
+        Rank-1 arrays of data points.
+    w : ndarray, optional
+        Rank-1 array of weights. By default ``w=np.ones(len(x))``.
+    xb, xe : float, optional
+        End points of approximation interval in `x`.
+        By default ``xb = x.min(), xe=x.max()``.
+    yb, ye : float, optional
+        End points of approximation interval in `y`.
+        By default ``yb=y.min(), ye = y.max()``.
+    kx, ky : int, optional
+        The degrees of the spline (1 <= kx, ky <= 5).
+        Third order (kx=ky=3) is recommended.
+    task : int, optional
+        If task=0, find knots in x and y and coefficients for a given
+        smoothing factor, s.
+        If task=1, find knots and coefficients for another value of the
+        smoothing factor, s.  bisplrep must have been previously called
+        with task=0 or task=1.
+        If task=-1, find coefficients for a given set of knots tx, ty.
+    s : float, optional
+        A non-negative smoothing factor. If weights correspond
+        to the inverse of the standard-deviation of the errors in z,
+        then a good s-value should be found in the range
+        ``(m-sqrt(2*m),m+sqrt(2*m))`` where m=len(x).
+    eps : float, optional
+        A threshold for determining the effective rank of an
+        over-determined linear system of equations (0 < eps < 1).
+        `eps` is not likely to need changing.
+    tx, ty : ndarray, optional
+        Rank-1 arrays of the knots of the spline for task=-1
+    full_output : int, optional
+        Non-zero to return optional outputs.
+    nxest, nyest : int, optional
+        Over-estimates of the total number of knots. If None then
+        ``nxest = max(kx+sqrt(m/2),2*kx+3)``,
+        ``nyest = max(ky+sqrt(m/2),2*ky+3)``.
+    quiet : int, optional
+        Non-zero to suppress printing of messages.
+
+    Returns
+    -------
+    tck : array_like
+        A list [tx, ty, c, kx, ky] containing the knots (tx, ty) and
+        coefficients (c) of the bivariate B-spline representation of the
+        surface along with the degree of the spline.
+    fp : ndarray
+        The weighted sum of squared residuals of the spline approximation.
+    ier : int
+        An integer flag about splrep success. Success is indicated if
+        ier<=0. If ier in [1,2,3] an error occurred but was not raised.
+        Otherwise an error is raised.
+    msg : str
+        A message corresponding to the integer flag, ier.
+
+    See Also
+    --------
+    splprep, splrep, splint, sproot, splev
+    UnivariateSpline, BivariateSpline
+
+    Notes
+    -----
+    See `bisplev` to evaluate the value of the B-spline given its tck
+    representation.
+
+    If the input data is such that input dimensions have incommensurate
+    units and differ by many orders of magnitude, the interpolant may have
+    numerical artifacts. Consider rescaling the data before interpolation.
+
+    References
+    ----------
+    .. [1] Dierckx P.:An algorithm for surface fitting with spline functions
+       Ima J. Numer. Anal. 1 (1981) 267-283.
+    .. [2] Dierckx P.:An algorithm for surface fitting with spline functions
+       report tw50, Dept. Computer Science,K.U.Leuven, 1980.
+    .. [3] Dierckx P.:Curve and surface fitting with splines, Monographs on
+       Numerical Analysis, Oxford University Press, 1993.
+
+    Examples
+    --------
+    Examples are given :ref:`in the tutorial `.
+
+    """
+    x, y, z = map(ravel, [x, y, z])  # ensure 1-d arrays.
+    m = len(x)
+    if not (m == len(y) == len(z)):
+        raise TypeError('len(x)==len(y)==len(z) must hold.')
+    if w is None:
+        w = ones(m, float)
+    else:
+        w = atleast_1d(w)
+    if not len(w) == m:
+        raise TypeError(f'len(w)={len(w)} is not equal to m={m}')
+    if xb is None:
+        xb = x.min()
+    if xe is None:
+        xe = x.max()
+    if yb is None:
+        yb = y.min()
+    if ye is None:
+        ye = y.max()
+    if not (-1 <= task <= 1):
+        raise TypeError('task must be -1, 0 or 1')
+    if s is None:
+        s = m - sqrt(2*m)
+    if tx is None and task == -1:
+        raise TypeError('Knots_x must be given for task=-1')
+    if tx is not None:
+        _surfit_cache['tx'] = atleast_1d(tx)
+    nx = len(_surfit_cache['tx'])
+    if ty is None and task == -1:
+        raise TypeError('Knots_y must be given for task=-1')
+    if ty is not None:
+        _surfit_cache['ty'] = atleast_1d(ty)
+    ny = len(_surfit_cache['ty'])
+    if task == -1 and nx < 2*kx+2:
+        raise TypeError('There must be at least 2*kx+2 knots_x for task=-1')
+    if task == -1 and ny < 2*ky+2:
+        raise TypeError('There must be at least 2*ky+2 knots_x for task=-1')
+    if not ((1 <= kx <= 5) and (1 <= ky <= 5)):
+        raise TypeError(
+            f'Given degree of the spline (kx,ky={kx},{ky}) is not supported. (1<=k<=5)'
+        )
+    if m < (kx + 1)*(ky + 1):
+        raise TypeError('m >= (kx+1)(ky+1) must hold')
+    if nxest is None:
+        nxest = int(kx + sqrt(m/2))
+    if nyest is None:
+        nyest = int(ky + sqrt(m/2))
+    nxest, nyest = max(nxest, 2*kx + 3), max(nyest, 2*ky + 3)
+    if task >= 0 and s == 0:
+        nxest = int(kx + sqrt(3*m))
+        nyest = int(ky + sqrt(3*m))
+    if task == -1:
+        _surfit_cache['tx'] = atleast_1d(tx)
+        _surfit_cache['ty'] = atleast_1d(ty)
+    tx, ty = _surfit_cache['tx'], _surfit_cache['ty']
+    wrk = _surfit_cache['wrk']
+    u = nxest - kx - 1
+    v = nyest - ky - 1
+    km = max(kx, ky) + 1
+    ne = max(nxest, nyest)
+    bx, by = kx*v + ky + 1, ky*u + kx + 1
+    b1, b2 = bx, bx + v - ky
+    if bx > by:
+        b1, b2 = by, by + u - kx
+    msg = "Too many data points to interpolate"
+    # This computation is required to catch overflow on Python side
+    _ = _int_overflow(u*v*(2 + b1 + b2) +
+                          2*(u + v + km*(m + ne) + ne - kx - ky) + b2 + 1,
+                          OverflowError,
+                          msg=msg)
+    nmax = max(nxest, nyest)
+    wrk = _surfit_cache['wrk']
+    nx, tx, ny, ty, c, fp, ier, wrk = _fitpack.surfit(
+        task, x, y, z, w, xb, xe, yb, ye, kx, ky, s, nxest, nyest, nmax, eps, wrk
+    )
+
+    # The low-level routine may return `c` sized for the estimate (nxest, nyest)
+    # rather than the final (nx, ny). Trim to the coefficient count implied by
+    # the returned knots so downstream evaluators (bispev/parder) accept it.
+    ncoef = (len(tx) - kx - 1) * (len(ty) - ky - 1)
+    if ncoef > 0 and c.size != ncoef:
+        c = c[:ncoef]
+    _surfit_cache['tx'] = tx
+    _surfit_cache['ty'] = ty
+    tck = [tx, ty, c, kx, ky]
+
+    ierm = min(11, max(-3, ier))
+    if ierm <= 0 and not quiet:
+        _mess = (
+            _iermess2[ierm][0] +
+            f"\tkx,ky={kx},{ky} nx,ny={len(tx)},{len(ty)} m={m} fp={fp} s={s}"
+        )
+        warnings.warn(RuntimeWarning(_mess), stacklevel=2)
+    if ierm > 0 and not full_output:
+        if ier in [1, 2, 3, 4, 5]:
+            _mess = (
+                f"\n\tkx,ky={kx},{ky} nx,ny={len(tx)},{len(ty)} m={m} fp={fp} s={s}"
+            )
+            warnings.warn(RuntimeWarning(_iermess2[ierm][0] + _mess), stacklevel=2)
+        else:
+            try:
+                raise _iermess2[ierm][1](_iermess2[ierm][0])
+            except KeyError as e:
+                raise _iermess2['unknown'][1](_iermess2['unknown'][0]) from e
+    if full_output:
+        try:
+            return tck, fp, ier, _iermess2[ierm][0]
+        except KeyError:
+            return tck, fp, ier, _iermess2['unknown'][0]
+    else:
+        return tck
+
+
+@xp_capabilities(out_of_scope=True)
+def bisplev(x, y, tck, dx=0, dy=0):
+    """
+    Evaluate a bivariate B-spline and its derivatives.
+
+    Return a rank-2 array of spline function values (or spline derivative
+    values) at points given by the cross-product of the rank-1 arrays `x` and
+    `y`.  In special cases, return an array or just a float if either `x` or
+    `y` or both are floats.  Based on BISPEV and PARDER from FITPACK.
+
+    Parameters
+    ----------
+    x, y : ndarray
+        Rank-1 arrays specifying the domain over which to evaluate the
+        spline or its derivative.
+    tck : tuple
+        A sequence of length 5 returned by `bisplrep` containing the knot
+        locations, the coefficients, and the degree of the spline:
+        [tx, ty, c, kx, ky].
+    dx, dy : int, optional
+        The orders of the partial derivatives in `x` and `y` respectively.
+
+    Returns
+    -------
+    vals : ndarray
+        The B-spline or its derivative evaluated over the set formed by
+        the cross-product of `x` and `y`.
+
+    See Also
+    --------
+    splprep, splrep, splint, sproot, splev
+    UnivariateSpline, BivariateSpline
+
+    Notes
+    -----
+    See `bisplrep` to generate the `tck` representation.
+
+    References
+    ----------
+    .. [1] Dierckx P. : An algorithm for surface fitting
+       with spline functions
+       Ima J. Numer. Anal. 1 (1981) 267-283.
+    .. [2] Dierckx P. : An algorithm for surface fitting
+       with spline functions
+       report tw50, Dept. Computer Science,K.U.Leuven, 1980.
+    .. [3] Dierckx P. : Curve and surface fitting with splines,
+       Monographs on Numerical Analysis, Oxford University Press, 1993.
+
+    Examples
+    --------
+    Examples are given :ref:`in the tutorial `.
+
+    """
+    tx, ty, c, kx, ky = tck
+    if not (0 <= dx < kx):
+        raise ValueError(f"0 <= dx = {dx} < kx = {kx} must hold")
+    if not (0 <= dy < ky):
+        raise ValueError(f"0 <= dy = {dy} < ky = {ky} must hold")
+    x, y = map(atleast_1d, [x, y])
+    if (len(x.shape) != 1) or (len(y.shape) != 1):
+        raise ValueError("First two entries should be rank-1 arrays.")
+
+    msg = "Too many data points to interpolate."
+
+    _int_overflow(x.size * y.size, MemoryError, msg=msg)
+
+    if dx != 0 or dy != 0:
+        _int_overflow((tx.size - kx - 1)*(ty.size - ky - 1),
+                      MemoryError, msg=msg)
+        z, ier = _fitpack.parder(tx, ty, c, kx, ky, dx, dy, x, y)
+    else:
+        z, ier = _fitpack.bispev(tx, ty, c, kx, ky, x, y)
+
+    if ier == 10:
+        raise ValueError("Invalid input data")
+    if ier:
+        raise TypeError("An error occurred")
+    z = z.reshape((len(x), len(y)))
+    if len(z) > 1:
+        return z
+    if len(z[0]) > 1:
+        return z[0]
+    return z[0][0]
+
+
+def dblint(xa, xb, ya, yb, tck):
+    """Evaluate the integral of a spline over area [xa,xb] x [ya,yb].
+
+    Parameters
+    ----------
+    xa, xb : float
+        The end-points of the x integration interval.
+    ya, yb : float
+        The end-points of the y integration interval.
+    tck : list [tx, ty, c, kx, ky]
+        A sequence of length 5 returned by bisplrep containing the knot
+        locations tx, ty, the coefficients c, and the degrees kx, ky
+        of the spline.
+
+    Returns
+    -------
+    integ : float
+        The value of the resulting integral.
+    """
+    tx, ty, c, kx, ky = tck
+    return _fitpack.dblint(tx, ty, c, kx, ky, xa, xb, ya, yb)
+
+
+def insert(x, tck, m=1, per=0):
+    # see the docstring of `_fitpack_py/insert`
+    t, c, k = tck
+    try:
+        c[0][0]
+        parametric = True
+    except Exception:
+        parametric = False
+    if parametric:
+        cc = []
+        for c_vals in c:
+            tt, cc_val, kk = insert(x, [t, c_vals, k], m)
+            cc.append(cc_val)
+        return (tt, cc, kk)
+    else:
+        tt, cc, ier = _fitpack.insert(per, t, c, k, x, m)
+        if ier == 10:
+            raise ValueError("Invalid input data")
+        if ier:
+            raise TypeError("An error occurred")
+        return (tt, cc, k)
+
+
+def splder(tck, n=1, xp=None):
+    # see the docstring of `_fitpack_py/splder`
+    if n < 0:
+        return splantider(tck, -n)
+
+    t, c, k = tck
+
+    if xp is None:
+        xp = array_namespace(t, c)
+
+    if n > k:
+        raise ValueError(f"Order of derivative (n = {n!r}) must be <= "
+                         f"order of spline (k = {tck[2]!r})")
+
+    # Extra axes for the trailing dims of the `c` array:
+    sh = (slice(None),) + ((None,)*len(c.shape[1:]))
+
+    with np.errstate(invalid='raise', divide='raise'):
+        try:
+            for j in range(n):
+                # See e.g. Schumaker, Spline Functions: Basic Theory, Chapter 5
+
+                # Compute the denominator in the differentiation formula.
+                # (and append trailing dims, if necessary)
+                dt = t[k+1:-1] - t[1:-k-1]
+                dt = dt[sh]
+                # Compute the new coefficients
+                c = (c[1:-1-k, ...] - c[:-2-k, ...]) * k / dt
+                # Pad coefficient array to same size as knots (FITPACK
+                # convention)
+                c = concat_1d(xp, c, xp.zeros((k,) + c.shape[1:]))
+                # Adjust knots
+                t = t[1:-1]
+                k -= 1
+        except FloatingPointError as e:
+            raise ValueError("The spline has internal repeated knots "
+                              f"and is not differentiable {n} times") from e
+
+    return t, c, k
+
+
+def splantider(tck, n=1, *, xp=None):
+    # see the docstring of `_fitpack_py/splantider`
+    if n < 0:
+        return splder(tck, -n)
+
+    t, c, k = tck
+
+    if xp is None:
+        xp = array_namespace(t, c)
+
+    # Extra axes for the trailing dims of the `c` array:
+    sh = (slice(None),) + (None,)*len(c.shape[1:])
+
+    for j in range(n):
+        # This is the inverse set of operations to splder.
+
+        # Compute the multiplier in the antiderivative formula.
+        dt = t[k+1:] - t[:-k-1]
+        dt = dt[sh]
+        # Compute the new coefficients
+        c = xp.cumulative_sum(c[:-k-1, ...] * dt, axis=0) / (k + 1)
+        c = concat_1d(
+            xp,
+            xp.zeros((1,) + c.shape[1:]),
+            c,
+            xp.stack([c[-1, ...]] * (k+2)),
+        )
+        # New knots
+        t = concat_1d(xp, t[0], t, t[-1])
+        k += 1
+
+    return t, c, k
diff --git a/.venv/lib/python3.12/site-packages/scipy/interpolate/_fitpack_py.py b/.venv/lib/python3.12/site-packages/scipy/interpolate/_fitpack_py.py
new file mode 100644
index 0000000000000000000000000000000000000000..66b18cbea515f8be5e1c0d4b9eb1daf8f474d6fd
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/interpolate/_fitpack_py.py
@@ -0,0 +1,906 @@
+__all__ = ['splrep', 'splprep', 'splev', 'splint', 'sproot', 'spalde',
+           'bisplrep', 'bisplev', 'insert', 'splder', 'splantider']
+
+
+import numpy as np
+
+# These are in the API for fitpack even if not used in fitpack.py itself.
+from ._fitpack_impl import bisplrep, bisplev, dblint  # noqa: F401
+from . import _fitpack_impl as _impl
+from ._bsplines import BSpline
+from scipy._lib._array_api import xp_capabilities
+
+
+@xp_capabilities(out_of_scope=True)
+def splprep(x, w=None, u=None, ub=None, ue=None, k=3, task=0, s=None, t=None,
+            full_output=0, nest=None, per=0, quiet=1):
+    """
+    Find the B-spline representation of an N-D curve.
+
+    .. legacy:: function
+
+        Specifically, we recommend using `make_splprep` in new code.
+
+    Given a list of N rank-1 arrays, `x`, which represent a curve in
+    N-dimensional space parametrized by `u`, find a smooth approximating
+    spline curve g(`u`). Uses the FORTRAN routine parcur from FITPACK.
+
+    Parameters
+    ----------
+    x : array_like
+        A list of sample vector arrays representing the curve.
+    w : array_like, optional
+        Strictly positive rank-1 array of weights the same length as `x[0]`.
+        The weights are used in computing the weighted least-squares spline
+        fit. If the errors in the `x` values have standard-deviation given by
+        the vector d, then `w` should be 1/d. Default is ``ones(len(x[0]))``.
+    u : array_like, optional
+        An array of parameter values. If not given, these values are
+        calculated automatically as ``M = len(x[0])``, where
+
+        - ``v[0] = 0``
+        - ``v[i] = v[i-1] + distance(`x[i]`, `x[i-1]`)``
+        - ``u[i] = v[i] / v[M-1]``
+
+    ub, ue : int, optional
+        The end-points of the parameters interval.  Defaults to
+        u[0] and u[-1].
+    k : int, optional
+        Degree of the spline. Cubic splines are recommended.
+        Even values of `k` should be avoided especially with a small s-value.
+        ``1 <= k <= 5``, default is 3.
+    task : int, optional
+        If task==0 (default), find t and c for a given smoothing factor, s.
+        If task==1, find t and c for another value of the smoothing factor, s.
+        There must have been a previous call with task=0 or task=1
+        for the same set of data.
+        If task=-1 find the weighted least square spline for a given set of
+        knots, t.
+    s : float, optional
+        A smoothing condition.  The amount of smoothness is determined by
+        satisfying the conditions: ``sum((w * (y - g))**2,axis=0) <= s``,
+        where g(x) is the smoothed interpolation of (x,y).  The user can
+        use `s` to control the trade-off between closeness and smoothness
+        of fit.  Larger `s` means more smoothing while smaller values of `s`
+        indicate less smoothing. Recommended values of `s` depend on the
+        weights, w.  If the weights represent the inverse of the
+        standard-deviation of y, then a good `s` value should be found in
+        the range ``(m-sqrt(2*m),m+sqrt(2*m))``, where m is the number of
+        data points in x, y, and w.
+    t : array, optional
+        The knots needed for ``task=-1``.
+        There must be at least ``2*k+2`` knots.
+    full_output : int, optional
+        If non-zero, then return optional outputs.
+    nest : int, optional
+        An over-estimate of the total number of knots of the spline to
+        help in determining the storage space.  By default nest=m/2.
+        Always large enough is nest=m+k+1.
+    per : int, optional
+       If non-zero, data points are considered periodic with period
+       ``x[m-1] - x[0]`` and a smooth periodic spline approximation is
+       returned.  Values of ``y[m-1]`` and ``w[m-1]`` are not used.
+    quiet : int, optional
+         Non-zero to suppress messages.
+
+    Returns
+    -------
+    tck : tuple
+        A tuple, ``(t,c,k)`` containing the vector of knots, the B-spline
+        coefficients, and the degree of the spline.
+    u : array
+        An array of the values of the parameter.
+    fp : float
+        The weighted sum of squared residuals of the spline approximation.
+    ier : int
+        An integer flag about splrep success.  Success is indicated
+        if ier<=0. If ier in [1,2,3] an error occurred but was not raised.
+        Otherwise an error is raised.
+    msg : str
+        A message corresponding to the integer flag, ier.
+
+    See Also
+    --------
+    splrep, splev, sproot, spalde, splint,
+    bisplrep, bisplev
+    UnivariateSpline, BivariateSpline
+    BSpline
+    make_interp_spline
+
+    Notes
+    -----
+    See `splev` for evaluation of the spline and its derivatives.
+    The number of dimensions N must be smaller than 11.
+
+    The number of coefficients in the `c` array is ``k+1`` less than the number
+    of knots, ``len(t)``. This is in contrast with `splrep`, which zero-pads
+    the array of coefficients to have the same length as the array of knots.
+    These additional coefficients are ignored by evaluation routines, `splev`
+    and `BSpline`.
+
+    References
+    ----------
+    .. [1] P. Dierckx, "Algorithms for smoothing data with periodic and
+        parametric splines, Computer Graphics and Image Processing",
+        20 (1982) 171-184.
+    .. [2] P. Dierckx, "Algorithms for smoothing data with periodic and
+        parametric splines", report tw55, Dept. Computer Science,
+        K.U.Leuven, 1981.
+    .. [3] P. Dierckx, "Curve and surface fitting with splines", Monographs on
+        Numerical Analysis, Oxford University Press, 1993.
+
+    Examples
+    --------
+    Generate a discretization of a limacon curve in the polar coordinates:
+
+    >>> import numpy as np
+    >>> phi = np.linspace(0, 2.*np.pi, 40)
+    >>> r = 0.5 + np.cos(phi)         # polar coords
+    >>> x, y = r * np.cos(phi), r * np.sin(phi)    # convert to cartesian
+
+    And interpolate:
+
+    >>> from scipy.interpolate import splprep, splev
+    >>> tck, u = splprep([x, y], s=0)
+    >>> new_points = splev(u, tck)
+
+    Notice that (i) we force interpolation by using ``s=0``,
+    (ii) the parameterization, ``u``, is generated automatically.
+    Now plot the result:
+
+    >>> import matplotlib.pyplot as plt
+    >>> fig, ax = plt.subplots()
+    >>> ax.plot(x, y, 'ro')
+    >>> ax.plot(new_points[0], new_points[1], 'r-')
+    >>> plt.show()
+
+    """
+
+    res = _impl.splprep(x, w, u, ub, ue, k, task, s, t, full_output, nest, per,
+                        quiet)
+    return res
+
+
+@xp_capabilities(out_of_scope=True)
+def splrep(x, y, w=None, xb=None, xe=None, k=3, task=0, s=None, t=None,
+           full_output=0, per=0, quiet=1):
+    """
+    Find the B-spline representation of a 1-D curve.
+
+    .. legacy:: function
+
+        Specifically, we recommend using `make_splrep` in new code.
+
+
+    Given the set of data points ``(x[i], y[i])`` determine a smooth spline
+    approximation of degree k on the interval ``xb <= x <= xe``.
+
+    Parameters
+    ----------
+    x, y : array_like
+        The data points defining a curve ``y = f(x)``.
+    w : array_like, optional
+        Strictly positive rank-1 array of weights the same length as `x` and `y`.
+        The weights are used in computing the weighted least-squares spline
+        fit. If the errors in the `y` values have standard-deviation given by the
+        vector ``d``, then `w` should be ``1/d``. Default is ``ones(len(x))``.
+    xb, xe : float, optional
+        The interval to fit.  If None, these default to ``x[0]`` and ``x[-1]``
+        respectively.
+    k : int, optional
+        The degree of the spline fit. It is recommended to use cubic splines.
+        Even values of `k` should be avoided especially with small `s` values.
+        ``1 <= k <= 5``.
+    task : {1, 0, -1}, optional
+        If ``task==0``, find ``t`` and ``c`` for a given smoothing factor, `s`.
+
+        If ``task==1`` find ``t`` and ``c`` for another value of the smoothing factor,
+        `s`. There must have been a previous call with ``task=0`` or ``task=1`` for
+        the same set of data (``t`` will be stored an used internally)
+
+        If ``task=-1`` find the weighted least square spline for a given set of
+        knots, ``t``. These should be interior knots as knots on the ends will be
+        added automatically.
+    s : float, optional
+        A smoothing condition. The amount of smoothness is determined by
+        satisfying the conditions: ``sum((w * (y - g))**2,axis=0) <= s`` where ``g(x)``
+        is the smoothed interpolation of ``(x,y)``. The user can use `s` to control
+        the tradeoff between closeness and smoothness of fit. Larger `s` means
+        more smoothing while smaller values of `s` indicate less smoothing.
+        Recommended values of `s` depend on the weights, `w`. If the weights
+        represent the inverse of the standard-deviation of `y`, then a good `s`
+        value should be found in the range ``(m-sqrt(2*m),m+sqrt(2*m))`` where ``m`` is
+        the number of datapoints in `x`, `y`, and `w`. default : ``s=m-sqrt(2*m)`` if
+        weights are supplied. ``s = 0.0`` (interpolating) if no weights are
+        supplied.
+    t : array_like, optional
+        The knots needed for ``task=-1``. If given then task is automatically set
+        to ``-1``.
+    full_output : bool, optional
+        If non-zero, then return optional outputs.
+    per : bool, optional
+        If non-zero, data points are considered periodic with period ``x[m-1]`` -
+        ``x[0]`` and a smooth periodic spline approximation is returned. Values of
+        ``y[m-1]`` and ``w[m-1]`` are not used.
+        The default is zero, corresponding to boundary condition 'not-a-knot'.
+    quiet : bool, optional
+        Non-zero to suppress messages.
+
+    Returns
+    -------
+    tck : tuple
+        A tuple ``(t,c,k)`` containing the vector of knots, the B-spline
+        coefficients, and the degree of the spline.
+    fp : array, optional
+        The weighted sum of squared residuals of the spline approximation.
+    ier : int, optional
+        An integer flag about splrep success. Success is indicated if ``ier<=0``.
+        If ``ier in [1,2,3]``, an error occurred but was not raised. Otherwise an
+        error is raised.
+    msg : str, optional
+        A message corresponding to the integer flag, `ier`.
+
+    See Also
+    --------
+    UnivariateSpline, BivariateSpline
+    splprep, splev, sproot, spalde, splint
+    bisplrep, bisplev
+    BSpline
+    make_interp_spline
+
+    Notes
+    -----
+    See `splev` for evaluation of the spline and its derivatives. Uses the
+    FORTRAN routine ``curfit`` from FITPACK.
+
+    The user is responsible for assuring that the values of `x` are unique.
+    Otherwise, `splrep` will not return sensible results.
+
+    If provided, knots `t` must satisfy the Schoenberg-Whitney conditions,
+    i.e., there must be a subset of data points ``x[j]`` such that
+    ``t[j] < x[j] < t[j+k+1]``, for ``j=0, 1,...,n-k-2``.
+
+    This routine zero-pads the coefficients array ``c`` to have the same length
+    as the array of knots ``t`` (the trailing ``k + 1`` coefficients are ignored
+    by the evaluation routines, `splev` and `BSpline`.) This is in contrast with
+    `splprep`, which does not zero-pad the coefficients.
+
+    The default boundary condition is 'not-a-knot', i.e. the first and second
+    segment at a curve end are the same polynomial. More boundary conditions are
+    available in `CubicSpline`.
+
+    References
+    ----------
+    Based on algorithms described in [1]_, [2]_, [3]_, and [4]_:
+
+    .. [1] P. Dierckx, "An algorithm for smoothing, differentiation and
+       integration of experimental data using spline functions",
+       J.Comp.Appl.Maths 1 (1975) 165-184.
+    .. [2] P. Dierckx, "A fast algorithm for smoothing data on a rectangular
+       grid while using spline functions", SIAM J.Numer.Anal. 19 (1982)
+       1286-1304.
+    .. [3] P. Dierckx, "An improved algorithm for curve fitting with spline
+       functions", report tw54, Dept. Computer Science,K.U. Leuven, 1981.
+    .. [4] P. Dierckx, "Curve and surface fitting with splines", Monographs on
+       Numerical Analysis, Oxford University Press, 1993.
+
+    Examples
+    --------
+    You can interpolate 1-D points with a B-spline curve.
+    Further examples are given in
+    :ref:`in the tutorial `.
+
+    >>> import numpy as np
+    >>> import matplotlib.pyplot as plt
+    >>> from scipy.interpolate import splev, splrep
+    >>> x = np.linspace(0, 10, 10)
+    >>> y = np.sin(x)
+    >>> spl = splrep(x, y)
+    >>> x2 = np.linspace(0, 10, 200)
+    >>> y2 = splev(x2, spl)
+    >>> plt.plot(x, y, 'o', x2, y2)
+    >>> plt.show()
+
+    """
+    res = _impl.splrep(x, y, w, xb, xe, k, task, s, t, full_output, per, quiet)
+    return res
+
+
+@xp_capabilities(out_of_scope=True)
+def splev(x, tck, der=0, ext=0):
+    """
+    Evaluate a B-spline or its derivatives.
+
+    .. legacy:: function
+
+        Specifically, we recommend constructing a `BSpline` object and using
+        its ``__call__`` method.
+
+    Given the knots and coefficients of a B-spline representation, evaluate
+    the value of the smoothing polynomial and its derivatives. This is a
+    wrapper around the FORTRAN routines splev and splder of FITPACK.
+
+    Parameters
+    ----------
+    x : array_like
+        An array of points at which to return the value of the smoothed
+        spline or its derivatives. If `tck` was returned from `splprep`,
+        then the parameter values, u should be given.
+    tck : BSpline instance or tuple
+        If a tuple, then it should be a sequence of length 3 returned by
+        `splrep` or `splprep` containing the knots, coefficients, and degree
+        of the spline. (Also see Notes.)
+    der : int, optional
+        The order of derivative of the spline to compute (must be less than
+        or equal to k, the degree of the spline).
+    ext : int, optional
+        Controls the value returned for elements of ``x`` not in the
+        interval defined by the knot sequence.
+
+        * if ext=0, return the extrapolated value.
+        * if ext=1, return 0
+        * if ext=2, raise a ValueError
+        * if ext=3, return the boundary value.
+
+        The default value is 0.
+
+    Returns
+    -------
+    y : ndarray or list of ndarrays
+        An array of values representing the spline function evaluated at
+        the points in `x`.  If `tck` was returned from `splprep`, then this
+        is a list of arrays representing the curve in an N-D space.
+
+    See Also
+    --------
+    splprep, splrep, sproot, spalde, splint
+    bisplrep, bisplev
+    BSpline
+
+    Notes
+    -----
+    Manipulating the tck-tuples directly is not recommended. In new code,
+    prefer using `BSpline` objects.
+
+    References
+    ----------
+    .. [1] C. de Boor, "On calculating with b-splines", J. Approximation
+        Theory, 6, p.50-62, 1972.
+    .. [2] M. G. Cox, "The numerical evaluation of b-splines", J. Inst. Maths
+        Applics, 10, p.134-149, 1972.
+    .. [3] P. Dierckx, "Curve and surface fitting with splines", Monographs
+        on Numerical Analysis, Oxford University Press, 1993.
+
+    Examples
+    --------
+    Examples are given :ref:`in the tutorial `.
+
+    A comparison between `splev`, `splder` and `spalde` to compute the derivatives of a 
+    B-spline can be found in the `spalde` examples section.
+
+    """
+    if isinstance(tck, BSpline):
+        if tck.c.ndim > 1:
+            mesg = ("Calling splev() with BSpline objects with c.ndim > 1 is "
+                    "not allowed. Use BSpline.__call__(x) instead.")
+            raise ValueError(mesg)
+
+        # remap the out-of-bounds behavior
+        try:
+            extrapolate = {0: True, }[ext]
+        except KeyError as e:
+            raise ValueError(f"Extrapolation mode {ext} is not supported "
+                             "by BSpline.") from e
+
+        return tck(x, der, extrapolate=extrapolate)
+    else:
+        return _impl.splev(x, tck, der, ext)
+
+
+@xp_capabilities(out_of_scope=True)
+def splint(a, b, tck, full_output=0):
+    """
+    Evaluate the definite integral of a B-spline between two given points.
+
+    .. legacy:: function
+
+        Specifically, we recommend constructing a `BSpline` object and using its
+        ``integrate`` method.
+
+    Parameters
+    ----------
+    a, b : float
+        The end-points of the integration interval.
+    tck : tuple or a BSpline instance
+        If a tuple, then it should be a sequence of length 3, containing the
+        vector of knots, the B-spline coefficients, and the degree of the
+        spline (see `splev`).
+    full_output : int, optional
+        Non-zero to return optional output.
+
+    Returns
+    -------
+    integral : float
+        The resulting integral.
+    wrk : ndarray
+        An array containing the integrals of the normalized B-splines
+        defined on the set of knots.
+        (Only returned if `full_output` is non-zero)
+
+    See Also
+    --------
+    splprep, splrep, sproot, spalde, splev
+    bisplrep, bisplev
+    BSpline
+
+    Notes
+    -----
+    `splint` silently assumes that the spline function is zero outside the data
+    interval (`a`, `b`).
+
+    Manipulating the tck-tuples directly is not recommended. In new code,
+    prefer using the `BSpline` objects.
+
+    References
+    ----------
+    .. [1] P.W. Gaffney, The calculation of indefinite integrals of b-splines",
+        J. Inst. Maths Applics, 17, p.37-41, 1976.
+    .. [2] P. Dierckx, "Curve and surface fitting with splines", Monographs
+        on Numerical Analysis, Oxford University Press, 1993.
+
+    Examples
+    --------
+    Examples are given :ref:`in the tutorial `.
+
+    """
+    if isinstance(tck, BSpline):
+        if tck.c.ndim > 1:
+            mesg = ("Calling splint() with BSpline objects with c.ndim > 1 is "
+                    "not allowed. Use BSpline.integrate() instead.")
+            raise ValueError(mesg)
+
+        if full_output != 0:
+            mesg = (f"full_output = {full_output} is not supported. Proceeding as if "
+                    "full_output = 0")
+
+        return tck.integrate(a, b, extrapolate=False)
+    else:
+        return _impl.splint(a, b, tck, full_output)
+
+
+@xp_capabilities(out_of_scope=True)
+def sproot(tck, mest=10):
+    """
+    Find the roots of a cubic B-spline.
+
+    .. legacy:: function
+
+        Specifically, we recommend constructing a `BSpline` object and using the
+        following pattern: `PPoly.from_spline(spl).roots()`.
+
+    Given the knots (>=8) and coefficients of a cubic B-spline return the
+    roots of the spline.
+
+    Parameters
+    ----------
+    tck : tuple or a BSpline object
+        If a tuple, then it should be a sequence of length 3, containing the
+        vector of knots, the B-spline coefficients, and the degree of the
+        spline.
+        The number of knots must be >= 8, and the degree must be 3.
+        The knots must be a montonically increasing sequence.
+    mest : int, optional
+        An estimate of the number of zeros (Default is 10).
+
+    Returns
+    -------
+    zeros : ndarray
+        An array giving the roots of the spline.
+
+    See Also
+    --------
+    splprep, splrep, splint, spalde, splev
+    bisplrep, bisplev
+    BSpline
+
+    Notes
+    -----
+    Manipulating the tck-tuples directly is not recommended. In new code,
+    prefer using the `BSpline` objects.
+
+    References
+    ----------
+    .. [1] C. de Boor, "On calculating with b-splines", J. Approximation
+        Theory, 6, p.50-62, 1972.
+    .. [2] M. G. Cox, "The numerical evaluation of b-splines", J. Inst. Maths
+        Applics, 10, p.134-149, 1972.
+    .. [3] P. Dierckx, "Curve and surface fitting with splines", Monographs
+        on Numerical Analysis, Oxford University Press, 1993.
+
+    Examples
+    --------
+
+    For some data, this method may miss a root. This happens when one of
+    the spline knots (which FITPACK places automatically) happens to
+    coincide with the true root. A workaround is to convert to `PPoly`,
+    which uses a different root-finding algorithm.
+
+    For example,
+
+    >>> x = [1.96, 1.97, 1.98, 1.99, 2.00, 2.01, 2.02, 2.03, 2.04, 2.05]
+    >>> y = [-6.365470e-03, -4.790580e-03, -3.204320e-03, -1.607270e-03,
+    ...      4.440892e-16,  1.616930e-03,  3.243000e-03,  4.877670e-03,
+    ...      6.520430e-03,  8.170770e-03]
+    >>> from scipy.interpolate import splrep, sproot, PPoly
+    >>> tck = splrep(x, y, s=0)
+    >>> sproot(tck)
+    array([], dtype=float64)
+
+    Converting to a PPoly object does find the roots at ``x=2``:
+
+    >>> ppoly = PPoly.from_spline(tck)
+    >>> ppoly.roots(extrapolate=False)
+    array([2.])
+
+
+    Further examples are given :ref:`in the tutorial
+    `.
+
+    """
+    if isinstance(tck, BSpline):
+        if tck.c.ndim > 1:
+            mesg = ("Calling sproot() with BSpline objects with c.ndim > 1 is "
+                    "not allowed.")
+            raise ValueError(mesg)
+
+        t, c, k = tck.tck
+
+        # _impl.sproot expects the interpolation axis to be last, so roll it.
+        # NB: This transpose is a no-op if c is 1D.
+        sh = tuple(range(c.ndim))
+        c = c.transpose(sh[1:] + (0,))
+        return _impl.sproot((t, c, k), mest)
+    else:
+        return _impl.sproot(tck, mest)
+
+
+@xp_capabilities(out_of_scope=True)
+def spalde(x, tck):
+    """
+    Evaluate a B-spline and all its derivatives at one point (or set of points) up
+    to order k (the degree of the spline), being 0 the spline itself.
+
+    .. legacy:: function
+
+        Specifically, we recommend constructing a `BSpline` object and evaluate
+        its derivative in a loop or a list comprehension.
+
+    Parameters
+    ----------
+    x : array_like
+        A point or a set of points at which to evaluate the derivatives.
+        Note that ``t(k) <= x <= t(n-k+1)`` must hold for each `x`.
+    tck : tuple
+        A tuple (t,c,k) containing the vector of knots,
+        the B-spline coefficients, and the degree of the spline whose 
+        derivatives to compute.
+
+    Returns
+    -------
+    results : {ndarray, list of ndarrays}
+        An array (or a list of arrays) containing all derivatives
+        up to order k inclusive for each point `x`, being the first element the 
+        spline itself.
+
+    See Also
+    --------
+    splprep, splrep, splint, sproot, splev, bisplrep, bisplev,
+    UnivariateSpline, BivariateSpline
+
+    References
+    ----------
+    .. [1] de Boor C : On calculating with b-splines, J. Approximation Theory
+       6 (1972) 50-62.
+    .. [2] Cox M.G. : The numerical evaluation of b-splines, J. Inst. Maths
+       applics 10 (1972) 134-149.
+    .. [3] Dierckx P. : Curve and surface fitting with splines, Monographs on
+       Numerical Analysis, Oxford University Press, 1993.
+
+    Examples
+    --------
+    To calculate the derivatives of a B-spline there are several aproaches. 
+    In this example, we will demonstrate that `spalde` is equivalent to
+    calling `splev` and `splder`.
+    
+    >>> import numpy as np
+    >>> import matplotlib.pyplot as plt
+    >>> from scipy.interpolate import BSpline, spalde, splder, splev
+    
+    >>> # Store characteristic parameters of a B-spline
+    >>> tck = ((-2, -2, -2, -2, -1, 0, 1, 2, 2, 2, 2),  # knots
+    ...        (0, 0, 0, 6, 0, 0, 0),  # coefficients
+    ...        3)  # degree (cubic)
+    >>> # Instance a B-spline object
+    >>> # `BSpline` objects are preferred, except for spalde()
+    >>> bspl = BSpline(tck[0], tck[1], tck[2])
+    >>> # Generate extra points to get a smooth curve
+    >>> x = np.linspace(min(tck[0]), max(tck[0]), 100)
+    
+    Evaluate the curve and all derivatives
+    
+    >>> # The order of derivative must be less or equal to k, the degree of the spline
+    >>> # Method 1: spalde()
+    >>> f1_y_bsplin = [spalde(i, tck)[0] for i in x ]  # The B-spline itself
+    >>> f1_y_deriv1 = [spalde(i, tck)[1] for i in x ]  # 1st derivative
+    >>> f1_y_deriv2 = [spalde(i, tck)[2] for i in x ]  # 2nd derivative
+    >>> f1_y_deriv3 = [spalde(i, tck)[3] for i in x ]  # 3rd derivative
+    >>> # You can reach the same result by using `splev`and `splder`
+    >>> f2_y_deriv3 = splev(x, bspl, der=3)
+    >>> f3_y_deriv3 = splder(bspl, n=3)(x)
+    
+    >>> # Generate a figure with three axes for graphic comparison
+    >>> fig, (ax1, ax2, ax3) = plt.subplots(1, 3, figsize=(16, 5))
+    >>> suptitle = fig.suptitle(f'Evaluate a B-spline and all derivatives')
+    >>> # Plot B-spline and all derivatives using the three methods
+    >>> orders = range(4)
+    >>> linetypes = ['-', '--', '-.', ':']
+    >>> labels = ['B-Spline', '1st deriv.', '2nd deriv.', '3rd deriv.']
+    >>> functions = ['splev()', 'splder()', 'spalde()']
+    >>> for order, linetype, label in zip(orders, linetypes, labels):
+    ...     ax1.plot(x, splev(x, bspl, der=order), linetype, label=label)
+    ...     ax2.plot(x, splder(bspl, n=order)(x), linetype, label=label)
+    ...     ax3.plot(x, [spalde(i, tck)[order] for i in x], linetype, label=label)
+    >>> for ax, function in zip((ax1, ax2, ax3), functions):
+    ...     ax.set_title(function)
+    ...     ax.legend()
+    >>> plt.tight_layout()
+    >>> plt.show()
+
+    """
+    if isinstance(tck, BSpline):
+        raise TypeError("spalde does not accept BSpline instances.")
+    else:
+        return _impl.spalde(x, tck)
+
+
+@xp_capabilities(out_of_scope=True)
+def insert(x, tck, m=1, per=0):
+    """
+    Insert knots into a B-spline.
+
+    .. legacy:: function
+
+        Specifically, we recommend constructing a `BSpline` object and using
+        its ``insert_knot`` method.
+
+    Given the knots and coefficients of a B-spline representation, create a
+    new B-spline with a knot inserted `m` times at point `x`.
+    This is a wrapper around the FORTRAN routine insert of FITPACK.
+
+    Parameters
+    ----------
+    x : float
+        A knot value at which to insert a new knot.  If `tck` was returned
+        from ``splprep``, then the parameter values, u should be given.
+    tck : a `BSpline` instance or a tuple
+        If tuple, then it is expected to be a tuple (t,c,k) containing
+        the vector of knots, the B-spline coefficients, and the degree of
+        the spline.
+    m : int, optional
+        The number of times to insert the given knot (its multiplicity).
+        Default is 1.
+    per : int, optional
+        If non-zero, the input spline is considered periodic.
+
+    Returns
+    -------
+    BSpline instance or a tuple
+        A new B-spline with knots t, coefficients c, and degree k.
+        ``t(k+1) <= x <= t(n-k)``, where k is the degree of the spline.
+        In case of a periodic spline (``per != 0``) there must be
+        either at least k interior knots t(j) satisfying ``t(k+1)>> from scipy.interpolate import splrep, insert
+    >>> import numpy as np
+    >>> x = np.linspace(0, 10, 5)
+    >>> y = np.sin(x)
+    >>> tck = splrep(x, y)
+    >>> tck[0]
+    array([ 0.,  0.,  0.,  0.,  5., 10., 10., 10., 10.])
+
+    A knot is inserted:
+
+    >>> tck_inserted = insert(3, tck)
+    >>> tck_inserted[0]
+    array([ 0.,  0.,  0.,  0.,  3.,  5., 10., 10., 10., 10.])
+
+    Some knots are inserted:
+
+    >>> tck_inserted2 = insert(8, tck, m=3)
+    >>> tck_inserted2[0]
+    array([ 0.,  0.,  0.,  0.,  5.,  8.,  8.,  8., 10., 10., 10., 10.])
+
+    """
+    if isinstance(tck, BSpline):
+
+        t, c, k = tck.tck
+
+        # FITPACK expects the interpolation axis to be last, so roll it over
+        # NB: if c array is 1D, transposes are no-ops
+        sh = tuple(range(c.ndim))
+        c = c.transpose(sh[1:] + (0,))
+        t_, c_, k_ = _impl.insert(x, (t, c, k), m, per)
+
+        # and roll the last axis back
+        c_ = np.asarray(c_)
+        c_ = c_.transpose((sh[-1],) + sh[:-1])
+        return BSpline(t_, c_, k_)
+    else:
+        return _impl.insert(x, tck, m, per)
+
+
+@xp_capabilities(out_of_scope=True)
+def splder(tck, n=1):
+    """
+    Compute the spline representation of the derivative of a given spline.
+
+    .. legacy:: function
+
+        Specifically, we recommend constructing a `BSpline` object and using its
+        ``derivative`` method.
+
+    Parameters
+    ----------
+    tck : BSpline instance or tuple
+        BSpline instance or a tuple (t,c,k) containing the vector of knots,
+        the B-spline coefficients, and the degree of the spline whose 
+        derivative to compute
+    n : int, optional
+        Order of derivative to evaluate. Default: 1
+
+    Returns
+    -------
+    `BSpline` instance or tuple
+        Spline of order k2=k-n representing the derivative
+        of the input spline.
+        A tuple is returned if the input argument `tck` is a tuple, otherwise
+        a BSpline object is constructed and returned.
+
+    See Also
+    --------
+    splantider, splev, spalde
+    BSpline
+
+    Notes
+    -----
+
+    .. versionadded:: 0.13.0
+
+    Examples
+    --------
+    This can be used for finding maxima of a curve:
+
+    >>> from scipy.interpolate import splrep, splder, sproot
+    >>> import numpy as np
+    >>> x = np.linspace(0, 10, 70)
+    >>> y = np.sin(x)
+    >>> spl = splrep(x, y, k=4)
+
+    Now, differentiate the spline and find the zeros of the
+    derivative. (NB: `sproot` only works for order 3 splines, so we
+    fit an order 4 spline):
+
+    >>> dspl = splder(spl)
+    >>> sproot(dspl) / np.pi
+    array([ 0.50000001,  1.5       ,  2.49999998])
+
+    This agrees well with roots :math:`\\pi/2 + n\\pi` of
+    :math:`\\cos(x) = \\sin'(x)`.
+
+    A comparison between `splev`, `splder` and `spalde` to compute the derivatives of a 
+    B-spline can be found in the `spalde` examples section.
+
+    """
+    if isinstance(tck, BSpline):
+        return tck.derivative(n)
+    else:
+        return _impl.splder(tck, n)
+
+
+@xp_capabilities(out_of_scope=True)
+def splantider(tck, n=1):
+    """
+    Compute the spline for the antiderivative (integral) of a given spline.
+
+    .. legacy:: function
+
+        Specifically, we recommend constructing a `BSpline` object and using its
+        ``antiderivative`` method.
+
+    Parameters
+    ----------
+    tck : BSpline instance or a tuple of (t, c, k)
+        Spline whose antiderivative to compute
+    n : int, optional
+        Order of antiderivative to evaluate. Default: 1
+
+    Returns
+    -------
+    BSpline instance or a tuple of (t2, c2, k2)
+        Spline of order k2=k+n representing the antiderivative of the input
+        spline.
+        A tuple is returned iff the input argument `tck` is a tuple, otherwise
+        a BSpline object is constructed and returned.
+
+    See Also
+    --------
+    splder, splev, spalde
+    BSpline
+
+    Notes
+    -----
+    The `splder` function is the inverse operation of this function.
+    Namely, ``splder(splantider(tck))`` is identical to `tck`, modulo
+    rounding error.
+
+    .. versionadded:: 0.13.0
+
+    Examples
+    --------
+    >>> from scipy.interpolate import splrep, splder, splantider, splev
+    >>> import numpy as np
+    >>> x = np.linspace(0, np.pi/2, 70)
+    >>> y = 1 / np.sqrt(1 - 0.8*np.sin(x)**2)
+    >>> spl = splrep(x, y)
+
+    The derivative is the inverse operation of the antiderivative,
+    although some floating point error accumulates:
+
+    >>> splev(1.7, spl), splev(1.7, splder(splantider(spl)))
+    (array(2.1565429877197317), array(2.1565429877201865))
+
+    Antiderivative can be used to evaluate definite integrals:
+
+    >>> ispl = splantider(spl)
+    >>> splev(np.pi/2, ispl) - splev(0, ispl)
+    2.2572053588768486
+
+    This is indeed an approximation to the complete elliptic integral
+    :math:`K(m) = \\int_0^{\\pi/2} [1 - m\\sin^2 x]^{-1/2} dx`:
+
+    >>> from scipy.special import ellipk
+    >>> ellipk(0.8)
+    2.2572053268208538
+
+    """
+    if isinstance(tck, BSpline):
+        return tck.antiderivative(n)
+    else:
+        return _impl.splantider(tck, n)
+
diff --git a/.venv/lib/python3.12/site-packages/scipy/interpolate/_fitpack_repro.py b/.venv/lib/python3.12/site-packages/scipy/interpolate/_fitpack_repro.py
new file mode 100644
index 0000000000000000000000000000000000000000..9c626932ad7f186ff4696caf8e5ba30527241a70
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/interpolate/_fitpack_repro.py
@@ -0,0 +1,1339 @@
+""" Replicate FITPACK's logic for constructing smoothing spline functions and curves.
+
+    Currently provides analogs of splrep and splprep python routines, i.e.
+    curfit.f and parcur.f routines (the drivers are fpcurf.f and fppara.f, respectively)
+
+    The Fortran sources are from
+    https://github.com/scipy/scipy/blob/maintenance/1.11.x/scipy/interpolate/fitpack/
+
+    .. [1] P. Dierckx, "Algorithms for smoothing data with periodic and
+        parametric splines, Computer Graphics and Image Processing",
+        20 (1982) 171-184.
+        :doi:`10.1016/0146-664X(82)90043-0`.
+    .. [2] P. Dierckx, "Curve and surface fitting with splines", Monographs on
+         Numerical Analysis, Oxford University Press, 1993.
+    .. [3] P. Dierckx, "An algorithm for smoothing, differentiation and integration
+         of experimental data using spline functions",
+         Journal of Computational and Applied Mathematics, vol. I, no 3, p. 165 (1975).
+         :doi:`10.1016/0771-050X(75)90034-0`.
+"""
+import warnings
+import operator
+import numpy as np
+
+from scipy._lib._array_api import array_namespace, concat_1d, xp_capabilities
+
+from ._bsplines import (
+    _not_a_knot, make_interp_spline, BSpline, fpcheck, _lsq_solve_qr,
+    _lsq_solve_qr_for_root_rati_periodic, _periodic_knots
+)
+from . import _dierckx      # type: ignore[attr-defined]
+
+
+#    cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc
+#    c  part 1: determination of the number of knots and their position     c
+#    c  **************************************************************      c
+#
+# https://github.com/scipy/scipy/blob/maintenance/1.11.x/scipy/interpolate/fitpack/fpcurf.f#L31
+
+
+# Hardcoded in curfit.f
+TOL = 0.001
+MAXIT = 20
+
+
+def _get_residuals(x, y, t, k, w, periodic=False):
+    # inline the relevant part of
+    # >>> spl = make_lsq_spline(x, y, w=w2, t=t, k=k)
+    # NB:
+    #     1. y is assumed to be 2D here. For 1D case (parametric=False),
+    #        the call must have been preceded by y = y[:, None] (cf _validate_inputs)
+    #     2. We always sum the squares across axis=1:
+    #         * For 1D (parametric=False), the last dimension has size one,
+    #           so the summation is a no-op.
+    #         * For 2D (parametric=True), the summation is actually how the
+    #           'residuals' are defined, see Eq. (42) in Dierckx1982
+    #           (the reference is in the docstring of `class F`) below.
+    _, _, _, fp, residuals = _lsq_solve_qr(x, y, t, k, w, periodic=periodic)
+    if np.isnan(residuals.sum()):
+        raise ValueError(_iermesg[1])
+    return residuals, fp
+
+def _validate_bc_type(bc_type):
+    if bc_type is None:
+        return "not-a-knot"
+
+    if bc_type not in ("not-a-knot", "periodic"):
+        raise ValueError("Only 'not-a-knot' and 'periodic' "
+                         "boundary conditions are recognised, "
+                         f"found {bc_type}")
+
+    return bc_type
+
+
+def add_knot(x, t, k, residuals):
+    """Add a new knot.
+
+    (Approximately) replicate FITPACK's logic:
+      1. split the `x` array into knot intervals, ``t(j+k) <= x(i) <= t(j+k+1)``
+      2. find the interval with the maximum sum of residuals
+      3. insert a new knot into the middle of that interval.
+
+    NB: a new knot is in fact an `x` value at the middle of the interval.
+    So *the knots are a subset of `x`*.
+
+    This routine is an analog of
+    https://github.com/scipy/scipy/blob/v1.11.4/scipy/interpolate/fitpack/fpcurf.f#L190-L215
+    (cf _split function)
+
+    and https://github.com/scipy/scipy/blob/v1.11.4/scipy/interpolate/fitpack/fpknot.f
+    """
+    new_knot = _dierckx.fpknot(x, t, k, residuals)
+
+    idx_t = np.searchsorted(t, new_knot)
+    t_new = np.r_[t[:idx_t], new_knot, t[idx_t:]]
+    return t_new
+
+
+def _validate_inputs(x, y, w, k, s, xb, xe, parametric, periodic=False):
+    """Common input validations for generate_knots and make_splrep.
+    """
+    x = np.asarray(x, dtype=float)
+    y = np.asarray(y, dtype=float)
+
+    if not x.flags.c_contiguous:
+        x = x.copy()
+    if not y.flags.c_contiguous:
+        y = y.copy()
+
+    if w is None:
+        w = np.ones_like(x, dtype=float)
+    else:
+        w = np.asarray(w, dtype=float)
+        if not w.flags.c_contiguous:
+            w = w.copy()
+        if w.ndim != 1:
+            raise ValueError(f"{w.ndim = } not implemented yet.")
+        if (w < 0).any():
+            raise ValueError("Weights must be non-negative")
+        if w.sum() == 0:
+            raise ValueError("All weights are zero.")
+
+
+    if y.ndim == 0 or y.ndim > 2:
+        raise ValueError(f"{y.ndim = } not supported (must be 1 or 2.)")
+
+    parametric = bool(parametric)
+    if parametric:
+        if y.ndim != 2:
+            raise ValueError(f"{y.ndim = } != 2 not supported with {parametric =}.")
+    else:
+        if y.ndim != 1:
+            raise ValueError(f"{y.ndim = } != 1 not supported with {parametric =}.")
+        # all _impl functions expect y.ndim = 2
+        y = y[:, None]
+
+    if w.shape[0] != x.shape[0]:
+        raise ValueError(f"Weights is incompatible: {w.shape =} != {x.shape}.")
+
+    if x.shape[0] != y.shape[0]:
+        raise ValueError(f"Data is incompatible: {x.shape = } and {y.shape = }.")
+    if x.ndim != 1 or (x[1:] < x[:-1]).any():
+        raise ValueError("Expect `x` to be an ordered 1D sequence.")
+
+    k = operator.index(k)
+
+    if s < 0:
+        raise ValueError(f"`s` must be non-negative. Got {s = }")
+
+    if xb is None:
+        xb = min(x)
+    if xe is None:
+        xe = max(x)
+
+    if periodic and not np.allclose(y[0], y[-1], atol=1e-15):
+        raise ValueError("First and last points does not match which is required "
+                         "for `bc_type='periodic'`.")
+
+    return x, y, w, k, s, xb, xe
+
+
+@xp_capabilities(cpu_only=True, jax_jit=False, allow_dask_compute=True)
+def generate_knots(x, y, *, w=None, xb=None, xe=None,
+                   k=3, s=0, nest=None, bc_type=None):
+    """Generate knot vectors until the Least SQuares (LSQ) criterion is satified.
+
+    Parameters
+    ----------
+    x, y : array_like
+        The data points defining the curve ``y = f(x)``.
+    w : array_like, optional
+        Weights.
+    xb : float, optional
+        The boundary of the approximation interval. If None (default),
+        is set to ``x[0]``.
+    xe : float, optional
+        The boundary of the approximation interval. If None (default),
+        is set to ``x[-1]``.
+    k : int, optional
+        The spline degree. Default is cubic, ``k = 3``.
+    s : float, optional
+        The smoothing factor. Default is ``s = 0``.
+    nest : int, optional
+        Stop when at least this many knots are placed.
+          ends are equivalent.
+    bc_type : str, optional
+        Boundary conditions.
+        Default is `"not-a-knot"`.
+        The following boundary conditions are recognized:
+
+        * ``"not-a-knot"`` (default): The first and second segments are the
+          same polynomial. This is equivalent to having ``bc_type=None``.
+        * ``"periodic"``: The values and the first ``k-1`` derivatives at the
+          ends are equivalent.
+
+    Yields
+    ------
+    t : ndarray
+        Knot vectors with an increasing number of knots.
+        The generator is finite: it stops when the smoothing critetion is
+        satisfied, or when then number of knots exceeds the maximum value:
+        the user-provided `nest` or `x.size + k + 1` --- which is the knot vector
+        for the interpolating spline.
+
+    Examples
+    --------
+    Generate some noisy data and fit a sequence of LSQ splines:
+
+    >>> import numpy as np
+    >>> import matplotlib.pyplot as plt
+    >>> from scipy.interpolate import make_lsq_spline, generate_knots
+    >>> rng = np.random.default_rng(12345)
+    >>> x = np.linspace(-3, 3, 50)
+    >>> y = np.exp(-x**2) + 0.1 * rng.standard_normal(size=50)
+
+    >>> knots = list(generate_knots(x, y, s=1e-10))
+    >>> for t in knots[::3]:
+    ...     spl = make_lsq_spline(x, y, t)
+    ...     xs = xs = np.linspace(-3, 3, 201)
+    ...     plt.plot(xs, spl(xs), '-', label=f'n = {len(t)}', lw=3, alpha=0.7)
+    >>> plt.plot(x, y, 'o', label='data')
+    >>> plt.plot(xs, np.exp(-xs**2), '--')
+    >>> plt.legend()
+
+    Note that increasing the number of knots make the result follow the data
+    more and more closely.
+
+    Also note that a step of the generator may add multiple knots:
+
+    >>> [len(t) for t in knots]
+    [8, 9, 10, 12, 16, 24, 40, 48, 52, 54]
+
+    Notes
+    -----
+    The routine generates successive knots vectors of increasing length, starting
+    from ``2*(k+1)`` to ``len(x) + k + 1``, trying to make knots more dense
+    in the regions where the deviation of the LSQ spline from data is large.
+
+    When the maximum number of knots, ``len(x) + k + 1`` is reached
+    (this happens when ``s`` is small and ``nest`` is large), the generator
+    stops, and the last output is the knots for the interpolation with the
+    not-a-knot boundary condition.
+
+    Knots are located at data sites, unless ``k`` is even and the number of knots
+    is ``len(x) + k + 1``. In that case, the last output of the generator
+    has internal knots at Greville sites, ``(x[1:] + x[:-1]) / 2``.
+
+    .. versionadded:: 1.15.0
+
+    """
+    xp = array_namespace(x, y, w)
+    bc_type = _validate_bc_type(bc_type)
+    periodic = bc_type == 'periodic'
+
+    if s == 0:
+        if nest is not None or w is not None:
+            raise ValueError("s == 0 is interpolation only")
+        # For special-case k=1 (e.g., Lyche and Morken, Eq.(2.16)),
+        # _not_a_knot produces desired knot vector
+        if periodic and k > 1:
+            t = _periodic_knots(x, k)
+        else:
+            t = _not_a_knot(x, k)
+        yield xp.asarray(t)
+        return
+
+    x, y, w, k, s, xb, xe = _validate_inputs(
+        x, y, w, k, s, xb, xe, parametric=np.ndim(y) == 2,
+        periodic=periodic
+    )
+
+    yield from _generate_knots_impl(x, y, w, xb, xe, k, s, nest, periodic, xp=xp)
+
+
+def _generate_knots_impl(x, y, w, xb, xe, k, s, nest, periodic, xp=np):
+
+    acc = s * TOL
+    m = x.size    # the number of data points
+
+    if nest is None:
+        # the max number of knots. This is set in _fitpack_impl.py line 274
+        # and fitpack.pyf line 198
+        # Ref: https://github.com/scipy/scipy/blob/596b586e25e34bd842b575bac134b4d6924c6556/scipy/interpolate/_fitpack_impl.py#L260-L263
+        if periodic:
+            nest = max(m + 2*k, 2*k + 3)
+        else:
+            nest = max(m + k + 1, 2*k + 3)
+    else:
+        if nest < 2*(k + 1):
+            raise ValueError(f"`nest` too small: {nest = } < 2*(k+1) = {2*(k+1)}.")
+
+    if not periodic:
+        nmin = 2*(k + 1)    # the number of knots for an LSQ polynomial approximation
+        nmax = m + k + 1  # the number of knots for the spline interpolation
+    else:
+        # Ref: https://github.com/scipy/scipy/blob/maintenance/1.16.x/scipy/interpolate/fitpack/fpperi.f#L54
+        nmin = 2*(k + 1)    # the number of knots for an LSQ polynomial approximation
+        # Ref: https://github.com/scipy/scipy/blob/maintenance/1.16.x/scipy/interpolate/fitpack/fpperi.f#L61
+        nmax = m + 2*k  # the number of knots for the spline interpolation
+
+    per = xe - xb
+    # Ref: https://github.com/scipy/scipy/blob/maintenance/1.16.x/scipy/interpolate/fitpack/fpperi.f#L107-L123
+    # Computes fp0 for constant function
+    if periodic:
+        t = np.zeros(nmin, dtype=float)
+        for i in range(0, k + 1):
+            t[i] = x[0] - (k - i) * per
+            t[i + k + 1] = x[m - 1] + i * per
+        _, fp = _get_residuals(x, y, t, k, w, periodic=periodic)
+        # For periodic splines, check whether constant function
+        # satisfies accuracy criterion
+        # Also if maximal number of nodes is equal to the minimal
+        # then constant function is the direct solution
+        # Ref: https://github.com/scipy/scipy/blob/maintenance/1.16.x/scipy/interpolate/fitpack/fpperi.f#L600-L610
+        if fp - s < acc or nmax == nmin:
+            yield t
+            return
+    else:
+        fp = 0.0
+        fpold = 0.0
+
+    # start from no internal knots
+    if not periodic:
+        t = np.asarray([xb]*(k+1) + [xe]*(k+1), dtype=float)
+    else:
+        # Ref: https://github.com/scipy/scipy/blob/maintenance/1.16.x/scipy/interpolate/fitpack/fpperi.f#L131
+        # Initialize knot vector `t` of size (2k + 3) with zeros.
+        # The central knot `t[k + 1]` is seeded with the midpoint value from `x`.
+        # Note that, in the `if periodic:` block (in the main loop below),
+        # the boundary knots `t[k]` and `t[n - k - 1]` are set to the endpoints `xb` and
+        # `xe`. Then, the surrounding knots on both ends are updated to ensure
+        # periodicity.
+        # Specifically:
+        # - Left-side knots are mirrored from the right end minus the period (`per`).
+        # - Right-side knots are mirrored from the left end plus the period.
+        # These updates ensure that the knot vector wraps around correctly for periodic
+        # B-spline fitting.
+        t = np.zeros(2*k + 3, dtype=float)
+        t[k + 1] = x[(m + 1)//2 - 1]
+        nplus = 1
+    n = t.shape[0]
+
+    # c  main loop for the different sets of knots. m is a safe upper bound
+    # c  for the number of trials.
+    for iter in range(m):
+        # Ref: https://github.com/scipy/scipy/blob/maintenance/1.16.x/scipy/interpolate/fitpack/fpperi.f#L147-L158
+        if periodic:
+            n = t.shape[0]
+            t[k] = xb
+            t[n - k - 1] = xe
+            for j in range(1, k + 1):
+                t[k - j] = t[n - k - j - 1] - per
+                t[n - k + j - 1] = t[k + j] + per
+        yield xp.asarray(t)
+
+        # construct the LSQ spline with this set of knots
+        fpold = fp
+        residuals, fp = _get_residuals(x, y, t, k, w=w,
+                                        periodic=periodic)
+        fpms = fp - s
+
+        # c  test whether the approximation sinf(x) is an acceptable solution.
+        # c  if f(p=inf) < s accept the choice of knots.
+        if (abs(fpms) < acc) or (fpms < 0):
+            return
+
+        # ### c  increase the number of knots. ###
+
+        # c  determine the number of knots nplus we are going to add.
+        if n == nmin:
+            # the first iteration
+            nplus = 1
+        else:
+            delta = fpold - fp
+            npl1 = int(nplus * fpms / delta) if delta > acc else nplus*2
+            nplus = min(nplus*2, max(npl1, nplus//2, 1))
+
+        # actually add knots
+        for j in range(nplus):
+            t = add_knot(x, t, k, residuals)
+
+            # check if we have enough knots already
+
+            n = t.shape[0]
+            # c  if n = nmax, sinf(x) is an interpolating spline.
+            # c  if n=nmax we locate the knots as for interpolation.
+            if n >= nmax:
+                if not periodic:
+                    t = _not_a_knot(x, k)
+                else:
+                    t = _periodic_knots(x, k)
+                yield xp.asarray(t)
+                return
+
+            # c  if n=nest we cannot increase the number of knots because of
+            # c  the storage capacity limitation.
+            if n >= nest:
+                yield xp.asarray(t)
+                return
+
+            # recompute if needed
+            if j < nplus - 1:
+                residuals, _ = _get_residuals(x, y, t, k, w=w, periodic=periodic)
+
+    # this should never be reached
+    return
+
+
+#   cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc
+#   c  part 2: determination of the smoothing spline sp(x).                c
+#   c  ***************************************************                 c
+#   c  we have determined the number of knots and their position.          c
+#   c  we now compute the b-spline coefficients of the smoothing spline    c
+#   c  sp(x). the observation matrix a is extended by the rows of matrix   c
+#   c  b expressing that the kth derivative discontinuities of sp(x) at    c
+#   c  the interior knots t(k+2),...t(n-k-1) must be zero. the corres-     c
+#   c  ponding weights of these additional rows are set to 1/p.            c
+#   c  iteratively we then have to determine the value of p such that      c
+#   c  f(p)=sum((w(i)*(y(i)-sp(x(i))))**2) be = s. we already know that    c
+#   c  the least-squares kth degree polynomial corresponds to p=0, and     c
+#   c  that the least-squares spline corresponds to p=infinity. the        c
+#   c  iteration process which is proposed here, makes use of rational     c
+#   c  interpolation. since f(p) is a convex and strictly decreasing       c
+#   c  function of p, it can be approximated by a rational function        c
+#   c  r(p) = (u*p+v)/(p+w). three values of p(p1,p2,p3) with correspond-  c
+#   c  ing values of f(p) (f1=f(p1)-s,f2=f(p2)-s,f3=f(p3)-s) are used      c
+#   c  to calculate the new value of p such that r(p)=s. convergence is    c
+#   c  guaranteed by taking f1>0 and f3<0.                                 c
+#   cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc
+
+
+def prodd(t, i, j, k):
+    res = 1.0
+    for s in range(k+2):
+        if i + s != j:
+            res *= (t[j] - t[i+s])
+    return res
+
+
+def disc(t, k):
+    """Discontinuity matrix: jumps of k-th derivatives of b-splines at internal knots.
+
+    See Eqs. (9)-(10) of Ref. [1], or, equivalently, Eq. (3.43) of Ref. [2].
+
+    This routine assumes internal knots are all simple (have multiplicity =1).
+
+    Parameters
+    ----------
+    t : ndarray, 1D, shape(n,)
+        Knots.
+    k : int
+        The spline degree
+
+    Returns
+    -------
+    disc : ndarray, shape(n-2*k-1, k+2)
+        The jumps of the k-th derivatives of b-splines at internal knots,
+        ``t[k+1], ...., t[n-k-1]``.
+    offset : ndarray, shape(2-2*k-1,)
+        Offsets
+    nc : int
+
+    Notes
+    -----
+
+    The normalization here follows FITPACK:
+    (https://github.com/scipy/scipy/blob/maintenance/1.11.x/scipy/interpolate/fitpack/fpdisc.f#L36)
+
+    The k-th derivative jumps are multiplied by a factor::
+
+        (delta / nrint)**k / k!
+
+    where ``delta`` is the length of the interval spanned by internal knots, and
+    ``nrint`` is one less the number of internal knots (i.e., the number of
+    subintervals between them).
+
+    References
+    ----------
+    .. [1] Paul Dierckx, Algorithms for smoothing data with periodic and parametric
+           splines, Computer Graphics and Image Processing, vol. 20, p. 171 (1982).
+           :doi:`10.1016/0146-664X(82)90043-0`
+
+    .. [2] Tom Lyche and Knut Morken, Spline methods,
+        https://web.archive.org/web/20221205112612/https://www.uio.no/studier/emner/matnat/ifi/nedlagte-emner/INF-MAT5340/v05/undervisningsmateriale/hele.pdf
+
+    """
+    n = t.shape[0]
+
+    # the length of the base interval spanned by internal knots & the number
+    # of subintervas between these internal knots
+    delta = t[n - k - 1] - t[k]
+    nrint = n - 2*k - 1
+
+    matr = np.empty((nrint - 1, k + 2), dtype=float)
+    for jj in range(nrint - 1):
+        j = jj + k + 1
+        for ii in range(k + 2):
+            i = jj + ii
+            matr[jj, ii] = (t[i + k + 1] - t[i]) / prodd(t, i, j, k)
+        # NB: equivalent to
+        # row = [(t[i + k + 1] - t[i]) / prodd(t, i, j, k) for i in range(j-k-1, j+1)]
+        # assert (matr[j-k-1, :] == row).all()
+
+    # follow FITPACK
+    matr *= (delta/ nrint)**k
+
+    # make it packed
+    offset = np.array([i for i in range(nrint-1)], dtype=np.int64)
+    nc = n - k - 1
+    return matr, offset, nc
+
+
+class F:
+    """ The r.h.s. of ``f(p) = s``.
+
+    Given scalar `p`, we solve the system of equations in the LSQ sense:
+
+        | A     |  @ | c | = | y |
+        | B / p |    | 0 |   | 0 |
+
+    where `A` is the matrix of b-splines and `b` is the discontinuity matrix
+    (the jumps of the k-th derivatives of b-spline basis elements at knots).
+
+    Since we do that repeatedly while minimizing over `p`, we QR-factorize
+    `A` only once and update the QR factorization only of the `B` rows of the
+    augmented matrix |A, B/p|.
+
+    The system of equations is Eq. (15) Ref. [1]_, the strategy and implementation
+    follows that of FITPACK, see specific links below.
+
+    References
+    ----------
+    [1] P. Dierckx, Algorithms for Smoothing Data with Periodic and Parametric Splines,
+        COMPUTER GRAPHICS AND IMAGE PROCESSING vol. 20, pp 171-184 (1982.)
+        :doi:`10.1016/0146-664X(82)90043-0`.
+
+    """
+    def __init__(self, x, y, t, k, s, w=None, *, R=None, Y=None):
+        self.x = x
+        self.y = y
+        self.t = t
+        self.k = k
+        w = np.ones_like(x, dtype=float) if w is None else w
+        if w.ndim != 1:
+            raise ValueError(f"{w.ndim = } != 1.")
+        self.w = w
+        self.s = s
+
+        if y.ndim != 2:
+            raise ValueError(f"F: expected y.ndim == 2, got {y.ndim = } instead.")
+
+        # ### precompute what we can ###
+
+        # https://github.com/scipy/scipy/blob/maintenance/1.11.x/scipy/interpolate/fitpack/fpcurf.f#L250
+        # c  evaluate the discontinuity jump of the kth derivative of the
+        # c  b-splines at the knots t(l),l=k+2,...n-k-1 and store in b.
+        b, b_offset, b_nc = disc(t, k)
+
+        # the QR factorization of the data matrix, if not provided
+        # NB: otherwise, must be consistent with x,y & s, but this is not checked
+        if R is None and Y is None:
+            R, Y, _, _, _ = _lsq_solve_qr(x, y, t, k, w)
+
+        # prepare to combine R and the discontinuity matrix (AB); also r.h.s. (YY)
+        # https://github.com/scipy/scipy/blob/maintenance/1.11.x/scipy/interpolate/fitpack/fpcurf.f#L269
+        # c  the rows of matrix b with weight 1/p are rotated into the
+        # c  triangularised observation matrix a which is stored in g.
+        nc = t.shape[0] - k - 1
+        nz = k + 1
+        if R.shape[1] != nz:
+            raise ValueError(f"Internal error: {R.shape[1] =} != {k+1 =}.")
+
+        # r.h.s. of the augmented system
+        z = np.zeros((b.shape[0], Y.shape[1]), dtype=float)
+        self.YY = np.r_[Y[:nc], z]
+
+        # l.h.s. of the augmented system
+        AA = np.zeros((nc + b.shape[0], self.k+2), dtype=float)
+        AA[:nc, :nz] = R[:nc, :]
+        # AA[nc:, :] = b.a / p  # done in __call__(self, p)
+        self.AA  = AA
+        self.offset = np.r_[np.arange(nc, dtype=np.int64), b_offset]
+
+        self.nc = nc
+        self.b = b
+
+    def __call__(self, p):
+        # https://github.com/scipy/scipy/blob/maintenance/1.11.x/scipy/interpolate/fitpack/fpcurf.f#L279
+        # c  the row of matrix b is rotated into triangle by givens transformation
+
+        # copy the precomputed matrices over for in-place work
+        # R = PackedMatrix(self.AB.a.copy(), self.AB.offset.copy(), nc)
+        AB = self.AA.copy()
+        offset = self.offset.copy()
+        nc = self.nc
+
+        AB[nc:, :] = self.b / p
+        QY = self.YY.copy()
+
+        # heavy lifting happens here, in-place
+        _dierckx.qr_reduce(AB, offset, nc, QY, startrow=nc)
+
+        # solve for the coefficients
+        c, _, fp = _dierckx.fpback(AB, nc, self.x, self.y, self.t, self.k, self.w, QY)
+
+        spl = BSpline(self.t, c, self.k)
+        self.spl = spl   # store it
+
+        return fp - self.s
+
+class Fperiodic:
+    """
+    Fit a smooth periodic B-spline curve to given data points.
+
+    This class fits a periodic B-spline curve S(t) of degree k through data points
+    (x, y) with knots t. The spline is smooth and repeats itself at the start and
+    end, meaning the function and its derivatives up to order k-1 are equal
+    at the boundaries.
+
+    We want to find spline coefficients c that minimize the difference between
+    the spline and the data, while also keeping the spline smooth. This is done
+    by solving:
+
+        minimize || W^{1/2} (Y - B c) ||^2 + s * c^T @ R @ c
+        subject to periodic constraints on c.
+
+    where:
+      - Y is the data values,
+      - B is the matrix of B-spline basis functions at points x,
+      - W is a weighting matrix for the data points,
+      - s is the smoothing parameter (larger s means smoother curve),
+      - R is a matrix that penalizes wiggliness of the spline,
+      - c spline coefficients to be solved for
+      - periodic constraints ensure the spline repeats smoothly.
+
+    The solution is obtained by forming augmented matrices and performing
+    a QR factorization that incorporates these constraints, following the
+    approach in FITPACK's `fpperi.f`.
+
+    Parameters:
+    -----------
+    x : array_like, shape (n,)
+    y : array_like, shape (n, m)
+    t : array_like, shape (nt,)
+        Knot vector for the spline
+    k : int
+        Degree of the spline.
+    s : float
+        Controls smoothness: bigger s means smoother curve, smaller s fits data closer.
+    w : array_like, shape (n,), optional
+        Weights for data points. Defaults to all ones.
+    R, Y, A1, A2, Z : arrays, optional
+        Precomputed matrices from least squares and QR factorization steps to speed up
+        repeated fits with the same knots and data.
+
+    Attributes:
+    -----------
+    G1, G2 : arrays
+        Augmented matrices combining the original QR factors and constraints related to
+        the spline basis and data. G1 is roughly the "upper-triangular" part;
+        G2 contains additional constraint information for periodicity.
+
+    H1, H2 : arrays
+        Matrices associated with the discontinuity jump constraints of the k-th
+        derivative of B-splines at the knots. These encode the periodicity
+        conditions and are scaled by the smoothing parameter.
+
+    offset : array
+        Offset indices used for efficient indexing during QR reduction.
+
+    Methods:
+    --------
+    __call__(p):
+        Perform QR reduction of augmented matrices scaled by 1/p, solve for spline
+        coefficients, and return residual difference fp - s.
+
+    References:
+    -----------
+    - FITPACK's fpperi.f and fpcurf.f Fortran routines for periodic spline fitting.
+    """
+    def __init__(self, x, y, t, k, s, w=None, *,
+                 R=None, Y=None, A1=None, A2=None, Z=None):
+        # Initialize the class with input data points x, y,
+        # knot vector t, spline degree k, smoothing factor s,
+        # optional weights w, and optionally precomputed matrices.
+        self.x = x
+        self.y = y
+        self.t = t
+        self.k = k
+
+        # If weights not provided, default to uniform weights (all ones)
+        w = np.ones_like(x, dtype=float) if w is None else w
+
+        if w.ndim != 1:
+            raise ValueError(f"{w.ndim = } != 1.")
+        self.w = w
+
+        self.s = s
+
+        if y.ndim != 2:
+            raise ValueError(f"F: expected y.ndim == 2, got {y.ndim = } instead.")
+
+        # ### precompute matrices and factors needed for spline fitting ###
+
+        # Compute the discontinuity jump vector 'b' for the k-th derivative
+        # of B-splines at internal knots. This is needed for enforcing
+        # periodicity constraints. The jump discontinuities are stored in b.
+        # Refer: https://github.com/scipy/scipy/blob/maintenance/1.16.x/scipy/interpolate/fitpack/fpcurf.f#L252
+        b, b_offset, b_nc = disc(t, k)
+
+        # If QR factorization or auxiliary matrices (A1, A2, Z) are not provided,
+        # compute them via least squares on the data (x,y) with weights w.
+        # These matrices come from fitting B-spline basis to data.
+        if ((A1 is None or A2 is None or Z is None) or
+            (R is None and Y is None)):
+            # _lsq_solve_qr_for_root_rati_periodic computes QR factorization of
+            # data matrix and returns related matrices.
+            # Refer: https://github.com/scipy/scipy/blob/maintenance/1.16.x/scipy/interpolate/fitpack/fpperi.f#L171-L215
+            R, A1, A2, Z, _, _, _, _ = _lsq_solve_qr_for_root_rati_periodic(
+                x, y, t, k, w)
+
+        # Initialize augmented matrices G1, G2, H1, H2 and offset used
+        # for periodic B-spline fitting with constraints.
+        # This calls the C++ function `init_augmented_matrices` to set
+        # up these matrices based on A1, A2, and discontinuity vector b.
+        # Refer: https://github.com/scipy/scipy/blob/maintenance/1.16.x/scipy/interpolate/fitpack/fpperi.f#L441-L493
+        G1, G2, H1, H2, offset = _dierckx.init_augmented_matrices(A1, A2, b, len(t), k)
+
+        # Store these matrices as class attributes for use in evaluation
+        self.G1_ = G1
+        self.G2_ = G2
+        self.H1_ = H1
+        self.H2_ = H2
+        self.Z_ = Z
+        self.offset_ = offset
+
+    def __call__(self, p):
+        # Create copies of the augmented matrices to avoid overwriting originals
+        G1 = self.G1_.copy()
+        G2 = self.G2_.copy()
+        H1 = self.H1_.copy()
+        H2 = self.H2_.copy()
+        Z = self.Z_.copy()
+
+        # Scale H1 and H2 by the inverse of p (1/p), applying the pinv multiplier
+        # This scaling is required before QR reduction step to control smoothing.
+        pinv = 1/p
+        H1 = H1 * pinv
+        H2 = H2 * pinv
+
+        # Initialize vector c for coefficients with shape compatible with matrices.
+        # The first part of c is set from Z, which is related to least squares fit.
+        c = np.empty((len(self.t) - self.k - 1, Z.shape[1]), dtype=Z.dtype)
+        c[:len(self.t) - 2*self.k - 1, :] = Z[:len(self.t) - 2*self.k - 1, :]
+
+        # Perform QR factorization reduction on the augmented matrices
+        # This corresponds to the C++ function qr_reduce_augmented_matrices.
+        # It applies Givens rotations to eliminate entries and
+        # reduces the problem dimension by accounting for constraints.
+        # Refer: https://github.com/scipy/scipy/blob/maintenance/1.16.x/scipy/interpolate/fitpack/fpperi.f#L498-L534
+        _dierckx.qr_reduce_augmented_matrices(
+            G1, G2, H1, H2, c, self.offset_, len(self.t), self.k)
+
+        # Solve for the B-spline coefficients by backward substitution
+        # using the reduced matrices. This corresponds to the fpbacp routine in fitpack.
+        c, _, fp = _dierckx.fpbacp(
+            G1, G2, c,
+            self.k, self.k + 1, self.x[:-1], self.y[:-1, :],
+            self.t, self.w[:-1])
+
+        # Construct a BSpline object using knot vector t, coefficients c, and degree k
+        spl = BSpline(self.t, c, self.k)
+        self.spl = spl  # store it in the object
+
+        # Return the difference between the final residual fp and smoothing parameter s
+        # This quantity is used to assess fit quality in root-finding procedures.
+        return fp - self.s
+
+
+def fprati(p1, f1, p2, f2, p3, f3):
+    """The root of r(p) = (u*p + v) / (p + w) given three points and values,
+    (p1, f2), (p2, f2) and (p3, f3).
+
+    The FITPACK analog adjusts the bounds, and we do not
+    https://github.com/scipy/scipy/blob/maintenance/1.11.x/scipy/interpolate/fitpack/fprati.f
+
+    NB: FITPACK uses p < 0 to encode p=infinity. We just use the infinity itself.
+    Since the bracket is ``p1 <= p2 <= p3``, ``p3`` can be infinite (in fact,
+    this is what the minimizer starts with, ``p3=inf``).
+    """
+    h1 = f1 * (f2 - f3)
+    h2 = f2 * (f3 - f1)
+    h3 = f3 * (f1 - f2)
+    if p3 == np.inf:
+        return -(p2*h1 + p1*h2) / h3
+    return -(p1*p2*h3 + p2*p3*h1 + p1*p3*h2) / (p1*h1 + p2*h2 + p3*h3)
+
+
+class Bunch:
+    def __init__(self, **kwargs):
+        self.__dict__.update(**kwargs)
+
+
+_iermesg1 = """error. a theoretically impossible result was found during
+the iteration process for finding a smoothing spline with
+fp = s. probably causes : s too small.
+"""
+
+_iermesg = {
+1: _iermesg1 + """the weighted sum of squared residuals is becoming NaN
+""",
+2: _iermesg1 + """there is an approximation returned but the corresponding
+weighted sum of squared residuals does not satisfy the
+condition abs(fp-s)/s < tol.
+""",
+3: """error. the maximal number of iterations maxit (set to 20
+by the program) allowed for finding a smoothing spline
+with fp=s has been reached. probably causes : s too small
+there is an approximation returned but the corresponding
+weighted sum of squared residuals does not satisfy the
+condition abs(fp-s)/s < tol.
+"""
+}
+
+
+def root_rati(f, p0, bracket, acc, maxit=MAXIT):
+    """Solve `f(p) = 0` using a rational function approximation.
+
+    In a nutshell, since the function f(p) is known to be monotonically decreasing, we
+       - maintain the bracket (p1, f1), (p2, f2) and (p3, f3)
+       - at each iteration step, approximate f(p) by a rational function
+         r(p) = (u*p + v) / (p + w)
+         and make a step to p_new to the root of f(p): r(p_new) = 0.
+         The coefficients u, v and w are found from the bracket values p1..3 and f1...3
+
+    The algorithm and implementation follows
+    https://github.com/scipy/scipy/blob/maintenance/1.11.x/scipy/interpolate/fitpack/fpcurf.f#L229
+    and
+    https://github.com/scipy/scipy/blob/maintenance/1.11.x/scipy/interpolate/fitpack/fppara.f#L290
+
+    Note that the latter is for parametric splines and the former is for 1D spline
+    functions. The minimization is indentical though [modulo a summation over the
+    dimensions in the computation of f(p)], so we reuse the minimizer for both
+    d=1 and d>1.
+    """
+    # Magic values from
+    # https://github.com/scipy/scipy/blob/maintenance/1.11.x/scipy/interpolate/fitpack/fpcurf.f#L27
+    con1 = 0.1
+    con9 = 0.9
+    con4 = 0.04
+
+    # bracketing flags (follow FITPACK)
+    # https://github.com/scipy/scipy/blob/maintenance/1.11.x/scipy/interpolate/fitpack/fppara.f#L365
+    ich1, ich3 = 0, 0
+
+    (p1, f1), (p3, f3)  = bracket
+    p = p0
+
+    for it in range(maxit):
+        p2, f2 = p, f(p)
+
+        # c  test whether the approximation sp(x) is an acceptable solution.
+        if abs(f2) < acc:
+            ier, converged = 0, True
+            break
+
+        # c  carry out one more step of the iteration process.
+        if ich3 == 0:
+            if f2 - f3 <= acc:
+                # c  our initial choice of p is too large.
+                p3 = p2
+                f3 = f2
+                p = p*con4
+                if p <= p1:
+                    p = p1*con9 + p2*con1
+                continue
+            else:
+                if f2 < 0:
+                    ich3 = 1
+
+        if ich1 == 0:
+            if f1 - f2 <= acc:
+                # c  our initial choice of p is too small
+                p1 = p2
+                f1 = f2
+                p = p/con4
+                if p3 != np.inf and p <= p3:
+                    p = p2*con1 + p3*con9
+                continue
+            else:
+                if f2 > 0:
+                    ich1 = 1
+
+        # c  test whether the iteration process proceeds as theoretically expected.
+        # [f(p) should be monotonically decreasing]
+        if f1 <= f2 or f2 <= f3:
+            ier, converged = 2, False
+            break
+
+        # actually make the iteration step
+        p = fprati(p1, f1, p2, f2, p3, f3)
+
+        # c  adjust the value of p1,f1,p3 and f3 such that f1 > 0 and f3 < 0.
+        if f2 < 0:
+            p3, f3 = p2, f2
+        else:
+            p1, f1 = p2, f2
+
+    else:
+        # not converged in MAXIT iterations
+        ier, converged = 3, False
+
+    if ier != 0:
+        warnings.warn(RuntimeWarning(_iermesg[ier]), stacklevel=2)
+
+    return Bunch(converged=converged, root=p, iterations=it, ier=ier)
+
+def _make_splrep_impl(x, y, w, xb, xe, k, s, t, nest, periodic, xp=np):
+    """Shared infra for make_splrep and make_splprep.
+    """
+    acc = s * TOL
+    m = x.size    # the number of data points
+
+    if nest is None:
+        # the max number of knots. This is set in _fitpack_impl.py line 274
+        # and fitpack.pyf line 198
+        # Ref: https://github.com/scipy/scipy/blob/596b586e25e34bd842b575bac134b4d6924c6556/scipy/interpolate/_fitpack_impl.py#L260-L263
+        if periodic:
+            nest = max(m + 2*k, 2*k + 3)
+        else:
+            nest = max(m + k + 1, 2*k + 3)
+    else:
+        if nest < 2*(k + 1):
+            raise ValueError(f"`nest` too small: {nest = } < 2*(k+1) = {2*(k+1)}.")
+        if t is not None:
+            raise ValueError("Either supply `t` or `nest`.")
+
+    if t is None:
+        gen = _generate_knots_impl(x, y, w, xb, xe, k, s, nest, periodic)
+        t = list(gen)[-1]
+    else:
+        fpcheck(x, t, k, periodic=periodic)
+
+    if t.shape[0] == 2 * (k + 1):
+        # nothing to optimize
+        _, _, c, _, _ = _lsq_solve_qr(x, y, t, k, w, periodic=periodic)
+        t, c = xp.asarray(t), xp.asarray(c)
+        return BSpline(t, c, k)
+
+    ### solve ###
+
+    # c  initial value for p.
+    # https://github.com/scipy/scipy/blob/maintenance/1.11.x/scipy/interpolate/fitpack/fpcurf.f#L253
+    if periodic:
+        # N.B. - Check _lsq_solve_qr computation
+        # of p for periodic splines
+        R, A1, A2, Z, Y, _, p, _ = _lsq_solve_qr_for_root_rati_periodic(x, y, t, k, w)
+    else:
+        R, Y, _, _, _ = _lsq_solve_qr(x, y, t, k, w, periodic=periodic)
+    nc = t.shape[0] -k -1
+    if not periodic:
+        p = nc / R[:, 0].sum()
+
+    # ### bespoke solver ####
+    # initial conditions
+    # f(p=inf) : LSQ spline with knots t   (XXX: reuse R, c)
+    # N.B. - Check _lsq_solve_qr which is called
+    # via _get_residuals for logic behind
+    # computation of fp for periodic splines
+    _, fp = _get_residuals(x, y, t, k, w, periodic=periodic)
+    fpinf = fp - s
+
+    # f(p=0): LSQ spline without internal knots
+    if not periodic:
+        _, fp0 = _get_residuals(x, y, np.array([xb]*(k+1) + [xe]*(k+1)), k, w)
+        fp0 = fp0 - s
+    else:
+        # f(p=0) is fp for constant function
+        # in case of periodic splines
+        per = xe - xb
+        tc = np.zeros(2*(k + 1), dtype=float)
+        for i in range(0, k + 1):
+            tc[i] = x[0] - (k - i) * per
+            tc[i + k + 1] = x[m - 1] + i * per
+        _, fp0 = _get_residuals(x, y, tc, k, w, periodic=periodic)
+        fp0 = fp0 - s
+
+    # solve
+    bracket = (0, fp0), (np.inf, fpinf)
+    if not periodic:
+        f = F(x, y, t, k=k, s=s, w=w, R=R, Y=Y)
+    else:
+        f = Fperiodic(x, y, t, k=k, s=s, w=w, R=R, Y=Y, A1=A1, A2=A2, Z=Z)
+    _ = root_rati(f, p, bracket, acc)
+
+    # solve ALTERNATIVE: is roughly equivalent, gives slightly different results
+    # starting from scratch, that would have probably been tolerable;
+    # backwards compatibility dictates that we replicate the FITPACK minimizer though.
+ #   f = F(x, y, t, k=k, s=s, w=w, R=R, Y=Y)
+ #   from scipy.optimize import root_scalar
+ #   res_ = root_scalar(f, x0=p, rtol=acc)
+ #   assert res_.converged
+
+    # f.spl is the spline corresponding to the found `p` value
+    t, c, k = f.spl.tck
+    axis, extrap = f.spl.axis, f.spl.extrapolate
+    t, c = xp.asarray(t), xp.asarray(c)
+    spl = BSpline.construct_fast(t, c, k, axis=axis, extrapolate=extrap)
+    return spl
+
+
+@xp_capabilities(cpu_only=True, jax_jit=False, allow_dask_compute=True)
+def make_splrep(x, y, *, w=None, xb=None, xe=None,
+                k=3, s=0, t=None, nest=None, bc_type=None):
+    r"""Create a smoothing B-spline function with bounded error, minimizing derivative jumps.
+
+    Given the set of data points ``(x[i], y[i])``, determine a smooth spline
+    approximation of degree ``k`` on the interval ``xb <= x <= xe``.
+
+    Parameters
+    ----------
+    x, y : array_like, shape (m,)
+        The data points defining a curve ``y = f(x)``.
+    w : array_like, shape (m,), optional
+        Strictly positive 1D array of weights, of the same length as `x` and `y`.
+        The weights are used in computing the weighted least-squares spline
+        fit. If the errors in the y values have standard-deviation given by the
+        vector ``d``, then `w` should be ``1/d``.
+        Default is ``np.ones(m)``.
+    xb, xe : float, optional
+        The interval to fit.  If None, these default to ``x[0]`` and ``x[-1]``,
+        respectively.
+    k : int, optional
+        The degree of the spline fit. It is recommended to use cubic splines,
+        ``k=3``, which is the default. Even values of `k` should be avoided,
+        especially with small `s` values.
+    s : float, optional
+        The smoothing condition. The amount of smoothness is determined by
+        satisfying the LSQ (least-squares) constraint::
+
+            sum((w * (g(x)  - y))**2 ) <= s
+
+        where ``g(x)`` is the smoothed fit to ``(x, y)``. The user can use `s`
+        to control the tradeoff between closeness to data and smoothness of fit.
+        Larger `s` means more smoothing while smaller values of `s` indicate less
+        smoothing.
+        Recommended values of `s` depend on the weights, `w`. If the weights
+        represent the inverse of the standard deviation of `y`, then a good `s`
+        value should be found in the range ``(m-sqrt(2*m), m+sqrt(2*m))`` where
+        ``m`` is the number of datapoints in `x`, `y`, and `w`.
+        Default is ``s = 0.0``, i.e. interpolation.
+    t : array_like, optional
+        The spline knots. If None (default), the knots will be constructed
+        automatically.
+        There must be at least ``2*k + 2`` and at most ``m + k + 1`` knots.
+    nest : int, optional
+        The target length of the knot vector. Should be between ``2*(k + 1)``
+        (the minimum number of knots for a degree-``k`` spline), and
+        ``m + k + 1`` (the number of knots of the interpolating spline).
+        The actual number of knots returned by this routine may be slightly
+        larger than `nest`.
+        Default is None (no limit, add up to ``m + k + 1`` knots).
+    bc_type : str, optional
+        Boundary conditions.
+        Default is `"not-a-knot"`.
+        The following boundary conditions are recognized:
+
+        * ``"not-a-knot"`` (default): The first and second segments are the
+          same polynomial. This is equivalent to having ``bc_type=None``.
+        * ``"periodic"``: The values and the first ``k-1`` derivatives at the
+          ends are equivalent.
+
+    Returns
+    -------
+    spl : a `BSpline` instance
+        For `s=0`,  ``spl(x) == y``.
+        For non-zero values of `s` the `spl` represents the smoothed approximation
+        to `(x, y)`, generally with fewer knots.
+
+    See Also
+    --------
+    generate_knots : is used under the hood for generating the knots
+    make_splprep : the analog of this routine for parametric curves
+    make_interp_spline : construct an interpolating spline (``s = 0``)
+    make_lsq_spline : construct the least-squares spline given the knot vector
+    splrep : a FITPACK analog of this routine
+
+    References
+    ----------
+    .. [1] P. Dierckx, "Algorithms for smoothing data with periodic and
+        parametric splines, Computer Graphics and Image Processing",
+        20 (1982) 171-184.
+    .. [2] P. Dierckx, "Curve and surface fitting with splines", Monographs on
+        Numerical Analysis, Oxford University Press, 1993.
+
+    Notes
+    -----
+    This routine constructs the smoothing spline function, :math:`g(x)`, to
+    minimize the sum of jumps, :math:`D_j`, of the ``k``-th derivative at the
+    internal knots (:math:`x_b < t_i < x_e`), where
+
+    .. math::
+
+        D_i = g^{(k)}(t_i + 0) - g^{(k)}(t_i - 0)
+
+    Specifically, the routine constructs the spline function :math:`g(x)` which
+    minimizes
+
+    .. math::
+
+            \sum_i | D_i |^2 \to \mathrm{min}
+
+    provided that
+
+    .. math::
+
+           \sum_{j=1}^m (w_j \times (g(x_j) - y_j))^2 \leqslant s ,
+
+    where :math:`s > 0` is the input parameter.
+
+    In other words, we balance maximizing the smoothness (measured as the jumps
+    of the derivative, the first criterion), and the deviation of :math:`g(x_j)`
+    from the data :math:`y_j` (the second criterion).
+
+    Note that the summation in the second criterion is over all data points,
+    and in the first criterion it is over the internal spline knots (i.e.
+    those with ``xb < t[i] < xe``). The spline knots are in general a subset
+    of data, see `generate_knots` for details.
+
+    Also note the difference of this routine to `make_lsq_spline`: the latter
+    routine does not consider smoothness and simply solves a least-squares
+    problem
+
+    .. math::
+
+        \sum w_j \times (g(x_j) - y_j)^2 \to \mathrm{min}
+
+    for a spline function :math:`g(x)` with a _fixed_ knot vector ``t``.
+
+    .. versionadded:: 1.15.0
+    """  # noqa:E501
+    xp = array_namespace(x, y, w, t)
+    if t is not None:
+        t = xp.asarray(t)
+    bc_type = _validate_bc_type(bc_type)
+
+    if s == 0:
+        if t is not None or w is not None or nest is not None:
+            raise ValueError("s==0 is for interpolation only")
+        return make_interp_spline(x, y, k=k, bc_type=bc_type)
+
+    periodic = (bc_type == 'periodic')
+
+    x, y, w, k, s, xb, xe = _validate_inputs(x, y, w, k, s, xb, xe,
+                                             parametric=False, periodic=periodic)
+
+    spl = _make_splrep_impl(x, y, w, xb, xe, k, s, t, nest, periodic, xp=xp)
+
+    # postprocess: squeeze out the last dimension: was added to simplify the internals.
+    spl.c = spl.c[:, 0]
+    # make periodic if needed
+    spl.extrapolate = "periodic" if periodic else True
+    return spl
+
+
+@xp_capabilities(cpu_only=True, jax_jit=False, allow_dask_compute=True)
+def make_splprep(x, *, w=None, u=None, ub=None, ue=None,
+                 k=3, s=0, t=None, nest=None, bc_type=None):
+    r"""
+    Create a smoothing parametric B-spline curve with bounded error, minimizing derivative jumps.
+
+    Given a list of N 1D arrays, `x`, which represent a curve in
+    N-dimensional space parametrized by `u`, find a smooth approximating
+    spline curve ``g(u)``.
+
+    Parameters
+    ----------
+    x : array_like, shape (ndim, m)
+        Sampled data points representing the curve in ``ndim`` dimensions.
+        The typical use is a list of 1D arrays, each of length ``m``.
+    w : array_like, shape(m,), optional
+        Strictly positive 1D array of weights.
+        The weights are used in computing the weighted least-squares spline
+        fit. If the errors in the `x` values have standard deviation given by
+        the vector d, then `w` should be 1/d. Default is ``np.ones(m)``.
+    u : array_like, optional
+        An array of parameter values for the curve in the parametric form.
+        If not given, these values are calculated automatically, according to::
+
+            v[0] = 0
+            v[i] = v[i-1] + distance(x[i], x[i-1])
+            u[i] = v[i] / v[-1]
+
+    ub, ue : float, optional
+        The end-points of the parameters interval. Default to ``u[0]`` and ``u[-1]``.
+    k : int, optional
+        Degree of the spline. Cubic splines, ``k=3``, are recommended.
+        Even values of `k` should be avoided especially with a small ``s`` value.
+        Default is ``k=3``
+    s : float, optional
+        A smoothing condition.  The amount of smoothness is determined by
+        satisfying the conditions::
+
+            sum((w * (g(u) - x))**2) <= s,
+
+        where ``g(u)`` is the smoothed approximation to ``x``.  The user can
+        use `s` to control the trade-off between closeness and smoothness
+        of fit.  Larger ``s`` means more smoothing while smaller values of ``s``
+        indicate less smoothing.
+        Recommended values of ``s`` depend on the weights, ``w``.  If the weights
+        represent the inverse of the standard deviation of ``x``, then a good
+        ``s`` value should be found in the range ``(m - sqrt(2*m), m + sqrt(2*m))``,
+        where ``m`` is the number of data points in ``x`` and ``w``.
+    t : array_like, optional
+        The spline knots. If None (default), the knots will be constructed
+        automatically.
+        There must be at least ``2*k + 2`` and at most ``m + k + 1`` knots.
+    nest : int, optional
+        The target length of the knot vector. Should be between ``2*(k + 1)``
+        (the minimum number of knots for a degree-``k`` spline), and
+        ``m + k + 1`` (the number of knots of the interpolating spline).
+        The actual number of knots returned by this routine may be slightly
+        larger than `nest`.
+        Default is None (no limit, add up to ``m + k + 1`` knots).
+    bc_type : str, optional
+        Boundary conditions.
+        Default is `"not-a-knot"`.
+        The following boundary conditions are recognized:
+
+        * ``"not-a-knot"`` (default): The first and second segments are the
+          same polynomial. This is equivalent to having ``bc_type=None``.
+        * ``"periodic"``: The values and the first ``k-1`` derivatives at the
+          ends are equivalent.
+
+    Returns
+    -------
+    spl : a `BSpline` instance
+        For `s=0`,  ``spl(u) == x``.
+        For non-zero values of ``s``, `spl` represents the smoothed approximation
+        to ``x``, generally with fewer knots.
+    u : ndarray
+        The values of the parameters
+
+    See Also
+    --------
+    generate_knots : is used under the hood for generating the knots
+    make_splrep : the analog of this routine 1D functions
+    make_interp_spline : construct an interpolating spline (``s = 0``)
+    make_lsq_spline : construct the least-squares spline given the knot vector
+    splprep : a FITPACK analog of this routine
+
+    Notes
+    -----
+    Given a set of :math:`m` data points in :math:`D` dimensions, :math:`\vec{x}_j`,
+    with :math:`j=1, ..., m` and :math:`\vec{x}_j = (x_{j; 1}, ..., x_{j; D})`,
+    this routine constructs the parametric spline curve :math:`g_a(u)` with
+    :math:`a=1, ..., D`, to minimize the sum of jumps, :math:`D_{i; a}`, of the
+    ``k``-th derivative at the internal knots (:math:`u_b < t_i < u_e`), where
+
+    .. math::
+
+        D_{i; a} = g_a^{(k)}(t_i + 0) - g_a^{(k)}(t_i - 0)
+
+    Specifically, the routine constructs the spline function :math:`g(u)` which
+    minimizes
+
+    .. math::
+
+            \sum_i \sum_{a=1}^D | D_{i; a} |^2 \to \mathrm{min}
+
+    provided that
+
+    .. math::
+
+        \sum_{j=1}^m \sum_{a=1}^D (w_j \times (g_a(u_j) - x_{j; a}))^2 \leqslant s
+
+    where :math:`u_j` is the value of the parameter corresponding to the data point
+    :math:`(x_{j; 1}, ..., x_{j; D})`, and :math:`s > 0` is the input parameter.
+
+    In other words, we balance maximizing the smoothness (measured as the jumps
+    of the derivative, the first criterion), and the deviation of :math:`g(u_j)`
+    from the data :math:`x_j` (the second criterion).
+
+    Note that the summation in the second criterion is over all data points,
+    and in the first criterion it is over the internal spline knots (i.e.
+    those with ``ub < t[i] < ue``). The spline knots are in general a subset
+    of data, see `generate_knots` for details.
+
+    .. versionadded:: 1.15.0
+
+    References
+    ----------
+    .. [1] P. Dierckx, "Algorithms for smoothing data with periodic and
+        parametric splines, Computer Graphics and Image Processing",
+        20 (1982) 171-184.
+    .. [2] P. Dierckx, "Curve and surface fitting with splines", Monographs on
+        Numerical Analysis, Oxford University Press, 1993.
+    """  # noqa:E501
+
+    bc_type = _validate_bc_type(bc_type)
+
+    periodic = (bc_type == 'periodic')
+
+    # x can be either a 2D array or a list of 1D arrays
+    if isinstance(x, list):
+        xp = array_namespace(*x, w, u, t)
+    else:
+        xp = array_namespace(x, w, u, t)
+
+    x = xp.stack(x, axis=1)
+
+    # construct the default parametrization of the curve
+    if u is None:
+        dp = (x[1:, :] - x[:-1, :])**2
+        u = xp.cumulative_sum( xp.sqrt(xp.sum(dp, axis=1)) )
+        u = concat_1d(xp, 0., u / u[-1])
+
+    if s == 0:
+        if t is not None or w is not None or nest is not None:
+            raise ValueError("s==0 is for interpolation only")
+        return make_interp_spline(u, x.T, k=k, bc_type=bc_type, axis=1), u
+
+    u, x, w, k, s, ub, ue = _validate_inputs(u, x, w, k, s, ub, ue,
+                                             parametric=True, periodic=periodic)
+
+    if t is not None:
+        t = xp.asarray(t)
+
+    spl = _make_splrep_impl(u, x, w, ub, ue, k, s, t,
+                            nest, periodic=periodic, xp=xp)
+
+    # posprocess: `axis=1` so that spl(u).shape == np.shape(x)
+    # when `x` is a list of 1D arrays (cf original splPrep)
+    cc = spl.c.T
+    spl1 = BSpline(
+        spl.t, cc, spl.k, axis=1,
+        extrapolate='periodic' if periodic else True
+    )
+
+    return spl1, xp.asarray(u)
diff --git a/.venv/lib/python3.12/site-packages/scipy/interpolate/_interpnd.cpython-312-x86_64-linux-gnu.so b/.venv/lib/python3.12/site-packages/scipy/interpolate/_interpnd.cpython-312-x86_64-linux-gnu.so
new file mode 100644
index 0000000000000000000000000000000000000000..b759e7726233581cce71fd0ed0d9cc64d5260556
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/interpolate/_interpnd.cpython-312-x86_64-linux-gnu.so
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:b42390ecb266086a1158d593fc45fa0c3b6f83caa07c876a79d79febfc1428e4
+size 255936
diff --git a/.venv/lib/python3.12/site-packages/scipy/interpolate/_interpolate.py b/.venv/lib/python3.12/site-packages/scipy/interpolate/_interpolate.py
new file mode 100644
index 0000000000000000000000000000000000000000..94fc8b0c3becfcb5625fd47397b1709a577b668e
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/interpolate/_interpolate.py
@@ -0,0 +1,2787 @@
+__all__ = ['interp1d', 'interp2d', 'lagrange', 'PPoly', 'BPoly', 'NdPPoly']
+import functools
+import os
+from math import prod
+from types import GenericAlias
+import warnings
+
+import numpy as np
+from numpy import array, asarray, intp, poly1d, searchsorted
+
+import scipy.special as spec
+from scipy._lib._util import copy_if_needed
+from scipy.special import comb
+
+from scipy._lib._array_api import (
+    array_namespace, xp_capabilities, scipy_namespace_for, is_numpy
+)
+
+from . import _fitpack_py
+from ._polyint import _Interpolator1D
+from . import _ppoly
+from ._interpnd import _ndim_coords_from_arrays
+from ._bsplines import make_interp_spline, BSpline
+
+
+@xp_capabilities(out_of_scope=True)
+def lagrange(x, w):
+    r"""
+    Return a Lagrange interpolating polynomial.
+
+    Given two 1-D arrays `x` and `w,` returns the Lagrange interpolating
+    polynomial through the points ``(x, w)``.
+
+    Warning: This implementation is numerically unstable. Do not expect to
+    be able to use more than about 20 points even if they are chosen optimally.
+
+    .. deprecated:: 1.18.0
+        This function is deprecated and will be removed in SciPy 1.20.0. Use
+        `scipy.interpolate.BarycentricInterpolator` instead.
+
+    Parameters
+    ----------
+    x : array_like
+        `x` represents the x-coordinates of a set of datapoints.
+    w : array_like
+        `w` represents the y-coordinates of a set of datapoints, i.e., f(`x`).
+
+    Returns
+    -------
+    lagrange : `numpy.poly1d` instance
+        The Lagrange interpolating polynomial.
+
+    Notes
+    -----
+    The name of this function refers to the fact that the returned object represents
+    a Lagrange polynomial, the unique polynomial of lowest degree that interpolates
+    a given set of data [1]_. It computes the polynomial using Newton's divided
+    differences formula [2]_; that is, it works with Newton basis polynomials rather
+    than Lagrange basis polynomials. For numerical calculations, the barycentric form
+    of Lagrange interpolation (`scipy.interpolate.BarycentricInterpolator`) is
+    typically more appropriate.
+
+    References
+    ----------
+    .. [1] Lagrange polynomial. *Wikipedia*.
+           https://en.wikipedia.org/wiki/Lagrange_polynomial
+    .. [2] Newton polynomial. *Wikipedia*.
+           https://en.wikipedia.org/wiki/Newton_polynomial
+
+    Examples
+    --------
+    Interpolate :math:`f(x) = x^3` by 3 points.
+
+    >>> import numpy as np
+    >>> from scipy.interpolate import lagrange
+    >>> x = np.array([0, 1, 2])
+    >>> y = x**3
+    >>> poly = lagrange(x, y)
+
+    Since there are only 3 points, the Lagrange polynomial has degree 2. Explicitly,
+    it is given by
+
+    .. math::
+
+        \begin{aligned}
+            L(x) &= 1\times \frac{x (x - 2)}{-1} + 8\times \frac{x (x-1)}{2} \\
+                 &= x (-2 + 3x)
+        \end{aligned}
+
+    >>> from numpy.polynomial.polynomial import Polynomial
+    >>> Polynomial(poly.coef[::-1]).coef
+    array([ 0., -2.,  3.])
+
+    >>> import matplotlib.pyplot as plt
+    >>> x_new = np.arange(0, 2.1, 0.1)
+    >>> plt.scatter(x, y, label='data')
+    >>> plt.plot(x_new, Polynomial(poly.coef[::-1])(x_new), label='Polynomial')
+    >>> plt.plot(x_new, 3*x_new**2 - 2*x_new + 0*x_new,
+    ...          label=r"$3 x^2 - 2 x$", linestyle='-.')
+    >>> plt.legend()
+    >>> plt.show()
+
+    """
+    _warn_skips = (os.path.dirname(__file__),)
+    msg = ("`lagrange` is deprecated and will be removed in SciPy 1.20.0. Use "
+           "`scipy.interpolate.BarycentricInterpolator` instead.")
+    warnings.warn(msg, DeprecationWarning, skip_file_prefixes=_warn_skips)
+    M = len(x)
+    p = poly1d(0.0)
+    for j in range(M):
+        pt = poly1d(w[j])
+        for k in range(M):
+            if k == j:
+                continue
+            fac = x[j]-x[k]
+            pt *= poly1d([1.0, -x[k]])/fac
+        p += pt
+    return p
+
+
+# !! Need to find argument for keeping initialize. If it isn't
+# !! found, get rid of it!
+
+
+err_mesg = """\
+`interp2d` has been removed in SciPy 1.14.0.
+
+For legacy code, nearly bug-for-bug compatible replacements are
+`RectBivariateSpline` on regular grids, and `bisplrep`/`bisplev` for
+scattered 2D data.
+
+In new code, for regular grids use `RegularGridInterpolator` instead.
+For scattered data, prefer `LinearNDInterpolator` or
+`CloughTocher2DInterpolator`.
+
+For more details see
+https://scipy.github.io/devdocs/tutorial/interpolate/interp_transition_guide.html
+"""
+
+class interp2d:
+    """
+    interp2d(x, y, z, kind='linear', copy=True, bounds_error=False,
+             fill_value=None)
+
+    Class for 2D interpolation (deprecated and removed).
+
+    .. versionremoved:: 1.14.0
+
+        `interp2d` has been removed in SciPy 1.14.0.
+
+        For legacy code, nearly bug-for-bug compatible replacements are
+        `RectBivariateSpline` on regular grids, and `bisplrep`/`bisplev` for
+        scattered 2D data.
+
+        In new code, for regular grids use `RegularGridInterpolator` instead.
+        For scattered data, prefer `LinearNDInterpolator` or
+        `CloughTocher2DInterpolator`.
+
+        For more details see :ref:`interp-transition-guide`.
+    """
+    def __init__(self, x, y, z, kind='linear', copy=True, bounds_error=False,
+                 fill_value=None):
+        raise NotImplementedError(err_mesg)
+
+
+def _check_broadcast_up_to(arr_from, shape_to, name):
+    """Helper to check that arr_from broadcasts up to shape_to"""
+    shape_from = arr_from.shape
+    if len(shape_to) >= len(shape_from):
+        for t, f in zip(shape_to[::-1], shape_from[::-1]):
+            if f != 1 and f != t:
+                break
+        else:  # all checks pass, do the upcasting that we need later
+            if arr_from.size != 1 and arr_from.shape != shape_to:
+                arr_from = np.ones(shape_to, arr_from.dtype) * arr_from
+            return arr_from.ravel()
+    # at least one check failed
+    raise ValueError(f'{name} argument must be able to broadcast up '
+                     f'to shape {shape_to} but had shape {shape_from}')
+
+
+def _do_extrapolate(fill_value):
+    """Helper to check if fill_value == "extrapolate" without warnings"""
+    return (isinstance(fill_value, str) and
+            fill_value == 'extrapolate')
+
+
+@xp_capabilities(out_of_scope=True)
+class interp1d(_Interpolator1D):
+    """
+    Interpolate a 1-D function (legacy).
+
+    .. legacy:: class
+
+        For a guide to the intended replacements for `interp1d` see
+        :ref:`tutorial-interpolate_1Dsection`.
+
+    `x` and `y` are arrays of values used to approximate some function f:
+    ``y = f(x)``. This class returns a function whose call method uses
+    interpolation to find the value of new points.
+
+    Parameters
+    ----------
+    x : (npoints, ) array_like
+        A 1-D array of real values.
+    y : (..., npoints, ...) array_like
+        An N-D array of real values. The length of `y` along the interpolation
+        axis must be equal to the length of `x`. Use the ``axis`` parameter
+        to select correct axis. Unlike other interpolators, the default
+        interpolation axis is the last axis of `y`.
+    kind : str or int, optional
+        Specifies the kind of interpolation as a string or as an integer
+        specifying the order of the spline interpolator to use.
+        The string has to be one of 'linear', 'nearest', 'nearest-up', 'zero',
+        'slinear', 'quadratic', 'cubic', 'previous', or 'next'. 'zero',
+        'slinear', 'quadratic' and 'cubic' refer to a spline interpolation of
+        zeroth, first, second or third order; 'previous' and 'next' simply
+        return the previous or next value of the point; 'nearest-up' and
+        'nearest' differ when interpolating half-integers (e.g. 0.5, 1.5)
+        in that 'nearest-up' rounds up and 'nearest' rounds down. Default
+        is 'linear'.
+    axis : int, optional
+        Axis in the ``y`` array corresponding to the x-coordinate values. Unlike
+        other interpolators, defaults to ``axis=-1``.
+    copy : bool, optional
+        If ``True``, the class makes internal copies of x and y. If ``False``,
+        references to ``x`` and ``y`` are used if possible. The default is to copy.
+    bounds_error : bool, optional
+        If True, a ValueError is raised any time interpolation is attempted on
+        a value outside of the range of x (where extrapolation is
+        necessary). If False, out of bounds values are assigned `fill_value`.
+        By default, an error is raised unless ``fill_value="extrapolate"``.
+    fill_value : array-like or (array-like, array_like) or "extrapolate", optional
+        - if an ndarray (or float), this value will be used to fill in for
+          requested points outside of the data range. If not provided, then
+          the default is NaN. The array-like must broadcast properly to the
+          dimensions of the non-interpolation axes.
+        - If a two-element tuple, then the first element is used as a
+          fill value for ``x_new < x[0]`` and the second element is used for
+          ``x_new > x[-1]``. Anything that is not a 2-element tuple (e.g.,
+          list or ndarray, regardless of shape) is taken to be a single
+          array-like argument meant to be used for both bounds as
+          ``below, above = fill_value, fill_value``. Using a two-element tuple
+          or ndarray requires ``bounds_error=False``.
+
+          .. versionadded:: 0.17.0
+        - If "extrapolate", then points outside the data range will be
+          extrapolated.
+
+          .. versionadded:: 0.17.0
+    assume_sorted : bool, optional
+        If False, values of `x` can be in any order and they are sorted first.
+        If True, `x` has to be an array of monotonically increasing values.
+
+    Attributes
+    ----------
+    fill_value
+
+    Methods
+    -------
+    __call__
+
+    See Also
+    --------
+    splrep, splev
+        Spline interpolation/smoothing based on FITPACK.
+    UnivariateSpline : An object-oriented wrapper of the FITPACK routines.
+    interp2d : 2-D interpolation
+
+    Notes
+    -----
+    Calling `interp1d` with NaNs present in input values results in
+    undefined behaviour.
+
+    Input values `x` and `y` must be convertible to `float` values like
+    `int` or `float`.
+
+    If the values in `x` are not unique, the resulting behavior is
+    undefined and specific to the choice of `kind`, i.e., changing
+    `kind` will change the behavior for duplicates.
+
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> import matplotlib.pyplot as plt
+    >>> from scipy import interpolate
+    >>> x = np.arange(0, 10)
+    >>> y = np.exp(-x/3.0)
+    >>> f = interpolate.interp1d(x, y)
+
+    >>> xnew = np.arange(0, 9, 0.1)
+    >>> ynew = f(xnew)   # use interpolation function returned by `interp1d`
+    >>> plt.plot(x, y, 'o', xnew, ynew, '-')
+    >>> plt.show()
+    """
+
+    def __init__(self, x, y, kind='linear', axis=-1,
+                 copy=True, bounds_error=None, fill_value=np.nan,
+                 assume_sorted=False):
+        """ Initialize a 1-D linear interpolation class."""
+        _Interpolator1D.__init__(self, x, y, axis=axis)
+
+        self.bounds_error = bounds_error  # used by fill_value setter
+
+        # `copy` keyword semantics changed in NumPy 2.0, once that is
+        # the minimum version this can use `copy=None`.
+        self.copy = copy
+        if not copy:
+            self.copy = copy_if_needed
+
+        if kind in ['zero', 'slinear', 'quadratic', 'cubic']:
+            order = {'zero': 0, 'slinear': 1,
+                     'quadratic': 2, 'cubic': 3}[kind]
+            kind = 'spline'
+        elif isinstance(kind, int):
+            order = kind
+            kind = 'spline'
+        elif kind not in ('linear', 'nearest', 'nearest-up', 'previous',
+                          'next'):
+            raise NotImplementedError(f"{kind} is unsupported: Use fitpack "
+                                      "routines for other types.")
+        x = array(x, copy=self.copy)
+        y = array(y, copy=self.copy)
+
+        if not assume_sorted:
+            ind = np.argsort(x, kind="mergesort")
+            x = x[ind]
+            y = np.take(y, ind, axis=axis)
+
+        if x.ndim != 1:
+            raise ValueError("the x array must have exactly one dimension.")
+        if y.ndim == 0:
+            raise ValueError("the y array must have at least one dimension.")
+
+        # Force-cast y to a floating-point type, if it's not yet one
+        if not issubclass(y.dtype.type, np.inexact):
+            y = y.astype(np.float64)
+
+        # Backward compatibility
+        self.axis = axis % y.ndim
+
+        # Interpolation goes internally along the first axis
+        self.y = y
+        self._y = self._reshape_yi(self.y)
+        self.x = x
+        del y, x  # clean up namespace to prevent misuse; use attributes
+        self._kind = kind
+
+        # Adjust to interpolation kind; store reference to *unbound*
+        # interpolation methods, in order to avoid circular references to self
+        # stored in the bound instance methods, and therefore delayed garbage
+        # collection.  See: https://docs.python.org/reference/datamodel.html
+        if kind in ('linear', 'nearest', 'nearest-up', 'previous', 'next'):
+            # Make a "view" of the y array that is rotated to the interpolation
+            # axis.
+            minval = 1
+            if kind == 'nearest':
+                # Do division before addition to prevent possible integer
+                # overflow
+                self._side = 'left'
+                self.x_bds = self.x / 2.0
+                self.x_bds = self.x_bds[1:] + self.x_bds[:-1]
+
+                self._call = self.__class__._call_nearest
+            elif kind == 'nearest-up':
+                # Do division before addition to prevent possible integer
+                # overflow
+                self._side = 'right'
+                self.x_bds = self.x / 2.0
+                self.x_bds = self.x_bds[1:] + self.x_bds[:-1]
+
+                self._call = self.__class__._call_nearest
+            elif kind == 'previous':
+                # Side for np.searchsorted and index for clipping
+                self._side = 'left'
+                self._ind = 0
+                # Move x by one floating point value to the left
+                self._x_shift = np.nextafter(self.x, -np.inf)
+                self._call = self.__class__._call_previousnext
+                if _do_extrapolate(fill_value):
+                    self._check_and_update_bounds_error_for_extrapolation()
+                    # assume y is sorted by x ascending order here.
+                    fill_value = (np.nan, np.take(self.y, -1, axis))
+            elif kind == 'next':
+                self._side = 'right'
+                self._ind = 1
+                # Move x by one floating point value to the right
+                self._x_shift = np.nextafter(self.x, np.inf)
+                self._call = self.__class__._call_previousnext
+                if _do_extrapolate(fill_value):
+                    self._check_and_update_bounds_error_for_extrapolation()
+                    # assume y is sorted by x ascending order here.
+                    fill_value = (np.take(self.y, 0, axis), np.nan)
+            else:
+                # Check if we can delegate to numpy.interp (2x-10x faster).
+                np_dtypes = (np.dtype(np.float64), np.dtype(int))
+                cond = self.x.dtype in np_dtypes and self.y.dtype in np_dtypes
+                cond = cond and self.y.ndim == 1
+                cond = cond and not _do_extrapolate(fill_value)
+
+                if cond:
+                    self._call = self.__class__._call_linear_np
+                else:
+                    self._call = self.__class__._call_linear
+        else:
+            minval = order + 1
+
+            rewrite_nan = False
+            xx, yy = self.x, self._y
+            if order > 1:
+                # Quadratic or cubic spline. If input contains even a single
+                # nan, then the output is all nans. We cannot just feed data
+                # with nans to make_interp_spline because it calls LAPACK.
+                # So, we make up a bogus x and y with no nans and use it
+                # to get the correct shape of the output, which we then fill
+                # with nans.
+                # For slinear or zero order spline, we just pass nans through.
+                mask = np.isnan(self.x)
+                if mask.any():
+                    sx = self.x[~mask]
+                    if sx.size == 0:
+                        raise ValueError("`x` array is all-nan")
+                    xx = np.linspace(np.nanmin(self.x),
+                                     np.nanmax(self.x),
+                                     len(self.x))
+                    rewrite_nan = True
+                if np.isnan(self._y).any():
+                    yy = np.ones_like(self._y)
+                    rewrite_nan = True
+
+            self._spline = make_interp_spline(xx, yy, k=order,
+                                              check_finite=False)
+            if rewrite_nan:
+                self._call = self.__class__._call_nan_spline
+            else:
+                self._call = self.__class__._call_spline
+
+        if len(self.x) < minval:
+            raise ValueError(f"x and y arrays must have at least {minval} entries")
+
+        self.fill_value = fill_value  # calls the setter, can modify bounds_err
+
+    @property
+    def fill_value(self):
+        """The fill value."""
+        # backwards compat: mimic a public attribute
+        return self._fill_value_orig
+
+    @fill_value.setter
+    def fill_value(self, fill_value):
+        # extrapolation only works for nearest neighbor and linear methods
+        if _do_extrapolate(fill_value):
+            self._check_and_update_bounds_error_for_extrapolation()
+            self._extrapolate = True
+        else:
+            broadcast_shape = (self.y.shape[:self.axis] +
+                               self.y.shape[self.axis + 1:])
+            if len(broadcast_shape) == 0:
+                broadcast_shape = (1,)
+            # it's either a pair (_below_range, _above_range) or a single value
+            # for both above and below range
+            if isinstance(fill_value, tuple) and len(fill_value) == 2:
+                below_above = [np.asarray(fill_value[0]),
+                               np.asarray(fill_value[1])]
+                names = ('fill_value (below)', 'fill_value (above)')
+                for ii in range(2):
+                    below_above[ii] = _check_broadcast_up_to(
+                        below_above[ii], broadcast_shape, names[ii])
+            else:
+                fill_value = np.asarray(fill_value)
+                below_above = [_check_broadcast_up_to(
+                    fill_value, broadcast_shape, 'fill_value')] * 2
+            self._fill_value_below, self._fill_value_above = below_above
+            self._extrapolate = False
+            if self.bounds_error is None:
+                self.bounds_error = True
+        # backwards compat: fill_value was a public attr; make it writeable
+        self._fill_value_orig = fill_value
+
+    def _check_and_update_bounds_error_for_extrapolation(self):
+        if self.bounds_error:
+            raise ValueError("Cannot extrapolate and raise "
+                             "at the same time.")
+        self.bounds_error = False
+
+    def _call_linear_np(self, x_new):
+        # Note that out-of-bounds values are taken care of in self._evaluate
+        return np.interp(x_new, self.x, self.y)
+
+    def _call_linear(self, x_new):
+        # 2. Find where in the original data, the values to interpolate
+        #    would be inserted.
+        #    Note: If x_new[n] == x[m], then m is returned by searchsorted.
+        x_new_indices = searchsorted(self.x, x_new)
+
+        # 3. Clip x_new_indices so that they are within the range of
+        #    self.x indices and at least 1. Removes mis-interpolation
+        #    of x_new[n] = x[0]
+        x_new_indices = x_new_indices.clip(1, len(self.x)-1).astype(int)
+
+        # 4. Calculate y_new using de Boor's algorithm for linear interpolation.
+        lo = x_new_indices - 1
+        hi = x_new_indices
+
+        x_lo = self.x[lo]
+        x_hi = self.x[hi]
+        y_lo = self._y[lo]
+        y_hi = self._y[hi]
+
+        # Note that the following expression relies on the specifics of the
+        # broadcasting semantics.
+        y_new = (
+            ((x_new - x_lo)/(x_hi - x_lo))[:, None] * y_hi
+            + ((x_hi - x_new)/(x_hi - x_lo))[:, None] * y_lo
+            )
+
+        return y_new
+
+    def _call_nearest(self, x_new):
+        """ Find nearest neighbor interpolated y_new = f(x_new)."""
+
+        # 2. Find where in the averaged data the values to interpolate
+        #    would be inserted.
+        #    Note: use side='left' (right) to searchsorted() to define the
+        #    halfway point to be nearest to the left (right) neighbor
+        x_new_indices = searchsorted(self.x_bds, x_new, side=self._side)
+
+        # 3. Clip x_new_indices so that they are within the range of x indices.
+        x_new_indices = x_new_indices.clip(0, len(self.x)-1).astype(intp)
+
+        # 4. Calculate the actual value for each entry in x_new.
+        y_new = self._y[x_new_indices]
+
+        return y_new
+
+    def _call_previousnext(self, x_new):
+        """Use previous/next neighbor of x_new, y_new = f(x_new)."""
+
+        # 1. Get index of left/right value
+        x_new_indices = searchsorted(self._x_shift, x_new, side=self._side)
+
+        # 2. Clip x_new_indices so that they are within the range of x indices.
+        x_new_indices = x_new_indices.clip(1-self._ind,
+                                           len(self.x)-self._ind).astype(intp)
+
+        # 3. Calculate the actual value for each entry in x_new.
+        y_new = self._y[x_new_indices+self._ind-1]
+
+        return y_new
+
+    def _call_spline(self, x_new):
+        return self._spline(x_new)
+
+    def _call_nan_spline(self, x_new):
+        out = self._spline(x_new)
+        out[...] = np.nan
+        return out
+
+    # pyrefly: ignore[bad-override-param-name]
+    def _evaluate(self, x_new):
+        # 1. Handle values in x_new that are outside of x. Throw error,
+        #    or return a list of mask array indicating the outofbounds values.
+        #    The behavior is set by the bounds_error variable.
+        x_new = asarray(x_new)
+        y_new = self._call(self, x_new)
+        if not self._extrapolate:
+            below_bounds, above_bounds = self._check_bounds(x_new)
+            if len(y_new) > 0:
+                # Note fill_value must be broadcast up to the proper size
+                # and flattened to work here
+                y_new[below_bounds] = self._fill_value_below
+                y_new[above_bounds] = self._fill_value_above
+        return y_new
+
+    def _check_bounds(self, x_new):
+        """Check the inputs for being in the bounds of the interpolated data.
+
+        Parameters
+        ----------
+        x_new : array
+
+        Returns
+        -------
+        out_of_bounds : bool array
+            The mask on x_new of values that are out of the bounds.
+        """
+
+        # If self.bounds_error is True, we raise an error if any x_new values
+        # fall outside the range of x. Otherwise, we return an array indicating
+        # which values are outside the boundary region.
+        below_bounds = x_new < self.x[0]
+        above_bounds = x_new > self.x[-1]
+
+        if self.bounds_error and below_bounds.any():
+            below_bounds_value = x_new[np.argmax(below_bounds)]
+            raise ValueError(f"A value ({below_bounds_value}) in x_new is below "
+                             f"the interpolation range's minimum value ({self.x[0]}).")
+        if self.bounds_error and above_bounds.any():
+            above_bounds_value = x_new[np.argmax(above_bounds)]
+            raise ValueError(f"A value ({above_bounds_value}) in x_new is above "
+                             f"the interpolation range's maximum value ({self.x[-1]}).")
+
+        # !! Should we emit a warning if some values are out of bounds?
+        # !! matlab does not.
+        return below_bounds, above_bounds
+
+
+class _PPolyBase:
+    """Base class for piecewise polynomials -- NumPy backend."""
+    __slots__ = ('c', 'x', 'extrapolate', 'axis')
+
+    # generic type compatibility with scipy-stubs
+    __class_getitem__: classmethod = classmethod(GenericAlias)
+
+    def __init__(self, c, x, extrapolate=None, axis=0):
+        self.c = np.asarray(c)
+        self.x = np.ascontiguousarray(x, dtype=np.float64)
+
+        if extrapolate is None:
+            extrapolate = True
+        elif extrapolate != 'periodic':
+            extrapolate = bool(extrapolate)
+        self.extrapolate = extrapolate
+
+        if self.c.ndim < 2:
+            raise ValueError("Coefficients array must be at least "
+                             "2-dimensional.")
+
+        if not (0 <= axis < self.c.ndim - 1):
+            raise ValueError(f"axis={axis} must be between 0 and {self.c.ndim-1}")
+
+        self.axis = axis
+        if axis != 0:
+            # move the interpolation axis to be the first one in self.c
+            # More specifically, the target shape for self.c is (k, m, ...),
+            # and axis !=0 means that we have c.shape (..., k, m, ...)
+            #                                               ^
+            #                                              axis
+            # So we roll two of them.
+            self.c = np.moveaxis(self.c, axis+1, 0)
+            self.c = np.moveaxis(self.c, axis+1, 0)
+
+        if self.x.ndim != 1:
+            raise ValueError("x must be 1-dimensional")
+        if self.x.size < 2:
+            raise ValueError("at least 2 breakpoints are needed")
+        if self.c.ndim < 2:
+            raise ValueError("c must have at least 2 dimensions")
+        if self.c.shape[0] == 0:
+            raise ValueError("polynomial must be at least of order 0")
+        if self.c.shape[1] != self.x.size-1:
+            raise ValueError("number of coefficients != len(x)-1")
+        dx = np.diff(self.x)
+        if not (np.all(dx >= 0) or np.all(dx <= 0)):
+            raise ValueError("`x` must be strictly increasing or decreasing.")
+
+        dtype = self._get_dtype(self.c.dtype)
+        self.c = np.ascontiguousarray(self.c, dtype=dtype)
+
+    def _get_dtype(self, dtype):
+        if np.issubdtype(dtype, np.complexfloating) \
+               or np.issubdtype(self.c.dtype, np.complexfloating):
+            return np.complex128
+        else:
+            return np.float64
+
+    @classmethod
+    def construct_fast(cls, c, x, extrapolate=None, axis=0):
+        self = object.__new__(cls)
+        self.c = np.asarray(c)
+        self.x = np.asarray(x)
+        self.axis = axis
+        if extrapolate is None:
+            extrapolate = True
+        self.extrapolate = extrapolate
+        return self
+
+    def _ensure_c_contiguous(self):
+        """
+        c and x may be modified by the user. The Cython code expects
+        that they are C contiguous.
+        """
+        if not self.x.flags.c_contiguous:
+            self.x = self.x.copy()
+        if not self.c.flags.c_contiguous:
+            self.c = self.c.copy()
+
+    def extend(self, c, x):
+        c = np.asarray(c)
+        x = np.asarray(x)
+
+        if c.ndim < 2:
+            raise ValueError("invalid dimensions for c")
+        if x.ndim != 1:
+            raise ValueError("invalid dimensions for x")
+        if x.shape[0] != c.shape[1]:
+            raise ValueError(f"Shapes of x {x.shape} and c {c.shape} are incompatible")
+        if c.shape[2:] != self.c.shape[2:] or c.ndim != self.c.ndim:
+            raise ValueError(
+                f"Shapes of c {c.shape} and self.c {self.c.shape} are incompatible"
+            )
+
+        if c.size == 0:
+            return
+
+        dx = np.diff(x)
+        if not (np.all(dx >= 0) or np.all(dx <= 0)):
+            raise ValueError("`x` is not sorted.")
+
+        if self.x[-1] >= self.x[0]:
+            if not x[-1] >= x[0]:
+                raise ValueError("`x` is in the different order "
+                                "than `self.x`.")
+
+            if x[0] >= self.x[-1]:
+                action = 'append'
+            elif x[-1] <= self.x[0]:
+                action = 'prepend'
+            else:
+                raise ValueError("`x` is neither on the left or on the right "
+                                "from `self.x`.")
+        else:
+            if not x[-1] <= x[0]:
+                raise ValueError("`x` is in the different order "
+                                "than `self.x`.")
+
+            if x[0] <= self.x[-1]:
+                action = 'append'
+            elif x[-1] >= self.x[0]:
+                action = 'prepend'
+            else:
+                raise ValueError("`x` is neither on the left or on the right "
+                                "from `self.x`.")
+
+        dtype = self._get_dtype(c.dtype)
+
+        k2 = max(c.shape[0], self.c.shape[0])
+        c2 = np.zeros((k2, self.c.shape[1] + c.shape[1]) + self.c.shape[2:],
+                    dtype=dtype)
+
+        if action == 'append':
+            c2[k2-self.c.shape[0]:, :self.c.shape[1]] = self.c
+            c2[k2-c.shape[0]:, self.c.shape[1]:] = c
+            self.x = np.r_[self.x, x]
+        elif action == 'prepend':
+            c2[k2-self.c.shape[0]:, :c.shape[1]] = c
+            c2[k2-c.shape[0]:, c.shape[1]:] = self.c
+            self.x = np.r_[x, self.x]
+
+        self.c = c2
+
+    def __call__(self, x, nu=0, extrapolate=None):
+        if extrapolate is None:
+            extrapolate = self.extrapolate
+        x = np.asarray(x)
+        x_shape, x_ndim = x.shape, x.ndim
+        x = np.ascontiguousarray(x.ravel(), dtype=np.float64)
+
+        # With periodic extrapolation we map x to the segment
+        # [self.x[0], self.x[-1]].
+        if extrapolate == 'periodic':
+            x = self.x[0] + (x - self.x[0]) % (self.x[-1] - self.x[0])
+            extrapolate = False
+
+        out = np.empty((len(x), prod(self.c.shape[2:])), dtype=self.c.dtype)
+        self._ensure_c_contiguous()
+        self._evaluate(x, nu, extrapolate, out)
+        out = out.reshape(x_shape + self.c.shape[2:])
+        if self.axis != 0:
+            # transpose to move the calculated values to the interpolation axis
+            l = list(range(out.ndim))
+            l = l[x_ndim:x_ndim+self.axis] + l[:x_ndim] + l[x_ndim+self.axis:]
+            out = out.transpose(l)
+        return out
+
+
+class _PPoly(_PPolyBase):
+    """NumPy backend for PPoly."""
+
+    def _evaluate(self, x, nu, extrapolate, out):
+        _ppoly.evaluate(self.c.reshape(self.c.shape[0], self.c.shape[1], -1),
+                        self.x, x, nu, bool(extrapolate), out)
+
+    def derivative(self, nu=1):
+        if nu < 0:
+            return self.antiderivative(-nu)
+
+        # reduce order
+        if nu == 0:
+            c2 = self.c.copy()
+        else:
+            c2 = self.c[:-nu, :].copy()
+
+        if c2.shape[0] == 0:
+            # derivative of order 0 is zero
+            c2 = np.zeros((1,) + c2.shape[1:], dtype=c2.dtype)
+
+        # multiply by the correct rising factorials
+        factor = spec.poch(np.arange(c2.shape[0], 0, -1), nu)
+        c2 *= factor[(slice(None),) + (None,)*(c2.ndim-1)]
+
+        # construct a compatible polynomial
+        return self.construct_fast(c2, self.x, self.extrapolate, self.axis)
+
+    def antiderivative(self, nu=1):
+        """
+        Construct a new piecewise polynomial representing the antiderivative.
+
+        Antiderivative is also the indefinite integral of the function,
+        and derivative is its inverse operation.
+
+        Parameters
+        ----------
+        nu : int, optional
+            Order of antiderivative to evaluate. Default is 1, i.e., compute
+            the first integral. If negative, the derivative is returned.
+
+        Returns
+        -------
+        pp : PPoly
+            Piecewise polynomial of order k2 = k + n representing
+            the antiderivative of this polynomial.
+
+        Notes
+        -----
+        The antiderivative returned by this function is continuous and
+        continuously differentiable to order n-1, up to floating point
+        rounding error.
+
+        If antiderivative is computed and ``self.extrapolate='periodic'``,
+        it will be set to False for the returned instance. This is done because
+        the antiderivative is no longer periodic and its correct evaluation
+        outside of the initially given x interval is difficult.
+        """
+        if nu <= 0:
+            return self.derivative(-nu)
+
+        c = np.zeros((self.c.shape[0] + nu, self.c.shape[1]) + self.c.shape[2:],
+                     dtype=self.c.dtype)
+        c[:-nu] = self.c
+
+        # divide by the correct rising factorials
+        factor = spec.poch(np.arange(self.c.shape[0], 0, -1), nu)
+        c[:-nu] /= factor[(slice(None),) + (None,)*(c.ndim-1)]
+
+        # fix continuity of added degrees of freedom
+        self._ensure_c_contiguous()
+        _ppoly.fix_continuity(c.reshape(c.shape[0], c.shape[1], -1),
+                              self.x, nu - 1)
+
+        if self.extrapolate == 'periodic':
+            extrapolate = False
+        else:
+            extrapolate = self.extrapolate
+
+        # construct a compatible polynomial
+        return self.construct_fast(c, self.x, extrapolate, self.axis)
+
+    def integrate(self, a, b, extrapolate=None):
+        if extrapolate is None:
+            extrapolate = self.extrapolate
+
+        # Swap integration bounds if needed
+        sign = 1
+        if b < a:
+            a, b = b, a
+            sign = -1
+
+        range_int = np.empty((prod(self.c.shape[2:]),), dtype=self.c.dtype)
+        self._ensure_c_contiguous()
+
+        # Compute the integral.
+        if extrapolate == 'periodic':
+            # Split the integral into the part over period (can be several
+            # of them) and the remaining part.
+
+            xs, xe = self.x[0], self.x[-1]
+            period = xe - xs
+            interval = b - a
+            n_periods, left = divmod(interval, period)
+
+            if n_periods > 0:
+                _ppoly.integrate(
+                    self.c.reshape(self.c.shape[0], self.c.shape[1], -1),
+                    self.x, xs, xe, False, out=range_int)
+                range_int *= n_periods
+            else:
+                range_int.fill(0)
+
+            # Map a to [xs, xe], b is always a + left.
+            a = xs + (a - xs) % period
+            b = a + left
+
+            # If b <= xe then we need to integrate over [a, b], otherwise
+            # over [a, xe] and from xs to what is remained.
+            remainder_int = np.empty_like(range_int)
+            if b <= xe:
+                _ppoly.integrate(
+                    self.c.reshape(self.c.shape[0], self.c.shape[1], -1),
+                    self.x, a, b, False, out=remainder_int)
+                range_int += remainder_int
+            else:
+                _ppoly.integrate(
+                    self.c.reshape(self.c.shape[0], self.c.shape[1], -1),
+                    self.x, a, xe, False, out=remainder_int)
+                range_int += remainder_int
+
+                _ppoly.integrate(
+                    self.c.reshape(self.c.shape[0], self.c.shape[1], -1),
+                    self.x, xs, xs + left + a - xe, False, out=remainder_int)
+                range_int += remainder_int
+        else:
+            _ppoly.integrate(
+                self.c.reshape(self.c.shape[0], self.c.shape[1], -1),
+                self.x, a, b, bool(extrapolate), out=range_int)
+
+        # Return
+        range_int *= sign
+        return range_int.reshape(self.c.shape[2:])
+
+    def solve(self, y=0., discontinuity=True, extrapolate=None):
+
+        if extrapolate is None:
+            extrapolate = self.extrapolate
+
+        self._ensure_c_contiguous()
+
+        if np.issubdtype(self.c.dtype, np.complexfloating):
+            raise ValueError("Root finding is only for "
+                             "real-valued polynomials")
+
+        y = float(y)
+        r = _ppoly.real_roots(self.c.reshape(self.c.shape[0], self.c.shape[1], -1),
+                              self.x, y, bool(discontinuity),
+                              bool(extrapolate))
+        if self.c.ndim == 2:
+            return r[0]
+        else:
+            r2 = np.empty(prod(self.c.shape[2:]), dtype=object)
+            # this for-loop is equivalent to ``r2[...] = r``, but that's broken
+            # in NumPy 1.6.0
+            for ii, root in enumerate(r):
+                r2[ii] = root
+
+            return r2.reshape(self.c.shape[2:])
+
+    def roots(self, discontinuity=True, extrapolate=None):
+        return self.solve(0, discontinuity, extrapolate)
+
+    @classmethod
+    def from_spline(cls, tck, extrapolate=None):
+        t, c, k = tck
+
+        cvals = np.empty((k + 1, len(t)-1), dtype=c.dtype)
+        for m in range(k, -1, -1):
+            y = _fitpack_py.splev(t[:-1], (t, c, k), der=m)
+            cvals[k - m, :] = y / spec.gamma(m+1)
+
+        return cls.construct_fast(cvals, t, extrapolate)
+
+    @classmethod
+    def from_bernstein_basis(cls, bp, extrapolate=None):
+        dx = np.diff(bp.x)
+        k = bp.c.shape[0] - 1  # polynomial order
+
+        rest = (None,)*(bp.c.ndim-2)
+
+        c = np.zeros_like(bp.c)
+        for a in range(k+1):
+            factor = (-1)**a * comb(k, a) * bp.c[a]
+            for s in range(a, k+1):
+                val = comb(k-a, s-a) * (-1)**s
+                c[k-s] += factor * val / dx[(slice(None),)+rest]**s
+
+        if extrapolate is None:
+            extrapolate = bp.extrapolate
+
+        return cls.construct_fast(c, bp.x, extrapolate, bp.axis)
+
+
+class _BPoly(_PPolyBase):
+    """NumPy backend for BPoly."""
+
+    def _evaluate(self, x, nu, extrapolate, out):
+        _ppoly.evaluate_bernstein(
+            self.c.reshape(self.c.shape[0], self.c.shape[1], -1),
+            self.x, x, nu, bool(extrapolate), out)
+
+    def derivative(self, nu=1):
+        if nu < 0:
+            return self.antiderivative(-nu)
+
+        if nu > 1:
+            bp = self
+            for k in range(nu):
+                bp = bp.derivative()
+            return bp
+
+        # reduce order
+        if nu == 0:
+            c2 = self.c.copy()
+        else:
+            # For a polynomial
+            #    B(x) = \sum_{a=0}^{k} c_a b_{a, k}(x),
+            # we use the fact that
+            #   b'_{a, k} = k ( b_{a-1, k-1} - b_{a, k-1} ),
+            # which leads to
+            #   B'(x) = \sum_{a=0}^{k-1} (c_{a+1} - c_a) b_{a, k-1}
+            #
+            # finally, for an interval [y, y + dy] with dy != 1,
+            # we need to correct for an extra power of dy
+
+            rest = (None,)*(self.c.ndim-2)
+
+            k = self.c.shape[0] - 1
+            dx = np.diff(self.x)[(None, slice(None))+rest]
+            c2 = k * np.diff(self.c, axis=0) / dx
+
+        if c2.shape[0] == 0:
+            # derivative of order 0 is zero
+            c2 = np.zeros((1,) + c2.shape[1:], dtype=c2.dtype)
+
+        # construct a compatible polynomial
+        return self.construct_fast(c2, self.x, self.extrapolate, self.axis)
+
+    def antiderivative(self, nu=1):
+        if nu <= 0:
+            return self.derivative(-nu)
+
+        if nu > 1:
+            bp = self
+            for k in range(nu):
+                bp = bp.antiderivative()
+            return bp
+
+        # Construct the indefinite integrals on individual intervals
+        c, x = self.c, self.x
+        k = c.shape[0]
+        c2 = np.zeros((k+1,) + c.shape[1:], dtype=c.dtype)
+
+        c2[1:, ...] = np.cumsum(c, axis=0) / k
+        delta = x[1:] - x[:-1]
+        c2 *= delta[(None, slice(None)) + (None,)*(c.ndim-2)]
+
+        # Now fix continuity: on the very first interval, take the integration
+        # constant to be zero; on an interval [x_j, x_{j+1}) with j>0,
+        # the integration constant is then equal to the jump of the `bp` at x_j.
+        # The latter is given by the coefficient of B_{n+1, n+1}
+        # *on the previous interval* (other B. polynomials are zero at the
+        # breakpoint). Finally, use the fact that BPs form a partition of unity.
+        c2[:, 1:] += np.cumsum(c2[k, :], axis=0)[:-1]
+
+        if self.extrapolate == 'periodic':
+            extrapolate = False
+        else:
+            extrapolate = self.extrapolate
+
+        return self.construct_fast(c2, self.x, extrapolate, axis=self.axis)
+
+    def integrate(self, a, b, extrapolate=None):
+        # XXX: can probably use instead the fact that
+        # \int_0^{1} B_{j, n}(x) \dx = 1/(n+1)
+        ib = self.antiderivative()
+        if extrapolate is None:
+            extrapolate = self.extrapolate
+
+        # ib.extrapolate shouldn't be 'periodic', it is converted to
+        # False for 'periodic. in antiderivative() call.
+        if extrapolate != 'periodic':
+            ib.extrapolate = extrapolate
+
+        if extrapolate == 'periodic':
+            # Split the integral into the part over period (can be several
+            # of them) and the remaining part.
+
+            # For simplicity and clarity convert to a <= b case.
+            if a <= b:
+                sign = 1
+            else:
+                a, b = b, a
+                sign = -1
+
+            xs, xe = self.x[0], self.x[-1]
+            period = xe - xs
+            interval = b - a
+            n_periods, left = divmod(interval, period)
+            res = n_periods * (ib(xe) - ib(xs))
+
+            # Map a and b to [xs, xe].
+            a = xs + (a - xs) % period
+            b = a + left
+
+            # If b <= xe then we need to integrate over [a, b], otherwise
+            # over [a, xe] and from xs to what is remained.
+            if b <= xe:
+                res += ib(b) - ib(a)
+            else:
+                res += ib(xe) - ib(a) + ib(xs + left + a - xe) - ib(xs)
+
+            return sign * res
+        else:
+            return ib(b) - ib(a)
+
+    def extend(self, c, x):
+        k = max(self.c.shape[0], c.shape[0])
+        self.c = self._raise_degree(self.c, k - self.c.shape[0])
+        c = self._raise_degree(c, k - c.shape[0])
+        _PPolyBase.extend(self, c, x)
+    extend.__doc__ = _PPolyBase.extend.__doc__
+
+    @classmethod
+    def from_power_basis(cls, pp, extrapolate=None):
+        dx = np.diff(pp.x)
+        k = pp.c.shape[0] - 1   # polynomial order
+
+        rest = (None,)*(pp.c.ndim-2)
+
+        c = np.zeros_like(pp.c)
+        for a in range(k+1):
+            factor = pp.c[a] / comb(k, k-a) * dx[(slice(None),) + rest]**(k-a)
+            for j in range(k-a, k+1):
+                c[j] += factor * comb(j, k-a)
+
+        if extrapolate is None:
+            extrapolate = pp.extrapolate
+
+        return cls.construct_fast(c, pp.x, extrapolate, pp.axis)
+
+    @classmethod
+    def from_derivatives(cls, xi, yi, orders=None, extrapolate=None):
+        xi = np.asarray(xi)
+        if len(xi) != len(yi):
+            raise ValueError("xi and yi need to have the same length")
+        if np.any(xi[1:] - xi[:1] <= 0):
+            raise ValueError("x coordinates are not in increasing order")
+
+        # number of intervals
+        m = len(xi) - 1
+
+        # global poly order is k-1, local orders are <=k and can vary
+        try:
+            k = max(len(yi[i]) + len(yi[i+1]) for i in range(m))
+        except TypeError as e:
+            raise ValueError(
+                "Using a 1-D array for y? Please .reshape(-1, 1)."
+            ) from e
+
+        if orders is None:
+            orders = [None] * m
+        else:
+            if isinstance(orders, int | np.integer):
+                orders = [orders] * m
+            k = max(k, max(orders))
+
+            if any(o <= 0 for o in orders):
+                raise ValueError("Orders must be positive.")
+
+        c = []
+        for i in range(m):
+            y1, y2 = yi[i], yi[i+1]
+            if orders[i] is None:
+                n1, n2 = len(y1), len(y2)
+            else:
+                n = orders[i]+1
+                n1 = min(n//2, len(y1))
+                n2 = min(n - n1, len(y2))
+                n1 = min(n - n2, len(y2))
+                if n1 + n2 != n:
+                    mesg = (
+                        f"Point {xi[i]} has {len(y1)} derivatives, point {xi[i+1]} has "
+                        f"{len(y2)} derivatives, but order {orders[i]} requested"
+                    )
+                    raise ValueError(mesg)
+
+                if not (n1 <= len(y1) and n2 <= len(y2)):
+                    raise ValueError("`order` input incompatible with"
+                                     " length y1 or y2.")
+
+            b = _BPoly._construct_from_derivatives(xi[i], xi[i+1],
+                                                  y1[:n1], y2[:n2])
+            if len(b) < k:
+                b = _BPoly._raise_degree(b, k - len(b))
+            c.append(b)
+
+        c = np.asarray(c)
+        return cls(c.swapaxes(0, 1), xi, extrapolate)
+
+    @staticmethod
+    def _construct_from_derivatives(xa, xb, ya, yb):
+        ya, yb = np.asarray(ya), np.asarray(yb)
+        if ya.shape[1:] != yb.shape[1:]:
+            raise ValueError(
+                f"Shapes of ya {ya.shape} and yb {yb.shape} are incompatible"
+            )
+
+        dta, dtb = ya.dtype, yb.dtype
+        if (np.issubdtype(dta, np.complexfloating) or
+               np.issubdtype(dtb, np.complexfloating)):
+            dt = np.complex128
+        else:
+            dt = np.float64
+
+        na, nb = len(ya), len(yb)
+        n = na + nb
+
+        c = np.empty((na+nb,) + ya.shape[1:], dtype=dt)
+
+        # compute coefficients of a polynomial degree na+nb-1
+        # walk left-to-right
+        for q in range(0, na):
+            c[q] = ya[q] / spec.poch(n - q, q) * (xb - xa)**q
+            for j in range(0, q):
+                c[q] -= (-1)**(j+q) * comb(q, j) * c[j]
+
+        # now walk right-to-left
+        for q in range(0, nb):
+            c[-q-1] = yb[q] / spec.poch(n - q, q) * (-1)**q * (xb - xa)**q
+            for j in range(0, q):
+                c[-q-1] -= (-1)**(j+1) * comb(q, j+1) * c[-q+j]
+
+        return c
+
+    @staticmethod
+    def _raise_degree(c, d):
+        if d == 0:
+            return c
+
+        k = c.shape[0] - 1
+        out = np.zeros((c.shape[0] + d,) + c.shape[1:], dtype=c.dtype)
+
+        for a in range(c.shape[0]):
+            f = c[a] * comb(k, a)
+            for j in range(d+1):
+                out[a+j] += f * comb(d, j) / comb(k+d, a+j)
+        return out
+
+
+@functools.lru_cache(16)
+def _get_xp_ppoly_cls(xp):
+    """Returns ppoly class to delegate to for xp along with internal array namespace.
+
+    Parameters
+    ----------
+    xp : module
+
+    Returns
+    -------
+    cls : type
+        The ppoly class to delegate to for namespace `xp`.
+    namespace : module
+        The internal namespace that calculations are performed with
+        (may differ from `xp`, e.g. numpy delegation for torch on CPU).
+    """
+    # A device kwarg could be added to give device dependent delegation
+    # e.g., delegating torch to numpy on CPU and cupy on GPU.
+    if is_numpy(xp):
+        return _PPoly, xp
+    spx = scipy_namespace_for(xp)
+    cls = getattr(getattr(spx, "interpolate", None), "PPoly", None)
+    if cls is not None:
+        return cls, xp
+    return _PPoly, np
+
+
+@functools.lru_cache(16)
+def _get_xp_bpoly_cls(xp):
+    """Returns bpoly class to delegate to for xp along with internal array namespace.
+
+    Parameters
+    ----------
+    xp : module
+
+    Returns
+    -------
+    cls : type
+        The bpoly class to delegate to for namespace `xp`.
+    namespace : module
+        The internal namespace that calculations are performed with
+        (may differ from `xp`, e.g. numpy delegation for torch on CPU).
+    """
+    # A device kwarg could be added to give device dependent delegation
+    # e.g., delegating torch to numpy on CPU and cupy on GPU.
+    if is_numpy(xp):
+        return _BPoly, xp
+    spx = scipy_namespace_for(xp)
+    cls = getattr(getattr(spx, "interpolate", None), "BPoly", None)
+    if cls is not None:
+        return cls, xp
+    return _BPoly, np
+
+
+_ppoly_extra_note = (
+    """The methods ``solve`` and ``roots`` are currently not supported
+    with CuPy. ``solve`` and ``roots`` with ``c.ndim > 2`` are currently
+    only supported with NumPy.
+
+    If a ppoly object is called on an input array ``x`` with namespace
+    different from the namespace ``xp`` of the breakpoints and coefficients
+    with which the ppoly object was instantiated, an attempt will be made to
+    coerce ``x`` to the ``xp`` namespace. If the conversion succeeds, the
+    output will be an array from the ``xp`` namespace. Mixing namespaces in
+    this way is not recommended.
+
+    """
+)
+
+
+@xp_capabilities(
+    cpu_only=True, jax_jit=False,
+    exceptions=["cupy"],
+    skip_backends=[
+        ("dask.array",
+         "https://github.com/scipy/scipy/issues/24205")
+    ],
+    method_capabilities={
+        "roots": dict(
+            cpu_only=True,
+            jax_jit=False,
+            skip_backends=[
+                ("dask.array",
+                 "https://github.com/scipy/scipy/issues/24205")
+            ],
+        ),
+        "solve": dict(
+            cpu_only=True,
+            jax_jit=False,
+            skip_backends=[
+                ("dask.array",
+                 "https://github.com/scipy/scipy/issues/24205")
+            ],
+        ),
+    },
+    extra_note=_ppoly_extra_note,
+)
+class PPoly:
+    """Piecewise polynomial in the power basis.
+
+    The polynomial between ``x[i]`` and ``x[i + 1]`` is written in the
+    local power basis::
+
+        S = sum(c[m, i] * (xp - x[i])**(k-m) for m in range(k+1))
+
+    where ``k`` is the degree of the polynomial.
+
+    Parameters
+    ----------
+    c : ndarray, shape (k+1, m, ...)
+        Polynomial coefficients, degree `k` and `m` intervals.
+    x : ndarray, shape (m+1,)
+        Polynomial breakpoints. Must be sorted in either increasing or
+        decreasing order.
+    extrapolate : {bool, 'periodic', None}, optional
+        If bool, determines whether to extrapolate to out-of-bounds points
+        based on first and last intervals, or to return NaNs. If 'periodic',
+        periodic extrapolation is used. If None (default), it is set to True.
+        See :ref:`tutorial-interpolate_out_of_bounds`.
+    axis : int, optional
+        Interpolation axis. Default is zero.
+
+    Attributes
+    ----------
+    x : ndarray
+        Breakpoints.
+    c : ndarray
+        Coefficients of the polynomials. They are reshaped
+        to a 3-D array with the last dimension representing
+        the trailing dimensions of the original coefficient array.
+    axis : int
+        Interpolation axis.
+
+    Methods
+    -------
+    __call__
+    derivative
+    antiderivative
+    integrate
+    solve
+    roots
+    extend
+    from_spline
+    from_bernstein_basis
+    construct_fast
+
+    See Also
+    --------
+    BPoly : piecewise polynomials in the Bernstein basis
+
+    Notes
+    -----
+    High-order polynomials in the power basis can be numerically
+    unstable. Precision problems can start to appear for orders
+    larger than 20-30.
+    """
+
+    # generic type compatibility with scipy-stubs
+    __class_getitem__: classmethod = classmethod(GenericAlias)
+
+    def __init__(self, c, x, extrapolate=None, axis=0):
+        xp = array_namespace(c, x)
+        xp_ppoly_cls, xp_internal = _get_xp_ppoly_cls(xp)
+        if not is_numpy(xp):
+            c, x = xp_internal.asarray(c), xp_internal.asarray(x)
+        self._delegate_to = xp_ppoly_cls(c, x, extrapolate=extrapolate, axis=axis)
+        self._xp = xp
+        self._xp_internal = xp_internal
+
+    def __getstate__(self):
+        state = self.__dict__.copy()
+        state["_xp"] = state["_xp"].empty(0)
+        state.pop("_xp_internal")
+        return state
+
+    def __setstate__(self, state):
+        self._xp = array_namespace(state.pop("_xp"))
+        _, xp_internal = _get_xp_ppoly_cls(self._xp)
+        self._xp_internal = xp_internal
+        self.__dict__.update(state)
+
+    @classmethod
+    def _construct_from_xp(cls, xp_ppoly, *, xp_external):
+        self = object.__new__(cls)
+        self._delegate_to = xp_ppoly
+        self._xp = xp_external
+        self._xp_internal = array_namespace(xp_ppoly.c)
+        return self
+
+    @classmethod
+    def construct_fast(cls, c, x, extrapolate=None, axis=0):
+        """
+        Construct the piecewise polynomial without making checks.
+
+        Takes the same parameters as the constructor. Input arguments
+        ``c`` and ``x`` must be arrays of the correct shape and type. The
+        ``c`` array can only be of dtypes float and complex, and ``x``
+        array must have dtype float.
+        """
+        xp = array_namespace(c, x)
+        xp_ppoly_cls, xp_internal = _get_xp_ppoly_cls(xp)
+        c, x = xp_internal.asarray(c), xp_internal.asarray(x)
+        return cls._construct_from_xp(
+            xp_ppoly_cls.construct_fast(
+                c, x, extrapolate=extrapolate, axis=axis
+            ),
+            xp_external=xp,
+        )
+
+    @property
+    def c(self):
+        return self._xp.asarray(self._delegate_to.c)
+
+    @c.setter
+    def c(self, c):
+        self._delegate_to.c = (
+            self._xp_internal.asarray(c) if is_numpy(self._xp_internal) else c
+        )
+
+    @property
+    def x(self):
+        return self._xp.asarray(self._delegate_to.x)
+
+    @x.setter
+    def x(self, x):
+        self._delegate_to.x = (
+            self._xp_internal.asarray(x) if is_numpy(self._xp_internal) else x
+        )
+
+    @property
+    def extrapolate(self):
+        return self._delegate_to.extrapolate
+
+    @extrapolate.setter
+    def extrapolate(self, extrapolate):
+        self._delegate_to.extrapolate = extrapolate
+
+    @property
+    def axis(self):
+        return self._delegate_to.axis
+
+    @axis.setter
+    def axis(self, axis):
+        self._delegate_to.axis = axis
+
+    def extend(self, c, x):
+        """
+        Add additional breakpoints and coefficients to the polynomial.
+
+        Parameters
+        ----------
+        c : ndarray, size (k, m, ...)
+            Additional coefficients for polynomials in intervals. Note that
+            the first additional interval will be formed using one of the
+            ``self.x`` end points.
+        x : ndarray, size (m,)
+            Additional breakpoints. Must be sorted in the same order as
+            ``self.x`` and either to the right or to the left of the current
+            breakpoints.
+
+        Notes
+        -----
+        This method is not thread safe and must not be executed concurrently
+        with other methods available in this class. Doing so may cause
+        unexpected errors or numerical output mismatches.
+        """
+        c, x = self._xp_internal.asarray(c), self._xp_internal.asarray(x)
+        self._delegate_to.extend(c, x)
+
+    def __call__(self, x, nu=0, extrapolate=None):
+        """
+        Evaluate the piecewise polynomial or its derivative.
+
+        Parameters
+        ----------
+        x : array_like
+            Points to evaluate the interpolant at.
+        nu : int, optional
+            Order of derivative to evaluate. Must be non-negative.
+        extrapolate : {bool, 'periodic', None}, optional
+            If bool, determines whether to extrapolate to out-of-bounds points
+            based on first and last intervals, or to return NaNs.
+            If 'periodic', periodic extrapolation is used.
+            If None (default), use `self.extrapolate`.
+
+        Returns
+        -------
+        y : array_like
+            Interpolated values. Shape is determined by replacing
+            the interpolation axis in the original array with the shape of x.
+
+        Notes
+        -----
+        Derivatives are evaluated piecewise for each polynomial
+        segment, even if the polynomial is not differentiable at the
+        breakpoints. The polynomial intervals are considered half-open,
+        ``[a, b)``, except for the last interval which is closed
+        ``[a, b]``.
+        """
+        return self._xp.asarray(
+            self._delegate_to(
+                self._xp_internal.asarray(x), nu=nu, extrapolate=extrapolate
+            )
+        )
+
+    def derivative(self, nu=1):
+        """
+        Construct a new piecewise polynomial representing the derivative.
+
+        Parameters
+        ----------
+        nu : int, optional
+            Order of derivative to evaluate. Default is 1, i.e., compute the
+            first derivative. If negative, the antiderivative is returned.
+
+        Returns
+        -------
+        pp : PPoly
+            Piecewise polynomial of order k2 = k - n representing the derivative
+            of this polynomial.
+
+        Notes
+        -----
+        Derivatives are evaluated piecewise for each polynomial
+        segment, even if the polynomial is not differentiable at the
+        breakpoints. The polynomial intervals are considered half-open,
+        ``[a, b)``, except for the last interval which is closed
+        ``[a, b]``.
+        """
+        return self._construct_from_xp(
+            self._delegate_to.derivative(nu=nu),
+            xp_external=self._xp,
+        )
+
+    def antiderivative(self, nu=1):
+        """
+        Construct a new piecewise polynomial representing the antiderivative.
+
+        Antiderivative is also the indefinite integral of the function,
+        and derivative is its inverse operation.
+
+        Parameters
+        ----------
+        nu : int, optional
+            Order of antiderivative to evaluate. Default is 1, i.e., compute
+            the first integral. If negative, the derivative is returned.
+
+        Returns
+        -------
+        pp : PPoly
+            Piecewise polynomial of order k2 = k + n representing
+            the antiderivative of this polynomial.
+
+        Notes
+        -----
+        The antiderivative returned by this function is continuous and
+        continuously differentiable to order n-1, up to floating point
+        rounding error.
+
+        If antiderivative is computed and ``self.extrapolate='periodic'``,
+        it will be set to False for the returned instance. This is done because
+        the antiderivative is no longer periodic and its correct evaluation
+        outside of the initially given x interval is difficult.
+        """
+        return self._construct_from_xp(
+            self._delegate_to.antiderivative(nu=nu),
+            xp_external=self._xp,
+        )
+
+    def integrate(self, a, b, extrapolate=None):
+        """
+        Compute a definite integral over a piecewise polynomial.
+
+        Parameters
+        ----------
+        a : float
+            Lower integration bound
+        b : float
+            Upper integration bound
+        extrapolate : {bool, 'periodic', None}, optional
+            If bool, determines whether to extrapolate to out-of-bounds points
+            based on first and last intervals, or to return NaNs.
+            If 'periodic', periodic extrapolation is used.
+            If None (default), use `self.extrapolate`.
+
+        Returns
+        -------
+        ig : array_like
+            Definite integral of the piecewise polynomial over [a, b]
+        """
+        return self._xp.asarray(
+            self._delegate_to.integrate(a, b, extrapolate=extrapolate)
+        )
+
+    def solve(self, y=0, discontinuity=True, extrapolate=None):
+        """
+        Find real solutions of the equation ``pp(x) == y``.
+
+        Parameters
+        ----------
+        y : float, optional
+            Right-hand side. Default is zero.
+        discontinuity : bool, optional
+            Whether to report sign changes across discontinuities at
+            breakpoints as roots.
+        extrapolate : {bool, 'periodic', None}, optional
+            If bool, determines whether to return roots from the polynomial
+            extrapolated based on first and last intervals, 'periodic' works
+            the same as False. If None (default), use `self.extrapolate`.
+
+        Returns
+        -------
+        roots : ndarray
+            Roots of the polynomial(s).
+
+            If the PPoly object describes multiple polynomials, the
+            return value is an object array whose each element is an
+            ndarray containing the roots.
+
+        Notes
+        -----
+        This routine works only on real-valued polynomials.
+
+        If the piecewise polynomial contains sections that are
+        identically zero, the root list will contain the start point
+        of the corresponding interval, followed by a ``nan`` value.
+
+        If the polynomial is discontinuous across a breakpoint, and
+        there is a sign change across the breakpoint, this is reported
+        if the `discont` parameter is True.
+
+        Examples
+        --------
+
+        Finding roots of ``[x**2 - 1, (x - 1)**2]`` defined on intervals
+        ``[-2, 1], [1, 2]``:
+
+        >>> import numpy as np
+        >>> from scipy.interpolate import PPoly
+        >>> pp = PPoly(np.array([[1, -4, 3], [1, 0, 0]]).T, [-2, 1, 2])
+        >>> pp.solve()
+        array([-1.,  1.])
+        """
+        return self._xp.asarray(
+            self._delegate_to.solve(
+                y=y, discontinuity=discontinuity, extrapolate=extrapolate
+            )
+        )
+
+    def roots(self, discontinuity=True, extrapolate=None):
+        """
+        Find real roots of the piecewise polynomial.
+
+        Parameters
+        ----------
+        discontinuity : bool, optional
+            Whether to report sign changes across discontinuities at
+            breakpoints as roots.
+        extrapolate : {bool, 'periodic', None}, optional
+            If bool, determines whether to return roots from the polynomial
+            extrapolated based on first and last intervals, 'periodic' works
+            the same as False. If None (default), use `self.extrapolate`.
+
+        Returns
+        -------
+        roots : ndarray
+            Roots of the polynomial(s).
+
+            If the PPoly object describes multiple polynomials, the
+            return value is an object array whose each element is an
+            ndarray containing the roots.
+
+        See Also
+        --------
+        PPoly.solve
+        """
+        return self.solve(0, discontinuity, extrapolate)
+
+    @classmethod
+    def from_spline(cls, tck, extrapolate=None):
+        """
+        Construct a piecewise polynomial from a spline
+
+        Parameters
+        ----------
+        tck
+            A spline, as returned by `splrep` or a BSpline object.
+        extrapolate : bool or 'periodic', optional
+            If bool, determines whether to extrapolate to out-of-bounds points
+            based on first and last intervals, or to return NaNs.
+            If 'periodic', periodic extrapolation is used. Default is True.
+
+        Examples
+        --------
+        Construct an interpolating spline and convert it to a `PPoly` instance
+
+        >>> import numpy as np
+        >>> from scipy.interpolate import splrep, PPoly
+        >>> x = np.linspace(0, 1, 11)
+        >>> y = np.sin(2*np.pi*x)
+        >>> tck = splrep(x, y, s=0)
+        >>> p = PPoly.from_spline(tck)
+        >>> isinstance(p, PPoly)
+        True
+
+        Note that this function only supports 1D splines out of the box.
+
+        If the ``tck`` object represents a parametric spline (e.g. constructed
+        by `splprep` or a `BSpline` with ``c.ndim > 1``), you will need to loop
+        over the dimensions manually.
+
+        >>> from scipy.interpolate import splprep, splev
+        >>> t = np.linspace(0, 1, 11)
+        >>> x = np.sin(2*np.pi*t)
+        >>> y = np.cos(2*np.pi*t)
+        >>> (t, c, k), u = splprep([x, y], s=0)
+
+        Note that ``c`` is a list of two arrays of length 11.
+
+        >>> unew = np.arange(0, 1.01, 0.01)
+        >>> out = splev(unew, (t, c, k))
+
+        To convert this spline to the power basis, we convert each
+        component of the list of b-spline coefficients, ``c``, into the
+        corresponding cubic polynomial.
+
+        >>> polys = [PPoly.from_spline((t, cj, k)) for cj in c]
+        >>> polys[0].c.shape
+        (4, 14)
+
+        Note that the coefficients of the polynomials `polys` are in the
+        power basis and their dimensions reflect just that: here 4 is the order
+        (degree+1), and 14 is the number of intervals---which is nothing but
+        the length of the knot array of the original `tck` minus one.
+
+        Optionally, we can stack the components into a single `PPoly` along
+        the third dimension:
+
+        >>> cc = np.dstack([p.c for p in polys])    # has shape = (4, 14, 2)
+        >>> poly = PPoly(cc, polys[0].x)
+        >>> np.allclose(poly(unew).T,     # note the transpose to match `splev`
+        ...             out, atol=1e-15)
+        True
+
+        """
+        if isinstance(tck, BSpline):
+            t, c, k = tck.tck
+            xp = tck._xp
+            if extrapolate is None:
+                extrapolate = tck.extrapolate
+        else:
+            t, c, k = tck
+            xp = array_namespace(t, c)
+        xp_cls, xp_internal = _get_xp_ppoly_cls(xp)
+        t, c = xp_internal.asarray(t), xp_internal.asarray(c)
+        pp = xp_cls.from_spline((t, c, k), extrapolate=extrapolate)
+        return cls._construct_from_xp(pp, xp_external=xp)
+
+    @classmethod
+    def from_bernstein_basis(cls, bp, extrapolate=None):
+        """
+        Construct a piecewise polynomial in the power basis
+        from a polynomial in Bernstein basis.
+
+        Parameters
+        ----------
+        bp : BPoly
+            A Bernstein basis polynomial, as created by BPoly
+        extrapolate : bool or 'periodic', optional
+            If bool, determines whether to extrapolate to out-of-bounds points
+            based on first and last intervals, or to return NaNs.
+            If 'periodic', periodic extrapolation is used. Default is True.
+        """
+        if not isinstance(bp, BPoly):
+            raise TypeError(f".from_bernstein_basis only accepts BPoly instances. "
+                            f"Got {type(bp)} instead.")
+        xp = bp._xp
+        xp_cls, _ = _get_xp_ppoly_cls(xp)
+        pp = xp_cls.from_bernstein_basis(bp._delegate_to, extrapolate=extrapolate)
+        return cls._construct_from_xp(pp, xp_external=xp)
+
+
+_bpoly_extra_note = (
+    """If a bpoly object is called on an input array ``x`` with namespace
+    different from the namespace ``xp`` of the breakpoints and coefficients
+    with which the bpoly object was instantiated, an attempt will be made to
+    coerce ``x`` to the ``xp`` namespace. If the conversion succeeds, the
+    output will be an array from the ``xp`` namespace. Mixing namespaces in
+    this way is not recommended.
+
+    """
+)
+
+
+@xp_capabilities(
+    cpu_only=True, jax_jit=False,
+    exceptions=["cupy"],
+    skip_backends=[
+        ("dask.array",
+         "https://github.com/scipy/scipy/issues/24205")
+    ],
+    extra_note=_bpoly_extra_note,
+)
+class BPoly:
+    """Piecewise polynomial in the Bernstein basis.
+
+    The polynomial between ``x[i]`` and ``x[i + 1]`` is written in the
+    Bernstein polynomial basis::
+
+        S = sum(c[a, i] * b(a, k; x) for a in range(k+1)),
+
+    where ``k`` is the degree of the polynomial, and::
+
+        b(a, k; x) = binom(k, a) * t**a * (1 - t)**(k - a),
+
+    with ``t = (x - x[i]) / (x[i+1] - x[i])`` and ``binom`` is the binomial
+    coefficient.
+
+    Parameters
+    ----------
+    c : ndarray, shape (k, m, ...)
+        Polynomial coefficients, order `k` and `m` intervals
+    x : ndarray, shape (m+1,)
+        Polynomial breakpoints. Must be sorted in either increasing or
+        decreasing order.
+    extrapolate : {bool, 'periodic', None}, optional
+        If bool, determines whether to extrapolate to out-of-bounds points
+        based on first and last intervals, or to return NaNs. If 'periodic',
+        periodic extrapolation is used. If None (default), it is set to True.
+        See :ref:`tutorial-interpolate_out_of_bounds`.
+    axis : int, optional
+        Interpolation axis. Default is zero.
+
+    Attributes
+    ----------
+    x : ndarray
+        Breakpoints.
+    c : ndarray
+        Coefficients of the polynomials. They are reshaped
+        to a 3-D array with the last dimension representing
+        the trailing dimensions of the original coefficient array.
+    axis : int
+        Interpolation axis.
+
+    Methods
+    -------
+    __call__
+    extend
+    derivative
+    antiderivative
+    integrate
+    construct_fast
+    from_power_basis
+    from_derivatives
+
+    See Also
+    --------
+    PPoly : piecewise polynomials in the power basis
+
+    Notes
+    -----
+    Properties of Bernstein polynomials are well documented in the literature,
+    see for example [1]_ [2]_ [3]_.
+
+    References
+    ----------
+    .. [1] https://en.wikipedia.org/wiki/Bernstein_polynomial
+
+    .. [2] Kenneth I. Joy, Bernstein polynomials,
+       http://www.idav.ucdavis.edu/education/CAGDNotes/Bernstein-Polynomials.pdf
+
+    .. [3] E. H. Doha, A. H. Bhrawy, and M. A. Saker, Boundary Value Problems,
+           vol 2011, article ID 829546, :doi:`10.1155/2011/829543`.
+
+    Examples
+    --------
+    >>> from scipy.interpolate import BPoly
+    >>> x = [0, 1]
+    >>> c = [[1], [2], [3]]
+    >>> bp = BPoly(c, x)
+
+    This creates a 2nd order polynomial
+
+    .. math::
+
+        B(x) = 1 \\times b_{0, 2}(x) + 2 \\times b_{1, 2}(x) + 3
+               \\times b_{2, 2}(x) \\\\
+             = 1 \\times (1-x)^2 + 2 \\times 2 x (1 - x) + 3 \\times x^2
+
+    """  # noqa: E501
+
+    # generic type compatibility with scipy-stubs
+    __class_getitem__: classmethod = classmethod(GenericAlias)
+
+    def __init__(self, c, x, extrapolate=None, axis=0):
+        xp = array_namespace(c, x)
+        xp_bpoly_cls, xp_internal = _get_xp_bpoly_cls(xp)
+        if not is_numpy(xp):
+            c, x = xp_internal.asarray(c), xp_internal.asarray(x)
+        self._delegate_to = xp_bpoly_cls(c, x, extrapolate=extrapolate, axis=axis)
+        self._xp = xp
+        self._xp_internal = xp_internal
+
+    def __getstate__(self):
+        state = self.__dict__.copy()
+        state["_xp"] = state["_xp"].empty(0)
+        state.pop("_xp_internal")
+        return state
+
+    def __setstate__(self, state):
+        self._xp = array_namespace(state.pop("_xp"))
+        _, xp_internal = _get_xp_bpoly_cls(self._xp)
+        self._xp_internal = xp_internal
+        self.__dict__.update(state)
+
+    @classmethod
+    def _construct_from_xp(cls, xp_bpoly, *, xp_external):
+        self = object.__new__(cls)
+        self._delegate_to = xp_bpoly
+        self._xp = xp_external
+        self._xp_internal = array_namespace(xp_bpoly.c)
+        return self
+
+    @classmethod
+    def construct_fast(cls, c, x, extrapolate=None, axis=0):
+        """
+        Construct the piecewise polynomial without making checks.
+
+        Takes the same parameters as the constructor. Input arguments
+        ``c`` and ``x`` must be arrays of the correct shape and type. The
+        ``c`` array can only be of dtypes float and complex, and ``x``
+        array must have dtype float.
+        """
+        xp = array_namespace(c, x)
+        xp_ppoly_cls, xp_internal = _get_xp_ppoly_cls(xp)
+        c, x = xp_internal.asarray(c), xp_internal.asarray(x)
+        return cls._construct_from_xp(
+            xp_ppoly_cls.construct_fast(
+                c, x, extrapolate=extrapolate, axis=axis
+            ),
+            xp_external=xp,
+        )
+
+    @property
+    def c(self):
+        return self._xp.asarray(self._delegate_to.c)
+
+    @c.setter
+    def c(self, c):
+        self._delegate_to.c = (
+            self._xp_internal.asarray(c) if is_numpy(self._xp_internal) else c
+        )
+
+    @property
+    def x(self):
+        return self._xp.asarray(self._delegate_to.x)
+
+    @x.setter
+    def x(self, x):
+        self._delegate_to.x = (
+            self._xp_internal.asarray(x) if is_numpy(self._xp_internal) else x
+        )
+
+    @property
+    def extrapolate(self):
+        return self._delegate_to.extrapolate
+
+    @extrapolate.setter
+    def extrapolate(self, extrapolate):
+        self._delegate_to.extrapolate = extrapolate
+
+    @property
+    def axis(self):
+        return self._delegate_to.axis
+
+    @axis.setter
+    def axis(self, axis):
+        self._delegate_to.axis = axis
+
+    def extend(self, c, x):
+        """
+        Add additional breakpoints and coefficients to the polynomial.
+
+        Parameters
+        ----------
+        c : ndarray, size (k, m, ...)
+            Additional coefficients for polynomials in intervals. Note that
+            the first additional interval will be formed using one of the
+            ``self.x`` end points.
+        x : ndarray, size (m,)
+            Additional breakpoints. Must be sorted in the same order as
+            ``self.x`` and either to the right or to the left of the current
+            breakpoints.
+
+        Notes
+        -----
+        This method is not thread safe and must not be executed concurrently
+        with other methods available in this class. Doing so may cause
+        unexpected errors or numerical output mismatches.
+        """
+        c, x = self._xp_internal.asarray(c), self._xp_internal.asarray(x)
+        self._delegate_to.extend(c, x)
+
+    def __call__(self, x, nu=0, extrapolate=None):
+        """
+        Evaluate the piecewise polynomial or its derivative.
+
+        Parameters
+        ----------
+        x : array_like
+            Points to evaluate the interpolant at.
+        nu : int, optional
+            Order of derivative to evaluate. Must be non-negative.
+        extrapolate : {bool, 'periodic', None}, optional
+            If bool, determines whether to extrapolate to out-of-bounds points
+            based on first and last intervals, or to return NaNs.
+            If 'periodic', periodic extrapolation is used.
+            If None (default), use `self.extrapolate`.
+
+        Returns
+        -------
+        y : array_like
+            Interpolated values. Shape is determined by replacing
+            the interpolation axis in the original array with the shape of x.
+
+        Notes
+        -----
+        Derivatives are evaluated piecewise for each polynomial
+        segment, even if the polynomial is not differentiable at the
+        breakpoints. The polynomial intervals are considered half-open,
+        ``[a, b)``, except for the last interval which is closed
+        ``[a, b]``.
+        """
+        return self._xp.asarray(
+            self._delegate_to(
+                self._xp_internal.asarray(x), nu=nu, extrapolate=extrapolate
+            )
+        )
+
+    def derivative(self, nu=1):
+        """
+        Construct a new piecewise polynomial representing the derivative.
+
+        Parameters
+        ----------
+        nu : int, optional
+            Order of derivative to evaluate. Default is 1, i.e., compute the
+            first derivative. If negative, the antiderivative is returned.
+
+        Returns
+        -------
+        bp : BPoly
+            Piecewise polynomial of order k - nu representing the derivative of
+            this polynomial.
+
+        """
+        return self._construct_from_xp(
+            self._delegate_to.derivative(nu=nu),
+            xp_external=self._xp,
+        )
+
+    def antiderivative(self, nu=1):
+        """
+        Construct a new piecewise polynomial representing the antiderivative.
+
+        Parameters
+        ----------
+        nu : int, optional
+            Order of antiderivative to evaluate. Default is 1, i.e., compute
+            the first integral. If negative, the derivative is returned.
+
+        Returns
+        -------
+        bp : BPoly
+            Piecewise polynomial of order k + nu representing the
+            antiderivative of this polynomial.
+
+        Notes
+        -----
+        If antiderivative is computed and ``self.extrapolate='periodic'``,
+        it will be set to False for the returned instance. This is done because
+        the antiderivative is no longer periodic and its correct evaluation
+        outside of the initially given x interval is difficult.
+        """
+        return self._construct_from_xp(
+            self._delegate_to.antiderivative(nu=nu),
+            xp_external=self._xp,
+        )
+
+    def integrate(self, a, b, extrapolate=None):
+        """
+        Compute a definite integral over a piecewise polynomial.
+
+        Parameters
+        ----------
+        a : float
+            Lower integration bound
+        b : float
+            Upper integration bound
+        extrapolate : {bool, 'periodic', None}, optional
+            Whether to extrapolate to out-of-bounds points based on first
+            and last intervals, or to return NaNs. If 'periodic', periodic
+            extrapolation is used. If None (default), use `self.extrapolate`.
+
+        Returns
+        -------
+        array_like
+            Definite integral of the piecewise polynomial over [a, b]
+
+        """
+        return self._xp.asarray(
+            self._delegate_to.integrate(a, b, extrapolate=extrapolate)
+        )
+
+    @classmethod
+    def from_power_basis(cls, pp, extrapolate=None):
+        """
+        Construct a piecewise polynomial in Bernstein basis
+        from a power basis polynomial.
+
+        Parameters
+        ----------
+        pp : PPoly
+            A piecewise polynomial in the power basis
+        extrapolate : bool or 'periodic', optional
+            If bool, determines whether to extrapolate to out-of-bounds points
+            based on first and last intervals, or to return NaNs.
+            If 'periodic', periodic extrapolation is used. Default is True.
+        """
+        if not isinstance(pp, PPoly):
+            raise TypeError(f".from_power_basis only accepts PPoly instances. "
+                            f"Got {type(pp)} instead.")
+        xp = pp._xp
+        xp_cls, _ = _get_xp_bpoly_cls(xp)
+        bp = xp_cls.from_power_basis(pp._delegate_to, extrapolate=extrapolate)
+        return cls._construct_from_xp(bp, xp_external=xp)
+
+    @classmethod
+    def from_derivatives(cls, xi, yi, orders=None, extrapolate=None):
+        """Construct a piecewise polynomial in the Bernstein basis,
+        compatible with the specified values and derivatives at breakpoints.
+
+        Parameters
+        ----------
+        xi : array_like
+            sorted 1-D array of x-coordinates
+        yi : array_like or list of array_likes
+            ``yi[i][j]`` is the ``j``\\ th derivative known at ``xi[i]``
+        orders : None or int or array_like of ints. Default: None.
+            Specifies the degree of local polynomials. If not None, some
+            derivatives are ignored.
+        extrapolate : bool or 'periodic', optional
+            If bool, determines whether to extrapolate to out-of-bounds points
+            based on first and last intervals, or to return NaNs.
+            If 'periodic', periodic extrapolation is used. Default is True.
+
+        Notes
+        -----
+        If ``k`` derivatives are specified at a breakpoint ``x``, the
+        constructed polynomial is exactly ``k`` times continuously
+        differentiable at ``x``, unless the ``order`` is provided explicitly.
+        In the latter case, the smoothness of the polynomial at
+        the breakpoint is controlled by the ``order``.
+
+        Deduces the number of derivatives to match at each end
+        from ``order`` and the number of derivatives available. If
+        possible it uses the same number of derivatives from
+        each end; if the number is odd it tries to take the
+        extra one from y2. In any case if not enough derivatives
+        are available at one end or another it draws enough to
+        make up the total from the other end.
+
+        If the order is too high and not enough derivatives are available,
+        an exception is raised.
+
+        Examples
+        --------
+
+        >>> from scipy.interpolate import BPoly
+        >>> BPoly.from_derivatives([0, 1], [[1, 2], [3, 4]])
+
+        Creates a polynomial `f(x)` of degree 3, defined on ``[0, 1]``
+        such that `f(0) = 1, df/dx(0) = 2, f(1) = 3, df/dx(1) = 4`
+
+        >>> BPoly.from_derivatives([0, 1, 2], [[0, 1], [0], [2]])
+
+        Creates a piecewise polynomial `f(x)`, such that
+        `f(0) = f(1) = 0`, `f(2) = 2`, and `df/dx(0) = 1`.
+        Based on the number of derivatives provided, the order of the
+        local polynomials is 2 on ``[0, 1]`` and 1 on ``[1, 2]``.
+        Notice that no restriction is imposed on the derivatives at
+        ``x = 1`` and ``x = 2``.
+
+        Indeed, the explicit form of the polynomial is::
+
+            f(x) = | x * (1 - x),  0 <= x < 1
+                   | 2 * (x - 1),  1 <= x <= 2
+
+        So that f'(1-0) = -1 and f'(1+0) = 2
+
+        """
+        if isinstance(yi, (list, tuple)):
+            # yi is documented as accepting arrays or lists of
+            # arrays.  The following line with star unpacking will not
+            # work for array ``yi`` for some backends because some are
+            # stricting than others about whether arrays can be iterated over.
+            xp = array_namespace(xi, *yi)
+        else:
+            xp = array_namespace(xi, yi)
+        xp_cls, xp_internal = _get_xp_bpoly_cls(xp)
+        xi = xp_internal.asarray(xi)
+        if isinstance(yi, (list, tuple)):
+            # If yi is a ragged list or tuple of arrays, then need to apply
+            # xp_internal.asarray separately over each element.
+            yi = list(map(xp_internal.asarray, yi))
+        else:
+            yi = xp_internal.asarray(yi)
+
+        bp = xp_cls.from_derivatives(
+            xi, yi, orders=orders, extrapolate=extrapolate
+        )
+        return cls._construct_from_xp(bp, xp_external=xp)
+
+    @staticmethod
+    def _construct_from_derivatives(xa, xb, ya, yb):
+        r"""Compute the coefficients of a polynomial in the Bernstein basis
+        given the values and derivatives at the edges.
+
+        Return the coefficients of a polynomial in the Bernstein basis
+        defined on ``[xa, xb]`` and having the values and derivatives at the
+        endpoints `xa` and `xb` as specified by `ya` and `yb`.
+        The polynomial constructed is of the minimal possible degree, i.e.,
+        if the lengths of `ya` and `yb` are `na` and `nb`, the degree
+        of the polynomial is ``na + nb - 1``.
+
+        Parameters
+        ----------
+        xa : float
+            Left-hand end point of the interval
+        xb : float
+            Right-hand end point of the interval
+        ya : array_like
+            Derivatives at `xa`. ``ya[0]`` is the value of the function, and
+            ``ya[i]`` for ``i > 0`` is the value of the ``i``\ th derivative.
+        yb : array_like
+            Derivatives at `xb`.
+
+        Returns
+        -------
+        array
+            coefficient array of a polynomial having specified derivatives
+
+        Notes
+        -----
+        This uses several facts from life of Bernstein basis functions.
+        First of all,
+
+            .. math:: b'_{a, n} = n (b_{a-1, n-1} - b_{a, n-1})
+
+        If B(x) is a linear combination of the form
+
+            .. math:: B(x) = \sum_{a=0}^{n} c_a b_{a, n},
+
+        then :math: B'(x) = n \sum_{a=0}^{n-1} (c_{a+1} - c_{a}) b_{a, n-1}.
+        Iterating the latter one, one finds for the q-th derivative
+
+            .. math:: B^{q}(x) = n!/(n-q)! \sum_{a=0}^{n-q} Q_a b_{a, n-q},
+
+        with
+
+          .. math:: Q_a = \sum_{j=0}^{q} (-)^{j+q} comb(q, j) c_{j+a}
+
+        This way, only `a=0` contributes to :math: `B^{q}(x = xa)`, and
+        `c_q` are found one by one by iterating `q = 0, ..., na`.
+
+        At ``x = xb`` it's the same with ``a = n - q``.
+
+        """
+        xp = array_namespace(ya, yb)
+        xp_cls, xp_internal = _get_xp_bpoly_cls(xp)
+        ya, yb = xp_internal.asarray(ya), xp_internal.asarray(yb)
+        return xp.asarray(xp_cls._construct_from_derivatives(xa, xb, ya, yb))
+
+    @staticmethod
+    def _raise_degree(c, d):
+        r"""Raise a degree of a polynomial in the Bernstein basis.
+
+        Given the coefficients of a polynomial degree `k`, return (the
+        coefficients of) the equivalent polynomial of degree `k+d`.
+
+        Parameters
+        ----------
+        c : array_like
+            coefficient array, 1-D
+        d : int
+
+        Returns
+        -------
+        array
+            coefficient array, 1-D array of length `c.shape[0] + d`
+
+        Notes
+        -----
+        This uses the fact that a Bernstein polynomial `b_{a, k}` can be
+        identically represented as a linear combination of polynomials of
+        a higher degree `k+d`:
+
+            .. math:: b_{a, k} = comb(k, a) \sum_{j=0}^{d} b_{a+j, k+d} \
+                                 comb(d, j) / comb(k+d, a+j)
+
+        """
+        xp = array_namespace(c)
+        xp_cls, xp_internal = _get_xp_bpoly_cls(xp)
+        return xp.asarray(xp_cls._raise_degree(xp_internal.asarray(c), d))
+
+class NdPPoly:
+    """
+    Piecewise tensor product polynomial.
+
+    The value at point ``xp = (x', y', z', ...)`` is evaluated by first
+    computing the interval indices `i` such that::
+
+        x[0][i[0]] <= x' < x[0][i[0]+1]
+        x[1][i[1]] <= y' < x[1][i[1]+1]
+        ...
+
+    and then computing::
+
+        S = sum(c[k0-m0-1,...,kn-mn-1,i[0],...,i[n]]
+                * (xp[0] - x[0][i[0]])**m0
+                * ...
+                * (xp[n] - x[n][i[n]])**mn
+                for m0 in range(k[0]+1)
+                ...
+                for mn in range(k[n]+1))
+
+    where ``k[j]`` is the degree of the polynomial in dimension j. This
+    representation is the piecewise multivariate power basis.
+
+    Parameters
+    ----------
+    c : ndarray, shape (k0, ..., kn, m0, ..., mn, ...)
+        Polynomial coefficients, with polynomial order `kj` and
+        `mj+1` intervals for each dimension `j`.
+    x : ndim-tuple of ndarrays, shapes (mj+1,)
+        Polynomial breakpoints for each dimension. These must be
+        sorted in increasing order.
+    extrapolate : bool, optional
+        Whether to extrapolate to out-of-bounds points based on first
+        and last intervals, or to return NaNs. Default: True.
+
+    Attributes
+    ----------
+    x : tuple of ndarrays
+        Breakpoints.
+    c : ndarray
+        Coefficients of the polynomials.
+
+    Methods
+    -------
+    __call__
+    derivative
+    antiderivative
+    integrate
+    integrate_1d
+    construct_fast
+
+    See Also
+    --------
+    PPoly : piecewise polynomials in 1D
+
+    Notes
+    -----
+    High-order polynomials in the power basis can be numerically
+    unstable.
+
+    """
+    
+    # generic type compatibility with scipy-stubs
+    __class_getitem__: classmethod = classmethod(GenericAlias)
+
+    def __init__(self, c, x, extrapolate=None):
+        self.x = tuple(np.ascontiguousarray(v, dtype=np.float64) for v in x)
+        self.c = np.asarray(c)
+        if extrapolate is None:
+            extrapolate = True
+        self.extrapolate = bool(extrapolate)
+
+        ndim = len(self.x)
+        if any(v.ndim != 1 for v in self.x):
+            raise ValueError("x arrays must all be 1-dimensional")
+        if any(v.size < 2 for v in self.x):
+            raise ValueError("x arrays must all contain at least 2 points")
+        if c.ndim < 2*ndim:
+            raise ValueError("c must have at least 2*len(x) dimensions")
+        if any(np.any(v[1:] - v[:-1] < 0) for v in self.x):
+            raise ValueError("x-coordinates are not in increasing order")
+        if any(a != b.size - 1 for a, b in zip(c.shape[ndim:2*ndim], self.x)):
+            raise ValueError("x and c do not agree on the number of intervals")
+
+        dtype = self._get_dtype(self.c.dtype)
+        self.c = np.ascontiguousarray(self.c, dtype=dtype)
+
+    @classmethod
+    def construct_fast(cls, c, x, extrapolate=None):
+        """
+        Construct the piecewise polynomial without making checks.
+
+        Takes the same parameters as the constructor. Input arguments
+        ``c`` and ``x`` must be arrays of the correct shape and type.  The
+        ``c`` array can only be of dtypes float and complex, and ``x``
+        array must have dtype float.
+
+        """
+        self = object.__new__(cls)
+        self.c = c
+        self.x = x
+        if extrapolate is None:
+            extrapolate = True
+        self.extrapolate = extrapolate
+        return self
+
+    def _get_dtype(self, dtype):
+        if np.issubdtype(dtype, np.complexfloating) \
+               or np.issubdtype(self.c.dtype, np.complexfloating):
+            return np.complex128
+        else:
+            return np.float64
+
+    def _ensure_c_contiguous(self):
+        if not self.c.flags.c_contiguous:
+            self.c = self.c.copy()
+        if not isinstance(self.x, tuple):
+            self.x = tuple(self.x)
+
+    def __call__(self, x, nu=None, extrapolate=None):
+        """
+        Evaluate the piecewise polynomial or its derivative
+
+        Parameters
+        ----------
+        x : array-like
+            Points to evaluate the interpolant at.
+        nu : tuple, optional
+            Orders of derivatives to evaluate. Each must be non-negative.
+        extrapolate : bool, optional
+            Whether to extrapolate to out-of-bounds points based on first
+            and last intervals, or to return NaNs.
+
+        Returns
+        -------
+        y : array-like
+            Interpolated values. Shape is determined by replacing
+            the interpolation axis in the original array with the shape of x.
+
+        Notes
+        -----
+        Derivatives are evaluated piecewise for each polynomial
+        segment, even if the polynomial is not differentiable at the
+        breakpoints. The polynomial intervals are considered half-open,
+        ``[a, b)``, except for the last interval which is closed
+        ``[a, b]``.
+
+        """
+        if extrapolate is None:
+            extrapolate = self.extrapolate
+        else:
+            extrapolate = bool(extrapolate)
+
+        ndim = len(self.x)
+
+        x = _ndim_coords_from_arrays(x)
+        x_shape = x.shape
+        x = np.ascontiguousarray(x.reshape(-1, x.shape[-1]), dtype=np.float64)
+
+        if nu is None:
+            nu = np.zeros((ndim,), dtype=np.intc)
+        else:
+            nu = np.asarray(nu, dtype=np.intc)
+            if nu.ndim != 1 or nu.shape[0] != ndim:
+                raise ValueError("invalid number of derivative orders nu")
+
+        dim1 = prod(self.c.shape[:ndim])
+        dim2 = prod(self.c.shape[ndim:2*ndim])
+        dim3 = prod(self.c.shape[2*ndim:])
+        ks = np.array(self.c.shape[:ndim], dtype=np.intc)
+
+        out = np.empty((x.shape[0], dim3), dtype=self.c.dtype)
+        self._ensure_c_contiguous()
+
+        _ppoly.evaluate_nd(self.c.reshape(dim1, dim2, dim3),
+                           self.x,
+                           ks,
+                           x,
+                           nu,
+                           bool(extrapolate),
+                           out)
+
+        return out.reshape(x_shape[:-1] + self.c.shape[2*ndim:])
+
+    def _derivative_inplace(self, nu, axis):
+        """
+        Compute 1-D derivative along a selected dimension in-place
+        May result to non-contiguous c array.
+        """
+        if nu < 0:
+            return self._antiderivative_inplace(-nu, axis)
+
+        ndim = len(self.x)
+        axis = axis % ndim
+
+        # reduce order
+        if nu == 0:
+            # noop
+            return
+        else:
+            sl = [slice(None)]*ndim
+            sl[axis] = slice(None, -nu, None)
+            c2 = self.c[tuple(sl)]
+
+        if c2.shape[axis] == 0:
+            # derivative of order 0 is zero
+            shp = list(c2.shape)
+            shp[axis] = 1
+            c2 = np.zeros(shp, dtype=c2.dtype)
+
+        # multiply by the correct rising factorials
+        factor = spec.poch(np.arange(c2.shape[axis], 0, -1), nu)
+        sl = [None]*c2.ndim
+        sl[axis] = slice(None)
+        c2 *= factor[tuple(sl)]
+
+        self.c = c2
+
+    def _antiderivative_inplace(self, nu, axis):
+        """
+        Compute 1-D antiderivative along a selected dimension
+        May result to non-contiguous c array.
+        """
+        if nu <= 0:
+            return self._derivative_inplace(-nu, axis)
+
+        ndim = len(self.x)
+        axis = axis % ndim
+
+        perm = list(range(ndim))
+        perm[0], perm[axis] = perm[axis], perm[0]
+        perm = perm + list(range(ndim, self.c.ndim))
+
+        c = self.c.transpose(perm)
+
+        c2 = np.zeros((c.shape[0] + nu,) + c.shape[1:],
+                     dtype=c.dtype)
+        c2[:-nu] = c
+
+        # divide by the correct rising factorials
+        factor = spec.poch(np.arange(c.shape[0], 0, -1), nu)
+        c2[:-nu] /= factor[(slice(None),) + (None,)*(c.ndim-1)]
+
+        # fix continuity of added degrees of freedom
+        perm2 = list(range(c2.ndim))
+        perm2[1], perm2[ndim+axis] = perm2[ndim+axis], perm2[1]
+
+        c2 = c2.transpose(perm2)
+        c2 = c2.copy()
+        _ppoly.fix_continuity(c2.reshape(c2.shape[0], c2.shape[1], -1),
+                              self.x[axis], nu-1)
+
+        c2 = c2.transpose(perm2)
+        c2 = c2.transpose(perm)
+
+        # Done
+        self.c = c2
+
+    def derivative(self, nu):
+        """
+        Construct a new piecewise polynomial representing the derivative.
+
+        Parameters
+        ----------
+        nu : ndim-tuple of int
+            Order of derivatives to evaluate for each dimension.
+            If negative, the antiderivative is returned.
+
+        Returns
+        -------
+        pp : NdPPoly
+            Piecewise polynomial of orders (k[0] - nu[0], ..., k[n] - nu[n])
+            representing the derivative of this polynomial.
+
+        Notes
+        -----
+        Derivatives are evaluated piecewise for each polynomial
+        segment, even if the polynomial is not differentiable at the
+        breakpoints. The polynomial intervals in each dimension are
+        considered half-open, ``[a, b)``, except for the last interval
+        which is closed ``[a, b]``.
+
+        """
+        p = self.construct_fast(self.c.copy(), self.x, self.extrapolate)
+
+        for axis, n in enumerate(nu):
+            p._derivative_inplace(n, axis)
+
+        p._ensure_c_contiguous()
+        return p
+
+    def antiderivative(self, nu):
+        """
+        Construct a new piecewise polynomial representing the antiderivative.
+
+        Antiderivative is also the indefinite integral of the function,
+        and derivative is its inverse operation.
+
+        Parameters
+        ----------
+        nu : ndim-tuple of int
+            Order of derivatives to evaluate for each dimension.
+            If negative, the derivative is returned.
+
+        Returns
+        -------
+        pp : PPoly
+            Piecewise polynomial of order k2 = k + n representing
+            the antiderivative of this polynomial.
+
+        Notes
+        -----
+        The antiderivative returned by this function is continuous and
+        continuously differentiable to order n-1, up to floating point
+        rounding error.
+
+        """
+        p = self.construct_fast(self.c.copy(), self.x, self.extrapolate)
+
+        for axis, n in enumerate(nu):
+            p._antiderivative_inplace(n, axis)
+
+        p._ensure_c_contiguous()
+        return p
+
+    def integrate_1d(self, a, b, axis, extrapolate=None):
+        r"""
+        Compute NdPPoly representation for one dimensional definite integral.
+
+        The result is a piecewise polynomial representing the integral:
+
+        .. math::
+
+           p(y, z, ...) = \int_a^b dx\, p(x, y, z, ...)
+
+        where the dimension integrated over is specified with the
+        `axis` parameter.
+
+        Parameters
+        ----------
+        a, b : float
+            Lower and upper bound for integration.
+        axis : int
+            Dimension over which to compute the 1-D integrals
+        extrapolate : bool, optional
+            Whether to extrapolate to out-of-bounds points based on first
+            and last intervals, or to return NaNs.
+
+        Returns
+        -------
+        ig : NdPPoly or array-like
+            Definite integral of the piecewise polynomial over [a, b].
+            If the polynomial was 1D, an array is returned,
+            otherwise, an NdPPoly object.
+
+        """
+        if extrapolate is None:
+            extrapolate = self.extrapolate
+        else:
+            extrapolate = bool(extrapolate)
+
+        ndim = len(self.x)
+        axis = int(axis) % ndim
+
+        # reuse 1-D integration routines
+        c = self.c
+        swap = list(range(c.ndim))
+        swap.insert(0, swap[axis])
+        del swap[axis + 1]
+        swap.insert(1, swap[ndim + axis])
+        del swap[ndim + axis + 1]
+
+        c = c.transpose(swap)
+        p = PPoly.construct_fast(c.reshape(c.shape[0], c.shape[1], -1),
+                                 self.x[axis],
+                                 extrapolate=extrapolate)
+        out = p.integrate(a, b, extrapolate=extrapolate)
+
+        # Construct result
+        if ndim == 1:
+            return out.reshape(c.shape[2:])
+        else:
+            c = out.reshape(c.shape[2:])
+            x = self.x[:axis] + self.x[axis+1:]
+            return self.construct_fast(c, x, extrapolate=extrapolate)
+
+    def integrate(self, ranges, extrapolate=None):
+        """
+        Compute a definite integral over a piecewise polynomial.
+
+        Parameters
+        ----------
+        ranges : ndim-tuple of 2-tuples float
+            Sequence of lower and upper bounds for each dimension,
+            ``[(a[0], b[0]), ..., (a[ndim-1], b[ndim-1])]``
+        extrapolate : bool, optional
+            Whether to extrapolate to out-of-bounds points based on first
+            and last intervals, or to return NaNs.
+
+        Returns
+        -------
+        ig : array_like
+            Definite integral of the piecewise polynomial over
+            [a[0], b[0]] x ... x [a[ndim-1], b[ndim-1]]
+
+        """
+
+        ndim = len(self.x)
+
+        if extrapolate is None:
+            extrapolate = self.extrapolate
+        else:
+            extrapolate = bool(extrapolate)
+
+        if not hasattr(ranges, '__len__') or len(ranges) != ndim:
+            raise ValueError("Range not a sequence of correct length")
+
+        self._ensure_c_contiguous()
+
+        # Reuse 1D integration routine
+        c = self.c
+        for n, (a, b) in enumerate(ranges):
+            swap = list(range(c.ndim))
+            swap.insert(1, swap[ndim - n])
+            del swap[ndim - n + 1]
+
+            c = c.transpose(swap)
+
+            p = PPoly.construct_fast(c, self.x[n], extrapolate=extrapolate)
+            out = p.integrate(a, b, extrapolate=extrapolate)
+            c = out.reshape(c.shape[2:])
+
+        return c
diff --git a/.venv/lib/python3.12/site-packages/scipy/interpolate/_ndbspline.py b/.venv/lib/python3.12/site-packages/scipy/interpolate/_ndbspline.py
new file mode 100644
index 0000000000000000000000000000000000000000..80413fb6012279b792e551d0beacc39e8061bee4
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/interpolate/_ndbspline.py
@@ -0,0 +1,518 @@
+import itertools
+import functools
+import operator
+import numpy as np
+
+from math import prod
+from types import GenericAlias
+
+from . import _dierckx  # type: ignore[attr-defined]
+
+import scipy.sparse.linalg as ssl
+from scipy.sparse import csr_array
+from scipy._lib._array_api import array_namespace, xp_capabilities
+
+from ._bsplines import _not_a_knot, BSpline
+
+__all__ = ["NdBSpline"]
+
+
+def _get_dtype(dtype):
+    """Return np.complex128 for complex dtypes, np.float64 otherwise."""
+    if np.issubdtype(dtype, np.complexfloating):
+        return np.complex128
+    else:
+        return np.float64
+
+
+@xp_capabilities(
+    cpu_only=True, jax_jit=False,
+    skip_backends=[
+        ("dask.array",
+         "https://github.com/data-apis/array-api-extra/issues/488")
+    ]
+)
+class NdBSpline:
+    """Tensor product spline object.
+
+    The value at point ``xp = (x1, x2, ..., xN)`` is evaluated as a linear
+    combination of products of one-dimensional b-splines in each of the ``N``
+    dimensions::
+
+       c[i1, i2, ..., iN] * B(x1; i1, t1) * B(x2; i2, t2) * ... * B(xN; iN, tN)
+
+
+    Here ``B(x; i, t)`` is the ``i``-th b-spline defined by the knot vector
+    ``t`` evaluated at ``x``.
+
+    Parameters
+    ----------
+    t : tuple of 1D ndarrays
+        knot vectors in directions 1, 2, ... N,
+        ``len(t[i]) == n[i] + k + 1``
+    c : ndarray, shape (n1, n2, ..., nN, ...)
+        b-spline coefficients
+    k : int or length-d tuple of integers
+        spline degrees.
+        A single integer is interpreted as having this degree for
+        all dimensions.
+    extrapolate : bool, optional
+        Whether to extrapolate out-of-bounds inputs, or return `nan`.
+        Default is to extrapolate.
+
+    Attributes
+    ----------
+    t : tuple of ndarrays
+        Knots vectors.
+    c : ndarray
+        Coefficients of the tensor-product spline.
+    k : tuple of integers
+        Degrees for each dimension.
+    extrapolate : bool, optional
+        Whether to extrapolate or return nans for out-of-bounds inputs.
+        Defaults to true.
+
+    Methods
+    -------
+    __call__
+    derivative
+    design_matrix
+
+    See Also
+    --------
+    BSpline : a one-dimensional B-spline object
+    NdPPoly : an N-dimensional piecewise tensor product polynomial
+
+    """
+
+    # generic type compatibility with scipy-stubs
+    __class_getitem__: classmethod = classmethod(GenericAlias)
+
+    def __init__(self, t, c, k, *, extrapolate=None):
+        self._k, self._indices_k1d, (self._t, self._len_t) = _preprocess_inputs(k, t)
+
+        self._asarray = array_namespace(c, *t).asarray
+
+        if extrapolate is None:
+            extrapolate = True
+        self.extrapolate = bool(extrapolate)
+
+        self._c = np.asarray(c)
+
+        ndim = self._t.shape[0]   # == len(self.t)
+        if self._c.ndim < ndim:
+            raise ValueError(f"Coefficients must be at least {ndim}-dimensional.")
+
+        for d in range(ndim):
+            td = self.t[d]
+            kd = self.k[d]
+            n = td.shape[0] - kd - 1
+
+            if self._c.shape[d] != n:
+                raise ValueError(f"Knots, coefficients and degree in dimension"
+                                 f" {d} are inconsistent:"
+                                 f" got {self._c.shape[d]} coefficients for"
+                                 f" {len(td)} knots, need at least {n} for"
+                                 f" k={k}.")
+
+        dt = _get_dtype(self._c.dtype)
+        self._c = np.ascontiguousarray(self._c, dtype=dt)
+
+    @property
+    def k(self):
+        return tuple(self._k)
+
+    @property
+    def t(self):
+        # repack the knots into a tuple
+        return tuple(
+            self._asarray(self._t[d, :self._len_t[d]]) for d in range(self._t.shape[0])
+        )
+
+    @property
+    def c(self):
+        return self._asarray(self._c)
+
+    def __call__(self, xi, *, nu=None, extrapolate=None):
+        """Evaluate the tensor product b-spline at ``xi``.
+
+        Parameters
+        ----------
+        xi : array_like, shape(..., ndim)
+            The coordinates to evaluate the interpolator at.
+            This can be a list or tuple of ndim-dimensional points
+            or an array with the shape (num_points, ndim).
+        nu : sequence of length ``ndim``, optional
+            Orders of derivatives to evaluate. Each must be non-negative.
+            Defaults to the zeroth derivivative.
+        extrapolate : bool, optional
+            Whether to exrapolate based on first and last intervals in each
+            dimension, or return `nan`. Default is to ``self.extrapolate``.
+
+        Returns
+        -------
+        values : ndarray, shape ``xi.shape[:-1] + self.c.shape[ndim:]``
+            Interpolated values at ``xi``
+        """
+        ndim = self._t.shape[0]  # == len(self.t)
+
+        if extrapolate is None:
+            extrapolate = self.extrapolate
+        extrapolate = bool(extrapolate)
+
+        if nu is None:
+            nu = np.zeros((ndim,), dtype=np.int64)
+        else:
+            nu = np.asarray(nu, dtype=np.int64)
+            if nu.ndim != 1 or nu.shape[0] != ndim:
+                raise ValueError(
+                    f"invalid number of derivative orders {nu = } for "
+                    f"ndim = {len(self.t)}.")
+            if any(nu < 0):
+                raise ValueError(f"derivatives must be positive, got {nu = }")
+
+        # prepare xi : shape (..., m1, ..., md) -> (1, m1, ..., md)
+        xi = np.asarray(xi, dtype=float)
+        xi_shape = xi.shape
+        xi = xi.reshape(-1, xi_shape[-1])
+        xi = np.ascontiguousarray(xi)
+
+        if xi_shape[-1] != ndim:
+            raise ValueError(f"Shapes: xi.shape={xi_shape} and ndim={ndim}")
+
+        # complex -> double
+        was_complex = self._c.dtype.kind == 'c'
+        cc = self._c
+        if was_complex and self._c.ndim == ndim:
+            # make sure that core dimensions are intact, and complex->float
+            # size doubling only adds a trailing dimension
+            cc = self._c[..., None]
+        cc = cc.view(float)
+
+        # prepare the coefficients: flatten the trailing dimensions
+        c1 = cc.reshape(cc.shape[:ndim] + (-1,))
+        c1r = c1.ravel()
+
+        # replacement for np.ravel_multi_index for indexing of `c1`:
+        _strides_c1 = np.asarray([s // c1.dtype.itemsize
+                                  for s in c1.strides], dtype=np.int64)
+
+        num_c_tr = c1.shape[-1]  # # of trailing coefficients
+        out = _dierckx.evaluate_ndbspline(xi,
+                                 self._t,
+                                 self._len_t,
+                                 self._k,
+                                 nu,
+                                 extrapolate,
+                                 c1r,
+                                 num_c_tr,
+                                 _strides_c1,
+                                 self._indices_k1d,
+        )
+        out = out.view(self._c.dtype)
+        out = out.reshape(xi_shape[:-1] + self._c.shape[ndim:])
+        return self._asarray(out)
+
+    @classmethod
+    def design_matrix(cls, xvals, t, k, extrapolate=True):
+        """Construct the design matrix as a CSR format sparse array.
+
+        Parameters
+        ----------
+        xvals :  ndarray, shape(npts, ndim)
+            Data points. ``xvals[j, :]`` gives the ``j``-th data point as an
+            ``ndim``-dimensional array.
+        t : tuple of 1D ndarrays, length-ndim
+            Knot vectors in directions 1, 2, ... ndim,
+        k : int
+            B-spline degree.
+        extrapolate : bool, optional
+            Whether to extrapolate out-of-bounds values of raise a `ValueError`
+
+        Returns
+        -------
+        design_matrix : a CSR array
+            Each row of the design matrix corresponds to a value in `xvals` and
+            contains values of b-spline basis elements which are non-zero
+            at this value.
+
+        """
+        xvals = np.asarray(xvals, dtype=float)
+        ndim = xvals.shape[-1]
+        if len(t) != ndim:
+            raise ValueError(
+                f"Data and knots are inconsistent: len(t) = {len(t)} for "
+                f" {ndim = }."
+            )
+
+        # tabulate the flat indices for iterating over the (k+1)**ndim subarray
+        k, _indices_k1d, (_t, len_t) = _preprocess_inputs(k, t)
+
+        # Precompute the shape and strides of the 'coefficients array'.
+        # This would have been the NdBSpline coefficients; in the present context
+        # this is a helper to compute the indices into the colocation matrix.
+        c_shape = tuple(len_t[d] - k[d] - 1 for d in range(ndim))
+
+        # The strides of the coeffs array: the computation is equivalent to
+        # >>> cstrides = [s // 8 for s in np.empty(c_shape).strides]
+        cs = c_shape[1:] + (1,)
+        cstrides = np.cumprod(cs[::-1], dtype=np.int64)[::-1].copy()
+
+        # heavy lifting happens here
+        data, indices, indptr = _dierckx._coloc_nd(xvals,
+                _t, len_t, k, _indices_k1d, cstrides)
+
+        return csr_array((data, indices, indptr))
+
+    def _bspline_derivative_along_axis(self, c, t, k, axis, nu=1):
+        # Move the selected axis to front
+        c = np.moveaxis(c, axis, 0)
+        n = c.shape[0]
+        trailing_shape = c.shape[1:]
+        c_flat = c.reshape(n, -1)
+
+        new_c_list = []
+        new_t = None
+
+        for i in range(c_flat.shape[1]):
+            if k >= nu:
+                b = BSpline.construct_fast(t, c_flat[:, i], k)
+                db = b.derivative(nu)
+                # truncate coefficients to match new knot/degree size
+                db.c = db.c[:len(db.t) - db.k - 1]
+            else:
+                db = BSpline.construct_fast(t, np.zeros(len(t) - 1), 0)
+
+            if new_t is None:
+                new_t = db.t
+
+            new_c_list.append(db.c)
+
+        new_c = np.stack(new_c_list, axis=1).reshape(
+            (len(new_c_list[0]),) + trailing_shape)
+        new_c = np.moveaxis(new_c, 0, axis)
+
+        return new_c, new_t
+
+    def derivative(self, nu):
+        """
+        Construct a new NdBSpline representing the partial derivative.
+
+        Parameters
+        ----------
+        nu : array_like of shape (ndim,)
+            Orders of the partial derivatives to compute along each dimension.
+
+        Returns
+        -------
+        NdBSpline
+            A new NdBSpline representing the partial derivative of the original spline.
+
+        """
+        nu_arr = np.asarray(nu, dtype=np.int64)
+        ndim = len(self.t)
+
+        if nu_arr.ndim != 1 or nu_arr.shape[0] != ndim:
+            raise ValueError(
+                f"invalid number of derivative orders {nu = } for "
+                f"ndim = {len(self.t)}.")
+
+        if any(nu_arr < 0):
+            raise ValueError(f"derivative orders must be positive, got {nu = }")
+
+        # extract t and c as numpy arrays
+        t_new = [self._t[d, :self._len_t[d]] for d in range(self._t.shape[0])]
+        k_new = list(self.k)
+        c_new = self._c.copy()
+
+        for axis, n in enumerate(nu_arr):
+            if n == 0:
+                continue
+
+            c_new, t_new[axis] = self._bspline_derivative_along_axis(
+                c_new, t_new[axis], k_new[axis], axis, nu=n
+            )
+            k_new[axis] = max(k_new[axis] - n, 0)
+
+        return NdBSpline(tuple(self._asarray(t) for t in t_new),
+                         self._asarray(c_new),
+                         tuple(k_new),
+                         extrapolate=self.extrapolate
+        )
+
+def _preprocess_inputs(k, t_tpl):
+    """Helpers: validate and preprocess NdBSpline inputs.
+
+       Parameters
+       ----------
+       k : int or tuple
+          Spline orders
+       t_tpl : tuple or array-likes
+          Knots.
+    """
+    # 1. Make sure t_tpl is a tuple
+    if not isinstance(t_tpl, tuple):
+        raise ValueError(f"Expect `t` to be a tuple of array-likes. "
+                         f"Got {t_tpl} instead."
+        )
+
+    # 2. Make ``k`` a tuple of integers
+    ndim = len(t_tpl)
+    try:
+        len(k)
+    except TypeError:
+        # make k a tuple
+        k = (k,)*ndim
+
+    k = np.asarray([operator.index(ki) for ki in k], dtype=np.int64)
+
+    if len(k) != ndim:
+        raise ValueError(f"len(t) = {len(t_tpl)} != {len(k) = }.")
+
+    # 3. Validate inputs
+    ndim = len(t_tpl)
+    for d in range(ndim):
+        td = np.asarray(t_tpl[d])
+        kd = k[d]
+        n = td.shape[0] - kd - 1
+        if kd < 0:
+            raise ValueError(f"Spline degree in dimension {d} cannot be"
+                             f" negative.")
+        if td.ndim != 1:
+            raise ValueError(f"Knot vector in dimension {d} must be"
+                             f" one-dimensional.")
+        if n < kd + 1:
+            raise ValueError(f"Need at least {2*kd + 2} knots for degree"
+                             f" {kd} in dimension {d}.")
+        if (np.diff(td) < 0).any():
+            raise ValueError(f"Knots in dimension {d} must be in a"
+                             f" non-decreasing order.")
+        if len(np.unique(td[kd:n + 1])) < 2:
+            raise ValueError(f"Need at least two internal knots in"
+                             f" dimension {d}.")
+        if not np.isfinite(td).all():
+            raise ValueError(f"Knots in dimension {d} should not have"
+                             f" nans or infs.")
+
+    # 4. tabulate the flat indices for iterating over the (k+1)**ndim subarray
+    # non-zero b-spline elements
+    shape = tuple(kd + 1 for kd in k)
+    indices = np.unravel_index(np.arange(prod(shape)), shape)
+    _indices_k1d = np.asarray(indices, dtype=np.int64).T.copy()
+
+    # 5. pack the knots into a single array:
+    #    ([1, 2, 3, 4], [5, 6], (7, 8, 9)) -->
+    #    array([[1, 2, 3, 4],
+    #           [5, 6, nan, nan],
+    #           [7, 8, 9, nan]])
+    t_tpl = [np.asarray(t) for t in t_tpl]
+    ndim = len(t_tpl)
+    len_t = [len(ti) for ti in t_tpl]
+    _t = np.empty((ndim, max(len_t)), dtype=float)
+    _t.fill(np.nan)
+    for d in range(ndim):
+        _t[d, :len(t_tpl[d])] = t_tpl[d]
+    len_t = np.asarray(len_t, dtype=np.int64)
+
+    return k, _indices_k1d, (_t, len_t)
+
+
+def _iter_solve(a, b, solver=ssl.gcrotmk, **solver_args):
+    # work around iterative solvers not accepting multiple r.h.s.
+
+    # also work around a.dtype == float64 and b.dtype == complex128
+    # cf https://github.com/scipy/scipy/issues/19644
+    if np.issubdtype(b.dtype, np.complexfloating):
+        real = _iter_solve(a, b.real, solver, **solver_args)
+        imag = _iter_solve(a, b.imag, solver, **solver_args)
+        return real + 1j*imag
+
+    if b.ndim == 2 and b.shape[1] !=1:
+        res = np.empty_like(b)
+        for j in range(b.shape[1]):
+            res[:, j], info = solver(a, b[:, j], **solver_args)
+            if info != 0:
+                raise ValueError(f"{solver = } returns {info =} for column {j}.")
+        return res
+    else:
+        res, info = solver(a, b, **solver_args)
+        if info != 0:
+            raise ValueError(f"{solver = } returns {info = }.")
+        return res
+
+
+def make_ndbspl(points, values, k=3, *, solver=ssl.gcrotmk, **solver_args):
+    """Construct an interpolating NdBspline.
+
+    Parameters
+    ----------
+    points : tuple of ndarrays of float, with shapes (m1,), ... (mN,)
+        The points defining the regular grid in N dimensions. The points in
+        each dimension (i.e. every element of the `points` tuple) must be
+        strictly ascending or descending.
+    values : ndarray of float, shape (m1, ..., mN, ...)
+        The data on the regular grid in n dimensions.
+    k : int, optional
+        The spline degree. Must be odd. Default is cubic, k=3
+    solver : a `scipy.sparse.linalg` solver (iterative or direct), optional.
+        An iterative solver from `scipy.sparse.linalg` or a direct one,
+        `sparse.sparse.linalg.spsolve`.
+        Used to solve the sparse linear system
+        ``design_matrix @ coefficients = rhs`` for the coefficients.
+        Default is `scipy.sparse.linalg.gcrotmk`
+    solver_args : dict, optional
+        Additional arguments for the solver. The call signature is
+        ``solver(csr_array, rhs_vector, **solver_args)``
+
+    Returns
+    -------
+    spl : NdBSpline object
+
+    Notes
+    -----
+    Boundary conditions are not-a-knot in all dimensions.
+    """
+    ndim = len(points)
+    xi_shape = tuple(len(x) for x in points)
+
+    try:
+        len(k)
+    except TypeError:
+        # make k a tuple
+        k = (k,)*ndim
+
+    for d, point in enumerate(points):
+        numpts = len(np.atleast_1d(point))
+        if numpts <= k[d]:
+            raise ValueError(f"There are {numpts} points in dimension {d},"
+                             f" but order {k[d]} requires at least "
+                             f" {k[d]+1} points per dimension.")
+
+    t = tuple(_not_a_knot(np.asarray(points[d], dtype=float), k[d])
+              for d in range(ndim))
+    xvals = np.asarray([xv for xv in itertools.product(*points)], dtype=float)
+
+    # construct the colocation matrix
+    matr = NdBSpline.design_matrix(xvals, t, k)
+
+    # Remove zeros from the sparse matrix
+    # If k=1, then solve() doesn't take long enough for this to help
+    if k[0] >= 3:
+        matr.eliminate_zeros()
+
+    # Solve for the coefficients given `values`.
+    # Trailing dimensions: first ndim dimensions are data, the rest are batch
+    # dimensions, so stack `values` into a 2D array for `spsolve` to undestand.
+    v_shape = values.shape
+    vals_shape = (prod(v_shape[:ndim]), prod(v_shape[ndim:]))
+    vals = values.reshape(vals_shape)
+
+    if solver != ssl.spsolve:
+        solver = functools.partial(_iter_solve, solver=solver)
+        if "atol" not in solver_args:
+            # avoid a DeprecationWarning, grumble grumble
+            solver_args["atol"] = 1e-6
+
+    coef = solver(matr, vals, **solver_args)
+    coef = coef.reshape(xi_shape + v_shape[ndim:])
+    return NdBSpline(t, coef, k)
diff --git a/.venv/lib/python3.12/site-packages/scipy/interpolate/_ndgriddata.py b/.venv/lib/python3.12/site-packages/scipy/interpolate/_ndgriddata.py
new file mode 100644
index 0000000000000000000000000000000000000000..0726925620c53e3110d1863520a5500b76bb22a7
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/interpolate/_ndgriddata.py
@@ -0,0 +1,345 @@
+"""
+Convenience interface to N-D interpolation
+
+.. versionadded:: 0.9
+
+"""
+import numpy as np
+from ._interpnd import (LinearNDInterpolator, NDInterpolatorBase,
+     CloughTocher2DInterpolator, _ndim_coords_from_arrays)
+from scipy.spatial import KDTree
+
+__all__ = ['griddata', 'NearestNDInterpolator', 'LinearNDInterpolator',
+           'CloughTocher2DInterpolator']
+
+#------------------------------------------------------------------------------
+# Nearest-neighbor interpolation
+#------------------------------------------------------------------------------
+
+
+class NearestNDInterpolator(NDInterpolatorBase):
+    """Nearest-neighbor interpolator in N > 1 dimensions.
+
+    Parameters
+    ----------
+    x : (npoints, ndims) 2-D ndarray of floats
+        Data point coordinates.
+    y : (npoints, ...) N-D ndarray of float or complex
+        Data values. The length of `y` along the first axis must be equal to
+        the length of `x`.
+    rescale : bool, optional
+        Rescale points to unit cube before performing interpolation.
+        This is useful if some of the input dimensions have
+        incommensurable units and differ by many orders of magnitude.
+
+        .. versionadded:: 0.14.0
+    tree_options : dict, optional
+        Options passed to the underlying ``KDTree``.
+
+        .. versionadded:: 0.17.0
+
+    Methods
+    -------
+    __call__
+
+    See Also
+    --------
+    griddata :
+        Interpolate unstructured D-D data.
+    LinearNDInterpolator :
+        Piecewise linear interpolator in N dimensions.
+    CloughTocher2DInterpolator :
+        Piecewise cubic, C1 smooth, curvature-minimizing interpolator in 2D.
+    interpn : Interpolation on a regular grid or rectilinear grid.
+    RegularGridInterpolator : Interpolator on a regular or rectilinear grid
+                              in arbitrary dimensions (`interpn` wraps this
+                              class).
+
+    Notes
+    -----
+    Uses ``scipy.spatial.KDTree``
+
+    .. note:: For data on a regular grid use `interpn` instead.
+
+    Examples
+    --------
+    We can interpolate values on a 2D plane:
+
+    >>> from scipy.interpolate import NearestNDInterpolator
+    >>> import numpy as np
+    >>> import matplotlib.pyplot as plt
+    >>> rng = np.random.default_rng()
+    >>> x = rng.random(10) - 0.5
+    >>> y = rng.random(10) - 0.5
+    >>> z = np.hypot(x, y)
+    >>> X = np.linspace(min(x), max(x))
+    >>> Y = np.linspace(min(y), max(y))
+    >>> X, Y = np.meshgrid(X, Y)  # 2D grid for interpolation
+    >>> interp = NearestNDInterpolator(list(zip(x, y)), z)
+    >>> Z = interp(X, Y)
+    >>> plt.pcolormesh(X, Y, Z, shading='auto')
+    >>> plt.plot(x, y, "ok", label="input point")
+    >>> plt.legend()
+    >>> plt.colorbar()
+    >>> plt.axis("equal")
+    >>> plt.show()
+    """
+
+    def __init__(self, x, y, rescale=False, tree_options=None):
+        NDInterpolatorBase.__init__(self, x, y, rescale=rescale,
+                                    need_contiguous=False,
+                                    need_values=False)
+        if tree_options is None:
+            tree_options = dict()
+        self.tree = KDTree(self.points, **tree_options)
+        self.values = np.asarray(y)
+
+    def __call__(self, *args, **query_options):
+        """
+        Evaluate interpolator at given points.
+
+        Parameters
+        ----------
+        x1, x2, ... xn : array-like of float
+            Points where to interpolate data at.
+            x1, x2, ... xn can be array-like of float with broadcastable shape.
+            or x1 can be array-like of float with shape ``(..., ndim)``
+        **query_options
+            This allows ``eps``, ``p``, ``distance_upper_bound``, and ``workers``
+            being passed to the KDTree's query function to be explicitly set.
+            See `scipy.spatial.KDTree.query` for an overview of the different options.
+
+            .. versionadded:: 1.12.0
+
+        """
+        # For the sake of enabling subclassing, NDInterpolatorBase._set_xi performs
+        # some operations which are not required by NearestNDInterpolator.__call__,
+        # hence here we operate on xi directly, without calling a parent class function.
+        xi = _ndim_coords_from_arrays(args, ndim=self.points.shape[1])
+        xi = self._check_call_shape(xi)
+        xi = self._scale_x(xi)
+
+        # We need to handle two important cases:
+        # (1) the case where xi has trailing dimensions (..., ndim), and
+        # (2) the case where y has trailing dimensions
+        # We will first flatten xi to deal with case (1),
+        # do the computation in flattened array while retaining y's dimensionality,
+        # and then reshape the interpolated values back to match xi's shape.
+
+        # Flatten xi for the query
+        xi_flat = xi.reshape(-1, xi.shape[-1])
+        original_shape = xi.shape
+        flattened_shape = xi_flat.shape
+
+        # if distance_upper_bound is set to not be infinite,
+        # then we need to consider the case where KDtree
+        # does not find any points within distance_upper_bound to return.
+        # It marks those points as having infinte distance, which is what will be used
+        # below to mask the array and return only the points that were deemed
+        # to have a close enough neighbor to return something useful.
+        dist, i = self.tree.query(xi_flat, **query_options)
+        valid_mask = np.isfinite(dist)
+
+        # create a holder interp_values array and fill with nans.
+        if self.values.ndim > 1:
+            interp_shape = flattened_shape[:-1] + self.values.shape[1:]
+        else:
+            interp_shape = flattened_shape[:-1]
+
+        if np.issubdtype(self.values.dtype, np.complexfloating):
+            interp_values = np.full(interp_shape, np.nan, dtype=self.values.dtype)
+        else:
+            interp_values = np.full(interp_shape, np.nan)
+
+        interp_values[valid_mask] = self.values[i[valid_mask], ...]
+
+        if self.values.ndim > 1:
+            new_shape = original_shape[:-1] + self.values.shape[1:]
+        else:
+            new_shape = original_shape[:-1]
+        interp_values = interp_values.reshape(new_shape)
+
+        return interp_values
+
+
+#------------------------------------------------------------------------------
+# Convenience interface function
+#------------------------------------------------------------------------------
+
+
+def griddata(points, values, xi, method='linear', fill_value=np.nan,
+             rescale=False, simplex_tolerance=1.0):
+    """
+    Convenience function for interpolating unstructured data in multiple dimensions.
+
+    Parameters
+    ----------
+    points : 2-D ndarray of floats with shape (n, D), or length D tuple of 1-D ndarrays with shape (n,)
+        Data point coordinates.
+    values : ndarray of float or complex, shape (n,)
+        Data values.
+    xi : 2-D ndarray of floats with shape (m, D), or length D tuple of ndarrays broadcastable to the same shape
+        Points at which to interpolate data.
+    method : {'linear', 'nearest', 'cubic'}, optional
+        Method of interpolation. One of
+
+        ``nearest``
+          return the value at the data point closest to
+          the point of interpolation. See `NearestNDInterpolator` for
+          more details.
+
+        ``linear``
+          tessellate the input point set to N-D
+          simplices, and interpolate linearly on each simplex. See
+          `LinearNDInterpolator` for more details.
+
+        ``cubic`` (1-D)
+          return the value determined from a cubic
+          spline.
+
+        ``cubic`` (2-D)
+          return the value determined from a
+          piecewise cubic, continuously differentiable (C1), and
+          approximately curvature-minimizing polynomial surface. See
+          `CloughTocher2DInterpolator` for more details.
+    fill_value : float, optional
+        Value used to fill in for requested points outside of the
+        convex hull of the input points. If not provided, then the
+        default is ``nan``. This option has no effect for the
+        'nearest' method.
+    rescale : bool, optional
+        Rescale points to unit cube before performing interpolation.
+        This is useful if some of the input dimensions have
+        incommensurable units and differ by many orders of magnitude.
+
+        .. versionadded:: 0.14.0
+    simplex_tolerance : float, optional
+        Multiplier for the default tolerance QHull uses to assign
+        a simplex to the xi.  Default is 1.0.  Increase if there are
+        difficulties assigning points to simplexes; this is most
+        reproducible with points exatly on the border of a very
+        oblique triangle.  Only relevant for linear and 2-D cubic
+        interpolation.
+
+        .. versionadded:: 1.18.0
+
+    Returns
+    -------
+    ndarray
+        Array of interpolated values.
+
+    Raises
+    ------
+    ValueError
+        If simplex_tolerance <= 0
+
+    See Also
+    --------
+    LinearNDInterpolator :
+        Piecewise linear interpolator in N dimensions.
+    NearestNDInterpolator :
+        Nearest-neighbor interpolator in N dimensions.
+    CloughTocher2DInterpolator :
+        Piecewise cubic, C1 smooth, curvature-minimizing interpolator in 2D.
+    interpn : Interpolation on a regular grid or rectilinear grid.
+    RegularGridInterpolator : Interpolator on a regular or rectilinear grid
+                              in arbitrary dimensions (`interpn` wraps this
+                              class).
+
+    Notes
+    -----
+
+    .. versionadded:: 0.9
+
+    .. note:: For data on a regular grid use `interpn` instead.
+
+    Examples
+    --------
+
+    Suppose we want to interpolate the 2-D function
+
+    >>> import numpy as np
+    >>> def func(x, y):
+    ...     return x*(1-x)*np.cos(4*np.pi*x) * np.sin(4*np.pi*y**2)**2
+
+    on a grid in [0, 1]x[0, 1]
+
+    >>> grid_x, grid_y = np.mgrid[0:1:100j, 0:1:200j]
+
+    but we only know its values at 1000 data points:
+
+    >>> rng = np.random.default_rng()
+    >>> points = rng.random((1000, 2))
+    >>> values = func(points[:,0], points[:,1])
+
+    This can be done with `griddata` -- below we try out all of the
+    interpolation methods:
+
+    >>> from scipy.interpolate import griddata
+    >>> grid_z0 = griddata(points, values, (grid_x, grid_y), method='nearest')
+    >>> grid_z1 = griddata(points, values, (grid_x, grid_y), method='linear')
+    >>> grid_z2 = griddata(points, values, (grid_x, grid_y), method='cubic')
+
+    One can see that the exact result is reproduced by all of the
+    methods to some degree, but for this smooth function the piecewise
+    cubic interpolant gives the best results:
+
+    >>> import matplotlib.pyplot as plt
+    >>> plt.subplot(221)
+    >>> plt.imshow(func(grid_x, grid_y).T, extent=(0,1,0,1), origin='lower')
+    >>> plt.plot(points[:,0], points[:,1], 'k.', ms=1)
+    >>> plt.title('Original')
+    >>> plt.subplot(222)
+    >>> plt.imshow(grid_z0.T, extent=(0,1,0,1), origin='lower')
+    >>> plt.title('Nearest')
+    >>> plt.subplot(223)
+    >>> plt.imshow(grid_z1.T, extent=(0,1,0,1), origin='lower')
+    >>> plt.title('Linear')
+    >>> plt.subplot(224)
+    >>> plt.imshow(grid_z2.T, extent=(0,1,0,1), origin='lower')
+    >>> plt.title('Cubic')
+    >>> plt.gcf().set_size_inches(6, 6)
+    >>> plt.show()
+
+    """ # numpy/numpydoc#87  # noqa: E501
+    if simplex_tolerance <= 0:
+        raise ValueError("simplex_tolerance must be positive")
+
+    points = _ndim_coords_from_arrays(points)
+
+    if points.ndim < 2:
+        ndim = points.ndim
+    else:
+        ndim = points.shape[-1]
+
+    if ndim == 1 and method in ('nearest', 'linear', 'cubic'):
+        from ._interpolate import interp1d
+        points = points.ravel()
+        if isinstance(xi, tuple):
+            if len(xi) != 1:
+                raise ValueError("invalid number of dimensions in xi")
+            xi, = xi
+        # Sort points/values together, necessary as input for interp1d
+        idx = np.argsort(points)
+        points = points[idx]
+        values = values[idx]
+        if method == 'nearest':
+            fill_value = 'extrapolate'
+        ip = interp1d(points, values, kind=method, axis=0, bounds_error=False,
+                      fill_value=fill_value)
+        return ip(xi)
+    elif method == 'nearest':
+        ip = NearestNDInterpolator(points, values, rescale=rescale)
+        return ip(xi)
+    elif method == 'linear':
+        ip = LinearNDInterpolator(points, values, fill_value=fill_value,
+                                  rescale=rescale)
+        return ip(xi, simplex_tolerance=simplex_tolerance)
+    elif method == 'cubic' and ndim == 2:
+        ip = CloughTocher2DInterpolator(points, values, fill_value=fill_value,
+                                        rescale=rescale)
+        return ip(xi, simplex_tolerance=simplex_tolerance)
+    else:
+        raise ValueError(
+            f"Unknown interpolation method {method!r} for {ndim} dimensional data"
+        )
diff --git a/.venv/lib/python3.12/site-packages/scipy/interpolate/_pade.py b/.venv/lib/python3.12/site-packages/scipy/interpolate/_pade.py
new file mode 100644
index 0000000000000000000000000000000000000000..0c7d3315d0cc67db97b2bef5ca20a0ce6736683b
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/interpolate/_pade.py
@@ -0,0 +1,80 @@
+import warnings
+import os
+
+from numpy import zeros, asarray, eye, poly1d, hstack, r_
+from scipy import linalg
+from scipy._lib._array_api import xp_capabilities
+
+__all__ = ["pade"]
+
+@xp_capabilities(out_of_scope=True)
+def pade(an, m, n=None):
+    """
+    Return Pade approximation to a polynomial as the ratio of two polynomials.
+
+    .. deprecated:: 1.18.0
+        This function is deprecated and will be removed in SciPy 1.20.0. Use
+        `mpmath.pade` instead.
+
+    Parameters
+    ----------
+    an : (N,) array_like
+        Taylor series coefficients.
+    m : int
+        The order of the returned approximating polynomial `q`.
+    n : int, optional
+        The order of the returned approximating polynomial `p`. By default,
+        the order is ``len(an)-1-m``.
+
+    Returns
+    -------
+    p, q : Polynomial class
+        The Pade approximation of the polynomial defined by `an` is
+        ``p(x)/q(x)``.
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy.interpolate import pade
+    >>> e_exp = [1.0, 1.0, 1.0/2.0, 1.0/6.0, 1.0/24.0, 1.0/120.0]
+    >>> p, q = pade(e_exp, 2)
+
+    >>> e_exp.reverse()
+    >>> e_poly = np.poly1d(e_exp)
+
+    Compare ``e_poly(x)`` and the Pade approximation ``p(x)/q(x)``
+
+    >>> e_poly(1)
+    2.7166666666666668
+
+    >>> p(1)/q(1)
+    2.7179487179487181
+
+    """
+    _warn_skips = (os.path.dirname(__file__),)
+    msg = ("`pade` is deprecated and will be removed in SciPy 1.20.0. Use "
+           "`mpmath.pade` instead.")
+    warnings.warn(msg, DeprecationWarning, skip_file_prefixes=_warn_skips)
+    an = asarray(an)
+    if n is None:
+        n = len(an) - 1 - m
+        if n < 0:
+            raise ValueError("Order of q  must be smaller than len(an)-1.")
+    if n < 0:
+        raise ValueError("Order of p  must be greater than 0.")
+    N = m + n
+    if N > len(an)-1:
+        raise ValueError("Order of q+p  must be smaller than len(an).")
+    an = an[:N+1]
+    Akj = eye(N+1, n+1, dtype=an.dtype)
+    Bkj = zeros((N+1, m), dtype=an.dtype)
+    for row in range(1, m+1):
+        Bkj[row,:row] = -(an[:row])[::-1]
+    for row in range(m+1, N+1):
+        Bkj[row,:] = -(an[row-m:row])[::-1]
+    C = hstack((Akj, Bkj))
+    pq = linalg.solve(C, an)
+    p = pq[:n+1]
+    q = r_[1.0, pq[n+1:]]
+    return poly1d(p[::-1]), poly1d(q[::-1])
+
diff --git a/.venv/lib/python3.12/site-packages/scipy/interpolate/_polyint.py b/.venv/lib/python3.12/site-packages/scipy/interpolate/_polyint.py
new file mode 100644
index 0000000000000000000000000000000000000000..74e93168d76ab30deffd926d9f928e174d59c510
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/interpolate/_polyint.py
@@ -0,0 +1,1051 @@
+import warnings
+from types import GenericAlias
+import os
+
+import numpy as np
+from scipy.special import factorial
+from scipy._lib._util import (_asarray_validated, float_factorial, check_random_state,
+                              _transition_to_rng)
+from scipy._lib._array_api import xp_capabilities
+
+
+__all__ = ["KroghInterpolator", "krogh_interpolate",
+           "BarycentricInterpolator", "barycentric_interpolate",
+           "approximate_taylor_polynomial"]
+
+
+def _isscalar(x):
+    """Check whether x is if a scalar type, or 0-dim"""
+    return np.isscalar(x) or hasattr(x, 'shape') and x.shape == ()
+
+
+class _Interpolator1D:
+    """
+    Common features in univariate interpolation
+
+    Deal with input data type and interpolation axis rolling. The
+    actual interpolator can assume the y-data is of shape (n, r) where
+    `n` is the number of x-points, and `r` the number of variables,
+    and use self.dtype as the y-data type.
+
+    Attributes
+    ----------
+    _y_axis
+        Axis along which the interpolation goes in the original array
+    _y_extra_shape
+        Additional trailing shape of the input arrays, excluding
+        the interpolation axis.
+    dtype
+        Dtype of the y-data arrays. Can be set via _set_dtype, which
+        forces it to be float or complex.
+
+    Methods
+    -------
+    __call__
+    _prepare_x
+    _finish_y
+    _reshape_yi
+    _set_yi
+    _set_dtype
+    _evaluate
+
+    """
+
+    __slots__ = ('_y_axis', '_y_extra_shape', 'dtype')
+
+    # generic type compatibility with scipy-stubs
+    __class_getitem__: classmethod = classmethod(GenericAlias)
+
+    def __init__(self, xi=None, yi=None, axis=None):
+        self._y_axis = axis
+        self._y_extra_shape = None
+        self.dtype = None
+        if yi is not None:
+            self._set_yi(yi, xi=xi, axis=axis)
+
+    def __call__(self, x):
+        """
+        Evaluate the interpolant
+
+        Parameters
+        ----------
+        x : array_like
+            Point or points at which to evaluate the interpolant.
+
+        Returns
+        -------
+        y : array_like
+            Interpolated values. Shape is determined by replacing
+            the interpolation axis in the original array with the shape of `x`.
+
+        Notes
+        -----
+        Input values `x` must be convertible to `float` values like `int`
+        or `float`.
+
+        """
+        x, x_shape = self._prepare_x(x)
+        y = self._evaluate(x)
+        return self._finish_y(y, x_shape)
+
+    def _evaluate(self, x):
+        """
+        Actually evaluate the value of the interpolator.
+        """
+        raise NotImplementedError()
+
+    def _prepare_x(self, x):
+        """Reshape input x array to 1-D"""
+        x = _asarray_validated(x, check_finite=False, as_inexact=True)
+        x_shape = x.shape
+        return x.ravel(), x_shape
+
+    def _finish_y(self, y, x_shape):
+        """Reshape interpolated y back to an N-D array similar to initial y"""
+        y = y.reshape(x_shape + self._y_extra_shape)
+        if self._y_axis != 0 and x_shape != ():
+            nx = len(x_shape)
+            ny = len(self._y_extra_shape)
+            s = (list(range(nx, nx + self._y_axis))
+                 + list(range(nx)) + list(range(nx+self._y_axis, nx+ny)))
+            y = y.transpose(s)
+        return y
+
+    def _reshape_yi(self, yi, check=False):
+        yi = np.moveaxis(np.asarray(yi), self._y_axis, 0)
+        if check and yi.shape[1:] != self._y_extra_shape:
+            ok_shape = (f"{self._y_extra_shape[-self._y_axis:]!r} + (N,) + "
+                        f"{self._y_extra_shape[:-self._y_axis]!r}")
+            raise ValueError(f"Data must be of shape {ok_shape}")
+        return yi.reshape((yi.shape[0], -1))
+
+    def _set_yi(self, yi, xi=None, axis=None):
+        if axis is None:
+            axis = self._y_axis
+        if axis is None:
+            raise ValueError("no interpolation axis specified")
+
+        yi = np.asarray(yi)
+
+        shape = yi.shape
+        if shape == ():
+            shape = (1,)
+        if xi is not None and shape[axis] != len(xi):
+            raise ValueError("x and y arrays must be equal in length along "
+                             "interpolation axis.")
+
+        self._y_axis = (axis % yi.ndim)
+        self._y_extra_shape = yi.shape[:self._y_axis] + yi.shape[self._y_axis+1:]
+        self.dtype = None
+        self._set_dtype(yi.dtype)
+
+    def _set_dtype(self, dtype, union=False):
+        if np.issubdtype(dtype, np.complexfloating) \
+               or np.issubdtype(self.dtype, np.complexfloating):
+            self.dtype = np.complex128
+        else:
+            if not union or self.dtype != np.complex128:
+                self.dtype = np.float64
+
+
+class _Interpolator1DWithDerivatives(_Interpolator1D):
+    def derivatives(self, x, der=None):
+        """
+        Evaluate several derivatives of the polynomial at the point `x`.
+
+        Produce an array of derivatives evaluated at the point `x`.
+
+        Parameters
+        ----------
+        x : array_like
+            Point or points at which to evaluate the derivatives
+        der : int or list or None, optional
+            How many derivatives to evaluate, or None for all potentially
+            nonzero derivatives (that is, a number equal to the number
+            of points), or a list of derivatives to evaluate. This number
+            includes the function value as the '0th' derivative.
+
+        Returns
+        -------
+        d : ndarray
+            Array with derivatives; ``d[j]`` contains the jth derivative.
+            Shape of ``d[j]`` is determined by replacing the interpolation
+            axis in the original array with the shape of `x`.
+
+        Examples
+        --------
+        >>> from scipy.interpolate import KroghInterpolator
+        >>> KroghInterpolator([0,0,0],[1,2,3]).derivatives(0)
+        array([1.0,2.0,3.0])
+        >>> KroghInterpolator([0,0,0],[1,2,3]).derivatives([0,0])
+        array([[1.0,1.0],
+               [2.0,2.0],
+               [3.0,3.0]])
+
+        """
+        x, x_shape = self._prepare_x(x)
+        y = self._evaluate_derivatives(x, der)
+
+        y = y.reshape((y.shape[0],) + x_shape + self._y_extra_shape)
+        if self._y_axis != 0 and x_shape != ():
+            nx = len(x_shape)
+            ny = len(self._y_extra_shape)
+            s = ([0] + list(range(nx+1, nx + self._y_axis+1))
+                 + list(range(1, nx+1)) +
+                 list(range(nx+1+self._y_axis, nx+ny+1)))
+            y = y.transpose(s)
+        return y
+
+    def derivative(self, x, der=1):
+        """
+        Evaluate a single derivative of the polynomial at the point `x`.
+
+        Parameters
+        ----------
+        x : array_like
+            Point or points at which to evaluate the derivatives
+
+        der : int, optional
+            Which derivative to evaluate (default: first derivative).
+            This number includes the function value as 0th derivative.
+
+        Returns
+        -------
+        d : ndarray
+            Derivative interpolated at the x-points. Shape of `d` is
+            determined by replacing the interpolation axis in the
+            original array with the shape of `x`.
+
+        Notes
+        -----
+        This may be computed by evaluating all derivatives up to the desired
+        one (using self.derivatives()) and then discarding the rest.
+
+        """
+        x, x_shape = self._prepare_x(x)
+        y = self._evaluate_derivatives(x, der+1)
+        return self._finish_y(y[der], x_shape)
+
+    def _evaluate_derivatives(self, x, der=None):
+        """
+        Actually evaluate the derivatives.
+
+        Parameters
+        ----------
+        x : array_like
+            1D array of points at which to evaluate the derivatives
+        der : int, optional
+            The number of derivatives to evaluate, from 'order 0' (der=1)
+            to order der-1.  If omitted, return all possibly-non-zero
+            derivatives, ie 0 to order n-1.
+
+        Returns
+        -------
+        d : ndarray
+            Array of shape ``(der, x.size, self.yi.shape[1])`` containing
+            the derivatives from 0 to der-1
+        """
+        raise NotImplementedError()
+
+
+class KroghInterpolator(_Interpolator1DWithDerivatives):
+    """Krogh interpolator (C∞ smooth).
+
+    The polynomial passes through all the pairs ``(xi, yi)``. One may
+    additionally specify a number of derivatives at each point `xi`;
+    this is done by repeating the value `xi` and specifying the
+    derivatives as successive `yi` values.
+
+    Allows evaluation of the polynomial and all its derivatives.
+    For reasons of numerical stability, this function does not compute
+    the coefficients of the polynomial, although they can be obtained
+    by evaluating all the derivatives.
+
+    Parameters
+    ----------
+    xi : array_like, shape (npoints, )
+        Known x-coordinates. Must be sorted in increasing order.
+    yi : array_like, shape (..., npoints, ...)
+        Known y-coordinates. When an xi occurs two or more times in
+        a row, the corresponding yi's represent derivative values. The length of `yi`
+        along the interpolation axis must be equal to the length of `xi`. Use the
+        `axis` parameter to select the correct axis.
+    axis : int, optional
+        Axis in the `yi` array corresponding to the x-coordinate values. Defaults to
+        ``axis=0``.
+
+    Notes
+    -----
+    Be aware that the algorithms implemented here are not necessarily
+    the most numerically stable known. Moreover, even in a world of
+    exact computation, unless the x coordinates are chosen very
+    carefully - Chebyshev zeros (e.g., cos(i*pi/n)) are a good choice -
+    polynomial interpolation itself is a very ill-conditioned process
+    due to the Runge phenomenon. In general, even with well-chosen
+    x values, degrees higher than about thirty cause problems with
+    numerical instability in this code.
+
+    Based on [1]_.
+
+    References
+    ----------
+    .. [1] Krogh, "Efficient Algorithms for Polynomial Interpolation
+        and Numerical Differentiation", 1970.
+
+    Examples
+    --------
+    To produce a polynomial that is zero at 0 and 1 and has
+    derivative 2 at 0, call
+
+    >>> from scipy.interpolate import KroghInterpolator
+    >>> KroghInterpolator([0,0,1],[0,2,0])
+
+    This constructs the quadratic :math:`2x^2-2x`. The derivative condition
+    is indicated by the repeated zero in the `xi` array; the corresponding
+    yi values are 0, the function value, and 2, the derivative value.
+
+    For another example, given `xi`, `yi`, and a derivative `ypi` for each
+    point, appropriate arrays can be constructed as:
+
+    >>> import numpy as np
+    >>> rng = np.random.default_rng()
+    >>> xi = np.linspace(0, 1, 5)
+    >>> yi, ypi = rng.random((2, 5))
+    >>> xi_k, yi_k = np.repeat(xi, 2), np.ravel(np.dstack((yi,ypi)))
+    >>> KroghInterpolator(xi_k, yi_k)
+
+    To produce a vector-valued polynomial, supply a higher-dimensional
+    array for `yi`:
+
+    >>> KroghInterpolator([0,1],[[2,3],[4,5]])
+
+    This constructs a linear polynomial giving (2,3) at 0 and (4,5) at 1.
+
+    """
+
+    def __init__(self, xi, yi, axis=0):
+        super().__init__(xi, yi, axis)
+
+        self.xi = np.asarray(xi)
+        self.yi = self._reshape_yi(yi)
+        self.n, self.r = self.yi.shape
+
+        if (deg := self.xi.size) > 30:
+            warnings.warn(f"{deg} degrees provided, degrees higher than about"
+                          " thirty cause problems with numerical instability "
+                          "with 'KroghInterpolator'", stacklevel=2)
+
+        c = np.zeros((self.n+1, self.r), dtype=self.dtype)
+        c[0] = self.yi[0]
+        Vk = np.zeros((self.n, self.r), dtype=self.dtype)
+        for k in range(1, self.n):
+            s = 0
+            while s <= k and xi[k-s] == xi[k]:
+                s += 1
+            s -= 1
+            Vk[0] = self.yi[k]/float_factorial(s)
+            for i in range(k-s):
+                if xi[i] == xi[k]:
+                    raise ValueError("Elements of `xi` can't be equal.")
+                if s == 0:
+                    Vk[i+1] = (c[i]-Vk[i])/(xi[i]-xi[k])
+                else:
+                    Vk[i+1] = (Vk[i+1]-Vk[i])/(xi[i]-xi[k])
+            c[k] = Vk[k-s]
+        self.c = c
+
+    def _evaluate(self, x):
+        pi = 1
+        p = np.zeros((len(x), self.r), dtype=self.dtype)
+        p += self.c[0,np.newaxis,:]
+        for k in range(1, self.n):
+            w = x - self.xi[k-1]
+            pi = w*pi
+            p += pi[:,np.newaxis] * self.c[k]
+        return p
+
+    def _evaluate_derivatives(self, x, der=None):
+        n = self.n
+        r = self.r
+
+        if der is None:
+            der = self.n
+
+        pi = np.zeros((n, len(x)))
+        w = np.zeros((n, len(x)))
+        pi[0] = 1
+        p = np.zeros((len(x), self.r), dtype=self.dtype)
+        p += self.c[0, np.newaxis, :]
+
+        for k in range(1, n):
+            w[k-1] = x - self.xi[k-1]
+            pi[k] = w[k-1] * pi[k-1]
+            p += pi[k, :, np.newaxis] * self.c[k]
+
+        cn = np.zeros((max(der, n+1), len(x), r), dtype=self.dtype)
+        cn[:n+1, :, :] += self.c[:n+1, np.newaxis, :]
+        cn[0] = p
+        for k in range(1, n):
+            for i in range(1, n-k+1):
+                pi[i] = w[k+i-1]*pi[i-1] + pi[i]
+                cn[k] = cn[k] + pi[i, :, np.newaxis]*cn[k+i]
+            cn[k] *= float_factorial(k)
+
+        cn[n, :, :] = 0
+        return cn[:der]
+
+
+def krogh_interpolate(xi, yi, x, der=0, axis=0):
+    """Convenience function for Krogh interpolation.
+
+    See `KroghInterpolator` for more details.
+
+    Parameters
+    ----------
+    xi : array_like
+        Interpolation points (known x-coordinates).
+    yi : array_like
+        Known y-coordinates, of shape ``(xi.size, R)``. Interpreted as
+        vectors of length R, or scalars if R=1.
+    x : array_like
+        Point or points at which to evaluate the derivatives.
+    der : int or list or None, optional
+        How many derivatives to evaluate, or None for all potentially
+        nonzero derivatives (that is, a number equal to the number
+        of points), or a list of derivatives to evaluate. This number
+        includes the function value as the '0th' derivative.
+    axis : int, optional
+        Axis in the `yi` array corresponding to the x-coordinate values.
+
+    Returns
+    -------
+    d : ndarray
+        If the interpolator's values are R-D then the
+        returned array will be the number of derivatives by N by R.
+        If `x` is a scalar, the middle dimension will be dropped; if
+        the `yi` are scalars then the last dimension will be dropped.
+
+    See Also
+    --------
+    KroghInterpolator : Krogh interpolator
+
+    Notes
+    -----
+    Construction of the interpolating polynomial is a relatively expensive
+    process. If you want to evaluate it repeatedly consider using the class
+    KroghInterpolator (which is what this function uses).
+
+    Examples
+    --------
+    We can interpolate 2D observed data using Krogh interpolation:
+
+    >>> import numpy as np
+    >>> import matplotlib.pyplot as plt
+    >>> from scipy.interpolate import krogh_interpolate
+    >>> x_observed = np.linspace(0.0, 10.0, 11)
+    >>> y_observed = np.sin(x_observed)
+    >>> x = np.linspace(min(x_observed), max(x_observed), num=100)
+    >>> y = krogh_interpolate(x_observed, y_observed, x)
+    >>> plt.plot(x_observed, y_observed, "o", label="observation")
+    >>> plt.plot(x, y, label="krogh interpolation")
+    >>> plt.legend()
+    >>> plt.show()
+    """
+
+    P = KroghInterpolator(xi, yi, axis=axis)
+    if der == 0:
+        return P(x)
+    elif _isscalar(der):
+        return P.derivative(x, der=der)
+    else:
+        return P.derivatives(x, der=np.amax(der)+1)[der]
+
+
+@xp_capabilities(out_of_scope=True)
+def approximate_taylor_polynomial(f,x,degree,scale,order=None):
+    """
+    Estimate the Taylor polynomial of f at x by polynomial fitting.
+
+    .. deprecated:: 1.18.0
+        This function is deprecated and will be removed in SciPy 1.20.0. Use the
+        following code instead:
+
+        .. code-block:: python
+
+            import numpy as np
+
+            def f(z): return np.exp(z**2)  # example function
+            N = 10  # number of terms in the Taylor expansion
+            zz = np.exp(2j * np.pi * np.arange(N) / N)  # roots of unity
+            c = np.fft.fft(f(zz)) / N
+            c = np.real(c)  # c must be real by symmetry
+
+
+    Parameters
+    ----------
+    f : callable
+        The function whose Taylor polynomial is sought. Should accept
+        a vector of `x` values.
+    x : scalar
+        The point at which the polynomial is to be evaluated.
+    degree : int
+        The degree of the Taylor polynomial
+    scale : scalar
+        The width of the interval to use to evaluate the Taylor polynomial.
+        Function values spread over a range this wide are used to fit the
+        polynomial. Must be chosen carefully.
+    order : int or None, optional
+        The order of the polynomial to be used in the fitting; `f` will be
+        evaluated ``order+1`` times. If None, use `degree`.
+
+    Returns
+    -------
+    p : poly1d instance
+        The Taylor polynomial (translated to the origin, so that
+        for example p(0)=f(x)).
+
+    Notes
+    -----
+    The appropriate choice of "scale" is a trade-off; too large and the
+    function differs from its Taylor polynomial too much to get a good
+    answer, too small and round-off errors overwhelm the higher-order terms.
+    The algorithm used becomes numerically unstable around order 30 even
+    under ideal circumstances.
+
+    Choosing order somewhat larger than degree may improve the higher-order
+    terms.
+
+    Examples
+    --------
+    We can calculate Taylor approximation polynomials of sin function with
+    various degrees:
+
+    >>> import numpy as np
+    >>> import matplotlib.pyplot as plt
+    >>> from scipy.interpolate import approximate_taylor_polynomial
+    >>> x = np.linspace(-10.0, 10.0, num=100)
+    >>> plt.plot(x, np.sin(x), label="sin curve")
+    >>> for degree in np.arange(1, 15, step=2):
+    ...     sin_taylor = approximate_taylor_polynomial(np.sin, 0, degree, 1,
+    ...                                                order=degree + 2)
+    ...     plt.plot(x, sin_taylor(x), label=f"degree={degree}")
+    >>> plt.legend(bbox_to_anchor=(1.05, 1), loc='upper left',
+    ...            borderaxespad=0.0, shadow=True)
+    >>> plt.tight_layout()
+    >>> plt.axis([-10, 10, -10, 10])
+    >>> plt.show()
+
+    """
+    _warn_skips = (os.path.dirname(__file__),)
+    msg = ("`approximate_taylor_polynomial` is deprecated and will be removed in "
+           "SciPy 1.20.0.")
+    warnings.warn(msg, DeprecationWarning, skip_file_prefixes=_warn_skips)
+    if order is None:
+        order = degree
+
+    n = order+1
+    # Choose n points that cluster near the endpoints of the interval in
+    # a way that avoids the Runge phenomenon. Ensure, by including the
+    # endpoint or not as appropriate, that one point always falls at x
+    # exactly.
+    xs = scale*np.cos(np.linspace(0,np.pi,n,endpoint=n % 1)) + x
+
+    P = KroghInterpolator(xs, f(xs))
+    d = P.derivatives(x,der=degree+1)
+
+    return np.poly1d((d/factorial(np.arange(degree+1)))[::-1])
+
+
+class BarycentricInterpolator(_Interpolator1DWithDerivatives):
+    r"""Barycentric (Lagrange with improved stability) interpolator (C∞ smooth).
+
+    Constructs a polynomial that passes through a given set of points.
+    Allows evaluation of the polynomial and all its derivatives,
+    efficient changing of the y-values to be interpolated,
+    and updating by adding more x- and y-values. For numerical stability, a barycentric
+    representation is used rather than computing the coefficients of the polynomial
+    directly.
+
+
+    Parameters
+    ----------
+    xi : array_like, shape (npoints, )
+        1-D array of x-coordinates of the points the polynomial
+        should pass through
+    yi : array_like, shape (..., npoints, ...), optional
+        N-D array of y-coordinates of the points the polynomial should pass through.
+        If None, the y values will be supplied later via the `set_y` method.
+        The length of `yi` along the interpolation axis must be equal to the length
+        of `xi`. Use the ``axis`` parameter to select correct axis.
+    axis : int, optional
+        Axis in the yi array corresponding to the x-coordinate values. Defaults
+        to ``axis=0``.
+    wi : array_like, optional
+        The barycentric weights for the chosen interpolation points `xi`.
+        If absent or None, the weights will be computed from `xi` (default).
+        This allows for the reuse of the weights `wi` if several interpolants
+        are being calculated using the same nodes `xi`, without re-computation. This
+        also allows for computing the weights explicitly for some choices of
+        `xi` (see notes).
+    rng : {None, int, `numpy.random.Generator`}, optional
+        If `rng` is passed by keyword, types other than `numpy.random.Generator` are
+        passed to `numpy.random.default_rng` to instantiate a ``Generator``.
+        If `rng` is already a ``Generator`` instance, then the provided instance is
+        used. Specify `rng` for repeatable interpolation.
+
+        If this argument `random_state` is passed by keyword,
+        legacy behavior for the argument `random_state` applies:
+
+        - If `random_state` is None (or `numpy.random`), the `numpy.random.RandomState`
+          singleton is used.
+        - If `random_state` is an int, a new ``RandomState`` instance is used,
+          seeded with `random_state`.
+        - If `random_state` is already a ``Generator`` or ``RandomState`` instance then
+          that instance is used.
+
+        .. versionchanged:: 1.15.0
+            As part of the `SPEC-007 `_
+            transition from use of `numpy.random.RandomState` to
+            `numpy.random.Generator` this keyword was changed from `random_state` to `rng`.
+            For an interim period, both keywords will continue to work (only specify
+            one of them). After the interim period using the `random_state` keyword will emit
+            warnings. The behavior of the `random_state` and `rng` keywords is outlined above.
+
+    Notes
+    -----
+    This method is a variant of Lagrange polynomial interpolation [1]_ based on [2]_.
+    Instead of using Lagrange's or Newton's formula, the polynomial is represented by
+    the barycentric formula
+
+    .. math::
+
+        p(x) =
+        \frac{\sum_{i=1}^m\ w_i y_i / (x - x_i)}{\sum_{i=1}^m w_i / (x - x_i)},
+
+    where :math:`w_i` are the barycentric weights computed with the general formula
+
+    .. math::
+
+        w_i = \left( \prod_{k \neq i} x_i - x_k \right)^{-1}.
+
+    This is the same barycentric form used by `AAA` and `FloaterHormannInterpolator`.
+    However, in contrast, the weights :math:`w_i` are defined such that
+    :math:`p(x)` is a polynomial rather than a rational function.
+
+    The barycentric representation avoids many of the problems associated with
+    polynomial interpolation caused by floating-point arithmetic. However, it does not
+    avoid issues that are intrinsic to polynomial interpolation. Namely, if the
+    x-coordinates are equally spaced, then the weights can be computed explicitly using
+    the formula from [2]_
+
+    .. math::
+
+        w_i = (-1)^i {n \choose i},
+
+    where :math:`n` is the number of x-coordinates. As noted in [2]_, this means that
+    for large :math:`n` the weights vary by exponentially large factors, leading to the
+    Runge phenomenon.
+
+    To avoid this ill-conditioning, the x-coordinates should be clustered at the
+    endpoints of the interval. An excellent choice of points on the interval
+    :math:`[a,b]` are Chebyshev points of the second kind
+
+    .. math::
+
+        x_i = \frac{a + b}{2} + \frac{a - b}{2}\cos(i\pi/n).
+
+    in which case the weights can be computed explicitly as
+
+    .. math::
+
+        w_i = \begin{cases}
+                  (-1)^i/2 & i = 0,n \\
+                  (-1)^i   & \text{otherwise}
+              \end{cases}.
+
+    See [2]_ for more infomation. Note that for large :math:`n`, computing the weights
+    explicitly (see examples) will be faster than the generic formula.
+
+    References
+    ----------
+    .. [1] https://en.wikipedia.org/wiki/Lagrange_polynomial
+    .. [2] Jean-Paul Berrut and Lloyd N. Trefethen, "Barycentric Lagrange
+           Interpolation", SIAM Review 2004 46:3, 501-517
+           :doi:`10.1137/S0036144502417715`
+
+    Examples
+    --------
+    To produce a quintic barycentric interpolant approximating the function
+    :math:`\sin x`, and its first four derivatives, using six randomly-spaced
+    nodes in :math:`(0, \pi/2)`:
+
+    >>> import numpy as np
+    >>> import matplotlib.pyplot as plt
+    >>> from scipy.interpolate import BarycentricInterpolator
+    >>> rng = np.random.default_rng()
+    >>> xi = rng.random(6) * np.pi/2
+    >>> f, f_d1, f_d2, f_d3, f_d4 = np.sin, np.cos, lambda x: -np.sin(x), lambda x: -np.cos(x), np.sin
+    >>> P = BarycentricInterpolator(xi, f(xi), random_state=rng)
+    >>> fig, axs = plt.subplots(5, 1, sharex=True, layout='constrained', figsize=(7,10))
+    >>> x = np.linspace(0, np.pi, 100)
+    >>> axs[0].plot(x, P(x), 'r:', x, f(x), 'k--', xi, f(xi), 'xk')
+    >>> axs[1].plot(x, P.derivative(x), 'r:', x, f_d1(x), 'k--', xi, f_d1(xi), 'xk')
+    >>> axs[2].plot(x, P.derivative(x, 2), 'r:', x, f_d2(x), 'k--', xi, f_d2(xi), 'xk')
+    >>> axs[3].plot(x, P.derivative(x, 3), 'r:', x, f_d3(x), 'k--', xi, f_d3(xi), 'xk')
+    >>> axs[4].plot(x, P.derivative(x, 4), 'r:', x, f_d4(x), 'k--', xi, f_d4(xi), 'xk')
+    >>> axs[0].set_xlim(0, np.pi)
+    >>> axs[4].set_xlabel(r"$x$")
+    >>> axs[4].set_xticks([i * np.pi / 4 for i in range(5)],
+    ...                   ["0", r"$\frac{\pi}{4}$", r"$\frac{\pi}{2}$", r"$\frac{3\pi}{4}$", r"$\pi$"])
+    >>> for ax, label in zip(axs, ("$f(x)$", "$f'(x)$", "$f''(x)$", "$f^{(3)}(x)$", "$f^{(4)}(x)$")):
+    ...     ax.set_ylabel(label)
+    >>> labels = ['Interpolation nodes', 'True function $f$', 'Barycentric interpolation']
+    >>> axs[0].legend(axs[0].get_lines()[::-1], labels, bbox_to_anchor=(0., 1.02, 1., .102),
+    ...               loc='lower left', ncols=3, mode="expand", borderaxespad=0., frameon=False)
+    >>> plt.show()
+
+    Next, we show how using Chebyshev points of the second kind avoids the
+    Runge phenomenon. In this example, we also compute the weights explicitly.
+
+    >>> n = 20
+    >>> def f(x): return np.abs(x) + 0.5*x - x**2
+    >>> i = np.arange(n)
+    >>> x_cheb = np.cos(i*np.pi/(n - 1))  # Chebyshev points on [-1, 1]
+    >>> w_i_cheb = (-1.)**i  # Explicit formula for weights of Chebyshev points
+    >>> w_i_cheb[[0, -1]] /= 2
+    >>> p_cheb = BarycentricInterpolator(x_cheb, f(x_cheb), wi=w_i_cheb)
+    >>> x_equi = np.linspace(-1, 1, n)
+    >>> p_equi = BarycentricInterpolator(x_equi, f(x_equi))
+    >>> xx = np.linspace(-1, 1, 1000)
+    >>> fig, ax = plt.subplots()
+    >>> ax.plot(xx, f(xx), label="Original Function")
+    >>> ax.plot(xx, p_cheb(xx), "--", label="Chebshev Points")
+    >>> ax.plot(xx, p_equi(xx), "--", label="Equally Spaced Points")
+    >>> ax.set(xlabel="$x$", ylabel="$f(x)$", xlim=[-1, 1])
+    >>> ax.legend()
+    >>> plt.show()
+
+    """ # numpy/numpydoc#87  # noqa: E501
+
+    @_transition_to_rng("random_state", replace_doc=False)
+    def __init__(self, xi, yi=None, axis=0, *, wi=None, rng=None):
+        super().__init__(xi, yi, axis)
+
+        rng = check_random_state(rng)
+
+        self.xi = np.asarray(xi, dtype=np.float64)
+        self.set_yi(yi)
+        self.n = len(self.xi)
+
+        # cache derivative object to avoid re-computing the weights with every call.
+        self._diff_cij = None
+
+        if wi is not None:
+            self.wi = wi
+        else:
+            # See page 510 of Berrut and Trefethen 2004 for an explanation of the
+            # capacity scaling and the suggestion of using a random permutation of
+            # the input factors.
+            # At the moment, the permutation is not performed for xi that are
+            # appended later through the add_xi interface. It's not clear to me how
+            # to implement that and it seems that most situations that require
+            # these numerical stability improvements will be able to provide all
+            # the points to the constructor.
+            self._inv_capacity = 4.0 / (np.max(self.xi) - np.min(self.xi))
+            permute = rng.permutation(self.n, )
+            inv_permute = np.zeros(self.n, dtype=np.int32)
+            inv_permute[permute] = np.arange(self.n)
+            self.wi = np.zeros(self.n)
+
+            for i in range(self.n):
+                dist = self._inv_capacity * (self.xi[i] - self.xi[permute])
+                dist[inv_permute[i]] = 1.0
+                prod = np.prod(dist)
+                if prod == 0.0:
+                    raise ValueError("Interpolation points xi must be"
+                                     " distinct.")
+                self.wi[i] = 1.0 / prod
+
+    def set_yi(self, yi, axis=None):
+        """
+        Update the y values to be interpolated.
+
+        The barycentric interpolation algorithm requires the calculation
+        of weights, but these depend only on the `xi`. The `yi` can be changed
+        at any time.
+
+        Parameters
+        ----------
+        yi : array_like
+            The y-coordinates of the points the polynomial will pass through.
+            If None, the y values must be supplied later.
+        axis : int, optional
+            Axis in the `yi` array corresponding to the x-coordinate values.
+
+        """
+        if yi is None:
+            self.yi = None
+            return
+        self._set_yi(yi, xi=self.xi, axis=axis)
+        self.yi = self._reshape_yi(yi)
+        self.n, self.r = self.yi.shape
+        self._diff_baryint = None
+
+    def add_xi(self, xi, yi=None):
+        """
+        Add more x values to the set to be interpolated.
+
+        The barycentric interpolation algorithm allows easy updating by
+        adding more points for the polynomial to pass through.
+
+        Parameters
+        ----------
+        xi : array_like
+            The x coordinates of the points that the polynomial should pass
+            through.
+        yi : array_like, optional
+            The y coordinates of the points the polynomial should pass through.
+            Should have shape ``(xi.size, R)``; if R > 1 then the polynomial is
+            vector-valued.
+            If `yi` is not given, the y values will be supplied later. `yi`
+            should be given if and only if the interpolator has y values
+            specified.
+
+        Notes
+        -----
+        The new points added by `add_xi` are not randomly permuted
+        so there is potential for numerical instability,
+        especially for a large number of points. If this
+        happens, please reconstruct interpolation from scratch instead.
+        """
+        if yi is not None:
+            if self.yi is None:
+                raise ValueError("No previous yi value to update!")
+            yi = self._reshape_yi(yi, check=True)
+            self.yi = np.vstack((self.yi,yi))
+        else:
+            if self.yi is not None:
+                raise ValueError("No update to yi provided!")
+        old_n = self.n
+        self.xi = np.concatenate((self.xi,xi))
+        self.n = len(self.xi)
+        self.wi **= -1
+        old_wi = self.wi
+        self.wi = np.zeros(self.n)
+        self.wi[:old_n] = old_wi
+        for j in range(old_n, self.n):
+            self.wi[:j] *= self._inv_capacity * (self.xi[j]-self.xi[:j])
+            self.wi[j] = np.multiply.reduce(
+                self._inv_capacity * (self.xi[:j]-self.xi[j])
+            )
+        self.wi **= -1
+        self._diff_cij = None
+        self._diff_baryint = None
+
+    def __call__(self, x):
+        """Evaluate the interpolating polynomial at the points x
+
+        Parameters
+        ----------
+        x : array_like
+            Point or points at which to evaluate the interpolant.
+
+        Returns
+        -------
+        y : array_like
+            Interpolated values. Shape is determined by replacing
+            the interpolation axis in the original array with the shape of `x`.
+
+        Notes
+        -----
+        Currently the code computes an outer product between `x` and the
+        weights, that is, it constructs an intermediate array of size
+        ``(N, len(x))``, where N is the degree of the polynomial.
+        """
+        return _Interpolator1D.__call__(self, x)
+
+    def _evaluate(self, x):
+        if x.size == 0:
+            p = np.zeros((0, self.r), dtype=self.dtype)
+        else:
+            c = x[..., np.newaxis] - self.xi
+            z = c == 0
+            c[z] = 1
+            c = self.wi / c
+            with np.errstate(divide='ignore'):
+                p = np.dot(c, self.yi) / np.sum(c, axis=-1)[..., np.newaxis]
+            # Now fix where x==some xi
+            r = np.nonzero(z)
+            if len(r) == 1:  # evaluation at a scalar
+                if len(r[0]) > 0:  # equals one of the points
+                    p = self.yi[r[0][0]]
+            else:
+                p[r[:-1]] = self.yi[r[-1]]
+        return p
+
+    def derivative(self, x, der=1):
+        """
+        Evaluate a single derivative of the polynomial at the point x.
+
+        Parameters
+        ----------
+        x : array_like
+            Point or points at which to evaluate the derivatives
+        der : int, optional
+            Which derivative to evaluate (default: first derivative).
+            This number includes the function value as 0th derivative.
+
+        Returns
+        -------
+        d : ndarray
+            Derivative interpolated at the x-points. Shape of `d` is
+            determined by replacing the interpolation axis in the
+            original array with the shape of `x`.
+        """
+        x, x_shape = self._prepare_x(x)
+        y = self._evaluate_derivatives(x, der+1, all_lower=False)
+        return self._finish_y(y, x_shape)
+
+    def _evaluate_derivatives(self, x, der=None, all_lower=True):
+        # NB: der here is not the order of the highest derivative;
+        # instead, it is the size of the derivatives matrix that
+        # would be returned with all_lower=True, including the
+        # '0th' derivative (the undifferentiated function).
+        # E.g. to evaluate the 5th derivative alone, call
+        # _evaluate_derivatives(x, der=6, all_lower=False).
+
+        if (not all_lower) and (x.size == 0 or self.r == 0):
+            return np.zeros((0, self.r), dtype=self.dtype)
+
+        if (not all_lower) and der == 1:
+            return self._evaluate(x)
+
+        if (not all_lower) and (der > self.n):
+            return np.zeros((len(x), self.r), dtype=self.dtype)
+
+        if der is None:
+            der = self.n
+
+        if all_lower and (x.size == 0 or self.r == 0):
+            return np.zeros((der, len(x), self.r), dtype=self.dtype)
+
+        if self._diff_cij is None:
+            # c[i,j] = xi[i] - xi[j]
+            c = self.xi[:, np.newaxis] - self.xi
+
+            # avoid division by 0 (diagonal entries are so far zero by construction)
+            np.fill_diagonal(c, 1)
+
+            # c[i,j] = (w[j] / w[i]) / (xi[i] - xi[j]) (equation 9.4)
+            c = self.wi/ (c * self.wi[..., np.newaxis])
+
+            # fill in correct diagonal entries: each column sums to 0
+            np.fill_diagonal(c, 0)
+
+            # calculate diagonal
+            # c[j,j] = -sum_{i != j} c[i,j] (equation 9.5)
+            d = -c.sum(axis=1)
+            # c[i,j] = l_j(x_i)
+            np.fill_diagonal(c, d)
+
+            self._diff_cij = c
+
+        if self._diff_baryint is None:
+            # initialise and cache derivative interpolator and cijs;
+            # reuse weights wi (which depend only on interpolation points xi),
+            # to avoid unnecessary re-computation
+            self._diff_baryint = BarycentricInterpolator(xi=self.xi,
+                                                         yi=self._diff_cij @ self.yi,
+                                                         wi=self.wi)
+            self._diff_baryint._diff_cij = self._diff_cij
+
+        if all_lower:
+            # assemble matrix of derivatives from order 0 to order der-1,
+            # in the format required by _Interpolator1DWithDerivatives.
+            cn = np.zeros((der, len(x), self.r), dtype=self.dtype)
+            for d in range(der):
+                cn[d, :, :] = self._evaluate_derivatives(x, d+1, all_lower=False)
+            return cn
+
+        # recursively evaluate only the derivative requested
+        return self._diff_baryint._evaluate_derivatives(x, der-1, all_lower=False)
+
+
+def barycentric_interpolate(xi, yi, x, axis=0, *, der=0, rng=None):
+    """Convenience function for barycentric interpolation.
+
+    Constructs a polynomial that passes through a given set of points,
+    then evaluates the polynomial. For reasons of numerical stability,
+    this function does not compute the coefficients of the polynomial.
+
+    This function uses a "barycentric interpolation" method that treats
+    the problem as a special case of rational function interpolation.
+    This algorithm is quite stable, numerically, but even in a world of
+    exact computation, unless the `x` coordinates are chosen very
+    carefully - Chebyshev zeros (e.g., cos(i*pi/n)) are a good choice -
+    polynomial interpolation itself is a very ill-conditioned process
+    due to the Runge phenomenon.
+
+    Parameters
+    ----------
+    xi : array_like
+        1-D array of x coordinates of the points the polynomial should
+        pass through
+    yi : array_like
+        The y coordinates of the points the polynomial should pass through.
+    x : scalar or array_like
+        Point or points at which to evaluate the interpolant.
+    axis : int, optional
+        Axis in the `yi` array corresponding to the x-coordinate values.
+    der : int or list or None, optional
+        How many derivatives to evaluate, or None for all potentially
+        nonzero derivatives (that is, a number equal to the number
+        of points), or a list of derivatives to evaluate. This number
+        includes the function value as the '0th' derivative.
+    rng : `numpy.random.Generator`, optional
+        Pseudorandom number generator state. When `rng` is None, a new
+        `numpy.random.Generator` is created using entropy from the
+        operating system. Types other than `numpy.random.Generator` are
+        passed to `numpy.random.default_rng` to instantiate a ``Generator``.
+
+    Returns
+    -------
+    y : scalar or array_like
+        Interpolated values. Shape is determined by replacing
+        the interpolation axis in the original array with the shape of `x`.
+
+    See Also
+    --------
+    BarycentricInterpolator : Barycentric interpolator
+
+    Notes
+    -----
+    Construction of the interpolation weights is a relatively slow process.
+    If you want to call this many times with the same xi (but possibly
+    varying yi or x) you should use the class `BarycentricInterpolator`.
+    This is what this function uses internally.
+
+    Examples
+    --------
+    We can interpolate 2D observed data using barycentric interpolation:
+
+    >>> import numpy as np
+    >>> import matplotlib.pyplot as plt
+    >>> from scipy.interpolate import barycentric_interpolate
+    >>> x_observed = np.linspace(0.0, 10.0, 11)
+    >>> y_observed = np.sin(x_observed)
+    >>> x = np.linspace(min(x_observed), max(x_observed), num=100)
+    >>> y = barycentric_interpolate(x_observed, y_observed, x)
+    >>> plt.plot(x_observed, y_observed, "o", label="observation")
+    >>> plt.plot(x, y, label="barycentric interpolation")
+    >>> plt.legend()
+    >>> plt.show()
+
+    """
+    P = BarycentricInterpolator(xi, yi, axis=axis, rng=rng)
+    if der == 0:
+        return P(x)
+    elif _isscalar(der):
+        return P.derivative(x, der=der)
+    else:
+        return P.derivatives(x, der=np.amax(der)+1)[der]
diff --git a/.venv/lib/python3.12/site-packages/scipy/interpolate/_ppoly.cpython-312-x86_64-linux-gnu.so b/.venv/lib/python3.12/site-packages/scipy/interpolate/_ppoly.cpython-312-x86_64-linux-gnu.so
new file mode 100644
index 0000000000000000000000000000000000000000..984686a0d277eac86976742990652e606cefcc4f
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/interpolate/_ppoly.cpython-312-x86_64-linux-gnu.so
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:2e8b80cb46e559663aefaee45ff519f7dcbccf9d60aee3f1ce959b0a61c3d35f
+size 222784
diff --git a/.venv/lib/python3.12/site-packages/scipy/interpolate/_rbf.py b/.venv/lib/python3.12/site-packages/scipy/interpolate/_rbf.py
new file mode 100644
index 0000000000000000000000000000000000000000..abc071b64d7faec5714396a8053cf5341d13e4e2
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/interpolate/_rbf.py
@@ -0,0 +1,292 @@
+"""rbf - Radial basis functions for interpolation/smoothing scattered N-D data.
+
+Written by John Travers , February 2007
+Based closely on Matlab code by Alex Chirokov
+Additional, large, improvements by Robert Hetland
+Some additional alterations by Travis Oliphant
+Interpolation with multi-dimensional target domain by Josua Sassen
+
+Permission to use, modify, and distribute this software is given under the
+terms of the SciPy (BSD style) license. See LICENSE.txt that came with
+this distribution for specifics.
+
+NO WARRANTY IS EXPRESSED OR IMPLIED. USE AT YOUR OWN RISK.
+
+Copyright (c) 2006-2007, Robert Hetland 
+Copyright (c) 2007, John Travers 
+
+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 Robert Hetland nor the names of any
+       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.
+"""
+import numpy as np
+
+from scipy import linalg
+from scipy.special import xlogy
+from scipy.spatial.distance import cdist, pdist, squareform
+from scipy._lib._array_api import xp_capabilities
+
+__all__ = ['Rbf']
+
+
+@xp_capabilities(out_of_scope=True)
+class Rbf:
+    """
+    Rbf(*args, **kwargs)
+
+    Class for radial basis function interpolation of functions from
+    N-D scattered data to an M-D domain (legacy).
+
+    .. legacy:: class
+
+        `Rbf` is legacy code, for new usage please use `RBFInterpolator`
+        instead.
+
+    Parameters
+    ----------
+    *args : arrays
+        x, y, z, ..., d, where x, y, z, ... are the coordinates of the nodes
+        and d is the array of values at the nodes
+    function : str or callable, optional
+        The radial basis function, based on the radius, r, given by the norm
+        (default is Euclidean distance); the default is 'multiquadric'::
+
+            'multiquadric': sqrt((r/self.epsilon)**2 + 1)
+            'inverse': 1.0/sqrt((r/self.epsilon)**2 + 1)
+            'gaussian': exp(-(r/self.epsilon)**2)
+            'linear': r
+            'cubic': r**3
+            'quintic': r**5
+            'thin_plate': r**2 * log(r)
+
+        If callable, then it must take 2 arguments (self, r). The epsilon
+        parameter will be available as self.epsilon. Other keyword
+        arguments passed in will be available as well.
+
+    epsilon : float, optional
+        Adjustable constant for gaussian or multiquadrics functions
+        - defaults to approximate average distance between nodes (which is
+        a good start).
+    smooth : float, optional
+        Values greater than zero increase the smoothness of the
+        approximation. 0 is for interpolation (default), the function will
+        always go through the nodal points in this case.
+    norm : str, callable, optional
+        A function that returns the 'distance' between two points, with
+        inputs as arrays of positions (x, y, z, ...), and an output as an
+        array of distance. E.g., the default: 'euclidean', such that the result
+        is a matrix of the distances from each point in ``x1`` to each point in
+        ``x2``. For more options, see documentation of
+        `scipy.spatial.distances.cdist`.
+    mode : str, optional
+        Mode of the interpolation, can be '1-D' (default) or 'N-D'. When it is
+        '1-D' the data `d` will be considered as 1-D and flattened
+        internally. When it is 'N-D' the data `d` is assumed to be an array of
+        shape (n_samples, m), where m is the dimension of the target domain.
+
+
+    Attributes
+    ----------
+    N : int
+        The number of data points (as determined by the input arrays).
+    di : ndarray
+        The 1-D array of data values at each of the data coordinates `xi`.
+    xi : ndarray
+        The 2-D array of data coordinates.
+    function : str or callable
+        The radial basis function. See description under Parameters.
+    epsilon : float
+        Parameter used by gaussian or multiquadrics functions. See Parameters.
+    smooth : float
+        Smoothing parameter. See description under Parameters.
+    norm : str or callable
+        The distance function. See description under Parameters.
+    mode : str
+        Mode of the interpolation. See description under Parameters.
+    nodes : ndarray
+        A 1-D array of node values for the interpolation.
+    A : internal property, do not use
+
+    See Also
+    --------
+    RBFInterpolator
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy.interpolate import Rbf
+    >>> rng = np.random.default_rng()
+    >>> x, y, z, d = rng.random((4, 50))
+    >>> rbfi = Rbf(x, y, z, d)  # radial basis function interpolator instance
+    >>> xi = yi = zi = np.linspace(0, 1, 20)
+    >>> di = rbfi(xi, yi, zi)   # interpolated values
+    >>> di.shape
+    (20,)
+
+    """
+    # Available radial basis functions that can be selected as strings;
+    # they all start with _h_ (self._init_function relies on that)
+    def _h_multiquadric(self, r):
+        return np.sqrt((1.0/self.epsilon*r)**2 + 1)
+
+    def _h_inverse_multiquadric(self, r):
+        return 1.0/np.sqrt((1.0/self.epsilon*r)**2 + 1)
+
+    def _h_gaussian(self, r):
+        return np.exp(-(1.0/self.epsilon*r)**2)
+
+    def _h_linear(self, r):
+        return r
+
+    def _h_cubic(self, r):
+        return r**3
+
+    def _h_quintic(self, r):
+        return r**5
+
+    def _h_thin_plate(self, r):
+        return xlogy(r**2, r)
+
+    # Setup self._function and do smoke test on initial r
+    def _init_function(self, r):
+        if isinstance(self.function, str):
+            self.function = self.function.lower()
+            _mapped = {'inverse': 'inverse_multiquadric',
+                       'inverse multiquadric': 'inverse_multiquadric',
+                       'thin-plate': 'thin_plate'}
+            if self.function in _mapped:
+                self.function = _mapped[self.function]
+
+            func_name = "_h_" + self.function
+            if hasattr(self, func_name):
+                self._function = getattr(self, func_name)
+            else:
+                functionlist = [x[3:] for x in dir(self)
+                                if x.startswith('_h_')]
+                raise ValueError("function must be a callable or one of " +
+                                 ", ".join(functionlist))
+            self._function = getattr(self, "_h_"+self.function)
+        elif callable(self.function):
+            allow_one = False
+            if hasattr(self.function, 'func_code') or \
+               hasattr(self.function, '__code__'):
+                val = self.function
+                allow_one = True
+            elif hasattr(self.function, "__call__"):
+                val = self.function.__call__.__func__
+            else:
+                raise ValueError("Cannot determine number of arguments to "
+                                 "function")
+
+            argcount = val.__code__.co_argcount
+            if allow_one and argcount == 1:
+                self._function = self.function
+            elif argcount == 2:
+                self._function = self.function.__get__(self, Rbf)
+            else:
+                raise ValueError("Function argument must take 1 or 2 "
+                                 "arguments.")
+
+        a0 = self._function(r)
+        if a0.shape != r.shape:
+            raise ValueError("Callable must take array and return array of "
+                             "the same shape")
+        return a0
+
+    def __init__(self, *args, **kwargs):
+        # `args` can be a variable number of arrays; we flatten them and store
+        # them as a single 2-D array `xi` of shape (n_args-1, array_size),
+        # plus a 1-D array `di` for the values.
+        # All arrays must have the same number of elements
+        self.xi = np.asarray([np.asarray(a, dtype=np.float64).flatten()
+                              for a in args[:-1]])
+        self.N = self.xi.shape[-1]
+
+        self.mode = kwargs.pop('mode', '1-D')
+
+        if self.mode == '1-D':
+            self.di = np.asarray(args[-1]).flatten()
+            self._target_dim = 1
+        elif self.mode == 'N-D':
+            self.di = np.asarray(args[-1])
+            self._target_dim = self.di.shape[-1]
+        else:
+            raise ValueError("Mode has to be 1-D or N-D.")
+
+        if not all([x.size == self.di.shape[0] for x in self.xi]):
+            raise ValueError("All arrays must be equal length.")
+
+        self.norm = kwargs.pop('norm', 'euclidean')
+        self.epsilon = kwargs.pop('epsilon', None)
+        if self.epsilon is None:
+            # default epsilon is the "the average distance between nodes" based
+            # on a bounding hypercube
+            ximax = np.amax(self.xi, axis=1)
+            ximin = np.amin(self.xi, axis=1)
+            edges = ximax - ximin
+            edges = edges[np.nonzero(edges)]
+            self.epsilon = np.power(np.prod(edges)/self.N, 1.0/edges.size)
+
+        self.smooth = kwargs.pop('smooth', 0.0)
+        self.function = kwargs.pop('function', 'multiquadric')
+
+        # attach anything left in kwargs to self for use by any user-callable
+        # function or to save on the object returned.
+        for item, value in kwargs.items():
+            setattr(self, item, value)
+
+        # Compute weights
+        if self._target_dim > 1:  # If we have more than one target dimension,
+            # we first factorize the matrix
+            self.nodes = np.zeros((self.N, self._target_dim), dtype=self.di.dtype)
+            lu, piv = linalg.lu_factor(self.A)
+            for i in range(self._target_dim):
+                self.nodes[:, i] = linalg.lu_solve((lu, piv), self.di[:, i])
+        else:
+            self.nodes = linalg.solve(self.A, self.di)
+
+    @property
+    def A(self):
+        # this only exists for backwards compatibility: self.A was available
+        # and, at least technically, public.
+        r = squareform(pdist(self.xi.T, self.norm))  # Pairwise norm
+        return self._init_function(r) - np.eye(self.N)*self.smooth
+
+    def _call_norm(self, x1, x2):
+        return cdist(x1.T, x2.T, self.norm)
+
+    def __call__(self, *args):
+        args = [np.asarray(x) for x in args]
+        if not all([x.shape == y.shape for x in args for y in args]):
+            raise ValueError("Array lengths must be equal")
+        if self._target_dim > 1:
+            shp = args[0].shape + (self._target_dim,)
+        else:
+            shp = args[0].shape
+        xa = np.asarray([a.flatten() for a in args], dtype=np.float64)
+        r = self._call_norm(xa, self.xi)
+        return np.dot(self._function(r), self.nodes).reshape(shp)
diff --git a/.venv/lib/python3.12/site-packages/scipy/interpolate/_rbfinterp.py b/.venv/lib/python3.12/site-packages/scipy/interpolate/_rbfinterp.py
new file mode 100644
index 0000000000000000000000000000000000000000..deea4e34338886b31016885c0747c2eed49ab886
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/interpolate/_rbfinterp.py
@@ -0,0 +1,540 @@
+"""Module for RBF interpolation."""
+import warnings
+from types import GenericAlias
+
+import numpy as np
+from scipy.spatial import KDTree
+
+from . import _rbfinterp_np
+from . import _rbfinterp_xp
+
+from scipy._lib._array_api import (
+    _asarray, array_namespace, xp_size, is_numpy, xp_capabilities
+)
+import scipy._external.array_api_extra as xpx
+
+
+__all__ = ["RBFInterpolator"]
+
+
+# These RBFs are implemented.
+_AVAILABLE = {
+    "linear",
+    "thin_plate_spline",
+    "cubic",
+    "quintic",
+    "multiquadric",
+    "inverse_multiquadric",
+    "inverse_quadratic",
+    "gaussian"
+    }
+
+
+# The shape parameter does not need to be specified when using these RBFs.
+_SCALE_INVARIANT = {"linear", "thin_plate_spline", "cubic", "quintic"}
+
+
+# For RBFs that are conditionally positive definite of order m, the interpolant
+# should include polynomial terms with degree >= m - 1. Define the minimum
+# degrees here. These values are from Chapter 8 of Fasshauer's "Meshfree
+# Approximation Methods with MATLAB". The RBFs that are not in this dictionary
+# are positive definite and do not need polynomial terms.
+_NAME_TO_MIN_DEGREE = {
+    "multiquadric": 0,
+    "linear": 0,
+    "thin_plate_spline": 1,
+    "cubic": 1,
+    "quintic": 2
+    }
+
+
+def _get_backend(xp):
+    if is_numpy(xp):
+        return _rbfinterp_np
+    return _rbfinterp_xp
+
+
+extra_note="""Only the default ``neighbors=None`` is Array API compatible.
+    If a non-default value of ``neighbors`` is given, the behavior is NumPy -only.
+
+"""
+
+@xp_capabilities(
+    skip_backends=[
+        ("dask.array", "linalg.lu is broken; array_api_extra#488"),
+        ("array_api_strict", "array-api#977, diag, view")
+    ],
+    extra_note=extra_note
+)
+class RBFInterpolator:
+    """Radial basis function interpolator in N ≥ 1 dimensions.
+
+    Parameters
+    ----------
+    y : (npoints, ndims) array_like
+        2-D array of data point coordinates.
+    d : (npoints, ...) array_like
+        N-D array of data values at `y`. The length of `d` along the first
+        axis must be equal to the length of `y`. Unlike some interpolators, the
+        interpolation axis cannot be changed.
+    neighbors : int, optional
+        If specified, the value of the interpolant at each evaluation point
+        will be computed using only this many nearest data points. All the data
+        points are used by default.
+    smoothing : float or (npoints, ) array_like, optional
+        Smoothing parameter. The interpolant perfectly fits the data when this
+        is set to 0. For large values, the interpolant approaches a least
+        squares fit of a polynomial with the specified degree. Default is 0.
+    kernel : str, optional
+        Type of RBF. This should be one of
+
+        - 'linear'               : ``-r``
+        - 'thin_plate_spline'    : ``r**2 * log(r)``
+        - 'cubic'                : ``r**3``
+        - 'quintic'              : ``-r**5``
+        - 'multiquadric'         : ``-sqrt(1 + r**2)``
+        - 'inverse_multiquadric' : ``1/sqrt(1 + r**2)``
+        - 'inverse_quadratic'    : ``1/(1 + r**2)``
+        - 'gaussian'             : ``exp(-r**2)``
+
+        Default is 'thin_plate_spline'.
+    epsilon : float, optional
+        Shape parameter that scales the input to the RBF. If `kernel` is
+        'linear', 'thin_plate_spline', 'cubic', or 'quintic', this defaults to
+        1 and can be ignored because it has the same effect as scaling the
+        smoothing parameter. Otherwise, this must be specified.
+    degree : int, optional
+        Degree of the added polynomial. For some RBFs the interpolant may not
+        be well-posed if the polynomial degree is too small. Those RBFs and
+        their corresponding minimum degrees are
+
+        - 'multiquadric'      : 0
+        - 'linear'            : 0
+        - 'thin_plate_spline' : 1
+        - 'cubic'             : 1
+        - 'quintic'           : 2
+
+        The default value is the minimum degree for `kernel` or 0 if there is
+        no minimum degree. Set this to -1 for no added polynomial.
+
+    Notes
+    -----
+    An RBF is a scalar valued function in N-dimensional space whose value at
+    :math:`x` can be expressed in terms of :math:`r=||x - c||`, where :math:`c`
+    is the center of the RBF.
+
+    An RBF interpolant for the vector of data values :math:`d`, which are from
+    locations :math:`y`, is a linear combination of RBFs centered at :math:`y`
+    plus a polynomial with a specified degree. The RBF interpolant is written
+    as
+
+    .. math::
+        f(x) = K(x, y) a + P(x) b,
+
+    where :math:`K(x, y)` is a matrix of RBFs with centers at :math:`y`
+    evaluated at the points :math:`x`, and :math:`P(x)` is a matrix of
+    monomials, which span polynomials with the specified degree, evaluated at
+    :math:`x`. The coefficients :math:`a` and :math:`b` are the solution to the
+    linear equations
+
+    .. math::
+        (K(x, y) + \\lambda I) a + P(y) b = d
+
+    and
+
+    .. math::
+        P(y)^T a = 0,
+
+    where :math:`\\lambda` is a non-negative smoothing parameter that controls
+    how well we want to fit the data. The data are fit exactly when the
+    smoothing parameter is 0.
+
+    The above system is uniquely solvable if the following requirements are
+    met:
+
+    - :math:`P(y)` must have full column rank. :math:`P(y)` always has full
+      column rank when `degree` is -1 or 0. When `degree` is 1,
+      :math:`P(y)` has full column rank if the data point locations are not
+      all collinear (N=2), coplanar (N=3), etc.
+    - If `kernel` is 'multiquadric', 'linear', 'thin_plate_spline',
+      'cubic', or 'quintic', then `degree` must not be lower than the
+      minimum value listed above.
+    - If `smoothing` is 0, then each data point location must be distinct.
+
+    When using an RBF that is not scale invariant ('multiquadric',
+    'inverse_multiquadric', 'inverse_quadratic', or 'gaussian'), an appropriate
+    shape parameter must be chosen (e.g., through cross validation). Smaller
+    values for the shape parameter correspond to wider RBFs. The problem can
+    become ill-conditioned or singular when the shape parameter is too small.
+
+    The memory required to solve for the RBF interpolation coefficients
+    increases quadratically with the number of data points, which can become
+    impractical when interpolating more than about a thousand data points.
+    To overcome memory limitations for large interpolation problems, the
+    `neighbors` argument can be specified to compute an RBF interpolant for
+    each evaluation point using only the nearest data points.
+
+    .. versionadded:: 1.7.0
+
+    See Also
+    --------
+    NearestNDInterpolator
+    LinearNDInterpolator
+    CloughTocher2DInterpolator
+
+    References
+    ----------
+    .. [1] Fasshauer, G., 2007. Meshfree Approximation Methods with Matlab.
+        World Scientific Publishing Co.
+
+    .. [2] http://amadeus.math.iit.edu/~fass/603_ch3.pdf
+
+    .. [3] Wahba, G., 1990. Spline Models for Observational Data. SIAM.
+
+    .. [4] http://pages.stat.wisc.edu/~wahba/stat860public/lect/lect8/lect8.pdf
+
+    Examples
+    --------
+    Demonstrate interpolating scattered data to a grid in 2-D.
+
+    >>> import numpy as np
+    >>> import matplotlib.pyplot as plt
+    >>> from scipy.interpolate import RBFInterpolator
+    >>> from scipy.stats.qmc import Halton
+
+    >>> rng = np.random.default_rng()
+    >>> xobs = 2*Halton(2, seed=rng).random(100) - 1
+    >>> yobs = np.sum(xobs, axis=1)*np.exp(-6*np.sum(xobs**2, axis=1))
+
+    >>> x1 = np.linspace(-1, 1, 50)
+    >>> xgrid = np.asarray(np.meshgrid(x1, x1, indexing='ij'))
+    >>> xflat = xgrid.reshape(2, -1).T     # make it a 2-D array
+    >>> yflat = RBFInterpolator(xobs, yobs)(xflat)
+    >>> ygrid = yflat.reshape(50, 50)
+
+    >>> fig, ax = plt.subplots()
+    >>> ax.pcolormesh(*xgrid, ygrid, vmin=-0.25, vmax=0.25, shading='gouraud')
+    >>> p = ax.scatter(*xobs.T, c=yobs, s=50, ec='k', vmin=-0.25, vmax=0.25)
+    >>> fig.colorbar(p)
+    >>> plt.show()
+
+    """
+
+    # generic type compatibility with scipy-stubs
+    __class_getitem__: classmethod = classmethod(GenericAlias)
+
+    def __init__(self, y, d,
+                 neighbors=None,
+                 smoothing=0.0,
+                 kernel="thin_plate_spline",
+                 epsilon=None,
+                 degree=None):
+        xp = array_namespace(y, d, smoothing)
+        _backend = _get_backend(xp)
+
+        if neighbors is not None:
+            if not is_numpy(xp):
+                raise NotImplementedError(
+                    "neighbors not None is numpy-only because it relies on KDTree"
+                )
+
+        y = _asarray(y, dtype=xp.float64, order="C", xp=xp)
+        if y.ndim != 2:
+            raise ValueError("`y` must be a 2-dimensional array.")
+
+        ny, ndim = y.shape
+
+        d = xp.asarray(d)
+        if xp.isdtype(d.dtype, 'complex floating'):
+            d_dtype = xp.complex128
+        else:
+            d_dtype = xp.float64
+        d = _asarray(d, dtype=d_dtype, order="C", xp=xp)
+
+        if d.shape[0] != ny:
+            raise ValueError(
+                f"Expected the first axis of `d` to have length {ny}."
+                )
+
+        d_shape = d.shape[1:]
+        d = xp.reshape(d, (ny, -1))
+        # If `d` is complex, convert it to a float array with twice as many
+        # columns. Otherwise, the LHS matrix would need to be converted to
+        # complex and take up 2x more memory than necessary.
+        d = d.view(float)     # NB not Array API compliant (and jax copies)
+
+        if isinstance(smoothing, int | float) or smoothing.shape == ():
+            smoothing = xp.full(ny, smoothing, dtype=xp.float64)
+        else:
+            smoothing = _asarray(smoothing, dtype=float, order="C", xp=xp)
+            if smoothing.shape != (ny,):
+                raise ValueError(
+                    "Expected `smoothing` to be a scalar or have shape "
+                    f"({ny},)."
+                    )
+
+        kernel = kernel.lower()
+        if kernel not in _AVAILABLE:
+            raise ValueError(f"`kernel` must be one of {_AVAILABLE}.")
+
+        if epsilon is None:
+            if kernel in _SCALE_INVARIANT:
+                epsilon = 1.0
+            else:
+                raise ValueError(
+                    "`epsilon` must be specified if `kernel` is not one of "
+                    f"{_SCALE_INVARIANT}."
+                    )
+        else:
+            epsilon = float(epsilon)
+
+        min_degree = _NAME_TO_MIN_DEGREE.get(kernel, -1)
+        if degree is None:
+            degree = max(min_degree, 0)
+        else:
+            degree = int(degree)
+            if degree < -1:
+                raise ValueError("`degree` must be at least -1.")
+            elif -1 < degree < min_degree:
+                warnings.warn(
+                    f"`degree` should not be below {min_degree} except -1 "
+                    f"when `kernel` is '{kernel}'."
+                    f"The interpolant may not be uniquely "
+                    f"solvable, and the smoothing parameter may have an "
+                    f"unintuitive effect.",
+                    UserWarning, stacklevel=2
+                )
+
+        if neighbors is None:
+            nobs = ny
+        else:
+            # Make sure the number of nearest neighbors used for interpolation
+            # does not exceed the number of observations.
+            neighbors = int(min(neighbors, ny))
+            nobs = neighbors
+
+        powers = _backend._monomial_powers(ndim, degree, xp)
+        # The polynomial matrix must have full column rank in order for the
+        # interpolant to be well-posed, which is not possible if there are
+        # fewer observations than monomials.
+        if powers.shape[0] > nobs:
+            raise ValueError(
+                f"At least {powers.shape[0]} data points are required when "
+                f"`degree` is {degree} and the number of dimensions is {ndim}."
+                )
+
+        if neighbors is None:
+            shift, scale, coeffs = _backend._build_and_solve_system(
+                y, d, smoothing, kernel, epsilon, powers,
+                xp
+            )
+
+            # Make these attributes private since they do not always exist.
+            self._shift = shift
+            self._scale = scale
+            self._coeffs = coeffs
+
+        else:
+            self._tree = KDTree(y)
+
+        self.y = y
+        self.d = d
+        self.d_shape = d_shape
+        self.d_dtype = d_dtype
+        self.neighbors = neighbors
+        self.smoothing = smoothing
+        self.kernel = kernel
+        self.epsilon = epsilon
+        self.powers = powers
+        self._xp = xp
+
+    def __setstate__(self, state):
+        tpl1, tpl2 = state
+        (self.y, self.d, self.d_shape, self.d_dtype, self.neighbors,
+         self.smoothing, self.kernel, self.epsilon, self.powers) = tpl1
+
+        if self.neighbors is None:
+            self._shift, self._scale, self._coeffs = tpl2
+        else:
+            self._tree, = tpl2
+
+        self._xp = array_namespace(self.y, self.d, self.smoothing)
+
+    def __getstate__(self):
+        tpl = (self.y, self.d, self.d_shape, self.d_dtype, self.neighbors,
+               self.smoothing, self.kernel, self.epsilon, self.powers
+        )
+
+        if self.neighbors is None:
+            tpl2 = (self._shift, self._scale, self._coeffs)
+        else:
+            tpl2 = (self._tree,)
+
+        return (tpl, tpl2)
+
+    def _chunk_evaluator(
+            self,
+            x,
+            y,
+            shift,
+            scale,
+            coeffs,
+            memory_budget=1000000
+    ):
+        """
+        Evaluate the interpolation while controlling memory consumption.
+        We chunk the input if we need more memory than specified.
+
+        Parameters
+        ----------
+        x : (Q, N) float ndarray
+            array of points on which to evaluate
+        y: (P, N) float ndarray
+            array of points on which we know function values
+        shift: (N, ) ndarray
+            Domain shift used to create the polynomial matrix.
+        scale : (N,) float ndarray
+            Domain scaling used to create the polynomial matrix.
+        coeffs: (P+R, S) float ndarray
+            Coefficients in front of basis functions
+        memory_budget: int
+            Total amount of memory (in units of sizeof(float)) we wish
+            to devote for storing the array of coefficients for
+            interpolated points. If we need more memory than that, we
+            chunk the input.
+
+        Returns
+        -------
+        (Q, S) float ndarray
+        Interpolated array
+        """
+        _backend = _get_backend(self._xp)
+
+        nx, ndim = x.shape
+        if self.neighbors is None:
+            nnei = y.shape[0]
+        else:
+            nnei = self.neighbors
+        # in each chunk we consume the same space we already occupy
+        chunksize = memory_budget // (self.powers.shape[0] + nnei) + 1
+        if chunksize <= nx:
+            out = self._xp.empty((nx, self.d.shape[1]), dtype=self._xp.float64)
+            for i in range(0, nx, chunksize):
+                chunk = _backend.compute_interpolation(
+                    x[i:i + chunksize, :],
+                    y,
+                    self.kernel,
+                    self.epsilon,
+                    self.powers,
+                    shift,
+                    scale,
+                    coeffs,
+                    self._xp
+                )
+                out = xpx.at(out, (slice(i, i + chunksize), slice(None,))).set(chunk)
+        else:
+            out = _backend.compute_interpolation(
+                x,
+                y,
+                self.kernel,
+                self.epsilon,
+                self.powers,
+                shift,
+                scale,
+                coeffs,
+                self._xp
+            )
+        return out
+
+    def __call__(self, x):
+        """Evaluate the interpolant at `x`.
+
+        Parameters
+        ----------
+        x : (npts, ndim) array_like
+            Evaluation point coordinates.
+
+        Returns
+        -------
+        ndarray, shape (npts, )
+            Values of the interpolant at `x`.
+
+        """
+        x = _asarray(x, dtype=self._xp.float64, order="C", xp=self._xp)
+        if x.ndim != 2:
+            raise ValueError("`x` must be a 2-dimensional array.")
+
+        nx, ndim = x.shape
+        if ndim != self.y.shape[1]:
+            raise ValueError("Expected the second axis of `x` to have length "
+                             f"{self.y.shape[1]}.")
+
+        # Our memory budget for storing RBF coefficients is
+        # based on how many floats in memory we already occupy
+        # If this number is below 1e6 we just use 1e6
+        # This memory budget is used to decide how we chunk
+        # the inputs
+        memory_budget = max(xp_size(x) + xp_size(self.y) + xp_size(self.d), 1_000_000)
+
+        if self.neighbors is None:
+            out = self._chunk_evaluator(
+                x,
+                self.y,
+                self._shift,
+                self._scale,
+                self._coeffs,
+                memory_budget=memory_budget)
+        else:
+            # XXX: this relies on KDTree, hence is numpy-only until KDTree is converted
+            _build_and_solve_system = _get_backend(np)._build_and_solve_system
+
+            # Get the indices of the k nearest observation points to each
+            # evaluation point.
+            _, yindices = self._tree.query(x, self.neighbors)
+            if self.neighbors == 1:
+                # `KDTree` squeezes the output when neighbors=1.
+                yindices = yindices[:, None]
+
+            # Multiple evaluation points may have the same neighborhood of
+            # observation points. Make the neighborhoods unique so that we only
+            # compute the interpolation coefficients once for each
+            # neighborhood.
+            yindices = np.sort(yindices, axis=1)
+            yindices, inv = np.unique(yindices, return_inverse=True, axis=0)
+            inv = np.reshape(inv, (-1,))  # flatten, we need 1-D indices
+            # `inv` tells us which neighborhood will be used by each evaluation
+            # point. Now we find which evaluation points will be using each
+            # neighborhood.
+            xindices = [[] for _ in range(len(yindices))]
+            for i, j in enumerate(inv):
+                xindices[j].append(i)
+
+            out = np.empty((nx, self.d.shape[1]), dtype=float)
+            for xidx, yidx in zip(xindices, yindices):
+                # `yidx` are the indices of the observations in this
+                # neighborhood. `xidx` are the indices of the evaluation points
+                # that are using this neighborhood.
+                xnbr = x[xidx]
+                ynbr = self.y[yidx]
+                dnbr = self.d[yidx]
+                snbr = self.smoothing[yidx]
+                shift, scale, coeffs = _build_and_solve_system(
+                    ynbr,
+                    dnbr,
+                    snbr,
+                    self.kernel,
+                    self.epsilon,
+                    self.powers,
+                    np
+                )
+                out[xidx] = self._chunk_evaluator(
+                    xnbr,
+                    ynbr,
+                    shift,
+                    scale,
+                    coeffs,
+                    memory_budget=memory_budget)
+
+        out = out.view(self.d_dtype)    # NB not Array API compliant (and jax copies)
+        out = self._xp.reshape(out, (nx, ) + self.d_shape)
+        return out
diff --git a/.venv/lib/python3.12/site-packages/scipy/interpolate/_rbfinterp_common.py b/.venv/lib/python3.12/site-packages/scipy/interpolate/_rbfinterp_common.py
new file mode 100644
index 0000000000000000000000000000000000000000..528fe7a97187d1f46557833bfa218bab245b7251
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/interpolate/_rbfinterp_common.py
@@ -0,0 +1,32 @@
+# Impl routines common for all backends
+from itertools import combinations_with_replacement
+from math import comb
+
+def _monomial_powers_impl(ndim, degree):
+    """Return the powers for each monomial in a polynomial.
+
+    Parameters
+    ----------
+    ndim : int
+        Number of variables in the polynomial.
+    degree : int
+        Degree of the polynomial.
+
+    Returns
+    -------
+    (nmonos, ndim) int ndarray
+        Array where each row contains the powers for each variable in a
+        monomial.
+
+    """
+    nmonos = comb(degree + ndim, ndim)
+    out = [[0]*ndim for _ in range(nmonos)]
+    count = 0
+    for deg in range(degree + 1):
+        for mono in combinations_with_replacement(range(ndim), deg):
+            # `mono` is a tuple of variables in the current monomial with
+            # multiplicity indicating power (e.g., (0, 1, 1) represents x*y**2)
+            for var in mono:
+                out[count][var] += 1
+            count += 1
+    return out
diff --git a/.venv/lib/python3.12/site-packages/scipy/interpolate/_rbfinterp_np.py b/.venv/lib/python3.12/site-packages/scipy/interpolate/_rbfinterp_np.py
new file mode 100644
index 0000000000000000000000000000000000000000..d73e9bac8a10e70b92387e3392beaed7a8b12d0f
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/interpolate/_rbfinterp_np.py
@@ -0,0 +1,95 @@
+import numpy as np
+from numpy.linalg import LinAlgError
+from scipy.linalg.lapack import get_lapack_funcs
+from ._rbfinterp_common import _monomial_powers_impl
+
+from ._rbfinterp_pythran import (
+    _build_system as _pythran_build_system,
+    _build_evaluation_coefficients as _pythran_build_evaluation_coefficients,
+    _polynomial_matrix as _pythran_polynomial_matrix
+)
+
+
+dsysv = get_lapack_funcs('sysv', dtype=np.float64, ilp64="preferred")
+
+
+# trampolines for pythran-compiled functions to drop the `xp` argument
+def _build_evaluation_coefficients(
+    x, y, kernel, epsilon, powers, shift, scale, xp
+):
+    return _pythran_build_evaluation_coefficients(
+        x, y, kernel, epsilon, powers, shift, scale
+    )
+
+def polynomial_matrix(x, powers, xp):
+    return _pythran_polynomial_matrix(x, powers)
+
+
+def _monomial_powers(ndim, degree, xp):
+    out = _monomial_powers_impl(ndim, degree)
+    out = np.asarray(out, dtype=np.int64)
+    if len(out) == 0:
+        out = out.reshape(0, ndim)
+    return out
+
+
+def _build_system(y, d, smoothing, kernel, epsilon, powers, xp):
+    return _pythran_build_system(y, d, smoothing, kernel, epsilon, powers)
+
+
+def _build_and_solve_system(y, d, smoothing, kernel, epsilon, powers, xp):
+    """Build and solve the RBF interpolation system of equations.
+
+    Parameters
+    ----------
+    y : (P, N) float ndarray
+        Data point coordinates.
+    d : (P, S) float ndarray
+        Data values at `y`.
+    smoothing : (P,) float ndarray
+        Smoothing parameter for each data point.
+    kernel : str
+        Name of the RBF.
+    epsilon : float
+        Shape parameter.
+    powers : (R, N) int ndarray
+        The exponents for each monomial in the polynomial.
+
+    Returns
+    -------
+    coeffs : (P + R, S) float ndarray
+        Coefficients for each RBF and monomial.
+    shift : (N,) float ndarray
+        Domain shift used to create the polynomial matrix.
+    scale : (N,) float ndarray
+        Domain scaling used to create the polynomial matrix.
+
+    """
+    lhs, rhs, shift, scale = _build_system(
+        y, d, smoothing, kernel, epsilon, powers, xp
+        )
+    _, _, coeffs, info = dsysv(lhs, rhs, overwrite_a=True, overwrite_b=True)
+    if info < 0:
+        raise ValueError(f"The {-info}-th argument had an illegal value.")
+    elif info > 0:
+        msg = "Singular matrix."
+        nmonos = powers.shape[0]
+        if nmonos > 0:
+            pmat = polynomial_matrix((y - shift)/scale, powers, xp)
+            rank = np.linalg.matrix_rank(pmat)
+            if rank < nmonos:
+                msg = (
+                    "Singular matrix. The matrix of monomials evaluated at "
+                    "the data point coordinates does not have full column "
+                    f"rank ({rank}/{nmonos})."
+                    )
+
+        raise LinAlgError(msg)
+
+    return shift, scale, coeffs
+
+def compute_interpolation(x, y, kernel, epsilon, powers, shift, scale, coeffs, xp):
+    vec = _build_evaluation_coefficients(
+        x, y, kernel, epsilon, powers, shift, scale, xp
+    )
+    return vec @ coeffs
diff --git a/.venv/lib/python3.12/site-packages/scipy/interpolate/_rbfinterp_pythran.cpython-312-x86_64-linux-gnu.so b/.venv/lib/python3.12/site-packages/scipy/interpolate/_rbfinterp_pythran.cpython-312-x86_64-linux-gnu.so
new file mode 100644
index 0000000000000000000000000000000000000000..f64a3f93ea7802e43cea93c10a20dea8bc29c4b7
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/interpolate/_rbfinterp_pythran.cpython-312-x86_64-linux-gnu.so
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:221cfc526838f78a7e9d18da0c06ec819a652c987b52c081a48a2c9bf38e78cc
+size 248184
diff --git a/.venv/lib/python3.12/site-packages/scipy/interpolate/_rbfinterp_xp.py b/.venv/lib/python3.12/site-packages/scipy/interpolate/_rbfinterp_xp.py
new file mode 100644
index 0000000000000000000000000000000000000000..57cf3da5d967c5b2eafaddacca5a039580ac55d1
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/interpolate/_rbfinterp_xp.py
@@ -0,0 +1,266 @@
+"""
+'Generic' Array API backend for RBF interpolation.
+
+The general logic is this: `_rbfinterp.py` implements the user API and calls
+into either `_rbfinterp_np` (the "numpy backend"), or `_rbfinterp_xp` (the
+"generic backend".
+
+The numpy backend offloads performance-critical computations to the
+pythran-compiled `_rbfinterp_pythran` extension. This way, the call chain is
+
+    _rbfinterp.py <-- _rbfinterp_np.py <-- _rbfinterp_pythran.py
+
+The "generic" backend here is a drop-in replacement of the API of
+`_rbfinterp_np.py` for use in `_rbfinterp.py` with non-numpy arrays.
+
+The implementation closely follows `_rbfinterp_np + _rbfinterp_pythran`, with
+the following differences:
+
+  -  We used vectorized code not explicit loops in `_build_system` and
+     `_build_evaluation_coefficients`; this is more torch/jax friendly;
+  - RBF kernels are also "vectorized" and not scalar: they receive an
+    array of norms not a single norm;
+  - RBF kernels accept an extra xp= argument;
+
+In general, we would prefer less code duplication. The main blocker ATM is
+that pythran cannot compile functions with an xp= argument where xp is numpy.
+"""
+from numpy.linalg import LinAlgError
+from ._rbfinterp_common import _monomial_powers_impl
+
+
+def _monomial_powers(ndim, degree, xp):
+    out = _monomial_powers_impl(ndim, degree)
+    out = xp.asarray(out)
+    if out.shape[0] == 0:
+        out = xp.reshape(out, (0, ndim))
+    return out
+
+
+def _build_and_solve_system(y, d, smoothing, kernel, epsilon, powers, xp):
+    """Build and solve the RBF interpolation system of equations.
+
+    Parameters
+    ----------
+    y : (P, N) float ndarray
+        Data point coordinates.
+    d : (P, S) float ndarray
+        Data values at `y`.
+    smoothing : (P,) float ndarray
+        Smoothing parameter for each data point.
+    kernel : str
+        Name of the RBF.
+    epsilon : float
+        Shape parameter.
+    powers : (R, N) int ndarray
+        The exponents for each monomial in the polynomial.
+
+    Returns
+    -------
+    coeffs : (P + R, S) float ndarray
+        Coefficients for each RBF and monomial.
+    shift : (N,) float ndarray
+        Domain shift used to create the polynomial matrix.
+    scale : (N,) float ndarray
+        Domain scaling used to create the polynomial matrix.
+
+    """
+    lhs, rhs, shift, scale = _build_system(
+        y, d, smoothing, kernel, epsilon, powers, xp
+        )
+    try:
+        coeffs = xp.linalg.solve(lhs, rhs)
+    except Exception:
+        # Best-effort attempt to emit a helpful message.
+        # `_rbfinterp_np` backend gives better diagnostics; it is hard to
+        # match it in a backend-agnostic way: e.g. jax emits no error at all,
+        # and instead returns an array of nans for a singular `lhs`.
+        msg = "Singular matrix"
+        nmonos = powers.shape[0]
+        if nmonos > 0:
+            pmat = polynomial_matrix((y - shift)/scale, powers, xp=xp)
+            rank = xp.linalg.matrix_rank(pmat)
+            if rank < nmonos:
+                msg = (
+                    "Singular matrix. The matrix of monomials evaluated at "
+                    "the data point coordinates does not have full column "
+                    f"rank ({rank}/{nmonos})."
+                    )
+        raise LinAlgError(msg)
+
+    return shift, scale, coeffs
+
+
+def linear(r, xp):
+    return -r
+
+
+def thin_plate_spline(r, xp):
+    # NB: changed w.r.t. pythran, vectorized
+    return xp.where(r == 0, 0, r**2 * xp.log(r))
+
+
+def cubic(r, xp):
+    return r**3
+
+
+def quintic(r, xp):
+    return -r**5
+
+
+def multiquadric(r, xp):
+    return -xp.sqrt(r**2 + 1)
+
+
+def inverse_multiquadric(r, xp):
+    return 1.0 / xp.sqrt(r**2 + 1.0)
+
+
+def inverse_quadratic(r, xp):
+    return 1.0 / (r**2 + 1.0)
+
+
+def gaussian(r, xp):
+    return xp.exp(-r**2)
+
+
+NAME_TO_FUNC = {
+   "linear": linear,
+   "thin_plate_spline": thin_plate_spline,
+   "cubic": cubic,
+   "quintic": quintic,
+   "multiquadric": multiquadric,
+   "inverse_multiquadric": inverse_multiquadric,
+   "inverse_quadratic": inverse_quadratic,
+   "gaussian": gaussian
+   }
+
+
+def kernel_matrix(x, kernel_func, xp):
+    """Evaluate RBFs, with centers at `x`, at `x`."""
+    return kernel_func(
+        xp.linalg.vector_norm(x[None, :, :] - x[:, None, :], axis=-1), xp
+    )
+
+
+def polynomial_matrix(x, powers, xp):
+    """Evaluate monomials, with exponents from `powers`, at `x`."""
+    return xp.prod(x[:, None, :] ** powers, axis=-1)
+
+
+def _build_system(y, d, smoothing, kernel, epsilon, powers, xp):
+    """Build the system used to solve for the RBF interpolant coefficients.
+
+    Parameters
+    ----------
+    y : (P, N) float ndarray
+        Data point coordinates.
+    d : (P, S) float ndarray
+        Data values at `y`.
+    smoothing : (P,) float ndarray
+        Smoothing parameter for each data point.
+    kernel : str
+        Name of the RBF.
+    epsilon : float
+        Shape parameter.
+    powers : (R, N) int ndarray
+        The exponents for each monomial in the polynomial.
+
+    Returns
+    -------
+    lhs : (P + R, P + R) float ndarray
+        Left-hand side matrix.
+    rhs : (P + R, S) float ndarray
+        Right-hand side matrix.
+    shift : (N,) float ndarray
+        Domain shift used to create the polynomial matrix.
+    scale : (N,) float ndarray
+        Domain scaling used to create the polynomial matrix.
+
+    """
+    s = d.shape[1]
+    r = powers.shape[0]
+    kernel_func = NAME_TO_FUNC[kernel]
+
+    # Shift and scale the polynomial domain to be between -1 and 1
+    mins = xp.min(y, axis=0)
+    maxs = xp.max(y, axis=0)
+    shift = (maxs + mins)/2
+    scale = (maxs - mins)/2
+    # The scale may be zero if there is a single point or all the points have
+    # the same value for some dimension. Avoid division by zero by replacing
+    # zeros with ones.
+    scale = xp.where(scale == 0.0, 1.0, scale)
+
+    yeps = y*epsilon
+    yhat = (y - shift)/scale
+
+    out_kernels  = kernel_matrix(yeps, kernel_func, xp)
+    out_poly = polynomial_matrix(yhat, powers, xp)
+
+    lhs = xp.concat(
+        [
+         xp.concat((out_kernels, out_poly), axis=1),
+         xp.concat((out_poly.T, xp.zeros((r, r))), axis=1)
+        ]
+    , axis=0) + xp.diag(xp.concat([smoothing, xp.zeros(r)]))
+
+    rhs = xp.concat([d, xp.zeros((r, s))], axis=0)
+
+    return lhs, rhs, shift, scale
+
+
+def _build_evaluation_coefficients(
+    x, y, kernel, epsilon, powers, shift, scale, xp
+):
+    """Construct the coefficients needed to evaluate
+    the RBF.
+
+    Parameters
+    ----------
+    x : (Q, N) float ndarray
+        Evaluation point coordinates.
+    y : (P, N) float ndarray
+        Data point coordinates.
+    kernel : str
+        Name of the RBF.
+    epsilon : float
+        Shape parameter.
+    powers : (R, N) int ndarray
+        The exponents for each monomial in the polynomial.
+    shift : (N,) float ndarray
+        Shifts the polynomial domain for numerical stability.
+    scale : (N,) float ndarray
+        Scales the polynomial domain for numerical stability.
+
+    Returns
+    -------
+    (Q, P + R) float ndarray
+
+    """
+    kernel_func = NAME_TO_FUNC[kernel]
+
+    yeps = y*epsilon
+    xeps = x*epsilon
+    xhat = (x - shift)/scale
+
+    # NB: changed w.r.t. pythran
+    vec = xp.concat(
+        [
+            kernel_func(
+                xp.linalg.vector_norm(
+                    xeps[:, None, :] - yeps[None, :, :], axis=-1
+                ), xp
+            ),
+            xp.prod(xhat[:, None, :] ** powers, axis=-1)
+        ], axis=-1
+    )
+
+    return vec
+
+
+def compute_interpolation(x, y, kernel, epsilon, powers, shift, scale, coeffs, xp):
+    vec = _build_evaluation_coefficients(
+        x, y, kernel, epsilon, powers, shift, scale, xp
+    )
+    return vec @ coeffs
diff --git a/.venv/lib/python3.12/site-packages/scipy/interpolate/_regrid.py b/.venv/lib/python3.12/site-packages/scipy/interpolate/_regrid.py
new file mode 100644
index 0000000000000000000000000000000000000000..e78aa12fe6341771765dbba91f1d2cc41fa4996f
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/interpolate/_regrid.py
@@ -0,0 +1,1109 @@
+"""
+Regrid (2-D smoothing B-splines via separable 1-D FITPACK kernels)
+==================================================================
+
+1) Overview
+-----------
+This module fits a bivariate tensor-product B-spline surface to gridded data
+`Z[i, j]` sampled on strictly increasing coordinates `x[i]`, `y[j]`. It mirrors
+the adaptive spirit of FITPACK's REGRID/fpgrre (knot growth + smoothing
+parameter search to meet a target residual `s`) while keeping the control flow
+explicit in Python and returning a 2-D `NdBSpline`.
+
+**Key conventions**
+- **Penalty scaling is 1/p** - *same as FITPACK*. The augmented system stacks
+  `(D / p)` under the data matrix. Smaller `p` -> stronger smoothing; larger `p`
+  -> weaker smoothing (approaching interpolation).
+- `p == -1` is used **as a sentinel for `p = ∞`** (interpolatory limit): when
+  seen, the solver omits penalty rows entirely.
+
+2) Mathematics (and how this differs from FITPACK's REGRID)
+-----------------------------------------------------------
+Let `A_x`, `A_y` be banded 1-D design matrices and `D_x`, `D_y` the banded
+1-D roughness (difference) matrices returned by FITPACK/Dierckx's 1-D APIs
+(`data_matrix`, `disc`). The 2-D smoothing objective is
+
+    minimize  ||A c - z||^2 + (1/p) ||D c||^2,            (1)
+
+implemented by the **augmented** least squares system
+
+    [ A ] c ~ [ z ]
+    [D/p]     [ 0 ].
+
+**Same as FITPACK:** Equation (1) uses the *1/p* convention.
+**Different in this module:** We realize the 2-D problem by composing **1-D**
+banded operators in two separable passes (x then y), instead of calling a
+monolithic 2-D routine. This makes the mathematics transparent while producing
+the same normal equations structure that REGRID targets internally.
+
+3) Residual energy: definition and use
+--------------------------------------
+After solving on the current knots (initially at the interpolatory limit,
+`p = ∞`), we evaluate the surface and form
+
+    R = Z - Zhat,                         fp = sum(R[i, j]^2).
+
+We then **project** residual energy to knot spans along each axis:
+
+- Row energy  `row_energy[i] = sum(R[i, j]^2, j)`  -> accumulated into `fpintx`.
+- Column energy `col_energy[j] = sum(R[i, j]^2, i)` -> accumulated into `fpinty`.
+
+These per-span energies guide **adaptive knot insertion**: the algorithm picks
+high-energy spans (skipping zero-length ones) and inserts data-aligned knots
+(e.g., median sample within the span), with simple batch sizing and headroom
+limits. This is conceptually the same idea as REGRID's `fpint` arrays; here it
+is implemented explicitly and vectorized in Python for clarity.
+
+4) Solver used here vs. FITPACK's REGRID
+----------------------------------------
+**This module (separable 1-D composition):**
+- Uses **1-D FITPACK/Dierckx kernels** (`data_matrix`, `disc`, `qr_reduce`,
+  `fpback`) to solve 2-D via two passes:
+  1) augment/QR/backsolve along **x**, producing an intermediate;
+  2) augment/QR/backsolve along **y**, producing the coefficient grid `C`.
+- The augmented rows are stacked as `[A; D/p]` (1/p scaling, **same as FITPACK**).
+- If `fp > s` after knot growth, performs a **scalar search in `p`** using a
+  ratio-of-roots routine; `p == -1` is treated as `p = ∞` for the interpolatory
+  reference without penalty rows.
+
+**FITPACK REGRID (monolithic 2-D routine):**
+- Implements the same mathematical objective and **1/p** penalty scaling,
+  but inside a specialized, fully 2-D Fortran routine with in-place Givens/QR
+  and a rational update for `p`.
+- Handles residual partitioning, knot insertion, and `p` updates internally.
+
+**Practical difference:** We build the 2-D solve from **1-D building blocks**,
+which keeps each stage observable/testable and uses the same low-level kernels
+as FITPACK, but without relying on the single monolithic REGRID entry point.
+
+5) Execution flow (who calls whom)
+----------------------------------
+
+**Top-level**
+1. `_regrid`
+   - Validates shapes/monotonicity and normalizes `bbox`.
+   - Dispatches to `_regrid_fitpack(...)`.
+
+**Core driver**
+2. `_regrid_fitpack`
+   - Clips inputs to `bbox` via `_apply_bbox_grid` -> `(x_fit, y_fit, Z_fit)`.
+   - If `s == 0` (interpolation path):
+     - Build initial not-a-knot vectors: `tx = _not_a_knot(x_fit, kx)`,
+       `ty = _not_a_knot(y_fit, ky)`.
+     - Build design matrices: `(Ax, Ay, Q) = build_design_matrices(...)`.
+     - Solve once at `p = -1` (inf): `C0, fp = _solve_2d_fitpack(...)`.
+     - Return `return_NdBSpline(...)`.
+   - Else (`s > 0`, smoothing with adaptive knots):
+     - Initialize clamped no-interior-knot vectors with
+       `_initialise_knots` (for x and y).
+     - **Knot-growth loop** (up to `len(x_fit)+len(y_fit)` iterations):
+       1) Build design matrices: `(Ax, Ay, Q) = build_design_matrices(...)`.
+       2) Interpolatory reference solve (`p = -1`): `C0, fp = _solve_2d_fitpack(...)`.
+       3) If both `tx`, `ty` are at minimal size, record `fp0 = fp`
+          (used to bracket the p-search).
+       4) If `fp < s`: **stop growth** and proceed to p-search / finalize.
+       5) Compute residuals for knot insertion:
+          - Convert packed to CSR once per axis for evaluation:
+            `_Ax = Ax.tocsr(...)`, `_Ay = Ay.tocsr(...)`
+          - Evaluate `Z0 = _Ax @ C0 @ _Ay.T`, residual `R = Z_fit - Z0`.
+       6) Insert knots on alternating axes using energy heuristics:
+          - If last axis was `y`, grow `tx` with
+            `_add_knots(..., residuals=np.sum(R**2, axis=1), ...)`.
+          - Else, grow `ty` with `_add_knots(..., residuals=np.sum(R**2, axis=0), ...)`.
+          - Update `fpold`, `nplus{ x|y }`, `last_axis`.
+     - If growth ended with both axes still minimal: return `return_NdBSpline(...)`.
+     - **Finite-p smoothing (if needed):**
+       - Build 1-D penalty operators: `(Drx, _, ncx) = disc(tx, kx)`,
+         `(Dry, _, ncy) = disc(ty, ky)`, wrap as `PackedMatrix`.
+       - Rebuild design matrices on the final `(tx, ty)`.
+       - Run `_p_search_hit_s(...)` to find `p*` such that `fp(p*) ~ s`:
+         - Internally constructs `F(...)` which evaluates `fp(p)`
+           by calling `_solve_2d_fitpack(...)`.
+         - Uses `root_rati` on `g(p) = fp(p) - s` with the interpolatory
+           reference at `p = inf` and `fp0` bracket.
+       - Return `return_NdBSpline(...)`.
+
+**Separable solver (used by both interpolation and p-search)**
+3. `_solve_2d_fitpack`
+   - Forms augmented banded systems via `_stack_augmented_fitpack`:
+     - X-side: `Ax_aug = [Ax; Dx/p]` if `p != -1`, else just `Ax`.
+     - Y-side: `Ay_aug = [Ay; Dy/p]` if `p != -1`, else just `Ay`.
+     - Pads RHS `Q` with zeros when penalties are stacked.
+   - **Stage X**: `_dierckx.qr_reduce(Ax_aug, ...)` then
+     `_dierckx.fpback(...)` -> intermediate `T`.
+   - Transpose `T` to feed Y solves column-wise; pad if needed.
+   - **Stage Y**: `_dierckx.qr_reduce(Ay_aug, ...)` then
+     `_dierckx.fpback(...)` -> coefficients `C`.
+   - Build CSR design matrices once: `_Ax = Ax.tocsr(...)`, `_Ay = Ay.tocsr(...)`.
+   - Evaluate `zhat = _Ax @ C.T @ _Ay.T`, compute `fp = ||Z_fit - zhat||^2`.
+   - Return `C.T` (in `(nx_coef, ny_coef)` layout) and `fp`.
+
+**Helpers**
+- `_apply_bbox_grid(...)` - slices to `(x_fit, y_fit, Z_fit)`.
+- `build_design_matrices(...)` - wraps `_dierckx.data_matrix` and
+  returns `PackedMatrix` wrappers + `Q`.
+- `_initialise_knots(...)`, `_add_knots(...)` - FITPACK-style knot bookkeeping/growth.
+- `disc(...)` - 1-D roughness operators (packed band form).
+- `F` + `root_rati` - maps `p -> fp(p)` and finds `p*` with `fp(p*) ~ s`.
+- `return_NdBSpline(...)` - packs `(tx, ty, C)` into an `NdBSpline`.
+"""
+import numpy as np
+from scipy.interpolate._ndbspline import NdBSpline
+from scipy.interpolate._fitpack_repro import (
+    root_rati, disc, add_knot, _not_a_knot)
+from . import _dierckx      # type: ignore[attr-defined]
+from scipy.sparse import csr_array
+from scipy._lib._util import _validate_int
+
+def _ndbspline_call_like_bivariate(ndbs, x, y, dx=0, dy=0, grid=True):
+    """
+    Evaluate a 2D `NdBSpline` like a classical bivariate API.
+
+    Parameters
+    ----------
+    ndbs : NdBSpline
+        A 2D spline object (``len(ndbs.t) == 2``).
+    x, y : array_like
+        Sample locations. If ``grid=True``, these must be 1-D strictly
+        increasing vectors. If ``grid=False``, they can be broadcastable
+        arrays of the same shape.
+    dx, dy : int, optional
+        Derivative orders along `x` and `y` respectively, by default 0.
+    grid : bool, optional
+        If True, evaluate on the cartesian product of `x` and `y`;
+        otherwise treat `(x, y)` as paired coordinates, by default True.
+
+    Returns
+    -------
+    ndarray or (ndarray, dict)
+        Evaluated values with shape:
+        - ``(len(x), len(y), ...)`` if ``grid=True``.
+        - ``x.shape + ...`` if ``grid=False``.
+
+    Raises
+    ------
+    ValueError
+        If `ndbs` is not 2D, derivatives are negative, or monotonicity checks fail.
+
+    Notes
+    -----
+    This is a thin convenience wrapper around ``NdBSpline.__call__`` with input
+    validation and optional profiling.
+    """
+    if len(ndbs.t) != 2:
+        raise ValueError("ndbs must be a 2D NdBSpline (len(t) == 2).")
+
+    dx = _validate_int(dx, 'dx')
+    dy = _validate_int(dy, 'dy')
+    if dx < 0 or dy < 0:
+        raise ValueError("order of derivative must be positive or zero")
+
+    trailing = ndbs.c.shape[2:]
+    x = np.asarray(x)
+    y = np.asarray(y)
+
+    if grid:
+        if x.size == 0 or y.size == 0:
+            vals = np.zeros((x.size, y.size) + trailing, dtype=ndbs.c.dtype)
+            return vals
+
+        if (x.size >= 2) and (not np.all(np.diff(x) >= 0.0)):
+            raise ValueError("x must be strictly increasing when `grid` is True")
+        if (y.size >= 2) and (not np.all(np.diff(y) >= 0.0)):
+            raise ValueError("y must be strictly increasing when `grid` is True")
+
+        X, Y = np.meshgrid(x, y, indexing="ij")
+        xi = np.stack((X, Y), axis=-1)  # (len(x), len(y), 2)
+
+        vals = ndbs(xi, nu=(dx, dy), extrapolate=ndbs.extrapolate)
+
+        return vals
+    else:
+        if x.shape != y.shape:
+            x, y = np.broadcast_arrays(x, y)
+
+        if x.size == 0:
+            return np.zeros(x.shape + trailing, dtype=ndbs.c.dtype)
+        xi = np.stack((x.ravel(), y.ravel()), axis=-1)
+        vals = ndbs(xi, nu=(dx, dy), extrapolate=ndbs.extrapolate)
+        return vals.reshape(x.shape + trailing)
+
+
+def return_NdBSpline(fp, tck, degrees):
+    """
+    Build a 2D ``NdBSpline`` from knot vectors and a coefficient grid.
+
+    Parameters
+    ----------
+    fp : float
+        Residual sum of squares of the produced fit (kept for upstream use).
+    tck : tuple
+        Tuple ``(tx, ty, C)`` where ``tx``, ``ty`` are knot vectors and ``C``
+        is a coefficient array with shape ``(nx - kx - 1, ny - ky - 1)`` or
+        a compatible shape that can be reshaped to that.
+    degrees : tuple of int
+        Degrees ``(kx, ky)`` along x and y.
+
+    Returns
+    -------
+    NdBSpline
+        The constructed 2D spline.
+
+    Notes
+    -----
+    Only repacks the coefficient grid; ``fp`` is not used internally here.
+    """
+    nx, ny = len(tck[0]), len(tck[1])
+    kx, ky = degrees
+    c = tck[2].reshape(nx - kx - 1, ny - ky - 1)
+    return NdBSpline((tck[0], tck[1]), c, degrees)
+
+
+class PackedMatrix:
+    """A simplified CSR format for when non-zeros in each row are consecutive.
+
+    Assuming that each row of an `(m, nc)` matrix 1) only has `nz` non-zeros, and
+    2) these non-zeros are consecutive, we only store an `(m, nz)` matrix of
+    non-zeros and a 1D array of row offsets. This way, a row `i` of the original
+    matrix A is ``A[i, offset[i]: offset[i] + nz]``.
+
+    """
+    def __init__(self, a, offset, nc):
+        self.a = a
+        self.offset = offset
+        self.nc = nc
+
+    @property
+    def shape(self):
+        return self.a.shape[0], self.nc
+
+    def todense(self):
+        out = np.zeros(self.shape)
+        nelem = self.a.shape[1]
+        for i in range(out.shape[0]):
+            nel = min(self.nc - self.offset[i], nelem)
+            out[i, self.offset[i]:self.offset[i] + nel] = self.a[i, :nel]
+        return out
+
+    def tocsr(self, k, m, len_t):
+        # Inlined from https://github.com/scipy/scipy/blob/v1.16.2/scipy/interpolate/_bsplines.py#L455-L466
+        data = self.a.ravel()
+
+        # Convert from per-row offsets to the CSR indices/indptr format
+        indices = np.repeat(self.offset, k+1).reshape(-1, k+1)
+        indices = indices + np.arange(k+1, dtype=self.offset.dtype)
+        indices = indices.ravel()
+
+        indptr = np.arange(0, (m + 1) * (k + 1), k + 1,
+                           dtype=self.offset.dtype)
+
+        return csr_array(
+            (data, indices, indptr),
+            shape=(m, len_t - k - 1)
+    )
+
+
+def _stack_augmented_fitpack(A, D, nc, k, p):
+    """
+    Builds augmented banded matrix.
+
+    Parameters
+    ----------
+    A : PackedMatrix
+        Banded data/design matrix for one axis (from `_dierckx.data_matrix`).
+    D : PackedMatrix
+        Banded roughness (difference) penalty matrix for the same axis
+        (from `disc`).
+    nc : int
+        Number of top (data) rows from `A` to include.
+    k : int
+        Spline degree (used only for sizing in the current implementation).
+    p : float
+        Smoothing parameter. The effective penalization term is scaled as **1/p**:
+        larger `p` means *less* smoothing (approaching interpolation).
+        If `p == -1`, it signals *p -> inf*, i.e. a pure interpolatory system
+        with **no** penalty rows appended.
+
+    Returns
+    -------
+    AA : ndarray
+        Augmented banded matrix with `A` stacked over `(D / p)` when `p != -1`.
+    offset : ndarray
+        Concatenated band offsets for the augmented matrix.
+    nc : int
+        Returned unchanged for downstream convenience.
+    """
+    if p == -1:
+        return A.a.copy(), A.offset.copy(), nc
+
+    nz = k + 1
+    AA = np.zeros((nc + D.shape[0], k + 2), dtype=float)
+    AA[:nc, :nz] = A.a[:nc, :]
+    AA[nc:, :] = D.a / p
+    offset = np.concatenate((A.offset, D.offset))
+    return AA, offset, nc
+
+def _solve_2d_fitpack(Ax, Ay, Q, p,
+                      kx, tx, x_x,
+                      ky, ty, x_y, z,
+                      Dx=None, Dy=None):
+    """
+    Solve the 2-D tensor-product spline system using separable banded QR.
+
+    ================================================================
+    Mathematical model (step by step, plain text)
+    ================================================================
+
+    Shapes:
+        Z      : (mx, my)  -> original data
+        Ax, Ay : design matrices for x and y
+        Dx, Dy : roughness penalty matrices for x and y
+        C      : (nx, ny)  -> spline coefficients to solve for
+
+    Surface approximation:
+        Zhat = Ax * C * Ay^T
+
+    Objective (smoothing formulation):
+        minimize ||Ax*C*Ay^T - Z||^2 + (1/p)*(||Dx*C||^2 + ||C*Dy^T||^2)
+
+    In practice (FITPACK-style separable approach), we solve this in two stages:
+
+    --------------------------------------------------------
+    Stage 1 (x-direction solve for all y-columns together):
+    --------------------------------------------------------
+
+        For each column of Z:
+            minimize ||Ax*T - Z||^2 + (1/p)*||Dx*T||^2
+
+        This is equivalent to the augmented least-squares system:
+            [Ax]       [Z]
+            [Dx/p] * T = [0]
+
+        i.e.  minimize || [Ax; Dx/p]*T - [Z; 0] ||^2
+
+        The solution T is obtained by QR reduction and back-substitution.
+
+    --------------------------------------------------------
+    Stage 2 (y-direction solve using transposed result):
+    --------------------------------------------------------
+        Now treat T^T as the new RHS for the y-direction:
+            minimize ||Ay*C^T - T^T||^2 + (1/p)*||Dy*C^T||^2
+
+        Equivalent to augmented system:
+            [Ay]       [T^T]
+            [Dy/p] * C^T = [0]
+
+        i.e.  minimize || [Ay; Dy/p]*C^T - [T^T; 0] ||^2
+
+        Solving this gives C^T (then transposed back to C).
+
+    --------------------------------------------------------
+    Interpolation limit:
+    --------------------------------------------------------
+        If p == -1, penalties are omitted (Dx, Dy are not stacked).
+        The solver behaves as a near-interpolating system.
+
+    --------------------------------------------------------
+    Residual computation:
+    --------------------------------------------------------
+        Zhat = Ax * C * Ay^T
+        R    = Z - Zhat
+        fp   = sum(R^2)
+
+    Parameters
+    ----------
+    Ax, Ay : PackedMatrix
+        Banded data matrices for the x and y axes.
+    Q : ndarray, shape (mx, my)
+        RHS data grid (copied from `Z`).
+    p : float
+        Smoothing parameter. The penalty term is scaled as **1/p**.
+        Setting `p == -1` signals *p -> inf* (interpolation, omit penalty).
+    kx, ky : int
+        Spline degrees along x and y.
+    tx, ty : ndarray
+        Knot vectors along x and y.
+    x_x, x_y : ndarray
+        Sample coordinates.
+    z : ndarray
+        Original data grid for residual evaluation.
+    Dx, Dy : ndarray
+        Banded roughness penalty matrices for x and y.
+        Optional, Only needed when ``p != -1``.
+
+    Returns
+    -------
+    C : ndarray
+        2-D B-spline coefficient grid.
+    fp : float
+        Residual sum of squares between fitted surface and `z`.
+    R : ndarray, shape (mx, my)
+        Residual matrix ``z - zhat``, where ``zhat = Ax @ C @ Ay.T``.
+
+    Notes
+    -----
+    This performs two separable QR solves (x then y), each augmented by
+    `(D / p)` when `p != -1`.  Setting `p = -1` skips all penalty rows,
+    yielding an interpolatory surface.  The resulting coefficients and residual
+    follow the same conventions as FITPACK's `fpgrre`.
+    """
+    # Dummy unit weights for FITPACK fpback APIs.
+    w_x = np.ones_like(x_x)
+    w_y = np.ones_like(x_y)
+
+    # https://github.com/scipy/scipy/blob/v1.16.2/scipy/interpolate/fitpack/fpgrre.f#L97-L105
+    # Build the augmented banded matrix for x:
+    #   - If p != -1, stack (Dx / p) under Ax for FITPACK-style smoothing.
+    #   - If p == -1, _stack_augmented_fitpack omits the penalty part entirely.
+    # Returns:
+    #   Ax_aug      : augmented banded matrix (data [+ penalty]).
+    #   offset_aug_x: band offsets compatible with Ax_aug.
+    #   nc_augx     : number of top data rows within Ax_aug (== ncx).
+    Ax_aug, offset_aug_x, nc_augx = _stack_augmented_fitpack(
+        Ax, Dx, Ax.shape[0], kx, p)
+    nc_x = Ax.nc
+
+    # Same for y: build Ay_aug with (Dy / p) stacked if p != -1.
+    Ay_aug, offset_aug_y, nc_augy = _stack_augmented_fitpack(
+        Ay, Dy, Ay.shape[0], ky, p)
+    nc_y = Ay.nc
+
+    # If we stacked penalty rows on the x side, the RHS must be padded with zeros
+    # to match the augmented row count for the QR reduction call.
+    if p != -1: # https://github.com/scipy/scipy/blob/v1.16.2/scipy/interpolate/fitpack/fpgrre.f#L97
+        # Dx.shape[0] is the number of penalty rows; add that many zero rows
+        # so Ax_aug and Q have compatible leading dimensions for in-place QR.
+        # https://github.com/scipy/scipy/blob/v1.16.2/scipy/interpolate/fitpack/fpgrre.f#L110-L118
+        Q = np.vstack([Q, np.zeros((Dx.shape[0], Q.shape[1]), dtype=float)])
+
+    # https://github.com/scipy/scipy/blob/v1.16.2/scipy/interpolate/fitpack/fpgrre.f#L106-L175
+    # Perform in-place banded QR reduction of the x-augmented system:
+    # This orthogonalizes/eliminates along x for all RHS columns in Q simultaneously.
+    # After this, fpback can do x-direction back-substitution to
+    # get c^T (partial coeffs).
+    _dierckx.qr_reduce(Ax_aug, offset_aug_x, nc_augx, Q)
+
+    # https://github.com/scipy/scipy/blob/v1.16.2/scipy/interpolate/fitpack/fpgrre.f#L246-L253
+    # Back-substitute along x to solve the reduced system:
+    #   cT has shape (ncoef_x, num_y_data) in this calling pattern, i.e. per y-column.
+    # The API uses:
+    #   Ax_aug, nc_augx: reduced upper structure
+    #   x_x, tx, kx, w_x: x-sample grid, knot vector, degree, and (unit) weights
+    #   Q: RHS (current)
+    # fpback returns shape (nc_x, num_y_data)
+    T, _, _ = _dierckx.fpback(
+        Ax_aug, nc_x, x_x,
+        Q, tx, kx, w_x,
+        Q, False
+    )
+
+    # We now want to treat the *y*-direction solve with these as the new RHS.
+    # Transpose so each column corresponds to a y-solve RHS consistently.
+    Q = np.ascontiguousarray(T.T)
+
+    # If we stacked penalty rows on the y side, pad RHS with zeros to match Ay_aug.
+    if p != -1: # https://github.com/scipy/scipy/blob/v1.16.2/scipy/interpolate/fitpack/fpgrre.f#L97
+        # https://github.com/scipy/scipy/blob/v1.16.2/scipy/interpolate/fitpack/fpgrre.f#L110-L118
+        Q = np.vstack([Q, np.zeros((Dy.shape[0], Q.shape[1]), dtype=float)])
+
+    # https://github.com/scipy/scipy/blob/v1.16.2/scipy/interpolate/fitpack/fpgrre.f#L176-L245
+    # Perform in-place banded QR reduction along y for all columns of Q.
+    _dierckx.qr_reduce(Ay_aug, offset_aug_y, nc_augy, Q)
+
+    # https://github.com/scipy/scipy/blob/v1.16.2/scipy/interpolate/fitpack/fpgrre.f#L254-L269
+    # Final back-substitution along y:
+    # Returns:
+    #   C  : coefficient matrix with shape (nc_y, nc_x)
+    #   fp : FITPACK's internal residual metric from the y-solve
+    #        (we recompute below anyway)
+    C, _, fp = _dierckx.fpback(
+        Ay_aug, nc_y,
+        x_y, Q, ty, ky, w_y,    # y-grid, y-knots, degree, weights
+        Q,                      # RHS -> solution becomes coefficients along y
+        False
+    )
+
+    # Build explicit design matrices to evaluate the fitted surface:
+    # _Ax: [mx × nx_coef], _Ay: [my × ny_coef]
+    # Note: We call PackedMatrix.tocsr here because matrix multiplication
+    # with the packed banded format (returned by _dierckx.data_matrix)
+    # is not implemented. PackedMatrix.tocsr returns the design matrix,
+    # in CSR format, that supports standard @ operations for residual
+    # evaluation and diagnostics.
+    _Ax = Ax.tocsr(kx, x_x.shape[0], len(tx))
+    _Ay = Ay.tocsr(ky, x_y.shape[0], len(ty))
+
+    # Evaluate the fitted surface: zhat = Ax * C^T * Ay^T
+    # Note: C currently aligns so that C.T matches x-first multiplication order.
+    zhat = _Ax @ C.T @ _Ay.T
+
+    # Compute residual matrix R and fp in one pass; return R so callers that
+    # need per-span energy for knot placement can reuse it directly instead of
+    # recomputing zhat a second time.
+    R = z - zhat
+    fp = np.sum(np.square(R))
+
+    # Return coefficients in the conventional (nx_coef, ny_coef) orientation,
+    # fp, and the residual matrix R.
+    return C.T, fp, R
+
+class F:
+    """
+    Callable wrapper for computing `fp(p)` for a fixed spline configuration.
+
+    Parameters
+    ----------
+    Ax, Ay : PackedMatrix
+        Banded data matrices.
+    Dx, Dy : PackedMatrix
+        Banded penalty matrices.
+    kx, ky : int
+        Degrees along x and y.
+    tx, ty : ndarray
+        Knot vectors along x and y.
+    x_x, x_y : ndarray
+        Sample coordinates.
+    w_x, w_y : ndarray
+        Weights (usually ones).
+    z : ndarray
+        Data grid for computing the residual.
+
+    Attributes
+    ----------
+    C : ndarray
+        Coefficient matrix from the most recent solve.
+    fp : float
+        Residual value from the most recent solve.
+
+    Notes
+    -----
+    The penalty is applied as **1/p**, so smaller `p` values yield heavier
+    smoothing. Setting `p == -1` corresponds to *p = inf*, i.e. interpolation.
+    Intended for use by `_p_search_hit_s` to iteratively evaluate `fp(p)`.
+    """
+
+    def __init__(self, Ax, Dx, Ay, Dy, Q,
+                 kx, tx, x_x, ky, ty,
+                 x_y, z):
+        self.Ax = Ax
+        self.Dx = Dx
+        self.Ay = Ay
+        self.Dy = Dy
+        self.Q = Q
+        self.kx = kx
+        self.tx = tx
+        self.x_x = x_x
+        self.ky = ky
+        self.ty = ty
+        self.x_y = x_y
+        self.z = z
+
+    def __call__(self, p):
+        # _stack_augmented_fitpack always allocates fresh arrays (np.zeros for
+        # p != -1, .copy() for p == -1), so qr_reduce never writes back into
+        # the original PackedMatrix.a buffers.  The four copies below are
+        # therefore unnecessary and are removed to reduce memory pressure.
+        C, fp, _ = _solve_2d_fitpack(
+            self.Ax, self.Ay, self.Q.copy(),
+            p, self.kx, self.tx, self.x_x,
+            self.ky, self.ty, self.x_y, self.z,
+            Dx=self.Dx, Dy=self.Dy)
+        self.C = C
+        self.fp = fp
+        return fp
+
+# https://github.com/scipy/scipy/blob/v1.16.2/scipy/interpolate/fitpack/fpregr.f#L301-L367
+def _p_search_hit_s(
+    Ax, Dx, Ay, Dy, Q, kx,
+    tx, x_x, ky, ty, x_y, z, s, fp0, *,
+    p_init=1.0, tol_rel=1e-3, maxit=40):
+    """
+    Search for a smoothing parameter `p` such that `fp(p) ~ s`.
+
+    Parameters
+    ----------
+    Ax, Ay : PackedMatrix
+        Banded data matrices.
+    Dx, Dy : PackedMatrix
+        Banded penalty matrices.
+    Q : ndarray
+        RHS data grid (copy of `Z`).
+    kx, ky : int
+        Spline degrees.
+    tx, ty : ndarray
+        Knot vectors.
+    x_x, x_y : ndarray
+        Sample coordinates.
+    w_x, w_y : ndarray
+        Sample weights.
+    z : ndarray
+        Original data grid for residuals.
+    s : float
+        Target smoothing residual (`fp` target).
+    fp0 : float or None
+        Residual at `p = inf` (interpolatory limit,
+                               represented by `p == -1`).
+    p_init : float, optional
+        Starting guess for the finite `p` search, default 1.0.
+    tol_rel : float, optional
+        Relative tolerance for matching `fp(p)` to `s`.
+    maxit : int, optional
+        Maximum iterations for the root search.
+
+    Returns
+    -------
+    p_star : float
+        Smoothing parameter for which `fp(p_star)` ~ `s`.
+    C_star : ndarray
+        Coefficient grid corresponding to `p_star`.
+    fp_star : float
+        Residual at `p_star`.
+
+    Notes
+    -----
+    The solver treats `p == -1` as *p = inf* (interpolatory, no penalty).
+    For finite `p`, the penalty scales as **1/p** - smaller `p` increases
+    smoothing. A ratio-of-roots search (`root_rati`) iteratively adjusts `p`
+    until the residual `fp(p)` matches the target `s` within tolerance.
+    """
+
+    fp_at = F(Ax, Dx, Ay, Dy, Q, kx,
+              tx, x_x, ky, ty, x_y, z)
+
+    def g(p):
+        return fp_at(p) - s
+
+    fpms = g(-1)
+
+    bracket = ((0.0, fp0 - s), (np.inf, fpms))
+    ftol = max(s * tol_rel, 1e-12)
+
+    r = root_rati(g, p_init, bracket, ftol, maxit=maxit)
+    p_star = r.root
+    fp_star = fp_at(p_star)
+    C_star = fp_at.C
+
+    return p_star, C_star, fp_star
+
+
+def _apply_bbox_grid(x, y, Z, bbox):
+    """
+    Restrict (x, y, Z) to a rectangular bounding box.
+
+    Parameters
+    ----------
+    x, y : ndarray
+        Monotonic sample coordinates.
+    Z : ndarray, shape (len(x), len(y))
+        Data grid.
+    bbox : sequence of 4 scalars or None
+        ``(xb, xe, yb, ye)``; any element may be None to skip clipping.
+
+    Returns
+    -------
+    x_fit, y_fit, Z_fit : ndarray
+        Sliced arrays restricted to bbox.
+    ix, iy : slice or ndarray
+        Indexers mapping from full arrays to the restricted ones.
+
+    Raises
+    ------
+    ValueError
+        If bbox is invalid or excludes all samples along an axis.
+    """
+    if all([bboxi is None for bboxi in bbox]):
+        return x, y, Z, slice(None), slice(None)
+
+    xb, xe, yb, ye = bbox
+    if not (xb < xe and yb < ye):
+        raise ValueError("bbox must satisfy xb < xe and yb < ye")
+
+    ix = np.where((x >= xb) & (x <= xe))[0]
+    iy = np.where((y >= yb) & (y <= ye))[0]
+    if ix.size == 0 or iy.size == 0:
+        raise ValueError("bbox excludes all samples in x or y.")
+
+    return x[ix], y[iy], Z[np.ix_(ix, iy)], np.s_[ix], np.s_[iy]
+
+
+def _build_design_matrices(x, y, z, tx, ty, kx, ky):
+
+    w_x = np.ones_like(x)
+    w_y = np.ones_like(y)
+
+    Ax, offset_x, nc_x = _dierckx.data_matrix(x, tx, kx, w_x)
+    Ay, offset_y, nc_y = _dierckx.data_matrix(y, ty, ky, w_y)
+    Q = z.copy()
+
+    return (PackedMatrix(Ax, offset_x, nc_x),
+            PackedMatrix(Ay, offset_y, nc_y),
+            Q)
+
+
+def _initialise_knots(m, xb, xe, k, nest=None):
+    """
+    Initialize a non-periodic knot vector.
+
+    Parameters
+    ----------
+    m : int
+        Number of data points (equivalent to len(x) if x were provided).
+    xb, xe : float
+        Domain endpoints used to seed the initial knot vector with no internal knots.
+    k : int
+        Spline degree.
+    nest : int, optional
+        Storage cap for knots. If None, defaults to max(m + k + 1, 2*k + 3).
+        Must satisfy nest >= 2*(k + 1); otherwise a ValueError is raised.
+
+    Returns
+    -------
+    t : 1-D ndarray
+        Initial knot vector with no internal knots: [xb]*(k+1) + [xe]*(k+1).
+    nest : int
+        The finalized storage cap for knots.
+    nmin : int
+        Lower bound on knot count.
+    nmax : int
+        Upper bound on knot count.
+
+    What this does
+    --------------
+    - Computes defaults and bounds used by FITPACK-style knot growth:
+        * nest: storage cap for knots (defaults to max(m + k + 1, 2*k + 3))
+        * nmin: minimal knot count (2*(k+1))
+        * nmax: maximal knot count (m + k + 1)
+    - Returns an initial knot vector with no internal knots:
+        t = [xb]*(k+1) + [xe]*(k+1)
+    """
+    if nest is None:
+        nest = max(m + k + 1, 2*k + 3)
+    else:
+        if nest < 2*(k + 1):
+            raise ValueError(f"`nest` too small: {nest = } < 2*(k+1) = {2*(k+1)}.")
+
+    nmin = 2*(k + 1)    # the number of knots for an LSQ polynomial approximation
+    nmax = m + k + 1  # the number of knots for the spline interpolation
+
+    # start from no internal knots
+    t = np.asarray([xb]*(k+1) + [xe]*(k+1))
+
+    return t, nest, nmin, nmax
+
+
+TOL = 0.001
+
+def _add_knots(x, k, s, t, nmin, nmax,
+               nest, fp, fpold,
+               residuals, nplus):
+    """
+    Knot-growth helper for knot-finding loop (non-periodic).
+
+    Parameters
+    ----------
+    x : 1-D ndarray
+        Strictly increasing sample coordinates.
+    k : int
+        Spline degree.
+    s : float
+        Target smoothing.
+    t : 1-D ndarray
+        Current knot vector to be grown.
+    nmin, nmax : int
+        Lower/upper bounds on knot count (from initialisation).
+    nest : int
+        Storage cap for total knots.
+    fp, fpold : float
+        Current and previous residual sums of squares. Used to update nplus.
+    residuals : 1-D ndarray
+        Most recent residual signal used by `add_knot` to decide placement.
+    nplus : int
+        Previous iteration's proposed number of knots; used to update the next nplus.
+
+    Returns
+    -------
+    t_new, nplus : tuple
+        Updated knot vector and the nplus chosen for this step.
+        If n >= nmax, t_new is a not-a-knot layout. If n >= nest, t_new is the
+        current vector respecting the storage cap.
+
+    What this function does
+    -----------------------
+    - Assumes the caller has already decided to GROW (i.e., checks
+      like |fp - s| < acc or fp < s has FAILED).
+    - Updates nplus (how many knots to add next) using the FITPACK heuristic
+      based on the previous improvement (delta = fpold - fp).
+    - Inserts up to nplus new internal knots using `add_knot(x, t, k, residuals)`.
+    - Stops early if storage or interpolation caps are reached:
+        * if n >= nmax: switch to interpolation layout (not-a-knot) and return
+        * if n >= nest: return current t respecting storage cap
+
+    How it compares with _fitpack_repro.py::_generate_knots_impl
+    -------------------------------------------------------------
+    Similarities:
+      1) Same growth logic for nplus:
+         - Use delta = fpold - fp with ratio fpms/delta
+         - Apply min/max caps (doubling and halving behavior)
+      3) Same storage guard:
+         - If n reaches nest, stop and return current t
+      4) Same end behavior at the "interpolating" cap:
+         - When n >= nmax, switch to not-a-knot layout and return
+
+    Differences:
+      1) API style:
+         - _generate_knots_impl is a generator that yields trial knot vectors and
+           recomputes residuals/fp internally on each iteration.
+         - `_add_knots` is a stateful helper that only grows knots; it expects the
+           caller to handle residual computation and fp/fpold updates between calls.
+      2) Periodicity:
+         - _generate_knots_impl supports periodic=True.
+         - `_add_knots` is non-periodic only; it uses not-a-knot when n >= nmax.
+      3) Residual computation:
+         - _generate_knots_impl calls an internal residual routine each iteration.
+         - `_add_knots` does not compute residuals; the caller must supply:
+             residuals (used by add_knot), fp, fpold.
+      4) Return values:
+         - _generate_knots_impl yields multiple t's and eventually returns None.
+         - `_add_knots` returns:
+             * (t_new, nplus) after inserting knots,
+             * (not_a_knot_t, nplus) if n >= nmax,
+             * (t, nplus) if n >= nest (storage cap).
+    """
+
+    acc = s * TOL
+    n = t.size
+    fpms = fp - s
+
+    # ### c  increase the number of knots. ###
+
+    # c  determine the number of knots nplus we are going to add.
+    # https://github.com/scipy/scipy/blob/v1.16.2/scipy/interpolate/fitpack/fpregr.f#L248-L261
+    if n == nmin:
+        nplus = 1
+    else:
+        delta = fpold - fp
+        npl1 = int(nplus * fpms / delta) if delta > acc else nplus*2
+        nplus = min(nplus*2, max(npl1, nplus//2, 1))
+
+    # actually add knots
+    # https://github.com/scipy/scipy/blob/v1.16.2/scipy/interpolate/fitpack/fpregr.f#L271-L281
+    # https://github.com/scipy/scipy/blob/v1.16.2/scipy/interpolate/fitpack/fpregr.f#L288-L295
+    for j in range(nplus):
+        t = add_knot(x, t, k, residuals)
+
+        # check if we have enough knots already
+
+        n = t.shape[0]
+        # c  if n = nmax, sinf(x) is an interpolating spline.
+        # c  if n=nmax we locate the knots as for interpolation.
+        # https://github.com/scipy/scipy/blob/v1.16.2/scipy/interpolate/fitpack/fpregr.f#L276-L279
+        if n >= nmax:
+            # https://github.com/scipy/scipy/blob/v1.16.2/scipy/interpolate/fitpack/fpregr.f#L93-L109
+            # https://github.com/scipy/scipy/blob/v1.16.2/scipy/interpolate/fitpack/fpregr.f#L114-L131
+            return _not_a_knot(x, k), nplus
+
+        # c  if n=nest we cannot increase the number of knots because of
+        # c  the storage capacity limitation.
+        # https://github.com/scipy/scipy/blob/v1.16.2/scipy/interpolate/fitpack/fpregr.f#L280
+        # https://github.com/scipy/scipy/blob/v1.16.2/scipy/interpolate/fitpack/fpregr.f#L294
+        if n >= nest:
+            return t, nplus
+
+    return t, nplus
+
+
+def _regrid_fitpack(
+    x, y, Z, *, kx=3, ky=3, s=0.0,
+    maxit=50, nestx=None, nesty=None,
+    bbox=None):
+    """
+    Core adaptive bivariate spline fitter using the 1/p-penalty convention.
+
+    Parameters
+    ----------
+    x, y : array_like
+        Strictly increasing coordinate vectors.
+    Z : array_like, shape (len(x), len(y))
+        Data grid.
+    kx, ky : int, optional
+        Spline degrees along x and y, default 3 (cubic).
+    s : float, optional
+        Target residual (`fp` target). `s = 0` requests an interpolatory
+        surface; `s > 0` triggers smoothing with penalty weight **1/p**.
+    maxit : int, optional
+        Maximum iterations for the `p`-search when smoothing, default 50.
+    nestx, nesty : int or None
+        Max coefficient counts per axis (nesting limits).
+    bbox : sequence of 4 scalars
+        Optional domain limits `(xb, xe, yb, ye)`. Use `None` entries to skip.
+
+    Returns
+    -------
+    NdBSpline
+        Fitted 2-D spline surface.
+
+    Notes
+    -----
+    The internal smoothing parameter `p` follows the **inverse**-penalty
+    rule: penalty term is 1/p.  Hence, larger `p` -> weaker smoothing
+    (approaching interpolation), while smaller `p` -> stronger smoothing.
+    A sentinel value `p == -1` is interpreted as *p = inf*, corresponding to
+    an exact (interpolatory) fit.
+
+    The iterative process adaptively grows knot vectors based on residual
+    energy and optionally performs a 1-D search over `p` to satisfy `fp ~ s`.
+    """
+    x_fit, y_fit, Z_fit, _, _ = _apply_bbox_grid(x, y, Z, bbox)
+
+    if x_fit.size < (kx + 1) or y_fit.size < (ky + 1):
+        raise ValueError(
+            f"Not enough samples inside bbox for degrees (kx={kx}, ky={ky}). "
+            f"Need at least k+1 per axis: ({kx+1}, {ky+1}). "
+            f"Got ({x_fit.size}, {y_fit.size})."
+        )
+
+    xb = float(x_fit[0] if bbox[0] is None else bbox[0])
+    xe = float(x_fit[-1] if bbox[1] is None else bbox[1])
+    yb = float(y_fit[0] if bbox[2] is None else bbox[2])
+    ye = float(y_fit[-1] if bbox[3] is None else bbox[3])
+
+    p = -1
+
+    if s == 0.0:
+        if nestx is not None or nesty is not None:
+            raise ValueError("s == 0 is interpolation only")
+        # For special-case k=1 (e.g., Lyche and Morken, Eq.(2.16)),
+        # _not_a_knot produces desired knot vector
+        tx = _not_a_knot(x_fit, kx)
+        ty = _not_a_knot(y_fit, ky)
+        (Ax, Ay, Q) = _build_design_matrices(
+             x_fit, y_fit, Z, tx, ty, kx, ky)
+        C0, fp, _ = _solve_2d_fitpack(Ax, Ay, Q, p,
+                                     kx, tx, x_fit, ky, ty,
+                                     y_fit, Z_fit)
+        return return_NdBSpline(fp, (tx, ty, C0), (kx, ky))
+
+    tx, nestx, nminx, nmaxx = _initialise_knots(x_fit.size, xb, xe, kx, nest=nestx)
+    ty, nesty, nminy, nmaxy = _initialise_knots(y_fit.size, yb, ye, ky, nest=nesty)
+
+    fpold = None
+    last_axis = "y"
+    mpm = len(x) + len(y)
+    fp0 = None
+    nplusx = None
+    nplusy = None
+
+    # https://github.com/scipy/scipy/blob/v1.16.2/scipy/interpolate/fitpack/fpregr.f#L51-L300
+    for _ in range(mpm):
+
+        (Ax, Ay, Q) = _build_design_matrices(
+             x_fit, y_fit, Z, tx, ty, kx, ky)
+        # _solve_2d_fitpack now returns R = Z_fit - zhat alongside C0 and fp,
+        # so we can reuse it directly for knot placement instead of
+        # recomputing zhat a second time via tocsr + dense matmul.
+        C0, fp, R = _solve_2d_fitpack(Ax, Ay, Q, p,
+                                      kx, tx, x_fit,
+                                      ky, ty, y_fit,
+                                      Z_fit)
+
+        # https://github.com/scipy/scipy/blob/v1.16.2/scipy/interpolate/fitpack/fpregr.f#L190
+        # https://github.com/scipy/scipy/blob/v1.16.2/scipy/interpolate/fitpack/fpregr.f#L224
+        if len(tx) == nminx and len(ty) == nminy:
+            fp0 = fp
+
+        if fp < s:
+            break
+
+        # https://github.com/scipy/scipy/blob/v1.16.2/scipy/interpolate/fitpack/fpregr.f#L265-L295
+        if last_axis == "y":
+            tx, nplusx = _add_knots(
+                x_fit, kx, s, tx, nmin=nminx, nmax=nmaxx,
+                nest=nestx, fp=fp, fpold=fpold,
+                residuals=np.sum(R**2, axis=1),
+                nplus=nplusx)
+            last_axis = "x"
+        else:
+            ty, nplusy = _add_knots(
+                y_fit, ky, s, ty, nmin=nminy, nmax=nmaxy,
+                nest=nesty, fp=fp, fpold=fpold,
+                residuals=np.sum(R**2, axis=0),
+                nplus=nplusy)
+            last_axis = "y"
+
+        # When both knot vectors have reached their maximum size no further
+        # growth is possible; break to avoid redundant loop iterations.
+        if len(tx) >= nmaxx and len(ty) >= nmaxy:
+            break
+
+        fpold = fp
+
+    if len(tx) == nminx and len(ty) == nminy:
+        return return_NdBSpline(fp, (tx, ty, C0), (kx, ky))
+
+    p = 1
+    Drx, offset_dx, nc_dx = disc(tx, kx)
+    Dry, offset_dy, nc_dy = disc(ty, ky)
+    Drx = PackedMatrix(Drx, offset_dx, nc_dx)
+    Dry = PackedMatrix(Dry, offset_dy, nc_dy)
+    (Ax, Ay, Q) = _build_design_matrices(
+        x_fit, y_fit, Z, tx, ty, kx, ky)
+    _, C_sm, fp_sm = _p_search_hit_s(Ax, Drx, Ay, Dry, Q,
+                                     kx, tx, x_fit, ky,
+                                     ty, y_fit, Z_fit, s,
+                                     fp0, maxit=maxit, p_init=p)
+    return return_NdBSpline(fp_sm, (tx, ty, C_sm), (kx, ky))
+
+
+def _regrid(x, y, z, *, bbox=None, kx=3, ky=3, s=0.0, maxit=50):
+    """
+    Interface for 2-D smoothing B-spline fitting (1/p penalty form).
+
+    Parameters
+    ----------
+    x, y : array_like
+        Strictly increasing 1-D coordinate vectors.
+    z : array_like, shape (len(x), len(y))
+        Data grid.
+    bbox : sequence of 4 scalars
+        Optional bounding box ``(xb, xe, yb, ye)``; use ``None`` entries to disable.
+    kx, ky : int, optional
+        Spline degrees along `x` and `y`, default cubic (3).
+    s : float, optional
+        Target smoothing residual (`fp` target). Must satisfy ``s >= 0``.
+        The underlying formulation uses a **1/p** penalty, meaning:
+        - small `p` -> heavy smoothing,
+        - large `p` -> light smoothing (approaching interpolation).
+        Setting `p == -1` internally denotes *p = inf*, i.e. a pure interpolant.
+    maxit : int, optional
+        Maximum iterations for `p`-search if invoked.
+
+    Returns
+    -------
+    NdBSpline
+        Fitted bivariate spline surface.
+    """
+    if bbox is None:
+        bbox = [None]*4
+
+    x = np.asarray(x, dtype=float)
+    y = np.asarray(y, dtype=float)
+    z = np.asarray(z, dtype=float)
+    bbox = np.ravel(bbox)
+    s = float(s)
+
+    if not np.all(np.diff(x) > 0.0):
+        raise ValueError("x must be strictly increasing")
+    if not np.all(np.diff(y) > 0.0):
+        raise ValueError("y must be strictly increasing")
+    if x.size != z.shape[0]:
+        raise ValueError("x dimension of z must have same number of elements as x")
+    if y.size != z.shape[1]:
+        raise ValueError("y dimension of z must have same number of elements as y")
+    if (s < 0.0):
+        raise ValueError("s should be s >= 0.0")
+    if not bbox.shape == (4,):
+        raise ValueError(f"bbox shape should be (4,), found: {bbox.shape}")
+
+    return _regrid_fitpack(
+        x, y, z, kx=kx, ky=ky, s=s, maxit=maxit,
+        nestx=None, nesty=None, bbox=bbox)
diff --git a/.venv/lib/python3.12/site-packages/scipy/interpolate/_rgi.py b/.venv/lib/python3.12/site-packages/scipy/interpolate/_rgi.py
new file mode 100644
index 0000000000000000000000000000000000000000..d117aba6b7307c97f205c9fa12936449fd9fd31c
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/interpolate/_rgi.py
@@ -0,0 +1,853 @@
+__all__ = ['RegularGridInterpolator', 'interpn']
+
+import itertools
+from types import GenericAlias
+
+import numpy as np
+
+import scipy.sparse.linalg as ssl
+from scipy._lib._array_api import array_namespace, xp_capabilities
+from scipy._external.array_api_compat import is_array_api_obj
+
+from ._interpnd import _ndim_coords_from_arrays
+from ._cubic import PchipInterpolator
+from ._rgi_cython import evaluate_linear_2d, find_indices
+from ._bsplines import make_interp_spline
+from ._fitpack2 import RectBivariateSpline
+from ._ndbspline import make_ndbspl
+
+
+def _check_points(points):
+    descending_dimensions = []
+    grid = []
+    for i, p in enumerate(points):
+        # early make points float
+        # see https://github.com/scipy/scipy/pull/17230
+        p = np.asarray(p, dtype=float)
+        if not np.all(p[1:] > p[:-1]):
+            if np.all(p[1:] < p[:-1]):
+                # input is descending, so make it ascending
+                descending_dimensions.append(i)
+                p = np.flip(p)
+            else:
+                raise ValueError(
+                    f"The points in dimension {i} must be strictly ascending or "
+                    f"descending"
+                )
+        # see https://github.com/scipy/scipy/issues/17716
+        p = np.ascontiguousarray(p)
+        grid.append(p)
+    return tuple(grid), tuple(descending_dimensions)
+
+
+def _check_dimensionality(points, values):
+    if len(points) > values.ndim:
+        raise ValueError(
+            f"There are {len(points)} point arrays, but values has "
+            f"{values.ndim} dimensions"
+        )
+    for i, p in enumerate(points):
+        if not np.asarray(p).ndim == 1:
+            raise ValueError(f"The points in dimension {i} must be 1-dimensional")
+        if not values.shape[i] == len(p):
+            raise ValueError(
+                f"There are {len(p)} points and {values.shape[i]} values in "
+                f"dimension {i}"
+            )
+
+
+@xp_capabilities(
+    cpu_only=True, jax_jit=False,
+    skip_backends=[
+        ("dask.array",
+         "https://github.com/data-apis/array-api-extra/issues/488")
+    ]
+)
+class RegularGridInterpolator:
+    """Interpolator of specified order on a rectilinear grid in N ≥ 1 dimensions.
+
+    The data must be defined on a rectilinear grid; that is, a rectangular
+    grid with even or uneven spacing. Linear, nearest-neighbor, spline
+    interpolations are supported. After setting up the interpolator object,
+    the interpolation method may be chosen at each evaluation.
+
+    Parameters
+    ----------
+    points : tuple of ndarray of float, with shapes (m1, ), ..., (mn, )
+        The points defining the regular grid in n dimensions. The points in
+        each dimension (i.e. every elements of the points tuple) must be
+        strictly ascending or descending.
+
+    values : array_like, shape (m1, ..., mn, ...)
+        The data on the regular grid in n dimensions. Complex data is
+        accepted.
+
+    method : str, optional
+        The method of interpolation to perform. Supported are "linear",
+        "nearest", "slinear", "cubic", "quintic" and "pchip". This
+        parameter will become the default for the object's ``__call__``
+        method. Default is "linear".
+
+    bounds_error : bool, optional
+        If True, when interpolated values are requested outside of the
+        domain of the input data, a ValueError is raised.
+        If False, then `fill_value` is used.
+        Default is True.
+
+    fill_value : float or None, optional
+        The value to use for points outside of the interpolation domain.
+        If None, values outside the domain are extrapolated.
+        Default is ``np.nan``.
+
+    solver : callable, optional
+        Only used for methods "slinear", "cubic" and "quintic".
+        Sparse linear algebra solver for construction of the NdBSpline instance.
+        Default is the iterative solver `scipy.sparse.linalg.gcrotmk`.
+
+        .. versionadded:: 1.13
+
+    solver_args : dict, optional
+        Additional arguments to pass to `solver`, if any.
+
+        .. versionadded:: 1.13
+
+    Methods
+    -------
+    __call__
+
+    Attributes
+    ----------
+    grid : tuple of ndarrays
+        The points defining the regular grid in n dimensions.
+        This tuple defines the full grid via
+        ``np.meshgrid(*grid, indexing='ij')``
+    values : ndarray
+        Data values at the grid.
+    method : str
+        Interpolation method.
+    fill_value : float or ``None``
+        Use this value for out-of-bounds arguments to `__call__`.
+    bounds_error : bool
+        If ``True``, out-of-bounds argument raise a ``ValueError``.
+
+    Notes
+    -----
+    Contrary to `LinearNDInterpolator` and `NearestNDInterpolator`, this class
+    avoids expensive triangulation of the input data by taking advantage of the
+    regular grid structure.
+
+    In other words, this class assumes that the data is defined on a
+    *rectilinear* grid.
+
+    .. versionadded:: 0.14
+
+    The 'slinear'(k=1), 'cubic'(k=3), and 'quintic'(k=5) methods are
+    tensor-product spline interpolators, where `k` is the spline degree,
+    If any dimension has fewer points than `k` + 1, an error will be raised.
+
+    .. versionadded:: 1.9
+
+    If the input data is such that dimensions have incommensurate
+    units and differ by many orders of magnitude, the interpolant may have
+    numerical artifacts. Consider rescaling the data before interpolating.
+
+    **Choosing a solver for spline methods**
+
+    Spline methods, "slinear", "cubic" and "quintic" involve solving a
+    large sparse linear system at instantiation time. Depending on data,
+    the default solver may or may not be adequate. When it is not, you may
+    need to experiment with an optional `solver` argument, where you may
+    choose between the direct solver (`scipy.sparse.linalg.spsolve`) or
+    iterative solvers from `scipy.sparse.linalg`. You may need to supply
+    additional parameters via the optional `solver_args` parameter (for instance,
+    you may supply the starting value or target tolerance). See the
+    `scipy.sparse.linalg` documentation for the full list of available options.
+
+    Alternatively, you may instead use the legacy methods, "slinear_legacy",
+    "cubic_legacy" and "quintic_legacy". These methods allow faster construction
+    but evaluations will be much slower.
+
+    **Rounding rule at half points with `nearest` method**
+
+    The rounding rule with the `nearest` method at half points is rounding *down*.
+
+
+    Examples
+    --------
+    **Evaluate a function on the points of a 3-D grid**
+
+    As a first example, we evaluate a simple example function on the points of
+    a 3-D grid:
+
+    >>> from scipy.interpolate import RegularGridInterpolator
+    >>> import numpy as np
+    >>> def f(x, y, z):
+    ...     return 2 * x**3 + 3 * y**2 - z
+    >>> x = np.linspace(1, 4, 11)
+    >>> y = np.linspace(4, 7, 22)
+    >>> z = np.linspace(7, 9, 33)
+    >>> xg, yg ,zg = np.meshgrid(x, y, z, indexing='ij', sparse=True)
+    >>> data = f(xg, yg, zg)
+
+    ``data`` is now a 3-D array with ``data[i, j, k] = f(x[i], y[j], z[k])``.
+    Next, define an interpolating function from this data:
+
+    >>> interp = RegularGridInterpolator((x, y, z), data)
+
+    Evaluate the interpolating function at the two points
+    ``(x,y,z) = (2.1, 6.2, 8.3)`` and ``(3.3, 5.2, 7.1)``:
+
+    >>> pts = np.array([[2.1, 6.2, 8.3],
+    ...                 [3.3, 5.2, 7.1]])
+    >>> interp(pts)
+    array([ 125.80469388,  146.30069388])
+
+    which is indeed a close approximation to
+
+    >>> f(2.1, 6.2, 8.3), f(3.3, 5.2, 7.1)
+    (125.54200000000002, 145.894)
+
+    **Interpolate and extrapolate a 2D dataset**
+
+    As a second example, we interpolate and extrapolate a 2D data set:
+
+    >>> x, y = np.array([-2, 0, 4]), np.array([-2, 0, 2, 5])
+    >>> def ff(x, y):
+    ...     return x**2 + y**2
+
+    >>> xg, yg = np.meshgrid(x, y, indexing='ij')
+    >>> data = ff(xg, yg)
+    >>> interp = RegularGridInterpolator((x, y), data,
+    ...                                  bounds_error=False, fill_value=None)
+
+    >>> import matplotlib.pyplot as plt
+    >>> fig = plt.figure()
+    >>> ax = fig.add_subplot(projection='3d')
+    >>> ax.scatter(xg.ravel(), yg.ravel(), data.ravel(),
+    ...            s=60, c='k', label='data')
+
+    Evaluate and plot the interpolator on a finer grid
+
+    >>> xx = np.linspace(-4, 9, 31)
+    >>> yy = np.linspace(-4, 9, 31)
+    >>> X, Y = np.meshgrid(xx, yy, indexing='ij')
+
+    >>> # interpolator
+    >>> ax.plot_wireframe(X, Y, interp((X, Y)), rstride=3, cstride=3,
+    ...                   alpha=0.4, color='m', label='linear interp')
+
+    >>> # ground truth
+    >>> ax.plot_wireframe(X, Y, ff(X, Y), rstride=3, cstride=3,
+    ...                   alpha=0.4, label='ground truth')
+    >>> plt.legend()
+    >>> plt.show()
+
+    Other examples are given
+    :ref:`in the tutorial `.
+
+    See Also
+    --------
+    NearestNDInterpolator : Nearest neighbor interpolator on *unstructured*
+                            data in N dimensions
+
+    LinearNDInterpolator : Piecewise linear interpolator on *unstructured* data
+                           in N dimensions
+
+    interpn : a convenience function which wraps `RegularGridInterpolator`
+
+    scipy.ndimage.map_coordinates : interpolation on grids with equal spacing
+                                    (suitable for e.g., N-D image resampling)
+
+    References
+    ----------
+    .. [1] Python package *regulargrid* by Johannes Buchner, see
+           https://pypi.python.org/pypi/regulargrid/
+    .. [2] Wikipedia, "Trilinear interpolation",
+           https://en.wikipedia.org/wiki/Trilinear_interpolation
+    .. [3] Weiser, Alan, and Sergio E. Zarantonello. "A note on piecewise linear
+           and multilinear table interpolation in many dimensions." MATH.
+           COMPUT. 50.181 (1988): 189-196.
+           https://www.ams.org/journals/mcom/1988-50-181/S0025-5718-1988-0917826-0/S0025-5718-1988-0917826-0.pdf
+           :doi:`10.1090/S0025-5718-1988-0917826-0`
+
+    """
+    # this class is based on code originally programmed by Johannes Buchner,
+    # see https://github.com/JohannesBuchner/regulargrid
+
+    _SPLINE_DEGREE_MAP = {"slinear": 1, "cubic": 3, "quintic": 5, 'pchip': 3,
+                          "slinear_legacy": 1, "cubic_legacy": 3, "quintic_legacy": 5,}
+    _SPLINE_METHODS_recursive = {"slinear_legacy", "cubic_legacy",
+                                "quintic_legacy", "pchip"}
+    _SPLINE_METHODS_ndbspl = {"slinear", "cubic", "quintic"}
+    _SPLINE_METHODS = list(_SPLINE_DEGREE_MAP.keys())
+    _ALL_METHODS = ["linear", "nearest"] + _SPLINE_METHODS
+
+    # generic type compatibility with scipy-stubs
+    __class_getitem__: classmethod = classmethod(GenericAlias)
+
+    def __init__(self, points, values, method="linear", bounds_error=True,
+                 fill_value=np.nan, *, solver=None, solver_args=None):
+        if method not in self._ALL_METHODS:
+            raise ValueError(f"Method '{method}' is not defined")
+        elif method in self._SPLINE_METHODS:
+            self._validate_grid_dimensions(points, method)   # NB: uses np.atleast_1d
+
+        try:
+            xp = array_namespace(*points, values)
+        except Exception as e:
+            # either "duck-type" values or a user error?
+            xp = array_namespace(*points) # still forbid mixed namespaces in `points`
+            try:
+                xp_v = array_namespace(values)
+            except Exception:
+                # "duck-type" values indeed, continue with `xp` as the namespace
+                pass
+            else:
+                # both `points` and `values` are array API objects, check consistency
+                if xp_v != xp:
+                    raise e
+
+        self._asarray = xp.asarray
+        self.method = method
+        self._spline = None
+        self.bounds_error = bounds_error
+        self._grid, self._descending_dimensions = _check_points(points)
+        self._values = self._check_values(values)
+        self._check_dimensionality(self._grid, self._values)
+        self.fill_value = self._check_fill_value(self._values, fill_value)
+        if self._descending_dimensions:
+            self._values = np.flip(values, axis=self._descending_dimensions)
+        if self.method == "pchip" and np.iscomplexobj(self._values):
+            msg = ("`PchipInterpolator` only works with real values. If you are trying "
+                   "to use the real components of the passed array, use `np.real` on "
+                   "the array before passing to `RegularGridInterpolator`.")
+            raise ValueError(msg)
+        if method in self._SPLINE_METHODS_ndbspl:
+            if solver_args is None:
+                solver_args = {}
+            self._spline = self._construct_spline(method, solver, **solver_args)
+        else:
+            if solver is not None or solver_args:
+                raise ValueError(
+                    f"{method =} does not accept the 'solver' argument. Got "
+                    f" {solver = } and with arguments {solver_args}."
+                )
+
+    def _construct_spline(self, method, solver=None, **solver_args):
+        if solver is None:
+            solver = ssl.gcrotmk
+        spl = make_ndbspl(
+                self._grid, self._values, self._SPLINE_DEGREE_MAP[method],
+                solver=solver, **solver_args
+              )
+        return spl
+
+    def _check_dimensionality(self, grid, values):
+        _check_dimensionality(grid, values)
+
+    def _check_points(self, points):
+        return _check_points(points)
+
+    def _check_values(self, values):
+        if is_array_api_obj(values):
+            values = np.asarray(values)
+
+        if not hasattr(values, 'ndim'):
+            # allow reasonable duck-typed values
+            values = np.asarray(values)
+
+        if hasattr(values, 'dtype') and hasattr(values, 'astype'):
+            if not np.issubdtype(values.dtype, np.inexact):
+                values = values.astype(float)
+
+        return values
+
+    def _check_fill_value(self, values, fill_value):
+        if fill_value is not None:
+            fill_value_dtype = np.asarray(fill_value).dtype
+            if (hasattr(values, 'dtype') and not
+                    np.can_cast(fill_value_dtype, values.dtype,
+                                casting='same_kind')):
+                raise ValueError("fill_value must be either 'None' or "
+                                 "of a type compatible with values")
+        return fill_value
+
+    def __call__(self, xi, method=None, *, nu=None):
+        """
+        Interpolation at coordinates.
+
+        Parameters
+        ----------
+        xi : ndarray of shape (..., ndim)
+            The coordinates to evaluate the interpolator at.
+
+        method : str, optional
+            The method of interpolation to perform. Supported are "linear",
+            "nearest", "slinear", "cubic", "quintic" and "pchip". Default is
+            the method chosen when the interpolator was created.
+
+        nu : sequence of ints, length ndim, optional
+            If not None, the orders of the derivatives to evaluate.
+            Each entry must be non-negative.
+            Only allowed for methods "slinear", "cubic" and "quintic".
+
+            .. versionadded:: 1.13
+
+        Returns
+        -------
+        values_x : ndarray, shape xi.shape[:-1] + values.shape[ndim:]
+            Interpolated values at `xi`. See notes for behaviour when
+            ``xi.ndim == 1``.
+
+        Notes
+        -----
+        In the case that ``xi.ndim == 1`` a new axis is inserted into
+        the 0 position of the returned array, values_x, so its shape is
+        instead ``(1,) + values.shape[ndim:]``.
+
+        Examples
+        --------
+        Here we define a nearest-neighbor interpolator of a simple function
+
+        >>> import numpy as np
+        >>> x, y = np.array([0, 1, 2]), np.array([1, 3, 7])
+        >>> def f(x, y):
+        ...     return x**2 + y**2
+        >>> data = f(*np.meshgrid(x, y, indexing='ij', sparse=True))
+        >>> from scipy.interpolate import RegularGridInterpolator
+        >>> interp = RegularGridInterpolator((x, y), data, method='nearest')
+
+        By construction, the interpolator uses the nearest-neighbor
+        interpolation
+
+        >>> interp([[1.5, 1.3], [0.3, 4.5]])
+        array([2., 9.])
+
+        We can however evaluate the linear interpolant by overriding the
+        `method` parameter
+
+        >>> interp([[1.5, 1.3], [0.3, 4.5]], method='linear')
+        array([ 4.7, 24.3])
+        """
+        _spline = self._spline
+        method = self.method if method is None else method
+        is_method_changed = self.method != method
+        if method not in self._ALL_METHODS:
+            raise ValueError(f"Method '{method}' is not defined")
+        if is_method_changed and method in self._SPLINE_METHODS_ndbspl:
+            _spline = self._construct_spline(method)
+
+        if nu is not None and method not in self._SPLINE_METHODS_ndbspl:
+            raise ValueError(
+                f"Can only compute derivatives for methods "
+                f"{self._SPLINE_METHODS_ndbspl}, got {method =}."
+            )
+
+        xi, xi_shape, ndim, nans, out_of_bounds = self._prepare_xi(xi)
+
+        if method == "linear":
+            indices, norm_distances = self._find_indices(xi.T)
+            if (ndim == 2 and hasattr(self._values, 'dtype') and
+                    self._values.ndim == 2 and self._values.flags.writeable and
+                    self._values.dtype in (np.float64, np.complex128) and
+                    self._values.dtype.byteorder == '='):
+                # until cython supports const fused types, the fast path
+                # cannot support non-writeable values
+                # a fast path
+                out = np.empty(indices.shape[1], dtype=self._values.dtype)
+                result = evaluate_linear_2d(self._values,
+                                            indices,
+                                            norm_distances,
+                                            self._grid,
+                                            out)
+            else:
+                result = self._evaluate_linear(indices, norm_distances)
+        elif method == "nearest":
+            indices, norm_distances = self._find_indices(xi.T)
+            result = self._evaluate_nearest(indices, norm_distances)
+        elif method in self._SPLINE_METHODS:
+            if is_method_changed:
+                self._validate_grid_dimensions(self._grid, method)
+            if method in self._SPLINE_METHODS_recursive:
+                result = self._evaluate_spline(xi, method)
+            else:
+                result = _spline(xi, nu=nu)
+
+        if not self.bounds_error and self.fill_value is not None:
+            result[out_of_bounds] = self.fill_value
+
+        # f(nan) = nan, if any
+        if np.any(nans):
+            result[nans] = np.nan
+        return self._asarray(result.reshape(xi_shape[:-1] + self._values.shape[ndim:]))
+
+    @property
+    def grid(self):
+        return tuple(self._asarray(p) for p in self._grid)
+
+    @property
+    def values(self):
+        return self._asarray(self._values)
+
+    def _prepare_xi(self, xi):
+        ndim = len(self._grid)
+        xi = _ndim_coords_from_arrays(xi, ndim=ndim)
+        if xi.shape[-1] != ndim:
+            raise ValueError("The requested sample points xi have dimension "
+                             f"{xi.shape[-1]} but this "
+                             f"RegularGridInterpolator has dimension {ndim}")
+
+        xi_shape = xi.shape
+        xi = xi.reshape(-1, xi_shape[-1])
+        xi = np.asarray(xi, dtype=float)
+
+        # find nans in input
+        nans = np.any(np.isnan(xi), axis=-1)
+
+        if self.bounds_error:
+            for i, p in enumerate(xi.T):
+                if not np.logical_and(np.all(self._grid[i][0] <= p),
+                                      np.all(p <= self._grid[i][-1])):
+                    raise ValueError(
+                        f"One of the requested xi is out of bounds in dimension {i}"
+                    )
+            out_of_bounds = None
+        else:
+            out_of_bounds = self._find_out_of_bounds(xi.T)
+
+        return xi, xi_shape, ndim, nans, out_of_bounds
+
+    def _evaluate_linear(self, indices, norm_distances):
+        # slice for broadcasting over trailing dimensions in self._values
+        vslice = (slice(None),) + (None,)*(self._values.ndim - len(indices))
+
+        # Compute shifting up front before zipping everything together
+        shift_norm_distances = [1 - yi for yi in norm_distances]
+        shift_indices = [i + 1 for i in indices]
+
+        # The formula for linear interpolation in 2d takes the form:
+        # values = self._values[(i0, i1)] * (1 - y0) * (1 - y1) + \
+        #          self._values[(i0, i1 + 1)] * (1 - y0) * y1 + \
+        #          self._values[(i0 + 1, i1)] * y0 * (1 - y1) + \
+        #          self._values[(i0 + 1, i1 + 1)] * y0 * y1
+        # We pair i with 1 - yi (zipped1) and i + 1 with yi (zipped2)
+        zipped1 = zip(indices, shift_norm_distances)
+        zipped2 = zip(shift_indices, norm_distances)
+
+        # Take all products of zipped1 and zipped2 and iterate over them
+        # to get the terms in the above formula. This corresponds to iterating
+        # over the vertices of a hypercube.
+        hypercube = itertools.product(*zip(zipped1, zipped2))
+        value = np.array([0.])
+        for h in hypercube:
+            edge_indices, weights = zip(*h)
+            weight = np.array([1.])
+            for w in weights:
+                weight = weight * w
+            term = np.asarray(self._values[edge_indices]) * weight[vslice]
+            value = value + term   # cannot use += because broadcasting
+        return value
+
+    def _evaluate_nearest(self, indices, norm_distances):
+        idx_res = [np.where(yi <= .5, i, i + 1)
+                   for i, yi in zip(indices, norm_distances)]
+        return self._values[tuple(idx_res)]
+
+    def _validate_grid_dimensions(self, points, method):
+        k = self._SPLINE_DEGREE_MAP[method]
+        for i, point in enumerate(points):
+            ndim = len(np.atleast_1d(point))
+            if ndim <= k:
+                raise ValueError(f"There are {ndim} points in dimension {i},"
+                                 f" but method {method} requires at least "
+                                 f" {k+1} points per dimension.")
+
+    def _evaluate_spline(self, xi, method):
+        # ensure xi is 2D list of points to evaluate (`m` is the number of
+        # points and `n` is the number of interpolation dimensions,
+        # ``n == len(self._grid)``.)
+        if xi.ndim == 1:
+            xi = xi.reshape((1, xi.size))
+        m, n = xi.shape
+
+        # Reorder the axes: n-dimensional process iterates over the
+        # interpolation axes from the last axis downwards: E.g. for a 4D grid
+        # the order of axes is 3, 2, 1, 0. Each 1D interpolation works along
+        # the 0th axis of its argument array (for 1D routine it's its ``y``
+        # array). Thus permute the interpolation axes of `values` *and keep
+        # trailing dimensions trailing*.
+        axes = tuple(range(self._values.ndim))
+        axx = axes[:n][::-1] + axes[n:]
+        values = self._values.transpose(axx)
+
+        if method == 'pchip':
+            _eval_func = self._do_pchip
+        else:
+            _eval_func = self._do_spline_fit
+        k = self._SPLINE_DEGREE_MAP[method]
+
+        # Non-stationary procedure: difficult to vectorize this part entirely
+        # into numpy-level operations. Unfortunately this requires explicit
+        # looping over each point in xi.
+
+        # can at least vectorize the first pass across all points in the
+        # last variable of xi.
+        last_dim = n - 1
+        first_values = _eval_func(self._grid[last_dim],
+                                  values,
+                                  xi[:, last_dim],
+                                  k)
+
+        # the rest of the dimensions have to be on a per point-in-xi basis
+        shape = (m, *self._values.shape[n:])
+        result = np.empty(shape, dtype=self._values.dtype)
+        for j in range(m):
+            # Main process: Apply 1D interpolate in each dimension
+            # sequentially, starting with the last dimension.
+            # These are then "folded" into the next dimension in-place.
+            folded_values = first_values[j, ...]
+            for i in range(last_dim-1, -1, -1):
+                # Interpolate for each 1D from the last dimensions.
+                # This collapses each 1D sequence into a scalar.
+                folded_values = _eval_func(self._grid[i],
+                                           folded_values,
+                                           xi[j, i],
+                                           k)
+            result[j, ...] = folded_values
+
+        return result
+
+    @staticmethod
+    def _do_spline_fit(x, y, pt, k):
+        local_interp = make_interp_spline(x, y, k=k, axis=0)
+        values = local_interp(pt)
+        return values
+
+    @staticmethod
+    def _do_pchip(x, y, pt, k):
+        local_interp = PchipInterpolator(x, y, axis=0)
+        values = local_interp(pt)
+        return values
+
+    def _find_indices(self, xi):
+        return find_indices(self._grid, xi)
+
+    def _find_out_of_bounds(self, xi):
+        # check for out of bounds xi
+        out_of_bounds = np.zeros((xi.shape[1]), dtype=bool)
+        # iterate through dimensions
+        for x, grid in zip(xi, self._grid):
+            out_of_bounds += x < grid[0]
+            out_of_bounds += x > grid[-1]
+        return out_of_bounds
+
+
+def interpn(points, values, xi, method="linear", bounds_error=True,
+            fill_value=np.nan):
+    """
+    Multidimensional interpolation on regular or rectilinear grids.
+
+    Strictly speaking, not all regular grids are supported - this function
+    works on *rectilinear* grids, that is, a rectangular grid with even or
+    uneven spacing.
+
+    Parameters
+    ----------
+    points : tuple of ndarray of float, with shapes (m1, ), ..., (mn, )
+        The points defining the regular grid in n dimensions. The points in
+        each dimension (i.e. every elements of the points tuple) must be
+        strictly ascending or descending.
+
+    values : array_like, shape (m1, ..., mn, ...)
+        The data on the regular grid in n dimensions. Complex data is
+        accepted.
+    xi : ndarray of shape (..., ndim)
+        The coordinates to sample the gridded data at
+
+    method : str, optional
+        The method of interpolation to perform. Supported are "linear",
+        "nearest", "slinear", "cubic", "quintic", "pchip", and "splinef2d".
+        "splinef2d" is only supported for 2-dimensional data.
+
+    bounds_error : bool, optional
+        If True, when interpolated values are requested outside of the
+        domain of the input data, a ValueError is raised.
+        If False, then `fill_value` is used.
+
+    fill_value : number, optional
+        If provided, the value to use for points outside of the
+        interpolation domain. If None, values outside
+        the domain are extrapolated.  Extrapolation is not supported by method
+        "splinef2d".
+
+    Returns
+    -------
+    values_x : ndarray, shape xi.shape[:-1] + values.shape[ndim:]
+        Interpolated values at `xi`. See notes for behaviour when
+        ``xi.ndim == 1``.
+
+    See Also
+    --------
+    NearestNDInterpolator : Nearest neighbor interpolation on unstructured
+                            data in N dimensions
+    LinearNDInterpolator : Piecewise linear interpolant on unstructured data
+                           in N dimensions
+    RegularGridInterpolator : interpolation on a regular or rectilinear grid
+                              in arbitrary dimensions (`interpn` wraps this
+                              class).
+    RectBivariateSpline : Bivariate spline approximation over a rectangular mesh
+    scipy.ndimage.map_coordinates : interpolation on grids with equal spacing
+                                    (suitable for e.g., N-D image resampling)
+
+    Notes
+    -----
+
+    .. versionadded:: 0.14
+
+    In the case that ``xi.ndim == 1`` a new axis is inserted into
+    the 0 position of the returned array, values_x, so its shape is
+    instead ``(1,) + values.shape[ndim:]``.
+
+    If the input data is such that input dimensions have incommensurate
+    units and differ by many orders of magnitude, the interpolant may have
+    numerical artifacts. Consider rescaling the data before interpolation.
+
+    Examples
+    --------
+    Evaluate a simple example function on the points of a regular 3-D grid:
+
+    >>> import numpy as np
+    >>> from scipy.interpolate import interpn
+    >>> def value_func_3d(x, y, z):
+    ...     return 2 * x + 3 * y - z
+    >>> x = np.linspace(0, 4, 5)
+    >>> y = np.linspace(0, 5, 6)
+    >>> z = np.linspace(0, 6, 7)
+    >>> points = (x, y, z)
+    >>> values = value_func_3d(*np.meshgrid(*points, indexing='ij'))
+
+    Evaluate the interpolating function at a point
+
+    >>> point = np.array([2.21, 3.12, 1.15])
+    >>> print(interpn(points, values, point))
+    [12.63]
+
+    Compare with value at point by function
+
+    >>> value_func_3d(*point)
+    12.63 # up to rounding
+
+    Since the function is linear, the interpolation is exact using linear method.
+
+    If ``fill_value=None``, then values outside of the domain are extrapolated.
+
+    >>> x = np.linspace(0, 10, 11)
+    >>> y = np.linspace(0, 15, 16)
+    >>> def value_func_2d(x, y):
+    ...    return 5 * x - 3 * y
+    >>> points = (x, y)
+    >>> values = value_func_2d(*np.meshgrid(*points, indexing='ij'))
+    >>> xi = np.array([[25, 36]])
+    >>> interpn(points, values, xi, method='linear', bounds_error=False,
+    ...         fill_value=None)
+    array([17.])
+
+    If a ``fill_value`` is specified, any points outside the domain will be set to
+    ``fill_value``.
+
+    >>> interpn(points, values, xi, method='linear', bounds_error=False, fill_value=42)
+    array([42.])
+
+    When one axis is a single grid point, interpolation is only done at that
+    coordinate. Any other value along that axis is out of bounds, and set
+    to ``fill_value`` (if there is one).
+
+    Evaluate interpolation function at a point outside of the single-point axis
+
+    >>> x = np.array([0.0]) # x axis has length 1
+    >>> y = np.linspace(0, 10, 11)
+    >>> points = (x, y) 
+    >>> values = value_func_2d(*np.meshgrid(*points, indexing='ij'))
+    >>> xi = np.array([[1.0, 0.5]])
+    >>> interpn(points, values, xi, method='linear', bounds_error=False,
+    ...         fill_value = 42)
+    array([42.])
+
+    Evaluate interpolation function at a point on the single-point axis
+
+    >>> xi = np.array([[0.0, 0.5]])
+    >>> interpn(points, values, xi, method='linear', bounds_error=False,
+    ...         fill_value = 42) 
+    array([-1.5])   # interpolation as normal along y
+
+    """
+    # sanity check 'method' kwarg
+    if method not in ["linear", "nearest", "cubic", "quintic", "pchip",
+                      "splinef2d", "slinear",
+                      "slinear_legacy", "cubic_legacy", "quintic_legacy"]:
+        raise ValueError("interpn only understands the methods 'linear', "
+                         "'nearest', 'slinear', 'cubic', 'quintic', 'pchip', "
+                         f"and 'splinef2d'. You provided {method}.")
+
+    if not hasattr(values, 'ndim'):
+        values = np.asarray(values)
+
+    ndim = values.ndim
+    if ndim > 2 and method == "splinef2d":
+        raise ValueError("The method splinef2d can only be used for "
+                         "2-dimensional input data")
+    if not bounds_error and fill_value is None and method == "splinef2d":
+        raise ValueError("The method splinef2d does not support extrapolation.")
+
+    # sanity check consistency of input dimensions
+    if len(points) > ndim:
+        raise ValueError(
+            f"There are {len(points)} point arrays, but values has {ndim} dimensions"
+        )
+    if len(points) != ndim and method == 'splinef2d':
+        raise ValueError("The method splinef2d can only be used for "
+                         "scalar data with one point per coordinate")
+
+    grid, descending_dimensions = _check_points(points)
+    _check_dimensionality(grid, values)
+
+    # sanity check requested xi
+    xi = _ndim_coords_from_arrays(xi, ndim=len(grid))
+    if xi.shape[-1] != len(grid):
+        raise ValueError(
+            f"The requested sample points xi have dimension {xi.shape[-1]}, "
+            f"but this RegularGridInterpolator has dimension {len(grid)}"
+        )
+
+    if bounds_error:
+        for i, p in enumerate(xi.T):
+            if not np.logical_and(np.all(grid[i][0] <= p),
+                                  np.all(p <= grid[i][-1])):
+                raise ValueError(
+                    f"One of the requested xi is out of bounds in dimension {i}"
+                )
+
+    # perform interpolation
+    if method in RegularGridInterpolator._ALL_METHODS:
+        interp = RegularGridInterpolator(points, values, method=method,
+                                         bounds_error=bounds_error,
+                                         fill_value=fill_value)
+        return interp(xi)
+    elif method == "splinef2d":
+        xi_shape = xi.shape
+        xi = xi.reshape(-1, xi.shape[-1])
+
+        # RectBivariateSpline doesn't support fill_value; we need to wrap here
+        idx_valid = np.all((grid[0][0] <= xi[:, 0], xi[:, 0] <= grid[0][-1],
+                            grid[1][0] <= xi[:, 1], xi[:, 1] <= grid[1][-1]),
+                           axis=0)
+        result = np.empty_like(xi[:, 0])
+
+        # make a copy of values for RectBivariateSpline
+        interp = RectBivariateSpline(points[0], points[1], values[:])
+        result[idx_valid] = interp.ev(xi[idx_valid, 0], xi[idx_valid, 1])
+        result[np.logical_not(idx_valid)] = fill_value
+
+        return result.reshape(xi_shape[:-1])
+    else:
+        raise ValueError(f"unknown {method = }")
diff --git a/.venv/lib/python3.12/site-packages/scipy/interpolate/_rgi_cython.cpython-312-x86_64-linux-gnu.so b/.venv/lib/python3.12/site-packages/scipy/interpolate/_rgi_cython.cpython-312-x86_64-linux-gnu.so
new file mode 100644
index 0000000000000000000000000000000000000000..05efe4c5d460dcb0a21204da92a89bebd201496e
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/interpolate/_rgi_cython.cpython-312-x86_64-linux-gnu.so
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:936ce7dc812c28ea1b2c379a9bf9dbde6caad44abeb96b7c069c02e1b29730d1
+size 128016
diff --git a/.venv/lib/python3.12/site-packages/scipy/interpolate/dfitpack.py b/.venv/lib/python3.12/site-packages/scipy/interpolate/dfitpack.py
new file mode 100644
index 0000000000000000000000000000000000000000..7922cafeaae0eab0e8e2f6990ad0abf9ba9bcb2f
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/interpolate/dfitpack.py
@@ -0,0 +1,24 @@
+# This file is not meant for public use and will be removed in SciPy v2.0.0.
+# Use the `scipy.interpolate` namespace for importing the functions
+# included below.
+
+from scipy._lib.deprecation import _sub_module_deprecation
+
+
+__all__ = [  # noqa: F822
+    'spalde',
+    'splder',
+    'splev',
+    'splint',
+    'sproot',
+]
+
+
+def __dir__():
+    return __all__
+
+
+def __getattr__(name):
+    return _sub_module_deprecation(sub_package="interpolate", module="dfitpack",
+                                   private_modules=["_fitpack"], all=__all__,
+                                   attribute=name)
diff --git a/.venv/lib/python3.12/site-packages/scipy/interpolate/fitpack.py b/.venv/lib/python3.12/site-packages/scipy/interpolate/fitpack.py
new file mode 100644
index 0000000000000000000000000000000000000000..6490c93fe02b4c665b032d09e2ad3c269e1f7970
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/interpolate/fitpack.py
@@ -0,0 +1,31 @@
+# This file is not meant for public use and will be removed in SciPy v2.0.0.
+# Use the `scipy.interpolate` namespace for importing the functions
+# included below.
+
+from scipy._lib.deprecation import _sub_module_deprecation
+
+
+__all__ = [  # noqa: F822
+    'BSpline',
+    'bisplev',
+    'bisplrep',
+    'insert',
+    'spalde',
+    'splantider',
+    'splder',
+    'splev',
+    'splint',
+    'splprep',
+    'splrep',
+    'sproot',
+]
+
+
+def __dir__():
+    return __all__
+
+
+def __getattr__(name):
+    return _sub_module_deprecation(sub_package="interpolate", module="fitpack",
+                                   private_modules=["_fitpack_py"], all=__all__,
+                                   attribute=name)
diff --git a/.venv/lib/python3.12/site-packages/scipy/interpolate/fitpack2.py b/.venv/lib/python3.12/site-packages/scipy/interpolate/fitpack2.py
new file mode 100644
index 0000000000000000000000000000000000000000..f993961f94d913d632aa3d2cc7b1348659a6a613
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/interpolate/fitpack2.py
@@ -0,0 +1,29 @@
+# This file is not meant for public use and will be removed in SciPy v2.0.0.
+# Use the `scipy.interpolate` namespace for importing the functions
+# included below.
+
+from scipy._lib.deprecation import _sub_module_deprecation
+
+
+__all__ = [  # noqa: F822
+    'BivariateSpline',
+    'InterpolatedUnivariateSpline',
+    'LSQBivariateSpline',
+    'LSQSphereBivariateSpline',
+    'LSQUnivariateSpline',
+    'RectBivariateSpline',
+    'RectSphereBivariateSpline',
+    'SmoothBivariateSpline',
+    'SmoothSphereBivariateSpline',
+    'UnivariateSpline',
+]
+
+
+def __dir__():
+    return __all__
+
+
+def __getattr__(name):
+    return _sub_module_deprecation(sub_package="interpolate", module="fitpack2",
+                                   private_modules=["_fitpack2"], all=__all__,
+                                   attribute=name)
diff --git a/.venv/lib/python3.12/site-packages/scipy/interpolate/interpnd.py b/.venv/lib/python3.12/site-packages/scipy/interpolate/interpnd.py
new file mode 100644
index 0000000000000000000000000000000000000000..36bfa6b9f5669803b016a0471e327bc87e546733
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/interpolate/interpnd.py
@@ -0,0 +1,21 @@
+# This file is not meant for public use and will be removed in SciPy v2.0.0.
+# Use the `scipy.interpolate` namespace for importing the functions
+# included below.
+
+from scipy._lib.deprecation import _sub_module_deprecation
+
+
+__all__ = [  # noqa: F822
+    'CloughTocher2DInterpolator',
+    'LinearNDInterpolator',
+]
+
+
+def __dir__():
+    return __all__
+
+
+def __getattr__(name):
+    return _sub_module_deprecation(sub_package="interpolate", module="interpnd",
+                                   private_modules=["_interpnd"], all=__all__,
+                                   attribute=name, dep_version="1.17.0")
diff --git a/.venv/lib/python3.12/site-packages/scipy/interpolate/interpolate.py b/.venv/lib/python3.12/site-packages/scipy/interpolate/interpolate.py
new file mode 100644
index 0000000000000000000000000000000000000000..341d13954c81130cceb8afe070db023a82550e7a
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/interpolate/interpolate.py
@@ -0,0 +1,30 @@
+# This file is not meant for public use and will be removed in SciPy v2.0.0.
+# Use the `scipy.interpolate` namespace for importing the functions
+# included below.
+
+from scipy._lib.deprecation import _sub_module_deprecation
+
+
+__all__ = [  # noqa: F822
+    'BPoly',
+    'BSpline',
+    'NdPPoly',
+    'PPoly',
+    'RectBivariateSpline',
+    'RegularGridInterpolator',
+    'interp1d',
+    'interp2d',
+    'interpn',
+    'lagrange',
+    'make_interp_spline',
+]
+
+
+def __dir__():
+    return __all__
+
+
+def __getattr__(name):
+    return _sub_module_deprecation(sub_package="interpolate", module="interpolate",
+                                   private_modules=["_interpolate", "fitpack2", "_rgi"],
+                                   all=__all__, attribute=name)
diff --git a/.venv/lib/python3.12/site-packages/scipy/interpolate/ndgriddata.py b/.venv/lib/python3.12/site-packages/scipy/interpolate/ndgriddata.py
new file mode 100644
index 0000000000000000000000000000000000000000..20373eaaedaa1cdec6c7a4bc12639d9658bfa85b
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/interpolate/ndgriddata.py
@@ -0,0 +1,23 @@
+# This file is not meant for public use and will be removed in SciPy v2.0.0.
+# Use the `scipy.interpolate` namespace for importing the functions
+# included below.
+
+from scipy._lib.deprecation import _sub_module_deprecation
+
+
+__all__ = [  # noqa: F822
+    'CloughTocher2DInterpolator',
+    'LinearNDInterpolator',
+    'NearestNDInterpolator',
+    'griddata',
+]
+
+
+def __dir__():
+    return __all__
+
+
+def __getattr__(name):
+    return _sub_module_deprecation(sub_package="interpolate", module="ndgriddata",
+                                   private_modules=["_ndgriddata"], all=__all__,
+                                   attribute=name)
diff --git a/.venv/lib/python3.12/site-packages/scipy/interpolate/polyint.py b/.venv/lib/python3.12/site-packages/scipy/interpolate/polyint.py
new file mode 100644
index 0000000000000000000000000000000000000000..e81306304abffb313ab5abe09116a162642a9d67
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/interpolate/polyint.py
@@ -0,0 +1,24 @@
+# This file is not meant for public use and will be removed in SciPy v2.0.0.
+# Use the `scipy.interpolate` namespace for importing the functions
+# included below.
+
+from scipy._lib.deprecation import _sub_module_deprecation
+
+
+__all__ = [  # noqa: F822
+    'BarycentricInterpolator',
+    'KroghInterpolator',
+    'approximate_taylor_polynomial',
+    'barycentric_interpolate',
+    'krogh_interpolate',
+]
+
+
+def __dir__():
+    return __all__
+
+
+def __getattr__(name):
+    return _sub_module_deprecation(sub_package="interpolate", module="polyint",
+                                   private_modules=["_polyint"], all=__all__,
+                                   attribute=name)
diff --git a/.venv/lib/python3.12/site-packages/scipy/interpolate/rbf.py b/.venv/lib/python3.12/site-packages/scipy/interpolate/rbf.py
new file mode 100644
index 0000000000000000000000000000000000000000..772752ef536f4a3b47fb6f9b5d250c5d7f198d85
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/interpolate/rbf.py
@@ -0,0 +1,18 @@
+# This file is not meant for public use and will be removed in SciPy v2.0.0.
+# Use the `scipy.interpolate` namespace for importing the functions
+# included below.
+
+from scipy._lib.deprecation import _sub_module_deprecation
+
+
+__all__ = ["Rbf"]  # noqa: F822
+
+
+def __dir__():
+    return __all__
+
+
+def __getattr__(name):
+    return _sub_module_deprecation(sub_package="interpolate", module="rbf",
+                                   private_modules=["_rbf"], all=__all__,
+                                   attribute=name)
diff --git a/.venv/lib/python3.12/site-packages/scipy/interpolate/tests/__init__.py b/.venv/lib/python3.12/site-packages/scipy/interpolate/tests/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/.venv/lib/python3.12/site-packages/scipy/interpolate/tests/data/bug-1310.npz b/.venv/lib/python3.12/site-packages/scipy/interpolate/tests/data/bug-1310.npz
new file mode 100644
index 0000000000000000000000000000000000000000..8bddf805c36b29dc449556c27a2b489691f841af
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/interpolate/tests/data/bug-1310.npz
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:8d6803c0b398f2704c236f1d1b9e8e5ede06bd165a0abb0f228281abbd455ae9
+size 2648
diff --git a/.venv/lib/python3.12/site-packages/scipy/interpolate/tests/data/estimate_gradients_hang.npy b/.venv/lib/python3.12/site-packages/scipy/interpolate/tests/data/estimate_gradients_hang.npy
new file mode 100644
index 0000000000000000000000000000000000000000..c5ef8f63f263a476823ddeacf2571551c2fe4690
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/interpolate/tests/data/estimate_gradients_hang.npy
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:406c10857417ff5ea98d8cd28945c9d0e4f5c24f92a48ad0e8fab955bf2477f1
+size 35680
diff --git a/.venv/lib/python3.12/site-packages/scipy/interpolate/tests/data/gcvspl.npz b/.venv/lib/python3.12/site-packages/scipy/interpolate/tests/data/gcvspl.npz
new file mode 100644
index 0000000000000000000000000000000000000000..50e9348dcca79eae861e67092add93cdb8ff1ca3
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/interpolate/tests/data/gcvspl.npz
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:03ce8155a6cba0c1bf0a2441a10c228191f916dec36cb820723429811296bba8
+size 3138
diff --git a/.venv/lib/python3.12/site-packages/scipy/interpolate/tests/test_bary_rational.py b/.venv/lib/python3.12/site-packages/scipy/interpolate/tests/test_bary_rational.py
new file mode 100644
index 0000000000000000000000000000000000000000..a5c94f77f89899278c0266f7f99641adb4d8d9e4
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/interpolate/tests/test_bary_rational.py
@@ -0,0 +1,411 @@
+# Copyright (c) 2017, The Chancellor, Masters and Scholars of the University
+# of Oxford, and the Chebfun Developers. 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 Oxford nor the names of its
+#       contributors may be used to endorse or promote products derived from
+#       this software without specific prior written permission.
+#
+# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
+# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
+# ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+# (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
+# ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
+# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+
+from math import factorial
+
+import numpy as np
+from numpy.testing import assert_allclose, assert_equal, assert_array_less
+import pytest
+import scipy
+from scipy.interpolate import AAA, FloaterHormannInterpolator, BarycentricInterpolator
+
+TOL = 1e4 * np.finfo(np.float64).eps
+UNIT_INTERVAL = np.linspace(-1, 1, num=1000)
+PTS = np.logspace(-15, 0, base=10, num=500)
+PTS = np.concatenate([-PTS[::-1], [0], PTS])
+
+
+@pytest.mark.parametrize("method", [AAA, FloaterHormannInterpolator])
+@pytest.mark.parametrize("dtype", [np.float32, np.float64, np.complex64, np.complex128])
+def test_dtype_preservation(method, dtype):
+    rtol = np.finfo(dtype).eps ** 0.75 * 100
+    if method is FloaterHormannInterpolator:
+        rtol *= 100
+    rng = np.random.default_rng(59846294526092468)
+
+    z = np.linspace(-1, 1, dtype=dtype)
+    r = method(z, np.sin(z))
+
+    z2 = rng.uniform(-1, 1, size=100).astype(dtype)
+    assert_allclose(r(z2), np.sin(z2), rtol=rtol)
+    assert r(z2).dtype == dtype
+
+    if method is AAA:
+        assert r.support_points.dtype == dtype
+        assert r.support_values.dtype == dtype
+        assert r.errors.dtype == z.real.dtype
+    assert r.weights.dtype == dtype
+    assert r.poles().dtype == np.result_type(dtype, 1j)
+    assert r.residues().dtype == np.result_type(dtype, 1j)
+    assert r.roots().dtype == np.result_type(dtype, 1j)
+
+
+@pytest.mark.parametrize("method", [AAA, FloaterHormannInterpolator])
+@pytest.mark.parametrize("dtype", [np.int16, np.int32, np.int64])
+def test_integer_promotion(method, dtype):
+    z = np.arange(10, dtype=dtype)
+    r = method(z, z)
+    assert r.weights.dtype == np.result_type(dtype, 1.0)
+    if method is AAA:
+        assert r.support_points.dtype == np.result_type(dtype, 1.0)
+        assert r.support_values.dtype == np.result_type(dtype, 1.0)
+        assert r.errors.dtype == np.result_type(dtype, 1.0)
+    assert r.poles().dtype == np.result_type(dtype, 1j)
+    assert r.residues().dtype == np.result_type(dtype, 1j)
+    assert r.roots().dtype == np.result_type(dtype, 1j)
+
+    assert r(z).dtype == np.result_type(dtype, 1.0)
+
+
+class TestAAA:
+    def test_input_validation(self):
+        with pytest.raises(ValueError, match="`x` be of size 2 but got size 1."):
+            AAA([0], [1, 1])
+        with pytest.raises(ValueError, match="1-D"):
+            AAA([[0], [0]], [[1], [1]])
+        with pytest.raises(ValueError, match="finite"):
+            AAA([np.inf], [1])
+        with pytest.raises(TypeError):
+            AAA([1], [1], max_terms=1.0)
+        with pytest.raises(ValueError, match="greater"):
+            AAA([1], [1], max_terms=-1)
+
+    def test_convergence_error(self):
+        with pytest.warns(RuntimeWarning, match="AAA failed"):
+            AAA(UNIT_INTERVAL, np.exp(UNIT_INTERVAL),  max_terms=1)
+
+    # The following tests are based on:
+    # https://github.com/chebfun/chebfun/blob/master/tests/chebfun/test_aaa.m
+    def test_exp(self):
+        f = np.exp(UNIT_INTERVAL)
+        r = AAA(UNIT_INTERVAL, f)
+
+        assert_allclose(r(UNIT_INTERVAL), f, atol=TOL)
+        assert_equal(r(np.nan), np.nan)
+        assert np.isfinite(r(np.inf))
+
+        m1 = r.support_points.size
+        r = AAA(UNIT_INTERVAL, f, rtol=1e-3)
+        assert r.support_points.size < m1
+
+    def test_tan(self):
+        f = np.tan(np.pi * UNIT_INTERVAL)
+        r = AAA(UNIT_INTERVAL, f)
+
+        assert_allclose(r(UNIT_INTERVAL), f, atol=10 * TOL, rtol=1.4e-7)
+        assert_allclose(np.min(np.abs(r.roots())), 0, atol=3e-10)
+        assert_allclose(np.min(np.abs(r.poles() - 0.5)), 0, atol=TOL)
+        # Test for spurious poles (poles with tiny residue are likely spurious)
+        assert np.min(np.abs(r.residues())) > 1e-13
+
+    def test_short_cases(self):
+        # Computed using Chebfun:
+        # >> format long
+        # >> [r, pol, res, zer, zj, fj, wj, errvec] = aaa([1 2], [0 1])
+        z = np.array([0, 1])
+        f = np.array([1, 2])
+        r = AAA(z, f, rtol=1e-13)
+        assert_allclose(r(z), f, atol=TOL)
+        assert_allclose(r.poles(), 0.5)
+        assert_allclose(r.residues(), 0.25)
+        assert_allclose(r.roots(), 1/3)
+        assert_equal(r.support_points, z)
+        assert_equal(r.support_values, f)
+        assert_allclose(r.weights, [0.707106781186547, 0.707106781186547])
+        assert_equal(r.errors, [1, 0])
+
+        # >> format long
+        # >> [r, pol, res, zer, zj, fj, wj, errvec] = aaa([1 0 0], [0 1 2])
+        z = np.array([0, 1, 2])
+        f = np.array([1, 0, 0])
+        r = AAA(z, f, rtol=1e-13)
+        assert_allclose(r(z), f, atol=TOL)
+        assert_allclose(np.sort(r.poles()),
+                        np.sort([1.577350269189626, 0.422649730810374]))
+        assert_allclose(np.sort(r.residues()),
+                        np.sort([-0.070441621801729, -0.262891711531604]))
+        assert_allclose(np.sort(r.roots()), np.sort([2, 1]))
+        assert_equal(r.support_points, z)
+        assert_equal(r.support_values, f)
+        assert_allclose(r.weights, [0.577350269189626, 0.577350269189626,
+                                    0.577350269189626])
+        assert_equal(r.errors, [1, 1, 0])
+
+    def test_scale_invariance(self):
+        z = np.linspace(0.3, 1.5)
+        f = np.exp(z) / (1 + 1j)
+        r1 = AAA(z, f)
+        r2 = AAA(z, (2**311 * f).astype(np.complex128))
+        r3 = AAA(z, (2**-311 * f).astype(np.complex128))
+        assert_equal(r1(0.2j), 2**-311 * r2(0.2j))
+        assert_equal(r1(1.4), 2**311 * r3(1.4))
+
+    def test_log_func(self):
+        rng = np.random.default_rng(1749382759832758297)
+        z = rng.standard_normal(10000) + 3j * rng.standard_normal(10000)
+
+        def f(z):
+            return np.log(5 - z) / (1 + z**2)
+
+        r = AAA(z, f(z))
+        assert_allclose(r(0), f(0), atol=TOL)
+
+    def test_infinite_data(self):
+        z = np.linspace(-1, 1)
+        r = AAA(z, scipy.special.gamma(z))
+        assert_allclose(r(0.63), scipy.special.gamma(0.63), atol=1e-15)
+
+    def test_nan(self):
+        x = np.linspace(0, 20)
+        with np.errstate(invalid="ignore"):
+            f = np.sin(x) / x
+        r = AAA(x, f)
+        assert_allclose(r(2), np.sin(2) / 2, atol=1e-15)
+
+    def test_residues(self):
+        x = np.linspace(-1.337, 2, num=537)
+        r = AAA(x, np.exp(x) / x)
+        ii = np.flatnonzero(np.abs(r.poles()) < 1e-8)
+        assert_allclose(r.residues()[ii], 1, atol=1e-15)
+
+        r = AAA(x, (1 + 1j) * scipy.special.gamma(x))
+        ii = np.flatnonzero(abs(r.poles() - (-1)) < 1e-8)
+        assert_allclose(r.residues()[ii], -1 - 1j, atol=1e-15)
+
+    # The following tests are based on:
+    # https://github.com/complexvariables/RationalFunctionApproximation.jl/blob/main/test/interval.jl
+    @pytest.mark.parametrize("func,atol,rtol",
+                             [(lambda x: np.abs(x + 0.5 + 0.01j), 5e-13, 1e-7),
+                              (lambda x: np.sin(1/(1.05 - x)), 2e-13, 1e-7),
+                              (lambda x: np.exp(-1/(x**2)), 3.5e-11, 0),
+                              (lambda x: np.exp(-100*x**2), 2e-12, 0),
+                              (lambda x: np.exp(-10/(1.2 - x)), 1e-14, 0),
+                              (lambda x: 1/(1+np.exp(100*(x + 0.5))), 2e-13, 1e-7),
+                              (lambda x: np.abs(x - 0.95), 1e-6, 1e-7)])
+    def test_basic_functions(self, func, atol, rtol):
+        with np.errstate(divide="ignore"):
+            f = func(PTS)
+        assert_allclose(AAA(UNIT_INTERVAL, func(UNIT_INTERVAL))(PTS),
+                        f, atol=atol, rtol=rtol)
+
+    def test_poles_zeros_residues(self):
+        def f(z):
+            return (z+1) * (z+2) / ((z+3) * (z+4))
+        r = AAA(UNIT_INTERVAL, f(UNIT_INTERVAL))
+        assert_allclose(np.sum(r.poles() + r.roots()), -10, atol=1e-12)
+
+        def f(z):
+            return 2/(3 + z) + 5/(z - 2j)
+        r = AAA(UNIT_INTERVAL, f(UNIT_INTERVAL))
+        assert_allclose(r.residues().prod(), 10, atol=1e-8)
+
+        r = AAA(UNIT_INTERVAL, np.sin(10*np.pi*UNIT_INTERVAL))
+        assert_allclose(np.sort(np.abs(r.roots()))[18], 0.9, atol=1e-12)
+
+        def f(z):
+            return (z - (3 + 3j))/(z + 2)
+        r = AAA(UNIT_INTERVAL, f(UNIT_INTERVAL))
+        assert_allclose(r.poles()[0]*r.roots()[0],  -6-6j, atol=1e-12)
+
+    @pytest.mark.parametrize("func",
+                             [lambda z: np.zeros_like(z), lambda z: z, lambda z: 1j*z,
+                              lambda z: z**2 + z, lambda z: z**3 + z,
+                              lambda z: 1/(1.1 + z), lambda z: 1/(1 + 1j*z),
+                              lambda z: 1/(3 + z + z**2), lambda z: 1/(1.01 + z**3)])
+    def test_polynomials_and_reciprocals(self, func):
+        assert_allclose(AAA(UNIT_INTERVAL, func(UNIT_INTERVAL))(PTS),
+                        func(PTS), atol=2e-13)
+
+    # The following tests are taken from:
+    # https://github.com/macd/BaryRational.jl/blob/main/test/test_aaa.jl
+    def test_spiral(self):
+        z = np.exp(np.linspace(-0.5, 0.5 + 15j*np.pi, num=1000))
+        r = AAA(z, np.tan(np.pi*z/2))
+        assert_allclose(np.sort(np.abs(r.poles()))[:4], [1, 1, 3, 3], rtol=9e-7)
+
+    def test_spiral_cleanup(self):
+        z = np.exp(np.linspace(-0.5, 0.5 + 15j*np.pi, num=1000))
+        # here we set `rtol=0` to force froissart doublets, without cleanup there
+        # are many spurious poles
+        with pytest.warns(RuntimeWarning):
+            r = AAA(z, np.tan(np.pi*z/2), rtol=0, max_terms=60, clean_up=False)
+        n_spurious = np.sum(np.abs(r.residues()) < 1e-14)
+        with pytest.warns(RuntimeWarning):
+            assert r.clean_up() >= 1
+        # check there are less potentially spurious poles than before
+        assert np.sum(np.abs(r.residues()) < 1e-14) < n_spurious
+        # check accuracy
+        assert_allclose(r(z), np.tan(np.pi*z/2), atol=6e-12, rtol=3e-12)
+
+    def test_diag_scaling(self):
+        # fails without diag scaling
+        z = np.logspace(-15, 0, 300)
+        f = np.sqrt(z)
+        r = AAA(z, f)
+
+        zz = np.logspace(-15, 0, 500)
+        assert_allclose(r(zz), np.sqrt(zz), rtol=1e-5)
+
+
+class BatchFloaterHormann:
+    # FloaterHormann class with reference batch behaviour
+    def __init__(self, x, y, axis):
+        y = np.moveaxis(y, axis, -1)
+        self._batch_shape = y.shape[:-1]
+        self._interps = [FloaterHormannInterpolator(x, yi,)
+                         for yi in y.reshape(-1, y.shape[-1])]
+        self._axis = axis
+
+    def __call__(self, x):
+        y = [interp(x) for interp in self._interps]
+        y = np.reshape(y, self._batch_shape + x.shape)
+        return np.moveaxis(y, -1, self._axis) if x.shape else y
+
+
+class TestFloaterHormann:
+    def runge(self, z):
+        return 1/(1 + z**2)
+
+    def scale(self, n, d):
+        return (-1)**(np.arange(n) + d) * factorial(d)
+
+    def test_iv(self):
+        with pytest.raises(ValueError, match="`x`"):
+            FloaterHormannInterpolator([[0]], [0], d=0)
+        with pytest.raises(ValueError, match="`y`"):
+            FloaterHormannInterpolator([0], 0, d=0)
+        with pytest.raises(ValueError, match="`x` be of size 2 but got size 1."):
+            FloaterHormannInterpolator([0], [[1, 1], [1, 1]], d=0)
+        with pytest.raises(ValueError, match="finite"):
+            FloaterHormannInterpolator([np.inf], [1], d=0)
+        with pytest.raises(ValueError, match="`d`"):
+            FloaterHormannInterpolator([0], [0], d=-1)
+        with pytest.raises(ValueError, match="`d`"):
+            FloaterHormannInterpolator([0], [0], d=10)
+        with pytest.raises(TypeError):
+            FloaterHormannInterpolator([0], [0], d=0.0)
+
+    # reference values from Floater and Hormann 2007 page 8.
+    @pytest.mark.parametrize("d,expected", [
+        (0, [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]),
+        (1, [1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 1]),
+        (2, [1, 3, 4, 4, 4, 4, 4, 4, 4, 3, 1]),
+        (3, [1, 4, 7, 8, 8, 8, 8, 8, 7, 4, 1]),
+        (4, [1, 5, 11, 15, 16, 16, 16, 15, 11, 5, 1])
+    ])
+    def test_uniform_grid(self, d, expected):
+        # Check against explicit results on a uniform grid
+        x = np.arange(11)
+        r = FloaterHormannInterpolator(x, 0.0*x, d=d)
+        assert_allclose(r.weights.ravel()*self.scale(x.size, d), expected,
+                        rtol=1e-15, atol=1e-15)
+
+    @pytest.mark.parametrize("d", range(10))
+    def test_runge(self, d):
+        x = np.linspace(0, 1, 51)
+        rng = np.random.default_rng(802754237598370893)
+        xx = rng.uniform(0, 1, size=1000)
+        y = self.runge(x)
+        h = x[1] - x[0]
+
+        r = FloaterHormannInterpolator(x, y, d=d)
+
+        tol = 10*h**(d+1)
+        assert_allclose(r(xx), self.runge(xx), atol=1e-10, rtol=tol)
+        # check interpolation property
+        assert_equal(r(x), self.runge(x))
+
+    def test_complex(self):
+        x = np.linspace(-1, 1)
+        z = x + x*1j
+        r = FloaterHormannInterpolator(z, np.sin(z), d=12)
+        xx = np.linspace(-1, 1, num=1000)
+        zz = xx + xx*1j
+        assert_allclose(r(zz), np.sin(zz), rtol=1e-12)
+
+    def test_polyinterp(self):
+        # check that when d=n-1 FH gives a polynomial interpolant
+        x = np.linspace(0, 1, 11)
+        xx = np.linspace(0, 1, 1001)
+        y = np.sin(x)
+        r = FloaterHormannInterpolator(x, y, d=x.size-1)
+        p = BarycentricInterpolator(x, y)
+        assert_allclose(r(xx), p(xx), rtol=1e-12, atol=1e-12)
+
+    @pytest.mark.parametrize("y_shape", [(2,), (2, 3, 1), (1, 5, 6, 4)])
+    @pytest.mark.parametrize("xx_shape", [(100), (10, 10)])
+    def test_trailing_dim(self, y_shape, xx_shape):
+        x = np.linspace(0, 1)
+        y = np.broadcast_to(
+            np.expand_dims(np.sin(x), tuple(range(1, len(y_shape) + 1))),
+            x.shape + y_shape
+        )
+
+        r = FloaterHormannInterpolator(x, y)
+
+        rng = np.random.default_rng(897138947238097528091759187597)
+        xx = rng.random(xx_shape)
+        yy = np.broadcast_to(
+            np.expand_dims(np.sin(xx), tuple(range(xx.ndim, len(y_shape) + xx.ndim))),
+            xx.shape + y_shape
+        )
+        rr = r(xx)
+        assert rr.shape == xx.shape + y_shape
+        assert_allclose(rr, yy, rtol=1e-6)
+
+
+    def test_zeros(self):
+        x = np.linspace(0, 10, num=100)
+        r = FloaterHormannInterpolator(x, np.sin(np.pi*x))
+
+        err = np.abs(np.subtract.outer(r.roots(), np.arange(11))).min(axis=0)
+        assert_array_less(err, 1e-5)
+
+    def test_no_poles(self):
+        x = np.linspace(-1, 1)
+        r = FloaterHormannInterpolator(x, 1/x**2)
+        p = r.poles()
+        mask = (p.real >= -1) & (p.real <= 1) & (np.abs(p.imag) < 1.e-12)
+        assert np.sum(mask) == 0
+
+    @pytest.mark.parametrize('eval_shape', [(), (1,), (3,)])
+    @pytest.mark.parametrize('axis', [-1, 0, 1])
+    def test_batch(self, eval_shape, axis):
+        rng = np.random.default_rng(4329872134985134)
+        n = 10
+        shape = (2, 3, 4, n)
+        domain = (0, 10)
+
+        x = np.linspace(*domain, n)
+        y = np.moveaxis(rng.random(shape), -1, axis)
+
+        res = FloaterHormannInterpolator(x, y, axis=axis)
+        ref = BatchFloaterHormann(x, y, axis=axis)
+
+        x = rng.uniform(*domain, size=eval_shape)
+        assert_allclose(res(x), ref(x))
+
+        pytest.raises(NotImplementedError, res.roots)
+        pytest.raises(NotImplementedError, res.residues)
diff --git a/.venv/lib/python3.12/site-packages/scipy/interpolate/tests/test_bsplines.py b/.venv/lib/python3.12/site-packages/scipy/interpolate/tests/test_bsplines.py
new file mode 100644
index 0000000000000000000000000000000000000000..bc6667103d2d9790cc0eb94103d88d54bda55ba9
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/interpolate/tests/test_bsplines.py
@@ -0,0 +1,4419 @@
+import os
+import operator
+import itertools
+import math
+import cmath
+import threading
+import copy
+import warnings
+import sys
+
+import numpy as np
+from scipy._lib._array_api import (
+    xp_assert_equal, xp_assert_close, xp_default_dtype, concat_1d, make_xp_test_case,
+    xp_ravel, _xp_copy_to_numpy, array_namespace
+)
+import scipy._external.array_api_extra as xpx
+from pytest import raises as assert_raises
+import pytest
+
+from scipy.interpolate import (
+        BSpline, BPoly, PPoly, make_interp_spline, make_lsq_spline,
+        splev, splrep, splprep, splder, splantider, sproot, splint, insert,
+        CubicSpline, NdBSpline, make_smoothing_spline, RegularGridInterpolator,
+)
+import scipy.linalg as sl
+import scipy.sparse.linalg as ssl
+
+from scipy.interpolate._bsplines import (_not_a_knot, _augknt,
+                                        _woodbury_algorithm, _periodic_knots,
+                                         _make_interp_per_full_matr)
+from scipy.interpolate._fitpack_repro import Fperiodic, root_rati
+
+from scipy.interpolate import generate_knots, make_splrep, make_splprep
+
+import scipy.interpolate._fitpack_impl as _impl
+from scipy._lib._util import AxisError
+from scipy._lib._testutils import _run_concurrent_barrier
+
+# XXX: move to the interpolate namespace
+from scipy.interpolate._ndbspline import make_ndbspl
+
+from scipy.interpolate import _fitpack as dfitpack
+from scipy.interpolate import _bsplines as _b
+from scipy.interpolate import _dierckx
+
+skip_xp_backends = pytest.mark.skip_xp_backends
+xfail_xp_backends = pytest.mark.xfail_xp_backends
+
+
+@make_xp_test_case(BSpline)
+class TestBSpline:
+
+    def test_ctor(self, xp):
+        # knots should be an ordered 1-D array of finite real numbers
+        assert_raises((TypeError, ValueError), BSpline,
+                **dict(t=[1, 1.j], c=[1.], k=0))
+        with np.errstate(invalid='ignore'):
+            assert_raises(ValueError, BSpline, **dict(t=[1, np.nan], c=[1.], k=0))
+        assert_raises(ValueError, BSpline, **dict(t=[1, np.inf], c=[1.], k=0))
+        assert_raises(ValueError, BSpline, **dict(t=[1, -1], c=[1.], k=0))
+        assert_raises(ValueError, BSpline, **dict(t=[[1], [1]], c=[1.], k=0))
+
+        # for n+k+1 knots and degree k need at least n coefficients
+        assert_raises(ValueError, BSpline, **dict(t=[0, 1, 2], c=[1], k=0))
+        assert_raises(ValueError, BSpline,
+                **dict(t=[0, 1, 2, 3, 4], c=[1., 1.], k=2))
+
+        # non-integer orders
+        assert_raises(TypeError, BSpline,
+                **dict(t=[0., 0., 1., 2., 3., 4.], c=[1., 1., 1.], k="cubic"))
+        assert_raises(TypeError, BSpline,
+                **dict(t=[0., 0., 1., 2., 3., 4.], c=[1., 1., 1.], k=2.5))
+
+        # basic interval cannot have measure zero (here: [1..1])
+        assert_raises(ValueError, BSpline,
+                **dict(t=[0., 0, 1, 1, 2, 3], c=[1., 1, 1], k=2))
+
+        # tck vs self.tck
+        n, k = 11, 3
+        t = xp.arange(n+k+1, dtype=xp.float64)
+        c = xp.asarray(np.random.random(n))
+        b = BSpline(t, c, k)
+
+        xp_assert_close(t, b.t)
+        xp_assert_close(c, b.c)
+        assert k == b.k
+
+    def test_tck(self):
+        b = _make_random_spline()
+        tck = b.tck
+
+        xp_assert_close(b.t, tck[0], atol=1e-15, rtol=1e-15)
+        xp_assert_close(b.c, tck[1], atol=1e-15, rtol=1e-15)
+        assert b.k == tck[2]
+
+        # b.tck is read-only
+        with pytest.raises(AttributeError):
+            b.tck = 'foo'
+
+    def test_call_namespace(self, xp):
+        # similar to test_degree_0 below, only parametrized with xp
+        # (test_degree_0 tests array-like inputs, which resolve to numpy)
+        b = BSpline(t=xp.asarray([0, 1., 2]), c=xp.asarray([3., 4]), k=0)
+        xx = xp.linspace(0, 2, 10)
+
+        expected = xp.where(xx < 1., xp.asarray(3., dtype=xp.float64), 4.0)
+        xp_assert_close(b(xx), expected)
+
+    def test_attributes_have_correct_namespace(self, xp):
+        b = BSpline(t=xp.asarray([0, 1., 2]), c=xp.asarray([3., 4]), k=0)
+        assert array_namespace(b.t) is xp
+        assert array_namespace(b.c) is xp
+
+    def test_degree_0(self):
+        xx = np.linspace(0, 1, 10)
+
+        b = BSpline(t=[0, 1], c=[3.], k=0)
+        xp_assert_close(b(xx), np.ones_like(xx) * 3.0)
+
+        b = BSpline(t=[0, 0.35, 1], c=[3, 4], k=0)
+        xp_assert_close(b(xx), np.where(xx < 0.35, 3.0, 4.0))
+
+    def test_degree_1(self, xp):
+        t = xp.asarray([0, 1, 2, 3, 4])
+        c = xp.asarray([1.0, 2, 3])
+        k = 1
+        b = BSpline(t, c, k)
+
+        x = xp.linspace(1.0, 3.0, 50, dtype=xp.float64)
+        xp_assert_close(
+            b(x),
+            c[0]*B_012(x, xp=xp) + c[1]*B_012(x-1, xp=xp) + c[2]*B_012(x-2, xp=xp),
+            atol=1e-14
+        )
+        x_np, t_np, c_np = map(_xp_copy_to_numpy, (x, t, c))
+        splev_result = splev(x_np, (t_np, c_np, k))
+        xp_assert_close(b(x), xp.asarray(splev_result), atol=1e-14)
+
+    def test_bernstein(self, xp):
+        # a special knot vector: Bernstein polynomials
+        k = 3
+        t = xp.asarray([0]*(k+1) + [1]*(k+1))
+        c = xp.asarray([1., 2., 3., 4.])
+        bp = BPoly(
+            _xp_copy_to_numpy(xp.reshape(c, (-1, 1))),
+            _xp_copy_to_numpy(xp.asarray([0, 1])),
+        )
+        bspl = BSpline(t, c, k)
+
+        xx = xp.linspace(-1., 2., 10)
+        xp_assert_close(
+            bspl(xx, extrapolate=True),
+            xp.asarray(bp(_xp_copy_to_numpy(xx), extrapolate=True)),
+            atol=1e-14,
+        )
+
+    @skip_xp_backends("dask.array", reason="_naive_eval is not dask-compatible")
+    @skip_xp_backends("jax.numpy", reason="too slow; XXX a slow-if marker?")
+    @skip_xp_backends("torch", reason="OOB on CI")
+    def test_rndm_naive_eval(self, xp):
+        # test random coefficient spline *on the base interval*,
+        # t[k] <= x < t[-k-1]
+        b = _make_random_spline(xp=xp)
+        t, c, k = b.tck
+        xx = xp.linspace(t[k], t[-k-1], 50)
+        y_b = b(xx)
+        y_n = xp.stack([_naive_eval(x, t, c, k, xp=xp) for x in xx])
+        xp_assert_close(y_b, y_n, atol=1e-14)
+
+        y_n2 = xp.stack([_naive_eval_2(x, t, c, k, xp=xp) for x in xx])
+        xp_assert_close(y_b, y_n2, atol=1e-14)
+
+    def test_rndm_splev(self):
+        b = _make_random_spline()
+        t, c, k = b.tck
+        xx = np.linspace(t[k], t[-k-1], 50)
+        xp_assert_close(b(xx), splev(xx, (t, c, k)), atol=1e-14)
+
+    def test_rndm_splrep(self):
+        rng = np.random.RandomState(1234)
+        x = np.sort(rng.random(20))
+        y = rng.random(20)
+
+        tck = splrep(x, y)
+        b = BSpline(*tck)
+
+        t, k = b.t, b.k
+        xx = np.linspace(t[k], t[-k-1], 80)
+        xp_assert_close(b(xx), splev(xx, tck), atol=1e-14)
+
+    def test_rndm_unity(self, xp):
+        b = _make_random_spline(xp=xp)
+        b.c = xp.ones_like(b.c)
+        xx = xp.linspace(b.t[b.k], b.t[-b.k-1], 100, dtype=xp.float64)
+        xp_assert_close(b(xx), xp.ones_like(xx))
+
+    def test_vectorization(self, xp):
+        rng = np.random.RandomState(1234)
+        n, k = 22, 3
+        t = np.sort(rng.random(n))
+        c = rng.random(size=(n, 6, 7))
+        t, c = map(xp.asarray, (t, c))
+        b = BSpline(t, c, k)
+        tm, tp = t[k], t[-k-1]
+        xx = tm + (tp - tm) * xp.asarray(rng.random((3, 4, 5)))
+        assert b(xx).shape == (3, 4, 5, 6, 7)
+
+    def test_len_c(self):
+        # for n+k+1 knots, only first n coefs are used.
+        # and BTW this is consistent with FITPACK
+        rng = np.random.RandomState(1234)
+        n, k = 33, 3
+        t = np.sort(rng.random(n+k+1))
+        c = rng.random(n)
+
+        # pad coefficients with random garbage
+        c_pad = np.r_[c, rng.random(k+1)]
+
+        b, b_pad = BSpline(t, c, k), BSpline(t, c_pad, k)
+
+        dt = t[-1] - t[0]
+        xx = np.linspace(t[0] - dt, t[-1] + dt, 50)
+        xp_assert_close(b(xx), b_pad(xx), atol=1e-14)
+        xp_assert_close(b(xx), splev(xx, (t, c, k)), atol=1e-14)
+        xp_assert_close(b(xx), splev(xx, (t, c_pad, k)), atol=1e-14)
+
+    def test_endpoints(self, num_parallel_threads):
+        # base interval is closed
+        b = _make_random_spline()
+        t, _, k = b.tck
+        tm, tp = t[k], t[-k-1]
+        # atol = 1e-9 if num_parallel_threads == 1 else 1e-7
+        for extrap in (True, False):
+            xp_assert_close(b([tm, tp], extrap),
+                            b([tm + 1e-10, tp - 1e-10], extrap), atol=1e-9, rtol=1e-7)
+
+    def test_continuity(self, num_parallel_threads):
+        # assert continuity at internal knots
+        b = _make_random_spline()
+        t, _, k = b.tck
+        xp_assert_close(b(t[k+1:-k-1] - 1e-10), b(t[k+1:-k-1] + 1e-10),
+                atol=1e-9)
+
+    def test_extrap(self, xp):
+        b = _make_random_spline(xp=xp)
+        t, c, k = b.tck
+        dt = t[-1] - t[0]
+        xx = xp.linspace(t[k] - dt, t[-k-1] + dt, 50)
+        mask = (t[k] < xx) & (xx < t[-k-1])
+
+        # extrap has no effect within the base interval
+        xp_assert_close(b(xx[mask], extrapolate=True),
+                        b(xx[mask], extrapolate=False))
+
+        # extrapolated values agree with FITPACK
+        xx_np, t_np, c_np = map(_xp_copy_to_numpy, (xx, t, c))
+        splev_result = xp.asarray(splev(xx_np, (t_np, c_np, k), ext=0))
+        xp_assert_close(b(xx, extrapolate=True), splev_result)
+
+    def test_default_extrap(self):
+        # BSpline defaults to extrapolate=True
+        b = _make_random_spline()
+        t, _, k = b.tck
+        xx = [t[0] - 1, t[-1] + 1]
+        yy = b(xx)
+        assert not np.all(np.isnan(yy))
+
+    def test_periodic_extrap(self, xp):
+        rng = np.random.RandomState(1234)
+        t = np.sort(rng.random(8))
+        c = rng.random(4)
+        t, c = map(xp.asarray, (t, c))
+        k = 3
+        b = BSpline(t, c, k, extrapolate='periodic')
+        n = t.shape[0] - (k + 1)
+
+        dt = t[-1] - t[0]
+        xx = xp.linspace(t[k] - dt, t[n] + dt, 50)
+        xy = t[k] + (xx - t[k]) % (t[n] - t[k])
+        xy_np, t_np, c_np = map(_xp_copy_to_numpy, (xy, t, c))
+        atol = 1e-12 if xp_default_dtype(xp) == xp.float64 else 2e-7
+        xp_assert_close(
+            b(xx), xp.asarray(splev(xy_np, (t_np, c_np, k))), atol=atol
+        )
+
+        # Direct check
+        xx = xp.asarray([-1, 0, 0.5, 1])
+        xy = t[k] + (xx - t[k]) % (t[n] - t[k])
+        xp_assert_close(
+            b(xx, extrapolate='periodic'),
+            b(xy, extrapolate=True),
+            atol=1e-14 if xp_default_dtype(xp) == xp.float64 else 5e-7
+        )
+
+    def test_ppoly(self):
+        b = _make_random_spline()
+        t, c, k = b.tck
+        pp = PPoly.from_spline((t, c, k))
+
+        xx = np.linspace(t[k], t[-k], 100)
+        xp_assert_close(b(xx), pp(xx), atol=1e-14, rtol=1e-14)
+
+    def test_derivative_rndm(self):
+        b = _make_random_spline()
+        t, c, k = b.tck
+        xx = np.linspace(t[0], t[-1], 50)
+        xx = np.r_[xx, t]
+
+        for der in range(1, k+1):
+            yd = splev(xx, (t, c, k), der=der)
+            xp_assert_close(yd, b(xx, nu=der), atol=1e-14)
+
+        # higher derivatives all vanish
+        xp_assert_close(b(xx, nu=k+1), np.zeros_like(xx), atol=1e-14)
+
+    def test_derivative_jumps(self):
+        # example from de Boor, Chap IX, example (24)
+        # NB: knots augmented & corresp coefs are zeroed out
+        # in agreement with the convention (29)
+        k = 2
+        t = [-1, -1, 0, 1, 1, 3, 4, 6, 6, 6, 7, 7]
+        rng = np.random.RandomState(1234)
+        c = np.r_[0, 0, rng.random(5), 0, 0]
+        b = BSpline(t, c, k)
+
+        # b is continuous at x != 6 (triple knot)
+        x = np.asarray([1, 3, 4, 6])
+        xp_assert_close(b(x[x != 6] - 1e-10),
+                        b(x[x != 6] + 1e-10))
+        assert not np.allclose(b(6.-1e-10), b(6+1e-10))
+
+        # 1st derivative jumps at double knots, 1 & 6:
+        x0 = np.asarray([3, 4])
+        xp_assert_close(b(x0 - 1e-10, nu=1),
+                        b(x0 + 1e-10, nu=1))
+        x1 = np.asarray([1, 6])
+        assert not np.allclose(b(x1 - 1e-10, nu=1), b(x1 + 1e-10, nu=1))
+
+        # 2nd derivative is not guaranteed to be continuous either
+        assert not np.allclose(b(x - 1e-10, nu=2), b(x + 1e-10, nu=2))
+
+    @skip_xp_backends("cupy", reason="CuPy doesn't raise")
+    def test_basis_element_invalid_too_short(self, xp):
+        # There should be at least 2 knots
+        assert_raises(ValueError, BSpline.basis_element, **dict(t=xp.asarray([0])))
+        assert_raises(ValueError, BSpline.basis_element, **dict(t=xp.asarray([])))
+
+    def test_basis_element_quadratic(self, xp):
+        xx = xp.linspace(-1, 4, 20)
+        b = BSpline.basis_element(t=xp.asarray([0, 1, 2, 3]))
+
+        xx_np, t_np, c_np = map(_xp_copy_to_numpy, (xx, b.t, b.c))
+        splev_result = xp.asarray(splev(xx_np, (t_np, c_np, b.k)))
+        xp_assert_close(b(xx), splev_result, atol=1e-14)
+
+        atol=1e-14 if xp_default_dtype(xp) == xp.float64 else 1e-7
+        xp_assert_close(b(xx), xp.asarray(B_0123(xx), dtype=xp.float64), atol=atol)
+
+        b = BSpline.basis_element(t=xp.asarray([0, 1, 1, 2]))
+        xx = xp.linspace(0, 2, 10, dtype=xp.float64)
+        xp_assert_close(b(xx),
+                xp.where(xx < 1, xx*xx, (2.-xx)**2), atol=1e-14)
+
+    def test_basis_element_rndm(self):
+        b = _make_random_spline()
+        t, c, k = b.tck
+        xx = np.linspace(t[k], t[-k-1], 20)
+        xp_assert_close(b(xx), _sum_basis_elements(xx, t, c, k), atol=1e-14)
+
+    def test_cmplx(self):
+        b = _make_random_spline()
+        t, c, k = b.tck
+        cc = c * (1. + 3.j)
+
+        b = BSpline(t, cc, k)
+        b_re = BSpline(t, b.c.real, k)
+        b_im = BSpline(t, b.c.imag, k)
+
+        xx = np.linspace(t[k], t[-k-1], 20)
+        xp_assert_close(b(xx).real, b_re(xx), atol=1e-14)
+        xp_assert_close(b(xx).imag, b_im(xx), atol=1e-14)
+
+    def test_nan(self, xp):
+        # nan in, nan out.
+        b = BSpline.basis_element(xp.asarray([0, 1, 1, 2]))
+        assert xp.isnan(b(xp.nan))
+
+    def test_derivative_method(self, xp):
+        b = _make_random_spline(k=5, xp=xp)
+        t, c, k = b.tck
+        b0 = BSpline(t, c, k)
+        xx = xp.linspace(t[k], t[-k-1], 20)
+        for j in range(1, k):
+            b = b.derivative()
+            xp_assert_close(b0(xx, j), b(xx), atol=1e-12, rtol=1e-12)
+
+    def test_antiderivative_method(self, xp):
+        b = _make_random_spline(xp=xp)
+        t, c, k = b.tck
+        xx = xp.linspace(t[k], t[-k-1], 20)
+        xp_assert_close(b.antiderivative().derivative()(xx),
+                        b(xx), atol=1e-14, rtol=1e-14)
+
+        # repeat with N-D array for c
+        c = xp.stack((c, c, c), axis=1)
+        c = xp.stack((c, c), axis=2)
+        b = BSpline(t, c, k)
+        xp_assert_close(b.antiderivative().derivative()(xx),
+                        b(xx), atol=1e-14, rtol=1e-14)
+
+    def test_integral(self, xp):
+        b = BSpline.basis_element(xp.asarray([0, 1, 2]))  # x for x < 1 else 2 - x
+        assert math.isclose(b.integrate(0, 1), 0.5, abs_tol=1e-14)
+        assert math.isclose(b.integrate(1, 0), -1 * 0.5, abs_tol=1e-14)
+        assert math.isclose(b.integrate(1, 0), -0.5, abs_tol=1e-14)
+
+
+        assert math.isclose(b.integrate(0, 1), 0.5, abs_tol=1e-14)
+        assert math.isclose(b.integrate(1, 0), -1 * 0.5, abs_tol=1e-14)
+        assert math.isclose(b.integrate(1, 0), -0.5, abs_tol=1e-14)
+
+        # extrapolate or zeros outside of [0, 2]; default is yes
+        assert math.isclose(b.integrate(-1, 1), 0.0, abs_tol=1e-14)
+        assert math.isclose(b.integrate(-1, 1, extrapolate=True), 0.0, abs_tol=1e-14)
+        assert math.isclose(b.integrate(-1, 1, extrapolate=False), 0.5, abs_tol=1e-14)
+        assert math.isclose(b.integrate(1, -1, extrapolate=False), -0.5, abs_tol=1e-14)
+
+        # Test ``_fitpack._splint()``
+        assert math.isclose(b.integrate(1, -1, extrapolate=False),
+                            _impl.splint(1, -1, map(_xp_copy_to_numpy, b.tck)),
+                            abs_tol=1e-14)
+
+    @xfail_xp_backends("cupy", reason="CuPy periodic extrapolation seems broken")
+    def test_integral_periodic(self, xp):
+        # Test ``extrapolate='periodic'``.
+        b = BSpline.basis_element(xp.asarray([0, 1, 2]))  # x for x < 1 else 2 - x
+        b.extrapolate = 'periodic'
+        i = b.antiderivative()
+        period_int = xp.asarray(i(2) - i(0), dtype=xp.float64)
+
+        assert math.isclose(b.integrate(0, 2), period_int)
+        assert math.isclose(b.integrate(2, 0), -1 * period_int)
+        assert math.isclose(b.integrate(-9, -7), period_int)
+        assert math.isclose(b.integrate(-8, -4), 2 * period_int)
+
+        xp_assert_close(b.integrate(0.5, 1.5),
+                        xp.asarray(i(1.5) - i(0.5)))
+        xp_assert_close(b.integrate(1.5, 3),
+                        xp.asarray(i(1) - i(0) + i(2) - i(1.5)))
+        xp_assert_close(b.integrate(1.5 + 12, 3 + 12),
+                        xp.asarray(i(1) - i(0) + i(2) - i(1.5)))
+        xp_assert_close(b.integrate(1.5, 3 + 12),
+                        xp.asarray(i(1) - i(0) + i(2) - i(1.5) + 6 * period_int))
+
+        xp_assert_close(b.integrate(0, -1), xp.asarray(i(0) - i(1)))
+        xp_assert_close(b.integrate(-9, -10), xp.asarray(i(0) - i(1)))
+        xp_assert_close(b.integrate(0, -9),
+                        xp.asarray(i(1) - i(2) - 4 * period_int))
+
+    def test_integrate_ppoly(self):
+        # test .integrate method to be consistent with PPoly.integrate
+        x = [0, 1, 2, 3, 4]
+        b = make_interp_spline(x, x)
+        b.extrapolate = 'periodic'
+        p = PPoly.from_spline(b)
+
+        for x0, x1 in [(-5, 0.5), (0.5, 5), (-4, 13)]:
+            xp_assert_close(b.integrate(x0, x1),
+                            p.integrate(x0, x1))
+
+    def test_integrate_0D_always(self):
+        # make sure the result is always a 0D array (not a python scalar)
+        b = BSpline.basis_element([0, 1, 2])
+        for extrapolate in (True, False):
+            res = b.integrate(0, 1, extrapolate=extrapolate)
+            assert isinstance(res, np.ndarray)
+            assert res.ndim == 0
+
+    def test_subclassing(self):
+        # classmethods should not decay to the base class
+        class B(BSpline):
+            pass
+
+        b = B.basis_element([0, 1, 2, 2])
+        assert b.__class__ == B
+        assert b.derivative().__class__ == B
+        assert b.antiderivative().__class__ == B
+
+    @pytest.mark.parametrize('axis', range(-4, 4))
+    def test_axis(self, axis, xp):
+        n, k = 22, 3
+        t = xp.linspace(0, 1, n + k + 1)
+        sh = [6, 7, 8]
+        # We need the positive axis for some of the indexing and slices used
+        # in this test.
+        pos_axis = axis % 4
+        sh.insert(pos_axis, n)   # [22, 6, 7, 8] etc
+        sh = tuple(sh)
+        rng = np.random.RandomState(1234)
+        c = xp.asarray(rng.random(size=sh))
+        b = BSpline(t, c, k, axis=axis)
+        assert b.c.shape == (sh[pos_axis],) + sh[:pos_axis] + sh[pos_axis+1:]
+
+        xp = rng.random((3, 4, 5))
+        assert b(xp).shape == sh[:pos_axis] + xp.shape + sh[pos_axis+1:]
+
+        # -c.ndim <= axis < c.ndim
+        for ax in [-c.ndim - 1, c.ndim]:
+            assert_raises(AxisError, BSpline,
+                          **dict(t=t, c=c, k=k, axis=ax))
+
+        # derivative, antiderivative keeps the axis
+        for b1 in [BSpline(t, c, k, axis=axis).derivative(),
+                   BSpline(t, c, k, axis=axis).derivative(2),
+                   BSpline(t, c, k, axis=axis).antiderivative(),
+                   BSpline(t, c, k, axis=axis).antiderivative(2)]:
+            assert b1.axis == b.axis
+
+    def test_neg_axis(self, xp):
+        k = 2
+        t = xp.asarray([0, 1, 2, 3, 4, 5, 6])
+        c = xp.asarray([[-1, 2, 0, -1], [2, 0, -3, 1]])
+
+        spl = BSpline(t, c, k, axis=-1)
+        spl0 = BSpline(t, c[0, :], k)
+        spl1 = BSpline(t, c[1, :], k)
+        xp_assert_equal(spl(2.5), xp.stack([spl0(2.5), spl1(2.5)]))
+
+    def test_design_matrix_bc_types(self):
+        '''
+        Splines with different boundary conditions are built on different
+        types of vectors of knots. As far as design matrix depends only on
+        vector of knots, `k` and `x` it is useful to make tests for different
+        boundary conditions (and as following different vectors of knots).
+        '''
+        def run_design_matrix_tests(n, k, bc_type):
+            '''
+            To avoid repetition of code the following function is provided.
+            '''
+            rng = np.random.RandomState(1234)
+            x = np.sort(rng.random_sample(n) * 40 - 20)
+            y = rng.random_sample(n) * 40 - 20
+            if bc_type == "periodic":
+                y[0] = y[-1]
+
+            bspl = make_interp_spline(x, y, k=k, bc_type=bc_type)
+
+            c = np.eye(len(bspl.t) - k - 1)
+            des_matr_def = BSpline(bspl.t, c, k)(x)
+            des_matr_csr = BSpline.design_matrix(x,
+                                                 bspl.t,
+                                                 k).toarray()
+            xp_assert_close(des_matr_csr @ bspl.c, y, atol=1e-14)
+            xp_assert_close(des_matr_def, des_matr_csr, atol=1e-14)
+
+        # "clamped" and "natural" work only with `k = 3`
+        n = 11
+        k = 3
+        for bc in ["clamped", "natural"]:
+            run_design_matrix_tests(n, k, bc)
+
+        # "not-a-knot" works with odd `k`
+        for k in range(3, 8, 2):
+            run_design_matrix_tests(n, k, "not-a-knot")
+
+        # "periodic" works with any `k` (even more than `n`)
+        n = 5  # smaller `n` to test `k > n` case
+        for k in range(2, 7):
+            run_design_matrix_tests(n, k, "periodic")
+
+    @pytest.mark.parametrize('extrapolate', [False, True, 'periodic'])
+    @pytest.mark.parametrize('degree', range(5))
+    def test_design_matrix_same_as_BSpline_call(self, extrapolate, degree):
+        """Test that design_matrix(x) is equivalent to BSpline(..)(x)."""
+        rng = np.random.RandomState(1234)
+        x = rng.random_sample(10 * (degree + 1))
+        xmin, xmax = np.amin(x), np.amax(x)
+        k = degree
+        t = np.r_[np.linspace(xmin - 2, xmin - 1, degree),
+                  np.linspace(xmin, xmax, 2 * (degree + 1)),
+                  np.linspace(xmax + 1, xmax + 2, degree)]
+        c = np.eye(len(t) - k - 1)
+        bspline = BSpline(t, c, k, extrapolate)
+        xp_assert_close(
+            bspline(x), BSpline.design_matrix(x, t, k, extrapolate).toarray()
+        )
+
+        # extrapolation regime
+        x = np.array([xmin - 10, xmin - 1, xmax + 1.5, xmax + 10])
+        if not extrapolate:
+            with pytest.raises(ValueError):
+                BSpline.design_matrix(x, t, k, extrapolate)
+        else:
+            xp_assert_close(
+                bspline(x),
+                BSpline.design_matrix(x, t, k, extrapolate).toarray()
+            )
+
+    def test_design_matrix_x_shapes(self):
+        # test for different `x` shapes
+        rng = np.random.RandomState(1234)
+        n = 10
+        k = 3
+        x = np.sort(rng.random_sample(n) * 40 - 20)
+        y = rng.random_sample(n) * 40 - 20
+
+        bspl = make_interp_spline(x, y, k=k)
+        for i in range(1, 4):
+            xc = x[:i]
+            yc = y[:i]
+            des_matr_csr = BSpline.design_matrix(xc,
+                                                 bspl.t,
+                                                 k).toarray()
+            xp_assert_close(des_matr_csr @ bspl.c, yc, atol=1e-14)
+
+    def test_design_matrix_t_shapes(self):
+        # test for minimal possible `t` shape
+        t = [1., 1., 1., 2., 3., 4., 4., 4.]
+        des_matr = BSpline.design_matrix(2., t, 3).toarray()
+        xp_assert_close(des_matr,
+                        [[0.25, 0.58333333, 0.16666667, 0.]],
+                        atol=1e-14)
+
+    def test_design_matrix_asserts(self):
+        rng = np.random.RandomState(1234)
+        n = 10
+        k = 3
+        x = np.sort(rng.random_sample(n) * 40 - 20)
+        y = rng.random_sample(n) * 40 - 20
+        bspl = make_interp_spline(x, y, k=k)
+        # invalid vector of knots (should be a 1D non-descending array)
+        # here the actual vector of knots is reversed, so it is invalid
+        with assert_raises(ValueError):
+            BSpline.design_matrix(x, bspl.t[::-1], k)
+        k = 2
+        t = [0., 1., 2., 3., 4., 5.]
+        x = [1., 2., 3., 4.]
+        # out of bounds
+        with assert_raises(ValueError):
+            BSpline.design_matrix(x, t, k)
+
+    @pytest.mark.parametrize('bc_type', ['natural', 'clamped',
+                                         'periodic', 'not-a-knot'])
+    def test_from_power_basis(self, bc_type):
+        # TODO: convert CubicSpline
+        rng = np.random.RandomState(1234)
+        x = np.sort(rng.random(20))
+        y = rng.random(20)
+        if bc_type == 'periodic':
+            y[-1] = y[0]
+        cb = CubicSpline(x, y, bc_type=bc_type)
+        bspl = BSpline.from_power_basis(cb, bc_type=bc_type)
+        xx = np.linspace(0, 1, 20)
+        xp_assert_close(cb(xx), bspl(xx), atol=1e-15)
+        bspl_new = make_interp_spline(x, y, bc_type=bc_type)
+        xp_assert_close(bspl.c, bspl_new.c, atol=1e-15)
+
+    @pytest.mark.parametrize('bc_type', ['natural', 'clamped',
+                                         'periodic', 'not-a-knot'])
+    def test_from_power_basis_complex(self, bc_type):
+        # TODO: convert CubicSpline
+        rng = np.random.RandomState(1234)
+        x = np.sort(rng.random(20))
+        y = rng.random(20) + rng.random(20) * 1j
+        if bc_type == 'periodic':
+            y[-1] = y[0]
+        cb = CubicSpline(x, y, bc_type=bc_type)
+        bspl = BSpline.from_power_basis(cb, bc_type=bc_type)
+        bspl_new_real = make_interp_spline(x, y.real, bc_type=bc_type)
+        bspl_new_imag = make_interp_spline(x, y.imag, bc_type=bc_type)
+        xp_assert_close(bspl.c, bspl_new_real.c + 1j * bspl_new_imag.c, atol=1e-15)
+
+    def test_from_power_basis_exmp(self):
+        '''
+        For x = [0, 1, 2, 3, 4] and y = [1, 1, 1, 1, 1]
+        the coefficients of Cubic Spline in the power basis:
+
+        $[[0, 0, 0, 0, 0],\\$
+        $[0, 0, 0, 0, 0],\\$
+        $[0, 0, 0, 0, 0],\\$
+        $[1, 1, 1, 1, 1]]$
+
+        It could be shown explicitly that coefficients of the interpolating
+        function in B-spline basis are c = [1, 1, 1, 1, 1, 1, 1]
+        '''
+        x = np.array([0, 1, 2, 3, 4])
+        y = np.array([1, 1, 1, 1, 1])
+        bspl = BSpline.from_power_basis(CubicSpline(x, y, bc_type='natural'),
+                                        bc_type='natural')
+        xp_assert_close(bspl.c, [1.0, 1, 1, 1, 1, 1, 1], atol=1e-15)
+
+    def test_read_only(self):
+        # BSpline must work on read-only knots and coefficients.
+        t = np.array([0, 1])
+        c = np.array([3.0])
+        t.setflags(write=False)
+        c.setflags(write=False)
+
+        xx = np.linspace(0, 1, 10)
+        xx.setflags(write=False)
+
+        b = BSpline(t=t, c=c, k=0)
+        xp_assert_close(b(xx), np.ones_like(xx) * 3.0)
+
+    def test_concurrency(self, xp):
+        # Check that no segfaults appear with concurrent access to BSpline
+        b = _make_random_spline(xp=xp)
+
+        def worker_fn(_, b):
+            t, _, k = b.tck
+            xx = xp.linspace(t[k], t[-k-1], 10000)
+            b(xx)
+
+        _run_concurrent_barrier(10, worker_fn, b)
+
+
+    @pytest.mark.xfail(
+        sys.platform == "cygwin",
+        reason="threading.get_native_id not implemented",
+        raises=AttributeError
+    )
+    def test_memmap(self, tmpdir):
+        # Make sure that memmaps can be used as t and c atrributes after the
+        # spline has been constructed. This is similar to what happens in a
+        # scikit-learn context, where joblib can create read-only memmap to
+        # share objects between workers. For more details, see
+        # https://github.com/scipy/scipy/issues/22143
+        b = _make_random_spline()
+        xx = np.linspace(0, 1, 10)
+
+        expected = b(xx)
+
+        tid = threading.get_native_id()
+        t_mm = np.memmap(str(tmpdir.join(f't{tid}.dat')), mode='w+',
+                         dtype=b.t.dtype, shape=b.t.shape)
+        t_mm[:] = b.t
+        c_mm = np.memmap(str(tmpdir.join(f'c{tid}.dat')), mode='w+',
+                         dtype=b.c.dtype, shape=b.c.shape)
+        c_mm[:] = b.c
+        b.t = t_mm
+        b.c = c_mm
+
+        xp_assert_close(b(xx), expected)
+
+
+@make_xp_test_case((BSpline, "insert_knot"))
+class TestInsert:
+
+    @pytest.mark.parametrize('xval', [0.0, 1.0, 2.5, 4, 6.5, 7.0])
+    def test_insert(self, xval, xp):
+        # insert a knot, incl edges (0.0, 7.0) and exactly at an existing knot (4.0)
+        x = xp.arange(8, dtype=xp.float64)
+        y = xp.sin(x)**3
+        spl = make_interp_spline(x, y, k=3)
+
+        tck = (_xp_copy_to_numpy(spl.t), _xp_copy_to_numpy(spl.c), spl.k)
+        spl_1f = BSpline(*insert(xval, tck))     # FITPACK
+        spl_1 = spl.insert_knot(xval)
+
+        xp_assert_close(spl_1.t, xp.asarray(spl_1f.t), atol=1e-15)
+        xp_assert_close(spl_1.c, xp.asarray(spl_1f.c[:-spl.k-1]), atol=1e-15)
+
+        # knot insertion preserves values, unless multiplicity >= k+1
+        xx = x if xval != x[-1] else x[:-1]
+        xx = xp.concat((xx, 0.5*(x[1:] + x[:-1])))
+        xp_assert_close(spl(xx), spl_1(xx), atol=1e-15)
+
+        # ... repeat with ndim > 1
+        y1 = xp.cos(x)**3
+        spl_y1 = make_interp_spline(x, y1, k=3)
+        spl_yy = make_interp_spline(x, xp.stack((y, y1), axis=1), k=3)
+        spl_yy1 = spl_yy.insert_knot(xval)
+
+        xp_assert_close(spl_yy1.t, spl_1.t, atol=1e-15)
+        xp_assert_close(
+            spl_yy1.c,
+            xp.stack((spl.insert_knot(xval).c, spl_y1.insert_knot(xval).c), axis=1),
+            atol=1e-15
+        )
+
+        xx = x if xval != x[-1] else x[:-1]
+        xx = xp.concat((xx, 0.5*(x[1:] + x[:-1])))
+        xp_assert_close(spl_yy(xx), spl_yy1(xx), atol=1e-15)
+
+
+    @pytest.mark.parametrize(
+        'xval, m', [(0.0, 2), (1.0, 3), (1.5, 5), (4, 2), (7.0, 2)]
+    )
+    def test_insert_multi(self, xval, m, xp):
+        x = xp.arange(8, dtype=xp.float64)
+        y = xp.sin(x)**3
+        spl = make_interp_spline(x, y, k=3)
+
+        spl_1f = BSpline(
+            *insert(
+                xval, (_xp_copy_to_numpy(spl.t), _xp_copy_to_numpy(spl.c), spl.k), m=m
+            )
+        )
+        spl_1 = spl.insert_knot(xval, m)
+
+        xp_assert_close(spl_1.t, xp.asarray(spl_1f.t), atol=1e-15)
+        xp_assert_close(spl_1.c, xp.asarray(spl_1f.c[:-spl.k-1]), atol=1e-15)
+
+        xx = x if xval != x[-1] else x[:-1]
+        xx = xp.concat((xx, 0.5*(x[1:] + x[:-1])))
+        xp_assert_close(spl(xx), spl_1(xx), atol=1e-15)
+
+    def test_insert_random(self, xp):
+        rng = np.random.default_rng(12345)
+        n, k = 11, 3
+
+        t = xp.asarray(np.sort(rng.uniform(size=n+k+1)))
+        c = xp.asarray(rng.uniform(size=(n, 3, 2)))
+        spl = BSpline(t, c, k)
+
+        xv = xp.asarray(rng.uniform(low=t[k+1], high=t[-k-1]))
+        spl_1 = spl.insert_knot(xv)
+
+        xx = xp.asarray(rng.uniform(low=t[k+1], high=t[-k-1], size=33))
+        xp_assert_close(spl(xx), spl_1(xx), atol=1e-15)
+
+    @pytest.mark.parametrize('xv', [0, 0.1, 2.0, 4.0, 4.5,      # l.h. edge
+                                    5.5, 6.0, 6.1, 7.0]         # r.h. edge
+    )
+    def test_insert_periodic(self, xv, xp):
+        x = xp.arange(8, dtype=xp.float64)
+        y = xp.sin(x)**3
+        t, c, k = splrep(x, y, k=3)
+        t, c = map(xp.asarray, (t, c))
+        spl = BSpline(t, c, k, extrapolate="periodic")
+
+        spl_1 = spl.insert_knot(xv)
+        tf, cf, k = insert(xv, spl.tck, per=True)
+
+        xp_assert_close(spl_1.t, xp.asarray(tf), atol=1e-15)
+        xp_assert_close(spl_1.c[:-k-1], xp.asarray(cf[:-k-1]), atol=1e-15)
+
+        xx_np = np.random.default_rng(1234).uniform(low=0, high=7, size=41)
+        xx = xp.asarray(xx_np)
+        xp_assert_close(spl_1(xx), xp.asarray(splev(xx_np, (tf, cf, k))), atol=1e-15)
+
+    @pytest.mark.parametrize('extrapolate', [None, 'periodic'])
+    def test_complex(self, extrapolate, xp):
+        x = xp.arange(8, dtype=xp.float64) * 2 * np.pi
+        y_re, y_im = xp.sin(x), xp.cos(x)
+
+        spl = make_interp_spline(x, y_re + 1j*y_im, k=3)
+        spl.extrapolate = extrapolate
+
+        spl_re = make_interp_spline(x, y_re, k=3)
+        spl_re.extrapolate = extrapolate
+
+        spl_im = make_interp_spline(x, y_im, k=3)
+        spl_im.extrapolate = extrapolate
+
+        xv = 3.5
+        spl_1 = spl.insert_knot(xv)
+        spl_1re = spl_re.insert_knot(xv)
+        spl_1im = spl_im.insert_knot(xv)
+
+        xp_assert_close(spl_1.t, spl_1re.t, atol=1e-15)
+        xp_assert_close(spl_1.t, spl_1im.t, atol=1e-15)
+        xp_assert_close(spl_1.c, spl_1re.c + 1j*spl_1im.c, atol=1e-15)
+
+    def test_insert_periodic_too_few_internal_knots(self):
+        # both FITPACK and spl.insert_knot raise when there's not enough
+        # internal knots to make a periodic extension.
+        # Below the internal knots are 2, 3,    , 4, 5
+        #                                     ^
+        #                              2, 3, 3.5, 4, 5
+        #   so two knots from each side from the new one, while need at least
+        #   from either left or right.
+        xv = 3.5
+        k = 3
+        t = np.array([0]*(k+1) + [2, 3, 4, 5] + [7]*(k+1))
+        c = np.ones(len(t) - k - 1)
+        spl = BSpline(t, c, k, extrapolate="periodic")
+
+        with assert_raises(ValueError):
+            insert(xv, (t, c, k), per=True)
+
+        with assert_raises(ValueError):
+            spl.insert_knot(xv)
+
+    def test_insert_no_extrap(self):
+        k = 3
+        t = np.array([0]*(k+1) + [2, 3, 4, 5] + [7]*(k+1))
+        c = np.ones(len(t) - k - 1)
+        spl = BSpline(t, c, k)
+
+        with assert_raises(ValueError):
+            spl.insert_knot(-1)
+
+        with assert_raises(ValueError):
+            spl.insert_knot(8)
+
+        with assert_raises(ValueError):
+            spl.insert_knot(3, m=0)
+
+
+def test_knots_multiplicity():
+    # Take a spline w/ random coefficients, throw in knots of varying
+    # multiplicity.
+
+    def check_splev(b, j, der=0, atol=1e-14, rtol=1e-14):
+        # check evaluations against FITPACK, incl extrapolations
+        t, c, k = b.tck
+        x = np.unique(t)
+        x = np.r_[t[0]-0.1, 0.5*(x[1:] + x[:1]), t[-1]+0.1]
+        xp_assert_close(splev(x, (t, c, k), der), b(x, der),
+                atol=atol, rtol=rtol, err_msg=f'der = {der}  k = {b.k}')
+
+    # test loop itself
+    # [the index `j` is for interpreting the traceback in case of a failure]
+    for k in [1, 2, 3, 4, 5]:
+        b = _make_random_spline(k=k)
+        for j, b1 in enumerate(_make_multiples(b)):
+            check_splev(b1, j)
+            for der in range(1, k+1):
+                check_splev(b1, j, der, 1e-12, 1e-12)
+
+
+def _naive_B(x, k, i, t):
+    """
+    Naive way to compute B-spline basis functions. Useful only for testing!
+    computes B(x; t[i],..., t[i+k+1])
+    """
+    if k == 0:
+        return 1.0 if t[i] <= x < t[i+1] else 0.0
+    if t[i+k] == t[i]:
+        c1 = 0.0
+    else:
+        c1 = (x - t[i])/(t[i+k] - t[i]) * _naive_B(x, k-1, i, t)
+    if t[i+k+1] == t[i+1]:
+        c2 = 0.0
+    else:
+        c2 = (t[i+k+1] - x)/(t[i+k+1] - t[i+1]) * _naive_B(x, k-1, i+1, t)
+    return (c1 + c2)
+
+
+def _naive_eval(x, t, c, k, *, xp):
+    """
+    Naive B-spline evaluation. Useful only for testing!
+    """
+    if x == t[k]:
+        i = k
+    else:
+        i = xp.searchsorted(t, x) - 1
+
+    assert t[i] <= x <= t[i+1]
+    assert i >= k and i < t.shape[0] - k
+    return sum(c[i-j] * _naive_B(x, k, i-j, t) for j in range(0, k+1))
+
+
+def _naive_eval_2(x, t, c, k, *, xp):
+    """Naive B-spline evaluation, another way."""
+    n = t.shape[0] - (k+1)
+    assert n >= k+1
+    assert c.shape[0] >= n
+    assert t[k] <= x <= t[n]
+    return sum(c[i] * _naive_B(x, k, i, t) for i in range(n))
+
+
+def _sum_basis_elements(x, t, c, k):
+    n = len(t) - (k+1)
+    assert n >= k+1
+    assert c.shape[0] >= n
+    s = 0.
+    for i in range(n):
+        b = BSpline.basis_element(t[i:i+k+2], extrapolate=False)(x)
+        s += c[i] * np.nan_to_num(b)   # zero out out-of-bounds elements
+    return s
+
+
+def B_012(x, xp=np):
+    """ A linear B-spline function B(x | 0, 1, 2)."""
+    x = np.atleast_1d(_xp_copy_to_numpy(x))
+    result = np.piecewise(x, [(x < 0) | (x > 2),
+                            (x >= 0) & (x < 1),
+                            (x >= 1) & (x <= 2)],
+                           [lambda x: 0., lambda x: x, lambda x: 2.-x])
+    return xp.asarray(result)
+
+
+def B_0123(x, der=0):
+    """A quadratic B-spline function B(x | 0, 1, 2, 3)."""
+    x = np.atleast_1d(_xp_copy_to_numpy(x))
+    conds = [x < 1, (x > 1) & (x < 2), x > 2]
+    if der == 0:
+        funcs = [lambda x: x*x/2.,
+                 lambda x: 3./4 - (x-3./2)**2,
+                 lambda x: (3.-x)**2 / 2]
+    elif der == 2:
+        funcs = [lambda x: 1.,
+                 lambda x: -2.,
+                 lambda x: 1.]
+    else:
+        raise ValueError(f'never be here: der={der}')
+    pieces = np.piecewise(x, conds, funcs)
+    return pieces
+
+
+def _make_random_spline(n=35, k=3, xp=np):
+    rng = np.random.RandomState(123)
+    t = np.sort(rng.random(n+k+1))
+    c = rng.random(n)
+    t, c = xp.asarray(t), xp.asarray(c)
+    return BSpline.construct_fast(t, c, k)
+
+
+def _make_multiples(b):
+    """Increase knot multiplicity."""
+    c, k = b.c, b.k
+
+    t1 = b.t.copy()
+    t1[17:19] = t1[17]
+    t1[22] = t1[21]
+    yield BSpline(t1, c, k)
+
+    t1 = b.t.copy()
+    t1[:k+1] = t1[0]
+    yield BSpline(t1, c, k)
+
+    t1 = b.t.copy()
+    t1[-k-1:] = t1[-1]
+    yield BSpline(t1, c, k)
+
+
+class TestInterop:
+    #
+    # Test that FITPACK-based spl* functions can deal with BSpline objects
+    #
+    def setup_method(self):
+        xx = np.linspace(0, 4.*np.pi, 41)
+        yy = np.cos(xx)
+        b = make_interp_spline(xx, yy)
+        self.tck = (b.t, b.c, b.k)
+        self.xx, self.yy, self.b = xx, yy, b
+
+        self.xnew = np.linspace(0, 4.*np.pi, 21)
+
+        c2 = np.c_[b.c, b.c, b.c]
+        self.c2 = np.dstack((c2, c2))
+        self.b2 = BSpline(b.t, self.c2, b.k)
+
+    def test_splev(self):
+        xnew, b, b2 = self.xnew, self.b, self.b2
+
+        # check that splev works with 1-D array of coefficients
+        # for array and scalar `x`
+        xp_assert_close(splev(xnew, b),
+                        b(xnew), atol=1e-15, rtol=1e-15)
+        xp_assert_close(splev(xnew, b.tck),
+                        b(xnew), atol=1e-15, rtol=1e-15)
+        xp_assert_close(np.asarray([splev(x, b) for x in xnew]),
+                        b(xnew), atol=1e-15, rtol=1e-15)
+
+        # With N-D coefficients, there's a quirck:
+        # splev(x, BSpline) is equivalent to BSpline(x)
+        with assert_raises(ValueError, match="Calling splev.. with BSpline"):
+            splev(xnew, b2)
+
+        # However, splev(x, BSpline.tck) needs some transposes. This is because
+        # BSpline interpolates along the first axis, while the legacy FITPACK
+        # wrapper does list(map(...)) which effectively interpolates along the
+        # last axis. Like so:
+        sh = tuple(range(1, b2.c.ndim)) + (0,)   # sh = (1, 2, 0)
+        cc = b2.c.transpose(sh)
+        tck = (b2.t, cc, b2.k)
+        xp_assert_close(np.asarray(splev(xnew, tck)),
+                        b2(xnew).transpose(sh), atol=1e-15, rtol=1e-15)
+
+    def test_splrep(self):
+        x, y = self.xx, self.yy
+        # test that "new" splrep is equivalent to _impl.splrep
+        tck = splrep(x, y)
+        t, c, k = _impl.splrep(x, y)
+        xp_assert_close(tck[0], t, atol=1e-15)
+        xp_assert_close(tck[1], c, atol=1e-15)
+        assert tck[2] == k
+
+        # also cover the `full_output=True` branch
+        tck_f, _, _, _ = splrep(x, y, full_output=True)
+        xp_assert_close(tck_f[0], t, atol=1e-15)
+        xp_assert_close(tck_f[1], c, atol=1e-15)
+        assert tck_f[2] == k
+
+        # test that the result of splrep roundtrips with splev:
+        # evaluate the spline on the original `x` points
+        yy = splev(x, tck)
+        xp_assert_close(y, yy, atol=1e-15)
+
+        # ... and also it roundtrips if wrapped in a BSpline
+        b = BSpline(*tck)
+        xp_assert_close(y, b(x), atol=1e-15)
+
+    def test_splrep_errors(self):
+        # test that both "old" and "new" splrep raise for an N-D ``y`` array
+        # with n > 1
+        x, y = self.xx, self.yy
+        y2 = np.c_[y, y]
+        with assert_raises(ValueError):
+            splrep(x, y2)
+        with assert_raises(ValueError):
+            _impl.splrep(x, y2)
+
+        # input below minimum size
+        with assert_raises(TypeError, match="m > k must hold"):
+            splrep(x[:3], y[:3])
+        with assert_raises(TypeError, match="m > k must hold"):
+            _impl.splrep(x[:3], y[:3])
+
+    def test_splprep(self):
+        x = np.arange(15, dtype=np.float64).reshape((3, 5))
+        b, u = splprep(x)
+        tck, u1 = _impl.splprep(x)
+
+        # test the roundtrip with splev for both "old" and "new" output
+        xp_assert_close(u, u1, atol=1e-15)
+        xp_assert_close(np.asarray(splev(u, b)), x, atol=1e-15)
+        xp_assert_close(np.asarray(splev(u, tck)), x, atol=1e-15)
+
+        # cover the ``full_output=True`` branch
+        (b_f, u_f), _, _, _ = splprep(x, s=0, full_output=True)
+        xp_assert_close(u, u_f, atol=1e-15)
+        xp_assert_close(np.asarray(splev(u_f, b_f)), x, atol=1e-15)
+
+    def test_splprep_errors(self):
+        # test that both "old" and "new" code paths raise for x.ndim > 2
+        x = np.arange(3*4*5).reshape((3, 4, 5))
+        with assert_raises(ValueError, match="too many values to unpack"):
+            splprep(x)
+        with assert_raises(ValueError, match="too many values to unpack"):
+            _impl.splprep(x)
+
+        # input below minimum size
+        x = np.linspace(0, 40, num=3)
+        with assert_raises(TypeError, match="m > k must hold"):
+            splprep([x])
+        with assert_raises(TypeError, match="m > k must hold"):
+            _impl.splprep([x])
+
+        # automatically calculated parameters are non-increasing
+        # see gh-7589
+        x = [-50.49072266, -50.49072266, -54.49072266, -54.49072266]
+        with assert_raises(ValueError, match="Error on input data"):
+            splprep([x])
+        with assert_raises(ValueError, match="Error on input data"):
+            _impl.splprep([x])
+
+        # given non-increasing parameter values u
+        x = [1, 3, 2, 4]
+        u = [0, 0.3, 0.2, 1]
+        with assert_raises(ValueError, match="Error on input data"):
+            splprep(*[[x], None, u])
+
+    def test_sproot(self):
+        b, b2 = self.b, self.b2
+        roots = np.array([0.5, 1.5, 2.5, 3.5])*np.pi
+        # sproot accepts a BSpline obj w/ 1-D coef array
+        xp_assert_close(sproot(b), roots, atol=1e-7, rtol=1e-7)
+        xp_assert_close(sproot((b.t, b.c, b.k)), roots, atol=1e-7, rtol=1e-7)
+
+        # ... and deals with trailing dimensions if coef array is N-D
+        with assert_raises(ValueError, match="Calling sproot.. with BSpline"):
+            sproot(b2, mest=50)
+
+        # and legacy behavior is preserved for a tck tuple w/ N-D coef
+        c2r = b2.c.transpose(1, 2, 0)
+        rr = np.asarray(sproot((b2.t, c2r, b2.k), mest=50))
+        assert rr.shape == (3, 2, 4)
+        xp_assert_close(rr - roots, np.zeros_like(rr), atol=1e-12)
+
+    def test_splint(self):
+        # test that splint accepts BSpline objects
+        b, b2 = self.b, self.b2
+
+        xp_assert_close(splint(0, 1, b),
+                        splint(0, 1, b.tck), atol=1e-14, check_0d=False)
+        xp_assert_close(splint(0, 1, b),
+                        b.integrate(0, 1), atol=1e-14, check_0d=False)
+
+        # ... and deals with N-D arrays of coefficients
+        with assert_raises(ValueError, match="Calling splint.. with BSpline"):
+            splint(0, 1, b2)
+
+        # and the legacy behavior is preserved for a tck tuple w/ N-D coef
+        c2r = b2.c.transpose(1, 2, 0)
+        integr = np.asarray(splint(0, 1, (b2.t, c2r, b2.k)))
+        assert integr.shape == (3, 2)
+        xp_assert_close(integr,
+                        splint(0, 1, b), atol=1e-14, check_shape=False)
+
+    def test_splder(self):
+        for b in [self.b, self.b2]:
+            # pad the c array (FITPACK convention)
+            ct = len(b.t) - len(b.c)
+            b_c = b.c.copy()
+            if ct > 0:
+                b_c = np.r_[b_c, np.zeros((ct,) + b_c.shape[1:])]
+
+            for n in [1, 2, 3]:
+                bd = splder(b)
+                tck_d = _impl.splder((b.t.copy(), b_c, b.k))
+                xp_assert_close(bd.t, tck_d[0], atol=1e-15)
+                xp_assert_close(bd.c, tck_d[1], atol=1e-15)
+                assert bd.k == tck_d[2]
+                assert isinstance(bd, BSpline)
+                assert isinstance(tck_d, tuple)  # back-compat: tck in and out
+
+    def test_splantider(self):
+        for b in [self.b, self.b2]:
+            # pad the c array (FITPACK convention)
+            ct = len(b.t) - len(b.c)
+            b_c = b.c.copy()
+            if ct > 0:
+                b_c = np.r_[b_c, np.zeros((ct,) + b_c.shape[1:])]
+
+            for n in [1, 2, 3]:
+                bd = splantider(b)
+                tck_d = _impl.splantider((b.t.copy(), b_c, b.k))
+                xp_assert_close(bd.t, tck_d[0], atol=1e-15)
+                xp_assert_close(bd.c, tck_d[1], atol=1e-15)
+                assert bd.k == tck_d[2]
+                assert isinstance(bd, BSpline)
+                assert isinstance(tck_d, tuple)  # back-compat: tck in and out
+
+    def test_insert(self):
+        b, b2, xx = self.b, self.b2, self.xx
+
+        j = b.t.size // 2
+        tn = 0.5*(b.t[j] + b.t[j+1])
+
+        bn, tck_n = insert(tn, b), insert(tn, (b.t, b.c, b.k))
+        xp_assert_close(splev(xx, bn),
+                        splev(xx, tck_n), atol=1e-15)
+        assert isinstance(bn, BSpline)
+        assert isinstance(tck_n, tuple)   # back-compat: tck in, tck out
+
+        # for N-D array of coefficients, BSpline.c needs to be transposed
+        # after that, the results are equivalent.
+        sh = tuple(range(b2.c.ndim))
+        c_ = b2.c.transpose(sh[1:] + (0,))
+        tck_n2 = insert(tn, (b2.t, c_, b2.k))
+
+        bn2 = insert(tn, b2)
+
+        # need a transpose for comparing the results, cf test_splev
+        xp_assert_close(np.asarray(splev(xx, tck_n2)).transpose(2, 0, 1),
+                        bn2(xx), atol=1e-15)
+        assert isinstance(bn2, BSpline)
+        assert isinstance(tck_n2, tuple)   # back-compat: tck in, tck out
+
+
+@make_xp_test_case(make_interp_spline)
+class TestInterp:
+    #
+    # Test basic ways of constructing interpolating splines.
+    #
+    xx = np.linspace(0., 2.*np.pi)
+    yy = np.sin(xx)
+
+    def _get_xy(self, xp):
+        return xp.asarray(self.xx), xp.asarray(self.yy)
+
+    def test_non_int_order(self):
+        with assert_raises(TypeError):
+            make_interp_spline(self.xx, self.yy, k=2.5)
+
+    def test_order_0(self, xp):
+        xx, yy = self._get_xy(xp)
+        b = make_interp_spline(xx, yy, k=0)
+        xp_assert_close(b(xx), yy, atol=1e-14, rtol=1e-14)
+        b = make_interp_spline(xx, yy, k=0, axis=-1)
+        xp_assert_close(b(xx), yy, atol=1e-14, rtol=1e-14)
+
+    def test_linear(self, xp):
+        xx, yy = self._get_xy(xp)
+        b = make_interp_spline(xx, yy, k=1)
+        xp_assert_close(b(xx), yy, atol=1e-14, rtol=1e-14)
+        b = make_interp_spline(xx, yy, k=1, axis=-1)
+        xp_assert_close(b(xx), yy, atol=1e-14, rtol=1e-14)
+
+    @pytest.mark.parametrize('k', [0, 1, 2, 3])
+    def test_incompatible_x_y(self, k):
+        x = [0, 1, 2, 3, 4, 5]
+        y = [0, 1, 2, 3, 4, 5, 6, 7]
+        with assert_raises(ValueError, match="Shapes of x"):
+            make_interp_spline(x, y, k=k)
+
+    @pytest.mark.parametrize('k', [0, 1, 2, 3])
+    def test_broken_x(self, k):
+        x = [0, 1, 1, 2, 3, 4]      # duplicates
+        y = [0, 1, 2, 3, 4, 5]
+        with assert_raises(ValueError, match="x to not have duplicates"):
+            make_interp_spline(x, y, k=k)
+
+        x = [0, 2, 1, 3, 4, 5]      # unsorted
+        with assert_raises(ValueError, match="Expect x to be a 1D strictly"):
+            make_interp_spline(x, y, k=k)
+
+        x = [0, 1, 2, 3, 4, 5]
+        x = np.asarray(x).reshape((1, -1))     # 1D
+        with assert_raises(ValueError, match="Expect x to be a 1D strictly"):
+            make_interp_spline(x, y, k=k)
+
+    def test_not_a_knot(self, xp):
+        xx, yy = self._get_xy(xp)
+        for k in [2, 3, 4, 5, 6, 7]:
+            b = make_interp_spline(xx, yy, k)
+            xp_assert_close(b(xx), yy, atol=1e-14, rtol=1e-14)
+
+    def test_periodic(self, xp):
+        xx, yy = self._get_xy(xp)
+
+        # k = 5 here for more derivatives
+        b = make_interp_spline(xx, yy, k=5, bc_type='periodic')
+        xp_assert_close(b(xx), yy, atol=1e-14, rtol=1e-14)
+        # in periodic case it is expected equality of k-1 first
+        # derivatives at the boundaries
+        for i in range(1, 5):
+            xp_assert_close(b(xx[0], nu=i), b(xx[-1], nu=i), atol=1e-11)
+        # tests for axis=-1
+        b = make_interp_spline(xx, yy, k=5, bc_type='periodic', axis=-1)
+        xp_assert_close(b(xx), yy, atol=1e-14, rtol=1e-14)
+        for i in range(1, 5):
+            xp_assert_close(b(xx[0], nu=i), b(xx[-1], nu=i), atol=1e-11)
+
+    @pytest.mark.parametrize('k', [2, 3, 4, 5, 6, 7])
+    def test_periodic_random(self, k, xp):
+        # tests for both cases (k > n and k <= n)
+        n = 5
+        rng = np.random.RandomState(1234)
+        x = np.sort(rng.random_sample(n) * 10)
+        y = rng.random_sample(n) * 100
+        y[0] = y[-1]
+        x, y = xp.asarray(x), xp.asarray(y)
+
+        b = make_interp_spline(x, y, k=k, bc_type='periodic')
+        xp_assert_close(b(x), y, atol=1e-14)
+
+    def test_periodic_axis(self, xp):
+        n = self.xx.shape[0]
+        rng = np.random.RandomState(1234)
+        x = rng.random_sample(n) * 2 * np.pi
+        x = np.sort(x)
+        x[0] = 0.
+        x[-1] = 2 * np.pi
+        y = np.zeros((2, n))
+        y[0] = np.sin(x)
+        y[1] = np.cos(x)
+        x, y = xp.asarray(x), xp.asarray(y)
+
+        b = make_interp_spline(x, y, k=5, bc_type='periodic', axis=1)
+        for i in range(n):
+            xp_assert_close(b(x[i]), y[:, i], atol=1e-14)
+        xp_assert_close(b(x[0]), b(x[-1]), atol=1e-14)
+
+    def test_periodic_points_exception(self):
+        # first and last points should match when periodic case expected
+        rng = np.random.RandomState(1234)
+        k = 5
+        n = 8
+        x = np.sort(rng.random_sample(n))
+        y = rng.random_sample(n)
+        y[0] = y[-1] - 1  # to be sure that they are not equal
+        with assert_raises(ValueError):
+            make_interp_spline(x, y, k=k, bc_type='periodic')
+
+    def test_periodic_knots_exception(self):
+        # `periodic` case does not work with passed vector of knots
+        rng = np.random.RandomState(1234)
+        k = 3
+        n = 7
+        x = np.sort(rng.random_sample(n))
+        y = rng.random_sample(n)
+        t = np.zeros(n + 2 * k)
+        with assert_raises(ValueError):
+            make_interp_spline(x, y, k, t, 'periodic')
+
+    @pytest.mark.parametrize('k', [2, 3, 4, 5])
+    def test_periodic_splev(self, k):
+        # comparison values of periodic b-spline with splev
+        b = make_interp_spline(self.xx, self.yy, k=k, bc_type='periodic')
+        tck = splrep(self.xx, self.yy, per=True, k=k)
+        spl = splev(self.xx, tck)
+        xp_assert_close(spl, b(self.xx), atol=1e-14)
+
+        # comparison derivatives of periodic b-spline with splev
+        for i in range(1, k):
+            spl = splev(self.xx, tck, der=i)
+            xp_assert_close(spl, b(self.xx, nu=i), atol=1e-10)
+
+    def test_periodic_cubic(self):
+        # comparison values of cubic periodic b-spline with CubicSpline
+        b = make_interp_spline(self.xx, self.yy, k=3, bc_type='periodic')
+        cub = CubicSpline(self.xx, self.yy, bc_type='periodic')
+        xp_assert_close(b(self.xx), cub(self.xx), atol=1e-14)
+
+        # edge case: Cubic interpolation on 3 points
+        rng = np.random.RandomState(1234)
+        n = 3
+        x = np.sort(rng.random_sample(n) * 10)
+        y = rng.random_sample(n) * 100
+        y[0] = y[-1]
+        b = make_interp_spline(x, y, k=3, bc_type='periodic')
+        cub = CubicSpline(x, y, bc_type='periodic')
+        xp_assert_close(b(x), cub(x), atol=1e-14)
+
+    def test_periodic_full_matrix(self):
+        # comparison values of cubic periodic b-spline with
+        # solution of the system with full matrix
+        k = 3
+        b = make_interp_spline(self.xx, self.yy, k=k, bc_type='periodic')
+        t = _periodic_knots(self.xx, k)
+        c = _make_interp_per_full_matr(self.xx, self.yy, t, k)
+        b1 = np.vectorize(lambda x: _naive_eval(x, t, c, k, xp=np))
+        xp_assert_close(b(self.xx), b1(self.xx), atol=1e-14)
+
+    def test_quadratic_deriv(self, xp):
+        xx, yy = self._get_xy(xp)
+        der = [(1, 8.)]  # order, value: f'(x) = 8.
+
+        # derivative at right-hand edge
+        b = make_interp_spline(xx, yy, k=2, bc_type=(None, der))
+        xp_assert_close(b(xx), yy, atol=1e-14, rtol=1e-14)
+        xp_assert_close(
+            b(xx[-1], 1),
+            xp.asarray(der[0][1], dtype=xp.float64),
+            atol=1e-14, rtol=1e-14, check_0d=False
+        )
+
+        # derivative at left-hand edge
+        b = make_interp_spline(xx, yy, k=2, bc_type=(der, None))
+        xp_assert_close(b(xx), yy, atol=1e-14, rtol=1e-14)
+        xp_assert_close(
+            b(xx[0], 1),
+            xp.asarray(der[0][1], dtype=xp.float64),
+            atol=1e-14, rtol=1e-14, check_0d=False
+        )
+
+    def test_cubic_deriv(self, xp):
+        xx, yy = self._get_xy(xp)
+        k = 3
+
+        # first derivatives at left & right edges:
+        der_l, der_r = [(1, 3.)], [(1, 4.)]
+        b = make_interp_spline(xx, yy, k, bc_type=(der_l, der_r))
+        xp_assert_close(b(xx), yy, atol=1e-14, rtol=1e-14)
+        xp_assert_close(
+            b(xx[0], 1),
+            xp.asarray(der_l[0][1], dtype=xp.float64), atol=1e-14, rtol=1e-14
+        )
+        xp_assert_close(
+            b(xx[-1], 1),
+            xp.asarray(der_r[0][1], dtype=xp.float64), atol=1e-14, rtol=1e-14
+        )
+
+        # 'natural' cubic spline, zero out 2nd derivatives at the boundaries
+        der_l, der_r = [(2, 0)], [(2, 0)]
+        b = make_interp_spline(xx, yy, k, bc_type=(der_l, der_r))
+        xp_assert_close(b(xx), yy, atol=1e-14, rtol=1e-14)
+
+    def test_quintic_derivs(self, xp):
+        k, n = 5, 7
+        x = xp.arange(n, dtype=xp.float64)
+        y = xp.sin(x)
+        der_l = [(1, -12.), (2, 1)]
+        der_r = [(1, 8.), (2, 3.)]
+        b = make_interp_spline(x, y, k=k, bc_type=(der_l, der_r))
+        xp_assert_close(b(x), y, atol=1e-14, rtol=1e-14)
+        xp_assert_close(xp.stack([b(x[0], 1), b(x[0], 2)]),
+                        xp.asarray([val for (nu, val) in der_l], dtype=xp.float64))
+        xp_assert_close(xp.stack([b(x[-1], 1), b(x[-1], 2)]),
+                        xp.asarray([val for (nu, val) in der_r], dtype=xp.float64))
+
+    @pytest.mark.xfail(reason='unstable')
+    def test_cubic_deriv_unstable(self):
+        # 1st and 2nd derivative at x[0], no derivative information at x[-1]
+        # The problem is not that it fails [who would use this anyway],
+        # the problem is that it fails *silently*, and I've no idea
+        # how to detect this sort of instability.
+        # In this particular case: it's OK for len(t) < 20, goes haywire
+        # at larger `len(t)`.
+        k = 3
+        t = _augknt(self.xx, k)
+
+        der_l = [(1, 3.), (2, 4.)]
+        b = make_interp_spline(self.xx, self.yy, k, t, bc_type=(der_l, None))
+        xp_assert_close(b(self.xx), self.yy, atol=1e-14, rtol=1e-14)
+
+    def test_knots_not_data_sites(self, xp):
+        # Knots need not coincide with the data sites.
+        # use a quadratic spline, knots are at data averages,
+        # two additional constraints are zero 2nd derivatives at edges
+        k = 2
+        xx, yy = self._get_xy(xp)
+
+        t = concat_1d(xp,
+                xp.ones(k+1) * xx[0],
+                (xx[1:] + xx[:-1]) / 2.,
+                xp.ones(k+1) * xx[-1]
+        )
+        b = make_interp_spline(xx, yy, k, t,
+                               bc_type=([(2, 0)], [(2, 0)]))
+
+        xp_assert_close(b(xx), yy, atol=1e-14, rtol=1e-14)
+        assert math.isclose(b(xx[0], 2), 0.0, abs_tol=1e-14)
+        assert math.isclose(b(xx[-1], 2), 0.0, abs_tol=1e-14)
+
+    def test_minimum_points_and_deriv(self, xp):
+        # interpolation of f(x) = x**3 between 0 and 1. f'(x) = 3 * xx**2 and
+        # f'(0) = 0, f'(1) = 3.
+        k = 3
+        x = xp.asarray([0., 1.])
+        y = xp.asarray([0., 1.])
+        b = make_interp_spline(x, y, k, bc_type=([(1, 0.)], [(1, 3.)]))
+
+        xx = xp.linspace(0., 1., 21, dtype=xp.float64)
+        yy = xx**3
+        xp_assert_close(b(xx), yy, atol=1e-14, rtol=1e-14)
+
+    def test_deriv_spec(self):
+        # If one of the derivatives is omitted, the spline definition is
+        # incomplete.
+        x = y = [1.0, 2, 3, 4, 5, 6]
+
+        with assert_raises(ValueError):
+            make_interp_spline(x, y, bc_type=([(1, 0.)], None))
+
+        with assert_raises(ValueError):
+            make_interp_spline(x, y, bc_type=(1, 0.))
+
+        with assert_raises(ValueError):
+            make_interp_spline(x, y, bc_type=[(1, 0.)])
+
+        with assert_raises(ValueError):
+            make_interp_spline(x, y, bc_type=42)
+
+        # CubicSpline expects`bc_type=(left_pair, right_pair)`, while
+        # here we expect `bc_type=(iterable, iterable)`.
+        l, r = (1, 0.0), (1, 0.0)
+        with assert_raises(ValueError):
+            make_interp_spline(x, y, bc_type=(l, r))
+
+    def test_deriv_order_too_large(self, xp):
+        x = xp.arange(7)
+        y = x**2
+        l, r = [(6, 0)], [(1, 0)]    # 6th derivative = 0 at x[0] for k=3
+        with assert_raises(ValueError, match="Bad boundary conditions at 0."):
+            # cannot fix 6th derivative at x[0]: does not segfault
+            make_interp_spline(x, y, bc_type=(l, r))
+
+        l, r = [(1, 0)], [(-6, 0)]    # derivative order < 0 at x[-1]
+        with assert_raises(ValueError, match="Bad boundary conditions at 6."):
+            # does not segfault
+            make_interp_spline(x, y, bc_type=(l, r))
+
+    def test_complex(self, xp):
+        k = 3
+        xx, yy = self._get_xy(xp)
+        yy = yy + 1.j*yy
+
+        # first derivatives at left & right edges:
+        der_l, der_r = [(1, 3.j)], [(1, 4.+2.j)]
+        b = make_interp_spline(xx, yy, k, bc_type=(der_l, der_r))
+        xp_assert_close(b(xx), yy, atol=1e-14, rtol=1e-14)
+        assert cmath.isclose(b(xx[0], 1), der_l[0][1], abs_tol=1e-14)
+        assert cmath.isclose(b(xx[-1], 1), der_r[0][1], abs_tol=1e-14)
+
+        # also test zero and first order
+        for k in (0, 1):
+            b = make_interp_spline(xx, yy, k=k)
+            xp_assert_close(b(xx), yy, atol=1e-14, rtol=1e-14)
+
+    def test_int_xy(self, xp):
+        x = xp.arange(10, dtype=xp.int32)
+        y = xp.arange(10, dtype=xp.int32)
+
+        # Cython chokes on "buffer type mismatch" (construction) or
+        # "no matching signature found" (evaluation)
+        for k in (0, 1, 2, 3):
+            b = make_interp_spline(x, y, k=k)
+            b(x)
+
+    def test_sliced_input(self, xp):
+        # Cython code chokes on non C contiguous arrays
+        xx = xp.linspace(-1, 1, 100)
+
+        x = xx[::5]
+        y = xx[::5]
+
+        for k in (0, 1, 2, 3):
+            make_interp_spline(x, y, k=k)
+
+    def test_check_finite(self, xp):
+        # check_finite defaults to True; nans and such trigger a ValueError
+        x = xp.arange(10, dtype=xp.float64)
+        y = x**2
+
+        for z in [xp.nan, xp.inf, -xp.inf]:
+            y = xpx.at(y, -1).set(z)
+            assert_raises(ValueError, make_interp_spline, x, y)
+
+    @pytest.mark.parametrize('k', [1, 2, 3, 5])
+    def test_list_input(self, k):
+        # regression test for gh-8714: TypeError for x, y being lists and k=2
+        x = list(range(10))
+        y = [a**2 for a in x]
+        make_interp_spline(x, y, k=k)
+
+    def test_multiple_rhs(self, xp):
+        xx, yy = self._get_xy(xp)
+        yy = xp.stack((xx, yy), axis=1)
+        der_l = [(1, [1., 2.])]
+        der_r = [(1, [3., 4.])]
+
+        b = make_interp_spline(xx, yy, k=3, bc_type=(der_l, der_r))
+        xp_assert_close(b(xx), yy, atol=1e-14, rtol=1e-14)
+        xp_assert_close(
+            b(xx[0], 1),
+            xp.asarray(der_l[0][1], dtype=xp.float64), atol=1e-14, rtol=1e-14
+        )
+        xp_assert_close(
+            b(xx[-1], 1),
+            xp.asarray(der_r[0][1], dtype=xp.float64), atol=1e-14, rtol=1e-14
+        )
+
+    def test_shapes(self):
+        rng = np.random.RandomState(1234)
+        k, n = 3, 22
+        x = np.sort(rng.random(size=n))
+        y = rng.random(size=(n, 5, 6, 7))
+
+        b = make_interp_spline(x, y, k)
+        assert b.c.shape == (n, 5, 6, 7)
+
+        # now throw in some derivatives
+        d_l = [(1, rng.random((5, 6, 7)))]
+        d_r = [(1, rng.random((5, 6, 7)))]
+        b = make_interp_spline(x, y, k, bc_type=(d_l, d_r))
+        assert b.c.shape == (n + k - 1, 5, 6, 7)
+
+    def test_string_aliases(self, xp):
+        xx, yy = self._get_xy(xp)
+        yy = xp.sin(xx)
+
+        # a single string is duplicated
+        b1 = make_interp_spline(xx, yy, k=3, bc_type='natural')
+        b2 = make_interp_spline(xx, yy, k=3, bc_type=([(2, 0)], [(2, 0)]))
+        xp_assert_close(b1.c, b2.c, atol=1e-15)
+
+        # two strings are handled
+        b1 = make_interp_spline(xx, yy, k=3,
+                                bc_type=('natural', 'clamped'))
+        b2 = make_interp_spline(xx, yy, k=3,
+                                bc_type=([(2, 0)], [(1, 0)]))
+        xp_assert_close(b1.c, b2.c, atol=1e-15)
+
+        # one-sided BCs are OK
+        b1 = make_interp_spline(xx, yy, k=2, bc_type=(None, 'clamped'))
+        b2 = make_interp_spline(xx, yy, k=2, bc_type=(None, [(1, 0.0)]))
+        xp_assert_close(b1.c, b2.c, atol=1e-15)
+
+        # 'not-a-knot' is equivalent to None
+        b1 = make_interp_spline(xx, yy, k=3, bc_type='not-a-knot')
+        b2 = make_interp_spline(xx, yy, k=3, bc_type=None)
+        xp_assert_close(b1.c, b2.c, atol=1e-15)
+
+        # unknown strings do not pass
+        with assert_raises(ValueError):
+            make_interp_spline(xx, yy, k=3, bc_type='typo')
+
+        # string aliases are handled for 2D values
+        yy = xp.stack((xp.sin(xx), xp.cos(xx)), axis=1)
+        der_l = [(1, [0., 0.])]
+        der_r = [(2, [0., 0.])]
+        b2 = make_interp_spline(xx, yy, k=3, bc_type=(der_l, der_r))
+        b1 = make_interp_spline(xx, yy, k=3,
+                                bc_type=('clamped', 'natural'))
+        xp_assert_close(b1.c, b2.c, atol=1e-15)
+
+        # ... and for N-D values:
+        rng = np.random.RandomState(1234)
+        k, n = 3, 22
+        x = np.sort(rng.random(size=n))
+        y = rng.random(size=(n, 5, 6, 7))
+        x, y = xp.asarray(x), xp.asarray(y)
+
+        # now throw in some derivatives
+        d_l = [(1, xp.zeros((5, 6, 7)))]
+        d_r = [(1, xp.zeros((5, 6, 7)))]
+        b1 = make_interp_spline(x, y, k, bc_type=(d_l, d_r))
+        b2 = make_interp_spline(x, y, k, bc_type='clamped')
+        xp_assert_close(b1.c, b2.c, atol=1e-15)
+
+    def test_full_matrix(self, xp):
+        rng = np.random.RandomState(1234)
+        k, n = 3, 7
+        x_np = np.sort(rng.random(size=n))
+        y_np = rng.random(size=n)
+        t_np = _not_a_knot(x_np, k)
+        cf = make_interp_full_matr(x_np, y_np, t_np, k)
+        cf = xp.asarray(cf)
+
+        x, y, t = map(xp.asarray, (x_np, y_np, t_np))
+        b = make_interp_spline(x, y, k, t)
+        xp_assert_close(b.c, cf, atol=1e-14, rtol=1e-14)
+
+    def test_woodbury(self):
+        '''
+        Random elements in diagonal matrix with blocks in the
+        left lower and right upper corners checking the
+        implementation of Woodbury algorithm.
+        '''
+        rng = np.random.RandomState(1234)
+        n = 201
+        for k in range(3, 32, 2):
+            offset = int((k - 1) / 2)
+            a = np.diagflat(rng.random((1, n)))
+            for i in range(1, offset + 1):
+                a[:-i, i:] += np.diagflat(rng.random((1, n - i)))
+                a[i:, :-i] += np.diagflat(rng.random((1, n - i)))
+            ur = rng.random((offset, offset))
+            a[:offset, -offset:] = ur
+            ll = rng.random((offset, offset))
+            a[-offset:, :offset] = ll
+            d = np.zeros((k, n))
+            for i, j in enumerate(range(offset, -offset - 1, -1)):
+                if j < 0:
+                    d[i, :j] = np.diagonal(a, offset=j)
+                else:
+                    d[i, j:] = np.diagonal(a, offset=j)
+            b = rng.random(n)
+            xp_assert_close(_woodbury_algorithm(d, ur, ll, b, k),
+                            np.linalg.solve(a, b), atol=1e-14)
+
+
+def make_interp_full_matr(x, y, t, k):
+    """Assemble an spline order k with knots t to interpolate
+    y(x) using full matrices.
+    Not-a-knot BC only.
+
+    This routine is here for testing only (even though it's functional).
+    """
+    assert x.size == y.size
+    assert t.size == x.size + k + 1
+    n = x.size
+
+    A = np.zeros((n, n), dtype=np.float64)
+
+    for j in range(n):
+        xval = x[j]
+        if xval == t[k]:
+            left = k
+        else:
+            left = np.searchsorted(t, xval) - 1
+
+        # fill a row
+        bb = _dierckx.evaluate_all_bspl(t, k, xval, left)
+        A[j, left-k:left+1] = bb
+
+    c = sl.solve(A, y)
+    return c
+
+
+def make_lsq_full_matrix(x, y, t, k=3):
+    """Make the least-square spline, full matrices."""
+    x, y, t = map(np.asarray, (x, y, t))
+    m = x.size
+    n = t.size - k - 1
+
+    A = np.zeros((m, n), dtype=np.float64)
+
+    for j in range(m):
+        xval = x[j]
+        # find interval
+        if xval == t[k]:
+            left = k
+        else:
+            left = np.searchsorted(t, xval) - 1
+
+        # fill a row
+        bb = _dierckx.evaluate_all_bspl(t, k, xval, left)
+        A[j, left-k:left+1] = bb
+
+    # have observation matrix, can solve the LSQ problem
+    B = np.dot(A.T, A)
+    Y = np.dot(A.T, y)
+    c = sl.solve(B, Y)
+
+    return c, (A, Y)
+
+
+parametrize_lsq_methods = pytest.mark.parametrize("method", ["norm-eq", "qr"])
+
+
+@make_xp_test_case(make_lsq_spline)
+class TestLSQ:
+    #
+    # Test make_lsq_spline
+    #
+    rng = np.random.RandomState(1234)
+    n, k = 13, 3
+    x = np.sort(rng.random(n))
+    y = rng.random(n)
+    t = _augknt(np.linspace(x[0], x[-1], 7), k)
+
+    @parametrize_lsq_methods
+    def test_lstsq(self, method):
+        # check LSQ construction vs a full matrix version
+        x, y, t, k = self.x, self.y, self.t, self.k
+
+        c0, AY = make_lsq_full_matrix(x, y, t, k)
+        b = make_lsq_spline(x, y, t, k, method=method)
+
+        xp_assert_close(b.c, c0)
+        assert b.c.shape == (t.size - k - 1,)
+
+        # also check against numpy.lstsq
+        aa, yy = AY
+        c1, _, _, _ = np.linalg.lstsq(aa, y, rcond=-1)
+        xp_assert_close(b.c, c1)
+
+    @parametrize_lsq_methods
+    def test_weights(self, method, xp):
+        # weights = 1 is same as None
+        x, y, t, k = *map(xp.asarray, (self.x, self.y, self.t)), self.k
+        w = xp.ones_like(x)
+
+        b = make_lsq_spline(x, y, t, k, method=method)
+        b_w = make_lsq_spline(x, y, t, k, w=w, method=method)
+
+        xp_assert_close(b.t, b_w.t, atol=1e-14)
+        xp_assert_close(b.c, b_w.c, atol=1e-14)
+        assert b.k == b_w.k
+
+    def test_weights_same(self, xp):
+        # both methods treat weights
+        x, y, t, k = *map(xp.asarray, (self.x, self.y, self.t)), self.k
+        w = np.random.default_rng(1234).uniform(size=x.shape[0])
+        w = xp.asarray(w)
+
+        b_ne = make_lsq_spline(x, y, t, k, w=w, method="norm-eq")
+        b_qr = make_lsq_spline(x, y, t, k, w=w, method="qr")
+        b_no_w = make_lsq_spline(x, y, t, k, method="qr")
+
+        xp_assert_close(b_ne.c, b_qr.c, atol=1e-14)
+        assert not xp.all(xp.abs(b_no_w.c - b_qr.c) < 1e-14)
+
+    @parametrize_lsq_methods
+    def test_multiple_rhs(self, method, xp):
+        x, t, k, n = *map(xp.asarray, (self.x, self.t)), self.k, self.n
+        rng = np.random.RandomState(1234)
+        y = rng.random(size=(n, 5, 6, 7))
+        y = xp.asarray(y)
+
+        b = make_lsq_spline(x, y, t, k, method=method)
+        assert b.c.shape == (t.shape[0] - k - 1, 5, 6, 7)
+
+    @parametrize_lsq_methods
+    def test_multiple_rhs_2(self, method, xp):
+        x, t, k, n = *map(xp.asarray, (self.x, self.t)), self.k, self.n
+        nrhs = 3
+        rng = np.random.RandomState(1234)
+        y = rng.random(size=(n, nrhs))
+        y = xp.asarray(y)
+        b = make_lsq_spline(x, y, t, k, method=method)
+
+        bb = [make_lsq_spline(x, y[:, i], t, k, method=method)
+              for i in range(nrhs)]
+        coefs = xp.stack([bb[i].c for i in range(nrhs)]).T
+
+        xp_assert_close(coefs, b.c, atol=1e-15)
+
+    def test_multiple_rhs_3(self, xp):
+        x, t, k, n = *map(xp.asarray, (self.x, self.t)), self.k, self.n
+        nrhs = 3
+        y = np.random.random(size=(n, nrhs))
+        y = xp.asarray(y)
+        b_qr = make_lsq_spline(x, y, t, k, method="qr")
+        b_neq = make_lsq_spline(x, y, t, k, method="norm-eq")
+        xp_assert_close(b_qr.c, b_neq.c, atol=1e-15)
+
+    @parametrize_lsq_methods
+    def test_complex(self, method, xp):
+        # cmplx-valued `y`
+        x, t, k = *map(xp.asarray, (self.x, self.t)), self.k
+        yc = xp.asarray(self.y * (1. + 2.j))
+
+        b = make_lsq_spline(x, yc, t, k, method=method)
+        b_re = make_lsq_spline(x, xp.real(yc), t, k, method=method)
+        b_im = make_lsq_spline(x, xp.imag(yc), t, k, method=method)
+
+        xp_assert_close(b(x), b_re(x) + 1.j*b_im(x), atol=1e-15, rtol=1e-15)
+
+    def test_complex_2(self, xp):
+        # test complex-valued y with y.ndim > 1
+
+        x, t, k = *map(xp.asarray, (self.x, self.t)), self.k
+        yc = xp.asarray(self.y * (1. + 2.j))
+        yc = xp.stack((yc, yc), axis=1)
+
+        b = make_lsq_spline(x, yc, t, k)
+        b_re = make_lsq_spline(x, xp.real(yc), t, k)
+        b_im = make_lsq_spline(x, xp.imag(yc), t, k)
+
+        xp_assert_close(b(x), b_re(x) + 1.j*b_im(x), atol=1e-15, rtol=1e-15)
+
+        # repeat with num_trailing_dims > 1 : yc.shape[1:] = (2, 2)
+        yc = xp.stack((yc, yc), axis=1)
+
+        b = make_lsq_spline(x, yc, t, k)
+        b_re = make_lsq_spline(x, xp.real(yc), t, k)
+        b_im = make_lsq_spline(x, xp.imag(yc), t, k)
+
+        xp_assert_close(b(x), b_re(x) + 1.j*b_im(x), atol=1e-15, rtol=1e-15)
+
+    @parametrize_lsq_methods
+    def test_int_xy(self, method):
+        x = np.arange(10).astype(int)
+        y = np.arange(10).astype(int)
+        t = _augknt(x, k=1)
+        # Cython chokes on "buffer type mismatch"
+        make_lsq_spline(x, y, t, k=1, method=method)
+
+    @parametrize_lsq_methods
+    def test_f32_xy(self, method):
+        x = np.arange(10, dtype=np.float32)
+        y = np.arange(10, dtype=np.float32)
+        t = _augknt(x, k=1)
+        spl_f32 = make_lsq_spline(x, y, t, k=1, method=method)
+        spl_f64 = make_lsq_spline(
+            x.astype(float), y.astype(float), t.astype(float), k=1, method=method
+        )
+
+        x2 = (x[1:] + x[:-1]) / 2.0
+        xp_assert_close(spl_f32(x2), spl_f64(x2), atol=1e-15)
+
+    @parametrize_lsq_methods
+    def test_sliced_input(self, method):
+        # Cython code chokes on non C contiguous arrays
+        xx = np.linspace(-1, 1, 100)
+
+        x = xx[::3]
+        y = xx[::3]
+        t = _augknt(x, 1)
+        make_lsq_spline(x, y, t, k=1, method=method)
+
+    @parametrize_lsq_methods
+    def test_checkfinite(self, method):
+        # check_finite defaults to True; nans and such trigger a ValueError
+        x = np.arange(12).astype(float)
+        y = x**2
+        t = _augknt(x, 3)
+
+        for z in [np.nan, np.inf, -np.inf]:
+            y[-1] = z
+            assert_raises(ValueError, make_lsq_spline, x, y, t, method=method)
+
+    @parametrize_lsq_methods
+    def test_read_only(self, method):
+        # Check that make_lsq_spline works with read only arrays
+        x, y, t = self.x, self.y, self.t
+        x.setflags(write=False)
+        y.setflags(write=False)
+        t.setflags(write=False)
+        make_lsq_spline(x=x, y=y, t=t, method=method)
+
+    @pytest.mark.parametrize('k', list(range(1, 7)))
+    def test_qr_vs_norm_eq(self, k):
+        # check that QR and normal eq solutions match
+        x, y = self.x, self.y
+        t = _augknt(np.linspace(x[0], x[-1], 7), k)
+        spl_norm_eq = make_lsq_spline(x, y, t, k=k, method='norm-eq')
+        spl_qr = make_lsq_spline(x, y, t, k=k, method='qr')
+
+        xx = (x[1:] + x[:-1]) / 2.0
+        xp_assert_close(spl_norm_eq(xx), spl_qr(xx), atol=1e-15)
+
+    def test_duplicates(self):
+        # method="qr" can handle duplicated data points
+        x = np.repeat(self.x, 2)
+        y = np.repeat(self.y, 2)
+        spl_1 = make_lsq_spline(self.x, self.y, self.t, k=3, method='qr')
+        spl_2 = make_lsq_spline(x, y, self.t, k=3, method='qr')
+
+        xx = (x[1:] + x[:-1]) / 2.0
+        xp_assert_close(spl_1(xx), spl_2(xx), atol=1e-15)
+
+
+class PackedMatrix:
+    """A simplified CSR format for when non-zeros in each row are consecutive.
+
+    Assuming that each row of an `(m, nc)` matrix 1) only has `nz` non-zeros, and
+    2) these non-zeros are consecutive, we only store an `(m, nz)` matrix of
+    non-zeros and a 1D array of row offsets. This way, a row `i` of the original
+    matrix A is ``A[i, offset[i]: offset[i] + nz]``.
+
+    """
+    def __init__(self, a, offset, nc):
+        self.a = a
+        self.offset = offset
+        self.nc = nc
+
+        assert a.ndim == 2
+        assert offset.ndim == 1
+        assert a.shape[0] == offset.shape[0]
+
+    @property
+    def shape(self):
+        return self.a.shape[0], self.nc
+
+    def todense(self):
+        out = np.zeros(self.shape)
+        nelem = self.a.shape[1]
+        for i in range(out.shape[0]):
+            nel = min(self.nc - self.offset[i], nelem)
+            out[i, self.offset[i]:self.offset[i] + nel] = self.a[i, :nel]
+        return out
+
+
+def _qr_reduce_py(a_p, y, startrow=1):
+    """This is a python counterpart of the `_qr_reduce` routine,
+    declared in interpolate/src/__fitpack.h
+    """
+    from scipy.linalg.lapack import get_lapack_funcs
+    dlartg = get_lapack_funcs('lartg', dtype=np.float64, ilp64='preferred')
+
+    # unpack the packed format
+    a = a_p.a
+    offset = a_p.offset
+    nc = a_p.nc
+
+    m, nz = a.shape
+
+    assert y.shape[0] == m
+    R = a.copy()
+    y1 = y.copy()
+
+    for i in range(startrow, m):
+        oi = offset[i]
+        for j in range(oi, nc):
+            # rotate only the lower diagonal
+            if j >= min(i, nc):
+                break
+
+            # In dense format: diag a1[j, j] vs a1[i, j]
+            c, s, r = dlartg(R[j, 0], R[i, 0])
+
+            # rotate l.h.s.
+            R[j, 0] = r
+            for l in range(1, nz):
+                R[j, l], R[i, l-1] = fprota(c, s, R[j, l], R[i, l])
+            R[i, -1] = 0.0
+
+            # rotate r.h.s.
+            for l in range(y1.shape[1]):
+                y1[j, l], y1[i, l] = fprota(c, s, y1[j, l], y1[i, l])
+
+    # convert to packed
+    offs = list(range(R.shape[0]))
+    R_p = PackedMatrix(R, np.array(offs, dtype=np.int64), nc)
+
+    return R_p, y1
+
+
+def fprota(c, s, a, b):
+    """Givens rotate [a, b].
+
+    [aa] = [ c s] @ [a]
+    [bb]   [-s c]   [b]
+
+    """
+    aa =  c*a + s*b
+    bb = -s*a + c*b
+    return aa, bb
+
+
+def fpback(R_p, y):
+    """Backsubsitution solve upper triangular banded `R @ c = y.`
+
+    `R` is in the "packed" format: `R[i, :]` is `a[i, i:i+k+1]`
+    """
+    R = R_p.a
+    _, nz = R.shape
+    nc = R_p.nc
+    assert y.shape[0] == R.shape[0]
+
+    c = np.zeros_like(y[:nc])
+    c[nc-1, ...] = y[nc-1] / R[nc-1, 0]
+    for i in range(nc-2, -1, -1):
+        nel = min(nz, nc-i)
+        # NB: broadcast R across trailing dimensions of `c`.
+        summ = (R[i, 1:nel, None] * c[i+1:i+nel, ...]).sum(axis=0)
+        c[i, ...] = ( y[i] - summ ) / R[i, 0]
+    return c
+
+
+class TestGivensQR:
+    # Test row-by-row QR factorization, used for the LSQ spline construction.
+    # This is implementation detail; still test it separately.
+    def _get_xyt(self, n):
+        k = 3
+        x = np.arange(n, dtype=float)
+        y = x**3 + 1/(1+x)
+        t = _not_a_knot(x, k)
+        return x, y, t, k
+
+    def test_vs_full(self):
+        n = 10
+        x, y, t, k = self._get_xyt(n)
+
+        # design matrix
+        a_csr = BSpline.design_matrix(x, t, k)
+
+        # dense QR
+        q, r = sl.qr(a_csr.todense())
+        qTy = q.T @ y
+
+        # prepare the PackedMatrix to factorize
+        # convert to "packed" format
+        m, nc = a_csr.shape
+        assert nc == t.shape[0] - k - 1
+
+        offset = a_csr.indices[::(k+1)]
+        offset = np.ascontiguousarray(offset, dtype=np.int64)
+        A = a_csr.data.reshape(m, k+1)
+
+        R = PackedMatrix(A, offset, nc)
+        y_ = y[:, None]     # _qr_reduce requires `y` a 2D array
+        _dierckx.qr_reduce(A, offset, nc, y_)      # modifies arguments in-place
+
+        # signs may differ
+        xp_assert_close(np.minimum(R.todense() + r,
+                                   R.todense() - r), np.zeros_like(r), atol=1e-15)
+        xp_assert_close(np.minimum(abs(qTy - y_[:, 0]),
+                                   abs(qTy + y_[:, 0])), np.zeros_like(qTy), atol=2e-13)
+
+        # sign changes are consistent between Q and R:
+        c_full = sl.solve(r, qTy)
+        c_banded, _, _ = _dierckx.fpback(R.a, R.nc, x, y_, t, k, np.ones_like(y), y_)
+        xp_assert_close(c_full, c_banded[:, 0], atol=5e-13)
+
+    def test_py_vs_compiled(self):
+        # test _qr_reduce vs a python implementation
+        n = 10
+        x, y, t, k = self._get_xyt(n)
+
+        # design matrix
+        a_csr = BSpline.design_matrix(x, t, k)
+        m, nc = a_csr.shape
+        assert nc == t.shape[0] - k - 1
+
+        offset = a_csr.indices[::(k+1)]
+        offset = np.ascontiguousarray(offset, dtype=np.int64)
+        A = a_csr.data.reshape(m, k+1)
+
+        R = PackedMatrix(A, offset, nc)
+        y_ = y[:, None]
+
+        RR, yy = _qr_reduce_py(R, y_)
+        _dierckx.qr_reduce(A, offset, nc , y_)   # in-place
+
+        xp_assert_close(RR.a, R.a, atol=1e-15)
+        xp_assert_equal(RR.offset, R.offset, check_dtype=False)
+        assert RR.nc == R.nc
+        xp_assert_close(yy, y_, atol=1e-15)
+
+    # Test C-level construction of the design matrix
+
+    def test_data_matrix(self):
+        n = 10
+        x, y, t, k = self._get_xyt(n)
+        w = np.arange(1, n+1, dtype=float)
+
+        A, offset, nc = _dierckx.data_matrix(x, t, k, w)
+
+        m = x.shape[0]
+        a_csr = BSpline.design_matrix(x, t, k)
+        a_w = (a_csr * w[:, None]).tocsr()
+        A_ = a_w.data.reshape((m, k+1))
+        offset_ = a_w.indices[::(k+1)].astype(np.int64)
+
+        xp_assert_close(A, A_, atol=1e-15)
+        xp_assert_equal(offset, offset_)
+        assert nc == t.shape[0] - k - 1
+
+    def test_fpback(self):
+        n = 10
+        x, y, t, k = self._get_xyt(n)
+        y = np.c_[y, y**2]
+        A, offset, nc = _dierckx.data_matrix(x, t, k, np.ones_like(x))
+        R = PackedMatrix(A, offset, nc)
+        _dierckx.qr_reduce(A, offset, nc, y)
+
+        c = fpback(R, y)
+        cc, _, _ = _dierckx.fpback(A, nc, x, y, t, k, np.ones_like(x), y)
+
+        xp_assert_close(cc, c, atol=1e-14)
+
+    def test_evaluate_all_bspl(self):
+        n = 10
+        x, _, t, k = self._get_xyt(n)
+        zero_array = np.zeros((k + 1,), dtype=float)
+        for xval in x:
+            xp_assert_equal(
+                _dierckx.evaluate_all_bspl(t, k, xval, n, k + 2), zero_array)
+            xp_assert_equal(
+                _dierckx.evaluate_all_bspl(t, k, xval, n, 2*k), zero_array)
+
+
+def data_file(basename):
+    return os.path.join(os.path.abspath(os.path.dirname(__file__)),
+                        'data', basename)
+
+
+@make_xp_test_case(make_smoothing_spline)
+class TestSmoothingSpline:
+    #
+    # test make_smoothing_spline
+    #
+    def test_invalid_input(self):
+        rng = np.random.RandomState(1234)
+        n = 100
+        x = np.sort(rng.random_sample(n) * 4 - 2)
+        y = x**2 * np.sin(4 * x) + x**3 + rng.normal(0., 1.5, n)
+
+        # ``x`` and ``y`` should have same shapes (1-D array)
+        with assert_raises(ValueError):
+            make_smoothing_spline(x, y[1:])
+        with assert_raises(ValueError):
+            make_smoothing_spline(x[1:], y)
+        with assert_raises(ValueError):
+            make_smoothing_spline(x.reshape(1, n), y)
+
+        # ``x`` should be an ascending array
+        with assert_raises(ValueError):
+            make_smoothing_spline(x[::-1], y)
+
+        x_dupl = np.copy(x)
+        x_dupl[0] = x_dupl[1]
+
+        with assert_raises(ValueError):
+            make_smoothing_spline(x_dupl, y)
+
+        # x and y length must be >= 5
+        x = np.arange(4)
+        y = np.ones(4)
+        exception_message = "``x`` and ``y`` length must be at least 5"
+        with pytest.raises(ValueError, match=exception_message):
+            make_smoothing_spline(x, y)
+
+    def test_compare_with_GCVSPL(self):
+        """
+        Data is generated in the following way:
+        >>> np.random.seed(1234)
+        >>> n = 100
+        >>> x = np.sort(np.random.random_sample(n) * 4 - 2)
+        >>> y = np.sin(x) + np.random.normal(scale=.5, size=n)
+        >>> np.savetxt('x.csv', x)
+        >>> np.savetxt('y.csv', y)
+
+        We obtain the result of performing the GCV smoothing splines
+        package (by Woltring, gcvspl) on the sample data points
+        using its version for Octave (https://github.com/srkuberski/gcvspl).
+        In order to use this implementation, one should clone the repository
+        and open the folder in Octave.
+        In Octave, we load up ``x`` and ``y`` (generated from Python code
+        above):
+
+        >>> x = csvread('x.csv');
+        >>> y = csvread('y.csv');
+
+        Then, in order to access the implementation, we compile gcvspl files in
+        Octave:
+
+        >>> mex gcvsplmex.c gcvspl.c
+        >>> mex spldermex.c gcvspl.c
+
+        The first function computes the vector of unknowns from the dataset
+        (x, y) while the second one evaluates the spline in certain points
+        with known vector of coefficients.
+
+        >>> c = gcvsplmex( x, y, 2 );
+        >>> y0 = spldermex( x, c, 2, x, 0 );
+
+        If we want to compare the results of the gcvspl code, we can save
+        ``y0`` in csv file:
+
+        >>> csvwrite('y0.csv', y0);
+
+        """
+        # load the data sample
+        with np.load(data_file('gcvspl.npz')) as data:
+            # data points
+            x = data['x']
+            y = data['y']
+
+            y_GCVSPL = data['y_GCVSPL']
+        y_compr = make_smoothing_spline(x, y)(x)
+
+        # such tolerance is explained by the fact that the spline is built
+        # using an iterative algorithm for minimizing the GCV criteria. These
+        # algorithms may vary, so the tolerance should be rather low.
+        # Not checking dtypes as gcvspl.npz stores little endian arrays, which
+        # result in conflicting dtypes on big endian systems.
+        xp_assert_close(y_compr, y_GCVSPL, atol=1e-4, rtol=1e-4, check_dtype=False)
+
+    def test_non_regularized_case(self, xp):
+        """
+        In case the regularization parameter is 0, the resulting spline
+        is an interpolation spline with natural boundary conditions.
+        """
+        # create data sample
+        rng = np.random.RandomState(1234)
+        n = 100
+        x = np.sort(rng.random_sample(n) * 4 - 2)
+        y = x**2 * np.sin(4 * x) + x**3 + rng.normal(0., 1.5, n)
+
+        x, y = xp.asarray(x), xp.asarray(y)
+
+        spline_GCV = make_smoothing_spline(x, y, lam=0.)
+        spline_interp = make_interp_spline(x, y, 3, bc_type='natural')
+
+        grid = xp.linspace(x[0], x[-1], 2 * n)
+        xp_assert_close(spline_GCV(grid),
+                        spline_interp(grid),
+                        atol=1e-15)
+
+    @pytest.mark.fail_slow(2)
+    def test_weighted_smoothing_spline(self, xp):
+        # create data sample
+        rng = np.random.RandomState(1234)
+        n = 100
+        x = np.sort(rng.random_sample(n) * 4 - 2)
+        y = x**2 * np.sin(4 * x) + x**3 + rng.normal(0., 1.5, n)
+
+        x, y = map(xp.asarray, (x, y))
+
+        spl = make_smoothing_spline(x, y)
+
+        # in order not to iterate over all of the indices, we select 10 of
+        # them randomly
+        for ind in rng.choice(range(100), size=10):
+            w = xp.ones(n)
+            xpx.at(w, int(ind)).set(30.)    # w[int(ind)] = 30.
+            spl_w = make_smoothing_spline(x, y, w)
+            # check that spline with weight in a certain point is closer to the
+            # original point than the one without weights
+            orig = abs(spl(x[ind]) - y[ind])
+            weighted = abs(spl_w(x[ind]) - y[ind])
+
+            if orig < weighted:
+                raise ValueError(f'Spline with weights should be closer to the'
+                                 f' points than the original one: {orig:.4} < '
+                                 f'{weighted:.4}')
+
+
+################################
+# NdBSpline tests
+def bspline2(xy, t, c, k):
+    """A naive 2D tensort product spline evaluation."""
+    x, y = xy
+    tx, ty = t
+    nx = len(tx) - k - 1
+    assert (nx >= k+1)
+    ny = len(ty) - k - 1
+    assert (ny >= k+1)
+    res = sum(c[ix, iy] * B(x, k, ix, tx) * B(y, k, iy, ty)
+              for ix in range(nx) for iy in range(ny))
+    return np.asarray(res)
+
+
+def B(x, k, i, t):
+    if k == 0:
+        return 1.0 if t[i] <= x < t[i+1] else 0.0
+    if t[i+k] == t[i]:
+        c1 = 0.0
+    else:
+        c1 = (x - t[i])/(t[i+k] - t[i]) * B(x, k-1, i, t)
+    if t[i+k+1] == t[i+1]:
+        c2 = 0.0
+    else:
+        c2 = (t[i+k+1] - x)/(t[i+k+1] - t[i+1]) * B(x, k-1, i+1, t)
+    return c1 + c2
+
+
+def bspline(x, t, c, k):
+    n = len(t) - k - 1
+    assert (n >= k+1) and (len(c) >= n)
+    return sum(c[i] * B(x, k, i, t) for i in range(n))
+
+
+class NdBSpline0:
+    def __init__(self, t, c, k=3):
+        """Tensor product spline object.
+
+        c[i1, i2, ..., id] * B(x1, i1) * B(x2, i2) * ... * B(xd, id)
+
+        Parameters
+        ----------
+        c : ndarray, shape (n1, n2, ..., nd, ...)
+            b-spline coefficients
+        t : tuple of 1D ndarrays
+            knot vectors in directions 1, 2, ... d
+            ``len(t[i]) == n[i] + k + 1``
+        k : int or length-d tuple of integers
+            spline degrees.
+        """
+        ndim = len(t)
+        assert ndim <= len(c.shape)
+
+        try:
+            len(k)
+        except TypeError:
+            # make k a tuple
+            k = (k,)*ndim
+
+        self.k = tuple(operator.index(ki) for ki in k)
+        self.t = tuple(np.asarray(ti, dtype=float) for ti in t)
+        self.c = c
+
+    def __call__(self, x):
+        ndim = len(self.t)
+        # a single evaluation point: `x` is a 1D array_like, shape (ndim,)
+        assert len(x) == ndim
+
+        # get the indices in an ndim-dimensional vector
+        i = ['none', ]*ndim
+        for d in range(ndim):
+            td, xd = self.t[d], x[d]
+            k = self.k[d]
+
+            # find the index for x[d]
+            if xd == td[k]:
+                i[d] = k
+            else:
+                i[d] = np.searchsorted(td, xd) - 1
+            assert td[i[d]] <= xd <= td[i[d]+1]
+            assert i[d] >= k and i[d] < len(td) - k
+        i = tuple(i)
+
+        # iterate over the dimensions, form linear combinations of
+        # products B(x_1) * B(x_2) * ... B(x_N) of (k+1)**N b-splines
+        # which are non-zero at `i = (i_1, i_2, ..., i_N)`.
+        result = 0
+        iters = [range(i[d] - self.k[d], i[d] + 1) for d in range(ndim)]
+        for idx in itertools.product(*iters):
+            term = self.c[idx] * np.prod([B(x[d], self.k[d], idx[d], self.t[d])
+                                          for d in range(ndim)])
+            result += term
+        return np.asarray(result)
+
+
+@make_xp_test_case(NdBSpline)
+class TestNdBSpline:
+
+    def test_1D(self, xp):
+        # test ndim=1 agrees with BSpline
+        rng = np.random.default_rng(12345)
+        n, k = 11, 3
+        n_tr = 7
+        t = np.sort(rng.uniform(size=n + k + 1))
+        c = rng.uniform(size=(n, n_tr))
+
+        t = xp.asarray(t)
+        c = xp.asarray(c)
+
+        b = BSpline(t, c, k)
+        nb = NdBSpline((t,), c, k)
+
+        xi = rng.uniform(size=21)
+        xi = xp.asarray(xi)
+
+        # NdBSpline expects xi.shape=(npts, ndim)
+        xp_assert_close(nb(xi[:, None]),
+                        b(xi), atol=1e-14)
+        assert nb(xi[:, None]).shape == (xi.shape[0], c.shape[1])
+
+    def make_2d_case(self, xp=np):
+        # make a 2D separable spline
+        x = xp.arange(6)
+        y = x**3
+        spl = make_interp_spline(x, y, k=3)
+
+        y_1 = x**3 + 2*x
+        spl_1 = make_interp_spline(x, y_1, k=3)
+
+        t2 = (spl.t, spl_1.t)
+        c2 = spl.c[:, None] * spl_1.c[None, :]
+
+        return t2, c2, 3
+
+    def make_2d_mixed(self, xp=np):
+        # make a 2D separable spline w/ kx=3, ky=2
+        x = xp.arange(6)
+        y = x**3
+        spl = make_interp_spline(x, y, k=3)
+
+        x = xp.arange(5, dtype=xp.float64) + 1.5
+        y_1 = x**2 + 2*x
+        spl_1 = make_interp_spline(x, y_1, k=2)
+
+        t2 = (spl.t, spl_1.t)
+        c2 = spl.c[:, None] * spl_1.c[None, :]
+
+        return t2, c2, spl.k, spl_1.k
+
+    def test_2D_separable(self, xp):
+        xi = [(1.5, 2.5), (2.5, 1), (0.5, 1.5)]
+        t2, c2, k = self.make_2d_case(xp=xp)
+        target = [x**3 * (y**3 + 2*y) for (x, y) in xi]
+
+        # sanity check: bspline2 gives the product as constructed
+        b2 = [bspline2(
+                xy,
+                [np.asarray(_) for _ in t2],
+                np.asarray(c2),
+                k
+              ) for xy in xi
+        ]
+        b2 = np.asarray(b2, dtype=np.float64)
+        xp_assert_close(xp.asarray(b2),
+                        xp.asarray(target, dtype=xp.float64),
+                        check_shape=False,
+                        atol=1e-14)
+
+        # check evaluation on a 2D array: the 1D array of 2D points
+        bspl2 = NdBSpline(t2, c2, k=3)
+        assert bspl2(xi).shape == (len(xi), )
+        xp_assert_close(bspl2(xi),
+                        xp.asarray(target, dtype=xp.float64), atol=1e-14)
+
+        # test that a nan in -> nan out
+        xi = np.asarray(xi)
+        xi[0, 1] = np.nan
+        xi = xp.asarray(xi)
+        xp_assert_equal(xp.isnan(bspl2(xi)), xp.asarray([True, False, False]))
+
+        # now check on a multidim xi
+        rng = np.random.default_rng(12345)
+        xi = rng.uniform(size=(4, 3, 2)) * 5
+        xi = xp.asarray(xi)
+        result = bspl2(xi)
+        assert result.shape == (4, 3)
+
+        # also check the values
+        rrr = xp.reshape(xi, (-1, 2)).T
+        x, y = rrr[0, ...], rrr[1, ...]
+        xp_assert_close(xp_ravel(result, xp=xp),
+                        x**3 * (y**3 + 2*y), atol=1e-14)
+
+    def test_2D_separable_2(self, xp):
+        # test `c` with trailing dimensions, i.e. c.ndim > ndim
+        ndim = 2
+        xi = [(1.5, 2.5), (2.5, 1), (0.5, 1.5)]
+        target = [x**3 * (y**3 + 2*y) for (x, y) in xi]
+
+        t2, c2, k = self.make_2d_case(xp=xp)
+        c2_4 = xp.stack((c2, c2, c2, c2), axis=2)   # c22.shape = (6, 6, 4)
+
+        xy = (1.5, 2.5)
+        bspl2_4 = NdBSpline(t2, c2_4, k=3)
+        result = bspl2_4(xy)
+        val_single = NdBSpline(t2, c2, k)(xy)
+        assert result.shape == (4,)
+        xp_assert_close(result,
+                        xp.stack([val_single, ]*4), atol=1e-14)
+
+        # now try the array xi : the output.shape is (3, 4) where 3
+        # is the number of points in xi and 4 is the trailing dimension of c
+        assert bspl2_4(xi).shape == np.shape(xi)[:-1] + bspl2_4.c.shape[ndim:]
+        xp_assert_close(bspl2_4(xi),
+                        xp.asarray(target, dtype=xp.float64)[:, None],
+                        check_shape=False,
+                        atol=5e-14)
+
+        # two trailing dimensions
+        c2_22 = xp.reshape(c2_4, (6, 6, 2, 2))
+        bspl2_22 = NdBSpline(t2, c2_22, k=3)
+
+        result = bspl2_22(xy)
+        assert result.shape == (2, 2)
+        target2_22 = xp.ones((2, 2), dtype=xp.float64)*val_single
+        xp_assert_close(result, target2_22, atol=1e-14)
+
+        # now try the array xi : the output shape is (3, 2, 2)
+        # for 3 points in xi and c trailing dimensions being (2, 2)
+        assert (bspl2_22(xi).shape ==
+                np.shape(xi)[:-1] + bspl2_22.c.shape[ndim:])
+        xp_assert_close(bspl2_22(xi),
+                        xp.asarray(target, dtype=xp.float64)[:, None, None],
+                        check_shape=False,
+                        atol=5e-14)
+
+    def test_2D_separable_2_complex(self, xp):
+        # test `c` with c.dtype == complex, with and w/o trailing dims
+        xi = [(1.5, 2.5), (2.5, 1), (0.5, 1.5)]
+        target = [x**3 * (y**3 + 2*y) for (x, y) in xi]
+
+        target = [t + 2j*t for t in target]
+
+        t2, c2, k = self.make_2d_case(xp=xp)
+        c2 = c2 * (1 + 2j)
+        c2_4 = xp.stack((c2, c2, c2, c2), axis=2)   # c2_4.shape = (6, 6, 4)
+
+        xy = (1.5, 2.5)
+        bspl2_4 = NdBSpline(t2, c2_4, k=3)
+        result = bspl2_4(xy)
+        val_single = NdBSpline(t2, c2, k)(xy)
+        assert result.shape == (4,)
+        xp_assert_close(result,
+                        xp.stack([val_single]*4), atol=1e-14)
+
+    def test_2D_random(self):
+        rng = np.random.default_rng(12345)
+        k = 3
+        tx = np.r_[0, 0, 0, 0, np.sort(rng.uniform(size=7)) * 3, 3, 3, 3, 3]
+        ty = np.r_[0, 0, 0, 0, np.sort(rng.uniform(size=8)) * 4, 4, 4, 4, 4]
+        c = rng.uniform(size=(tx.size-k-1, ty.size-k-1))
+
+        spl = NdBSpline((tx, ty), c, k=k)
+
+        xi = (1., 1.)
+        xp_assert_close(spl(xi),
+                        bspline2(xi, (tx, ty), c, k), atol=1e-14)
+
+        xi = np.c_[[1, 1.5, 2],
+                   [1.1, 1.6, 2.1]]
+        xp_assert_close(spl(xi),
+                        [bspline2(xy, (tx, ty), c, k) for xy in xi],
+                        atol=1e-14)
+
+    def test_2D_mixed(self):
+        t2, c2, kx, ky = self.make_2d_mixed()
+        xi = [(1.4, 4.5), (2.5, 2.4), (4.5, 3.5)]
+        target = [x**3 * (y**2 + 2*y) for (x, y) in xi]
+        bspl2 = NdBSpline(t2, c2, k=(kx, ky))
+        assert bspl2(xi).shape == (len(xi), )
+        xp_assert_close(bspl2(xi),
+                        target, atol=1e-14)
+
+    def test_2D_derivative(self, xp):
+        t2, c2, kx, ky = self.make_2d_mixed(xp=xp)
+        xi = [(1.4, 4.5), (2.5, 2.4), (4.5, 3.5)]
+        bspl2 = NdBSpline(t2, c2, k=(kx, ky))
+
+        # Derivative orders and expected functions
+        test_cases = {
+            (1, 0): lambda x, y: 3 * x**2 * (y**2 + 2*y),
+            (1, 1): lambda x, y: 3 * x**2 * (2*y + 2),
+            (0, 0): lambda x, y: x**3 * (y**2 + 2*y),
+            (2*kx, 1): lambda x, y: 0,
+            (2*kx, 0): lambda x, y: 0,
+            (1, 3*ky): lambda x, y: 0,
+            (0, 3*ky): lambda x, y: 0,
+            (3*kx, 2*ky): lambda x, y: 0,
+        }
+
+        for nu, expected_fn in test_cases.items():
+            expected_vals = xp.asarray(
+                [expected_fn(x, y) for x, y in xi], dtype=xp.float64
+            )
+
+            # Evaluate via nu argument
+            direct = bspl2(xi, nu=nu)
+            xp_assert_close(direct, expected_vals, atol=1e-14)
+
+            # Evaluate via .derivative() call
+            via_method = bspl2.derivative(nu)(xi)
+            xp_assert_close(via_method, expected_vals, atol=1e-14)
+
+        # Error cases
+        for bad_nu in [(-1, 0), # all(nu >= 0)
+                       (-1, 0, 1)]: # len(nu) == ndim
+            with assert_raises(ValueError):
+                bspl2(xi, nu=bad_nu)
+            with assert_raises(ValueError):
+                bspl2.derivative(bad_nu)
+
+    def test_2D_mixed_random(self):
+        rng = np.random.default_rng(12345)
+        kx, ky = 2, 3
+        tx = np.r_[0, 0, 0, 0, np.sort(rng.uniform(size=7)) * 3, 3, 3, 3, 3]
+        ty = np.r_[0, 0, 0, 0, np.sort(rng.uniform(size=8)) * 4, 4, 4, 4, 4]
+        c = rng.uniform(size=(tx.size - kx - 1, ty.size - ky - 1))
+
+        xi = np.c_[[1, 1.5, 2],
+                   [1.1, 1.6, 2.1]]
+
+        bspl2 = NdBSpline((tx, ty), c, k=(kx, ky))
+        bspl2_0 = NdBSpline0((tx, ty), c, k=(kx, ky))
+
+        xp_assert_close(bspl2(xi),
+                        [bspl2_0(xp) for xp in xi], atol=1e-14)
+
+    def test_tx_neq_ty(self):
+        # 2D separable spline w/ len(tx) != len(ty)
+        x = np.arange(6)
+        y = np.arange(7) + 1.5
+
+        spl_x = make_interp_spline(x, x**3, k=3)
+        spl_y = make_interp_spline(y, y**2 + 2*y, k=3)
+        cc = spl_x.c[:, None] * spl_y.c[None, :]
+        bspl = NdBSpline((spl_x.t, spl_y.t), cc, (spl_x.k, spl_y.k))
+
+        values = (x**3)[:, None] * (y**2 + 2*y)[None, :]
+        rgi = RegularGridInterpolator((x, y), values)
+
+        xi = [(a, b) for a, b in itertools.product(x, y)]
+        bxi = bspl(xi)
+
+        assert not np.isnan(bxi).any()
+        xp_assert_close(bxi, rgi(xi), atol=1e-14)
+        xp_assert_close(bxi.reshape(values.shape), values, atol=1e-14)
+
+    def make_3d_case(self, xp=np):
+        # make a 3D separable spline
+        x = xp.arange(6)
+        y = x**3
+        spl = make_interp_spline(x, y, k=3)
+
+        y_1 = x**3 + 2*x
+        spl_1 = make_interp_spline(x, y_1, k=3)
+
+        y_2 = x**3 + 3*x + 1
+        spl_2 = make_interp_spline(x, y_2, k=3)
+
+        t2 = (spl.t, spl_1.t, spl_2.t)
+        c2 = (spl.c[:, None, None] *
+              spl_1.c[None, :, None] *
+              spl_2.c[None, None, :])
+
+        return t2, c2, 3
+
+    def test_3D_separable(self):
+        rng = np.random.default_rng(12345)
+        x, y, z = rng.uniform(size=(3, 11)) * 5
+        target = x**3 * (y**3 + 2*y) * (z**3 + 3*z + 1)
+
+        t3, c3, k = self.make_3d_case()
+        bspl3 = NdBSpline(t3, c3, k=3)
+
+        xi = [_ for _ in zip(x, y, z)]
+        result = bspl3(xi)
+        assert result.shape == (11,)
+        xp_assert_close(result, target, atol=1e-14)
+
+    def test_3D_derivative(self, xp):
+        t3, c3, k = self.make_3d_case(xp=xp)
+        bspl3 = NdBSpline(t3, c3, k=3)
+        rng = np.random.default_rng(12345)
+        x, y, z = rng.uniform(size=(3, 11)) * 5
+
+        xi_np = [_ for _ in zip(x, y, z)]
+        xi = xp.asarray(xi_np)
+
+        # Derivative orders and their expected expressions
+        test_cases = {
+            (1, 0, 0): lambda x, y, z: 3 * x**2 * (y**3 + 2*y) * (z**3 + 3*z + 1),
+            (2, 0, 0): lambda x, y, z: 6 * x * (y**3 + 2*y) * (z**3 + 3*z + 1),
+            (2, 1, 0): lambda x, y, z: 6 * x * (3*y**2 + 2) * (z**3 + 3*z + 1),
+            (2, 1, 3): lambda x, y, z: 6 * x * (3*y**2 + 2) * 6,
+            (2, 1, 4): lambda x, y, z: 0.0,
+        }
+
+        for nu, expected_fn in test_cases.items():
+            expected_vals = [expected_fn(xi_, yi_, zi_) for xi_, yi_, zi_ in xi_np]
+            expected_vals = xp.asarray(expected_vals, dtype=xp.float64)
+            xp_assert_close(bspl3(xi, nu=nu), expected_vals, atol=1e-14)
+            xp_assert_close(bspl3.derivative(nu)(xi), expected_vals, atol=1e-14)
+
+    def test_3D_random(self):
+        rng = np.random.default_rng(12345)
+        k = 3
+        tx = np.r_[0, 0, 0, 0, np.sort(rng.uniform(size=7)) * 3, 3, 3, 3, 3]
+        ty = np.r_[0, 0, 0, 0, np.sort(rng.uniform(size=8)) * 4, 4, 4, 4, 4]
+        tz = np.r_[0, 0, 0, 0, np.sort(rng.uniform(size=8)) * 4, 4, 4, 4, 4]
+        c = rng.uniform(size=(tx.size-k-1, ty.size-k-1, tz.size-k-1))
+
+        spl = NdBSpline((tx, ty, tz), c, k=k)
+        spl_0 = NdBSpline0((tx, ty, tz), c, k=k)
+
+        xi = (1., 1., 1)
+        xp_assert_close(spl(xi), spl_0(xi), atol=1e-14)
+
+        xi = np.c_[[1, 1.5, 2],
+                   [1.1, 1.6, 2.1],
+                   [0.9, 1.4, 1.9]]
+        xp_assert_close(spl(xi), [spl_0(xp) for xp in xi], atol=1e-14)
+
+    def test_3D_random_complex(self):
+        rng = np.random.default_rng(12345)
+        k = 3
+        tx = np.r_[0, 0, 0, 0, np.sort(rng.uniform(size=7)) * 3, 3, 3, 3, 3]
+        ty = np.r_[0, 0, 0, 0, np.sort(rng.uniform(size=8)) * 4, 4, 4, 4, 4]
+        tz = np.r_[0, 0, 0, 0, np.sort(rng.uniform(size=8)) * 4, 4, 4, 4, 4]
+        c = (rng.uniform(size=(tx.size-k-1, ty.size-k-1, tz.size-k-1)) +
+             rng.uniform(size=(tx.size-k-1, ty.size-k-1, tz.size-k-1))*1j)
+
+        spl = NdBSpline((tx, ty, tz), c, k=k)
+        spl_re = NdBSpline((tx, ty, tz), c.real, k=k)
+        spl_im = NdBSpline((tx, ty, tz), c.imag, k=k)
+
+        xi = np.c_[[1, 1.5, 2],
+                   [1.1, 1.6, 2.1],
+                   [0.9, 1.4, 1.9]]
+        xp_assert_close(spl(xi),
+                        spl_re(xi) + 1j*spl_im(xi), atol=1e-14)
+
+    @pytest.mark.parametrize('cls_extrap', [None, True])
+    @pytest.mark.parametrize('call_extrap', [None, True])
+    def test_extrapolate_3D_separable(self, cls_extrap, call_extrap):
+        # test that extrapolate=True does extrapolate
+        t3, c3, k = self.make_3d_case()
+        bspl3 = NdBSpline(t3, c3, k=3, extrapolate=cls_extrap)
+
+        # evaluate out of bounds
+        x, y, z = [-2, -1, 7], [-3, -0.5, 6.5], [-1, -1.5, 7.5]
+        x, y, z = map(np.asarray, (x, y, z))
+        xi = [_ for _ in zip(x, y, z)]
+        target = x**3 * (y**3 + 2*y) * (z**3 + 3*z + 1)
+
+        result = bspl3(xi, extrapolate=call_extrap)
+        xp_assert_close(result, target, atol=1e-14)
+
+    @pytest.mark.parametrize('extrap', [(False, True), (True, None)])
+    def test_extrapolate_3D_separable_2(self, extrap):
+        # test that call(..., extrapolate=None) defers to self.extrapolate,
+        # otherwise supersedes self.extrapolate
+        t3, c3, k = self.make_3d_case()
+        cls_extrap, call_extrap = extrap
+        bspl3 = NdBSpline(t3, c3, k=3, extrapolate=cls_extrap)
+
+        # evaluate out of bounds
+        x, y, z = [-2, -1, 7], [-3, -0.5, 6.5], [-1, -1.5, 7.5]
+        x, y, z = map(np.asarray, (x, y, z))
+        xi = [_ for _ in zip(x, y, z)]
+        target = x**3 * (y**3 + 2*y) * (z**3 + 3*z + 1)
+
+        result = bspl3(xi, extrapolate=call_extrap)
+        xp_assert_close(result, target, atol=1e-14)
+
+    def test_extrapolate_false_3D_separable(self):
+        # test that extrapolate=False produces nans for out-of-bounds values
+        t3, c3, k = self.make_3d_case()
+        bspl3 = NdBSpline(t3, c3, k=3)
+
+        # evaluate out of bounds and inside
+        x, y, z = [-2, 1, 7], [-3, 0.5, 6.5], [-1, 1.5, 7.5]
+        x, y, z = map(np.asarray, (x, y, z))
+        xi = [_ for _ in zip(x, y, z)]
+        target = x**3 * (y**3 + 2*y) * (z**3 + 3*z + 1)
+
+        result = bspl3(xi, extrapolate=False)
+        assert np.isnan(result[0])
+        assert np.isnan(result[-1])
+        xp_assert_close(result[1:-1], target[1:-1], atol=1e-14)
+
+    def test_x_nan_3D(self):
+        # test that spline(nan) is nan
+        t3, c3, k = self.make_3d_case()
+        bspl3 = NdBSpline(t3, c3, k=3)
+
+        # evaluate out of bounds and inside
+        x = np.asarray([-2, 3, np.nan, 1, 2, 7, np.nan])
+        y = np.asarray([-3, 3.5, 1, np.nan, 3, 6.5, 6.5])
+        z = np.asarray([-1, 3.5, 2, 3, np.nan, 7.5, 7.5])
+        xi = [_ for _ in zip(x, y, z)]
+        target = x**3 * (y**3 + 2*y) * (z**3 + 3*z + 1)
+        mask = np.isnan(x) | np.isnan(y) | np.isnan(z)
+        target[mask] = np.nan
+
+        result = bspl3(xi)
+        assert np.isnan(result[mask]).all()
+        xp_assert_close(result, target, atol=1e-14)
+
+    def test_non_c_contiguous(self):
+        # check that non C-contiguous inputs are OK
+        rng = np.random.default_rng(12345)
+        kx, ky = 3, 3
+        tx = np.sort(rng.uniform(low=0, high=4, size=16))
+        tx = np.r_[(tx[0],)*kx, tx, (tx[-1],)*kx]
+        ty = np.sort(rng.uniform(low=0, high=4, size=16))
+        ty = np.r_[(ty[0],)*ky, ty, (ty[-1],)*ky]
+
+        assert not tx[::2].flags.c_contiguous
+        assert not ty[::2].flags.c_contiguous
+
+        c = rng.uniform(size=(tx.size//2 - kx - 1, ty.size//2 - ky - 1))
+        c = c.T
+        assert not c.flags.c_contiguous
+
+        xi = np.c_[[1, 1.5, 2],
+                   [1.1, 1.6, 2.1]]
+
+        bspl2 = NdBSpline((tx[::2], ty[::2]), c, k=(kx, ky))
+        bspl2_0 = NdBSpline0((tx[::2], ty[::2]), c, k=(kx, ky))
+
+        xp_assert_close(bspl2(xi),
+                        [bspl2_0(xp) for xp in xi], atol=1e-14)
+
+    def test_readonly(self):
+        t3, c3, k = self.make_3d_case()
+        bspl3 = NdBSpline(t3, c3, k=3)
+
+        for i in range(3):
+            t3[i].flags.writeable = False
+        c3.flags.writeable = False
+
+        bspl3_ = NdBSpline(t3, c3, k=3)
+
+        assert bspl3((1, 2, 3)) == bspl3_((1, 2, 3))
+
+    def test_design_matrix(self):
+        t3, c3, k = self.make_3d_case()
+
+        xi = np.asarray([[1, 2, 3], [4, 5, 6]])
+        dm = NdBSpline(t3, c3, k).design_matrix(xi, t3, k)
+        dm1 = NdBSpline.design_matrix(xi, t3, [k, k, k])
+        assert dm.shape[0] == xi.shape[0]
+        xp_assert_close(dm.todense(), dm1.todense(), atol=1e-16)
+
+        with assert_raises(ValueError):
+            NdBSpline.design_matrix([1, 2, 3], t3, [k]*3)
+
+        with assert_raises(ValueError, match="Data and knots*"):
+            NdBSpline.design_matrix([[1, 2]], t3, [k]*3)
+
+    def test_concurrency(self):
+        rng = np.random.default_rng(12345)
+        k = 3
+        tx = np.r_[0, 0, 0, 0, np.sort(rng.uniform(size=7)) * 3, 3, 3, 3, 3]
+        ty = np.r_[0, 0, 0, 0, np.sort(rng.uniform(size=8)) * 4, 4, 4, 4, 4]
+        tz = np.r_[0, 0, 0, 0, np.sort(rng.uniform(size=8)) * 4, 4, 4, 4, 4]
+        c = rng.uniform(size=(tx.size-k-1, ty.size-k-1, tz.size-k-1))
+
+        spl = NdBSpline((tx, ty, tz), c, k=k)
+
+        def worker_fn(_, spl):
+            xi = np.c_[[1, 1.5, 2],
+                       [1.1, 1.6, 2.1],
+                       [0.9, 1.4, 1.9]]
+            spl(xi)
+
+        _run_concurrent_barrier(10, worker_fn, spl)
+
+
+class TestMakeND:
+    def test_2D_separable_simple(self):
+        x = np.arange(6)
+        y = np.arange(6) + 0.5
+        values = x[:, None]**3 * (y**3 + 2*y)[None, :]
+        xi = [(a, b) for a, b in itertools.product(x, y)]
+
+        bspl = make_ndbspl((x, y), values, k=1)
+        xp_assert_close(bspl(xi), values.ravel(), atol=1e-15)
+
+        # test the coefficients vs outer product of 1D coefficients
+        spl_x = make_interp_spline(x, x**3, k=1)
+        spl_y = make_interp_spline(y, y**3 + 2*y, k=1)
+        cc = spl_x.c[:, None] * spl_y.c[None, :]
+        xp_assert_close(cc, bspl.c, atol=1e-11, rtol=0)
+
+        # test against RGI
+        from scipy.interpolate import RegularGridInterpolator as RGI
+        rgi = RGI((x, y), values, method='linear')
+        xp_assert_close(rgi(xi), bspl(xi), atol=1e-14)
+
+    def test_2D_separable_trailing_dims(self):
+        # test `c` with trailing dimensions, i.e. c.ndim > ndim
+        x = np.arange(6)
+        y = np.arange(6)
+        xi = [(a, b) for a, b in itertools.product(x, y)]
+
+        # make values4.shape = (6, 6, 4)
+        values = x[:, None]**3 * (y**3 + 2*y)[None, :]
+        values4 = np.dstack((values, values, values, values))
+        bspl = make_ndbspl((x, y), values4, k=3, solver=ssl.spsolve)
+
+        result = bspl(xi)
+        target = np.dstack((values, values, values, values)).astype(float)
+        assert result.shape == (36, 4)
+        xp_assert_close(result.reshape(6, 6, 4),
+                        target, atol=1e-14)
+
+        # now two trailing dimensions
+        values22 = values4.reshape((6, 6, 2, 2))
+        bspl = make_ndbspl((x, y), values22, k=3, solver=ssl.spsolve)
+
+        result = bspl(xi)
+        assert result.shape == (36, 2, 2)
+        xp_assert_close(result.reshape(6, 6, 2, 2),
+                        target.reshape((6, 6, 2, 2)), atol=1e-14)
+
+    @pytest.mark.parametrize('k', [(3, 3), (1, 1), (3, 1), (1, 3), (3, 5)])
+    def test_2D_mixed(self, k):
+        # make a 2D separable spline w/ len(tx) != len(ty)
+        x = np.arange(6)
+        y = np.arange(7) + 1.5
+        xi = [(a, b) for a, b in itertools.product(x, y)]
+
+        values = (x**3)[:, None] * (y**2 + 2*y)[None, :]
+        bspl = make_ndbspl((x, y), values, k=k, solver=ssl.spsolve)
+        xp_assert_close(bspl(xi), values.ravel(), atol=1e-15)
+
+    def test_2D_nans(self):
+        x = np.arange(6)
+        y = np.arange(6) + 0.5
+        y[-1] = np.nan
+        values = x[:, None]**3 * (y**3 + 2*y)[None, :]
+
+        with assert_raises(ValueError):
+            make_ndbspl((x, y), values, k=1)
+
+    def _get_sample_2d_data(self):
+        # from test_rgi.py::TestIntepN
+        x = np.array([.5, 2., 3., 4., 5.5, 6.])
+        y = np.array([.5, 2., 3., 4., 5.5, 6.])
+        z = np.array(
+            [
+                [1, 2, 1, 2, 1, 1],
+                [1, 2, 1, 2, 1, 1],
+                [1, 2, 3, 2, 1, 1],
+                [1, 2, 2, 2, 1, 1],
+                [1, 2, 1, 2, 1, 1],
+                [1, 2, 2, 2, 1, 1],
+            ]
+        )
+        return x, y, z
+
+    def test_2D_vs_RGI_linear(self):
+        x, y, z = self._get_sample_2d_data()
+        bspl = make_ndbspl((x, y), z, k=1)
+        rgi = RegularGridInterpolator((x, y), z, method='linear')
+
+        xi = np.array([[1, 2.3, 5.3, 0.5, 3.3, 1.2, 3],
+                       [1, 3.3, 1.2, 4.0, 5.0, 1.0, 3]]).T
+
+        xp_assert_close(bspl(xi), rgi(xi), atol=1e-14)
+
+    def test_2D_vs_RGI_cubic(self):
+        x, y, z = self._get_sample_2d_data()
+        bspl = make_ndbspl((x, y), z, k=3, solver=ssl.spsolve)
+        rgi = RegularGridInterpolator((x, y), z, method='cubic_legacy')
+
+        xi = np.array([[1, 2.3, 5.3, 0.5, 3.3, 1.2, 3],
+                       [1, 3.3, 1.2, 4.0, 5.0, 1.0, 3]]).T
+
+        xp_assert_close(bspl(xi), rgi(xi), atol=1e-14)
+
+    @pytest.mark.parametrize('solver', [ssl.gmres, ssl.gcrotmk])
+    def test_2D_vs_RGI_cubic_iterative(self, solver):
+        # same as `test_2D_vs_RGI_cubic`, only with an iterative solver.
+        # Note the need to add an explicit `rtol` solver_arg to achieve the
+        # target accuracy of 1e-14. (the relation between solver atol/rtol
+        # and the accuracy of the final result is not direct and needs experimenting)
+        x, y, z = self._get_sample_2d_data()
+        bspl = make_ndbspl((x, y), z, k=3, solver=solver, rtol=1e-6)
+        rgi = RegularGridInterpolator((x, y), z, method='cubic_legacy')
+
+        xi = np.array([[1, 2.3, 5.3, 0.5, 3.3, 1.2, 3],
+                       [1, 3.3, 1.2, 4.0, 5.0, 1.0, 3]]).T
+
+        xp_assert_close(bspl(xi), rgi(xi), atol=1e-14, rtol=1e-7)
+
+    def test_2D_vs_RGI_quintic(self):
+        x, y, z = self._get_sample_2d_data()
+        bspl = make_ndbspl((x, y), z, k=5, solver=ssl.spsolve)
+        rgi = RegularGridInterpolator((x, y), z, method='quintic_legacy')
+
+        xi = np.array([[1, 2.3, 5.3, 0.5, 3.3, 1.2, 3],
+                       [1, 3.3, 1.2, 4.0, 5.0, 1.0, 3]]).T
+
+        xp_assert_close(bspl(xi), rgi(xi), atol=1e-14)
+
+    @pytest.mark.parametrize(
+        'k, meth', [(1, 'linear'), (3, 'cubic_legacy'), (5, 'quintic_legacy')]
+    )
+    def test_3D_random_vs_RGI(self, k, meth):
+        rndm = np.random.default_rng(123456)
+        x = np.cumsum(rndm.uniform(size=6))
+        y = np.cumsum(rndm.uniform(size=7))
+        z = np.cumsum(rndm.uniform(size=8))
+        values = rndm.uniform(size=(6, 7, 8))
+
+        bspl = make_ndbspl((x, y, z), values, k=k, solver=ssl.spsolve)
+        rgi = RegularGridInterpolator((x, y, z), values, method=meth)
+
+        xi = np.random.uniform(low=0.7, high=2.1, size=(11, 3))
+        xp_assert_close(bspl(xi), rgi(xi), atol=1e-14)
+
+    def test_solver_err_not_converged(self):
+        x, y, z = self._get_sample_2d_data()
+        solver_args = {'maxiter': 1}
+        with assert_raises(ValueError, match='solver'):
+            make_ndbspl((x, y), z, k=3, **solver_args)
+
+        with assert_raises(ValueError, match='solver'):
+            make_ndbspl((x, y), np.dstack((z, z)), k=3, **solver_args)
+
+
+class TestFpchec:
+    # https://github.com/scipy/scipy/blob/main/scipy/interpolate/fitpack/fpchec.f
+
+    def test_1D_x_t(self):
+        k = 1
+        t = np.arange(12).reshape(2, 6)
+        x = np.arange(12)
+
+        with pytest.raises(ValueError, match="1D sequence"):
+            _b.fpcheck(x, t, k)
+
+        with pytest.raises(ValueError, match="1D sequence"):
+            _b.fpcheck(t, x, k)
+
+    def test_condition_1(self):
+        # c      1) k+1 <= n-k-1 <= m
+        k = 3
+        n  = 2*(k + 1) - 1    # not OK
+        m = n + 11            # OK
+        t = np.arange(n)
+        x = np.arange(m)
+
+        assert dfitpack.fpchec(x, t, k) == 10
+        with pytest.raises(ValueError, match="Need k+1*"):
+            _b.fpcheck(x, t, k)
+
+        n = 2*(k+1) + 1   # OK
+        m = n - k - 2     # not OK
+        t = np.arange(n)
+        x = np.arange(m)
+
+        assert dfitpack.fpchec(x, t, k) == 10
+        with pytest.raises(ValueError, match="Need k+1*"):
+            _b.fpcheck(x, t, k)
+
+    def test_condition_2(self):
+        # c      2) t(1) <= t(2) <= ... <= t(k+1)
+        # c         t(n-k) <= t(n-k+1) <= ... <= t(n)
+        k = 3
+        t = [0]*(k+1) + [2] + [5]*(k+1)   # this is OK
+        x = [1, 2, 3, 4, 4.5]
+
+        assert dfitpack.fpchec(x, t, k) == 0
+        assert _b.fpcheck(x, t, k) is None    # does not raise
+
+        tt = t.copy()
+        tt[-1] = tt[0]   # not OK
+        assert dfitpack.fpchec(x, tt, k) == 20
+        with pytest.raises(ValueError, match="Last k knots*"):
+            _b.fpcheck(x, tt, k)
+
+        tt = t.copy()
+        tt[0] = tt[-1]   # not OK
+        assert dfitpack.fpchec(x, tt, k) == 20
+        with pytest.raises(ValueError, match="First k knots*"):
+            _b.fpcheck(x, tt, k)
+
+    def test_condition_3(self):
+        # c      3) t(k+1) < t(k+2) < ... < t(n-k)
+        k = 3
+        t = [0]*(k+1) + [2, 3] + [5]*(k+1)   # this is OK
+        x = [1, 2, 3, 3.5, 4, 4.5]
+        assert dfitpack.fpchec(x, t, k) == 0
+        assert _b.fpcheck(x, t, k) is None
+
+        t = [0]*(k+1) + [2, 2] + [5]*(k+1)   # this is not OK
+        assert dfitpack.fpchec(x, t, k) == 30
+        with pytest.raises(ValueError, match="Internal knots*"):
+            _b.fpcheck(x, t, k)
+
+    def test_condition_4(self):
+        # c      4) t(k+1) <= x(i) <= t(n-k)
+        # NB: FITPACK's fpchec only checks x[0] & x[-1], so we follow.
+        k = 3
+        t = [0]*(k+1) + [5]*(k+1)
+        x = [1, 2, 3, 3.5, 4, 4.5]      # this is OK
+        assert dfitpack.fpchec(x, t, k) == 0
+        assert _b.fpcheck(x, t, k) is None
+
+        xx = x.copy()
+        xx[0] = t[0]    # still OK
+        assert dfitpack.fpchec(xx, t, k) == 0
+        assert _b.fpcheck(x, t, k) is None
+
+        xx = x.copy()
+        xx[0] = t[0] - 1    # not OK
+        assert dfitpack.fpchec(xx, t, k) == 40
+        with pytest.raises(ValueError, match="Out of bounds*"):
+            _b.fpcheck(xx, t, k)
+
+        xx = x.copy()
+        xx[-1] = t[-1] + 1    # not OK
+        assert dfitpack.fpchec(xx, t, k) == 40
+        with pytest.raises(ValueError, match="Out of bounds*"):
+            _b.fpcheck(xx, t, k)
+
+    # ### Test the S-W condition (no 5)
+    # c      5) the conditions specified by schoenberg and whitney must hold
+    # c         for at least one subset of data points, i.e. there must be a
+    # c         subset of data points y(j) such that
+    # c             t(j) < y(j) < t(j+k+1), j=1,2,...,n-k-1
+    def test_condition_5_x1xm(self):
+        # x(1).ge.t(k2) .or. x(m).le.t(nk1)
+        k = 1
+        t = [0, 0, 1, 2, 2]
+        x = [1.1, 1.1, 1.1]
+        assert dfitpack.fpchec(x, t, k) == 50
+        with pytest.raises(ValueError, match="Schoenberg-Whitney*"):
+            _b.fpcheck(x, t, k)
+
+        x = [0.5, 0.5, 0.5]
+        assert dfitpack.fpchec(x, t, k) == 50
+        with pytest.raises(ValueError, match="Schoenberg-Whitney*"):
+            _b.fpcheck(x, t, k)
+
+    def test_condition_5_k1(self):
+        # special case nk3 (== n - k - 2) < 2
+        k = 1
+        t = [0, 0, 1, 1]
+        x = [0.5, 0.6]
+        assert dfitpack.fpchec(x, t, k) == 0
+        assert _b.fpcheck(x, t, k) is None
+
+    def test_condition_5_1(self):
+        # basically, there can't be an interval of t[j]..t[j+k+1] with no x
+        k = 3
+        t = [0]*(k+1) + [2] + [5]*(k+1)
+        x = [3]*5
+        assert dfitpack.fpchec(x, t, k) == 50
+        with pytest.raises(ValueError, match="Schoenberg-Whitney*"):
+            _b.fpcheck(x, t, k)
+
+        t = [0]*(k+1) + [2] + [5]*(k+1)
+        x = [1]*5
+        assert dfitpack.fpchec(x, t, k) == 50
+        with pytest.raises(ValueError, match="Schoenberg-Whitney*"):
+            _b.fpcheck(x, t, k)
+
+    def test_condition_5_2(self):
+        # same as _5_1, only the empty interval is in the middle
+        k = 3
+        t = [0]*(k+1) + [2, 3] + [5]*(k+1)
+        x = [1.1]*5 + [4]
+
+        assert dfitpack.fpchec(x, t, k) == 50
+        with pytest.raises(ValueError, match="Schoenberg-Whitney*"):
+            _b.fpcheck(x, t, k)
+
+        # and this one is OK
+        x = [1.1]*4 + [4, 4]
+        assert dfitpack.fpchec(x, t, k) == 0
+        assert _b.fpcheck(x, t, k) is None
+
+    def test_condition_5_3(self):
+        # similar to _5_2, covers a different failure branch
+        k = 1
+        t = [0, 0, 2, 3, 4, 5, 6, 7, 7]
+        x = [1, 1, 1, 5.2, 5.2, 5.2, 6.5]
+
+        assert dfitpack.fpchec(x, t, k) == 50
+        with pytest.raises(ValueError, match="Schoenberg-Whitney*"):
+            _b.fpcheck(x, t, k)
+
+
+# ### python replicas of generate_knots(...) implementation details, for testing.
+# ### see TestGenerateKnots::test_split_and_add_knot
+def _split(x, t, k, residuals):
+    """Split the knot interval into "runs".
+    """
+    ix = np.searchsorted(x, t[k:-k])
+    # sum half-open intervals
+    fparts = [residuals[ix[i]:ix[i+1]].sum() for i in range(len(ix)-1)]
+    carries = residuals[ix[1:-1]]
+
+    for i in range(len(carries)):     # split residuals at internal knots
+        carry = carries[i] / 2
+        fparts[i] += carry
+        fparts[i+1] -= carry
+
+    fparts[-1] += residuals[-1]       # add the contribution of the last knot
+
+    xp_assert_close(sum(fparts), sum(residuals), atol=1e-15)
+
+    return fparts, ix
+
+
+def _add_knot(x, t, k, residuals):
+    """Insert a new knot given reduals."""
+    fparts, ix = _split(x, t, k, residuals)
+
+    # find the interval with max fparts and non-zero number of x values inside
+    idx_max = -101
+    fpart_max = -1e100
+    for i in range(len(fparts)):
+        if ix[i+1] - ix[i] > 1 and fparts[i] > fpart_max:
+            idx_max = i
+            fpart_max = fparts[i]
+
+    if idx_max == -101:
+        raise ValueError("Internal error, please report it to SciPy developers.")
+
+    # round up, like Dierckx does? This is really arbitrary though.
+    idx_newknot = (ix[idx_max] + ix[idx_max+1] + 1) // 2
+    new_knot = x[idx_newknot]
+    idx_t = np.searchsorted(t, new_knot)
+    t_new = np.r_[t[:idx_t], new_knot, t[idx_t:]]
+    return t_new
+
+
+@make_xp_test_case(generate_knots)
+class TestGenerateKnots:
+    def test_split_add_knot(self):
+        # smoke test implementation details: insert a new knot given residuals
+        x = np.arange(8, dtype=float)
+        y = x**3 + 1./(1 + x)
+        k = 3
+        t = np.array([0.]*(k+1) + [7.]*(k+1))
+        spl = make_lsq_spline(x, y, k=k, t=t)
+        residuals = (spl(x) - y)**2
+
+        from scipy.interpolate import _fitpack_repro as _fr
+        new_t = _fr.add_knot(x, t, k, residuals)
+        new_t_py = _add_knot(x, t, k, residuals)
+
+        xp_assert_close(new_t, new_t_py, atol=1e-15)
+
+        # redo with new knots
+        spl2 = make_lsq_spline(x, y, k=k, t=new_t)
+        residuals2 = (spl2(x) - y)**2
+
+        new_t2 = _fr.add_knot(x, new_t, k, residuals2)
+        new_t2_py = _add_knot(x, new_t, k, residuals2)
+
+        xp_assert_close(new_t2, new_t2_py, atol=1e-15)
+
+    @pytest.mark.parametrize('k', [1, 2, 3, 4, 5])
+    def test_s0(self, k, xp):
+        x = xp.arange(8, dtype=xp.float64)
+        y = xp.sin(x*xp.pi/8)
+        t = list(generate_knots(x, y, k=k, s=0))[-1]
+
+        tt = splrep(x, y, k=k, s=0)[0]
+        tt = xp.asarray(tt, dtype=xp.float64)
+        xp_assert_close(t, tt, atol=1e-15)
+
+    def test_s0_1(self, xp):
+        # with these data, naive algorithm tries to insert >= nmax knots
+        n = 10
+        x = xp.arange(n, dtype=xp.float64)
+        y = x**3
+        knots = list(generate_knots(x, y, k=3, s=0))   # does not error out
+        expected = xp.asarray(_not_a_knot(np.asarray(x), 3))
+        xp_assert_close(knots[-1], expected, atol=1e-15)
+
+    def test_s0_n20(self, xp):
+        n = 20
+        x = xp.arange(n)
+        y = x**3
+        knots = list(generate_knots(x, y, k=3, s=0))
+        expected = xp.asarray(_not_a_knot(np.asarray(x), 3))
+        xp_assert_close(knots[-1], expected, atol=1e-15)
+
+    def test_s0_nest(self):
+        # s=0 and non-default nest: not implemented, errors out
+        x = np.arange(10)
+        y = x**3
+        with assert_raises(ValueError):
+            list(generate_knots(x, y, k=3, s=0, nest=10))
+
+    def test_s_switch(self, xp):
+        # test the process switching to interpolating knots when len(t) == m + k + 1
+        """
+        To generate the `wanted` list below apply the following diff and rerun
+        the test. The stdout will contain successive iterations of the `t`
+        array.
+
+$ git diff scipy/interpolate/fitpack/fpcurf.f
+diff --git a/scipy/interpolate/fitpack/fpcurf.f b/scipy/interpolate/fitpack/fpcurf.f
+index 1afb1900f1..d817e51ad8 100644
+--- a/scipy/interpolate/fitpack/fpcurf.f
++++ b/scipy/interpolate/fitpack/fpcurf.f
+@@ -216,6 +216,9 @@ c  t(j+k) <= x(i) <= t(j+k+1) and store it in fpint(j),j=1,2,...nrint.
+         do 190 l=1,nplus
+ c  add a new knot.
+           call fpknot(x,m,t,n,fpint,nrdata,nrint,nest,1)
++          print*, l, nest, ': ', t
++          print*, "n, nmax = ", n, nmax
++
+ c  if n=nmax we locate the knots as for interpolation.
+           if(n.eq.nmax) go to 10
+ c  test whether we cannot further increase the number of knots.
+        """  # NOQA: E501
+        x = xp.arange(8, dtype=xp.float64)
+        y = xp.sin(x*np.pi/8)
+        k = 3
+
+        knots = list(generate_knots(x, y, k=k, s=1e-7))
+        wanted = [[0., 0., 0., 0., 7., 7., 7., 7.],
+                  [0., 0., 0., 0., 4., 7., 7., 7., 7.],
+                  [0., 0., 0., 0., 2., 4., 7., 7., 7., 7.],
+                  [0., 0., 0., 0., 2., 4., 6., 7., 7., 7., 7.],
+                  [0., 0., 0., 0., 2., 3., 4., 5., 7, 7., 7., 7.]
+        ]
+        wanted = [xp.asarray(want, dtype=xp.float64) for want in wanted]
+
+        assert len(knots) == len(wanted)
+        for t, tt in zip(knots, wanted):
+            xp_assert_close(t, tt, atol=1e-15)
+
+        # also check that the last knot vector matches FITPACK
+        t, _, _ = splrep(x, y, k=k, s=1e-7)
+        xp_assert_close(knots[-1], xp.asarray(t), atol=1e-15)
+
+    def test_list_input(self):
+        # test that list inputs are accepted
+        x = list(range(8))
+        gen = generate_knots(x, x, s=0.1, k=1)
+        next(gen)
+
+    def test_nest(self, xp):
+        # test that nest < nmax stops the process early (and we get 10 knots not 12)
+        x = xp.arange(8, dtype=xp.float64)
+        y = xp.sin(x*xp.pi/8)
+        s = 1e-7
+
+        knots = list(generate_knots(x, y, k=3, s=s, nest=10))
+        xp_assert_close(
+            knots[-1],
+            xp.asarray([0., 0., 0., 0., 2., 4., 7., 7., 7., 7.], dtype=xp.float64),
+            atol=1e-15
+        )
+
+        with assert_raises(ValueError):
+            # nest < 2*(k+1)
+            list(generate_knots(x, y, k=3, nest=4))
+
+    def test_weights(self):
+        x = np.arange(8)
+        y = np.sin(x*np.pi/8)
+
+        with assert_raises(ValueError):
+            list(generate_knots(x, y, w=np.arange(11)))   # len(w) != len(x)
+
+        with assert_raises(ValueError):
+            list(generate_knots(x, y, w=-np.ones(8)))    # w < 0
+
+    @pytest.mark.parametrize("npts", [30, 50, 100])
+    @pytest.mark.parametrize("s", [0.1, 1e-2, 0])
+    def test_vs_splrep(self, s, npts):
+        # XXX this test is brittle: differences start apearing for k=3 and s=1e-6,
+        # also for k != 3. Might be worth investigating at some point.
+        # I think we do not really guarantee exact agreement with splrep. Instead,
+        # we guarantee it is the same *in most cases*; otherwise slight differences
+        # are allowed. There is no theorem, it is al heuristics by P. Dierckx.
+        # The best we can do it to best-effort reproduce it.
+        rndm = np.random.RandomState(12345)
+        x = 10*np.sort(rndm.uniform(size=npts))
+        y = np.sin(x*np.pi/10) + np.exp(-(x-6)**2)
+
+        k = 3
+        t = splrep(x, y, k=k, s=s)[0]
+        tt = list(generate_knots(x, y, k=k, s=s))[-1]
+
+        xp_assert_close(tt, t, atol=1e-15)
+
+    def test_s_too_small(self):
+        n = 14
+        x = np.arange(n)
+        y = x**3
+
+        # XXX splrep warns that "s too small": ier=2
+        knots = list(generate_knots(x, y, k=3, s=1e-50))
+
+        with pytest.warns(RuntimeWarning) as r:
+            tck = splrep(x, y, k=3, s=1e-50)
+        assert len(r) == 1
+        xp_assert_equal(knots[-1], tck[0])
+
+    def test_zero_weights(self):
+        # regression test for https://github.com/scipy/scipy/issues/23542
+        gen = generate_knots([0.,1.,2.,3.], [4.,5.,6.,7.], w=[0.,0.,0.,0.], s=1)
+        with pytest.raises(ValueError, match="weights are zero"):
+            list(gen)
+
+
+def disc_naive(t, k):
+    """Straitforward way to compute the discontinuity matrix. For testing ONLY.
+
+    This routine returns a dense matrix, while `_fitpack_repro.disc` returns
+    a packed one.
+    """
+    n = t.shape[0]
+
+    delta = t[n - k - 1] - t[k]
+    nrint = n - 2*k - 1
+
+    ti = t[k+1:n-k-1]   # internal knots
+    tii = np.repeat(ti, 2)
+    tii[::2] += 1e-10
+    tii[1::2] -= 1e-10
+    m = BSpline(t, np.eye(n - k - 1), k)(tii, nu=k)
+
+    matr = np.empty((nrint-1, m.shape[1]), dtype=float)
+    for i in range(0, m.shape[0], 2):
+        matr[i//2, :] = m[i, :] - m[i+1, :]
+
+    matr *= (delta/nrint)**k / math.factorial(k)
+    return matr
+
+
+class F_dense:
+    """ The r.h.s. of ``f(p) = s``, an analog of _fitpack_repro.F
+    Uses full matrices, so is for tests only.
+    """
+    def __init__(self, x, y, t, k, s, w=None, extrapolate=True):
+        self.x = x
+        self.y = y
+        self.t = t
+        self.k = k
+        self.w = np.ones_like(x, dtype=float) if w is None else w
+        self.extrapolate = extrapolate
+        assert self.w.ndim == 1
+
+        # lhs
+        a_dense = BSpline(t, np.eye(t.shape[0] - k - 1), k, extrapolate=extrapolate)(x)
+        self.a_dense = a_dense * self.w[:, None]
+
+        from scipy.interpolate import _fitpack_repro as _fr
+        self.b_dense = PackedMatrix(*_fr.disc(t, k)).todense()
+
+        # rhs
+        assert y.ndim == 1
+        yy = y * self.w
+        self.yy = np.r_[yy, np.zeros(self.b_dense.shape[0])]
+
+        self.s = s
+
+    def __call__(self, p):
+        ab = np.vstack((self.a_dense, self.b_dense / p))
+
+        # LSQ solution of ab @ c = yy
+        from scipy.linalg import qr, solve
+        q, r = qr(ab, mode='economic')
+
+        qy = q.T @ self.yy
+
+        nc = r.shape[1]
+        c = solve(r[:nc, :nc], qy[:nc])
+
+        spl = BSpline(self.t, c, self.k, extrapolate=self.extrapolate)
+        fp = np.sum(self.w**2 * (spl(self.x) - self.y)**2)
+
+        self.spl = spl   # store it
+
+        return fp - self.s
+
+
+class _TestMakeSplrepBase:
+
+    bc_type = None
+
+    def _get_xykt(self, xp=np):
+        if self.bc_type == 'periodic':
+            x = xp.linspace(0, 2*np.pi, 10)    # nodes
+            y  = xp.sin(x)
+            s = 1.7e-4
+
+            return x, y, s
+        else:
+            x = xp.linspace(0, 5, 11)
+            y  = xp.sin(x*3.14 / 5)**2
+            s = 1.7e-4
+
+            return x, y, s
+
+    def test_input_errors(self):
+        x = np.linspace(0, 10, 11)
+        y = np.linspace(0, 10, 12)
+        with assert_raises(ValueError):
+            # len(x) != len(y)
+            make_splrep(x, y, bc_type=self.bc_type)
+
+        with assert_raises(ValueError):
+            # 0D inputs
+            make_splrep(1, 2, s=0.1, bc_type=self.bc_type)
+
+        with assert_raises(ValueError):
+            # y.ndim > 2
+            y = np.ones((x.size, 2, 2, 2))
+            make_splrep(x, y, s=0.1, bc_type=self.bc_type)
+
+        w = np.ones(12)
+        with assert_raises(ValueError):
+            # len(weights) != len(x)
+            make_splrep(x, x**3, w=w, s=0.1, bc_type=self.bc_type)
+
+        w = -np.ones(12)
+        with assert_raises(ValueError):
+            # w < 0
+            make_splrep(x, x**3, w=w, s=0.1, bc_type=self.bc_type)
+
+        w = np.ones((x.shape[0], 2))
+        with assert_raises(ValueError):
+            # w.ndim != 1
+            make_splrep(x, x**3, w=w, s=0.1, bc_type=self.bc_type)
+
+        with assert_raises(ValueError):
+            # x not ordered
+            make_splrep(x[::-1], x**3, s=0.1, bc_type=self.bc_type)
+
+        with assert_raises(TypeError):
+            # k != int(k)
+            make_splrep(x, x**3, k=2.5, s=0.1, bc_type=self.bc_type)
+
+        with assert_raises(ValueError):
+            # s < 0
+            make_splrep(x, x**3, s=-1, bc_type=self.bc_type)
+
+        with assert_raises(ValueError):
+            # nest < 2*k + 2
+            make_splrep(x, x**3, k=3, nest=2, s=0.1, bc_type=self.bc_type)
+
+        with assert_raises(ValueError):
+            # nest not None and s==0
+            make_splrep(x, x**3, s=0, nest=11, bc_type=self.bc_type)
+
+        with assert_raises(ValueError):
+            # len(x) != len(y)
+            make_splrep(np.arange(8), np.arange(9), s=0.1, bc_type=self.bc_type)
+
+    def _test_with_knots(self, x, y, k, s):
+        t = list(generate_knots(x, y, k=k, s=s, bc_type=self.bc_type))[-1]
+
+        spl_auto = make_splrep(x, y, k=k, s=s, bc_type=self.bc_type)
+        spl_t = make_splrep(x, y, t=t, k=k, s=s, bc_type=self.bc_type)
+
+        xp_assert_close(spl_auto.t, spl_t.t, atol=1e-15)
+        xp_assert_close(spl_auto.c, spl_t.c, atol=1e-15)
+        assert spl_auto.k == spl_t.k
+
+    @pytest.mark.parametrize("k", [1, 2, 3, 4, 5, 6])
+    def test_with_knots(self, k):
+        x, y, s = self._get_xykt()
+
+        self._test_with_knots(x, y, k, s)
+
+    def _test_default_s(self, x, y, k):
+        spl = make_splrep(x, y, k=k, bc_type=self.bc_type)
+        spl_i = make_interp_spline(x, y, k=k, bc_type=self.bc_type)
+        t = list(generate_knots(x, y, k=k, bc_type=self.bc_type))[-1]
+
+        xp_assert_close(spl.c, spl_i.c, atol=1e-15)
+        xp_assert_close(spl.t, t, atol=1e-15)
+        xp_assert_close(spl_i.t, t, atol=1e-15)
+
+    @pytest.mark.parametrize("k", [1, 2, 3, 4, 5, 6])
+    def test_default_s(self, k):
+        x, y, _ = self._get_xykt()
+        self._test_default_s(x, y, k)
+
+    @pytest.mark.thread_unsafe
+    def test_s_too_small(self):
+        # both splrep and make_splrep warn that "s too small": ier=2
+        s = 1e-30
+        if self.bc_type == 'periodic':
+            x = np.linspace(0, 2*np.pi, 14)
+            y = np.sin(x)
+        else:
+            x = np.arange(14)
+            y = x**3
+
+        with warnings.catch_warnings():
+            warnings.simplefilter(
+                "ignore",
+                RuntimeWarning
+            )
+            tck = splrep(x, y, k=3, s=s, per=(self.bc_type == 'periodic'))
+
+        with warnings.catch_warnings():
+            warnings.simplefilter(
+                "ignore",
+                RuntimeWarning
+            )
+            spl = make_splrep(x, y, k=3, s=s, bc_type=self.bc_type)
+
+        xp_assert_close(spl.t, tck[0])
+        xp_assert_close(np.r_[spl.c, [0]*(spl.k+1)],
+                        tck[1], atol=5e-13)
+
+    @pytest.mark.parametrize("k", [1, 2, 3])
+    def test_shape(self, k):
+        # make sure coefficients have the right shape (not extra dims)
+        n = 10
+        if self.bc_type == 'periodic':
+            x = np.linspace(0, 2*np.pi, n)
+            y = np.cos(x)
+        else:
+            x = np.arange(n)
+            y = x**3
+
+        spl = make_splrep(x, y, k=k, bc_type=self.bc_type)
+        spl_1 = make_splrep(x, y, k=k, s=1e-5, bc_type=self.bc_type)
+
+        assert spl.c.ndim == 1
+        assert spl_1.c.ndim == 1
+
+        # force the general code path, not shortcuts
+        spl_2 = make_splrep(x, y + 1/(1+y), k=k, s=1e-5, bc_type=self.bc_type)
+        assert spl_2.c.ndim == 1
+
+    def test_error_on_invalid_bc_type(self):
+        N = 10
+        a, b = 0, 2*np.pi
+        x = np.linspace(a, b, N + 1)    # nodes
+        y = np.exp(x)
+
+        with assert_raises(ValueError):
+            make_splrep(x, y, s=1e-8, bc_type="nonsense")
+
+    @pytest.mark.parametrize("bc_type", ["periodic", None])
+    @pytest.mark.parametrize("k", [1, 2, 3, 4, 5])
+    def test_make_splrep_with_unequal_weights(self, bc_type, k):
+        # Sample data
+        x = np.linspace(0, 2*np.pi, 10)
+        y = np.sin(x)
+
+        w = np.linspace(1, 5, len(x))
+
+        tck = splrep(x, y, w=w, k=k, s=1e-8, per=(bc_type == 'periodic'))
+        spl = make_splrep(x, y, w=w, s=1e-8, k=k, bc_type=bc_type)
+
+        xp_assert_close(spl.t, tck[0])
+        xp_assert_close(np.r_[spl.c, [0]*(spl.k+1)],
+                        tck[1], atol=1e-8)
+
+
+    @pytest.mark.parametrize("bc_type", ["periodic", None])
+    def test_make_splrep_with_non_c_contiguous_input(self, bc_type):
+          # regression test for https://github.com/scipy/scipy/issues/23371
+
+        def check(spl, tck):
+            xp_assert_close(spl.t, tck[0])
+            xp_assert_close(np.r_[spl.c, [0]*(spl.k+1)],
+                            tck[1], atol=1e-8)
+
+        # Sample data
+        x = np.linspace(0, 2*np.pi, 10)
+        y = np.sin(x)
+
+        x1, y1 = np.c_[x, y].T
+
+        # Safety check to make sure inputs
+        # are actually not C contiguous
+        assert x1.flags.c_contiguous is False
+        assert y1.flags.c_contiguous is False
+
+        w = np.linspace(1, 5, len(x))
+        w1, _ = np.c_[w, w].T
+
+        # Safety check to make sure inputs
+        # are actually not C contiguous
+        assert w1.flags.c_contiguous is False
+
+        tck = splrep(x, y, w=w, k=3, s=1e-8, per=(bc_type == 'periodic'))
+
+        # only x.flags.c_contiguous is False
+        spl = make_splrep(x1, y, w=w, s=1e-8, k=3, bc_type=bc_type)
+        check(spl, tck)
+
+        # only x.flags.c_contiguous is False
+        spl = make_splrep(x, y1, w=w, s=1e-8, k=3, bc_type=bc_type)
+        check(spl, tck)
+
+        # only w.flags.c_contiguous is False
+        spl = make_splrep(x, y, w=w1, s=1e-8, k=3, bc_type=bc_type)
+        check(spl, tck)
+
+        # x, y, z all have c_contiguous False
+        spl = make_splrep(x1, y1, w=w1, s=1e-8, k=3,
+                          bc_type=bc_type)
+        check(spl, tck)
+
+
+    @pytest.mark.parametrize("bc_type", ["periodic", None])
+    @pytest.mark.parametrize("k", [1, 2, 3, 4, 5])
+    def test_make_splrep_impl_no_optimization(self, bc_type, k):
+        # Sample data
+        x = np.linspace(0, 1, 10)
+        y = np.sin(2 * np.pi * x)
+
+        xb, xe = x[0], x[-1]
+        k = 3  # Cubic spline
+        s = 1e-8  # No smoothing
+
+        # Provide t with only boundary knots -> length = 2*(k+1)
+        t = np.array([xb] * (k + 1) + [xe] * (k + 1))
+
+        # Should skip optimization
+        spl = make_splrep(x, y, xb=xb, xe=xe, k=k,
+                        s=s, t=t, nest=None, bc_type=bc_type)
+
+        assert isinstance(spl, BSpline)
+        assert spl.t.shape[0] == 2 * (k + 1)
+        assert spl.k == k
+        xp_assert_close(spl.t[:k+1], np.asarray([xb] * (k + 1)))
+        xp_assert_close(spl.t[-(k+1):], np.asarray([xe] * (k + 1)))
+
+    @pytest.mark.parametrize("n", [100, 51, 15, 11])
+    @pytest.mark.parametrize("s", [10, 8, 5, 1, 1e-2])
+    def test_make_splrep_matches_splrep_periodic(self, n, s):
+        rng = np.random.default_rng(123)
+        x = np.r_[0, np.sort(rng.uniform(0, 2 * np.pi, size=n - 2)), 2 * np.pi]
+        y = np.sin(x) + np.cos(x)
+
+        t, c, k = splrep(x, y, s=s, per=(self.bc_type == "periodic"))
+        spl = make_splrep(x, y, s=s, bc_type=self.bc_type)
+
+        if not (n == 11 and s == 1 and self.bc_type == "periodic"):
+            xp_assert_close(spl.t, t, atol=1e-15)
+            xp_assert_close(spl.c, c[:-k - 1], atol=1e-15)
+
+    @pytest.mark.parametrize("n", [100, 51, 15, 11])
+    @pytest.mark.parametrize("s", [10, 8, 5, 1, 1e-2])
+    def test_make_splrep_with_splrep_knots(self, n, s):
+        rng = np.random.default_rng(123)
+        x = np.r_[0, np.sort(rng.uniform(0, 2 * np.pi, size=n - 2)), 2 * np.pi]
+        y = np.sin(x) + np.cos(x)
+
+        t, c, k = splrep(x, y, s=s, per=(self.bc_type == "periodic"))
+        spl = make_splrep(x, y, s=s, bc_type=self.bc_type, t=t)
+        xp_assert_close(spl.c, c[:-k - 1], atol=1e-15)
+
+
+@make_xp_test_case(make_splrep)
+class TestMakeSplrep(_TestMakeSplrepBase):
+
+    @pytest.mark.parametrize("k", [1, 2, 3, 4, 5, 6])
+    def test_fitpack_F(self, k):
+        # test an implementation detail: banded/packed linalg vs full matrices
+        from scipy.interpolate._fitpack_repro import F
+
+        x, y, s = self._get_xykt()
+        t = np.array([0]*(k+1) + [2.5, 4.0] + [5]*(k+1))
+        f = F(x, y[:, None], t, k, s)    # F expects y to be 2D
+        f_d = F_dense(x, y, t, k, s)
+        for p in [1, 10, 100]:
+            xp_assert_close(f(p), f_d(p), atol=1e-15)
+
+    @pytest.mark.parametrize("k", [1, 2, 3, 4, 5, 6])
+    def test_fitpack_F_with_weights(self, k):
+        # repeat test_fitpack_F, with weights
+        from scipy.interpolate._fitpack_repro import F
+
+        x, y, s = self._get_xykt()
+        t = np.array([0]*(k+1) + [2.5, 4.0] + [5]*(k+1))
+        w = np.arange(x.shape[0], dtype=float)
+        fw = F(x, y[:, None], t, k, s, w=w)       # F expects y to be 2D
+        fw_d = F_dense(x, y, t, k, s, w=w)
+
+        f_d = F_dense(x, y, t, k, s)   # no weights
+
+        for p in [1, 10, 100]:
+            xp_assert_close(fw(p), fw_d(p), atol=1e-15)
+            assert not np.allclose(f_d(p), fw_d(p), atol=1e-15)
+
+    def test_disc_matrix(self):
+        # test an implementation detail: discontinuity matrix
+        # (jumps of k-th derivative at knots)
+        import scipy.interpolate._fitpack_repro as _fr
+
+        rng = np.random.default_rng(12345)
+        t = np.r_[0, 0, 0, 0, np.sort(rng.uniform(size=7))*5, 5, 5, 5, 5]
+
+        n, k = len(t), 3
+        D = PackedMatrix(*_fr.disc(t, k)).todense()
+        D_dense = disc_naive(t, k)
+        assert D.shape[0] == n - 2*k - 2   # number of internal knots
+        xp_assert_close(D, D_dense, atol=1e-15)
+
+    def test_simple_vs_splrep(self, xp):
+        # XX: Non-periodic splines do not work for all supported degrees
+        k = 3
+        x, y, s = self._get_xykt(xp)
+        tt = xp.asarray([0]*(k+1) + [2.5, 4.0] + [5]*(k+1))
+
+        t, c, k = splrep(x, y, k=k, s=s)
+        t, c = xp.asarray(t), xp.asarray(c)
+        assert all(t == tt)
+
+        spl = make_splrep(x, y, k=k, s=s)
+        xp_assert_close(c[:spl.c.shape[0]], spl.c, atol=1e-15)
+
+    def test_with_knots(self):
+        k = 3
+        x, y, s = self._get_xykt()
+
+        t = list(generate_knots(x, y, k=k, s=s))[-1]
+
+        spl_auto = make_splrep(x, y, k=k, s=s)
+        spl_t = make_splrep(x, y, t=t, k=k, s=s)
+
+        xp_assert_close(spl_auto.t, spl_t.t, atol=1e-15)
+        xp_assert_close(spl_auto.c, spl_t.c, atol=1e-15)
+        assert spl_auto.k == spl_t.k
+
+    def test_no_internal_knots(self, xp):
+        # should not fail if there are no internal knots
+        n = 10
+        x = xp.arange(n, dtype=xp.float64)
+        y = x**3
+        k = 3
+        spl = make_splrep(x, y, k=k, s=1)
+        assert spl.t.shape[0] == 2*(k+1)
+
+    def test_default_s(self, xp):
+        n = 10
+        x = xp.arange(n, dtype=xp.float64)
+        y = x**3
+        spl = make_splrep(x, y, k=3)
+        spl_i = make_interp_spline(x, y, k=3)
+
+        xp_assert_close(spl.c, spl_i.c, atol=1e-15)
+
+    def test_s_too_small(self):
+        # both splrep and make_splrep warn that "s too small": ier=2
+        n = 14
+        x = np.arange(n)
+        y = x**3
+
+        with pytest.warns(RuntimeWarning) as r:
+            tck = splrep(x, y, k=3, s=1e-50)
+            spl = make_splrep(x, y, k=3, s=1e-50)
+            xp_assert_equal(spl.t, tck[0])
+            xp_assert_close(np.r_[spl.c, [0]*(spl.k+1)],
+                            tck[1], atol=5e-13)
+        assert len(r) == 2
+
+    def test_issue_22704(self):
+        # Reference - https://github.com/scipy/scipy/issues/22704
+        x = np.asarray([20.00, 153.81, 175.57, 202.47, 237.11,
+             253.61, 258.56, 273.40, 284.54, 293.61,
+             298.56, 301.86, 305.57, 307.22, 308.45,
+             310.10, 310.10, 310.50], dtype=np.float64)
+        y = np.asarray([53.00, 49.50, 48.60, 46.80, 43.20,
+             40.32, 39.60, 36.00, 32.40, 28.80,
+             25.20, 21.60, 18.00, 14.40, 10.80,
+             7.20, 3.60, 0.0], dtype=np.float64)
+        w = np.asarray([1.38723] * y.shape[0], dtype=np.float64)
+        with assert_raises(ValueError):
+            make_splrep(x, y, w=w, k=2, s=12)
+
+    def test_shape(self, xp):
+        # make sure coefficients have the right shape (not extra dims)
+        n, k = 10, 3
+        x = xp.arange(n, dtype=xp.float64)
+        y = x**3
+
+        spl = make_splrep(x, y, k=k)
+        spl_1 = make_splrep(x, y, k=k, s=1e-5)
+
+        assert spl.c.ndim == 1
+        assert spl_1.c.ndim == 1
+
+        # force the general code path, not shortcuts
+        spl_2 = make_splrep(x, y + 1/(1+y), k=k, s=1e-5)
+        assert spl_2.c.ndim == 1
+
+    def test_s0_vs_not(self, xp):
+        # check that the shapes are consistent
+        n, k = 10, 3
+        x = xp.arange(n, dtype=xp.float64)
+        y = x**3
+
+        spl_0 = make_splrep(x, y, k=3, s=0)
+        spl_1 = make_splrep(x, y, k=3, s=1)
+
+        assert spl_0.c.ndim == 1
+        assert spl_1.c.ndim == 1
+
+        assert spl_0.t.shape[0] == n + k + 1
+        assert spl_1.t.shape[0] == 2 * (k + 1)
+
+
+@make_xp_test_case(make_splrep)
+class TestMakeSplrepPeriodic(_TestMakeSplrepBase):
+
+    bc_type = 'periodic'
+
+    @pytest.mark.parametrize("k", [1, 2, 3, 4, 5, 6])
+    def test_no_internal_knots(self, k, xp):
+        # should not fail if there are no internal knots
+        x = xp.linspace(0, 10, 11)    # nodes
+        y = xp.ones((11,))
+
+        spl = make_splrep(x, y, k=k, s=1, bc_type=self.bc_type)
+        assert spl.t.shape[0] == 2*(k+1)
+
+    @pytest.mark.parametrize("k", [1, 2, 3, 4, 5, 6])
+    def test_s0_vs_not(self, k):
+        # check that the shapes are consistent
+        n = 10
+        x = np.linspace(0, 2*np.pi, n)
+        y = np.sin(x) + np.cos(x)
+
+        spl_0 = make_splrep(x, y, k=k, s=0, bc_type=self.bc_type)
+        spl_1 = make_splrep(x, y, k=k, s=1, bc_type=self.bc_type)
+
+        assert spl_0.c.ndim == 1
+        assert spl_1.c.ndim == 1
+
+        assert spl_0.t.shape[0] == n + 2 * k
+
+    def test_periodic_with_periodic_data(self, xp):
+        N = 10
+        a, b = 0, 2*xp.pi
+        x = xp.linspace(a, b, N + 1, dtype=xp.float64)    # nodes
+
+        y = xp.cos(x)
+        spl = make_splrep(x, y, s=1e-8, bc_type=self.bc_type)
+        xp_assert_close(splev(x, spl), y, atol=1e-5, rtol=1e-4)
+
+        y = xp.sin(x) + xp.cos(x)
+        spl = make_splrep(x, y, s=1e-12, bc_type=self.bc_type)
+        xp_assert_close(splev(x, spl), y, atol=1e-5, rtol=1e-6)
+
+        y = 5*xp.sin(x) + xp.cos(x)*3
+        spl = make_splrep(x, y, s=1e-8, bc_type=self.bc_type)
+        xp_assert_close(splev(x, spl), y, atol=1e-5, rtol=1e-4)
+
+    def test_periodic_with_non_periodic_data(self):
+        N = 10
+        a, b = 0, 2*np.pi
+        x = np.linspace(a, b, N + 1)    # nodes
+
+        y = np.exp(x)
+        with assert_raises(ValueError):
+            make_splrep(x, y, s=1e-8, bc_type=self.bc_type)
+
+    @pytest.mark.parametrize("s", [0, 1e-50])
+    def test_make_splrep_periodic_m_eq_2_k_eq_1(self, s):
+        # Two data points (m = 2)
+        x = np.array([0.0, 1.0])
+        y = np.array([5.0, 5.0])  # constant function
+        w = np.array([1.0, 1.0]) if s > 0 else None
+
+        # Degree 1 periodic spline
+        spl = make_splrep(x, y, w=w, k=1, bc_type="periodic", s=s)
+        tck = splrep(x, y, w=w, k=1, per=1, s=s)
+
+        if s > 0:
+            xp_assert_close(spl.t, tck[0])
+        xp_assert_close(np.r_[spl.c, [0]*(spl.k+1)],
+                        tck[1])
+
+    @pytest.mark.parametrize("s", [1, 1e-8, 42])
+    def test_spline_endpoints_match(self, s):
+        """make_splrep with bc_type='periodic' must produce a periodic
+        spline."""
+        theta = np.linspace(0, 1, 11)
+        y = np.cos(2*np.pi*theta)
+        spl = make_splrep(theta, y, s=s, bc_type="periodic")
+        xp_assert_close(spl(theta[0]), spl(theta[-1]), atol=1e-12)
+        assert spl.extrapolate == 'periodic'
+        # check wraparound: spl(u + delta) = spl(u + 2 * delta)
+        xp_assert_close(spl(theta[-1] + 0.2), spl(theta[0] + 0.2), atol=1e-12)
+        xp_assert_close(spl(theta[0] - 0.2), spl(theta[-1] - 0.2), atol=1e-12)
+        # check k-derivatives
+        nus = np.arange(spl.k)
+        vals_right = np.array([spl(theta[-1] + 0.2, nu) for nu in nus])
+        vals_left = np.array([spl(theta[0] + 0.2, nu) for nu in nus])
+        xp_assert_close(vals_right, vals_left, atol=1e-10)
+
+    @pytest.mark.parametrize("k_fp", [(1, -0.0001), (2, -0.0001), (3, -8.62e-05)])
+    @pytest.mark.parametrize("s", [1e-4])
+    def test_fperiodic_basic_fit(self, k_fp, s):
+        n = 10
+        x = np.linspace(0, 1, n)
+        y = np.sin(2 * np.pi * x)
+        k, fp = k_fp
+
+        tck = splrep(x, y, k=k, s=s, per=1)
+
+        fp0 = 4.5
+
+        spline = Fperiodic(x, y[:, None], tck[0], k=k, s=s)
+        with warnings.catch_warnings():
+            warnings.simplefilter("ignore", RuntimeWarning)
+            _ = root_rati(spline, 2.0, ((0, fp0 - s), (np.inf, fp - s)), s * 0.001)
+
+        # Check the returned spline is periodic at endpoints
+        bs = spline.spl
+        x_check = np.array([0.0, 1.0])
+        y_check = bs(x_check)
+
+        xp_assert_close(y_check[0], y_check[1])
+
+@make_xp_test_case(make_splprep)
+class TestMakeSplprep:
+    def _get_xyk(self, m=10, k=3, xp=np):
+        x = xp.arange(m, dtype=xp.float64) * xp.pi / m
+        y = [xp.sin(x), xp.cos(x)]
+        return x, y, k
+
+    @pytest.mark.parametrize('s', [0, 0.1, 1e-3, 1e-5])
+    def test_simple_vs_splprep(self, s):
+        # Check/document the interface vs splPrep
+        # The four values of `s` are to probe all code paths and shortcuts
+        m, k = 10, 3
+        x = np.arange(m) * np.pi / m
+        y = [np.sin(x), np.cos(x)]
+
+        # the number of knots depends on `s` (this is by construction)
+        num_knots = {0: 14, 0.1: 8, 1e-3: 8 + 1, 1e-5: 8 + 2}
+
+        # construct the splines
+        (t, c, k), u_ = splprep(y, s=s)
+        spl, u = make_splprep(y, s=s)
+
+        # parameters
+        xp_assert_close(u, u_, atol=1e-15)
+
+        # knots
+        xp_assert_close(spl.t, t, atol=1e-15)
+        assert len(t) == num_knots[s]
+
+        # coefficients: note the transpose
+        cc = np.asarray(c).T
+        xp_assert_close(spl.c, cc, atol=1e-15)
+
+        # values: note axis=1
+        xp_assert_close(spl(u),
+                        BSpline(t, c, k, axis=1)(u), atol=1e-15)
+    @pytest.mark.parametrize('s', [0, 0.1, 1e-3, 1e-5])
+    def test_array_not_list(self, s):
+        # the argument of splPrep is either a list of arrays or a 2D array (sigh)
+        _, y, _ = self._get_xyk()
+        assert isinstance(y, list)
+        assert np.shape(y)[0] == 2
+
+        # assert the behavior of FITPACK's splrep
+        tck, u = splprep(y, s=s)
+        tck_a, u_a = splprep(np.asarray(y), s=s)
+        xp_assert_close(u, u_a, atol=s)
+        xp_assert_close(tck[0], tck_a[0], atol=1e-15)
+        assert len(tck[1]) == len(tck_a[1])
+        xp_assert_close(tck[1], tck_a[1], atol=1e-15)
+        assert tck[2] == tck_a[2]
+        assert np.shape(splev(u, tck)) == np.shape(y)
+
+        spl, u = make_splprep(y, s=s)
+        xp_assert_close(u, u_a, atol=1e-15)
+        xp_assert_close(spl.t, tck_a[0], atol=1e-15)
+        xp_assert_close(spl.c.T, tck_a[1], atol=1e-15)
+        assert spl.k == tck_a[2]
+        assert spl(u).shape == np.shape(y)
+
+        spl, u = make_splprep(np.asarray(y), s=s)
+        xp_assert_close(u, u_a, atol=1e-15)
+        xp_assert_close(spl.t, tck_a[0], atol=1e-15)
+        xp_assert_close(spl.c.T, tck_a[1], atol=1e-15)
+        assert spl.k == tck_a[2]
+        assert spl(u).shape == np.shape(y)
+
+        with assert_raises(ValueError):
+            make_splprep(np.asarray(y).T, s=s)
+
+    def test_default_s_is_zero(self, xp):
+        x, y, k = self._get_xyk(m=10, xp=xp)
+
+        spl, u = make_splprep(y)
+        xp_assert_close(spl(u), xp.stack(y), atol=1e-15)
+
+    def test_s_zero_vs_near_zero(self, xp):
+        # s=0 and s \approx 0 are consistent
+        x, y, k = self._get_xyk(m=10, xp=xp)
+
+        spl_i, u_i = make_splprep(y, s=0)
+        spl_n, u_n = make_splprep(y, s=1e-15)
+
+        xp_assert_close(u_i, u_n, atol=1e-15)
+        xp_assert_close(spl_i(u_i), xp.stack(y), atol=1e-15)
+        xp_assert_close(spl_n(u_n), xp.stack(y), atol=1e-7)
+        assert spl_i.axis == spl_n.axis
+        assert spl_i.c.shape == spl_n.c.shape
+
+    def test_1D(self):
+        x = np.arange(8, dtype=float)
+        with assert_raises(ValueError):
+            splprep(x)
+
+        with assert_raises(ValueError):
+            make_splprep(x, s=0)
+
+        with assert_raises(ValueError):
+            make_splprep(x, s=0.1)
+
+        tck, u_ = splprep([x], s=1e-5)
+        spl, u = make_splprep([x], s=1e-5)
+
+        assert spl(u).shape == (1, 8)
+        xp_assert_close(spl(u), [x], atol=1e-15)
+
+
+@make_xp_test_case(make_splprep)
+class TestMakeSplprepPeriodic:
+
+    def _get_xyk(self, n=10, k=3, xp=np):
+        x = xp.linspace(0, 2*xp.pi, n, dtype=xp.float64)
+        y = [xp.sin(x), xp.cos(x)]
+        return x, y, k
+
+    @pytest.mark.parametrize('s', [0, 1e-4, 1e-5, 1e-6])
+    def test_simple_vs_splprep(self, s):
+        # Check/document the interface vs splPrep
+        # The four values of `s` are to probe all code paths and shortcuts
+        n = 10
+        x = np.linspace(0, 2*np.pi, n)
+        y = [np.sin(x), np.cos(x)]
+
+        # the number of knots depends on `s` (this is by construction)
+        num_knots = {0: 16, 1e-4: 16, 1e-5: 16, 1e-6: 16}
+
+        # construct the splines
+        (t, c, k), u_ = splprep(y, s=s, per=1)
+        spl, u = make_splprep(y, s=s, bc_type="periodic")
+
+        # parameters
+        xp_assert_close(u, u_, atol=1e-15)
+
+        # knots
+        assert len(spl.t) == num_knots[s]
+
+        # values: note axis=1
+        xp_assert_close(spl(u), BSpline(t, c, k, axis=1)(u),
+                        atol=1e-06, rtol=1e-06)
+
+    @pytest.mark.parametrize("s", [1, 1e-8, 42])
+    def test_spline_endpoints_match(self, s):
+        """make_splprep with bc_type='periodic' must produce a periodic
+        spline: matching endpoint values, extrapolate='periodic'."""
+        theta = np.linspace(0, 1, 11)
+        x = np.sin(2*np.pi*theta)
+        y = np.cos(2*np.pi*theta)
+        spl, u = make_splprep([x, y], u=theta, s=s, bc_type="periodic")
+        xp_assert_close(spl(u[0]), spl(u[-1]), atol=1e-12)
+        assert spl.extrapolate == 'periodic'
+        # check wraparound: spl(u + delta) = spl(u + 2 * delta)
+        xp_assert_close(spl(u[-1] + 0.2), spl(u[0] + 0.2), atol=1e-12)
+        xp_assert_close(spl(u[0] - 0.2), spl(u[-1] - 0.2), atol=1e-12)
+        # check k-derivatives match
+        nus = np.arange(spl.k)
+        vals_right = np.array([spl(u[-1] + 0.2, nu) for nu in nus])
+        vals_left = np.array([spl(u[0] + 0.2, nu) for nu in nus])
+        xp_assert_close(vals_right, vals_left, atol=1e-10)
+
+    @pytest.mark.parametrize('s', [0, 1e-4, 1e-5, 1e-6])
+    def test_array_not_list(self, s):
+        # the argument of splPrep is either a list of arrays or a 2D array (sigh)
+        _, y, _ = self._get_xyk()
+        assert isinstance(y, list)
+        assert np.shape(y)[0] == 2
+
+        # assert the behavior of FITPACK's splrep
+        tck, u = splprep(y, s=s, per=1)
+        tck_a, u_a = splprep(np.asarray(y), s=s, per=1)
+        xp_assert_close(u, u_a, atol=s)
+        xp_assert_close(tck[0], tck_a[0], atol=1e-15)
+        assert len(tck[1]) == len(tck_a[1])
+        for c1, c2 in zip(tck[1], tck_a[1]):
+            xp_assert_close(c1, c2, atol=1e-15)
+        assert tck[2] == tck_a[2]
+        assert np.shape(splev(u, tck)) == np.shape(y)
+
+        spl, u = make_splprep(y, s=s, bc_type="periodic")
+        xp_assert_close(u, u_a, atol=1e-15)
+        assert spl.k == tck_a[2]
+        assert spl(u).shape == np.shape(y)
+
+        spl, u = make_splprep(np.asarray(y), s=s, bc_type="periodic")
+        xp_assert_close(u, u_a, atol=1e-15)
+        assert spl.k == tck_a[2]
+        assert spl(u).shape == np.shape(y)
+
+        with assert_raises(ValueError):
+            make_splprep(np.asarray(y).T, s=s, bc_type="periodic")
+
+    def test_default_s_is_zero(self, xp):
+        x, y, k = self._get_xyk(n=10, xp=xp)
+
+        spl, u = make_splprep(y, bc_type="periodic")
+        xp_assert_close(spl(u), xp.stack(y), atol=1e-15)
+
+    def test_s_zero_vs_near_zero(self, xp):
+        # s=0 and s \approx 0 are consistent
+        x, y, k = self._get_xyk(n=10, xp=xp)
+
+        spl_i, u_i = make_splprep(y, s=0, bc_type="periodic")
+        spl_n, u_n = make_splprep(y, s=1e-12, bc_type="periodic")
+
+        xp_assert_close(u_i, u_n, atol=1e-15)
+
+        y_arr = xp.stack(y)   #  xp_assert_close chokes on the list `y`
+        xp_assert_close(spl_i(u_i), y_arr, atol=1e-15)
+        xp_assert_close(spl_n(u_n), y_arr, atol=1e-7, rtol=1e-6)
+        assert spl_i.axis == spl_n.axis
+
+    def test_1D(self):
+        x = np.linspace(0, 2*np.pi, 8)
+        x = np.sin(x)
+        with assert_raises(ValueError):
+            splprep(x, per=1)
+
+        with assert_raises(ValueError):
+            make_splprep(x, s=0, bc_type="periodic")
+
+        with assert_raises(ValueError):
+            make_splprep(x, s=0.1, bc_type="periodic")
+
+        spl, u = make_splprep([x], s=1e-15, bc_type="periodic")
+
+        assert spl(u).shape == (1, 8)
+        xp_assert_close(spl(u), [x], atol=1e-15)
+
+    @pytest.mark.parametrize("bc_type", [None, "not-a-knot", "periodic"])
+    @pytest.mark.parametrize("matching_endpoints", [True, False])
+    def test_bc_type_match_s0(self, bc_type, matching_endpoints):
+        # make_splprep at s=0 must match bc_type correctly to
+        # make_interp_spline, for every bc_type, endpoint-matching
+        theta = np.linspace(0, 1, 11)
+        x = np.sin(2*np.pi*theta)
+        y = np.cos(2*np.pi*theta)
+
+        if not matching_endpoints:
+            x = x.copy()
+            x[-1] = 1
+
+        periodic = (bc_type == "periodic")
+        should_raise = periodic and not matching_endpoints
+        xy = np.column_stack([x, y])
+        if should_raise:
+            with assert_raises(ValueError):
+                make_splprep([x, y], u=theta, s=0, bc_type=bc_type)
+            with assert_raises(ValueError):
+                make_interp_spline(theta, xy, bc_type=bc_type)
+        else:
+            spl, u = make_splprep([x, y], u=theta, s=0, bc_type=bc_type)
+            expected = make_interp_spline(theta, xy, bc_type=bc_type)
+            xp_assert_close(spl.c, expected.c, atol=1e-12)
+            xp_assert_close(spl.t, expected.t, atol=1e-12)
+            assert spl.extrapolate == expected.extrapolate
+
+class BatchSpline:
+    # BSpline-line class with reference batch behavior
+    def __init__(self, x, y, axis, *, spline, **kwargs):
+        y = np.moveaxis(y, axis, -1)
+        self._batch_shape = y.shape[:-1]
+        self._splines = [spline(x, yi, **kwargs) for yi in y.reshape(-1, y.shape[-1])]
+        self._axis = axis
+
+    def __call__(self, x):
+        y = [spline(x) for spline in self._splines]
+        y = np.reshape(y, self._batch_shape + x.shape)
+        return np.moveaxis(y, -1, self._axis) if x.shape else y
+
+    def integrate(self, a, b, extrapolate=None):
+        y = [spline.integrate(a, b, extrapolate) for spline in self._splines]
+        return np.reshape(y, self._batch_shape)
+
+    def derivative(self, nu):
+        res = copy.deepcopy(self)
+        res._splines = [spline.derivative(nu) for spline in res._splines]
+        return res
+
+    def antiderivative(self, nu):
+        res = copy.deepcopy(self)
+        res._splines = [spline.antiderivative(nu) for spline in res._splines]
+        return res
+
+
+class TestBatch:
+    @pytest.mark.parametrize('make_spline, kwargs',
+        [(make_interp_spline, {}),
+         (make_smoothing_spline, {}),
+         (make_smoothing_spline, {'lam': 1.0}),
+         (make_lsq_spline, {'method': "norm-eq"}),
+         (make_lsq_spline, {'method': "qr"}),
+         ])
+    @pytest.mark.parametrize('eval_shape', [(), (1,), (3,)])
+    @pytest.mark.parametrize('axis', [-1, 0, 1])
+    def test_batch(self, make_spline, kwargs, axis, eval_shape):
+        rng = np.random.default_rng(4329872134985134)
+        n = 10
+        shape = (2, 3, 4, n)
+        domain = (0, 10)
+
+        x = np.linspace(*domain, n)
+        y = np.moveaxis(rng.random(shape), -1, axis)
+
+        if make_spline == make_lsq_spline:
+            k = 3  # spline degree, if needed
+            t = (x[0],) * (k + 1) + (x[-1],) * (k + 1)  # valid knots, if needed
+            kwargs = kwargs | dict(t=t, k=k)
+
+        res = make_spline(x, y, axis=axis, **kwargs)
+        ref = BatchSpline(x, y, axis=axis, spline=make_spline, **kwargs)
+
+        x = rng.uniform(*domain, size=eval_shape)
+        np.testing.assert_allclose(res(x), ref(x))
+
+        res, ref = res.antiderivative(1), ref.antiderivative(1)
+        np.testing.assert_allclose(res(x), ref(x))
+
+        res, ref = res.derivative(2), ref.derivative(2)
+        np.testing.assert_allclose(res(x), ref(x))
+
+        np.testing.assert_allclose(res.integrate(*domain), ref.integrate(*domain))
diff --git a/.venv/lib/python3.12/site-packages/scipy/interpolate/tests/test_fitpack.py b/.venv/lib/python3.12/site-packages/scipy/interpolate/tests/test_fitpack.py
new file mode 100644
index 0000000000000000000000000000000000000000..fdf305008650002b5a47fe0253a643717541e382
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/interpolate/tests/test_fitpack.py
@@ -0,0 +1,549 @@
+import itertools
+import os
+
+import numpy as np
+from scipy._lib._array_api import (
+    xp_assert_equal, xp_assert_close, assert_almost_equal, assert_array_almost_equal
+)
+from pytest import raises as assert_raises
+import pytest
+from scipy._lib._testutils import check_free_memory
+
+from scipy.interpolate import RectBivariateSpline
+from scipy.interpolate import make_splrep
+
+from scipy.interpolate._fitpack_py import (splrep, splev, bisplrep, bisplev,
+     sproot, splprep, splint, spalde, splder, splantider, insert, dblint)
+from scipy.interpolate._fitpack2 import _regrid_smth as regrid_smth
+from scipy.interpolate._regrid import _regrid
+
+dfitpack_int = np.int32
+
+
+def data_file(basename):
+    return os.path.join(os.path.abspath(os.path.dirname(__file__)),
+                        'data', basename)
+
+
+def norm2(x):
+    return np.sqrt(np.dot(x.T, x))
+
+
+def f1(x, d=0):
+    """Derivatives of sin->cos->-sin->-cos."""
+    if d % 4 == 0:
+        return np.sin(x)
+    if d % 4 == 1:
+        return np.cos(x)
+    if d % 4 == 2:
+        return -np.sin(x)
+    if d % 4 == 3:
+        return -np.cos(x)
+
+
+def makepairs(x, y):
+    """Helper function to create an array of pairs of x and y."""
+    xy = np.array(list(itertools.product(np.asarray(x), np.asarray(y))))
+    return xy.T
+
+
+class TestSmokeTests:
+    """
+    Smoke tests (with a few asserts) for fitpack routines -- mostly
+    check that they are runnable
+    """
+    def check_1(self, per=0, s=0, a=0, b=2*np.pi, at_nodes=False,
+                xb=None, xe=None):
+        if xb is None:
+            xb = a
+        if xe is None:
+            xe = b
+
+        N = 20
+        # nodes and middle points of the nodes
+        x = np.linspace(a, b, N + 1)
+        x1 = a + (b - a) * np.arange(1, N, dtype=float) / float(N - 1)
+        v = f1(x)
+
+        def err_est(k, d):
+            # Assume f has all derivatives < 1
+            h = 1.0 / N
+            tol = 5 * h**(.75*(k-d))
+            if s > 0:
+                tol += 1e5*s
+            return tol
+
+        for k in range(1, 6):
+            tck = splrep(x, v, s=s, per=per, k=k, xe=xe)
+            tt = tck[0][k:-k] if at_nodes else x1
+
+            for d in range(k+1):
+                tol = err_est(k, d)
+                err = norm2(f1(tt, d) - splev(tt, tck, d)) / norm2(f1(tt, d))
+                assert err < tol
+
+            # smoke test make_splrep
+            if not per:
+                spl = make_splrep(x, v, k=k, s=s, xb=xb, xe=xe)
+                if len(spl.t) == len(tck[0]):
+                    xp_assert_close(spl.t, tck[0], atol=1e-15)
+                    xp_assert_close(spl.c, tck[1][:spl.c.size], atol=1e-13)
+                else:
+                    assert k == 5   # knot length differ in some k=5 cases
+            else:
+                if np.allclose(v[0], v[-1], atol=1e-15):
+                    spl = make_splrep(x, v, k=k, s=s, xb=xb, xe=xe, bc_type='periodic')
+                    if k != 1: # knots for k == 1 in some cases
+                        xp_assert_close(spl.t, tck[0], atol=1e-15)
+                        xp_assert_close(spl.c, tck[1][:spl.c.size], atol=1e-13)
+                else:
+                    with assert_raises(ValueError):
+                        spl = make_splrep(x, v, k=k, s=s,
+                                          xb=xb, xe=xe, bc_type='periodic')
+
+    def check_2(self, per=0, N=20, ia=0, ib=2*np.pi):
+        a, b, dx = 0, 2*np.pi, 0.2*np.pi
+        x = np.linspace(a, b, N+1)    # nodes
+        v = np.sin(x)
+
+        def err_est(k, d):
+            # Assume f has all derivatives < 1
+            h = 1.0 / N
+            tol = 5 * h**(.75*(k-d))
+            return tol
+
+        nk = []
+        for k in range(1, 6):
+            tck = splrep(x, v, s=0, per=per, k=k, xe=b)
+            nk.append([splint(ia, ib, tck), spalde(dx, tck)])
+
+        k = 1
+        for r in nk:
+            d = 0
+            for dr in r[1]:
+                tol = err_est(k, d)
+                xp_assert_close(dr, f1(dx, d), atol=0, rtol=tol)
+                d = d+1
+            k = k+1
+
+    def test_smoke_splrep_splev(self):
+        self.check_1(s=1e-6)
+        self.check_1(b=1.5*np.pi)
+
+    def test_smoke_splrep_splev_periodic(self):
+        self.check_1(b=1.5*np.pi, xe=2*np.pi, per=1, s=1e-1)
+        self.check_1(b=2*np.pi, per=1, s=1e-1)
+
+    @pytest.mark.parametrize('per', [0, 1])
+    @pytest.mark.parametrize('at_nodes', [True, False])
+    def test_smoke_splrep_splev_2(self, per, at_nodes):
+        self.check_1(per=per, at_nodes=at_nodes)
+
+    @pytest.mark.parametrize('N', [20, 50])
+    @pytest.mark.parametrize('per', [0, 1])
+    def test_smoke_splint_spalde(self, N, per):
+        self.check_2(per=per, N=N)
+
+    @pytest.mark.parametrize('N', [20, 50])
+    @pytest.mark.parametrize('per', [0, 1])
+    def test_smoke_splint_spalde_iaib(self, N, per):
+        self.check_2(ia=0.2*np.pi, ib=np.pi, N=N, per=per)
+
+    def test_smoke_sproot(self):
+        # sproot is only implemented for k=3
+        a, b = 0.1, 15
+        x = np.linspace(a, b, 20)
+        v = np.sin(x)
+
+        for k in [1, 2, 4, 5]:
+            tck = splrep(x, v, s=0, per=0, k=k, xe=b)
+            with assert_raises(ValueError):
+                sproot(tck)
+
+        k = 3
+        tck = splrep(x, v, s=0, k=3)
+        roots = sproot(tck)
+        xp_assert_close(splev(roots, tck), np.zeros(len(roots)), atol=1e-10, rtol=1e-10)
+        xp_assert_close(roots, np.pi * np.array([1, 2, 3, 4]), rtol=1e-3)
+
+    @pytest.mark.parametrize('N', [20, 50])
+    @pytest.mark.parametrize('k', [1, 2, 3, 4, 5])
+    def test_smoke_splprep_splrep_splev(self, N, k):
+        a, b, dx = 0, 2.*np.pi, 0.2*np.pi
+        x = np.linspace(a, b, N+1)    # nodes
+        v = np.sin(x)
+
+        tckp, u = splprep([x, v], s=0, per=0, k=k, nest=-1)
+        uv = splev(dx, tckp)
+        err1 = abs(uv[1] - np.sin(uv[0]))
+        assert err1 < 1e-2
+
+        tck = splrep(x, v, s=0, per=0, k=k)
+        err2 = abs(splev(uv[0], tck) - np.sin(uv[0]))
+        assert err2 < 1e-2
+
+        # Derivatives of parametric cubic spline at u (first function)
+        if k == 3:
+            tckp, u = splprep([x, v], s=0, per=0, k=k, nest=-1)
+            for d in range(1, k+1):
+                uv = splev(dx, tckp, d)
+
+    def test_smoke_bisplrep_bisplev(self):
+        xb, xe = 0, 2.*np.pi
+        yb, ye = 0, 2.*np.pi
+        kx, ky = 3, 3
+        Nx, Ny = 20, 20
+
+        def f2(x, y):
+            return np.sin(x+y)
+
+        x = np.linspace(xb, xe, Nx + 1)
+        y = np.linspace(yb, ye, Ny + 1)
+        xy = makepairs(x, y)
+        tck = bisplrep(xy[0], xy[1], f2(xy[0], xy[1]), s=0, kx=kx, ky=ky)
+
+        tt = [tck[0][kx:-kx], tck[1][ky:-ky]]
+        t2 = makepairs(tt[0], tt[1])
+        v1 = bisplev(tt[0], tt[1], tck)
+        v2 = f2(t2[0], t2[1])
+        v2 = v2.reshape(len(tt[0]), len(tt[1]))
+
+        assert norm2(np.ravel(v1 - v2)) < 1e-2
+
+
+class TestSplev:
+    def test_1d_shape(self):
+        x = [1,2,3,4,5]
+        y = [4,5,6,7,8]
+        tck = splrep(x, y)
+        z = splev([1], tck)
+        assert z.shape == (1,)
+        z = splev(1, tck)
+        assert z.shape == ()
+
+    def test_2d_shape(self):
+        x = [1, 2, 3, 4, 5]
+        y = [4, 5, 6, 7, 8]
+        tck = splrep(x, y)
+        t = np.array([[1.0, 1.5, 2.0, 2.5],
+                      [3.0, 3.5, 4.0, 4.5]])
+        z = splev(t, tck)
+        z0 = splev(t[0], tck)
+        z1 = splev(t[1], tck)
+        xp_assert_equal(z, np.vstack((z0, z1)))
+
+    def test_extrapolation_modes(self):
+        # test extrapolation modes
+        #    * if ext=0, return the extrapolated value.
+        #    * if ext=1, return 0
+        #    * if ext=2, raise a ValueError
+        #    * if ext=3, return the boundary value.
+        x = [1,2,3]
+        y = [0,2,4]
+        tck = splrep(x, y, k=1)
+
+        rstl = [[-2, 6], [0, 0], None, [0, 4]]
+        for ext in (0, 1, 3):
+            assert_array_almost_equal(splev([0, 4], tck, ext=ext), rstl[ext])
+
+        assert_raises(ValueError, splev, [0, 4], tck, ext=2)
+
+
+class TestSplder:
+    def setup_method(self):
+        # non-uniform grid, just to make it sure
+        x = np.linspace(0, 1, 100)**3
+        y = np.sin(20 * x)
+        self.spl = splrep(x, y)
+
+        # double check that knots are non-uniform
+        assert np.ptp(np.diff(self.spl[0])) > 0
+
+    def test_inverse(self):
+        # Check that antiderivative + derivative is identity.
+        for n in range(5):
+            spl2 = splantider(self.spl, n)
+            spl3 = splder(spl2, n)
+            xp_assert_close(self.spl[0], spl3[0])
+            xp_assert_close(self.spl[1], spl3[1])
+            assert self.spl[2] == spl3[2]
+
+    def test_splder_vs_splev(self):
+        # Check derivative vs. FITPACK
+
+        for n in range(3+1):
+            # Also extrapolation!
+            xx = np.linspace(-1, 2, 2000)
+            if n == 3:
+                # ... except that FITPACK extrapolates strangely for
+                # order 0, so let's not check that.
+                xx = xx[(xx >= 0) & (xx <= 1)]
+
+            dy = splev(xx, self.spl, n)
+            spl2 = splder(self.spl, n)
+            dy2 = splev(xx, spl2)
+            if n == 1:
+                xp_assert_close(dy, dy2, rtol=2e-6)
+            else:
+                xp_assert_close(dy, dy2)
+
+    def test_splantider_vs_splint(self):
+        # Check antiderivative vs. FITPACK
+        spl2 = splantider(self.spl)
+
+        # no extrapolation, splint assumes function is zero outside
+        # range
+        xx = np.linspace(0, 1, 20)
+
+        for x1 in xx:
+            for x2 in xx:
+                y1 = splint(x1, x2, self.spl)
+                y2 = splev(x2, spl2) - splev(x1, spl2)
+                xp_assert_close(np.asarray(y1), np.asarray(y2))
+
+    def test_order0_diff(self):
+        assert_raises(ValueError, splder, self.spl, 4)
+
+    def test_kink(self):
+        # Should refuse to differentiate splines with kinks
+
+        spl2 = insert(0.5, self.spl, m=2)
+        splder(spl2, 2)  # Should work
+        assert_raises(ValueError, splder, spl2, 3)
+
+        spl2 = insert(0.5, self.spl, m=3)
+        splder(spl2, 1)  # Should work
+        assert_raises(ValueError, splder, spl2, 2)
+
+        spl2 = insert(0.5, self.spl, m=4)
+        assert_raises(ValueError, splder, spl2, 1)
+
+    def test_multidim(self):
+        # c can have trailing dims
+        for n in range(3):
+            t, c, k = self.spl
+            c2 = np.c_[c, c, c]
+            c2 = np.dstack((c2, c2))
+
+            spl2 = splantider((t, c2, k), n)
+            spl3 = splder(spl2, n)
+
+            xp_assert_close(t, spl3[0])
+            xp_assert_close(c2, spl3[1])
+            assert k == spl3[2]
+
+
+class TestSplint:
+    def test_len_c(self):
+        n, k = 7, 3
+        x = np.arange(n)
+        y = x**3
+        t, c, k = splrep(x, y, s=0)
+
+        # note that len(c) == len(t) == 11 (== len(x) + 2*(k-1))
+        assert len(t) == len(c) == n + 2*(k-1)
+
+        # integrate directly: $\int_0^6 x^3 dx = 6^4 / 4$
+        res = splint(0, 6, (t, c, k))
+        expected = 6**4 / 4
+        assert abs(res - expected) < 1e-13
+
+        # check that the coefficients past len(t) - k - 1 are ignored
+        c0 = c.copy()
+        c0[len(t) - k - 1:] = np.nan
+        res0 = splint(0, 6, (t, c0, k))
+        assert abs(res0 - expected) < 1e-13
+
+        # however, all other coefficients *are* used
+        c0[6] = np.nan
+        assert np.isnan(splint(0, 6, (t, c0, k)))
+
+        # check that the coefficient array can have length `len(t) - k - 1`
+        c1 = c[:len(t) - k - 1]
+        res1 = splint(0, 6, (t, c1, k))
+        assert (res1 - expected) < 1e-13
+
+
+        # however shorter c arrays raise. The error from f2py is a
+        # `dftipack.error`, which is an Exception but not ValueError etc.
+        with assert_raises(Exception, match=r">=n-k-1"):
+            splint(0, 1, (np.ones(10), np.ones(5), 3))
+
+
+class TestBisplrep:
+    def test_overflow(self):
+        from numpy.lib.stride_tricks import as_strided
+        if dfitpack_int.itemsize == 8:
+            size = 1500000**2
+        else:
+            size = 400**2
+        # Don't allocate a real array, as it's very big, but rely
+        # on that it's not referenced
+        x = as_strided(np.zeros(()), shape=(size,))
+        assert_raises(OverflowError, bisplrep, x, x, x, w=x,
+                      xb=0, xe=1, yb=0, ye=1, s=0)
+
+    def test_regression_1310(self):
+        # Regression test for gh-1310
+        with np.load(data_file('bug-1310.npz')) as loaded_data:
+            data = loaded_data['data']
+
+        # Shouldn't crash -- the input data triggers work array sizes
+        # that caused previously some data to not be aligned on
+        # sizeof(double) boundaries in memory, which made the Fortran
+        # code to crash when compiled with -O3
+        bisplrep(data[:,0], data[:,1], data[:,2], kx=3, ky=3, s=0,
+                 full_output=True)
+
+    @pytest.mark.skipif(dfitpack_int != np.int64, reason="needs ilp64 fitpack")
+    def test_ilp64_bisplrep(self):
+        check_free_memory(28000)  # VM size, doesn't actually use the pages
+        x = np.linspace(0, 1, 400)
+        y = np.linspace(0, 1, 400)
+        x, y = np.meshgrid(x, y)
+        z = np.zeros_like(x)
+        tck = bisplrep(x, y, z, kx=3, ky=3, s=0)
+        xp_assert_close(bisplev(0.5, 0.5, tck), 0.0)
+
+
+@pytest.mark.parametrize("k", [3, 4])
+def test_dblint(k):
+    # Basic test to see it runs and gives the correct result on a trivial
+    # problem. Note that `dblint` is not exposed in the interpolate namespace.
+    x = np.linspace(0, 1)
+    y = np.linspace(0, 1)
+    xx, yy = np.meshgrid(x, y)
+    rect = RectBivariateSpline(x, y, 4 * xx * yy,
+                               kx=k, ky=k)
+    rect_custom = _regrid(x, y, 4 * xx * yy,
+                                              kx=k, ky=k)
+    tck = list(rect.tck)
+    tck.extend(rect.degrees)
+    tck_custom = list(rect_custom.t + (rect_custom.c.flatten(),))
+    tck_custom.extend(rect.degrees)
+
+    assert abs(dblint(0, 1, 0, 1, tck) - 1) < 1e-10
+    assert abs(dblint(0, 1, 0, 1, tck_custom) - 1) < 1e-10
+
+    assert abs(dblint(0, 0.5, 0, 1, tck) - 0.25) < 1e-10
+    assert abs(dblint(0, 0.5, 0, 1, tck_custom) - 0.25) < 1e-10
+
+    assert abs(dblint(0.5, 1, 0, 1, tck) - 0.75) < 1e-10
+    assert abs(dblint(0.5, 1, 0, 1, tck_custom) - 0.75) < 1e-10
+
+    assert abs(dblint(-100, 100, -100, 100, tck) - 1) < 1e-10
+    assert abs(dblint(-100, 100, -100, 100, tck_custom) - 1) < 1e-10
+
+
+def test_splev_der_k():
+    # regression test for gh-2188: splev(x, tck, der=k) gives garbage or crashes
+    # for x outside of knot range
+
+    # test case from gh-2188
+    tck = (np.array([0., 0., 2.5, 2.5]),
+           np.array([-1.56679978, 2.43995873, 0., 0.]),
+           1)
+    t, c, k = tck
+    x = np.array([-3, 0, 2.5, 3])
+
+    # an explicit form of the linear spline
+    xp_assert_close(splev(x, tck), c[0] + (c[1] - c[0]) * x/t[2])
+    xp_assert_close(splev(x, tck, 1),
+                    np.ones_like(x) * (c[1] - c[0]) / t[2]
+    )
+
+    # now check a random spline vs splder
+    np.random.seed(1234)
+    x = np.sort(np.random.random(30))
+    y = np.random.random(30)
+    t, c, k = splrep(x, y)
+
+    x = [t[0] - 1., t[-1] + 1.]
+    tck2 = splder((t, c, k), k)
+    xp_assert_close(splev(x, (t, c, k), k), splev(x, tck2))
+
+
+def test_splprep_segfault():
+    # regression test for gh-3847: splprep segfaults if knots are specified
+    # for task=-1
+    t = np.arange(0, 1.1, 0.1)
+    x = np.sin(2*np.pi*t)
+    y = np.cos(2*np.pi*t)
+    tck, u = splprep([x, y], s=0)
+    np.arange(0, 1.01, 0.01)
+
+    uknots = tck[0]  # using the knots from the previous fitting
+    tck, u = splprep([x, y], task=-1, t=uknots)  # here is the crash
+
+
+@pytest.mark.skipif(dfitpack_int == np.int64,
+        reason='Will crash (see gh-23396), test only meant for 32-bit overflow')
+def test_bisplev_integer_overflow():
+    np.random.seed(1)
+
+    x = np.linspace(0, 1, 11)
+    y = x
+    z = np.random.randn(11, 11).ravel()
+    kx = 1
+    ky = 1
+
+    nx, tx, ny, ty, c, fp, ier = regrid_smth(
+        x, y, z, None, None, None, None, kx=kx, ky=ky, s=0.0, maxit=20)
+    tck = (tx[:nx], ty[:ny], c[:(nx - kx - 1) * (ny - ky - 1)], kx, ky)
+
+    xp = np.zeros([2621440])
+    yp = np.zeros([2621440])
+
+    assert_raises((RuntimeError, MemoryError), bisplev, xp, yp, tck)
+
+
+@pytest.mark.xslow
+def test_gh_1766():
+    # this should fail gracefully instead of segfaulting (int overflow)
+    size = 22
+    kx, ky = 3, 3
+    def f2(x, y):
+        return np.sin(x+y)
+
+    x = np.linspace(0, 10, size)
+    y = np.linspace(50, 700, size)
+    xy = makepairs(x, y)
+    tck = bisplrep(xy[0], xy[1], f2(xy[0], xy[1]), s=0, kx=kx, ky=ky)
+    # the size value here can either segfault
+    # or produce a MemoryError on main
+    tx_ty_size = 500000
+    tck[0] = np.arange(tx_ty_size)
+    tck[1] = np.arange(tx_ty_size) * 4
+    tt_0 = np.arange(50)
+    tt_1 = np.arange(50) * 3
+    with pytest.raises(MemoryError):
+        bisplev(tt_0, tt_1, tck, 1, 1)
+
+
+def test_spalde_scalar_input():
+    # Ticket #629
+    x = np.linspace(0, 10)
+    y = x**3
+    tck = splrep(x, y, k=3, t=[5])
+    res = spalde(np.float64(1), tck)
+    des = np.array([1., 3., 6., 6.])
+    assert_almost_equal(res, des)
+
+
+def test_spalde_nc():
+    # regression test for https://github.com/scipy/scipy/issues/19002
+    # here len(t) = 29 and len(c) = 25 (== len(t) - k - 1)
+    x = np.asarray([-10., -9., -8., -7., -6., -5., -4., -3., -2.5, -2., -1.5,
+                    -1., -0.5, 0., 0.5, 1., 1.5, 2., 2.5, 3., 4., 5., 6.],
+                    dtype="float")
+    t = [-10.0, -10.0, -10.0, -10.0, -9.0, -8.0, -7.0, -6.0, -5.0, -4.0, -3.0,
+         -2.5, -2.0, -1.5, -1.0, -0.5, 0.0, 0.5, 1.0, 1.5, 2.0, 2.5, 3.0, 4.0,
+         5.0, 6.0, 6.0, 6.0, 6.0]
+    c = np.asarray([1., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.,
+                    0., 0., 0., 0., 0., 0., 0., 0., 0., 0.])
+    k = 3
+
+    res = spalde(x, (t, c, k))
+    res = np.vstack(res)
+    res_splev = np.asarray([splev(x, (t, c, k), nu) for nu in range(4)])
+    xp_assert_close(res, res_splev.T, atol=1e-15)
diff --git a/.venv/lib/python3.12/site-packages/scipy/interpolate/tests/test_fitpack2.py b/.venv/lib/python3.12/site-packages/scipy/interpolate/tests/test_fitpack2.py
new file mode 100644
index 0000000000000000000000000000000000000000..a65b2834e57fed0fc015ba46a603f11e229cc0c0
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/interpolate/tests/test_fitpack2.py
@@ -0,0 +1,1950 @@
+# Created by Pearu Peterson, June 2003
+import itertools
+import sys
+import warnings
+
+import numpy as np
+import pytest
+from pytest import raises as assert_raises
+from scipy._lib._array_api import (
+    xp_assert_equal, xp_assert_close, assert_almost_equal, assert_array_almost_equal
+)
+
+from numpy import array, diff, linspace, meshgrid, ones, pi, shape
+from scipy.interpolate._fitpack_py import bisplrep, bisplev, splrep, spalde
+from scipy.interpolate._fitpack2 import (UnivariateSpline,
+        LSQUnivariateSpline, InterpolatedUnivariateSpline,
+        LSQBivariateSpline, SmoothBivariateSpline, RectBivariateSpline,
+        LSQSphereBivariateSpline, SmoothSphereBivariateSpline,
+        RectSphereBivariateSpline)
+
+from scipy._lib._testutils import _run_concurrent_barrier
+
+from scipy.interpolate import make_splrep, NdBSpline
+from scipy.interpolate._regrid import (_regrid,
+        _ndbspline_call_like_bivariate)
+
+def convert_to_ndbspline(lut):
+    tx, ty = lut.get_knots()
+    kx, ky = lut.degrees
+    nx, ny = len(tx), len(ty)
+    c = lut.get_coeffs().reshape((nx - kx - 1, ny - ky - 1))
+    return NdBSpline((tx, ty), c, (kx, ky))
+
+class TestUnivariateSpline:
+    def test_linear_constant(self):
+        x = [1,2,3]
+        y = [3,3,3]
+        lut = UnivariateSpline(x,y,k=1)
+        assert_array_almost_equal(lut.get_knots(), [1, 3])
+        assert_array_almost_equal(lut.get_coeffs(), [3, 3])
+        assert abs(lut.get_residual()) < 1e-10
+        assert_array_almost_equal(lut([1, 1.5, 2]), [3, 3, 3])
+
+    @pytest.mark.parametrize("bc_type", [None, 'periodic'])
+    def test_linear_constant_periodic(self, bc_type):
+        x = [1,2,3]
+        y = [3,3,3]
+        lut = UnivariateSpline(x,y,k=1)
+
+        spl = make_splrep(x, y, k=1, s=len(x), bc_type=bc_type)
+        xp_assert_close(spl.t[1:-1], lut.get_knots(), atol=1e-15)
+        xp_assert_close(spl.c, lut.get_coeffs(), atol=1e-15)
+
+    def test_preserve_shape(self):
+        x = [1, 2, 3]
+        y = [0, 2, 4]
+        lut = UnivariateSpline(x, y, k=1)
+        arg = 2
+        assert shape(arg) == shape(lut(arg))
+        assert shape(arg) == shape(lut(arg, nu=1))
+        arg = [1.5, 2, 2.5]
+        assert shape(arg) == shape(lut(arg))
+        assert shape(arg) == shape(lut(arg, nu=1))
+
+    def test_linear_1d(self):
+        x = [1,2,3]
+        y = [0,2,4]
+        lut = UnivariateSpline(x,y,k=1)
+        assert_array_almost_equal(lut.get_knots(),[1,3])
+        assert_array_almost_equal(lut.get_coeffs(),[0,4])
+        assert abs(lut.get_residual()) < 1e-15
+        assert_array_almost_equal(lut([1,1.5,2]),[0,1,2])
+
+    def test_subclassing(self):
+        # See #731
+
+        class ZeroSpline(UnivariateSpline):
+            def __call__(self, x):
+                return 0*array(x)
+
+        sp = ZeroSpline([1,2,3,4,5], [3,2,3,2,3], k=2)
+        xp_assert_equal(sp([1.5, 2.5]), [0., 0.])
+
+    def test_empty_input(self):
+        # Test whether empty input returns an empty output. Ticket 1014
+        x = [1,3,5,7,9]
+        y = [0,4,9,12,21]
+        spl = UnivariateSpline(x, y, k=3)
+        xp_assert_equal(spl([]), array([]))
+
+    def test_roots(self):
+        x = [1, 3, 5, 7, 9]
+        y = [0, 4, 9, 12, 21]
+        spl = UnivariateSpline(x, y, k=3)
+        assert_almost_equal(spl.roots()[0], 1.050290639101332)
+
+    def test_roots_length(self): # for gh18335
+        x = np.linspace(0, 50 * np.pi, 1000)
+        y = np.cos(x)
+        spl = UnivariateSpline(x, y, s=0)
+        assert len(spl.roots()) == 50
+
+    def test_derivatives(self):
+        x = [1, 3, 5, 7, 9]
+        y = [0, 4, 9, 12, 21]
+        spl = UnivariateSpline(x, y, k=3)
+        assert_almost_equal(spl.derivatives(3.5),
+                            [5.5152902, 1.7146577, -0.1830357, 0.3125])
+
+    def test_derivatives_2(self):
+        x = np.arange(8)
+        y = x**3 + 2.*x**2
+
+        tck = splrep(x, y, s=0)
+        ders = spalde(3, tck)
+        xp_assert_close(ders, [45.,   # 3**3 + 2*(3)**2
+                               39.,   # 3*(3)**2 + 4*(3)
+                               22.,   # 6*(3) + 4
+                               6.],   # 6*3**0
+                        atol=1e-15)
+        spl = UnivariateSpline(x, y, s=0, k=3)
+        xp_assert_close(spl.derivatives(3),
+                        ders,
+                        atol=1e-15)
+
+    def test_resize_regression(self):
+        """Regression test for #1375."""
+        x = [-1., -0.65016502, -0.58856235, -0.26903553, -0.17370892,
+             -0.10011001, 0., 0.10011001, 0.17370892, 0.26903553, 0.58856235,
+             0.65016502, 1.]
+        y = [1.,0.62928599, 0.5797223, 0.39965815, 0.36322694, 0.3508061,
+             0.35214793, 0.3508061, 0.36322694, 0.39965815, 0.5797223,
+             0.62928599, 1.]
+        w = [1.00000000e+12, 6.88875973e+02, 4.89314737e+02, 4.26864807e+02,
+             6.07746770e+02, 4.51341444e+02, 3.17480210e+02, 4.51341444e+02,
+             6.07746770e+02, 4.26864807e+02, 4.89314737e+02, 6.88875973e+02,
+             1.00000000e+12]
+        spl = UnivariateSpline(x=x, y=y, w=w, s=None)
+        desired = array([0.35100374, 0.51715855, 0.87789547, 0.98719344])
+        xp_assert_close(spl([0.1, 0.5, 0.9, 0.99]), desired, atol=5e-4)
+
+    def test_out_of_range_regression(self):
+        # Test different extrapolation modes. See ticket 3557
+        x = np.arange(5, dtype=float)
+        y = x**3
+
+        xp = linspace(-8, 13, 100)
+        xp_zeros = xp.copy()
+        xp_zeros[np.logical_or(xp_zeros < 0., xp_zeros > 4.)] = 0
+        xp_clip = xp.copy()
+        xp_clip[xp_clip < x[0]] = x[0]
+        xp_clip[xp_clip > x[-1]] = x[-1]
+
+        for cls in [UnivariateSpline, InterpolatedUnivariateSpline]:
+            spl = cls(x=x, y=y)
+            for ext in [0, 'extrapolate']:
+                xp_assert_close(spl(xp, ext=ext), xp**3, atol=1e-16)
+                xp_assert_close(cls(x, y, ext=ext)(xp), xp**3, atol=1e-16)
+            for ext in [1, 'zeros']:
+                xp_assert_close(spl(xp, ext=ext), xp_zeros**3, atol=1e-16)
+                xp_assert_close(cls(x, y, ext=ext)(xp), xp_zeros**3, atol=1e-16)
+            for ext in [2, 'raise']:
+                assert_raises(ValueError, spl, xp, **dict(ext=ext))
+            for ext in [3, 'const']:
+                xp_assert_close(spl(xp, ext=ext), xp_clip**3, atol=2e-16)
+                xp_assert_close(cls(x, y, ext=ext)(xp), xp_clip**3, atol=2e-16)
+
+        # also test LSQUnivariateSpline [which needs explicit knots]
+        t = spl.get_knots()[3:4]  # interior knots w/ default k=3
+        spl = LSQUnivariateSpline(x, y, t)
+        xp_assert_close(spl(xp, ext=0), xp**3, atol=1e-16)
+        xp_assert_close(spl(xp, ext=1), xp_zeros**3, atol=1e-16)
+        assert_raises(ValueError, spl, xp, **dict(ext=2))
+        xp_assert_close(spl(xp, ext=3), xp_clip**3, atol=1e-16)
+
+        # also make sure that unknown values for `ext` are caught early
+        for ext in [-1, 'unknown']:
+            spl = UnivariateSpline(x, y)
+            assert_raises(ValueError, spl, xp, **dict(ext=ext))
+            assert_raises(ValueError, UnivariateSpline,
+                    **dict(x=x, y=y, ext=ext))
+
+    def test_lsq_fpchec(self):
+        xs = np.arange(100) * 1.
+        ys = np.arange(100) * 1.
+        knots = np.linspace(0, 99, 10)
+        bbox = (-1, 101)
+        assert_raises(ValueError, LSQUnivariateSpline, xs, ys, knots,
+                      bbox=bbox)
+
+    def test_derivative_and_antiderivative(self):
+        # Thin wrappers to splder/splantider, so light smoke test only.
+        x = np.linspace(0, 1, 70)**3
+        y = np.cos(x)
+
+        spl = UnivariateSpline(x, y, s=0)
+        spl2 = spl.antiderivative(2).derivative(2)
+        xp_assert_close(spl(0.3), spl2(0.3))
+
+        spl2 = spl.antiderivative(1)
+        xp_assert_close(spl2(0.6) - spl2(0.2),
+                        spl.integral(0.2, 0.6))
+
+    def test_derivative_extrapolation(self):
+        # Regression test for gh-10195: for a const-extrapolation spline
+        # its derivative evaluates to zero for extrapolation
+        x_values = [1, 2, 4, 6, 8.5]
+        y_values = [0.5, 0.8, 1.3, 2.5, 5]
+        f = UnivariateSpline(x_values, y_values, ext='const', k=3)
+
+        x = [-1, 0, -0.5, 9, 9.5, 10]
+        xp_assert_close(f.derivative()(x), np.zeros_like(x), atol=1e-15)
+
+    def test_integral_out_of_bounds(self):
+        # Regression test for gh-7906: .integral(a, b) is wrong if both
+        # a and b are out-of-bounds
+        x = np.linspace(0., 1., 7)
+        for ext in range(4):
+            f = UnivariateSpline(x, x, s=0, ext=ext)
+            for (a, b) in [(1, 1), (1, 5), (2, 5),
+                           (0, 0), (-2, 0), (-2, -1)]:
+                assert abs(f.integral(a, b)) < 1e-15
+
+    def test_nan(self):
+        # bail out early if the input data contains nans
+        x = np.arange(10, dtype=float)
+        y = x**3
+        w = np.ones_like(x)
+        # also test LSQUnivariateSpline [which needs explicit knots]
+        spl = UnivariateSpline(x, y, check_finite=True)
+        t = spl.get_knots()[3:4]  # interior knots w/ default k=3
+        y_end = y[-1]
+        for z in [np.nan, np.inf, -np.inf]:
+            y[-1] = z
+            assert_raises(ValueError, UnivariateSpline,
+                    **dict(x=x, y=y, check_finite=True))
+            assert_raises(ValueError, InterpolatedUnivariateSpline,
+                    **dict(x=x, y=y, check_finite=True))
+            assert_raises(ValueError, LSQUnivariateSpline,
+                    **dict(x=x, y=y, t=t, check_finite=True))
+            y[-1] = y_end  # check valid y but invalid w
+            w[-1] = z
+            assert_raises(ValueError, UnivariateSpline,
+                    **dict(x=x, y=y, w=w, check_finite=True))
+            assert_raises(ValueError, InterpolatedUnivariateSpline,
+                    **dict(x=x, y=y, w=w, check_finite=True))
+            assert_raises(ValueError, LSQUnivariateSpline,
+                    **dict(x=x, y=y, t=t, w=w, check_finite=True))
+
+    def test_strictly_increasing_x(self):
+        # Test the x is required to be strictly increasing for
+        # UnivariateSpline if s=0 and for InterpolatedUnivariateSpline,
+        # but merely increasing for UnivariateSpline if s>0
+        # and for LSQUnivariateSpline; see gh-8535
+        xx = np.arange(10, dtype=float)
+        yy = xx**3
+        x = np.arange(10, dtype=float)
+        x[1] = x[0]
+        y = x**3
+        w = np.ones_like(x)
+        # also test LSQUnivariateSpline [which needs explicit knots]
+        spl = UnivariateSpline(xx, yy, check_finite=True)
+        t = spl.get_knots()[3:4]  # interior knots w/ default k=3
+        UnivariateSpline(x=x, y=y, w=w, s=1, check_finite=True)
+        LSQUnivariateSpline(x=x, y=y, t=t, w=w, check_finite=True)
+        assert_raises(ValueError, UnivariateSpline,
+                **dict(x=x, y=y, s=0, check_finite=True))
+        assert_raises(ValueError, InterpolatedUnivariateSpline,
+                **dict(x=x, y=y, check_finite=True))
+
+    def test_increasing_x(self):
+        # Test that x is required to be increasing, see gh-8535
+        xx = np.arange(10, dtype=float)
+        yy = xx**3
+        x = np.arange(10, dtype=float)
+        x[1] = x[0] - 1.0
+        y = x**3
+        w = np.ones_like(x)
+        # also test LSQUnivariateSpline [which needs explicit knots]
+        spl = UnivariateSpline(xx, yy, check_finite=True)
+        t = spl.get_knots()[3:4]  # interior knots w/ default k=3
+        assert_raises(ValueError, UnivariateSpline,
+                **dict(x=x, y=y, check_finite=True))
+        assert_raises(ValueError, InterpolatedUnivariateSpline,
+                **dict(x=x, y=y, check_finite=True))
+        assert_raises(ValueError, LSQUnivariateSpline,
+                **dict(x=x, y=y, t=t, w=w, check_finite=True))
+
+    def test_invalid_input_for_univariate_spline(self):
+
+        with assert_raises(ValueError) as info:
+            x_values = [1, 2, 4, 6, 8.5]
+            y_values = [0.5, 0.8, 1.3, 2.5]
+            UnivariateSpline(x_values, y_values)
+        assert "x and y should have a same length" in str(info.value)
+
+        with assert_raises(ValueError) as info:
+            x_values = [1, 2, 4, 6, 8.5]
+            y_values = [0.5, 0.8, 1.3, 2.5, 2.8]
+            w_values = [-1.0, 1.0, 1.0, 1.0]
+            UnivariateSpline(x_values, y_values, w=w_values)
+        assert "x, y, and w should have a same length" in str(info.value)
+
+        with assert_raises(ValueError) as info:
+            bbox = (-1)
+            UnivariateSpline(x_values, y_values, bbox=bbox)
+        assert "bbox shape should be (2,)" in str(info.value)
+
+        with assert_raises(ValueError) as info:
+            UnivariateSpline(x_values, y_values, k=6)
+        assert "k should be 1 <= k <= 5" in str(info.value)
+
+        with assert_raises(ValueError) as info:
+            UnivariateSpline(x_values, y_values, s=-1.0)
+        assert "s should be s >= 0.0" in str(info.value)
+
+    def test_invalid_input_for_interpolated_univariate_spline(self):
+
+        with assert_raises(ValueError) as info:
+            x_values = [1, 2, 4, 6, 8.5]
+            y_values = [0.5, 0.8, 1.3, 2.5]
+            InterpolatedUnivariateSpline(x_values, y_values)
+        assert "x and y should have a same length" in str(info.value)
+
+        with assert_raises(ValueError) as info:
+            x_values = [1, 2, 4, 6, 8.5]
+            y_values = [0.5, 0.8, 1.3, 2.5, 2.8]
+            w_values = [-1.0, 1.0, 1.0, 1.0]
+            InterpolatedUnivariateSpline(x_values, y_values, w=w_values)
+        assert "x, y, and w should have a same length" in str(info.value)
+
+        with assert_raises(ValueError) as info:
+            bbox = (-1)
+            InterpolatedUnivariateSpline(x_values, y_values, bbox=bbox)
+        assert "bbox shape should be (2,)" in str(info.value)
+
+        with assert_raises(ValueError) as info:
+            InterpolatedUnivariateSpline(x_values, y_values, k=6)
+        assert "k should be 1 <= k <= 5" in str(info.value)
+
+    def test_invalid_input_for_lsq_univariate_spline(self):
+
+        x_values = [1, 2, 4, 6, 8.5]
+        y_values = [0.5, 0.8, 1.3, 2.5, 2.8]
+        spl = UnivariateSpline(x_values, y_values, check_finite=True)
+        t_values = spl.get_knots()[3:4]  # interior knots w/ default k=3
+
+        with assert_raises(ValueError) as info:
+            x_values = [1, 2, 4, 6, 8.5]
+            y_values = [0.5, 0.8, 1.3, 2.5]
+            LSQUnivariateSpline(x_values, y_values, t_values)
+        assert "x and y should have a same length" in str(info.value)
+
+        with assert_raises(ValueError) as info:
+            x_values = [1, 2, 4, 6, 8.5]
+            y_values = [0.5, 0.8, 1.3, 2.5, 2.8]
+            w_values = [1.0, 1.0, 1.0, 1.0]
+            LSQUnivariateSpline(x_values, y_values, t_values, w=w_values)
+        assert "x, y, and w should have a same length" in str(info.value)
+
+        message = "Interior knots t must satisfy Schoenberg-Whitney conditions"
+        with assert_raises(ValueError, match=message) as info:
+            bbox = (100, -100)
+            LSQUnivariateSpline(x_values, y_values, t_values, bbox=bbox)
+
+        with assert_raises(ValueError) as info:
+            bbox = (-1)
+            LSQUnivariateSpline(x_values, y_values, t_values, bbox=bbox)
+        assert "bbox shape should be (2,)" in str(info.value)
+
+        with assert_raises(ValueError) as info:
+            LSQUnivariateSpline(x_values, y_values, t_values, k=6)
+        assert "k should be 1 <= k <= 5" in str(info.value)
+
+    def test_array_like_input(self):
+        x_values = np.array([1, 2, 4, 6, 8.5])
+        y_values = np.array([0.5, 0.8, 1.3, 2.5, 2.8])
+        w_values = np.array([1.0, 1.0, 1.0, 1.0, 1.0])
+        bbox = np.array([-100, 100])
+        # np.array input
+        spl1 = UnivariateSpline(x=x_values, y=y_values, w=w_values,
+                                bbox=bbox)
+        # list input
+        spl2 = UnivariateSpline(x=x_values.tolist(), y=y_values.tolist(),
+                                w=w_values.tolist(), bbox=bbox.tolist())
+
+        xp_assert_close(spl1([0.1, 0.5, 0.9, 0.99]),
+                        spl2([0.1, 0.5, 0.9, 0.99]))
+
+    def test_fpknot_oob_crash(self):
+        # https://github.com/scipy/scipy/issues/3691
+        x = range(109)
+        y = [0., 0., 0., 0., 0., 10.9, 0., 11., 0.,
+             0., 0., 10.9, 0., 0., 0., 0., 0., 0.,
+             10.9, 0., 0., 0., 11., 0., 0., 0., 10.9,
+             0., 0., 0., 10.5, 0., 0., 0., 10.7, 0.,
+             0., 0., 11., 0., 0., 0., 0., 0., 0.,
+             10.9, 0., 0., 10.7, 0., 0., 0., 10.6, 0.,
+             0., 0., 10.5, 0., 0., 10.7, 0., 0., 10.5,
+             0., 0., 11.5, 0., 0., 0., 10.7, 0., 0.,
+             10.7, 0., 0., 10.9, 0., 0., 10.8, 0., 0.,
+             0., 10.7, 0., 0., 10.6, 0., 0., 0., 10.4,
+             0., 0., 10.6, 0., 0., 10.5, 0., 0., 0.,
+             10.7, 0., 0., 0., 10.4, 0., 0., 0., 10.8, 0.]
+        msg = r"does not satisfy the condition abs\(fp-s\)/s < tol"
+        with pytest.warns(UserWarning, match=msg):
+            UnivariateSpline(x, y, k=1)
+
+    def test_concurrency(self):
+        # Check that no segfaults appear with concurrent access to
+        # UnivariateSpline
+        xx = np.arange(100, dtype=float)
+        yy = xx**3
+        x = np.arange(100, dtype=float)
+        x[1] = x[0]
+        spl = UnivariateSpline(xx, yy, check_finite=True)
+
+        def worker_fn(_, interp, x):
+            interp(x)
+
+        _run_concurrent_barrier(10, worker_fn, spl, x)
+
+    def test_curfit_2d_array_handling(self):
+        """Test that 2D arrays are flattened correctly in Fortran order."""
+
+        # Create 1D data
+        x_1d = np.array([0., 1., 2., 3., 4., 5.])
+        y_1d = np.array([0., 1., 4., 9., 16., 25.])  # y = x^2
+
+        # Column vector (shape (n, 1)); should work and give same result as 1D
+        x_col = x_1d.reshape(-1, 1)
+        y_col = y_1d.reshape(-1, 1)
+
+        spl_1d = InterpolatedUnivariateSpline(x_1d, y_1d)
+        spl_col = InterpolatedUnivariateSpline(x_col, y_col)
+
+        test_points = np.array([0.5, 1.5, 2.5, 3.5])
+        np.testing.assert_allclose(spl_1d(test_points), spl_col(test_points))
+
+        # Row vector (shape (1, n)) - should work and give same result as 1D
+        x_row = x_1d.reshape(1, -1)
+        y_row = y_1d.reshape(1, -1)
+
+        spl_row = InterpolatedUnivariateSpline(x_row, y_row)
+        np.testing.assert_allclose(spl_1d(test_points), spl_row(test_points))
+
+        # Verify F-order flattening for truly 2D case. Not a likely input but
+        # for general testing purposes.
+        #
+        # Create a 2x3 array where F-order and C-order give different results
+        # F-order: [1,4,2,5,3,6], C-order: [1,2,3,4,5,6]
+        x_2d = np.array([[1., 2., 3.],
+                        [4., 5., 6.]])
+        y_2d = np.array([[1., 4., 9.],
+                        [16., 25., 36.]])
+
+        # With F-order flattening: x = [1,4,2,5,3,6], y = [1,16,4,25,9,36]
+        # This would NOT be sorted, so the spline should fail or give different results
+        # than C-order which would give sorted x = [1,2,3,4,5,6]
+
+        # The F-order flattened x is not monotonic, so FITPACK returns ier=10
+        # and emits a UserWarning about erronous input.
+        with pytest.warns(UserWarning, match="x\\[0\\]10.
+        x = np.linspace(-2, 2, 80)
+        y = np.linspace(-2, 2, 80)
+        z = x + y
+        xi = np.linspace(-1, 1, 100)
+        yi = np.linspace(-2, 2, 100)
+        tck = bisplrep(x, y, z)
+        res1 = bisplev(xi, yi, tck)
+        interp_ = SmoothBivariateSpline(x, y, z)
+        res2 = interp_(xi, yi)
+        assert_almost_equal(res1, res2)
+
+    def test_invalid_input(self):
+
+        with assert_raises(ValueError) as info:
+            x = np.linspace(1.0, 10.0)
+            y = np.linspace(1.0, 10.0)
+            z = np.linspace(1.0, 10.0, num=10)
+            SmoothBivariateSpline(x, y, z)
+        assert "x, y, and z should have a same length" in str(info.value)
+
+        with assert_raises(ValueError) as info:
+            x = np.linspace(1.0, 10.0)
+            y = np.linspace(1.0, 10.0)
+            z = np.linspace(1.0, 10.0)
+            w = np.linspace(1.0, 10.0, num=20)
+            SmoothBivariateSpline(x, y, z, w=w)
+        assert "x, y, z, and w should have a same length" in str(info.value)
+
+        with assert_raises(ValueError) as info:
+            w = np.linspace(-1.0, 10.0)
+            SmoothBivariateSpline(x, y, z, w=w)
+        assert "w should be positive" in str(info.value)
+
+        with assert_raises(ValueError) as info:
+            bbox = (-100, 100, -100)
+            SmoothBivariateSpline(x, y, z, bbox=bbox)
+        assert "bbox shape should be (4,)" in str(info.value)
+
+        with assert_raises(ValueError) as info:
+            SmoothBivariateSpline(x, y, z, kx=10, ky=10)
+        assert "The length of x, y and z should be at least (kx+1) * (ky+1)" in\
+               str(info.value)
+
+        with assert_raises(ValueError) as info:
+            SmoothBivariateSpline(x, y, z, s=-1.0)
+        assert "s should be s >= 0.0" in str(info.value)
+
+        with assert_raises(ValueError) as exc_info:
+            SmoothBivariateSpline(x, y, z, eps=0.0)
+        assert "eps should be between (0, 1)" in str(exc_info.value)
+
+        with assert_raises(ValueError) as exc_info:
+            SmoothBivariateSpline(x, y, z, eps=1.0)
+        assert "eps should be between (0, 1)" in str(exc_info.value)
+
+    def test_array_like_input(self):
+        x = np.array([1, 1, 1, 2, 2, 2, 3, 3, 3])
+        y = np.array([1, 2, 3, 1, 2, 3, 1, 2, 3])
+        z = np.array([3, 3, 3, 3, 3, 3, 3, 3, 3])
+        w = np.array([1, 1, 1, 1, 1, 1, 1, 1, 1])
+        bbox = np.array([1.0, 3.0, 1.0, 3.0])
+        # np.array input
+        spl1 = SmoothBivariateSpline(x, y, z, w=w, bbox=bbox, kx=1, ky=1)
+        # list input
+        spl2 = SmoothBivariateSpline(x.tolist(), y.tolist(), z.tolist(),
+                                     bbox=bbox.tolist(), w=w.tolist(),
+                                     kx=1, ky=1)
+        xp_assert_close(spl1(0.1, 0.5), spl2(0.1, 0.5))
+
+    def test_0d(self):
+        # regression test for https://github.com/scipy/scipy/issues/25471
+        # result shapes checked with SciPy 1.16.3 (pre FITPACK C port)
+        rng = np.random.default_rng(0)
+        xs, ys = rng.random(30), rng.random(30)
+        zs = xs * ys
+        s = SmoothBivariateSpline(xs, ys, zs)(0.4, 0.5, grid=False)
+        assert s.ndim == 0
+
+        s = SmoothBivariateSpline(xs, ys, zs)([0.4], 0.5, grid=False)
+        assert s.ndim == 1
+
+
+def _contiguous(a):
+    """C-contiguous reference layout."""
+    return np.ascontiguousarray(a, dtype=np.float64)
+
+
+def _strided(a):
+    """Return a non-contiguous view of `a`, interleaved with NaN. A read that
+    wrongly assumes C-contiguity picks up a NaN; a correct strided read does
+    not."""
+    a = np.asarray(a, dtype=np.float64)
+    v = np.stack([a, np.full_like(a, np.nan)], axis=-1)[..., 0]
+    assert not v.flags["C_CONTIGUOUS"]
+    return v
+
+
+# Builders for the non-contiguous-input sweep below. Each applies `prep` to
+# every array input and returns the fit evaluated at fixed points (flattened).
+# Data is regenerated identically per call (fixed seed) so the only difference
+# between two calls is `prep`.
+def _scattered_data():
+    rng = np.random.default_rng(0)
+    src = rng.uniform(-5, 5, (400, 2))
+    x, y = src[:, 0].copy(), src[:, 1].copy()
+    return x, y, x ** 2 + y
+
+
+def _sphere_scattered_data():
+    rng = np.random.default_rng(0)
+    theta = rng.uniform(0.1, np.pi - 0.1, 200)
+    phi = rng.uniform(0.1, 2 * np.pi - 0.1, 200)
+    return theta, phi, np.sin(theta) * np.cos(phi)
+
+
+def _fit_smooth_bivariate(prep):
+    x, y, z = _scattered_data()
+    return SmoothBivariateSpline(prep(x), prep(y), prep(z), kx=2, ky=2).ev(x, y)
+
+
+def _fit_lsq_bivariate(prep):
+    x, y, z = _scattered_data()
+    t = np.linspace(-4, 4, 3)
+    return LSQBivariateSpline(prep(x), prep(y), prep(z), prep(t), prep(t),
+                              kx=2, ky=2).ev(x, y)
+
+
+def _fit_rect_bivariate(prep):
+    gx, gy = np.linspace(0, 1, 12), np.linspace(0, 1, 14)
+    gz = np.sin(gx[:, None]) * np.cos(gy[None, :])
+    spl = RectBivariateSpline(prep(gx), prep(gy), prep(gz))
+    return spl(np.linspace(0.1, 0.9, 5), np.linspace(0.1, 0.9, 5)).ravel()
+
+
+def _fit_smooth_sphere(prep):
+    theta, phi, r = _sphere_scattered_data()
+    spl = SmoothSphereBivariateSpline(prep(theta), prep(phi), prep(r), s=2.0)
+    return spl.ev(theta, phi)
+
+
+def _fit_lsq_sphere(prep):
+    theta, phi, r = _sphere_scattered_data()
+    tt = np.linspace(0, np.pi, 5)[1:-1]
+    tp = np.linspace(0, 2 * np.pi, 5)[1:-1]
+    return LSQSphereBivariateSpline(prep(theta), prep(phi), prep(r),
+                                    prep(tt), prep(tp)).ev(theta, phi)
+
+
+def _fit_rect_sphere(prep):
+    u = np.linspace(0, np.pi, 14)[1:-1]
+    v = np.linspace(0, 2 * np.pi, 14, endpoint=False)
+    rg = np.sin(u[:, None]) * np.cos(v[None, :])
+    return RectSphereBivariateSpline(prep(u), prep(v), prep(rg))(u, v).ravel()
+
+
+@pytest.mark.parametrize("fit", [
+    pytest.param(_fit_smooth_bivariate, id="SmoothBivariateSpline"),
+    pytest.param(_fit_lsq_bivariate, id="LSQBivariateSpline"),
+    pytest.param(_fit_rect_bivariate, id="RectBivariateSpline"),
+    pytest.param(_fit_smooth_sphere, id="SmoothSphereBivariateSpline"),
+    pytest.param(_fit_lsq_sphere, id="LSQSphereBivariateSpline"),
+    pytest.param(_fit_rect_sphere, id="RectSphereBivariateSpline"),
+])
+def test_bivariate_spline_noncontiguous_input(fit):
+    # The FITPACK C bindings read x/y/z/w buffers assuming C-contiguity.
+    xp_assert_close(fit(_strided), fit(_contiguous))
+
+
+class TestLSQSphereBivariateSpline:
+    def setup_method(self):
+        # define the input data and coordinates
+        ntheta, nphi = 70, 90
+        theta = linspace(0.5/(ntheta - 1), 1 - 0.5/(ntheta - 1), ntheta) * pi
+        phi = linspace(0.5/(nphi - 1), 1 - 0.5/(nphi - 1), nphi) * 2. * pi
+        data = ones((theta.shape[0], phi.shape[0]))
+        # define knots and extract data values at the knots
+        knotst = theta[::5]
+        knotsp = phi[::5]
+        knotdata = data[::5, ::5]
+        # calculate spline coefficients
+        lats, lons = meshgrid(theta, phi)
+        lut_lsq = LSQSphereBivariateSpline(lats.ravel(), lons.ravel(),
+                                           data.T.ravel(), knotst, knotsp)
+        self.lut_lsq = lut_lsq
+        self.data = knotdata
+        self.new_lons, self.new_lats = knotsp, knotst
+
+    def test_linear_constant(self):
+        assert abs(self.lut_lsq.get_residual()) < 1e-15
+        assert_array_almost_equal(self.lut_lsq(self.new_lats, self.new_lons),
+                                  self.data)
+
+    def test_empty_input(self):
+        assert_array_almost_equal(self.lut_lsq([], []), np.zeros((0,0)))
+        assert_array_almost_equal(self.lut_lsq([], [], grid=False), np.zeros((0,)))
+
+    def test_invalid_input(self):
+        ntheta, nphi = 70, 90
+        theta = linspace(0.5 / (ntheta - 1), 1 - 0.5 / (ntheta - 1),
+                         ntheta) * pi
+        phi = linspace(0.5 / (nphi - 1), 1 - 0.5 / (nphi - 1), nphi) * 2. * pi
+        data = ones((theta.shape[0], phi.shape[0]))
+        # define knots and extract data values at the knots
+        knotst = theta[::5]
+        knotsp = phi[::5]
+
+        with assert_raises(ValueError) as exc_info:
+            invalid_theta = linspace(-0.1, 1.0, num=ntheta) * pi
+            invalid_lats, lons = meshgrid(invalid_theta, phi)
+            LSQSphereBivariateSpline(invalid_lats.ravel(), lons.ravel(),
+                                     data.T.ravel(), knotst, knotsp)
+        assert "theta should be between [0, pi]" in str(exc_info.value)
+
+        with assert_raises(ValueError) as exc_info:
+            invalid_theta = linspace(0.1, 1.1, num=ntheta) * pi
+            invalid_lats, lons = meshgrid(invalid_theta, phi)
+            LSQSphereBivariateSpline(invalid_lats.ravel(), lons.ravel(),
+                                     data.T.ravel(), knotst, knotsp)
+        assert "theta should be between [0, pi]" in str(exc_info.value)
+
+        with assert_raises(ValueError) as exc_info:
+            invalid_phi = linspace(-0.1, 1.0, num=ntheta) * 2.0 * pi
+            lats, invalid_lons = meshgrid(theta, invalid_phi)
+            LSQSphereBivariateSpline(lats.ravel(), invalid_lons.ravel(),
+                                     data.T.ravel(), knotst, knotsp)
+        assert "phi should be between [0, 2pi]" in str(exc_info.value)
+
+        with assert_raises(ValueError) as exc_info:
+            invalid_phi = linspace(0.0, 1.1, num=ntheta) * 2.0 * pi
+            lats, invalid_lons = meshgrid(theta, invalid_phi)
+            LSQSphereBivariateSpline(lats.ravel(), invalid_lons.ravel(),
+                                     data.T.ravel(), knotst, knotsp)
+        assert "phi should be between [0, 2pi]" in str(exc_info.value)
+
+        lats, lons = meshgrid(theta, phi)
+
+        with assert_raises(ValueError) as exc_info:
+            invalid_knotst = np.copy(knotst)
+            invalid_knotst[0] = -0.1
+            LSQSphereBivariateSpline(lats.ravel(), lons.ravel(),
+                                     data.T.ravel(), invalid_knotst, knotsp)
+        assert "tt should be between (0, pi)" in str(exc_info.value)
+
+        with assert_raises(ValueError) as exc_info:
+            invalid_knotst = np.copy(knotst)
+            invalid_knotst[0] = pi
+            LSQSphereBivariateSpline(lats.ravel(), lons.ravel(),
+                                     data.T.ravel(), invalid_knotst, knotsp)
+        assert "tt should be between (0, pi)" in str(exc_info.value)
+
+        with assert_raises(ValueError) as exc_info:
+            invalid_knotsp = np.copy(knotsp)
+            invalid_knotsp[0] = -0.1
+            LSQSphereBivariateSpline(lats.ravel(), lons.ravel(),
+                                     data.T.ravel(), knotst, invalid_knotsp)
+        assert "tp should be between (0, 2pi)" in str(exc_info.value)
+
+        with assert_raises(ValueError) as exc_info:
+            invalid_knotsp = np.copy(knotsp)
+            invalid_knotsp[0] = 2 * pi
+            LSQSphereBivariateSpline(lats.ravel(), lons.ravel(),
+                                     data.T.ravel(), knotst, invalid_knotsp)
+        assert "tp should be between (0, 2pi)" in str(exc_info.value)
+
+        with assert_raises(ValueError) as exc_info:
+            invalid_w = array([-1.0, 1.0, 1.5, 0.5, 1.0, 1.5, 0.5, 1.0, 1.0])
+            LSQSphereBivariateSpline(lats.ravel(), lons.ravel(), data.T.ravel(),
+                                     knotst, knotsp, w=invalid_w)
+        assert "w should be positive" in str(exc_info.value)
+
+        with assert_raises(ValueError) as exc_info:
+            LSQSphereBivariateSpline(lats.ravel(), lons.ravel(), data.T.ravel(),
+                                     knotst, knotsp, eps=0.0)
+        assert "eps should be between (0, 1)" in str(exc_info.value)
+
+        with assert_raises(ValueError) as exc_info:
+            LSQSphereBivariateSpline(lats.ravel(), lons.ravel(), data.T.ravel(),
+                                     knotst, knotsp, eps=1.0)
+        assert "eps should be between (0, 1)" in str(exc_info.value)
+
+    def test_array_like_input(self):
+        ntheta, nphi = 70, 90
+        theta = linspace(0.5 / (ntheta - 1), 1 - 0.5 / (ntheta - 1),
+                         ntheta) * pi
+        phi = linspace(0.5 / (nphi - 1), 1 - 0.5 / (nphi - 1),
+                       nphi) * 2. * pi
+        lats, lons = meshgrid(theta, phi)
+        data = ones((theta.shape[0], phi.shape[0]))
+        # define knots and extract data values at the knots
+        knotst = theta[::5]
+        knotsp = phi[::5]
+        w = ones(lats.ravel().shape[0])
+
+        # np.array input
+        spl1 = LSQSphereBivariateSpline(lats.ravel(), lons.ravel(),
+                                        data.T.ravel(), knotst, knotsp, w=w)
+        # list input
+        spl2 = LSQSphereBivariateSpline(lats.ravel().tolist(),
+                                        lons.ravel().tolist(),
+                                        data.T.ravel().tolist(),
+                                        knotst.tolist(),
+                                        knotsp.tolist(), w=w.tolist())
+        assert_array_almost_equal(spl1(1.0, 1.0), spl2(1.0, 1.0))
+
+
+class TestSmoothSphereBivariateSpline:
+    def setup_method(self):
+        theta = array([.25*pi, .25*pi, .25*pi, .5*pi, .5*pi, .5*pi, .75*pi,
+                       .75*pi, .75*pi])
+        phi = array([.5 * pi, pi, 1.5 * pi, .5 * pi, pi, 1.5 * pi, .5 * pi, pi,
+                     1.5 * pi])
+        r = array([3, 3, 3, 3, 3, 3, 3, 3, 3])
+        self.lut = SmoothSphereBivariateSpline(theta, phi, r, s=1E10)
+
+    def test_linear_constant(self):
+        assert abs(self.lut.get_residual()) < 1e-15
+        assert_array_almost_equal(self.lut([1, 1.5, 2],[1, 1.5]),
+                                  [[3, 3], [3, 3], [3, 3]])
+
+    def test_empty_input(self):
+        assert_array_almost_equal(self.lut([], []), np.zeros((0,0)))
+        assert_array_almost_equal(self.lut([], [], grid=False), np.zeros((0,)))
+
+    def test_invalid_input(self):
+        theta = array([.25 * pi, .25 * pi, .25 * pi, .5 * pi, .5 * pi, .5 * pi,
+                       .75 * pi, .75 * pi, .75 * pi])
+        phi = array([.5 * pi, pi, 1.5 * pi, .5 * pi, pi, 1.5 * pi, .5 * pi, pi,
+                     1.5 * pi])
+        r = array([3, 3, 3, 3, 3, 3, 3, 3, 3])
+
+        with assert_raises(ValueError) as exc_info:
+            invalid_theta = array([-0.1 * pi, .25 * pi, .25 * pi, .5 * pi,
+                                   .5 * pi, .5 * pi, .75 * pi, .75 * pi,
+                                   .75 * pi])
+            SmoothSphereBivariateSpline(invalid_theta, phi, r, s=1E10)
+        assert "theta should be between [0, pi]" in str(exc_info.value)
+
+        with assert_raises(ValueError) as exc_info:
+            invalid_theta = array([.25 * pi, .25 * pi, .25 * pi, .5 * pi,
+                                   .5 * pi, .5 * pi, .75 * pi, .75 * pi,
+                                   1.1 * pi])
+            SmoothSphereBivariateSpline(invalid_theta, phi, r, s=1E10)
+        assert "theta should be between [0, pi]" in str(exc_info.value)
+
+        with assert_raises(ValueError) as exc_info:
+            invalid_phi = array([-.1 * pi, pi, 1.5 * pi, .5 * pi, pi, 1.5 * pi,
+                                 .5 * pi, pi, 1.5 * pi])
+            SmoothSphereBivariateSpline(theta, invalid_phi, r, s=1E10)
+        assert "phi should be between [0, 2pi]" in str(exc_info.value)
+
+        with assert_raises(ValueError) as exc_info:
+            invalid_phi = array([1.0 * pi, pi, 1.5 * pi, .5 * pi, pi, 1.5 * pi,
+                                 .5 * pi, pi, 2.1 * pi])
+            SmoothSphereBivariateSpline(theta, invalid_phi, r, s=1E10)
+        assert "phi should be between [0, 2pi]" in str(exc_info.value)
+
+        with assert_raises(ValueError) as exc_info:
+            invalid_w = array([-1.0, 1.0, 1.5, 0.5, 1.0, 1.5, 0.5, 1.0, 1.0])
+            SmoothSphereBivariateSpline(theta, phi, r, w=invalid_w, s=1E10)
+        assert "w should be positive" in str(exc_info.value)
+
+        with assert_raises(ValueError) as exc_info:
+            SmoothSphereBivariateSpline(theta, phi, r, s=-1.0)
+        assert "s should be positive" in str(exc_info.value)
+
+        with assert_raises(ValueError) as exc_info:
+            SmoothSphereBivariateSpline(theta, phi, r, eps=-1.0)
+        assert "eps should be between (0, 1)" in str(exc_info.value)
+
+        with assert_raises(ValueError) as exc_info:
+            SmoothSphereBivariateSpline(theta, phi, r, eps=1.0)
+        assert "eps should be between (0, 1)" in str(exc_info.value)
+
+    def test_array_like_input(self):
+        theta = np.array([.25 * pi, .25 * pi, .25 * pi, .5 * pi, .5 * pi,
+                          .5 * pi, .75 * pi, .75 * pi, .75 * pi])
+        phi = np.array([.5 * pi, pi, 1.5 * pi, .5 * pi, pi, 1.5 * pi, .5 * pi,
+                        pi, 1.5 * pi])
+        r = np.array([3, 3, 3, 3, 3, 3, 3, 3, 3])
+        w = np.array([1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0])
+
+        # np.array input
+        spl1 = SmoothSphereBivariateSpline(theta, phi, r, w=w, s=1E10)
+
+        # list input
+        spl2 = SmoothSphereBivariateSpline(theta.tolist(), phi.tolist(),
+                                           r.tolist(), w=w.tolist(), s=1E10)
+        assert_array_almost_equal(spl1(1.0, 1.0), spl2(1.0, 1.0))
+
+
+class TestRectBivariateSpline:
+    @pytest.mark.parametrize("k", [3, 4])
+    def test_defaults(self, k):
+        x = array([1, 2, 3, 4, 5])
+        y = array([1, 2, 3, 4, 5])
+        z = array([[1, 2, 1, 2, 1],
+                   [1, 2, 1, 2, 1],
+                   [1, 2, 3, 2, 1],
+                   [1, 2, 2, 2, 1],
+                   [1, 2, 1, 2, 1]])
+
+        lut = RectBivariateSpline(x, y, z, kx=k, ky=k)
+        assert_array_almost_equal(lut(x, y), z)
+
+        lut_custom = _regrid(x, y, z, kx=k, ky=k)
+        xp_assert_close(
+            _ndbspline_call_like_bivariate(lut_custom, x, y), z.astype(np.float64))
+
+    @pytest.mark.parametrize("k", [3, 4])
+    def test_interpolated_offgrid_points(self, k):
+        # Setup
+        x = np.linspace(0, 4, 5)
+        y = np.linspace(0, 4, 5)
+        z = np.sin(x[:, None]) * np.cos(y[None, :])
+
+        xi = np.linspace(0, 4, 50)  # much finer grid
+        yi = np.linspace(0, 4, 50)
+
+        ref = RectBivariateSpline(x, y, z, kx=k, ky=k)
+        ref_vals = ref(xi, yi)
+
+        custom = _regrid(x, y, z, kx=k, ky=k)
+        custom_vals = _ndbspline_call_like_bivariate(custom, xi, yi)
+        # Compare interpolated values
+        xp_assert_close(custom_vals, ref_vals,
+                        rtol=0, atol=1.5*10**(-6))
+
+    @pytest.mark.parametrize("k", [3, 4])
+    def test_midpoints(self, k):
+        # Midpoint interpolation
+        x = np.arange(1, k + 2)
+        y = np.arange(1, k + 2)
+        z = x[:, None] + y[None, :]  # simple known function
+
+        xi = (x[:-1] + x[1:]) / 2
+        yi = (y[:-1] + y[1:]) / 2
+
+        ref = RectBivariateSpline(x, y, z, kx=k, ky=k)
+        custom = _regrid(x, y, z, kx=k, ky=k)
+
+        ref_vals = ref(xi, yi)
+        custom_vals = _ndbspline_call_like_bivariate(custom, xi, yi)
+
+        xp_assert_close(custom_vals, ref_vals,
+                        rtol=0, atol=1.5*10**(-6))
+
+    @pytest.mark.parametrize("s_val", [0.1, 1.0, 10.0, 100.0])
+    @pytest.mark.parametrize("k", [3, 4])
+    def test_custom_matches_reference(self, s_val, k):
+        x = np.linspace(0, 4, 20)
+        y = np.linspace(0, 4, 20)
+        X, Y = np.meshgrid(x, y, indexing="ij")
+        z = X + Y
+
+        x_mid = (x[:-1] + x[1:]) / 2
+        y_mid = (y[:-1] + y[1:]) / 2
+        xi_dense = np.linspace(0, 4, 50)
+        yi_dense = np.linspace(0, 4, 50)
+
+        query_sets = [
+            ("original grid", x, y),
+            ("midpoints", x_mid, y_mid),
+            ("dense grid", xi_dense, yi_dense),
+        ]
+
+        ref = RectBivariateSpline(x, y, z, s=s_val, kx=k, ky=k)
+        custom = _regrid(x, y, z, s=s_val, kx=k, ky=k)
+
+        for _, xi, yi in query_sets:
+            ref_vals = ref(xi, yi)
+            custom_vals = _ndbspline_call_like_bivariate(custom, xi, yi)
+
+            xp_assert_close(custom_vals, ref_vals,
+                            rtol=2e-2, atol=2e-2)
+
+    @pytest.mark.parametrize("k", [3, 4])
+    def test_evaluate(self, k):
+        x = array([1,2,3,4,5])
+        y = array([1,2,3,4,5])
+        z = array([[1,2,1,2,1],[1,2,1,2,1],[1,2,3,2,1],[1,2,2,2,1],[1,2,1,2,1]])
+        lut = RectBivariateSpline(x,y,z,kx=k,ky=k)
+        lut_custom = _regrid(x, y, z, kx=k, ky=k)
+
+        xi = [1, 2.3, 5.3, 0.5, 3.3, 1.2, 3]
+        yi = [1, 3.3, 1.2, 4.0, 5.0, 1.0, 3]
+        zi = lut.ev(xi, yi)
+        zi2 = array([lut(xp, yp)[0,0] for xp, yp in zip(xi, yi)])
+
+        assert_almost_equal(zi, zi2)
+
+        zi_custom = _ndbspline_call_like_bivariate(lut_custom, xi, yi, grid=False)
+        zi2_custom = array([_ndbspline_call_like_bivariate(lut_custom, xp, yp)[0, 0]
+                            for xp, yp in zip(xi, yi)])
+        xp_assert_close(zi_custom, zi2_custom,
+                        rtol=0, atol=1.5*10**(-6))
+
+    def test_derivatives_grid(self):
+        x = array([1,2,3,4,5])
+        y = array([1,2,3,4,5])
+        z = array([[1,2,1,2,1],[1,2,1,2,1],[1,2,3,2,1],[1,2,2,2,1],[1,2,1,2,1]])
+        dx = array([[0,0,-20,0,0],[0,0,13,0,0],[0,0,4,0,0],
+            [0,0,-11,0,0],[0,0,4,0,0]])/6.
+        dy = array([[4,-1,0,1,-4],[4,-1,0,1,-4],[0,1.5,0,-1.5,0],
+            [2,.25,0,-.25,-2],[4,-1,0,1,-4]])
+        dxdy = array([[40,-25,0,25,-40],[-26,16.25,0,-16.25,26],
+            [-8,5,0,-5,8],[22,-13.75,0,13.75,-22],[-8,5,0,-5,8]])/6.
+
+        lut = RectBivariateSpline(x,y,z)
+        lut_custom = _regrid(x,y,z)
+
+        assert_array_almost_equal(lut(x,y,dx=1),dx)
+        assert_array_almost_equal(lut(x,y,dy=1),dy)
+        assert_array_almost_equal(lut(x,y,dx=1,dy=1),dxdy)
+        xp_assert_close(
+            _ndbspline_call_like_bivariate(lut_custom, x,y,dx=1),dx,
+            rtol=0, atol=1.5*10**(-6))
+        xp_assert_close(
+            _ndbspline_call_like_bivariate(lut_custom, x,y,dy=1),dy,
+            rtol=0, atol=1.5*10**(-6))
+        xp_assert_close(
+            _ndbspline_call_like_bivariate(lut_custom, x,y,dx=1,dy=1),dxdy,
+            rtol=0, atol=1.5*10**(-6))
+
+    def test_derivatives(self):
+        x = array([1,2,3,4,5])
+        y = array([1,2,3,4,5])
+        z = array([[1,2,1,2,1],[1,2,1,2,1],[1,2,3,2,1],[1,2,2,2,1],[1,2,1,2,1]])
+        dx = array([0,0,2./3,0,0])
+        dy = array([4,-1,0,-.25,-4])
+        dxdy = array([160,65,0,55,32])/24.
+        lut = RectBivariateSpline(x,y,z)
+        assert_array_almost_equal(lut(x,y,dx=1,grid=False),dx)
+        assert_array_almost_equal(lut(x,y,dy=1,grid=False),dy)
+        assert_array_almost_equal(lut(x,y,dx=1,dy=1,grid=False),dxdy)
+
+        lut_custom = _regrid(x,y,z)
+        xp_assert_close(
+            _ndbspline_call_like_bivariate(lut_custom,x,y,dx=1,grid=False),
+            dx,rtol=0, atol=1.5*10**(-6)
+        )
+        xp_assert_close(
+            _ndbspline_call_like_bivariate(lut_custom,x,y,dy=1,grid=False),
+            dy,rtol=0, atol=1.5*10**(-6)
+        )
+        xp_assert_close(
+            _ndbspline_call_like_bivariate(lut_custom,x,y,dx=1,dy=1,grid=False),
+            dxdy,rtol=0, atol=1.5*10**(-6)
+        )
+
+    def make_pair_grid(self, x, y):
+        """
+        Create an array of (xi, yi) pairs for all xi in x and yi in y,
+        and reshape it to the desired shape.
+
+        Parameters
+        ----------
+        x : array_like
+            1D array of x-values.
+        y : array_like
+            1D array of y-values.
+        dest_shape : tuple
+            Desired output shape.
+
+        Returns
+        -------
+        np.ndarray
+            Reshaped array of (x, y) pairs.
+        """
+        return np.array([[xi, yi] for xi in x for yi in y])
+
+    def test_partial_derivative_method_grid(self):
+        x = array([1, 2, 3, 4, 5])
+        y = array([1, 2, 3, 4, 5])
+        z = array([[1, 2, 1, 2, 1],
+                   [1, 2, 1, 2, 1],
+                   [1, 2, 3, 2, 1],
+                   [1, 2, 2, 2, 1],
+                   [1, 2, 1, 2, 1]])
+        dx = array([[0, 0, -20, 0, 0],
+                    [0, 0, 13, 0, 0],
+                    [0, 0, 4, 0, 0],
+                    [0, 0, -11, 0, 0],
+                    [0, 0, 4, 0, 0]]) / 6.
+        dy = array([[4, -1, 0, 1, -4],
+                    [4, -1, 0, 1, -4],
+                    [0, 1.5, 0, -1.5, 0],
+                    [2, .25, 0, -.25, -2],
+                    [4, -1, 0, 1, -4]])
+        dxdy = array([[40, -25, 0, 25, -40],
+                      [-26, 16.25, 0, -16.25, 26],
+                      [-8, 5, 0, -5, 8],
+                      [22, -13.75, 0, 13.75, -22],
+                      [-8, 5, 0, -5, 8]]) / 6.
+        lut = RectBivariateSpline(x, y, z)
+        lut_ndbspline = convert_to_ndbspline(lut)
+        for orders, expected in [([1, 0], dx), ([0, 1], dy), ([1, 1], dxdy)]:
+            actual_rect = lut.partial_derivative(*orders)(x, y)
+            actual_ndb = lut_ndbspline.derivative(orders)(
+                self.make_pair_grid(x, y)
+            ).reshape(expected.shape)
+
+            assert_array_almost_equal(actual_rect, expected)
+            assert_array_almost_equal(actual_ndb, expected)
+
+        lut_custom = _regrid(x, y, z)
+        xp_assert_close(
+            _ndbspline_call_like_bivariate(lut_custom.derivative([1, 0]), x, y),
+            dx,rtol=0, atol=1.5*10**(-6)
+        )
+        xp_assert_close(
+            _ndbspline_call_like_bivariate(lut_custom.derivative([0, 1]), x, y),
+            dy,rtol=0, atol=1.5*10**(-6)
+        )
+        xp_assert_close(
+            _ndbspline_call_like_bivariate(lut_custom.derivative([1, 1]), x, y),
+            dxdy,rtol=0, atol=1.5*10**(-6)
+        )
+
+    def test_partial_derivative_method(self):
+        x = array([1, 2, 3, 4, 5])
+        y = array([1, 2, 3, 4, 5])
+        z = array([[1, 2, 1, 2, 1],
+                   [1, 2, 1, 2, 1],
+                   [1, 2, 3, 2, 1],
+                   [1, 2, 2, 2, 1],
+                   [1, 2, 1, 2, 1]])
+        expected = {
+            (1, 0): array([0, 0, 2./3, 0, 0]), # dx
+            (0, 1): array([4, -1, 0, -.25, -4]), # dy
+            (1, 1): array([160, 65, 0, 55, 32]) / 24. # dxdy
+        }
+
+        lut = RectBivariateSpline(x, y, z)
+        lut_ndbspline = convert_to_ndbspline(lut)
+        lut_custom = _regrid(x, y, z)
+
+        points = self.make_pair_grid(x, y)  # shape: (25, 2)
+
+        # Evaluate only the diagonal points: (x[i], y[i])
+        diag_idx = np.arange(len(x))
+        diag_points = points[diag_idx * len(y) + diag_idx]
+
+        for orders, expected_vals in expected.items():
+            dx, dy = orders
+            # RectBivariateSpline result
+            actual_rbs = lut.partial_derivative(dx, dy)(x, y, grid=False)
+            assert_array_almost_equal(actual_rbs, expected_vals)
+
+            # NdBSpline result
+            actual_ndb = lut_ndbspline.derivative([dx, dy])(diag_points)
+            assert_array_almost_equal(actual_ndb, expected_vals)
+
+            # regrid result
+            actual_rp = _ndbspline_call_like_bivariate(lut_custom.derivative([dx, dy]),
+                x, y, grid=False)
+            xp_assert_close(actual_rp, expected_vals,
+                            rtol=0, atol=1.5*10**(-6))
+
+    @pytest.mark.parametrize("k", [3, 4])
+    def test_partial_derivative_order_too_large(self, k):
+        x = array([0, 1, 2, 3, 4], dtype=float)
+        y = x.copy()
+        z = ones((x.size, y.size))
+        lut = RectBivariateSpline(x, y, z)
+        lut_ndbspline = convert_to_ndbspline(lut)
+        with assert_raises(ValueError):
+            lut.partial_derivative(k + 1, 1)
+
+        assert (lut_ndbspline.derivative([k + 1, 1]).c == 0.0).all()
+
+        lut = RectBivariateSpline(x, y, z, kx=k, ky=k)
+        with assert_raises(ValueError):
+            lut.partial_derivative(k + 1, 1)
+
+        lut_custom = _regrid(x, y, z, kx=k, ky=k)
+        assert (lut_custom.derivative([k + 1, 1]).c == 0.0).all()
+
+    @pytest.mark.parametrize("k", [3, 4])
+    def test_broadcast(self, k):
+        x = array([1,2,3,4,5])
+        y = array([1,2,3,4,5])
+        z = array([[1,2,1,2,1],[1,2,1,2,1],[1,2,3,2,1],[1,2,2,2,1],[1,2,1,2,1]])
+        lut = RectBivariateSpline(x,y,z,kx=k,ky=k)
+        xp_assert_close(lut(x, y), lut(x[:,None], y[None,:], grid=False))
+
+    def test_invalid_input(self):
+
+        x = array([6, 2, 3, 4, 5])
+        y = array([1, 2, 3, 4, 5])
+        z = array([[1, 2, 1, 2, 1], [1, 2, 1, 2, 1], [1, 2, 3, 2, 1],
+                    [1, 2, 2, 2, 1], [1, 2, 1, 2, 1]])
+
+        with assert_raises(ValueError) as info:
+            RectBivariateSpline(x, y, z)
+        assert "x must be strictly increasing" in str(info.value)
+
+        with assert_raises(ValueError) as info_custom:
+            _regrid(x, y, z)
+        assert "x must be strictly increasing" in str(info_custom.value)
+
+        x = array([1, 2, 3, 4, 5])
+        y = array([2, 2, 3, 4, 5])
+        z = array([[1, 2, 1, 2, 1], [1, 2, 1, 2, 1], [1, 2, 3, 2, 1],
+                    [1, 2, 2, 2, 1], [1, 2, 1, 2, 1]])
+        with assert_raises(ValueError) as info:
+            RectBivariateSpline(x, y, z)
+        assert "y must be strictly increasing" in str(info.value)
+
+        with assert_raises(ValueError) as info_custom:
+            _regrid(x, y, z)
+        assert "y must be strictly increasing" in str(info_custom.value)
+
+        x = array([1, 2, 3, 4, 5])
+        y = array([1, 2, 3, 4, 5])
+        z = array([[1, 2, 1, 2, 1], [1, 2, 1, 2, 1], [1, 2, 3, 2, 1],
+                    [1, 2, 2, 2, 1]])
+        with assert_raises(ValueError) as info:
+            RectBivariateSpline(x, y, z)
+        assert "x dimension of z must have same number of elements as x"\
+               in str(info.value)
+
+        with assert_raises(ValueError) as info_custom:
+            _regrid(x, y, z)
+        assert "x dimension of z must have same number of elements as x"\
+               in str(info_custom.value)
+
+        x = array([1, 2, 3, 4, 5])
+        y = array([1, 2, 3, 4, 5])
+        z = array([[1, 2, 1, 2], [1, 2, 1, 2], [1, 2, 3, 2],
+                    [1, 2, 2, 2], [1, 2, 1, 2]])
+
+        with assert_raises(ValueError) as info:
+            RectBivariateSpline(x, y, z)
+        assert "y dimension of z must have same number of elements as y"\
+               in str(info.value)
+
+        with assert_raises(ValueError) as info_custom:
+            _regrid(x, y, z)
+        assert "y dimension of z must have same number of elements as y"\
+               in str(info_custom.value)
+
+        x = array([1, 2, 3, 4, 5])
+        y = array([1, 2, 3, 4, 5])
+        z = array([[1, 2, 1, 2, 1], [1, 2, 1, 2, 1], [1, 2, 3, 2, 1],
+                    [1, 2, 2, 2, 1], [1, 2, 1, 2, 1]])
+        bbox = (-100, 100, -100)
+
+        with assert_raises(ValueError) as info:
+            RectBivariateSpline(x, y, z, bbox=bbox)
+        assert "bbox shape should be (4,)" in str(info.value)
+
+        with assert_raises(ValueError) as info_custom:
+            _regrid(x, y, z, bbox=bbox)
+        assert "bbox shape should be (4,)" in str(info_custom.value)
+
+        with assert_raises(ValueError) as info:
+            RectBivariateSpline(x, y, z, s=-1.0)
+        assert "s should be s >= 0.0" in str(info.value)
+
+        with assert_raises(ValueError) as info_custom:
+            _regrid(x, y, z, s=-1.0)
+        assert "s should be s >= 0.0" in str(info_custom.value)
+
+    @pytest.mark.parametrize("k", [3, 4])
+    def test_array_like_input(self, k):
+        x = array([1, 2, 3, 4, 5])
+        y = array([1, 2, 3, 4, 5])
+        z = array([[1, 2, 1, 2, 1], [1, 2, 1, 2, 1], [1, 2, 3, 2, 1],
+                   [1, 2, 2, 2, 1], [1, 2, 1, 2, 1]])
+        bbox = array([1, 5, 1, 5])
+
+        spl1 = RectBivariateSpline(x, y, z, bbox=bbox, kx=k, ky=k)
+        spl1_custom = _regrid(x, y, z, bbox=bbox, kx=k, ky=k)
+        spl2 = RectBivariateSpline(x.tolist(), y.tolist(), z.tolist(),
+                                   bbox=bbox.tolist(), kx=k, ky=k)
+        spl2_custom = _regrid(x.tolist(), y.tolist(), z.tolist(),
+                                   bbox=bbox.tolist(), kx=k, ky=k)
+        assert_array_almost_equal(spl1(1.0, 1.0), spl2(1.0, 1.0))
+        xp_assert_close(spl1(1.0, 1.0),
+                        _ndbspline_call_like_bivariate(spl1_custom, 1.0, 1.0),
+                        rtol=0, atol=1.5*10**(-6))
+        xp_assert_close(spl2(1.0, 1.0),
+                        _ndbspline_call_like_bivariate(spl2_custom, 1.0, 1.0),
+                        rtol=0, atol=1.5*10**(-6))
+        xp_assert_close(_ndbspline_call_like_bivariate(spl1_custom, 1.0, 1.0),
+                        _ndbspline_call_like_bivariate(spl2_custom, 1.0, 1.0),
+                        rtol=0, atol=1.5*10**(-6))
+
+    def test_not_increasing_input(self):
+        # gh-8565
+        NSamp = 20
+        Theta = np.random.uniform(0, np.pi, NSamp)
+        Phi = np.random.uniform(0, 2 * np.pi, NSamp)
+        Data = np.ones(NSamp)
+
+        Interpolator = SmoothSphereBivariateSpline(Theta, Phi, Data, s=3.5)
+
+        NLon = 6
+        NLat = 3
+        GridPosLats = np.arange(NLat) / NLat * np.pi
+        GridPosLons = np.arange(NLon) / NLon * 2 * np.pi
+
+        # No error
+        Interpolator(GridPosLats, GridPosLons)
+
+        nonGridPosLats = GridPosLats.copy()
+        nonGridPosLats[2] = 0.001
+        with assert_raises(ValueError) as exc_info:
+            Interpolator(nonGridPosLats, GridPosLons)
+        assert "x must be strictly increasing" in str(exc_info.value)
+
+        nonGridPosLons = GridPosLons.copy()
+        nonGridPosLons[2] = 0.001
+        with assert_raises(ValueError) as exc_info:
+            Interpolator(GridPosLats, nonGridPosLons)
+        assert "y must be strictly increasing" in str(exc_info.value)
+
+    def test_grid_sparse_meshgrid(self):
+        # gh-25730
+        x = np.arange(-10.0, 10.0)
+        y = np.arange(-20.0, 20.0)
+        lut = RectBivariateSpline(x, y, np.hypot(x[:, None], y[None, :]), s=0)
+
+        xi = np.linspace(-10.0, 10.0, 25)
+        yi = np.linspace(-20.0, 20.0, 30)
+        xs, ys = np.meshgrid(xi, yi, sparse=True, indexing="ij")
+        assert xs.ndim == 2 and ys.ndim == 2
+
+        xp_assert_close(lut(xs, ys), lut(xi, yi), atol=1e-14)
+
+    def test_grid_sparse_meshgrid_values(self):
+        # gh-25730
+        # The snippet from the issue, without its denominator so that no nans
+        # enter the fit. Reference values obtained by running it on scipy 1.16.1.
+        x = np.arange(-10, 10)
+        y = np.arange(-20, 20)
+        x_mesh, y_mesh = np.meshgrid(x, y)
+        z = np.sin(np.sqrt(x_mesh**2 + y_mesh**2))
+
+        xi = np.linspace(-10, 10, endpoint=True, num=3)
+        yi = np.linspace(-20, 20, endpoint=True, num=3)
+        xs, ys = np.meshgrid(xi, yi, sparse=True)
+
+        expected = np.array([
+            [-3.61178317e-01, 9.12945251e-01, 5.94013869e-02],
+            [-5.44021111e-01, -2.15105711e-16, 4.12118485e-01],
+            [4.97086683e-01, 1.49877210e-01, 8.23386213e-01],
+        ])
+        xp_assert_close(RectBivariateSpline(y, x, z, s=0)(ys, xs), expected, atol=1e-14)
+
+    def test_not_increasing_input_2d(self):
+        # gh-25730
+        x = np.arange(5.0)
+        y = np.arange(6.0)
+        lut = RectBivariateSpline(x, y, np.hypot(x[:, None], y[None, :]), s=0)
+
+        decreasing = np.array([3.0, 1.0, 4.0])
+        with assert_raises(ValueError) as exc_info:
+            lut(decreasing[:, None], y[None, :])
+        assert "x must be strictly increasing" in str(exc_info.value)
+
+        with assert_raises(ValueError) as exc_info:
+            lut(x[:, None], decreasing[None, :])
+        assert "y must be strictly increasing" in str(exc_info.value)
+
+    def _sample_large_2d_data(self, nx, ny):
+        rng = np.random.default_rng(1)
+        x = np.arange(nx)
+        y = np.arange(ny)
+        z = rng.integers(0, 100, (nx, ny))
+
+        return x, y, z.astype(np.float64)
+
+    # Thin wrapper used as the ``RectBivariateSpline`` entry in the
+    # ``spl_apis`` parametrize dimension of ``test_spline_large_2d`` and
+    # ``test_spline_large_2d_maxit``.  A standalone callable is required
+    # because ``RectBivariateSpline.__call__`` cannot be passed directly as a
+    # parametrize value alongside ``_ndbspline_call_like_bivariate``.
+    def _RectBivariateSplineEval(spl, x, y):
+        return spl(x, y)
+
+    @pytest.mark.slow()
+    @pytest.mark.parametrize('shape', [(350, 850), (2000, 170)])
+    @pytest.mark.parametrize('s_tols', [(0, 1e-12, 1e-7),
+                                        (1, 7e-3, 1e-4),
+                                        (3, 2e-2, 1e-4)])
+    @pytest.mark.parametrize("spl_apis", ((RectBivariateSpline,
+                                           _RectBivariateSplineEval),
+                                          (_regrid,
+                                           _ndbspline_call_like_bivariate)))
+    def test_spline_large_2d(self, shape, s_tols, spl_apis):
+        # Reference - https://github.com/scipy/scipy/issues/17787
+        #
+        # ``spl_apis`` is intentionally a parametrize dimension
+        # so that pytest-timeout's ``--timeout`` limit is applied
+        # individually to each (API, shape, s_tols) combination.  If both APIs
+        # were called sequentially inside a single test function they would
+        # share one timeout budget, making it much easier to exceed the limit
+        # on slow platforms (e.g. Windows CI) and triggering the
+        # ``--timeout-method=thread`` worker crash described in gh-25142.
+        nx, ny = shape
+        s, atol, rtol = s_tols
+        x, y, z = self._sample_large_2d_data(nx, ny)
+
+        spl_construct, spl_eval = spl_apis
+
+        spl = spl_construct(x, y, z, s=s)
+        z_spl = spl_eval(spl, x, y)
+        assert(not np.isnan(z_spl).any())
+        xp_assert_close(z_spl, z, atol=atol, rtol=rtol)
+
+    @pytest.mark.xslow()
+    @pytest.mark.skipif(sys.maxsize <= 2**32, reason="Segfaults on 32-bit system "
+                                                     "due to large input data")
+    @pytest.mark.parametrize("k", [3, 4])
+    @pytest.mark.parametrize("spl_apis", ((RectBivariateSpline,
+                                           _RectBivariateSplineEval),
+                                          (_regrid,
+                                           _ndbspline_call_like_bivariate)))
+    def test_spline_large_2d_maxit(self, k, spl_apis):
+        # Reference - for https://github.com/scipy/scipy/issues/17787
+        #
+        # ``spl_apis`` is intentionally a parametrize dimension
+        # for the same reason as in ``test_spline_large_2d``: so
+        # that pytest-timeout's ``--timeout`` limit is applied individually to
+        # each (API, k) combination instead of being shared across both APIs
+        # in a single call, which would risk a ``--timeout-method=thread``
+        # worker crash on Windows CI (see gh-25142).
+        nx, ny = 1000, 1700
+        s, atol, rtol = 2, 2e-2, 1e-12
+        x, y, z = self._sample_large_2d_data(nx, ny)
+
+        spl_construct, spl_eval = spl_apis
+
+        spl = spl_construct(x, y, z, s=s,
+                            maxit=30, kx=k, ky=k)
+        z_spl = spl_eval(spl, x, y)
+        assert(not np.isnan(z_spl).any())
+        xp_assert_close(z_spl, z, atol=atol, rtol=rtol)
+
+    @pytest.mark.parametrize("spl_apis", ((RectBivariateSpline,
+                                           _RectBivariateSplineEval),
+                                          (_regrid,
+                                           _ndbspline_call_like_bivariate)))
+    def test_spline_synthetic_data(self, spl_apis):
+        """
+        Test regrid with synthetic smooth data (mixed frequencies + noise).
+        """
+        # ``spl_apis`` is parametrized for consistency with
+        # ``test_spline_large_2d`` and ``test_spline_large_2d_maxit``,
+        # ensuring both APIs are exercised under the same test structure.
+        #
+        # Create strictly-increasing axes and smooth test surface
+        nx, ny = 64, 64
+        kx, ky = 3, 3
+        s = 0.3
+
+        rng = np.random.default_rng(0)
+        x = np.linspace(0.0, 4.0, nx, dtype=float)
+        y = np.linspace(0.0, 4.0, ny, dtype=float)
+
+        # Smooth, nontrivial surface with mixed frequencies + mild noise
+        X, Y = np.meshgrid(x, y, indexing="ij")
+        z = (
+            np.sin(X) * np.cos(Y)
+            + 0.2 * np.sin(2 * X + 0.5) * np.cos(1.5 * Y - 0.3)
+            + 0.05 * rng.normal(size=(nx, ny))
+        ).astype(float)
+
+        spl_construct, spl_eval = spl_apis
+
+        spl = spl_construct(x, y, z, kx=kx, ky=ky, s=s)
+        z_spl = spl_eval(spl, x, y)
+        assert not np.isnan(z_spl).any()
+        xp_assert_close(z_spl, z, atol=0.1, rtol=0.1)
+
+    def test_0d(self):
+        # regression test for https://github.com/scipy/scipy/issues/25471
+        # result shapes checked with SciPy 1.16.3 (pre FITPACK C port)
+        x = np.arange(6.0)
+        r = RectBivariateSpline(x, x, np.outer(x, x))(2.5, 3.5, grid=False)
+        assert r.ndim == 0
+
+        r = RectBivariateSpline(x, x, np.outer(x, x))([2.5], 3.5, grid=False)
+        assert r.ndim == 1
+
+
+class TestRectSphereBivariateSpline:
+    def test_defaults(self):
+        y = linspace(0.01, 2*pi-0.01, 7)
+        x = linspace(0.01, pi-0.01, 7)
+        z = array([[1,2,1,2,1,2,1],[1,2,1,2,1,2,1],[1,2,3,2,1,2,1],
+                   [1,2,2,2,1,2,1],[1,2,1,2,1,2,1],[1,2,2,2,1,2,1],
+                   [1,2,1,2,1,2,1]])
+        lut = RectSphereBivariateSpline(x,y,z)
+        assert_array_almost_equal(lut(x,y),z)
+
+    def test_evaluate(self):
+        y = linspace(0.01, 2*pi-0.01, 7)
+        x = linspace(0.01, pi-0.01, 7)
+        z = array([[1,2,1,2,1,2,1],[1,2,1,2,1,2,1],[1,2,3,2,1,2,1],
+                   [1,2,2,2,1,2,1],[1,2,1,2,1,2,1],[1,2,2,2,1,2,1],
+                   [1,2,1,2,1,2,1]])
+        lut = RectSphereBivariateSpline(x,y,z)
+        yi = [0.2, 1, 2.3, 2.35, 3.0, 3.99, 5.25]
+        xi = [1.5, 0.4, 1.1, 0.45, 0.2345, 1., 0.0001]
+        zi = lut.ev(xi, yi)
+        zi2 = array([lut(xp, yp)[0,0] for xp, yp in zip(xi, yi)])
+        assert_almost_equal(zi, zi2)
+
+    def test_invalid_input(self):
+        data = np.dot(np.atleast_2d(90. - np.linspace(-80., 80., 18)).T,
+                      np.atleast_2d(180. - np.abs(np.linspace(0., 350., 9)))).T
+
+        with assert_raises(ValueError) as exc_info:
+            lats = np.linspace(-1, 170, 9) * np.pi / 180.
+            lons = np.linspace(0, 350, 18) * np.pi / 180.
+            RectSphereBivariateSpline(lats, lons, data)
+        assert "u should be between (0, pi)" in str(exc_info.value)
+
+        with assert_raises(ValueError) as exc_info:
+            lats = np.linspace(10, 181, 9) * np.pi / 180.
+            lons = np.linspace(0, 350, 18) * np.pi / 180.
+            RectSphereBivariateSpline(lats, lons, data)
+        assert "u should be between (0, pi)" in str(exc_info.value)
+
+        with assert_raises(ValueError) as exc_info:
+            lats = np.linspace(10, 170, 9) * np.pi / 180.
+            lons = np.linspace(-181, 10, 18) * np.pi / 180.
+            RectSphereBivariateSpline(lats, lons, data)
+        assert "v[0] should be between [-pi, pi)" in str(exc_info.value)
+
+        with assert_raises(ValueError) as exc_info:
+            lats = np.linspace(10, 170, 9) * np.pi / 180.
+            lons = np.linspace(-10, 360, 18) * np.pi / 180.
+            RectSphereBivariateSpline(lats, lons, data)
+        assert "v[-1] should be v[0] + 2pi or less" in str(exc_info.value)
+
+        with assert_raises(ValueError) as exc_info:
+            lats = np.linspace(10, 170, 9) * np.pi / 180.
+            lons = np.linspace(10, 350, 18) * np.pi / 180.
+            RectSphereBivariateSpline(lats, lons, data, s=-1)
+        assert "s should be positive" in str(exc_info.value)
+
+    def test_derivatives_grid(self):
+        y = linspace(0.01, 2*pi-0.01, 7)
+        x = linspace(0.01, pi-0.01, 7)
+        z = array([[1,2,1,2,1,2,1],[1,2,1,2,1,2,1],[1,2,3,2,1,2,1],
+                   [1,2,2,2,1,2,1],[1,2,1,2,1,2,1],[1,2,2,2,1,2,1],
+                   [1,2,1,2,1,2,1]])
+
+        lut = RectSphereBivariateSpline(x,y,z)
+
+        y = linspace(0.02, 2*pi-0.02, 7)
+        x = linspace(0.02, pi-0.02, 7)
+
+        xp_assert_close(lut(x, y, dtheta=1), _numdiff_2d(lut, x, y, dx=1),
+                        rtol=1e-4, atol=1e-4)
+        xp_assert_close(lut(x, y, dphi=1), _numdiff_2d(lut, x, y, dy=1),
+                        rtol=1e-4, atol=1e-4)
+        xp_assert_close(lut(x, y, dtheta=1, dphi=1),
+                        _numdiff_2d(lut, x, y, dx=1, dy=1, eps=1e-6),
+                        rtol=1e-3, atol=1e-3)
+
+        xp_assert_equal(lut(x, y, dtheta=1),
+                           lut.partial_derivative(1, 0)(x, y))
+        xp_assert_equal(lut(x, y, dphi=1),
+                           lut.partial_derivative(0, 1)(x, y))
+        xp_assert_equal(lut(x, y, dtheta=1, dphi=1),
+                           lut.partial_derivative(1, 1)(x, y))
+
+        xp_assert_equal(lut(x, y, dtheta=1, grid=False),
+                           lut.partial_derivative(1, 0)(x, y, grid=False))
+        xp_assert_equal(lut(x, y, dphi=1, grid=False),
+                           lut.partial_derivative(0, 1)(x, y, grid=False))
+        xp_assert_equal(lut(x, y, dtheta=1, dphi=1, grid=False),
+                           lut.partial_derivative(1, 1)(x, y, grid=False))
+
+    def test_derivatives(self):
+        y = linspace(0.01, 2*pi-0.01, 7)
+        x = linspace(0.01, pi-0.01, 7)
+        z = array([[1,2,1,2,1,2,1],[1,2,1,2,1,2,1],[1,2,3,2,1,2,1],
+                   [1,2,2,2,1,2,1],[1,2,1,2,1,2,1],[1,2,2,2,1,2,1],
+                   [1,2,1,2,1,2,1]])
+
+        lut = RectSphereBivariateSpline(x,y,z)
+
+        y = linspace(0.02, 2*pi-0.02, 7)
+        x = linspace(0.02, pi-0.02, 7)
+
+        assert lut(x, y, dtheta=1, grid=False).shape == x.shape
+        xp_assert_close(lut(x, y, dtheta=1, grid=False),
+                        _numdiff_2d(lambda x,y: lut(x,y,grid=False), x, y, dx=1),
+                        rtol=1e-4, atol=1e-4)
+        xp_assert_close(lut(x, y, dphi=1, grid=False),
+                        _numdiff_2d(lambda x,y: lut(x,y,grid=False), x, y, dy=1),
+                        rtol=1e-4, atol=1e-4)
+        xp_assert_close(lut(x, y, dtheta=1, dphi=1, grid=False),
+                        _numdiff_2d(lambda x,y: lut(x,y,grid=False),
+                                    x, y, dx=1, dy=1, eps=1e-6),
+                        rtol=1e-3, atol=1e-3)
+
+    def test_invalid_input_2(self):
+        data = np.dot(np.atleast_2d(90. - np.linspace(-80., 80., 18)).T,
+                      np.atleast_2d(180. - np.abs(np.linspace(0., 350., 9)))).T
+
+        with assert_raises(ValueError) as exc_info:
+            lats = np.linspace(0, 170, 9) * np.pi / 180.
+            lons = np.linspace(0, 350, 18) * np.pi / 180.
+            RectSphereBivariateSpline(lats, lons, data)
+        assert "u should be between (0, pi)" in str(exc_info.value)
+
+        with assert_raises(ValueError) as exc_info:
+            lats = np.linspace(10, 180, 9) * np.pi / 180.
+            lons = np.linspace(0, 350, 18) * np.pi / 180.
+            RectSphereBivariateSpline(lats, lons, data)
+        assert "u should be between (0, pi)" in str(exc_info.value)
+
+        with assert_raises(ValueError) as exc_info:
+            lats = np.linspace(10, 170, 9) * np.pi / 180.
+            lons = np.linspace(-181, 10, 18) * np.pi / 180.
+            RectSphereBivariateSpline(lats, lons, data)
+        assert "v[0] should be between [-pi, pi)" in str(exc_info.value)
+
+        with assert_raises(ValueError) as exc_info:
+            lats = np.linspace(10, 170, 9) * np.pi / 180.
+            lons = np.linspace(-10, 360, 18) * np.pi / 180.
+            RectSphereBivariateSpline(lats, lons, data)
+        assert "v[-1] should be v[0] + 2pi or less" in str(exc_info.value)
+
+        with assert_raises(ValueError) as exc_info:
+            lats = np.linspace(10, 170, 9) * np.pi / 180.
+            lons = np.linspace(10, 350, 18) * np.pi / 180.
+            RectSphereBivariateSpline(lats, lons, data, s=-1)
+        assert "s should be positive" in str(exc_info.value)
+
+    def test_array_like_input(self):
+        y = linspace(0.01, 2 * pi - 0.01, 7)
+        x = linspace(0.01, pi - 0.01, 7)
+        z = array([[1, 2, 1, 2, 1, 2, 1], [1, 2, 1, 2, 1, 2, 1],
+                   [1, 2, 3, 2, 1, 2, 1],
+                   [1, 2, 2, 2, 1, 2, 1], [1, 2, 1, 2, 1, 2, 1],
+                   [1, 2, 2, 2, 1, 2, 1],
+                   [1, 2, 1, 2, 1, 2, 1]])
+        # np.array input
+        spl1 = RectSphereBivariateSpline(x, y, z)
+        # list input
+        spl2 = RectSphereBivariateSpline(x.tolist(), y.tolist(), z.tolist())
+        assert_array_almost_equal(spl1(x, y), spl2(x, y))
+
+    def test_negative_evaluation(self):
+        lats = np.array([25, 30, 35, 40, 45])
+        lons = np.array([-90, -85, -80, -75, 70])
+        mesh = np.meshgrid(lats, lons)
+        data = mesh[0] + mesh[1]  # lon + lat value
+        lat_r = np.radians(lats)
+        lon_r = np.radians(lons)
+        interpolator = RectSphereBivariateSpline(lat_r, lon_r, data)
+        query_lat = np.radians(np.array([35, 37.5]))
+        query_lon = np.radians(np.array([-80, -77.5]))
+        data_interp = interpolator(query_lat, query_lon)
+        ans = np.array([[-45.0, -42.480862],
+                        [-49.0625, -46.54315]])
+        assert_array_almost_equal(data_interp, ans)
+
+    def test_pole_continuity_gh_14591(self):
+        # regression test for https://github.com/scipy/scipy/issues/14591
+        # with pole_continuty=(True, True), the internal work array size
+        # was too small, leading to a FITPACK data validation error.
+
+        # The reproducer in gh-14591 was using a NetCDF4 file with
+        # 361x507 arrays, so here we trivialize array sizes to a minimum
+        # which still demonstrates the issue.
+        u = np.arange(1, 10) * np.pi / 10
+        v = np.arange(1, 10) * np.pi / 10
+        r = np.zeros((9, 9))
+        for p in [(True, True), (True, False), (False, False)]:
+            RectSphereBivariateSpline(u, v, r, s=0, pole_continuity=p)
+
+
+def _numdiff_2d(func, x, y, dx=0, dy=0, eps=1e-8):
+    if dx == 0 and dy == 0:
+        return func(x, y)
+    elif dx == 1 and dy == 0:
+        return (func(x + eps, y) - func(x - eps, y)) / (2*eps)
+    elif dx == 0 and dy == 1:
+        return (func(x, y + eps) - func(x, y - eps)) / (2*eps)
+    elif dx == 1 and dy == 1:
+        return (func(x + eps, y + eps) - func(x - eps, y + eps)
+                - func(x + eps, y - eps) + func(x - eps, y - eps)) / (2*eps)**2
+    else:
+        raise ValueError("invalid derivative order")
+
+
+class Test_DerivedBivariateSpline:
+    """Test the creation, usage, and attribute access of the (private)
+    _DerivedBivariateSpline class.
+    """
+    def setup_method(self):
+        x = np.concatenate(list(zip(range(10), range(10))))
+        y = np.concatenate(list(zip(range(10), range(1, 11))))
+        z = np.concatenate((np.linspace(3, 1, 10), np.linspace(1, 3, 10)))
+        with pytest.warns(UserWarning, match="\nThe coefficients of the spline"):
+            self.lut_lsq = LSQBivariateSpline(x, y, z,
+                                              linspace(0.5, 19.5, 4),
+                                              linspace(1.5, 20.5, 4),
+                                              eps=1e-2)
+        self.lut_smooth = SmoothBivariateSpline(x, y, z)
+        xx = linspace(0, 1, 20)
+        yy = xx + 1.0
+        zz = array([np.roll(z, i) for i in range(z.size)])
+        self.lut_rect = RectBivariateSpline(xx, yy, zz, kx=4, ky=4)
+        self.lut_rect_custom = _regrid(xx, yy, zz, kx=4, ky=4)
+        self.orders = list(itertools.product(range(3), range(3)))
+
+    def test_creation_from_LSQ(self):
+        for nux, nuy in self.orders:
+            lut_der = self.lut_lsq.partial_derivative(nux, nuy)
+            a = lut_der(3.5, 3.5, grid=False)
+            b = self.lut_lsq(3.5, 3.5, dx=nux, dy=nuy, grid=False)
+            assert a == b
+
+    def test_creation_from_Smooth(self):
+        for nux, nuy in self.orders:
+            lut_der = self.lut_smooth.partial_derivative(nux, nuy)
+            a = lut_der(5.5, 5.5, grid=False)
+            b = self.lut_smooth(5.5, 5.5, dx=nux, dy=nuy, grid=False)
+            assert a == b
+
+    def test_creation_from_Rect(self):
+        for nux, nuy in self.orders:
+            lut_der = self.lut_rect.partial_derivative(nux, nuy)
+            a = lut_der(0.5, 1.5, grid=False)
+            b = self.lut_rect(0.5, 1.5, dx=nux, dy=nuy, grid=False)
+            assert a == b
+
+        for nux, nuy in self.orders:
+            lut_der = self.lut_rect_custom.derivative([nux, nuy])
+            a = _ndbspline_call_like_bivariate(lut_der, 0.5, 1.5)
+            b = _ndbspline_call_like_bivariate(
+                self.lut_rect_custom, 0.5, 1.5, dx=nux, dy=nuy)
+            xp_assert_close(a, b, rtol=0, atol=1.5*10**(-6))
+
+        for nux, nuy in self.orders:
+            lut_der = self.lut_rect.partial_derivative(nux, nuy)
+            lut_ndspline = convert_to_ndbspline(self.lut_rect)
+            lut_der_ndbspline = lut_ndspline.derivative((nux, nuy))
+            a = lut_der(0.5, 1.5, grid=False)
+            a_ndbspline = lut_der_ndbspline([(0.5, 1.5)])
+            b = self.lut_rect(0.5, 1.5, dx=nux, dy=nuy, grid=False)
+            b_ndbspline = lut_ndspline([(0.5, 1.5)], nu=(nux, nuy))
+            assert a == b
+            assert_almost_equal(a_ndbspline, b_ndbspline)
+
+    def test_invalid_attribute_fp(self):
+        der = self.lut_rect.partial_derivative(1, 1)
+        with assert_raises(AttributeError):
+            der.fp
+
+        der = self.lut_rect_custom.derivative([1, 1])
+        with assert_raises(AttributeError):
+            der.fp
+
+        lut_ndbspline = convert_to_ndbspline(self.lut_rect)
+        der = lut_ndbspline.derivative(nu=[1, 1])
+        with assert_raises(AttributeError):
+            der.fp
+
+    def test_invalid_attribute_get_residual(self):
+        der = self.lut_smooth.partial_derivative(1, 1)
+        with assert_raises(AttributeError):
+            der.get_residual()
diff --git a/.venv/lib/python3.12/site-packages/scipy/interpolate/tests/test_gil.py b/.venv/lib/python3.12/site-packages/scipy/interpolate/tests/test_gil.py
new file mode 100644
index 0000000000000000000000000000000000000000..f123f9457628c9f8c56ee14401aa39d8f81c472f
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/interpolate/tests/test_gil.py
@@ -0,0 +1,80 @@
+import itertools
+import threading
+import time
+
+import numpy as np
+import pytest
+import scipy.interpolate
+
+class TestGIL:
+    """Check if the GIL is properly released by scipy.interpolate functions."""
+
+    def setup_method(self):
+        self.messages = []
+
+    def log(self, message):
+        self.messages.append(message)
+
+    def make_worker_thread(self, target, args):
+        log = self.log
+
+        class WorkerThread(threading.Thread):
+            def run(self):
+                log('interpolation started')
+                target(*args)
+                log('interpolation complete')
+
+        return WorkerThread()
+
+    @pytest.mark.xslow
+    @pytest.mark.xfail(reason='race conditions, may depend on system load')
+    def test_rectbivariatespline(self):
+        def generate_params(n_points):
+            x = y = np.linspace(0, 1000, n_points)
+            x_grid, y_grid = np.meshgrid(x, y)
+            z = x_grid * y_grid
+            return x, y, z
+
+        def calibrate_delay(requested_time):
+            for n_points in itertools.count(5000, 1000):
+                args = generate_params(n_points)
+                time_started = time.time()
+                interpolate(*args)
+                if time.time() - time_started > requested_time:
+                    return args
+
+        def interpolate(x, y, z):
+            scipy.interpolate.RectBivariateSpline(x, y, z)
+
+        def interpolate_custom(x, y, z):
+            scipy.interpolate._regrid._regrid(x, y, z)
+
+        args = calibrate_delay(requested_time=3)
+        worker_thread = self.make_worker_thread(interpolate, args)
+        worker_thread.start()
+        for i in range(3):
+            time.sleep(0.5)
+            self.log('working')
+        worker_thread.join()
+        assert self.messages == [
+            'interpolation started',
+            'working',
+            'working',
+            'working',
+            'interpolation complete',
+        ]
+
+        args = calibrate_delay(requested_time=3)
+        worker_thread = self.make_worker_thread(interpolate_custom, args)
+        worker_thread.start()
+        for i in range(3):
+            time.sleep(0.5)
+            self.log('working')
+        worker_thread.join()
+        assert self.messages == [
+            'interpolation started',
+            'working',
+            'working',
+            'working',
+            'interpolation complete',
+        ]
diff --git a/.venv/lib/python3.12/site-packages/scipy/interpolate/tests/test_interpnd.py b/.venv/lib/python3.12/site-packages/scipy/interpolate/tests/test_interpnd.py
new file mode 100644
index 0000000000000000000000000000000000000000..bcd157b47268e2ef9e2a5bfaf7c3d7876a99d7e0
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/interpolate/tests/test_interpnd.py
@@ -0,0 +1,538 @@
+import os
+import sys
+import warnings
+
+import numpy as np
+from pytest import raises as assert_raises
+import pytest
+from scipy._lib._array_api import xp_assert_close, assert_almost_equal
+
+from scipy._lib._testutils import check_free_memory
+import scipy.interpolate._interpnd as interpnd
+import scipy.spatial._qhull as qhull
+
+import pickle
+import threading
+
+_IS_32BIT = (sys.maxsize < 2**32)
+
+
+def data_file(basename):
+    return os.path.join(os.path.abspath(os.path.dirname(__file__)),
+                        'data', basename)
+
+
+class TestLinearNDInterpolation:
+    def test_smoketest(self):
+        # Test at single points
+        x = np.array([(0,0), (-0.5,-0.5), (-0.5,0.5), (0.5, 0.5), (0.25, 0.3)],
+                     dtype=np.float64)
+        y = np.arange(x.shape[0], dtype=np.float64)
+
+        yi = interpnd.LinearNDInterpolator(x, y)(x)
+        assert_almost_equal(y, yi)
+
+    def test_smoketest_alternate(self):
+        # Test at single points, alternate calling convention
+        x = np.array([(0,0), (-0.5,-0.5), (-0.5,0.5), (0.5, 0.5), (0.25, 0.3)],
+                     dtype=np.float64)
+        y = np.arange(x.shape[0], dtype=np.float64)
+
+        yi = interpnd.LinearNDInterpolator((x[:,0], x[:,1]), y)(x[:,0], x[:,1])
+        assert_almost_equal(y, yi)
+
+    def test_complex_smoketest(self):
+        # Test at single points
+        x = np.array([(0,0), (-0.5,-0.5), (-0.5,0.5), (0.5, 0.5), (0.25, 0.3)],
+                     dtype=np.float64)
+        y = np.arange(x.shape[0], dtype=np.float64)
+        y = y - 3j*y
+
+        yi = interpnd.LinearNDInterpolator(x, y)(x)
+        assert_almost_equal(y, yi)
+
+    def test_tri_input(self):
+        # Test at single points
+        x = np.array([(0,0), (-0.5,-0.5), (-0.5,0.5), (0.5, 0.5), (0.25, 0.3)],
+                     dtype=np.float64)
+        y = np.arange(x.shape[0], dtype=np.float64)
+        y = y - 3j*y
+
+        tri = qhull.Delaunay(x)
+        interpolator = interpnd.LinearNDInterpolator(tri, y)
+        yi = interpolator(x)
+        assert_almost_equal(y, yi)
+        assert interpolator.tri is tri
+
+    def test_square(self):
+        # Test barycentric interpolation on a square against a manual
+        # implementation
+
+        points = np.array([(0,0), (0,1), (1,1), (1,0)], dtype=np.float64)
+        values = np.array([1., 2., -3., 5.], dtype=np.float64)
+
+        # NB: assume triangles (0, 1, 3) and (1, 2, 3)
+        #
+        #  1----2
+        #  | \  |
+        #  |  \ |
+        #  0----3
+
+        def ip(x, y):
+            t1 = (x + y <= 1)
+            t2 = ~t1
+
+            x1 = x[t1]
+            y1 = y[t1]
+
+            x2 = x[t2]
+            y2 = y[t2]
+
+            z = 0*x
+
+            z[t1] = (values[0]*(1 - x1 - y1)
+                     + values[1]*y1
+                     + values[3]*x1)
+
+            z[t2] = (values[2]*(x2 + y2 - 1)
+                     + values[1]*(1 - x2)
+                     + values[3]*(1 - y2))
+            return z
+
+        xx, yy = np.broadcast_arrays(np.linspace(0, 1, 14)[:,None],
+                                     np.linspace(0, 1, 14)[None,:])
+        xx = xx.ravel()
+        yy = yy.ravel()
+
+        xi = np.array([xx, yy]).T.copy()
+        zi = interpnd.LinearNDInterpolator(points, values)(xi)
+
+        assert_almost_equal(zi, ip(xx, yy))
+
+    def test_smoketest_rescale(self):
+        # Test at single points
+        x = np.array([(0, 0), (-5, -5), (-5, 5), (5, 5), (2.5, 3)],
+                     dtype=np.float64)
+        y = np.arange(x.shape[0], dtype=np.float64)
+
+        yi = interpnd.LinearNDInterpolator(x, y, rescale=True)(x)
+        assert_almost_equal(y, yi)
+
+    def test_square_rescale(self):
+        # Test barycentric interpolation on a rectangle with rescaling
+        # agaings the same implementation without rescaling
+
+        points = np.array([(0,0), (0,100), (10,100), (10,0)], dtype=np.float64)
+        values = np.array([1., 2., -3., 5.], dtype=np.float64)
+
+        xx, yy = np.broadcast_arrays(np.linspace(0, 10, 14)[:,None],
+                                     np.linspace(0, 100, 14)[None,:])
+        xx = xx.ravel()
+        yy = yy.ravel()
+        xi = np.array([xx, yy]).T.copy()
+        zi = interpnd.LinearNDInterpolator(points, values)(xi)
+        zi_rescaled = interpnd.LinearNDInterpolator(points, values,
+                rescale=True)(xi)
+
+        assert_almost_equal(zi, zi_rescaled)
+
+    def test_tripoints_input_rescale(self):
+        # Test at single points
+        x = np.array([(0,0), (-5,-5), (-5,5), (5, 5), (2.5, 3)],
+                     dtype=np.float64)
+        y = np.arange(x.shape[0], dtype=np.float64)
+        y = y - 3j*y
+
+        tri = qhull.Delaunay(x)
+        yi = interpnd.LinearNDInterpolator(tri.points, y)(x)
+        yi_rescale = interpnd.LinearNDInterpolator(tri.points, y,
+                rescale=True)(x)
+        assert_almost_equal(yi, yi_rescale)
+
+    def test_tri_input_rescale(self):
+        # Test at single points
+        x = np.array([(0,0), (-5,-5), (-5,5), (5, 5), (2.5, 3)],
+                     dtype=np.float64)
+        y = np.arange(x.shape[0], dtype=np.float64)
+        y = y - 3j*y
+
+        tri = qhull.Delaunay(x)
+        match = ("Rescaling is not supported when passing a "
+                 "Delaunay triangulation as ``points``.")
+        with pytest.raises(ValueError, match=match):
+            interpnd.LinearNDInterpolator(tri, y, rescale=True)(x)
+
+    def test_pickle(self):
+        # Test at single points
+        np.random.seed(1234)
+        x = np.random.rand(30, 2)
+        y = np.random.rand(30) + 1j*np.random.rand(30)
+
+        ip = interpnd.LinearNDInterpolator(x, y)
+        ip2 = pickle.loads(pickle.dumps(ip))
+
+        assert_almost_equal(ip(0.5, 0.5), ip2(0.5, 0.5))
+
+    @pytest.mark.slow
+    @pytest.mark.skipif(_IS_32BIT, reason='it fails on 32-bit')
+    def test_threading(self):
+        # This test was taken from issue 8856
+        # https://github.com/scipy/scipy/issues/8856
+        check_free_memory(10000)
+
+        r_ticks = np.arange(0, 4200, 10)
+        phi_ticks = np.arange(0, 4200, 10)
+        r_grid, phi_grid = np.meshgrid(r_ticks, phi_ticks)
+
+        def do_interp(interpolator, slice_rows, slice_cols):
+            grid_x, grid_y = np.mgrid[slice_rows, slice_cols]
+            res = interpolator((grid_x, grid_y))
+            return res
+
+        points = np.vstack((r_grid.ravel(), phi_grid.ravel())).T
+        values = (r_grid * phi_grid).ravel()
+        interpolator = interpnd.LinearNDInterpolator(points, values)
+
+        worker_thread_1 = threading.Thread(
+            target=do_interp,
+            args=(interpolator, slice(0, 2100), slice(0, 2100)))
+        worker_thread_2 = threading.Thread(
+            target=do_interp,
+            args=(interpolator, slice(2100, 4200), slice(0, 2100)))
+        worker_thread_3 = threading.Thread(
+            target=do_interp,
+            args=(interpolator, slice(0, 2100), slice(2100, 4200)))
+        worker_thread_4 = threading.Thread(
+            target=do_interp,
+            args=(interpolator, slice(2100, 4200), slice(2100, 4200)))
+
+        worker_thread_1.start()
+        worker_thread_2.start()
+        worker_thread_3.start()
+        worker_thread_4.start()
+
+        worker_thread_1.join()
+        worker_thread_2.join()
+        worker_thread_3.join()
+        worker_thread_4.join()
+
+
+class TestEstimateGradients2DGlobal:
+    def test_smoketest(self):
+        x = np.array([(0, 0), (0, 2),
+                      (1, 0), (1, 2), (0.25, 0.75), (0.6, 0.8)], dtype=float)
+        tri = qhull.Delaunay(x)
+
+        # Should be exact for linear functions, independent of triangulation
+
+        funcs = [
+            (lambda x, y: 0*x + 1, (0, 0)),
+            (lambda x, y: 0 + x, (1, 0)),
+            (lambda x, y: -2 + y, (0, 1)),
+            (lambda x, y: 3 + 3*x + 14.15*y, (3, 14.15))
+        ]
+
+        for j, (func, grad) in enumerate(funcs):
+            z = func(x[:,0], x[:,1])
+            dz = interpnd.estimate_gradients_2d_global(tri, z, tol=1e-6)
+
+            assert dz.shape == (6, 2)
+            xp_assert_close(
+                dz, np.array(grad)[None, :] + 0*dz, rtol=1e-5, atol=1e-5, 
+                err_msg=f"item {j}"
+            )
+
+    def test_regression_2359(self):
+        # Check regression --- for certain point sets, gradient
+        # estimation could end up in an infinite loop
+        points = np.load(data_file('estimate_gradients_hang.npy'))
+        values = np.random.rand(points.shape[0])
+        tri = qhull.Delaunay(points)
+
+        # This should not hang
+        with warnings.catch_warnings():
+            warnings.filterwarnings(
+                "ignore",
+                "Gradient estimation did not converge",
+                interpnd.GradientEstimationWarning
+            )
+            interpnd.estimate_gradients_2d_global(tri, values, maxiter=1)
+
+
+class TestCloughTocher2DInterpolator:
+
+    def _check_accuracy(self, func, x=None, tol=1e-6, alternate=False,
+                        rescale=False, **kw):
+        rng = np.random.RandomState(1234)
+        # np.random.seed(1234)
+        if x is None:
+            x = np.array([(0, 0), (0, 1),
+                          (1, 0), (1, 1), (0.25, 0.75), (0.6, 0.8),
+                          (0.5, 0.2)],
+                         dtype=float)
+
+        if not alternate:
+            ip = interpnd.CloughTocher2DInterpolator(x, func(x[:,0], x[:,1]),
+                                                     tol=1e-6, rescale=rescale)
+        else:
+            ip = interpnd.CloughTocher2DInterpolator((x[:,0], x[:,1]),
+                                                     func(x[:,0], x[:,1]),
+                                                     tol=1e-6, rescale=rescale)
+
+        p = rng.rand(50, 2)
+
+        if not alternate:
+            a = ip(p)
+        else:
+            a = ip(p[:,0], p[:,1])
+        b = func(p[:,0], p[:,1])
+
+        try:
+            xp_assert_close(a, b, **kw)
+        except AssertionError:
+            print("_check_accuracy: abs(a-b):", abs(a - b))
+            print("ip.grad:", ip.grad)
+            raise
+
+    def test_linear_smoketest(self):
+        # Should be exact for linear functions, independent of triangulation
+        funcs = [
+            lambda x, y: 0*x + 1,
+            lambda x, y: 0 + x,
+            lambda x, y: -2 + y,
+            lambda x, y: 3 + 3*x + 14.15*y,
+        ]
+
+        for j, func in enumerate(funcs):
+            self._check_accuracy(
+                func, tol=1e-13, atol=1e-7, rtol=1e-7, err_msg=f"Function {j}"
+            )
+            self._check_accuracy(
+                func, tol=1e-13, atol=1e-7, rtol=1e-7, alternate=True, 
+                err_msg=f"Function (alternate) {j}"
+            )
+            # check rescaling
+            self._check_accuracy(
+                func, tol=1e-13, atol=1e-7, rtol=1e-7, 
+                err_msg=f"Function (rescaled) {j}", rescale=True
+            )
+            self._check_accuracy(
+                func, tol=1e-13, atol=1e-7, rtol=1e-7, alternate=True, rescale=True, 
+                err_msg=f"Function (alternate, rescaled) {j}"
+            )
+
+    def test_quadratic_smoketest(self):
+        # Should be reasonably accurate for quadratic functions
+        funcs = [
+            lambda x, y: x**2,
+            lambda x, y: y**2,
+            lambda x, y: x**2 - y**2,
+            lambda x, y: x*y,
+        ]
+
+        for j, func in enumerate(funcs):
+            self._check_accuracy(
+                func, tol=1e-9, atol=0.22, rtol=0, err_msg=f"Function {j}"
+            )
+            self._check_accuracy(
+                func, tol=1e-9, atol=0.22, rtol=0, err_msg=f"Function {j}", rescale=True
+            )
+
+    def test_tri_input(self):
+        # Test at single points
+        x = np.array([(0,0), (-0.5,-0.5), (-0.5,0.5), (0.5, 0.5), (0.25, 0.3)],
+                     dtype=np.float64)
+        y = np.arange(x.shape[0], dtype=np.float64)
+        y = y - 3j*y
+
+        tri = qhull.Delaunay(x)
+        yi = interpnd.CloughTocher2DInterpolator(tri, y)(x)
+        assert_almost_equal(y, yi)
+
+    def test_tri_input_rescale(self):
+        # Test at single points
+        x = np.array([(0,0), (-5,-5), (-5,5), (5, 5), (2.5, 3)],
+                     dtype=np.float64)
+        y = np.arange(x.shape[0], dtype=np.float64)
+        y = y - 3j*y
+
+        tri = qhull.Delaunay(x)
+        match = ("Rescaling is not supported when passing a "
+                 "Delaunay triangulation as ``points``.")
+        with pytest.raises(ValueError, match=match):
+            interpnd.CloughTocher2DInterpolator(tri, y, rescale=True)(x)
+
+    def test_tripoints_input_rescale(self):
+        # Test at single points
+        x = np.array([(0,0), (-5,-5), (-5,5), (5, 5), (2.5, 3)],
+                     dtype=np.float64)
+        y = np.arange(x.shape[0], dtype=np.float64)
+        y = y - 3j*y
+
+        tri = qhull.Delaunay(x)
+        yi = interpnd.CloughTocher2DInterpolator(tri.points, y)(x)
+        yi_rescale = interpnd.CloughTocher2DInterpolator(tri.points, y, rescale=True)(x)
+        assert_almost_equal(yi, yi_rescale)
+
+    @pytest.mark.fail_slow(5)
+    def test_dense(self):
+        # Should be more accurate for dense meshes
+        funcs = [
+            lambda x, y: x**2,
+            lambda x, y: y**2,
+            lambda x, y: x**2 - y**2,
+            lambda x, y: x*y,
+            lambda x, y: np.cos(2*np.pi*x)*np.sin(2*np.pi*y)
+        ]
+
+        rng = np.random.RandomState(4321)  # use a different seed than the check!
+        grid = np.r_[np.array([(0,0), (0,1), (1,0), (1,1)], dtype=float),
+                     rng.rand(30*30, 2)]
+
+        for j, func in enumerate(funcs):
+            self._check_accuracy(
+                func, x=grid, tol=1e-9, atol=5e-3, rtol=1e-2, err_msg=f"Function {j}"
+            )
+            self._check_accuracy(
+                func, x=grid, tol=1e-9, atol=5e-3, rtol=1e-2, 
+                err_msg=f"Function {j}", rescale=True
+            )
+
+    def test_wrong_ndim(self):
+        x = np.random.randn(30, 3)
+        y = np.random.randn(30)
+        assert_raises(ValueError, interpnd.CloughTocher2DInterpolator, x, y)
+
+    def test_pickle(self):
+        # Test at single points
+        rng = np.random.RandomState(1234)
+        x = rng.rand(30, 2)
+        y = rng.rand(30) + 1j*rng.rand(30)
+
+        ip = interpnd.CloughTocher2DInterpolator(x, y)
+        ip2 = pickle.loads(pickle.dumps(ip))
+
+        assert_almost_equal(ip(0.5, 0.5), ip2(0.5, 0.5))
+
+    def test_boundary_tri_symmetry(self):
+        # Interpolation at neighbourless triangles should retain
+        # symmetry with mirroring the triangle.
+
+        # Equilateral triangle
+        points = np.array([(0, 0), (1, 0), (0.5, np.sqrt(3)/2)])
+        values = np.array([1, 0, 0])
+
+        ip = interpnd.CloughTocher2DInterpolator(points, values)
+
+        # Set gradient to zero at vertices
+        ip.grad[...] = 0
+
+        # Interpolation should be symmetric vs. bisector
+        alpha = 0.3
+        p1 = np.array([0.5 * np.cos(alpha), 0.5 * np.sin(alpha)])
+        p2 = np.array([0.5 * np.cos(np.pi/3 - alpha), 0.5 * np.sin(np.pi/3 - alpha)])
+
+        v1 = ip(p1)
+        v2 = ip(p2)
+        xp_assert_close(v1, v2)
+
+        # ... and affine invariant
+        rng = np.random.RandomState(1)
+        A = rng.randn(2, 2)
+        b = rng.randn(2)
+
+        points = A.dot(points.T).T + b[None,:]
+        p1 = A.dot(p1) + b
+        p2 = A.dot(p2) + b
+
+        ip = interpnd.CloughTocher2DInterpolator(points, values)
+        ip.grad[...] = 0
+
+        w1 = ip(p1)
+        w2 = ip(p2)
+        xp_assert_close(w1, v1)
+        xp_assert_close(w2, v2)
+
+
+@pytest.mark.parametrize("simplex_tolerance", [1, 10])
+@pytest.mark.parametrize(
+    "interpolation_class",
+    [interpnd.LinearNDInterpolator, interpnd.CloughTocher2DInterpolator]
+)
+def test_interp_from_boundary(interpolation_class, simplex_tolerance):
+    """Test that SciPy can interpolate to a regular grid from the boundary.
+
+    Based on gh-21910
+    """
+    coords = np.block(
+        [[0, np.arange(400, 500), np.zeros(100), 800],
+         [0, np.zeros(100), np.arange(400, 500), 800]]
+    )
+    values = np.ones(202)
+    interpolator = interpolation_class(coords.T, values)
+    results = interpolator(
+        np.mgrid[:500, :500].T, simplex_tolerance=simplex_tolerance
+    )
+    num_nans = np.count_nonzero(np.isnan(results))
+    if simplex_tolerance == 1:
+        # The default tolerance doesn't work when filling from a
+        # dense boundary
+        assert num_nans > 0
+    else:
+        # The larger tolerance allows QHull to assign a simplex
+        # for each point
+        assert num_nans == 0
+
+
+@pytest.mark.parametrize("simplex_tolerance", [1, 10])
+@pytest.mark.parametrize(
+    "interpolator_factory",
+    [interpnd.CloughTocher2DInterpolator, interpnd.LinearNDInterpolator]
+)
+def test_reproduction_NaN_on_points_linear_combination(
+    simplex_tolerance, interpolator_factory
+):
+    """Test that SciPy can interpolate to the edge of a triangle.
+
+    Based on gh-22831
+    """
+    inputs = np.array([[ 0.       ,  0.       ],
+                      [ 0.       ,  0.008016],
+                      [ 3.       , -2.       ]])
+    values = np.ones(len(inputs))
+    # Create the interpolator
+    interpolator = interpolator_factory(inputs, values)
+    t1 = 0.6
+    p1 = inputs[0]
+    p2 = inputs[2]
+    point_on_edge = p1 + t1 * (p2 - p1)
+    value = interpolator(*point_on_edge, simplex_tolerance=simplex_tolerance)
+    if simplex_tolerance == 1:
+        assert np.isnan(value)
+    else:
+        assert np.isfinite(value)
+
+@pytest.mark.parametrize("simplex_tolerance", [1, 10])
+@pytest.mark.parametrize(
+    "interpolator_factory",
+    [interpnd.CloughTocher2DInterpolator, interpnd.LinearNDInterpolator]
+)
+def test_reproduction_NaN_on_input_points(
+        simplex_tolerance, interpolator_factory
+):
+    """Test that SciPy can interpolate to the input points.
+
+    Based on gh-21279.
+    Should probably be generalized to a hypothesis test.
+    """
+    inputs = np.array([[-0.004167550182114899, 0.3422659245670766],
+                       [-0.0015600025635140293, 0.2293516674374961],
+                       [-0.0014546640482194341, 0.22508674815327132],
+                       [-0.0014520968885052055, 0.2212277697065949]])
+    values = np.ones_like(inputs[:, 0])
+    interpolator = interpolator_factory(inputs, values)
+    results = interpolator(inputs, simplex_tolerance=simplex_tolerance)
+    if simplex_tolerance == 1:
+        assert np.any(np.isnan(results))
+    else:
+        assert np.all(np.isfinite(results))
diff --git a/.venv/lib/python3.12/site-packages/scipy/interpolate/tests/test_interpolate.py b/.venv/lib/python3.12/site-packages/scipy/interpolate/tests/test_interpolate.py
new file mode 100644
index 0000000000000000000000000000000000000000..3476060d2f5fbcb5415beb6a3a7f5ea71c9396d4
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/interpolate/tests/test_interpolate.py
@@ -0,0 +1,2851 @@
+import pickle
+
+from scipy._lib._array_api import (
+    xp_assert_equal, xp_assert_close, assert_almost_equal, assert_array_almost_equal,
+    make_xp_test_case, is_cupy, _xp_copy_to_numpy
+)
+from scipy._external import array_api_extra as xpx
+from pytest import raises as assert_raises
+import pytest
+
+from numpy import mgrid, pi, sin, poly1d
+import numpy as np
+
+from scipy.interpolate import (interp1d, interp2d, lagrange, PPoly, BPoly,
+        splrep, splev, splantider, splint, sproot, Akima1DInterpolator,
+        NdPPoly, BSpline, PchipInterpolator, make_interp_spline, CubicSpline,
+        FloaterHormannInterpolator, BarycentricInterpolator, KroghInterpolator,
+        CubicHermiteSpline, LinearNDInterpolator, NearestNDInterpolator,
+        CloughTocher2DInterpolator, RBFInterpolator, RegularGridInterpolator)
+
+from scipy.special import poch, gamma
+
+from scipy.interpolate import _ppoly
+
+from scipy._lib._gcutils import assert_deallocated
+from scipy._lib._testutils import _run_concurrent_barrier
+
+from scipy.integrate import nquad
+
+from scipy.special import binom
+
+skip_xp_backends = pytest.mark.skip_xp_backends
+xfail_xp_backends = pytest.mark.xfail_xp_backends
+
+
+class TestInterp2D:
+    def test_interp2d(self):
+        y, x = mgrid[0:2:20j, 0:pi:21j]
+        z = sin(x+0.5*y)
+        with assert_raises(NotImplementedError):
+            interp2d(x, y, z)
+
+
+class TestInterp1D:
+
+    def setup_method(self):
+        self.x5 = np.arange(5.)
+        self.x10 = np.arange(10.)
+        self.y10 = np.arange(10.)
+        self.x25 = self.x10.reshape((2,5))
+        self.x2 = np.arange(2.)
+        self.y2 = np.arange(2.)
+        self.x1 = np.array([0.])
+        self.y1 = np.array([0.])
+
+        self.y210 = np.arange(20.).reshape((2, 10))
+        self.y102 = np.arange(20.).reshape((10, 2))
+        self.y225 = np.arange(20.).reshape((2, 2, 5))
+        self.y25 = np.arange(10.).reshape((2, 5))
+        self.y235 = np.arange(30.).reshape((2, 3, 5))
+        self.y325 = np.arange(30.).reshape((3, 2, 5))
+
+        # Edge updated test matrix 1
+        # array([[ 30,   1,   2,   3,   4,   5,   6,   7,   8, -30],
+        #        [ 30,  11,  12,  13,  14,  15,  16,  17,  18, -30]])
+        self.y210_edge_updated = np.arange(20.).reshape((2, 10))
+        self.y210_edge_updated[:, 0] = 30
+        self.y210_edge_updated[:, -1] = -30
+
+        # Edge updated test matrix 2
+        # array([[ 30,  30],
+        #       [  2,   3],
+        #       [  4,   5],
+        #       [  6,   7],
+        #       [  8,   9],
+        #       [ 10,  11],
+        #       [ 12,  13],
+        #       [ 14,  15],
+        #       [ 16,  17],
+        #       [-30, -30]])
+        self.y102_edge_updated = np.arange(20.).reshape((10, 2))
+        self.y102_edge_updated[0, :] = 30
+        self.y102_edge_updated[-1, :] = -30
+
+        self.fill_value = -100.0
+
+    def test_validation(self):
+        # Make sure that appropriate exceptions are raised when invalid values
+        # are given to the constructor.
+
+        # These should all work.
+        for kind in ('nearest', 'nearest-up', 'zero', 'linear', 'slinear',
+                     'quadratic', 'cubic', 'previous', 'next'):
+            interp1d(self.x10, self.y10, kind=kind)
+            interp1d(self.x10, self.y10, kind=kind, fill_value="extrapolate")
+        interp1d(self.x10, self.y10, kind='linear', fill_value=(-1, 1))
+        interp1d(self.x10, self.y10, kind='linear',
+                 fill_value=np.array([-1]))
+        interp1d(self.x10, self.y10, kind='linear',
+                 fill_value=(-1,))
+        interp1d(self.x10, self.y10, kind='linear',
+                 fill_value=-1)
+        interp1d(self.x10, self.y10, kind='linear',
+                 fill_value=(-1, -1))
+        interp1d(self.x10, self.y10, kind=0)
+        interp1d(self.x10, self.y10, kind=1)
+        interp1d(self.x10, self.y10, kind=2)
+        interp1d(self.x10, self.y10, kind=3)
+        interp1d(self.x10, self.y210, kind='linear', axis=-1,
+                 fill_value=(-1, -1))
+        interp1d(self.x2, self.y210, kind='linear', axis=0,
+                 fill_value=np.ones(10))
+        interp1d(self.x2, self.y210, kind='linear', axis=0,
+                 fill_value=(np.ones(10), np.ones(10)))
+        interp1d(self.x2, self.y210, kind='linear', axis=0,
+                 fill_value=(np.ones(10), -1))
+
+        # x array must be 1D.
+        assert_raises(ValueError, interp1d, self.x25, self.y10)
+
+        # y array cannot be a scalar.
+        assert_raises(ValueError, interp1d, self.x10, np.array(0))
+
+        # Check for x and y arrays having the same length.
+        assert_raises(ValueError, interp1d, self.x10, self.y2)
+        assert_raises(ValueError, interp1d, self.x2, self.y10)
+        assert_raises(ValueError, interp1d, self.x10, self.y102)
+        interp1d(self.x10, self.y210)
+        interp1d(self.x10, self.y102, axis=0)
+
+        # Check for x and y having at least 1 element.
+        assert_raises(ValueError, interp1d, self.x1, self.y10)
+        assert_raises(ValueError, interp1d, self.x10, self.y1)
+
+        # Bad fill values
+        assert_raises(ValueError, interp1d, self.x10, self.y10, kind='linear',
+                      fill_value=(-1, -1, -1))  # doesn't broadcast
+        assert_raises(ValueError, interp1d, self.x10, self.y10, kind='linear',
+                      fill_value=[-1, -1, -1])  # doesn't broadcast
+        assert_raises(ValueError, interp1d, self.x10, self.y10, kind='linear',
+                      fill_value=np.array((-1, -1, -1)))  # doesn't broadcast
+        assert_raises(ValueError, interp1d, self.x10, self.y10, kind='linear',
+                      fill_value=[[-1]])  # doesn't broadcast
+        assert_raises(ValueError, interp1d, self.x10, self.y10, kind='linear',
+                      fill_value=[-1, -1])  # doesn't broadcast
+        assert_raises(ValueError, interp1d, self.x10, self.y10, kind='linear',
+                      fill_value=np.array([]))  # doesn't broadcast
+        assert_raises(ValueError, interp1d, self.x10, self.y10, kind='linear',
+                      fill_value=())  # doesn't broadcast
+        assert_raises(ValueError, interp1d, self.x2, self.y210, kind='linear',
+                      axis=0, fill_value=[-1, -1])  # doesn't broadcast
+        assert_raises(ValueError, interp1d, self.x2, self.y210, kind='linear',
+                      axis=0, fill_value=(0., [-1, -1]))  # above doesn't bc
+
+    def test_init(self):
+        # Check that the attributes are initialized appropriately by the
+        # constructor.
+        assert interp1d(self.x10, self.y10).copy
+        assert not interp1d(self.x10, self.y10, copy=False).copy
+        assert interp1d(self.x10, self.y10).bounds_error
+        assert not interp1d(self.x10, self.y10, bounds_error=False).bounds_error
+        assert np.isnan(interp1d(self.x10, self.y10).fill_value)
+        assert interp1d(self.x10, self.y10, fill_value=3.0).fill_value == 3.0
+        assert (interp1d(self.x10, self.y10, fill_value=(1.0, 2.0)).fill_value ==
+                (1.0, 2.0)
+        )
+        assert interp1d(self.x10, self.y10).axis == 0
+        assert interp1d(self.x10, self.y210).axis == 1
+        assert interp1d(self.x10, self.y102, axis=0).axis == 0
+        xp_assert_equal(interp1d(self.x10, self.y10).x, self.x10)
+        xp_assert_equal(interp1d(self.x10, self.y10).y, self.y10)
+        xp_assert_equal(interp1d(self.x10, self.y210).y, self.y210)
+
+    def test_assume_sorted(self):
+        # Check for unsorted arrays
+        interp10 = interp1d(self.x10, self.y10)
+        interp10_unsorted = interp1d(self.x10[::-1], self.y10[::-1])
+
+        assert_array_almost_equal(interp10_unsorted(self.x10), self.y10)
+        assert_array_almost_equal(interp10_unsorted(1.2), np.array(1.2))
+        assert_array_almost_equal(interp10_unsorted([2.4, 5.6, 6.0]),
+                                  interp10([2.4, 5.6, 6.0]))
+
+        # Check assume_sorted keyword (defaults to False)
+        interp10_assume_kw = interp1d(self.x10[::-1], self.y10[::-1],
+                                      assume_sorted=False)
+        assert_array_almost_equal(interp10_assume_kw(self.x10), self.y10)
+
+        interp10_assume_kw2 = interp1d(self.x10[::-1], self.y10[::-1],
+                                       assume_sorted=True)
+        # Should raise an error for unsorted input if assume_sorted=True
+        assert_raises(ValueError, interp10_assume_kw2, self.x10)
+
+        # Check that if y is a 2-D array, things are still consistent
+        interp10_y_2d = interp1d(self.x10, self.y210)
+        interp10_y_2d_unsorted = interp1d(self.x10[::-1], self.y210[:, ::-1])
+        assert_array_almost_equal(interp10_y_2d(self.x10),
+                                  interp10_y_2d_unsorted(self.x10))
+
+    def test_linear(self):
+        for kind in ['linear', 'slinear']:
+            self._check_linear(kind)
+
+    def _check_linear(self, kind):
+        # Check the actual implementation of linear interpolation.
+        interp10 = interp1d(self.x10, self.y10, kind=kind)
+        assert_array_almost_equal(interp10(self.x10), self.y10)
+        assert_array_almost_equal(interp10(1.2), np.array(1.2))
+        assert_array_almost_equal(interp10([2.4, 5.6, 6.0]),
+                                  np.array([2.4, 5.6, 6.0]))
+
+        # test fill_value="extrapolate"
+        extrapolator = interp1d(self.x10, self.y10, kind=kind,
+                                fill_value='extrapolate')
+        xp_assert_close(extrapolator([-1., 0, 9, 11]),
+                        np.asarray([-1.0, 0, 9, 11]), rtol=1e-14)
+
+        opts = dict(kind=kind,
+                    fill_value='extrapolate',
+                    bounds_error=True)
+        assert_raises(ValueError, interp1d, self.x10, self.y10, **opts)
+
+    def test_linear_dtypes(self):
+        # regression test for gh-5898, where 1D linear interpolation has been
+        # delegated to numpy.interp for all float dtypes, and the latter was
+        # not handling e.g. np.float128.
+        for dtyp in [np.float16,
+                     np.float32,
+                     np.float64,
+                     np.longdouble]:
+            x = np.arange(8, dtype=dtyp)
+            y = x
+            yp = interp1d(x, y, kind='linear')(x)
+            assert yp.dtype == dtyp
+            xp_assert_close(yp, y, atol=1e-15)
+
+        # regression test for gh-14531, where 1D linear interpolation has been
+        # has been extended to delegate to numpy.interp for integer dtypes
+        x = [0, 1, 2]
+        y = [np.nan, 0, 1]
+        yp = interp1d(x, y)(x)
+        xp_assert_close(yp, y, atol=1e-15)
+
+    def test_linear_numerical_stability(self):
+        # regression test for gh-24281: Using de Boor's algorithm, there 
+        # should be no floating point error for query points contained 
+        # exactly in the x input array
+        x = np.array([0.0007499999999999, 0.002])
+        y = np.array([[0.0, 0.0], [0.0004164930555555557, 0.0]])
+        yp = interp1d(x, y)(x)
+        xp_assert_close(yp, y, atol=1e-20)
+        assert np.all(yp >= 0) # less stable computations give yp[1,1] = -5e-20
+
+    def test_slinear_dtypes(self):
+        # regression test for gh-7273: 1D slinear interpolation fails with
+        # float32 inputs
+        dt_r = [np.float16, np.float32, np.float64]
+        dt_rc = dt_r + [np.complex64, np.complex128]
+        spline_kinds = ['slinear', 'zero', 'quadratic', 'cubic']
+        for dtx in dt_r:
+            x = np.arange(0, 10, dtype=dtx)
+            for dty in dt_rc:
+                y = np.exp(-x/3.0).astype(dty)
+                for dtn in dt_r:
+                    xnew = x.astype(dtn)
+                    for kind in spline_kinds:
+                        f = interp1d(x, y, kind=kind, bounds_error=False)
+                        xp_assert_close(f(xnew), y, atol=1e-7,
+                                        check_dtype=False,
+                                        err_msg=f"{dtx}, {dty} {dtn}")
+
+    def test_cubic(self):
+        # Check the actual implementation of spline interpolation.
+        interp10 = interp1d(self.x10, self.y10, kind='cubic')
+        assert_array_almost_equal(interp10(self.x10), self.y10)
+        assert_array_almost_equal(interp10(1.2), np.array(1.2))
+        assert_array_almost_equal(interp10(1.5), np.array(1.5))
+        assert_array_almost_equal(interp10([2.4, 5.6, 6.0]),
+                                  np.array([2.4, 5.6, 6.0]),)
+
+    def test_nearest(self):
+        # Check the actual implementation of nearest-neighbour interpolation.
+        # Nearest asserts that half-integer case (1.5) rounds down to 1
+        interp10 = interp1d(self.x10, self.y10, kind='nearest')
+        assert_array_almost_equal(interp10(self.x10), self.y10)
+        assert_array_almost_equal(interp10(1.2), np.array(1.))
+        assert_array_almost_equal(interp10(1.5), np.array(1.))
+        assert_array_almost_equal(interp10([2.4, 5.6, 6.0]),
+                                  np.array([2., 6., 6.]),)
+
+        # test fill_value="extrapolate"
+        extrapolator = interp1d(self.x10, self.y10, kind='nearest',
+                                fill_value='extrapolate')
+        xp_assert_close(extrapolator([-1., 0, 9, 11]),
+                        [0.0, 0, 9, 9], rtol=1e-14)
+
+        opts = dict(kind='nearest',
+                    fill_value='extrapolate',
+                    bounds_error=True)
+        assert_raises(ValueError, interp1d, self.x10, self.y10, **opts)
+
+    def test_nearest_up(self):
+        # Check the actual implementation of nearest-neighbour interpolation.
+        # Nearest-up asserts that half-integer case (1.5) rounds up to 2
+        interp10 = interp1d(self.x10, self.y10, kind='nearest-up')
+        assert_array_almost_equal(interp10(self.x10), self.y10)
+        assert_array_almost_equal(interp10(1.2), np.array(1.))
+        assert_array_almost_equal(interp10(1.5), np.array(2.))
+        assert_array_almost_equal(interp10([2.4, 5.6, 6.0]),
+                                  np.array([2., 6., 6.]),)
+
+        # test fill_value="extrapolate"
+        extrapolator = interp1d(self.x10, self.y10, kind='nearest-up',
+                                fill_value='extrapolate')
+        xp_assert_close(extrapolator([-1., 0, 9, 11]),
+                        [0.0, 0, 9, 9], rtol=1e-14)
+
+        opts = dict(kind='nearest-up',
+                    fill_value='extrapolate',
+                    bounds_error=True)
+        assert_raises(ValueError, interp1d, self.x10, self.y10, **opts)
+
+    def test_previous(self):
+        # Check the actual implementation of previous interpolation.
+        interp10 = interp1d(self.x10, self.y10, kind='previous')
+        assert_array_almost_equal(interp10(self.x10), self.y10)
+        assert_array_almost_equal(interp10(1.2), np.array(1.))
+        assert_array_almost_equal(interp10(1.5), np.array(1.))
+        assert_array_almost_equal(interp10([2.4, 5.6, 6.0]),
+                                  np.array([2., 5., 6.]),)
+
+        # test fill_value="extrapolate"
+        extrapolator = interp1d(self.x10, self.y10, kind='previous',
+                                fill_value='extrapolate')
+        xp_assert_close(extrapolator([-1., 0, 9, 11]),
+                        [np.nan, 0, 9, 9], rtol=1e-14)
+
+        # Tests for gh-9591
+        interpolator1D = interp1d(self.x10, self.y10, kind="previous",
+                                  fill_value='extrapolate')
+        xp_assert_close(interpolator1D([-1, -2, 5, 8, 12, 25]),
+                        [np.nan, np.nan, 5, 8, 9, 9])
+
+        interpolator2D = interp1d(self.x10, self.y210, kind="previous",
+                                  fill_value='extrapolate')
+        xp_assert_close(interpolator2D([-1, -2, 5, 8, 12, 25]),
+                        [[np.nan, np.nan, 5, 8, 9, 9],
+                         [np.nan, np.nan, 15, 18, 19, 19]])
+
+        interpolator2DAxis0 = interp1d(self.x10, self.y102, kind="previous",
+                                       axis=0, fill_value='extrapolate')
+        xp_assert_close(interpolator2DAxis0([-2, 5, 12]),
+                        [[np.nan, np.nan],
+                         [10, 11],
+                         [18, 19]])
+
+        opts = dict(kind='previous',
+                    fill_value='extrapolate',
+                    bounds_error=True)
+        assert_raises(ValueError, interp1d, self.x10, self.y10, **opts)
+
+        # Tests for gh-16813
+        interpolator1D = interp1d([0, 1, 2],
+                                  [0, 1, -1], kind="previous",
+                                  fill_value='extrapolate',
+                                  assume_sorted=True)
+        xp_assert_close(interpolator1D([-2, -1, 0, 1, 2, 3, 5]),
+                        [np.nan, np.nan, 0, 1, -1, -1, -1])
+
+        interpolator1D = interp1d([2, 0, 1],  # x is not ascending
+                                  [-1, 0, 1], kind="previous",
+                                  fill_value='extrapolate',
+                                  assume_sorted=False)
+        xp_assert_close(interpolator1D([-2, -1, 0, 1, 2, 3, 5]),
+                        [np.nan, np.nan, 0, 1, -1, -1, -1])
+
+        interpolator2D = interp1d(self.x10, self.y210_edge_updated,
+                                  kind="previous",
+                                  fill_value='extrapolate')
+        xp_assert_close(interpolator2D([-1, -2, 5, 8, 12, 25]),
+                        [[np.nan, np.nan, 5, 8, -30, -30],
+                         [np.nan, np.nan, 15, 18, -30, -30]])
+
+        interpolator2DAxis0 = interp1d(self.x10, self.y102_edge_updated,
+                                       kind="previous",
+                                       axis=0, fill_value='extrapolate')
+        xp_assert_close(interpolator2DAxis0([-2, 5, 12]),
+                        [[np.nan, np.nan],
+                         [10, 11],
+                         [-30, -30]])
+
+    def test_next(self):
+        # Check the actual implementation of next interpolation.
+        interp10 = interp1d(self.x10, self.y10, kind='next')
+        assert_array_almost_equal(interp10(self.x10), self.y10)
+        assert_array_almost_equal(interp10(1.2), np.array(2.))
+        assert_array_almost_equal(interp10(1.5), np.array(2.))
+        assert_array_almost_equal(interp10([2.4, 5.6, 6.0]),
+                                  np.array([3., 6., 6.]),)
+
+        # test fill_value="extrapolate"
+        extrapolator = interp1d(self.x10, self.y10, kind='next',
+                                fill_value='extrapolate')
+        xp_assert_close(extrapolator([-1., 0, 9, 11]),
+                        [0, 0, 9, np.nan], rtol=1e-14)
+
+        # Tests for gh-9591
+        interpolator1D = interp1d(self.x10, self.y10, kind="next",
+                                  fill_value='extrapolate')
+        xp_assert_close(interpolator1D([-1, -2, 5, 8, 12, 25]),
+                        [0, 0, 5, 8, np.nan, np.nan])
+
+        interpolator2D = interp1d(self.x10, self.y210, kind="next",
+                                  fill_value='extrapolate')
+        xp_assert_close(interpolator2D([-1, -2, 5, 8, 12, 25]),
+                        [[0, 0, 5, 8, np.nan, np.nan],
+                         [10, 10, 15, 18, np.nan, np.nan]])
+
+        interpolator2DAxis0 = interp1d(self.x10, self.y102, kind="next",
+                                       axis=0, fill_value='extrapolate')
+        xp_assert_close(interpolator2DAxis0([-2, 5, 12]),
+                        [[0, 1],
+                         [10, 11],
+                         [np.nan, np.nan]])
+
+        opts = dict(kind='next',
+                    fill_value='extrapolate',
+                    bounds_error=True)
+        assert_raises(ValueError, interp1d, self.x10, self.y10, **opts)
+
+        # Tests for gh-16813
+        interpolator1D = interp1d([0, 1, 2],
+                                  [0, 1, -1], kind="next",
+                                  fill_value='extrapolate',
+                                  assume_sorted=True)
+        xp_assert_close(interpolator1D([-2, -1, 0, 1, 2, 3, 5]),
+                        [0, 0, 0, 1, -1, np.nan, np.nan])
+
+        interpolator1D = interp1d([2, 0, 1],  # x is not ascending
+                                  [-1, 0, 1], kind="next",
+                                  fill_value='extrapolate',
+                                  assume_sorted=False)
+        xp_assert_close(interpolator1D([-2, -1, 0, 1, 2, 3, 5]),
+                        [0, 0, 0, 1, -1, np.nan, np.nan])
+
+        interpolator2D = interp1d(self.x10, self.y210_edge_updated,
+                                  kind="next",
+                                  fill_value='extrapolate')
+        xp_assert_close(interpolator2D([-1, -2, 5, 8, 12, 25]),
+                        [[30, 30, 5, 8, np.nan, np.nan],
+                         [30, 30, 15, 18, np.nan, np.nan]])
+
+        interpolator2DAxis0 = interp1d(self.x10, self.y102_edge_updated,
+                                       kind="next",
+                                       axis=0, fill_value='extrapolate')
+        xp_assert_close(interpolator2DAxis0([-2, 5, 12]),
+                        [[30, 30],
+                         [10, 11],
+                         [np.nan, np.nan]])
+
+    def test_zero(self):
+        # Check the actual implementation of zero-order spline interpolation.
+        interp10 = interp1d(self.x10, self.y10, kind='zero')
+        assert_array_almost_equal(interp10(self.x10), self.y10)
+        assert_array_almost_equal(interp10(1.2), np.array(1.))
+        assert_array_almost_equal(interp10(1.5), np.array(1.))
+        assert_array_almost_equal(interp10([2.4, 5.6, 6.0]),
+                                  np.array([2., 5., 6.]))
+
+    def bounds_check_helper(self, interpolant, test_array, fail_value):
+        # Asserts that a ValueError is raised and that the error message
+        # contains the value causing this exception.
+        assert_raises(ValueError, interpolant, test_array)
+        try:
+            interpolant(test_array)
+        except ValueError as err:
+            assert (f"{fail_value}" in str(err))
+
+    def _bounds_check(self, kind='linear'):
+        # Test that our handling of out-of-bounds input is correct.
+        extrap10 = interp1d(self.x10, self.y10, fill_value=self.fill_value,
+                            bounds_error=False, kind=kind)
+
+        xp_assert_equal(extrap10(11.2), np.array(self.fill_value))
+        xp_assert_equal(extrap10(-3.4), np.array(self.fill_value))
+        xp_assert_equal(extrap10([[[11.2], [-3.4], [12.6], [19.3]]]),
+                           np.array(self.fill_value), check_shape=False)
+        xp_assert_equal(extrap10._check_bounds(
+                               np.array([-1.0, 0.0, 5.0, 9.0, 11.0])),
+                           np.array([[True, False, False, False, False],
+                                     [False, False, False, False, True]]))
+
+        raises_bounds_error = interp1d(self.x10, self.y10, bounds_error=True,
+                                       kind=kind)
+
+        self.bounds_check_helper(raises_bounds_error, -1.0, -1.0)
+        self.bounds_check_helper(raises_bounds_error, 11.0, 11.0)
+        self.bounds_check_helper(raises_bounds_error, [0.0, -1.0, 0.0], -1.0)
+        self.bounds_check_helper(raises_bounds_error, [0.0, 1.0, 21.0], 21.0)
+
+        raises_bounds_error([0.0, 5.0, 9.0])
+
+    def _bounds_check_int_nan_fill(self, kind='linear'):
+        x = np.arange(10).astype(int)
+        y = np.arange(10).astype(int)
+        c = interp1d(x, y, kind=kind, fill_value=np.nan, bounds_error=False)
+        yi = c(x - 1)
+        assert np.isnan(yi[0])
+        assert_array_almost_equal(yi, np.r_[np.nan, y[:-1]])
+
+    def test_bounds(self):
+        for kind in ('linear', 'cubic', 'nearest', 'previous', 'next',
+                     'slinear', 'zero', 'quadratic'):
+            self._bounds_check(kind)
+            self._bounds_check_int_nan_fill(kind)
+
+    def _check_fill_value(self, kind):
+        interp = interp1d(self.x10, self.y10, kind=kind,
+                          fill_value=(-100, 100), bounds_error=False)
+        assert_array_almost_equal(interp(10), np.asarray(100.))
+        assert_array_almost_equal(interp(-10), np.asarray(-100.))
+        assert_array_almost_equal(interp([-10, 10]), [-100, 100])
+
+        # Proper broadcasting:
+        #    interp along axis of length 5
+        # other dim=(2, 3), (3, 2), (2, 2), or (2,)
+
+        # one singleton fill_value (works for all)
+        for y in (self.y235, self.y325, self.y225, self.y25):
+            interp = interp1d(self.x5, y, kind=kind, axis=-1,
+                              fill_value=100, bounds_error=False)
+            assert_array_almost_equal(interp(10), np.asarray(100.))
+            assert_array_almost_equal(interp(-10), np.asarray(100.))
+            assert_array_almost_equal(interp([-10, 10]), np.asarray(100.))
+
+            # singleton lower, singleton upper
+            interp = interp1d(self.x5, y, kind=kind, axis=-1,
+                              fill_value=(-100, 100), bounds_error=False)
+            assert_array_almost_equal(interp(10), np.asarray(100.))
+            assert_array_almost_equal(interp(-10), np.asarray(-100.))
+            if y.ndim == 3:
+                result = [[[-100, 100]] * y.shape[1]] * y.shape[0]
+            else:
+                result = [[-100, 100]] * y.shape[0]
+            assert_array_almost_equal(interp([-10, 10]), result)
+
+        # one broadcastable (3,) fill_value
+        fill_value = [100, 200, 300]
+        for y in (self.y325, self.y225):
+            assert_raises(ValueError, interp1d, self.x5, y, kind=kind,
+                          axis=-1, fill_value=fill_value, bounds_error=False)
+        interp = interp1d(self.x5, self.y235, kind=kind, axis=-1,
+                          fill_value=fill_value, bounds_error=False)
+        assert_array_almost_equal(interp(10), [[100, 200, 300]] * 2)
+        assert_array_almost_equal(interp(-10), [[100, 200, 300]] * 2)
+        assert_array_almost_equal(interp([-10, 10]), [[[100, 100],
+                                                       [200, 200],
+                                                       [300, 300]]] * 2)
+
+        # one broadcastable (2,) fill_value
+        fill_value = [100, 200]
+        assert_raises(ValueError, interp1d, self.x5, self.y235, kind=kind,
+                      axis=-1, fill_value=fill_value, bounds_error=False)
+        for y in (self.y225, self.y325, self.y25):
+            interp = interp1d(self.x5, y, kind=kind, axis=-1,
+                              fill_value=fill_value, bounds_error=False)
+            result = [100, 200]
+            if y.ndim == 3:
+                result = [result] * y.shape[0]
+            assert_array_almost_equal(interp(10), result)
+            assert_array_almost_equal(interp(-10), result)
+            result = [[100, 100], [200, 200]]
+            if y.ndim == 3:
+                result = [result] * y.shape[0]
+            assert_array_almost_equal(interp([-10, 10]), result)
+
+        # broadcastable (3,) lower, singleton upper
+        fill_value = (np.array([-100, -200, -300]), 100)
+        for y in (self.y325, self.y225):
+            assert_raises(ValueError, interp1d, self.x5, y, kind=kind,
+                          axis=-1, fill_value=fill_value, bounds_error=False)
+        interp = interp1d(self.x5, self.y235, kind=kind, axis=-1,
+                          fill_value=fill_value, bounds_error=False)
+        assert_array_almost_equal(interp(10), np.asarray(100.))
+        assert_array_almost_equal(interp(-10), [[-100, -200, -300]] * 2)
+        assert_array_almost_equal(interp([-10, 10]), [[[-100, 100],
+                                                       [-200, 100],
+                                                       [-300, 100]]] * 2)
+
+        # broadcastable (2,) lower, singleton upper
+        fill_value = (np.array([-100, -200]), 100)
+        assert_raises(ValueError, interp1d, self.x5, self.y235, kind=kind,
+                      axis=-1, fill_value=fill_value, bounds_error=False)
+        for y in (self.y225, self.y325, self.y25):
+            interp = interp1d(self.x5, y, kind=kind, axis=-1,
+                              fill_value=fill_value, bounds_error=False)
+            assert_array_almost_equal(interp(10), np.asarray(100))
+            result = [-100, -200]
+            if y.ndim == 3:
+                result = [result] * y.shape[0]
+            assert_array_almost_equal(interp(-10), result)
+            result = [[-100, 100], [-200, 100]]
+            if y.ndim == 3:
+                result = [result] * y.shape[0]
+            assert_array_almost_equal(interp([-10, 10]), result)
+
+        # broadcastable (3,) lower, broadcastable (3,) upper
+        fill_value = ([-100, -200, -300], [100, 200, 300])
+        for y in (self.y325, self.y225):
+            assert_raises(ValueError, interp1d, self.x5, y, kind=kind,
+                          axis=-1, fill_value=fill_value, bounds_error=False)
+        for ii in range(2):  # check ndarray as well as list here
+            if ii == 1:
+                fill_value = tuple(np.array(f) for f in fill_value)
+            interp = interp1d(self.x5, self.y235, kind=kind, axis=-1,
+                              fill_value=fill_value, bounds_error=False)
+            assert_array_almost_equal(interp(10), [[100, 200, 300]] * 2)
+            assert_array_almost_equal(interp(-10), [[-100, -200, -300]] * 2)
+            assert_array_almost_equal(interp([-10, 10]), [[[-100, 100],
+                                                           [-200, 200],
+                                                           [-300, 300]]] * 2)
+        # broadcastable (2,) lower, broadcastable (2,) upper
+        fill_value = ([-100, -200], [100, 200])
+        assert_raises(ValueError, interp1d, self.x5, self.y235, kind=kind,
+                      axis=-1, fill_value=fill_value, bounds_error=False)
+        for y in (self.y325, self.y225, self.y25):
+            interp = interp1d(self.x5, y, kind=kind, axis=-1,
+                              fill_value=fill_value, bounds_error=False)
+            result = [100, 200]
+            if y.ndim == 3:
+                result = [result] * y.shape[0]
+            assert_array_almost_equal(interp(10), result)
+            result = [-100, -200]
+            if y.ndim == 3:
+                result = [result] * y.shape[0]
+            assert_array_almost_equal(interp(-10), result)
+            result = [[-100, 100], [-200, 200]]
+            if y.ndim == 3:
+                result = [result] * y.shape[0]
+            assert_array_almost_equal(interp([-10, 10]), result)
+
+        # one broadcastable (2, 2) array-like
+        fill_value = [[100, 200], [1000, 2000]]
+        for y in (self.y235, self.y325, self.y25):
+            assert_raises(ValueError, interp1d, self.x5, y, kind=kind,
+                          axis=-1, fill_value=fill_value, bounds_error=False)
+        for ii in range(2):
+            if ii == 1:
+                fill_value = np.array(fill_value)
+            interp = interp1d(self.x5, self.y225, kind=kind, axis=-1,
+                              fill_value=fill_value, bounds_error=False)
+            assert_array_almost_equal(interp(10), [[100, 200], [1000, 2000]])
+            assert_array_almost_equal(interp(-10), [[100, 200], [1000, 2000]])
+            assert_array_almost_equal(interp([-10, 10]), [[[100, 100],
+                                                           [200, 200]],
+                                                          [[1000, 1000],
+                                                           [2000, 2000]]])
+
+        # broadcastable (2, 2) lower, broadcastable (2, 2) upper
+        fill_value = ([[-100, -200], [-1000, -2000]],
+                      [[100, 200], [1000, 2000]])
+        for y in (self.y235, self.y325, self.y25):
+            assert_raises(ValueError, interp1d, self.x5, y, kind=kind,
+                          axis=-1, fill_value=fill_value, bounds_error=False)
+        for ii in range(2):
+            if ii == 1:
+                fill_value = (np.array(fill_value[0]), np.array(fill_value[1]))
+            interp = interp1d(self.x5, self.y225, kind=kind, axis=-1,
+                              fill_value=fill_value, bounds_error=False)
+            assert_array_almost_equal(interp(10), [[100, 200], [1000, 2000]])
+            assert_array_almost_equal(interp(-10), [[-100, -200],
+                                                    [-1000, -2000]])
+            assert_array_almost_equal(interp([-10, 10]), [[[-100, 100],
+                                                           [-200, 200]],
+                                                          [[-1000, 1000],
+                                                           [-2000, 2000]]])
+
+    def test_fill_value(self):
+        # test that two-element fill value works
+        for kind in ('linear', 'nearest', 'cubic', 'slinear', 'quadratic',
+                     'zero', 'previous', 'next'):
+            self._check_fill_value(kind)
+
+    def test_fill_value_writeable(self):
+        # backwards compat: fill_value is a public writeable attribute
+        interp = interp1d(self.x10, self.y10, fill_value=123.0)
+        assert interp.fill_value == 123.0
+        interp.fill_value = 321.0
+        assert interp.fill_value == 321.0
+
+    def _nd_check_interp(self, kind='linear'):
+        # Check the behavior when the inputs and outputs are multidimensional.
+
+        # Multidimensional input.
+        interp10 = interp1d(self.x10, self.y10, kind=kind)
+        assert_array_almost_equal(interp10(np.array([[3., 5.], [2., 7.]])),
+                                  np.array([[3., 5.], [2., 7.]]))
+
+        # Scalar input -> 0-dim scalar array output
+        assert isinstance(interp10(1.2), np.ndarray)
+        assert interp10(1.2).shape == ()
+
+        # Multidimensional outputs.
+        interp210 = interp1d(self.x10, self.y210, kind=kind)
+        assert_array_almost_equal(interp210(1.), np.array([1., 11.]))
+        assert_array_almost_equal(interp210(np.array([1., 2.])),
+                                  np.array([[1., 2.], [11., 12.]]))
+
+        interp102 = interp1d(self.x10, self.y102, axis=0, kind=kind)
+        assert_array_almost_equal(interp102(1.), np.array([2.0, 3.0]))
+        assert_array_almost_equal(interp102(np.array([1., 3.])),
+                                  np.array([[2., 3.], [6., 7.]]))
+
+        # Both at the same time!
+        x_new = np.array([[3., 5.], [2., 7.]])
+        assert_array_almost_equal(interp210(x_new),
+                                  np.array([[[3., 5.], [2., 7.]],
+                                            [[13., 15.], [12., 17.]]]))
+        assert_array_almost_equal(interp102(x_new),
+                                  np.array([[[6., 7.], [10., 11.]],
+                                            [[4., 5.], [14., 15.]]]))
+
+    def _nd_check_shape(self, kind='linear'):
+        # Check large N-D output shape
+        a = [4, 5, 6, 7]
+        y = np.arange(np.prod(a)).reshape(*a)
+        for n, s in enumerate(a):
+            x = np.arange(s)
+            z = interp1d(x, y, axis=n, kind=kind)
+            assert_array_almost_equal(z(x), y, err_msg=kind)
+
+            x2 = np.arange(2*3*1).reshape((2,3,1)) / 12.
+            b = list(a)
+            b[n:n+1] = [2, 3, 1]
+            assert z(x2).shape == tuple(b), kind
+
+    def test_nd(self):
+        for kind in ('linear', 'cubic', 'slinear', 'quadratic', 'nearest',
+                     'zero', 'previous', 'next'):
+            self._nd_check_interp(kind)
+            self._nd_check_shape(kind)
+
+    def _check_complex(self, dtype=np.complex128, kind='linear'):
+        x = np.array([1, 2.5, 3, 3.1, 4, 6.4, 7.9, 8.0, 9.5, 10])
+        y = x * x ** (1 + 2j)
+        y = y.astype(dtype)
+
+        # simple test
+        c = interp1d(x, y, kind=kind)
+        assert_array_almost_equal(y[:-1], c(x)[:-1])
+
+        # check against interpolating real+imag separately
+        xi = np.linspace(1, 10, 31)
+        cr = interp1d(x, y.real, kind=kind)
+        ci = interp1d(x, y.imag, kind=kind)
+        assert_array_almost_equal(c(xi).real, cr(xi))
+        assert_array_almost_equal(c(xi).imag, ci(xi))
+
+    def test_complex(self):
+        for kind in ('linear', 'nearest', 'cubic', 'slinear', 'quadratic',
+                     'zero', 'previous', 'next'):
+            self._check_complex(np.complex64, kind)
+            self._check_complex(np.complex128, kind)
+
+    def test_circular_refs(self):
+        # Test interp1d can be automatically garbage collected
+        x = np.linspace(0, 1)
+        y = np.linspace(0, 1)
+        # Confirm interp can be released from memory after use
+        with assert_deallocated(interp1d, x, y) as interp:
+            interp([0.1, 0.2])
+            del interp
+
+    def test_overflow_nearest(self):
+        # Test that the x range doesn't overflow when given integers as input
+        for kind in ('nearest', 'previous', 'next'):
+            x = np.array([0, 50, 127], dtype=np.int8)
+            ii = interp1d(x, x, kind=kind)
+            assert_array_almost_equal(ii(x), x)
+
+    def test_local_nans(self):
+        # check that for local interpolation kinds (slinear, zero) a single nan
+        # only affects its local neighborhood
+        x = np.arange(10).astype(float)
+        y = x.copy()
+        y[6] = np.nan
+        for kind in ('zero', 'slinear'):
+            ir = interp1d(x, y, kind=kind)
+            vals = ir([4.9, 7.0])
+            assert np.isfinite(vals).all()
+
+    def test_spline_nans(self):
+        # Backwards compat: a single nan makes the whole spline interpolation
+        # return nans in an array of the correct shape. And it doesn't raise,
+        # just quiet nans because of backcompat.
+        x = np.arange(8).astype(float)
+        y = x.copy()
+        yn = y.copy()
+        yn[3] = np.nan
+
+        for kind in ['quadratic', 'cubic']:
+            ir = interp1d(x, y, kind=kind)
+            irn = interp1d(x, yn, kind=kind)
+            for xnew in (6, [1, 6], [[1, 6], [3, 5]]):
+                xnew = np.asarray(xnew)
+                out, outn = ir(x), irn(x)
+                assert np.isnan(outn).all()
+                assert out.shape == outn.shape
+
+    def test_all_nans(self):
+        # regression test for gh-11637: interp1d core dumps with all-nan `x`
+        x = np.ones(10) * np.nan
+        y = np.arange(10)
+        with assert_raises(ValueError):
+            interp1d(x, y, kind='cubic')
+
+    def test_read_only(self):
+        x = np.arange(0, 10)
+        y = np.exp(-x / 3.0)
+        xnew = np.arange(0, 9, 0.1)
+        # Check both read-only and not read-only:
+        for xnew_writeable in (True, False):
+            xnew.flags.writeable = xnew_writeable
+            x.flags.writeable = False
+            for kind in ('linear', 'nearest', 'zero', 'slinear', 'quadratic',
+                         'cubic'):
+                f = interp1d(x, y, kind=kind)
+                vals = f(xnew)
+                assert np.isfinite(vals).all()
+
+    @pytest.mark.parametrize(
+        "kind", ("linear", "nearest", "nearest-up", "previous", "next")
+    )
+    def test_single_value(self, kind):
+        # https://github.com/scipy/scipy/issues/4043
+        f = interp1d([1.5], [6], kind=kind, bounds_error=False,
+                     fill_value=(2, 10))
+        xp_assert_equal(f([1, 1.5, 2]), np.asarray([2.0, 6, 10]))
+        # check still error if bounds_error=True
+        f = interp1d([1.5], [6], kind=kind, bounds_error=True)
+        with assert_raises(ValueError, match="x_new is above"):
+            f(2.0)
+
+
+class TestLagrange:
+
+    def test_lagrange(self):
+        p = poly1d([5,2,1,4,3])
+        xs = np.arange(len(p.coeffs))
+        ys = p(xs)
+        with pytest.warns(DeprecationWarning, match="`lagrange`"):
+            pl = lagrange(xs,ys)
+        assert_array_almost_equal(p.coeffs,pl.coeffs)
+
+
+@make_xp_test_case(Akima1DInterpolator)
+class TestAkima1DInterpolator:
+    def test_eval(self, xp):
+        x = xp.arange(0., 11., dtype=xp.float64)
+        y = xp.asarray(
+            [0., 2., 1., 3., 2., 6., 5.5, 5.5, 2.7, 5.1, 3.], dtype=xp.float64
+        )
+        ak = Akima1DInterpolator(x, y)
+        xi = xp.asarray([0., 0.5, 1., 1.5, 2.5, 3.5, 4.5, 5.1, 6.5, 7.2,
+            8.6, 9.9, 10.], dtype=xp.float64)
+        yi = xp.asarray([0., 1.375, 2., 1.5, 1.953125, 2.484375,
+            4.1363636363636366866103344, 5.9803623910336236590978842,
+            5.5067291516462386624652936, 5.2031367459745245795943447,
+            4.1796554159017080820603951, 3.4110386597938129327189927,
+            3.], dtype=xp.float64)
+        xp_assert_close(ak(xi), yi)
+
+    def test_eval_mod(self, xp):
+        # Reference values generated with the following MATLAB code:
+        # format longG
+        # x = 0:10; y = [0. 2. 1. 3. 2. 6. 5.5 5.5 2.7 5.1 3.];
+        # xi = [0. 0.5 1. 1.5 2.5 3.5 4.5 5.1 6.5 7.2 8.6 9.9 10.];
+        # makima(x, y, xi)
+        x = xp.arange(0., 11., dtype=xp.float64)
+        y = xp.asarray(
+            [0., 2., 1., 3., 2., 6., 5.5, 5.5, 2.7, 5.1, 3.], dtype=xp.float64
+        )
+        ak = Akima1DInterpolator(x, y, method="makima")
+        xi = xp.asarray([0., 0.5, 1., 1.5, 2.5, 3.5, 4.5, 5.1, 6.5, 7.2,
+                       8.6, 9.9, 10.], dtype=xp.float64)
+        yi = xp.asarray([
+            0.0, 1.34471153846154, 2.0, 1.44375, 1.94375, 2.51939102564103,
+            4.10366931918656, 5.98501550899192, 5.51756330960439, 5.1757231914014,
+            4.12326636931311, 3.32931513157895, 3.0], dtype=xp.float64)
+        xp_assert_close(ak(xi), yi)
+
+    def test_eval_2d(self, xp):
+        x = xp.arange(0., 11., dtype=xp.float64)
+        y = xp.asarray(
+            [0., 2., 1., 3., 2., 6., 5.5, 5.5, 2.7, 5.1, 3.], dtype=xp.float64
+        )
+        y = xp.stack((y, 2. * y), axis=1)
+        ak = Akima1DInterpolator(x, y)
+        xi = xp.asarray([0., 0.5, 1., 1.5, 2.5, 3.5, 4.5, 5.1, 6.5, 7.2,
+                       8.6, 9.9, 10.], dtype=xp.float64)
+        yi = xp.asarray([0., 1.375, 2., 1.5, 1.953125, 2.484375,
+                       4.1363636363636366866103344,
+                       5.9803623910336236590978842,
+                       5.5067291516462386624652936,
+                       5.2031367459745245795943447,
+                       4.1796554159017080820603951,
+                       3.4110386597938129327189927, 3.], dtype=xp.float64)
+        yi = xp.stack((yi, 2. * yi), axis=1)
+        xp_assert_close(ak(xi), yi)
+
+    def test_eval_3d(self):
+        x = np.arange(0., 11.)
+        y_ = np.array([0., 2., 1., 3., 2., 6., 5.5, 5.5, 2.7, 5.1, 3.])
+        y = np.empty((11, 2, 2))
+        y[:, 0, 0] = y_
+        y[:, 1, 0] = 2. * y_
+        y[:, 0, 1] = 3. * y_
+        y[:, 1, 1] = 4. * y_
+        ak = Akima1DInterpolator(x, y)
+        xi = np.array([0., 0.5, 1., 1.5, 2.5, 3.5, 4.5, 5.1, 6.5, 7.2,
+                       8.6, 9.9, 10.])
+        yi = np.empty((13, 2, 2))
+        yi_ = np.array([0., 1.375, 2., 1.5, 1.953125, 2.484375,
+                        4.1363636363636366866103344,
+                        5.9803623910336236590978842,
+                        5.5067291516462386624652936,
+                        5.2031367459745245795943447,
+                        4.1796554159017080820603951,
+                        3.4110386597938129327189927, 3.])
+        yi[:, 0, 0] = yi_
+        yi[:, 1, 0] = 2. * yi_
+        yi[:, 0, 1] = 3. * yi_
+        yi[:, 1, 1] = 4. * yi_
+        xp_assert_close(ak(xi), yi)
+
+    def test_linear_interpolant_edge_case_1d(self, xp):
+        x = xp.asarray([0.0, 1.0], dtype=xp.float64)
+        y = xp.asarray([0.5, 1.0])
+        akima = Akima1DInterpolator(x, y, axis=0, extrapolate=None)
+        xp_assert_close(akima(0.45), xp.asarray(0.725, dtype=xp.float64))
+
+    def test_linear_interpolant_edge_case_2d(self, xp):
+        x = xp.asarray([0., 1.])
+        y = xp.stack((x, 2. * x, 3. * x, 4. * x), axis=1)
+
+        ak = Akima1DInterpolator(x, y)
+        xi = xp.asarray([0.5, 1.])
+        yi = xp.asarray([[0.5, 1., 1.5, 2.],
+                         [1., 2., 3., 4.]], dtype=xp.float64
+        )
+        xp_assert_close(ak(xi), yi)
+
+        ak = Akima1DInterpolator(x, y.T, axis=1)
+        xp_assert_close(ak(xi), yi.T)
+
+    def test_linear_interpolant_edge_case_3d(self):
+        x = np.arange(0., 2.)
+        y_ = np.array([0., 1.])
+        y = np.empty((2, 2, 2))
+        y[:, 0, 0] = y_
+        y[:, 1, 0] = 2. * y_
+        y[:, 0, 1] = 3. * y_
+        y[:, 1, 1] = 4. * y_
+        ak = Akima1DInterpolator(x, y)
+        yi_ = np.array([0.5, 1.])
+        yi = np.empty((2, 2, 2))
+        yi[:, 0, 0] = yi_
+        yi[:, 1, 0] = 2. * yi_
+        yi[:, 0, 1] = 3. * yi_
+        yi[:, 1, 1] = 4. * yi_
+        xi = yi_
+        xp_assert_close(ak(xi), yi)
+
+        ak = Akima1DInterpolator(x, y.transpose(1, 0, 2), axis=1)
+        xp_assert_close(ak(xi), yi.transpose(1, 0, 2))
+
+        ak = Akima1DInterpolator(x, y.transpose(2, 1, 0), axis=2)
+        xp_assert_close(ak(xi), yi.transpose(2, 1, 0))
+
+    def test_degenerate_case_multidimensional(self, xp):
+        # This test is for issue #5683.
+        x = xp.asarray([0, 1, 2], dtype=xp.float64)
+        y = xp.stack((x, x**2)).T
+        ak = Akima1DInterpolator(x, y)
+        x_eval = xp.asarray([0.5, 1.5], dtype=xp.float64)
+        y_eval = ak(x_eval)
+        xp_assert_close(y_eval, xp.stack((x_eval, x_eval**2)).T)
+
+    def test_extend(self):
+        x = np.arange(0., 11.)
+        y = np.array([0., 2., 1., 3., 2., 6., 5.5, 5.5, 2.7, 5.1, 3.])
+        ak = Akima1DInterpolator(x, y)
+        match = "Extending a 1-D Akima interpolator is not yet implemented"
+        with pytest.raises(NotImplementedError, match=match):
+            ak.extend(None, None)
+
+    def test_mod_invalid_method(self):
+        x = np.arange(0., 11.)
+        y = np.array([0., 2., 1., 3., 2., 6., 5.5, 5.5, 2.7, 5.1, 3.])
+        match = "`method`=invalid is unsupported."
+        with pytest.raises(NotImplementedError, match=match):
+            Akima1DInterpolator(x, y, method="invalid")  # type: ignore
+
+    def test_extrapolate_attr(self):
+        #
+        x = np.linspace(-5, 5, 11)
+        y = x**2
+        x_ext = np.linspace(-10, 10, 17)
+        y_ext = x_ext**2
+        # Testing all extrapolate cases.
+        ak_true = Akima1DInterpolator(x, y, extrapolate=True)
+        ak_false = Akima1DInterpolator(x, y, extrapolate=False)
+        ak_none = Akima1DInterpolator(x, y, extrapolate=None)
+        # None should default to False; extrapolated points are NaN.
+        xp_assert_close(ak_false(x_ext), ak_none(x_ext), atol=1e-15)
+        xp_assert_equal(ak_false(x_ext)[0:4], np.full(4, np.nan))
+        xp_assert_equal(ak_false(x_ext)[-4:-1], np.full(3, np.nan))
+        # Extrapolation on call and attribute should be equal.
+        xp_assert_close(ak_false(x_ext, extrapolate=True), ak_true(x_ext), atol=1e-15)
+        # Testing extrapoation to actual function.
+        xp_assert_close(y_ext, ak_true(x_ext), atol=1e-15)
+
+
+    def test_no_overflow(self):
+        # check a large jump does not cause a float overflow
+        x = np.arange(1, 10)
+        y = 1.e6*np.sqrt(np.finfo(float).max)*np.heaviside(x-4, 0.5)
+
+        ak1 = Akima1DInterpolator(x, y, method='makima')
+        ak2 = Akima1DInterpolator(x, y, method='akima')
+
+        y_eval1 = ak1(x)
+        y_eval2 = ak2(x)
+
+        assert np.isfinite(y_eval1).all()
+        assert np.isfinite(y_eval2).all()
+
+
+@pytest.mark.parametrize("method", [Akima1DInterpolator, PchipInterpolator])
+def test_complex(method):
+    # Complex-valued data deprecated
+    x = np.arange(0., 11.)
+    y = np.array([0., 2., 1., 3., 2., 6., 5.5, 5.5, 2.7, 5.1, 3.])
+    y = y - 2j*y
+    msg = "real values"
+    with pytest.raises(ValueError, match=msg):
+        method(x, y)
+
+    def test_concurrency(self):
+        # Check that no segfaults appear with concurrent access to Akima1D
+        x = np.linspace(-5, 5, 11)
+        y = x**2
+        x_ext = np.linspace(-10, 10, 17)
+        ak = Akima1DInterpolator(x, y, extrapolate=True)
+
+        def worker_fn(_, ak, x_ext):
+            ak(x_ext)
+
+        _run_concurrent_barrier(10, worker_fn, ak, x_ext)
+
+
+@make_xp_test_case(PPoly, BPoly)
+class TestPPolyCommon:
+    # test basic functionality for PPoly and BPoly
+    def test_sort_check(self, xp):
+        c = xp.asarray([[1, 4], [2, 5], [3, 6]])
+        x = xp.asarray([0, 1, 0.5])
+        assert_raises(ValueError, PPoly, c, x)
+        assert_raises(ValueError, BPoly, c, x)
+
+    def test_ctor_c(self, xp):
+        # wrong shape: `c` must be at least 2D
+        with assert_raises(ValueError):
+            PPoly(xp.asarray([1, 2]), xp.asarray([0, 1]))
+
+    def test_extend(self, xp):
+        # Test adding new points to the piecewise polynomial
+        np.random.seed(1234)
+
+        order = 3
+        x = np.unique(np.r_[0, 10 * np.random.rand(30), 10])
+        c = 2*np.random.rand(order+1, len(x)-1, 2, 3) - 1
+
+        c, x = xp.asarray(c), xp.asarray(x)
+
+        for cls in (PPoly, BPoly):
+            pp = cls(c[:, :9, ...], x[:10])
+            pp.extend(c[:, 9:, ...], x[10:])
+
+            pp2 = cls(c[:, 10:, ...], x[10:])
+            pp2.extend(c[:, :10, ...], x[:10])
+
+            pp3 = cls(c, x)
+
+            xp_assert_equal(pp.c, pp3.c)
+            xp_assert_equal(pp.x, pp3.x)
+            xp_assert_equal(pp2.c, pp3.c)
+            xp_assert_equal(pp2.x, pp3.x)
+
+    def test_extend_diff_orders(self, xp):
+        # Test extending polynomial with different order one
+        np.random.seed(1234)
+
+        x = xp.linspace(0, 1, 6)
+        c = xp.asarray(np.random.rand(2, 5))
+
+        x2 = xp.linspace(1, 2, 6)
+        c2 = xp.asarray(np.random.rand(4, 5))
+
+        for cls in (PPoly, BPoly):
+            pp1 = cls(c, x)
+            pp2 = cls(c2, x2)
+
+            pp_comb = cls(c, x)
+            pp_comb.extend(c2, x2[1:])
+
+            # NB. doesn't match to pp1 at the endpoint, because pp1 is not
+            #     continuous with pp2 as we took random coefs.
+            xi1 = xp.linspace(0, 1, 300, endpoint=False)
+            xi2 = xp.linspace(1, 2, 300)
+
+            xp_assert_close(pp1(xi1), pp_comb(xi1))
+            xp_assert_close(pp2(xi2), pp_comb(xi2))
+
+    def test_extend_descending(self, xp):
+        np.random.seed(0)
+
+        order = 3
+        x = np.sort(np.random.uniform(0, 10, 20))
+        c = np.random.rand(order + 1, x.shape[0] - 1, 2, 3)
+
+        c, x = xp.asarray(c), xp.asarray(x)
+
+        for cls in (PPoly, BPoly):
+            p = cls(c, x)
+
+            p1 = cls(c[:, :9, ...], x[:10])
+            p1.extend(c[:, 9:, ...], x[10:])
+
+            p2 = cls(c[:, 10:, ...], x[10:])
+            p2.extend(c[:, :10, ...], x[:10])
+
+            xp_assert_equal(p1.c, p.c)
+            xp_assert_equal(p1.x, p.x)
+            xp_assert_equal(p2.c, p.c)
+            xp_assert_equal(p2.x, p.x)
+
+    def test_shape(self, xp):
+        np.random.seed(1234)
+        c = xp.asarray(np.random.rand(8, 12, 5, 6, 7))
+        x = xp.asarray(np.sort(np.random.rand(13)))
+        x_p = xp.asarray(np.random.rand(3, 4))
+        for cls in (PPoly, BPoly):
+            p = cls(c, x)
+            assert p(x_p).shape == (3, 4, 5, 6, 7)
+
+    def test_shape_scalars(self):
+        np.random.seed(1234)
+        c = np.random.rand(8, 12, 5, 6, 7)
+        x = np.sort(np.random.rand(13))
+
+        for cls in (PPoly, BPoly):
+            p = cls(c[..., 0, 0, 0], x)
+
+            assert np.shape(p(0.5)) == ()
+            assert np.shape(p(np.array(0.5))) == ()
+
+            assert_raises(ValueError, p, np.array([[0.1, 0.2], [0.4]], dtype=object))
+
+    def test_concurrency(self, xp):
+        # Check that no segfaults appear with concurrent access to BPoly, PPoly
+        c = np.random.rand(8, 12, 5, 6, 7)
+        x = np.sort(np.random.rand(13))
+        xpp = np.random.rand(3, 4)
+
+        c, x, xpp = map(xp.asarray, (c, x, xpp))
+
+        for cls in (PPoly, BPoly):
+            interp = cls(c, x)
+
+            def worker_fn(_, interp, xpp):
+                interp(xpp)
+
+            _run_concurrent_barrier(10, worker_fn, interp, xpp)
+
+    def test_complex_coef(self, xp):
+        np.random.seed(12345)
+        x = xp.asarray(np.sort(np.random.random(13)))
+        c = xp.asarray(np.random.random((8, 12)) * (1. + 0.3j))
+        c_re, c_im = xp.real(c), xp.imag(c)
+        x_p = xp.asarray(np.random.random(5))
+        for cls in (PPoly, BPoly):
+            p, p_re, p_im = cls(c, x), cls(c_re, x), cls(c_im, x)
+            for nu in [0, 1, 2]:
+                xp_assert_close(xp.real(p(x_p, nu)), p_re(x_p, nu))
+                xp_assert_close(xp.imag(p(x_p, nu)), p_im(x_p, nu))
+
+    def test_axis(self, xp):
+        np.random.seed(12345)
+        c = np.random.rand(3, 4, 5, 6, 7, 8)
+        c_s = c.shape
+        xpp = np.random.random((1, 2))
+
+        c, xpp = xp.asarray(c), xp.asarray(xpp)
+
+        for axis in (0, 1, 2, 3):
+            m = c.shape[axis+1]
+            x = xp.asarray(np.sort(np.random.rand(m+1)))
+            for cls in (PPoly, BPoly):
+                p = cls(c, x, axis=axis)
+                assert p.c.shape == c_s[axis:axis+2] + c_s[:axis] + c_s[axis+2:]
+                res = p(xpp)
+                targ_shape = c_s[:axis] + xpp.shape + c_s[2+axis:]
+                assert res.shape == targ_shape
+
+                # deriv/antideriv does not drop the axis
+                for p1 in [cls(c, x, axis=axis).derivative(),
+                           cls(c, x, axis=axis).derivative(2),
+                           cls(c, x, axis=axis).antiderivative(),
+                           cls(c, x, axis=axis).antiderivative(2)]:
+                    assert p1.axis == p.axis
+
+        # c array needs two axes for the coefficients and intervals, so
+        # 0 <= axis < c.ndim-1; raise otherwise
+        for axis in (-1, 4, 5, 6):
+            for cls in (BPoly, PPoly):
+                assert_raises(ValueError, cls, **dict(c=c, x=x, axis=axis))
+
+
+class TestPolySubclassing:
+    class P(PPoly):
+        pass
+
+    class B(BPoly):
+        pass
+
+    def _make_polynomials(self):
+        np.random.seed(1234)
+        x = np.sort(np.random.random(3))
+        c = np.random.random((4, 2))
+        return self.P(c, x), self.B(c, x)
+
+    def test_derivative(self):
+        pp, bp = self._make_polynomials()
+        for p in (pp, bp):
+            pd = p.derivative()
+            assert p.__class__ == pd.__class__
+
+        ppa = pp.antiderivative()
+        assert pp.__class__ == ppa.__class__
+
+    def test_from_spline(self):
+        np.random.seed(1234)
+        x = np.sort(np.r_[0, np.random.rand(11), 1])
+        y = np.random.rand(len(x))
+
+        spl = splrep(x, y, s=0)
+        pp = self.P.from_spline(spl)
+        assert pp.__class__ == self.P
+
+    def test_conversions(self):
+        pp, bp = self._make_polynomials()
+
+        pp1 = self.P.from_bernstein_basis(bp)
+        assert pp1.__class__ == self.P
+
+        bp1 = self.B.from_power_basis(pp)
+        assert bp1.__class__ == self.B
+
+    def test_from_derivatives(self):
+        x = [0, 1, 2]
+        y = [[1], [2], [3]]
+        bp = self.B.from_derivatives(x, y)
+        assert bp.__class__ == self.B
+
+
+@make_xp_test_case(PPoly)
+class TestPPoly:
+    def test_simple(self, xp):
+        c = xp.asarray([[1, 4], [2, 5], [3, 6]])
+        x = xp.asarray([0, 0.5, 1])
+        p = PPoly(c, x)
+        xp_assert_close(p(0.3), xp.asarray(1*0.3**2 + 2*0.3 + 3, dtype=xp.float64))
+        xp_assert_close(
+            p(0.7), xp.asarray(4*(0.7-0.5)**2 + 5*(0.7-0.5) + 6, dtype=xp.float64)
+        )
+
+    def test_periodic(self, xp):
+        c = xp.asarray([[1, 4], [2, 5], [3, 6]])
+        x = xp.asarray([0, 0.5, 1])
+        p = PPoly(c, x, extrapolate='periodic')
+
+        xp_assert_close(p(1.3),
+                        xp.asarray(1 * 0.3 ** 2 + 2 * 0.3 + 3, dtype=xp.float64))
+        xp_assert_close(
+            p(-0.3),
+            xp.asarray(4 * (0.7 - 0.5) ** 2 + 5 * (0.7 - 0.5) + 6, dtype=xp.float64)
+        )
+
+        xp_assert_close(p(1.3, 1), xp.asarray(2 * 0.3 + 2, dtype=xp.float64))
+        xp_assert_close(p(-0.3, 1), xp.asarray(8 * (0.7 - 0.5) + 5, dtype=xp.float64))
+
+    def test_read_only(self):
+        c = np.array([[1, 4], [2, 5], [3, 6]])
+        x = np.array([0, 0.5, 1])
+        xnew = np.array([0, 0.1, 0.2])
+        PPoly(c, x, extrapolate='periodic')
+
+        for writeable in (True, False):
+            x.flags.writeable = writeable
+            c.flags.writeable = writeable
+            f = PPoly(c, x)
+            vals = f(xnew)
+            assert np.isfinite(vals).all()
+
+    @make_xp_test_case((PPoly, "roots"))
+    def test_descending(self, xp):
+        def binom_matrix(power):
+            n = np.arange(power + 1).reshape(-1, 1)
+            k = np.arange(power + 1)
+            B = binom(n, k)
+            return B[::-1, ::-1]
+
+        rng = np.random.RandomState(0)
+
+        power = 3
+        for m in [10, 20, 30]:
+            x = np.sort(rng.uniform(0, 10, m + 1))
+            ca = rng.uniform(-2, 2, size=(power + 1, m))
+
+            h = np.diff(x)
+            h_powers = h[None, :] ** np.arange(power + 1)[::-1, None]
+            B = binom_matrix(power)
+            cap = ca * h_powers
+            cdp = np.dot(B.T, cap)
+            cd = cdp / h_powers
+
+            ca, cd, x = map(xp.asarray, (ca, cd, x))
+            pa = PPoly(ca, x, extrapolate=True)
+            pd = PPoly(xp.flip(cd, axis=-1), xp.flip(x, axis=-1), extrapolate=True)
+
+            x_test = xp.asarray(rng.uniform(-10, 20, 100))
+            xp_assert_close(pa(x_test), pd(x_test), rtol=1e-13)
+            xp_assert_close(pa(x_test, 1), pd(x_test, 1), rtol=1e-13)
+
+            pa_d = pa.derivative()
+            pd_d = pd.derivative()
+
+            xp_assert_close(pa_d(x_test), pd_d(x_test), rtol=1e-13)
+
+            # Antiderivatives won't be equal because fixing continuity is
+            # done in the reverse order, but surely the differences should be
+            # equal.
+            pa_i = pa.antiderivative()
+            pd_i = pd.antiderivative()
+            for a, b in rng.uniform(-10, 20, (5, 2)):
+                a, b = map(xp.asarray, (a, b))
+                int_a = pa.integrate(a, b)
+                int_d = pd.integrate(a, b)
+                xp_assert_close(int_a, int_d, rtol=1e-13)
+                xp_assert_close(pa_i(b) - pa_i(a), pd_i(b) - pd_i(a),
+                                rtol=1e-13)
+
+            roots_d = pd.roots()
+            roots_a = pa.roots()
+            xp_assert_close(roots_a, xp.sort(roots_d), rtol=1e-12)
+
+    def test_multi_shape(self, xp):
+        c = np.random.rand(6, 2, 1, 2, 3)
+        x = np.array([0, 0.5, 1])
+
+        p = PPoly(c, x)
+        assert p.x.shape == x.shape
+        assert p.c.shape == c.shape
+        assert p(0.3).shape == c.shape[2:]
+
+        assert p(np.random.rand(5, 6)).shape == (5, 6) + c.shape[2:]
+
+        dp = p.derivative()
+        assert dp.c.shape == (5, 2, 1, 2, 3)
+        ip = p.antiderivative()
+        assert ip.c.shape == (7, 2, 1, 2, 3)
+
+    def test_construct_fast(self, xp):
+        np.random.seed(1234)
+        c = np.array([[1, 4], [2, 5], [3, 6]], dtype=float)
+        x = np.array([0, 0.5, 1])
+        p = PPoly.construct_fast(xp.asarray(c), xp.asarray(x))
+        xp_assert_close(p(0.3), xp.asarray(1*0.3**2 + 2*0.3 + 3, dtype=xp.float64))
+        xp_assert_close(
+            p(0.7), xp.asarray(4*(0.7-0.5)**2 + 5*(0.7-0.5) + 6, dtype=xp.float64)
+        )
+
+    def test_vs_alternative_implementations(self, xp):
+        rng = np.random.RandomState(1234)
+        c_np = rng.rand(3, 12, 22)
+        x_np = np.sort(np.r_[0, rng.rand(11), 1])
+        x_p_np = np.r_[0.3, 0.5, 0.33, 0.6]
+
+        c, x, x_p = map(xp.asarray, (c_np, x_np, x_p_np))
+
+        p = PPoly(c, x)
+
+        expected = xp.asarray(_ppoly_eval_1(c_np, x_np, x_p_np))
+        xp_assert_close(p(x_p), expected)
+
+        expected = xp.asarray(_ppoly_eval_2(c_np[:, :, 0], x_np, x_p_np))
+        xp_assert_close(p(x_p)[:, 0], expected)
+
+    def test_from_spline(self, xp):
+        rng = np.random.RandomState(1234)
+        x = np.sort(np.r_[0, rng.rand(11), 1])
+        y = rng.rand(len(x))
+
+        t_np, c_np, k = splrep(x, y, s=0)
+        t, c = xp.asarray(t_np), xp.asarray(c_np)
+        pp = PPoly.from_spline((t, c, k))
+
+        xi_np = np.linspace(0, 1, 200)
+        xi = xp.asarray(xi_np)
+        xp_assert_close(pp(xi), xp.asarray(splev(xi_np, (t_np, c_np, k))))
+
+        # make sure .from_spline accepts BSpline objects
+        b = BSpline(t, c, k)
+        ppp = PPoly.from_spline(b)
+        xp_assert_close(ppp(xi), b(xi))
+
+        # BSpline's extrapolate attribute propagates unless overridden
+        for extrap in (None, True, False):
+            b = BSpline(t, c, k, extrapolate=extrap)
+            p = PPoly.from_spline(b)
+            assert p.extrapolate == b.extrapolate
+
+    def test_from_spline_2(self, xp):
+        # BSpline namespace propagates to PPoly
+        rng = np.random.RandomState(1234)
+        x = np.sort(np.r_[0, rng.rand(11), 1])
+        y = rng.rand(len(x))
+        t, c, k = splrep(x, y, s=0)     
+        spl = BSpline(xp.asarray(t), xp.asarray(c), k)
+        pp = PPoly.from_spline(spl)
+
+        xi = xp.linspace(0, 1, 11)
+        xp_assert_close(pp(xi), spl(xi))
+
+    def test_derivative_simple(self, xp):
+        np.random.seed(1234)
+        c = xp.asarray([[4, 3, 2, 1]]).T
+        dc = xp.asarray([[3*4, 2*3, 2]]).T
+        ddc = xp.asarray([[2*3*4, 1*2*3]]).T
+        x = xp.asarray([0, 1])
+
+        pp = PPoly(c, x)
+        dpp = PPoly(dc, x)
+        ddpp = PPoly(ddc, x)
+
+        xp_assert_close(pp.derivative().c, dpp.c)
+        xp_assert_close(pp.derivative(2).c, ddpp.c)
+
+    def test_derivative_eval(self, xp):
+        rng = np.random.RandomState(1234)
+        x = np.sort(np.r_[0, rng.rand(11), 1])
+        y = rng.rand(len(x))
+
+        t_np, c_np, k = splrep(x, y, s=0)
+        t, c = xp.asarray(t_np), xp.asarray(c_np)
+        pp = PPoly.from_spline((t, c, k))
+
+        xi_np = np.linspace(0, 1, 200)
+        xi = xp.asarray(xi_np)
+        for dx in range(0, 3):
+            xp_assert_close(pp(xi, dx), xp.asarray(splev(xi_np, (t_np, c_np, k), dx)))
+
+    def test_derivative(self, xp):
+        rng = np.random.RandomState(1234)
+        x_np = np.sort(np.r_[0, rng.rand(11), 1])
+        y_np = rng.rand(len(x_np))
+
+        t_np, c_np, k = splrep(x_np, y_np, s=0, k=5)
+        t, c = xp.asarray(t_np), xp.asarray(c_np)
+        pp = PPoly.from_spline((t, c, k))
+
+        xi = xp.linspace(0, 1, 200)
+        for dx in range(0, 10):
+            xp_assert_close(pp(xi, dx), pp.derivative(dx)(xi), err_msg=f"dx={dx}")
+
+    def test_antiderivative_of_constant(self, xp):
+        # https://github.com/scipy/scipy/issues/4216
+        p = PPoly(xp.asarray([[1.]]), xp.asarray([0, 1]))
+        xp_assert_equal(
+            p.antiderivative().c,
+            PPoly(xp.asarray([[1], [0]]), xp.asarray([0, 1])).c
+        )
+        xp_assert_equal(
+            p.antiderivative().x,
+            PPoly(xp.asarray([[1], [0]]), xp.asarray([0, 1])).x
+        )
+
+    def test_antiderivative_regression_4355(self, xp):
+        # https://github.com/scipy/scipy/issues/4355
+        p = PPoly(xp.asarray([[1., 0.5]]), xp.asarray([0, 1, 2]))
+        q = p.antiderivative()
+        xp_assert_equal(q.c, xp.asarray([[1, 0.5], [0, 1]], dtype=xp.float64))
+        xp_assert_equal(q.x, xp.asarray([0.0, 1, 2], dtype=xp.float64))
+        xp_assert_close(p.integrate(0, 2), xp.asarray(1.5, dtype=xp.float64))
+        xp_assert_close(xp.asarray(q(2) - q(0)),
+                        xp.asarray(1.5, dtype=xp.float64))
+
+    def test_antiderivative_simple(self, xp):
+        # [ p1(x) = 3*x**2 + 2*x + 1,
+        #   p2(x) = 1.6875]
+        c = xp.asarray([[3, 2, 1], [0, 0, 1.6875]], dtype=xp.float64).T
+        # [ pp1(x) = x**3 + x**2 + x,
+        #   pp2(x) = 1.6875*(x - 0.25) + pp1(0.25)]
+        ic = xp.asarray([[1, 1, 1, 0], [0, 0, 1.6875, 0.328125]], dtype=xp.float64).T
+        # [ ppp1(x) = (1/4)*x**4 + (1/3)*x**3 + (1/2)*x**2,
+        #   ppp2(x) = (1.6875/2)*(x - 0.25)**2 + pp1(0.25)*x + ppp1(0.25)]
+        iic = xp.asarray([[1/4, 1/3, 1/2, 0, 0],
+                          [0, 0, 1.6875/2, 0.328125, 0.037434895833333336]],
+                         dtype=xp.float64
+        ).T
+        x = xp.asarray([0, 0.25, 1], dtype=xp.float64)
+
+        pp = PPoly(c, x)
+        ipp = pp.antiderivative()
+        iipp = pp.antiderivative(2)
+        iipp2 = ipp.antiderivative()
+
+        xp_assert_close(ipp.x, x)
+        xp_assert_close(ipp.c.T, ic.T)
+        xp_assert_close(iipp.c.T, iic.T)
+        xp_assert_close(iipp2.c.T, iic.T)
+
+    def test_antiderivative_vs_derivative(self, xp):
+        rng = np.random.RandomState(1234)
+        x_np = np.linspace(0, 1, 30)**2
+        y_np = rng.rand(len(x_np))
+        t_np, c_np, k = splrep(x_np, y_np, s=0, k=5)
+        t, c = xp.asarray(t_np), xp.asarray(c_np)
+        pp = PPoly.from_spline((t, c, k))
+
+        for dx in range(0, 10):
+            ipp = pp.antiderivative(dx)
+
+            # check that derivative is inverse op
+            pp2 = ipp.derivative(dx)
+            xp_assert_close(pp.c, pp2.c)
+
+            # check continuity
+            for k in range(dx):
+                pp2 = ipp.derivative(k)
+
+                r = 1e-13
+                endpoint = r*pp2.x[:-1] + (1 - r)*pp2.x[1:]
+
+                xp_assert_close(
+                    pp2(pp2.x[1:]), pp2(endpoint), rtol=1e-7, err_msg=f"dx={dx} k={k}"
+                )
+
+    def test_antiderivative_vs_spline(self, xp):
+        rng = np.random.RandomState(1234)
+        x_np = np.sort(np.r_[0, rng.rand(11), 1])
+        y_np = rng.rand(len(x_np))
+
+        t_np, c_np, k = splrep(x_np, y_np, s=0, k=5)
+        t, c = xp.asarray(t_np), xp.asarray(c_np)
+        pp = PPoly.from_spline((t, c, k))
+
+        for dx in range(0, 10):
+            pp2 = pp.antiderivative(dx)
+            t2_np, c2_np, k2 = splantider((t_np, c_np, k), dx)
+            xi_np = np.linspace(0, 1, 200)
+            xi = xp.asarray(xi_np)
+            xp_assert_close(pp2(xi), xp.asarray(splev(xi_np, (t2_np, c2_np, k2))),
+                            rtol=1e-7)
+
+    def test_antiderivative_continuity(self, xp):
+        c = xp.asarray([[2, 1, 2, 2], [2, 1, 3, 3]]).T
+        x = xp.asarray([0, 0.5, 1], dtype=xp.float64)
+
+        p = PPoly(c, x)
+        ip = p.antiderivative()
+
+        # check continuity
+        xp_assert_close(ip(0.5 - 1e-9), ip(0.5 + 1e-9), rtol=1e-8)
+
+        # check that only lowest order coefficients were changed
+        p2 = ip.derivative()
+        xp_assert_close(p2.c, p.c)
+
+    def test_integrate(self, xp):
+        rng = np.random.RandomState(1234)
+        x_np = np.sort(np.r_[0, rng.rand(11), 1])
+        y_np = rng.rand(len(x_np))
+
+        t_np, c_np, k = splrep(x_np, y_np, s=0, k=5)
+        t, c = xp.asarray(t_np), xp.asarray(c_np)
+        pp = PPoly.from_spline((t, c, k))
+
+        a, b = 0.3, 0.9
+        ig = pp.integrate(a, b)
+
+        ipp = pp.antiderivative()
+        xp_assert_close(ig, ipp(b) - ipp(a), check_0d=False)
+        xp_assert_close(
+            ig, xp.asarray(splint(a, b, (t_np, c_np, k)), dtype=xp.float64),
+            check_0d=False
+        )
+
+        a, b = -0.3, 0.9
+        ig = pp.integrate(a, b, extrapolate=True)
+        xp_assert_close(ig, ipp(b) - ipp(a), check_0d=False)
+
+        assert xp.all(xp.isnan(pp.integrate(a, b, extrapolate=False)))
+
+    def test_integrate_readonly(self):
+        x = np.array([1, 2, 4])
+        c = np.array([[0., 0.], [-1., -1.], [2., -0.], [1., 2.]])
+
+        for writeable in (True, False):
+            x.flags.writeable = writeable
+
+            P = PPoly(c, x)
+            vals = P.integrate(1, 4)
+
+            assert np.isfinite(vals).all()
+
+    def test_integrate_periodic(self, xp):
+        x_np = np.array([1, 2, 4])
+        c_np = np.array([[0., 0.], [-1., -1.], [2., -0.], [1., 2.]])
+
+        x, c = xp.asarray(x_np), xp.asarray(c_np)
+
+        P = PPoly(c, x, extrapolate='periodic')
+        I = P.antiderivative()
+
+        period_int = xp.asarray(I(4) - I(1), dtype=xp.float64)
+
+        xp_assert_close(P.integrate(1, 4), period_int)
+        xp_assert_close(P.integrate(-10, -7), period_int)
+        xp_assert_close(P.integrate(-10, -4), xp.asarray(2 * period_int))
+
+        xp_assert_close(P.integrate(1.5, 2.5),
+                        xp.asarray(I(2.5) - I(1.5), dtype=xp.float64))
+        xp_assert_close(P.integrate(3.5, 5),
+                        xp.asarray(I(2) - I(1) + I(4) - I(3.5), dtype=xp.float64))
+        xp_assert_close(P.integrate(3.5 + 12, 5 + 12),
+                        xp.asarray(I(2) - I(1) + I(4) - I(3.5), dtype=xp.float64))
+        xp_assert_close(
+            P.integrate(3.5, 5 + 12),
+            xp.asarray(
+                I(2) - I(1) + I(4) - I(3.5) + 4 * period_int, dtype=xp.float64
+            )
+        )
+        xp_assert_close(P.integrate(0, -1),
+                        xp.asarray(I(2) - I(3), dtype=xp.float64))
+        xp_assert_close(P.integrate(-9, -10),
+                        xp.asarray(I(2) - I(3), dtype=xp.float64))
+        xp_assert_close(P.integrate(0, -10),
+                        xp.asarray(I(2) - I(3) - 3 * period_int, dtype=xp.float64))
+
+    @make_xp_test_case((PPoly, "roots"))
+    def test_roots(self, xp):
+        x_np = np.linspace(0, 1, 31)**2
+        y_np = np.sin(30*x_np)
+
+        (t_np, c_np, k) = splrep(x_np, y_np, s=0, k=3)
+        t, c = xp.asarray(t_np), xp.asarray(c_np)
+        pp = PPoly.from_spline((t, c, k))
+
+        r = pp.roots()
+        r = r[(r >= 0 - 1e-15) & (r <= 1 + 1e-15)]
+        xp_assert_close(r, xp.asarray(sproot((t_np, c_np, k))), atol=1e-15)
+
+    @make_xp_test_case((PPoly, "roots"))
+    def test_roots_idzero(self, xp):
+        # Roots for piecewise polynomials with identically zero
+        # sections.
+        c = xp.asarray([[-1, 0.25], [0, 0], [-1, 0.25]], dtype=xp.float64).T
+        x = xp.asarray([0, 0.4, 0.6, 1.0], dtype=xp.float64)
+
+        pp = PPoly(c, x)
+        xp_assert_equal(
+            pp.roots(),
+            xp.asarray([0.25, 0.4, xp.nan, 0.6 + 0.25], dtype=xp.float64),
+        )
+        # ditto for p.solve(const) with sections identically equal const
+        const = 2.
+        c1 = _xp_copy_to_numpy(c)
+        c1[1, :] += const
+        c1 = xp.asarray(c1)
+        pp1 = PPoly(c1, x)
+
+        xp_assert_equal(
+            pp1.solve(const),
+            xp.asarray([0.25, 0.4, xp.nan, 0.6 + 0.25], dtype=xp.float64),
+        )
+
+    @make_xp_test_case((PPoly, "roots"), (PPoly, "solve"))
+    def test_roots_all_zero(self, xp):
+        # test the code path for the polynomial being identically zero everywhere
+        c = [[0], [0]]
+        x = [0, 1]
+        p = PPoly(xp.asarray(c), xp.asarray(x))
+        xp_assert_equal(p.roots(), xp.asarray([0, xp.nan], dtype=xp.float64))
+        xp_assert_equal(p.solve(0), xp.asarray([0, xp.nan], dtype=xp.float64))
+        xp_assert_equal(p.solve(1), xp.asarray([], dtype=xp.float64))
+
+        c = [[0, 0], [0, 0]]
+        x = [0, 1, 2]
+        p = PPoly(xp.asarray(c), xp.asarray(x))
+        xp_assert_equal(
+            p.roots(), xp.asarray([0, xp.nan, 1, xp.nan], dtype=xp.float64)
+        )
+        xp_assert_equal(
+            p.solve(0), xp.asarray([0, xp.nan, 1, xp.nan], dtype=xp.float64)
+        )
+        xp_assert_equal(p.solve(1), xp.asarray([], dtype=xp.float64))
+
+    @make_xp_test_case((PPoly, "roots"))
+    def test_roots_repeated(self, xp):
+        # Check roots repeated in multiple sections are reported only
+        # once.
+
+        # [(x + 1)**2 - 1, -x**2] ; x == 0 is a repeated root
+        c = xp.asarray([[1, 0, -1], [-1, 0, 0]], dtype=xp.float64).T
+        x = xp.asarray([-1, 0, 1], dtype=xp.float64)
+
+        pp = PPoly(c, x)
+        xp_assert_equal(pp.roots(), xp.asarray([-2.0, 0.0], dtype=xp.float64))
+        xp_assert_equal(
+            pp.roots(extrapolate=False), xp.asarray([0.0], dtype=xp.float64)
+        )
+
+    @make_xp_test_case((PPoly, "roots"), (PPoly, "solve"))
+    def test_roots_discont(self, xp):
+        # Check that a discontinuity across zero is reported as root
+        c = xp.asarray([[1], [-1]], dtype=xp.float64).T
+        x = xp.asarray([0, 0.5, 1], dtype=xp.float64)
+        pp = PPoly(c, x)
+        xp_assert_equal(pp.roots(), xp.asarray([0.5], dtype=xp.float64))
+        xp_assert_equal(
+            pp.roots(discontinuity=False), xp.asarray([], dtype=xp.float64)
+        )
+
+        # ditto for a discontinuity across y:
+        xp_assert_equal(pp.solve(0.5), xp.asarray([0.5], dtype=xp.float64))
+        xp_assert_equal(
+            pp.solve(0.5, discontinuity=False), xp.asarray([], dtype=xp.float64)
+        )
+
+        xp_assert_equal(pp.solve(1.5), xp.asarray([], dtype=xp.float64))
+        xp_assert_equal(
+            pp.solve(1.5, discontinuity=False), xp.asarray([], dtype=xp.float64)
+        )
+
+    @make_xp_test_case((PPoly, "roots"), (PPoly, "solve"))
+    @skip_xp_backends(np_only=True, reason="solve returns object array for c.ndim > 2")
+    def test_roots_random(self, xp):
+        # Check high-order polynomials with random coefficients
+        rng = np.random.RandomState(1234)
+
+        num = 0
+
+        for extrapolate in (True, False):
+            for order in range(0, 20):
+                x_np = np.unique(np.r_[0, 10 * rng.rand(30), 10])
+                c_np = 2*rng.rand(order+1, len(x_np)-1, 2, 3) - 1
+                x, c = xp.asarray(x_np), xp.asarray(c_np)
+                pp = PPoly(c, x)
+                for y in [0.0, float(rng.random())]:
+                    r = pp.solve(y, discontinuity=False, extrapolate=extrapolate)
+                    for i in range(2):
+                        for j in range(3):
+                            rr = r[i,j]
+                            if rr.size > 0:
+                                # Check that the reported roots indeed are roots
+                                num += rr.size
+                                val = pp(rr, extrapolate=extrapolate)[:,i,j]
+                                cmpval = pp(rr, nu=1,
+                                            extrapolate=extrapolate)[:,i,j]
+                                msg = f"({extrapolate!r}) r = {repr(rr)}"
+                                xp_assert_close((val-y) / cmpval, np.asarray(0.0),
+                                                atol=1e-7,
+                                                err_msg=msg, check_shape=False)
+
+        # Check that we checked a number of roots
+        assert num > 100, repr(num)
+
+    def test_roots_croots(self):
+        # Test the complex root finding algorithm
+        rng = np.random.RandomState(1234)
+
+        for k in range(1, 15):
+            c = rng.rand(k, 1, 130)
+
+            if k == 3:
+                # add a case with zero discriminant
+                c[:,0,0] = 1, 2, 1
+
+            for y in [0, rng.random()]:
+                w = np.empty(c.shape, dtype=complex)
+                _ppoly._croots_poly1(c, w, y)
+
+                if k == 1:
+                    assert np.isnan(w).all()
+                    continue
+
+                res = -y
+                cres = 0
+                for i in range(k):
+                    res += c[i,None] * w**(k-1-i)
+                    cres += abs(c[i,None] * w**(k-1-i))
+                with np.errstate(invalid='ignore'):
+                    res /= cres
+                res = res.ravel()
+                res = res[~np.isnan(res)]
+                xp_assert_close(res, np.zeros_like(res), atol=1e-10)
+
+    def test_extrapolate_attr(self, xp):
+        # [ 1 - x**2 ]
+        c_np = np.array([[-1, 0, 1]]).T
+        x_np = np.array([0, 1])
+        c, x = xp.asarray(c_np), xp.asarray(x_np)
+
+        for extrapolate in [True, False, None]:
+            pp = PPoly(c, x, extrapolate=extrapolate)
+            pp_d = pp.derivative()
+            pp_i = pp.antiderivative()
+
+            if extrapolate is False:
+                assert xp.all(xp.isnan(pp(xp.asarray([-0.1, 1.1]))))
+                assert xp.all(xp.isnan(pp_i(xp.asarray([-0.1, 1.1]))))
+                assert xp.all(xp.isnan(pp_d(xp.asarray([-0.1, 1.1]))))
+                if not is_cupy(xp):
+                    xp_assert_equal(
+                        pp.roots(), xp.asarray([1.0], dtype=xp.float64)
+                    )
+            else:
+                xp_assert_close(
+                    pp([-0.1, 1.1]),
+                    xp.asarray([1-0.1**2, 1-1.1**2], dtype=xp.float64),
+                )
+                assert not xp.any(xp.isnan(pp_i(xp.asarray([-0.1, 1.1]))))
+                assert not xp.any(xp.isnan(pp_d(xp.asarray([-0.1, 1.1]))))
+                if not is_cupy(xp):
+                    xp_assert_close(
+                        pp.roots(), xp.asarray([1.0, -1.0], dtype=xp.float64)
+                    )
+
+
+@make_xp_test_case(BPoly)
+class TestBPoly:
+    def test_simple(self, xp):
+        x = xp.asarray([0, 1])
+        c = xp.asarray([[3]])
+        bp = BPoly(c, x)
+        xp_assert_close(bp(0.1), xp.asarray(3., dtype=xp.float64))
+
+    def test_simple2(self, xp):
+        x = xp.asarray([0, 1])
+        c = xp.asarray([[3], [1]])
+        bp = BPoly(c, x)   # 3*(1-x) + 1*x
+        xp_assert_close(bp(0.1), xp.asarray(3*0.9 + 1.*0.1, dtype=xp.float64))
+
+    def test_simple3(self, xp):
+        x = xp.asarray([0, 1])
+        c = xp.asarray([[3], [1], [4]])
+        bp = BPoly(c, x)   # 3 * (1-x)**2 + 2 * x (1-x) + 4 * x**2
+        xp_assert_close(
+            bp(0.2),
+            xp.asarray(3 * 0.8*0.8 + 1 * 2*0.2*0.8 + 4 * 0.2*0.2, dtype=xp.float64)
+        )
+
+    def test_simple4(self, xp):
+        x = xp.asarray([0, 1])
+        c = xp.asarray([[1], [1], [1], [2]])
+        bp = BPoly(c, x)
+        xp_assert_close(bp(0.3),
+                        xp.asarray(    0.7**3 +
+                                   3 * 0.7**2 * 0.3 +
+                                   3 * 0.7 * 0.3**2 +
+                                   2 * 0.3**3, dtype=xp.float64)
+        )
+
+    def test_simple5(self, xp):
+        x = xp.asarray([0, 1])
+        c = xp.asarray([[1], [1], [8], [2], [1]])
+        bp = BPoly(c, x)
+        xp_assert_close(bp(0.3),
+                        xp.asarray(  0.7**4 +
+                                 4 * 0.7**3 * 0.3 +
+                             8 * 6 * 0.7**2 * 0.3**2 +
+                             2 * 4 * 0.7 * 0.3**3 +
+                                 0.3**4, dtype=xp.float64)
+        )
+
+    def test_periodic(self, xp):
+        x = xp.asarray([0, 1, 3])
+        c = xp.asarray([[3, 0], [0, 0], [0, 2]])
+        # [3*(1-x)**2, 2*((x-1)/2)**2]
+        bp = BPoly(c, x, extrapolate='periodic')
+
+        xp_assert_close(bp(3.4), xp.asarray(3 * 0.6**2, dtype=xp.float64))
+        xp_assert_close(bp(-1.3), xp.asarray(2 * (0.7/2)**2, dtype=xp.float64))
+
+        xp_assert_close(bp(3.4, 1), xp.asarray(-6 * 0.6, dtype=xp.float64))
+        xp_assert_close(bp(-1.3, 1), xp.asarray(2 * (0.7/2), dtype=xp.float64))
+
+    def test_descending(self, xp):
+        rng = np.random.RandomState(0)
+
+        power = 3
+        for m in [10, 20, 30]:
+            x_np = np.sort(rng.uniform(0, 10, m + 1))
+            ca_np = rng.uniform(-0.1, 0.1, size=(power + 1, m))
+            # We need only to flip coefficients to get it right!
+            cd_np = ca_np[::-1].copy()
+
+            x, ca, cd = map(xp.asarray, (x_np, ca_np, cd_np))
+
+            pa = BPoly(ca, x, extrapolate=True)
+            pd = BPoly(xp.flip(cd, axis=-1), xp.flip(x, axis=-1), extrapolate=True)
+
+            x_test = xp.asarray(rng.uniform(-10, 20, 100))
+            xp_assert_close(pa(x_test), pd(x_test), rtol=1e-13)
+            xp_assert_close(pa(x_test, 1), pd(x_test, 1), rtol=1e-13)
+
+            pa_d = pa.derivative()
+            pd_d = pd.derivative()
+
+            xp_assert_close(pa_d(x_test), pd_d(x_test), rtol=1e-13)
+
+            # Antiderivatives won't be equal because fixing continuity is
+            # done in the reverse order, but surely the differences should be
+            # equal.
+            pa_i = pa.antiderivative()
+            pd_i = pd.antiderivative()
+            for a, b in rng.uniform(-10, 20, (5, 2)):
+                int_a = pa.integrate(a, b)
+                int_d = pd.integrate(a, b)
+                xp_assert_close(int_a, int_d, rtol=1e-12)
+                xp_assert_close(pa_i(b) - pa_i(a), pd_i(b) - pd_i(a),
+                                rtol=1e-12)
+
+    def test_multi_shape(self, xp):
+        rng = np.random.RandomState(1234)
+        c_np = rng.rand(6, 2, 1, 2, 3)
+        x_np = np.array([0, 0.5, 1])
+        c, x = xp.asarray(c_np), xp.asarray(x_np)
+        p = BPoly(c, x)
+        assert p.x.shape == x.shape
+        assert p.c.shape == c.shape
+        assert p(0.3).shape == c.shape[2:]
+        assert p(rng.rand(5, 6)).shape == (5, 6) + c.shape[2:]
+
+        dp = p.derivative()
+        assert dp.c.shape == (5, 2, 1, 2, 3)
+
+    def test_interval_length(self, xp):
+        x = xp.asarray([0, 2])
+        c = xp.asarray([[3], [1], [4]])
+        bp = BPoly(c, x)
+        xval = 0.1
+        s = xval / 2  # s = (x - xa) / (xb - xa)
+        xp_assert_close(
+            bp(xval),
+            xp.asarray(3 * (1-s)*(1-s) + 1 * 2*s*(1-s) + 4 * s*s, dtype=xp.float64)
+        )
+
+    def test_two_intervals(self, xp):
+        x = xp.asarray([0, 1, 3])
+        c = xp.asarray([[3, 0], [0, 0], [0, 2]])
+        bp = BPoly(c, x)  # [3*(1-x)**2, 2*((x-1)/2)**2]
+
+        xp_assert_close(bp(0.4), xp.asarray(3 * 0.6*0.6, dtype=xp.float64))
+        xp_assert_close(bp(1.7), xp.asarray(2 * (0.7/2)**2, dtype=xp.float64))
+
+    def test_extrapolate_attr(self, xp):
+        x = xp.asarray([0, 2], dtype=xp.float64)
+        c = xp.asarray([[3], [1], [4]], dtype=xp.float64)
+        bp = BPoly(c, x)
+
+        for extrapolate in (True, False, None):
+            bp = BPoly(c, x, extrapolate=extrapolate)
+            bp_d = bp.derivative()
+            if extrapolate is False:
+                assert xp.all(xp.isnan(bp(xp.asarray([-0.1, 2.1]))))
+                assert xp.all(xp.isnan(bp_d(xp.asarray([-0.1, 2.1]))))
+            else:
+                assert not xp.any(xp.isnan(bp(xp.asarray([-0.1, 2.1]))))
+                assert not xp.any(xp.isnan(bp_d(xp.asarray([-0.1, 2.1]))))
+
+
+@make_xp_test_case(BPoly)
+class TestBPolyCalculus:
+    def test_derivative(self, xp):
+        x = xp.asarray([0, 1, 3])
+        c = xp.asarray([[3, 0], [0, 0], [0, 2]])
+        bp = BPoly(c, x)  # [3*(1-x)**2, 2*((x-1)/2)**2]
+        bp_der = bp.derivative()
+        xp_assert_close(bp_der(0.4), xp.asarray(-6*(0.6), dtype=xp.float64))
+        xp_assert_close(bp_der(1.7), xp.asarray(0.7, dtype=xp.float64))
+
+        # derivatives in-place
+        xp_assert_close(xp.stack([bp(0.4, nu) for nu in [1, 2, 3]]),
+                        xp.asarray([-6*(1-0.4), 6., 0.], dtype=xp.float64)
+        )
+        xp_assert_close(xp.stack([bp(1.7, nu) for nu in [1, 2, 3]]),
+                        xp.asarray([0.7, 1., 0], dtype=xp.float64)
+        )
+
+    def test_derivative_ppoly(self, xp):
+        # make sure it's consistent w/ power basis
+        rng = np.random.RandomState(1234)
+        m, k = 5, 8   # number of intervals, order
+        x = np.sort(rng.random(m))
+        c = rng.random((k, m-1))
+
+        c, x = xp.asarray(c), xp.asarray(x)
+        bp = BPoly(c, x)
+        pp = PPoly.from_bernstein_basis(bp)
+
+        for d in range(k):
+            bp = bp.derivative()
+            pp = pp.derivative()
+            xpp = xp.linspace(x[0], x[-1], 21)
+            xp_assert_close(bp(xpp), pp(xpp))
+
+    def test_deriv_inplace(self, xp):
+        rng = np.random.RandomState(1234)
+        m, k = 5, 8   # number of intervals, order
+        x_np = np.sort(rng.random(m))
+        c_np = rng.random((k, m-1))
+
+        # test both real and complex coefficients
+        for cc_np in [c_np.copy(), c_np*(1. + 2.j)]:
+            cc, x = xp.asarray(cc_np), xp.asarray(x_np)
+            bp = BPoly(cc, x)
+            xpp = xp.linspace(x[0], x[-1], 21)
+            for i in range(k):
+                xp_assert_close(bp(xpp, i), bp.derivative(i)(xpp))
+
+    def test_antiderivative_simple(self, xp):
+        # f(x) = x        for x \in [0, 1),
+        #        (x-1)/2  for x \in [1, 3]
+        #
+        # antiderivative is then
+        # F(x) = x**2 / 2            for x \in [0, 1),
+        #        0.5*x*(x/2 - 1) + A  for x \in [1, 3]
+        # where A = 3/4 for continuity at x = 1.
+        x = xp.asarray([0, 1, 3])
+        c = xp.asarray([[0, 0], [1, 1]])
+
+        bp = BPoly(c, x)
+        bi = bp.antiderivative()
+
+        xx = xp.linspace(0, 3, 11, dtype=xp.float64)
+        xp_assert_close(bi(xx),
+                        xp.where(xx < 1, xx**2 / 2.,
+                                         0.5 * xx * (xx/2. - 1) + 3./4),
+                        atol=1e-12, rtol=1e-12)
+
+    def test_der_antider(self, xp):
+        rng = np.random.RandomState(1234)
+        x = xp.asarray(np.sort(rng.random(11)), dtype=xp.float64)
+        c = xp.asarray(rng.random((4, 10, 2, 3)), dtype=xp.float64)
+        bp = BPoly(c, x)
+
+        xx = xp.linspace(x[0], x[-1], 100)
+        xp_assert_close(bp.antiderivative().derivative()(xx),
+                        bp(xx), atol=1e-12, rtol=1e-12)
+
+    def test_antider_ppoly(self):
+        rng = np.random.RandomState(1234)
+        x = np.sort(rng.random(11))
+        c = rng.random((4, 10, 2, 3))
+        bp = BPoly(c, x)
+        pp = PPoly.from_bernstein_basis(bp)
+
+        xx = np.linspace(x[0], x[-1], 10)
+
+        xp_assert_close(bp.antiderivative(2)(xx),
+                        pp.antiderivative(2)(xx), atol=1e-12, rtol=1e-12)
+
+    def test_antider_continuous(self, xp):
+        rng = np.random.RandomState(1234)
+        x = xp.asarray(np.sort(rng.random(11)), dtype=xp.float64)
+        c = xp.asarray(rng.random((4, 10)), dtype=xp.float64)
+        bp = BPoly(c, x).antiderivative()
+
+        xx = bp.x[1:-1]
+        xp_assert_close(bp(xx - 1e-14),
+                        bp(xx + 1e-14), atol=1e-12, rtol=1e-12)
+
+    def test_integrate(self, xp):
+        rng = np.random.RandomState(1234)
+        x = np.sort(rng.random(11))
+        c = rng.random((4, 10))
+        x, c = xp.asarray(x), xp.asarray(c)
+        bp = BPoly(c, x)
+        pp = PPoly.from_bernstein_basis(bp)
+        xp_assert_close(bp.integrate(0, 1),
+                        pp.integrate(0, 1), atol=1e-12, rtol=1e-12, check_0d=False)
+
+    def test_integrate_extrap(self, xp):
+        c = xp.asarray([[1]], dtype=xp.float64)
+        x = xp.asarray([0, 1], dtype=xp.float64)
+        b = BPoly(c, x)
+
+        # default is extrapolate=True
+        xp_assert_close(b.integrate(0, 2), xp.asarray(2., dtype=xp.float64),
+                        atol=1e-14, check_0d=False)
+
+        # .integrate argument overrides self.extrapolate
+        b1 = BPoly(c, x, extrapolate=False)
+        assert xp.isnan(b1.integrate(0, 2))
+        xp_assert_close(b1.integrate(0, 2, extrapolate=True),
+                        xp.asarray(2., dtype=xp.float64), atol=1e-14, check_0d=False)
+
+    def test_integrate_periodic(self, xp):
+        x = xp.asarray([1, 2, 4])
+        c = xp.asarray([[0., 0.], [-1., -1.], [2., -0.], [1., 2.]])
+
+        P = BPoly.from_power_basis(PPoly(c, x), extrapolate='periodic')
+        I = P.antiderivative()
+
+        period_int = xp.asarray(I(4) - I(1))
+
+        xp_assert_close(P.integrate(1, 4), period_int) #, check_0d=False)
+        xp_assert_close(P.integrate(-10, -7), period_int)
+        xp_assert_close(P.integrate(-10, -4), xp.asarray(2 * period_int))
+
+        xp_assert_close(P.integrate(1.5, 2.5), xp.asarray(I(2.5) - I(1.5)))
+        xp_assert_close(P.integrate(3.5, 5), xp.asarray(I(2) - I(1) + I(4) - I(3.5)))
+        xp_assert_close(P.integrate(3.5 + 12, 5 + 12),
+                        xp.asarray(I(2) - I(1) + I(4) - I(3.5)))
+        xp_assert_close(P.integrate(3.5, 5 + 12),
+                        xp.asarray(I(2) - I(1) + I(4) - I(3.5) + 4 * period_int))
+
+        xp_assert_close(P.integrate(0, -1), xp.asarray(I(2) - I(3)))
+        xp_assert_close(P.integrate(-9, -10), xp.asarray(I(2) - I(3)))
+        xp_assert_close(P.integrate(0, -10), xp.asarray(I(2) - I(3) - 3 * period_int))
+
+    def test_antider_neg(self, xp):
+        # .derivative(-nu) ==> .andiderivative(nu) and vice versa
+        c = xp.asarray([[1]])
+        x = xp.asarray([0, 1])
+        b = BPoly(c, x)
+
+        xx = xp.linspace(0, 1, 21)
+
+        xp_assert_close(b.derivative(-1)(xx), b.antiderivative()(xx),
+                        atol=1e-12, rtol=1e-12)
+        xp_assert_close(b.derivative(1)(xx), b.antiderivative(-1)(xx),
+                        atol=1e-12, rtol=1e-12)
+
+
+@make_xp_test_case(BPoly, PPoly)
+class TestPolyConversions:
+    def test_bp_from_pp(self, xp):
+        x = xp.asarray([0, 1, 3])
+        c = xp.asarray([[3, 2], [1, 8], [4, 3]])
+        pp = PPoly(c, x)
+        bp = BPoly.from_power_basis(pp)
+        pp1 = PPoly.from_bernstein_basis(bp)
+
+        xv = xp.asarray([0.1, 1.4])
+        xp_assert_close(pp(xv), bp(xv))
+        xp_assert_close(pp(xv), pp1(xv))
+
+    def test_bp_from_pp_random(self, xp):
+        rng = np.random.RandomState(1234)
+        m, k = 5, 8   # number of intervals, order
+        x = xp.asarray(np.sort(rng.random(m)))
+        c = xp.asarray(rng.random((k, m-1)))
+        pp = PPoly(c, x)
+        bp = BPoly.from_power_basis(pp)
+        pp1 = PPoly.from_bernstein_basis(bp)
+
+        xv = xp.linspace(x[0], x[-1], 21)
+        xp_assert_close(pp(xv), bp(xv))
+        xp_assert_close(pp(xv), pp1(xv))
+
+    def test_pp_from_bp(self, xp):
+        x = xp.asarray([0, 1, 3], dtype=xp.float64)
+        c = xp.asarray([[3, 3], [1, 1], [4, 2]], dtype=xp.float64)
+        bp = BPoly(c, x)
+        pp = PPoly.from_bernstein_basis(bp)
+        bp1 = BPoly.from_power_basis(pp)
+
+        xv = xp.asarray([0.1, 1.4])
+        xp_assert_close(bp(xv), pp(xv))
+        xp_assert_close(bp(xv), bp1(xv))
+
+    def test_broken_conversions(self, xp):
+        # regression test for gh-10597: from_power_basis only accepts PPoly etc.
+        x = xp.asarray([0, 1, 3], dtype=xp.float64)
+        c = xp.asarray([[3, 3], [1, 1], [4, 2]], dtype=xp.float64)
+        pp = PPoly(c, x)
+        with assert_raises(TypeError):
+            PPoly.from_bernstein_basis(pp)
+
+        bp = BPoly(c, x)
+        with assert_raises(TypeError):
+            BPoly.from_power_basis(bp)
+
+
+@make_xp_test_case(BPoly)
+class TestBPolyFromDerivatives:
+    def test_make_poly_1(self, xp):
+        c1 = BPoly._construct_from_derivatives(
+            0, 1, xp.asarray([2], dtype=xp.float64), xp.asarray([3], dtype=xp.float64)
+        )
+        xp_assert_close(c1, xp.asarray([2., 3.], dtype=xp.float64))
+
+    def test_make_poly_2(self, xp):
+        c1 = BPoly._construct_from_derivatives(
+            0, 1, xp.asarray([1, 0], dtype=xp.float64),
+            xp.asarray([1], dtype=xp.float64)
+        )
+        xp_assert_close(c1, xp.asarray([1., 1., 1.], dtype=xp.float64))
+
+        # f'(0) = 3
+        c2 = BPoly._construct_from_derivatives(
+            0, 1, xp.asarray([2, 3], dtype=xp.float64),
+            xp.asarray([1], dtype=xp.float64)
+        )
+        xp_assert_close(c2, xp.asarray([2., 7./2, 1.], dtype=xp.float64))
+
+        # f'(1) = 3
+        c3 = BPoly._construct_from_derivatives(
+            0, 1, xp.asarray([2], dtype=xp.float64),
+            xp.asarray([1, 3], dtype=xp.float64)
+        )
+        xp_assert_close(c3, xp.asarray([2., -0.5, 1.], dtype=xp.float64))
+
+    def test_make_poly_3(self, xp):
+        # f'(0)=2, f''(0)=3
+        c1 = BPoly._construct_from_derivatives(
+            0, 1, xp.asarray([1, 2, 3], dtype=xp.float64),
+            xp.asarray([4], dtype=xp.float64)
+        )
+        xp_assert_close(c1, xp.asarray([1., 5./3, 17./6, 4.], dtype=xp.float64))
+
+        # f'(1)=2, f''(1)=3
+        c2 = BPoly._construct_from_derivatives(
+            0, 1, xp.asarray([1], dtype=xp.float64),
+            xp.asarray([4, 2, 3], dtype=xp.float64),
+        )
+        xp_assert_close(c2, xp.asarray([1., 19./6, 10./3, 4.], dtype=xp.float64))
+
+        # f'(0)=2, f'(1)=3
+        c3 = BPoly._construct_from_derivatives(
+            0, 1, xp.asarray([1, 2], dtype=xp.float64),
+            xp.asarray([4, 3], dtype=xp.float64),
+        )
+        xp_assert_close(c3, xp.asarray([1., 5./3, 3., 4.], dtype=xp.float64))
+
+    def test_make_poly_12(self, xp):
+        rng = np.random.RandomState(12345)
+        ya = xp.asarray(np.r_[0, rng.random(5)])
+        yb = xp.asarray(np.r_[0, rng.random(5)])
+
+        c = BPoly._construct_from_derivatives(0, 1, ya, yb)
+        pp = BPoly(c[:, None], xp.asarray([0, 1], dtype=xp.float64))
+        for j in range(6):
+            xp_assert_close(pp(0.), ya[j], check_0d=False)
+            xp_assert_close(pp(1.), yb[j], check_0d=False)
+            pp = pp.derivative()
+
+    def test_raise_degree(self, xp):
+        rng = np.random.RandomState(12345)
+        x = xp.asarray([0, 1], dtype=xp.float64)
+        k, d = 8, 5
+        c = xp.asarray(rng.random((k, 1, 2, 3, 4)), dtype=xp.float64)
+        bp = BPoly(c, x)
+
+        c1 = BPoly._raise_degree(c, d)
+        bp1 = BPoly(c1, x)
+
+        xp = xp.linspace(0, 1, 11)
+        xp_assert_close(bp(xp), bp1(xp))
+
+    def test_xi_yi(self, xp):
+        assert_raises(
+            ValueError, BPoly.from_derivatives,
+            xp.asarray([0, 1], dtype=xp.float64), xp.asarray([0], dtype=xp.float64)
+        )
+
+    def test_coords_order(self, xp):
+        xi = xp.asarray([0, 0, 1], dtype=xp.float64)
+        yi = xp.asarray([[0], [0], [0]], dtype=xp.float64)
+        assert_raises(ValueError, BPoly.from_derivatives, xi, yi)
+
+    def test_zeros(self, xp):
+        xi = xp.asarray([0, 1, 2, 3], dtype=xp.float64)
+        # NB: will have to raise the degree
+        yi = list(
+            map(
+                lambda x: xp.asarray(x, dtype=xp.float64),
+                [[0, 0], [0], [0, 0], [0, 0]],
+            )
+        )
+        pp = BPoly.from_derivatives(xi, yi)
+        assert pp.c.shape == (4, 3)
+
+        ppd = pp.derivative()
+        for x_p in [0., 0.1, 1., 1.1, 1.9, 2., 2.5]:
+            xp_assert_close(pp(x_p), xp.asarray(0.0, dtype=xp.float64))
+            xp_assert_close(ppd(x_p), xp.asarray(0.0, dtype=xp.float64))
+
+    def _make_random_mk(self, m, k, xp):
+        # k derivatives at each breakpoint
+        rng = np.random.RandomState(1234)
+        xi = xp.asarray([1. * j**2 for j in range(m+1)], dtype=xp.float64)
+        yi = [xp.asarray(rng.random(k)) for j in range(m+1)]
+        return xi, yi
+
+    def test_random_12(self, xp):
+        m, k = 5, 12
+        xi, yi = self._make_random_mk(m, k, xp)
+        pp = BPoly.from_derivatives(xi, yi)
+
+        for order in range(k//2):
+            xp_assert_close(pp(xi), xp.stack([yy[order] for yy in yi]))
+            pp = pp.derivative()
+
+    def test_order_zero(self, xp):
+        m, k = 5, 12
+        xi, yi = self._make_random_mk(m, k, xp)
+        assert_raises(ValueError, BPoly.from_derivatives,
+                **dict(xi=xi, yi=yi, orders=0))
+
+    def test_orders_too_high(self, xp):
+        m, k = 5, 12
+        xi, yi = self._make_random_mk(m, k, xp)
+
+        BPoly.from_derivatives(xi, yi, orders=2*k-1)   # this is still ok
+        assert_raises(ValueError, BPoly.from_derivatives,   # but this is not
+                **dict(xi=xi, yi=yi, orders=2*k))
+
+    def test_orders_global(self, xp):
+        m, k = 5, 12
+        xi, yi = self._make_random_mk(m, k, xp)
+
+        # ok, this is confusing. Local polynomials will be of the order 5
+        # which means that up to the 2nd derivatives will be used at each point
+        order = 5
+        pp = BPoly.from_derivatives(xi, yi, orders=order)
+
+        for j in range(order//2+1):
+            xp_assert_close(pp(xi[1:-1] - 1e-12), pp(xi[1:-1] + 1e-12))
+            pp = pp.derivative()
+        assert not xp.all(xpx.isclose(pp(xi[1:-1] - 1e-12), pp(xi[1:-1] + 1e-12)))
+
+        # now repeat with `order` being even: on each interval, it uses
+        # order//2 'derivatives' @ the right-hand endpoint and
+        # order//2+1 @ 'derivatives' the left-hand endpoint
+        order = 6
+        pp = BPoly.from_derivatives(xi, yi, orders=order)
+        for j in range(order//2):
+            xp_assert_close(pp(xi[1:-1] - 1e-12), pp(xi[1:-1] + 1e-12))
+            pp = pp.derivative()
+        assert not xp.all(xpx.isclose(pp(xi[1:-1] - 1e-12), pp(xi[1:-1] + 1e-12)))
+
+    def test_orders_local(self, xp):
+        m, k = 7, 12
+        xi, yi = self._make_random_mk(m, k, xp)
+
+        orders = [o + 1 for o in range(m)]
+        for i, x in enumerate(xi[1:-1]):
+            pp = BPoly.from_derivatives(xi, yi, orders=orders)
+            for j in range(orders[i] // 2 + 1):
+                xp_assert_close(pp(x - 1e-12), pp(x + 1e-12))
+                pp = pp.derivative()
+            assert not xp.all(xpx.isclose(pp(x - 1e-12), pp(x + 1e-12)))
+
+    def test_yi_trailing_dims(self, xp):
+        rng = np.random.RandomState(1234)
+        m, k = 7, 5
+        xi = xp.asarray(np.sort(rng.random(m+1)))
+        yi = xp.asarray(rng.random((m+1, k, 6, 7, 8)))
+        pp = BPoly.from_derivatives(xi, yi)
+        assert pp.c.shape == (2*k, m, 6, 7, 8)
+
+    def test_gh_5430(self):
+        # At least one of these raises an error unless gh-5430 is
+        # fixed. In py2k an int is implemented using a C long, so
+        # which one fails depends on your system. In py3k there is only
+        # one arbitrary precision integer type, so both should fail.
+        orders = np.int32(1)
+        p = BPoly.from_derivatives([0, 1], [[0], [0]], orders=orders)
+        assert_almost_equal(p(0), np.asarray(0))
+        orders = np.int64(1)
+        p = BPoly.from_derivatives([0, 1], [[0], [0]], orders=orders)
+        assert_almost_equal(p(0), np.asarray(0))
+        orders = 1
+        # This worked before; make sure it still works
+        p = BPoly.from_derivatives([0, 1], [[0], [0]], orders=orders)
+        assert_almost_equal(p(0), np.asarray(0))
+        orders = 1
+
+
+class TestNdPPoly:
+    def test_simple_1d(self):
+        rng = np.random.RandomState(1234)
+
+        c = rng.rand(4, 5)
+        x = np.linspace(0, 1, 5+1)
+
+        xi = rng.rand(200)
+
+        p = NdPPoly(c, (x,))
+        v1 = p((xi,))
+
+        v2 = _ppoly_eval_1(c[:,:,None], x, xi).ravel()
+        xp_assert_close(v1, v2)
+
+    def test_simple_2d(self):
+        rng = np.random.RandomState(1234)
+
+        c = rng.rand(4, 5, 6, 7)
+        x = np.linspace(0, 1, 6+1)
+        y = np.linspace(0, 1, 7+1)**2
+
+        xi = rng.rand(200)
+        yi = rng.rand(200)
+
+        v1 = np.empty([len(xi), 1], dtype=c.dtype)
+        v1.fill(np.nan)
+        _ppoly.evaluate_nd(c.reshape(4*5, 6*7, 1),
+                           (x, y),
+                           np.array([4, 5], dtype=np.intc),
+                           np.c_[xi, yi],
+                           np.array([0, 0], dtype=np.intc),
+                           1,
+                           v1)
+        v1 = v1.ravel()
+        v2 = _ppoly2d_eval(c, (x, y), xi, yi)
+        xp_assert_close(v1, v2)
+
+        p = NdPPoly(c, (x, y))
+        for nu in (None, (0, 0), (0, 1), (1, 0), (2, 3), (9, 2)):
+            v1 = p(np.c_[xi, yi], nu=nu)
+            v2 = _ppoly2d_eval(c, (x, y), xi, yi, nu=nu)
+            xp_assert_close(v1, v2, err_msg=repr(nu))
+
+    def test_simple_3d(self):
+        rng = np.random.RandomState(1234)
+
+        c = rng.rand(4, 5, 6, 7, 8, 9)
+        x = np.linspace(0, 1, 7+1)
+        y = np.linspace(0, 1, 8+1)**2
+        z = np.linspace(0, 1, 9+1)**3
+
+        xi = rng.rand(40)
+        yi = rng.rand(40)
+        zi = rng.rand(40)
+
+        p = NdPPoly(c, (x, y, z))
+
+        for nu in (None, (0, 0, 0), (0, 1, 0), (1, 0, 0), (2, 3, 0),
+                   (6, 0, 2)):
+            v1 = p((xi, yi, zi), nu=nu)
+            v2 = _ppoly3d_eval(c, (x, y, z), xi, yi, zi, nu=nu)
+            xp_assert_close(v1, v2, err_msg=repr(nu))
+
+    def test_simple_4d(self):
+        rng = np.random.RandomState(1234)
+
+        c = rng.rand(4, 5, 6, 7, 8, 9, 10, 11)
+        x = np.linspace(0, 1, 8+1)
+        y = np.linspace(0, 1, 9+1)**2
+        z = np.linspace(0, 1, 10+1)**3
+        u = np.linspace(0, 1, 11+1)**4
+
+        xi = rng.rand(20)
+        yi = rng.rand(20)
+        zi = rng.rand(20)
+        ui = rng.rand(20)
+
+        p = NdPPoly(c, (x, y, z, u))
+        v1 = p((xi, yi, zi, ui))
+
+        v2 = _ppoly4d_eval(c, (x, y, z, u), xi, yi, zi, ui)
+        xp_assert_close(v1, v2)
+
+    def test_deriv_1d(self):
+        rng = np.random.RandomState(1234)
+
+        c = rng.rand(4, 5)
+        x = np.linspace(0, 1, 5+1)
+
+        p = NdPPoly(c, (x,))
+
+        # derivative
+        dp = p.derivative(nu=[1])
+        p1 = PPoly(c, x)
+        dp1 = p1.derivative()
+        xp_assert_close(dp.c, dp1.c)
+
+        # antiderivative
+        dp = p.antiderivative(nu=[2])
+        p1 = PPoly(c, x)
+        dp1 = p1.antiderivative(2)
+        xp_assert_close(dp.c, dp1.c)
+
+    def test_deriv_3d(self):
+        rng = np.random.RandomState(1234)
+
+        c = rng.rand(4, 5, 6, 7, 8, 9)
+        x = np.linspace(0, 1, 7+1)
+        y = np.linspace(0, 1, 8+1)**2
+        z = np.linspace(0, 1, 9+1)**3
+
+        p = NdPPoly(c, (x, y, z))
+
+        # differentiate vs x
+        p1 = PPoly(c.transpose(0, 3, 1, 2, 4, 5), x)
+        dp = p.derivative(nu=[2])
+        dp1 = p1.derivative(2)
+        xp_assert_close(dp.c,
+                        dp1.c.transpose(0, 2, 3, 1, 4, 5))
+
+        # antidifferentiate vs y
+        p1 = PPoly(c.transpose(1, 4, 0, 2, 3, 5), y)
+        dp = p.antiderivative(nu=[0, 1, 0])
+        dp1 = p1.antiderivative(1)
+        xp_assert_close(dp.c,
+                        dp1.c.transpose(2, 0, 3, 4, 1, 5))
+
+        # differentiate vs z
+        p1 = PPoly(c.transpose(2, 5, 0, 1, 3, 4), z)
+        dp = p.derivative(nu=[0, 0, 3])
+        dp1 = p1.derivative(3)
+        xp_assert_close(dp.c,
+                        dp1.c.transpose(2, 3, 0, 4, 5, 1))
+
+    def test_deriv_3d_simple(self):
+        # Integrate to obtain function x y**2 z**4 / (2! 4!)
+        rng = np.random.RandomState(1234)
+
+        c = np.ones((1, 1, 1, 3, 4, 5))
+        x = np.linspace(0, 1, 3+1)**1
+        y = np.linspace(0, 1, 4+1)**2
+        z = np.linspace(0, 1, 5+1)**3
+
+        p = NdPPoly(c, (x, y, z))
+        ip = p.antiderivative((1, 0, 4))
+        ip = ip.antiderivative((0, 2, 0))
+
+        xi = rng.rand(20)
+        yi = rng.rand(20)
+        zi = rng.rand(20)
+
+        xp_assert_close(ip((xi, yi, zi)),
+                        xi * yi**2 * zi**4 / (gamma(3)*gamma(5)))
+
+    def test_integrate_2d(self):
+        rng = np.random.RandomState(1234)
+        c = rng.rand(4, 5, 16, 17)
+        x = np.linspace(0, 1, 16+1)**1
+        y = np.linspace(0, 1, 17+1)**2
+
+        # make continuously differentiable so that nquad() has an
+        # easier time
+        c = c.transpose(0, 2, 1, 3)
+        cx = c.reshape(c.shape[0], c.shape[1], -1).copy()
+        _ppoly.fix_continuity(cx, x, 2)
+        c = cx.reshape(c.shape)
+        c = c.transpose(0, 2, 1, 3)
+        c = c.transpose(1, 3, 0, 2)
+        cx = c.reshape(c.shape[0], c.shape[1], -1).copy()
+        _ppoly.fix_continuity(cx, y, 2)
+        c = cx.reshape(c.shape)
+        c = c.transpose(2, 0, 3, 1).copy()
+
+        # Check integration
+        p = NdPPoly(c, (x, y))
+
+        for ranges in [[(0, 1), (0, 1)],
+                       [(0, 0.5), (0, 1)],
+                       [(0, 1), (0, 0.5)],
+                       [(0.3, 0.7), (0.6, 0.2)]]:
+
+            ig = p.integrate(ranges)
+            ig2, err2 = nquad(lambda x, y: p((x, y)), ranges,
+                              opts=[dict(epsrel=1e-5, epsabs=1e-5)]*2)
+            xp_assert_close(ig, ig2, rtol=1e-5, atol=1e-5, check_0d=False,
+                            err_msg=repr(ranges))
+
+    def test_integrate_1d(self):
+        rng = np.random.RandomState(1234)
+        c = rng.rand(4, 5, 6, 16, 17, 18)
+        x = np.linspace(0, 1, 16+1)**1
+        y = np.linspace(0, 1, 17+1)**2
+        z = np.linspace(0, 1, 18+1)**3
+
+        # Check 1-D integration
+        p = NdPPoly(c, (x, y, z))
+
+        u = rng.rand(200)
+        v = rng.rand(200)
+        a, b = 0.2, 0.7
+
+        px = p.integrate_1d(a, b, axis=0)
+        pax = p.antiderivative((1, 0, 0))
+        xp_assert_close(px((u, v)), pax((b, u, v)) - pax((a, u, v)))
+
+        py = p.integrate_1d(a, b, axis=1)
+        pay = p.antiderivative((0, 1, 0))
+        xp_assert_close(py((u, v)), pay((u, b, v)) - pay((u, a, v)))
+
+        pz = p.integrate_1d(a, b, axis=2)
+        paz = p.antiderivative((0, 0, 1))
+        xp_assert_close(pz((u, v)), paz((u, v, b)) - paz((u, v, a)))
+
+    def test_concurrency(self):
+        rng = np.random.default_rng(12345)
+
+        c = rng.uniform(size=(4, 5, 6, 7, 8, 9))
+        x = np.linspace(0, 1, 7+1)
+        y = np.linspace(0, 1, 8+1)**2
+        z = np.linspace(0, 1, 9+1)**3
+
+        p = NdPPoly(c, (x, y, z))
+
+        def worker_fn(_, spl):
+            xi = rng.uniform(size=40)
+            yi = rng.uniform(size=40)
+            zi = rng.uniform(size=40)
+            spl((xi, yi, zi))
+
+        _run_concurrent_barrier(10, worker_fn, p)
+
+
+def _ppoly_eval_1(c, x, xps):
+    """Evaluate piecewise polynomial manually"""
+    out = np.zeros((len(xps), c.shape[2]))
+    for i, xp in enumerate(xps):
+        if xp < 0 or xp > 1:
+            out[i,:] = np.nan
+            continue
+        j = np.searchsorted(x, xp) - 1
+        d = xp - x[j]
+        assert x[j] <= xp < x[j+1]
+        r = sum(c[k,j] * d**(c.shape[0]-k-1)
+                for k in range(c.shape[0]))
+        out[i,:] = r
+    return out
+
+
+def _ppoly_eval_2(coeffs, breaks, xnew, fill=np.nan):
+    """Evaluate piecewise polynomial manually (another way)"""
+    a = breaks[0]
+    b = breaks[-1]
+    K = coeffs.shape[0]
+
+    saveshape = np.shape(xnew)
+    xnew = np.ravel(xnew)
+    res = np.empty_like(xnew)
+    mask = (xnew >= a) & (xnew <= b)
+    res[~mask] = fill
+    xx = xnew.compress(mask)
+    indxs = np.searchsorted(breaks, xx)-1
+    indxs = indxs.clip(0, len(breaks))
+    pp = coeffs
+    diff = xx - breaks.take(indxs)
+    V = np.vander(diff, N=K)
+    values = np.array([np.dot(V[k, :], pp[:, indxs[k]]) for k in range(len(xx))])
+    res[mask] = values
+    res = res.reshape(saveshape)
+    return res
+
+
+def _dpow(x, y, n):
+    """
+    d^n (x**y) / dx^n
+    """
+    if n < 0:
+        raise ValueError("invalid derivative order")
+    elif n > y:
+        return 0
+    else:
+        return poch(y - n + 1, n) * x**(y - n)
+
+
+def _ppoly2d_eval(c, xs, xnew, ynew, nu=None):
+    """
+    Straightforward evaluation of 2-D piecewise polynomial
+    """
+    if nu is None:
+        nu = (0, 0)
+
+    out = np.empty((len(xnew),), dtype=c.dtype)
+
+    nx, ny = c.shape[:2]
+
+    for jout, (x, y) in enumerate(zip(xnew, ynew)):
+        if not ((xs[0][0] <= x <= xs[0][-1]) and
+                (xs[1][0] <= y <= xs[1][-1])):
+            out[jout] = np.nan
+            continue
+
+        j1 = np.searchsorted(xs[0], x) - 1
+        j2 = np.searchsorted(xs[1], y) - 1
+
+        s1 = x - xs[0][j1]
+        s2 = y - xs[1][j2]
+
+        val = 0
+
+        for k1 in range(c.shape[0]):
+            for k2 in range(c.shape[1]):
+                val += (c[nx-k1-1,ny-k2-1,j1,j2]
+                        * _dpow(s1, k1, nu[0])
+                        * _dpow(s2, k2, nu[1]))
+
+        out[jout] = val
+
+    return out
+
+
+def _ppoly3d_eval(c, xs, xnew, ynew, znew, nu=None):
+    """
+    Straightforward evaluation of 3-D piecewise polynomial
+    """
+    if nu is None:
+        nu = (0, 0, 0)
+
+    out = np.empty((len(xnew),), dtype=c.dtype)
+
+    nx, ny, nz = c.shape[:3]
+
+    for jout, (x, y, z) in enumerate(zip(xnew, ynew, znew)):
+        if not ((xs[0][0] <= x <= xs[0][-1]) and
+                (xs[1][0] <= y <= xs[1][-1]) and
+                (xs[2][0] <= z <= xs[2][-1])):
+            out[jout] = np.nan
+            continue
+
+        j1 = np.searchsorted(xs[0], x) - 1
+        j2 = np.searchsorted(xs[1], y) - 1
+        j3 = np.searchsorted(xs[2], z) - 1
+
+        s1 = x - xs[0][j1]
+        s2 = y - xs[1][j2]
+        s3 = z - xs[2][j3]
+
+        val = 0
+        for k1 in range(c.shape[0]):
+            for k2 in range(c.shape[1]):
+                for k3 in range(c.shape[2]):
+                    val += (c[nx-k1-1,ny-k2-1,nz-k3-1,j1,j2,j3]
+                            * _dpow(s1, k1, nu[0])
+                            * _dpow(s2, k2, nu[1])
+                            * _dpow(s3, k3, nu[2]))
+
+        out[jout] = val
+
+    return out
+
+
+def _ppoly4d_eval(c, xs, xnew, ynew, znew, unew, nu=None):
+    """
+    Straightforward evaluation of 4-D piecewise polynomial
+    """
+    if nu is None:
+        nu = (0, 0, 0, 0)
+
+    out = np.empty((len(xnew),), dtype=c.dtype)
+
+    mx, my, mz, mu = c.shape[:4]
+
+    for jout, (x, y, z, u) in enumerate(zip(xnew, ynew, znew, unew)):
+        if not ((xs[0][0] <= x <= xs[0][-1]) and
+                (xs[1][0] <= y <= xs[1][-1]) and
+                (xs[2][0] <= z <= xs[2][-1]) and
+                (xs[3][0] <= u <= xs[3][-1])):
+            out[jout] = np.nan
+            continue
+
+        j1 = np.searchsorted(xs[0], x) - 1
+        j2 = np.searchsorted(xs[1], y) - 1
+        j3 = np.searchsorted(xs[2], z) - 1
+        j4 = np.searchsorted(xs[3], u) - 1
+
+        s1 = x - xs[0][j1]
+        s2 = y - xs[1][j2]
+        s3 = z - xs[2][j3]
+        s4 = u - xs[3][j4]
+
+        val = 0
+        for k1 in range(c.shape[0]):
+            for k2 in range(c.shape[1]):
+                for k3 in range(c.shape[2]):
+                    for k4 in range(c.shape[3]):
+                        val += (c[mx-k1-1,my-k2-1,mz-k3-1,mu-k4-1,j1,j2,j3,j4]
+                                * _dpow(s1, k1, nu[0])
+                                * _dpow(s2, k2, nu[1])
+                                * _dpow(s3, k3, nu[2])
+                                * _dpow(s4, k4, nu[3]))
+
+        out[jout] = val
+
+    return out
+
+@pytest.mark.parametrize("interp", [make_interp_spline,  # BSpline
+                                    CubicSpline,
+                                    PchipInterpolator,
+                                    Akima1DInterpolator,
+                                    FloaterHormannInterpolator,
+                                    BarycentricInterpolator,
+                                    KroghInterpolator,
+                                    lambda x, y: BPoly.from_derivatives(
+                                        x,[[yi, yi, yi] for yi in y]),
+                                    lambda x, y: CubicHermiteSpline(x, y, y)])  # PPoly
+def test_pickleable_1D(interp):
+    x = np.linspace(0, 1, 10)
+    y = np.exp(x)
+    x_eval = np.linspace(0, 1, 100)
+    obj = interp(x, y)
+    y1 = obj(x_eval)
+    y2 = pickle.loads(pickle.dumps(obj))(x_eval)
+    xp_assert_close(y1, y2, atol=1e-12)
+
+
+@pytest.mark.parametrize("interp", [LinearNDInterpolator,
+                                    NearestNDInterpolator,
+                                    CloughTocher2DInterpolator,
+                                    RBFInterpolator,
+                                    RegularGridInterpolator,])
+def test_pickleable_2D(interp):
+    # generate data on a regular grid
+    x = np.linspace(0, 1, 5)
+    y = np.linspace(0, 1, 5)
+    X, Y = np.meshgrid(x, y)
+    Z = np.exp(X + Y)
+    points = np.column_stack([X.ravel(), Y.ravel()])
+    if interp is RegularGridInterpolator:
+        obj = interp((x, y), Z)
+    else:
+        obj = interp(points, Z.ravel())
+    x_eval = np.linspace(0, 1, 10)
+    y_eval = np.linspace(0, 1, 10)
+    X_eval, Y_eval = np.meshgrid(x_eval, y_eval)
+    eval_points = np.column_stack([X_eval.ravel(), Y_eval.ravel()])
+    Z1 = obj(eval_points)
+    Z2 = pickle.loads(pickle.dumps(obj))(eval_points)
+    xp_assert_close(Z1, Z2, atol=1e-12)
diff --git a/.venv/lib/python3.12/site-packages/scipy/interpolate/tests/test_ndgriddata.py b/.venv/lib/python3.12/site-packages/scipy/interpolate/tests/test_ndgriddata.py
new file mode 100644
index 0000000000000000000000000000000000000000..586189b647e4caab0bdb5e57f3247b9ed8632152
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/interpolate/tests/test_ndgriddata.py
@@ -0,0 +1,307 @@
+import numpy as np
+from scipy._lib._array_api import (
+    xp_assert_equal, xp_assert_close
+)
+import pytest
+from pytest import raises as assert_raises
+
+from scipy.interpolate import (griddata, NearestNDInterpolator,
+                               LinearNDInterpolator,
+                               CloughTocher2DInterpolator)
+from scipy._lib._testutils import _run_concurrent_barrier
+
+
+parametrize_interpolators = pytest.mark.parametrize(
+    "interpolator", [NearestNDInterpolator, LinearNDInterpolator,
+                     CloughTocher2DInterpolator]
+)
+parametrize_methods = pytest.mark.parametrize(
+    'method',
+    ('nearest', 'linear', 'cubic'),
+)
+parametrize_rescale = pytest.mark.parametrize(
+    'rescale',
+    (True, False),
+)
+
+
+class TestGriddata:
+    def test_fill_value(self):
+        x = [(0,0), (0,1), (1,0)]
+        y = [1, 2, 3]
+
+        yi = griddata(x, y, [(1,1), (1,2), (0,0)], fill_value=-1)
+        xp_assert_equal(yi, [-1., -1, 1])
+
+        yi = griddata(x, y, [(1,1), (1,2), (0,0)])
+        xp_assert_equal(yi, [np.nan, np.nan, 1])
+
+    @parametrize_methods
+    @parametrize_rescale
+    def test_alternative_call(self, method, rescale):
+        x = np.array([(0,0), (-0.5,-0.5), (-0.5,0.5), (0.5, 0.5), (0.25, 0.3)],
+                     dtype=np.float64)
+        y = (np.arange(x.shape[0], dtype=np.float64)[:,None]
+             + np.array([0,1])[None,:])
+
+        msg = repr((method, rescale))
+        yi = griddata((x[:,0], x[:,1]), y, (x[:,0], x[:,1]), method=method,
+                      rescale=rescale)
+        xp_assert_close(y, yi, atol=1e-14, err_msg=msg)
+
+    @parametrize_methods
+    @parametrize_rescale
+    def test_multivalue_2d(self, method, rescale):
+        x = np.array([(0,0), (-0.5,-0.5), (-0.5,0.5), (0.5, 0.5), (0.25, 0.3)],
+                     dtype=np.float64)
+        y = (np.arange(x.shape[0], dtype=np.float64)[:,None]
+             + np.array([0,1])[None,:])
+
+        msg = repr((method, rescale))
+        yi = griddata(x, y, x, method=method, rescale=rescale)
+        xp_assert_close(y, yi, atol=1e-14, err_msg=msg)
+
+    @parametrize_methods
+    @parametrize_rescale
+    def test_multipoint_2d(self, method, rescale):
+        x = np.array([(0,0), (-0.5,-0.5), (-0.5,0.5), (0.5, 0.5), (0.25, 0.3)],
+                     dtype=np.float64)
+        y = np.arange(x.shape[0], dtype=np.float64)
+
+        xi = x[:,None,:] + np.array([0,0,0])[None,:,None]
+
+        msg = repr((method, rescale))
+        yi = griddata(x, y, xi, method=method, rescale=rescale)
+
+        assert yi.shape == (5, 3), msg
+        xp_assert_close(yi, np.tile(y[:,None], (1, 3)),
+                        atol=1e-14, err_msg=msg)
+
+    @parametrize_methods
+    @parametrize_rescale
+    def test_complex_2d(self, method, rescale):
+        x = np.array([(0,0), (-0.5,-0.5), (-0.5,0.5), (0.5, 0.5), (0.25, 0.3)],
+                     dtype=np.float64)
+        y = np.arange(x.shape[0], dtype=np.float64)
+        y = y - 2j*y[::-1]
+
+        xi = x[:,None,:] + np.array([0,0,0])[None,:,None]
+
+        msg = repr((method, rescale))
+        yi = griddata(x, y, xi, method=method, rescale=rescale)
+
+        assert yi.shape == (5, 3)
+        xp_assert_close(yi, np.tile(y[:,None], (1, 3)),
+                        atol=1e-14, err_msg=msg)
+
+    @parametrize_methods
+    def test_1d(self, method):
+        x = np.array([1, 2.5, 3, 4.5, 5, 6])
+        y = np.array([1, 2, 0, 3.9, 2, 1])
+
+        xp_assert_close(griddata(x, y, x, method=method), y,
+                        err_msg=method, atol=1e-14)
+        xp_assert_close(griddata(x.reshape(6, 1), y, x, method=method), y,
+                        err_msg=method, atol=1e-14)
+        xp_assert_close(griddata((x,), y, (x,), method=method), y,
+                        err_msg=method, atol=1e-14)
+
+    def test_1d_borders(self):
+        # Test for nearest neighbor case with xi outside
+        # the range of the values.
+        x = np.array([1, 2.5, 3, 4.5, 5, 6])
+        y = np.array([1, 2, 0, 3.9, 2, 1])
+        xi = np.array([0.9, 6.5])
+        yi_should = np.array([1.0, 1.0])
+
+        method = 'nearest'
+        xp_assert_close(griddata(x, y, xi,
+                                 method=method), yi_should,
+                        err_msg=method,
+                        atol=1e-14)
+        xp_assert_close(griddata(x.reshape(6, 1), y, xi,
+                                 method=method), yi_should,
+                        err_msg=method,
+                        atol=1e-14)
+        xp_assert_close(griddata((x, ), y, (xi, ),
+                                 method=method), yi_should,
+                        err_msg=method,
+                        atol=1e-14)
+
+    @parametrize_methods
+    def test_1d_unsorted(self, method):
+        x = np.array([2.5, 1, 4.5, 5, 6, 3])
+        y = np.array([1, 2, 0, 3.9, 2, 1])
+
+        xp_assert_close(griddata(x, y, x, method=method), y,
+                        err_msg=method, atol=1e-10)
+        xp_assert_close(griddata(x.reshape(6, 1), y, x, method=method), y,
+                        err_msg=method, atol=1e-10)
+        xp_assert_close(griddata((x,), y, (x,), method=method), y,
+                        err_msg=method, atol=1e-10)
+
+    @parametrize_methods
+    def test_square_rescale_manual(self, method):
+        points = np.array([(0,0), (0,100), (10,100), (10,0), (1, 5)], dtype=np.float64)
+        points_rescaled = np.array([(0,0), (0,1), (1,1), (1,0), (0.1, 0.05)],
+                                   dtype=np.float64)
+        values = np.array([1., 2., -3., 5., 9.], dtype=np.float64)
+
+        xx, yy = np.broadcast_arrays(np.linspace(0, 10, 14)[:,None],
+                                     np.linspace(0, 100, 14)[None,:])
+        xx = xx.ravel()
+        yy = yy.ravel()
+        xi = np.array([xx, yy]).T.copy()
+
+        msg = method
+        zi = griddata(points_rescaled, values, xi/np.array([10, 100.]),
+                      method=method)
+        zi_rescaled = griddata(points, values, xi, method=method,
+                               rescale=True)
+        xp_assert_close(zi, zi_rescaled, err_msg=msg,
+                        atol=1e-12)
+
+    @parametrize_methods
+    def test_xi_1d(self, method):
+        # Check that 1-D xi is interpreted as a coordinate
+        x = np.array([(0,0), (-0.5,-0.5), (-0.5,0.5), (0.5, 0.5), (0.25, 0.3)],
+                     dtype=np.float64)
+        y = np.arange(x.shape[0], dtype=np.float64)
+        y = y - 2j*y[::-1]
+
+        xi = np.array([0.5, 0.5])
+
+        p1 = griddata(x, y, xi, method=method)
+        p2 = griddata(x, y, xi[None,:], method=method)
+        xp_assert_close(p1, p2, err_msg=method)
+
+        xi1 = np.array([0.5])
+        xi3 = np.array([0.5, 0.5, 0.5])
+        assert_raises(ValueError, griddata, x, y, xi1,
+                      method=method)
+        assert_raises(ValueError, griddata, x, y, xi3,
+                      method=method)
+
+
+class TestNearestNDInterpolator:
+    def test_nearest_options(self):
+        # smoke test that NearestNDInterpolator accept cKDTree options
+        npts, nd = 4, 3
+        x = np.arange(npts*nd).reshape((npts, nd))
+        y = np.arange(npts)
+        nndi = NearestNDInterpolator(x, y)
+
+        opts = {'balanced_tree': False, 'compact_nodes': False}
+        nndi_o = NearestNDInterpolator(x, y, tree_options=opts)
+        xp_assert_close(nndi(x), nndi_o(x), atol=1e-14)
+
+    def test_nearest_list_argument(self):
+        nd = np.array([[0, 0, 0, 0, 1, 0, 1],
+                       [0, 0, 0, 0, 0, 1, 1],
+                       [0, 0, 0, 0, 1, 1, 2]])
+        d = nd[:, 3:]
+
+        # z is np.array
+        NI = NearestNDInterpolator((d[0], d[1]), d[2])
+        xp_assert_equal(NI([0.1, 0.9], [0.1, 0.9]), [0.0, 2.0])
+
+        # z is list
+        NI = NearestNDInterpolator((d[0], d[1]), list(d[2]))
+        xp_assert_equal(NI([0.1, 0.9], [0.1, 0.9]), [0.0, 2.0])
+
+    def test_nearest_query_options(self):
+        nd = np.array([[0, 0.5, 0, 1],
+                       [0, 0, 0.5, 1],
+                       [0, 1, 1, 2]])
+        delta = 0.1
+        query_points = [0 + delta, 1 + delta], [0 + delta, 1 + delta]
+
+        # case 1 - query max_dist is smaller than
+        # the query points' nearest distance to nd.
+        NI = NearestNDInterpolator((nd[0], nd[1]), nd[2])
+        distance_upper_bound = np.sqrt(delta ** 2 + delta ** 2) - 1e-7
+        xp_assert_equal(NI(query_points, distance_upper_bound=distance_upper_bound),
+                           [np.nan, np.nan])
+
+        # case 2 - query p is inf, will return [0, 2]
+        distance_upper_bound = np.sqrt(delta ** 2 + delta ** 2) - 1e-7
+        p = np.inf
+        xp_assert_equal(
+            NI(query_points, distance_upper_bound=distance_upper_bound, p=p),
+            [0.0, 2.0]
+        )
+
+        # case 3 - query max_dist is larger, so should return non np.nan
+        distance_upper_bound = np.sqrt(delta ** 2 + delta ** 2) + 1e-7
+        xp_assert_equal(
+            NI(query_points, distance_upper_bound=distance_upper_bound),
+            [0.0, 2.0]
+        )
+
+    def test_nearest_query_valid_inputs(self):
+        nd = np.array([[0, 1, 0, 1],
+                       [0, 0, 1, 1],
+                       [0, 1, 1, 2]])
+        NI = NearestNDInterpolator((nd[0], nd[1]), nd[2])
+        with assert_raises(TypeError):
+            NI([0.5, 0.5], query_options="not a dictionary")
+
+    def test_concurrency(self):
+        npts, nd = 50, 3
+        x = np.arange(npts * nd).reshape((npts, nd))
+        y = np.arange(npts)
+        nndi = NearestNDInterpolator(x, y)
+
+        def worker_fn(_, spl):
+            spl(x)
+
+        _run_concurrent_barrier(10, worker_fn, nndi)
+
+
+class TestNDInterpolators:
+    @parametrize_interpolators
+    def test_broadcastable_input(self, interpolator):
+        # input data
+        rng = np.random.RandomState(0)
+        x = rng.random(10)
+        y = rng.random(10)
+        z = np.hypot(x, y)
+
+        # x-y grid for interpolation
+        X = np.linspace(min(x), max(x))
+        Y = np.linspace(min(y), max(y))
+        X, Y = np.meshgrid(X, Y)
+        XY = np.vstack((X.ravel(), Y.ravel())).T
+        interp = interpolator(list(zip(x, y)), z)
+        # single array input
+        interp_points0 = interp(XY)
+        # tuple input
+        interp_points1 = interp((X, Y))
+        interp_points2 = interp((X, 0.0))
+        # broadcastable input
+        interp_points3 = interp(X, Y)
+        interp_points4 = interp(X, 0.0)
+
+        assert (interp_points0.size ==
+                interp_points1.size ==
+                interp_points2.size ==
+                interp_points3.size ==
+                interp_points4.size)
+
+    @parametrize_interpolators
+    def test_read_only(self, interpolator):
+        # input data
+        rng = np.random.RandomState(0)
+        xy = rng.random((10, 2))
+        x, y = xy[:, 0], xy[:, 1]
+        z = np.hypot(x, y)
+
+        # interpolation points
+        XY = rng.random((50, 2))
+
+        xy.setflags(write=False)
+        z.setflags(write=False)
+        XY.setflags(write=False)
+
+        interp = interpolator(xy, z)
+        interp(XY)
diff --git a/.venv/lib/python3.12/site-packages/scipy/interpolate/tests/test_pade.py b/.venv/lib/python3.12/site-packages/scipy/interpolate/tests/test_pade.py
new file mode 100644
index 0000000000000000000000000000000000000000..cd2b3dc18ed3a9ce85a043e3c16593399fef5ac7
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/interpolate/tests/test_pade.py
@@ -0,0 +1,114 @@
+import numpy as np
+import pytest
+
+from scipy.interpolate import pade
+from scipy._lib._array_api import (
+    xp_assert_equal, assert_array_almost_equal
+)
+
+def test_pade_trivial():
+    with pytest.warns(DeprecationWarning, match="`pade` is deprecated"):
+        nump, denomp = pade([1.0], 0)
+    xp_assert_equal(nump.c, np.asarray([1.0]))
+    xp_assert_equal(denomp.c, np.asarray([1.0]))
+
+    with pytest.warns(DeprecationWarning, match="`pade` is deprecated"):
+        nump, denomp = pade([1.0], 0, 0)
+    xp_assert_equal(nump.c, np.asarray([1.0]))
+    xp_assert_equal(denomp.c, np.asarray([1.0]))
+
+
+@pytest.mark.filterwarnings("ignore: `pade` is deprecated")
+def test_pade_4term_exp():
+    # First four Taylor coefficients of exp(x).
+    # Unlike poly1d, the first array element is the zero-order term.
+    an = [1.0, 1.0, 0.5, 1.0/6]
+
+    nump, denomp = pade(an, 0)
+    assert_array_almost_equal(nump.c, [1.0/6, 0.5, 1.0, 1.0])
+    assert_array_almost_equal(denomp.c, [1.0])
+
+    nump, denomp = pade(an, 1)
+    assert_array_almost_equal(nump.c, [1.0/6, 2.0/3, 1.0])
+    assert_array_almost_equal(denomp.c, [-1.0/3, 1.0])
+
+    nump, denomp = pade(an, 2)
+    assert_array_almost_equal(nump.c, [1.0/3, 1.0])
+    assert_array_almost_equal(denomp.c, [1.0/6, -2.0/3, 1.0])
+
+    nump, denomp = pade(an, 3)
+    assert_array_almost_equal(nump.c, [1.0])
+    assert_array_almost_equal(denomp.c, [-1.0/6, 0.5, -1.0, 1.0])
+
+    # Testing inclusion of optional parameter
+    nump, denomp = pade(an, 0, 3)
+    assert_array_almost_equal(nump.c, [1.0/6, 0.5, 1.0, 1.0])
+    assert_array_almost_equal(denomp.c, [1.0])
+
+    nump, denomp = pade(an, 1, 2)
+    assert_array_almost_equal(nump.c, [1.0/6, 2.0/3, 1.0])
+    assert_array_almost_equal(denomp.c, [-1.0/3, 1.0])
+
+    nump, denomp = pade(an, 2, 1)
+    assert_array_almost_equal(nump.c, [1.0/3, 1.0])
+    assert_array_almost_equal(denomp.c, [1.0/6, -2.0/3, 1.0])
+
+    nump, denomp = pade(an, 3, 0)
+    assert_array_almost_equal(nump.c, [1.0])
+    assert_array_almost_equal(denomp.c, [-1.0/6, 0.5, -1.0, 1.0])
+
+    # Testing reducing array.
+    nump, denomp = pade(an, 0, 2)
+    assert_array_almost_equal(nump.c, [0.5, 1.0, 1.0])
+    assert_array_almost_equal(denomp.c, [1.0])
+
+    nump, denomp = pade(an, 1, 1)
+    assert_array_almost_equal(nump.c, [1.0/2, 1.0])
+    assert_array_almost_equal(denomp.c, [-1.0/2, 1.0])
+
+    nump, denomp = pade(an, 2, 0)
+    assert_array_almost_equal(nump.c, [1.0])
+    assert_array_almost_equal(denomp.c, [1.0/2, -1.0, 1.0])
+
+
+@pytest.mark.filterwarnings("ignore: `pade` is deprecated")
+def test_pade_ints():
+    # Simple test sequences (one of ints, one of floats).
+    an_int = [1, 2, 3, 4]
+    an_flt = [1.0, 2.0, 3.0, 4.0]
+
+    # Make sure integer arrays give the same result as float arrays with same values.
+    for i in range(0, len(an_int)):
+        for j in range(0, len(an_int) - i):
+
+            # Create float and int pade approximation for given order.
+            nump_int, denomp_int = pade(an_int, i, j)
+            nump_flt, denomp_flt = pade(an_flt, i, j)
+
+            # Check that they are the same.
+            xp_assert_equal(nump_int.c, nump_flt.c)
+            xp_assert_equal(denomp_int.c, denomp_flt.c)
+
+
+@pytest.mark.filterwarnings("ignore: `pade` is deprecated")
+def test_pade_complex():
+    # Test sequence with known solutions - see page 6 of 10.1109/PESGM.2012.6344759.
+    # Variable x is parameter - these tests will work with any complex number.
+    x = 0.2 + 0.6j
+    an = [1.0, x, -x*x.conjugate(), x.conjugate()*(x**2) + x*(x.conjugate()**2),
+          -(x**3)*x.conjugate() - 3*(x*x.conjugate())**2 - x*(x.conjugate()**3)]
+
+    nump, denomp = pade(an, 1, 1)
+    assert_array_almost_equal(nump.c, [x + x.conjugate(), 1.0])
+    assert_array_almost_equal(denomp.c, [x.conjugate(), 1.0])
+
+    nump, denomp = pade(an, 1, 2)
+    assert_array_almost_equal(nump.c, [x**2, 2*x + x.conjugate(), 1.0])
+    assert_array_almost_equal(denomp.c, [x + x.conjugate(), 1.0])
+
+    nump, denomp = pade(an, 2, 2)
+    assert_array_almost_equal(
+        nump.c,
+        [x**2 + x*x.conjugate() + x.conjugate()**2, 2*(x + x.conjugate()), 1.0]
+    )
+    assert_array_almost_equal(denomp.c, [x.conjugate()**2, x + 2*x.conjugate(), 1.0])
diff --git a/.venv/lib/python3.12/site-packages/scipy/interpolate/tests/test_polyint.py b/.venv/lib/python3.12/site-packages/scipy/interpolate/tests/test_polyint.py
new file mode 100644
index 0000000000000000000000000000000000000000..5c8922f27556512f2e76878da0117a930f4403f9
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/interpolate/tests/test_polyint.py
@@ -0,0 +1,977 @@
+import warnings
+import io
+import numpy as np
+
+from scipy._lib._array_api import (
+    xp_assert_equal, xp_assert_close, assert_array_almost_equal, assert_almost_equal,
+    make_xp_test_case
+)
+from pytest import raises as assert_raises
+import pytest
+
+from scipy.interpolate import (
+    KroghInterpolator, krogh_interpolate,
+    BarycentricInterpolator, barycentric_interpolate,
+    approximate_taylor_polynomial, CubicHermiteSpline, pchip,
+    PchipInterpolator, pchip_interpolate, Akima1DInterpolator, CubicSpline,
+    make_interp_spline)
+from scipy._lib._testutils import _run_concurrent_barrier
+
+skip_xp_backends = pytest.mark.skip_xp_backends
+xfail_xp_backends = pytest.mark.xfail_xp_backends
+
+
+def check_shape(interpolator_cls, x_shape, y_shape, deriv_shape=None, axis=0,
+                extra_args=None):
+    if extra_args is None:
+        extra_args = {}
+    rng = np.random.RandomState(1234)
+
+    x = [-1, 0, 1, 2, 3, 4]
+    s = list(range(1, len(y_shape)+1))
+    s.insert(axis % (len(y_shape)+1), 0)
+    y = rng.rand(*((6,) + y_shape)).transpose(s)
+
+    xi = np.zeros(x_shape)
+    if interpolator_cls is CubicHermiteSpline:
+        dydx = rng.rand(*((6,) + y_shape)).transpose(s)
+        yi = interpolator_cls(x, y, dydx, axis=axis, **extra_args)(xi)
+    else:
+        yi = interpolator_cls(x, y, axis=axis, **extra_args)(xi)
+
+    target_shape = ((deriv_shape or ()) + y.shape[:axis]
+                    + x_shape + y.shape[axis:][1:])
+    assert yi.shape == target_shape
+
+    # check it works also with lists
+    if x_shape and y.size > 0:
+        if interpolator_cls is CubicHermiteSpline:
+            interpolator_cls(list(x), list(y), list(dydx), axis=axis,
+                             **extra_args)(list(xi))
+        else:
+            interpolator_cls(list(x), list(y), axis=axis,
+                             **extra_args)(list(xi))
+
+    # check also values
+    if xi.size > 0 and deriv_shape is None:
+        bs_shape = y.shape[:axis] + (1,)*len(x_shape) + y.shape[axis:][1:]
+        yv = y[((slice(None,),)*(axis % y.ndim)) + (1,)]
+        yv = yv.reshape(bs_shape)
+
+        yi, y = np.broadcast_arrays(yi, yv)
+        xp_assert_close(yi, y)
+
+
+SHAPES = [(), (0,), (1,), (6, 2, 5)]
+
+
+def test_shapes():
+
+    def spl_interp(x, y, axis):
+        return make_interp_spline(x, y, axis=axis)
+
+    for ip in [KroghInterpolator, BarycentricInterpolator, CubicHermiteSpline,
+               pchip, Akima1DInterpolator, CubicSpline, spl_interp]:
+        for s1 in SHAPES:
+            for s2 in SHAPES:
+                for axis in range(-len(s2), len(s2)):
+                    if ip != CubicSpline:
+                        check_shape(ip, s1, s2, None, axis)
+                    else:
+                        for bc in ['natural', 'clamped']:
+                            extra = {'bc_type': bc}
+                            check_shape(ip, s1, s2, None, axis, extra)
+
+def test_derivs_shapes():
+    for ip in [KroghInterpolator, BarycentricInterpolator]:
+        def interpolator_derivs(x, y, axis=0):
+            return ip(x, y, axis).derivatives
+
+        for s1 in SHAPES:
+            for s2 in SHAPES:
+                for axis in range(-len(s2), len(s2)):
+                    check_shape(interpolator_derivs, s1, s2, (6,), axis)
+
+
+def test_deriv_shapes():
+    def krogh_deriv(x, y, axis=0):
+        return KroghInterpolator(x, y, axis).derivative
+
+    def bary_deriv(x, y, axis=0):
+        return BarycentricInterpolator(x, y, axis).derivative
+
+    def pchip_deriv(x, y, axis=0):
+        return pchip(x, y, axis).derivative()
+
+    def pchip_deriv2(x, y, axis=0):
+        return pchip(x, y, axis).derivative(2)
+
+    def pchip_antideriv(x, y, axis=0):
+        return pchip(x, y, axis).antiderivative()
+
+    def pchip_antideriv2(x, y, axis=0):
+        return pchip(x, y, axis).antiderivative(2)
+
+    def pchip_deriv_inplace(x, y, axis=0):
+        class P(PchipInterpolator):
+            def __call__(self, x):
+                return PchipInterpolator.__call__(self, x, 1)
+            pass
+        return P(x, y, axis)
+
+    def akima_deriv(x, y, axis=0):
+        return Akima1DInterpolator(x, y, axis).derivative()
+
+    def akima_antideriv(x, y, axis=0):
+        return Akima1DInterpolator(x, y, axis).antiderivative()
+
+    def cspline_deriv(x, y, axis=0):
+        return CubicSpline(x, y, axis).derivative()
+
+    def cspline_antideriv(x, y, axis=0):
+        return CubicSpline(x, y, axis).antiderivative()
+
+    def bspl_deriv(x, y, axis=0):
+        return make_interp_spline(x, y, axis=axis).derivative()
+
+    def bspl_antideriv(x, y, axis=0):
+        return make_interp_spline(x, y, axis=axis).antiderivative()
+
+    for ip in [krogh_deriv, bary_deriv, pchip_deriv, pchip_deriv2, pchip_deriv_inplace,
+               pchip_antideriv, pchip_antideriv2, akima_deriv, akima_antideriv,
+               cspline_deriv, cspline_antideriv, bspl_deriv, bspl_antideriv]:
+        for s1 in SHAPES:
+            for s2 in SHAPES:
+                for axis in range(-len(s2), len(s2)):
+                    check_shape(ip, s1, s2, (), axis)
+
+
+def test_complex():
+    x = [1, 2, 3, 4]
+    y = [1, 2, 1j, 3]
+
+    for ip in [KroghInterpolator, BarycentricInterpolator, CubicSpline]:
+        p = ip(x, y)
+        xp_assert_close(p(x), np.asarray(y))
+
+    dydx = [0, -1j, 2, 3j]
+    p = CubicHermiteSpline(x, y, dydx)
+    xp_assert_close(p(x), np.asarray(y))
+    xp_assert_close(p(x, 1), np.asarray(dydx))
+
+
+class TestKrogh:
+    def setup_method(self):
+        self.true_poly = np.polynomial.Polynomial([-4, 5, 1, 3, -2])
+        self.test_xs = np.linspace(-1,1,100)
+        self.xs = np.linspace(-1,1,5)
+        self.ys = self.true_poly(self.xs)
+
+    def test_lagrange(self):
+        P = KroghInterpolator(self.xs,self.ys)
+        assert_almost_equal(self.true_poly(self.test_xs),P(self.test_xs))
+
+    def test_scalar(self):
+        P = KroghInterpolator(self.xs,self.ys)
+        assert_almost_equal(self.true_poly(7), P(7), check_0d=False)
+        assert_almost_equal(self.true_poly(np.array(7)), P(np.array(7)), check_0d=False)
+
+    def test_derivatives(self):
+        P = KroghInterpolator(self.xs,self.ys)
+        D = P.derivatives(self.test_xs)
+        for i in range(D.shape[0]):
+            assert_almost_equal(self.true_poly.deriv(i)(self.test_xs),
+                                D[i])
+
+    def test_low_derivatives(self):
+        P = KroghInterpolator(self.xs,self.ys)
+        D = P.derivatives(self.test_xs,len(self.xs)+2)
+        for i in range(D.shape[0]):
+            assert_almost_equal(self.true_poly.deriv(i)(self.test_xs),
+                                D[i])
+
+    def test_derivative(self):
+        P = KroghInterpolator(self.xs,self.ys)
+        m = 10
+        r = P.derivatives(self.test_xs,m)
+        for i in range(m):
+            assert_almost_equal(P.derivative(self.test_xs,i),r[i])
+
+    def test_high_derivative(self):
+        P = KroghInterpolator(self.xs,self.ys)
+        for i in range(len(self.xs), 2*len(self.xs)):
+            assert_almost_equal(P.derivative(self.test_xs,i),
+                                np.zeros(len(self.test_xs)))
+
+    def test_ndim_derivatives(self):
+        poly1 = self.true_poly
+        poly2 = np.polynomial.Polynomial([-2, 5, 3, -1])
+        poly3 = np.polynomial.Polynomial([12, -3, 4, -5, 6])
+        ys = np.stack((poly1(self.xs), poly2(self.xs), poly3(self.xs)), axis=-1)
+
+        P = KroghInterpolator(self.xs, ys, axis=0)
+        D = P.derivatives(self.test_xs)
+        for i in range(D.shape[0]):
+            xp_assert_close(D[i],
+                            np.stack((poly1.deriv(i)(self.test_xs),
+                                      poly2.deriv(i)(self.test_xs),
+                                      poly3.deriv(i)(self.test_xs)),
+                                     axis=-1))
+
+    def test_ndim_derivative(self):
+        poly1 = self.true_poly
+        poly2 = np.polynomial.Polynomial([-2, 5, 3, -1])
+        poly3 = np.polynomial.Polynomial([12, -3, 4, -5, 6])
+        ys = np.stack((poly1(self.xs), poly2(self.xs), poly3(self.xs)), axis=-1)
+
+        P = KroghInterpolator(self.xs, ys, axis=0)
+        for i in range(P.n):
+            xp_assert_close(P.derivative(self.test_xs, i),
+                            np.stack((poly1.deriv(i)(self.test_xs),
+                                      poly2.deriv(i)(self.test_xs),
+                                      poly3.deriv(i)(self.test_xs)),
+                                     axis=-1))
+
+    def test_hermite(self):
+        P = KroghInterpolator(self.xs,self.ys)
+        assert_almost_equal(self.true_poly(self.test_xs),P(self.test_xs))
+
+    def test_vector(self):
+        xs = [0, 1, 2]
+        ys = np.array([[0,1],[1,0],[2,1]])
+        P = KroghInterpolator(xs,ys)
+        Pi = [KroghInterpolator(xs,ys[:,i]) for i in range(ys.shape[1])]
+        test_xs = np.linspace(-1,3,100)
+        assert_almost_equal(P(test_xs),
+                            np.asarray([p(test_xs) for p in Pi]).T)
+        assert_almost_equal(P.derivatives(test_xs),
+                np.transpose(np.asarray([p.derivatives(test_xs) for p in Pi]),
+                    (1,2,0)))
+
+    def test_empty(self):
+        P = KroghInterpolator(self.xs,self.ys)
+        xp_assert_equal(P([]), np.asarray([]))
+
+    def test_shapes_scalarvalue(self):
+        P = KroghInterpolator(self.xs,self.ys)
+        assert np.shape(P(0)) == ()
+        assert np.shape(P(np.array(0))) == ()
+        assert np.shape(P([0])) == (1,)
+        assert np.shape(P([0,1])) == (2,)
+
+    def test_shapes_scalarvalue_derivative(self):
+        P = KroghInterpolator(self.xs,self.ys)
+        n = P.n
+        assert np.shape(P.derivatives(0)) == (n,)
+        assert np.shape(P.derivatives(np.array(0))) == (n,)
+        assert np.shape(P.derivatives([0])) == (n, 1)
+        assert np.shape(P.derivatives([0, 1])) == (n, 2)
+
+    def test_shapes_vectorvalue(self):
+        P = KroghInterpolator(self.xs,np.outer(self.ys,np.arange(3)))
+        assert np.shape(P(0)) == (3,)
+        assert np.shape(P([0])) == (1, 3)
+        assert np.shape(P([0, 1])) == (2, 3)
+
+    def test_shapes_1d_vectorvalue(self):
+        P = KroghInterpolator(self.xs,np.outer(self.ys,[1]))
+        assert np.shape(P(0)) == (1,)
+        assert np.shape(P([0])) == (1, 1)
+        assert np.shape(P([0,1])) == (2, 1)
+
+    def test_shapes_vectorvalue_derivative(self):
+        P = KroghInterpolator(self.xs,np.outer(self.ys,np.arange(3)))
+        n = P.n
+        assert np.shape(P.derivatives(0)) == (n, 3)
+        assert np.shape(P.derivatives([0])) == (n, 1, 3)
+        assert np.shape(P.derivatives([0,1])) == (n, 2, 3)
+
+    def test_wrapper(self):
+        P = KroghInterpolator(self.xs, self.ys)
+        ki = krogh_interpolate
+        assert_almost_equal(P(self.test_xs), ki(self.xs, self.ys, self.test_xs))
+        assert_almost_equal(P.derivative(self.test_xs, 2),
+                            ki(self.xs, self.ys, self.test_xs, der=2))
+        assert_almost_equal(P.derivatives(self.test_xs, 2),
+                            ki(self.xs, self.ys, self.test_xs, der=[0, 1]))
+
+    def test_int_inputs(self):
+        # Check input args are cast correctly to floats, gh-3669
+        x = [0, 234, 468, 702, 936, 1170, 1404, 2340, 3744, 6084, 8424,
+             13104, 60000]
+        offset_cdf = np.array([-0.95, -0.86114777, -0.8147762, -0.64072425,
+                               -0.48002351, -0.34925329, -0.26503107,
+                               -0.13148093, -0.12988833, -0.12979296,
+                               -0.12973574, -0.08582937, 0.05])
+        f = KroghInterpolator(x, offset_cdf)
+
+        xp_assert_close(abs((f(x) - offset_cdf) / f.derivative(x, 1)),
+                        np.zeros_like(offset_cdf), atol=1e-10)
+
+    def test_derivatives_complex(self):
+        # regression test for gh-7381: krogh.derivatives(0) fails complex y
+        x, y = np.array([-1, -1, 0, 1, 1]), np.array([1, 1.0j, 0, -1, 1.0j])
+        func = KroghInterpolator(x, y)
+        cmplx = func.derivatives(0)
+
+        cmplx2 = (KroghInterpolator(x, y.real).derivatives(0) +
+                  1j*KroghInterpolator(x, y.imag).derivatives(0))
+        xp_assert_close(cmplx, cmplx2, atol=1e-15)
+
+    def test_high_degree_warning(self):
+        with pytest.warns(UserWarning, match="40 degrees provided,"):
+            KroghInterpolator(np.arange(40), np.ones(40))
+
+    def test_concurrency(self):
+        P = KroghInterpolator(self.xs, self.ys)
+
+        def worker_fn(_, interp):
+            interp(self.xs)
+
+        _run_concurrent_barrier(10, worker_fn, P)
+
+
+class TestTaylor:
+    def test_exponential(self):
+        degree = 5
+        with pytest.warns(DeprecationWarning, match="`approximate_taylor_polynomial`"):
+            p = approximate_taylor_polynomial(np.exp, 0, degree, 1, 15)
+        for i in range(degree+1):
+            assert_almost_equal(p(0),1)
+            p = p.deriv()
+        assert_almost_equal(p(0),0)
+
+
+class TestBarycentric:
+    def setup_method(self):
+        self.true_poly = np.polynomial.Polynomial([-4, 5, 1, 3, -2])
+        self.test_xs = np.linspace(-1, 1, 100)
+        self.xs = np.linspace(-1, 1, 5)
+        self.ys = self.true_poly(self.xs)
+
+    def test_lagrange(self):
+        # Ensure backwards compatible post SPEC7
+        P = BarycentricInterpolator(self.xs, self.ys, random_state=1)
+        xp_assert_close(P(self.test_xs), self.true_poly(self.test_xs))
+
+    def test_scalar(self):
+        P = BarycentricInterpolator(self.xs, self.ys, rng=1)
+        xp_assert_close(P(7), self.true_poly(7), check_0d=False)
+        xp_assert_close(P(np.array(7)), self.true_poly(np.array(7)), check_0d=False)
+
+    def test_derivatives(self):
+        P = BarycentricInterpolator(self.xs, self.ys)
+        D = P.derivatives(self.test_xs)
+        for i in range(D.shape[0]):
+            xp_assert_close(self.true_poly.deriv(i)(self.test_xs), D[i])
+
+    def test_low_derivatives(self):
+        P = BarycentricInterpolator(self.xs, self.ys)
+        D = P.derivatives(self.test_xs, len(self.xs)+2)
+        for i in range(D.shape[0]):
+            xp_assert_close(self.true_poly.deriv(i)(self.test_xs),
+                            D[i],
+                            atol=1e-12)
+
+    def test_derivative(self):
+        P = BarycentricInterpolator(self.xs, self.ys)
+        m = 10
+        r = P.derivatives(self.test_xs, m)
+        for i in range(m):
+            xp_assert_close(P.derivative(self.test_xs, i), r[i])
+
+    def test_high_derivative(self):
+        P = BarycentricInterpolator(self.xs, self.ys)
+        for i in range(len(self.xs), 5*len(self.xs)):
+            xp_assert_close(P.derivative(self.test_xs, i),
+                            np.zeros(len(self.test_xs)))
+
+    def test_ndim_derivatives(self):
+        poly1 = self.true_poly
+        poly2 = np.polynomial.Polynomial([-2, 5, 3, -1])
+        poly3 = np.polynomial.Polynomial([12, -3, 4, -5, 6])
+        ys = np.stack((poly1(self.xs), poly2(self.xs), poly3(self.xs)), axis=-1)
+
+        P = BarycentricInterpolator(self.xs, ys, axis=0)
+        D = P.derivatives(self.test_xs)
+        for i in range(D.shape[0]):
+            xp_assert_close(D[i],
+                            np.stack((poly1.deriv(i)(self.test_xs),
+                                      poly2.deriv(i)(self.test_xs),
+                                      poly3.deriv(i)(self.test_xs)),
+                                     axis=-1),
+                            atol=1e-12)
+
+    def test_ndim_derivative(self):
+        poly1 = self.true_poly
+        poly2 = np.polynomial.Polynomial([-2, 5, 3, -1])
+        poly3 = np.polynomial.Polynomial([12, -3, 4, -5, 6])
+        ys = np.stack((poly1(self.xs), poly2(self.xs), poly3(self.xs)), axis=-1)
+
+        P = BarycentricInterpolator(self.xs, ys, axis=0)
+        for i in range(P.n):
+            xp_assert_close(P.derivative(self.test_xs, i),
+                            np.stack((poly1.deriv(i)(self.test_xs),
+                                      poly2.deriv(i)(self.test_xs),
+                                      poly3.deriv(i)(self.test_xs)),
+                                     axis=-1),
+                            atol=1e-12)
+
+    def test_delayed(self):
+        P = BarycentricInterpolator(self.xs)
+        P.set_yi(self.ys)
+        assert_almost_equal(self.true_poly(self.test_xs), P(self.test_xs))
+
+    def test_append(self):
+        P = BarycentricInterpolator(self.xs[:3], self.ys[:3])
+        P.add_xi(self.xs[3:], self.ys[3:])
+        assert_almost_equal(self.true_poly(self.test_xs), P(self.test_xs))
+
+    def test_vector(self):
+        xs = [0, 1, 2]
+        ys = np.array([[0, 1], [1, 0], [2, 1]])
+        BI = BarycentricInterpolator
+        P = BI(xs, ys)
+        Pi = [BI(xs, ys[:, i]) for i in range(ys.shape[1])]
+        test_xs = np.linspace(-1, 3, 100)
+        assert_almost_equal(P(test_xs),
+                            np.asarray([p(test_xs) for p in Pi]).T)
+
+    def test_shapes_scalarvalue(self):
+        P = BarycentricInterpolator(self.xs, self.ys)
+        assert np.shape(P(0)) == ()
+        assert np.shape(P(np.array(0))) == ()
+        assert np.shape(P([0])) == (1,)
+        assert np.shape(P([0, 1])) == (2,)
+
+    def test_shapes_scalarvalue_derivative(self):
+        P = BarycentricInterpolator(self.xs,self.ys)
+        n = P.n
+        assert np.shape(P.derivatives(0)) == (n,)
+        assert np.shape(P.derivatives(np.array(0))) == (n,)
+        assert np.shape(P.derivatives([0])) == (n,1)
+        assert np.shape(P.derivatives([0,1])) == (n,2)
+
+    def test_shapes_vectorvalue(self):
+        P = BarycentricInterpolator(self.xs, np.outer(self.ys, np.arange(3)))
+        assert np.shape(P(0)) == (3,)
+        assert np.shape(P([0])) == (1, 3)
+        assert np.shape(P([0, 1])) == (2, 3)
+
+    def test_shapes_1d_vectorvalue(self):
+        P = BarycentricInterpolator(self.xs, np.outer(self.ys, [1]))
+        assert np.shape(P(0)) == (1,)
+        assert np.shape(P([0])) == (1, 1)
+        assert np.shape(P([0, 1])) == (2, 1)
+
+    def test_shapes_vectorvalue_derivative(self):
+        P = BarycentricInterpolator(self.xs,np.outer(self.ys,np.arange(3)))
+        n = P.n
+        assert np.shape(P.derivatives(0)) == (n, 3)
+        assert np.shape(P.derivatives([0])) == (n, 1, 3)
+        assert np.shape(P.derivatives([0, 1])) == (n, 2, 3)
+
+    def test_wrapper(self):
+        P = BarycentricInterpolator(self.xs, self.ys, rng=1)
+        bi = barycentric_interpolate
+        xp_assert_close(P(self.test_xs), bi(self.xs, self.ys, self.test_xs, rng=1))
+        xp_assert_close(P.derivative(self.test_xs, 2),
+                        bi(self.xs, self.ys, self.test_xs, der=2, rng=1))
+        xp_assert_close(P.derivatives(self.test_xs, 2),
+                        bi(self.xs, self.ys, self.test_xs, der=[0, 1], rng=1))
+
+    def test_int_input(self):
+        x = 1000 * np.arange(1, 11)  # np.prod(x[-1] - x[:-1]) overflows
+        y = np.arange(1, 11)
+        value = barycentric_interpolate(x, y, 1000 * 9.5)
+        assert_almost_equal(value, np.asarray(9.5))
+
+    def test_large_chebyshev(self):
+        # The weights for Chebyshev points of the second kind have analytically
+        # solvable weights. Naive calculation of barycentric weights will fail
+        # for large N because of numerical underflow and overflow. We test
+        # correctness for large N against analytical Chebyshev weights.
+
+        # Without capacity scaling or permutation, n=800 fails,
+        # With just capacity scaling, n=1097 fails
+        # With both capacity scaling and random permutation, n=30000 succeeds
+        n = 1100
+        j = np.arange(n + 1).astype(np.float64)
+        x = np.cos(j * np.pi / n)
+
+        # See page 506 of Berrut and Trefethen 2004 for this formula
+        w = (-1) ** j
+        w[0] *= 0.5
+        w[-1] *= 0.5
+
+        P = BarycentricInterpolator(x)
+
+        # It's okay to have a constant scaling factor in the weights because it
+        # cancels out in the evaluation of the polynomial.
+        factor = P.wi[0]
+        assert_almost_equal(P.wi / (2 * factor), w)
+
+    def test_warning(self):
+        # Test if the divide-by-zero warning is properly ignored when computing
+        # interpolated values equals to interpolation points
+        P = BarycentricInterpolator([0, 1], [1, 2])
+        with np.errstate(divide='raise'):
+            yi = P(P.xi)
+
+        # Check if the interpolated values match the input values
+        # at the nodes
+        assert_almost_equal(yi, P.yi.ravel())
+
+    def test_repeated_node(self):
+        # check that a repeated node raises a ValueError
+        # (computing the weights requires division by xi[i] - xi[j])
+        xis = np.array([0.1, 0.5, 0.9, 0.5])
+        ys = np.array([1, 2, 3, 4])
+        with pytest.raises(ValueError,
+                           match="Interpolation points xi must be distinct."):
+            BarycentricInterpolator(xis, ys)
+
+    def test_concurrency(self):
+        P = BarycentricInterpolator(self.xs, self.ys)
+
+        def worker_fn(_, interp):
+            interp(self.xs)
+
+        _run_concurrent_barrier(10, worker_fn, P)
+
+
+class TestPCHIP:
+    def _make_random(self, npts=20):
+        rng = np.random.RandomState(1234)
+        xi = np.sort(rng.random(npts))
+        yi = rng.random(npts)
+        return pchip(xi, yi), xi, yi
+
+    def test_overshoot(self):
+        # PCHIP should not overshoot
+        p, xi, yi = self._make_random()
+        for i in range(len(xi)-1):
+            x1, x2 = xi[i], xi[i+1]
+            y1, y2 = yi[i], yi[i+1]
+            if y1 > y2:
+                y1, y2 = y2, y1
+            xp = np.linspace(x1, x2, 10)
+            yp = p(xp)
+            assert ((y1 <= yp + 1e-15) & (yp <= y2 + 1e-15)).all()
+
+    def test_monotone(self):
+        # PCHIP should preserve monotonicty
+        p, xi, yi = self._make_random()
+        for i in range(len(xi)-1):
+            x1, x2 = xi[i], xi[i+1]
+            y1, y2 = yi[i], yi[i+1]
+            xp = np.linspace(x1, x2, 10)
+            yp = p(xp)
+            assert ((y2-y1) * (yp[1:] - yp[:1]) > 0).all()
+
+    def test_cast(self):
+        # regression test for integer input data, see gh-3453
+        data = np.array([[0, 4, 12, 27, 47, 60, 79, 87, 99, 100],
+                         [-33, -33, -19, -2, 12, 26, 38, 45, 53, 55]])
+        xx = np.arange(100)
+        curve = pchip(data[0], data[1])(xx)
+
+        data1 = data * 1.0
+        curve1 = pchip(data1[0], data1[1])(xx)
+
+        xp_assert_close(curve, curve1, atol=1e-14, rtol=1e-14)
+
+    def test_nag(self):
+        # Example from NAG C implementation,
+        # http://nag.com/numeric/cl/nagdoc_cl25/html/e01/e01bec.html
+        # suggested in gh-5326 as a smoke test for the way the derivatives
+        # are computed (see also gh-3453)
+        dataStr = '''
+          7.99   0.00000E+0
+          8.09   0.27643E-4
+          8.19   0.43750E-1
+          8.70   0.16918E+0
+          9.20   0.46943E+0
+         10.00   0.94374E+0
+         12.00   0.99864E+0
+         15.00   0.99992E+0
+         20.00   0.99999E+0
+        '''
+        data = np.loadtxt(io.StringIO(dataStr))
+        pch = pchip(data[:,0], data[:,1])
+
+        resultStr = '''
+           7.9900       0.0000
+           9.1910       0.4640
+          10.3920       0.9645
+          11.5930       0.9965
+          12.7940       0.9992
+          13.9950       0.9998
+          15.1960       0.9999
+          16.3970       1.0000
+          17.5980       1.0000
+          18.7990       1.0000
+          20.0000       1.0000
+        '''
+        result = np.loadtxt(io.StringIO(resultStr))
+        xp_assert_close(result[:,1], pch(result[:,0]), rtol=0., atol=5e-5)
+
+    def test_endslopes(self):
+        # this is a smoke test for gh-3453: PCHIP interpolator should not
+        # set edge slopes to zero if the data do not suggest zero edge derivatives
+        x = np.array([0.0, 0.1, 0.25, 0.35])
+        y1 = np.array([279.35, 0.5e3, 1.0e3, 2.5e3])
+        y2 = np.array([279.35, 2.5e3, 1.50e3, 1.0e3])
+        for pp in (pchip(x, y1), pchip(x, y2)):
+            for t in (x[0], x[-1]):
+                assert pp(t, 1) != 0
+
+    def test_all_zeros(self):
+        x = np.arange(10)
+        y = np.zeros_like(x)
+
+        # this should work and not generate any warnings
+        with warnings.catch_warnings():
+            warnings.filterwarnings('error')
+            pch = pchip(x, y)
+
+        xx = np.linspace(0, 9, 101)
+        assert all(pch(xx) == 0.)
+
+    def test_two_points(self):
+        # regression test for gh-6222: pchip([0, 1], [0, 1]) fails because
+        # it tries to use a three-point scheme to estimate edge derivatives,
+        # while there are only two points available.
+        # Instead, it should construct a linear interpolator.
+        x = np.linspace(0, 1, 11)
+        p = pchip([0, 1], [0, 2])
+        xp_assert_close(p(x), 2*x, atol=1e-15)
+
+    def test_pchip_interpolate(self):
+        assert_array_almost_equal(
+            pchip_interpolate([1, 2, 3], [4, 5, 6], [0.5], der=1),
+            np.asarray([1.]))
+
+        assert_array_almost_equal(
+            pchip_interpolate([1, 2, 3], [4, 5, 6], [0.5], der=0),
+            np.asarray([3.5]))
+
+        assert_array_almost_equal(
+            np.asarray(pchip_interpolate([1, 2, 3], [4, 5, 6], [0.5], der=[0, 1])),
+            np.asarray([[3.5], [1]]))
+
+    def test_roots(self):
+        # regression test for gh-6357: .roots method should work
+        p = pchip([0, 1], [-1, 1])
+        r = p.roots()
+        xp_assert_close(r, np.asarray([0.5]))
+
+
+@make_xp_test_case(CubicSpline)
+class TestCubicSpline:
+    @staticmethod
+    def check_correctness(S, bc_start='not-a-knot', bc_end='not-a-knot',
+                          tol=1e-14):
+        """Check that spline coefficients satisfy the continuity and boundary
+        conditions."""
+        x = S.x
+        c = S.c
+        dx = np.diff(x)
+        dx = dx.reshape([dx.shape[0]] + [1] * (c.ndim - 2))
+        dxi = dx[:-1]
+
+        # Check C2 continuity.
+        xp_assert_close(c[3, 1:], c[0, :-1] * dxi**3 + c[1, :-1] * dxi**2 +
+                        c[2, :-1] * dxi + c[3, :-1], rtol=tol, atol=tol)
+        xp_assert_close(c[2, 1:], 3 * c[0, :-1] * dxi**2 +
+                        2 * c[1, :-1] * dxi + c[2, :-1], rtol=tol, atol=tol)
+        xp_assert_close(c[1, 1:], 3 * c[0, :-1] * dxi + c[1, :-1],
+                        rtol=tol, atol=tol)
+
+        # Check that we found a parabola, the third derivative is 0.
+        if x.size == 3 and bc_start == 'not-a-knot' and bc_end == 'not-a-knot':
+            xp_assert_close(c[0], np.zeros_like(c[0]), rtol=tol, atol=tol)
+            return
+
+        # Check periodic boundary conditions.
+        if bc_start == 'periodic':
+            xp_assert_close(S(x[0], 0), S(x[-1], 0), rtol=tol, atol=tol)
+            xp_assert_close(S(x[0], 1), S(x[-1], 1), rtol=tol, atol=tol)
+            xp_assert_close(S(x[0], 2), S(x[-1], 2), rtol=tol, atol=tol)
+            return
+
+        # Check other boundary conditions.
+        if bc_start == 'not-a-knot':
+            if x.size == 2:
+                slope = (S(x[1]) - S(x[0])) / dx[0]
+                slope = np.asarray(slope)
+                xp_assert_close(S(x[0], 1), slope, rtol=tol, atol=tol)
+            else:
+                xp_assert_close(c[0, 0], c[0, 1], rtol=tol, atol=tol)
+        elif bc_start == 'clamped':
+            xp_assert_close(
+                S(x[0], 1), np.zeros_like(S(x[0], 1)), rtol=tol, atol=tol)
+        elif bc_start == 'natural':
+            xp_assert_close(
+                S(x[0], 2), np.zeros_like(S(x[0], 2)), rtol=tol, atol=tol)
+        else:
+            order, value = bc_start
+            xp_assert_close(S(x[0], order), np.asarray(value), rtol=tol, atol=tol)
+
+        if bc_end == 'not-a-knot':
+            if x.size == 2:
+                slope = (S(x[1]) - S(x[0])) / dx[0]
+                slope = np.asarray(slope)
+                xp_assert_close(S(x[1], 1), slope, rtol=tol, atol=tol)
+            else:
+                xp_assert_close(c[0, -1], c[0, -2], rtol=tol, atol=tol)
+        elif bc_end == 'clamped':
+            xp_assert_close(S(x[-1], 1), np.zeros_like(S(x[-1], 1)),
+                            rtol=tol, atol=tol)
+        elif bc_end == 'natural':
+            xp_assert_close(S(x[-1], 2), np.zeros_like(S(x[-1], 2)),
+                            rtol=2*tol, atol=2*tol)
+        else:
+            order, value = bc_end
+            xp_assert_close(S(x[-1], order), np.asarray(value), rtol=tol, atol=tol)
+
+    def check_all_bc(self, x, y, axis):
+        deriv_shape = list(y.shape)
+        del deriv_shape[axis]
+        first_deriv = np.empty(deriv_shape)
+        first_deriv.fill(2)
+        second_deriv = np.empty(deriv_shape)
+        second_deriv.fill(-1)
+        bc_all = [
+            'not-a-knot',
+            'natural',
+            'clamped',
+            (1, first_deriv),
+            (2, second_deriv)
+        ]
+        for bc in bc_all[:3]:
+            S = CubicSpline(x, y, axis=axis, bc_type=bc)
+            self.check_correctness(S, bc, bc)
+
+        for bc_start in bc_all:
+            for bc_end in bc_all:
+                S = CubicSpline(x, y, axis=axis, bc_type=(bc_start, bc_end))
+                self.check_correctness(S, bc_start, bc_end, tol=2e-14)
+
+    def test_general(self):
+        x = np.array([-1, 0, 0.5, 2, 4, 4.5, 5.5, 9])
+        y = np.array([0, -0.5, 2, 3, 2.5, 1, 1, 0.5])
+        for n in [2, 3, x.size]:
+            self.check_all_bc(x[:n], y[:n], 0)
+
+            Y = np.empty((2, n, 2))
+            Y[0, :, 0] = y[:n]
+            Y[0, :, 1] = y[:n] - 1
+            Y[1, :, 0] = y[:n] + 2
+            Y[1, :, 1] = y[:n] + 3
+            self.check_all_bc(x[:n], Y, 1)
+
+    def test_periodic(self):
+        for n in [2, 3, 5]:
+            x = np.linspace(0, 2 * np.pi, n)
+            y = np.cos(x)
+            S = CubicSpline(x, y, bc_type='periodic')
+            self.check_correctness(S, 'periodic', 'periodic')
+
+            Y = np.empty((2, n, 2))
+            Y[0, :, 0] = y
+            Y[0, :, 1] = y + 2
+            Y[1, :, 0] = y - 1
+            Y[1, :, 1] = y + 5
+            S = CubicSpline(x, Y, axis=1, bc_type='periodic')
+            self.check_correctness(S, 'periodic', 'periodic')
+
+    def test_periodic_eval(self, xp):
+        x = xp.linspace(0, 2 * xp.pi, 10, dtype=xp.float64)
+        y = xp.cos(x)
+        S = CubicSpline(x, y, bc_type='periodic')
+        assert_almost_equal(S(1), S(1 + 2 * xp.pi), decimal=15)
+
+        S = CubicSpline(x, y)
+        assert_almost_equal(S(x), xp.cos(x), decimal=15)
+
+    def test_second_derivative_continuity_gh_11758(self):
+        # gh-11758: C2 continuity fail
+        x = np.array([0.9, 1.3, 1.9, 2.1, 2.6, 3.0, 3.9, 4.4, 4.7, 5.0, 6.0,
+                      7.0, 8.0, 9.2, 10.5, 11.3, 11.6, 12.0, 12.6, 13.0, 13.3])
+        y = np.array([1.3, 1.5, 1.85, 2.1, 2.6, 2.7, 2.4, 2.15, 2.05, 2.1,
+                      2.25, 2.3, 2.25, 1.95, 1.4, 0.9, 0.7, 0.6, 0.5, 0.4, 1.3])
+        S = CubicSpline(x, y, bc_type='periodic', extrapolate='periodic')
+        self.check_correctness(S, 'periodic', 'periodic')
+
+    def test_three_points(self):
+        # gh-11758: Fails computing a_m2_m1
+        # In this case, s (first derivatives) could be found manually by solving
+        # system of 2 linear equations. Due to solution of this system,
+        # s[i] = (h1m2 + h2m1) / (h1 + h2), where h1 = x[1] - x[0], h2 = x[2] - x[1],
+        # m1 = (y[1] - y[0]) / h1, m2 = (y[2] - y[1]) / h2
+        x = np.array([1.0, 2.75, 3.0])
+        y = np.array([1.0, 15.0, 1.0])
+        S = CubicSpline(x, y, bc_type='periodic')
+        self.check_correctness(S, 'periodic', 'periodic')
+        xp_assert_close(S.derivative(1)(x), np.array([-48.0, -48.0, -48.0]))
+
+    def test_periodic_three_points_multidim(self):
+        # make sure one multidimensional interpolator does the same as multiple
+        # one-dimensional interpolators
+        x = np.array([0.0, 1.0, 3.0])
+        y = np.array([[0.0, 1.0], [1.0, 0.0], [0.0, 1.0]])
+        S = CubicSpline(x, y, bc_type="periodic")
+        self.check_correctness(S, 'periodic', 'periodic')
+        S0 = CubicSpline(x, y[:, 0], bc_type="periodic")
+        S1 = CubicSpline(x, y[:, 1], bc_type="periodic")
+        q = np.linspace(0, 2, 5)
+        xp_assert_close(S(q)[:, 0], S0(q))
+        xp_assert_close(S(q)[:, 1], S1(q))
+
+    def test_dtypes(self):
+        x = np.array([0, 1, 2, 3], dtype=int)
+        y = np.array([-5, 2, 3, 1], dtype=int)
+        S = CubicSpline(x, y)
+        self.check_correctness(S)
+
+        y = np.array([-1+1j, 0.0, 1-1j, 0.5-1.5j])
+        S = CubicSpline(x, y)
+        self.check_correctness(S)
+
+        S = CubicSpline(x, x ** 3, bc_type=("natural", (1, 2j)))
+        self.check_correctness(S, "natural", (1, 2j))
+
+        y = np.array([-5, 2, 3, 1])
+        S = CubicSpline(x, y, bc_type=[(1, 2 + 0.5j), (2, 0.5 - 1j)])
+        self.check_correctness(S, (1, 2 + 0.5j), (2, 0.5 - 1j))
+
+    def test_small_dx(self):
+        rng = np.random.RandomState(0)
+        x = np.sort(rng.uniform(size=100))
+        y = 1e4 + rng.uniform(size=100)
+        S = CubicSpline(x, y)
+        self.check_correctness(S, tol=1e-13)
+
+    def test_incorrect_inputs(self):
+        x = np.array([1, 2, 3, 4])
+        y = np.array([1, 2, 3, 4])
+        xc = np.array([1 + 1j, 2, 3, 4])
+        xn = np.array([np.nan, 2, 3, 4])
+        xo = np.array([2, 1, 3, 4])
+        yn = np.array([np.nan, 2, 3, 4])
+        y3 = [1, 2, 3]
+        x1 = [1]
+        y1 = [1]
+
+        assert_raises(ValueError, CubicSpline, xc, y)
+        assert_raises(ValueError, CubicSpline, xn, y)
+        assert_raises(ValueError, CubicSpline, x, yn)
+        assert_raises(ValueError, CubicSpline, xo, y)
+        assert_raises(ValueError, CubicSpline, x, y3)
+        assert_raises(ValueError, CubicSpline, x[:, np.newaxis], y)
+        assert_raises(ValueError, CubicSpline, x1, y1)
+
+        wrong_bc = [('periodic', 'clamped'),
+                    ((2, 0), (3, 10)),
+                    ((1, 0), ),
+                    (0., 0.),
+                    'not-a-typo']
+
+        for bc_type in wrong_bc:
+            assert_raises(ValueError, CubicSpline, x, y, 0, bc_type, True)
+
+        # Shapes mismatch when giving arbitrary derivative values:
+        Y = np.c_[y, y]
+        bc1 = ('clamped', (1, 0))
+        bc2 = ('clamped', (1, [0, 0, 0]))
+        bc3 = ('clamped', (1, [[0, 0]]))
+        assert_raises(ValueError, CubicSpline, x, Y, 0, bc1, True)
+        assert_raises(ValueError, CubicSpline, x, Y, 0, bc2, True)
+        assert_raises(ValueError, CubicSpline, x, Y, 0, bc3, True)
+
+        # periodic condition, y[-1] must be equal to y[0]:
+        assert_raises(ValueError, CubicSpline, x, y, 0, 'periodic', True)
+
+
+@make_xp_test_case(CubicHermiteSpline)
+def test_CubicHermiteSpline_correctness(xp):
+    x = xp.asarray([0, 2, 7])
+    y = xp.asarray([-1, 2, 3])
+    dydx = xp.asarray([0, 3, 7])
+    s = CubicHermiteSpline(x, y, dydx)
+    xp_assert_close(s(x), y, check_shape=False, check_dtype=False, rtol=1e-15)
+    xp_assert_close(s(x, 1), dydx, check_shape=False, check_dtype=False, rtol=1e-15)
+
+
+def test_CubicHermiteSpline_error_handling():
+    x = [1, 2, 3]
+    y = [0, 3, 5]
+    dydx = [1, -1, 2, 3]
+    assert_raises(ValueError, CubicHermiteSpline, x, y, dydx)
+
+    dydx_with_nan = [1, 0, np.nan]
+    assert_raises(ValueError, CubicHermiteSpline, x, y, dydx_with_nan)
+
+
+def test_roots_extrapolate_gh_11185():
+    x = np.array([0.001, 0.002])
+    y = np.array([1.66066935e-06, 1.10410807e-06])
+    dy = np.array([-1.60061854, -1.600619])
+    p = CubicHermiteSpline(x, y, dy)
+
+    # roots(extrapolate=True) for a polynomial with a single interval
+    # should return all three real roots
+    r = p.roots(extrapolate=True)
+    assert p.c.shape[1] == 1
+    assert r.size == 3
+
+
+class TestZeroSizeArrays:
+    # regression tests for gh-17241 : CubicSpline et al must not segfault
+    # when y.size == 0
+    # The two methods below are _almost_ the same, but not quite:
+    # one is for objects which have the `bc_type` argument (CubicSpline)
+    # and the other one is for those which do not (Pchip, Akima1D)
+
+    @pytest.mark.parametrize('y', [np.zeros((10, 0, 5)),
+                                   np.zeros((10, 5, 0))])
+    @pytest.mark.parametrize('bc_type',
+                             ['not-a-knot', 'periodic', 'natural', 'clamped'])
+    @pytest.mark.parametrize('axis', [0, 1, 2])
+    @pytest.mark.parametrize('cls', [make_interp_spline, CubicSpline])
+    def test_zero_size(self, cls, y, bc_type, axis):
+        x = np.arange(10)
+        xval = np.arange(3)
+
+        obj = cls(x, y, bc_type=bc_type)
+        assert obj(xval).size == 0
+        assert obj(xval).shape == xval.shape + y.shape[1:]
+
+        # Also check with an explicit non-default axis
+        yt = np.moveaxis(y, 0, axis)  # (10, 0, 5) --> (0, 10, 5) if axis=1 etc
+
+        obj = cls(x, yt, bc_type=bc_type, axis=axis)
+        sh = yt.shape[:axis] + (xval.size, ) + yt.shape[axis+1:]
+        assert obj(xval).size == 0
+        assert obj(xval).shape == sh
+
+    @pytest.mark.parametrize('y', [np.zeros((10, 0, 5)),
+                                   np.zeros((10, 5, 0))])
+    @pytest.mark.parametrize('axis', [0, 1, 2])
+    @pytest.mark.parametrize('cls', [PchipInterpolator, Akima1DInterpolator])
+    def test_zero_size_2(self, cls, y, axis):
+        x = np.arange(10)
+        xval = np.arange(3)
+
+        obj = cls(x, y)
+        assert obj(xval).size == 0
+        assert obj(xval).shape == xval.shape + y.shape[1:]
+
+        # Also check with an explicit non-default axis
+        yt = np.moveaxis(y, 0, axis)  # (10, 0, 5) --> (0, 10, 5) if axis=1 etc
+
+        obj = cls(x, yt, axis=axis)
+        sh = yt.shape[:axis] + (xval.size, ) + yt.shape[axis+1:]
+        assert obj(xval).size == 0
+        assert obj(xval).shape == sh
diff --git a/.venv/lib/python3.12/site-packages/scipy/interpolate/tests/test_rbf.py b/.venv/lib/python3.12/site-packages/scipy/interpolate/tests/test_rbf.py
new file mode 100644
index 0000000000000000000000000000000000000000..5ed4bbfabc1b1ceac1555d9f36f0c0cdaf16553a
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/interpolate/tests/test_rbf.py
@@ -0,0 +1,244 @@
+# Created by John Travers, Robert Hetland, 2007
+""" Test functions for rbf module """
+
+import numpy as np
+
+
+from scipy._lib._array_api import assert_array_almost_equal, assert_almost_equal
+
+from numpy import linspace, sin, cos, exp, allclose
+from scipy.interpolate._rbf import Rbf
+from scipy._lib._testutils import _run_concurrent_barrier
+
+
+FUNCTIONS = ('multiquadric', 'inverse multiquadric', 'gaussian',
+             'cubic', 'quintic', 'thin-plate', 'linear')
+
+
+def check_rbf1d_interpolation(function):
+    # Check that the Rbf function interpolates through the nodes (1D)
+    x = linspace(0,10,9)
+    y = sin(x)
+    rbf = Rbf(x, y, function=function)
+    yi = rbf(x)
+    assert_array_almost_equal(y, yi)
+    assert_almost_equal(rbf(float(x[0])), y[0], check_0d=False)
+
+
+def check_rbf2d_interpolation(function):
+    # Check that the Rbf function interpolates through the nodes (2D).
+    rng = np.random.RandomState(1234)
+    x = rng.rand(50,1)*4-2
+    y = rng.rand(50,1)*4-2
+    z = x*exp(-x**2-1j*y**2)
+    rbf = Rbf(x, y, z, epsilon=2, function=function)
+    zi = rbf(x, y)
+    zi = zi.reshape(x.shape)
+    assert_array_almost_equal(z, zi)
+
+
+def check_rbf3d_interpolation(function):
+    # Check that the Rbf function interpolates through the nodes (3D).
+    rng = np.random.RandomState(1234)
+    x = rng.rand(50, 1)*4 - 2
+    y = rng.rand(50, 1)*4 - 2
+    z = rng.rand(50, 1)*4 - 2
+    d = x*exp(-x**2 - y**2)
+    rbf = Rbf(x, y, z, d, epsilon=2, function=function)
+    di = rbf(x, y, z)
+    di = di.reshape(x.shape)
+    assert_array_almost_equal(di, d)
+
+
+def test_rbf_interpolation():
+    for function in FUNCTIONS:
+        check_rbf1d_interpolation(function)
+        check_rbf2d_interpolation(function)
+        check_rbf3d_interpolation(function)
+
+
+def check_2drbf1d_interpolation(function):
+    # Check that the 2-D Rbf function interpolates through the nodes (1D)
+    x = linspace(0, 10, 9)
+    y0 = sin(x)
+    y1 = cos(x)
+    y = np.vstack([y0, y1]).T
+    rbf = Rbf(x, y, function=function, mode='N-D')
+    yi = rbf(x)
+    assert_array_almost_equal(y, yi)
+    assert_almost_equal(rbf(float(x[0])), y[0])
+
+
+def check_2drbf2d_interpolation(function):
+    # Check that the 2-D Rbf function interpolates through the nodes (2D).
+    rng = np.random.RandomState(1234)
+    x = rng.rand(50, ) * 4 - 2
+    y = rng.rand(50, ) * 4 - 2
+    z0 = x * exp(-x ** 2 - 1j * y ** 2)
+    z1 = y * exp(-y ** 2 - 1j * x ** 2)
+    z = np.vstack([z0, z1]).T
+    rbf = Rbf(x, y, z, epsilon=2, function=function, mode='N-D')
+    zi = rbf(x, y)
+    zi = zi.reshape(z.shape)
+    assert_array_almost_equal(z, zi)
+
+
+def check_2drbf3d_interpolation(function):
+    # Check that the 2-D Rbf function interpolates through the nodes (3D).
+    rng = np.random.RandomState(1234)
+    x = rng.rand(50, ) * 4 - 2
+    y = rng.rand(50, ) * 4 - 2
+    z = rng.rand(50, ) * 4 - 2
+    d0 = x * exp(-x ** 2 - y ** 2)
+    d1 = y * exp(-y ** 2 - x ** 2)
+    d = np.vstack([d0, d1]).T
+    rbf = Rbf(x, y, z, d, epsilon=2, function=function, mode='N-D')
+    di = rbf(x, y, z)
+    di = di.reshape(d.shape)
+    assert_array_almost_equal(di, d)
+
+
+def test_2drbf_interpolation():
+    for function in FUNCTIONS:
+        check_2drbf1d_interpolation(function)
+        check_2drbf2d_interpolation(function)
+        check_2drbf3d_interpolation(function)
+
+
+def check_rbf1d_regularity(function, atol):
+    # Check that the Rbf function approximates a smooth function well away
+    # from the nodes.
+    x = linspace(0, 10, 9)
+    y = sin(x)
+    rbf = Rbf(x, y, function=function)
+    xi = linspace(0, 10, 100)
+    yi = rbf(xi)
+    msg = f"abs-diff: {abs(yi - sin(xi)).max():f}"
+    assert allclose(yi, sin(xi), atol=atol), msg
+
+
+def test_rbf_regularity():
+    tolerances = {
+        'multiquadric': 0.1,
+        'inverse multiquadric': 0.15,
+        'gaussian': 0.15,
+        'cubic': 0.15,
+        'quintic': 0.1,
+        'thin-plate': 0.1,
+        'linear': 0.2
+    }
+    for function in FUNCTIONS:
+        check_rbf1d_regularity(function, tolerances.get(function, 1e-2))
+
+
+def check_2drbf1d_regularity(function, atol):
+    # Check that the 2-D Rbf function approximates a smooth function well away
+    # from the nodes.
+    x = linspace(0, 10, 9)
+    y0 = sin(x)
+    y1 = cos(x)
+    y = np.vstack([y0, y1]).T
+    rbf = Rbf(x, y, function=function, mode='N-D')
+    xi = linspace(0, 10, 100)
+    yi = rbf(xi)
+    msg = f"abs-diff: {abs(yi - np.vstack([sin(xi), cos(xi)]).T).max():f}"
+    assert allclose(yi, np.vstack([sin(xi), cos(xi)]).T, atol=atol), msg
+
+
+def test_2drbf_regularity():
+    tolerances = {
+        'multiquadric': 0.1,
+        'inverse multiquadric': 0.15,
+        'gaussian': 0.15,
+        'cubic': 0.15,
+        'quintic': 0.1,
+        'thin-plate': 0.15,
+        'linear': 0.2
+    }
+    for function in FUNCTIONS:
+        check_2drbf1d_regularity(function, tolerances.get(function, 1e-2))
+
+
+def check_rbf1d_stability(function):
+    # Check that the Rbf function with default epsilon is not subject
+    # to overshoot. Regression for issue #4523.
+    #
+    # Generate some data (fixed random seed hence deterministic)
+    rng = np.random.RandomState(1234)
+    x = np.linspace(0, 10, 50)
+    z = x + 4.0 * rng.randn(len(x))
+
+    rbf = Rbf(x, z, function=function)
+    xi = np.linspace(0, 10, 1000)
+    yi = rbf(xi)
+
+    # subtract the linear trend and make sure there no spikes
+    assert np.abs(yi-xi).max() / np.abs(z-x).max() < 1.1
+
+def test_rbf_stability():
+    for function in FUNCTIONS:
+        check_rbf1d_stability(function)
+
+
+def test_default_construction():
+    # Check that the Rbf class can be constructed with the default
+    # multiquadric basis function. Regression test for ticket #1228.
+    x = linspace(0,10,9)
+    y = sin(x)
+    rbf = Rbf(x, y)
+    yi = rbf(x)
+    assert_array_almost_equal(y, yi)
+
+
+def test_function_is_callable():
+    # Check that the Rbf class can be constructed with function=callable.
+    x = linspace(0,10,9)
+    y = sin(x)
+    def linfunc(x):
+        return x
+    rbf = Rbf(x, y, function=linfunc)
+    yi = rbf(x)
+    assert_array_almost_equal(y, yi)
+
+
+def test_two_arg_function_is_callable():
+    # Check that the Rbf class can be constructed with a two argument
+    # function=callable.
+    def _func(self, r):
+        return self.epsilon + r
+
+    x = linspace(0,10,9)
+    y = sin(x)
+    rbf = Rbf(x, y, function=_func)
+    yi = rbf(x)
+    assert_array_almost_equal(y, yi)
+
+
+def test_rbf_epsilon_none():
+    x = linspace(0, 10, 9)
+    y = sin(x)
+    Rbf(x, y, epsilon=None)
+
+
+def test_rbf_epsilon_none_collinear():
+    # Check that collinear points in one dimension doesn't cause an error
+    # due to epsilon = 0
+    x = [1, 2, 3]
+    y = [4, 4, 4]
+    z = [5, 6, 7]
+    rbf = Rbf(x, y, z, epsilon=None)
+    assert rbf.epsilon > 0
+
+
+def test_rbf_concurrency():
+    x = linspace(0, 10, 100)
+    y0 = sin(x)
+    y1 = cos(x)
+    y = np.vstack([y0, y1]).T
+    rbf = Rbf(x, y, mode='N-D')
+
+    def worker_fn(_, interp, xp):
+        interp(xp)
+
+    _run_concurrent_barrier(10, worker_fn, rbf, x)
+
diff --git a/.venv/lib/python3.12/site-packages/scipy/interpolate/tests/test_rbfinterp.py b/.venv/lib/python3.12/site-packages/scipy/interpolate/tests/test_rbfinterp.py
new file mode 100644
index 0000000000000000000000000000000000000000..e7a1005f6ca11275475762b57f75d316309dd490
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/interpolate/tests/test_rbfinterp.py
@@ -0,0 +1,592 @@
+import pickle
+import pytest
+import numpy as np
+from numpy.linalg import LinAlgError
+from scipy._lib._array_api import xp_assert_close, make_xp_test_case
+from scipy.stats.qmc import Halton
+from scipy.spatial import cKDTree  # type: ignore[attr-defined]
+from scipy.interpolate._rbfinterp import (
+    _AVAILABLE, _SCALE_INVARIANT, _NAME_TO_MIN_DEGREE, RBFInterpolator,
+    _get_backend
+    )
+from scipy.interpolate import _rbfinterp_pythran
+from scipy._lib._testutils import _run_concurrent_barrier
+
+skip_xp_backends = pytest.mark.skip_xp_backends
+
+
+def _vandermonde(x, degree, xp=np):
+    # Returns a matrix of monomials that span polynomials with the specified
+    # degree evaluated at x.
+    backend = _get_backend(xp)
+    powers = backend._monomial_powers(x.shape[1], degree, xp)
+    return backend.polynomial_matrix(x, powers, xp)
+
+
+def _1d_test_function(x, xp):
+    # Test function used in Wahba's "Spline Models for Observational Data".
+    # domain ~= (0, 3), range ~= (-1.0, 0.2)
+    x = x[:, 0]
+    y = 4.26*(xp.exp(-x) - 4*xp.exp(-2*x) + 3*xp.exp(-3*x))
+    return y
+
+
+def _2d_test_function(x, xp):
+    # Franke's test function.
+    # domain ~= (0, 1) X (0, 1), range ~= (0.0, 1.2)
+    x1, x2 = x[:, 0], x[:, 1]
+    term1 = 0.75 * xp.exp(-(9*x1-2)**2/4 - (9*x2-2)**2/4)
+    term2 = 0.75 * xp.exp(-(9*x1+1)**2/49 - (9*x2+1)/10)
+    term3 = 0.5 * xp.exp(-(9*x1-7)**2/4 - (9*x2-3)**2/4)
+    term4 = -0.2 * xp.exp(-(9*x1-4)**2 - (9*x2-7)**2)
+    y = term1 + term2 + term3 + term4
+    return y
+
+
+def _is_conditionally_positive_definite(kernel, m):
+    # Tests whether the kernel is conditionally positive definite of order m.
+    # See chapter 7 of Fasshauer's "Meshfree Approximation Methods with
+    # MATLAB".
+    nx = 10
+    ntests = 100
+    for ndim in [1, 2, 3, 4, 5]:
+        # Generate sample points with a Halton sequence to avoid samples that
+        # are too close to each other, which can make the matrix singular.
+        seq = Halton(ndim, scramble=False, seed=np.random.RandomState())
+        for _ in range(ntests):
+            x = 2*seq.random(nx) - 1
+            A = _rbfinterp_pythran._kernel_matrix(x, kernel)
+            P = _vandermonde(x, m - 1)
+            Q, R = np.linalg.qr(P, mode='complete')
+            # Q2 forms a basis spanning the space where P.T.dot(x) = 0. Project
+            # A onto this space, and then see if it is positive definite using
+            # the Cholesky decomposition. If not, then the kernel is not c.p.d.
+            # of order m.
+            Q2 = Q[:, P.shape[1]:]
+            B = Q2.T.dot(A).dot(Q2)
+            try:
+                np.linalg.cholesky(B)
+            except np.linalg.LinAlgError:
+                return False
+
+    return True
+
+
+# Sorting the parametrize arguments is necessary to avoid a parallelization
+# issue described here: https://github.com/pytest-dev/pytest-xdist/issues/432.
+@pytest.mark.parametrize('kernel', sorted(_AVAILABLE))
+def test_conditionally_positive_definite(kernel):
+    # Test if each kernel in _AVAILABLE is conditionally positive definite of
+    # order m, where m comes from _NAME_TO_MIN_DEGREE. This is a necessary
+    # condition for the smoothed RBF interpolant to be well-posed in general.
+    m = _NAME_TO_MIN_DEGREE.get(kernel, -1) + 1
+    assert _is_conditionally_positive_definite(kernel, m)
+
+
+class _TestRBFInterpolator:
+    @pytest.mark.parametrize('kernel', sorted(_SCALE_INVARIANT))
+    def test_scale_invariance_1d(self, kernel, xp):
+        # Verify that the functions in _SCALE_INVARIANT are insensitive to the
+        # shape parameter (when smoothing == 0) in 1d.
+        seq = Halton(1, scramble=False, seed=np.random.RandomState())
+        x = 3*seq.random(50)
+        x = xp.asarray(x)
+
+        y = _1d_test_function(x, xp)
+        xitp = 3*seq.random(50)
+        xitp = xp.asarray(xitp)
+
+        yitp1 = self.build(x, y, epsilon=1.0, kernel=kernel)(xitp)
+        yitp2 = self.build(x, y, epsilon=2.0, kernel=kernel)(xitp)
+        xp_assert_close(yitp1, yitp2, atol=1e-8)
+
+    @pytest.mark.parametrize('kernel', sorted(_SCALE_INVARIANT))
+    def test_scale_invariance_2d(self, kernel, xp):
+        # Verify that the functions in _SCALE_INVARIANT are insensitive to the
+        # shape parameter (when smoothing == 0) in 2d.
+        seq = Halton(2, scramble=False, seed=np.random.RandomState())
+        x = seq.random(100)
+        x = xp.asarray(x)
+
+        y = _2d_test_function(x, xp)
+        xitp = seq.random(100)
+        xitp = xp.asarray(xitp)
+
+        yitp1 = self.build(x, y, epsilon=1.0, kernel=kernel)(xitp)
+        yitp2 = self.build(x, y, epsilon=2.0, kernel=kernel)(xitp)
+        xp_assert_close(yitp1, yitp2, atol=1e-8)
+
+    @pytest.mark.parametrize('kernel', sorted(_AVAILABLE))
+    def test_extreme_domains(self, kernel, xp):
+        # Make sure the interpolant remains numerically stable for very
+        # large/small domains.
+        seq = Halton(2, scramble=False, seed=np.random.RandomState())
+        scale = 1e50
+        shift = 1e55
+
+        x = seq.random(100)
+        x = xp.asarray(x)
+
+        y = _2d_test_function(x, xp)
+        xitp = seq.random(100)
+        xitp = xp.asarray(xitp)
+
+        if kernel in _SCALE_INVARIANT:
+            yitp1 = self.build(x, y, kernel=kernel)(xitp)
+            yitp2 = self.build(
+                x*scale + shift, y,
+                kernel=kernel
+                )(xitp*scale + shift)
+        else:
+            yitp1 = self.build(x, y, epsilon=5.0, kernel=kernel)(xitp)
+            yitp2 = self.build(
+                x*scale + shift, y,
+                epsilon=5.0/scale,
+                kernel=kernel
+                )(xitp*scale + shift)
+
+        xp_assert_close(yitp1, yitp2, atol=1e-8)
+
+    def test_polynomial_reproduction(self, xp):
+        # If the observed data comes from a polynomial, then the interpolant
+        # should be able to reproduce the polynomial exactly, provided that
+        # `degree` is sufficiently high.
+        rng = np.random.RandomState(0)
+        seq = Halton(2, scramble=False, seed=rng)
+        degree = 3
+
+        x = seq.random(50)
+        xitp = seq.random(50)
+        x = xp.asarray(x)
+        xitp = xp.asarray(xitp)
+
+        P = _vandermonde(x, degree, xp)
+        Pitp = _vandermonde(xitp, degree, xp)
+
+        poly_coeffs = rng.normal(0.0, 1.0, P.shape[1])
+        poly_coeffs = xp.asarray(poly_coeffs)
+
+        y = P @ poly_coeffs  #y = P.dot(poly_coeffs)
+        yitp1 = Pitp @ poly_coeffs  #yitp1 = Pitp.dot(poly_coeffs)
+        yitp2 = self.build(x, y, degree=degree)(xitp)
+
+        xp_assert_close(yitp1, yitp2, atol=1e-8)
+
+    @pytest.mark.slow
+    def test_chunking(self, monkeypatch, xp):
+        # If the observed data comes from a polynomial, then the interpolant
+        # should be able to reproduce the polynomial exactly, provided that
+        # `degree` is sufficiently high.
+        rng = np.random.RandomState(0)
+        seq = Halton(2, scramble=False, seed=rng)
+        degree = 3
+
+        largeN = 1000 + 33
+        # this is large to check that chunking of the RBFInterpolator is tested
+        x = seq.random(50)
+        xitp = seq.random(largeN)
+
+        x = xp.asarray(x)
+        xitp = xp.asarray(xitp)
+
+        P = _vandermonde(x, degree, xp)
+        Pitp = _vandermonde(xitp, degree, xp)
+
+        poly_coeffs = rng.normal(0.0, 1.0, P.shape[1])
+        poly_coeffs = xp.asarray(poly_coeffs)
+
+        y = P @ poly_coeffs   # y = P.dot(poly_coeffs)
+        yitp1 = Pitp @ poly_coeffs   # yitp1 = Pitp.dot(poly_coeffs)
+        interp = self.build(x, y, degree=degree)
+        ce_real = interp._chunk_evaluator
+
+        def _chunk_evaluator(*args, **kwargs):
+            kwargs.update(memory_budget=100)
+            return ce_real(*args, **kwargs)
+
+        monkeypatch.setattr(interp, '_chunk_evaluator', _chunk_evaluator)
+        yitp2 = interp(xitp)
+        xp_assert_close(yitp1, yitp2, atol=1e-8)
+
+    def test_vector_data(self, xp):
+        # Make sure interpolating a vector field is the same as interpolating
+        # each component separately.
+        seq = Halton(2, scramble=False, seed=np.random.RandomState())
+
+        x = seq.random(100)
+        xitp = seq.random(100)
+
+        x = xp.asarray(x)
+        xitp = xp.asarray(xitp)
+
+        y = xp.stack([_2d_test_function(x, xp),
+                      _2d_test_function(xp.flip(x, axis=1), xp)]).T
+
+        yitp1 = self.build(x, y)(xitp)
+        yitp2 = self.build(x, y[:, 0])(xitp)
+        yitp3 = self.build(x, y[:, 1])(xitp)
+
+        xp_assert_close(yitp1[:, 0], yitp2)
+        xp_assert_close(yitp1[:, 1], yitp3)
+
+    def test_complex_data(self, xp):
+        # Interpolating complex input should be the same as interpolating the
+        # real and complex components.
+        seq = Halton(2, scramble=False, seed=np.random.RandomState())
+
+        x = seq.random(100)
+        xitp = seq.random(100)
+
+        y = _2d_test_function(x, np) + 1j*_2d_test_function(x[:, ::-1], np)
+
+        x, xitp, y = map(xp.asarray, (x, xitp, y))
+
+        yitp1 = self.build(x, y)(xitp)
+        yitp2 = self.build(x, y.real)(xitp)
+        yitp3 = self.build(x, y.imag)(xitp)
+
+        xp_assert_close(yitp1.real, yitp2)
+        xp_assert_close(yitp1.imag, yitp3)
+
+    @pytest.mark.parametrize('kernel', sorted(_AVAILABLE))
+    def test_interpolation_misfit_1d(self, kernel, xp):
+        # Make sure that each kernel, with its default `degree` and an
+        # appropriate `epsilon`, does a good job at interpolation in 1d.
+        seq = Halton(1, scramble=False, seed=np.random.RandomState())
+
+        x = 3*seq.random(50)
+        xitp = 3*seq.random(50)
+
+        x = xp.asarray(x)
+        xitp = xp.asarray(xitp)
+
+        y = _1d_test_function(x, xp)
+        ytrue = _1d_test_function(xitp, xp)
+        yitp = self.build(x, y, epsilon=5.0, kernel=kernel)(xitp)
+
+        mse = xp.mean((yitp - ytrue)**2)
+        assert mse < 1.0e-4
+
+    @pytest.mark.parametrize('kernel', sorted(_AVAILABLE))
+    def test_interpolation_misfit_2d(self, kernel, xp):
+        # Make sure that each kernel, with its default `degree` and an
+        # appropriate `epsilon`, does a good job at interpolation in 2d.
+        seq = Halton(2, scramble=False, seed=np.random.RandomState())
+
+        x = seq.random(100)
+        xitp = seq.random(100)
+        x = xp.asarray(x)
+        xitp = xp.asarray(xitp)
+
+        y = _2d_test_function(x, xp)
+        ytrue = _2d_test_function(xitp, xp)
+        yitp = self.build(x, y, epsilon=5.0, kernel=kernel)(xitp)
+
+        mse = xp.mean((yitp - ytrue)**2)
+        assert mse < 2.0e-4
+
+    @pytest.mark.parametrize('kernel', sorted(_AVAILABLE))
+    def test_smoothing_misfit(self, kernel, xp):
+        # Make sure we can find a smoothing parameter for each kernel that
+        # removes a sufficient amount of noise.
+        rng = np.random.RandomState(0)
+        seq = Halton(1, scramble=False, seed=rng)
+
+        noise = 0.2
+        rmse_tol = 0.1
+        smoothing_range = 10**xp.linspace(-4, 1, 20)
+
+        x = 3*seq.random(100)
+        y = _1d_test_function(x, np) + rng.normal(0.0, noise, (100,))
+
+        x = xp.asarray(x)
+        y = xp.asarray(y)
+        ytrue = _1d_test_function(x, xp)
+        rmse_within_tol = False
+        for smoothing in smoothing_range:
+            ysmooth = self.build(
+                x, y,
+                epsilon=1.0,
+                smoothing=smoothing,
+                kernel=kernel)(x)
+            rmse = xp.sqrt(xp.mean((ysmooth - ytrue)**2))
+            if rmse < rmse_tol:
+                rmse_within_tol = True
+                break
+
+        assert rmse_within_tol
+
+    def test_array_smoothing(self, xp):
+        # Test using an array for `smoothing` to give less weight to a known
+        # outlier.
+        rng = np.random.RandomState(0)
+        seq = Halton(1, scramble=False, seed=rng)
+        degree = 2
+
+        x = seq.random(50)
+        P = _vandermonde(x, degree)
+        poly_coeffs = rng.normal(0.0, 1.0, P.shape[1])
+        y = P @ poly_coeffs  # y = P.dot(poly_coeffs)
+
+        y_with_outlier = y.copy()
+        y_with_outlier[10] += 1.0
+        smoothing = np.zeros((50,))
+        smoothing[10] = 1000.0
+
+        x, P, poly_coeffs, y = map(xp.asarray, (x, P, poly_coeffs, y))
+        y_with_outlier, smoothing = map(xp.asarray, (y_with_outlier, smoothing))
+
+        yitp = self.build(x, y_with_outlier, smoothing=smoothing)(x)
+        # Should be able to reproduce the uncorrupted data almost exactly.
+        xp_assert_close(yitp, y, atol=1e-4)
+
+    def test_inconsistent_x_dimensions_error(self):
+        # ValueError should be raised if the observation points and evaluation
+        # points have a different number of dimensions.
+        y = Halton(2, scramble=False, seed=np.random.RandomState()).random(10)
+        d = _2d_test_function(y, np)
+        x = Halton(1, scramble=False, seed=np.random.RandomState()).random(10)
+        match = 'Expected the second axis of `x`'
+        with pytest.raises(ValueError, match=match):
+            self.build(y, d)(x)
+
+    def test_inconsistent_d_length_error(self):
+        y = np.linspace(0, 1, 5)[:, None]
+        d = np.zeros(1)
+        match = 'Expected the first axis of `d`'
+        with pytest.raises(ValueError, match=match):
+            self.build(y, d)
+
+    def test_y_not_2d_error(self):
+        y = np.linspace(0, 1, 5)
+        d = np.zeros(5)
+        match = '`y` must be a 2-dimensional array.'
+        with pytest.raises(ValueError, match=match):
+            self.build(y, d)
+
+    def test_inconsistent_smoothing_length_error(self):
+        y = np.linspace(0, 1, 5)[:, None]
+        d = np.zeros(5)
+        smoothing = np.ones(1)
+        match = 'Expected `smoothing` to be'
+        with pytest.raises(ValueError, match=match):
+            self.build(y, d, smoothing=smoothing)
+
+    def test_invalid_kernel_name_error(self):
+        y = np.linspace(0, 1, 5)[:, None]
+        d = np.zeros(5)
+        match = '`kernel` must be one of'
+        with pytest.raises(ValueError, match=match):
+            self.build(y, d, kernel='test')
+
+    def test_epsilon_not_specified_error(self):
+        y = np.linspace(0, 1, 5)[:, None]
+        d = np.zeros(5)
+        for kernel in _AVAILABLE:
+            if kernel in _SCALE_INVARIANT:
+                continue
+
+            match = '`epsilon` must be specified'
+            with pytest.raises(ValueError, match=match):
+                self.build(y, d, kernel=kernel)
+
+    def test_x_not_2d_error(self):
+        y = np.linspace(0, 1, 5)[:, None]
+        x = np.linspace(0, 1, 5)
+        d = np.zeros(5)
+        match = '`x` must be a 2-dimensional array.'
+        with pytest.raises(ValueError, match=match):
+            self.build(y, d)(x)
+
+    def test_not_enough_observations_error(self):
+        y = np.linspace(0, 1, 1)[:, None]
+        d = np.zeros(1)
+        match = 'At least 2 data points are required'
+        with pytest.raises(ValueError, match=match):
+            self.build(y, d, kernel='thin_plate_spline')
+
+    def test_degree_warning(self):
+        y = np.linspace(0, 1, 5)[:, None]
+        d = np.zeros(5)
+        for kernel, deg in _NAME_TO_MIN_DEGREE.items():
+            # Only test for kernels that its minimum degree is not 0.
+            if deg >= 1:
+                match = f'`degree` should not be below {deg}'
+                with pytest.warns(Warning, match=match):
+                    self.build(y, d, epsilon=1.0, kernel=kernel, degree=deg-1)
+
+    def test_minus_one_degree(self):
+        # Make sure a degree of -1 is accepted without any warning.
+        y = np.linspace(0, 1, 5)[:, None]
+        d = np.zeros(5)
+        for kernel, _ in _NAME_TO_MIN_DEGREE.items():
+            self.build(y, d, epsilon=1.0, kernel=kernel, degree=-1)
+
+    @skip_xp_backends("jax.numpy", reason="solve raises no error for a singular matrix")
+    @skip_xp_backends("cupy", reason="solve raises no error for a singular matrix")
+    def test_rank_error(self, xp):
+        # An error should be raised when `kernel` is "thin_plate_spline" and
+        # observations are 2-D and collinear.
+        y = xp.asarray([[2.0, 0.0], [1.0, 0.0], [0.0, 0.0]])
+        d = xp.asarray([0.0, 0.0, 0.0])
+        match = 'does not have full column rank'
+        with pytest.raises(LinAlgError, match=match):
+            self.build(y, d, kernel='thin_plate_spline')(y)
+
+    def test_single_point(self, xp):
+        # Make sure interpolation still works with only one point (in 1, 2, and
+        # 3 dimensions).
+        for dim in [1, 2, 3]:
+            y = xp.zeros((1, dim))
+            d = xp.ones((1,), dtype=xp.float64)
+            f = self.build(y, d, kernel='linear')(y)
+            xp_assert_close(f, d)
+
+    def test_pickleable(self, xp):
+        # Make sure we can pickle and unpickle the interpolant without any
+        # changes in the behavior.
+        seq = Halton(1, scramble=False, seed=np.random.RandomState(2305982309))
+
+        x = 3*seq.random(50)
+        xitp = 3*seq.random(50)
+        x, xitp = xp.asarray(x), xp.asarray(xitp)
+
+        y = _1d_test_function(x, xp)
+
+        interp = self.build(x, y)
+
+        yitp1 = interp(xitp)
+        yitp2 = pickle.loads(pickle.dumps(interp))(xitp)
+
+        xp_assert_close(yitp1, yitp2, atol=1e-16)
+
+
+@make_xp_test_case(RBFInterpolator)
+class TestRBFInterpolatorNeighborsNone(_TestRBFInterpolator):
+    def build(self, *args, **kwargs):
+        return RBFInterpolator(*args, **kwargs)
+
+    def test_smoothing_limit_1d(self):
+        # For large smoothing parameters, the interpolant should approach a
+        # least squares fit of a polynomial with the specified degree.
+        seq = Halton(1, scramble=False, seed=np.random.RandomState())
+
+        degree = 3
+        smoothing = 1e8
+
+        x = 3*seq.random(50)
+        xitp = 3*seq.random(50)
+        y = _1d_test_function(x, np)
+
+        yitp1 = self.build(
+            x, y,
+            degree=degree,
+            smoothing=smoothing
+            )(xitp)
+
+        P = _vandermonde(x, degree)
+        Pitp = _vandermonde(xitp, degree)
+        yitp2 = Pitp.dot(np.linalg.lstsq(P, y, rcond=None)[0])
+
+        xp_assert_close(yitp1, yitp2, atol=1e-8)
+
+    def test_smoothing_limit_2d(self):
+        # For large smoothing parameters, the interpolant should approach a
+        # least squares fit of a polynomial with the specified degree.
+        seq = Halton(2, scramble=False, seed=np.random.RandomState())
+
+        degree = 3
+        smoothing = 1e8
+
+        x = seq.random(100)
+        xitp = seq.random(100)
+
+        y = _2d_test_function(x, np)
+
+        yitp1 = self.build(
+            x, y,
+            degree=degree,
+            smoothing=smoothing
+            )(xitp)
+
+        P = _vandermonde(x, degree)
+        Pitp = _vandermonde(xitp, degree)
+        yitp2 = Pitp.dot(np.linalg.lstsq(P, y, rcond=None)[0])
+
+        xp_assert_close(yitp1, yitp2, atol=1e-8)
+
+    def test_singular(self):
+        # regression test for https://github.com/scipy/scipy/issues/23761
+        # The input is singular in floating-point, make sure the singularity is detected
+        points = np.array(
+            [[2.0, 0.0],
+             [0.0, 0.0],
+             [0.0, 1.0735703551645039e-302],
+             [0.5, 3.0]]
+        )
+        values = np.array([0.0, 0.0, 0.0, 1.0])
+
+        with pytest.raises(LinAlgError, match="Singular matrix"):
+            RBFInterpolator(points, values.reshape(-1, 1))
+
+
+@skip_xp_backends(np_only=True, reason="neighbors not None uses KDTree")
+@make_xp_test_case(RBFInterpolator)
+class TestRBFInterpolatorNeighbors20(_TestRBFInterpolator):
+    # RBFInterpolator using 20 nearest neighbors.
+    def build(self, *args, **kwargs):
+        return RBFInterpolator(*args, **kwargs, neighbors=20)
+
+    def test_equivalent_to_rbf_interpolator(self):
+        seq = Halton(2, scramble=False, seed=np.random.RandomState())
+
+        x = seq.random(100)
+        xitp = seq.random(100)
+
+        y = _2d_test_function(x, np)
+
+        yitp1 = self.build(x, y)(xitp)
+
+        yitp2 = []
+        tree = cKDTree(x)
+        for xi in xitp:
+            _, nbr = tree.query(xi, 20)
+            yitp2.append(RBFInterpolator(x[nbr], y[nbr])(xi[None])[0])
+
+        xp_assert_close(yitp1, yitp2, atol=1e-8)
+
+    def test_concurrency(self):
+        # Check that no segfaults appear with concurrent access to
+        # RbfInterpolator
+        seq = Halton(2, scramble=False, seed=np.random.RandomState(0))
+        x = seq.random(100)
+        xitp = seq.random(100)
+
+        y = _2d_test_function(x, np)
+
+        interp = self.build(x, y)
+
+        def worker_fn(_, interp, xp):
+            interp(xp)
+
+        _run_concurrent_barrier(10, worker_fn, interp, xitp)
+
+
+@skip_xp_backends(np_only=True, reason="neighbors not None uses KDTree")
+class TestRBFInterpolatorNeighborsInf(TestRBFInterpolatorNeighborsNone):
+    # RBFInterpolator using neighbors=np.inf. This should give exactly the same
+    # results as neighbors=None, but it will be slower.
+    def build(self, *args, **kwargs):
+        return RBFInterpolator(*args, **kwargs, neighbors=np.inf)
+
+    def test_equivalent_to_rbf_interpolator(self):
+        seq = Halton(1, scramble=False, seed=np.random.RandomState())
+
+        x = 3*seq.random(50)
+        xitp = 3*seq.random(50)
+
+        y = _1d_test_function(x, np)
+        yitp1 = self.build(x, y)(xitp)
+        yitp2 = RBFInterpolator(x, y)(xitp)
+
+        xp_assert_close(yitp1, yitp2, atol=1e-8)
diff --git a/.venv/lib/python3.12/site-packages/scipy/interpolate/tests/test_rgi.py b/.venv/lib/python3.12/site-packages/scipy/interpolate/tests/test_rgi.py
new file mode 100644
index 0000000000000000000000000000000000000000..bbfaa8d7d5af1300b54c51a0f3bb0147df41f438
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/interpolate/tests/test_rgi.py
@@ -0,0 +1,1249 @@
+import itertools
+
+import pytest
+import numpy as np
+
+from numpy.exceptions import ComplexWarning
+
+from scipy._lib._array_api import (
+    xp_assert_equal, xp_assert_close, assert_array_almost_equal,
+    make_xp_test_case
+)
+from scipy.conftest import skip_xp_invalid_arg
+
+from pytest import raises as assert_raises
+
+from scipy.interpolate import (RegularGridInterpolator, interpn,
+                               RectBivariateSpline,
+                               NearestNDInterpolator, LinearNDInterpolator)
+from scipy.interpolate._regrid import (_regrid,
+                                              _ndbspline_call_like_bivariate)
+
+from scipy.sparse._sputils import matrix
+from scipy._lib._testutils import _run_concurrent_barrier
+
+
+parametrize_rgi_interp_methods = pytest.mark.parametrize(
+    "method", RegularGridInterpolator._ALL_METHODS
+)
+
+@make_xp_test_case(RegularGridInterpolator)
+class TestRegularGridInterpolator:
+    def _get_sample_4d(self, xp):
+        # create a 4-D grid of 3 points in each dimension
+        points = [(0., .5, 1.)] * 4
+        values = xp.asarray([0., .5, 1.])
+        values0 = values[:, np.newaxis, np.newaxis, np.newaxis]
+        values1 = values[np.newaxis, :, np.newaxis, np.newaxis]
+        values2 = values[np.newaxis, np.newaxis, :, np.newaxis]
+        values3 = values[np.newaxis, np.newaxis, np.newaxis, :]
+        values = (values0 + values1 * 10 + values2 * 100 + values3 * 1000)
+        return points, values
+
+    def _get_sample_4d_2(self, xp):
+        # create another 4-D grid of 3 points in each dimension
+        points = [(0., .5, 1.)] * 2 + [(0., 5., 10.)] * 2
+        values = xp.asarray([0., .5, 1.])
+        values0 = values[:, np.newaxis, np.newaxis, np.newaxis]
+        values1 = values[np.newaxis, :, np.newaxis, np.newaxis]
+        values2 = values[np.newaxis, np.newaxis, :, np.newaxis]
+        values3 = values[np.newaxis, np.newaxis, np.newaxis, :]
+        values = (values0 + values1 * 10 + values2 * 100 + values3 * 1000)
+        return points, values
+
+    def _get_sample_4d_3(self, xp):
+        # create another 4-D grid of 7 points in each dimension
+        points = [(0.0, 0.5, 1.0, 1.5, 2.0, 2.5, 3.0)] * 4
+        values = xp.asarray([0.0, 0.5, 1.0, 1.5, 2.0, 2.5, 3.0])
+        values0 = values[:, np.newaxis, np.newaxis, np.newaxis]
+        values1 = values[np.newaxis, :, np.newaxis, np.newaxis]
+        values2 = values[np.newaxis, np.newaxis, :, np.newaxis]
+        values3 = values[np.newaxis, np.newaxis, np.newaxis, :]
+        values = (values0 + values1 * 10 + values2 * 100 + values3 * 1000)
+        return points, values
+
+    def _get_sample_4d_4(self, xp):
+        # create another 4-D grid of 2 points in each dimension
+        points = [(0.0, 1.0)] * 4
+        values = xp.asarray([0.0, 1.0])
+        values0 = values[:, np.newaxis, np.newaxis, np.newaxis]
+        values1 = values[np.newaxis, :, np.newaxis, np.newaxis]
+        values2 = values[np.newaxis, np.newaxis, :, np.newaxis]
+        values3 = values[np.newaxis, np.newaxis, np.newaxis, :]
+        values = (values0 + values1 * 10 + values2 * 100 + values3 * 1000)
+        return points, values
+
+    @parametrize_rgi_interp_methods
+    def test_list_input(self, method):
+        points, values = self._get_sample_4d_3(xp=np)
+
+        sample = np.asarray([[0.1, 0.1, 1., .9], [0.2, 0.1, .45, .8],
+                             [0.5, 0.5, .5, .5]])
+
+        interp = RegularGridInterpolator(points,
+                                         values.tolist(),
+                                         method=method)
+        v1 = interp(sample.tolist())
+        interp = RegularGridInterpolator(points,
+                                         values,
+                                         method=method)
+        v2 = interp(sample)
+        xp_assert_close(v1, v2)
+
+    @pytest.mark.parametrize('method', ['cubic', 'quintic', 'pchip'])
+    def test_spline_dim_error(self, method, xp):
+        points, values = self._get_sample_4d_4(xp)
+        points = list(xp.asarray(p) for p in points)
+        match = "points in dimension"
+
+        # Check error raise when creating interpolator
+        with pytest.raises(ValueError, match=match):
+            RegularGridInterpolator(points, values, method=method)
+
+        # Check error raise when creating interpolator
+        interp = RegularGridInterpolator(points, values)
+        sample = xp.asarray([[0.1, 0.1, 1., .9], [0.2, 0.1, .45, .8],
+                             [0.5, 0.5, .5, .5]])
+        with pytest.raises(ValueError, match=match):
+            interp(sample, method=method)
+
+    @pytest.mark.parametrize(
+        "points_values, sample",
+        [
+            (
+                _get_sample_4d,
+                np.asarray(
+                [[0.1, 0.1, 1.0, 0.9],
+                 [0.2, 0.1, 0.45, 0.8],
+                 [0.5, 0.5, 0.5, 0.5]]
+                ),
+            ),
+            (_get_sample_4d_2, np.asarray([0.1, 0.1, 10.0, 9.0])),
+        ],
+    )
+    def test_linear_and_slinear_close(self, points_values, sample, xp):
+        points, values = points_values(self, xp)
+        points, sample = list(xp.asarray(p) for p in points), xp.asarray(sample)
+        interp = RegularGridInterpolator(points, values, method="linear")
+        v1 = interp(sample)
+        interp = RegularGridInterpolator(points, values, method="slinear")
+        v2 = interp(sample)
+        xp_assert_close(v1, v2)
+
+    def test_derivatives(self, xp):
+        points, values = self._get_sample_4d(xp)
+        points = list(xp.asarray(p) for p in points)
+        sample = xp.asarray([[0.1 , 0.1 , 1.  , 0.9 ],
+                           [0.2 , 0.1 , 0.45, 0.8 ],
+                           [0.5 , 0.5 , 0.5 , 0.5 ]])
+        interp = RegularGridInterpolator(points, values, method="slinear")
+
+        with assert_raises(ValueError):
+            # wrong number of derivatives (need 4)
+            interp(sample, nu=1)
+
+        xp_assert_close(interp(sample, nu=(1, 0, 0, 0)),
+                        xp.asarray([1.0, 1, 1], dtype=xp.float64), atol=1e-15)
+        xp_assert_close(interp(sample, nu=(0, 1, 0, 0)),
+                        xp.asarray([10.0, 10, 10], dtype=xp.float64), atol=1e-15)
+
+        # 2nd derivatives of a linear function are zero
+        xp_assert_close(interp(sample, nu=(0, 1, 1, 0)),
+                        xp.asarray([0.0, 0, 0], dtype=xp.float64), atol=2e-12)
+
+    @parametrize_rgi_interp_methods
+    def test_complex(self, method, xp):
+        if method == "pchip":
+            pytest.skip("pchip does not make sense for complex data")
+        points, values = self._get_sample_4d_3(xp)
+        points = list(xp.asarray(p) for p in points)
+        values = values - 2j*values
+        sample = xp.asarray([[0.1, 0.1, 1., .9], [0.2, 0.1, .45, .8],
+                             [0.5, 0.5, .5, .5]])
+
+        interp = RegularGridInterpolator(points, values, method=method)
+        rinterp = RegularGridInterpolator(points, xp.real(values), method=method)
+        iinterp = RegularGridInterpolator(points, xp.imag(values), method=method)
+
+        v1 = interp(sample)
+        v2 = rinterp(sample) + 1j*iinterp(sample)
+        xp_assert_close(v1, v2)
+
+    def test_cubic_vs_pchip(self, xp):
+        x, y = xp.asarray([1, 2, 3, 4]), xp.asarray([1, 2, 3, 4])
+        xg, yg = xp.meshgrid(x, y, indexing='ij')
+
+        values = (lambda x, y: x**4 * y**4)(xg, yg)
+        cubic = RegularGridInterpolator((x, y), values, method='cubic')
+        pchip = RegularGridInterpolator((x, y), values, method='pchip')
+
+        vals_cubic = cubic([1.5, 2])
+        vals_pchip = pchip([1.5, 2])
+        #assert not np.allclose(vals_cubic, vals_pchip, atol=1e-14, rtol=0)
+        assert not xp.all(xp.abs(vals_cubic - vals_pchip) < 1e-14)
+
+    def test_linear_xi1d(self, xp):
+        points, values = self._get_sample_4d_2(xp)
+        points = list(xp.asarray(p) for p in points)
+        interp = RegularGridInterpolator(points, values)
+        sample = xp.asarray([0.1, 0.1, 10., 9.])
+        wanted = xp.asarray([1001.1], dtype=xp.float64)
+        assert_array_almost_equal(interp(sample), wanted)
+
+    def test_linear_xi3d(self, xp):
+        points, values = self._get_sample_4d(xp)
+        points = list(xp.asarray(p) for p in points)
+        interp = RegularGridInterpolator(points, values)
+        sample = xp.asarray([[0.1, 0.1, 1., .9], [0.2, 0.1, .45, .8],
+                             [0.5, 0.5, .5, .5]])
+        wanted = xp.asarray([1001.1, 846.2, 555.5])
+        assert_array_almost_equal(interp(sample), wanted)
+
+    @pytest.mark.parametrize(
+        "sample, wanted",
+        [
+            ([0.1, 0.1, 0.9, 0.9], 1100.0),
+            ([0.1, 0.1, 0.1, 0.1], 0.0),
+            ([0.0, 0.0, 0.0, 0.0], 0.0),
+            ([1.0, 1.0, 1.0, 1.0], 1111.0),
+            ([0.1, 0.4, 0.6, 0.9], 1055.0),
+        ],
+    )
+    def test_nearest(self, sample, wanted, xp):
+        points, values = self._get_sample_4d(xp)
+        points, sample = tuple(xp.asarray(p) for p in points), xp.asarray(sample)
+        interp = RegularGridInterpolator(points, values, method="nearest")
+        wanted = xp.asarray([wanted], dtype=xp.float64)
+        assert_array_almost_equal(interp(sample), wanted)
+
+    def test_linear_edges(self, xp):
+        points, values = self._get_sample_4d(xp)
+        points = list(xp.asarray(p) for p in points)
+        interp = RegularGridInterpolator(points, values)
+        sample = xp.asarray([[0., 0., 0., 0.], [1., 1., 1., 1.]])
+        wanted = xp.asarray([0., 1111.])
+        assert_array_almost_equal(interp(sample), wanted)
+
+    def test_valid_create(self):
+        # create a 2-D grid of 3 points in each dimension
+        points = [(0., .5, 1.), (0., 1., .5)]
+        values = np.asarray([0., .5, 1.])
+        values0 = values[:, np.newaxis]
+        values1 = values[np.newaxis, :]
+        values = (values0 + values1 * 10)
+        assert_raises(ValueError, RegularGridInterpolator, points, values)
+        points = [((0., .5, 1.), ), (0., .5, 1.)]
+        assert_raises(ValueError, RegularGridInterpolator, points, values)
+        points = [(0., .5, .75, 1.), (0., .5, 1.)]
+        assert_raises(ValueError, RegularGridInterpolator, points, values)
+        points = [(0., .5, 1.), (0., .5, 1.), (0., .5, 1.)]
+        assert_raises(ValueError, RegularGridInterpolator, points, values)
+        points = [(0., .5, 1.), (0., .5, 1.)]
+        assert_raises(ValueError, RegularGridInterpolator, points, values,
+                      method="undefmethod")
+
+    def test_valid_call(self, xp):
+        points, values = self._get_sample_4d(xp)
+        points = list(xp.asarray(p) for p in points)
+        interp = RegularGridInterpolator(points, values)
+        sample = xp.asarray([[0., 0., 0., 0.], [1., 1., 1., 1.]])
+        with assert_raises(ValueError):
+            interp(sample, "undefmethod")
+
+        sample = xp.asarray([[0., 0., 0.], [1., 1., 1.]])
+        with assert_raises(ValueError):
+            interp(sample)
+
+        sample = xp.asarray([[0., 0., 0., 0.], [1., 1., 1., 1.1]])
+        with assert_raises(ValueError):
+            interp(sample)
+
+    def test_out_of_bounds_extrap(self, xp):
+        points, values = self._get_sample_4d(xp)
+        points = list(xp.asarray(p) for p in points)
+        interp = RegularGridInterpolator(points, values, bounds_error=False,
+                                         fill_value=None)
+        sample = xp.asarray([[-.1, -.1, -.1, -.1], [1.1, 1.1, 1.1, 1.1],
+                             [21, 2.1, -1.1, -11], [2.1, 2.1, -1.1, -1.1]],
+                            dtype=xp.float64)
+        wanted = xp.asarray([0., 1111., 11., 11.], dtype=xp.float64)
+        assert_array_almost_equal(interp(sample, method="nearest"), wanted)
+        wanted = xp.asarray([-111.1, 1222.1, -11068., -1186.9], dtype=xp.float64)
+        assert_array_almost_equal(interp(sample, method="linear"), wanted)
+
+    def test_out_of_bounds_extrap2(self, xp):
+        points, values = self._get_sample_4d_2(xp)
+        points = list(xp.asarray(p) for p in points)
+        interp = RegularGridInterpolator(points, values, bounds_error=False,
+                                         fill_value=None)
+        sample = xp.asarray([[-.1, -.1, -.1, -.1], [1.1, 1.1, 1.1, 1.1],
+                             [21, 2.1, -1.1, -11], [2.1, 2.1, -1.1, -1.1]],
+                            dtype=xp.float64)
+        wanted = xp.asarray([0., 11., 11., 11.], dtype=xp.float64)
+        assert_array_almost_equal(interp(sample, method="nearest"), wanted)
+        wanted = xp.asarray([-12.1, 133.1, -1069., -97.9], dtype=xp.float64)
+        assert_array_almost_equal(interp(sample, method="linear"), wanted)
+
+    def test_out_of_bounds_fill(self, xp):
+        points, values = self._get_sample_4d(xp)
+        points = list(xp.asarray(p) for p in points)
+        interp = RegularGridInterpolator(points, values, bounds_error=False,
+                                         fill_value=xp.nan)
+        sample = xp.asarray([[-.1, -.1, -.1, -.1], [1.1, 1.1, 1.1, 1.1],
+                             [2.1, 2.1, -1.1, -1.1]])
+        wanted = xp.asarray([xp.nan, xp.nan, xp.nan])
+        assert_array_almost_equal(interp(sample, method="nearest"), wanted)
+        assert_array_almost_equal(interp(sample, method="linear"), wanted)
+        sample = xp.asarray([[0.1, 0.1, 1., .9], [0.2, 0.1, .45, .8],
+                             [0.5, 0.5, .5, .5]])
+        wanted = xp.asarray([1001.1, 846.2, 555.5])
+        assert_array_almost_equal(interp(sample), wanted)
+
+    def test_nearest_compare_qhull(self):
+        points, values = self._get_sample_4d(np)
+        interp = RegularGridInterpolator(points, values, method="nearest")
+        points_qhull = itertools.product(*points)
+        points_qhull = [p for p in points_qhull]
+        points_qhull = np.asarray(points_qhull)
+        values_qhull = values.reshape(-1)
+        interp_qhull = NearestNDInterpolator(points_qhull, values_qhull)
+        sample = np.asarray([[0.1, 0.1, 1., .9], [0.2, 0.1, .45, .8],
+                             [0.5, 0.5, .5, .5]])
+        assert_array_almost_equal(interp(sample), interp_qhull(sample))
+
+    def test_linear_compare_qhull(self):
+        points, values = self._get_sample_4d(np)
+        interp = RegularGridInterpolator(points, values)
+        points_qhull = itertools.product(*points)
+        points_qhull = [p for p in points_qhull]
+        points_qhull = np.asarray(points_qhull)
+        values_qhull = values.reshape(-1)
+        interp_qhull = LinearNDInterpolator(points_qhull, values_qhull)
+        sample = np.asarray([[0.1, 0.1, 1., .9], [0.2, 0.1, .45, .8],
+                             [0.5, 0.5, .5, .5]])
+        assert_array_almost_equal(interp(sample), interp_qhull(sample))
+
+    @pytest.mark.parametrize("method", ["nearest", "linear"])
+    def test_duck_typed_values(self, method):
+        x = np.linspace(0, 2, 5)
+        y = np.linspace(0, 1, 7)
+
+        values = MyValue((5, 7))
+
+        interp = RegularGridInterpolator((x, y), values, method=method)
+        v1 = interp([0.4, 0.7])
+
+        interp = RegularGridInterpolator((x, y), values._v, method=method)
+        v2 = interp([0.4, 0.7])
+        xp_assert_close(v1, v2, check_dtype=False)
+
+    def test_invalid_fill_value(self):
+        np.random.seed(1234)
+        x = np.linspace(0, 2, 5)
+        y = np.linspace(0, 1, 7)
+        values = np.random.rand(5, 7)
+
+        # integers can be cast to floats
+        RegularGridInterpolator((x, y), values, fill_value=1)
+
+        # complex values cannot
+        assert_raises(ValueError, RegularGridInterpolator,
+                      (x, y), values, fill_value=1+2j)
+
+    def test_fillvalue_type(self):
+        # from #3703; test that interpolator object construction succeeds
+        values = np.ones((10, 20, 30), dtype='>f4')
+        points = [np.arange(n) for n in values.shape]
+        # xi = [(1, 1, 1)]
+        RegularGridInterpolator(points, values)
+        RegularGridInterpolator(points, values, fill_value=0.)
+
+    @pytest.mark.parametrize("dtype", [np.float32, np.float64])
+    @pytest.mark.parametrize("ndim", [1, 2, 3])
+    @pytest.mark.parametrize("method", ["linear", "nearest"])
+    def test_length_one_axis_all(self, dtype, ndim, method):
+        # gh-23171: length-1 axes in all dimensions are legal
+        # for all methods parametrized above.
+
+        # Construct test point 'x0' with coordinates[0, 1, ..., ndim-1].
+        # NOTE: choice of coordinates is arbitrary, could be random numbers,
+        # but using np.arange for convenience.
+        x0 = np.arange(ndim, dtype=dtype)
+
+        # Unpack 'x0'; loosly speaking this is the inverse of np.mgrid.
+        # By construction 'points' defines a grid of length one along all axes.
+        points = tuple(np.asarray([xi]) for xi in x0)
+
+        # Construct 'values' array of dimensions (1, 1, ...) from 0D 'val'.
+        val = np.asarray(1/7, dtype=dtype)
+        values = np.full(shape=(1, )*ndim, fill_value=val)
+
+        # Fill value, as a 0D array of correct dtype.
+        fill = np.asarray(1/42, dtype=dtype)
+
+        # method "linear" promotes results to np.float64
+        promoted_dtype = np.float64 if method == "linear" else dtype
+
+        # Create interpolator instances, with and without 'bounds_error' check.
+        interp_fill = RegularGridInterpolator(
+            points, values, method=method, bounds_error=False, fill_value=fill
+        )
+        interp_err = RegularGridInterpolator(
+            points, values, method=method, bounds_error=True,
+        )
+
+        # Check interpolator returns correct value for valid sample.
+        sample = np.asarray([x0])
+        wanted = np.asarray([val], dtype=promoted_dtype)
+        for result in [interp_fill(sample), interp_err(sample)]:
+            xp_assert_equal(result, wanted)
+
+        # Check out of bound point along first direction.
+        x0[0] += 1
+        sample = np.asarray([x0])
+        wanted = np.asarray([fill], dtype=promoted_dtype)
+        result = interp_fill(sample)
+        xp_assert_equal(result, wanted)
+        with pytest.raises(
+            ValueError,
+            match="^One of the requested xi is out of bounds in dimension 0$",
+        ):
+            interp_err(sample)
+
+        # check point with NaN in first direction
+        x0[0] = np.nan
+        sample = np.asarray([x0])
+        wanted = np.asarray([np.nan], dtype=promoted_dtype)
+        result = interp_fill(sample)
+        xp_assert_equal(result, wanted)
+        with pytest.raises(
+            ValueError,
+            match="^One of the requested xi is out of bounds in dimension 0$",
+        ):
+            interp_err(sample)
+
+    def test_length_one_axis(self):
+        # gh-5890, gh-9524 : length-1 axis is legal for method='linear'.
+        # Along the axis it's linear interpolation; away from the length-1
+        # axis, it's an extrapolation, so fill_value should be used.
+        def f(x, y):
+            return x + y
+        x = np.linspace(1, 1, 1)
+        y = np.linspace(1, 10, 10)
+        data = f(*np.meshgrid(x, y, indexing="ij", sparse=True))
+
+        interp = RegularGridInterpolator((x, y), data, method="linear",
+                                         bounds_error=False, fill_value=101)
+
+        # check values at the grid
+        xp_assert_close(interp(np.array([[1, 1], [1, 5], [1, 10]])),
+                        np.asarray([2.0, 6, 11]),
+                        atol=1e-14)
+
+        # check off-grid interpolation is indeed linear
+        xp_assert_close(interp(np.array([[1, 1.4], [1, 5.3], [1, 10]])),
+                        [2.4, 6.3, 11],
+                        atol=1e-14)
+
+        # check exrapolation w/ fill_value
+        xp_assert_close(interp(np.array([1.1, 2.4])),
+                        interp.fill_value,
+                        check_dtype=False, check_shape=False, check_0d=False,
+                        atol=1e-14)
+
+        # check extrapolation: linear along the `y` axis, const along `x`
+        interp.fill_value = None
+        xp_assert_close(interp([[1, 0.3], [1, 11.5]]),
+                        [1.3, 12.5], atol=1e-15)
+
+        xp_assert_close(interp([[1.5, 0.3], [1.9, 11.5]]),
+                        [1.3, 12.5], atol=1e-15)
+
+        # extrapolation with method='nearest'
+        interp = RegularGridInterpolator((x, y), data, method="nearest",
+                                         bounds_error=False, fill_value=None)
+        xp_assert_close(interp([[1.5, 1.8], [-4, 5.1]]),
+                        np.asarray([3.0, 6]),
+                        atol=1e-15)
+
+    @pytest.mark.parametrize("fill_value", [None, np.nan, np.pi])
+    @pytest.mark.parametrize("method", ['linear', 'nearest'])
+    def test_length_one_axis2(self, fill_value, method):
+        options = {"fill_value": fill_value, "bounds_error": False,
+                   "method": method}
+
+        x = np.linspace(0, 2*np.pi, 20)
+        z = np.sin(x)
+
+        fa = RegularGridInterpolator((x,), z[:], **options)
+        fb = RegularGridInterpolator((x, [0]), z[:, None], **options)
+
+        x1a = np.linspace(-1, 2*np.pi+1, 100)
+        za = fa(x1a)
+
+        # evaluated at provided y-value, fb should behave exactly as fa
+        y1b = np.zeros(100)
+        zb = fb(np.vstack([x1a, y1b]).T)
+        xp_assert_close(zb, za)
+
+        # evaluated at a different y-value, fb should return fill value
+        y1b = np.ones(100)
+        zb = fb(np.vstack([x1a, y1b]).T)
+        if fill_value is None:
+            xp_assert_close(zb, za)
+        else:
+            xp_assert_close(zb, np.full_like(zb, fill_value))
+
+    @pytest.mark.parametrize("method", ['nearest', 'linear'])
+    def test_nan_x_1d(self, method):
+        # gh-6624 : if x is nan, result should be nan
+        f = RegularGridInterpolator(([1, 2, 3],), [10, 20, 30], fill_value=1,
+                                    bounds_error=False, method=method)
+        assert np.isnan(f([np.nan]))
+
+        # test arbitrary nan pattern
+        rng = np.random.default_rng(8143215468)
+        x = rng.random(size=100)*4
+        i = rng.random(size=100) > 0.5
+        x[i] = np.nan
+        with np.errstate(invalid='ignore'):
+            # out-of-bounds comparisons, `out_of_bounds += x < grid[0]`,
+            # generate numpy warnings if `x` contains nans.
+            # These warnings should propagate to user (since `x` is user
+            # input) and we simply filter them out.
+            res = f(x)
+
+        assert np.isnan(res[i]).all()
+        xp_assert_equal(res[~i], f(x[~i]))
+
+        # also test the length-one axis f(nan)
+        x = [1, 2, 3]
+        y = [1, ]
+        data = np.ones((3, 1))
+        f = RegularGridInterpolator((x, y), data, fill_value=1,
+                                    bounds_error=False, method=method)
+        assert np.all(np.isnan(f([np.nan, 1])))
+        assert np.all(np.isnan(f([1, np.nan])))
+
+    @pytest.mark.parametrize("method", ['nearest', 'linear'])
+    def test_nan_x_2d(self, method):
+        x, y = np.array([0, 1, 2]), np.array([1, 3, 7])
+
+        def f(x, y):
+            return x**2 + y**2
+
+        xg, yg = np.meshgrid(x, y, indexing='ij', sparse=True)
+        data = f(xg, yg)
+        interp = RegularGridInterpolator((x, y), data,
+                                         method=method, bounds_error=False)
+
+        with np.errstate(invalid='ignore'):
+            res = interp([[1.5, np.nan], [1, 1]])
+        xp_assert_close(res[1], 2.0, atol=1e-14)
+        assert np.isnan(res[0])
+
+        # test arbitrary nan pattern
+        rng = np.random.default_rng(8143215468)
+        x = rng.random(size=100)*4-1
+        y = rng.random(size=100)*8
+        i1 = rng.random(size=100) > 0.5
+        i2 = rng.random(size=100) > 0.5
+        i = i1 | i2
+        x[i1] = np.nan
+        y[i2] = np.nan
+        z = np.array([x, y]).T
+        with np.errstate(invalid='ignore'):
+            # out-of-bounds comparisons, `out_of_bounds += x < grid[0]`,
+            # generate numpy warnings if `x` contains nans.
+            # These warnings should propagate to user (since `x` is user
+            # input) and we simply filter them out.
+            res = interp(z)
+
+        assert np.isnan(res[i]).all()
+        xp_assert_equal(res[~i], interp(z[~i]), check_dtype=False)
+
+    @pytest.mark.fail_slow(10)
+    @parametrize_rgi_interp_methods
+    @pytest.mark.parametrize(("ndims", "func"), [
+        (2, lambda x, y: 2 * x ** 3 + 3 * y ** 2),
+        (3, lambda x, y, z: 2 * x ** 3 + 3 * y ** 2 - z),
+        (4, lambda x, y, z, a: 2 * x ** 3 + 3 * y ** 2 - z + a),
+        (5, lambda x, y, z, a, b: 2 * x ** 3 + 3 * y ** 2 - z + a * b),
+    ])
+    def test_descending_points_nd(self, method, ndims, func):
+
+        if ndims >= 4 and method in {"cubic", "quintic"}:
+            pytest.skip("too slow; OOM (quintic); or nearly so (cubic)")
+
+        rng = np.random.default_rng(42)
+        sample_low = 1
+        sample_high = 5
+        test_points = rng.uniform(sample_low, sample_high, size=(2, ndims))
+
+        ascending_points = [np.linspace(sample_low, sample_high, 12)
+                            for _ in range(ndims)]
+
+        ascending_values = func(*np.meshgrid(*ascending_points,
+                                             indexing="ij",
+                                             sparse=True))
+
+        ascending_interp = RegularGridInterpolator(ascending_points,
+                                                   ascending_values,
+                                                   method=method)
+        ascending_result = ascending_interp(test_points)
+
+        descending_points = [xi[::-1] for xi in ascending_points]
+        descending_values = func(*np.meshgrid(*descending_points,
+                                              indexing="ij",
+                                              sparse=True))
+        descending_interp = RegularGridInterpolator(descending_points,
+                                                    descending_values,
+                                                    method=method)
+        descending_result = descending_interp(test_points)
+
+        xp_assert_equal(ascending_result, descending_result)
+
+    def test_invalid_points_order(self):
+        def val_func_2d(x, y):
+            return 2 * x ** 3 + 3 * y ** 2
+
+        x = np.array([.5, 2., 0., 4., 5.5])  # not ascending or descending
+        y = np.array([.5, 2., 3., 4., 5.5])
+        points = (x, y)
+        values = val_func_2d(*np.meshgrid(*points, indexing='ij',
+                                          sparse=True))
+        match = "must be strictly ascending or descending"
+        with pytest.raises(ValueError, match=match):
+            RegularGridInterpolator(points, values)
+
+    @parametrize_rgi_interp_methods
+    def test_fill_value(self, method):
+        interp = RegularGridInterpolator([np.arange(6)], np.ones(6),
+                                         method=method, bounds_error=False)
+        assert np.isnan(interp([10]))
+
+    @pytest.mark.fail_slow(5)
+    @parametrize_rgi_interp_methods
+    def test_nonscalar_values(self, method):
+
+        if method == "quintic":
+            pytest.skip("Way too slow.")
+
+        # Verify that non-scalar valued values also works
+        points = [(0.0, 0.5, 1.0, 1.5, 2.0, 2.5)] * 2 + [
+            (0.0, 5.0, 10.0, 15.0, 20, 25.0)
+        ] * 2
+
+        rng = np.random.default_rng(1234)
+        values = rng.random((6, 6, 6, 6, 8))
+        sample = rng.random((7, 3, 4))
+
+        interp = RegularGridInterpolator(points, values, method=method,
+                                         bounds_error=False)
+        v = interp(sample)
+        assert v.shape == (7, 3, 8), method
+
+        vs = []
+        for j in range(8):
+            interp = RegularGridInterpolator(points, values[..., j],
+                                             method=method,
+                                             bounds_error=False)
+            vs.append(interp(sample))
+        v2 = np.array(vs).transpose(1, 2, 0)
+
+        xp_assert_close(v, v2, atol=1e-14, err_msg=method)
+
+    @parametrize_rgi_interp_methods
+    @pytest.mark.parametrize("flip_points", [False, True])
+    def test_nonscalar_values_2(self, method, flip_points):
+
+        if method in {"cubic", "quintic"}:
+            pytest.skip("Way too slow.")
+
+        # Verify that non-scalar valued values also work : use different
+        # lengths of axes to simplify tracing the internals
+        points = [(0.0, 0.5, 1.0, 1.5, 2.0, 2.5),
+                  (0.0, 0.5, 1.0, 1.5, 2.0, 2.5, 3.0),
+                  (0.0, 5.0, 10.0, 15.0, 20, 25.0, 35.0, 36.0),
+                  (0.0, 5.0, 10.0, 15.0, 20, 25.0, 35.0, 36.0, 47)]
+
+        # verify, that strictly decreasing dimensions work
+        if flip_points:
+            points = [tuple(reversed(p)) for p in points]
+
+        rng = np.random.default_rng(1234)
+
+        trailing_points = (3, 2)
+        # NB: values has a `num_trailing_dims` trailing dimension
+        values = rng.random((6, 7, 8, 9, *trailing_points))
+        sample = rng.random(4)   # a single sample point !
+
+        interp = RegularGridInterpolator(points, values, method=method,
+                                         bounds_error=False)
+        v = interp(sample)
+
+        # v has a single sample point *per entry in the trailing dimensions*
+        assert v.shape == (1, *trailing_points)
+
+        # check the values, too : manually loop over the trailing dimensions
+        vs = np.empty(values.shape[-2:])
+        for i in range(values.shape[-2]):
+            for j in range(values.shape[-1]):
+                interp = RegularGridInterpolator(points, values[..., i, j],
+                                                 method=method,
+                                                 bounds_error=False)
+                vs[i, j] = interp(sample).item()
+        v2 = np.expand_dims(vs, axis=0)
+        xp_assert_close(v, v2, atol=1e-14, err_msg=method)
+
+    def test_nonscalar_values_linear_2D(self):
+        # Verify that non-scalar values work in the 2D fast path
+        method = 'linear'
+        points = [(0.0, 0.5, 1.0, 1.5, 2.0, 2.5),
+                  (0.0, 0.5, 1.0, 1.5, 2.0, 2.5, 3.0), ]
+
+        rng = np.random.default_rng(1234)
+
+        trailing_points = (3, 4)
+        # NB: values has a `num_trailing_dims` trailing dimension
+        values = rng.random((6, 7, *trailing_points))
+        sample = rng.random(2)   # a single sample point !
+
+        interp = RegularGridInterpolator(points, values, method=method,
+                                         bounds_error=False)
+        v = interp(sample)
+
+        # v has a single sample point *per entry in the trailing dimensions*
+        assert v.shape == (1, *trailing_points)
+
+        # check the values, too : manually loop over the trailing dimensions
+        vs = np.empty(values.shape[-2:])
+        for i in range(values.shape[-2]):
+            for j in range(values.shape[-1]):
+                interp = RegularGridInterpolator(points, values[..., i, j],
+                                                 method=method,
+                                                 bounds_error=False)
+                vs[i, j] = interp(sample).item()
+        v2 = np.expand_dims(vs, axis=0)
+        xp_assert_close(v, v2, atol=1e-14, err_msg=method)
+
+    @pytest.mark.parametrize(
+        "dtype",
+        [np.float32, np.float64, np.complex64, np.complex128]
+    )
+    @pytest.mark.parametrize("xi_dtype", [np.float32, np.float64])
+    def test_float32_values(self, dtype, xi_dtype):
+        # regression test for gh-17718: values.dtype=float32 fails
+        def f(x, y):
+            return 2 * x**3 + 3 * y**2
+
+        x = np.linspace(1, 4, 11)
+        y = np.linspace(4, 7, 22)
+
+        xg, yg = np.meshgrid(x, y, indexing='ij', sparse=True)
+        data = f(xg, yg)
+
+        data = data.astype(dtype)
+
+        interp = RegularGridInterpolator((x, y), data)
+
+        pts = np.array([[2.1, 6.2],
+                        [3.3, 5.2]], dtype=xi_dtype)
+
+        # the values here are just what the call returns; the test checks that
+        # that the call succeeds at all, instead of failing with cython not
+        # having a float32 kernel
+        xp_assert_close(interp(pts), [134.10469388, 153.40069388],
+                        atol=1e-7, rtol=1e-7, check_dtype=False)
+
+    def test_bad_solver(self):
+        x = np.linspace(0, 3, 7)
+        y = np.linspace(0, 3, 7)
+        xg, yg = np.meshgrid(x, y, indexing='ij', sparse=True)
+        data = xg + yg
+
+        # default method 'linear' does not accept 'solver'
+        with assert_raises(ValueError):
+            RegularGridInterpolator((x, y), data, solver=lambda x: x)
+
+        with assert_raises(TypeError):
+            # wrong solver interface
+            RegularGridInterpolator(
+                (x, y), data, method='slinear', solver=lambda x: x
+            )
+
+        with assert_raises(TypeError):
+            # unknown argument
+            RegularGridInterpolator(
+                (x, y), data, method='slinear', solver=lambda x: x, woof='woof'
+            )
+
+        with assert_raises(TypeError):
+            # unknown argument
+            RegularGridInterpolator(
+                (x, y), data, method='slinear',  solver_args={'woof': 42}
+            )
+
+    def test_concurrency(self):
+        points, values = self._get_sample_4d(np)
+        sample = np.array([[0.1 , 0.1 , 1.  , 0.9 ],
+                           [0.2 , 0.1 , 0.45, 0.8 ],
+                           [0.5 , 0.5 , 0.5 , 0.5 ],
+                           [0.3 , 0.1 , 0.2 , 0.4 ]])
+        interp = RegularGridInterpolator(points, values, method="slinear")
+
+        # A call to RGI with a method different from the one specified on the
+        # constructor, should not mutate it.
+        methods = ['slinear', 'nearest']
+        def worker_fn(tid, interp):
+            spline = interp._spline
+            method = methods[tid % 2]
+            interp(sample, method=method)
+            assert interp._spline is spline
+
+        _run_concurrent_barrier(10, worker_fn, interp)
+
+
+class MyValue:
+    """
+    Minimal indexable object
+    """
+
+    def __init__(self, shape):
+        self.ndim = 2
+        self.shape = shape
+        self._v = np.arange(np.prod(shape)).reshape(shape)
+
+    def __getitem__(self, idx):
+        return self._v[idx]
+
+    def __array_interface__(self):
+        return None
+
+    def __array__(self, dtype=None, copy=None):
+        raise RuntimeError("No array representation")
+
+
+class TestInterpN:
+    def _sample_2d_data(self):
+        x = np.array([.5, 2., 3., 4., 5.5, 6.])
+        y = np.array([.5, 2., 3., 4., 5.5, 6.])
+        z = np.array(
+            [
+                [1, 2, 1, 2, 1, 1],
+                [1, 2, 1, 2, 1, 1],
+                [1, 2, 3, 2, 1, 1],
+                [1, 2, 2, 2, 1, 1],
+                [1, 2, 1, 2, 1, 1],
+                [1, 2, 2, 2, 1, 1],
+            ]
+        )
+        return x, y, z
+
+    def test_spline_2d(self):
+        x, y, z = self._sample_2d_data()
+        lut = RectBivariateSpline(x, y, z)
+        lut_custom = _regrid(x, y, z)
+
+        xi = np.array([[1, 2.3, 5.3, 0.5, 3.3, 1.2, 3],
+                       [1, 3.3, 1.2, 4.0, 5.0, 1.0, 3]]).T
+        assert_array_almost_equal(interpn((x, y), z, xi, method="splinef2d"),
+                                  lut.ev(xi[:, 0], xi[:, 1]))
+        xp_assert_close(interpn((x, y), z, xi, method="splinef2d"),
+                                  _ndbspline_call_like_bivariate(
+                                      lut_custom, xi[:, 0], xi[:, 1],
+                                      grid=False))
+
+    @parametrize_rgi_interp_methods
+    def test_list_input(self, method):
+        x, y, z = self._sample_2d_data()
+        xi = np.array([[1, 2.3, 5.3, 0.5, 3.3, 1.2, 3],
+                       [1, 3.3, 1.2, 4.0, 5.0, 1.0, 3]]).T
+        v1 = interpn((x, y), z, xi, method=method)
+        v2 = interpn(
+            (x.tolist(), y.tolist()), z.tolist(), xi.tolist(), method=method
+        )
+        xp_assert_close(v1, v2, err_msg=method)
+
+    def test_spline_2d_outofbounds(self):
+        x = np.array([.5, 2., 3., 4., 5.5])
+        y = np.array([.5, 2., 3., 4., 5.5])
+        z = np.array([[1, 2, 1, 2, 1], [1, 2, 1, 2, 1], [1, 2, 3, 2, 1],
+                      [1, 2, 2, 2, 1], [1, 2, 1, 2, 1]])
+        lut = RectBivariateSpline(x, y, z)
+        lut_custom = _regrid(x, y, z)
+
+        xi = np.array([[1, 2.3, 6.3, 0.5, 3.3, 1.2, 3],
+                       [1, 3.3, 1.2, -4.0, 5.0, 1.0, 3]]).T
+        actual = interpn((x, y), z, xi, method="splinef2d",
+                         bounds_error=False, fill_value=999.99)
+        expected = lut.ev(xi[:, 0], xi[:, 1])
+        expected[2:4] = 999.99
+        assert_array_almost_equal(actual, expected)
+
+        expected_custom = _ndbspline_call_like_bivariate(
+            lut_custom, xi[:, 0], xi[:, 1], grid=False)
+        expected_custom[2:4] = 999.99
+        xp_assert_close(actual, expected_custom)
+
+        expected_custom[2:4] = 999.99
+        xp_assert_close(actual, expected_custom)
+
+        # no extrapolation for splinef2d
+        assert_raises(ValueError, interpn, (x, y), z, xi, method="splinef2d",
+                      bounds_error=False, fill_value=None)
+
+    def _sample_4d_data(self):
+        points = [(0., .5, 1.)] * 2 + [(0., 5., 10.)] * 2
+        values = np.asarray([0., .5, 1.])
+        values0 = values[:, np.newaxis, np.newaxis, np.newaxis]
+        values1 = values[np.newaxis, :, np.newaxis, np.newaxis]
+        values2 = values[np.newaxis, np.newaxis, :, np.newaxis]
+        values3 = values[np.newaxis, np.newaxis, np.newaxis, :]
+        values = (values0 + values1 * 10 + values2 * 100 + values3 * 1000)
+        return points, values
+
+    def test_linear_4d(self):
+        # create a 4-D grid of 3 points in each dimension
+        points, values = self._sample_4d_data()
+        interp_rg = RegularGridInterpolator(points, values)
+        sample = np.asarray([[0.1, 0.1, 10., 9.]])
+        wanted = interpn(points, values, sample, method="linear")
+        assert_array_almost_equal(interp_rg(sample), wanted)
+
+    def test_4d_linear_outofbounds(self):
+        # create a 4-D grid of 3 points in each dimension
+        points, values = self._sample_4d_data()
+        sample = np.asarray([[0.1, -0.1, 10.1, 9.]])
+        wanted = np.asarray([999.99])
+        actual = interpn(points, values, sample, method="linear",
+                         bounds_error=False, fill_value=999.99)
+        assert_array_almost_equal(actual, wanted)
+
+    def test_nearest_4d(self):
+        # create a 4-D grid of 3 points in each dimension
+        points, values = self._sample_4d_data()
+        interp_rg = RegularGridInterpolator(points, values, method="nearest")
+        sample = np.asarray([[0.1, 0.1, 10., 9.]])
+        wanted = interpn(points, values, sample, method="nearest")
+        assert_array_almost_equal(interp_rg(sample), wanted)
+
+    def test_4d_nearest_outofbounds(self):
+        # create a 4-D grid of 3 points in each dimension
+        points, values = self._sample_4d_data()
+        sample = np.asarray([[0.1, -0.1, 10.1, 9.]])
+        wanted = np.asarray([999.99])
+        actual = interpn(points, values, sample, method="nearest",
+                         bounds_error=False, fill_value=999.99)
+        assert_array_almost_equal(actual, wanted)
+
+    def test_xi_1d(self):
+        # verify that 1-D xi works as expected
+        points, values = self._sample_4d_data()
+        sample = np.asarray([0.1, 0.1, 10., 9.])
+        v1 = interpn(points, values, sample, bounds_error=False)
+        v2 = interpn(points, values, sample[None,:], bounds_error=False)
+        xp_assert_close(v1, v2)
+
+    def test_xi_nd(self):
+        # verify that higher-d xi works as expected
+        points, values = self._sample_4d_data()
+
+        np.random.seed(1234)
+        sample = np.random.rand(2, 3, 4)
+
+        v1 = interpn(points, values, sample, method='nearest',
+                     bounds_error=False)
+        assert v1.shape == (2, 3)
+
+        v2 = interpn(points, values, sample.reshape(-1, 4),
+                     method='nearest', bounds_error=False)
+        xp_assert_close(v1, v2.reshape(v1.shape))
+
+    @parametrize_rgi_interp_methods
+    def test_xi_broadcast(self, method):
+        # verify that the interpolators broadcast xi
+        x, y, values = self._sample_2d_data()
+        points = (x, y)
+
+        xi = np.linspace(0, 1, 2)
+        yi = np.linspace(0, 3, 3)
+
+        sample = (xi[:, None], yi[None, :])
+        v1 = interpn(points, values, sample, method=method, bounds_error=False)
+        assert v1.shape == (2, 3)
+
+        xx, yy = np.meshgrid(xi, yi)
+        sample = np.c_[xx.T.ravel(), yy.T.ravel()]
+
+        v2 = interpn(points, values, sample,
+                     method=method, bounds_error=False)
+        xp_assert_close(v1, v2.reshape(v1.shape))
+
+    @pytest.mark.fail_slow(5)
+    @parametrize_rgi_interp_methods
+    def test_nonscalar_values(self, method):
+
+        if method == "quintic":
+            pytest.skip("Way too slow.")
+
+        # Verify that non-scalar valued values also works
+        points = [(0.0, 0.5, 1.0, 1.5, 2.0, 2.5)] * 2 + [
+            (0.0, 5.0, 10.0, 15.0, 20, 25.0)
+        ] * 2
+
+        rng = np.random.default_rng(1234)
+        values = rng.random((6, 6, 6, 6, 8))
+        sample = rng.random((7, 3, 4))
+
+        v = interpn(points, values, sample, method=method,
+                    bounds_error=False)
+        assert v.shape == (7, 3, 8), method
+
+        vs = [interpn(points, values[..., j], sample, method=method,
+                      bounds_error=False) for j in range(8)]
+        v2 = np.array(vs).transpose(1, 2, 0)
+
+        xp_assert_close(v, v2, atol=1e-14, err_msg=method)
+
+    @parametrize_rgi_interp_methods
+    def test_nonscalar_values_2(self, method):
+
+        if method in {"cubic", "quintic"}:
+            pytest.skip("Way too slow.")
+
+        # Verify that non-scalar valued values also work : use different
+        # lengths of axes to simplify tracing the internals
+        points = [(0.0, 0.5, 1.0, 1.5, 2.0, 2.5),
+                  (0.0, 0.5, 1.0, 1.5, 2.0, 2.5, 3.0),
+                  (0.0, 5.0, 10.0, 15.0, 20, 25.0, 35.0, 36.0),
+                  (0.0, 5.0, 10.0, 15.0, 20, 25.0, 35.0, 36.0, 47)]
+
+        rng = np.random.default_rng(1234)
+
+        trailing_points = (3, 2)
+        # NB: values has a `num_trailing_dims` trailing dimension
+        values = rng.random((6, 7, 8, 9, *trailing_points))
+        sample = rng.random(4)   # a single sample point !
+
+        v = interpn(points, values, sample, method=method, bounds_error=False)
+
+        # v has a single sample point *per entry in the trailing dimensions*
+        assert v.shape == (1, *trailing_points)
+
+        # check the values, too : manually loop over the trailing dimensions
+        vs = [[
+                interpn(points, values[..., i, j], sample, method=method,
+                        bounds_error=False) for i in range(values.shape[-2])
+              ] for j in range(values.shape[-1])]
+
+        xp_assert_close(v, np.asarray(vs).T, atol=1e-14, err_msg=method)
+
+    def test_non_scalar_values_splinef2d(self):
+        # Vector-valued splines supported with fitpack
+        points, values = self._sample_4d_data()
+
+        np.random.seed(1234)
+        values = np.random.rand(3, 3, 3, 3, 6)
+        sample = np.random.rand(7, 11, 4)
+        assert_raises(ValueError, interpn, points, values, sample,
+                      method='splinef2d')
+
+    @parametrize_rgi_interp_methods
+    def test_complex(self, method):
+        if method == "pchip":
+            pytest.skip("pchip does not make sense for complex data")
+
+        x, y, values = self._sample_2d_data()
+        points = (x, y)
+        values = values - 2j*values
+
+        sample = np.array([[1, 2.3, 5.3, 0.5, 3.3, 1.2, 3],
+                           [1, 3.3, 1.2, 4.0, 5.0, 1.0, 3]]).T
+
+        v1 = interpn(points, values, sample, method=method)
+        v2r = interpn(points, values.real, sample, method=method)
+        v2i = interpn(points, values.imag, sample, method=method)
+        v2 = v2r + 1j*v2i
+
+        xp_assert_close(v1, v2)
+
+    def test_complex_pchip(self):
+        # Complex-valued data deprecated for pchip
+        x, y, values = self._sample_2d_data()
+        points = (x, y)
+        values = values - 2j*values
+
+        sample = np.array([[1, 2.3, 5.3, 0.5, 3.3, 1.2, 3],
+                           [1, 3.3, 1.2, 4.0, 5.0, 1.0, 3]]).T
+        with pytest.raises(ValueError, match='real'):
+            interpn(points, values, sample, method='pchip')
+
+    def test_complex_spline2fd(self):
+        # Complex-valued data not supported by spline2fd
+        x, y, values = self._sample_2d_data()
+        points = (x, y)
+        values = values - 2j*values
+
+        sample = np.array([[1, 2.3, 5.3, 0.5, 3.3, 1.2, 3],
+                           [1, 3.3, 1.2, 4.0, 5.0, 1.0, 3]]).T
+        with pytest.warns(ComplexWarning):
+            interpn(points, values, sample, method='splinef2d')
+
+    @pytest.mark.parametrize(
+        "method",
+        ["linear", "nearest"]
+    )
+    def test_duck_typed_values(self, method):
+        x = np.linspace(0, 2, 5)
+        y = np.linspace(0, 1, 7)
+
+        values = MyValue((5, 7))
+
+        v1 = interpn((x, y), values, [0.4, 0.7], method=method)
+        v2 = interpn((x, y), values._v, [0.4, 0.7], method=method)
+        xp_assert_close(v1, v2, check_dtype=False)
+
+    @skip_xp_invalid_arg
+    @parametrize_rgi_interp_methods
+    def test_matrix_input(self, method):
+        """np.matrix inputs are allowed for backwards compatibility"""
+        x = np.linspace(0, 2, 6)
+        y = np.linspace(0, 1, 7)
+
+        values = matrix(np.random.rand(6, 7))
+
+        sample = np.random.rand(3, 7, 2)
+
+        v1 = interpn((x, y), values, sample, method=method)
+        v2 = interpn((x, y), np.asarray(values), sample, method=method)
+        if method == "quintic":
+            # https://github.com/scipy/scipy/issues/20472
+            xp_assert_close(v1, v2, atol=5e-5, rtol=2e-6)
+        else:
+            xp_assert_close(v1, v2)
+
+    def test_length_one_axis(self):
+        # gh-5890, gh-9524 : length-1 axis is legal for method='linear'.
+        # Along the axis it's linear interpolation; away from the length-1
+        # axis, it's an extrapolation, so fill_value should be used.
+
+        values = np.array([[0.1, 1, 10]])
+        xi = np.array([[1, 2.2], [1, 3.2], [1, 3.8]])
+
+        res = interpn(([1], [2, 3, 4]), values, xi)
+        wanted = [0.9*0.2 + 0.1,   # on [2, 3) it's 0.9*(x-2) + 0.1
+                  9*0.2 + 1,       # on [3, 4] it's 9*(x-3) + 1
+                  9*0.8 + 1]
+
+        xp_assert_close(res, wanted, atol=1e-15)
+
+        # check extrapolation
+        xi = np.array([[1.1, 2.2], [1.5, 3.2], [-2.3, 3.8]])
+        res = interpn(([1], [2, 3, 4]), values, xi,
+                      bounds_error=False, fill_value=None)
+
+        xp_assert_close(res, wanted, atol=1e-15)
+
+    def test_descending_points(self):
+        def value_func_4d(x, y, z, a):
+            return 2 * x ** 3 + 3 * y ** 2 - z - a
+
+        x1 = np.array([0, 1, 2, 3])
+        x2 = np.array([0, 10, 20, 30])
+        x3 = np.array([0, 10, 20, 30])
+        x4 = np.array([0, .1, .2, .30])
+        points = (x1, x2, x3, x4)
+        values = value_func_4d(
+            *np.meshgrid(*points, indexing='ij', sparse=True))
+        pts = (0.1, 0.3, np.transpose(np.linspace(0, 30, 4)),
+               np.linspace(0, 0.3, 4))
+        correct_result = interpn(points, values, pts)
+
+        x1_descend = x1[::-1]
+        x2_descend = x2[::-1]
+        x3_descend = x3[::-1]
+        x4_descend = x4[::-1]
+        points_shuffled = (x1_descend, x2_descend, x3_descend, x4_descend)
+        values_shuffled = value_func_4d(
+            *np.meshgrid(*points_shuffled, indexing='ij', sparse=True))
+        test_result = interpn(points_shuffled, values_shuffled, pts)
+
+        xp_assert_equal(correct_result, test_result)
+
+    def test_invalid_points_order(self):
+        x = np.array([.5, 2., 0., 4., 5.5])  # not ascending or descending
+        y = np.array([.5, 2., 3., 4., 5.5])
+        z = np.array([[1, 2, 1, 2, 1], [1, 2, 1, 2, 1], [1, 2, 3, 2, 1],
+                      [1, 2, 2, 2, 1], [1, 2, 1, 2, 1]])
+        xi = np.array([[1, 2.3, 6.3, 0.5, 3.3, 1.2, 3],
+                       [1, 3.3, 1.2, -4.0, 5.0, 1.0, 3]]).T
+
+        match = "must be strictly ascending or descending"
+        with pytest.raises(ValueError, match=match):
+            interpn((x, y), z, xi)
+
+    def test_invalid_xi_dimensions(self):
+        # https://github.com/scipy/scipy/issues/16519
+        points = [(0, 1)]
+        values = [0, 1]
+        xi = np.ones((1, 1, 3))
+        msg = ("The requested sample points xi have dimension 3, but this "
+               "RegularGridInterpolator has dimension 1")
+        with assert_raises(ValueError, match=msg):
+            interpn(points, values, xi)
+
+    def test_readonly_grid(self):
+        # https://github.com/scipy/scipy/issues/17716
+        x = np.linspace(0, 4, 5)
+        y = np.linspace(0, 5, 6)
+        z = np.linspace(0, 6, 7)
+        points = (x, y, z)
+        values = np.ones((5, 6, 7))
+        point = np.array([2.21, 3.12, 1.15])
+        for d in points:
+            d.flags.writeable = False
+        values.flags.writeable = False
+        point.flags.writeable = False
+        interpn(points, values, point)
+        RegularGridInterpolator(points, values)(point)
+
+    def test_2d_readonly_grid(self):
+        # https://github.com/scipy/scipy/issues/17716
+        # test special 2d case
+        x = np.linspace(0, 4, 5)
+        y = np.linspace(0, 5, 6)
+        points = (x, y)
+        values = np.ones((5, 6))
+        point = np.array([2.21, 3.12])
+        for d in points:
+            d.flags.writeable = False
+        values.flags.writeable = False
+        point.flags.writeable = False
+        interpn(points, values, point)
+        RegularGridInterpolator(points, values)(point)
+
+    def test_non_c_contiguous_grid(self):
+        # https://github.com/scipy/scipy/issues/17716
+        x = np.linspace(0, 4, 5)
+        x = np.vstack((x, np.empty_like(x))).T.copy()[:, 0]
+        assert not x.flags.c_contiguous
+        y = np.linspace(0, 5, 6)
+        z = np.linspace(0, 6, 7)
+        points = (x, y, z)
+        values = np.ones((5, 6, 7))
+        point = np.array([2.21, 3.12, 1.15])
+        interpn(points, values, point)
+        RegularGridInterpolator(points, values)(point)
+
+    @pytest.mark.parametrize("dtype", ['>f8', '`__
+
+MATLAB® files
+=============
+
+.. autosummary::
+   :toctree: generated/
+
+   loadmat - Read a MATLAB style mat file (version 4 through 7.1)
+   savemat - Write a MATLAB style mat file (version 4 through 7.1)
+   whosmat - List contents of a MATLAB style mat file (version 4 through 7.1)
+
+For low-level MATLAB reading and writing utilities, see `scipy.io.matlab`.
+
+IDL® files
+==========
+
+.. autosummary::
+   :toctree: generated/
+
+   readsav - Read an IDL 'save' file
+
+Matrix Market files
+===================
+
+.. autosummary::
+   :toctree: generated/
+
+   mminfo - Query matrix info from Matrix Market formatted file
+   mmread - Read matrix from Matrix Market formatted file
+   mmwrite - Write matrix to Matrix Market formatted file
+
+Unformatted Fortran files
+===============================
+
+.. autosummary::
+   :toctree: generated/
+
+   FortranFile - A file object for unformatted sequential Fortran files
+   FortranEOFError - Exception indicating the end of a well-formed file
+   FortranFormattingError - Exception indicating an inappropriate end
+
+Netcdf
+======
+
+.. autosummary::
+   :toctree: generated/
+
+   netcdf_file - A file object for NetCDF data
+   netcdf_variable - A data object for the netcdf module
+
+Harwell-Boeing files
+====================
+
+.. autosummary::
+   :toctree: generated/
+
+   hb_read   -- read H-B file
+   hb_write  -- write H-B file
+
+Wav sound files (:mod:`scipy.io.wavfile`)
+=========================================
+
+.. module:: scipy.io.wavfile
+
+.. autosummary::
+   :toctree: generated/
+
+   read
+   write
+   WavFileWarning
+
+Arff files (:mod:`scipy.io.arff`)
+=================================
+
+.. module:: scipy.io.arff
+
+.. autosummary::
+   :toctree: generated/
+
+   loadarff
+   MetaData
+   ArffError
+   ParseArffError
+"""
+# matfile read and write
+from .matlab import loadmat, savemat, whosmat
+
+# netCDF file support
+from ._netcdf import netcdf_file, netcdf_variable
+
+# Fortran file support
+from ._fortran import FortranFile, FortranEOFError, FortranFormattingError
+
+from ._fast_matrix_market import mminfo, mmread, mmwrite
+from ._idl import readsav
+from ._harwell_boeing import hb_read, hb_write
+
+# Deprecated namespaces, to be removed in v2.0.0
+from . import arff, harwell_boeing, idl, mmio, netcdf, wavfile
+
+__all__ = [s for s in dir() if not s.startswith('_')]
+
+from scipy._lib._testutils import PytestTester
+test = PytestTester(__name__)
+del PytestTester
diff --git a/.venv/lib/python3.12/site-packages/scipy/io/_fast_matrix_market/__init__.py b/.venv/lib/python3.12/site-packages/scipy/io/_fast_matrix_market/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..10d67d41f1eb9433ec3e658922d7dfaa36ecb8f1
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/io/_fast_matrix_market/__init__.py
@@ -0,0 +1,619 @@
+# Copyright (C) 2022-2023 Adam Lugowski. All rights reserved.
+# Use of this source code is governed by the BSD 2-clause license found in
+# the LICENSE.txt file.
+# SPDX-License-Identifier: BSD-2-Clause
+"""
+Matrix Market I/O with a C++ backend.
+See http://math.nist.gov/MatrixMarket/formats.html
+for information about the Matrix Market format.
+
+.. versionadded:: 1.12.0
+"""
+import io
+import os
+
+from warnings import warn
+
+import numpy as np
+from scipy.sparse import coo_array, issparse, coo_matrix
+from scipy.io import _mmio
+from scipy._lib.deprecation import _NoValue
+
+__all__ = ['mminfo', 'mmread', 'mmwrite']
+
+PARALLELISM = 0
+"""
+Number of threads that `mmread()` and `mmwrite()` use.
+0 means number of CPUs in the system.
+Use `threadpoolctl` to set this value.
+"""
+
+ALWAYS_FIND_SYMMETRY = False
+"""
+Whether mmwrite() with symmetry='AUTO' will always search for symmetry
+inside the matrix. This is scipy.io._mmio.mmwrite()'s default behavior,
+but has a significant performance cost on large matrices.
+"""
+
+_field_to_dtype = {
+    "integer": "int64",
+    "unsigned-integer": "uint64",
+    "real": "float64",
+    "complex": "complex",
+    "pattern": "float64",
+}
+
+
+def _fmm_version():
+    from . import _fmm_core
+    return _fmm_core.__version__
+
+
+# Register with threadpoolctl, if available
+try:
+    import threadpoolctl
+
+    class _FMMThreadPoolCtlController(threadpoolctl.LibController):
+        user_api = "scipy"
+        internal_api = "scipy_mmio"
+
+        filename_prefixes = ("_fmm_core",)
+
+        def get_num_threads(self):
+            global PARALLELISM
+            return PARALLELISM
+
+        def set_num_threads(self, num_threads):
+            global PARALLELISM
+            PARALLELISM = num_threads
+
+        def get_version(self):
+            return _fmm_version()
+
+        def set_additional_attributes(self):
+            pass
+
+    threadpoolctl.register(_FMMThreadPoolCtlController)
+except (ImportError, AttributeError):
+    # threadpoolctl not installed or version too old
+    pass
+
+
+class _TextToBytesWrapper(io.BufferedReader):
+    """
+    Convert a TextIOBase string stream to a byte stream.
+    """
+
+    def __init__(self, text_io_buffer, encoding=None, errors=None, **kwargs):
+        super().__init__(text_io_buffer, **kwargs)
+        self.encoding = encoding or text_io_buffer.encoding or 'utf-8'
+        self.errors = errors or text_io_buffer.errors or 'strict'
+
+    def __del__(self):
+        # do not close the wrapped stream
+        self.detach()
+
+    def _encoding_call(self, method_name, *args, **kwargs):
+        raw_method = getattr(self.raw, method_name)
+        val = raw_method(*args, **kwargs)
+        return val.encode(self.encoding, errors=self.errors)
+
+    def read(self, size=-1):
+        return self._encoding_call('read', size)
+
+    def read1(self, size=-1):
+        return self._encoding_call('read1', size)
+
+    def peek(self, size=-1):
+        return self._encoding_call('peek', size)
+
+    def seek(self, offset, whence=0):
+        # Random seeks are not allowed because of non-trivial conversion
+        # between byte and character offsets,
+        # with the possibility of a byte offset landing within a character.
+        if offset == 0 and whence == 0 or \
+           offset == 0 and whence == 2:
+            # seek to start or end is ok
+            super().seek(offset, whence)
+        else:
+            # Drop any other seek
+            # In this application this may happen when pystreambuf seeks during sync(),
+            # which can happen when closing a partially-read stream.
+            # Ex. when mminfo() only reads the header then exits.
+            pass
+
+
+def _read_body_array(cursor):
+    """
+    Read MatrixMarket array body
+    """
+    from . import _fmm_core
+
+    vals = np.zeros(cursor.header.shape, dtype=_field_to_dtype.get(cursor.header.field))
+    _fmm_core.read_body_array(cursor, vals)
+    return vals
+
+
+def _read_body_coo(cursor, generalize_symmetry=True):
+    """
+    Read MatrixMarket coordinate body
+    """
+    from . import _fmm_core
+
+    index_dtype = "int32"
+    if cursor.header.nrows >= 2**31 or cursor.header.ncols >= 2**31:
+        # Dimensions are too large to fit in int32
+        index_dtype = "int64"
+
+    i = np.zeros(cursor.header.nnz, dtype=index_dtype)
+    j = np.zeros(cursor.header.nnz, dtype=index_dtype)
+    data = np.zeros(cursor.header.nnz, dtype=_field_to_dtype.get(cursor.header.field))
+
+    _fmm_core.read_body_coo(cursor, i, j, data)
+
+    if generalize_symmetry and cursor.header.symmetry != "general":
+        off_diagonal_mask = (i != j)
+        off_diagonal_rows = i[off_diagonal_mask]
+        off_diagonal_cols = j[off_diagonal_mask]
+        off_diagonal_data = data[off_diagonal_mask]
+
+        if cursor.header.symmetry == "skew-symmetric":
+            off_diagonal_data *= -1
+        elif cursor.header.symmetry == "hermitian":
+            off_diagonal_data = off_diagonal_data.conjugate()
+
+        i = np.concatenate((i, off_diagonal_cols))
+        j = np.concatenate((j, off_diagonal_rows))
+        data = np.concatenate((data, off_diagonal_data))
+
+    return (data, (i, j)), cursor.header.shape
+
+
+def _get_read_cursor(source, parallelism=None):
+    """
+    Open file for reading.
+    """
+    from . import _fmm_core
+
+    ret_stream_to_close = None
+    if parallelism is None:
+        parallelism = PARALLELISM
+
+    try:
+        source = os.fspath(source)
+        # It's a file path
+        is_path = True
+    except TypeError:
+        is_path = False
+
+    if is_path:
+        path = str(source)
+        if path.endswith('.gz'):
+            import gzip
+            source = gzip.GzipFile(path, 'r')
+            ret_stream_to_close = source
+        elif path.endswith('.bz2'):
+            import bz2
+            source = bz2.BZ2File(path, 'rb')
+            ret_stream_to_close = source
+        else:
+            if not os.path.exists(path):
+                raise FileNotFoundError(f"The source file does not exist: {path}")
+            return _fmm_core.open_read_file(path, parallelism), ret_stream_to_close
+
+    # Stream object.
+    if hasattr(source, "read"):
+        if isinstance(source, io.TextIOBase):
+            source = _TextToBytesWrapper(source)
+        return _fmm_core.open_read_stream(source, parallelism), ret_stream_to_close
+    else:
+        raise TypeError("Unknown source type")
+
+
+def _get_write_cursor(target, h=None, comment=None, parallelism=None,
+                      symmetry="general", precision=None):
+    """
+    Open file for writing.
+    """
+    from . import _fmm_core
+
+    if parallelism is None:
+        parallelism = PARALLELISM
+    if comment is None:
+        comment = ''
+    if symmetry is None:
+        symmetry = "general"
+    if precision is None:
+        precision = -1
+
+    if not h:
+        h = _fmm_core.header(comment=comment, symmetry=symmetry)
+
+    try:
+        target = os.fspath(target)
+        # It's a file path
+        if target[-4:] != '.mtx':
+            target += '.mtx'
+        return _fmm_core.open_write_file(str(target), h, parallelism, precision)
+    except TypeError:
+        pass
+
+    if hasattr(target, "write"):
+        # Stream object.
+        if isinstance(target, io.TextIOBase):
+            raise TypeError("target stream must be open in binary mode.")
+        return _fmm_core.open_write_stream(target, h, parallelism, precision)
+    else:
+        raise TypeError("Unknown source object")
+
+
+def _apply_field(data, field, no_pattern=False):
+    """
+    Ensure that ``data.dtype`` is compatible with the specified MatrixMarket field type.
+
+    Parameters
+    ----------
+    data : ndarray
+        Input array.
+
+    field : str
+        Matrix Market field, such as 'real', 'complex', 'integer', 'pattern'.
+
+    no_pattern : bool, optional
+        Whether an empty array may be returned for a 'pattern' field.
+
+    Returns
+    -------
+    data : ndarray
+        Input data if no conversion necessary, or a converted version
+    """
+
+    if field is None:
+        return data
+    if field == "pattern":
+        if no_pattern:
+            return data
+        else:
+            return np.zeros(0)
+
+    dtype = _field_to_dtype.get(field, None)
+    if dtype is None:
+        raise ValueError("Invalid field.")
+
+    return np.asarray(data, dtype=dtype)
+
+
+def _validate_symmetry(symmetry):
+    """
+    Check that the symmetry parameter is one that MatrixMarket allows..
+    """
+    if symmetry is None:
+        return "general"
+
+    symmetry = str(symmetry).lower()
+    symmetries = ["general", "symmetric", "skew-symmetric", "hermitian"]
+    if symmetry not in symmetries:
+        raise ValueError("Invalid symmetry. Must be one of: " + ", ".join(symmetries))
+
+    return symmetry
+
+
+def mmread(source, *, spmatrix=_NoValue):
+    """
+    Reads the contents of a Matrix Market file-like 'source' into a matrix.
+
+    Parameters
+    ----------
+    source : str or file-like
+        Matrix Market filename (extensions .mtx, .mtz.gz)
+        or open file-like object.
+    spmatrix : bool, optional (default: True)
+        If ``True``, return sparse matrix. Otherwise return sparse array.
+
+        .. deprecated:: 1.18.0
+            The default value for `spmatrix` is changing to False in v1.20.
+            That means the default return value will be a sparse array.
+            Unless you use * instead of @, ** for matrix power, or you depend
+            on 2D shapes from e.g. ``A.sum(axis=0)`` it may not matter to you.
+            See :ref:`Migration from spmatrix to sparray `.
+
+    Returns
+    -------
+    a : ndarray or coo_array
+        Dense or sparse array depending on the matrix format in the
+        Matrix Market file.
+
+    Notes
+    -----
+    .. versionchanged:: 1.12.0
+        C++ implementation.
+
+    Examples
+    --------
+    >>> from io import StringIO
+    >>> from scipy.io import mmread
+
+    >>> text = '''%%MatrixMarket matrix coordinate real general
+    ...  5 5 7
+    ...  2 3 1.0
+    ...  3 4 2.0
+    ...  3 5 3.0
+    ...  4 1 4.0
+    ...  4 2 5.0
+    ...  4 3 6.0
+    ...  4 4 7.0
+    ... '''
+
+    ``mmread(source)`` returns the data as sparse array in COO format.
+
+    >>> m = mmread(StringIO(text), spmatrix=False)
+    >>> m
+    
+    >>> m.toarray()
+    array([[0., 0., 0., 0., 0.],
+           [0., 0., 1., 0., 0.],
+           [0., 0., 0., 2., 3.],
+           [4., 5., 6., 7., 0.],
+           [0., 0., 0., 0., 0.]])
+
+    This method is threaded.
+    The default number of threads is equal to the number of CPUs in the system.
+    Use `threadpoolctl `_ to override:
+
+    >>> import threadpoolctl
+    >>>
+    >>> with threadpoolctl.threadpool_limits(limits=2):
+    ...     m = mmread(StringIO(text), spmatrix=False)
+
+    """
+    cursor, stream_to_close = _get_read_cursor(source)
+
+    if cursor.header.format == "array":
+        mat = _read_body_array(cursor)
+        if stream_to_close:
+            stream_to_close.close()
+        return mat
+    else:
+        triplet, shape = _read_body_coo(cursor, generalize_symmetry=True)
+        if stream_to_close:
+            stream_to_close.close()
+
+        if spmatrix is _NoValue:
+            msg = """The default value for `spmatrix` is changing to `False` in v1.20.
+             That means the default return type will be a sparse array.
+             Unless you use * instead of @, ** for matrix power, or you depend
+             on 2D shapes from e.g. `A.sum(axis=0)` it may not matter to you.
+             See the spmatrix to sparray migration guide for details.
+             https://docs.scipy.org/doc/scipy/reference/sparse.migration_to_sparray.html
+             """
+            prefixes = (os.path.dirname(__file__),)
+            warn(msg, DeprecationWarning, skip_file_prefixes=prefixes)
+            spmatrix = True
+
+        if spmatrix:
+            return coo_matrix(triplet, shape=shape)
+        return coo_array(triplet, shape=shape)
+
+
+def mmwrite(target, a, comment=None, field=None, precision=None, symmetry="AUTO"):
+    r"""
+    Writes the sparse or dense array `a` to Matrix Market file-like `target`.
+
+    Parameters
+    ----------
+    target : str or file-like
+        Matrix Market filename (extension .mtx) or open file-like object.
+    a : array like
+        Sparse or dense 2-D array.
+    comment : str, optional
+        Comments to be prepended to the Matrix Market file.
+    field : None or str, optional
+        Either 'real', 'complex', 'pattern', or 'integer'.
+    precision : None or int, optional
+        Number of digits to display for real or complex values.
+    symmetry : None or str, optional
+        Either 'AUTO', 'general', 'symmetric', 'skew-symmetric', or 'hermitian'.
+        If symmetry is None the symmetry type of 'a' is determined by its
+        values. If symmetry is 'AUTO' the symmetry type of 'a' is either
+        determined or set to 'general', at mmwrite's discretion.
+
+    Notes
+    -----
+    .. versionchanged:: 1.12.0
+        C++ implementation.
+
+    Examples
+    --------
+    >>> from io import BytesIO
+    >>> import numpy as np
+    >>> from scipy.sparse import coo_array
+    >>> from scipy.io import mmwrite
+
+    Write a small NumPy array to a matrix market file.  The file will be
+    written in the ``'array'`` format.
+
+    >>> a = np.array([[1.0, 0, 0, 0], [0, 2.5, 0, 6.25]])
+    >>> target = BytesIO()
+    >>> mmwrite(target, a)
+    >>> print(target.getvalue().decode('latin1'))
+    %%MatrixMarket matrix array real general
+    %
+    2 4
+    1
+    0
+    0
+    2.5
+    0
+    0
+    0
+    6.25
+
+    Add a comment to the output file, and set the precision to 3.
+
+    >>> target = BytesIO()
+    >>> mmwrite(target, a, comment='\n Some test data.\n', precision=3)
+    >>> print(target.getvalue().decode('latin1'))
+    %%MatrixMarket matrix array real general
+    %
+    % Some test data.
+    %
+    2 4
+    1.00e+00
+    0.00e+00
+    0.00e+00
+    2.50e+00
+    0.00e+00
+    0.00e+00
+    0.00e+00
+    6.25e+00
+
+    Convert to a sparse matrix before calling ``mmwrite``.  This will
+    result in the output format being ``'coordinate'`` rather than
+    ``'array'``.
+
+    >>> target = BytesIO()
+    >>> mmwrite(target, coo_array(a), precision=3)
+    >>> print(target.getvalue().decode('latin1'))
+    %%MatrixMarket matrix coordinate real general
+    %
+    2 4 3
+    1 1 1.00e+00
+    2 2 2.50e+00
+    2 4 6.25e+00
+
+    Write a complex Hermitian array to a matrix market file.  Note that
+    only six values are actually written to the file; the other values
+    are implied by the symmetry.
+
+    >>> z = np.array([[3, 1+2j, 4-3j], [1-2j, 1, -5j], [4+3j, 5j, 2.5]])
+    >>> z
+    array([[ 3. +0.j,  1. +2.j,  4. -3.j],
+           [ 1. -2.j,  1. +0.j, -0. -5.j],
+           [ 4. +3.j,  0. +5.j,  2.5+0.j]])
+
+    >>> target = BytesIO()
+    >>> mmwrite(target, z, precision=2)
+    >>> print(target.getvalue().decode('latin1'))
+    %%MatrixMarket matrix array complex hermitian
+    %
+    3 3
+    3.0e+00 0.0e+00
+    1.0e+00 -2.0e+00
+    4.0e+00 3.0e+00
+    1.0e+00 0.0e+00
+    0.0e+00 5.0e+00
+    2.5e+00 0.0e+00
+
+    This method is threaded.
+    The default number of threads is equal to the number of CPUs in the system.
+    Use `threadpoolctl `_ to override:
+
+    >>> import threadpoolctl
+    >>>
+    >>> target = BytesIO()
+    >>> with threadpoolctl.threadpool_limits(limits=2):
+    ...     mmwrite(target, a)
+
+    """
+    from . import _fmm_core
+
+    if isinstance(a, list) or isinstance(a, tuple) or hasattr(a, "__array__"):
+        a = np.asarray(a)
+
+    if symmetry == "AUTO":
+        if ALWAYS_FIND_SYMMETRY or (hasattr(a, "shape") and max(a.shape) < 100):
+            symmetry = None
+        else:
+            symmetry = "general"
+
+    if symmetry is None:
+        symmetry = _mmio.MMFile()._get_symmetry(a)
+
+    symmetry = _validate_symmetry(symmetry)
+    cursor = _get_write_cursor(target, comment=comment,
+                               precision=precision, symmetry=symmetry)
+
+    if isinstance(a, np.ndarray):
+        # Write dense numpy arrays
+        a = _apply_field(a, field, no_pattern=True)
+        _fmm_core.write_body_array(cursor, a)
+
+    elif issparse(a):
+        # Write sparse scipy matrices
+        a = a.tocoo()
+
+        if symmetry is not None and symmetry != "general":
+            # A symmetric matrix only specifies the elements below the diagonal.
+            # Ensure that the matrix satisfies this requirement.
+            lower_triangle_mask = a.row >= a.col
+            a = coo_array((a.data[lower_triangle_mask],
+                              (a.row[lower_triangle_mask],
+                               a.col[lower_triangle_mask])), shape=a.shape)
+
+        data = _apply_field(a.data, field)
+        _fmm_core.write_body_coo(cursor, a.shape, a.row, a.col, data)
+
+    else:
+        raise ValueError(f"unknown matrix type: {type(a)}")
+
+
+def mminfo(source):
+    """
+    Return size and storage parameters from Matrix Market file-like 'source'.
+
+    Parameters
+    ----------
+    source : str or file-like
+        Matrix Market filename (extension .mtx) or open file-like object
+
+    Returns
+    -------
+    rows : int
+        Number of matrix rows.
+    cols : int
+        Number of matrix columns.
+    entries : int
+        Number of non-zero entries of a sparse matrix
+        or rows*cols for a dense matrix.
+    format : str
+        Either 'coordinate' or 'array'.
+    field : str
+        Either 'real', 'complex', 'pattern', or 'integer'.
+    symmetry : str
+        Either 'general', 'symmetric', 'skew-symmetric', or 'hermitian'.
+
+    Notes
+    -----
+    .. versionchanged:: 1.12.0
+        C++ implementation.
+
+    Examples
+    --------
+    >>> from io import StringIO
+    >>> from scipy.io import mminfo
+
+    >>> text = '''%%MatrixMarket matrix coordinate real general
+    ...  5 5 7
+    ...  2 3 1.0
+    ...  3 4 2.0
+    ...  3 5 3.0
+    ...  4 1 4.0
+    ...  4 2 5.0
+    ...  4 3 6.0
+    ...  4 4 7.0
+    ... '''
+
+
+    ``mminfo(source)`` returns the number of rows, number of columns,
+    format, field type and symmetry attribute of the source file.
+
+    >>> mminfo(StringIO(text))
+    (5, 5, 7, 'coordinate', 'real', 'general')
+    """
+    cursor, stream_to_close = _get_read_cursor(source, 1)
+    h = cursor.header
+    cursor.close()
+    if stream_to_close:
+        stream_to_close.close()
+    return h.nrows, h.ncols, h.nnz, h.format, h.field, h.symmetry
diff --git a/.venv/lib/python3.12/site-packages/scipy/io/_fast_matrix_market/_fmm_core.cpython-312-x86_64-linux-gnu.so b/.venv/lib/python3.12/site-packages/scipy/io/_fast_matrix_market/_fmm_core.cpython-312-x86_64-linux-gnu.so
new file mode 100644
index 0000000000000000000000000000000000000000..0b82cc7df8c226defeea7a4264bdcd199ad88e03
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/io/_fast_matrix_market/_fmm_core.cpython-312-x86_64-linux-gnu.so
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:120a09a04f988fcf2ba5d67dc27c60b24cd7ea5b8847915d5944eba05f5e22a3
+size 4098088
diff --git a/.venv/lib/python3.12/site-packages/scipy/io/_fortran.py b/.venv/lib/python3.12/site-packages/scipy/io/_fortran.py
new file mode 100644
index 0000000000000000000000000000000000000000..1432797bc1ad8fbd5bccc2f8ecdf8deeb144ac7e
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/io/_fortran.py
@@ -0,0 +1,353 @@
+"""
+Module to read / write Fortran unformatted sequential files.
+
+This is in the spirit of code written by Neil Martinsen-Burrell and Joe Zuntz.
+
+"""
+import warnings
+import numpy as np
+
+__all__ = ['FortranFile', 'FortranEOFError', 'FortranFormattingError']
+
+
+class FortranEOFError(TypeError, OSError):
+    """Indicates that the file ended properly.
+
+    This error descends from TypeError because the code used to raise
+    TypeError (and this was the only way to know that the file had
+    ended) so users might have ``except TypeError:``.
+
+    """
+    pass
+
+
+class FortranFormattingError(TypeError, OSError):
+    """Indicates that the file ended mid-record.
+
+    Descends from TypeError for backward compatibility.
+
+    """
+    pass
+
+
+class FortranFile:
+    """
+    A file object for unformatted sequential files from Fortran code.
+
+    Parameters
+    ----------
+    filename : file or str
+        Open file object or filename.
+    mode : {'r', 'w'}, optional
+        Read-write mode, default is 'r'.
+    header_dtype : dtype, optional
+        Data type of the header. Size and endianness must match the input/output file.
+
+    Notes
+    -----
+    These files are broken up into records of unspecified types. The size of
+    each record is given at the start (although the size of this header is not
+    standard) and the data is written onto disk without any formatting. Fortran
+    compilers supporting the BACKSPACE statement will write a second copy of
+    the size to facilitate backwards seeking.
+
+    This class only supports files written with both sizes for the record.
+    It also does not support the subrecords used in Intel and gfortran compilers
+    for records which are greater than 2GB with a 4-byte header.
+
+    An example of an unformatted sequential file in Fortran would be written as::
+
+        OPEN(1, FILE=myfilename, FORM='unformatted')
+
+        WRITE(1) myvariable
+
+    Since this is a non-standard file format, whose contents depend on the
+    compiler and the endianness of the machine, caution is advised. Files from
+    gfortran 4.8.0 and gfortran 4.1.2 on x86_64 are known to work.
+
+    Consider using Fortran direct-access files or files from the newer Stream
+    I/O, which can be easily read by `numpy.fromfile`.
+
+    Examples
+    --------
+    To create an unformatted sequential Fortran file:
+
+    >>> from scipy.io import FortranFile
+    >>> import numpy as np
+    >>> f = FortranFile('test.unf', 'w')
+    >>> f.write_record(np.array([1,2,3,4,5], dtype=np.int32))
+    >>> f.write_record(np.linspace(0,1,20).reshape((5,4)).T)
+    >>> f.close()
+
+    To read this file:
+
+    >>> f = FortranFile('test.unf', 'r')
+    >>> print(f.read_ints(np.int32))
+    [1 2 3 4 5]
+    >>> print(f.read_reals(float).reshape((5,4), order="F"))
+    [[0.         0.05263158 0.10526316 0.15789474]
+     [0.21052632 0.26315789 0.31578947 0.36842105]
+     [0.42105263 0.47368421 0.52631579 0.57894737]
+     [0.63157895 0.68421053 0.73684211 0.78947368]
+     [0.84210526 0.89473684 0.94736842 1.        ]]
+    >>> f.close()
+
+    Or, in Fortran::
+
+        integer :: a(5), i
+        double precision :: b(5,4)
+        open(1, file='test.unf', form='unformatted')
+        read(1) a
+        read(1) b
+        close(1)
+        write(*,*) a
+        do i = 1, 5
+            write(*,*) b(i,:)
+        end do
+
+    """
+    def __init__(self, filename, mode='r', header_dtype=np.uint32):
+        if header_dtype is None:
+            raise ValueError('Must specify dtype')
+
+        header_dtype = np.dtype(header_dtype)
+        if header_dtype.kind != 'u':
+            warnings.warn("Given a dtype which is not unsigned.", stacklevel=2)
+
+        if mode not in 'rw' or len(mode) != 1:
+            raise ValueError('mode must be either r or w')
+
+        if hasattr(filename, 'seek'):
+            self._fp = filename
+        else:
+            self._fp = open(filename, f'{mode}b')
+
+        self._header_dtype = header_dtype
+
+    def _read_size(self, eof_ok=False):
+        n = self._header_dtype.itemsize
+        b = self._fp.read(n)
+        if (not b) and eof_ok:
+            raise FortranEOFError("End of file occurred at end of record")
+        elif len(b) < n:
+            raise FortranFormattingError(
+                "End of file in the middle of the record size")
+        return int(np.frombuffer(b, dtype=self._header_dtype, count=1)[0])
+
+    def write_record(self, *items):
+        """
+        Write a record (including sizes) to the file.
+
+        Parameters
+        ----------
+        *items : array_like
+            The data arrays to write.
+
+        Notes
+        -----
+        Writes data items to a file::
+
+            write_record(a.T, b.T, c.T, ...)
+
+            write(1) a, b, c, ...
+
+        Note that data in multidimensional arrays is written in
+        row-major order --- to make them read correctly by Fortran
+        programs, you need to transpose the arrays yourself when
+        writing them.
+
+        """
+        items = tuple(np.asarray(item) for item in items)
+        total_size = sum(item.nbytes for item in items)
+
+        nb = np.array([total_size], dtype=self._header_dtype)
+
+        nb.tofile(self._fp)
+        for item in items:
+            item.tofile(self._fp)
+        nb.tofile(self._fp)
+
+    def read_record(self, *dtypes, dtype=None):
+        """
+        Reads a record of a given type from the file.
+
+        Parameters
+        ----------
+        *dtypes : dtype, optional
+            Data type(s) specifying the size and endianness of the data.
+        dtype : dtype, optional
+            Data type specifying the size and endianness of the data
+
+        Returns
+        -------
+        data : ndarray
+            A 1-D array object.
+
+        Raises
+        ------
+        FortranEOFError
+            To signal that no further records are available
+        FortranFormattingError
+            To signal that the end of the file was encountered
+            part-way through a record
+
+        See Also
+        --------
+        read_reals
+        read_ints
+
+        Notes
+        -----
+        If the record contains a multidimensional array, you can specify
+        the size in the dtype. For example::
+
+            INTEGER var(5,4)
+
+        can be read with::
+
+            read_record('(4,5)i4').T
+
+        Note that this function does **not** assume the file data is in Fortran
+        column major order, so you need to (i) swap the order of dimensions
+        when reading and (ii) transpose the resulting array.
+
+        Alternatively, you can read the data as a 1-D array and handle the
+        ordering yourself. For example::
+
+            read_record('i4').reshape(5, 4, order='F')
+
+        For records that contain several variables or mixed types (as opposed
+        to single scalar or array types), give them as separate arguments::
+
+            double precision :: a
+            integer :: b
+            write(1) a, b
+
+            record = f.read_record(' 0, -n and n if n < 0
+
+        Parameters
+        ----------
+        n : int
+            max number one wants to be able to represent
+        min : int
+            minimum number of characters to use for the format
+
+        Returns
+        -------
+        res : IntFormat
+            IntFormat instance with reasonable (see Notes) computed width
+
+        Notes
+        -----
+        Reasonable should be understood as the minimal string length necessary
+        without losing precision. For example, IntFormat.from_number(1) will
+        return an IntFormat instance of width 2, so that any 0 and 1 may be
+        represented as 1-character strings without loss of information.
+        """
+        width = number_digits(n) + 1
+        if n < 0:
+            width += 1
+        repeat = 80 // width
+        return cls(width, min, repeat=repeat)
+
+    def __init__(self, width, min=None, repeat=None):
+        self.width = width
+        self.repeat = repeat
+        self.min = min
+
+    def __repr__(self):
+        r = "IntFormat("
+        if self.repeat:
+            r += f"{self.repeat}"
+        r += f"I{self.width}"
+        if self.min:
+            r += f".{self.min}"
+        return r + ")"
+
+    @property
+    def fortran_format(self):
+        r = "("
+        if self.repeat:
+            r += f"{self.repeat}"
+        r += f"I{self.width}"
+        if self.min:
+            r += f".{self.min}"
+        return r + ")"
+
+    @property
+    def python_format(self):
+        return "%" + str(self.width) + "d"
+
+
+class ExpFormat:
+    @classmethod
+    def from_number(cls, n, min=None):
+        """Given a float number, returns a "reasonable" ExpFormat instance to
+        represent any number between -n and n.
+
+        Parameters
+        ----------
+        n : float
+            max number one wants to be able to represent
+        min : int
+            minimum number of characters to use for the format
+
+        Returns
+        -------
+        res : ExpFormat
+            ExpFormat instance with reasonable (see Notes) computed width
+
+        Notes
+        -----
+        Reasonable should be understood as the minimal string length necessary
+        to avoid losing precision.
+        """
+        # len of one number in exp format: sign + 1|0 + "." +
+        # number of digit for fractional part + 'E' + sign of exponent +
+        # len of exponent
+        finfo = np.finfo(n.dtype)
+        # Number of digits for fractional part
+        n_prec = finfo.precision + 1
+        # Number of digits for exponential part
+        n_exp = number_digits(np.max(np.abs([finfo.maxexp, finfo.minexp])))
+        width = 1 + 1 + n_prec + 1 + n_exp + 1
+        if n < 0:
+            width += 1
+        repeat = int(np.floor(80 / width))
+        return cls(width, n_prec, min, repeat=repeat)
+
+    def __init__(self, width, significand, min=None, repeat=None):
+        """\
+        Parameters
+        ----------
+        width : int
+            number of characters taken by the string (includes space).
+        """
+        self.width = width
+        self.significand = significand
+        self.repeat = repeat
+        self.min = min
+
+    def __repr__(self):
+        r = "ExpFormat("
+        if self.repeat:
+            r += f"{self.repeat}"
+        r += f"E{self.width}.{self.significand}"
+        if self.min:
+            r += f"E{self.min}"
+        return r + ")"
+
+    @property
+    def fortran_format(self):
+        r = "("
+        if self.repeat:
+            r += f"{self.repeat}"
+        r += f"E{self.width}.{self.significand}"
+        if self.min:
+            r += f"E{self.min}"
+        return r + ")"
+
+    @property
+    def python_format(self):
+        return "%" + str(self.width-1) + "." + str(self.significand) + "E"
+
+
+class Token:
+    def __init__(self, type, value, pos):
+        self.type = type
+        self.value = value
+        self.pos = pos
+
+    def __str__(self):
+        return f"""Token('{self.type}', "{self.value}")"""
+
+    def __repr__(self):
+        return self.__str__()
+
+
+class Tokenizer:
+    def __init__(self):
+        self.tokens = list(TOKENS.keys())
+        self.res = [re.compile(TOKENS[i]) for i in self.tokens]
+
+    def input(self, s):
+        self.data = s
+        self.curpos = 0
+        self.len = len(s)
+
+    def next_token(self):
+        curpos = self.curpos
+
+        while curpos < self.len:
+            for i, r in enumerate(self.res):
+                m = r.match(self.data, curpos)
+                if m is None:
+                    continue
+                else:
+                    self.curpos = m.end()
+                    return Token(self.tokens[i], m.group(), self.curpos)
+            raise SyntaxError(
+                f"Unknown character at position {self.curpos} "
+                f"({self.data[self.curpos]})"
+            )
+
+
+# Grammar for fortran format:
+# format            : LPAR format_string RPAR
+# format_string     : repeated | simple
+# repeated          : repeat simple
+# simple            : int_fmt | exp_fmt
+# int_fmt           : INT_ID width
+# exp_fmt           : simple_exp_fmt
+# simple_exp_fmt    : EXP_ID width DOT significand
+# extended_exp_fmt  : EXP_ID width DOT significand EXP_ID ndigits
+# repeat            : INT
+# width             : INT
+# significand       : INT
+# ndigits           : INT
+
+# Naive fortran formatter - parser is hand-made
+class FortranFormatParser:
+    """Parser for Fortran format strings. The parse method returns a *Format
+    instance.
+
+    Notes
+    -----
+    Only ExpFormat (exponential format for floating values) and IntFormat
+    (integer format) for now.
+    """
+    def __init__(self):
+        self.tokenizer = threading.local()
+
+    def parse(self, s):
+        if not hasattr(self.tokenizer, 't'):
+            self.tokenizer.t = Tokenizer()
+
+        self.tokenizer.t.input(s)
+
+        tokens = []
+
+        try:
+            while True:
+                t = self.tokenizer.t.next_token()
+                if t is None:
+                    break
+                else:
+                    tokens.append(t)
+            return self._parse_format(tokens)
+        except SyntaxError as e:
+            raise BadFortranFormat(str(e)) from e
+
+    def _get_min(self, tokens):
+        next = tokens.pop(0)
+        if not next.type == "DOT":
+            raise SyntaxError()
+        next = tokens.pop(0)
+        return next.value
+
+    def _expect(self, token, tp):
+        if not token.type == tp:
+            raise SyntaxError()
+
+    def _parse_format(self, tokens):
+        if not tokens[0].type == "LPAR":
+            raise SyntaxError(
+                f"Expected left parenthesis at position {0} (got '{tokens[0].value}')"
+            )
+        elif not tokens[-1].type == "RPAR":
+            raise SyntaxError("Expected right parenthesis at position "
+                              f"{len(tokens)} (got '{tokens[-1].value}')")
+
+        tokens = tokens[1:-1]
+        types = [t.type for t in tokens]
+        if types[0] == "INT":
+            repeat = int(tokens.pop(0).value)
+        else:
+            repeat = None
+
+        next = tokens.pop(0)
+        if next.type == "INT_ID":
+            next = self._next(tokens, "INT")
+            width = int(next.value)
+            if tokens:
+                min = int(self._get_min(tokens))
+            else:
+                min = None
+            return IntFormat(width, min, repeat)
+        elif next.type == "EXP_ID":
+            next = self._next(tokens, "INT")
+            width = int(next.value)
+
+            next = self._next(tokens, "DOT")
+
+            next = self._next(tokens, "INT")
+            significand = int(next.value)
+
+            if tokens:
+                next = self._next(tokens, "EXP_ID")
+
+                next = self._next(tokens, "INT")
+                min = int(next.value)
+            else:
+                min = None
+            return ExpFormat(width, significand, min, repeat)
+        else:
+            raise SyntaxError(f"Invalid formatter type {next.value}")
+
+    def _next(self, tokens, tp):
+        if not len(tokens) > 0:
+            raise SyntaxError()
+        next = tokens.pop(0)
+        self._expect(next, tp)
+        return next
diff --git a/.venv/lib/python3.12/site-packages/scipy/io/_harwell_boeing/hb.py b/.venv/lib/python3.12/site-packages/scipy/io/_harwell_boeing/hb.py
new file mode 100644
index 0000000000000000000000000000000000000000..6a1232f12a3ce1091e9c94470494fc55d32f43e6
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/io/_harwell_boeing/hb.py
@@ -0,0 +1,592 @@
+"""
+Implementation of Harwell-Boeing read/write.
+
+At the moment not the full Harwell-Boeing format is supported. Supported
+features are:
+
+    - assembled, non-symmetric, real matrices
+    - integer for pointer/indices
+    - exponential format for float values, and int format
+
+"""
+# TODO:
+#   - Add more support (symmetric/complex matrices, non-assembled matrices ?)
+
+# XXX: reading is reasonably efficient (>= 85 % is in numpy.fromstring), but
+# takes a lot of memory. Being faster would require compiled code.
+# write is not efficient. Although not a terribly exciting task,
+# having reusable facilities to efficiently read/write fortran-formatted files
+# would be useful outside this module.
+
+import os
+import warnings
+
+import numpy as np
+from scipy._lib.deprecation import _NoValue
+from scipy.sparse import csc_array, csc_matrix
+from ._fortran_format_parser import FortranFormatParser, IntFormat, ExpFormat
+
+__all__ = ["hb_read", "hb_write"]
+
+
+class MalformedHeader(Exception):
+    pass
+
+
+class LineOverflow(Warning):
+    pass
+
+
+def _nbytes_full(fmt, nlines):
+    """Return the number of bytes to read to get every full lines for the
+    given parsed fortran format."""
+    return (fmt.repeat * fmt.width + 1) * (nlines - 1)
+
+
+class HBInfo:
+    @classmethod
+    def from_data(cls, m, title="Default title", key="0", mxtype=None, fmt=None):
+        """Create a HBInfo instance from an existing sparse matrix.
+
+        Parameters
+        ----------
+        m : sparse array or matrix
+            the HBInfo instance will derive its parameters from m
+        title : str
+            Title to put in the HB header
+        key : str
+            Key
+        mxtype : HBMatrixType
+            type of the input matrix
+        fmt : dict
+            not implemented
+
+        Returns
+        -------
+        hb_info : HBInfo instance
+        """
+        m = m.tocsc(copy=False)
+
+        pointer = m.indptr
+        indices = m.indices
+        values = m.data
+
+        nrows, ncols = m.shape
+        nnon_zeros = m.nnz
+
+        if fmt is None:
+            # +1 because HB uses one-based (Fortran) indexing.
+            # initial=1 supplies np.max's identity so empty indices/values
+            # (nnz == 0) still yield a valid format.
+            pointer_fmt = IntFormat.from_number(np.max(pointer + 1, initial=1))
+            indices_fmt = IntFormat.from_number(np.max(indices + 1, initial=1))
+
+            if values.dtype.kind in np.typecodes["AllFloat"]:
+                values_fmt = ExpFormat.from_number(
+                    -np.max(np.abs(values), initial=np.float64(1)))
+            elif values.dtype.kind in np.typecodes["AllInteger"]:
+                values_fmt = IntFormat.from_number(
+                    -np.max(np.abs(values), initial=1))
+            else:
+                message = f"type {values.dtype.kind} not implemented yet"
+                raise NotImplementedError(message)
+        else:
+            raise NotImplementedError("fmt argument not supported yet.")
+
+        if mxtype is None:
+            if not np.isrealobj(values):
+                raise ValueError("Complex values not supported yet")
+            if values.dtype.kind in np.typecodes["AllInteger"]:
+                tp = "integer"
+            elif values.dtype.kind in np.typecodes["AllFloat"]:
+                tp = "real"
+            else:
+                raise NotImplementedError(
+                    f"type {values.dtype} for values not implemented")
+            mxtype = HBMatrixType(tp, "unsymmetric", "assembled")
+        else:
+            raise ValueError("mxtype argument not handled yet.")
+
+        def _nlines(fmt, size):
+            nlines = size // fmt.repeat
+            if nlines * fmt.repeat != size:
+                nlines += 1
+            return nlines
+
+        pointer_nlines = _nlines(pointer_fmt, pointer.size)
+        indices_nlines = _nlines(indices_fmt, indices.size)
+        values_nlines = _nlines(values_fmt, values.size)
+
+        total_nlines = pointer_nlines + indices_nlines + values_nlines
+
+        return cls(title, key,
+            total_nlines, pointer_nlines, indices_nlines, values_nlines,
+            mxtype, nrows, ncols, nnon_zeros,
+            pointer_fmt.fortran_format, indices_fmt.fortran_format,
+            values_fmt.fortran_format)
+
+    @classmethod
+    def from_file(cls, fid):
+        """Create a HBInfo instance from a file object containing a matrix in the
+        HB format.
+
+        Parameters
+        ----------
+        fid : file-like matrix
+            File or file-like object containing a matrix in the HB format.
+
+        Returns
+        -------
+        hb_info : HBInfo instance
+        """
+        # First line
+        line = fid.readline().strip("\n")
+        if not len(line) > 72:
+            raise ValueError("Expected at least 72 characters for first line, "
+                             f"got: \n{line}")
+        title = line[:72]
+        key = line[72:]
+
+        # Second line
+        line = fid.readline().strip("\n")
+        if not len(line.rstrip()) >= 56:
+            raise ValueError("Expected at least 56 characters for second line, "
+                             f"got: \n{line}")
+        total_nlines = _expect_int(line[:14])
+        pointer_nlines = _expect_int(line[14:28])
+        indices_nlines = _expect_int(line[28:42])
+        values_nlines = _expect_int(line[42:56])
+
+        rhs_nlines = line[56:72].strip()
+        if rhs_nlines == '':
+            rhs_nlines = 0
+        else:
+            rhs_nlines = _expect_int(rhs_nlines)
+        if not rhs_nlines == 0:
+            raise ValueError("Only files without right hand side supported for "
+                             "now.")
+
+        # Third line
+        line = fid.readline().strip("\n")
+        if not len(line) >= 70:
+            raise ValueError(f"Expected at least 72 character for third line, "
+                             f"got:\n{line}")
+
+        mxtype_s = line[:3].upper()
+        if not len(mxtype_s) == 3:
+            raise ValueError("mxtype expected to be 3 characters long")
+
+        mxtype = HBMatrixType.from_fortran(mxtype_s)
+        if mxtype.value_type not in ["real", "integer"]:
+            raise ValueError("Only real or integer matrices supported for "
+                             f"now (detected {mxtype})")
+        if not mxtype.structure == "unsymmetric":
+            raise ValueError("Only unsymmetric matrices supported for "
+                             f"now (detected {mxtype})")
+        if not mxtype.storage == "assembled":
+            raise ValueError("Only assembled matrices supported for now")
+
+        if not line[3:14] == " " * 11:
+            raise ValueError(f"Malformed data for third line: {line}")
+
+        nrows = _expect_int(line[14:28])
+        ncols = _expect_int(line[28:42])
+        nnon_zeros = _expect_int(line[42:56])
+        nelementals = _expect_int(line[56:70])
+        if not nelementals == 0:
+            raise ValueError(
+                f"Unexpected value {nelementals} for nltvl (last entry of line 3)"
+            )
+        
+        # Fourth line
+        line = fid.readline().strip("\n")
+
+        ct = line.split()
+        if not len(ct) == 3:
+            raise ValueError(f"Expected 3 formats, got {ct}")
+
+        return cls(title, key,
+                   total_nlines, pointer_nlines, indices_nlines, values_nlines,
+                   mxtype, nrows, ncols, nnon_zeros,
+                   ct[0], ct[1], ct[2],
+                   rhs_nlines, nelementals)
+
+    def __init__(self, title, key,
+            total_nlines, pointer_nlines, indices_nlines, values_nlines,
+            mxtype, nrows, ncols, nnon_zeros,
+            pointer_format_str, indices_format_str, values_format_str,
+            right_hand_sides_nlines=0, nelementals=0):
+        """Do not use this directly, but the class ctrs (from_* functions)."""
+        if title is None:
+            title = "No Title"
+        if len(title) > 72:
+            raise ValueError("title cannot be > 72 characters")
+
+        if key is None:
+            key = "|No Key"
+        if len(key) > 8:
+            warnings.warn(f"key is > 8 characters (key is {key})",
+                          LineOverflow, stacklevel=3)
+        self.title = title
+        self.key = key
+
+        self.total_nlines = total_nlines
+        self.pointer_nlines = pointer_nlines
+        self.indices_nlines = indices_nlines
+        self.values_nlines = values_nlines
+
+        parser = FortranFormatParser()
+        pointer_format = parser.parse(pointer_format_str)
+        if not isinstance(pointer_format, IntFormat):
+            raise ValueError("Expected int format for pointer format, got "
+                             f"{pointer_format}")
+
+        indices_format = parser.parse(indices_format_str)
+        if not isinstance(indices_format, IntFormat):
+            raise ValueError("Expected int format for indices format, got "
+                             f"{indices_format}")
+
+        values_format = parser.parse(values_format_str)
+        if isinstance(values_format, ExpFormat):
+            if mxtype.value_type not in ["real", "complex"]:
+                raise ValueError(f"Inconsistency between matrix type {mxtype} and "
+                                 f"value type {values_format}")
+            values_dtype = np.float64
+        elif isinstance(values_format, IntFormat):
+            if mxtype.value_type not in ["integer"]:
+                raise ValueError(f"Inconsistency between matrix type {mxtype} and "
+                                 f"value type {values_format}")
+            # XXX: fortran int -> dtype association ?
+            values_dtype = int
+        else:
+            raise ValueError(f"Unsupported format for values {values_format!r}")
+
+        self.pointer_format = pointer_format
+        self.indices_format = indices_format
+        self.values_format = values_format
+
+        self.pointer_dtype = np.int32
+        self.indices_dtype = np.int32
+        self.values_dtype = values_dtype
+
+        self.pointer_nlines = pointer_nlines
+        self.pointer_nbytes_full = _nbytes_full(pointer_format, pointer_nlines)
+
+        self.indices_nlines = indices_nlines
+        self.indices_nbytes_full = _nbytes_full(indices_format, indices_nlines)
+
+        self.values_nlines = values_nlines
+        self.values_nbytes_full = _nbytes_full(values_format, values_nlines)
+
+        self.nrows = nrows
+        self.ncols = ncols
+        self.nnon_zeros = nnon_zeros
+        self.nelementals = nelementals
+        self.mxtype = mxtype
+
+    def dump(self):
+        """Gives the header corresponding to this instance as a string."""
+        header = [self.title.ljust(72) + self.key.ljust(8)]
+
+        header.append(f"{self.total_nlines:14d}{self.pointer_nlines:14d}{self.indices_nlines:14d}{self.values_nlines:14d}")
+        header.append(f"{self.mxtype.fortran_format.ljust(14):14s}{self.nrows:14d}{self.ncols:14d}{self.nnon_zeros:14d}{0:14d}")
+
+        pffmt = self.pointer_format.fortran_format
+        iffmt = self.indices_format.fortran_format
+        vffmt = self.values_format.fortran_format
+        header.append(f"{pffmt.ljust(16):16s}{iffmt.ljust(16):16s}{vffmt.ljust(20):20s}")
+        return "\n".join(header)
+
+
+def _expect_int(value, msg=None):
+    try:
+        return int(value)
+    except ValueError as e:
+        if msg is None:
+            msg = "Expected an int, got %s"
+        raise ValueError(msg % value) from e
+
+
+def _read_hb_data(content, header):
+    # XXX: look at a way to reduce memory here (big string creation)
+    ptr_string = "".join([content.read(header.pointer_nbytes_full),
+                           content.readline()])
+    ptr = np.fromstring(ptr_string,
+            dtype=int, sep=' ')
+
+    ind_string = "".join([content.read(header.indices_nbytes_full),
+                       content.readline()])
+    ind = np.fromstring(ind_string,
+            dtype=int, sep=' ')
+
+    val_string = "".join([content.read(header.values_nbytes_full),
+                          content.readline()])
+    val = np.fromstring(val_string,
+            dtype=header.values_dtype, sep=' ')
+
+    return csc_array((val, ind-1, ptr-1), shape=(header.nrows, header.ncols))
+
+
+def _write_data(m, fid, header):
+    m = m.tocsc(copy=False)
+
+    def write_array(f, ar, nlines, fmt):
+        # ar_nlines is the number of full lines, n is the number of items per
+        # line, ffmt the fortran format
+        pyfmt = fmt.python_format
+        pyfmt_full = pyfmt * fmt.repeat
+
+        # for each array to write, we first write the full lines, and special
+        # case for partial line
+        full = ar[:(nlines - 1) * fmt.repeat]
+        for row in full.reshape((nlines-1, fmt.repeat)):
+            f.write(pyfmt_full % tuple(row) + "\n")
+        nremain = ar.size - full.size
+        if nremain > 0:
+            f.write((pyfmt * nremain) % tuple(ar[ar.size - nremain:]) + "\n")
+
+    fid.write(header.dump())
+    fid.write("\n")
+    # +1 is for Fortran one-based indexing
+    write_array(fid, m.indptr+1, header.pointer_nlines,
+                header.pointer_format)
+    write_array(fid, m.indices+1, header.indices_nlines,
+                header.indices_format)
+    write_array(fid, m.data, header.values_nlines,
+                header.values_format)
+
+
+class HBMatrixType:
+    """Class to hold the matrix type."""
+    # q2f* translates qualified names to Fortran character
+    _q2f_type = {
+        "real": "R",
+        "complex": "C",
+        "pattern": "P",
+        "integer": "I",
+    }
+    _q2f_structure = {
+            "symmetric": "S",
+            "unsymmetric": "U",
+            "hermitian": "H",
+            "skewsymmetric": "Z",
+            "rectangular": "R"
+    }
+    _q2f_storage = {
+        "assembled": "A",
+        "elemental": "E",
+    }
+
+    _f2q_type = {j: i for i, j in _q2f_type.items()}
+    _f2q_structure = {j: i for i, j in _q2f_structure.items()}
+    _f2q_storage = {j: i for i, j in _q2f_storage.items()}
+
+    @classmethod
+    def from_fortran(cls, fmt):
+        if not len(fmt) == 3:
+            raise ValueError("Fortran format for matrix type should be 3 "
+                             "characters long")
+        try:
+            value_type = cls._f2q_type[fmt[0]]
+            structure = cls._f2q_structure[fmt[1]]
+            storage = cls._f2q_storage[fmt[2]]
+            return cls(value_type, structure, storage)
+        except KeyError as e:
+            raise ValueError(f"Unrecognized format {fmt}") from e
+
+    def __init__(self, value_type, structure, storage="assembled"):
+        self.value_type = value_type
+        self.structure = structure
+        self.storage = storage
+
+        if value_type not in self._q2f_type:
+            raise ValueError(f"Unrecognized type {value_type}")
+        if structure not in self._q2f_structure:
+            raise ValueError(f"Unrecognized structure {structure}")
+        if storage not in self._q2f_storage:
+            raise ValueError(f"Unrecognized storage {storage}")
+
+    @property
+    def fortran_format(self):
+        return self._q2f_type[self.value_type] + \
+               self._q2f_structure[self.structure] + \
+               self._q2f_storage[self.storage]
+
+    def __repr__(self):
+        return f"HBMatrixType({self.value_type}, {self.structure}, {self.storage})"
+
+
+class HBFile:
+    def __init__(self, file, hb_info=None):
+        """Create a HBFile instance.
+
+        Parameters
+        ----------
+        file : file-object
+            StringIO work as well
+        hb_info : HBInfo, optional
+            Should be given as an argument for writing, in which case the file
+            should be writable.
+        """
+        self._fid = file
+        if hb_info is None:
+            self._hb_info = HBInfo.from_file(file)
+        else:
+            #raise OSError("file %s is not writable, and hb_info "
+            #              "was given." % file)
+            self._hb_info = hb_info
+
+    @property
+    def title(self):
+        return self._hb_info.title
+
+    @property
+    def key(self):
+        return self._hb_info.key
+
+    @property
+    def type(self):
+        return self._hb_info.mxtype.value_type
+
+    @property
+    def structure(self):
+        return self._hb_info.mxtype.structure
+
+    @property
+    def storage(self):
+        return self._hb_info.mxtype.storage
+
+    def read_matrix(self):
+        return _read_hb_data(self._fid, self._hb_info)
+
+    def write_matrix(self, m):
+        return _write_data(m, self._fid, self._hb_info)
+
+
+def hb_read(path_or_open_file, *, spmatrix=_NoValue):
+    """Read HB-format file.
+
+    Parameters
+    ----------
+    path_or_open_file : path-like or file-like
+        If a file-like object, it is used as-is. Otherwise, it is opened
+        before reading.
+    spmatrix : bool, optional (default: True)
+        If ``True``, return sparse matrix. Otherwise return sparse array.
+
+        .. deprecated:: 1.18.0
+            The default value for `spmatrix` is changing to False in v1.20.
+            That means the default return value will be a sparse array.
+            Unless you use * instead of @, ** for matrix power, or you depend
+            on 2D shapes from e.g. ``A.sum(axis=0)``, it may not matter to you.
+            See :ref:`Migration from spmatrix to sparray `.
+
+    Returns
+    -------
+    data : csc_array or csc_matrix
+        The data read from the HB file as a sparse array.
+
+    Notes
+    -----
+    At the moment not the full Harwell-Boeing format is supported. Supported
+    features are:
+
+    - assembled, non-symmetric, real matrices
+    - integer for pointer/indices
+    - exponential format for float values, and int format
+
+    Examples
+    --------
+    We can read and write a harwell-boeing format file:
+
+    >>> from scipy.io import hb_read, hb_write
+    >>> from scipy.sparse import csr_array, eye
+    >>> data = csr_array(eye(3))  # create a sparse array
+    >>> hb_write("data.hb", data)  # write a hb file
+    >>> print(hb_read("data.hb", spmatrix=False))  # read a hb file
+    
+        Coords	Values
+        (0, 0)	1.0
+        (1, 1)	1.0
+        (2, 2)	1.0
+    """
+    def _get_matrix(fid):
+        hb = HBFile(fid)
+        return hb.read_matrix()
+
+    if hasattr(path_or_open_file, 'read'):
+        data = _get_matrix(path_or_open_file)
+    else:
+        with open(path_or_open_file) as f:
+            data = _get_matrix(f)
+
+    if spmatrix is _NoValue:
+        msg = """The default value for `spmatrix` is changing to `False` in v1.20.
+            That means the default return type will be a sparse array.
+            Unless you use * instead of @, ** for matrix power, or you depend
+            on 2D shapes from e.g. `A.sum(axis=0)` it may not matter to you.
+            See the spmatrix to sparray migration guide for details.
+            https://docs.scipy.org/doc/scipy/reference/sparse.migration_to_sparray.html
+            """
+        prefixes = (os.path.dirname(__file__),)
+        warnings.warn(msg, DeprecationWarning, skip_file_prefixes=prefixes)
+        spmatrix = True
+
+    if spmatrix:
+        return csc_matrix(data)
+    return data
+
+
+def hb_write(path_or_open_file, m, hb_info=None):
+    """Write HB-format file.
+
+    Parameters
+    ----------
+    path_or_open_file : path-like or file-like
+        If a file-like object, it is used as-is. Otherwise, it is opened
+        before writing.
+    m : sparse array or matrix
+        the sparse array to write
+    hb_info : HBInfo
+        contains the meta-data for write
+
+    Notes
+    -----
+    At the moment not the full Harwell-Boeing format is supported. Supported
+    features are:
+
+    - assembled, non-symmetric, real matrices
+    - integer for pointer/indices
+    - exponential format for float values, and int format
+
+    Examples
+    --------
+    We can read and write a harwell-boeing format file:
+
+    >>> from scipy.io import hb_read, hb_write
+    >>> from scipy.sparse import csr_array, eye
+    >>> data = csr_array(eye(3))  # create a sparse array
+    >>> hb_write("data.hb", data)  # write a hb file
+    >>> print(hb_read("data.hb", spmatrix=False))  # read a hb file
+    
+        Coords	Values
+        (0, 0)	1.0
+        (1, 1)	1.0
+        (2, 2)	1.0
+    """
+    m = m.tocsc(copy=False)
+
+    if hb_info is None:
+        hb_info = HBInfo.from_data(m)
+
+    def _set_matrix(fid):
+        hb = HBFile(fid, hb_info)
+        hb.write_matrix(m)
+
+    if hasattr(path_or_open_file, 'write'):
+        _set_matrix(path_or_open_file)
+    else:
+        with open(path_or_open_file, 'w') as f:
+            _set_matrix(f)
diff --git a/.venv/lib/python3.12/site-packages/scipy/io/_harwell_boeing/tests/__init__.py b/.venv/lib/python3.12/site-packages/scipy/io/_harwell_boeing/tests/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/.venv/lib/python3.12/site-packages/scipy/io/_harwell_boeing/tests/test_fortran_format.py b/.venv/lib/python3.12/site-packages/scipy/io/_harwell_boeing/tests/test_fortran_format.py
new file mode 100644
index 0000000000000000000000000000000000000000..dae040c523d6a6d618e89402d39a0cb05bad927a
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/io/_harwell_boeing/tests/test_fortran_format.py
@@ -0,0 +1,74 @@
+import numpy as np
+
+from numpy.testing import assert_equal
+from pytest import raises as assert_raises
+
+from scipy.io._harwell_boeing._fortran_format_parser import (
+        FortranFormatParser, IntFormat, ExpFormat, BadFortranFormat)
+
+
+class TestFortranFormatParser:
+    def setup_method(self):
+        self.parser = FortranFormatParser()
+
+    def _test_equal(self, format, ref):
+        ret = self.parser.parse(format)
+        assert_equal(ret.__dict__, ref.__dict__)
+
+    def test_simple_int(self):
+        self._test_equal("(I4)", IntFormat(4))
+
+    def test_simple_repeated_int(self):
+        self._test_equal("(3I4)", IntFormat(4, repeat=3))
+
+    def test_simple_exp(self):
+        self._test_equal("(E4.3)", ExpFormat(4, 3))
+
+    def test_exp_exp(self):
+        self._test_equal("(E8.3E3)", ExpFormat(8, 3, 3))
+
+    def test_repeat_exp(self):
+        self._test_equal("(2E4.3)", ExpFormat(4, 3, repeat=2))
+
+    def test_repeat_exp_exp(self):
+        self._test_equal("(2E8.3E3)", ExpFormat(8, 3, 3, repeat=2))
+
+    def test_wrong_formats(self):
+        def _test_invalid(bad_format):
+            assert_raises(BadFortranFormat, lambda: self.parser.parse(bad_format))
+        _test_invalid("I4")
+        _test_invalid("(E4)")
+        _test_invalid("(E4.)")
+        _test_invalid("(E4.E3)")
+
+
+class TestIntFormat:
+    def test_to_fortran(self):
+        f = [IntFormat(10), IntFormat(12, 10), IntFormat(12, 10, 3)]
+        res = ["(I10)", "(I12.10)", "(3I12.10)"]
+
+        for i, j in zip(f, res):
+            assert_equal(i.fortran_format, j)
+
+    def test_from_number(self):
+        f = [10, -12, 123456789]
+        r_f = [IntFormat(3, repeat=26), IntFormat(4, repeat=20),
+               IntFormat(10, repeat=8)]
+        for i, j in zip(f, r_f):
+            assert_equal(IntFormat.from_number(i).__dict__, j.__dict__)
+
+
+class TestExpFormat:
+    def test_to_fortran(self):
+        f = [ExpFormat(10, 5), ExpFormat(12, 10), ExpFormat(12, 10, min=3),
+             ExpFormat(10, 5, repeat=3)]
+        res = ["(E10.5)", "(E12.10)", "(E12.10E3)", "(3E10.5)"]
+
+        for i, j in zip(f, res):
+            assert_equal(i.fortran_format, j)
+
+    def test_from_number(self):
+        f = np.array([1.0, -1.2])
+        r_f = [ExpFormat(24, 16, repeat=3), ExpFormat(25, 16, repeat=3)]
+        for i, j in zip(f, r_f):
+            assert_equal(ExpFormat.from_number(i).__dict__, j.__dict__)
diff --git a/.venv/lib/python3.12/site-packages/scipy/io/_harwell_boeing/tests/test_hb.py b/.venv/lib/python3.12/site-packages/scipy/io/_harwell_boeing/tests/test_hb.py
new file mode 100644
index 0000000000000000000000000000000000000000..44c69349e4f267ba98a2fcfeb0f78848d1e20202
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/io/_harwell_boeing/tests/test_hb.py
@@ -0,0 +1,79 @@
+from io import StringIO
+import pytest
+import tempfile
+
+import numpy as np
+
+from numpy.testing import assert_equal, \
+    assert_array_almost_equal_nulp
+
+from scipy.sparse import coo_array, csc_array, random_array, sparray, issparse
+
+from scipy.io import hb_read, hb_write
+
+
+SIMPLE = """\
+No Title                                                                |No Key
+             9             4             1             4
+RUA                      100           100            10             0
+(26I3)          (26I3)          (3E23.15)
+1  2  2  2  2  3  3  3  3  3  3  3  3  3  3  3  3  3  3  3  3  3  3  3  3  3
+3  3  3  3  3  3  3  3  3  3  3  3  3  3  3  3  3  3  3  3  3  3  3  3  3  3
+3  3  3  3  3  3  3  4  4  4  6  6  6  6  6  6  6  6  6  6  6  8  9  9  9  9
+9  9  9  9  9  9  9  9  9  9  9  9  9  9  9  9  9  9  9  9  9  9 11
+37 71 89 18 30 45 70 19 25 52
+2.971243799687726e-01  3.662366682877375e-01  4.786962174699534e-01
+6.490068647991184e-01  6.617490424831662e-02  8.870370343191623e-01
+4.196478590163001e-01  5.649603072111251e-01  9.934423887087086e-01
+6.912334991524289e-01
+"""
+
+SIMPLE_MATRIX = coo_array(
+    ((0.297124379969, 0.366236668288, 0.47869621747, 0.649006864799,
+      0.0661749042483, 0.887037034319, 0.419647859016,
+      0.564960307211, 0.993442388709, 0.691233499152,),
+     (np.array([[36, 70, 88, 17, 29, 44, 69, 18, 24, 51],
+                [0, 4, 58, 61, 61, 72, 72, 73, 99, 99]]))))
+
+
+def assert_csc_almost_equal(r, l):
+    r = csc_array(r)
+    l = csc_array(l)
+    assert_equal(r.indptr, l.indptr)
+    assert_equal(r.indices, l.indices)
+    assert_array_almost_equal_nulp(r.data, l.data, 10000)
+
+
+class TestHBReader:
+    def test_simple(self):
+        m = hb_read(StringIO(SIMPLE), spmatrix=False)
+        assert_csc_almost_equal(m, SIMPLE_MATRIX)
+        assert isinstance(m, sparray)
+        m = hb_read(StringIO(SIMPLE), spmatrix=True)
+        assert issparse(m) and not isinstance(m, sparray)
+        with pytest.deprecated_call(match="The default value for `spmatrix"):
+            m = hb_read(StringIO(SIMPLE))  # default
+            assert issparse(m) and not isinstance(m, sparray)
+
+
+class TestHBReadWrite:
+
+    def check_save_load(self, value):
+        with tempfile.NamedTemporaryFile(mode='w+t') as file:
+            hb_write(file, value)
+            file.file.seek(0)
+            value_loaded = hb_read(file, spmatrix=False)
+        assert_csc_almost_equal(value, value_loaded)
+
+    def test_simple(self):
+        random_arr = random_array((10, 100), density=0.1)
+        for format in ('coo', 'csc', 'csr', 'bsr', 'dia', 'dok', 'lil'):
+            arr = random_arr.asformat(format, copy=False)
+            self.check_save_load(arr)
+
+    @pytest.mark.parametrize("dtype", [np.float64, np.int64])
+    def test_empty_roundtrip(self, dtype):
+        # gh-24082: nnz == 0 used to crash in HBInfo.from_data; the integer
+        # variant additionally exercised a mxtype/format inconsistency.
+        m = csc_array(np.zeros((2, 2), dtype=dtype))
+        self.check_save_load(m)
diff --git a/.venv/lib/python3.12/site-packages/scipy/io/_idl.py b/.venv/lib/python3.12/site-packages/scipy/io/_idl.py
new file mode 100644
index 0000000000000000000000000000000000000000..161ac9b8b8857623b943173859d2e466bd37b488
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/io/_idl.py
@@ -0,0 +1,917 @@
+# IDLSave - a python module to read IDL 'save' files
+# Copyright (c) 2010 Thomas P. Robitaille
+
+# Many thanks to Craig Markwardt for publishing the Unofficial Format
+# Specification for IDL .sav files, without which this Python module would not
+# exist (http://cow.physics.wisc.edu/~craigm/idl/savefmt).
+
+# This code was developed by with permission from ITT Visual Information
+# Systems. IDL(r) is a registered trademark of ITT Visual Information Systems,
+# Inc. for their Interactive Data Language software.
+
+# 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.
+
+__all__ = ['readsav']
+
+import struct
+import numpy as np
+import tempfile
+import zlib
+import warnings
+
+# Define the different data types that can be found in an IDL save file
+DTYPE_DICT = {1: '>u1',
+              2: '>i2',
+              3: '>i4',
+              4: '>f4',
+              5: '>f8',
+              6: '>c8',
+              7: '|O',
+              8: '|O',
+              9: '>c16',
+              10: '|O',
+              11: '|O',
+              12: '>u2',
+              13: '>u4',
+              14: '>i8',
+              15: '>u8'}
+
+# Define the different record types that can be found in an IDL save file
+RECTYPE_DICT = {0: "START_MARKER",
+                1: "COMMON_VARIABLE",
+                2: "VARIABLE",
+                3: "SYSTEM_VARIABLE",
+                6: "END_MARKER",
+                10: "TIMESTAMP",
+                12: "COMPILED",
+                13: "IDENTIFICATION",
+                14: "VERSION",
+                15: "HEAP_HEADER",
+                16: "HEAP_DATA",
+                17: "PROMOTE64",
+                19: "NOTICE",
+                20: "DESCRIPTION"}
+
+# Define a dictionary to contain structure definitions
+STRUCT_DICT: dict[str, dict] = {}
+
+
+def _align_32(f):
+    '''Align to the next 32-bit position in a file'''
+
+    pos = f.tell()
+    if pos % 4 != 0:
+        f.seek(pos + 4 - pos % 4)
+    return
+
+
+def _skip_bytes(f, n):
+    '''Skip `n` bytes'''
+    f.read(n)
+    return
+
+
+def _read_bytes(f, n):
+    '''Read the next `n` bytes'''
+    return f.read(n)
+
+
+def _read_byte(f):
+    '''Read a single byte'''
+    return np.uint8(struct.unpack('>B', f.read(4)[:1])[0])
+
+
+def _read_long(f):
+    '''Read a signed 32-bit integer'''
+    return np.int32(struct.unpack('>l', f.read(4))[0])
+
+
+def _read_int16(f):
+    '''Read a signed 16-bit integer'''
+    return np.int16(struct.unpack('>h', f.read(4)[2:4])[0])
+
+
+def _read_int32(f):
+    '''Read a signed 32-bit integer'''
+    return np.int32(struct.unpack('>i', f.read(4))[0])
+
+
+def _read_int64(f):
+    '''Read a signed 64-bit integer'''
+    return np.int64(struct.unpack('>q', f.read(8))[0])
+
+
+def _read_uint16(f):
+    '''Read an unsigned 16-bit integer'''
+    return np.uint16(struct.unpack('>H', f.read(4)[2:4])[0])
+
+
+def _read_uint32(f):
+    '''Read an unsigned 32-bit integer'''
+    return np.uint32(struct.unpack('>I', f.read(4))[0])
+
+
+def _read_uint64(f):
+    '''Read an unsigned 64-bit integer'''
+    return np.uint64(struct.unpack('>Q', f.read(8))[0])
+
+
+def _read_float32(f):
+    '''Read a 32-bit float'''
+    return np.float32(struct.unpack('>f', f.read(4))[0])
+
+
+def _read_float64(f):
+    '''Read a 64-bit float'''
+    return np.float64(struct.unpack('>d', f.read(8))[0])
+
+
+class Pointer:
+    '''Class used to define pointers'''
+
+    def __init__(self, index):
+        self.index = index
+        return
+
+
+class ObjectPointer(Pointer):
+    '''Class used to define object pointers'''
+    pass
+
+
+def _read_string(f):
+    '''Read a string'''
+    length = _read_long(f)
+    if length > 0:
+        chars = _read_bytes(f, length).decode('latin1')
+        _align_32(f)
+    else:
+        chars = ''
+    return chars
+
+
+def _read_string_data(f):
+    '''Read a data string (length is specified twice)'''
+    length = _read_long(f)
+    if length > 0:
+        length = _read_long(f)
+        string_data = _read_bytes(f, length)
+        _align_32(f)
+    else:
+        string_data = ''
+    return string_data
+
+
+def _read_data(f, dtype):
+    '''Read a variable with a specified data type'''
+    if dtype == 1:
+        if _read_int32(f) != 1:
+            raise Exception("Error occurred while reading byte variable")
+        return _read_byte(f)
+    elif dtype == 2:
+        return _read_int16(f)
+    elif dtype == 3:
+        return _read_int32(f)
+    elif dtype == 4:
+        return _read_float32(f)
+    elif dtype == 5:
+        return _read_float64(f)
+    elif dtype == 6:
+        real = _read_float32(f)
+        imag = _read_float32(f)
+        return np.complex64(real + imag * 1j)
+    elif dtype == 7:
+        return _read_string_data(f)
+    elif dtype == 8:
+        raise Exception("Should not be here - please report this")
+    elif dtype == 9:
+        real = _read_float64(f)
+        imag = _read_float64(f)
+        return np.complex128(real + imag * 1j)
+    elif dtype == 10:
+        return Pointer(_read_int32(f))
+    elif dtype == 11:
+        return ObjectPointer(_read_int32(f))
+    elif dtype == 12:
+        return _read_uint16(f)
+    elif dtype == 13:
+        return _read_uint32(f)
+    elif dtype == 14:
+        return _read_int64(f)
+    elif dtype == 15:
+        return _read_uint64(f)
+    else:
+        raise Exception(f"Unknown IDL type: {dtype} - please report this")
+
+
+def _read_structure(f, array_desc, struct_desc):
+    '''
+    Read a structure, with the array and structure descriptors given as
+    `array_desc` and `structure_desc` respectively.
+    '''
+
+    nrows = array_desc['nelements']
+    columns = struct_desc['tagtable']
+
+    dtype = []
+    for col in columns:
+        if col['structure'] or col['array']:
+            dtype.append(((col['name'].lower(), col['name']), np.object_))
+        else:
+            if col['typecode'] in DTYPE_DICT:
+                dtype.append(((col['name'].lower(), col['name']),
+                                    DTYPE_DICT[col['typecode']]))
+            else:
+                raise Exception(f"Variable type {col['typecode']} not implemented")
+
+    structure = np.rec.recarray((nrows, ), dtype=dtype)
+
+    for i in range(nrows):
+        for col in columns:
+            dtype = col['typecode']
+            if col['structure']:
+                structure[col['name']][i] = _read_structure(f,
+                                      struct_desc['arrtable'][col['name']],
+                                      struct_desc['structtable'][col['name']])
+            elif col['array']:
+                structure[col['name']][i] = _read_array(f, dtype,
+                                      struct_desc['arrtable'][col['name']])
+            else:
+                structure[col['name']][i] = _read_data(f, dtype)
+
+    # Reshape structure if needed
+    if array_desc['ndims'] > 1:
+        dims = array_desc['dims'][:int(array_desc['ndims'])]
+        dims.reverse()
+        structure = structure.reshape(dims)
+
+    return structure
+
+
+def _read_array(f, typecode, array_desc):
+    '''
+    Read an array of type `typecode`, with the array descriptor given as
+    `array_desc`.
+    '''
+
+    if typecode in [1, 3, 4, 5, 6, 9, 13, 14, 15]:
+
+        if typecode == 1:
+            nbytes = _read_int32(f)
+            if nbytes != array_desc['nbytes']:
+                warnings.warn("Not able to verify number of bytes from header",
+                              stacklevel=3)
+
+        # Read bytes as numpy array
+        array = np.frombuffer(f.read(array_desc['nbytes']),
+                              dtype=DTYPE_DICT[typecode])
+
+    elif typecode in [2, 12]:
+
+        # These are 2 byte types, need to skip every two as they are not packed
+
+        array = np.frombuffer(f.read(array_desc['nbytes']*2),
+                              dtype=DTYPE_DICT[typecode])[1::2]
+
+    else:
+
+        # Read bytes into list
+        array = []
+        for i in range(array_desc['nelements']):
+            dtype = typecode
+            data = _read_data(f, dtype)
+            array.append(data)
+
+        array = np.array(array, dtype=np.object_)
+
+    # Reshape array if needed
+    if array_desc['ndims'] > 1:
+        dims = array_desc['dims'][:int(array_desc['ndims'])]
+        dims.reverse()
+        array = array.reshape(dims)
+
+    # Go to next alignment position
+    _align_32(f)
+
+    return array
+
+
+def _read_record(f):
+    '''Function to read in a full record'''
+
+    record = {'rectype': _read_long(f)}
+
+    nextrec = _read_uint32(f)
+    nextrec += _read_uint32(f).astype(np.int64) * 2**32
+
+    _skip_bytes(f, 4)
+
+    if record['rectype'] not in RECTYPE_DICT:
+        raise Exception(f"Unknown RECTYPE: {record['rectype']}")
+
+    record['rectype'] = RECTYPE_DICT[record['rectype']]
+
+    if record['rectype'] in ["VARIABLE", "HEAP_DATA"]:
+
+        if record['rectype'] == "VARIABLE":
+            record['varname'] = _read_string(f)
+        else:
+            record['heap_index'] = _read_long(f)
+            _skip_bytes(f, 4)
+
+        rectypedesc = _read_typedesc(f)
+
+        if rectypedesc['typecode'] == 0:
+
+            if nextrec == f.tell():
+                record['data'] = None  # Indicates NULL value
+            else:
+                raise ValueError("Unexpected type code: 0")
+
+        else:
+
+            varstart = _read_long(f)
+            if varstart != 7:
+                raise Exception("VARSTART is not 7")
+
+            if rectypedesc['structure']:
+                record['data'] = _read_structure(f, rectypedesc['array_desc'],
+                                                    rectypedesc['struct_desc'])
+            elif rectypedesc['array']:
+                record['data'] = _read_array(f, rectypedesc['typecode'],
+                                                rectypedesc['array_desc'])
+            else:
+                dtype = rectypedesc['typecode']
+                record['data'] = _read_data(f, dtype)
+
+    elif record['rectype'] == "TIMESTAMP":
+
+        _skip_bytes(f, 4*256)
+        record['date'] = _read_string(f)
+        record['user'] = _read_string(f)
+        record['host'] = _read_string(f)
+
+    elif record['rectype'] == "VERSION":
+
+        record['format'] = _read_long(f)
+        record['arch'] = _read_string(f)
+        record['os'] = _read_string(f)
+        record['release'] = _read_string(f)
+
+    elif record['rectype'] == "IDENTIFICATION":
+
+        record['author'] = _read_string(f)
+        record['title'] = _read_string(f)
+        record['idcode'] = _read_string(f)
+
+    elif record['rectype'] == "NOTICE":
+
+        record['notice'] = _read_string(f)
+
+    elif record['rectype'] == "DESCRIPTION":
+
+        record['description'] = _read_string_data(f)
+
+    elif record['rectype'] == "HEAP_HEADER":
+
+        record['nvalues'] = _read_long(f)
+        record['indices'] = [_read_long(f) for _ in range(record['nvalues'])]
+
+    elif record['rectype'] == "COMMONBLOCK":
+
+        record['nvars'] = _read_long(f)
+        record['name'] = _read_string(f)
+        record['varnames'] = [_read_string(f) for _ in range(record['nvars'])]
+
+    elif record['rectype'] == "END_MARKER":
+
+        record['end'] = True
+
+    elif record['rectype'] == "UNKNOWN":
+
+        warnings.warn("Skipping UNKNOWN record", stacklevel=3)
+
+    elif record['rectype'] == "SYSTEM_VARIABLE":
+
+        warnings.warn("Skipping SYSTEM_VARIABLE record", stacklevel=3)
+
+    else:
+
+        raise Exception(f"record['rectype']={record['rectype']} not implemented")
+
+    f.seek(nextrec)
+
+    return record
+
+
+def _read_typedesc(f):
+    '''Function to read in a type descriptor'''
+
+    typedesc = {'typecode': _read_long(f), 'varflags': _read_long(f)}
+
+    if typedesc['varflags'] & 2 == 2:
+        raise Exception("System variables not implemented")
+
+    typedesc['array'] = typedesc['varflags'] & 4 == 4
+    typedesc['structure'] = typedesc['varflags'] & 32 == 32
+
+    if typedesc['structure']:
+        typedesc['array_desc'] = _read_arraydesc(f)
+        typedesc['struct_desc'] = _read_structdesc(f)
+    elif typedesc['array']:
+        typedesc['array_desc'] = _read_arraydesc(f)
+
+    return typedesc
+
+
+def _read_arraydesc(f):
+    '''Function to read in an array descriptor'''
+
+    arraydesc = {'arrstart': _read_long(f)}
+
+    if arraydesc['arrstart'] == 8:
+
+        _skip_bytes(f, 4)
+
+        arraydesc['nbytes'] = _read_long(f)
+        arraydesc['nelements'] = _read_long(f)
+        arraydesc['ndims'] = _read_long(f)
+
+        _skip_bytes(f, 8)
+
+        arraydesc['nmax'] = _read_long(f)
+
+        arraydesc['dims'] = [_read_long(f) for _ in range(arraydesc['nmax'])]
+
+    elif arraydesc['arrstart'] == 18:
+
+        warnings.warn("Using experimental 64-bit array read", stacklevel=3)
+
+        _skip_bytes(f, 8)
+
+        arraydesc['nbytes'] = _read_uint64(f)
+        arraydesc['nelements'] = _read_uint64(f)
+        arraydesc['ndims'] = _read_long(f)
+
+        _skip_bytes(f, 8)
+
+        arraydesc['nmax'] = 8
+
+        arraydesc['dims'] = []
+        for d in range(arraydesc['nmax']):
+            v = _read_long(f)
+            if v != 0:
+                raise Exception("Expected a zero in ARRAY_DESC")
+            arraydesc['dims'].append(_read_long(f))
+
+    else:
+        raise Exception(f"Unknown ARRSTART: {arraydesc['arrstart']}")
+
+    return arraydesc
+
+
+def _read_structdesc(f):
+    '''Function to read in a structure descriptor'''
+
+    structdesc = {}
+
+    structstart = _read_long(f)
+    if structstart != 9:
+        raise Exception("STRUCTSTART should be 9")
+
+    structdesc['name'] = _read_string(f)
+    predef = _read_long(f)
+    structdesc['ntags'] = _read_long(f)
+    structdesc['nbytes'] = _read_long(f)
+
+    structdesc['predef'] = predef & 1
+    structdesc['inherits'] = predef & 2
+    structdesc['is_super'] = predef & 4
+
+    if not structdesc['predef']:
+
+        structdesc['tagtable'] = [_read_tagdesc(f)
+                                  for _ in range(structdesc['ntags'])]
+
+        for tag in structdesc['tagtable']:
+            tag['name'] = _read_string(f)
+
+        structdesc['arrtable'] = {tag['name']: _read_arraydesc(f)
+                                  for tag in structdesc['tagtable']
+                                  if tag['array']}
+
+        structdesc['structtable'] = {tag['name']: _read_structdesc(f)
+                                     for tag in structdesc['tagtable']
+                                     if tag['structure']}
+
+        if structdesc['inherits'] or structdesc['is_super']:
+            structdesc['classname'] = _read_string(f)
+            structdesc['nsupclasses'] = _read_long(f)
+            structdesc['supclassnames'] = [
+                _read_string(f) for _ in range(structdesc['nsupclasses'])]
+            structdesc['supclasstable'] = [
+                _read_structdesc(f) for _ in range(structdesc['nsupclasses'])]
+
+        STRUCT_DICT[structdesc['name']] = structdesc
+
+    else:
+
+        if structdesc['name'] not in STRUCT_DICT:
+            raise Exception("PREDEF=1 but can't find definition")
+
+        structdesc = STRUCT_DICT[structdesc['name']]
+
+    return structdesc
+
+
+def _read_tagdesc(f):
+    '''Function to read in a tag descriptor'''
+
+    tagdesc = {'offset': _read_long(f)}
+
+    if tagdesc['offset'] == -1:
+        tagdesc['offset'] = _read_uint64(f)
+
+    tagdesc['typecode'] = _read_long(f)
+    tagflags = _read_long(f)
+
+    tagdesc['array'] = tagflags & 4 == 4
+    tagdesc['structure'] = tagflags & 32 == 32
+    tagdesc['scalar'] = tagdesc['typecode'] in DTYPE_DICT
+    # Assume '10'x is scalar
+
+    return tagdesc
+
+
+def _replace_heap(variable, heap):
+
+    if isinstance(variable, Pointer):
+
+        while isinstance(variable, Pointer):
+
+            if variable.index == 0:
+                variable = None
+            else:
+                if variable.index in heap:
+                    variable = heap[variable.index]
+                else:
+                    warnings.warn("Variable referenced by pointer not found "
+                                  "in heap: variable will be set to None",
+                                  stacklevel=3)
+                    variable = None
+
+        replace, new = _replace_heap(variable, heap)
+
+        if replace:
+            variable = new
+
+        return True, variable
+
+    elif isinstance(variable, np.rec.recarray):
+
+        # Loop over records
+        for ir, record in enumerate(variable):
+
+            replace, new = _replace_heap(record, heap)
+
+            if replace:
+                variable[ir] = new
+
+        return False, variable
+
+    elif isinstance(variable, np.record):
+
+        # Loop over values
+        for iv, value in enumerate(variable):
+
+            replace, new = _replace_heap(value, heap)
+
+            if replace:
+                variable[iv] = new
+
+        return False, variable
+
+    elif isinstance(variable, np.ndarray):
+
+        # Loop over values if type is np.object_
+        if variable.dtype.type is np.object_:
+
+            for iv in range(variable.size):
+
+                replace, new = _replace_heap(variable.item(iv), heap)
+
+                if replace:
+                    variable.reshape(-1)[iv] = new
+
+        return False, variable
+
+    else:
+
+        return False, variable
+
+
+class AttrDict(dict):
+    '''
+    A case-insensitive dictionary with access via item, attribute, and call
+    notations:
+
+        >>> from scipy.io._idl import AttrDict
+        >>> d = AttrDict()
+        >>> d['Variable'] = 123
+        >>> d['Variable']
+        123
+        >>> d.Variable
+        123
+        >>> d.variable
+        123
+        >>> d('VARIABLE')
+        123
+        >>> d['missing']
+        Traceback (most recent error last):
+        ...
+        KeyError: 'missing'
+        >>> d.missing
+        Traceback (most recent error last):
+        ...
+        AttributeError: 'AttrDict' object has no attribute 'missing'
+    '''
+
+    def __init__(self, init=None):
+        if init is None:
+            init = {}
+        dict.__init__(self, init)
+
+    def __getitem__(self, name):
+        return super().__getitem__(name.lower())
+
+    def __setitem__(self, key, value):
+        return super().__setitem__(key.lower(), value)
+
+    def __getattr__(self, name):
+        try:
+            return self.__getitem__(name)
+        except KeyError:
+            raise AttributeError(
+                f"'{type(self)}' object has no attribute '{name}'") from None
+
+    __setattr__ = __setitem__
+    __call__ = __getitem__
+
+
+def readsav(file_name, idict=None, python_dict=False,
+            uncompressed_file_name=None, verbose=False):
+    """
+    Read an IDL .sav file.
+
+    Parameters
+    ----------
+    file_name : str
+        Name of the IDL save file.
+    idict : dict, optional
+        Dictionary in which to insert .sav file variables.
+    python_dict : bool, optional
+        By default, the object return is not a Python dictionary, but a
+        case-insensitive dictionary with item, attribute, and call access
+        to variables. To get a standard Python dictionary, set this option
+        to True.
+    uncompressed_file_name : str, optional
+        This option only has an effect for .sav files written with the
+        /compress option. If a file name is specified, compressed .sav
+        files are uncompressed to this file. Otherwise, readsav will use
+        the `tempfile` module to determine a temporary filename
+        automatically, and will remove the temporary file upon successfully
+        reading it in.
+    verbose : bool, optional
+        Whether to print out information about the save file, including
+        the records read, and available variables.
+
+    Returns
+    -------
+    idl_dict : AttrDict or dict
+        If `python_dict` is set to False (default), this function returns a
+        case-insensitive dictionary with item, attribute, and call access
+        to variables. If `python_dict` is set to True, this function
+        returns a Python dictionary with all variable names in lowercase.
+        If `idict` was specified, then variables are written to the
+        dictionary specified, and the updated dictionary is returned.
+
+    Examples
+    --------
+    >>> from os.path import dirname, join as pjoin
+    >>> import scipy.io as sio
+    >>> from scipy.io import readsav
+
+    Get the filename for an example .sav file from the tests/data directory.
+
+    >>> data_dir = pjoin(dirname(sio.__file__), 'tests', 'data')
+    >>> sav_fname = pjoin(data_dir, 'array_float32_1d.sav')
+
+    Load the .sav file contents.
+
+    >>> sav_data = readsav(sav_fname)
+
+    Get keys of the .sav file contents.
+
+    >>> print(sav_data.keys())
+    dict_keys(['array1d'])
+
+    Access a content with a key.
+
+    >>> print(sav_data['array1d'])
+    [0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.
+     0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.
+     0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.
+     0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.
+     0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.
+     0. 0. 0.]
+
+    """
+
+    # Initialize record and variable holders
+    records = []
+    if python_dict or idict:
+        variables = {}
+    else:
+        variables = AttrDict()
+
+    # Open the IDL file
+    f = open(file_name, 'rb')
+
+    # Read the signature, which should be 'SR'
+    signature = _read_bytes(f, 2)
+    if signature != b'SR':
+        raise Exception(f"Invalid SIGNATURE: {signature}")
+
+    # Next, the record format, which is '\x00\x04' for normal .sav
+    # files, and '\x00\x06' for compressed .sav files.
+    recfmt = _read_bytes(f, 2)
+
+    if recfmt == b'\x00\x04':
+        pass
+
+    elif recfmt == b'\x00\x06':
+
+        if verbose:
+            print("IDL Save file is compressed")
+
+        if uncompressed_file_name:
+            fout = open(uncompressed_file_name, 'w+b')
+        else:
+            fout = tempfile.NamedTemporaryFile(suffix='.sav')
+
+        if verbose:
+            print(f" -> expanding to {fout.name}")
+
+        # Write header
+        fout.write(b'SR\x00\x04')
+
+        # Cycle through records
+        while True:
+
+            # Read record type
+            rectype = _read_long(f)
+            fout.write(struct.pack('>l', int(rectype)))
+
+            # Read position of next record and return as int
+            nextrec = _read_uint32(f)
+            nextrec += _read_uint32(f).astype(np.int64) * 2**32
+
+            # Read the unknown 4 bytes
+            unknown = f.read(4)
+
+            # Check if the end of the file has been reached
+            if RECTYPE_DICT[rectype] == 'END_MARKER':
+                modval = np.int64(2**32)
+                fout.write(struct.pack('>I', int(nextrec) % modval))
+                fout.write(
+                    struct.pack('>I', int((nextrec - (nextrec % modval)) / modval))
+                )
+                fout.write(unknown)
+                break
+
+            # Find current position
+            pos = f.tell()
+
+            # Decompress record
+            rec_string = zlib.decompress(f.read(nextrec-pos))
+
+            # Find new position of next record
+            nextrec = fout.tell() + len(rec_string) + 12
+
+            # Write out record
+            fout.write(struct.pack('>I', int(nextrec % 2**32)))
+            fout.write(struct.pack('>I', int((nextrec - (nextrec % 2**32)) / 2**32)))
+            fout.write(unknown)
+            fout.write(rec_string)
+
+        # Close the original compressed file
+        f.close()
+
+        # Set f to be the decompressed file, and skip the first four bytes
+        f = fout
+        f.seek(4)
+
+    else:
+        raise Exception(f"Invalid RECFMT: {recfmt}")
+
+    # Loop through records, and add them to the list
+    while True:
+        r = _read_record(f)
+        records.append(r)
+        if 'end' in r:
+            if r['end']:
+                break
+
+    # Close the file
+    f.close()
+
+    # Find heap data variables
+    heap = {}
+    for r in records:
+        if r['rectype'] == "HEAP_DATA":
+            heap[r['heap_index']] = r['data']
+
+    # Find all variables
+    for r in records:
+        if r['rectype'] == "VARIABLE":
+            replace, new = _replace_heap(r['data'], heap)
+            if replace:
+                r['data'] = new
+            variables[r['varname'].lower()] = r['data']
+
+    if verbose:
+
+        # Print out timestamp info about the file
+        for record in records:
+            if record['rectype'] == "TIMESTAMP":
+                print("-"*50)
+                print(f"Date: {record['date']}")
+                print(f"User: {record['user']}")
+                print(f"Host: {record['host']}")
+                break
+
+        # Print out version info about the file
+        for record in records:
+            if record['rectype'] == "VERSION":
+                print("-"*50)
+                print(f"Format: {record['format']}")
+                print(f"Architecture: {record['arch']}")
+                print(f"Operating System: {record['os']}")
+                print(f"IDL Version: {record['release']}")
+                break
+
+        # Print out identification info about the file
+        for record in records:
+            if record['rectype'] == "IDENTIFICATION":
+                print("-"*50)
+                print(f"Author: {record['author']}")
+                print(f"Title: {record['title']}")
+                print(f"ID Code: {record['idcode']}")
+                break
+
+        # Print out descriptions saved with the file
+        for record in records:
+            if record['rectype'] == "DESCRIPTION":
+                print("-"*50)
+                print(f"Description: {record['description']}")
+                break
+
+        print("-"*50)
+        print(f"Successfully read {len(records)} records of which:")
+
+        # Create convenience list of record types
+        rectypes = [r['rectype'] for r in records]
+
+        for rt in set(rectypes):
+            if rt != 'END_MARKER':
+                print(f" - {rectypes.count(rt)} are of type {rt}")
+        print("-"*50)
+
+        if 'VARIABLE' in rectypes:
+            print("Available variables:")
+            for var in variables:
+                print(f" - {var} [{type(variables[var])}]")
+            print("-"*50)
+
+    if idict:
+        for var in variables:
+            idict[var] = variables[var]
+        return idict
+    else:
+        return variables
diff --git a/.venv/lib/python3.12/site-packages/scipy/io/_mmio.py b/.venv/lib/python3.12/site-packages/scipy/io/_mmio.py
new file mode 100644
index 0000000000000000000000000000000000000000..c146354639ce7799eb272174add8720c4f480cf1
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/io/_mmio.py
@@ -0,0 +1,993 @@
+"""
+  Matrix Market I/O in Python.
+  See http://math.nist.gov/MatrixMarket/formats.html
+  for information about the Matrix Market format.
+"""
+#
+# Author: Pearu Peterson 
+# Created: October, 2004
+#
+# References:
+#  http://math.nist.gov/MatrixMarket/
+#
+import os
+from warnings import warn
+
+import numpy as np
+from numpy import (asarray, real, imag, conj, zeros, ndarray, concatenate,
+                   ones, can_cast)
+
+from scipy.sparse import coo_array, issparse, coo_matrix
+from scipy._lib.deprecation import _NoValue
+
+__all__ = ['mminfo', 'mmread', 'mmwrite', 'MMFile']
+
+
+# -----------------------------------------------------------------------------
+def asstr(s):
+    if isinstance(s, bytes):
+        return s.decode('latin1')
+    return str(s)
+
+
+def mminfo(source):
+    """
+    Return size and storage parameters from Matrix Market file-like 'source'.
+
+    Parameters
+    ----------
+    source : str or file-like
+        Matrix Market filename (extension .mtx) or open file-like object
+
+    Returns
+    -------
+    rows : int
+        Number of matrix rows.
+    cols : int
+        Number of matrix columns.
+    entries : int
+        Number of non-zero entries of a sparse matrix
+        or rows*cols for a dense matrix.
+    format : str
+        Either 'coordinate' or 'array'.
+    field : str
+        Either 'real', 'complex', 'pattern', or 'integer'.
+    symmetry : str
+        Either 'general', 'symmetric', 'skew-symmetric', or 'hermitian'.
+
+    Examples
+    --------
+    >>> from io import StringIO
+    >>> from scipy.io import mminfo
+
+    >>> text = '''%%MatrixMarket matrix coordinate real general
+    ...  5 5 7
+    ...  2 3 1.0
+    ...  3 4 2.0
+    ...  3 5 3.0
+    ...  4 1 4.0
+    ...  4 2 5.0
+    ...  4 3 6.0
+    ...  4 4 7.0
+    ... '''
+
+
+    ``mminfo(source)`` returns the number of rows, number of columns,
+    format, field type and symmetry attribute of the source file.
+
+    >>> mminfo(StringIO(text))
+    (5, 5, 7, 'coordinate', 'real', 'general')
+    """
+    return MMFile.info(source)
+
+# -----------------------------------------------------------------------------
+
+
+def mmread(source, *, spmatrix=_NoValue):
+    """
+    Reads the contents of a Matrix Market file-like 'source' into a matrix.
+
+    Parameters
+    ----------
+    source : str or file-like
+        Matrix Market filename (extensions .mtx, .mtz.gz)
+        or open file-like object.
+    spmatrix : bool, optional (default: True)
+        If ``True``, return sparse matrix. Otherwise return sparse array.
+
+        .. deprecated:: 1.18.0
+            The default value for `spmatrix` is changing to False in v1.20.
+            That means the default return value will be a sparse array.
+            Unless you use * instead of @, ** for matrix power, or you depend
+            on 2D shapes from e.g. ``A.sum(axis=0)`` it may not matter to you.
+            See :ref:`Migration from spmatrix to sparray `.
+
+    Returns
+    -------
+    a : ndarray or coo_array or coo_matrix
+        Dense or sparse array depending on the matrix format in the
+        Matrix Market file.
+
+    Examples
+    --------
+    >>> from io import StringIO
+    >>> from scipy.io import mmread
+
+    >>> text = '''%%MatrixMarket matrix coordinate real general
+    ...  5 5 7
+    ...  2 3 1.0
+    ...  3 4 2.0
+    ...  3 5 3.0
+    ...  4 1 4.0
+    ...  4 2 5.0
+    ...  4 3 6.0
+    ...  4 4 7.0
+    ... '''
+
+    ``mmread(source)`` returns the data as sparse matrix in COO format.
+
+    >>> m = mmread(StringIO(text), spmatrix=False)
+    >>> m
+    
+    >>> m.toarray()
+    array([[0., 0., 0., 0., 0.],
+           [0., 0., 1., 0., 0.],
+           [0., 0., 0., 2., 3.],
+           [4., 5., 6., 7., 0.],
+           [0., 0., 0., 0., 0.]])
+    """
+    return MMFile().read(source, spmatrix=spmatrix)
+
+# -----------------------------------------------------------------------------
+
+
+def mmwrite(target, a, comment='', field=None, precision=None, symmetry=None):
+    r"""
+    Writes the sparse or dense array `a` to Matrix Market file-like `target`.
+
+    Parameters
+    ----------
+    target : str or file-like
+        Matrix Market filename (extension .mtx) or open file-like object.
+    a : array like
+        Sparse or dense 2-D array.
+    comment : str, optional
+        Comments to be prepended to the Matrix Market file.
+    field : None or str, optional
+        Either 'real', 'complex', 'pattern', or 'integer'.
+    precision : None or int, optional
+        Number of digits to display for real or complex values.
+    symmetry : None or str, optional
+        Either 'general', 'symmetric', 'skew-symmetric', or 'hermitian'.
+        If symmetry is None the symmetry type of 'a' is determined by its
+        values.
+
+    Examples
+    --------
+    >>> from io import BytesIO
+    >>> import numpy as np
+    >>> from scipy.sparse import coo_array
+    >>> from scipy.io import mmwrite
+
+    Write a small NumPy array to a matrix market file.  The file will be
+    written in the ``'array'`` format.
+
+    >>> a = np.array([[1.0, 0, 0, 0], [0, 2.5, 0, 6.25]])
+    >>> target = BytesIO()
+    >>> mmwrite(target, a)
+    >>> print(target.getvalue().decode('latin1'))
+    %%MatrixMarket matrix array real general
+    %
+    2 4
+    1
+    0
+    0
+    2.5
+    0
+    0
+    0
+    6.25
+
+    Add a comment to the output file, and set the precision to 3.
+
+    >>> target = BytesIO()
+    >>> mmwrite(target, a, comment='\n Some test data.\n', precision=3)
+    >>> print(target.getvalue().decode('latin1'))
+    %%MatrixMarket matrix array real general
+    %
+    % Some test data.
+    %
+    2 4
+    1.00e+00
+    0.00e+00
+    0.00e+00
+    2.50e+00
+    0.00e+00
+    0.00e+00
+    0.00e+00
+    6.25e+00
+
+    Convert to a sparse matrix before calling ``mmwrite``.  This will
+    result in the output format being ``'coordinate'`` rather than
+    ``'array'``.
+
+    >>> target = BytesIO()
+    >>> mmwrite(target, coo_array(a), precision=3)
+    >>> print(target.getvalue().decode('latin1'))
+    %%MatrixMarket matrix coordinate real general
+    %
+    2 4 3
+    1 1 1.00e+00
+    2 2 2.50e+00
+    2 4 6.25e+00
+
+    Write a complex Hermitian array to a matrix market file.  Note that
+    only six values are actually written to the file; the other values
+    are implied by the symmetry.
+
+    >>> z = np.array([[3, 1+2j, 4-3j], [1-2j, 1, -5j], [4+3j, 5j, 2.5]])
+    >>> z
+    array([[ 3. +0.j,  1. +2.j,  4. -3.j],
+           [ 1. -2.j,  1. +0.j, -0. -5.j],
+           [ 4. +3.j,  0. +5.j,  2.5+0.j]])
+
+    >>> target = BytesIO()
+    >>> mmwrite(target, z, precision=2)
+    >>> print(target.getvalue().decode('latin1'))
+    %%MatrixMarket matrix array complex hermitian
+    %
+    3 3
+    3.0e+00 0.0e+00
+    1.0e+00 -2.0e+00
+    4.0e+00 3.0e+00
+    1.0e+00 0.0e+00
+    0.0e+00 5.0e+00
+    2.5e+00 0.0e+00
+
+    """
+    MMFile().write(target, a, comment, field, precision, symmetry)
+
+
+###############################################################################
+class MMFile:
+    __slots__ = ('_rows',
+                 '_cols',
+                 '_entries',
+                 '_format',
+                 '_field',
+                 '_symmetry')
+
+    @property
+    def rows(self):
+        return self._rows
+
+    @property
+    def cols(self):
+        return self._cols
+
+    @property
+    def entries(self):
+        return self._entries
+
+    @property
+    def format(self):
+        return self._format
+
+    @property
+    def field(self):
+        return self._field
+
+    @property
+    def symmetry(self):
+        return self._symmetry
+
+    @property
+    def has_symmetry(self):
+        return self._symmetry in (self.SYMMETRY_SYMMETRIC,
+                                  self.SYMMETRY_SKEW_SYMMETRIC,
+                                  self.SYMMETRY_HERMITIAN)
+
+    # format values
+    FORMAT_COORDINATE = 'coordinate'
+    FORMAT_ARRAY = 'array'
+    FORMAT_VALUES = (FORMAT_COORDINATE, FORMAT_ARRAY)
+
+    @classmethod
+    def _validate_format(self, format):
+        if format not in self.FORMAT_VALUES:
+            msg = f'unknown format type {format}, must be one of {self.FORMAT_VALUES}'
+            raise ValueError(msg)
+
+    # field values
+    FIELD_INTEGER = 'integer'
+    FIELD_UNSIGNED = 'unsigned-integer'
+    FIELD_REAL = 'real'
+    FIELD_COMPLEX = 'complex'
+    FIELD_PATTERN = 'pattern'
+    FIELD_VALUES = (FIELD_INTEGER, FIELD_UNSIGNED, FIELD_REAL, FIELD_COMPLEX,
+                    FIELD_PATTERN)
+
+    @classmethod
+    def _validate_field(self, field):
+        if field not in self.FIELD_VALUES:
+            msg = f'unknown field type {field}, must be one of {self.FIELD_VALUES}'
+            raise ValueError(msg)
+
+    # symmetry values
+    SYMMETRY_GENERAL = 'general'
+    SYMMETRY_SYMMETRIC = 'symmetric'
+    SYMMETRY_SKEW_SYMMETRIC = 'skew-symmetric'
+    SYMMETRY_HERMITIAN = 'hermitian'
+    SYMMETRY_VALUES = (SYMMETRY_GENERAL, SYMMETRY_SYMMETRIC,
+                       SYMMETRY_SKEW_SYMMETRIC, SYMMETRY_HERMITIAN)
+
+    @classmethod
+    def _validate_symmetry(self, symmetry):
+        if symmetry not in self.SYMMETRY_VALUES:
+            raise ValueError(f'unknown symmetry type {symmetry}, '
+                             f'must be one of {self.SYMMETRY_VALUES}')
+
+    DTYPES_BY_FIELD = {FIELD_INTEGER: 'intp',
+                       FIELD_UNSIGNED: 'uint64',
+                       FIELD_REAL: 'd',
+                       FIELD_COMPLEX: 'D',
+                       FIELD_PATTERN: 'd'}
+
+    # -------------------------------------------------------------------------
+    @staticmethod
+    def reader():
+        pass
+
+    # -------------------------------------------------------------------------
+    @staticmethod
+    def writer():
+        pass
+
+    # -------------------------------------------------------------------------
+    @classmethod
+    def info(self, source):
+        """
+        Return size, storage parameters from Matrix Market file-like 'source'.
+
+        Parameters
+        ----------
+        source : str or file-like
+            Matrix Market filename (extension .mtx) or open file-like object
+
+        Returns
+        -------
+        rows : int
+            Number of matrix rows.
+        cols : int
+            Number of matrix columns.
+        entries : int
+            Number of non-zero entries of a sparse matrix
+            or rows*cols for a dense matrix.
+        format : str
+            Either 'coordinate' or 'array'.
+        field : str
+            Either 'real', 'complex', 'pattern', or 'integer'.
+        symmetry : str
+            Either 'general', 'symmetric', 'skew-symmetric', or 'hermitian'.
+        """
+
+        stream, close_it = self._open(source)
+
+        try:
+
+            # read and validate header line
+            line = stream.readline()
+            mmid, matrix, format, field, symmetry = \
+                (asstr(part.strip()) for part in line.split())
+            if not mmid.startswith('%%MatrixMarket'):
+                raise ValueError('source is not in Matrix Market format')
+            if not matrix.lower() == 'matrix':
+                raise ValueError("Problem reading file header: " + line)
+
+            # http://math.nist.gov/MatrixMarket/formats.html
+            if format.lower() == 'array':
+                format = self.FORMAT_ARRAY
+            elif format.lower() == 'coordinate':
+                format = self.FORMAT_COORDINATE
+
+            # skip comments
+            # line.startswith('%')
+            while line:
+                if line.lstrip() and line.lstrip()[0] in ['%', 37]:
+                    line = stream.readline()
+                else:
+                    break
+
+            # skip empty lines
+            while not line.strip():
+                line = stream.readline()
+
+            split_line = line.split()
+            if format == self.FORMAT_ARRAY:
+                if not len(split_line) == 2:
+                    raise ValueError("Header line not of length 2: " +
+                                     line.decode('ascii'))
+                rows, cols = map(int, split_line)
+                entries = rows * cols
+            else:
+                if not len(split_line) == 3:
+                    raise ValueError("Header line not of length 3: " +
+                                     line.decode('ascii'))
+                rows, cols, entries = map(int, split_line)
+
+            return (rows, cols, entries, format, field.lower(),
+                    symmetry.lower())
+
+        finally:
+            if close_it:
+                stream.close()
+
+    # -------------------------------------------------------------------------
+    @staticmethod
+    def _open(filespec, mode='rb'):
+        """ Return an open file stream for reading based on source.
+
+        If source is a file name, open it (after trying to find it with mtx and
+        gzipped mtx extensions). Otherwise, just return source.
+
+        Parameters
+        ----------
+        filespec : str or file-like
+            String giving file name or file-like object
+        mode : str, optional
+            Mode with which to open file, if `filespec` is a file name.
+
+        Returns
+        -------
+        fobj : file-like
+            Open file-like object.
+        close_it : bool
+            True if the calling function should close this file when done,
+            false otherwise.
+        """
+        # If 'filespec' is path-like (str, pathlib.Path, os.DirEntry, other class
+        # implementing a '__fspath__' method), try to convert it to str. If this
+        # fails by throwing a 'TypeError', assume it's an open file handle and
+        # return it as-is.
+        try:
+            filespec = os.fspath(filespec)
+        except TypeError:
+            return filespec, False
+
+        # 'filespec' is definitely a str now
+
+        # open for reading
+        if mode[0] == 'r':
+
+            # determine filename plus extension
+            if not os.path.isfile(filespec):
+                if os.path.isfile(filespec+'.mtx'):
+                    filespec = filespec + '.mtx'
+                elif os.path.isfile(filespec+'.mtx.gz'):
+                    filespec = filespec + '.mtx.gz'
+                elif os.path.isfile(filespec+'.mtx.bz2'):
+                    filespec = filespec + '.mtx.bz2'
+            # open filename
+            if filespec.endswith('.gz'):
+                import gzip
+                stream = gzip.open(filespec, mode)
+            elif filespec.endswith('.bz2'):
+                import bz2
+                stream = bz2.BZ2File(filespec, 'rb')
+            else:
+                stream = open(filespec, mode)
+
+        # open for writing
+        else:
+            if filespec[-4:] != '.mtx':
+                filespec = filespec + '.mtx'
+            stream = open(filespec, mode)
+
+        return stream, True
+
+    # -------------------------------------------------------------------------
+    @staticmethod
+    def _get_symmetry(a):
+        m, n = a.shape
+        if m != n:
+            return MMFile.SYMMETRY_GENERAL
+        issymm = True
+        isskew = True
+        isherm = a.dtype.char in 'FD'
+
+        # sparse input
+        if issparse(a):
+            # check if number of nonzero entries of lower and upper triangle
+            # matrix are equal
+            a = a.tocoo()
+            (row, col) = a.nonzero()
+            if (row < col).sum() != (row > col).sum():
+                return MMFile.SYMMETRY_GENERAL
+
+            # define iterator over symmetric pair entries
+            a = a.todok()
+
+            def symm_iterator():
+                for ((i, j), aij) in a.items():
+                    if i > j:
+                        aji = a[j, i]
+                        yield (aij, aji, False)
+                    elif i == j:
+                        yield (aij, aij, True)
+
+        # non-sparse input
+        else:
+            # define iterator over symmetric pair entries
+            def symm_iterator():
+                for j in range(n):
+                    for i in range(j, n):
+                        aij, aji = a[i][j], a[j][i]
+                        yield (aij, aji, i == j)
+
+        # check for symmetry
+        # yields aij, aji, is_diagonal
+        for (aij, aji, is_diagonal) in symm_iterator():
+            if isskew and is_diagonal and aij != 0:
+                isskew = False
+            else:
+                if issymm and aij != aji:
+                    issymm = False
+                with np.errstate(over="ignore"):
+                    # This can give a warning for uint dtypes, so silence that
+                    if isskew and aij != -aji:
+                        isskew = False
+                if isherm and aij != conj(aji):
+                    isherm = False
+            if not (issymm or isskew or isherm):
+                break
+
+        # return symmetry value
+        if issymm:
+            return MMFile.SYMMETRY_SYMMETRIC
+        if isskew:
+            return MMFile.SYMMETRY_SKEW_SYMMETRIC
+        if isherm:
+            return MMFile.SYMMETRY_HERMITIAN
+        return MMFile.SYMMETRY_GENERAL
+
+    # -------------------------------------------------------------------------
+    @staticmethod
+    def _field_template(field, precision):
+        return {MMFile.FIELD_REAL: '%%.%ie\n' % precision,
+                MMFile.FIELD_INTEGER: '%i\n',
+                MMFile.FIELD_UNSIGNED: '%u\n',
+                MMFile.FIELD_COMPLEX: '%%.%ie %%.%ie\n' %
+                    (precision, precision)
+                }.get(field, None)
+
+    # -------------------------------------------------------------------------
+    def __init__(self, **kwargs):
+        self._init_attrs(**kwargs)
+
+    # -------------------------------------------------------------------------
+    def read(self, source, *, spmatrix=_NoValue):
+        """
+        Reads the contents of a Matrix Market file-like 'source' into a matrix.
+
+        Parameters
+        ----------
+        source : str or file-like
+            Matrix Market filename (extensions .mtx, .mtz.gz)
+            or open file object.
+        spmatrix : bool, optional (default: True)
+            If ``True``, return sparse matrix. Otherwise return sparse array.
+
+            .. deprecated:: 1.18.0
+                The default value for `spmatrix` is changing to False in v1.20.
+                That means the default return value will be a sparse array.
+                Unless you use * instead of @, ** for matrix power, or you depend
+                on 2D shapes from e.g. ``A.sum(axis=0)`` it may not matter to you.
+                See :ref:`Migration from spmatrix to sparray `.
+
+        Returns
+        -------
+        a : ndarray or coo_array or coo_matrix
+            Dense or sparse array depending on the matrix format in the
+            Matrix Market file.
+        """
+        stream, close_it = self._open(source)
+
+        try:
+            self._parse_header(stream)
+            data = self._parse_body(stream)
+
+        finally:
+            if close_it:
+                stream.close()
+
+        if spmatrix is _NoValue:
+            msg = """The default value for `spmatrix` is changing to `False` in v1.20.
+             That means the default return type will be a sparse array.
+             Unless you use * instead of @, ** for matrix power, or you depend
+             on 2D shapes from e.g. `A.sum(axis=0)` it may not matter to you.
+             See the spmatrix to sparray migration guide for details.
+             https://docs.scipy.org/doc/scipy/reference/sparse.migration_to_sparray.html
+             """
+            prefixes = (os.path.dirname(__file__),)
+            warn(msg, DeprecationWarning, skip_file_prefixes=prefixes)
+            spmatrix = True
+
+        if spmatrix and isinstance(data, coo_array):
+            data = coo_matrix(data)
+        return data
+
+
+    # -------------------------------------------------------------------------
+    def write(self, target, a, comment='', field=None, precision=None,
+              symmetry=None):
+        """
+        Writes sparse or dense array `a` to Matrix Market file-like `target`.
+
+        Parameters
+        ----------
+        target : str or file-like
+            Matrix Market filename (extension .mtx) or open file-like object.
+        a : array like
+            Sparse or dense 2-D array.
+        comment : str, optional
+            Comments to be prepended to the Matrix Market file.
+        field : None or str, optional
+            Either 'real', 'complex', 'pattern', or 'integer'.
+        precision : None or int, optional
+            Number of digits to display for real or complex values.
+        symmetry : None or str, optional
+            Either 'general', 'symmetric', 'skew-symmetric', or 'hermitian'.
+            If symmetry is None the symmetry type of 'a' is determined by its
+            values.
+        """
+
+        stream, close_it = self._open(target, 'wb')
+
+        try:
+            self._write(stream, a, comment, field, precision, symmetry)
+
+        finally:
+            if close_it:
+                stream.close()
+            else:
+                stream.flush()
+
+    # -------------------------------------------------------------------------
+    def _init_attrs(self, **kwargs):
+        """
+        Initialize each attributes with the corresponding keyword arg value
+        or a default of None
+        """
+
+        attrs = self.__class__.__slots__
+        public_attrs = [attr[1:] for attr in attrs]
+        invalid_keys = set(kwargs.keys()) - set(public_attrs)
+
+        if invalid_keys:
+            raise ValueError(f"found {tuple(invalid_keys)} invalid keyword "
+                             f"arguments, please only use {public_attrs}")
+
+        for attr in attrs:
+            setattr(self, attr, kwargs.get(attr[1:], None))
+
+    # -------------------------------------------------------------------------
+    def _parse_header(self, stream):
+        rows, cols, entries, format, field, symmetry = \
+            self.__class__.info(stream)
+        self._init_attrs(rows=rows, cols=cols, entries=entries, format=format,
+                         field=field, symmetry=symmetry)
+
+    # -------------------------------------------------------------------------
+    def _parse_body(self, stream):
+        rows, cols, entries, format, field, symm = (self.rows, self.cols,
+                                                    self.entries, self.format,
+                                                    self.field, self.symmetry)
+
+        dtype = self.DTYPES_BY_FIELD.get(field, None)
+
+        has_symmetry = self.has_symmetry
+        is_integer = field == self.FIELD_INTEGER
+        is_unsigned_integer = field == self.FIELD_UNSIGNED
+        is_complex = field == self.FIELD_COMPLEX
+        is_skew = symm == self.SYMMETRY_SKEW_SYMMETRIC
+        is_herm = symm == self.SYMMETRY_HERMITIAN
+        is_pattern = field == self.FIELD_PATTERN
+
+        if format == self.FORMAT_ARRAY:
+            a = zeros((rows, cols), dtype=dtype)
+            line = 1
+            i, j = 0, 0
+            if is_skew:
+                a[i, j] = 0
+                if i < rows - 1:
+                    i += 1
+            while line:
+                line = stream.readline()
+                # line.startswith('%')
+                if not line or line[0] in ['%', 37] or not line.strip():
+                    continue
+                if is_integer:
+                    aij = int(line)
+                elif is_unsigned_integer:
+                    aij = int(line)
+                elif is_complex:
+                    aij = complex(*map(float, line.split()))
+                else:
+                    aij = float(line)
+                a[i, j] = aij
+                if has_symmetry and i != j:
+                    if is_skew:
+                        a[j, i] = -aij
+                    elif is_herm:
+                        a[j, i] = conj(aij)
+                    else:
+                        a[j, i] = aij
+                if i < rows-1:
+                    i = i + 1
+                else:
+                    j = j + 1
+                    if not has_symmetry:
+                        i = 0
+                    else:
+                        i = j
+                        if is_skew:
+                            a[i, j] = 0
+                            if i < rows-1:
+                                i += 1
+
+            if is_skew:
+                if not (i in [0, j] and j == cols - 1):
+                    raise ValueError("Parse error, did not read all lines.")
+            else:
+                if not (i in [0, j] and j == cols):
+                    raise ValueError("Parse error, did not read all lines.")
+
+        elif format == self.FORMAT_COORDINATE:
+            # Read sparse COOrdinate format
+
+            if entries == 0:
+                # empty matrix
+                return coo_array((rows, cols), dtype=dtype)
+
+            I = zeros(entries, dtype='intc')
+            J = zeros(entries, dtype='intc')
+            if is_pattern:
+                V = ones(entries, dtype='int8')
+            elif is_integer:
+                V = zeros(entries, dtype='intp')
+            elif is_unsigned_integer:
+                V = zeros(entries, dtype='uint64')
+            elif is_complex:
+                V = zeros(entries, dtype='complex')
+            else:
+                V = zeros(entries, dtype='float')
+
+            entry_number = 0
+            for line in stream:
+                # line.startswith('%')
+                if not line or line[0] in ['%', 37] or not line.strip():
+                    continue
+
+                if entry_number+1 > entries:
+                    raise ValueError("'entries' in header is smaller than "
+                                     "number of entries")
+                l = line.split()
+                I[entry_number], J[entry_number] = map(int, l[:2])
+
+                if not is_pattern:
+                    if is_integer:
+                        V[entry_number] = int(l[2])
+                    elif is_unsigned_integer:
+                        V[entry_number] = int(l[2])
+                    elif is_complex:
+                        V[entry_number] = complex(*map(float, l[2:]))
+                    else:
+                        V[entry_number] = float(l[2])
+                entry_number += 1
+            if entry_number < entries:
+                raise ValueError("'entries' in header is larger than "
+                                 "number of entries")
+
+            I -= 1  # adjust indices (base 1 -> base 0)
+            J -= 1
+
+            if has_symmetry:
+                mask = (I != J)       # off diagonal mask
+                od_I = I[mask]
+                od_J = J[mask]
+                od_V = V[mask]
+
+                I = concatenate((I, od_J))
+                J = concatenate((J, od_I))
+
+                if is_skew:
+                    od_V *= -1
+                elif is_herm:
+                    od_V = od_V.conjugate()
+
+                V = concatenate((V, od_V))
+
+            a = coo_array((V, (I, J)), shape=(rows, cols), dtype=dtype)
+        else:
+            raise NotImplementedError(format)
+
+        return a
+
+    #  ------------------------------------------------------------------------
+    def _write(self, stream, a, comment='', field=None, precision=None,
+               symmetry=None):
+        if isinstance(a, list) or isinstance(a, ndarray) or \
+           isinstance(a, tuple) or hasattr(a, '__array__'):
+            rep = self.FORMAT_ARRAY
+            a = asarray(a)
+            if len(a.shape) != 2:
+                raise ValueError('Expected 2 dimensional array')
+            rows, cols = a.shape
+
+            if field is not None:
+
+                if field == self.FIELD_INTEGER:
+                    if not can_cast(a.dtype, 'intp'):
+                        raise OverflowError("mmwrite does not support integer "
+                                            "dtypes larger than native 'intp'.")
+                    a = a.astype('intp')
+                elif field == self.FIELD_REAL:
+                    if a.dtype.char not in 'fd':
+                        a = a.astype('d')
+                elif field == self.FIELD_COMPLEX:
+                    if a.dtype.char not in 'FD':
+                        a = a.astype('D')
+
+        else:
+            if not issparse(a):
+                raise ValueError(f'unknown matrix type: {type(a)}')
+
+            rep = 'coordinate'
+            rows, cols = a.shape
+
+        typecode = a.dtype.char
+
+        if precision is None:
+            if typecode in 'fF':
+                precision = 8
+            else:
+                precision = 16
+        if field is None:
+            kind = a.dtype.kind
+            if kind == 'i':
+                if not can_cast(a.dtype, 'intp'):
+                    raise OverflowError("mmwrite does not support integer "
+                                        "dtypes larger than native 'intp'.")
+                field = 'integer'
+            elif kind == 'f':
+                field = 'real'
+            elif kind == 'c':
+                field = 'complex'
+            elif kind == 'u':
+                field = 'unsigned-integer'
+            else:
+                raise TypeError('unexpected dtype kind ' + kind)
+
+        if symmetry is None:
+            symmetry = self._get_symmetry(a)
+
+        # validate rep, field, and symmetry
+        self.__class__._validate_format(rep)
+        self.__class__._validate_field(field)
+        self.__class__._validate_symmetry(symmetry)
+
+        # write initial header line
+        data = f'%%MatrixMarket matrix {rep} {field} {symmetry}\n'
+        stream.write(data.encode('latin1'))
+
+        # write comments
+        for line in comment.split('\n'):
+            data = f'%{line}\n'
+            stream.write(data.encode('latin1'))
+
+        template = self._field_template(field, precision)
+        # write dense format
+        if rep == self.FORMAT_ARRAY:
+            # write shape spec
+            data = '%i %i\n' % (rows, cols)
+            stream.write(data.encode('latin1'))
+
+            if field in (self.FIELD_INTEGER, self.FIELD_REAL,
+                         self.FIELD_UNSIGNED):
+                if symmetry == self.SYMMETRY_GENERAL:
+                    for j in range(cols):
+                        for i in range(rows):
+                            data = template % a[i, j]
+                            stream.write(data.encode('latin1'))
+
+                elif symmetry == self.SYMMETRY_SKEW_SYMMETRIC:
+                    for j in range(cols):
+                        for i in range(j + 1, rows):
+                            data = template % a[i, j]
+                            stream.write(data.encode('latin1'))
+
+                else:
+                    for j in range(cols):
+                        for i in range(j, rows):
+                            data = template % a[i, j]
+                            stream.write(data.encode('latin1'))
+
+            elif field == self.FIELD_COMPLEX:
+
+                if symmetry == self.SYMMETRY_GENERAL:
+                    for j in range(cols):
+                        for i in range(rows):
+                            aij = a[i, j]
+                            data = template % (real(aij), imag(aij))
+                            stream.write(data.encode('latin1'))
+                else:
+                    for j in range(cols):
+                        for i in range(j, rows):
+                            aij = a[i, j]
+                            data = template % (real(aij), imag(aij))
+                            stream.write(data.encode('latin1'))
+
+            elif field == self.FIELD_PATTERN:
+                raise ValueError('pattern type inconsisted with dense format')
+
+            else:
+                raise TypeError(f'Unknown field type {field}')
+
+        # write sparse format
+        else:
+            coo = a.tocoo()  # convert to COOrdinate format
+
+            # if symmetry format used, remove values above main diagonal
+            if symmetry != self.SYMMETRY_GENERAL:
+                lower_triangle_mask = coo.row >= coo.col
+                coo = coo_array((coo.data[lower_triangle_mask],
+                                (coo.row[lower_triangle_mask],
+                                 coo.col[lower_triangle_mask])),
+                                shape=coo.shape)
+
+            # write shape spec
+            data = '%i %i %i\n' % (rows, cols, coo.nnz)
+            stream.write(data.encode('latin1'))
+
+            template = self._field_template(field, precision-1)
+
+            if field == self.FIELD_PATTERN:
+                for r, c in zip(coo.row+1, coo.col+1):
+                    data = "%i %i\n" % (r, c)
+                    stream.write(data.encode('latin1'))
+            elif field in (self.FIELD_INTEGER, self.FIELD_REAL,
+                           self.FIELD_UNSIGNED):
+                for r, c, d in zip(coo.row+1, coo.col+1, coo.data):
+                    data = ("%i %i " % (r, c)) + (template % d)
+                    stream.write(data.encode('latin1'))
+            elif field == self.FIELD_COMPLEX:
+                for r, c, d in zip(coo.row+1, coo.col+1, coo.data):
+                    data = ("%i %i " % (r, c)) + (template % (d.real, d.imag))
+                    stream.write(data.encode('latin1'))
+            else:
+                raise TypeError(f'Unknown field type {field}')
+
+
+def _is_fromfile_compatible(stream):
+    """
+    Check whether `stream` is compatible with numpy.fromfile.
+
+    Passing a gzipped file object to ``fromfile/fromstring`` doesn't work with
+    Python 3.
+    """
+
+    bad_cls = []
+    try:
+        import gzip
+        bad_cls.append(gzip.GzipFile)
+    except ImportError:
+        pass
+    try:
+        import bz2
+        bad_cls.append(bz2.BZ2File)
+    except ImportError:
+        pass
+
+    bad_cls = tuple(bad_cls)
+    return not isinstance(stream, bad_cls)
diff --git a/.venv/lib/python3.12/site-packages/scipy/io/_netcdf.py b/.venv/lib/python3.12/site-packages/scipy/io/_netcdf.py
new file mode 100644
index 0000000000000000000000000000000000000000..a37993b3cc7dc2618bbbfb500fed60c691599a7e
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/io/_netcdf.py
@@ -0,0 +1,1103 @@
+"""
+NetCDF reader/writer module.
+
+This module is used to read and create NetCDF files. NetCDF files are
+accessed through the `netcdf_file` object. Data written to and from NetCDF
+files are contained in `netcdf_variable` objects. Attributes are given
+as member variables of the `netcdf_file` and `netcdf_variable` objects.
+
+This module implements the Scientific.IO.NetCDF API to read and create
+NetCDF files. The same API is also used in the PyNIO and pynetcdf
+modules, allowing these modules to be used interchangeably when working
+with NetCDF files.
+
+Only NetCDF3 is supported here; for NetCDF4 see
+`netCDF4-python `__,
+which has a similar API.
+
+"""
+
+# TODO:
+# * properly implement ``_FillValue``.
+# * fix character variables.
+# * implement PAGESIZE for Python 2.6?
+
+# The Scientific.IO.NetCDF API allows attributes to be added directly to
+# instances of ``netcdf_file`` and ``netcdf_variable``. To differentiate
+# between user-set attributes and instance attributes, user-set attributes
+# are automatically stored in the ``_attributes`` attribute by overloading
+#``__setattr__``. This is the reason why the code sometimes uses
+#``obj.__dict__['key'] = value``, instead of simply ``obj.key = value``;
+# otherwise the key would be inserted into userspace attributes.
+
+
+__all__ = ['netcdf_file', 'netcdf_variable']
+
+
+import warnings
+import weakref
+from operator import mul
+
+import mmap as mm
+
+import numpy as np
+from numpy import frombuffer, dtype, empty, array, asarray
+from numpy import little_endian as LITTLE_ENDIAN
+from functools import reduce
+
+
+ABSENT = b'\x00\x00\x00\x00\x00\x00\x00\x00'
+ZERO = b'\x00\x00\x00\x00'
+NC_BYTE = b'\x00\x00\x00\x01'
+NC_CHAR = b'\x00\x00\x00\x02'
+NC_SHORT = b'\x00\x00\x00\x03'
+NC_INT = b'\x00\x00\x00\x04'
+NC_FLOAT = b'\x00\x00\x00\x05'
+NC_DOUBLE = b'\x00\x00\x00\x06'
+NC_DIMENSION = b'\x00\x00\x00\n'
+NC_VARIABLE = b'\x00\x00\x00\x0b'
+NC_ATTRIBUTE = b'\x00\x00\x00\x0c'
+FILL_BYTE = b'\x81'
+FILL_CHAR = b'\x00'
+FILL_SHORT = b'\x80\x01'
+FILL_INT = b'\x80\x00\x00\x01'
+FILL_FLOAT = b'\x7C\xF0\x00\x00'
+FILL_DOUBLE = b'\x47\x9E\x00\x00\x00\x00\x00\x00'
+
+TYPEMAP = {NC_BYTE: ('b', 1),
+           NC_CHAR: ('c', 1),
+           NC_SHORT: ('h', 2),
+           NC_INT: ('i', 4),
+           NC_FLOAT: ('f', 4),
+           NC_DOUBLE: ('d', 8)}
+
+FILLMAP = {NC_BYTE: FILL_BYTE,
+           NC_CHAR: FILL_CHAR,
+           NC_SHORT: FILL_SHORT,
+           NC_INT: FILL_INT,
+           NC_FLOAT: FILL_FLOAT,
+           NC_DOUBLE: FILL_DOUBLE}
+
+REVERSE = {('b', 1): NC_BYTE,
+           ('B', 1): NC_CHAR,
+           ('c', 1): NC_CHAR,
+           ('h', 2): NC_SHORT,
+           ('i', 4): NC_INT,
+           ('f', 4): NC_FLOAT,
+           ('d', 8): NC_DOUBLE,
+
+           # these come from asarray(1).dtype.char and asarray('foo').dtype.char,
+           # used when getting the types from generic attributes.
+           ('l', 4): NC_INT,
+           ('S', 1): NC_CHAR}
+
+
+class netcdf_file:
+    """
+    A file object for NetCDF data.
+
+    A `netcdf_file` object has two standard attributes: `dimensions` and
+    `variables`. The values of both are dictionaries, mapping dimension
+    names to their associated lengths and variable names to variables,
+    respectively. Application programs should never modify these
+    dictionaries.
+
+    All other attributes correspond to global attributes defined in the
+    NetCDF file. Global file attributes are created by assigning to an
+    attribute of the `netcdf_file` object.
+
+    Parameters
+    ----------
+    filename : str or file-like
+        string -> filename
+    mode : {'r', 'w', 'a'}, optional
+        read-write-append mode, default is 'r'
+    mmap : None or bool, optional
+        Whether to mmap `filename` when reading.  Default is True
+        when `filename` is a file name, False when `filename` is a
+        file-like object. Note that when mmap is in use, data arrays
+        returned refer directly to the mmapped data on disk, and the
+        file cannot be closed as long as references to it exist.
+    version : {1, 2}, optional
+        version of netcdf to read / write, where 1 means *Classic
+        format* and 2 means *64-bit offset format*.  Default is 1.  See
+        `here `__
+        for more info.
+    maskandscale : bool, optional
+        Whether to automatically scale and/or mask data based on attributes.
+        Default is False.
+
+    Notes
+    -----
+    This module is derived from
+    `pupynere `_.
+    The major advantage of this module over other modules is that it doesn't
+    require the code to be linked to the NetCDF libraries. However, for a more
+    recent version of the NetCDF standard and additional features, please consider
+    the permissively-licensed
+    `netcdf4-python `_.
+
+    NetCDF files are a self-describing binary data format. The file contains
+    metadata that describes the dimensions and variables in the file. More
+    details about NetCDF files can be found `here
+    `__. There
+    are three main sections to a NetCDF data structure:
+
+    1. Dimensions
+    2. Variables
+    3. Attributes
+
+    The dimensions section records the name and length of each dimension used
+    by the variables. The variables would then indicate which dimensions it
+    uses and any attributes such as data units, along with containing the data
+    values for the variable. It is good practice to include a
+    variable that is the same name as a dimension to provide the values for
+    that axis. Lastly, the attributes section would contain additional
+    information such as the name of the file creator or the instrument used to
+    collect the data.
+
+    When writing data to a NetCDF file, there is often the need to indicate the
+    'record dimension'. A record dimension is the unbounded dimension for a
+    variable. For example, a temperature variable may have dimensions of
+    latitude, longitude and time. If one wants to add more temperature data to
+    the NetCDF file as time progresses, then the temperature variable should
+    have the time dimension flagged as the record dimension.
+
+    In addition, the NetCDF file header contains the position of the data in
+    the file, so access can be done in an efficient manner without loading
+    unnecessary data into memory. It uses the ``mmap`` module to create
+    Numpy arrays mapped to the data on disk, for the same purpose.
+
+    Note that when `netcdf_file` is used to open a file with mmap=True
+    (default for read-only), arrays returned by it refer to data
+    directly on the disk. The file should not be closed, and cannot be cleanly
+    closed when asked, if such arrays are alive. You may want to copy data arrays
+    obtained from mmapped NetCDF file if they are to be processed after the file
+    is closed, see the example below.
+
+    Examples
+    --------
+    To create a NetCDF file:
+
+    >>> from scipy.io import netcdf_file
+    >>> import numpy as np
+    >>> f = netcdf_file('simple.nc', 'w')
+    >>> f.history = 'Created for a test'
+    >>> f.createDimension('time', 10)
+    >>> time = f.createVariable('time', 'i', ('time',))
+    >>> time[:] = np.arange(10)
+    >>> time.units = 'days since 2008-01-01'
+    >>> f.close()
+
+    Note the assignment of ``arange(10)`` to ``time[:]``.  Exposing the slice
+    of the time variable allows for the data to be set in the object, rather
+    than letting ``arange(10)`` overwrite the ``time`` variable.
+
+    To read the NetCDF file we just created:
+
+    >>> from scipy.io import netcdf_file
+    >>> f = netcdf_file('simple.nc', 'r')
+    >>> print(f.history)
+    b'Created for a test'
+    >>> time = f.variables['time']
+    >>> print(time.units)
+    b'days since 2008-01-01'
+    >>> print(time.shape)
+    (10,)
+    >>> print(time[-1])
+    9
+
+    NetCDF files, when opened read-only, return arrays that refer
+    directly to memory-mapped data on disk:
+
+    >>> data = time[:]
+
+    If the data is to be processed after the file is closed, it needs
+    to be copied to main memory:
+
+    >>> data = time[:].copy()
+    >>> del time
+    >>> f.close()
+    >>> data.mean()
+    4.5
+
+    A NetCDF file can also be used as context manager:
+
+    >>> from scipy.io import netcdf_file
+    >>> with netcdf_file('simple.nc', 'r') as f:
+    ...     print(f.history)
+    b'Created for a test'
+
+    """
+    def __init__(self, filename, mode='r', mmap=None, version=1,
+                 maskandscale=False):
+        """Initialize netcdf_file from fileobj (str or file-like)."""
+        if mode not in 'rwa':
+            raise ValueError("Mode must be either 'r', 'w' or 'a'.")
+
+        if hasattr(filename, 'seek'):  # file-like
+            self.fp = filename
+            self.filename = 'None'
+            if mmap is None:
+                mmap = False
+            elif mmap and not hasattr(filename, 'fileno'):
+                raise ValueError('Cannot use file object for mmap')
+        else:  # maybe it's a string
+            self.filename = filename
+            omode = 'r+' if mode == 'a' else mode
+            self.fp = open(self.filename, f'{omode}b')
+            if mmap is None:
+                mmap = True
+
+        if mode != 'r':
+            # Cannot read write-only files
+            mmap = False
+
+        self.use_mmap = mmap
+        self.mode = mode
+        self.version_byte = version
+        self.maskandscale = maskandscale
+
+        self.dimensions = {}
+        self.variables = {}
+
+        self._dims = []
+        self._recs = 0
+        self._recsize = 0
+
+        self._mm = None
+        self._mm_buf = None
+        if self.use_mmap:
+            self._mm = mm.mmap(self.fp.fileno(), 0, access=mm.ACCESS_READ)
+            self._mm_buf = np.frombuffer(self._mm, dtype=np.int8)
+
+        self._attributes = {}
+
+        if mode in 'ra':
+            self._read()
+
+    def __setattr__(self, attr, value):
+        # Store user defined attributes in a separate dict,
+        # so we can save them to file later.
+        try:
+            self._attributes[attr] = value
+        except AttributeError:
+            pass
+        self.__dict__[attr] = value
+
+    def close(self):
+        """Closes the NetCDF file."""
+        if hasattr(self, 'fp') and not self.fp.closed:
+            try:
+                self.flush()
+            finally:
+                self.variables = {}
+                if self._mm_buf is not None:
+                    ref = weakref.ref(self._mm_buf)
+                    self._mm_buf = None
+                    if ref() is None:
+                        # self._mm_buf is gc'd, and we can close the mmap
+                        self._mm.close()
+                    else:
+                        # we cannot close self._mm, since self._mm_buf is
+                        # alive and there may still be arrays referring to it
+                        warnings.warn(
+                            "Cannot close a netcdf_file opened with mmap=True, when "
+                            "netcdf_variables or arrays referring to its data still "
+                            "exist. All data arrays obtained from such files refer "
+                            "directly to data on disk, and must be copied before the "
+                            "file can be cleanly closed. "
+                            "(See netcdf_file docstring for more information on mmap.)",
+                            category=RuntimeWarning, stacklevel=2,
+                        )
+                self._mm = None
+                self.fp.close()
+    __del__ = close
+
+    def __enter__(self):
+        return self
+
+    def __exit__(self, type, value, traceback):
+        self.close()
+
+    def createDimension(self, name, length):
+        """
+        Adds a dimension to the Dimension section of the NetCDF data structure.
+
+        Note that this function merely adds a new dimension that the variables can
+        reference. The values for the dimension, if desired, should be added as
+        a variable using `createVariable`, referring to this dimension.
+
+        Parameters
+        ----------
+        name : str
+            Name of the dimension (Eg, 'lat' or 'time').
+        length : int
+            Length of the dimension.
+
+        See Also
+        --------
+        createVariable
+
+        """
+        if length is None and self._dims:
+            raise ValueError("Only first dimension may be unlimited!")
+
+        self.dimensions[name] = length
+        self._dims.append(name)
+
+    def createVariable(self, name, type, dimensions):
+        """
+        Create an empty variable for the `netcdf_file` object, specifying its data
+        type and the dimensions it uses.
+
+        Parameters
+        ----------
+        name : str
+            Name of the new variable.
+        type : dtype or str
+            Data type of the variable.
+        dimensions : sequence of str
+            List of the dimension names used by the variable, in the desired order.
+
+        Returns
+        -------
+        variable : netcdf_variable
+            The newly created ``netcdf_variable`` object.
+            This object has also been added to the `netcdf_file` object as well.
+
+        See Also
+        --------
+        createDimension
+
+        Notes
+        -----
+        Any dimensions to be used by the variable should already exist in the
+        NetCDF data structure or should be created by `createDimension` prior to
+        creating the NetCDF variable.
+
+        """
+        shape = tuple([self.dimensions[dim] for dim in dimensions])
+        shape_ = tuple([dim or 0 for dim in shape])  # replace None with 0 for NumPy
+
+        type = dtype(type)
+        typecode, size = type.char, type.itemsize
+        if (typecode, size) not in REVERSE:
+            raise ValueError(f"NetCDF 3 does not support type {type}")
+
+        # convert to big endian always for NetCDF 3
+        data = empty(shape_, dtype=type.newbyteorder("B"))
+        self.variables[name] = netcdf_variable(
+                data, typecode, size, shape, dimensions,
+                maskandscale=self.maskandscale)
+        return self.variables[name]
+
+    def flush(self):
+        """
+        Perform a sync-to-disk flush if the `netcdf_file` object is in write mode.
+
+        See Also
+        --------
+        sync : Identical function
+
+        """
+        if hasattr(self, 'mode') and self.mode in 'wa':
+            self._write()
+    sync = flush
+
+    def _write(self):
+        self.fp.seek(0)
+        self.fp.write(b'CDF')
+        self.fp.write(array(self.version_byte, '>b').tobytes())
+
+        # Write headers and data.
+        self._write_numrecs()
+        self._write_dim_array()
+        self._write_gatt_array()
+        self._write_var_array()
+
+    def _write_numrecs(self):
+        # Get highest record count from all record variables.
+        for var in self.variables.values():
+            if var.isrec and len(var.data) > self._recs:
+                self.__dict__['_recs'] = len(var.data)
+        self._pack_int(self._recs)
+
+    def _write_dim_array(self):
+        if self.dimensions:
+            self.fp.write(NC_DIMENSION)
+            self._pack_int(len(self.dimensions))
+            for name in self._dims:
+                self._pack_string(name)
+                length = self.dimensions[name]
+                self._pack_int(length or 0)  # replace None with 0 for record dimension
+        else:
+            self.fp.write(ABSENT)
+
+    def _write_gatt_array(self):
+        self._write_att_array(self._attributes)
+
+    def _write_att_array(self, attributes):
+        if attributes:
+            self.fp.write(NC_ATTRIBUTE)
+            self._pack_int(len(attributes))
+            for name, values in attributes.items():
+                self._pack_string(name)
+                self._write_att_values(values)
+        else:
+            self.fp.write(ABSENT)
+
+    def _write_var_array(self):
+        if self.variables:
+            self.fp.write(NC_VARIABLE)
+            self._pack_int(len(self.variables))
+
+            # Sort variable names non-recs first, then recs.
+            def sortkey(n):
+                v = self.variables[n]
+                if v.isrec:
+                    return (-1,)
+                return v._shape
+            variables = sorted(self.variables, key=sortkey, reverse=True)
+
+            # Set the metadata for all variables.
+            for name in variables:
+                self._write_var_metadata(name)
+            # Now that we have the metadata, we know the vsize of
+            # each record variable, so we can calculate recsize.
+            self.__dict__['_recsize'] = sum([
+                    var._vsize for var in self.variables.values()
+                    if var.isrec])
+            # Set the data for all variables.
+            for name in variables:
+                self._write_var_data(name)
+        else:
+            self.fp.write(ABSENT)
+
+    def _write_var_metadata(self, name):
+        var = self.variables[name]
+
+        self._pack_string(name)
+        self._pack_int(len(var.dimensions))
+        for dimname in var.dimensions:
+            dimid = self._dims.index(dimname)
+            self._pack_int(dimid)
+
+        self._write_att_array(var._attributes)
+
+        nc_type = REVERSE[var.typecode(), var.itemsize()]
+        self.fp.write(nc_type)
+
+        if not var.isrec:
+            vsize = var.data.size * var.data.itemsize
+            vsize += -vsize % 4
+        else:  # record variable
+            try:
+                vsize = var.data[0].size * var.data.itemsize
+            except IndexError:
+                vsize = 0
+            rec_vars = len([v for v in self.variables.values()
+                            if v.isrec])
+            if rec_vars > 1:
+                vsize += -vsize % 4
+        self.variables[name].__dict__['_vsize'] = vsize
+        self._pack_int(vsize)
+
+        # Pack a bogus begin, and set the real value later.
+        self.variables[name].__dict__['_begin'] = self.fp.tell()
+        self._pack_begin(0)
+
+    def _write_var_data(self, name):
+        var = self.variables[name]
+
+        # Set begin in file header.
+        the_beguine = self.fp.tell()
+        self.fp.seek(var._begin)
+        self._pack_begin(the_beguine)
+        self.fp.seek(the_beguine)
+
+        # Write data.
+        if not var.isrec:
+            self.fp.write(var.data.tobytes())
+            count = var.data.size * var.data.itemsize
+            self._write_var_padding(var, var._vsize - count)
+        else:  # record variable
+            # Handle rec vars with shape[0] < nrecs.
+            if self._recs > len(var.data):
+                shape = (self._recs,) + var.data.shape[1:]
+                # Resize in-place does not always work since
+                # the array might not be single-segment
+                try:
+                    var.data.resize(shape)
+                except ValueError:
+                    dtype = var.data.dtype
+                    var.__dict__['data'] = np.resize(var.data, shape).astype(dtype)
+
+            pos0 = pos = self.fp.tell()
+            for rec in var.data:
+                # Apparently scalars cannot be converted to big endian. If we
+                # try to convert a ``=i4`` scalar to, say, '>i4' the dtype
+                # will remain as ``=i4``.
+                if not rec.shape and (rec.dtype.byteorder == '<' or
+                        (rec.dtype.byteorder == '=' and LITTLE_ENDIAN)):
+                    rec = rec.byteswap()
+                self.fp.write(rec.tobytes())
+                # Padding
+                count = rec.size * rec.itemsize
+                self._write_var_padding(var, var._vsize - count)
+                pos += self._recsize
+                self.fp.seek(pos)
+            self.fp.seek(pos0 + var._vsize)
+
+    def _write_var_padding(self, var, size):
+        encoded_fill_value = var._get_encoded_fill_value()
+        num_fills = size // len(encoded_fill_value)
+        self.fp.write(encoded_fill_value * num_fills)
+
+    def _write_att_values(self, values):
+        if hasattr(values, 'dtype'):
+            nc_type = REVERSE[values.dtype.char, values.dtype.itemsize]
+        else:
+            types = [(int, NC_INT), (float, NC_FLOAT), (str, NC_CHAR)]
+
+            # bytes index into scalars in py3k. Check for "string" types
+            if isinstance(values, str | bytes):
+                sample = values
+            else:
+                try:
+                    sample = values[0]  # subscriptable?
+                except TypeError:
+                    sample = values     # scalar
+
+            for class_, nc_type in types:
+                if isinstance(sample, class_):
+                    break
+
+        typecode, size = TYPEMAP[nc_type]
+        dtype_ = f'>{typecode}'
+        # asarray() dies with bytes and '>c' in py3k. Change to 'S'
+        dtype_ = 'S' if dtype_ == '>c' else dtype_
+
+        values = asarray(values, dtype=dtype_)
+
+        self.fp.write(nc_type)
+
+        if values.dtype.char == 'S':
+            nelems = values.itemsize
+        else:
+            nelems = values.size
+        self._pack_int(nelems)
+
+        if not values.shape and (values.dtype.byteorder == '<' or
+                (values.dtype.byteorder == '=' and LITTLE_ENDIAN)):
+            values = values.byteswap()
+        self.fp.write(values.tobytes())
+        count = values.size * values.itemsize
+        self.fp.write(b'\x00' * (-count % 4))  # pad
+
+    def _read(self):
+        # Check magic bytes and version
+        magic = self.fp.read(3)
+        if not magic == b'CDF':
+            raise TypeError(f"Error: {self.filename} is not a valid NetCDF 3 file")
+        self.__dict__['version_byte'] = frombuffer(self.fp.read(1), '>b')[0]
+
+        # Read file headers and set data.
+        self._read_numrecs()
+        self._read_dim_array()
+        self._read_gatt_array()
+        self._read_var_array()
+
+    def _read_numrecs(self):
+        self.__dict__['_recs'] = self._unpack_int()
+
+    def _read_dim_array(self):
+        header = self.fp.read(4)
+        if header not in [ZERO, NC_DIMENSION]:
+            raise ValueError("Unexpected header.")
+        count = self._unpack_int()
+
+        for dim in range(count):
+            name = self._unpack_string().decode('latin1')
+            length = self._unpack_int() or None  # None for record dimension
+            self.dimensions[name] = length
+            self._dims.append(name)  # preserve order
+
+    def _read_gatt_array(self):
+        for k, v in self._read_att_array().items():
+            self.__setattr__(k, v)
+
+    def _read_att_array(self):
+        header = self.fp.read(4)
+        if header not in [ZERO, NC_ATTRIBUTE]:
+            raise ValueError("Unexpected header.")
+        count = self._unpack_int()
+
+        attributes = {}
+        for attr in range(count):
+            name = self._unpack_string().decode('latin1')
+            attributes[name] = self._read_att_values()
+        return attributes
+
+    def _read_var_array(self):
+        header = self.fp.read(4)
+        if header not in [ZERO, NC_VARIABLE]:
+            raise ValueError("Unexpected header.")
+
+        begin = 0
+        dtypes = {'names': [], 'formats': []}
+        rec_vars = []
+        count = self._unpack_int()
+        for var in range(count):
+            (name, dimensions, shape, attributes,
+             typecode, size, dtype_, begin_, vsize) = self._read_var()
+            # https://www.unidata.ucar.edu/software/netcdf/guide_toc.html
+            # Note that vsize is the product of the dimension lengths
+            # (omitting the record dimension) and the number of bytes
+            # per value (determined from the type), increased to the
+            # next multiple of 4, for each variable. If a record
+            # variable, this is the amount of space per record. The
+            # netCDF "record size" is calculated as the sum of the
+            # vsize's of all the record variables.
+            #
+            # The vsize field is actually redundant, because its value
+            # may be computed from other information in the header. The
+            # 32-bit vsize field is not large enough to contain the size
+            # of variables that require more than 2^32 - 4 bytes, so
+            # 2^32 - 1 is used in the vsize field for such variables.
+            if shape and shape[0] is None:  # record variable
+                rec_vars.append(name)
+                # The netCDF "record size" is calculated as the sum of
+                # the vsize's of all the record variables.
+                self.__dict__['_recsize'] += vsize
+                if begin == 0:
+                    begin = begin_
+                dtypes['names'].append(name)
+                dtypes['formats'].append(str(shape[1:]) + dtype_)
+
+                # Handle padding with a virtual variable.
+                if typecode in 'bch':
+                    actual_size = reduce(mul, (1,) + shape[1:]) * size
+                    padding = -actual_size % 4
+                    if padding:
+                        dtypes['names'].append(f'_padding_{var}')
+                        dtypes['formats'].append(f'({padding},)>b')
+
+                # Data will be set later.
+                data = None
+            else:  # not a record variable
+                # Calculate size to avoid problems with vsize (above)
+                a_size = reduce(mul, shape, 1) * size
+                if self.use_mmap:
+                    data = self._mm_buf[begin_:begin_+a_size].view(dtype=dtype_)
+                    data = data.reshape(shape)
+                else:
+                    pos = self.fp.tell()
+                    self.fp.seek(begin_)
+                    data = frombuffer(self.fp.read(a_size), dtype=dtype_
+                                      ).copy()
+                    data = data.reshape(shape)
+                    self.fp.seek(pos)
+
+            # Add variable.
+            self.variables[name] = netcdf_variable(
+                    data, typecode, size, shape, dimensions, attributes,
+                    maskandscale=self.maskandscale)
+
+        if rec_vars:
+            # Remove padding when only one record variable.
+            if len(rec_vars) == 1:
+                dtypes['names'] = dtypes['names'][:1]
+                dtypes['formats'] = dtypes['formats'][:1]
+
+            # Build rec array.
+            if self.use_mmap:
+                buf = self._mm_buf[begin:begin+self._recs*self._recsize]
+                rec_array = buf.view(dtype=dtypes)
+                rec_array = rec_array.reshape((self._recs,))
+            else:
+                pos = self.fp.tell()
+                self.fp.seek(begin)
+                rec_array = frombuffer(self.fp.read(self._recs*self._recsize),
+                                       dtype=dtypes).copy()
+                rec_array = rec_array.reshape((self._recs,))
+                self.fp.seek(pos)
+
+            for var in rec_vars:
+                self.variables[var].__dict__['data'] = rec_array[var]
+
+    def _read_var(self):
+        name = self._unpack_string().decode('latin1')
+        dimensions = []
+        shape = []
+        dims = self._unpack_int()
+
+        for i in range(dims):
+            dimid = self._unpack_int()
+            dimname = self._dims[dimid]
+            dimensions.append(dimname)
+            dim = self.dimensions[dimname]
+            shape.append(dim)
+        dimensions = tuple(dimensions)
+        shape = tuple(shape)
+
+        attributes = self._read_att_array()
+        nc_type = self.fp.read(4)
+        vsize = self._unpack_int()
+        begin = [self._unpack_int, self._unpack_int64][self.version_byte-1]()
+
+        typecode, size = TYPEMAP[nc_type]
+        dtype_ = f'>{typecode}'
+
+        return name, dimensions, shape, attributes, typecode, size, dtype_, begin, vsize
+
+    def _read_att_values(self):
+        nc_type = self.fp.read(4)
+        n = self._unpack_int()
+
+        typecode, size = TYPEMAP[nc_type]
+
+        count = n*size
+        values = self.fp.read(int(count))
+        self.fp.read(-count % 4)  # read padding
+
+        if typecode != 'c':
+            values = frombuffer(values, dtype=f'>{typecode}').copy()
+            if values.shape == (1,):
+                values = values[0]
+        else:
+            values = values.rstrip(b'\x00')
+        return values
+
+    def _pack_begin(self, begin):
+        if self.version_byte == 1:
+            self._pack_int(begin)
+        elif self.version_byte == 2:
+            self._pack_int64(begin)
+
+    def _pack_int(self, value):
+        self.fp.write(array(value, '>i').tobytes())
+    _pack_int32 = _pack_int
+
+    def _unpack_int(self):
+        return int(frombuffer(self.fp.read(4), '>i')[0])
+    _unpack_int32 = _unpack_int
+
+    def _pack_int64(self, value):
+        self.fp.write(array(value, '>q').tobytes())
+
+    def _unpack_int64(self):
+        return frombuffer(self.fp.read(8), '>q')[0]
+
+    def _pack_string(self, s):
+        count = len(s)
+        self._pack_int(count)
+        self.fp.write(s.encode('latin1'))
+        self.fp.write(b'\x00' * (-count % 4))  # pad
+
+    def _unpack_string(self):
+        count = self._unpack_int()
+        s = self.fp.read(count).rstrip(b'\x00')
+        self.fp.read(-count % 4)  # read padding
+        return s
+
+
+class netcdf_variable:
+    """
+    A data object for netcdf files.
+
+    `netcdf_variable` objects are constructed by calling the method
+    `netcdf_file.createVariable` on the `netcdf_file` object. `netcdf_variable`
+    objects behave much like array objects defined in numpy, except that their
+    data resides in a file. Data is read by indexing and written by assigning
+    to an indexed subset; the entire array can be accessed by the index ``[:]``
+    or (for scalars) by using the methods `getValue` and `assignValue`.
+    `netcdf_variable` objects also have attribute `shape` with the same meaning
+    as for arrays, but the shape cannot be modified. There is another read-only
+    attribute `dimensions`, whose value is the tuple of dimension names.
+
+    All other attributes correspond to variable attributes defined in
+    the NetCDF file. Variable attributes are created by assigning to an
+    attribute of the `netcdf_variable` object.
+
+    Parameters
+    ----------
+    data : array_like
+        The data array that holds the values for the variable.
+        Typically, this is initialized as empty, but with the proper shape.
+    typecode : dtype character code
+        Desired data-type for the data array.
+    size : int
+        Desired element size for the data array.
+    shape : sequence of ints
+        The shape of the array. This should match the lengths of the
+        variable's dimensions.
+    dimensions : sequence of strings
+        The names of the dimensions used by the variable. Must be in the
+        same order of the dimension lengths given by `shape`.
+    attributes : dict, optional
+        Attribute values (any type) keyed by string names. These attributes
+        become attributes for the netcdf_variable object.
+    maskandscale : bool, optional
+        Whether to automatically scale and/or mask data based on attributes.
+        Default is False.
+
+
+    Attributes
+    ----------
+    dimensions : list of str
+        List of names of dimensions used by the variable object.
+    isrec, shape
+        Properties
+
+    See Also
+    --------
+    isrec, shape
+
+    Notes
+    -----
+    For a more recent version of the NetCDF standard and additional features, please
+    consider the permissively-licensed
+    `netcdf4-python `_.
+
+    """
+    def __init__(self, data, typecode, size, shape, dimensions,
+                 attributes=None,
+                 maskandscale=False):
+        self.data = data
+        self._typecode = typecode
+        self._size = size
+        self._shape = shape
+        self.dimensions = dimensions
+        self.maskandscale = maskandscale
+
+        self._attributes = attributes or {}
+        for k, v in self._attributes.items():
+            self.__dict__[k] = v
+
+    def __setattr__(self, attr, value):
+        # Store user defined attributes in a separate dict,
+        # so we can save them to file later.
+        try:
+            self._attributes[attr] = value
+        except AttributeError:
+            pass
+        self.__dict__[attr] = value
+
+    def isrec(self):
+        """Returns whether the variable has a record dimension or not.
+
+        A record dimension is a dimension along which additional data could be
+        easily appended in the netcdf data structure without much rewriting of
+        the data file. This attribute is a read-only property of the
+        `netcdf_variable`.
+
+        """
+        return bool(self.data.shape) and not self._shape[0]
+    isrec = property(isrec)
+
+    def shape(self):
+        """Returns the shape tuple of the data variable.
+
+        This is a read-only attribute and can not be modified in the
+        same manner of other numpy arrays.
+        """
+        return self.data.shape
+    shape = property(shape)
+
+    def getValue(self):
+        """
+        Retrieve a scalar value from a `netcdf_variable` of length one.
+
+        Returns
+        -------
+        scalar
+            The scalar value contained in the length-one netcdf variable.
+
+        Raises
+        ------
+        ValueError
+            If the netcdf variable is an array of length greater than one,
+            this exception will be raised.
+
+        """
+        return self.data.item()
+
+    def assignValue(self, value):
+        """
+        Assign a scalar value to a `netcdf_variable` of length one.
+
+        Parameters
+        ----------
+        value : scalar
+            Scalar value (of compatible type) to assign to a length-one netcdf
+            variable. This value will be written to file.
+
+        Raises
+        ------
+        ValueError
+            If the input is not a scalar, or if the destination is not a length-one
+            netcdf variable.
+
+        """
+        if not self.data.flags.writeable:
+            # Work-around for a bug in NumPy.  Calling itemset() on a read-only
+            # memory-mapped array causes a seg. fault.
+            # See NumPy ticket #1622, and SciPy ticket #1202.
+            # This check for `writeable` can be removed when the oldest version
+            # of NumPy still supported by scipy contains the fix for #1622.
+            raise RuntimeError("variable is not writeable")
+
+        self.data[:] = value
+
+    def typecode(self):
+        """
+        Return the typecode of the variable.
+
+        Returns
+        -------
+        typecode : char
+            The character typecode of the variable (e.g., 'i' for int).
+
+        """
+        return self._typecode
+
+    def itemsize(self):
+        """
+        Return the itemsize of the variable.
+
+        Returns
+        -------
+        itemsize : int
+            The element size of the variable (e.g., 8 for float64).
+
+        """
+        return self._size
+
+    def __getitem__(self, index):
+        if not self.maskandscale:
+            return self.data[index]
+
+        data = self.data[index].copy()
+        missing_value = self._get_missing_value()
+        data = self._apply_missing_value(data, missing_value)
+        scale_factor = self._attributes.get('scale_factor')
+        add_offset = self._attributes.get('add_offset')
+        if add_offset is not None or scale_factor is not None:
+            data = data.astype(np.float64)
+        if scale_factor is not None:
+            data = data * scale_factor
+        if add_offset is not None:
+            data += add_offset
+
+        return data
+
+    def __setitem__(self, index, data):
+        if self.maskandscale:
+            missing_value = (
+                    self._get_missing_value() or
+                    getattr(data, 'fill_value', 999999))
+            self._attributes.setdefault('missing_value', missing_value)
+            self._attributes.setdefault('_FillValue', missing_value)
+            data = ((data - self._attributes.get('add_offset', 0.0)) /
+                    self._attributes.get('scale_factor', 1.0))
+            data = np.ma.asarray(data).filled(missing_value)
+            if self._typecode not in 'fd' and data.dtype.kind == 'f':
+                data = np.round(data)
+
+        # Expand data for record vars?
+        if self.isrec:
+            if isinstance(index, tuple):
+                rec_index = index[0]
+            else:
+                rec_index = index
+            if isinstance(rec_index, slice):
+                recs = (rec_index.start or 0) + len(data)
+            else:
+                recs = rec_index + 1
+            if recs > len(self.data):
+                shape = (recs,) + self._shape[1:]
+                # Resize in-place does not always work since
+                # the array might not be single-segment
+                try:
+                    self.data.resize(shape)
+                except ValueError:
+                    dtype = self.data.dtype
+                    self.__dict__['data'] = np.resize(self.data, shape).astype(dtype)
+        self.data[index] = data
+
+    def _default_encoded_fill_value(self):
+        """
+        The default encoded fill-value for this Variable's data type.
+        """
+        nc_type = REVERSE[self.typecode(), self.itemsize()]
+        return FILLMAP[nc_type]
+
+    def _get_encoded_fill_value(self):
+        """
+        Returns the encoded fill value for this variable as bytes.
+
+        This is taken from either the _FillValue attribute, or the default fill
+        value for this variable's data type.
+        """
+        if '_FillValue' in self._attributes:
+            fill_value = np.array(self._attributes['_FillValue'],
+                                  dtype=self.data.dtype).tobytes()
+            if len(fill_value) == self.itemsize():
+                return fill_value
+            else:
+                return self._default_encoded_fill_value()
+        else:
+            return self._default_encoded_fill_value()
+
+    def _get_missing_value(self):
+        """
+        Returns the value denoting "no data" for this variable.
+
+        If this variable does not have a missing/fill value, returns None.
+
+        If both _FillValue and missing_value are given, give precedence to
+        _FillValue. The netCDF standard gives special meaning to _FillValue;
+        missing_value is  just used for compatibility with old datasets.
+        """
+
+        if '_FillValue' in self._attributes:
+            missing_value = self._attributes['_FillValue']
+        elif 'missing_value' in self._attributes:
+            missing_value = self._attributes['missing_value']
+        else:
+            missing_value = None
+
+        return missing_value
+
+    @staticmethod
+    def _apply_missing_value(data, missing_value):
+        """
+        Applies the given missing value to the data array.
+
+        Returns a numpy.ma array, with any value equal to missing_value masked
+        out (unless missing_value is None, in which case the original array is
+        returned).
+        """
+
+        if missing_value is None:
+            newdata = data
+        else:
+            try:
+                missing_value_isnan = np.isnan(missing_value)
+            except (TypeError, NotImplementedError):
+                # some data types (e.g., characters) cannot be tested for NaN
+                missing_value_isnan = False
+
+            if missing_value_isnan:
+                mymask = np.isnan(data)
+            else:
+                mymask = (data == missing_value)
+
+            newdata = np.ma.masked_where(mymask, data)
+
+        return newdata
+
+
+NetCDFFile = netcdf_file
+NetCDFVariable = netcdf_variable
diff --git a/.venv/lib/python3.12/site-packages/scipy/io/arff/__init__.py b/.venv/lib/python3.12/site-packages/scipy/io/arff/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..dcfe1c4237e69054b582a0fa52f710b25a1d7914
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/io/arff/__init__.py
@@ -0,0 +1,28 @@
+"""
+Module to read ARFF files
+=========================
+ARFF is the standard data format for WEKA.
+It is a text file format which support numerical, string and data values.
+The format can also represent missing data and sparse data.
+
+Notes
+-----
+The ARFF support in ``scipy.io`` provides file reading functionality only.
+For more extensive ARFF functionality, see `liac-arff
+`_.
+
+See the `WEKA website `_
+for more details about the ARFF format and available datasets.
+
+"""
+from ._arffread import *
+from . import _arffread
+
+# Deprecated namespaces, to be removed in v2.0.0
+from .import arffread
+
+__all__ = _arffread.__all__ + ['arffread']
+
+from scipy._lib._testutils import PytestTester
+test = PytestTester(__name__)
+del PytestTester
diff --git a/.venv/lib/python3.12/site-packages/scipy/io/arff/_arffread.py b/.venv/lib/python3.12/site-packages/scipy/io/arff/_arffread.py
new file mode 100644
index 0000000000000000000000000000000000000000..c46f741c2f515736f9e05e84b2fa04121c100b55
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/io/arff/_arffread.py
@@ -0,0 +1,893 @@
+# Last Change: Mon Aug 20 08:00 PM 2007 J
+import re
+import datetime
+
+import numpy as np
+
+import csv
+import ctypes
+
+"""A module to read arff files."""
+
+__all__ = ['MetaData', 'loadarff', 'ArffError', 'ParseArffError']
+
+# An Arff file is basically two parts:
+#   - header
+#   - data
+#
+# A header has each of its components starting by @META where META is one of
+# the keyword (attribute of relation, for now).
+
+# TODO:
+#   - both integer and reals are treated as numeric -> the integer info
+#    is lost!
+#   - Replace ValueError by ParseError or something
+
+# We know can handle the following:
+#   - numeric and nominal attributes
+#   - missing values for numeric attributes
+
+r_meta = re.compile(r'^\s*@')
+# Match a comment
+r_comment = re.compile(r'^%')
+# Match an empty line
+r_empty = re.compile(r'^\s+$')
+# Match a header line, that is a line which starts by @ + a word
+r_headerline = re.compile(r'^\s*@\S*')
+r_datameta = re.compile(r'^@[Dd][Aa][Tt][Aa]')
+r_relation = re.compile(r'^@[Rr][Ee][Ll][Aa][Tt][Ii][Oo][Nn]\s*(\S*)')
+r_attribute = re.compile(r'^\s*@[Aa][Tt][Tt][Rr][Ii][Bb][Uu][Tt][Ee]\s*(..*$)')
+
+r_nominal = re.compile(r'{(.+)}')
+r_date = re.compile(r"[Dd][Aa][Tt][Ee]\s+[\"']?(.+?)[\"']?$")
+
+# To get attributes name enclosed with ''
+r_comattrval = re.compile(r"'(..+)'\s+(..+$)")
+# To get normal attributes
+r_wcomattrval = re.compile(r"(\S+)\s+(..+$)")
+
+# ------------------------
+# Module defined exception
+# ------------------------
+
+
+class ArffError(OSError):
+    """
+    Base exception for errors when reading ARFF files.
+    
+    Raised when an ARFF file cannot be read due to file access issues,
+    corruption, or unsupported features.
+    """
+    pass
+
+
+class ParseArffError(ArffError):
+    """
+    Exception for syntax and parsing errors in ARFF files.
+    
+    Raised when an ARFF file has invalid syntax, malformed attributes,
+    or data that doesn't match the expected format.
+    """
+    pass
+
+
+# ----------
+# Attributes
+# ----------
+class Attribute:
+
+    type_name = None
+
+    def __init__(self, name):
+        self.name = name
+        self.range = None
+        self.dtype = np.object_
+
+    @classmethod
+    def parse_attribute(cls, name, attr_string):
+        """
+        Parse the attribute line if it knows how. Returns the parsed
+        attribute, or None.
+        """
+        return None
+
+    def parse_data(self, data_str):
+        """
+        Parse a value of this type.
+        """
+        return None
+
+    def __str__(self):
+        """
+        Parse a value of this type.
+        """
+        return self.name + ',' + self.type_name
+
+
+class NominalAttribute(Attribute):
+
+    type_name = 'nominal'
+
+    def __init__(self, name, values):
+        super().__init__(name)
+        self.values = values
+        self.range = values
+        self.dtype = (np.bytes_, max(len(i) for i in values))
+
+    @staticmethod
+    def _get_nom_val(atrv):
+        """Given a string containing a nominal type, returns a tuple of the
+        possible values.
+
+        A nominal type is defined as something framed between braces ({}).
+
+        Parameters
+        ----------
+        atrv : str
+           Nominal type definition
+
+        Returns
+        -------
+        poss_vals : tuple
+           possible values
+
+        Examples
+        --------
+        >>> from scipy.io.arff._arffread import NominalAttribute
+        >>> NominalAttribute._get_nom_val("{floup, bouga, fl, ratata}")
+        ('floup', 'bouga', 'fl', 'ratata')
+        """
+        m = r_nominal.match(atrv)
+        if m:
+            attrs, _ = split_data_line(m.group(1))
+            return tuple(attrs)
+        else:
+            raise ValueError("This does not look like a nominal string")
+
+    @classmethod
+    def parse_attribute(cls, name, attr_string):
+        """
+        Parse the attribute line if it knows how. Returns the parsed
+        attribute, or None.
+
+        For nominal attributes, the attribute string would be like '{,
+         , }'.
+        """
+        if attr_string[0] == '{':
+            values = cls._get_nom_val(attr_string)
+            return cls(name, values)
+        else:
+            return None
+
+    def parse_data(self, data_str):
+        """
+        Parse a value of this type.
+        """
+        if data_str in self.values:
+            return data_str
+        elif data_str == '?':
+            return data_str
+        else:
+            raise ValueError(f"{str(data_str)} value not in {str(self.values)}")
+
+    def __str__(self):
+        msg = self.name + ",{"
+        for i in range(len(self.values)-1):
+            msg += self.values[i] + ","
+        msg += self.values[-1]
+        msg += "}"
+        return msg
+
+
+class NumericAttribute(Attribute):
+
+    def __init__(self, name):
+        super().__init__(name)
+        self.type_name = 'numeric'
+        self.dtype = np.float64
+
+    @classmethod
+    def parse_attribute(cls, name, attr_string):
+        """
+        Parse the attribute line if it knows how. Returns the parsed
+        attribute, or None.
+
+        For numeric attributes, the attribute string would be like
+        'numeric' or 'int' or 'real'.
+        """
+
+        attr_string = attr_string.lower().strip()
+
+        if (attr_string[:len('numeric')] == 'numeric' or
+           attr_string[:len('int')] == 'int' or
+           attr_string[:len('real')] == 'real'):
+            return cls(name)
+        else:
+            return None
+
+    def parse_data(self, data_str):
+        """
+        Parse a value of this type.
+
+        Parameters
+        ----------
+        data_str : str
+           string to convert
+
+        Returns
+        -------
+        f : float
+           where float can be nan
+
+        Examples
+        --------
+        >>> from scipy.io.arff._arffread import NumericAttribute
+        >>> atr = NumericAttribute('atr')
+        >>> atr.parse_data('1')
+        1.0
+        >>> atr.parse_data('1\\n')
+        1.0
+        >>> atr.parse_data('?\\n')
+        nan
+        """
+        if '?' in data_str:
+            return np.nan
+        else:
+            return float(data_str)
+
+    def _basic_stats(self, data):
+        nbfac = data.size * 1. / (data.size - 1)
+        return (np.nanmin(data), np.nanmax(data),
+                np.mean(data), np.std(data) * nbfac)
+
+
+class StringAttribute(Attribute):
+
+    def __init__(self, name):
+        super().__init__(name)
+        self.type_name = 'string'
+
+    @classmethod
+    def parse_attribute(cls, name, attr_string):
+        """
+        Parse the attribute line if it knows how. Returns the parsed
+        attribute, or None.
+
+        For string attributes, the attribute string would be like
+        'string'.
+        """
+
+        attr_string = attr_string.lower().strip()
+
+        if attr_string[:len('string')] == 'string':
+            return cls(name)
+        else:
+            return None
+
+
+class DateAttribute(Attribute):
+
+    def __init__(self, name, date_format, datetime_unit):
+        super().__init__(name)
+        self.date_format = date_format
+        self.datetime_unit = datetime_unit
+        self.type_name = 'date'
+        self.range = date_format
+        self.dtype = np.datetime64(0, self.datetime_unit)
+
+    @staticmethod
+    def _get_date_format(atrv):
+        m = r_date.match(atrv)
+        if m:
+            pattern = m.group(1).strip()
+            # convert time pattern from Java's SimpleDateFormat to C's format
+            datetime_unit = None
+            if "yyyy" in pattern:
+                pattern = pattern.replace("yyyy", "%Y")
+                datetime_unit = "Y"
+            elif "yy":
+                pattern = pattern.replace("yy", "%y")
+                datetime_unit = "Y"
+            if "MM" in pattern:
+                pattern = pattern.replace("MM", "%m")
+                datetime_unit = "M"
+            if "dd" in pattern:
+                pattern = pattern.replace("dd", "%d")
+                datetime_unit = "D"
+            if "HH" in pattern:
+                pattern = pattern.replace("HH", "%H")
+                datetime_unit = "h"
+            if "mm" in pattern:
+                pattern = pattern.replace("mm", "%M")
+                datetime_unit = "m"
+            if "ss" in pattern:
+                pattern = pattern.replace("ss", "%S")
+                datetime_unit = "s"
+            if "z" in pattern or "Z" in pattern:
+                raise ValueError("Date type attributes with time zone not "
+                                 "supported, yet")
+
+            if datetime_unit is None:
+                raise ValueError("Invalid or unsupported date format")
+
+            return pattern, datetime_unit
+        else:
+            raise ValueError("Invalid or no date format")
+
+    @classmethod
+    def parse_attribute(cls, name, attr_string):
+        """
+        Parse the attribute line if it knows how. Returns the parsed
+        attribute, or None.
+
+        For date attributes, the attribute string would be like
+        'date '.
+        """
+
+        attr_string_lower = attr_string.lower().strip()
+
+        if attr_string_lower[:len('date')] == 'date':
+            date_format, datetime_unit = cls._get_date_format(attr_string)
+            return cls(name, date_format, datetime_unit)
+        else:
+            return None
+
+    def parse_data(self, data_str):
+        """
+        Parse a value of this type.
+        """
+        date_str = data_str.strip().strip("'").strip('"')
+        if date_str == '?':
+            return np.datetime64('NaT', self.datetime_unit)
+        else:
+            dt = datetime.datetime.strptime(date_str, self.date_format)
+            return np.datetime64(dt).astype(
+                f"datetime64[{self.datetime_unit}]")
+
+    def __str__(self):
+        return super().__str__() + ',' + self.date_format
+
+
+class RelationalAttribute(Attribute):
+
+    def __init__(self, name):
+        super().__init__(name)
+        self.type_name = 'relational'
+        self.dtype = np.object_
+        self.attributes = []
+        self.dialect = None
+
+    @classmethod
+    def parse_attribute(cls, name, attr_string):
+        """
+        Parse the attribute line if it knows how. Returns the parsed
+        attribute, or None.
+
+        For date attributes, the attribute string would be like
+        'date '.
+        """
+
+        attr_string_lower = attr_string.lower().strip()
+
+        if attr_string_lower[:len('relational')] == 'relational':
+            return cls(name)
+        else:
+            return None
+
+    def parse_data(self, data_str):
+        # Copy-pasted
+        elems = list(range(len(self.attributes)))
+
+        escaped_string = data_str.encode().decode("unicode-escape")
+
+        row_tuples = []
+
+        for raw in escaped_string.split("\n"):
+            row, self.dialect = split_data_line(raw, self.dialect)
+
+            row_tuples.append(tuple(
+                [self.attributes[i].parse_data(row[i]) for i in elems]))
+
+        return np.array(row_tuples,
+                        [(a.name, a.dtype) for a in self.attributes])
+
+    def __str__(self):
+        return (super().__str__() + '\n\t' +
+                '\n\t'.join(str(a) for a in self.attributes))
+
+
+# -----------------
+# Various utilities
+# -----------------
+def to_attribute(name, attr_string):
+    attr_classes = (NominalAttribute, NumericAttribute, DateAttribute,
+                    StringAttribute, RelationalAttribute)
+
+    for cls in attr_classes:
+        attr = cls.parse_attribute(name, attr_string)
+        if attr is not None:
+            return attr
+
+    raise ParseArffError(f"unknown attribute {attr_string}")
+
+
+def csv_sniffer_has_bug_last_field():
+    """
+    Checks if the bug https://bugs.python.org/issue30157 is unpatched.
+    """
+
+    # We only compute this once.
+    has_bug = getattr(csv_sniffer_has_bug_last_field, "has_bug", None)
+
+    if has_bug is None:
+        dialect = csv.Sniffer().sniff("3, 'a'")
+        csv_sniffer_has_bug_last_field.has_bug = dialect.quotechar != "'"
+        has_bug = csv_sniffer_has_bug_last_field.has_bug
+
+    return has_bug
+
+
+def workaround_csv_sniffer_bug_last_field(sniff_line, dialect, delimiters):
+    """
+    Workaround for the bug https://bugs.python.org/issue30157 if is unpatched.
+    """
+    if csv_sniffer_has_bug_last_field():
+        # Reuses code from the csv module
+        right_regex = r'(?P[^\w\n"\'])(?P ?)(?P["\']).*?(?P=quote)(?:$|\n)'  # noqa: E501
+
+        for restr in (r'(?P[^\w\n"\'])(?P ?)(?P["\']).*?(?P=quote)(?P=delim)',  # ,".*?",  # noqa: E501
+                      r'(?:^|\n)(?P["\']).*?(?P=quote)(?P[^\w\n"\'])(?P ?)',  # .*?",  # noqa: E501
+                      right_regex,  # ,".*?"
+                      r'(?:^|\n)(?P["\']).*?(?P=quote)(?:$|\n)'):  # ".*?" (no delim, no space)  # noqa: E501
+            regexp = re.compile(restr, re.DOTALL | re.MULTILINE)
+            matches = regexp.findall(sniff_line)
+            if matches:
+                break
+
+        # If it does not match the expression that was bugged,
+        # then this bug does not apply
+        if restr != right_regex:
+            return
+
+        groupindex = regexp.groupindex
+
+        # There is only one end of the string
+        assert len(matches) == 1
+        m = matches[0]
+
+        n = groupindex['quote'] - 1
+        quote = m[n]
+
+        n = groupindex['delim'] - 1
+        delim = m[n]
+
+        n = groupindex['space'] - 1
+        space = bool(m[n])
+
+        dq_regexp = re.compile(
+            rf"(({re.escape(delim)})|^)\W*{quote}[^{re.escape(delim)}\n]*{quote}[^{re.escape(delim)}\n]*{quote}\W*(({re.escape(delim)})|$)", re.MULTILINE  # noqa: E501
+        )
+
+        doublequote = bool(dq_regexp.search(sniff_line))
+
+        dialect.quotechar = quote
+        if delim in delimiters:
+            dialect.delimiter = delim
+        dialect.doublequote = doublequote
+        dialect.skipinitialspace = space
+
+
+def split_data_line(line, dialect=None):
+    delimiters = ",\t"
+
+    # This can not be done in a per reader basis, and relational fields
+    # can be HUGE
+    csv.field_size_limit(int(ctypes.c_ulong(-1).value // 2))
+
+    # Remove the line end if any
+    if line[-1] == '\n':
+        line = line[:-1]
+    
+    # Remove potential trailing whitespace
+    line = line.strip()
+    
+    sniff_line = line
+
+    # Add a delimiter if none is present, so that the csv.Sniffer
+    # does not complain for a single-field CSV.
+    if not any(d in line for d in delimiters):
+        sniff_line += ","
+
+    if dialect is None:
+        dialect = csv.Sniffer().sniff(sniff_line, delimiters=delimiters)
+        workaround_csv_sniffer_bug_last_field(sniff_line=sniff_line,
+                                              dialect=dialect,
+                                              delimiters=delimiters)
+
+    row = next(csv.reader([line], dialect))
+
+    return row, dialect
+
+
+# --------------
+# Parsing header
+# --------------
+def tokenize_attribute(iterable, attribute):
+    """Parse a raw string in header (e.g., starts by @attribute).
+
+    Given a raw string attribute, try to get the name and type of the
+    attribute. Constraints:
+
+    * The first line must start with @attribute (case insensitive, and
+      space like characters before @attribute are allowed)
+    * Works also if the attribute is spread on multilines.
+    * Works if empty lines or comments are in between
+
+    Parameters
+    ----------
+    attribute : str
+       the attribute string.
+
+    Returns
+    -------
+    name : str
+       name of the attribute
+    value : str
+       value of the attribute
+    next : str
+       next line to be parsed
+
+    Examples
+    --------
+    If attribute is a string defined in python as r"floupi real", will
+    return floupi as name, and real as value.
+
+    >>> from scipy.io.arff._arffread import tokenize_attribute
+    >>> iterable = iter([0] * 10) # dummy iterator
+    >>> tokenize_attribute(iterable, r"@attribute floupi real")
+    ('floupi', 'real', 0)
+
+    If attribute is r"'floupi 2' real", will return 'floupi 2' as name,
+    and real as value.
+
+    >>> tokenize_attribute(iterable, r"  @attribute 'floupi 2' real   ")
+    ('floupi 2', 'real', 0)
+
+    """
+    sattr = attribute.strip()
+    mattr = r_attribute.match(sattr)
+    if mattr:
+        # atrv is everything after @attribute
+        atrv = mattr.group(1)
+        if r_comattrval.match(atrv):
+            name, type = tokenize_single_comma(atrv)
+            next_item = next(iterable)
+        elif r_wcomattrval.match(atrv):
+            name, type = tokenize_single_wcomma(atrv)
+            next_item = next(iterable)
+        else:
+            # Not sure we should support this, as it does not seem supported by
+            # weka.
+            raise ValueError("multi line not supported yet")
+    else:
+        raise ValueError(f"First line unparsable: {sattr}")
+
+    attribute = to_attribute(name, type)
+
+    if type.lower() == 'relational':
+        next_item = read_relational_attribute(iterable, attribute, next_item)
+    #    raise ValueError("relational attributes not supported yet")
+
+    return attribute, next_item
+
+
+def tokenize_single_comma(val):
+    # XXX we match twice the same string (here and at the caller level). It is
+    # stupid, but it is easier for now...
+    m = r_comattrval.match(val)
+    if m:
+        try:
+            name = m.group(1).strip()
+            type = m.group(2).strip()
+        except IndexError as e:
+            raise ValueError("Error while tokenizing attribute") from e
+    else:
+        raise ValueError(f"Error while tokenizing single {val}")
+    return name, type
+
+
+def tokenize_single_wcomma(val):
+    # XXX we match twice the same string (here and at the caller level). It is
+    # stupid, but it is easier for now...
+    m = r_wcomattrval.match(val)
+    if m:
+        try:
+            name = m.group(1).strip()
+            type = m.group(2).strip()
+        except IndexError as e:
+            raise ValueError("Error while tokenizing attribute") from e
+    else:
+        raise ValueError(f"Error while tokenizing single {val}")
+    return name, type
+
+
+def read_relational_attribute(ofile, relational_attribute, i):
+    """Read the nested attributes of a relational attribute"""
+
+    r_end_relational = re.compile(r'^@[Ee][Nn][Dd]\s*' +
+                                  relational_attribute.name + r'\s*$')
+
+    while not r_end_relational.match(i):
+        m = r_headerline.match(i)
+        if m:
+            isattr = r_attribute.match(i)
+            if isattr:
+                attr, i = tokenize_attribute(ofile, i)
+                relational_attribute.attributes.append(attr)
+            else:
+                raise ValueError(f"Error parsing line {i}")
+        else:
+            i = next(ofile)
+
+    i = next(ofile)
+    return i
+
+
+def read_header(ofile):
+    """Read the header of the iterable ofile."""
+    i = next(ofile)
+
+    # Pass first comments
+    while r_comment.match(i):
+        i = next(ofile)
+
+    # Header is everything up to DATA attribute ?
+    relation = None
+    attributes = []
+    while not r_datameta.match(i):
+        m = r_headerline.match(i)
+        if m:
+            isattr = r_attribute.match(i)
+            if isattr:
+                attr, i = tokenize_attribute(ofile, i)
+                attributes.append(attr)
+            else:
+                isrel = r_relation.match(i)
+                if isrel:
+                    relation = isrel.group(1)
+                else:
+                    raise ValueError(f"Error parsing line {i}")
+                i = next(ofile)
+        else:
+            i = next(ofile)
+
+    return relation, attributes
+
+
+class MetaData:
+    """
+    Small container to keep useful information on an ARFF dataset.
+
+    Knows about attributes names and types.
+
+    Parameters
+    ----------
+    rel : str
+        Name of the relation.
+    attr : list of Attribute
+        Attributes of the dataset.
+
+    Methods
+    -------
+    names
+    types
+
+    Notes
+    -----
+    Also maintains the list of attributes in order, i.e., doing for i in
+    meta, where meta is an instance of MetaData, will return the
+    different attribute names in the order they were defined.
+
+    Examples
+    --------
+    ::
+
+        data, meta = loadarff('iris.arff')
+        # This will print the attributes names of the iris.arff dataset
+        for i in meta:
+            print(i)
+        # This works too
+        meta.names()
+        # Getting attribute type
+        types = meta.types()
+    """
+    def __init__(self, rel, attr):
+        self.name = rel
+        self._attributes = {a.name: a for a in attr}
+
+    def __repr__(self):
+        msg = ""
+        msg += f"Dataset: {self.name}\n"
+        for i in self._attributes:
+            msg += f"\t{i}'s type is {self._attributes[i].type_name}"
+            if self._attributes[i].range:
+                msg += f", range is {str(self._attributes[i].range)}"
+            msg += '\n'
+        return msg
+
+    def __iter__(self):
+        return iter(self._attributes)
+
+    def __getitem__(self, key):
+        attr = self._attributes[key]
+
+        return (attr.type_name, attr.range)
+
+    def names(self):
+        """Return the list of attribute names.
+
+        Returns
+        -------
+        attrnames : list of str
+            The attribute names.
+        """
+        return list(self._attributes)
+
+    def types(self):
+        """Return the list of attribute types.
+
+        Returns
+        -------
+        attr_types : list of str
+            The attribute types.
+        """
+        attr_types = [self._attributes[name].type_name
+                      for name in self._attributes]
+        return attr_types
+
+
+def loadarff(f):
+    """
+    Read an arff file.
+
+    The data is returned as a record array, which can be accessed much like
+    a dictionary of NumPy arrays. For example, if one of the attributes is
+    called 'pressure', then its first 10 data points can be accessed from the
+    ``data`` record array like so: ``data['pressure'][0:10]``
+
+
+    Parameters
+    ----------
+    f : file-like or str
+       File-like object to read from, or filename to open.
+
+    Returns
+    -------
+    data : record array
+       The data of the arff file, accessible by attribute names.
+    meta : `MetaData`
+       Contains information about the arff file such as name and
+       type of attributes, the relation (name of the dataset), etc.
+
+    Raises
+    ------
+    ParseArffError
+        This is raised if the given file is not ARFF-formatted.
+    NotImplementedError
+        The ARFF file has an attribute which is not supported yet.
+
+    Notes
+    -----
+
+    This function should be able to read most arff files. Not
+    implemented functionality include:
+
+    * date type attributes
+    * string type attributes
+
+    It can read files with numeric and nominal attributes. It cannot read
+    files with sparse data ({} in the file). However, this function can
+    read files with missing data (? in the file), representing the data
+    points as NaNs.
+
+    Examples
+    --------
+    >>> from scipy.io import arff
+    >>> from io import StringIO
+    >>> content = \"\"\"
+    ... @relation foo
+    ... @attribute width  numeric
+    ... @attribute height numeric
+    ... @attribute color  {red,green,blue,yellow,black}
+    ... @data
+    ... 5.0,3.25,blue
+    ... 4.5,3.75,green
+    ... 3.0,4.00,red
+    ... \"\"\"
+    >>> f = StringIO(content)
+    >>> data, meta = arff.loadarff(f)
+    >>> data
+    array([(5.0, 3.25, 'blue'), (4.5, 3.75, 'green'), (3.0, 4.0, 'red')],
+          dtype=[('width', '>> meta
+    Dataset: foo
+    \twidth's type is numeric
+    \theight's type is numeric
+    \tcolor's type is nominal, range is ('red', 'green', 'blue', 'yellow', 'black')
+
+    """
+    if hasattr(f, 'read'):
+        ofile = f
+    else:
+        ofile = open(f)
+    try:
+        return _loadarff(ofile)
+    finally:
+        if ofile is not f:  # only close what we opened
+            ofile.close()
+
+
+def _loadarff(ofile):
+    # Parse the header file
+    try:
+        rel, attr = read_header(ofile)
+    except ValueError as e:
+        msg = "Error while parsing header, error was: " + str(e)
+        raise ParseArffError(msg) from e
+
+    # Check whether we have a string attribute (not supported yet)
+    hasstr = False
+    for a in attr:
+        if isinstance(a, StringAttribute):
+            hasstr = True
+
+    meta = MetaData(rel, attr)
+
+    # XXX The following code is not great
+    # Build the type descriptor descr and the list of converters to convert
+    # each attribute to the suitable type (which should match the one in
+    # descr).
+
+    # This can be used once we want to support integer as integer values and
+    # not as numeric anymore (using masked arrays ?).
+
+    if hasstr:
+        # How to support string efficiently ? Ideally, we should know the max
+        # size of the string before allocating the numpy array.
+        raise NotImplementedError("String attributes not supported yet, sorry")
+
+    ni = len(attr)
+
+    def generator(row_iter, delim=','):
+        # TODO: this is where we are spending time (~80%). I think things
+        # could be made more efficiently:
+        #   - We could for example "compile" the function, because some values
+        #   do not change here.
+        #   - The function to convert a line to dtyped values could also be
+        #   generated on the fly from a string and be executed instead of
+        #   looping.
+        #   - The regex are overkill: for comments, checking that a line starts
+        #   by % should be enough and faster, and for empty lines, same thing
+        #   --> this does not seem to change anything.
+
+        # 'compiling' the range since it does not change
+        # Note, I have already tried zipping the converters and
+        # row elements and got slightly worse performance.
+        elems = list(range(ni))
+
+        dialect = None
+        for raw in row_iter:
+            # We do not abstract skipping comments and empty lines for
+            # performance reasons.
+            if r_comment.match(raw) or r_empty.match(raw):
+                continue
+
+            row, dialect = split_data_line(raw, dialect)
+
+            yield tuple([attr[i].parse_data(row[i]) for i in elems])
+
+    a = list(generator(ofile))
+    # No error should happen here: it is a bug otherwise
+    data = np.array(a, [(a.name, a.dtype) for a in attr])
+    return data, meta
+
diff --git a/.venv/lib/python3.12/site-packages/scipy/io/arff/arffread.py b/.venv/lib/python3.12/site-packages/scipy/io/arff/arffread.py
new file mode 100644
index 0000000000000000000000000000000000000000..c42ae31db6bde3987bd059cc7451d1ae87f0073c
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/io/arff/arffread.py
@@ -0,0 +1,19 @@
+# This file is not meant for public use and will be removed in SciPy v2.0.0.
+# Use the `scipy.io.arff` namespace for importing the functions
+# included below.
+
+from scipy._lib.deprecation import _sub_module_deprecation
+
+__all__ = [  # noqa: F822
+    'MetaData', 'loadarff', 'ArffError', 'ParseArffError',
+]
+
+
+def __dir__():
+    return __all__
+
+
+def __getattr__(name):
+    return _sub_module_deprecation(sub_package="io.arff", module="arffread",
+                                   private_modules=["_arffread"], all=__all__,
+                                   attribute=name)
diff --git a/.venv/lib/python3.12/site-packages/scipy/io/arff/tests/__init__.py b/.venv/lib/python3.12/site-packages/scipy/io/arff/tests/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/.venv/lib/python3.12/site-packages/scipy/io/arff/tests/data/iris.arff b/.venv/lib/python3.12/site-packages/scipy/io/arff/tests/data/iris.arff
new file mode 100644
index 0000000000000000000000000000000000000000..780480c7c6b9a68bf71aaf357c7d3f7a5b3b3f57
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/io/arff/tests/data/iris.arff
@@ -0,0 +1,225 @@
+% 1. Title: Iris Plants Database
+% 
+% 2. Sources:
+%      (a) Creator: R.A. Fisher
+%      (b) Donor: Michael Marshall (MARSHALL%PLU@io.arc.nasa.gov)
+%      (c) Date: July, 1988
+% 
+% 3. Past Usage:
+%    - Publications: too many to mention!!!  Here are a few.
+%    1. Fisher,R.A. "The use of multiple measurements in taxonomic problems"
+%       Annual Eugenics, 7, Part II, 179-188 (1936); also in "Contributions
+%       to Mathematical Statistics" (John Wiley, NY, 1950).
+%    2. Duda,R.O., & Hart,P.E. (1973) Pattern Classification and Scene Analysis.
+%       (Q327.D83) John Wiley & Sons.  ISBN 0-471-22361-1.  See page 218.
+%    3. Dasarathy, B.V. (1980) "Nosing Around the Neighborhood: A New System
+%       Structure and Classification Rule for Recognition in Partially Exposed
+%       Environments".  IEEE Transactions on Pattern Analysis and Machine
+%       Intelligence, Vol. PAMI-2, No. 1, 67-71.
+%       -- Results:
+%          -- very low misclassification rates (0% for the setosa class)
+%    4. Gates, G.W. (1972) "The Reduced Nearest Neighbor Rule".  IEEE 
+%       Transactions on Information Theory, May 1972, 431-433.
+%       -- Results:
+%          -- very low misclassification rates again
+%    5. See also: 1988 MLC Proceedings, 54-64.  Cheeseman et al's AUTOCLASS II
+%       conceptual clustering system finds 3 classes in the data.
+% 
+% 4. Relevant Information:
+%    --- This is perhaps the best known database to be found in the pattern
+%        recognition literature.  Fisher's paper is a classic in the field
+%        and is referenced frequently to this day.  (See Duda & Hart, for
+%        example.)  The data set contains 3 classes of 50 instances each,
+%        where each class refers to a type of iris plant.  One class is
+%        linearly separable from the other 2; the latter are NOT linearly
+%        separable from each other.
+%    --- Predicted attribute: class of iris plant.
+%    --- This is an exceedingly simple domain.
+% 
+% 5. Number of Instances: 150 (50 in each of three classes)
+% 
+% 6. Number of Attributes: 4 numeric, predictive attributes and the class
+% 
+% 7. Attribute Information:
+%    1. sepal length in cm
+%    2. sepal width in cm
+%    3. petal length in cm
+%    4. petal width in cm
+%    5. class: 
+%       -- Iris Setosa
+%       -- Iris Versicolour
+%       -- Iris Virginica
+% 
+% 8. Missing Attribute Values: None
+% 
+% Summary Statistics:
+%  	           Min  Max   Mean    SD   Class Correlation
+%    sepal length: 4.3  7.9   5.84  0.83    0.7826   
+%     sepal width: 2.0  4.4   3.05  0.43   -0.4194
+%    petal length: 1.0  6.9   3.76  1.76    0.9490  (high!)
+%     petal width: 0.1  2.5   1.20  0.76    0.9565  (high!)
+% 
+% 9. Class Distribution: 33.3% for each of 3 classes.
+
+@RELATION iris
+
+@ATTRIBUTE sepallength	REAL
+@ATTRIBUTE sepalwidth 	REAL
+@ATTRIBUTE petallength 	REAL
+@ATTRIBUTE petalwidth	REAL
+@ATTRIBUTE class 	{Iris-setosa,Iris-versicolor,Iris-virginica}
+
+@DATA
+5.1,3.5,1.4,0.2,Iris-setosa
+4.9,3.0,1.4,0.2,Iris-setosa
+4.7,3.2,1.3,0.2,Iris-setosa
+4.6,3.1,1.5,0.2,Iris-setosa
+5.0,3.6,1.4,0.2,Iris-setosa
+5.4,3.9,1.7,0.4,Iris-setosa
+4.6,3.4,1.4,0.3,Iris-setosa
+5.0,3.4,1.5,0.2,Iris-setosa
+4.4,2.9,1.4,0.2,Iris-setosa
+4.9,3.1,1.5,0.1,Iris-setosa
+5.4,3.7,1.5,0.2,Iris-setosa
+4.8,3.4,1.6,0.2,Iris-setosa
+4.8,3.0,1.4,0.1,Iris-setosa
+4.3,3.0,1.1,0.1,Iris-setosa
+5.8,4.0,1.2,0.2,Iris-setosa
+5.7,4.4,1.5,0.4,Iris-setosa
+5.4,3.9,1.3,0.4,Iris-setosa
+5.1,3.5,1.4,0.3,Iris-setosa
+5.7,3.8,1.7,0.3,Iris-setosa
+5.1,3.8,1.5,0.3,Iris-setosa
+5.4,3.4,1.7,0.2,Iris-setosa
+5.1,3.7,1.5,0.4,Iris-setosa
+4.6,3.6,1.0,0.2,Iris-setosa
+5.1,3.3,1.7,0.5,Iris-setosa
+4.8,3.4,1.9,0.2,Iris-setosa
+5.0,3.0,1.6,0.2,Iris-setosa
+5.0,3.4,1.6,0.4,Iris-setosa
+5.2,3.5,1.5,0.2,Iris-setosa
+5.2,3.4,1.4,0.2,Iris-setosa
+4.7,3.2,1.6,0.2,Iris-setosa
+4.8,3.1,1.6,0.2,Iris-setosa
+5.4,3.4,1.5,0.4,Iris-setosa
+5.2,4.1,1.5,0.1,Iris-setosa
+5.5,4.2,1.4,0.2,Iris-setosa
+4.9,3.1,1.5,0.1,Iris-setosa
+5.0,3.2,1.2,0.2,Iris-setosa
+5.5,3.5,1.3,0.2,Iris-setosa
+4.9,3.1,1.5,0.1,Iris-setosa
+4.4,3.0,1.3,0.2,Iris-setosa
+5.1,3.4,1.5,0.2,Iris-setosa
+5.0,3.5,1.3,0.3,Iris-setosa
+4.5,2.3,1.3,0.3,Iris-setosa
+4.4,3.2,1.3,0.2,Iris-setosa
+5.0,3.5,1.6,0.6,Iris-setosa
+5.1,3.8,1.9,0.4,Iris-setosa
+4.8,3.0,1.4,0.3,Iris-setosa
+5.1,3.8,1.6,0.2,Iris-setosa
+4.6,3.2,1.4,0.2,Iris-setosa
+5.3,3.7,1.5,0.2,Iris-setosa
+5.0,3.3,1.4,0.2,Iris-setosa
+7.0,3.2,4.7,1.4,Iris-versicolor
+6.4,3.2,4.5,1.5,Iris-versicolor
+6.9,3.1,4.9,1.5,Iris-versicolor
+5.5,2.3,4.0,1.3,Iris-versicolor
+6.5,2.8,4.6,1.5,Iris-versicolor
+5.7,2.8,4.5,1.3,Iris-versicolor
+6.3,3.3,4.7,1.6,Iris-versicolor
+4.9,2.4,3.3,1.0,Iris-versicolor
+6.6,2.9,4.6,1.3,Iris-versicolor
+5.2,2.7,3.9,1.4,Iris-versicolor
+5.0,2.0,3.5,1.0,Iris-versicolor
+5.9,3.0,4.2,1.5,Iris-versicolor
+6.0,2.2,4.0,1.0,Iris-versicolor
+6.1,2.9,4.7,1.4,Iris-versicolor
+5.6,2.9,3.6,1.3,Iris-versicolor
+6.7,3.1,4.4,1.4,Iris-versicolor
+5.6,3.0,4.5,1.5,Iris-versicolor
+5.8,2.7,4.1,1.0,Iris-versicolor
+6.2,2.2,4.5,1.5,Iris-versicolor
+5.6,2.5,3.9,1.1,Iris-versicolor
+5.9,3.2,4.8,1.8,Iris-versicolor
+6.1,2.8,4.0,1.3,Iris-versicolor
+6.3,2.5,4.9,1.5,Iris-versicolor
+6.1,2.8,4.7,1.2,Iris-versicolor
+6.4,2.9,4.3,1.3,Iris-versicolor
+6.6,3.0,4.4,1.4,Iris-versicolor
+6.8,2.8,4.8,1.4,Iris-versicolor
+6.7,3.0,5.0,1.7,Iris-versicolor
+6.0,2.9,4.5,1.5,Iris-versicolor
+5.7,2.6,3.5,1.0,Iris-versicolor
+5.5,2.4,3.8,1.1,Iris-versicolor
+5.5,2.4,3.7,1.0,Iris-versicolor
+5.8,2.7,3.9,1.2,Iris-versicolor
+6.0,2.7,5.1,1.6,Iris-versicolor
+5.4,3.0,4.5,1.5,Iris-versicolor
+6.0,3.4,4.5,1.6,Iris-versicolor
+6.7,3.1,4.7,1.5,Iris-versicolor
+6.3,2.3,4.4,1.3,Iris-versicolor
+5.6,3.0,4.1,1.3,Iris-versicolor
+5.5,2.5,4.0,1.3,Iris-versicolor
+5.5,2.6,4.4,1.2,Iris-versicolor
+6.1,3.0,4.6,1.4,Iris-versicolor
+5.8,2.6,4.0,1.2,Iris-versicolor
+5.0,2.3,3.3,1.0,Iris-versicolor
+5.6,2.7,4.2,1.3,Iris-versicolor
+5.7,3.0,4.2,1.2,Iris-versicolor
+5.7,2.9,4.2,1.3,Iris-versicolor
+6.2,2.9,4.3,1.3,Iris-versicolor
+5.1,2.5,3.0,1.1,Iris-versicolor
+5.7,2.8,4.1,1.3,Iris-versicolor
+6.3,3.3,6.0,2.5,Iris-virginica
+5.8,2.7,5.1,1.9,Iris-virginica
+7.1,3.0,5.9,2.1,Iris-virginica
+6.3,2.9,5.6,1.8,Iris-virginica
+6.5,3.0,5.8,2.2,Iris-virginica
+7.6,3.0,6.6,2.1,Iris-virginica
+4.9,2.5,4.5,1.7,Iris-virginica
+7.3,2.9,6.3,1.8,Iris-virginica
+6.7,2.5,5.8,1.8,Iris-virginica
+7.2,3.6,6.1,2.5,Iris-virginica
+6.5,3.2,5.1,2.0,Iris-virginica
+6.4,2.7,5.3,1.9,Iris-virginica
+6.8,3.0,5.5,2.1,Iris-virginica
+5.7,2.5,5.0,2.0,Iris-virginica
+5.8,2.8,5.1,2.4,Iris-virginica
+6.4,3.2,5.3,2.3,Iris-virginica
+6.5,3.0,5.5,1.8,Iris-virginica
+7.7,3.8,6.7,2.2,Iris-virginica
+7.7,2.6,6.9,2.3,Iris-virginica
+6.0,2.2,5.0,1.5,Iris-virginica
+6.9,3.2,5.7,2.3,Iris-virginica
+5.6,2.8,4.9,2.0,Iris-virginica
+7.7,2.8,6.7,2.0,Iris-virginica
+6.3,2.7,4.9,1.8,Iris-virginica
+6.7,3.3,5.7,2.1,Iris-virginica
+7.2,3.2,6.0,1.8,Iris-virginica
+6.2,2.8,4.8,1.8,Iris-virginica
+6.1,3.0,4.9,1.8,Iris-virginica
+6.4,2.8,5.6,2.1,Iris-virginica
+7.2,3.0,5.8,1.6,Iris-virginica
+7.4,2.8,6.1,1.9,Iris-virginica
+7.9,3.8,6.4,2.0,Iris-virginica
+6.4,2.8,5.6,2.2,Iris-virginica
+6.3,2.8,5.1,1.5,Iris-virginica
+6.1,2.6,5.6,1.4,Iris-virginica
+7.7,3.0,6.1,2.3,Iris-virginica
+6.3,3.4,5.6,2.4,Iris-virginica
+6.4,3.1,5.5,1.8,Iris-virginica
+6.0,3.0,4.8,1.8,Iris-virginica
+6.9,3.1,5.4,2.1,Iris-virginica
+6.7,3.1,5.6,2.4,Iris-virginica
+6.9,3.1,5.1,2.3,Iris-virginica
+5.8,2.7,5.1,1.9,Iris-virginica
+6.8,3.2,5.9,2.3,Iris-virginica
+6.7,3.3,5.7,2.5,Iris-virginica
+6.7,3.0,5.2,2.3,Iris-virginica
+6.3,2.5,5.0,1.9,Iris-virginica
+6.5,3.0,5.2,2.0,Iris-virginica
+6.2,3.4,5.4,2.3,Iris-virginica
+5.9,3.0,5.1,1.8,Iris-virginica
+%
+%
+%
diff --git a/.venv/lib/python3.12/site-packages/scipy/io/arff/tests/data/missing.arff b/.venv/lib/python3.12/site-packages/scipy/io/arff/tests/data/missing.arff
new file mode 100644
index 0000000000000000000000000000000000000000..dedc64c8fa2fcdc0081b30b7804be85114495ce2
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/io/arff/tests/data/missing.arff
@@ -0,0 +1,8 @@
+% This arff file contains some missing data
+@relation missing
+@attribute yop real
+@attribute yap real
+@data
+1,5
+2,4
+?,?
diff --git a/.venv/lib/python3.12/site-packages/scipy/io/arff/tests/data/nodata.arff b/.venv/lib/python3.12/site-packages/scipy/io/arff/tests/data/nodata.arff
new file mode 100644
index 0000000000000000000000000000000000000000..5766aeb229a1b31378026274c366e8e9e44fd487
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/io/arff/tests/data/nodata.arff
@@ -0,0 +1,11 @@
+@RELATION iris
+
+@ATTRIBUTE sepallength  REAL
+@ATTRIBUTE sepalwidth   REAL
+@ATTRIBUTE petallength  REAL
+@ATTRIBUTE petalwidth   REAL
+@ATTRIBUTE class    {Iris-setosa,Iris-versicolor,Iris-virginica}
+
+@DATA
+
+% This file has no data
diff --git a/.venv/lib/python3.12/site-packages/scipy/io/arff/tests/data/quoted_nominal.arff b/.venv/lib/python3.12/site-packages/scipy/io/arff/tests/data/quoted_nominal.arff
new file mode 100644
index 0000000000000000000000000000000000000000..7cd16d1ef9b50cc1194d034ef4d458ef3cf0d417
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/io/arff/tests/data/quoted_nominal.arff
@@ -0,0 +1,13 @@
+% Regression test for issue #10232 : Exception in loadarff with quoted nominal attributes
+% Spaces between elements are stripped by the parser
+
+@relation SOME_DATA
+@attribute age numeric
+@attribute smoker {'yes', 'no'}
+@data
+18,  'no'
+24, 'yes'
+44,     'no'
+56, 'no'
+89,'yes'
+11,  'no'
diff --git a/.venv/lib/python3.12/site-packages/scipy/io/arff/tests/data/quoted_nominal_spaces.arff b/.venv/lib/python3.12/site-packages/scipy/io/arff/tests/data/quoted_nominal_spaces.arff
new file mode 100644
index 0000000000000000000000000000000000000000..c799127862b6060442b29c9a0382836cc9c55537
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/io/arff/tests/data/quoted_nominal_spaces.arff
@@ -0,0 +1,13 @@
+% Regression test for issue #10232 : Exception in loadarff with quoted nominal attributes
+% Spaces inside quotes are NOT stripped by the parser
+
+@relation SOME_DATA
+@attribute age numeric
+@attribute smoker {'  yes', 'no  '}
+@data
+18,'no  '
+24,'  yes'
+44,'no  '
+56,'no  '
+89,'  yes'
+11,'no  '
diff --git a/.venv/lib/python3.12/site-packages/scipy/io/arff/tests/data/test1.arff b/.venv/lib/python3.12/site-packages/scipy/io/arff/tests/data/test1.arff
new file mode 100644
index 0000000000000000000000000000000000000000..ccc8e0cc7c43dc66ad7b3a8e4738c3322d3f79d8
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/io/arff/tests/data/test1.arff
@@ -0,0 +1,10 @@
+@RELATION test1
+
+@ATTRIBUTE attr0	REAL
+@ATTRIBUTE attr1 	REAL
+@ATTRIBUTE attr2 	REAL
+@ATTRIBUTE attr3	REAL
+@ATTRIBUTE class 	{class0, class1, class2, class3}
+
+@DATA
+0.1, 0.2, 0.3, 0.4,class1
diff --git a/.venv/lib/python3.12/site-packages/scipy/io/arff/tests/data/test10.arff b/.venv/lib/python3.12/site-packages/scipy/io/arff/tests/data/test10.arff
new file mode 100644
index 0000000000000000000000000000000000000000..094ac5094a842866666726b358d2c66bf927c9d2
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/io/arff/tests/data/test10.arff
@@ -0,0 +1,8 @@
+@relation test9
+
+@attribute attr_relational	    relational
+	@attribute attr_number	integer
+@end attr_relational
+
+@data
+'0\n1\n2\n3\n4\n5\n6\n7\n8\n9\n10\n11\n12\n13\n14\n15\n16\n17\n18\n19\n20\n21\n22\n23\n24\n25\n26\n27\n28\n29\n30\n31\n32\n33\n34\n35\n36\n37\n38\n39\n40\n41\n42\n43\n44\n45\n46\n47\n48\n49\n50\n51\n52\n53\n54\n55\n56\n57\n58\n59\n60\n61\n62\n63\n64\n65\n66\n67\n68\n69\n70\n71\n72\n73\n74\n75\n76\n77\n78\n79\n80\n81\n82\n83\n84\n85\n86\n87\n88\n89\n90\n91\n92\n93\n94\n95\n96\n97\n98\n99\n100\n101\n102\n103\n104\n105\n106\n107\n108\n109\n110\n111\n112\n113\n114\n115\n116\n117\n118\n119\n120\n121\n122\n123\n124\n125\n126\n127\n128\n129\n130\n131\n132\n133\n134\n135\n136\n137\n138\n139\n140\n141\n142\n143\n144\n145\n146\n147\n148\n149\n150\n151\n152\n153\n154\n155\n156\n157\n158\n159\n160\n161\n162\n163\n164\n165\n166\n167\n168\n169\n170\n171\n172\n173\n174\n175\n176\n177\n178\n179\n180\n181\n182\n183\n184\n185\n186\n187\n188\n189\n190\n191\n192\n193\n194\n195\n196\n197\n198\n199\n200\n201\n202\n203\n204\n205\n206\n207\n208\n209\n210\n211\n212\n213\n214\n215\n216\n217\n218\n219\n220\n221\n222\n223\n224\n225\n226\n227\n228\n229\n230\n231\n232\n233\n234\n235\n236\n237\n238\n239\n240\n241\n242\n243\n244\n245\n246\n247\n248\n249\n250\n251\n252\n253\n254\n255\n256\n257\n258\n259\n260\n261\n262\n263\n264\n265\n266\n267\n268\n269\n270\n271\n272\n273\n274\n275\n276\n277\n278\n279\n280\n281\n282\n283\n284\n285\n286\n287\n288\n289\n290\n291\n292\n293\n294\n295\n296\n297\n298\n299\n300\n301\n302\n303\n304\n305\n306\n307\n308\n309\n310\n311\n312\n313\n314\n315\n316\n317\n318\n319\n320\n321\n322\n323\n324\n325\n326\n327\n328\n329\n330\n331\n332\n333\n334\n335\n336\n337\n338\n339\n340\n341\n342\n343\n344\n345\n346\n347\n348\n349\n350\n351\n352\n353\n354\n355\n356\n357\n358\n359\n360\n361\n362\n363\n364\n365\n366\n367\n368\n369\n370\n371\n372\n373\n374\n375\n376\n377\n378\n379\n380\n381\n382\n383\n384\n385\n386\n387\n388\n389\n390\n391\n392\n393\n394\n395\n396\n397\n398\n399\n400\n401\n402\n403\n404\n405\n406\n407\n408\n409\n410\n411\n412\n413\n414\n415\n416\n417\n418\n419\n420\n421\n422\n423\n424\n425\n426\n427\n428\n429\n430\n431\n432\n433\n434\n435\n436\n437\n438\n439\n440\n441\n442\n443\n444\n445\n446\n447\n448\n449\n450\n451\n452\n453\n454\n455\n456\n457\n458\n459\n460\n461\n462\n463\n464\n465\n466\n467\n468\n469\n470\n471\n472\n473\n474\n475\n476\n477\n478\n479\n480\n481\n482\n483\n484\n485\n486\n487\n488\n489\n490\n491\n492\n493\n494\n495\n496\n497\n498\n499\n500\n501\n502\n503\n504\n505\n506\n507\n508\n509\n510\n511\n512\n513\n514\n515\n516\n517\n518\n519\n520\n521\n522\n523\n524\n525\n526\n527\n528\n529\n530\n531\n532\n533\n534\n535\n536\n537\n538\n539\n540\n541\n542\n543\n544\n545\n546\n547\n548\n549\n550\n551\n552\n553\n554\n555\n556\n557\n558\n559\n560\n561\n562\n563\n564\n565\n566\n567\n568\n569\n570\n571\n572\n573\n574\n575\n576\n577\n578\n579\n580\n581\n582\n583\n584\n585\n586\n587\n588\n589\n590\n591\n592\n593\n594\n595\n596\n597\n598\n599\n600\n601\n602\n603\n604\n605\n606\n607\n608\n609\n610\n611\n612\n613\n614\n615\n616\n617\n618\n619\n620\n621\n622\n623\n624\n625\n626\n627\n628\n629\n630\n631\n632\n633\n634\n635\n636\n637\n638\n639\n640\n641\n642\n643\n644\n645\n646\n647\n648\n649\n650\n651\n652\n653\n654\n655\n656\n657\n658\n659\n660\n661\n662\n663\n664\n665\n666\n667\n668\n669\n670\n671\n672\n673\n674\n675\n676\n677\n678\n679\n680\n681\n682\n683\n684\n685\n686\n687\n688\n689\n690\n691\n692\n693\n694\n695\n696\n697\n698\n699\n700\n701\n702\n703\n704\n705\n706\n707\n708\n709\n710\n711\n712\n713\n714\n715\n716\n717\n718\n719\n720\n721\n722\n723\n724\n725\n726\n727\n728\n729\n730\n731\n732\n733\n734\n735\n736\n737\n738\n739\n740\n741\n742\n743\n744\n745\n746\n747\n748\n749\n750\n751\n752\n753\n754\n755\n756\n757\n758\n759\n760\n761\n762\n763\n764\n765\n766\n767\n768\n769\n770\n771\n772\n773\n774\n775\n776\n777\n778\n779\n780\n781\n782\n783\n784\n785\n786\n787\n788\n789\n790\n791\n792\n793\n794\n795\n796\n797\n798\n799\n800\n801\n802\n803\n804\n805\n806\n807\n808\n809\n810\n811\n812\n813\n814\n815\n816\n817\n818\n819\n820\n821\n822\n823\n824\n825\n826\n827\n828\n829\n830\n831\n832\n833\n834\n835\n836\n837\n838\n839\n840\n841\n842\n843\n844\n845\n846\n847\n848\n849\n850\n851\n852\n853\n854\n855\n856\n857\n858\n859\n860\n861\n862\n863\n864\n865\n866\n867\n868\n869\n870\n871\n872\n873\n874\n875\n876\n877\n878\n879\n880\n881\n882\n883\n884\n885\n886\n887\n888\n889\n890\n891\n892\n893\n894\n895\n896\n897\n898\n899\n900\n901\n902\n903\n904\n905\n906\n907\n908\n909\n910\n911\n912\n913\n914\n915\n916\n917\n918\n919\n920\n921\n922\n923\n924\n925\n926\n927\n928\n929\n930\n931\n932\n933\n934\n935\n936\n937\n938\n939\n940\n941\n942\n943\n944\n945\n946\n947\n948\n949\n950\n951\n952\n953\n954\n955\n956\n957\n958\n959\n960\n961\n962\n963\n964\n965\n966\n967\n968\n969\n970\n971\n972\n973\n974\n975\n976\n977\n978\n979\n980\n981\n982\n983\n984\n985\n986\n987\n988\n989\n990\n991\n992\n993\n994\n995\n996\n997\n998\n999\n1000\n1001\n1002\n1003\n1004\n1005\n1006\n1007\n1008\n1009\n1010\n1011\n1012\n1013\n1014\n1015\n1016\n1017\n1018\n1019\n1020\n1021\n1022\n1023\n1024\n1025\n1026\n1027\n1028\n1029\n1030\n1031\n1032\n1033\n1034\n1035\n1036\n1037\n1038\n1039\n1040\n1041\n1042\n1043\n1044\n1045\n1046\n1047\n1048\n1049\n1050\n1051\n1052\n1053\n1054\n1055\n1056\n1057\n1058\n1059\n1060\n1061\n1062\n1063\n1064\n1065\n1066\n1067\n1068\n1069\n1070\n1071\n1072\n1073\n1074\n1075\n1076\n1077\n1078\n1079\n1080\n1081\n1082\n1083\n1084\n1085\n1086\n1087\n1088\n1089\n1090\n1091\n1092\n1093\n1094\n1095\n1096\n1097\n1098\n1099\n1100\n1101\n1102\n1103\n1104\n1105\n1106\n1107\n1108\n1109\n1110\n1111\n1112\n1113\n1114\n1115\n1116\n1117\n1118\n1119\n1120\n1121\n1122\n1123\n1124\n1125\n1126\n1127\n1128\n1129\n1130\n1131\n1132\n1133\n1134\n1135\n1136\n1137\n1138\n1139\n1140\n1141\n1142\n1143\n1144\n1145\n1146\n1147\n1148\n1149\n1150\n1151\n1152\n1153\n1154\n1155\n1156\n1157\n1158\n1159\n1160\n1161\n1162\n1163\n1164\n1165\n1166\n1167\n1168\n1169\n1170\n1171\n1172\n1173\n1174\n1175\n1176\n1177\n1178\n1179\n1180\n1181\n1182\n1183\n1184\n1185\n1186\n1187\n1188\n1189\n1190\n1191\n1192\n1193\n1194\n1195\n1196\n1197\n1198\n1199\n1200\n1201\n1202\n1203\n1204\n1205\n1206\n1207\n1208\n1209\n1210\n1211\n1212\n1213\n1214\n1215\n1216\n1217\n1218\n1219\n1220\n1221\n1222\n1223\n1224\n1225\n1226\n1227\n1228\n1229\n1230\n1231\n1232\n1233\n1234\n1235\n1236\n1237\n1238\n1239\n1240\n1241\n1242\n1243\n1244\n1245\n1246\n1247\n1248\n1249\n1250\n1251\n1252\n1253\n1254\n1255\n1256\n1257\n1258\n1259\n1260\n1261\n1262\n1263\n1264\n1265\n1266\n1267\n1268\n1269\n1270\n1271\n1272\n1273\n1274\n1275\n1276\n1277\n1278\n1279\n1280\n1281\n1282\n1283\n1284\n1285\n1286\n1287\n1288\n1289\n1290\n1291\n1292\n1293\n1294\n1295\n1296\n1297\n1298\n1299\n1300\n1301\n1302\n1303\n1304\n1305\n1306\n1307\n1308\n1309\n1310\n1311\n1312\n1313\n1314\n1315\n1316\n1317\n1318\n1319\n1320\n1321\n1322\n1323\n1324\n1325\n1326\n1327\n1328\n1329\n1330\n1331\n1332\n1333\n1334\n1335\n1336\n1337\n1338\n1339\n1340\n1341\n1342\n1343\n1344\n1345\n1346\n1347\n1348\n1349\n1350\n1351\n1352\n1353\n1354\n1355\n1356\n1357\n1358\n1359\n1360\n1361\n1362\n1363\n1364\n1365\n1366\n1367\n1368\n1369\n1370\n1371\n1372\n1373\n1374\n1375\n1376\n1377\n1378\n1379\n1380\n1381\n1382\n1383\n1384\n1385\n1386\n1387\n1388\n1389\n1390\n1391\n1392\n1393\n1394\n1395\n1396\n1397\n1398\n1399\n1400\n1401\n1402\n1403\n1404\n1405\n1406\n1407\n1408\n1409\n1410\n1411\n1412\n1413\n1414\n1415\n1416\n1417\n1418\n1419\n1420\n1421\n1422\n1423\n1424\n1425\n1426\n1427\n1428\n1429\n1430\n1431\n1432\n1433\n1434\n1435\n1436\n1437\n1438\n1439\n1440\n1441\n1442\n1443\n1444\n1445\n1446\n1447\n1448\n1449\n1450\n1451\n1452\n1453\n1454\n1455\n1456\n1457\n1458\n1459\n1460\n1461\n1462\n1463\n1464\n1465\n1466\n1467\n1468\n1469\n1470\n1471\n1472\n1473\n1474\n1475\n1476\n1477\n1478\n1479\n1480\n1481\n1482\n1483\n1484\n1485\n1486\n1487\n1488\n1489\n1490\n1491\n1492\n1493\n1494\n1495\n1496\n1497\n1498\n1499\n1500\n1501\n1502\n1503\n1504\n1505\n1506\n1507\n1508\n1509\n1510\n1511\n1512\n1513\n1514\n1515\n1516\n1517\n1518\n1519\n1520\n1521\n1522\n1523\n1524\n1525\n1526\n1527\n1528\n1529\n1530\n1531\n1532\n1533\n1534\n1535\n1536\n1537\n1538\n1539\n1540\n1541\n1542\n1543\n1544\n1545\n1546\n1547\n1548\n1549\n1550\n1551\n1552\n1553\n1554\n1555\n1556\n1557\n1558\n1559\n1560\n1561\n1562\n1563\n1564\n1565\n1566\n1567\n1568\n1569\n1570\n1571\n1572\n1573\n1574\n1575\n1576\n1577\n1578\n1579\n1580\n1581\n1582\n1583\n1584\n1585\n1586\n1587\n1588\n1589\n1590\n1591\n1592\n1593\n1594\n1595\n1596\n1597\n1598\n1599\n1600\n1601\n1602\n1603\n1604\n1605\n1606\n1607\n1608\n1609\n1610\n1611\n1612\n1613\n1614\n1615\n1616\n1617\n1618\n1619\n1620\n1621\n1622\n1623\n1624\n1625\n1626\n1627\n1628\n1629\n1630\n1631\n1632\n1633\n1634\n1635\n1636\n1637\n1638\n1639\n1640\n1641\n1642\n1643\n1644\n1645\n1646\n1647\n1648\n1649\n1650\n1651\n1652\n1653\n1654\n1655\n1656\n1657\n1658\n1659\n1660\n1661\n1662\n1663\n1664\n1665\n1666\n1667\n1668\n1669\n1670\n1671\n1672\n1673\n1674\n1675\n1676\n1677\n1678\n1679\n1680\n1681\n1682\n1683\n1684\n1685\n1686\n1687\n1688\n1689\n1690\n1691\n1692\n1693\n1694\n1695\n1696\n1697\n1698\n1699\n1700\n1701\n1702\n1703\n1704\n1705\n1706\n1707\n1708\n1709\n1710\n1711\n1712\n1713\n1714\n1715\n1716\n1717\n1718\n1719\n1720\n1721\n1722\n1723\n1724\n1725\n1726\n1727\n1728\n1729\n1730\n1731\n1732\n1733\n1734\n1735\n1736\n1737\n1738\n1739\n1740\n1741\n1742\n1743\n1744\n1745\n1746\n1747\n1748\n1749\n1750\n1751\n1752\n1753\n1754\n1755\n1756\n1757\n1758\n1759\n1760\n1761\n1762\n1763\n1764\n1765\n1766\n1767\n1768\n1769\n1770\n1771\n1772\n1773\n1774\n1775\n1776\n1777\n1778\n1779\n1780\n1781\n1782\n1783\n1784\n1785\n1786\n1787\n1788\n1789\n1790\n1791\n1792\n1793\n1794\n1795\n1796\n1797\n1798\n1799\n1800\n1801\n1802\n1803\n1804\n1805\n1806\n1807\n1808\n1809\n1810\n1811\n1812\n1813\n1814\n1815\n1816\n1817\n1818\n1819\n1820\n1821\n1822\n1823\n1824\n1825\n1826\n1827\n1828\n1829\n1830\n1831\n1832\n1833\n1834\n1835\n1836\n1837\n1838\n1839\n1840\n1841\n1842\n1843\n1844\n1845\n1846\n1847\n1848\n1849\n1850\n1851\n1852\n1853\n1854\n1855\n1856\n1857\n1858\n1859\n1860\n1861\n1862\n1863\n1864\n1865\n1866\n1867\n1868\n1869\n1870\n1871\n1872\n1873\n1874\n1875\n1876\n1877\n1878\n1879\n1880\n1881\n1882\n1883\n1884\n1885\n1886\n1887\n1888\n1889\n1890\n1891\n1892\n1893\n1894\n1895\n1896\n1897\n1898\n1899\n1900\n1901\n1902\n1903\n1904\n1905\n1906\n1907\n1908\n1909\n1910\n1911\n1912\n1913\n1914\n1915\n1916\n1917\n1918\n1919\n1920\n1921\n1922\n1923\n1924\n1925\n1926\n1927\n1928\n1929\n1930\n1931\n1932\n1933\n1934\n1935\n1936\n1937\n1938\n1939\n1940\n1941\n1942\n1943\n1944\n1945\n1946\n1947\n1948\n1949\n1950\n1951\n1952\n1953\n1954\n1955\n1956\n1957\n1958\n1959\n1960\n1961\n1962\n1963\n1964\n1965\n1966\n1967\n1968\n1969\n1970\n1971\n1972\n1973\n1974\n1975\n1976\n1977\n1978\n1979\n1980\n1981\n1982\n1983\n1984\n1985\n1986\n1987\n1988\n1989\n1990\n1991\n1992\n1993\n1994\n1995\n1996\n1997\n1998\n1999\n2000\n2001\n2002\n2003\n2004\n2005\n2006\n2007\n2008\n2009\n2010\n2011\n2012\n2013\n2014\n2015\n2016\n2017\n2018\n2019\n2020\n2021\n2022\n2023\n2024\n2025\n2026\n2027\n2028\n2029\n2030\n2031\n2032\n2033\n2034\n2035\n2036\n2037\n2038\n2039\n2040\n2041\n2042\n2043\n2044\n2045\n2046\n2047\n2048\n2049\n2050\n2051\n2052\n2053\n2054\n2055\n2056\n2057\n2058\n2059\n2060\n2061\n2062\n2063\n2064\n2065\n2066\n2067\n2068\n2069\n2070\n2071\n2072\n2073\n2074\n2075\n2076\n2077\n2078\n2079\n2080\n2081\n2082\n2083\n2084\n2085\n2086\n2087\n2088\n2089\n2090\n2091\n2092\n2093\n2094\n2095\n2096\n2097\n2098\n2099\n2100\n2101\n2102\n2103\n2104\n2105\n2106\n2107\n2108\n2109\n2110\n2111\n2112\n2113\n2114\n2115\n2116\n2117\n2118\n2119\n2120\n2121\n2122\n2123\n2124\n2125\n2126\n2127\n2128\n2129\n2130\n2131\n2132\n2133\n2134\n2135\n2136\n2137\n2138\n2139\n2140\n2141\n2142\n2143\n2144\n2145\n2146\n2147\n2148\n2149\n2150\n2151\n2152\n2153\n2154\n2155\n2156\n2157\n2158\n2159\n2160\n2161\n2162\n2163\n2164\n2165\n2166\n2167\n2168\n2169\n2170\n2171\n2172\n2173\n2174\n2175\n2176\n2177\n2178\n2179\n2180\n2181\n2182\n2183\n2184\n2185\n2186\n2187\n2188\n2189\n2190\n2191\n2192\n2193\n2194\n2195\n2196\n2197\n2198\n2199\n2200\n2201\n2202\n2203\n2204\n2205\n2206\n2207\n2208\n2209\n2210\n2211\n2212\n2213\n2214\n2215\n2216\n2217\n2218\n2219\n2220\n2221\n2222\n2223\n2224\n2225\n2226\n2227\n2228\n2229\n2230\n2231\n2232\n2233\n2234\n2235\n2236\n2237\n2238\n2239\n2240\n2241\n2242\n2243\n2244\n2245\n2246\n2247\n2248\n2249\n2250\n2251\n2252\n2253\n2254\n2255\n2256\n2257\n2258\n2259\n2260\n2261\n2262\n2263\n2264\n2265\n2266\n2267\n2268\n2269\n2270\n2271\n2272\n2273\n2274\n2275\n2276\n2277\n2278\n2279\n2280\n2281\n2282\n2283\n2284\n2285\n2286\n2287\n2288\n2289\n2290\n2291\n2292\n2293\n2294\n2295\n2296\n2297\n2298\n2299\n2300\n2301\n2302\n2303\n2304\n2305\n2306\n2307\n2308\n2309\n2310\n2311\n2312\n2313\n2314\n2315\n2316\n2317\n2318\n2319\n2320\n2321\n2322\n2323\n2324\n2325\n2326\n2327\n2328\n2329\n2330\n2331\n2332\n2333\n2334\n2335\n2336\n2337\n2338\n2339\n2340\n2341\n2342\n2343\n2344\n2345\n2346\n2347\n2348\n2349\n2350\n2351\n2352\n2353\n2354\n2355\n2356\n2357\n2358\n2359\n2360\n2361\n2362\n2363\n2364\n2365\n2366\n2367\n2368\n2369\n2370\n2371\n2372\n2373\n2374\n2375\n2376\n2377\n2378\n2379\n2380\n2381\n2382\n2383\n2384\n2385\n2386\n2387\n2388\n2389\n2390\n2391\n2392\n2393\n2394\n2395\n2396\n2397\n2398\n2399\n2400\n2401\n2402\n2403\n2404\n2405\n2406\n2407\n2408\n2409\n2410\n2411\n2412\n2413\n2414\n2415\n2416\n2417\n2418\n2419\n2420\n2421\n2422\n2423\n2424\n2425\n2426\n2427\n2428\n2429\n2430\n2431\n2432\n2433\n2434\n2435\n2436\n2437\n2438\n2439\n2440\n2441\n2442\n2443\n2444\n2445\n2446\n2447\n2448\n2449\n2450\n2451\n2452\n2453\n2454\n2455\n2456\n2457\n2458\n2459\n2460\n2461\n2462\n2463\n2464\n2465\n2466\n2467\n2468\n2469\n2470\n2471\n2472\n2473\n2474\n2475\n2476\n2477\n2478\n2479\n2480\n2481\n2482\n2483\n2484\n2485\n2486\n2487\n2488\n2489\n2490\n2491\n2492\n2493\n2494\n2495\n2496\n2497\n2498\n2499\n2500\n2501\n2502\n2503\n2504\n2505\n2506\n2507\n2508\n2509\n2510\n2511\n2512\n2513\n2514\n2515\n2516\n2517\n2518\n2519\n2520\n2521\n2522\n2523\n2524\n2525\n2526\n2527\n2528\n2529\n2530\n2531\n2532\n2533\n2534\n2535\n2536\n2537\n2538\n2539\n2540\n2541\n2542\n2543\n2544\n2545\n2546\n2547\n2548\n2549\n2550\n2551\n2552\n2553\n2554\n2555\n2556\n2557\n2558\n2559\n2560\n2561\n2562\n2563\n2564\n2565\n2566\n2567\n2568\n2569\n2570\n2571\n2572\n2573\n2574\n2575\n2576\n2577\n2578\n2579\n2580\n2581\n2582\n2583\n2584\n2585\n2586\n2587\n2588\n2589\n2590\n2591\n2592\n2593\n2594\n2595\n2596\n2597\n2598\n2599\n2600\n2601\n2602\n2603\n2604\n2605\n2606\n2607\n2608\n2609\n2610\n2611\n2612\n2613\n2614\n2615\n2616\n2617\n2618\n2619\n2620\n2621\n2622\n2623\n2624\n2625\n2626\n2627\n2628\n2629\n2630\n2631\n2632\n2633\n2634\n2635\n2636\n2637\n2638\n2639\n2640\n2641\n2642\n2643\n2644\n2645\n2646\n2647\n2648\n2649\n2650\n2651\n2652\n2653\n2654\n2655\n2656\n2657\n2658\n2659\n2660\n2661\n2662\n2663\n2664\n2665\n2666\n2667\n2668\n2669\n2670\n2671\n2672\n2673\n2674\n2675\n2676\n2677\n2678\n2679\n2680\n2681\n2682\n2683\n2684\n2685\n2686\n2687\n2688\n2689\n2690\n2691\n2692\n2693\n2694\n2695\n2696\n2697\n2698\n2699\n2700\n2701\n2702\n2703\n2704\n2705\n2706\n2707\n2708\n2709\n2710\n2711\n2712\n2713\n2714\n2715\n2716\n2717\n2718\n2719\n2720\n2721\n2722\n2723\n2724\n2725\n2726\n2727\n2728\n2729\n2730\n2731\n2732\n2733\n2734\n2735\n2736\n2737\n2738\n2739\n2740\n2741\n2742\n2743\n2744\n2745\n2746\n2747\n2748\n2749\n2750\n2751\n2752\n2753\n2754\n2755\n2756\n2757\n2758\n2759\n2760\n2761\n2762\n2763\n2764\n2765\n2766\n2767\n2768\n2769\n2770\n2771\n2772\n2773\n2774\n2775\n2776\n2777\n2778\n2779\n2780\n2781\n2782\n2783\n2784\n2785\n2786\n2787\n2788\n2789\n2790\n2791\n2792\n2793\n2794\n2795\n2796\n2797\n2798\n2799\n2800\n2801\n2802\n2803\n2804\n2805\n2806\n2807\n2808\n2809\n2810\n2811\n2812\n2813\n2814\n2815\n2816\n2817\n2818\n2819\n2820\n2821\n2822\n2823\n2824\n2825\n2826\n2827\n2828\n2829\n2830\n2831\n2832\n2833\n2834\n2835\n2836\n2837\n2838\n2839\n2840\n2841\n2842\n2843\n2844\n2845\n2846\n2847\n2848\n2849\n2850\n2851\n2852\n2853\n2854\n2855\n2856\n2857\n2858\n2859\n2860\n2861\n2862\n2863\n2864\n2865\n2866\n2867\n2868\n2869\n2870\n2871\n2872\n2873\n2874\n2875\n2876\n2877\n2878\n2879\n2880\n2881\n2882\n2883\n2884\n2885\n2886\n2887\n2888\n2889\n2890\n2891\n2892\n2893\n2894\n2895\n2896\n2897\n2898\n2899\n2900\n2901\n2902\n2903\n2904\n2905\n2906\n2907\n2908\n2909\n2910\n2911\n2912\n2913\n2914\n2915\n2916\n2917\n2918\n2919\n2920\n2921\n2922\n2923\n2924\n2925\n2926\n2927\n2928\n2929\n2930\n2931\n2932\n2933\n2934\n2935\n2936\n2937\n2938\n2939\n2940\n2941\n2942\n2943\n2944\n2945\n2946\n2947\n2948\n2949\n2950\n2951\n2952\n2953\n2954\n2955\n2956\n2957\n2958\n2959\n2960\n2961\n2962\n2963\n2964\n2965\n2966\n2967\n2968\n2969\n2970\n2971\n2972\n2973\n2974\n2975\n2976\n2977\n2978\n2979\n2980\n2981\n2982\n2983\n2984\n2985\n2986\n2987\n2988\n2989\n2990\n2991\n2992\n2993\n2994\n2995\n2996\n2997\n2998\n2999\n3000\n3001\n3002\n3003\n3004\n3005\n3006\n3007\n3008\n3009\n3010\n3011\n3012\n3013\n3014\n3015\n3016\n3017\n3018\n3019\n3020\n3021\n3022\n3023\n3024\n3025\n3026\n3027\n3028\n3029\n3030\n3031\n3032\n3033\n3034\n3035\n3036\n3037\n3038\n3039\n3040\n3041\n3042\n3043\n3044\n3045\n3046\n3047\n3048\n3049\n3050\n3051\n3052\n3053\n3054\n3055\n3056\n3057\n3058\n3059\n3060\n3061\n3062\n3063\n3064\n3065\n3066\n3067\n3068\n3069\n3070\n3071\n3072\n3073\n3074\n3075\n3076\n3077\n3078\n3079\n3080\n3081\n3082\n3083\n3084\n3085\n3086\n3087\n3088\n3089\n3090\n3091\n3092\n3093\n3094\n3095\n3096\n3097\n3098\n3099\n3100\n3101\n3102\n3103\n3104\n3105\n3106\n3107\n3108\n3109\n3110\n3111\n3112\n3113\n3114\n3115\n3116\n3117\n3118\n3119\n3120\n3121\n3122\n3123\n3124\n3125\n3126\n3127\n3128\n3129\n3130\n3131\n3132\n3133\n3134\n3135\n3136\n3137\n3138\n3139\n3140\n3141\n3142\n3143\n3144\n3145\n3146\n3147\n3148\n3149\n3150\n3151\n3152\n3153\n3154\n3155\n3156\n3157\n3158\n3159\n3160\n3161\n3162\n3163\n3164\n3165\n3166\n3167\n3168\n3169\n3170\n3171\n3172\n3173\n3174\n3175\n3176\n3177\n3178\n3179\n3180\n3181\n3182\n3183\n3184\n3185\n3186\n3187\n3188\n3189\n3190\n3191\n3192\n3193\n3194\n3195\n3196\n3197\n3198\n3199\n3200\n3201\n3202\n3203\n3204\n3205\n3206\n3207\n3208\n3209\n3210\n3211\n3212\n3213\n3214\n3215\n3216\n3217\n3218\n3219\n3220\n3221\n3222\n3223\n3224\n3225\n3226\n3227\n3228\n3229\n3230\n3231\n3232\n3233\n3234\n3235\n3236\n3237\n3238\n3239\n3240\n3241\n3242\n3243\n3244\n3245\n3246\n3247\n3248\n3249\n3250\n3251\n3252\n3253\n3254\n3255\n3256\n3257\n3258\n3259\n3260\n3261\n3262\n3263\n3264\n3265\n3266\n3267\n3268\n3269\n3270\n3271\n3272\n3273\n3274\n3275\n3276\n3277\n3278\n3279\n3280\n3281\n3282\n3283\n3284\n3285\n3286\n3287\n3288\n3289\n3290\n3291\n3292\n3293\n3294\n3295\n3296\n3297\n3298\n3299\n3300\n3301\n3302\n3303\n3304\n3305\n3306\n3307\n3308\n3309\n3310\n3311\n3312\n3313\n3314\n3315\n3316\n3317\n3318\n3319\n3320\n3321\n3322\n3323\n3324\n3325\n3326\n3327\n3328\n3329\n3330\n3331\n3332\n3333\n3334\n3335\n3336\n3337\n3338\n3339\n3340\n3341\n3342\n3343\n3344\n3345\n3346\n3347\n3348\n3349\n3350\n3351\n3352\n3353\n3354\n3355\n3356\n3357\n3358\n3359\n3360\n3361\n3362\n3363\n3364\n3365\n3366\n3367\n3368\n3369\n3370\n3371\n3372\n3373\n3374\n3375\n3376\n3377\n3378\n3379\n3380\n3381\n3382\n3383\n3384\n3385\n3386\n3387\n3388\n3389\n3390\n3391\n3392\n3393\n3394\n3395\n3396\n3397\n3398\n3399\n3400\n3401\n3402\n3403\n3404\n3405\n3406\n3407\n3408\n3409\n3410\n3411\n3412\n3413\n3414\n3415\n3416\n3417\n3418\n3419\n3420\n3421\n3422\n3423\n3424\n3425\n3426\n3427\n3428\n3429\n3430\n3431\n3432\n3433\n3434\n3435\n3436\n3437\n3438\n3439\n3440\n3441\n3442\n3443\n3444\n3445\n3446\n3447\n3448\n3449\n3450\n3451\n3452\n3453\n3454\n3455\n3456\n3457\n3458\n3459\n3460\n3461\n3462\n3463\n3464\n3465\n3466\n3467\n3468\n3469\n3470\n3471\n3472\n3473\n3474\n3475\n3476\n3477\n3478\n3479\n3480\n3481\n3482\n3483\n3484\n3485\n3486\n3487\n3488\n3489\n3490\n3491\n3492\n3493\n3494\n3495\n3496\n3497\n3498\n3499\n3500\n3501\n3502\n3503\n3504\n3505\n3506\n3507\n3508\n3509\n3510\n3511\n3512\n3513\n3514\n3515\n3516\n3517\n3518\n3519\n3520\n3521\n3522\n3523\n3524\n3525\n3526\n3527\n3528\n3529\n3530\n3531\n3532\n3533\n3534\n3535\n3536\n3537\n3538\n3539\n3540\n3541\n3542\n3543\n3544\n3545\n3546\n3547\n3548\n3549\n3550\n3551\n3552\n3553\n3554\n3555\n3556\n3557\n3558\n3559\n3560\n3561\n3562\n3563\n3564\n3565\n3566\n3567\n3568\n3569\n3570\n3571\n3572\n3573\n3574\n3575\n3576\n3577\n3578\n3579\n3580\n3581\n3582\n3583\n3584\n3585\n3586\n3587\n3588\n3589\n3590\n3591\n3592\n3593\n3594\n3595\n3596\n3597\n3598\n3599\n3600\n3601\n3602\n3603\n3604\n3605\n3606\n3607\n3608\n3609\n3610\n3611\n3612\n3613\n3614\n3615\n3616\n3617\n3618\n3619\n3620\n3621\n3622\n3623\n3624\n3625\n3626\n3627\n3628\n3629\n3630\n3631\n3632\n3633\n3634\n3635\n3636\n3637\n3638\n3639\n3640\n3641\n3642\n3643\n3644\n3645\n3646\n3647\n3648\n3649\n3650\n3651\n3652\n3653\n3654\n3655\n3656\n3657\n3658\n3659\n3660\n3661\n3662\n3663\n3664\n3665\n3666\n3667\n3668\n3669\n3670\n3671\n3672\n3673\n3674\n3675\n3676\n3677\n3678\n3679\n3680\n3681\n3682\n3683\n3684\n3685\n3686\n3687\n3688\n3689\n3690\n3691\n3692\n3693\n3694\n3695\n3696\n3697\n3698\n3699\n3700\n3701\n3702\n3703\n3704\n3705\n3706\n3707\n3708\n3709\n3710\n3711\n3712\n3713\n3714\n3715\n3716\n3717\n3718\n3719\n3720\n3721\n3722\n3723\n3724\n3725\n3726\n3727\n3728\n3729\n3730\n3731\n3732\n3733\n3734\n3735\n3736\n3737\n3738\n3739\n3740\n3741\n3742\n3743\n3744\n3745\n3746\n3747\n3748\n3749\n3750\n3751\n3752\n3753\n3754\n3755\n3756\n3757\n3758\n3759\n3760\n3761\n3762\n3763\n3764\n3765\n3766\n3767\n3768\n3769\n3770\n3771\n3772\n3773\n3774\n3775\n3776\n3777\n3778\n3779\n3780\n3781\n3782\n3783\n3784\n3785\n3786\n3787\n3788\n3789\n3790\n3791\n3792\n3793\n3794\n3795\n3796\n3797\n3798\n3799\n3800\n3801\n3802\n3803\n3804\n3805\n3806\n3807\n3808\n3809\n3810\n3811\n3812\n3813\n3814\n3815\n3816\n3817\n3818\n3819\n3820\n3821\n3822\n3823\n3824\n3825\n3826\n3827\n3828\n3829\n3830\n3831\n3832\n3833\n3834\n3835\n3836\n3837\n3838\n3839\n3840\n3841\n3842\n3843\n3844\n3845\n3846\n3847\n3848\n3849\n3850\n3851\n3852\n3853\n3854\n3855\n3856\n3857\n3858\n3859\n3860\n3861\n3862\n3863\n3864\n3865\n3866\n3867\n3868\n3869\n3870\n3871\n3872\n3873\n3874\n3875\n3876\n3877\n3878\n3879\n3880\n3881\n3882\n3883\n3884\n3885\n3886\n3887\n3888\n3889\n3890\n3891\n3892\n3893\n3894\n3895\n3896\n3897\n3898\n3899\n3900\n3901\n3902\n3903\n3904\n3905\n3906\n3907\n3908\n3909\n3910\n3911\n3912\n3913\n3914\n3915\n3916\n3917\n3918\n3919\n3920\n3921\n3922\n3923\n3924\n3925\n3926\n3927\n3928\n3929\n3930\n3931\n3932\n3933\n3934\n3935\n3936\n3937\n3938\n3939\n3940\n3941\n3942\n3943\n3944\n3945\n3946\n3947\n3948\n3949\n3950\n3951\n3952\n3953\n3954\n3955\n3956\n3957\n3958\n3959\n3960\n3961\n3962\n3963\n3964\n3965\n3966\n3967\n3968\n3969\n3970\n3971\n3972\n3973\n3974\n3975\n3976\n3977\n3978\n3979\n3980\n3981\n3982\n3983\n3984\n3985\n3986\n3987\n3988\n3989\n3990\n3991\n3992\n3993\n3994\n3995\n3996\n3997\n3998\n3999\n4000\n4001\n4002\n4003\n4004\n4005\n4006\n4007\n4008\n4009\n4010\n4011\n4012\n4013\n4014\n4015\n4016\n4017\n4018\n4019\n4020\n4021\n4022\n4023\n4024\n4025\n4026\n4027\n4028\n4029\n4030\n4031\n4032\n4033\n4034\n4035\n4036\n4037\n4038\n4039\n4040\n4041\n4042\n4043\n4044\n4045\n4046\n4047\n4048\n4049\n4050\n4051\n4052\n4053\n4054\n4055\n4056\n4057\n4058\n4059\n4060\n4061\n4062\n4063\n4064\n4065\n4066\n4067\n4068\n4069\n4070\n4071\n4072\n4073\n4074\n4075\n4076\n4077\n4078\n4079\n4080\n4081\n4082\n4083\n4084\n4085\n4086\n4087\n4088\n4089\n4090\n4091\n4092\n4093\n4094\n4095\n4096\n4097\n4098\n4099\n4100\n4101\n4102\n4103\n4104\n4105\n4106\n4107\n4108\n4109\n4110\n4111\n4112\n4113\n4114\n4115\n4116\n4117\n4118\n4119\n4120\n4121\n4122\n4123\n4124\n4125\n4126\n4127\n4128\n4129\n4130\n4131\n4132\n4133\n4134\n4135\n4136\n4137\n4138\n4139\n4140\n4141\n4142\n4143\n4144\n4145\n4146\n4147\n4148\n4149\n4150\n4151\n4152\n4153\n4154\n4155\n4156\n4157\n4158\n4159\n4160\n4161\n4162\n4163\n4164\n4165\n4166\n4167\n4168\n4169\n4170\n4171\n4172\n4173\n4174\n4175\n4176\n4177\n4178\n4179\n4180\n4181\n4182\n4183\n4184\n4185\n4186\n4187\n4188\n4189\n4190\n4191\n4192\n4193\n4194\n4195\n4196\n4197\n4198\n4199\n4200\n4201\n4202\n4203\n4204\n4205\n4206\n4207\n4208\n4209\n4210\n4211\n4212\n4213\n4214\n4215\n4216\n4217\n4218\n4219\n4220\n4221\n4222\n4223\n4224\n4225\n4226\n4227\n4228\n4229\n4230\n4231\n4232\n4233\n4234\n4235\n4236\n4237\n4238\n4239\n4240\n4241\n4242\n4243\n4244\n4245\n4246\n4247\n4248\n4249\n4250\n4251\n4252\n4253\n4254\n4255\n4256\n4257\n4258\n4259\n4260\n4261\n4262\n4263\n4264\n4265\n4266\n4267\n4268\n4269\n4270\n4271\n4272\n4273\n4274\n4275\n4276\n4277\n4278\n4279\n4280\n4281\n4282\n4283\n4284\n4285\n4286\n4287\n4288\n4289\n4290\n4291\n4292\n4293\n4294\n4295\n4296\n4297\n4298\n4299\n4300\n4301\n4302\n4303\n4304\n4305\n4306\n4307\n4308\n4309\n4310\n4311\n4312\n4313\n4314\n4315\n4316\n4317\n4318\n4319\n4320\n4321\n4322\n4323\n4324\n4325\n4326\n4327\n4328\n4329\n4330\n4331\n4332\n4333\n4334\n4335\n4336\n4337\n4338\n4339\n4340\n4341\n4342\n4343\n4344\n4345\n4346\n4347\n4348\n4349\n4350\n4351\n4352\n4353\n4354\n4355\n4356\n4357\n4358\n4359\n4360\n4361\n4362\n4363\n4364\n4365\n4366\n4367\n4368\n4369\n4370\n4371\n4372\n4373\n4374\n4375\n4376\n4377\n4378\n4379\n4380\n4381\n4382\n4383\n4384\n4385\n4386\n4387\n4388\n4389\n4390\n4391\n4392\n4393\n4394\n4395\n4396\n4397\n4398\n4399\n4400\n4401\n4402\n4403\n4404\n4405\n4406\n4407\n4408\n4409\n4410\n4411\n4412\n4413\n4414\n4415\n4416\n4417\n4418\n4419\n4420\n4421\n4422\n4423\n4424\n4425\n4426\n4427\n4428\n4429\n4430\n4431\n4432\n4433\n4434\n4435\n4436\n4437\n4438\n4439\n4440\n4441\n4442\n4443\n4444\n4445\n4446\n4447\n4448\n4449\n4450\n4451\n4452\n4453\n4454\n4455\n4456\n4457\n4458\n4459\n4460\n4461\n4462\n4463\n4464\n4465\n4466\n4467\n4468\n4469\n4470\n4471\n4472\n4473\n4474\n4475\n4476\n4477\n4478\n4479\n4480\n4481\n4482\n4483\n4484\n4485\n4486\n4487\n4488\n4489\n4490\n4491\n4492\n4493\n4494\n4495\n4496\n4497\n4498\n4499\n4500\n4501\n4502\n4503\n4504\n4505\n4506\n4507\n4508\n4509\n4510\n4511\n4512\n4513\n4514\n4515\n4516\n4517\n4518\n4519\n4520\n4521\n4522\n4523\n4524\n4525\n4526\n4527\n4528\n4529\n4530\n4531\n4532\n4533\n4534\n4535\n4536\n4537\n4538\n4539\n4540\n4541\n4542\n4543\n4544\n4545\n4546\n4547\n4548\n4549\n4550\n4551\n4552\n4553\n4554\n4555\n4556\n4557\n4558\n4559\n4560\n4561\n4562\n4563\n4564\n4565\n4566\n4567\n4568\n4569\n4570\n4571\n4572\n4573\n4574\n4575\n4576\n4577\n4578\n4579\n4580\n4581\n4582\n4583\n4584\n4585\n4586\n4587\n4588\n4589\n4590\n4591\n4592\n4593\n4594\n4595\n4596\n4597\n4598\n4599\n4600\n4601\n4602\n4603\n4604\n4605\n4606\n4607\n4608\n4609\n4610\n4611\n4612\n4613\n4614\n4615\n4616\n4617\n4618\n4619\n4620\n4621\n4622\n4623\n4624\n4625\n4626\n4627\n4628\n4629\n4630\n4631\n4632\n4633\n4634\n4635\n4636\n4637\n4638\n4639\n4640\n4641\n4642\n4643\n4644\n4645\n4646\n4647\n4648\n4649\n4650\n4651\n4652\n4653\n4654\n4655\n4656\n4657\n4658\n4659\n4660\n4661\n4662\n4663\n4664\n4665\n4666\n4667\n4668\n4669\n4670\n4671\n4672\n4673\n4674\n4675\n4676\n4677\n4678\n4679\n4680\n4681\n4682\n4683\n4684\n4685\n4686\n4687\n4688\n4689\n4690\n4691\n4692\n4693\n4694\n4695\n4696\n4697\n4698\n4699\n4700\n4701\n4702\n4703\n4704\n4705\n4706\n4707\n4708\n4709\n4710\n4711\n4712\n4713\n4714\n4715\n4716\n4717\n4718\n4719\n4720\n4721\n4722\n4723\n4724\n4725\n4726\n4727\n4728\n4729\n4730\n4731\n4732\n4733\n4734\n4735\n4736\n4737\n4738\n4739\n4740\n4741\n4742\n4743\n4744\n4745\n4746\n4747\n4748\n4749\n4750\n4751\n4752\n4753\n4754\n4755\n4756\n4757\n4758\n4759\n4760\n4761\n4762\n4763\n4764\n4765\n4766\n4767\n4768\n4769\n4770\n4771\n4772\n4773\n4774\n4775\n4776\n4777\n4778\n4779\n4780\n4781\n4782\n4783\n4784\n4785\n4786\n4787\n4788\n4789\n4790\n4791\n4792\n4793\n4794\n4795\n4796\n4797\n4798\n4799\n4800\n4801\n4802\n4803\n4804\n4805\n4806\n4807\n4808\n4809\n4810\n4811\n4812\n4813\n4814\n4815\n4816\n4817\n4818\n4819\n4820\n4821\n4822\n4823\n4824\n4825\n4826\n4827\n4828\n4829\n4830\n4831\n4832\n4833\n4834\n4835\n4836\n4837\n4838\n4839\n4840\n4841\n4842\n4843\n4844\n4845\n4846\n4847\n4848\n4849\n4850\n4851\n4852\n4853\n4854\n4855\n4856\n4857\n4858\n4859\n4860\n4861\n4862\n4863\n4864\n4865\n4866\n4867\n4868\n4869\n4870\n4871\n4872\n4873\n4874\n4875\n4876\n4877\n4878\n4879\n4880\n4881\n4882\n4883\n4884\n4885\n4886\n4887\n4888\n4889\n4890\n4891\n4892\n4893\n4894\n4895\n4896\n4897\n4898\n4899\n4900\n4901\n4902\n4903\n4904\n4905\n4906\n4907\n4908\n4909\n4910\n4911\n4912\n4913\n4914\n4915\n4916\n4917\n4918\n4919\n4920\n4921\n4922\n4923\n4924\n4925\n4926\n4927\n4928\n4929\n4930\n4931\n4932\n4933\n4934\n4935\n4936\n4937\n4938\n4939\n4940\n4941\n4942\n4943\n4944\n4945\n4946\n4947\n4948\n4949\n4950\n4951\n4952\n4953\n4954\n4955\n4956\n4957\n4958\n4959\n4960\n4961\n4962\n4963\n4964\n4965\n4966\n4967\n4968\n4969\n4970\n4971\n4972\n4973\n4974\n4975\n4976\n4977\n4978\n4979\n4980\n4981\n4982\n4983\n4984\n4985\n4986\n4987\n4988\n4989\n4990\n4991\n4992\n4993\n4994\n4995\n4996\n4997\n4998\n4999\n5000\n5001\n5002\n5003\n5004\n5005\n5006\n5007\n5008\n5009\n5010\n5011\n5012\n5013\n5014\n5015\n5016\n5017\n5018\n5019\n5020\n5021\n5022\n5023\n5024\n5025\n5026\n5027\n5028\n5029\n5030\n5031\n5032\n5033\n5034\n5035\n5036\n5037\n5038\n5039\n5040\n5041\n5042\n5043\n5044\n5045\n5046\n5047\n5048\n5049\n5050\n5051\n5052\n5053\n5054\n5055\n5056\n5057\n5058\n5059\n5060\n5061\n5062\n5063\n5064\n5065\n5066\n5067\n5068\n5069\n5070\n5071\n5072\n5073\n5074\n5075\n5076\n5077\n5078\n5079\n5080\n5081\n5082\n5083\n5084\n5085\n5086\n5087\n5088\n5089\n5090\n5091\n5092\n5093\n5094\n5095\n5096\n5097\n5098\n5099\n5100\n5101\n5102\n5103\n5104\n5105\n5106\n5107\n5108\n5109\n5110\n5111\n5112\n5113\n5114\n5115\n5116\n5117\n5118\n5119\n5120\n5121\n5122\n5123\n5124\n5125\n5126\n5127\n5128\n5129\n5130\n5131\n5132\n5133\n5134\n5135\n5136\n5137\n5138\n5139\n5140\n5141\n5142\n5143\n5144\n5145\n5146\n5147\n5148\n5149\n5150\n5151\n5152\n5153\n5154\n5155\n5156\n5157\n5158\n5159\n5160\n5161\n5162\n5163\n5164\n5165\n5166\n5167\n5168\n5169\n5170\n5171\n5172\n5173\n5174\n5175\n5176\n5177\n5178\n5179\n5180\n5181\n5182\n5183\n5184\n5185\n5186\n5187\n5188\n5189\n5190\n5191\n5192\n5193\n5194\n5195\n5196\n5197\n5198\n5199\n5200\n5201\n5202\n5203\n5204\n5205\n5206\n5207\n5208\n5209\n5210\n5211\n5212\n5213\n5214\n5215\n5216\n5217\n5218\n5219\n5220\n5221\n5222\n5223\n5224\n5225\n5226\n5227\n5228\n5229\n5230\n5231\n5232\n5233\n5234\n5235\n5236\n5237\n5238\n5239\n5240\n5241\n5242\n5243\n5244\n5245\n5246\n5247\n5248\n5249\n5250\n5251\n5252\n5253\n5254\n5255\n5256\n5257\n5258\n5259\n5260\n5261\n5262\n5263\n5264\n5265\n5266\n5267\n5268\n5269\n5270\n5271\n5272\n5273\n5274\n5275\n5276\n5277\n5278\n5279\n5280\n5281\n5282\n5283\n5284\n5285\n5286\n5287\n5288\n5289\n5290\n5291\n5292\n5293\n5294\n5295\n5296\n5297\n5298\n5299\n5300\n5301\n5302\n5303\n5304\n5305\n5306\n5307\n5308\n5309\n5310\n5311\n5312\n5313\n5314\n5315\n5316\n5317\n5318\n5319\n5320\n5321\n5322\n5323\n5324\n5325\n5326\n5327\n5328\n5329\n5330\n5331\n5332\n5333\n5334\n5335\n5336\n5337\n5338\n5339\n5340\n5341\n5342\n5343\n5344\n5345\n5346\n5347\n5348\n5349\n5350\n5351\n5352\n5353\n5354\n5355\n5356\n5357\n5358\n5359\n5360\n5361\n5362\n5363\n5364\n5365\n5366\n5367\n5368\n5369\n5370\n5371\n5372\n5373\n5374\n5375\n5376\n5377\n5378\n5379\n5380\n5381\n5382\n5383\n5384\n5385\n5386\n5387\n5388\n5389\n5390\n5391\n5392\n5393\n5394\n5395\n5396\n5397\n5398\n5399\n5400\n5401\n5402\n5403\n5404\n5405\n5406\n5407\n5408\n5409\n5410\n5411\n5412\n5413\n5414\n5415\n5416\n5417\n5418\n5419\n5420\n5421\n5422\n5423\n5424\n5425\n5426\n5427\n5428\n5429\n5430\n5431\n5432\n5433\n5434\n5435\n5436\n5437\n5438\n5439\n5440\n5441\n5442\n5443\n5444\n5445\n5446\n5447\n5448\n5449\n5450\n5451\n5452\n5453\n5454\n5455\n5456\n5457\n5458\n5459\n5460\n5461\n5462\n5463\n5464\n5465\n5466\n5467\n5468\n5469\n5470\n5471\n5472\n5473\n5474\n5475\n5476\n5477\n5478\n5479\n5480\n5481\n5482\n5483\n5484\n5485\n5486\n5487\n5488\n5489\n5490\n5491\n5492\n5493\n5494\n5495\n5496\n5497\n5498\n5499\n5500\n5501\n5502\n5503\n5504\n5505\n5506\n5507\n5508\n5509\n5510\n5511\n5512\n5513\n5514\n5515\n5516\n5517\n5518\n5519\n5520\n5521\n5522\n5523\n5524\n5525\n5526\n5527\n5528\n5529\n5530\n5531\n5532\n5533\n5534\n5535\n5536\n5537\n5538\n5539\n5540\n5541\n5542\n5543\n5544\n5545\n5546\n5547\n5548\n5549\n5550\n5551\n5552\n5553\n5554\n5555\n5556\n5557\n5558\n5559\n5560\n5561\n5562\n5563\n5564\n5565\n5566\n5567\n5568\n5569\n5570\n5571\n5572\n5573\n5574\n5575\n5576\n5577\n5578\n5579\n5580\n5581\n5582\n5583\n5584\n5585\n5586\n5587\n5588\n5589\n5590\n5591\n5592\n5593\n5594\n5595\n5596\n5597\n5598\n5599\n5600\n5601\n5602\n5603\n5604\n5605\n5606\n5607\n5608\n5609\n5610\n5611\n5612\n5613\n5614\n5615\n5616\n5617\n5618\n5619\n5620\n5621\n5622\n5623\n5624\n5625\n5626\n5627\n5628\n5629\n5630\n5631\n5632\n5633\n5634\n5635\n5636\n5637\n5638\n5639\n5640\n5641\n5642\n5643\n5644\n5645\n5646\n5647\n5648\n5649\n5650\n5651\n5652\n5653\n5654\n5655\n5656\n5657\n5658\n5659\n5660\n5661\n5662\n5663\n5664\n5665\n5666\n5667\n5668\n5669\n5670\n5671\n5672\n5673\n5674\n5675\n5676\n5677\n5678\n5679\n5680\n5681\n5682\n5683\n5684\n5685\n5686\n5687\n5688\n5689\n5690\n5691\n5692\n5693\n5694\n5695\n5696\n5697\n5698\n5699\n5700\n5701\n5702\n5703\n5704\n5705\n5706\n5707\n5708\n5709\n5710\n5711\n5712\n5713\n5714\n5715\n5716\n5717\n5718\n5719\n5720\n5721\n5722\n5723\n5724\n5725\n5726\n5727\n5728\n5729\n5730\n5731\n5732\n5733\n5734\n5735\n5736\n5737\n5738\n5739\n5740\n5741\n5742\n5743\n5744\n5745\n5746\n5747\n5748\n5749\n5750\n5751\n5752\n5753\n5754\n5755\n5756\n5757\n5758\n5759\n5760\n5761\n5762\n5763\n5764\n5765\n5766\n5767\n5768\n5769\n5770\n5771\n5772\n5773\n5774\n5775\n5776\n5777\n5778\n5779\n5780\n5781\n5782\n5783\n5784\n5785\n5786\n5787\n5788\n5789\n5790\n5791\n5792\n5793\n5794\n5795\n5796\n5797\n5798\n5799\n5800\n5801\n5802\n5803\n5804\n5805\n5806\n5807\n5808\n5809\n5810\n5811\n5812\n5813\n5814\n5815\n5816\n5817\n5818\n5819\n5820\n5821\n5822\n5823\n5824\n5825\n5826\n5827\n5828\n5829\n5830\n5831\n5832\n5833\n5834\n5835\n5836\n5837\n5838\n5839\n5840\n5841\n5842\n5843\n5844\n5845\n5846\n5847\n5848\n5849\n5850\n5851\n5852\n5853\n5854\n5855\n5856\n5857\n5858\n5859\n5860\n5861\n5862\n5863\n5864\n5865\n5866\n5867\n5868\n5869\n5870\n5871\n5872\n5873\n5874\n5875\n5876\n5877\n5878\n5879\n5880\n5881\n5882\n5883\n5884\n5885\n5886\n5887\n5888\n5889\n5890\n5891\n5892\n5893\n5894\n5895\n5896\n5897\n5898\n5899\n5900\n5901\n5902\n5903\n5904\n5905\n5906\n5907\n5908\n5909\n5910\n5911\n5912\n5913\n5914\n5915\n5916\n5917\n5918\n5919\n5920\n5921\n5922\n5923\n5924\n5925\n5926\n5927\n5928\n5929\n5930\n5931\n5932\n5933\n5934\n5935\n5936\n5937\n5938\n5939\n5940\n5941\n5942\n5943\n5944\n5945\n5946\n5947\n5948\n5949\n5950\n5951\n5952\n5953\n5954\n5955\n5956\n5957\n5958\n5959\n5960\n5961\n5962\n5963\n5964\n5965\n5966\n5967\n5968\n5969\n5970\n5971\n5972\n5973\n5974\n5975\n5976\n5977\n5978\n5979\n5980\n5981\n5982\n5983\n5984\n5985\n5986\n5987\n5988\n5989\n5990\n5991\n5992\n5993\n5994\n5995\n5996\n5997\n5998\n5999\n6000\n6001\n6002\n6003\n6004\n6005\n6006\n6007\n6008\n6009\n6010\n6011\n6012\n6013\n6014\n6015\n6016\n6017\n6018\n6019\n6020\n6021\n6022\n6023\n6024\n6025\n6026\n6027\n6028\n6029\n6030\n6031\n6032\n6033\n6034\n6035\n6036\n6037\n6038\n6039\n6040\n6041\n6042\n6043\n6044\n6045\n6046\n6047\n6048\n6049\n6050\n6051\n6052\n6053\n6054\n6055\n6056\n6057\n6058\n6059\n6060\n6061\n6062\n6063\n6064\n6065\n6066\n6067\n6068\n6069\n6070\n6071\n6072\n6073\n6074\n6075\n6076\n6077\n6078\n6079\n6080\n6081\n6082\n6083\n6084\n6085\n6086\n6087\n6088\n6089\n6090\n6091\n6092\n6093\n6094\n6095\n6096\n6097\n6098\n6099\n6100\n6101\n6102\n6103\n6104\n6105\n6106\n6107\n6108\n6109\n6110\n6111\n6112\n6113\n6114\n6115\n6116\n6117\n6118\n6119\n6120\n6121\n6122\n6123\n6124\n6125\n6126\n6127\n6128\n6129\n6130\n6131\n6132\n6133\n6134\n6135\n6136\n6137\n6138\n6139\n6140\n6141\n6142\n6143\n6144\n6145\n6146\n6147\n6148\n6149\n6150\n6151\n6152\n6153\n6154\n6155\n6156\n6157\n6158\n6159\n6160\n6161\n6162\n6163\n6164\n6165\n6166\n6167\n6168\n6169\n6170\n6171\n6172\n6173\n6174\n6175\n6176\n6177\n6178\n6179\n6180\n6181\n6182\n6183\n6184\n6185\n6186\n6187\n6188\n6189\n6190\n6191\n6192\n6193\n6194\n6195\n6196\n6197\n6198\n6199\n6200\n6201\n6202\n6203\n6204\n6205\n6206\n6207\n6208\n6209\n6210\n6211\n6212\n6213\n6214\n6215\n6216\n6217\n6218\n6219\n6220\n6221\n6222\n6223\n6224\n6225\n6226\n6227\n6228\n6229\n6230\n6231\n6232\n6233\n6234\n6235\n6236\n6237\n6238\n6239\n6240\n6241\n6242\n6243\n6244\n6245\n6246\n6247\n6248\n6249\n6250\n6251\n6252\n6253\n6254\n6255\n6256\n6257\n6258\n6259\n6260\n6261\n6262\n6263\n6264\n6265\n6266\n6267\n6268\n6269\n6270\n6271\n6272\n6273\n6274\n6275\n6276\n6277\n6278\n6279\n6280\n6281\n6282\n6283\n6284\n6285\n6286\n6287\n6288\n6289\n6290\n6291\n6292\n6293\n6294\n6295\n6296\n6297\n6298\n6299\n6300\n6301\n6302\n6303\n6304\n6305\n6306\n6307\n6308\n6309\n6310\n6311\n6312\n6313\n6314\n6315\n6316\n6317\n6318\n6319\n6320\n6321\n6322\n6323\n6324\n6325\n6326\n6327\n6328\n6329\n6330\n6331\n6332\n6333\n6334\n6335\n6336\n6337\n6338\n6339\n6340\n6341\n6342\n6343\n6344\n6345\n6346\n6347\n6348\n6349\n6350\n6351\n6352\n6353\n6354\n6355\n6356\n6357\n6358\n6359\n6360\n6361\n6362\n6363\n6364\n6365\n6366\n6367\n6368\n6369\n6370\n6371\n6372\n6373\n6374\n6375\n6376\n6377\n6378\n6379\n6380\n6381\n6382\n6383\n6384\n6385\n6386\n6387\n6388\n6389\n6390\n6391\n6392\n6393\n6394\n6395\n6396\n6397\n6398\n6399\n6400\n6401\n6402\n6403\n6404\n6405\n6406\n6407\n6408\n6409\n6410\n6411\n6412\n6413\n6414\n6415\n6416\n6417\n6418\n6419\n6420\n6421\n6422\n6423\n6424\n6425\n6426\n6427\n6428\n6429\n6430\n6431\n6432\n6433\n6434\n6435\n6436\n6437\n6438\n6439\n6440\n6441\n6442\n6443\n6444\n6445\n6446\n6447\n6448\n6449\n6450\n6451\n6452\n6453\n6454\n6455\n6456\n6457\n6458\n6459\n6460\n6461\n6462\n6463\n6464\n6465\n6466\n6467\n6468\n6469\n6470\n6471\n6472\n6473\n6474\n6475\n6476\n6477\n6478\n6479\n6480\n6481\n6482\n6483\n6484\n6485\n6486\n6487\n6488\n6489\n6490\n6491\n6492\n6493\n6494\n6495\n6496\n6497\n6498\n6499\n6500\n6501\n6502\n6503\n6504\n6505\n6506\n6507\n6508\n6509\n6510\n6511\n6512\n6513\n6514\n6515\n6516\n6517\n6518\n6519\n6520\n6521\n6522\n6523\n6524\n6525\n6526\n6527\n6528\n6529\n6530\n6531\n6532\n6533\n6534\n6535\n6536\n6537\n6538\n6539\n6540\n6541\n6542\n6543\n6544\n6545\n6546\n6547\n6548\n6549\n6550\n6551\n6552\n6553\n6554\n6555\n6556\n6557\n6558\n6559\n6560\n6561\n6562\n6563\n6564\n6565\n6566\n6567\n6568\n6569\n6570\n6571\n6572\n6573\n6574\n6575\n6576\n6577\n6578\n6579\n6580\n6581\n6582\n6583\n6584\n6585\n6586\n6587\n6588\n6589\n6590\n6591\n6592\n6593\n6594\n6595\n6596\n6597\n6598\n6599\n6600\n6601\n6602\n6603\n6604\n6605\n6606\n6607\n6608\n6609\n6610\n6611\n6612\n6613\n6614\n6615\n6616\n6617\n6618\n6619\n6620\n6621\n6622\n6623\n6624\n6625\n6626\n6627\n6628\n6629\n6630\n6631\n6632\n6633\n6634\n6635\n6636\n6637\n6638\n6639\n6640\n6641\n6642\n6643\n6644\n6645\n6646\n6647\n6648\n6649\n6650\n6651\n6652\n6653\n6654\n6655\n6656\n6657\n6658\n6659\n6660\n6661\n6662\n6663\n6664\n6665\n6666\n6667\n6668\n6669\n6670\n6671\n6672\n6673\n6674\n6675\n6676\n6677\n6678\n6679\n6680\n6681\n6682\n6683\n6684\n6685\n6686\n6687\n6688\n6689\n6690\n6691\n6692\n6693\n6694\n6695\n6696\n6697\n6698\n6699\n6700\n6701\n6702\n6703\n6704\n6705\n6706\n6707\n6708\n6709\n6710\n6711\n6712\n6713\n6714\n6715\n6716\n6717\n6718\n6719\n6720\n6721\n6722\n6723\n6724\n6725\n6726\n6727\n6728\n6729\n6730\n6731\n6732\n6733\n6734\n6735\n6736\n6737\n6738\n6739\n6740\n6741\n6742\n6743\n6744\n6745\n6746\n6747\n6748\n6749\n6750\n6751\n6752\n6753\n6754\n6755\n6756\n6757\n6758\n6759\n6760\n6761\n6762\n6763\n6764\n6765\n6766\n6767\n6768\n6769\n6770\n6771\n6772\n6773\n6774\n6775\n6776\n6777\n6778\n6779\n6780\n6781\n6782\n6783\n6784\n6785\n6786\n6787\n6788\n6789\n6790\n6791\n6792\n6793\n6794\n6795\n6796\n6797\n6798\n6799\n6800\n6801\n6802\n6803\n6804\n6805\n6806\n6807\n6808\n6809\n6810\n6811\n6812\n6813\n6814\n6815\n6816\n6817\n6818\n6819\n6820\n6821\n6822\n6823\n6824\n6825\n6826\n6827\n6828\n6829\n6830\n6831\n6832\n6833\n6834\n6835\n6836\n6837\n6838\n6839\n6840\n6841\n6842\n6843\n6844\n6845\n6846\n6847\n6848\n6849\n6850\n6851\n6852\n6853\n6854\n6855\n6856\n6857\n6858\n6859\n6860\n6861\n6862\n6863\n6864\n6865\n6866\n6867\n6868\n6869\n6870\n6871\n6872\n6873\n6874\n6875\n6876\n6877\n6878\n6879\n6880\n6881\n6882\n6883\n6884\n6885\n6886\n6887\n6888\n6889\n6890\n6891\n6892\n6893\n6894\n6895\n6896\n6897\n6898\n6899\n6900\n6901\n6902\n6903\n6904\n6905\n6906\n6907\n6908\n6909\n6910\n6911\n6912\n6913\n6914\n6915\n6916\n6917\n6918\n6919\n6920\n6921\n6922\n6923\n6924\n6925\n6926\n6927\n6928\n6929\n6930\n6931\n6932\n6933\n6934\n6935\n6936\n6937\n6938\n6939\n6940\n6941\n6942\n6943\n6944\n6945\n6946\n6947\n6948\n6949\n6950\n6951\n6952\n6953\n6954\n6955\n6956\n6957\n6958\n6959\n6960\n6961\n6962\n6963\n6964\n6965\n6966\n6967\n6968\n6969\n6970\n6971\n6972\n6973\n6974\n6975\n6976\n6977\n6978\n6979\n6980\n6981\n6982\n6983\n6984\n6985\n6986\n6987\n6988\n6989\n6990\n6991\n6992\n6993\n6994\n6995\n6996\n6997\n6998\n6999\n7000\n7001\n7002\n7003\n7004\n7005\n7006\n7007\n7008\n7009\n7010\n7011\n7012\n7013\n7014\n7015\n7016\n7017\n7018\n7019\n7020\n7021\n7022\n7023\n7024\n7025\n7026\n7027\n7028\n7029\n7030\n7031\n7032\n7033\n7034\n7035\n7036\n7037\n7038\n7039\n7040\n7041\n7042\n7043\n7044\n7045\n7046\n7047\n7048\n7049\n7050\n7051\n7052\n7053\n7054\n7055\n7056\n7057\n7058\n7059\n7060\n7061\n7062\n7063\n7064\n7065\n7066\n7067\n7068\n7069\n7070\n7071\n7072\n7073\n7074\n7075\n7076\n7077\n7078\n7079\n7080\n7081\n7082\n7083\n7084\n7085\n7086\n7087\n7088\n7089\n7090\n7091\n7092\n7093\n7094\n7095\n7096\n7097\n7098\n7099\n7100\n7101\n7102\n7103\n7104\n7105\n7106\n7107\n7108\n7109\n7110\n7111\n7112\n7113\n7114\n7115\n7116\n7117\n7118\n7119\n7120\n7121\n7122\n7123\n7124\n7125\n7126\n7127\n7128\n7129\n7130\n7131\n7132\n7133\n7134\n7135\n7136\n7137\n7138\n7139\n7140\n7141\n7142\n7143\n7144\n7145\n7146\n7147\n7148\n7149\n7150\n7151\n7152\n7153\n7154\n7155\n7156\n7157\n7158\n7159\n7160\n7161\n7162\n7163\n7164\n7165\n7166\n7167\n7168\n7169\n7170\n7171\n7172\n7173\n7174\n7175\n7176\n7177\n7178\n7179\n7180\n7181\n7182\n7183\n7184\n7185\n7186\n7187\n7188\n7189\n7190\n7191\n7192\n7193\n7194\n7195\n7196\n7197\n7198\n7199\n7200\n7201\n7202\n7203\n7204\n7205\n7206\n7207\n7208\n7209\n7210\n7211\n7212\n7213\n7214\n7215\n7216\n7217\n7218\n7219\n7220\n7221\n7222\n7223\n7224\n7225\n7226\n7227\n7228\n7229\n7230\n7231\n7232\n7233\n7234\n7235\n7236\n7237\n7238\n7239\n7240\n7241\n7242\n7243\n7244\n7245\n7246\n7247\n7248\n7249\n7250\n7251\n7252\n7253\n7254\n7255\n7256\n7257\n7258\n7259\n7260\n7261\n7262\n7263\n7264\n7265\n7266\n7267\n7268\n7269\n7270\n7271\n7272\n7273\n7274\n7275\n7276\n7277\n7278\n7279\n7280\n7281\n7282\n7283\n7284\n7285\n7286\n7287\n7288\n7289\n7290\n7291\n7292\n7293\n7294\n7295\n7296\n7297\n7298\n7299\n7300\n7301\n7302\n7303\n7304\n7305\n7306\n7307\n7308\n7309\n7310\n7311\n7312\n7313\n7314\n7315\n7316\n7317\n7318\n7319\n7320\n7321\n7322\n7323\n7324\n7325\n7326\n7327\n7328\n7329\n7330\n7331\n7332\n7333\n7334\n7335\n7336\n7337\n7338\n7339\n7340\n7341\n7342\n7343\n7344\n7345\n7346\n7347\n7348\n7349\n7350\n7351\n7352\n7353\n7354\n7355\n7356\n7357\n7358\n7359\n7360\n7361\n7362\n7363\n7364\n7365\n7366\n7367\n7368\n7369\n7370\n7371\n7372\n7373\n7374\n7375\n7376\n7377\n7378\n7379\n7380\n7381\n7382\n7383\n7384\n7385\n7386\n7387\n7388\n7389\n7390\n7391\n7392\n7393\n7394\n7395\n7396\n7397\n7398\n7399\n7400\n7401\n7402\n7403\n7404\n7405\n7406\n7407\n7408\n7409\n7410\n7411\n7412\n7413\n7414\n7415\n7416\n7417\n7418\n7419\n7420\n7421\n7422\n7423\n7424\n7425\n7426\n7427\n7428\n7429\n7430\n7431\n7432\n7433\n7434\n7435\n7436\n7437\n7438\n7439\n7440\n7441\n7442\n7443\n7444\n7445\n7446\n7447\n7448\n7449\n7450\n7451\n7452\n7453\n7454\n7455\n7456\n7457\n7458\n7459\n7460\n7461\n7462\n7463\n7464\n7465\n7466\n7467\n7468\n7469\n7470\n7471\n7472\n7473\n7474\n7475\n7476\n7477\n7478\n7479\n7480\n7481\n7482\n7483\n7484\n7485\n7486\n7487\n7488\n7489\n7490\n7491\n7492\n7493\n7494\n7495\n7496\n7497\n7498\n7499\n7500\n7501\n7502\n7503\n7504\n7505\n7506\n7507\n7508\n7509\n7510\n7511\n7512\n7513\n7514\n7515\n7516\n7517\n7518\n7519\n7520\n7521\n7522\n7523\n7524\n7525\n7526\n7527\n7528\n7529\n7530\n7531\n7532\n7533\n7534\n7535\n7536\n7537\n7538\n7539\n7540\n7541\n7542\n7543\n7544\n7545\n7546\n7547\n7548\n7549\n7550\n7551\n7552\n7553\n7554\n7555\n7556\n7557\n7558\n7559\n7560\n7561\n7562\n7563\n7564\n7565\n7566\n7567\n7568\n7569\n7570\n7571\n7572\n7573\n7574\n7575\n7576\n7577\n7578\n7579\n7580\n7581\n7582\n7583\n7584\n7585\n7586\n7587\n7588\n7589\n7590\n7591\n7592\n7593\n7594\n7595\n7596\n7597\n7598\n7599\n7600\n7601\n7602\n7603\n7604\n7605\n7606\n7607\n7608\n7609\n7610\n7611\n7612\n7613\n7614\n7615\n7616\n7617\n7618\n7619\n7620\n7621\n7622\n7623\n7624\n7625\n7626\n7627\n7628\n7629\n7630\n7631\n7632\n7633\n7634\n7635\n7636\n7637\n7638\n7639\n7640\n7641\n7642\n7643\n7644\n7645\n7646\n7647\n7648\n7649\n7650\n7651\n7652\n7653\n7654\n7655\n7656\n7657\n7658\n7659\n7660\n7661\n7662\n7663\n7664\n7665\n7666\n7667\n7668\n7669\n7670\n7671\n7672\n7673\n7674\n7675\n7676\n7677\n7678\n7679\n7680\n7681\n7682\n7683\n7684\n7685\n7686\n7687\n7688\n7689\n7690\n7691\n7692\n7693\n7694\n7695\n7696\n7697\n7698\n7699\n7700\n7701\n7702\n7703\n7704\n7705\n7706\n7707\n7708\n7709\n7710\n7711\n7712\n7713\n7714\n7715\n7716\n7717\n7718\n7719\n7720\n7721\n7722\n7723\n7724\n7725\n7726\n7727\n7728\n7729\n7730\n7731\n7732\n7733\n7734\n7735\n7736\n7737\n7738\n7739\n7740\n7741\n7742\n7743\n7744\n7745\n7746\n7747\n7748\n7749\n7750\n7751\n7752\n7753\n7754\n7755\n7756\n7757\n7758\n7759\n7760\n7761\n7762\n7763\n7764\n7765\n7766\n7767\n7768\n7769\n7770\n7771\n7772\n7773\n7774\n7775\n7776\n7777\n7778\n7779\n7780\n7781\n7782\n7783\n7784\n7785\n7786\n7787\n7788\n7789\n7790\n7791\n7792\n7793\n7794\n7795\n7796\n7797\n7798\n7799\n7800\n7801\n7802\n7803\n7804\n7805\n7806\n7807\n7808\n7809\n7810\n7811\n7812\n7813\n7814\n7815\n7816\n7817\n7818\n7819\n7820\n7821\n7822\n7823\n7824\n7825\n7826\n7827\n7828\n7829\n7830\n7831\n7832\n7833\n7834\n7835\n7836\n7837\n7838\n7839\n7840\n7841\n7842\n7843\n7844\n7845\n7846\n7847\n7848\n7849\n7850\n7851\n7852\n7853\n7854\n7855\n7856\n7857\n7858\n7859\n7860\n7861\n7862\n7863\n7864\n7865\n7866\n7867\n7868\n7869\n7870\n7871\n7872\n7873\n7874\n7875\n7876\n7877\n7878\n7879\n7880\n7881\n7882\n7883\n7884\n7885\n7886\n7887\n7888\n7889\n7890\n7891\n7892\n7893\n7894\n7895\n7896\n7897\n7898\n7899\n7900\n7901\n7902\n7903\n7904\n7905\n7906\n7907\n7908\n7909\n7910\n7911\n7912\n7913\n7914\n7915\n7916\n7917\n7918\n7919\n7920\n7921\n7922\n7923\n7924\n7925\n7926\n7927\n7928\n7929\n7930\n7931\n7932\n7933\n7934\n7935\n7936\n7937\n7938\n7939\n7940\n7941\n7942\n7943\n7944\n7945\n7946\n7947\n7948\n7949\n7950\n7951\n7952\n7953\n7954\n7955\n7956\n7957\n7958\n7959\n7960\n7961\n7962\n7963\n7964\n7965\n7966\n7967\n7968\n7969\n7970\n7971\n7972\n7973\n7974\n7975\n7976\n7977\n7978\n7979\n7980\n7981\n7982\n7983\n7984\n7985\n7986\n7987\n7988\n7989\n7990\n7991\n7992\n7993\n7994\n7995\n7996\n7997\n7998\n7999\n8000\n8001\n8002\n8003\n8004\n8005\n8006\n8007\n8008\n8009\n8010\n8011\n8012\n8013\n8014\n8015\n8016\n8017\n8018\n8019\n8020\n8021\n8022\n8023\n8024\n8025\n8026\n8027\n8028\n8029\n8030\n8031\n8032\n8033\n8034\n8035\n8036\n8037\n8038\n8039\n8040\n8041\n8042\n8043\n8044\n8045\n8046\n8047\n8048\n8049\n8050\n8051\n8052\n8053\n8054\n8055\n8056\n8057\n8058\n8059\n8060\n8061\n8062\n8063\n8064\n8065\n8066\n8067\n8068\n8069\n8070\n8071\n8072\n8073\n8074\n8075\n8076\n8077\n8078\n8079\n8080\n8081\n8082\n8083\n8084\n8085\n8086\n8087\n8088\n8089\n8090\n8091\n8092\n8093\n8094\n8095\n8096\n8097\n8098\n8099\n8100\n8101\n8102\n8103\n8104\n8105\n8106\n8107\n8108\n8109\n8110\n8111\n8112\n8113\n8114\n8115\n8116\n8117\n8118\n8119\n8120\n8121\n8122\n8123\n8124\n8125\n8126\n8127\n8128\n8129\n8130\n8131\n8132\n8133\n8134\n8135\n8136\n8137\n8138\n8139\n8140\n8141\n8142\n8143\n8144\n8145\n8146\n8147\n8148\n8149\n8150\n8151\n8152\n8153\n8154\n8155\n8156\n8157\n8158\n8159\n8160\n8161\n8162\n8163\n8164\n8165\n8166\n8167\n8168\n8169\n8170\n8171\n8172\n8173\n8174\n8175\n8176\n8177\n8178\n8179\n8180\n8181\n8182\n8183\n8184\n8185\n8186\n8187\n8188\n8189\n8190\n8191\n8192\n8193\n8194\n8195\n8196\n8197\n8198\n8199\n8200\n8201\n8202\n8203\n8204\n8205\n8206\n8207\n8208\n8209\n8210\n8211\n8212\n8213\n8214\n8215\n8216\n8217\n8218\n8219\n8220\n8221\n8222\n8223\n8224\n8225\n8226\n8227\n8228\n8229\n8230\n8231\n8232\n8233\n8234\n8235\n8236\n8237\n8238\n8239\n8240\n8241\n8242\n8243\n8244\n8245\n8246\n8247\n8248\n8249\n8250\n8251\n8252\n8253\n8254\n8255\n8256\n8257\n8258\n8259\n8260\n8261\n8262\n8263\n8264\n8265\n8266\n8267\n8268\n8269\n8270\n8271\n8272\n8273\n8274\n8275\n8276\n8277\n8278\n8279\n8280\n8281\n8282\n8283\n8284\n8285\n8286\n8287\n8288\n8289\n8290\n8291\n8292\n8293\n8294\n8295\n8296\n8297\n8298\n8299\n8300\n8301\n8302\n8303\n8304\n8305\n8306\n8307\n8308\n8309\n8310\n8311\n8312\n8313\n8314\n8315\n8316\n8317\n8318\n8319\n8320\n8321\n8322\n8323\n8324\n8325\n8326\n8327\n8328\n8329\n8330\n8331\n8332\n8333\n8334\n8335\n8336\n8337\n8338\n8339\n8340\n8341\n8342\n8343\n8344\n8345\n8346\n8347\n8348\n8349\n8350\n8351\n8352\n8353\n8354\n8355\n8356\n8357\n8358\n8359\n8360\n8361\n8362\n8363\n8364\n8365\n8366\n8367\n8368\n8369\n8370\n8371\n8372\n8373\n8374\n8375\n8376\n8377\n8378\n8379\n8380\n8381\n8382\n8383\n8384\n8385\n8386\n8387\n8388\n8389\n8390\n8391\n8392\n8393\n8394\n8395\n8396\n8397\n8398\n8399\n8400\n8401\n8402\n8403\n8404\n8405\n8406\n8407\n8408\n8409\n8410\n8411\n8412\n8413\n8414\n8415\n8416\n8417\n8418\n8419\n8420\n8421\n8422\n8423\n8424\n8425\n8426\n8427\n8428\n8429\n8430\n8431\n8432\n8433\n8434\n8435\n8436\n8437\n8438\n8439\n8440\n8441\n8442\n8443\n8444\n8445\n8446\n8447\n8448\n8449\n8450\n8451\n8452\n8453\n8454\n8455\n8456\n8457\n8458\n8459\n8460\n8461\n8462\n8463\n8464\n8465\n8466\n8467\n8468\n8469\n8470\n8471\n8472\n8473\n8474\n8475\n8476\n8477\n8478\n8479\n8480\n8481\n8482\n8483\n8484\n8485\n8486\n8487\n8488\n8489\n8490\n8491\n8492\n8493\n8494\n8495\n8496\n8497\n8498\n8499\n8500\n8501\n8502\n8503\n8504\n8505\n8506\n8507\n8508\n8509\n8510\n8511\n8512\n8513\n8514\n8515\n8516\n8517\n8518\n8519\n8520\n8521\n8522\n8523\n8524\n8525\n8526\n8527\n8528\n8529\n8530\n8531\n8532\n8533\n8534\n8535\n8536\n8537\n8538\n8539\n8540\n8541\n8542\n8543\n8544\n8545\n8546\n8547\n8548\n8549\n8550\n8551\n8552\n8553\n8554\n8555\n8556\n8557\n8558\n8559\n8560\n8561\n8562\n8563\n8564\n8565\n8566\n8567\n8568\n8569\n8570\n8571\n8572\n8573\n8574\n8575\n8576\n8577\n8578\n8579\n8580\n8581\n8582\n8583\n8584\n8585\n8586\n8587\n8588\n8589\n8590\n8591\n8592\n8593\n8594\n8595\n8596\n8597\n8598\n8599\n8600\n8601\n8602\n8603\n8604\n8605\n8606\n8607\n8608\n8609\n8610\n8611\n8612\n8613\n8614\n8615\n8616\n8617\n8618\n8619\n8620\n8621\n8622\n8623\n8624\n8625\n8626\n8627\n8628\n8629\n8630\n8631\n8632\n8633\n8634\n8635\n8636\n8637\n8638\n8639\n8640\n8641\n8642\n8643\n8644\n8645\n8646\n8647\n8648\n8649\n8650\n8651\n8652\n8653\n8654\n8655\n8656\n8657\n8658\n8659\n8660\n8661\n8662\n8663\n8664\n8665\n8666\n8667\n8668\n8669\n8670\n8671\n8672\n8673\n8674\n8675\n8676\n8677\n8678\n8679\n8680\n8681\n8682\n8683\n8684\n8685\n8686\n8687\n8688\n8689\n8690\n8691\n8692\n8693\n8694\n8695\n8696\n8697\n8698\n8699\n8700\n8701\n8702\n8703\n8704\n8705\n8706\n8707\n8708\n8709\n8710\n8711\n8712\n8713\n8714\n8715\n8716\n8717\n8718\n8719\n8720\n8721\n8722\n8723\n8724\n8725\n8726\n8727\n8728\n8729\n8730\n8731\n8732\n8733\n8734\n8735\n8736\n8737\n8738\n8739\n8740\n8741\n8742\n8743\n8744\n8745\n8746\n8747\n8748\n8749\n8750\n8751\n8752\n8753\n8754\n8755\n8756\n8757\n8758\n8759\n8760\n8761\n8762\n8763\n8764\n8765\n8766\n8767\n8768\n8769\n8770\n8771\n8772\n8773\n8774\n8775\n8776\n8777\n8778\n8779\n8780\n8781\n8782\n8783\n8784\n8785\n8786\n8787\n8788\n8789\n8790\n8791\n8792\n8793\n8794\n8795\n8796\n8797\n8798\n8799\n8800\n8801\n8802\n8803\n8804\n8805\n8806\n8807\n8808\n8809\n8810\n8811\n8812\n8813\n8814\n8815\n8816\n8817\n8818\n8819\n8820\n8821\n8822\n8823\n8824\n8825\n8826\n8827\n8828\n8829\n8830\n8831\n8832\n8833\n8834\n8835\n8836\n8837\n8838\n8839\n8840\n8841\n8842\n8843\n8844\n8845\n8846\n8847\n8848\n8849\n8850\n8851\n8852\n8853\n8854\n8855\n8856\n8857\n8858\n8859\n8860\n8861\n8862\n8863\n8864\n8865\n8866\n8867\n8868\n8869\n8870\n8871\n8872\n8873\n8874\n8875\n8876\n8877\n8878\n8879\n8880\n8881\n8882\n8883\n8884\n8885\n8886\n8887\n8888\n8889\n8890\n8891\n8892\n8893\n8894\n8895\n8896\n8897\n8898\n8899\n8900\n8901\n8902\n8903\n8904\n8905\n8906\n8907\n8908\n8909\n8910\n8911\n8912\n8913\n8914\n8915\n8916\n8917\n8918\n8919\n8920\n8921\n8922\n8923\n8924\n8925\n8926\n8927\n8928\n8929\n8930\n8931\n8932\n8933\n8934\n8935\n8936\n8937\n8938\n8939\n8940\n8941\n8942\n8943\n8944\n8945\n8946\n8947\n8948\n8949\n8950\n8951\n8952\n8953\n8954\n8955\n8956\n8957\n8958\n8959\n8960\n8961\n8962\n8963\n8964\n8965\n8966\n8967\n8968\n8969\n8970\n8971\n8972\n8973\n8974\n8975\n8976\n8977\n8978\n8979\n8980\n8981\n8982\n8983\n8984\n8985\n8986\n8987\n8988\n8989\n8990\n8991\n8992\n8993\n8994\n8995\n8996\n8997\n8998\n8999\n9000\n9001\n9002\n9003\n9004\n9005\n9006\n9007\n9008\n9009\n9010\n9011\n9012\n9013\n9014\n9015\n9016\n9017\n9018\n9019\n9020\n9021\n9022\n9023\n9024\n9025\n9026\n9027\n9028\n9029\n9030\n9031\n9032\n9033\n9034\n9035\n9036\n9037\n9038\n9039\n9040\n9041\n9042\n9043\n9044\n9045\n9046\n9047\n9048\n9049\n9050\n9051\n9052\n9053\n9054\n9055\n9056\n9057\n9058\n9059\n9060\n9061\n9062\n9063\n9064\n9065\n9066\n9067\n9068\n9069\n9070\n9071\n9072\n9073\n9074\n9075\n9076\n9077\n9078\n9079\n9080\n9081\n9082\n9083\n9084\n9085\n9086\n9087\n9088\n9089\n9090\n9091\n9092\n9093\n9094\n9095\n9096\n9097\n9098\n9099\n9100\n9101\n9102\n9103\n9104\n9105\n9106\n9107\n9108\n9109\n9110\n9111\n9112\n9113\n9114\n9115\n9116\n9117\n9118\n9119\n9120\n9121\n9122\n9123\n9124\n9125\n9126\n9127\n9128\n9129\n9130\n9131\n9132\n9133\n9134\n9135\n9136\n9137\n9138\n9139\n9140\n9141\n9142\n9143\n9144\n9145\n9146\n9147\n9148\n9149\n9150\n9151\n9152\n9153\n9154\n9155\n9156\n9157\n9158\n9159\n9160\n9161\n9162\n9163\n9164\n9165\n9166\n9167\n9168\n9169\n9170\n9171\n9172\n9173\n9174\n9175\n9176\n9177\n9178\n9179\n9180\n9181\n9182\n9183\n9184\n9185\n9186\n9187\n9188\n9189\n9190\n9191\n9192\n9193\n9194\n9195\n9196\n9197\n9198\n9199\n9200\n9201\n9202\n9203\n9204\n9205\n9206\n9207\n9208\n9209\n9210\n9211\n9212\n9213\n9214\n9215\n9216\n9217\n9218\n9219\n9220\n9221\n9222\n9223\n9224\n9225\n9226\n9227\n9228\n9229\n9230\n9231\n9232\n9233\n9234\n9235\n9236\n9237\n9238\n9239\n9240\n9241\n9242\n9243\n9244\n9245\n9246\n9247\n9248\n9249\n9250\n9251\n9252\n9253\n9254\n9255\n9256\n9257\n9258\n9259\n9260\n9261\n9262\n9263\n9264\n9265\n9266\n9267\n9268\n9269\n9270\n9271\n9272\n9273\n9274\n9275\n9276\n9277\n9278\n9279\n9280\n9281\n9282\n9283\n9284\n9285\n9286\n9287\n9288\n9289\n9290\n9291\n9292\n9293\n9294\n9295\n9296\n9297\n9298\n9299\n9300\n9301\n9302\n9303\n9304\n9305\n9306\n9307\n9308\n9309\n9310\n9311\n9312\n9313\n9314\n9315\n9316\n9317\n9318\n9319\n9320\n9321\n9322\n9323\n9324\n9325\n9326\n9327\n9328\n9329\n9330\n9331\n9332\n9333\n9334\n9335\n9336\n9337\n9338\n9339\n9340\n9341\n9342\n9343\n9344\n9345\n9346\n9347\n9348\n9349\n9350\n9351\n9352\n9353\n9354\n9355\n9356\n9357\n9358\n9359\n9360\n9361\n9362\n9363\n9364\n9365\n9366\n9367\n9368\n9369\n9370\n9371\n9372\n9373\n9374\n9375\n9376\n9377\n9378\n9379\n9380\n9381\n9382\n9383\n9384\n9385\n9386\n9387\n9388\n9389\n9390\n9391\n9392\n9393\n9394\n9395\n9396\n9397\n9398\n9399\n9400\n9401\n9402\n9403\n9404\n9405\n9406\n9407\n9408\n9409\n9410\n9411\n9412\n9413\n9414\n9415\n9416\n9417\n9418\n9419\n9420\n9421\n9422\n9423\n9424\n9425\n9426\n9427\n9428\n9429\n9430\n9431\n9432\n9433\n9434\n9435\n9436\n9437\n9438\n9439\n9440\n9441\n9442\n9443\n9444\n9445\n9446\n9447\n9448\n9449\n9450\n9451\n9452\n9453\n9454\n9455\n9456\n9457\n9458\n9459\n9460\n9461\n9462\n9463\n9464\n9465\n9466\n9467\n9468\n9469\n9470\n9471\n9472\n9473\n9474\n9475\n9476\n9477\n9478\n9479\n9480\n9481\n9482\n9483\n9484\n9485\n9486\n9487\n9488\n9489\n9490\n9491\n9492\n9493\n9494\n9495\n9496\n9497\n9498\n9499\n9500\n9501\n9502\n9503\n9504\n9505\n9506\n9507\n9508\n9509\n9510\n9511\n9512\n9513\n9514\n9515\n9516\n9517\n9518\n9519\n9520\n9521\n9522\n9523\n9524\n9525\n9526\n9527\n9528\n9529\n9530\n9531\n9532\n9533\n9534\n9535\n9536\n9537\n9538\n9539\n9540\n9541\n9542\n9543\n9544\n9545\n9546\n9547\n9548\n9549\n9550\n9551\n9552\n9553\n9554\n9555\n9556\n9557\n9558\n9559\n9560\n9561\n9562\n9563\n9564\n9565\n9566\n9567\n9568\n9569\n9570\n9571\n9572\n9573\n9574\n9575\n9576\n9577\n9578\n9579\n9580\n9581\n9582\n9583\n9584\n9585\n9586\n9587\n9588\n9589\n9590\n9591\n9592\n9593\n9594\n9595\n9596\n9597\n9598\n9599\n9600\n9601\n9602\n9603\n9604\n9605\n9606\n9607\n9608\n9609\n9610\n9611\n9612\n9613\n9614\n9615\n9616\n9617\n9618\n9619\n9620\n9621\n9622\n9623\n9624\n9625\n9626\n9627\n9628\n9629\n9630\n9631\n9632\n9633\n9634\n9635\n9636\n9637\n9638\n9639\n9640\n9641\n9642\n9643\n9644\n9645\n9646\n9647\n9648\n9649\n9650\n9651\n9652\n9653\n9654\n9655\n9656\n9657\n9658\n9659\n9660\n9661\n9662\n9663\n9664\n9665\n9666\n9667\n9668\n9669\n9670\n9671\n9672\n9673\n9674\n9675\n9676\n9677\n9678\n9679\n9680\n9681\n9682\n9683\n9684\n9685\n9686\n9687\n9688\n9689\n9690\n9691\n9692\n9693\n9694\n9695\n9696\n9697\n9698\n9699\n9700\n9701\n9702\n9703\n9704\n9705\n9706\n9707\n9708\n9709\n9710\n9711\n9712\n9713\n9714\n9715\n9716\n9717\n9718\n9719\n9720\n9721\n9722\n9723\n9724\n9725\n9726\n9727\n9728\n9729\n9730\n9731\n9732\n9733\n9734\n9735\n9736\n9737\n9738\n9739\n9740\n9741\n9742\n9743\n9744\n9745\n9746\n9747\n9748\n9749\n9750\n9751\n9752\n9753\n9754\n9755\n9756\n9757\n9758\n9759\n9760\n9761\n9762\n9763\n9764\n9765\n9766\n9767\n9768\n9769\n9770\n9771\n9772\n9773\n9774\n9775\n9776\n9777\n9778\n9779\n9780\n9781\n9782\n9783\n9784\n9785\n9786\n9787\n9788\n9789\n9790\n9791\n9792\n9793\n9794\n9795\n9796\n9797\n9798\n9799\n9800\n9801\n9802\n9803\n9804\n9805\n9806\n9807\n9808\n9809\n9810\n9811\n9812\n9813\n9814\n9815\n9816\n9817\n9818\n9819\n9820\n9821\n9822\n9823\n9824\n9825\n9826\n9827\n9828\n9829\n9830\n9831\n9832\n9833\n9834\n9835\n9836\n9837\n9838\n9839\n9840\n9841\n9842\n9843\n9844\n9845\n9846\n9847\n9848\n9849\n9850\n9851\n9852\n9853\n9854\n9855\n9856\n9857\n9858\n9859\n9860\n9861\n9862\n9863\n9864\n9865\n9866\n9867\n9868\n9869\n9870\n9871\n9872\n9873\n9874\n9875\n9876\n9877\n9878\n9879\n9880\n9881\n9882\n9883\n9884\n9885\n9886\n9887\n9888\n9889\n9890\n9891\n9892\n9893\n9894\n9895\n9896\n9897\n9898\n9899\n9900\n9901\n9902\n9903\n9904\n9905\n9906\n9907\n9908\n9909\n9910\n9911\n9912\n9913\n9914\n9915\n9916\n9917\n9918\n9919\n9920\n9921\n9922\n9923\n9924\n9925\n9926\n9927\n9928\n9929\n9930\n9931\n9932\n9933\n9934\n9935\n9936\n9937\n9938\n9939\n9940\n9941\n9942\n9943\n9944\n9945\n9946\n9947\n9948\n9949\n9950\n9951\n9952\n9953\n9954\n9955\n9956\n9957\n9958\n9959\n9960\n9961\n9962\n9963\n9964\n9965\n9966\n9967\n9968\n9969\n9970\n9971\n9972\n9973\n9974\n9975\n9976\n9977\n9978\n9979\n9980\n9981\n9982\n9983\n9984\n9985\n9986\n9987\n9988\n9989\n9990\n9991\n9992\n9993\n9994\n9995\n9996\n9997\n9998\n9999\n10000\n10001\n10002\n10003\n10004\n10005\n10006\n10007\n10008\n10009\n10010\n10011\n10012\n10013\n10014\n10015\n10016\n10017\n10018\n10019\n10020\n10021\n10022\n10023\n10024\n10025\n10026\n10027\n10028\n10029\n10030\n10031\n10032\n10033\n10034\n10035\n10036\n10037\n10038\n10039\n10040\n10041\n10042\n10043\n10044\n10045\n10046\n10047\n10048\n10049\n10050\n10051\n10052\n10053\n10054\n10055\n10056\n10057\n10058\n10059\n10060\n10061\n10062\n10063\n10064\n10065\n10066\n10067\n10068\n10069\n10070\n10071\n10072\n10073\n10074\n10075\n10076\n10077\n10078\n10079\n10080\n10081\n10082\n10083\n10084\n10085\n10086\n10087\n10088\n10089\n10090\n10091\n10092\n10093\n10094\n10095\n10096\n10097\n10098\n10099\n10100\n10101\n10102\n10103\n10104\n10105\n10106\n10107\n10108\n10109\n10110\n10111\n10112\n10113\n10114\n10115\n10116\n10117\n10118\n10119\n10120\n10121\n10122\n10123\n10124\n10125\n10126\n10127\n10128\n10129\n10130\n10131\n10132\n10133\n10134\n10135\n10136\n10137\n10138\n10139\n10140\n10141\n10142\n10143\n10144\n10145\n10146\n10147\n10148\n10149\n10150\n10151\n10152\n10153\n10154\n10155\n10156\n10157\n10158\n10159\n10160\n10161\n10162\n10163\n10164\n10165\n10166\n10167\n10168\n10169\n10170\n10171\n10172\n10173\n10174\n10175\n10176\n10177\n10178\n10179\n10180\n10181\n10182\n10183\n10184\n10185\n10186\n10187\n10188\n10189\n10190\n10191\n10192\n10193\n10194\n10195\n10196\n10197\n10198\n10199\n10200\n10201\n10202\n10203\n10204\n10205\n10206\n10207\n10208\n10209\n10210\n10211\n10212\n10213\n10214\n10215\n10216\n10217\n10218\n10219\n10220\n10221\n10222\n10223\n10224\n10225\n10226\n10227\n10228\n10229\n10230\n10231\n10232\n10233\n10234\n10235\n10236\n10237\n10238\n10239\n10240\n10241\n10242\n10243\n10244\n10245\n10246\n10247\n10248\n10249\n10250\n10251\n10252\n10253\n10254\n10255\n10256\n10257\n10258\n10259\n10260\n10261\n10262\n10263\n10264\n10265\n10266\n10267\n10268\n10269\n10270\n10271\n10272\n10273\n10274\n10275\n10276\n10277\n10278\n10279\n10280\n10281\n10282\n10283\n10284\n10285\n10286\n10287\n10288\n10289\n10290\n10291\n10292\n10293\n10294\n10295\n10296\n10297\n10298\n10299\n10300\n10301\n10302\n10303\n10304\n10305\n10306\n10307\n10308\n10309\n10310\n10311\n10312\n10313\n10314\n10315\n10316\n10317\n10318\n10319\n10320\n10321\n10322\n10323\n10324\n10325\n10326\n10327\n10328\n10329\n10330\n10331\n10332\n10333\n10334\n10335\n10336\n10337\n10338\n10339\n10340\n10341\n10342\n10343\n10344\n10345\n10346\n10347\n10348\n10349\n10350\n10351\n10352\n10353\n10354\n10355\n10356\n10357\n10358\n10359\n10360\n10361\n10362\n10363\n10364\n10365\n10366\n10367\n10368\n10369\n10370\n10371\n10372\n10373\n10374\n10375\n10376\n10377\n10378\n10379\n10380\n10381\n10382\n10383\n10384\n10385\n10386\n10387\n10388\n10389\n10390\n10391\n10392\n10393\n10394\n10395\n10396\n10397\n10398\n10399\n10400\n10401\n10402\n10403\n10404\n10405\n10406\n10407\n10408\n10409\n10410\n10411\n10412\n10413\n10414\n10415\n10416\n10417\n10418\n10419\n10420\n10421\n10422\n10423\n10424\n10425\n10426\n10427\n10428\n10429\n10430\n10431\n10432\n10433\n10434\n10435\n10436\n10437\n10438\n10439\n10440\n10441\n10442\n10443\n10444\n10445\n10446\n10447\n10448\n10449\n10450\n10451\n10452\n10453\n10454\n10455\n10456\n10457\n10458\n10459\n10460\n10461\n10462\n10463\n10464\n10465\n10466\n10467\n10468\n10469\n10470\n10471\n10472\n10473\n10474\n10475\n10476\n10477\n10478\n10479\n10480\n10481\n10482\n10483\n10484\n10485\n10486\n10487\n10488\n10489\n10490\n10491\n10492\n10493\n10494\n10495\n10496\n10497\n10498\n10499\n10500\n10501\n10502\n10503\n10504\n10505\n10506\n10507\n10508\n10509\n10510\n10511\n10512\n10513\n10514\n10515\n10516\n10517\n10518\n10519\n10520\n10521\n10522\n10523\n10524\n10525\n10526\n10527\n10528\n10529\n10530\n10531\n10532\n10533\n10534\n10535\n10536\n10537\n10538\n10539\n10540\n10541\n10542\n10543\n10544\n10545\n10546\n10547\n10548\n10549\n10550\n10551\n10552\n10553\n10554\n10555\n10556\n10557\n10558\n10559\n10560\n10561\n10562\n10563\n10564\n10565\n10566\n10567\n10568\n10569\n10570\n10571\n10572\n10573\n10574\n10575\n10576\n10577\n10578\n10579\n10580\n10581\n10582\n10583\n10584\n10585\n10586\n10587\n10588\n10589\n10590\n10591\n10592\n10593\n10594\n10595\n10596\n10597\n10598\n10599\n10600\n10601\n10602\n10603\n10604\n10605\n10606\n10607\n10608\n10609\n10610\n10611\n10612\n10613\n10614\n10615\n10616\n10617\n10618\n10619\n10620\n10621\n10622\n10623\n10624\n10625\n10626\n10627\n10628\n10629\n10630\n10631\n10632\n10633\n10634\n10635\n10636\n10637\n10638\n10639\n10640\n10641\n10642\n10643\n10644\n10645\n10646\n10647\n10648\n10649\n10650\n10651\n10652\n10653\n10654\n10655\n10656\n10657\n10658\n10659\n10660\n10661\n10662\n10663\n10664\n10665\n10666\n10667\n10668\n10669\n10670\n10671\n10672\n10673\n10674\n10675\n10676\n10677\n10678\n10679\n10680\n10681\n10682\n10683\n10684\n10685\n10686\n10687\n10688\n10689\n10690\n10691\n10692\n10693\n10694\n10695\n10696\n10697\n10698\n10699\n10700\n10701\n10702\n10703\n10704\n10705\n10706\n10707\n10708\n10709\n10710\n10711\n10712\n10713\n10714\n10715\n10716\n10717\n10718\n10719\n10720\n10721\n10722\n10723\n10724\n10725\n10726\n10727\n10728\n10729\n10730\n10731\n10732\n10733\n10734\n10735\n10736\n10737\n10738\n10739\n10740\n10741\n10742\n10743\n10744\n10745\n10746\n10747\n10748\n10749\n10750\n10751\n10752\n10753\n10754\n10755\n10756\n10757\n10758\n10759\n10760\n10761\n10762\n10763\n10764\n10765\n10766\n10767\n10768\n10769\n10770\n10771\n10772\n10773\n10774\n10775\n10776\n10777\n10778\n10779\n10780\n10781\n10782\n10783\n10784\n10785\n10786\n10787\n10788\n10789\n10790\n10791\n10792\n10793\n10794\n10795\n10796\n10797\n10798\n10799\n10800\n10801\n10802\n10803\n10804\n10805\n10806\n10807\n10808\n10809\n10810\n10811\n10812\n10813\n10814\n10815\n10816\n10817\n10818\n10819\n10820\n10821\n10822\n10823\n10824\n10825\n10826\n10827\n10828\n10829\n10830\n10831\n10832\n10833\n10834\n10835\n10836\n10837\n10838\n10839\n10840\n10841\n10842\n10843\n10844\n10845\n10846\n10847\n10848\n10849\n10850\n10851\n10852\n10853\n10854\n10855\n10856\n10857\n10858\n10859\n10860\n10861\n10862\n10863\n10864\n10865\n10866\n10867\n10868\n10869\n10870\n10871\n10872\n10873\n10874\n10875\n10876\n10877\n10878\n10879\n10880\n10881\n10882\n10883\n10884\n10885\n10886\n10887\n10888\n10889\n10890\n10891\n10892\n10893\n10894\n10895\n10896\n10897\n10898\n10899\n10900\n10901\n10902\n10903\n10904\n10905\n10906\n10907\n10908\n10909\n10910\n10911\n10912\n10913\n10914\n10915\n10916\n10917\n10918\n10919\n10920\n10921\n10922\n10923\n10924\n10925\n10926\n10927\n10928\n10929\n10930\n10931\n10932\n10933\n10934\n10935\n10936\n10937\n10938\n10939\n10940\n10941\n10942\n10943\n10944\n10945\n10946\n10947\n10948\n10949\n10950\n10951\n10952\n10953\n10954\n10955\n10956\n10957\n10958\n10959\n10960\n10961\n10962\n10963\n10964\n10965\n10966\n10967\n10968\n10969\n10970\n10971\n10972\n10973\n10974\n10975\n10976\n10977\n10978\n10979\n10980\n10981\n10982\n10983\n10984\n10985\n10986\n10987\n10988\n10989\n10990\n10991\n10992\n10993\n10994\n10995\n10996\n10997\n10998\n10999\n11000\n11001\n11002\n11003\n11004\n11005\n11006\n11007\n11008\n11009\n11010\n11011\n11012\n11013\n11014\n11015\n11016\n11017\n11018\n11019\n11020\n11021\n11022\n11023\n11024\n11025\n11026\n11027\n11028\n11029\n11030\n11031\n11032\n11033\n11034\n11035\n11036\n11037\n11038\n11039\n11040\n11041\n11042\n11043\n11044\n11045\n11046\n11047\n11048\n11049\n11050\n11051\n11052\n11053\n11054\n11055\n11056\n11057\n11058\n11059\n11060\n11061\n11062\n11063\n11064\n11065\n11066\n11067\n11068\n11069\n11070\n11071\n11072\n11073\n11074\n11075\n11076\n11077\n11078\n11079\n11080\n11081\n11082\n11083\n11084\n11085\n11086\n11087\n11088\n11089\n11090\n11091\n11092\n11093\n11094\n11095\n11096\n11097\n11098\n11099\n11100\n11101\n11102\n11103\n11104\n11105\n11106\n11107\n11108\n11109\n11110\n11111\n11112\n11113\n11114\n11115\n11116\n11117\n11118\n11119\n11120\n11121\n11122\n11123\n11124\n11125\n11126\n11127\n11128\n11129\n11130\n11131\n11132\n11133\n11134\n11135\n11136\n11137\n11138\n11139\n11140\n11141\n11142\n11143\n11144\n11145\n11146\n11147\n11148\n11149\n11150\n11151\n11152\n11153\n11154\n11155\n11156\n11157\n11158\n11159\n11160\n11161\n11162\n11163\n11164\n11165\n11166\n11167\n11168\n11169\n11170\n11171\n11172\n11173\n11174\n11175\n11176\n11177\n11178\n11179\n11180\n11181\n11182\n11183\n11184\n11185\n11186\n11187\n11188\n11189\n11190\n11191\n11192\n11193\n11194\n11195\n11196\n11197\n11198\n11199\n11200\n11201\n11202\n11203\n11204\n11205\n11206\n11207\n11208\n11209\n11210\n11211\n11212\n11213\n11214\n11215\n11216\n11217\n11218\n11219\n11220\n11221\n11222\n11223\n11224\n11225\n11226\n11227\n11228\n11229\n11230\n11231\n11232\n11233\n11234\n11235\n11236\n11237\n11238\n11239\n11240\n11241\n11242\n11243\n11244\n11245\n11246\n11247\n11248\n11249\n11250\n11251\n11252\n11253\n11254\n11255\n11256\n11257\n11258\n11259\n11260\n11261\n11262\n11263\n11264\n11265\n11266\n11267\n11268\n11269\n11270\n11271\n11272\n11273\n11274\n11275\n11276\n11277\n11278\n11279\n11280\n11281\n11282\n11283\n11284\n11285\n11286\n11287\n11288\n11289\n11290\n11291\n11292\n11293\n11294\n11295\n11296\n11297\n11298\n11299\n11300\n11301\n11302\n11303\n11304\n11305\n11306\n11307\n11308\n11309\n11310\n11311\n11312\n11313\n11314\n11315\n11316\n11317\n11318\n11319\n11320\n11321\n11322\n11323\n11324\n11325\n11326\n11327\n11328\n11329\n11330\n11331\n11332\n11333\n11334\n11335\n11336\n11337\n11338\n11339\n11340\n11341\n11342\n11343\n11344\n11345\n11346\n11347\n11348\n11349\n11350\n11351\n11352\n11353\n11354\n11355\n11356\n11357\n11358\n11359\n11360\n11361\n11362\n11363\n11364\n11365\n11366\n11367\n11368\n11369\n11370\n11371\n11372\n11373\n11374\n11375\n11376\n11377\n11378\n11379\n11380\n11381\n11382\n11383\n11384\n11385\n11386\n11387\n11388\n11389\n11390\n11391\n11392\n11393\n11394\n11395\n11396\n11397\n11398\n11399\n11400\n11401\n11402\n11403\n11404\n11405\n11406\n11407\n11408\n11409\n11410\n11411\n11412\n11413\n11414\n11415\n11416\n11417\n11418\n11419\n11420\n11421\n11422\n11423\n11424\n11425\n11426\n11427\n11428\n11429\n11430\n11431\n11432\n11433\n11434\n11435\n11436\n11437\n11438\n11439\n11440\n11441\n11442\n11443\n11444\n11445\n11446\n11447\n11448\n11449\n11450\n11451\n11452\n11453\n11454\n11455\n11456\n11457\n11458\n11459\n11460\n11461\n11462\n11463\n11464\n11465\n11466\n11467\n11468\n11469\n11470\n11471\n11472\n11473\n11474\n11475\n11476\n11477\n11478\n11479\n11480\n11481\n11482\n11483\n11484\n11485\n11486\n11487\n11488\n11489\n11490\n11491\n11492\n11493\n11494\n11495\n11496\n11497\n11498\n11499\n11500\n11501\n11502\n11503\n11504\n11505\n11506\n11507\n11508\n11509\n11510\n11511\n11512\n11513\n11514\n11515\n11516\n11517\n11518\n11519\n11520\n11521\n11522\n11523\n11524\n11525\n11526\n11527\n11528\n11529\n11530\n11531\n11532\n11533\n11534\n11535\n11536\n11537\n11538\n11539\n11540\n11541\n11542\n11543\n11544\n11545\n11546\n11547\n11548\n11549\n11550\n11551\n11552\n11553\n11554\n11555\n11556\n11557\n11558\n11559\n11560\n11561\n11562\n11563\n11564\n11565\n11566\n11567\n11568\n11569\n11570\n11571\n11572\n11573\n11574\n11575\n11576\n11577\n11578\n11579\n11580\n11581\n11582\n11583\n11584\n11585\n11586\n11587\n11588\n11589\n11590\n11591\n11592\n11593\n11594\n11595\n11596\n11597\n11598\n11599\n11600\n11601\n11602\n11603\n11604\n11605\n11606\n11607\n11608\n11609\n11610\n11611\n11612\n11613\n11614\n11615\n11616\n11617\n11618\n11619\n11620\n11621\n11622\n11623\n11624\n11625\n11626\n11627\n11628\n11629\n11630\n11631\n11632\n11633\n11634\n11635\n11636\n11637\n11638\n11639\n11640\n11641\n11642\n11643\n11644\n11645\n11646\n11647\n11648\n11649\n11650\n11651\n11652\n11653\n11654\n11655\n11656\n11657\n11658\n11659\n11660\n11661\n11662\n11663\n11664\n11665\n11666\n11667\n11668\n11669\n11670\n11671\n11672\n11673\n11674\n11675\n11676\n11677\n11678\n11679\n11680\n11681\n11682\n11683\n11684\n11685\n11686\n11687\n11688\n11689\n11690\n11691\n11692\n11693\n11694\n11695\n11696\n11697\n11698\n11699\n11700\n11701\n11702\n11703\n11704\n11705\n11706\n11707\n11708\n11709\n11710\n11711\n11712\n11713\n11714\n11715\n11716\n11717\n11718\n11719\n11720\n11721\n11722\n11723\n11724\n11725\n11726\n11727\n11728\n11729\n11730\n11731\n11732\n11733\n11734\n11735\n11736\n11737\n11738\n11739\n11740\n11741\n11742\n11743\n11744\n11745\n11746\n11747\n11748\n11749\n11750\n11751\n11752\n11753\n11754\n11755\n11756\n11757\n11758\n11759\n11760\n11761\n11762\n11763\n11764\n11765\n11766\n11767\n11768\n11769\n11770\n11771\n11772\n11773\n11774\n11775\n11776\n11777\n11778\n11779\n11780\n11781\n11782\n11783\n11784\n11785\n11786\n11787\n11788\n11789\n11790\n11791\n11792\n11793\n11794\n11795\n11796\n11797\n11798\n11799\n11800\n11801\n11802\n11803\n11804\n11805\n11806\n11807\n11808\n11809\n11810\n11811\n11812\n11813\n11814\n11815\n11816\n11817\n11818\n11819\n11820\n11821\n11822\n11823\n11824\n11825\n11826\n11827\n11828\n11829\n11830\n11831\n11832\n11833\n11834\n11835\n11836\n11837\n11838\n11839\n11840\n11841\n11842\n11843\n11844\n11845\n11846\n11847\n11848\n11849\n11850\n11851\n11852\n11853\n11854\n11855\n11856\n11857\n11858\n11859\n11860\n11861\n11862\n11863\n11864\n11865\n11866\n11867\n11868\n11869\n11870\n11871\n11872\n11873\n11874\n11875\n11876\n11877\n11878\n11879\n11880\n11881\n11882\n11883\n11884\n11885\n11886\n11887\n11888\n11889\n11890\n11891\n11892\n11893\n11894\n11895\n11896\n11897\n11898\n11899\n11900\n11901\n11902\n11903\n11904\n11905\n11906\n11907\n11908\n11909\n11910\n11911\n11912\n11913\n11914\n11915\n11916\n11917\n11918\n11919\n11920\n11921\n11922\n11923\n11924\n11925\n11926\n11927\n11928\n11929\n11930\n11931\n11932\n11933\n11934\n11935\n11936\n11937\n11938\n11939\n11940\n11941\n11942\n11943\n11944\n11945\n11946\n11947\n11948\n11949\n11950\n11951\n11952\n11953\n11954\n11955\n11956\n11957\n11958\n11959\n11960\n11961\n11962\n11963\n11964\n11965\n11966\n11967\n11968\n11969\n11970\n11971\n11972\n11973\n11974\n11975\n11976\n11977\n11978\n11979\n11980\n11981\n11982\n11983\n11984\n11985\n11986\n11987\n11988\n11989\n11990\n11991\n11992\n11993\n11994\n11995\n11996\n11997\n11998\n11999\n12000\n12001\n12002\n12003\n12004\n12005\n12006\n12007\n12008\n12009\n12010\n12011\n12012\n12013\n12014\n12015\n12016\n12017\n12018\n12019\n12020\n12021\n12022\n12023\n12024\n12025\n12026\n12027\n12028\n12029\n12030\n12031\n12032\n12033\n12034\n12035\n12036\n12037\n12038\n12039\n12040\n12041\n12042\n12043\n12044\n12045\n12046\n12047\n12048\n12049\n12050\n12051\n12052\n12053\n12054\n12055\n12056\n12057\n12058\n12059\n12060\n12061\n12062\n12063\n12064\n12065\n12066\n12067\n12068\n12069\n12070\n12071\n12072\n12073\n12074\n12075\n12076\n12077\n12078\n12079\n12080\n12081\n12082\n12083\n12084\n12085\n12086\n12087\n12088\n12089\n12090\n12091\n12092\n12093\n12094\n12095\n12096\n12097\n12098\n12099\n12100\n12101\n12102\n12103\n12104\n12105\n12106\n12107\n12108\n12109\n12110\n12111\n12112\n12113\n12114\n12115\n12116\n12117\n12118\n12119\n12120\n12121\n12122\n12123\n12124\n12125\n12126\n12127\n12128\n12129\n12130\n12131\n12132\n12133\n12134\n12135\n12136\n12137\n12138\n12139\n12140\n12141\n12142\n12143\n12144\n12145\n12146\n12147\n12148\n12149\n12150\n12151\n12152\n12153\n12154\n12155\n12156\n12157\n12158\n12159\n12160\n12161\n12162\n12163\n12164\n12165\n12166\n12167\n12168\n12169\n12170\n12171\n12172\n12173\n12174\n12175\n12176\n12177\n12178\n12179\n12180\n12181\n12182\n12183\n12184\n12185\n12186\n12187\n12188\n12189\n12190\n12191\n12192\n12193\n12194\n12195\n12196\n12197\n12198\n12199\n12200\n12201\n12202\n12203\n12204\n12205\n12206\n12207\n12208\n12209\n12210\n12211\n12212\n12213\n12214\n12215\n12216\n12217\n12218\n12219\n12220\n12221\n12222\n12223\n12224\n12225\n12226\n12227\n12228\n12229\n12230\n12231\n12232\n12233\n12234\n12235\n12236\n12237\n12238\n12239\n12240\n12241\n12242\n12243\n12244\n12245\n12246\n12247\n12248\n12249\n12250\n12251\n12252\n12253\n12254\n12255\n12256\n12257\n12258\n12259\n12260\n12261\n12262\n12263\n12264\n12265\n12266\n12267\n12268\n12269\n12270\n12271\n12272\n12273\n12274\n12275\n12276\n12277\n12278\n12279\n12280\n12281\n12282\n12283\n12284\n12285\n12286\n12287\n12288\n12289\n12290\n12291\n12292\n12293\n12294\n12295\n12296\n12297\n12298\n12299\n12300\n12301\n12302\n12303\n12304\n12305\n12306\n12307\n12308\n12309\n12310\n12311\n12312\n12313\n12314\n12315\n12316\n12317\n12318\n12319\n12320\n12321\n12322\n12323\n12324\n12325\n12326\n12327\n12328\n12329\n12330\n12331\n12332\n12333\n12334\n12335\n12336\n12337\n12338\n12339\n12340\n12341\n12342\n12343\n12344\n12345\n12346\n12347\n12348\n12349\n12350\n12351\n12352\n12353\n12354\n12355\n12356\n12357\n12358\n12359\n12360\n12361\n12362\n12363\n12364\n12365\n12366\n12367\n12368\n12369\n12370\n12371\n12372\n12373\n12374\n12375\n12376\n12377\n12378\n12379\n12380\n12381\n12382\n12383\n12384\n12385\n12386\n12387\n12388\n12389\n12390\n12391\n12392\n12393\n12394\n12395\n12396\n12397\n12398\n12399\n12400\n12401\n12402\n12403\n12404\n12405\n12406\n12407\n12408\n12409\n12410\n12411\n12412\n12413\n12414\n12415\n12416\n12417\n12418\n12419\n12420\n12421\n12422\n12423\n12424\n12425\n12426\n12427\n12428\n12429\n12430\n12431\n12432\n12433\n12434\n12435\n12436\n12437\n12438\n12439\n12440\n12441\n12442\n12443\n12444\n12445\n12446\n12447\n12448\n12449\n12450\n12451\n12452\n12453\n12454\n12455\n12456\n12457\n12458\n12459\n12460\n12461\n12462\n12463\n12464\n12465\n12466\n12467\n12468\n12469\n12470\n12471\n12472\n12473\n12474\n12475\n12476\n12477\n12478\n12479\n12480\n12481\n12482\n12483\n12484\n12485\n12486\n12487\n12488\n12489\n12490\n12491\n12492\n12493\n12494\n12495\n12496\n12497\n12498\n12499\n12500\n12501\n12502\n12503\n12504\n12505\n12506\n12507\n12508\n12509\n12510\n12511\n12512\n12513\n12514\n12515\n12516\n12517\n12518\n12519\n12520\n12521\n12522\n12523\n12524\n12525\n12526\n12527\n12528\n12529\n12530\n12531\n12532\n12533\n12534\n12535\n12536\n12537\n12538\n12539\n12540\n12541\n12542\n12543\n12544\n12545\n12546\n12547\n12548\n12549\n12550\n12551\n12552\n12553\n12554\n12555\n12556\n12557\n12558\n12559\n12560\n12561\n12562\n12563\n12564\n12565\n12566\n12567\n12568\n12569\n12570\n12571\n12572\n12573\n12574\n12575\n12576\n12577\n12578\n12579\n12580\n12581\n12582\n12583\n12584\n12585\n12586\n12587\n12588\n12589\n12590\n12591\n12592\n12593\n12594\n12595\n12596\n12597\n12598\n12599\n12600\n12601\n12602\n12603\n12604\n12605\n12606\n12607\n12608\n12609\n12610\n12611\n12612\n12613\n12614\n12615\n12616\n12617\n12618\n12619\n12620\n12621\n12622\n12623\n12624\n12625\n12626\n12627\n12628\n12629\n12630\n12631\n12632\n12633\n12634\n12635\n12636\n12637\n12638\n12639\n12640\n12641\n12642\n12643\n12644\n12645\n12646\n12647\n12648\n12649\n12650\n12651\n12652\n12653\n12654\n12655\n12656\n12657\n12658\n12659\n12660\n12661\n12662\n12663\n12664\n12665\n12666\n12667\n12668\n12669\n12670\n12671\n12672\n12673\n12674\n12675\n12676\n12677\n12678\n12679\n12680\n12681\n12682\n12683\n12684\n12685\n12686\n12687\n12688\n12689\n12690\n12691\n12692\n12693\n12694\n12695\n12696\n12697\n12698\n12699\n12700\n12701\n12702\n12703\n12704\n12705\n12706\n12707\n12708\n12709\n12710\n12711\n12712\n12713\n12714\n12715\n12716\n12717\n12718\n12719\n12720\n12721\n12722\n12723\n12724\n12725\n12726\n12727\n12728\n12729\n12730\n12731\n12732\n12733\n12734\n12735\n12736\n12737\n12738\n12739\n12740\n12741\n12742\n12743\n12744\n12745\n12746\n12747\n12748\n12749\n12750\n12751\n12752\n12753\n12754\n12755\n12756\n12757\n12758\n12759\n12760\n12761\n12762\n12763\n12764\n12765\n12766\n12767\n12768\n12769\n12770\n12771\n12772\n12773\n12774\n12775\n12776\n12777\n12778\n12779\n12780\n12781\n12782\n12783\n12784\n12785\n12786\n12787\n12788\n12789\n12790\n12791\n12792\n12793\n12794\n12795\n12796\n12797\n12798\n12799\n12800\n12801\n12802\n12803\n12804\n12805\n12806\n12807\n12808\n12809\n12810\n12811\n12812\n12813\n12814\n12815\n12816\n12817\n12818\n12819\n12820\n12821\n12822\n12823\n12824\n12825\n12826\n12827\n12828\n12829\n12830\n12831\n12832\n12833\n12834\n12835\n12836\n12837\n12838\n12839\n12840\n12841\n12842\n12843\n12844\n12845\n12846\n12847\n12848\n12849\n12850\n12851\n12852\n12853\n12854\n12855\n12856\n12857\n12858\n12859\n12860\n12861\n12862\n12863\n12864\n12865\n12866\n12867\n12868\n12869\n12870\n12871\n12872\n12873\n12874\n12875\n12876\n12877\n12878\n12879\n12880\n12881\n12882\n12883\n12884\n12885\n12886\n12887\n12888\n12889\n12890\n12891\n12892\n12893\n12894\n12895\n12896\n12897\n12898\n12899\n12900\n12901\n12902\n12903\n12904\n12905\n12906\n12907\n12908\n12909\n12910\n12911\n12912\n12913\n12914\n12915\n12916\n12917\n12918\n12919\n12920\n12921\n12922\n12923\n12924\n12925\n12926\n12927\n12928\n12929\n12930\n12931\n12932\n12933\n12934\n12935\n12936\n12937\n12938\n12939\n12940\n12941\n12942\n12943\n12944\n12945\n12946\n12947\n12948\n12949\n12950\n12951\n12952\n12953\n12954\n12955\n12956\n12957\n12958\n12959\n12960\n12961\n12962\n12963\n12964\n12965\n12966\n12967\n12968\n12969\n12970\n12971\n12972\n12973\n12974\n12975\n12976\n12977\n12978\n12979\n12980\n12981\n12982\n12983\n12984\n12985\n12986\n12987\n12988\n12989\n12990\n12991\n12992\n12993\n12994\n12995\n12996\n12997\n12998\n12999\n13000\n13001\n13002\n13003\n13004\n13005\n13006\n13007\n13008\n13009\n13010\n13011\n13012\n13013\n13014\n13015\n13016\n13017\n13018\n13019\n13020\n13021\n13022\n13023\n13024\n13025\n13026\n13027\n13028\n13029\n13030\n13031\n13032\n13033\n13034\n13035\n13036\n13037\n13038\n13039\n13040\n13041\n13042\n13043\n13044\n13045\n13046\n13047\n13048\n13049\n13050\n13051\n13052\n13053\n13054\n13055\n13056\n13057\n13058\n13059\n13060\n13061\n13062\n13063\n13064\n13065\n13066\n13067\n13068\n13069\n13070\n13071\n13072\n13073\n13074\n13075\n13076\n13077\n13078\n13079\n13080\n13081\n13082\n13083\n13084\n13085\n13086\n13087\n13088\n13089\n13090\n13091\n13092\n13093\n13094\n13095\n13096\n13097\n13098\n13099\n13100\n13101\n13102\n13103\n13104\n13105\n13106\n13107\n13108\n13109\n13110\n13111\n13112\n13113\n13114\n13115\n13116\n13117\n13118\n13119\n13120\n13121\n13122\n13123\n13124\n13125\n13126\n13127\n13128\n13129\n13130\n13131\n13132\n13133\n13134\n13135\n13136\n13137\n13138\n13139\n13140\n13141\n13142\n13143\n13144\n13145\n13146\n13147\n13148\n13149\n13150\n13151\n13152\n13153\n13154\n13155\n13156\n13157\n13158\n13159\n13160\n13161\n13162\n13163\n13164\n13165\n13166\n13167\n13168\n13169\n13170\n13171\n13172\n13173\n13174\n13175\n13176\n13177\n13178\n13179\n13180\n13181\n13182\n13183\n13184\n13185\n13186\n13187\n13188\n13189\n13190\n13191\n13192\n13193\n13194\n13195\n13196\n13197\n13198\n13199\n13200\n13201\n13202\n13203\n13204\n13205\n13206\n13207\n13208\n13209\n13210\n13211\n13212\n13213\n13214\n13215\n13216\n13217\n13218\n13219\n13220\n13221\n13222\n13223\n13224\n13225\n13226\n13227\n13228\n13229\n13230\n13231\n13232\n13233\n13234\n13235\n13236\n13237\n13238\n13239\n13240\n13241\n13242\n13243\n13244\n13245\n13246\n13247\n13248\n13249\n13250\n13251\n13252\n13253\n13254\n13255\n13256\n13257\n13258\n13259\n13260\n13261\n13262\n13263\n13264\n13265\n13266\n13267\n13268\n13269\n13270\n13271\n13272\n13273\n13274\n13275\n13276\n13277\n13278\n13279\n13280\n13281\n13282\n13283\n13284\n13285\n13286\n13287\n13288\n13289\n13290\n13291\n13292\n13293\n13294\n13295\n13296\n13297\n13298\n13299\n13300\n13301\n13302\n13303\n13304\n13305\n13306\n13307\n13308\n13309\n13310\n13311\n13312\n13313\n13314\n13315\n13316\n13317\n13318\n13319\n13320\n13321\n13322\n13323\n13324\n13325\n13326\n13327\n13328\n13329\n13330\n13331\n13332\n13333\n13334\n13335\n13336\n13337\n13338\n13339\n13340\n13341\n13342\n13343\n13344\n13345\n13346\n13347\n13348\n13349\n13350\n13351\n13352\n13353\n13354\n13355\n13356\n13357\n13358\n13359\n13360\n13361\n13362\n13363\n13364\n13365\n13366\n13367\n13368\n13369\n13370\n13371\n13372\n13373\n13374\n13375\n13376\n13377\n13378\n13379\n13380\n13381\n13382\n13383\n13384\n13385\n13386\n13387\n13388\n13389\n13390\n13391\n13392\n13393\n13394\n13395\n13396\n13397\n13398\n13399\n13400\n13401\n13402\n13403\n13404\n13405\n13406\n13407\n13408\n13409\n13410\n13411\n13412\n13413\n13414\n13415\n13416\n13417\n13418\n13419\n13420\n13421\n13422\n13423\n13424\n13425\n13426\n13427\n13428\n13429\n13430\n13431\n13432\n13433\n13434\n13435\n13436\n13437\n13438\n13439\n13440\n13441\n13442\n13443\n13444\n13445\n13446\n13447\n13448\n13449\n13450\n13451\n13452\n13453\n13454\n13455\n13456\n13457\n13458\n13459\n13460\n13461\n13462\n13463\n13464\n13465\n13466\n13467\n13468\n13469\n13470\n13471\n13472\n13473\n13474\n13475\n13476\n13477\n13478\n13479\n13480\n13481\n13482\n13483\n13484\n13485\n13486\n13487\n13488\n13489\n13490\n13491\n13492\n13493\n13494\n13495\n13496\n13497\n13498\n13499\n13500\n13501\n13502\n13503\n13504\n13505\n13506\n13507\n13508\n13509\n13510\n13511\n13512\n13513\n13514\n13515\n13516\n13517\n13518\n13519\n13520\n13521\n13522\n13523\n13524\n13525\n13526\n13527\n13528\n13529\n13530\n13531\n13532\n13533\n13534\n13535\n13536\n13537\n13538\n13539\n13540\n13541\n13542\n13543\n13544\n13545\n13546\n13547\n13548\n13549\n13550\n13551\n13552\n13553\n13554\n13555\n13556\n13557\n13558\n13559\n13560\n13561\n13562\n13563\n13564\n13565\n13566\n13567\n13568\n13569\n13570\n13571\n13572\n13573\n13574\n13575\n13576\n13577\n13578\n13579\n13580\n13581\n13582\n13583\n13584\n13585\n13586\n13587\n13588\n13589\n13590\n13591\n13592\n13593\n13594\n13595\n13596\n13597\n13598\n13599\n13600\n13601\n13602\n13603\n13604\n13605\n13606\n13607\n13608\n13609\n13610\n13611\n13612\n13613\n13614\n13615\n13616\n13617\n13618\n13619\n13620\n13621\n13622\n13623\n13624\n13625\n13626\n13627\n13628\n13629\n13630\n13631\n13632\n13633\n13634\n13635\n13636\n13637\n13638\n13639\n13640\n13641\n13642\n13643\n13644\n13645\n13646\n13647\n13648\n13649\n13650\n13651\n13652\n13653\n13654\n13655\n13656\n13657\n13658\n13659\n13660\n13661\n13662\n13663\n13664\n13665\n13666\n13667\n13668\n13669\n13670\n13671\n13672\n13673\n13674\n13675\n13676\n13677\n13678\n13679\n13680\n13681\n13682\n13683\n13684\n13685\n13686\n13687\n13688\n13689\n13690\n13691\n13692\n13693\n13694\n13695\n13696\n13697\n13698\n13699\n13700\n13701\n13702\n13703\n13704\n13705\n13706\n13707\n13708\n13709\n13710\n13711\n13712\n13713\n13714\n13715\n13716\n13717\n13718\n13719\n13720\n13721\n13722\n13723\n13724\n13725\n13726\n13727\n13728\n13729\n13730\n13731\n13732\n13733\n13734\n13735\n13736\n13737\n13738\n13739\n13740\n13741\n13742\n13743\n13744\n13745\n13746\n13747\n13748\n13749\n13750\n13751\n13752\n13753\n13754\n13755\n13756\n13757\n13758\n13759\n13760\n13761\n13762\n13763\n13764\n13765\n13766\n13767\n13768\n13769\n13770\n13771\n13772\n13773\n13774\n13775\n13776\n13777\n13778\n13779\n13780\n13781\n13782\n13783\n13784\n13785\n13786\n13787\n13788\n13789\n13790\n13791\n13792\n13793\n13794\n13795\n13796\n13797\n13798\n13799\n13800\n13801\n13802\n13803\n13804\n13805\n13806\n13807\n13808\n13809\n13810\n13811\n13812\n13813\n13814\n13815\n13816\n13817\n13818\n13819\n13820\n13821\n13822\n13823\n13824\n13825\n13826\n13827\n13828\n13829\n13830\n13831\n13832\n13833\n13834\n13835\n13836\n13837\n13838\n13839\n13840\n13841\n13842\n13843\n13844\n13845\n13846\n13847\n13848\n13849\n13850\n13851\n13852\n13853\n13854\n13855\n13856\n13857\n13858\n13859\n13860\n13861\n13862\n13863\n13864\n13865\n13866\n13867\n13868\n13869\n13870\n13871\n13872\n13873\n13874\n13875\n13876\n13877\n13878\n13879\n13880\n13881\n13882\n13883\n13884\n13885\n13886\n13887\n13888\n13889\n13890\n13891\n13892\n13893\n13894\n13895\n13896\n13897\n13898\n13899\n13900\n13901\n13902\n13903\n13904\n13905\n13906\n13907\n13908\n13909\n13910\n13911\n13912\n13913\n13914\n13915\n13916\n13917\n13918\n13919\n13920\n13921\n13922\n13923\n13924\n13925\n13926\n13927\n13928\n13929\n13930\n13931\n13932\n13933\n13934\n13935\n13936\n13937\n13938\n13939\n13940\n13941\n13942\n13943\n13944\n13945\n13946\n13947\n13948\n13949\n13950\n13951\n13952\n13953\n13954\n13955\n13956\n13957\n13958\n13959\n13960\n13961\n13962\n13963\n13964\n13965\n13966\n13967\n13968\n13969\n13970\n13971\n13972\n13973\n13974\n13975\n13976\n13977\n13978\n13979\n13980\n13981\n13982\n13983\n13984\n13985\n13986\n13987\n13988\n13989\n13990\n13991\n13992\n13993\n13994\n13995\n13996\n13997\n13998\n13999\n14000\n14001\n14002\n14003\n14004\n14005\n14006\n14007\n14008\n14009\n14010\n14011\n14012\n14013\n14014\n14015\n14016\n14017\n14018\n14019\n14020\n14021\n14022\n14023\n14024\n14025\n14026\n14027\n14028\n14029\n14030\n14031\n14032\n14033\n14034\n14035\n14036\n14037\n14038\n14039\n14040\n14041\n14042\n14043\n14044\n14045\n14046\n14047\n14048\n14049\n14050\n14051\n14052\n14053\n14054\n14055\n14056\n14057\n14058\n14059\n14060\n14061\n14062\n14063\n14064\n14065\n14066\n14067\n14068\n14069\n14070\n14071\n14072\n14073\n14074\n14075\n14076\n14077\n14078\n14079\n14080\n14081\n14082\n14083\n14084\n14085\n14086\n14087\n14088\n14089\n14090\n14091\n14092\n14093\n14094\n14095\n14096\n14097\n14098\n14099\n14100\n14101\n14102\n14103\n14104\n14105\n14106\n14107\n14108\n14109\n14110\n14111\n14112\n14113\n14114\n14115\n14116\n14117\n14118\n14119\n14120\n14121\n14122\n14123\n14124\n14125\n14126\n14127\n14128\n14129\n14130\n14131\n14132\n14133\n14134\n14135\n14136\n14137\n14138\n14139\n14140\n14141\n14142\n14143\n14144\n14145\n14146\n14147\n14148\n14149\n14150\n14151\n14152\n14153\n14154\n14155\n14156\n14157\n14158\n14159\n14160\n14161\n14162\n14163\n14164\n14165\n14166\n14167\n14168\n14169\n14170\n14171\n14172\n14173\n14174\n14175\n14176\n14177\n14178\n14179\n14180\n14181\n14182\n14183\n14184\n14185\n14186\n14187\n14188\n14189\n14190\n14191\n14192\n14193\n14194\n14195\n14196\n14197\n14198\n14199\n14200\n14201\n14202\n14203\n14204\n14205\n14206\n14207\n14208\n14209\n14210\n14211\n14212\n14213\n14214\n14215\n14216\n14217\n14218\n14219\n14220\n14221\n14222\n14223\n14224\n14225\n14226\n14227\n14228\n14229\n14230\n14231\n14232\n14233\n14234\n14235\n14236\n14237\n14238\n14239\n14240\n14241\n14242\n14243\n14244\n14245\n14246\n14247\n14248\n14249\n14250\n14251\n14252\n14253\n14254\n14255\n14256\n14257\n14258\n14259\n14260\n14261\n14262\n14263\n14264\n14265\n14266\n14267\n14268\n14269\n14270\n14271\n14272\n14273\n14274\n14275\n14276\n14277\n14278\n14279\n14280\n14281\n14282\n14283\n14284\n14285\n14286\n14287\n14288\n14289\n14290\n14291\n14292\n14293\n14294\n14295\n14296\n14297\n14298\n14299\n14300\n14301\n14302\n14303\n14304\n14305\n14306\n14307\n14308\n14309\n14310\n14311\n14312\n14313\n14314\n14315\n14316\n14317\n14318\n14319\n14320\n14321\n14322\n14323\n14324\n14325\n14326\n14327\n14328\n14329\n14330\n14331\n14332\n14333\n14334\n14335\n14336\n14337\n14338\n14339\n14340\n14341\n14342\n14343\n14344\n14345\n14346\n14347\n14348\n14349\n14350\n14351\n14352\n14353\n14354\n14355\n14356\n14357\n14358\n14359\n14360\n14361\n14362\n14363\n14364\n14365\n14366\n14367\n14368\n14369\n14370\n14371\n14372\n14373\n14374\n14375\n14376\n14377\n14378\n14379\n14380\n14381\n14382\n14383\n14384\n14385\n14386\n14387\n14388\n14389\n14390\n14391\n14392\n14393\n14394\n14395\n14396\n14397\n14398\n14399\n14400\n14401\n14402\n14403\n14404\n14405\n14406\n14407\n14408\n14409\n14410\n14411\n14412\n14413\n14414\n14415\n14416\n14417\n14418\n14419\n14420\n14421\n14422\n14423\n14424\n14425\n14426\n14427\n14428\n14429\n14430\n14431\n14432\n14433\n14434\n14435\n14436\n14437\n14438\n14439\n14440\n14441\n14442\n14443\n14444\n14445\n14446\n14447\n14448\n14449\n14450\n14451\n14452\n14453\n14454\n14455\n14456\n14457\n14458\n14459\n14460\n14461\n14462\n14463\n14464\n14465\n14466\n14467\n14468\n14469\n14470\n14471\n14472\n14473\n14474\n14475\n14476\n14477\n14478\n14479\n14480\n14481\n14482\n14483\n14484\n14485\n14486\n14487\n14488\n14489\n14490\n14491\n14492\n14493\n14494\n14495\n14496\n14497\n14498\n14499\n14500\n14501\n14502\n14503\n14504\n14505\n14506\n14507\n14508\n14509\n14510\n14511\n14512\n14513\n14514\n14515\n14516\n14517\n14518\n14519\n14520\n14521\n14522\n14523\n14524\n14525\n14526\n14527\n14528\n14529\n14530\n14531\n14532\n14533\n14534\n14535\n14536\n14537\n14538\n14539\n14540\n14541\n14542\n14543\n14544\n14545\n14546\n14547\n14548\n14549\n14550\n14551\n14552\n14553\n14554\n14555\n14556\n14557\n14558\n14559\n14560\n14561\n14562\n14563\n14564\n14565\n14566\n14567\n14568\n14569\n14570\n14571\n14572\n14573\n14574\n14575\n14576\n14577\n14578\n14579\n14580\n14581\n14582\n14583\n14584\n14585\n14586\n14587\n14588\n14589\n14590\n14591\n14592\n14593\n14594\n14595\n14596\n14597\n14598\n14599\n14600\n14601\n14602\n14603\n14604\n14605\n14606\n14607\n14608\n14609\n14610\n14611\n14612\n14613\n14614\n14615\n14616\n14617\n14618\n14619\n14620\n14621\n14622\n14623\n14624\n14625\n14626\n14627\n14628\n14629\n14630\n14631\n14632\n14633\n14634\n14635\n14636\n14637\n14638\n14639\n14640\n14641\n14642\n14643\n14644\n14645\n14646\n14647\n14648\n14649\n14650\n14651\n14652\n14653\n14654\n14655\n14656\n14657\n14658\n14659\n14660\n14661\n14662\n14663\n14664\n14665\n14666\n14667\n14668\n14669\n14670\n14671\n14672\n14673\n14674\n14675\n14676\n14677\n14678\n14679\n14680\n14681\n14682\n14683\n14684\n14685\n14686\n14687\n14688\n14689\n14690\n14691\n14692\n14693\n14694\n14695\n14696\n14697\n14698\n14699\n14700\n14701\n14702\n14703\n14704\n14705\n14706\n14707\n14708\n14709\n14710\n14711\n14712\n14713\n14714\n14715\n14716\n14717\n14718\n14719\n14720\n14721\n14722\n14723\n14724\n14725\n14726\n14727\n14728\n14729\n14730\n14731\n14732\n14733\n14734\n14735\n14736\n14737\n14738\n14739\n14740\n14741\n14742\n14743\n14744\n14745\n14746\n14747\n14748\n14749\n14750\n14751\n14752\n14753\n14754\n14755\n14756\n14757\n14758\n14759\n14760\n14761\n14762\n14763\n14764\n14765\n14766\n14767\n14768\n14769\n14770\n14771\n14772\n14773\n14774\n14775\n14776\n14777\n14778\n14779\n14780\n14781\n14782\n14783\n14784\n14785\n14786\n14787\n14788\n14789\n14790\n14791\n14792\n14793\n14794\n14795\n14796\n14797\n14798\n14799\n14800\n14801\n14802\n14803\n14804\n14805\n14806\n14807\n14808\n14809\n14810\n14811\n14812\n14813\n14814\n14815\n14816\n14817\n14818\n14819\n14820\n14821\n14822\n14823\n14824\n14825\n14826\n14827\n14828\n14829\n14830\n14831\n14832\n14833\n14834\n14835\n14836\n14837\n14838\n14839\n14840\n14841\n14842\n14843\n14844\n14845\n14846\n14847\n14848\n14849\n14850\n14851\n14852\n14853\n14854\n14855\n14856\n14857\n14858\n14859\n14860\n14861\n14862\n14863\n14864\n14865\n14866\n14867\n14868\n14869\n14870\n14871\n14872\n14873\n14874\n14875\n14876\n14877\n14878\n14879\n14880\n14881\n14882\n14883\n14884\n14885\n14886\n14887\n14888\n14889\n14890\n14891\n14892\n14893\n14894\n14895\n14896\n14897\n14898\n14899\n14900\n14901\n14902\n14903\n14904\n14905\n14906\n14907\n14908\n14909\n14910\n14911\n14912\n14913\n14914\n14915\n14916\n14917\n14918\n14919\n14920\n14921\n14922\n14923\n14924\n14925\n14926\n14927\n14928\n14929\n14930\n14931\n14932\n14933\n14934\n14935\n14936\n14937\n14938\n14939\n14940\n14941\n14942\n14943\n14944\n14945\n14946\n14947\n14948\n14949\n14950\n14951\n14952\n14953\n14954\n14955\n14956\n14957\n14958\n14959\n14960\n14961\n14962\n14963\n14964\n14965\n14966\n14967\n14968\n14969\n14970\n14971\n14972\n14973\n14974\n14975\n14976\n14977\n14978\n14979\n14980\n14981\n14982\n14983\n14984\n14985\n14986\n14987\n14988\n14989\n14990\n14991\n14992\n14993\n14994\n14995\n14996\n14997\n14998\n14999\n15000\n15001\n15002\n15003\n15004\n15005\n15006\n15007\n15008\n15009\n15010\n15011\n15012\n15013\n15014\n15015\n15016\n15017\n15018\n15019\n15020\n15021\n15022\n15023\n15024\n15025\n15026\n15027\n15028\n15029\n15030\n15031\n15032\n15033\n15034\n15035\n15036\n15037\n15038\n15039\n15040\n15041\n15042\n15043\n15044\n15045\n15046\n15047\n15048\n15049\n15050\n15051\n15052\n15053\n15054\n15055\n15056\n15057\n15058\n15059\n15060\n15061\n15062\n15063\n15064\n15065\n15066\n15067\n15068\n15069\n15070\n15071\n15072\n15073\n15074\n15075\n15076\n15077\n15078\n15079\n15080\n15081\n15082\n15083\n15084\n15085\n15086\n15087\n15088\n15089\n15090\n15091\n15092\n15093\n15094\n15095\n15096\n15097\n15098\n15099\n15100\n15101\n15102\n15103\n15104\n15105\n15106\n15107\n15108\n15109\n15110\n15111\n15112\n15113\n15114\n15115\n15116\n15117\n15118\n15119\n15120\n15121\n15122\n15123\n15124\n15125\n15126\n15127\n15128\n15129\n15130\n15131\n15132\n15133\n15134\n15135\n15136\n15137\n15138\n15139\n15140\n15141\n15142\n15143\n15144\n15145\n15146\n15147\n15148\n15149\n15150\n15151\n15152\n15153\n15154\n15155\n15156\n15157\n15158\n15159\n15160\n15161\n15162\n15163\n15164\n15165\n15166\n15167\n15168\n15169\n15170\n15171\n15172\n15173\n15174\n15175\n15176\n15177\n15178\n15179\n15180\n15181\n15182\n15183\n15184\n15185\n15186\n15187\n15188\n15189\n15190\n15191\n15192\n15193\n15194\n15195\n15196\n15197\n15198\n15199\n15200\n15201\n15202\n15203\n15204\n15205\n15206\n15207\n15208\n15209\n15210\n15211\n15212\n15213\n15214\n15215\n15216\n15217\n15218\n15219\n15220\n15221\n15222\n15223\n15224\n15225\n15226\n15227\n15228\n15229\n15230\n15231\n15232\n15233\n15234\n15235\n15236\n15237\n15238\n15239\n15240\n15241\n15242\n15243\n15244\n15245\n15246\n15247\n15248\n15249\n15250\n15251\n15252\n15253\n15254\n15255\n15256\n15257\n15258\n15259\n15260\n15261\n15262\n15263\n15264\n15265\n15266\n15267\n15268\n15269\n15270\n15271\n15272\n15273\n15274\n15275\n15276\n15277\n15278\n15279\n15280\n15281\n15282\n15283\n15284\n15285\n15286\n15287\n15288\n15289\n15290\n15291\n15292\n15293\n15294\n15295\n15296\n15297\n15298\n15299\n15300\n15301\n15302\n15303\n15304\n15305\n15306\n15307\n15308\n15309\n15310\n15311\n15312\n15313\n15314\n15315\n15316\n15317\n15318\n15319\n15320\n15321\n15322\n15323\n15324\n15325\n15326\n15327\n15328\n15329\n15330\n15331\n15332\n15333\n15334\n15335\n15336\n15337\n15338\n15339\n15340\n15341\n15342\n15343\n15344\n15345\n15346\n15347\n15348\n15349\n15350\n15351\n15352\n15353\n15354\n15355\n15356\n15357\n15358\n15359\n15360\n15361\n15362\n15363\n15364\n15365\n15366\n15367\n15368\n15369\n15370\n15371\n15372\n15373\n15374\n15375\n15376\n15377\n15378\n15379\n15380\n15381\n15382\n15383\n15384\n15385\n15386\n15387\n15388\n15389\n15390\n15391\n15392\n15393\n15394\n15395\n15396\n15397\n15398\n15399\n15400\n15401\n15402\n15403\n15404\n15405\n15406\n15407\n15408\n15409\n15410\n15411\n15412\n15413\n15414\n15415\n15416\n15417\n15418\n15419\n15420\n15421\n15422\n15423\n15424\n15425\n15426\n15427\n15428\n15429\n15430\n15431\n15432\n15433\n15434\n15435\n15436\n15437\n15438\n15439\n15440\n15441\n15442\n15443\n15444\n15445\n15446\n15447\n15448\n15449\n15450\n15451\n15452\n15453\n15454\n15455\n15456\n15457\n15458\n15459\n15460\n15461\n15462\n15463\n15464\n15465\n15466\n15467\n15468\n15469\n15470\n15471\n15472\n15473\n15474\n15475\n15476\n15477\n15478\n15479\n15480\n15481\n15482\n15483\n15484\n15485\n15486\n15487\n15488\n15489\n15490\n15491\n15492\n15493\n15494\n15495\n15496\n15497\n15498\n15499\n15500\n15501\n15502\n15503\n15504\n15505\n15506\n15507\n15508\n15509\n15510\n15511\n15512\n15513\n15514\n15515\n15516\n15517\n15518\n15519\n15520\n15521\n15522\n15523\n15524\n15525\n15526\n15527\n15528\n15529\n15530\n15531\n15532\n15533\n15534\n15535\n15536\n15537\n15538\n15539\n15540\n15541\n15542\n15543\n15544\n15545\n15546\n15547\n15548\n15549\n15550\n15551\n15552\n15553\n15554\n15555\n15556\n15557\n15558\n15559\n15560\n15561\n15562\n15563\n15564\n15565\n15566\n15567\n15568\n15569\n15570\n15571\n15572\n15573\n15574\n15575\n15576\n15577\n15578\n15579\n15580\n15581\n15582\n15583\n15584\n15585\n15586\n15587\n15588\n15589\n15590\n15591\n15592\n15593\n15594\n15595\n15596\n15597\n15598\n15599\n15600\n15601\n15602\n15603\n15604\n15605\n15606\n15607\n15608\n15609\n15610\n15611\n15612\n15613\n15614\n15615\n15616\n15617\n15618\n15619\n15620\n15621\n15622\n15623\n15624\n15625\n15626\n15627\n15628\n15629\n15630\n15631\n15632\n15633\n15634\n15635\n15636\n15637\n15638\n15639\n15640\n15641\n15642\n15643\n15644\n15645\n15646\n15647\n15648\n15649\n15650\n15651\n15652\n15653\n15654\n15655\n15656\n15657\n15658\n15659\n15660\n15661\n15662\n15663\n15664\n15665\n15666\n15667\n15668\n15669\n15670\n15671\n15672\n15673\n15674\n15675\n15676\n15677\n15678\n15679\n15680\n15681\n15682\n15683\n15684\n15685\n15686\n15687\n15688\n15689\n15690\n15691\n15692\n15693\n15694\n15695\n15696\n15697\n15698\n15699\n15700\n15701\n15702\n15703\n15704\n15705\n15706\n15707\n15708\n15709\n15710\n15711\n15712\n15713\n15714\n15715\n15716\n15717\n15718\n15719\n15720\n15721\n15722\n15723\n15724\n15725\n15726\n15727\n15728\n15729\n15730\n15731\n15732\n15733\n15734\n15735\n15736\n15737\n15738\n15739\n15740\n15741\n15742\n15743\n15744\n15745\n15746\n15747\n15748\n15749\n15750\n15751\n15752\n15753\n15754\n15755\n15756\n15757\n15758\n15759\n15760\n15761\n15762\n15763\n15764\n15765\n15766\n15767\n15768\n15769\n15770\n15771\n15772\n15773\n15774\n15775\n15776\n15777\n15778\n15779\n15780\n15781\n15782\n15783\n15784\n15785\n15786\n15787\n15788\n15789\n15790\n15791\n15792\n15793\n15794\n15795\n15796\n15797\n15798\n15799\n15800\n15801\n15802\n15803\n15804\n15805\n15806\n15807\n15808\n15809\n15810\n15811\n15812\n15813\n15814\n15815\n15816\n15817\n15818\n15819\n15820\n15821\n15822\n15823\n15824\n15825\n15826\n15827\n15828\n15829\n15830\n15831\n15832\n15833\n15834\n15835\n15836\n15837\n15838\n15839\n15840\n15841\n15842\n15843\n15844\n15845\n15846\n15847\n15848\n15849\n15850\n15851\n15852\n15853\n15854\n15855\n15856\n15857\n15858\n15859\n15860\n15861\n15862\n15863\n15864\n15865\n15866\n15867\n15868\n15869\n15870\n15871\n15872\n15873\n15874\n15875\n15876\n15877\n15878\n15879\n15880\n15881\n15882\n15883\n15884\n15885\n15886\n15887\n15888\n15889\n15890\n15891\n15892\n15893\n15894\n15895\n15896\n15897\n15898\n15899\n15900\n15901\n15902\n15903\n15904\n15905\n15906\n15907\n15908\n15909\n15910\n15911\n15912\n15913\n15914\n15915\n15916\n15917\n15918\n15919\n15920\n15921\n15922\n15923\n15924\n15925\n15926\n15927\n15928\n15929\n15930\n15931\n15932\n15933\n15934\n15935\n15936\n15937\n15938\n15939\n15940\n15941\n15942\n15943\n15944\n15945\n15946\n15947\n15948\n15949\n15950\n15951\n15952\n15953\n15954\n15955\n15956\n15957\n15958\n15959\n15960\n15961\n15962\n15963\n15964\n15965\n15966\n15967\n15968\n15969\n15970\n15971\n15972\n15973\n15974\n15975\n15976\n15977\n15978\n15979\n15980\n15981\n15982\n15983\n15984\n15985\n15986\n15987\n15988\n15989\n15990\n15991\n15992\n15993\n15994\n15995\n15996\n15997\n15998\n15999\n16000\n16001\n16002\n16003\n16004\n16005\n16006\n16007\n16008\n16009\n16010\n16011\n16012\n16013\n16014\n16015\n16016\n16017\n16018\n16019\n16020\n16021\n16022\n16023\n16024\n16025\n16026\n16027\n16028\n16029\n16030\n16031\n16032\n16033\n16034\n16035\n16036\n16037\n16038\n16039\n16040\n16041\n16042\n16043\n16044\n16045\n16046\n16047\n16048\n16049\n16050\n16051\n16052\n16053\n16054\n16055\n16056\n16057\n16058\n16059\n16060\n16061\n16062\n16063\n16064\n16065\n16066\n16067\n16068\n16069\n16070\n16071\n16072\n16073\n16074\n16075\n16076\n16077\n16078\n16079\n16080\n16081\n16082\n16083\n16084\n16085\n16086\n16087\n16088\n16089\n16090\n16091\n16092\n16093\n16094\n16095\n16096\n16097\n16098\n16099\n16100\n16101\n16102\n16103\n16104\n16105\n16106\n16107\n16108\n16109\n16110\n16111\n16112\n16113\n16114\n16115\n16116\n16117\n16118\n16119\n16120\n16121\n16122\n16123\n16124\n16125\n16126\n16127\n16128\n16129\n16130\n16131\n16132\n16133\n16134\n16135\n16136\n16137\n16138\n16139\n16140\n16141\n16142\n16143\n16144\n16145\n16146\n16147\n16148\n16149\n16150\n16151\n16152\n16153\n16154\n16155\n16156\n16157\n16158\n16159\n16160\n16161\n16162\n16163\n16164\n16165\n16166\n16167\n16168\n16169\n16170\n16171\n16172\n16173\n16174\n16175\n16176\n16177\n16178\n16179\n16180\n16181\n16182\n16183\n16184\n16185\n16186\n16187\n16188\n16189\n16190\n16191\n16192\n16193\n16194\n16195\n16196\n16197\n16198\n16199\n16200\n16201\n16202\n16203\n16204\n16205\n16206\n16207\n16208\n16209\n16210\n16211\n16212\n16213\n16214\n16215\n16216\n16217\n16218\n16219\n16220\n16221\n16222\n16223\n16224\n16225\n16226\n16227\n16228\n16229\n16230\n16231\n16232\n16233\n16234\n16235\n16236\n16237\n16238\n16239\n16240\n16241\n16242\n16243\n16244\n16245\n16246\n16247\n16248\n16249\n16250\n16251\n16252\n16253\n16254\n16255\n16256\n16257\n16258\n16259\n16260\n16261\n16262\n16263\n16264\n16265\n16266\n16267\n16268\n16269\n16270\n16271\n16272\n16273\n16274\n16275\n16276\n16277\n16278\n16279\n16280\n16281\n16282\n16283\n16284\n16285\n16286\n16287\n16288\n16289\n16290\n16291\n16292\n16293\n16294\n16295\n16296\n16297\n16298\n16299\n16300\n16301\n16302\n16303\n16304\n16305\n16306\n16307\n16308\n16309\n16310\n16311\n16312\n16313\n16314\n16315\n16316\n16317\n16318\n16319\n16320\n16321\n16322\n16323\n16324\n16325\n16326\n16327\n16328\n16329\n16330\n16331\n16332\n16333\n16334\n16335\n16336\n16337\n16338\n16339\n16340\n16341\n16342\n16343\n16344\n16345\n16346\n16347\n16348\n16349\n16350\n16351\n16352\n16353\n16354\n16355\n16356\n16357\n16358\n16359\n16360\n16361\n16362\n16363\n16364\n16365\n16366\n16367\n16368\n16369\n16370\n16371\n16372\n16373\n16374\n16375\n16376\n16377\n16378\n16379\n16380\n16381\n16382\n16383\n16384\n16385\n16386\n16387\n16388\n16389\n16390\n16391\n16392\n16393\n16394\n16395\n16396\n16397\n16398\n16399\n16400\n16401\n16402\n16403\n16404\n16405\n16406\n16407\n16408\n16409\n16410\n16411\n16412\n16413\n16414\n16415\n16416\n16417\n16418\n16419\n16420\n16421\n16422\n16423\n16424\n16425\n16426\n16427\n16428\n16429\n16430\n16431\n16432\n16433\n16434\n16435\n16436\n16437\n16438\n16439\n16440\n16441\n16442\n16443\n16444\n16445\n16446\n16447\n16448\n16449\n16450\n16451\n16452\n16453\n16454\n16455\n16456\n16457\n16458\n16459\n16460\n16461\n16462\n16463\n16464\n16465\n16466\n16467\n16468\n16469\n16470\n16471\n16472\n16473\n16474\n16475\n16476\n16477\n16478\n16479\n16480\n16481\n16482\n16483\n16484\n16485\n16486\n16487\n16488\n16489\n16490\n16491\n16492\n16493\n16494\n16495\n16496\n16497\n16498\n16499\n16500\n16501\n16502\n16503\n16504\n16505\n16506\n16507\n16508\n16509\n16510\n16511\n16512\n16513\n16514\n16515\n16516\n16517\n16518\n16519\n16520\n16521\n16522\n16523\n16524\n16525\n16526\n16527\n16528\n16529\n16530\n16531\n16532\n16533\n16534\n16535\n16536\n16537\n16538\n16539\n16540\n16541\n16542\n16543\n16544\n16545\n16546\n16547\n16548\n16549\n16550\n16551\n16552\n16553\n16554\n16555\n16556\n16557\n16558\n16559\n16560\n16561\n16562\n16563\n16564\n16565\n16566\n16567\n16568\n16569\n16570\n16571\n16572\n16573\n16574\n16575\n16576\n16577\n16578\n16579\n16580\n16581\n16582\n16583\n16584\n16585\n16586\n16587\n16588\n16589\n16590\n16591\n16592\n16593\n16594\n16595\n16596\n16597\n16598\n16599\n16600\n16601\n16602\n16603\n16604\n16605\n16606\n16607\n16608\n16609\n16610\n16611\n16612\n16613\n16614\n16615\n16616\n16617\n16618\n16619\n16620\n16621\n16622\n16623\n16624\n16625\n16626\n16627\n16628\n16629\n16630\n16631\n16632\n16633\n16634\n16635\n16636\n16637\n16638\n16639\n16640\n16641\n16642\n16643\n16644\n16645\n16646\n16647\n16648\n16649\n16650\n16651\n16652\n16653\n16654\n16655\n16656\n16657\n16658\n16659\n16660\n16661\n16662\n16663\n16664\n16665\n16666\n16667\n16668\n16669\n16670\n16671\n16672\n16673\n16674\n16675\n16676\n16677\n16678\n16679\n16680\n16681\n16682\n16683\n16684\n16685\n16686\n16687\n16688\n16689\n16690\n16691\n16692\n16693\n16694\n16695\n16696\n16697\n16698\n16699\n16700\n16701\n16702\n16703\n16704\n16705\n16706\n16707\n16708\n16709\n16710\n16711\n16712\n16713\n16714\n16715\n16716\n16717\n16718\n16719\n16720\n16721\n16722\n16723\n16724\n16725\n16726\n16727\n16728\n16729\n16730\n16731\n16732\n16733\n16734\n16735\n16736\n16737\n16738\n16739\n16740\n16741\n16742\n16743\n16744\n16745\n16746\n16747\n16748\n16749\n16750\n16751\n16752\n16753\n16754\n16755\n16756\n16757\n16758\n16759\n16760\n16761\n16762\n16763\n16764\n16765\n16766\n16767\n16768\n16769\n16770\n16771\n16772\n16773\n16774\n16775\n16776\n16777\n16778\n16779\n16780\n16781\n16782\n16783\n16784\n16785\n16786\n16787\n16788\n16789\n16790\n16791\n16792\n16793\n16794\n16795\n16796\n16797\n16798\n16799\n16800\n16801\n16802\n16803\n16804\n16805\n16806\n16807\n16808\n16809\n16810\n16811\n16812\n16813\n16814\n16815\n16816\n16817\n16818\n16819\n16820\n16821\n16822\n16823\n16824\n16825\n16826\n16827\n16828\n16829\n16830\n16831\n16832\n16833\n16834\n16835\n16836\n16837\n16838\n16839\n16840\n16841\n16842\n16843\n16844\n16845\n16846\n16847\n16848\n16849\n16850\n16851\n16852\n16853\n16854\n16855\n16856\n16857\n16858\n16859\n16860\n16861\n16862\n16863\n16864\n16865\n16866\n16867\n16868\n16869\n16870\n16871\n16872\n16873\n16874\n16875\n16876\n16877\n16878\n16879\n16880\n16881\n16882\n16883\n16884\n16885\n16886\n16887\n16888\n16889\n16890\n16891\n16892\n16893\n16894\n16895\n16896\n16897\n16898\n16899\n16900\n16901\n16902\n16903\n16904\n16905\n16906\n16907\n16908\n16909\n16910\n16911\n16912\n16913\n16914\n16915\n16916\n16917\n16918\n16919\n16920\n16921\n16922\n16923\n16924\n16925\n16926\n16927\n16928\n16929\n16930\n16931\n16932\n16933\n16934\n16935\n16936\n16937\n16938\n16939\n16940\n16941\n16942\n16943\n16944\n16945\n16946\n16947\n16948\n16949\n16950\n16951\n16952\n16953\n16954\n16955\n16956\n16957\n16958\n16959\n16960\n16961\n16962\n16963\n16964\n16965\n16966\n16967\n16968\n16969\n16970\n16971\n16972\n16973\n16974\n16975\n16976\n16977\n16978\n16979\n16980\n16981\n16982\n16983\n16984\n16985\n16986\n16987\n16988\n16989\n16990\n16991\n16992\n16993\n16994\n16995\n16996\n16997\n16998\n16999\n17000\n17001\n17002\n17003\n17004\n17005\n17006\n17007\n17008\n17009\n17010\n17011\n17012\n17013\n17014\n17015\n17016\n17017\n17018\n17019\n17020\n17021\n17022\n17023\n17024\n17025\n17026\n17027\n17028\n17029\n17030\n17031\n17032\n17033\n17034\n17035\n17036\n17037\n17038\n17039\n17040\n17041\n17042\n17043\n17044\n17045\n17046\n17047\n17048\n17049\n17050\n17051\n17052\n17053\n17054\n17055\n17056\n17057\n17058\n17059\n17060\n17061\n17062\n17063\n17064\n17065\n17066\n17067\n17068\n17069\n17070\n17071\n17072\n17073\n17074\n17075\n17076\n17077\n17078\n17079\n17080\n17081\n17082\n17083\n17084\n17085\n17086\n17087\n17088\n17089\n17090\n17091\n17092\n17093\n17094\n17095\n17096\n17097\n17098\n17099\n17100\n17101\n17102\n17103\n17104\n17105\n17106\n17107\n17108\n17109\n17110\n17111\n17112\n17113\n17114\n17115\n17116\n17117\n17118\n17119\n17120\n17121\n17122\n17123\n17124\n17125\n17126\n17127\n17128\n17129\n17130\n17131\n17132\n17133\n17134\n17135\n17136\n17137\n17138\n17139\n17140\n17141\n17142\n17143\n17144\n17145\n17146\n17147\n17148\n17149\n17150\n17151\n17152\n17153\n17154\n17155\n17156\n17157\n17158\n17159\n17160\n17161\n17162\n17163\n17164\n17165\n17166\n17167\n17168\n17169\n17170\n17171\n17172\n17173\n17174\n17175\n17176\n17177\n17178\n17179\n17180\n17181\n17182\n17183\n17184\n17185\n17186\n17187\n17188\n17189\n17190\n17191\n17192\n17193\n17194\n17195\n17196\n17197\n17198\n17199\n17200\n17201\n17202\n17203\n17204\n17205\n17206\n17207\n17208\n17209\n17210\n17211\n17212\n17213\n17214\n17215\n17216\n17217\n17218\n17219\n17220\n17221\n17222\n17223\n17224\n17225\n17226\n17227\n17228\n17229\n17230\n17231\n17232\n17233\n17234\n17235\n17236\n17237\n17238\n17239\n17240\n17241\n17242\n17243\n17244\n17245\n17246\n17247\n17248\n17249\n17250\n17251\n17252\n17253\n17254\n17255\n17256\n17257\n17258\n17259\n17260\n17261\n17262\n17263\n17264\n17265\n17266\n17267\n17268\n17269\n17270\n17271\n17272\n17273\n17274\n17275\n17276\n17277\n17278\n17279\n17280\n17281\n17282\n17283\n17284\n17285\n17286\n17287\n17288\n17289\n17290\n17291\n17292\n17293\n17294\n17295\n17296\n17297\n17298\n17299\n17300\n17301\n17302\n17303\n17304\n17305\n17306\n17307\n17308\n17309\n17310\n17311\n17312\n17313\n17314\n17315\n17316\n17317\n17318\n17319\n17320\n17321\n17322\n17323\n17324\n17325\n17326\n17327\n17328\n17329\n17330\n17331\n17332\n17333\n17334\n17335\n17336\n17337\n17338\n17339\n17340\n17341\n17342\n17343\n17344\n17345\n17346\n17347\n17348\n17349\n17350\n17351\n17352\n17353\n17354\n17355\n17356\n17357\n17358\n17359\n17360\n17361\n17362\n17363\n17364\n17365\n17366\n17367\n17368\n17369\n17370\n17371\n17372\n17373\n17374\n17375\n17376\n17377\n17378\n17379\n17380\n17381\n17382\n17383\n17384\n17385\n17386\n17387\n17388\n17389\n17390\n17391\n17392\n17393\n17394\n17395\n17396\n17397\n17398\n17399\n17400\n17401\n17402\n17403\n17404\n17405\n17406\n17407\n17408\n17409\n17410\n17411\n17412\n17413\n17414\n17415\n17416\n17417\n17418\n17419\n17420\n17421\n17422\n17423\n17424\n17425\n17426\n17427\n17428\n17429\n17430\n17431\n17432\n17433\n17434\n17435\n17436\n17437\n17438\n17439\n17440\n17441\n17442\n17443\n17444\n17445\n17446\n17447\n17448\n17449\n17450\n17451\n17452\n17453\n17454\n17455\n17456\n17457\n17458\n17459\n17460\n17461\n17462\n17463\n17464\n17465\n17466\n17467\n17468\n17469\n17470\n17471\n17472\n17473\n17474\n17475\n17476\n17477\n17478\n17479\n17480\n17481\n17482\n17483\n17484\n17485\n17486\n17487\n17488\n17489\n17490\n17491\n17492\n17493\n17494\n17495\n17496\n17497\n17498\n17499\n17500\n17501\n17502\n17503\n17504\n17505\n17506\n17507\n17508\n17509\n17510\n17511\n17512\n17513\n17514\n17515\n17516\n17517\n17518\n17519\n17520\n17521\n17522\n17523\n17524\n17525\n17526\n17527\n17528\n17529\n17530\n17531\n17532\n17533\n17534\n17535\n17536\n17537\n17538\n17539\n17540\n17541\n17542\n17543\n17544\n17545\n17546\n17547\n17548\n17549\n17550\n17551\n17552\n17553\n17554\n17555\n17556\n17557\n17558\n17559\n17560\n17561\n17562\n17563\n17564\n17565\n17566\n17567\n17568\n17569\n17570\n17571\n17572\n17573\n17574\n17575\n17576\n17577\n17578\n17579\n17580\n17581\n17582\n17583\n17584\n17585\n17586\n17587\n17588\n17589\n17590\n17591\n17592\n17593\n17594\n17595\n17596\n17597\n17598\n17599\n17600\n17601\n17602\n17603\n17604\n17605\n17606\n17607\n17608\n17609\n17610\n17611\n17612\n17613\n17614\n17615\n17616\n17617\n17618\n17619\n17620\n17621\n17622\n17623\n17624\n17625\n17626\n17627\n17628\n17629\n17630\n17631\n17632\n17633\n17634\n17635\n17636\n17637\n17638\n17639\n17640\n17641\n17642\n17643\n17644\n17645\n17646\n17647\n17648\n17649\n17650\n17651\n17652\n17653\n17654\n17655\n17656\n17657\n17658\n17659\n17660\n17661\n17662\n17663\n17664\n17665\n17666\n17667\n17668\n17669\n17670\n17671\n17672\n17673\n17674\n17675\n17676\n17677\n17678\n17679\n17680\n17681\n17682\n17683\n17684\n17685\n17686\n17687\n17688\n17689\n17690\n17691\n17692\n17693\n17694\n17695\n17696\n17697\n17698\n17699\n17700\n17701\n17702\n17703\n17704\n17705\n17706\n17707\n17708\n17709\n17710\n17711\n17712\n17713\n17714\n17715\n17716\n17717\n17718\n17719\n17720\n17721\n17722\n17723\n17724\n17725\n17726\n17727\n17728\n17729\n17730\n17731\n17732\n17733\n17734\n17735\n17736\n17737\n17738\n17739\n17740\n17741\n17742\n17743\n17744\n17745\n17746\n17747\n17748\n17749\n17750\n17751\n17752\n17753\n17754\n17755\n17756\n17757\n17758\n17759\n17760\n17761\n17762\n17763\n17764\n17765\n17766\n17767\n17768\n17769\n17770\n17771\n17772\n17773\n17774\n17775\n17776\n17777\n17778\n17779\n17780\n17781\n17782\n17783\n17784\n17785\n17786\n17787\n17788\n17789\n17790\n17791\n17792\n17793\n17794\n17795\n17796\n17797\n17798\n17799\n17800\n17801\n17802\n17803\n17804\n17805\n17806\n17807\n17808\n17809\n17810\n17811\n17812\n17813\n17814\n17815\n17816\n17817\n17818\n17819\n17820\n17821\n17822\n17823\n17824\n17825\n17826\n17827\n17828\n17829\n17830\n17831\n17832\n17833\n17834\n17835\n17836\n17837\n17838\n17839\n17840\n17841\n17842\n17843\n17844\n17845\n17846\n17847\n17848\n17849\n17850\n17851\n17852\n17853\n17854\n17855\n17856\n17857\n17858\n17859\n17860\n17861\n17862\n17863\n17864\n17865\n17866\n17867\n17868\n17869\n17870\n17871\n17872\n17873\n17874\n17875\n17876\n17877\n17878\n17879\n17880\n17881\n17882\n17883\n17884\n17885\n17886\n17887\n17888\n17889\n17890\n17891\n17892\n17893\n17894\n17895\n17896\n17897\n17898\n17899\n17900\n17901\n17902\n17903\n17904\n17905\n17906\n17907\n17908\n17909\n17910\n17911\n17912\n17913\n17914\n17915\n17916\n17917\n17918\n17919\n17920\n17921\n17922\n17923\n17924\n17925\n17926\n17927\n17928\n17929\n17930\n17931\n17932\n17933\n17934\n17935\n17936\n17937\n17938\n17939\n17940\n17941\n17942\n17943\n17944\n17945\n17946\n17947\n17948\n17949\n17950\n17951\n17952\n17953\n17954\n17955\n17956\n17957\n17958\n17959\n17960\n17961\n17962\n17963\n17964\n17965\n17966\n17967\n17968\n17969\n17970\n17971\n17972\n17973\n17974\n17975\n17976\n17977\n17978\n17979\n17980\n17981\n17982\n17983\n17984\n17985\n17986\n17987\n17988\n17989\n17990\n17991\n17992\n17993\n17994\n17995\n17996\n17997\n17998\n17999\n18000\n18001\n18002\n18003\n18004\n18005\n18006\n18007\n18008\n18009\n18010\n18011\n18012\n18013\n18014\n18015\n18016\n18017\n18018\n18019\n18020\n18021\n18022\n18023\n18024\n18025\n18026\n18027\n18028\n18029\n18030\n18031\n18032\n18033\n18034\n18035\n18036\n18037\n18038\n18039\n18040\n18041\n18042\n18043\n18044\n18045\n18046\n18047\n18048\n18049\n18050\n18051\n18052\n18053\n18054\n18055\n18056\n18057\n18058\n18059\n18060\n18061\n18062\n18063\n18064\n18065\n18066\n18067\n18068\n18069\n18070\n18071\n18072\n18073\n18074\n18075\n18076\n18077\n18078\n18079\n18080\n18081\n18082\n18083\n18084\n18085\n18086\n18087\n18088\n18089\n18090\n18091\n18092\n18093\n18094\n18095\n18096\n18097\n18098\n18099\n18100\n18101\n18102\n18103\n18104\n18105\n18106\n18107\n18108\n18109\n18110\n18111\n18112\n18113\n18114\n18115\n18116\n18117\n18118\n18119\n18120\n18121\n18122\n18123\n18124\n18125\n18126\n18127\n18128\n18129\n18130\n18131\n18132\n18133\n18134\n18135\n18136\n18137\n18138\n18139\n18140\n18141\n18142\n18143\n18144\n18145\n18146\n18147\n18148\n18149\n18150\n18151\n18152\n18153\n18154\n18155\n18156\n18157\n18158\n18159\n18160\n18161\n18162\n18163\n18164\n18165\n18166\n18167\n18168\n18169\n18170\n18171\n18172\n18173\n18174\n18175\n18176\n18177\n18178\n18179\n18180\n18181\n18182\n18183\n18184\n18185\n18186\n18187\n18188\n18189\n18190\n18191\n18192\n18193\n18194\n18195\n18196\n18197\n18198\n18199\n18200\n18201\n18202\n18203\n18204\n18205\n18206\n18207\n18208\n18209\n18210\n18211\n18212\n18213\n18214\n18215\n18216\n18217\n18218\n18219\n18220\n18221\n18222\n18223\n18224\n18225\n18226\n18227\n18228\n18229\n18230\n18231\n18232\n18233\n18234\n18235\n18236\n18237\n18238\n18239\n18240\n18241\n18242\n18243\n18244\n18245\n18246\n18247\n18248\n18249\n18250\n18251\n18252\n18253\n18254\n18255\n18256\n18257\n18258\n18259\n18260\n18261\n18262\n18263\n18264\n18265\n18266\n18267\n18268\n18269\n18270\n18271\n18272\n18273\n18274\n18275\n18276\n18277\n18278\n18279\n18280\n18281\n18282\n18283\n18284\n18285\n18286\n18287\n18288\n18289\n18290\n18291\n18292\n18293\n18294\n18295\n18296\n18297\n18298\n18299\n18300\n18301\n18302\n18303\n18304\n18305\n18306\n18307\n18308\n18309\n18310\n18311\n18312\n18313\n18314\n18315\n18316\n18317\n18318\n18319\n18320\n18321\n18322\n18323\n18324\n18325\n18326\n18327\n18328\n18329\n18330\n18331\n18332\n18333\n18334\n18335\n18336\n18337\n18338\n18339\n18340\n18341\n18342\n18343\n18344\n18345\n18346\n18347\n18348\n18349\n18350\n18351\n18352\n18353\n18354\n18355\n18356\n18357\n18358\n18359\n18360\n18361\n18362\n18363\n18364\n18365\n18366\n18367\n18368\n18369\n18370\n18371\n18372\n18373\n18374\n18375\n18376\n18377\n18378\n18379\n18380\n18381\n18382\n18383\n18384\n18385\n18386\n18387\n18388\n18389\n18390\n18391\n18392\n18393\n18394\n18395\n18396\n18397\n18398\n18399\n18400\n18401\n18402\n18403\n18404\n18405\n18406\n18407\n18408\n18409\n18410\n18411\n18412\n18413\n18414\n18415\n18416\n18417\n18418\n18419\n18420\n18421\n18422\n18423\n18424\n18425\n18426\n18427\n18428\n18429\n18430\n18431\n18432\n18433\n18434\n18435\n18436\n18437\n18438\n18439\n18440\n18441\n18442\n18443\n18444\n18445\n18446\n18447\n18448\n18449\n18450\n18451\n18452\n18453\n18454\n18455\n18456\n18457\n18458\n18459\n18460\n18461\n18462\n18463\n18464\n18465\n18466\n18467\n18468\n18469\n18470\n18471\n18472\n18473\n18474\n18475\n18476\n18477\n18478\n18479\n18480\n18481\n18482\n18483\n18484\n18485\n18486\n18487\n18488\n18489\n18490\n18491\n18492\n18493\n18494\n18495\n18496\n18497\n18498\n18499\n18500\n18501\n18502\n18503\n18504\n18505\n18506\n18507\n18508\n18509\n18510\n18511\n18512\n18513\n18514\n18515\n18516\n18517\n18518\n18519\n18520\n18521\n18522\n18523\n18524\n18525\n18526\n18527\n18528\n18529\n18530\n18531\n18532\n18533\n18534\n18535\n18536\n18537\n18538\n18539\n18540\n18541\n18542\n18543\n18544\n18545\n18546\n18547\n18548\n18549\n18550\n18551\n18552\n18553\n18554\n18555\n18556\n18557\n18558\n18559\n18560\n18561\n18562\n18563\n18564\n18565\n18566\n18567\n18568\n18569\n18570\n18571\n18572\n18573\n18574\n18575\n18576\n18577\n18578\n18579\n18580\n18581\n18582\n18583\n18584\n18585\n18586\n18587\n18588\n18589\n18590\n18591\n18592\n18593\n18594\n18595\n18596\n18597\n18598\n18599\n18600\n18601\n18602\n18603\n18604\n18605\n18606\n18607\n18608\n18609\n18610\n18611\n18612\n18613\n18614\n18615\n18616\n18617\n18618\n18619\n18620\n18621\n18622\n18623\n18624\n18625\n18626\n18627\n18628\n18629\n18630\n18631\n18632\n18633\n18634\n18635\n18636\n18637\n18638\n18639\n18640\n18641\n18642\n18643\n18644\n18645\n18646\n18647\n18648\n18649\n18650\n18651\n18652\n18653\n18654\n18655\n18656\n18657\n18658\n18659\n18660\n18661\n18662\n18663\n18664\n18665\n18666\n18667\n18668\n18669\n18670\n18671\n18672\n18673\n18674\n18675\n18676\n18677\n18678\n18679\n18680\n18681\n18682\n18683\n18684\n18685\n18686\n18687\n18688\n18689\n18690\n18691\n18692\n18693\n18694\n18695\n18696\n18697\n18698\n18699\n18700\n18701\n18702\n18703\n18704\n18705\n18706\n18707\n18708\n18709\n18710\n18711\n18712\n18713\n18714\n18715\n18716\n18717\n18718\n18719\n18720\n18721\n18722\n18723\n18724\n18725\n18726\n18727\n18728\n18729\n18730\n18731\n18732\n18733\n18734\n18735\n18736\n18737\n18738\n18739\n18740\n18741\n18742\n18743\n18744\n18745\n18746\n18747\n18748\n18749\n18750\n18751\n18752\n18753\n18754\n18755\n18756\n18757\n18758\n18759\n18760\n18761\n18762\n18763\n18764\n18765\n18766\n18767\n18768\n18769\n18770\n18771\n18772\n18773\n18774\n18775\n18776\n18777\n18778\n18779\n18780\n18781\n18782\n18783\n18784\n18785\n18786\n18787\n18788\n18789\n18790\n18791\n18792\n18793\n18794\n18795\n18796\n18797\n18798\n18799\n18800\n18801\n18802\n18803\n18804\n18805\n18806\n18807\n18808\n18809\n18810\n18811\n18812\n18813\n18814\n18815\n18816\n18817\n18818\n18819\n18820\n18821\n18822\n18823\n18824\n18825\n18826\n18827\n18828\n18829\n18830\n18831\n18832\n18833\n18834\n18835\n18836\n18837\n18838\n18839\n18840\n18841\n18842\n18843\n18844\n18845\n18846\n18847\n18848\n18849\n18850\n18851\n18852\n18853\n18854\n18855\n18856\n18857\n18858\n18859\n18860\n18861\n18862\n18863\n18864\n18865\n18866\n18867\n18868\n18869\n18870\n18871\n18872\n18873\n18874\n18875\n18876\n18877\n18878\n18879\n18880\n18881\n18882\n18883\n18884\n18885\n18886\n18887\n18888\n18889\n18890\n18891\n18892\n18893\n18894\n18895\n18896\n18897\n18898\n18899\n18900\n18901\n18902\n18903\n18904\n18905\n18906\n18907\n18908\n18909\n18910\n18911\n18912\n18913\n18914\n18915\n18916\n18917\n18918\n18919\n18920\n18921\n18922\n18923\n18924\n18925\n18926\n18927\n18928\n18929\n18930\n18931\n18932\n18933\n18934\n18935\n18936\n18937\n18938\n18939\n18940\n18941\n18942\n18943\n18944\n18945\n18946\n18947\n18948\n18949\n18950\n18951\n18952\n18953\n18954\n18955\n18956\n18957\n18958\n18959\n18960\n18961\n18962\n18963\n18964\n18965\n18966\n18967\n18968\n18969\n18970\n18971\n18972\n18973\n18974\n18975\n18976\n18977\n18978\n18979\n18980\n18981\n18982\n18983\n18984\n18985\n18986\n18987\n18988\n18989\n18990\n18991\n18992\n18993\n18994\n18995\n18996\n18997\n18998\n18999\n19000\n19001\n19002\n19003\n19004\n19005\n19006\n19007\n19008\n19009\n19010\n19011\n19012\n19013\n19014\n19015\n19016\n19017\n19018\n19019\n19020\n19021\n19022\n19023\n19024\n19025\n19026\n19027\n19028\n19029\n19030\n19031\n19032\n19033\n19034\n19035\n19036\n19037\n19038\n19039\n19040\n19041\n19042\n19043\n19044\n19045\n19046\n19047\n19048\n19049\n19050\n19051\n19052\n19053\n19054\n19055\n19056\n19057\n19058\n19059\n19060\n19061\n19062\n19063\n19064\n19065\n19066\n19067\n19068\n19069\n19070\n19071\n19072\n19073\n19074\n19075\n19076\n19077\n19078\n19079\n19080\n19081\n19082\n19083\n19084\n19085\n19086\n19087\n19088\n19089\n19090\n19091\n19092\n19093\n19094\n19095\n19096\n19097\n19098\n19099\n19100\n19101\n19102\n19103\n19104\n19105\n19106\n19107\n19108\n19109\n19110\n19111\n19112\n19113\n19114\n19115\n19116\n19117\n19118\n19119\n19120\n19121\n19122\n19123\n19124\n19125\n19126\n19127\n19128\n19129\n19130\n19131\n19132\n19133\n19134\n19135\n19136\n19137\n19138\n19139\n19140\n19141\n19142\n19143\n19144\n19145\n19146\n19147\n19148\n19149\n19150\n19151\n19152\n19153\n19154\n19155\n19156\n19157\n19158\n19159\n19160\n19161\n19162\n19163\n19164\n19165\n19166\n19167\n19168\n19169\n19170\n19171\n19172\n19173\n19174\n19175\n19176\n19177\n19178\n19179\n19180\n19181\n19182\n19183\n19184\n19185\n19186\n19187\n19188\n19189\n19190\n19191\n19192\n19193\n19194\n19195\n19196\n19197\n19198\n19199\n19200\n19201\n19202\n19203\n19204\n19205\n19206\n19207\n19208\n19209\n19210\n19211\n19212\n19213\n19214\n19215\n19216\n19217\n19218\n19219\n19220\n19221\n19222\n19223\n19224\n19225\n19226\n19227\n19228\n19229\n19230\n19231\n19232\n19233\n19234\n19235\n19236\n19237\n19238\n19239\n19240\n19241\n19242\n19243\n19244\n19245\n19246\n19247\n19248\n19249\n19250\n19251\n19252\n19253\n19254\n19255\n19256\n19257\n19258\n19259\n19260\n19261\n19262\n19263\n19264\n19265\n19266\n19267\n19268\n19269\n19270\n19271\n19272\n19273\n19274\n19275\n19276\n19277\n19278\n19279\n19280\n19281\n19282\n19283\n19284\n19285\n19286\n19287\n19288\n19289\n19290\n19291\n19292\n19293\n19294\n19295\n19296\n19297\n19298\n19299\n19300\n19301\n19302\n19303\n19304\n19305\n19306\n19307\n19308\n19309\n19310\n19311\n19312\n19313\n19314\n19315\n19316\n19317\n19318\n19319\n19320\n19321\n19322\n19323\n19324\n19325\n19326\n19327\n19328\n19329\n19330\n19331\n19332\n19333\n19334\n19335\n19336\n19337\n19338\n19339\n19340\n19341\n19342\n19343\n19344\n19345\n19346\n19347\n19348\n19349\n19350\n19351\n19352\n19353\n19354\n19355\n19356\n19357\n19358\n19359\n19360\n19361\n19362\n19363\n19364\n19365\n19366\n19367\n19368\n19369\n19370\n19371\n19372\n19373\n19374\n19375\n19376\n19377\n19378\n19379\n19380\n19381\n19382\n19383\n19384\n19385\n19386\n19387\n19388\n19389\n19390\n19391\n19392\n19393\n19394\n19395\n19396\n19397\n19398\n19399\n19400\n19401\n19402\n19403\n19404\n19405\n19406\n19407\n19408\n19409\n19410\n19411\n19412\n19413\n19414\n19415\n19416\n19417\n19418\n19419\n19420\n19421\n19422\n19423\n19424\n19425\n19426\n19427\n19428\n19429\n19430\n19431\n19432\n19433\n19434\n19435\n19436\n19437\n19438\n19439\n19440\n19441\n19442\n19443\n19444\n19445\n19446\n19447\n19448\n19449\n19450\n19451\n19452\n19453\n19454\n19455\n19456\n19457\n19458\n19459\n19460\n19461\n19462\n19463\n19464\n19465\n19466\n19467\n19468\n19469\n19470\n19471\n19472\n19473\n19474\n19475\n19476\n19477\n19478\n19479\n19480\n19481\n19482\n19483\n19484\n19485\n19486\n19487\n19488\n19489\n19490\n19491\n19492\n19493\n19494\n19495\n19496\n19497\n19498\n19499\n19500\n19501\n19502\n19503\n19504\n19505\n19506\n19507\n19508\n19509\n19510\n19511\n19512\n19513\n19514\n19515\n19516\n19517\n19518\n19519\n19520\n19521\n19522\n19523\n19524\n19525\n19526\n19527\n19528\n19529\n19530\n19531\n19532\n19533\n19534\n19535\n19536\n19537\n19538\n19539\n19540\n19541\n19542\n19543\n19544\n19545\n19546\n19547\n19548\n19549\n19550\n19551\n19552\n19553\n19554\n19555\n19556\n19557\n19558\n19559\n19560\n19561\n19562\n19563\n19564\n19565\n19566\n19567\n19568\n19569\n19570\n19571\n19572\n19573\n19574\n19575\n19576\n19577\n19578\n19579\n19580\n19581\n19582\n19583\n19584\n19585\n19586\n19587\n19588\n19589\n19590\n19591\n19592\n19593\n19594\n19595\n19596\n19597\n19598\n19599\n19600\n19601\n19602\n19603\n19604\n19605\n19606\n19607\n19608\n19609\n19610\n19611\n19612\n19613\n19614\n19615\n19616\n19617\n19618\n19619\n19620\n19621\n19622\n19623\n19624\n19625\n19626\n19627\n19628\n19629\n19630\n19631\n19632\n19633\n19634\n19635\n19636\n19637\n19638\n19639\n19640\n19641\n19642\n19643\n19644\n19645\n19646\n19647\n19648\n19649\n19650\n19651\n19652\n19653\n19654\n19655\n19656\n19657\n19658\n19659\n19660\n19661\n19662\n19663\n19664\n19665\n19666\n19667\n19668\n19669\n19670\n19671\n19672\n19673\n19674\n19675\n19676\n19677\n19678\n19679\n19680\n19681\n19682\n19683\n19684\n19685\n19686\n19687\n19688\n19689\n19690\n19691\n19692\n19693\n19694\n19695\n19696\n19697\n19698\n19699\n19700\n19701\n19702\n19703\n19704\n19705\n19706\n19707\n19708\n19709\n19710\n19711\n19712\n19713\n19714\n19715\n19716\n19717\n19718\n19719\n19720\n19721\n19722\n19723\n19724\n19725\n19726\n19727\n19728\n19729\n19730\n19731\n19732\n19733\n19734\n19735\n19736\n19737\n19738\n19739\n19740\n19741\n19742\n19743\n19744\n19745\n19746\n19747\n19748\n19749\n19750\n19751\n19752\n19753\n19754\n19755\n19756\n19757\n19758\n19759\n19760\n19761\n19762\n19763\n19764\n19765\n19766\n19767\n19768\n19769\n19770\n19771\n19772\n19773\n19774\n19775\n19776\n19777\n19778\n19779\n19780\n19781\n19782\n19783\n19784\n19785\n19786\n19787\n19788\n19789\n19790\n19791\n19792\n19793\n19794\n19795\n19796\n19797\n19798\n19799\n19800\n19801\n19802\n19803\n19804\n19805\n19806\n19807\n19808\n19809\n19810\n19811\n19812\n19813\n19814\n19815\n19816\n19817\n19818\n19819\n19820\n19821\n19822\n19823\n19824\n19825\n19826\n19827\n19828\n19829\n19830\n19831\n19832\n19833\n19834\n19835\n19836\n19837\n19838\n19839\n19840\n19841\n19842\n19843\n19844\n19845\n19846\n19847\n19848\n19849\n19850\n19851\n19852\n19853\n19854\n19855\n19856\n19857\n19858\n19859\n19860\n19861\n19862\n19863\n19864\n19865\n19866\n19867\n19868\n19869\n19870\n19871\n19872\n19873\n19874\n19875\n19876\n19877\n19878\n19879\n19880\n19881\n19882\n19883\n19884\n19885\n19886\n19887\n19888\n19889\n19890\n19891\n19892\n19893\n19894\n19895\n19896\n19897\n19898\n19899\n19900\n19901\n19902\n19903\n19904\n19905\n19906\n19907\n19908\n19909\n19910\n19911\n19912\n19913\n19914\n19915\n19916\n19917\n19918\n19919\n19920\n19921\n19922\n19923\n19924\n19925\n19926\n19927\n19928\n19929\n19930\n19931\n19932\n19933\n19934\n19935\n19936\n19937\n19938\n19939\n19940\n19941\n19942\n19943\n19944\n19945\n19946\n19947\n19948\n19949\n19950\n19951\n19952\n19953\n19954\n19955\n19956\n19957\n19958\n19959\n19960\n19961\n19962\n19963\n19964\n19965\n19966\n19967\n19968\n19969\n19970\n19971\n19972\n19973\n19974\n19975\n19976\n19977\n19978\n19979\n19980\n19981\n19982\n19983\n19984\n19985\n19986\n19987\n19988\n19989\n19990\n19991\n19992\n19993\n19994\n19995\n19996\n19997\n19998\n19999\n20000\n20001\n20002\n20003\n20004\n20005\n20006\n20007\n20008\n20009\n20010\n20011\n20012\n20013\n20014\n20015\n20016\n20017\n20018\n20019\n20020\n20021\n20022\n20023\n20024\n20025\n20026\n20027\n20028\n20029\n20030\n20031\n20032\n20033\n20034\n20035\n20036\n20037\n20038\n20039\n20040\n20041\n20042\n20043\n20044\n20045\n20046\n20047\n20048\n20049\n20050\n20051\n20052\n20053\n20054\n20055\n20056\n20057\n20058\n20059\n20060\n20061\n20062\n20063\n20064\n20065\n20066\n20067\n20068\n20069\n20070\n20071\n20072\n20073\n20074\n20075\n20076\n20077\n20078\n20079\n20080\n20081\n20082\n20083\n20084\n20085\n20086\n20087\n20088\n20089\n20090\n20091\n20092\n20093\n20094\n20095\n20096\n20097\n20098\n20099\n20100\n20101\n20102\n20103\n20104\n20105\n20106\n20107\n20108\n20109\n20110\n20111\n20112\n20113\n20114\n20115\n20116\n20117\n20118\n20119\n20120\n20121\n20122\n20123\n20124\n20125\n20126\n20127\n20128\n20129\n20130\n20131\n20132\n20133\n20134\n20135\n20136\n20137\n20138\n20139\n20140\n20141\n20142\n20143\n20144\n20145\n20146\n20147\n20148\n20149\n20150\n20151\n20152\n20153\n20154\n20155\n20156\n20157\n20158\n20159\n20160\n20161\n20162\n20163\n20164\n20165\n20166\n20167\n20168\n20169\n20170\n20171\n20172\n20173\n20174\n20175\n20176\n20177\n20178\n20179\n20180\n20181\n20182\n20183\n20184\n20185\n20186\n20187\n20188\n20189\n20190\n20191\n20192\n20193\n20194\n20195\n20196\n20197\n20198\n20199\n20200\n20201\n20202\n20203\n20204\n20205\n20206\n20207\n20208\n20209\n20210\n20211\n20212\n20213\n20214\n20215\n20216\n20217\n20218\n20219\n20220\n20221\n20222\n20223\n20224\n20225\n20226\n20227\n20228\n20229\n20230\n20231\n20232\n20233\n20234\n20235\n20236\n20237\n20238\n20239\n20240\n20241\n20242\n20243\n20244\n20245\n20246\n20247\n20248\n20249\n20250\n20251\n20252\n20253\n20254\n20255\n20256\n20257\n20258\n20259\n20260\n20261\n20262\n20263\n20264\n20265\n20266\n20267\n20268\n20269\n20270\n20271\n20272\n20273\n20274\n20275\n20276\n20277\n20278\n20279\n20280\n20281\n20282\n20283\n20284\n20285\n20286\n20287\n20288\n20289\n20290\n20291\n20292\n20293\n20294\n20295\n20296\n20297\n20298\n20299\n20300\n20301\n20302\n20303\n20304\n20305\n20306\n20307\n20308\n20309\n20310\n20311\n20312\n20313\n20314\n20315\n20316\n20317\n20318\n20319\n20320\n20321\n20322\n20323\n20324\n20325\n20326\n20327\n20328\n20329\n20330\n20331\n20332\n20333\n20334\n20335\n20336\n20337\n20338\n20339\n20340\n20341\n20342\n20343\n20344\n20345\n20346\n20347\n20348\n20349\n20350\n20351\n20352\n20353\n20354\n20355\n20356\n20357\n20358\n20359\n20360\n20361\n20362\n20363\n20364\n20365\n20366\n20367\n20368\n20369\n20370\n20371\n20372\n20373\n20374\n20375\n20376\n20377\n20378\n20379\n20380\n20381\n20382\n20383\n20384\n20385\n20386\n20387\n20388\n20389\n20390\n20391\n20392\n20393\n20394\n20395\n20396\n20397\n20398\n20399\n20400\n20401\n20402\n20403\n20404\n20405\n20406\n20407\n20408\n20409\n20410\n20411\n20412\n20413\n20414\n20415\n20416\n20417\n20418\n20419\n20420\n20421\n20422\n20423\n20424\n20425\n20426\n20427\n20428\n20429\n20430\n20431\n20432\n20433\n20434\n20435\n20436\n20437\n20438\n20439\n20440\n20441\n20442\n20443\n20444\n20445\n20446\n20447\n20448\n20449\n20450\n20451\n20452\n20453\n20454\n20455\n20456\n20457\n20458\n20459\n20460\n20461\n20462\n20463\n20464\n20465\n20466\n20467\n20468\n20469\n20470\n20471\n20472\n20473\n20474\n20475\n20476\n20477\n20478\n20479\n20480\n20481\n20482\n20483\n20484\n20485\n20486\n20487\n20488\n20489\n20490\n20491\n20492\n20493\n20494\n20495\n20496\n20497\n20498\n20499\n20500\n20501\n20502\n20503\n20504\n20505\n20506\n20507\n20508\n20509\n20510\n20511\n20512\n20513\n20514\n20515\n20516\n20517\n20518\n20519\n20520\n20521\n20522\n20523\n20524\n20525\n20526\n20527\n20528\n20529\n20530\n20531\n20532\n20533\n20534\n20535\n20536\n20537\n20538\n20539\n20540\n20541\n20542\n20543\n20544\n20545\n20546\n20547\n20548\n20549\n20550\n20551\n20552\n20553\n20554\n20555\n20556\n20557\n20558\n20559\n20560\n20561\n20562\n20563\n20564\n20565\n20566\n20567\n20568\n20569\n20570\n20571\n20572\n20573\n20574\n20575\n20576\n20577\n20578\n20579\n20580\n20581\n20582\n20583\n20584\n20585\n20586\n20587\n20588\n20589\n20590\n20591\n20592\n20593\n20594\n20595\n20596\n20597\n20598\n20599\n20600\n20601\n20602\n20603\n20604\n20605\n20606\n20607\n20608\n20609\n20610\n20611\n20612\n20613\n20614\n20615\n20616\n20617\n20618\n20619\n20620\n20621\n20622\n20623\n20624\n20625\n20626\n20627\n20628\n20629\n20630\n20631\n20632\n20633\n20634\n20635\n20636\n20637\n20638\n20639\n20640\n20641\n20642\n20643\n20644\n20645\n20646\n20647\n20648\n20649\n20650\n20651\n20652\n20653\n20654\n20655\n20656\n20657\n20658\n20659\n20660\n20661\n20662\n20663\n20664\n20665\n20666\n20667\n20668\n20669\n20670\n20671\n20672\n20673\n20674\n20675\n20676\n20677\n20678\n20679\n20680\n20681\n20682\n20683\n20684\n20685\n20686\n20687\n20688\n20689\n20690\n20691\n20692\n20693\n20694\n20695\n20696\n20697\n20698\n20699\n20700\n20701\n20702\n20703\n20704\n20705\n20706\n20707\n20708\n20709\n20710\n20711\n20712\n20713\n20714\n20715\n20716\n20717\n20718\n20719\n20720\n20721\n20722\n20723\n20724\n20725\n20726\n20727\n20728\n20729\n20730\n20731\n20732\n20733\n20734\n20735\n20736\n20737\n20738\n20739\n20740\n20741\n20742\n20743\n20744\n20745\n20746\n20747\n20748\n20749\n20750\n20751\n20752\n20753\n20754\n20755\n20756\n20757\n20758\n20759\n20760\n20761\n20762\n20763\n20764\n20765\n20766\n20767\n20768\n20769\n20770\n20771\n20772\n20773\n20774\n20775\n20776\n20777\n20778\n20779\n20780\n20781\n20782\n20783\n20784\n20785\n20786\n20787\n20788\n20789\n20790\n20791\n20792\n20793\n20794\n20795\n20796\n20797\n20798\n20799\n20800\n20801\n20802\n20803\n20804\n20805\n20806\n20807\n20808\n20809\n20810\n20811\n20812\n20813\n20814\n20815\n20816\n20817\n20818\n20819\n20820\n20821\n20822\n20823\n20824\n20825\n20826\n20827\n20828\n20829\n20830\n20831\n20832\n20833\n20834\n20835\n20836\n20837\n20838\n20839\n20840\n20841\n20842\n20843\n20844\n20845\n20846\n20847\n20848\n20849\n20850\n20851\n20852\n20853\n20854\n20855\n20856\n20857\n20858\n20859\n20860\n20861\n20862\n20863\n20864\n20865\n20866\n20867\n20868\n20869\n20870\n20871\n20872\n20873\n20874\n20875\n20876\n20877\n20878\n20879\n20880\n20881\n20882\n20883\n20884\n20885\n20886\n20887\n20888\n20889\n20890\n20891\n20892\n20893\n20894\n20895\n20896\n20897\n20898\n20899\n20900\n20901\n20902\n20903\n20904\n20905\n20906\n20907\n20908\n20909\n20910\n20911\n20912\n20913\n20914\n20915\n20916\n20917\n20918\n20919\n20920\n20921\n20922\n20923\n20924\n20925\n20926\n20927\n20928\n20929\n20930\n20931\n20932\n20933\n20934\n20935\n20936\n20937\n20938\n20939\n20940\n20941\n20942\n20943\n20944\n20945\n20946\n20947\n20948\n20949\n20950\n20951\n20952\n20953\n20954\n20955\n20956\n20957\n20958\n20959\n20960\n20961\n20962\n20963\n20964\n20965\n20966\n20967\n20968\n20969\n20970\n20971\n20972\n20973\n20974\n20975\n20976\n20977\n20978\n20979\n20980\n20981\n20982\n20983\n20984\n20985\n20986\n20987\n20988\n20989\n20990\n20991\n20992\n20993\n20994\n20995\n20996\n20997\n20998\n20999\n21000\n21001\n21002\n21003\n21004\n21005\n21006\n21007\n21008\n21009\n21010\n21011\n21012\n21013\n21014\n21015\n21016\n21017\n21018\n21019\n21020\n21021\n21022\n21023\n21024\n21025\n21026\n21027\n21028\n21029\n21030\n21031\n21032\n21033\n21034\n21035\n21036\n21037\n21038\n21039\n21040\n21041\n21042\n21043\n21044\n21045\n21046\n21047\n21048\n21049\n21050\n21051\n21052\n21053\n21054\n21055\n21056\n21057\n21058\n21059\n21060\n21061\n21062\n21063\n21064\n21065\n21066\n21067\n21068\n21069\n21070\n21071\n21072\n21073\n21074\n21075\n21076\n21077\n21078\n21079\n21080\n21081\n21082\n21083\n21084\n21085\n21086\n21087\n21088\n21089\n21090\n21091\n21092\n21093\n21094\n21095\n21096\n21097\n21098\n21099\n21100\n21101\n21102\n21103\n21104\n21105\n21106\n21107\n21108\n21109\n21110\n21111\n21112\n21113\n21114\n21115\n21116\n21117\n21118\n21119\n21120\n21121\n21122\n21123\n21124\n21125\n21126\n21127\n21128\n21129\n21130\n21131\n21132\n21133\n21134\n21135\n21136\n21137\n21138\n21139\n21140\n21141\n21142\n21143\n21144\n21145\n21146\n21147\n21148\n21149\n21150\n21151\n21152\n21153\n21154\n21155\n21156\n21157\n21158\n21159\n21160\n21161\n21162\n21163\n21164\n21165\n21166\n21167\n21168\n21169\n21170\n21171\n21172\n21173\n21174\n21175\n21176\n21177\n21178\n21179\n21180\n21181\n21182\n21183\n21184\n21185\n21186\n21187\n21188\n21189\n21190\n21191\n21192\n21193\n21194\n21195\n21196\n21197\n21198\n21199\n21200\n21201\n21202\n21203\n21204\n21205\n21206\n21207\n21208\n21209\n21210\n21211\n21212\n21213\n21214\n21215\n21216\n21217\n21218\n21219\n21220\n21221\n21222\n21223\n21224\n21225\n21226\n21227\n21228\n21229\n21230\n21231\n21232\n21233\n21234\n21235\n21236\n21237\n21238\n21239\n21240\n21241\n21242\n21243\n21244\n21245\n21246\n21247\n21248\n21249\n21250\n21251\n21252\n21253\n21254\n21255\n21256\n21257\n21258\n21259\n21260\n21261\n21262\n21263\n21264\n21265\n21266\n21267\n21268\n21269\n21270\n21271\n21272\n21273\n21274\n21275\n21276\n21277\n21278\n21279\n21280\n21281\n21282\n21283\n21284\n21285\n21286\n21287\n21288\n21289\n21290\n21291\n21292\n21293\n21294\n21295\n21296\n21297\n21298\n21299\n21300\n21301\n21302\n21303\n21304\n21305\n21306\n21307\n21308\n21309\n21310\n21311\n21312\n21313\n21314\n21315\n21316\n21317\n21318\n21319\n21320\n21321\n21322\n21323\n21324\n21325\n21326\n21327\n21328\n21329\n21330\n21331\n21332\n21333\n21334\n21335\n21336\n21337\n21338\n21339\n21340\n21341\n21342\n21343\n21344\n21345\n21346\n21347\n21348\n21349\n21350\n21351\n21352\n21353\n21354\n21355\n21356\n21357\n21358\n21359\n21360\n21361\n21362\n21363\n21364\n21365\n21366\n21367\n21368\n21369\n21370\n21371\n21372\n21373\n21374\n21375\n21376\n21377\n21378\n21379\n21380\n21381\n21382\n21383\n21384\n21385\n21386\n21387\n21388\n21389\n21390\n21391\n21392\n21393\n21394\n21395\n21396\n21397\n21398\n21399\n21400\n21401\n21402\n21403\n21404\n21405\n21406\n21407\n21408\n21409\n21410\n21411\n21412\n21413\n21414\n21415\n21416\n21417\n21418\n21419\n21420\n21421\n21422\n21423\n21424\n21425\n21426\n21427\n21428\n21429\n21430\n21431\n21432\n21433\n21434\n21435\n21436\n21437\n21438\n21439\n21440\n21441\n21442\n21443\n21444\n21445\n21446\n21447\n21448\n21449\n21450\n21451\n21452\n21453\n21454\n21455\n21456\n21457\n21458\n21459\n21460\n21461\n21462\n21463\n21464\n21465\n21466\n21467\n21468\n21469\n21470\n21471\n21472\n21473\n21474\n21475\n21476\n21477\n21478\n21479\n21480\n21481\n21482\n21483\n21484\n21485\n21486\n21487\n21488\n21489\n21490\n21491\n21492\n21493\n21494\n21495\n21496\n21497\n21498\n21499\n21500\n21501\n21502\n21503\n21504\n21505\n21506\n21507\n21508\n21509\n21510\n21511\n21512\n21513\n21514\n21515\n21516\n21517\n21518\n21519\n21520\n21521\n21522\n21523\n21524\n21525\n21526\n21527\n21528\n21529\n21530\n21531\n21532\n21533\n21534\n21535\n21536\n21537\n21538\n21539\n21540\n21541\n21542\n21543\n21544\n21545\n21546\n21547\n21548\n21549\n21550\n21551\n21552\n21553\n21554\n21555\n21556\n21557\n21558\n21559\n21560\n21561\n21562\n21563\n21564\n21565\n21566\n21567\n21568\n21569\n21570\n21571\n21572\n21573\n21574\n21575\n21576\n21577\n21578\n21579\n21580\n21581\n21582\n21583\n21584\n21585\n21586\n21587\n21588\n21589\n21590\n21591\n21592\n21593\n21594\n21595\n21596\n21597\n21598\n21599\n21600\n21601\n21602\n21603\n21604\n21605\n21606\n21607\n21608\n21609\n21610\n21611\n21612\n21613\n21614\n21615\n21616\n21617\n21618\n21619\n21620\n21621\n21622\n21623\n21624\n21625\n21626\n21627\n21628\n21629\n21630\n21631\n21632\n21633\n21634\n21635\n21636\n21637\n21638\n21639\n21640\n21641\n21642\n21643\n21644\n21645\n21646\n21647\n21648\n21649\n21650\n21651\n21652\n21653\n21654\n21655\n21656\n21657\n21658\n21659\n21660\n21661\n21662\n21663\n21664\n21665\n21666\n21667\n21668\n21669\n21670\n21671\n21672\n21673\n21674\n21675\n21676\n21677\n21678\n21679\n21680\n21681\n21682\n21683\n21684\n21685\n21686\n21687\n21688\n21689\n21690\n21691\n21692\n21693\n21694\n21695\n21696\n21697\n21698\n21699\n21700\n21701\n21702\n21703\n21704\n21705\n21706\n21707\n21708\n21709\n21710\n21711\n21712\n21713\n21714\n21715\n21716\n21717\n21718\n21719\n21720\n21721\n21722\n21723\n21724\n21725\n21726\n21727\n21728\n21729\n21730\n21731\n21732\n21733\n21734\n21735\n21736\n21737\n21738\n21739\n21740\n21741\n21742\n21743\n21744\n21745\n21746\n21747\n21748\n21749\n21750\n21751\n21752\n21753\n21754\n21755\n21756\n21757\n21758\n21759\n21760\n21761\n21762\n21763\n21764\n21765\n21766\n21767\n21768\n21769\n21770\n21771\n21772\n21773\n21774\n21775\n21776\n21777\n21778\n21779\n21780\n21781\n21782\n21783\n21784\n21785\n21786\n21787\n21788\n21789\n21790\n21791\n21792\n21793\n21794\n21795\n21796\n21797\n21798\n21799\n21800\n21801\n21802\n21803\n21804\n21805\n21806\n21807\n21808\n21809\n21810\n21811\n21812\n21813\n21814\n21815\n21816\n21817\n21818\n21819\n21820\n21821\n21822\n21823\n21824\n21825\n21826\n21827\n21828\n21829\n21830\n21831\n21832\n21833\n21834\n21835\n21836\n21837\n21838\n21839\n21840\n21841\n21842\n21843\n21844\n21845\n21846\n21847\n21848\n21849\n21850\n21851\n21852\n21853\n21854\n21855\n21856\n21857\n21858\n21859\n21860\n21861\n21862\n21863\n21864\n21865\n21866\n21867\n21868\n21869\n21870\n21871\n21872\n21873\n21874\n21875\n21876\n21877\n21878\n21879\n21880\n21881\n21882\n21883\n21884\n21885\n21886\n21887\n21888\n21889\n21890\n21891\n21892\n21893\n21894\n21895\n21896\n21897\n21898\n21899\n21900\n21901\n21902\n21903\n21904\n21905\n21906\n21907\n21908\n21909\n21910\n21911\n21912\n21913\n21914\n21915\n21916\n21917\n21918\n21919\n21920\n21921\n21922\n21923\n21924\n21925\n21926\n21927\n21928\n21929\n21930\n21931\n21932\n21933\n21934\n21935\n21936\n21937\n21938\n21939\n21940\n21941\n21942\n21943\n21944\n21945\n21946\n21947\n21948\n21949\n21950\n21951\n21952\n21953\n21954\n21955\n21956\n21957\n21958\n21959\n21960\n21961\n21962\n21963\n21964\n21965\n21966\n21967\n21968\n21969\n21970\n21971\n21972\n21973\n21974\n21975\n21976\n21977\n21978\n21979\n21980\n21981\n21982\n21983\n21984\n21985\n21986\n21987\n21988\n21989\n21990\n21991\n21992\n21993\n21994\n21995\n21996\n21997\n21998\n21999\n22000\n22001\n22002\n22003\n22004\n22005\n22006\n22007\n22008\n22009\n22010\n22011\n22012\n22013\n22014\n22015\n22016\n22017\n22018\n22019\n22020\n22021\n22022\n22023\n22024\n22025\n22026\n22027\n22028\n22029\n22030\n22031\n22032\n22033\n22034\n22035\n22036\n22037\n22038\n22039\n22040\n22041\n22042\n22043\n22044\n22045\n22046\n22047\n22048\n22049\n22050\n22051\n22052\n22053\n22054\n22055\n22056\n22057\n22058\n22059\n22060\n22061\n22062\n22063\n22064\n22065\n22066\n22067\n22068\n22069\n22070\n22071\n22072\n22073\n22074\n22075\n22076\n22077\n22078\n22079\n22080\n22081\n22082\n22083\n22084\n22085\n22086\n22087\n22088\n22089\n22090\n22091\n22092\n22093\n22094\n22095\n22096\n22097\n22098\n22099\n22100\n22101\n22102\n22103\n22104\n22105\n22106\n22107\n22108\n22109\n22110\n22111\n22112\n22113\n22114\n22115\n22116\n22117\n22118\n22119\n22120\n22121\n22122\n22123\n22124\n22125\n22126\n22127\n22128\n22129\n22130\n22131\n22132\n22133\n22134\n22135\n22136\n22137\n22138\n22139\n22140\n22141\n22142\n22143\n22144\n22145\n22146\n22147\n22148\n22149\n22150\n22151\n22152\n22153\n22154\n22155\n22156\n22157\n22158\n22159\n22160\n22161\n22162\n22163\n22164\n22165\n22166\n22167\n22168\n22169\n22170\n22171\n22172\n22173\n22174\n22175\n22176\n22177\n22178\n22179\n22180\n22181\n22182\n22183\n22184\n22185\n22186\n22187\n22188\n22189\n22190\n22191\n22192\n22193\n22194\n22195\n22196\n22197\n22198\n22199\n22200\n22201\n22202\n22203\n22204\n22205\n22206\n22207\n22208\n22209\n22210\n22211\n22212\n22213\n22214\n22215\n22216\n22217\n22218\n22219\n22220\n22221\n22222\n22223\n22224\n22225\n22226\n22227\n22228\n22229\n22230\n22231\n22232\n22233\n22234\n22235\n22236\n22237\n22238\n22239\n22240\n22241\n22242\n22243\n22244\n22245\n22246\n22247\n22248\n22249\n22250\n22251\n22252\n22253\n22254\n22255\n22256\n22257\n22258\n22259\n22260\n22261\n22262\n22263\n22264\n22265\n22266\n22267\n22268\n22269\n22270\n22271\n22272\n22273\n22274\n22275\n22276\n22277\n22278\n22279\n22280\n22281\n22282\n22283\n22284\n22285\n22286\n22287\n22288\n22289\n22290\n22291\n22292\n22293\n22294\n22295\n22296\n22297\n22298\n22299\n22300\n22301\n22302\n22303\n22304\n22305\n22306\n22307\n22308\n22309\n22310\n22311\n22312\n22313\n22314\n22315\n22316\n22317\n22318\n22319\n22320\n22321\n22322\n22323\n22324\n22325\n22326\n22327\n22328\n22329\n22330\n22331\n22332\n22333\n22334\n22335\n22336\n22337\n22338\n22339\n22340\n22341\n22342\n22343\n22344\n22345\n22346\n22347\n22348\n22349\n22350\n22351\n22352\n22353\n22354\n22355\n22356\n22357\n22358\n22359\n22360\n22361\n22362\n22363\n22364\n22365\n22366\n22367\n22368\n22369\n22370\n22371\n22372\n22373\n22374\n22375\n22376\n22377\n22378\n22379\n22380\n22381\n22382\n22383\n22384\n22385\n22386\n22387\n22388\n22389\n22390\n22391\n22392\n22393\n22394\n22395\n22396\n22397\n22398\n22399\n22400\n22401\n22402\n22403\n22404\n22405\n22406\n22407\n22408\n22409\n22410\n22411\n22412\n22413\n22414\n22415\n22416\n22417\n22418\n22419\n22420\n22421\n22422\n22423\n22424\n22425\n22426\n22427\n22428\n22429\n22430\n22431\n22432\n22433\n22434\n22435\n22436\n22437\n22438\n22439\n22440\n22441\n22442\n22443\n22444\n22445\n22446\n22447\n22448\n22449\n22450\n22451\n22452\n22453\n22454\n22455\n22456\n22457\n22458\n22459\n22460\n22461\n22462\n22463\n22464\n22465\n22466\n22467\n22468\n22469\n22470\n22471\n22472\n22473\n22474\n22475\n22476\n22477\n22478\n22479\n22480\n22481\n22482\n22483\n22484\n22485\n22486\n22487\n22488\n22489\n22490\n22491\n22492\n22493\n22494\n22495\n22496\n22497\n22498\n22499\n22500\n22501\n22502\n22503\n22504\n22505\n22506\n22507\n22508\n22509\n22510\n22511\n22512\n22513\n22514\n22515\n22516\n22517\n22518\n22519\n22520\n22521\n22522\n22523\n22524\n22525\n22526\n22527\n22528\n22529\n22530\n22531\n22532\n22533\n22534\n22535\n22536\n22537\n22538\n22539\n22540\n22541\n22542\n22543\n22544\n22545\n22546\n22547\n22548\n22549\n22550\n22551\n22552\n22553\n22554\n22555\n22556\n22557\n22558\n22559\n22560\n22561\n22562\n22563\n22564\n22565\n22566\n22567\n22568\n22569\n22570\n22571\n22572\n22573\n22574\n22575\n22576\n22577\n22578\n22579\n22580\n22581\n22582\n22583\n22584\n22585\n22586\n22587\n22588\n22589\n22590\n22591\n22592\n22593\n22594\n22595\n22596\n22597\n22598\n22599\n22600\n22601\n22602\n22603\n22604\n22605\n22606\n22607\n22608\n22609\n22610\n22611\n22612\n22613\n22614\n22615\n22616\n22617\n22618\n22619\n22620\n22621\n22622\n22623\n22624\n22625\n22626\n22627\n22628\n22629\n22630\n22631\n22632\n22633\n22634\n22635\n22636\n22637\n22638\n22639\n22640\n22641\n22642\n22643\n22644\n22645\n22646\n22647\n22648\n22649\n22650\n22651\n22652\n22653\n22654\n22655\n22656\n22657\n22658\n22659\n22660\n22661\n22662\n22663\n22664\n22665\n22666\n22667\n22668\n22669\n22670\n22671\n22672\n22673\n22674\n22675\n22676\n22677\n22678\n22679\n22680\n22681\n22682\n22683\n22684\n22685\n22686\n22687\n22688\n22689\n22690\n22691\n22692\n22693\n22694\n22695\n22696\n22697\n22698\n22699\n22700\n22701\n22702\n22703\n22704\n22705\n22706\n22707\n22708\n22709\n22710\n22711\n22712\n22713\n22714\n22715\n22716\n22717\n22718\n22719\n22720\n22721\n22722\n22723\n22724\n22725\n22726\n22727\n22728\n22729\n22730\n22731\n22732\n22733\n22734\n22735\n22736\n22737\n22738\n22739\n22740\n22741\n22742\n22743\n22744\n22745\n22746\n22747\n22748\n22749\n22750\n22751\n22752\n22753\n22754\n22755\n22756\n22757\n22758\n22759\n22760\n22761\n22762\n22763\n22764\n22765\n22766\n22767\n22768\n22769\n22770\n22771\n22772\n22773\n22774\n22775\n22776\n22777\n22778\n22779\n22780\n22781\n22782\n22783\n22784\n22785\n22786\n22787\n22788\n22789\n22790\n22791\n22792\n22793\n22794\n22795\n22796\n22797\n22798\n22799\n22800\n22801\n22802\n22803\n22804\n22805\n22806\n22807\n22808\n22809\n22810\n22811\n22812\n22813\n22814\n22815\n22816\n22817\n22818\n22819\n22820\n22821\n22822\n22823\n22824\n22825\n22826\n22827\n22828\n22829\n22830\n22831\n22832\n22833\n22834\n22835\n22836\n22837\n22838\n22839\n22840\n22841\n22842\n22843\n22844\n22845\n22846\n22847\n22848\n22849\n22850\n22851\n22852\n22853\n22854\n22855\n22856\n22857\n22858\n22859\n22860\n22861\n22862\n22863\n22864\n22865\n22866\n22867\n22868\n22869\n22870\n22871\n22872\n22873\n22874\n22875\n22876\n22877\n22878\n22879\n22880\n22881\n22882\n22883\n22884\n22885\n22886\n22887\n22888\n22889\n22890\n22891\n22892\n22893\n22894\n22895\n22896\n22897\n22898\n22899\n22900\n22901\n22902\n22903\n22904\n22905\n22906\n22907\n22908\n22909\n22910\n22911\n22912\n22913\n22914\n22915\n22916\n22917\n22918\n22919\n22920\n22921\n22922\n22923\n22924\n22925\n22926\n22927\n22928\n22929\n22930\n22931\n22932\n22933\n22934\n22935\n22936\n22937\n22938\n22939\n22940\n22941\n22942\n22943\n22944\n22945\n22946\n22947\n22948\n22949\n22950\n22951\n22952\n22953\n22954\n22955\n22956\n22957\n22958\n22959\n22960\n22961\n22962\n22963\n22964\n22965\n22966\n22967\n22968\n22969\n22970\n22971\n22972\n22973\n22974\n22975\n22976\n22977\n22978\n22979\n22980\n22981\n22982\n22983\n22984\n22985\n22986\n22987\n22988\n22989\n22990\n22991\n22992\n22993\n22994\n22995\n22996\n22997\n22998\n22999\n23000\n23001\n23002\n23003\n23004\n23005\n23006\n23007\n23008\n23009\n23010\n23011\n23012\n23013\n23014\n23015\n23016\n23017\n23018\n23019\n23020\n23021\n23022\n23023\n23024\n23025\n23026\n23027\n23028\n23029\n23030\n23031\n23032\n23033\n23034\n23035\n23036\n23037\n23038\n23039\n23040\n23041\n23042\n23043\n23044\n23045\n23046\n23047\n23048\n23049\n23050\n23051\n23052\n23053\n23054\n23055\n23056\n23057\n23058\n23059\n23060\n23061\n23062\n23063\n23064\n23065\n23066\n23067\n23068\n23069\n23070\n23071\n23072\n23073\n23074\n23075\n23076\n23077\n23078\n23079\n23080\n23081\n23082\n23083\n23084\n23085\n23086\n23087\n23088\n23089\n23090\n23091\n23092\n23093\n23094\n23095\n23096\n23097\n23098\n23099\n23100\n23101\n23102\n23103\n23104\n23105\n23106\n23107\n23108\n23109\n23110\n23111\n23112\n23113\n23114\n23115\n23116\n23117\n23118\n23119\n23120\n23121\n23122\n23123\n23124\n23125\n23126\n23127\n23128\n23129\n23130\n23131\n23132\n23133\n23134\n23135\n23136\n23137\n23138\n23139\n23140\n23141\n23142\n23143\n23144\n23145\n23146\n23147\n23148\n23149\n23150\n23151\n23152\n23153\n23154\n23155\n23156\n23157\n23158\n23159\n23160\n23161\n23162\n23163\n23164\n23165\n23166\n23167\n23168\n23169\n23170\n23171\n23172\n23173\n23174\n23175\n23176\n23177\n23178\n23179\n23180\n23181\n23182\n23183\n23184\n23185\n23186\n23187\n23188\n23189\n23190\n23191\n23192\n23193\n23194\n23195\n23196\n23197\n23198\n23199\n23200\n23201\n23202\n23203\n23204\n23205\n23206\n23207\n23208\n23209\n23210\n23211\n23212\n23213\n23214\n23215\n23216\n23217\n23218\n23219\n23220\n23221\n23222\n23223\n23224\n23225\n23226\n23227\n23228\n23229\n23230\n23231\n23232\n23233\n23234\n23235\n23236\n23237\n23238\n23239\n23240\n23241\n23242\n23243\n23244\n23245\n23246\n23247\n23248\n23249\n23250\n23251\n23252\n23253\n23254\n23255\n23256\n23257\n23258\n23259\n23260\n23261\n23262\n23263\n23264\n23265\n23266\n23267\n23268\n23269\n23270\n23271\n23272\n23273\n23274\n23275\n23276\n23277\n23278\n23279\n23280\n23281\n23282\n23283\n23284\n23285\n23286\n23287\n23288\n23289\n23290\n23291\n23292\n23293\n23294\n23295\n23296\n23297\n23298\n23299\n23300\n23301\n23302\n23303\n23304\n23305\n23306\n23307\n23308\n23309\n23310\n23311\n23312\n23313\n23314\n23315\n23316\n23317\n23318\n23319\n23320\n23321\n23322\n23323\n23324\n23325\n23326\n23327\n23328\n23329\n23330\n23331\n23332\n23333\n23334\n23335\n23336\n23337\n23338\n23339\n23340\n23341\n23342\n23343\n23344\n23345\n23346\n23347\n23348\n23349\n23350\n23351\n23352\n23353\n23354\n23355\n23356\n23357\n23358\n23359\n23360\n23361\n23362\n23363\n23364\n23365\n23366\n23367\n23368\n23369\n23370\n23371\n23372\n23373\n23374\n23375\n23376\n23377\n23378\n23379\n23380\n23381\n23382\n23383\n23384\n23385\n23386\n23387\n23388\n23389\n23390\n23391\n23392\n23393\n23394\n23395\n23396\n23397\n23398\n23399\n23400\n23401\n23402\n23403\n23404\n23405\n23406\n23407\n23408\n23409\n23410\n23411\n23412\n23413\n23414\n23415\n23416\n23417\n23418\n23419\n23420\n23421\n23422\n23423\n23424\n23425\n23426\n23427\n23428\n23429\n23430\n23431\n23432\n23433\n23434\n23435\n23436\n23437\n23438\n23439\n23440\n23441\n23442\n23443\n23444\n23445\n23446\n23447\n23448\n23449\n23450\n23451\n23452\n23453\n23454\n23455\n23456\n23457\n23458\n23459\n23460\n23461\n23462\n23463\n23464\n23465\n23466\n23467\n23468\n23469\n23470\n23471\n23472\n23473\n23474\n23475\n23476\n23477\n23478\n23479\n23480\n23481\n23482\n23483\n23484\n23485\n23486\n23487\n23488\n23489\n23490\n23491\n23492\n23493\n23494\n23495\n23496\n23497\n23498\n23499\n23500\n23501\n23502\n23503\n23504\n23505\n23506\n23507\n23508\n23509\n23510\n23511\n23512\n23513\n23514\n23515\n23516\n23517\n23518\n23519\n23520\n23521\n23522\n23523\n23524\n23525\n23526\n23527\n23528\n23529\n23530\n23531\n23532\n23533\n23534\n23535\n23536\n23537\n23538\n23539\n23540\n23541\n23542\n23543\n23544\n23545\n23546\n23547\n23548\n23549\n23550\n23551\n23552\n23553\n23554\n23555\n23556\n23557\n23558\n23559\n23560\n23561\n23562\n23563\n23564\n23565\n23566\n23567\n23568\n23569\n23570\n23571\n23572\n23573\n23574\n23575\n23576\n23577\n23578\n23579\n23580\n23581\n23582\n23583\n23584\n23585\n23586\n23587\n23588\n23589\n23590\n23591\n23592\n23593\n23594\n23595\n23596\n23597\n23598\n23599\n23600\n23601\n23602\n23603\n23604\n23605\n23606\n23607\n23608\n23609\n23610\n23611\n23612\n23613\n23614\n23615\n23616\n23617\n23618\n23619\n23620\n23621\n23622\n23623\n23624\n23625\n23626\n23627\n23628\n23629\n23630\n23631\n23632\n23633\n23634\n23635\n23636\n23637\n23638\n23639\n23640\n23641\n23642\n23643\n23644\n23645\n23646\n23647\n23648\n23649\n23650\n23651\n23652\n23653\n23654\n23655\n23656\n23657\n23658\n23659\n23660\n23661\n23662\n23663\n23664\n23665\n23666\n23667\n23668\n23669\n23670\n23671\n23672\n23673\n23674\n23675\n23676\n23677\n23678\n23679\n23680\n23681\n23682\n23683\n23684\n23685\n23686\n23687\n23688\n23689\n23690\n23691\n23692\n23693\n23694\n23695\n23696\n23697\n23698\n23699\n23700\n23701\n23702\n23703\n23704\n23705\n23706\n23707\n23708\n23709\n23710\n23711\n23712\n23713\n23714\n23715\n23716\n23717\n23718\n23719\n23720\n23721\n23722\n23723\n23724\n23725\n23726\n23727\n23728\n23729\n23730\n23731\n23732\n23733\n23734\n23735\n23736\n23737\n23738\n23739\n23740\n23741\n23742\n23743\n23744\n23745\n23746\n23747\n23748\n23749\n23750\n23751\n23752\n23753\n23754\n23755\n23756\n23757\n23758\n23759\n23760\n23761\n23762\n23763\n23764\n23765\n23766\n23767\n23768\n23769\n23770\n23771\n23772\n23773\n23774\n23775\n23776\n23777\n23778\n23779\n23780\n23781\n23782\n23783\n23784\n23785\n23786\n23787\n23788\n23789\n23790\n23791\n23792\n23793\n23794\n23795\n23796\n23797\n23798\n23799\n23800\n23801\n23802\n23803\n23804\n23805\n23806\n23807\n23808\n23809\n23810\n23811\n23812\n23813\n23814\n23815\n23816\n23817\n23818\n23819\n23820\n23821\n23822\n23823\n23824\n23825\n23826\n23827\n23828\n23829\n23830\n23831\n23832\n23833\n23834\n23835\n23836\n23837\n23838\n23839\n23840\n23841\n23842\n23843\n23844\n23845\n23846\n23847\n23848\n23849\n23850\n23851\n23852\n23853\n23854\n23855\n23856\n23857\n23858\n23859\n23860\n23861\n23862\n23863\n23864\n23865\n23866\n23867\n23868\n23869\n23870\n23871\n23872\n23873\n23874\n23875\n23876\n23877\n23878\n23879\n23880\n23881\n23882\n23883\n23884\n23885\n23886\n23887\n23888\n23889\n23890\n23891\n23892\n23893\n23894\n23895\n23896\n23897\n23898\n23899\n23900\n23901\n23902\n23903\n23904\n23905\n23906\n23907\n23908\n23909\n23910\n23911\n23912\n23913\n23914\n23915\n23916\n23917\n23918\n23919\n23920\n23921\n23922\n23923\n23924\n23925\n23926\n23927\n23928\n23929\n23930\n23931\n23932\n23933\n23934\n23935\n23936\n23937\n23938\n23939\n23940\n23941\n23942\n23943\n23944\n23945\n23946\n23947\n23948\n23949\n23950\n23951\n23952\n23953\n23954\n23955\n23956\n23957\n23958\n23959\n23960\n23961\n23962\n23963\n23964\n23965\n23966\n23967\n23968\n23969\n23970\n23971\n23972\n23973\n23974\n23975\n23976\n23977\n23978\n23979\n23980\n23981\n23982\n23983\n23984\n23985\n23986\n23987\n23988\n23989\n23990\n23991\n23992\n23993\n23994\n23995\n23996\n23997\n23998\n23999\n24000\n24001\n24002\n24003\n24004\n24005\n24006\n24007\n24008\n24009\n24010\n24011\n24012\n24013\n24014\n24015\n24016\n24017\n24018\n24019\n24020\n24021\n24022\n24023\n24024\n24025\n24026\n24027\n24028\n24029\n24030\n24031\n24032\n24033\n24034\n24035\n24036\n24037\n24038\n24039\n24040\n24041\n24042\n24043\n24044\n24045\n24046\n24047\n24048\n24049\n24050\n24051\n24052\n24053\n24054\n24055\n24056\n24057\n24058\n24059\n24060\n24061\n24062\n24063\n24064\n24065\n24066\n24067\n24068\n24069\n24070\n24071\n24072\n24073\n24074\n24075\n24076\n24077\n24078\n24079\n24080\n24081\n24082\n24083\n24084\n24085\n24086\n24087\n24088\n24089\n24090\n24091\n24092\n24093\n24094\n24095\n24096\n24097\n24098\n24099\n24100\n24101\n24102\n24103\n24104\n24105\n24106\n24107\n24108\n24109\n24110\n24111\n24112\n24113\n24114\n24115\n24116\n24117\n24118\n24119\n24120\n24121\n24122\n24123\n24124\n24125\n24126\n24127\n24128\n24129\n24130\n24131\n24132\n24133\n24134\n24135\n24136\n24137\n24138\n24139\n24140\n24141\n24142\n24143\n24144\n24145\n24146\n24147\n24148\n24149\n24150\n24151\n24152\n24153\n24154\n24155\n24156\n24157\n24158\n24159\n24160\n24161\n24162\n24163\n24164\n24165\n24166\n24167\n24168\n24169\n24170\n24171\n24172\n24173\n24174\n24175\n24176\n24177\n24178\n24179\n24180\n24181\n24182\n24183\n24184\n24185\n24186\n24187\n24188\n24189\n24190\n24191\n24192\n24193\n24194\n24195\n24196\n24197\n24198\n24199\n24200\n24201\n24202\n24203\n24204\n24205\n24206\n24207\n24208\n24209\n24210\n24211\n24212\n24213\n24214\n24215\n24216\n24217\n24218\n24219\n24220\n24221\n24222\n24223\n24224\n24225\n24226\n24227\n24228\n24229\n24230\n24231\n24232\n24233\n24234\n24235\n24236\n24237\n24238\n24239\n24240\n24241\n24242\n24243\n24244\n24245\n24246\n24247\n24248\n24249\n24250\n24251\n24252\n24253\n24254\n24255\n24256\n24257\n24258\n24259\n24260\n24261\n24262\n24263\n24264\n24265\n24266\n24267\n24268\n24269\n24270\n24271\n24272\n24273\n24274\n24275\n24276\n24277\n24278\n24279\n24280\n24281\n24282\n24283\n24284\n24285\n24286\n24287\n24288\n24289\n24290\n24291\n24292\n24293\n24294\n24295\n24296\n24297\n24298\n24299\n24300\n24301\n24302\n24303\n24304\n24305\n24306\n24307\n24308\n24309\n24310\n24311\n24312\n24313\n24314\n24315\n24316\n24317\n24318\n24319\n24320\n24321\n24322\n24323\n24324\n24325\n24326\n24327\n24328\n24329\n24330\n24331\n24332\n24333\n24334\n24335\n24336\n24337\n24338\n24339\n24340\n24341\n24342\n24343\n24344\n24345\n24346\n24347\n24348\n24349\n24350\n24351\n24352\n24353\n24354\n24355\n24356\n24357\n24358\n24359\n24360\n24361\n24362\n24363\n24364\n24365\n24366\n24367\n24368\n24369\n24370\n24371\n24372\n24373\n24374\n24375\n24376\n24377\n24378\n24379\n24380\n24381\n24382\n24383\n24384\n24385\n24386\n24387\n24388\n24389\n24390\n24391\n24392\n24393\n24394\n24395\n24396\n24397\n24398\n24399\n24400\n24401\n24402\n24403\n24404\n24405\n24406\n24407\n24408\n24409\n24410\n24411\n24412\n24413\n24414\n24415\n24416\n24417\n24418\n24419\n24420\n24421\n24422\n24423\n24424\n24425\n24426\n24427\n24428\n24429\n24430\n24431\n24432\n24433\n24434\n24435\n24436\n24437\n24438\n24439\n24440\n24441\n24442\n24443\n24444\n24445\n24446\n24447\n24448\n24449\n24450\n24451\n24452\n24453\n24454\n24455\n24456\n24457\n24458\n24459\n24460\n24461\n24462\n24463\n24464\n24465\n24466\n24467\n24468\n24469\n24470\n24471\n24472\n24473\n24474\n24475\n24476\n24477\n24478\n24479\n24480\n24481\n24482\n24483\n24484\n24485\n24486\n24487\n24488\n24489\n24490\n24491\n24492\n24493\n24494\n24495\n24496\n24497\n24498\n24499\n24500\n24501\n24502\n24503\n24504\n24505\n24506\n24507\n24508\n24509\n24510\n24511\n24512\n24513\n24514\n24515\n24516\n24517\n24518\n24519\n24520\n24521\n24522\n24523\n24524\n24525\n24526\n24527\n24528\n24529\n24530\n24531\n24532\n24533\n24534\n24535\n24536\n24537\n24538\n24539\n24540\n24541\n24542\n24543\n24544\n24545\n24546\n24547\n24548\n24549\n24550\n24551\n24552\n24553\n24554\n24555\n24556\n24557\n24558\n24559\n24560\n24561\n24562\n24563\n24564\n24565\n24566\n24567\n24568\n24569\n24570\n24571\n24572\n24573\n24574\n24575\n24576\n24577\n24578\n24579\n24580\n24581\n24582\n24583\n24584\n24585\n24586\n24587\n24588\n24589\n24590\n24591\n24592\n24593\n24594\n24595\n24596\n24597\n24598\n24599\n24600\n24601\n24602\n24603\n24604\n24605\n24606\n24607\n24608\n24609\n24610\n24611\n24612\n24613\n24614\n24615\n24616\n24617\n24618\n24619\n24620\n24621\n24622\n24623\n24624\n24625\n24626\n24627\n24628\n24629\n24630\n24631\n24632\n24633\n24634\n24635\n24636\n24637\n24638\n24639\n24640\n24641\n24642\n24643\n24644\n24645\n24646\n24647\n24648\n24649\n24650\n24651\n24652\n24653\n24654\n24655\n24656\n24657\n24658\n24659\n24660\n24661\n24662\n24663\n24664\n24665\n24666\n24667\n24668\n24669\n24670\n24671\n24672\n24673\n24674\n24675\n24676\n24677\n24678\n24679\n24680\n24681\n24682\n24683\n24684\n24685\n24686\n24687\n24688\n24689\n24690\n24691\n24692\n24693\n24694\n24695\n24696\n24697\n24698\n24699\n24700\n24701\n24702\n24703\n24704\n24705\n24706\n24707\n24708\n24709\n24710\n24711\n24712\n24713\n24714\n24715\n24716\n24717\n24718\n24719\n24720\n24721\n24722\n24723\n24724\n24725\n24726\n24727\n24728\n24729\n24730\n24731\n24732\n24733\n24734\n24735\n24736\n24737\n24738\n24739\n24740\n24741\n24742\n24743\n24744\n24745\n24746\n24747\n24748\n24749\n24750\n24751\n24752\n24753\n24754\n24755\n24756\n24757\n24758\n24759\n24760\n24761\n24762\n24763\n24764\n24765\n24766\n24767\n24768\n24769\n24770\n24771\n24772\n24773\n24774\n24775\n24776\n24777\n24778\n24779\n24780\n24781\n24782\n24783\n24784\n24785\n24786\n24787\n24788\n24789\n24790\n24791\n24792\n24793\n24794\n24795\n24796\n24797\n24798\n24799\n24800\n24801\n24802\n24803\n24804\n24805\n24806\n24807\n24808\n24809\n24810\n24811\n24812\n24813\n24814\n24815\n24816\n24817\n24818\n24819\n24820\n24821\n24822\n24823\n24824\n24825\n24826\n24827\n24828\n24829\n24830\n24831\n24832\n24833\n24834\n24835\n24836\n24837\n24838\n24839\n24840\n24841\n24842\n24843\n24844\n24845\n24846\n24847\n24848\n24849\n24850\n24851\n24852\n24853\n24854\n24855\n24856\n24857\n24858\n24859\n24860\n24861\n24862\n24863\n24864\n24865\n24866\n24867\n24868\n24869\n24870\n24871\n24872\n24873\n24874\n24875\n24876\n24877\n24878\n24879\n24880\n24881\n24882\n24883\n24884\n24885\n24886\n24887\n24888\n24889\n24890\n24891\n24892\n24893\n24894\n24895\n24896\n24897\n24898\n24899\n24900\n24901\n24902\n24903\n24904\n24905\n24906\n24907\n24908\n24909\n24910\n24911\n24912\n24913\n24914\n24915\n24916\n24917\n24918\n24919\n24920\n24921\n24922\n24923\n24924\n24925\n24926\n24927\n24928\n24929\n24930\n24931\n24932\n24933\n24934\n24935\n24936\n24937\n24938\n24939\n24940\n24941\n24942\n24943\n24944\n24945\n24946\n24947\n24948\n24949\n24950\n24951\n24952\n24953\n24954\n24955\n24956\n24957\n24958\n24959\n24960\n24961\n24962\n24963\n24964\n24965\n24966\n24967\n24968\n24969\n24970\n24971\n24972\n24973\n24974\n24975\n24976\n24977\n24978\n24979\n24980\n24981\n24982\n24983\n24984\n24985\n24986\n24987\n24988\n24989\n24990\n24991\n24992\n24993\n24994\n24995\n24996\n24997\n24998\n24999\n25000\n25001\n25002\n25003\n25004\n25005\n25006\n25007\n25008\n25009\n25010\n25011\n25012\n25013\n25014\n25015\n25016\n25017\n25018\n25019\n25020\n25021\n25022\n25023\n25024\n25025\n25026\n25027\n25028\n25029\n25030\n25031\n25032\n25033\n25034\n25035\n25036\n25037\n25038\n25039\n25040\n25041\n25042\n25043\n25044\n25045\n25046\n25047\n25048\n25049\n25050\n25051\n25052\n25053\n25054\n25055\n25056\n25057\n25058\n25059\n25060\n25061\n25062\n25063\n25064\n25065\n25066\n25067\n25068\n25069\n25070\n25071\n25072\n25073\n25074\n25075\n25076\n25077\n25078\n25079\n25080\n25081\n25082\n25083\n25084\n25085\n25086\n25087\n25088\n25089\n25090\n25091\n25092\n25093\n25094\n25095\n25096\n25097\n25098\n25099\n25100\n25101\n25102\n25103\n25104\n25105\n25106\n25107\n25108\n25109\n25110\n25111\n25112\n25113\n25114\n25115\n25116\n25117\n25118\n25119\n25120\n25121\n25122\n25123\n25124\n25125\n25126\n25127\n25128\n25129\n25130\n25131\n25132\n25133\n25134\n25135\n25136\n25137\n25138\n25139\n25140\n25141\n25142\n25143\n25144\n25145\n25146\n25147\n25148\n25149\n25150\n25151\n25152\n25153\n25154\n25155\n25156\n25157\n25158\n25159\n25160\n25161\n25162\n25163\n25164\n25165\n25166\n25167\n25168\n25169\n25170\n25171\n25172\n25173\n25174\n25175\n25176\n25177\n25178\n25179\n25180\n25181\n25182\n25183\n25184\n25185\n25186\n25187\n25188\n25189\n25190\n25191\n25192\n25193\n25194\n25195\n25196\n25197\n25198\n25199\n25200\n25201\n25202\n25203\n25204\n25205\n25206\n25207\n25208\n25209\n25210\n25211\n25212\n25213\n25214\n25215\n25216\n25217\n25218\n25219\n25220\n25221\n25222\n25223\n25224\n25225\n25226\n25227\n25228\n25229\n25230\n25231\n25232\n25233\n25234\n25235\n25236\n25237\n25238\n25239\n25240\n25241\n25242\n25243\n25244\n25245\n25246\n25247\n25248\n25249\n25250\n25251\n25252\n25253\n25254\n25255\n25256\n25257\n25258\n25259\n25260\n25261\n25262\n25263\n25264\n25265\n25266\n25267\n25268\n25269\n25270\n25271\n25272\n25273\n25274\n25275\n25276\n25277\n25278\n25279\n25280\n25281\n25282\n25283\n25284\n25285\n25286\n25287\n25288\n25289\n25290\n25291\n25292\n25293\n25294\n25295\n25296\n25297\n25298\n25299\n25300\n25301\n25302\n25303\n25304\n25305\n25306\n25307\n25308\n25309\n25310\n25311\n25312\n25313\n25314\n25315\n25316\n25317\n25318\n25319\n25320\n25321\n25322\n25323\n25324\n25325\n25326\n25327\n25328\n25329\n25330\n25331\n25332\n25333\n25334\n25335\n25336\n25337\n25338\n25339\n25340\n25341\n25342\n25343\n25344\n25345\n25346\n25347\n25348\n25349\n25350\n25351\n25352\n25353\n25354\n25355\n25356\n25357\n25358\n25359\n25360\n25361\n25362\n25363\n25364\n25365\n25366\n25367\n25368\n25369\n25370\n25371\n25372\n25373\n25374\n25375\n25376\n25377\n25378\n25379\n25380\n25381\n25382\n25383\n25384\n25385\n25386\n25387\n25388\n25389\n25390\n25391\n25392\n25393\n25394\n25395\n25396\n25397\n25398\n25399\n25400\n25401\n25402\n25403\n25404\n25405\n25406\n25407\n25408\n25409\n25410\n25411\n25412\n25413\n25414\n25415\n25416\n25417\n25418\n25419\n25420\n25421\n25422\n25423\n25424\n25425\n25426\n25427\n25428\n25429\n25430\n25431\n25432\n25433\n25434\n25435\n25436\n25437\n25438\n25439\n25440\n25441\n25442\n25443\n25444\n25445\n25446\n25447\n25448\n25449\n25450\n25451\n25452\n25453\n25454\n25455\n25456\n25457\n25458\n25459\n25460\n25461\n25462\n25463\n25464\n25465\n25466\n25467\n25468\n25469\n25470\n25471\n25472\n25473\n25474\n25475\n25476\n25477\n25478\n25479\n25480\n25481\n25482\n25483\n25484\n25485\n25486\n25487\n25488\n25489\n25490\n25491\n25492\n25493\n25494\n25495\n25496\n25497\n25498\n25499\n25500\n25501\n25502\n25503\n25504\n25505\n25506\n25507\n25508\n25509\n25510\n25511\n25512\n25513\n25514\n25515\n25516\n25517\n25518\n25519\n25520\n25521\n25522\n25523\n25524\n25525\n25526\n25527\n25528\n25529\n25530\n25531\n25532\n25533\n25534\n25535\n25536\n25537\n25538\n25539\n25540\n25541\n25542\n25543\n25544\n25545\n25546\n25547\n25548\n25549\n25550\n25551\n25552\n25553\n25554\n25555\n25556\n25557\n25558\n25559\n25560\n25561\n25562\n25563\n25564\n25565\n25566\n25567\n25568\n25569\n25570\n25571\n25572\n25573\n25574\n25575\n25576\n25577\n25578\n25579\n25580\n25581\n25582\n25583\n25584\n25585\n25586\n25587\n25588\n25589\n25590\n25591\n25592\n25593\n25594\n25595\n25596\n25597\n25598\n25599\n25600\n25601\n25602\n25603\n25604\n25605\n25606\n25607\n25608\n25609\n25610\n25611\n25612\n25613\n25614\n25615\n25616\n25617\n25618\n25619\n25620\n25621\n25622\n25623\n25624\n25625\n25626\n25627\n25628\n25629\n25630\n25631\n25632\n25633\n25634\n25635\n25636\n25637\n25638\n25639\n25640\n25641\n25642\n25643\n25644\n25645\n25646\n25647\n25648\n25649\n25650\n25651\n25652\n25653\n25654\n25655\n25656\n25657\n25658\n25659\n25660\n25661\n25662\n25663\n25664\n25665\n25666\n25667\n25668\n25669\n25670\n25671\n25672\n25673\n25674\n25675\n25676\n25677\n25678\n25679\n25680\n25681\n25682\n25683\n25684\n25685\n25686\n25687\n25688\n25689\n25690\n25691\n25692\n25693\n25694\n25695\n25696\n25697\n25698\n25699\n25700\n25701\n25702\n25703\n25704\n25705\n25706\n25707\n25708\n25709\n25710\n25711\n25712\n25713\n25714\n25715\n25716\n25717\n25718\n25719\n25720\n25721\n25722\n25723\n25724\n25725\n25726\n25727\n25728\n25729\n25730\n25731\n25732\n25733\n25734\n25735\n25736\n25737\n25738\n25739\n25740\n25741\n25742\n25743\n25744\n25745\n25746\n25747\n25748\n25749\n25750\n25751\n25752\n25753\n25754\n25755\n25756\n25757\n25758\n25759\n25760\n25761\n25762\n25763\n25764\n25765\n25766\n25767\n25768\n25769\n25770\n25771\n25772\n25773\n25774\n25775\n25776\n25777\n25778\n25779\n25780\n25781\n25782\n25783\n25784\n25785\n25786\n25787\n25788\n25789\n25790\n25791\n25792\n25793\n25794\n25795\n25796\n25797\n25798\n25799\n25800\n25801\n25802\n25803\n25804\n25805\n25806\n25807\n25808\n25809\n25810\n25811\n25812\n25813\n25814\n25815\n25816\n25817\n25818\n25819\n25820\n25821\n25822\n25823\n25824\n25825\n25826\n25827\n25828\n25829\n25830\n25831\n25832\n25833\n25834\n25835\n25836\n25837\n25838\n25839\n25840\n25841\n25842\n25843\n25844\n25845\n25846\n25847\n25848\n25849\n25850\n25851\n25852\n25853\n25854\n25855\n25856\n25857\n25858\n25859\n25860\n25861\n25862\n25863\n25864\n25865\n25866\n25867\n25868\n25869\n25870\n25871\n25872\n25873\n25874\n25875\n25876\n25877\n25878\n25879\n25880\n25881\n25882\n25883\n25884\n25885\n25886\n25887\n25888\n25889\n25890\n25891\n25892\n25893\n25894\n25895\n25896\n25897\n25898\n25899\n25900\n25901\n25902\n25903\n25904\n25905\n25906\n25907\n25908\n25909\n25910\n25911\n25912\n25913\n25914\n25915\n25916\n25917\n25918\n25919\n25920\n25921\n25922\n25923\n25924\n25925\n25926\n25927\n25928\n25929\n25930\n25931\n25932\n25933\n25934\n25935\n25936\n25937\n25938\n25939\n25940\n25941\n25942\n25943\n25944\n25945\n25946\n25947\n25948\n25949\n25950\n25951\n25952\n25953\n25954\n25955\n25956\n25957\n25958\n25959\n25960\n25961\n25962\n25963\n25964\n25965\n25966\n25967\n25968\n25969\n25970\n25971\n25972\n25973\n25974\n25975\n25976\n25977\n25978\n25979\n25980\n25981\n25982\n25983\n25984\n25985\n25986\n25987\n25988\n25989\n25990\n25991\n25992\n25993\n25994\n25995\n25996\n25997\n25998\n25999\n26000\n26001\n26002\n26003\n26004\n26005\n26006\n26007\n26008\n26009\n26010\n26011\n26012\n26013\n26014\n26015\n26016\n26017\n26018\n26019\n26020\n26021\n26022\n26023\n26024\n26025\n26026\n26027\n26028\n26029\n26030\n26031\n26032\n26033\n26034\n26035\n26036\n26037\n26038\n26039\n26040\n26041\n26042\n26043\n26044\n26045\n26046\n26047\n26048\n26049\n26050\n26051\n26052\n26053\n26054\n26055\n26056\n26057\n26058\n26059\n26060\n26061\n26062\n26063\n26064\n26065\n26066\n26067\n26068\n26069\n26070\n26071\n26072\n26073\n26074\n26075\n26076\n26077\n26078\n26079\n26080\n26081\n26082\n26083\n26084\n26085\n26086\n26087\n26088\n26089\n26090\n26091\n26092\n26093\n26094\n26095\n26096\n26097\n26098\n26099\n26100\n26101\n26102\n26103\n26104\n26105\n26106\n26107\n26108\n26109\n26110\n26111\n26112\n26113\n26114\n26115\n26116\n26117\n26118\n26119\n26120\n26121\n26122\n26123\n26124\n26125\n26126\n26127\n26128\n26129\n26130\n26131\n26132\n26133\n26134\n26135\n26136\n26137\n26138\n26139\n26140\n26141\n26142\n26143\n26144\n26145\n26146\n26147\n26148\n26149\n26150\n26151\n26152\n26153\n26154\n26155\n26156\n26157\n26158\n26159\n26160\n26161\n26162\n26163\n26164\n26165\n26166\n26167\n26168\n26169\n26170\n26171\n26172\n26173\n26174\n26175\n26176\n26177\n26178\n26179\n26180\n26181\n26182\n26183\n26184\n26185\n26186\n26187\n26188\n26189\n26190\n26191\n26192\n26193\n26194\n26195\n26196\n26197\n26198\n26199\n26200\n26201\n26202\n26203\n26204\n26205\n26206\n26207\n26208\n26209\n26210\n26211\n26212\n26213\n26214\n26215\n26216\n26217\n26218\n26219\n26220\n26221\n26222\n26223\n26224\n26225\n26226\n26227\n26228\n26229\n26230\n26231\n26232\n26233\n26234\n26235\n26236\n26237\n26238\n26239\n26240\n26241\n26242\n26243\n26244\n26245\n26246\n26247\n26248\n26249\n26250\n26251\n26252\n26253\n26254\n26255\n26256\n26257\n26258\n26259\n26260\n26261\n26262\n26263\n26264\n26265\n26266\n26267\n26268\n26269\n26270\n26271\n26272\n26273\n26274\n26275\n26276\n26277\n26278\n26279\n26280\n26281\n26282\n26283\n26284\n26285\n26286\n26287\n26288\n26289\n26290\n26291\n26292\n26293\n26294\n26295\n26296\n26297\n26298\n26299\n26300\n26301\n26302\n26303\n26304\n26305\n26306\n26307\n26308\n26309\n26310\n26311\n26312\n26313\n26314\n26315\n26316\n26317\n26318\n26319\n26320\n26321\n26322\n26323\n26324\n26325\n26326\n26327\n26328\n26329\n26330\n26331\n26332\n26333\n26334\n26335\n26336\n26337\n26338\n26339\n26340\n26341\n26342\n26343\n26344\n26345\n26346\n26347\n26348\n26349\n26350\n26351\n26352\n26353\n26354\n26355\n26356\n26357\n26358\n26359\n26360\n26361\n26362\n26363\n26364\n26365\n26366\n26367\n26368\n26369\n26370\n26371\n26372\n26373\n26374\n26375\n26376\n26377\n26378\n26379\n26380\n26381\n26382\n26383\n26384\n26385\n26386\n26387\n26388\n26389\n26390\n26391\n26392\n26393\n26394\n26395\n26396\n26397\n26398\n26399\n26400\n26401\n26402\n26403\n26404\n26405\n26406\n26407\n26408\n26409\n26410\n26411\n26412\n26413\n26414\n26415\n26416\n26417\n26418\n26419\n26420\n26421\n26422\n26423\n26424\n26425\n26426\n26427\n26428\n26429\n26430\n26431\n26432\n26433\n26434\n26435\n26436\n26437\n26438\n26439\n26440\n26441\n26442\n26443\n26444\n26445\n26446\n26447\n26448\n26449\n26450\n26451\n26452\n26453\n26454\n26455\n26456\n26457\n26458\n26459\n26460\n26461\n26462\n26463\n26464\n26465\n26466\n26467\n26468\n26469\n26470\n26471\n26472\n26473\n26474\n26475\n26476\n26477\n26478\n26479\n26480\n26481\n26482\n26483\n26484\n26485\n26486\n26487\n26488\n26489\n26490\n26491\n26492\n26493\n26494\n26495\n26496\n26497\n26498\n26499\n26500\n26501\n26502\n26503\n26504\n26505\n26506\n26507\n26508\n26509\n26510\n26511\n26512\n26513\n26514\n26515\n26516\n26517\n26518\n26519\n26520\n26521\n26522\n26523\n26524\n26525\n26526\n26527\n26528\n26529\n26530\n26531\n26532\n26533\n26534\n26535\n26536\n26537\n26538\n26539\n26540\n26541\n26542\n26543\n26544\n26545\n26546\n26547\n26548\n26549\n26550\n26551\n26552\n26553\n26554\n26555\n26556\n26557\n26558\n26559\n26560\n26561\n26562\n26563\n26564\n26565\n26566\n26567\n26568\n26569\n26570\n26571\n26572\n26573\n26574\n26575\n26576\n26577\n26578\n26579\n26580\n26581\n26582\n26583\n26584\n26585\n26586\n26587\n26588\n26589\n26590\n26591\n26592\n26593\n26594\n26595\n26596\n26597\n26598\n26599\n26600\n26601\n26602\n26603\n26604\n26605\n26606\n26607\n26608\n26609\n26610\n26611\n26612\n26613\n26614\n26615\n26616\n26617\n26618\n26619\n26620\n26621\n26622\n26623\n26624\n26625\n26626\n26627\n26628\n26629\n26630\n26631\n26632\n26633\n26634\n26635\n26636\n26637\n26638\n26639\n26640\n26641\n26642\n26643\n26644\n26645\n26646\n26647\n26648\n26649\n26650\n26651\n26652\n26653\n26654\n26655\n26656\n26657\n26658\n26659\n26660\n26661\n26662\n26663\n26664\n26665\n26666\n26667\n26668\n26669\n26670\n26671\n26672\n26673\n26674\n26675\n26676\n26677\n26678\n26679\n26680\n26681\n26682\n26683\n26684\n26685\n26686\n26687\n26688\n26689\n26690\n26691\n26692\n26693\n26694\n26695\n26696\n26697\n26698\n26699\n26700\n26701\n26702\n26703\n26704\n26705\n26706\n26707\n26708\n26709\n26710\n26711\n26712\n26713\n26714\n26715\n26716\n26717\n26718\n26719\n26720\n26721\n26722\n26723\n26724\n26725\n26726\n26727\n26728\n26729\n26730\n26731\n26732\n26733\n26734\n26735\n26736\n26737\n26738\n26739\n26740\n26741\n26742\n26743\n26744\n26745\n26746\n26747\n26748\n26749\n26750\n26751\n26752\n26753\n26754\n26755\n26756\n26757\n26758\n26759\n26760\n26761\n26762\n26763\n26764\n26765\n26766\n26767\n26768\n26769\n26770\n26771\n26772\n26773\n26774\n26775\n26776\n26777\n26778\n26779\n26780\n26781\n26782\n26783\n26784\n26785\n26786\n26787\n26788\n26789\n26790\n26791\n26792\n26793\n26794\n26795\n26796\n26797\n26798\n26799\n26800\n26801\n26802\n26803\n26804\n26805\n26806\n26807\n26808\n26809\n26810\n26811\n26812\n26813\n26814\n26815\n26816\n26817\n26818\n26819\n26820\n26821\n26822\n26823\n26824\n26825\n26826\n26827\n26828\n26829\n26830\n26831\n26832\n26833\n26834\n26835\n26836\n26837\n26838\n26839\n26840\n26841\n26842\n26843\n26844\n26845\n26846\n26847\n26848\n26849\n26850\n26851\n26852\n26853\n26854\n26855\n26856\n26857\n26858\n26859\n26860\n26861\n26862\n26863\n26864\n26865\n26866\n26867\n26868\n26869\n26870\n26871\n26872\n26873\n26874\n26875\n26876\n26877\n26878\n26879\n26880\n26881\n26882\n26883\n26884\n26885\n26886\n26887\n26888\n26889\n26890\n26891\n26892\n26893\n26894\n26895\n26896\n26897\n26898\n26899\n26900\n26901\n26902\n26903\n26904\n26905\n26906\n26907\n26908\n26909\n26910\n26911\n26912\n26913\n26914\n26915\n26916\n26917\n26918\n26919\n26920\n26921\n26922\n26923\n26924\n26925\n26926\n26927\n26928\n26929\n26930\n26931\n26932\n26933\n26934\n26935\n26936\n26937\n26938\n26939\n26940\n26941\n26942\n26943\n26944\n26945\n26946\n26947\n26948\n26949\n26950\n26951\n26952\n26953\n26954\n26955\n26956\n26957\n26958\n26959\n26960\n26961\n26962\n26963\n26964\n26965\n26966\n26967\n26968\n26969\n26970\n26971\n26972\n26973\n26974\n26975\n26976\n26977\n26978\n26979\n26980\n26981\n26982\n26983\n26984\n26985\n26986\n26987\n26988\n26989\n26990\n26991\n26992\n26993\n26994\n26995\n26996\n26997\n26998\n26999\n27000\n27001\n27002\n27003\n27004\n27005\n27006\n27007\n27008\n27009\n27010\n27011\n27012\n27013\n27014\n27015\n27016\n27017\n27018\n27019\n27020\n27021\n27022\n27023\n27024\n27025\n27026\n27027\n27028\n27029\n27030\n27031\n27032\n27033\n27034\n27035\n27036\n27037\n27038\n27039\n27040\n27041\n27042\n27043\n27044\n27045\n27046\n27047\n27048\n27049\n27050\n27051\n27052\n27053\n27054\n27055\n27056\n27057\n27058\n27059\n27060\n27061\n27062\n27063\n27064\n27065\n27066\n27067\n27068\n27069\n27070\n27071\n27072\n27073\n27074\n27075\n27076\n27077\n27078\n27079\n27080\n27081\n27082\n27083\n27084\n27085\n27086\n27087\n27088\n27089\n27090\n27091\n27092\n27093\n27094\n27095\n27096\n27097\n27098\n27099\n27100\n27101\n27102\n27103\n27104\n27105\n27106\n27107\n27108\n27109\n27110\n27111\n27112\n27113\n27114\n27115\n27116\n27117\n27118\n27119\n27120\n27121\n27122\n27123\n27124\n27125\n27126\n27127\n27128\n27129\n27130\n27131\n27132\n27133\n27134\n27135\n27136\n27137\n27138\n27139\n27140\n27141\n27142\n27143\n27144\n27145\n27146\n27147\n27148\n27149\n27150\n27151\n27152\n27153\n27154\n27155\n27156\n27157\n27158\n27159\n27160\n27161\n27162\n27163\n27164\n27165\n27166\n27167\n27168\n27169\n27170\n27171\n27172\n27173\n27174\n27175\n27176\n27177\n27178\n27179\n27180\n27181\n27182\n27183\n27184\n27185\n27186\n27187\n27188\n27189\n27190\n27191\n27192\n27193\n27194\n27195\n27196\n27197\n27198\n27199\n27200\n27201\n27202\n27203\n27204\n27205\n27206\n27207\n27208\n27209\n27210\n27211\n27212\n27213\n27214\n27215\n27216\n27217\n27218\n27219\n27220\n27221\n27222\n27223\n27224\n27225\n27226\n27227\n27228\n27229\n27230\n27231\n27232\n27233\n27234\n27235\n27236\n27237\n27238\n27239\n27240\n27241\n27242\n27243\n27244\n27245\n27246\n27247\n27248\n27249\n27250\n27251\n27252\n27253\n27254\n27255\n27256\n27257\n27258\n27259\n27260\n27261\n27262\n27263\n27264\n27265\n27266\n27267\n27268\n27269\n27270\n27271\n27272\n27273\n27274\n27275\n27276\n27277\n27278\n27279\n27280\n27281\n27282\n27283\n27284\n27285\n27286\n27287\n27288\n27289\n27290\n27291\n27292\n27293\n27294\n27295\n27296\n27297\n27298\n27299\n27300\n27301\n27302\n27303\n27304\n27305\n27306\n27307\n27308\n27309\n27310\n27311\n27312\n27313\n27314\n27315\n27316\n27317\n27318\n27319\n27320\n27321\n27322\n27323\n27324\n27325\n27326\n27327\n27328\n27329\n27330\n27331\n27332\n27333\n27334\n27335\n27336\n27337\n27338\n27339\n27340\n27341\n27342\n27343\n27344\n27345\n27346\n27347\n27348\n27349\n27350\n27351\n27352\n27353\n27354\n27355\n27356\n27357\n27358\n27359\n27360\n27361\n27362\n27363\n27364\n27365\n27366\n27367\n27368\n27369\n27370\n27371\n27372\n27373\n27374\n27375\n27376\n27377\n27378\n27379\n27380\n27381\n27382\n27383\n27384\n27385\n27386\n27387\n27388\n27389\n27390\n27391\n27392\n27393\n27394\n27395\n27396\n27397\n27398\n27399\n27400\n27401\n27402\n27403\n27404\n27405\n27406\n27407\n27408\n27409\n27410\n27411\n27412\n27413\n27414\n27415\n27416\n27417\n27418\n27419\n27420\n27421\n27422\n27423\n27424\n27425\n27426\n27427\n27428\n27429\n27430\n27431\n27432\n27433\n27434\n27435\n27436\n27437\n27438\n27439\n27440\n27441\n27442\n27443\n27444\n27445\n27446\n27447\n27448\n27449\n27450\n27451\n27452\n27453\n27454\n27455\n27456\n27457\n27458\n27459\n27460\n27461\n27462\n27463\n27464\n27465\n27466\n27467\n27468\n27469\n27470\n27471\n27472\n27473\n27474\n27475\n27476\n27477\n27478\n27479\n27480\n27481\n27482\n27483\n27484\n27485\n27486\n27487\n27488\n27489\n27490\n27491\n27492\n27493\n27494\n27495\n27496\n27497\n27498\n27499\n27500\n27501\n27502\n27503\n27504\n27505\n27506\n27507\n27508\n27509\n27510\n27511\n27512\n27513\n27514\n27515\n27516\n27517\n27518\n27519\n27520\n27521\n27522\n27523\n27524\n27525\n27526\n27527\n27528\n27529\n27530\n27531\n27532\n27533\n27534\n27535\n27536\n27537\n27538\n27539\n27540\n27541\n27542\n27543\n27544\n27545\n27546\n27547\n27548\n27549\n27550\n27551\n27552\n27553\n27554\n27555\n27556\n27557\n27558\n27559\n27560\n27561\n27562\n27563\n27564\n27565\n27566\n27567\n27568\n27569\n27570\n27571\n27572\n27573\n27574\n27575\n27576\n27577\n27578\n27579\n27580\n27581\n27582\n27583\n27584\n27585\n27586\n27587\n27588\n27589\n27590\n27591\n27592\n27593\n27594\n27595\n27596\n27597\n27598\n27599\n27600\n27601\n27602\n27603\n27604\n27605\n27606\n27607\n27608\n27609\n27610\n27611\n27612\n27613\n27614\n27615\n27616\n27617\n27618\n27619\n27620\n27621\n27622\n27623\n27624\n27625\n27626\n27627\n27628\n27629\n27630\n27631\n27632\n27633\n27634\n27635\n27636\n27637\n27638\n27639\n27640\n27641\n27642\n27643\n27644\n27645\n27646\n27647\n27648\n27649\n27650\n27651\n27652\n27653\n27654\n27655\n27656\n27657\n27658\n27659\n27660\n27661\n27662\n27663\n27664\n27665\n27666\n27667\n27668\n27669\n27670\n27671\n27672\n27673\n27674\n27675\n27676\n27677\n27678\n27679\n27680\n27681\n27682\n27683\n27684\n27685\n27686\n27687\n27688\n27689\n27690\n27691\n27692\n27693\n27694\n27695\n27696\n27697\n27698\n27699\n27700\n27701\n27702\n27703\n27704\n27705\n27706\n27707\n27708\n27709\n27710\n27711\n27712\n27713\n27714\n27715\n27716\n27717\n27718\n27719\n27720\n27721\n27722\n27723\n27724\n27725\n27726\n27727\n27728\n27729\n27730\n27731\n27732\n27733\n27734\n27735\n27736\n27737\n27738\n27739\n27740\n27741\n27742\n27743\n27744\n27745\n27746\n27747\n27748\n27749\n27750\n27751\n27752\n27753\n27754\n27755\n27756\n27757\n27758\n27759\n27760\n27761\n27762\n27763\n27764\n27765\n27766\n27767\n27768\n27769\n27770\n27771\n27772\n27773\n27774\n27775\n27776\n27777\n27778\n27779\n27780\n27781\n27782\n27783\n27784\n27785\n27786\n27787\n27788\n27789\n27790\n27791\n27792\n27793\n27794\n27795\n27796\n27797\n27798\n27799\n27800\n27801\n27802\n27803\n27804\n27805\n27806\n27807\n27808\n27809\n27810\n27811\n27812\n27813\n27814\n27815\n27816\n27817\n27818\n27819\n27820\n27821\n27822\n27823\n27824\n27825\n27826\n27827\n27828\n27829\n27830\n27831\n27832\n27833\n27834\n27835\n27836\n27837\n27838\n27839\n27840\n27841\n27842\n27843\n27844\n27845\n27846\n27847\n27848\n27849\n27850\n27851\n27852\n27853\n27854\n27855\n27856\n27857\n27858\n27859\n27860\n27861\n27862\n27863\n27864\n27865\n27866\n27867\n27868\n27869\n27870\n27871\n27872\n27873\n27874\n27875\n27876\n27877\n27878\n27879\n27880\n27881\n27882\n27883\n27884\n27885\n27886\n27887\n27888\n27889\n27890\n27891\n27892\n27893\n27894\n27895\n27896\n27897\n27898\n27899\n27900\n27901\n27902\n27903\n27904\n27905\n27906\n27907\n27908\n27909\n27910\n27911\n27912\n27913\n27914\n27915\n27916\n27917\n27918\n27919\n27920\n27921\n27922\n27923\n27924\n27925\n27926\n27927\n27928\n27929\n27930\n27931\n27932\n27933\n27934\n27935\n27936\n27937\n27938\n27939\n27940\n27941\n27942\n27943\n27944\n27945\n27946\n27947\n27948\n27949\n27950\n27951\n27952\n27953\n27954\n27955\n27956\n27957\n27958\n27959\n27960\n27961\n27962\n27963\n27964\n27965\n27966\n27967\n27968\n27969\n27970\n27971\n27972\n27973\n27974\n27975\n27976\n27977\n27978\n27979\n27980\n27981\n27982\n27983\n27984\n27985\n27986\n27987\n27988\n27989\n27990\n27991\n27992\n27993\n27994\n27995\n27996\n27997\n27998\n27999\n28000\n28001\n28002\n28003\n28004\n28005\n28006\n28007\n28008\n28009\n28010\n28011\n28012\n28013\n28014\n28015\n28016\n28017\n28018\n28019\n28020\n28021\n28022\n28023\n28024\n28025\n28026\n28027\n28028\n28029\n28030\n28031\n28032\n28033\n28034\n28035\n28036\n28037\n28038\n28039\n28040\n28041\n28042\n28043\n28044\n28045\n28046\n28047\n28048\n28049\n28050\n28051\n28052\n28053\n28054\n28055\n28056\n28057\n28058\n28059\n28060\n28061\n28062\n28063\n28064\n28065\n28066\n28067\n28068\n28069\n28070\n28071\n28072\n28073\n28074\n28075\n28076\n28077\n28078\n28079\n28080\n28081\n28082\n28083\n28084\n28085\n28086\n28087\n28088\n28089\n28090\n28091\n28092\n28093\n28094\n28095\n28096\n28097\n28098\n28099\n28100\n28101\n28102\n28103\n28104\n28105\n28106\n28107\n28108\n28109\n28110\n28111\n28112\n28113\n28114\n28115\n28116\n28117\n28118\n28119\n28120\n28121\n28122\n28123\n28124\n28125\n28126\n28127\n28128\n28129\n28130\n28131\n28132\n28133\n28134\n28135\n28136\n28137\n28138\n28139\n28140\n28141\n28142\n28143\n28144\n28145\n28146\n28147\n28148\n28149\n28150\n28151\n28152\n28153\n28154\n28155\n28156\n28157\n28158\n28159\n28160\n28161\n28162\n28163\n28164\n28165\n28166\n28167\n28168\n28169\n28170\n28171\n28172\n28173\n28174\n28175\n28176\n28177\n28178\n28179\n28180\n28181\n28182\n28183\n28184\n28185\n28186\n28187\n28188\n28189\n28190\n28191\n28192\n28193\n28194\n28195\n28196\n28197\n28198\n28199\n28200\n28201\n28202\n28203\n28204\n28205\n28206\n28207\n28208\n28209\n28210\n28211\n28212\n28213\n28214\n28215\n28216\n28217\n28218\n28219\n28220\n28221\n28222\n28223\n28224\n28225\n28226\n28227\n28228\n28229\n28230\n28231\n28232\n28233\n28234\n28235\n28236\n28237\n28238\n28239\n28240\n28241\n28242\n28243\n28244\n28245\n28246\n28247\n28248\n28249\n28250\n28251\n28252\n28253\n28254\n28255\n28256\n28257\n28258\n28259\n28260\n28261\n28262\n28263\n28264\n28265\n28266\n28267\n28268\n28269\n28270\n28271\n28272\n28273\n28274\n28275\n28276\n28277\n28278\n28279\n28280\n28281\n28282\n28283\n28284\n28285\n28286\n28287\n28288\n28289\n28290\n28291\n28292\n28293\n28294\n28295\n28296\n28297\n28298\n28299\n28300\n28301\n28302\n28303\n28304\n28305\n28306\n28307\n28308\n28309\n28310\n28311\n28312\n28313\n28314\n28315\n28316\n28317\n28318\n28319\n28320\n28321\n28322\n28323\n28324\n28325\n28326\n28327\n28328\n28329\n28330\n28331\n28332\n28333\n28334\n28335\n28336\n28337\n28338\n28339\n28340\n28341\n28342\n28343\n28344\n28345\n28346\n28347\n28348\n28349\n28350\n28351\n28352\n28353\n28354\n28355\n28356\n28357\n28358\n28359\n28360\n28361\n28362\n28363\n28364\n28365\n28366\n28367\n28368\n28369\n28370\n28371\n28372\n28373\n28374\n28375\n28376\n28377\n28378\n28379\n28380\n28381\n28382\n28383\n28384\n28385\n28386\n28387\n28388\n28389\n28390\n28391\n28392\n28393\n28394\n28395\n28396\n28397\n28398\n28399\n28400\n28401\n28402\n28403\n28404\n28405\n28406\n28407\n28408\n28409\n28410\n28411\n28412\n28413\n28414\n28415\n28416\n28417\n28418\n28419\n28420\n28421\n28422\n28423\n28424\n28425\n28426\n28427\n28428\n28429\n28430\n28431\n28432\n28433\n28434\n28435\n28436\n28437\n28438\n28439\n28440\n28441\n28442\n28443\n28444\n28445\n28446\n28447\n28448\n28449\n28450\n28451\n28452\n28453\n28454\n28455\n28456\n28457\n28458\n28459\n28460\n28461\n28462\n28463\n28464\n28465\n28466\n28467\n28468\n28469\n28470\n28471\n28472\n28473\n28474\n28475\n28476\n28477\n28478\n28479\n28480\n28481\n28482\n28483\n28484\n28485\n28486\n28487\n28488\n28489\n28490\n28491\n28492\n28493\n28494\n28495\n28496\n28497\n28498\n28499\n28500\n28501\n28502\n28503\n28504\n28505\n28506\n28507\n28508\n28509\n28510\n28511\n28512\n28513\n28514\n28515\n28516\n28517\n28518\n28519\n28520\n28521\n28522\n28523\n28524\n28525\n28526\n28527\n28528\n28529\n28530\n28531\n28532\n28533\n28534\n28535\n28536\n28537\n28538\n28539\n28540\n28541\n28542\n28543\n28544\n28545\n28546\n28547\n28548\n28549\n28550\n28551\n28552\n28553\n28554\n28555\n28556\n28557\n28558\n28559\n28560\n28561\n28562\n28563\n28564\n28565\n28566\n28567\n28568\n28569\n28570\n28571\n28572\n28573\n28574\n28575\n28576\n28577\n28578\n28579\n28580\n28581\n28582\n28583\n28584\n28585\n28586\n28587\n28588\n28589\n28590\n28591\n28592\n28593\n28594\n28595\n28596\n28597\n28598\n28599\n28600\n28601\n28602\n28603\n28604\n28605\n28606\n28607\n28608\n28609\n28610\n28611\n28612\n28613\n28614\n28615\n28616\n28617\n28618\n28619\n28620\n28621\n28622\n28623\n28624\n28625\n28626\n28627\n28628\n28629\n28630\n28631\n28632\n28633\n28634\n28635\n28636\n28637\n28638\n28639\n28640\n28641\n28642\n28643\n28644\n28645\n28646\n28647\n28648\n28649\n28650\n28651\n28652\n28653\n28654\n28655\n28656\n28657\n28658\n28659\n28660\n28661\n28662\n28663\n28664\n28665\n28666\n28667\n28668\n28669\n28670\n28671\n28672\n28673\n28674\n28675\n28676\n28677\n28678\n28679\n28680\n28681\n28682\n28683\n28684\n28685\n28686\n28687\n28688\n28689\n28690\n28691\n28692\n28693\n28694\n28695\n28696\n28697\n28698\n28699\n28700\n28701\n28702\n28703\n28704\n28705\n28706\n28707\n28708\n28709\n28710\n28711\n28712\n28713\n28714\n28715\n28716\n28717\n28718\n28719\n28720\n28721\n28722\n28723\n28724\n28725\n28726\n28727\n28728\n28729\n28730\n28731\n28732\n28733\n28734\n28735\n28736\n28737\n28738\n28739\n28740\n28741\n28742\n28743\n28744\n28745\n28746\n28747\n28748\n28749\n28750\n28751\n28752\n28753\n28754\n28755\n28756\n28757\n28758\n28759\n28760\n28761\n28762\n28763\n28764\n28765\n28766\n28767\n28768\n28769\n28770\n28771\n28772\n28773\n28774\n28775\n28776\n28777\n28778\n28779\n28780\n28781\n28782\n28783\n28784\n28785\n28786\n28787\n28788\n28789\n28790\n28791\n28792\n28793\n28794\n28795\n28796\n28797\n28798\n28799\n28800\n28801\n28802\n28803\n28804\n28805\n28806\n28807\n28808\n28809\n28810\n28811\n28812\n28813\n28814\n28815\n28816\n28817\n28818\n28819\n28820\n28821\n28822\n28823\n28824\n28825\n28826\n28827\n28828\n28829\n28830\n28831\n28832\n28833\n28834\n28835\n28836\n28837\n28838\n28839\n28840\n28841\n28842\n28843\n28844\n28845\n28846\n28847\n28848\n28849\n28850\n28851\n28852\n28853\n28854\n28855\n28856\n28857\n28858\n28859\n28860\n28861\n28862\n28863\n28864\n28865\n28866\n28867\n28868\n28869\n28870\n28871\n28872\n28873\n28874\n28875\n28876\n28877\n28878\n28879\n28880\n28881\n28882\n28883\n28884\n28885\n28886\n28887\n28888\n28889\n28890\n28891\n28892\n28893\n28894\n28895\n28896\n28897\n28898\n28899\n28900\n28901\n28902\n28903\n28904\n28905\n28906\n28907\n28908\n28909\n28910\n28911\n28912\n28913\n28914\n28915\n28916\n28917\n28918\n28919\n28920\n28921\n28922\n28923\n28924\n28925\n28926\n28927\n28928\n28929\n28930\n28931\n28932\n28933\n28934\n28935\n28936\n28937\n28938\n28939\n28940\n28941\n28942\n28943\n28944\n28945\n28946\n28947\n28948\n28949\n28950\n28951\n28952\n28953\n28954\n28955\n28956\n28957\n28958\n28959\n28960\n28961\n28962\n28963\n28964\n28965\n28966\n28967\n28968\n28969\n28970\n28971\n28972\n28973\n28974\n28975\n28976\n28977\n28978\n28979\n28980\n28981\n28982\n28983\n28984\n28985\n28986\n28987\n28988\n28989\n28990\n28991\n28992\n28993\n28994\n28995\n28996\n28997\n28998\n28999\n29000\n29001\n29002\n29003\n29004\n29005\n29006\n29007\n29008\n29009\n29010\n29011\n29012\n29013\n29014\n29015\n29016\n29017\n29018\n29019\n29020\n29021\n29022\n29023\n29024\n29025\n29026\n29027\n29028\n29029\n29030\n29031\n29032\n29033\n29034\n29035\n29036\n29037\n29038\n29039\n29040\n29041\n29042\n29043\n29044\n29045\n29046\n29047\n29048\n29049\n29050\n29051\n29052\n29053\n29054\n29055\n29056\n29057\n29058\n29059\n29060\n29061\n29062\n29063\n29064\n29065\n29066\n29067\n29068\n29069\n29070\n29071\n29072\n29073\n29074\n29075\n29076\n29077\n29078\n29079\n29080\n29081\n29082\n29083\n29084\n29085\n29086\n29087\n29088\n29089\n29090\n29091\n29092\n29093\n29094\n29095\n29096\n29097\n29098\n29099\n29100\n29101\n29102\n29103\n29104\n29105\n29106\n29107\n29108\n29109\n29110\n29111\n29112\n29113\n29114\n29115\n29116\n29117\n29118\n29119\n29120\n29121\n29122\n29123\n29124\n29125\n29126\n29127\n29128\n29129\n29130\n29131\n29132\n29133\n29134\n29135\n29136\n29137\n29138\n29139\n29140\n29141\n29142\n29143\n29144\n29145\n29146\n29147\n29148\n29149\n29150\n29151\n29152\n29153\n29154\n29155\n29156\n29157\n29158\n29159\n29160\n29161\n29162\n29163\n29164\n29165\n29166\n29167\n29168\n29169\n29170\n29171\n29172\n29173\n29174\n29175\n29176\n29177\n29178\n29179\n29180\n29181\n29182\n29183\n29184\n29185\n29186\n29187\n29188\n29189\n29190\n29191\n29192\n29193\n29194\n29195\n29196\n29197\n29198\n29199\n29200\n29201\n29202\n29203\n29204\n29205\n29206\n29207\n29208\n29209\n29210\n29211\n29212\n29213\n29214\n29215\n29216\n29217\n29218\n29219\n29220\n29221\n29222\n29223\n29224\n29225\n29226\n29227\n29228\n29229\n29230\n29231\n29232\n29233\n29234\n29235\n29236\n29237\n29238\n29239\n29240\n29241\n29242\n29243\n29244\n29245\n29246\n29247\n29248\n29249\n29250\n29251\n29252\n29253\n29254\n29255\n29256\n29257\n29258\n29259\n29260\n29261\n29262\n29263\n29264\n29265\n29266\n29267\n29268\n29269\n29270\n29271\n29272\n29273\n29274\n29275\n29276\n29277\n29278\n29279\n29280\n29281\n29282\n29283\n29284\n29285\n29286\n29287\n29288\n29289\n29290\n29291\n29292\n29293\n29294\n29295\n29296\n29297\n29298\n29299\n29300\n29301\n29302\n29303\n29304\n29305\n29306\n29307\n29308\n29309\n29310\n29311\n29312\n29313\n29314\n29315\n29316\n29317\n29318\n29319\n29320\n29321\n29322\n29323\n29324\n29325\n29326\n29327\n29328\n29329\n29330\n29331\n29332\n29333\n29334\n29335\n29336\n29337\n29338\n29339\n29340\n29341\n29342\n29343\n29344\n29345\n29346\n29347\n29348\n29349\n29350\n29351\n29352\n29353\n29354\n29355\n29356\n29357\n29358\n29359\n29360\n29361\n29362\n29363\n29364\n29365\n29366\n29367\n29368\n29369\n29370\n29371\n29372\n29373\n29374\n29375\n29376\n29377\n29378\n29379\n29380\n29381\n29382\n29383\n29384\n29385\n29386\n29387\n29388\n29389\n29390\n29391\n29392\n29393\n29394\n29395\n29396\n29397\n29398\n29399\n29400\n29401\n29402\n29403\n29404\n29405\n29406\n29407\n29408\n29409\n29410\n29411\n29412\n29413\n29414\n29415\n29416\n29417\n29418\n29419\n29420\n29421\n29422\n29423\n29424\n29425\n29426\n29427\n29428\n29429\n29430\n29431\n29432\n29433\n29434\n29435\n29436\n29437\n29438\n29439\n29440\n29441\n29442\n29443\n29444\n29445\n29446\n29447\n29448\n29449\n29450\n29451\n29452\n29453\n29454\n29455\n29456\n29457\n29458\n29459\n29460\n29461\n29462\n29463\n29464\n29465\n29466\n29467\n29468\n29469\n29470\n29471\n29472\n29473\n29474\n29475\n29476\n29477\n29478\n29479\n29480\n29481\n29482\n29483\n29484\n29485\n29486\n29487\n29488\n29489\n29490\n29491\n29492\n29493\n29494\n29495\n29496\n29497\n29498\n29499\n29500\n29501\n29502\n29503\n29504\n29505\n29506\n29507\n29508\n29509\n29510\n29511\n29512\n29513\n29514\n29515\n29516\n29517\n29518\n29519\n29520\n29521\n29522\n29523\n29524\n29525\n29526\n29527\n29528\n29529\n29530\n29531\n29532\n29533\n29534\n29535\n29536\n29537\n29538\n29539\n29540\n29541\n29542\n29543\n29544\n29545\n29546\n29547\n29548\n29549\n29550\n29551\n29552\n29553\n29554\n29555\n29556\n29557\n29558\n29559\n29560\n29561\n29562\n29563\n29564\n29565\n29566\n29567\n29568\n29569\n29570\n29571\n29572\n29573\n29574\n29575\n29576\n29577\n29578\n29579\n29580\n29581\n29582\n29583\n29584\n29585\n29586\n29587\n29588\n29589\n29590\n29591\n29592\n29593\n29594\n29595\n29596\n29597\n29598\n29599\n29600\n29601\n29602\n29603\n29604\n29605\n29606\n29607\n29608\n29609\n29610\n29611\n29612\n29613\n29614\n29615\n29616\n29617\n29618\n29619\n29620\n29621\n29622\n29623\n29624\n29625\n29626\n29627\n29628\n29629\n29630\n29631\n29632\n29633\n29634\n29635\n29636\n29637\n29638\n29639\n29640\n29641\n29642\n29643\n29644\n29645\n29646\n29647\n29648\n29649\n29650\n29651\n29652\n29653\n29654\n29655\n29656\n29657\n29658\n29659\n29660\n29661\n29662\n29663\n29664\n29665\n29666\n29667\n29668\n29669\n29670\n29671\n29672\n29673\n29674\n29675\n29676\n29677\n29678\n29679\n29680\n29681\n29682\n29683\n29684\n29685\n29686\n29687\n29688\n29689\n29690\n29691\n29692\n29693\n29694\n29695\n29696\n29697\n29698\n29699\n29700\n29701\n29702\n29703\n29704\n29705\n29706\n29707\n29708\n29709\n29710\n29711\n29712\n29713\n29714\n29715\n29716\n29717\n29718\n29719\n29720\n29721\n29722\n29723\n29724\n29725\n29726\n29727\n29728\n29729\n29730\n29731\n29732\n29733\n29734\n29735\n29736\n29737\n29738\n29739\n29740\n29741\n29742\n29743\n29744\n29745\n29746\n29747\n29748\n29749\n29750\n29751\n29752\n29753\n29754\n29755\n29756\n29757\n29758\n29759\n29760\n29761\n29762\n29763\n29764\n29765\n29766\n29767\n29768\n29769\n29770\n29771\n29772\n29773\n29774\n29775\n29776\n29777\n29778\n29779\n29780\n29781\n29782\n29783\n29784\n29785\n29786\n29787\n29788\n29789\n29790\n29791\n29792\n29793\n29794\n29795\n29796\n29797\n29798\n29799\n29800\n29801\n29802\n29803\n29804\n29805\n29806\n29807\n29808\n29809\n29810\n29811\n29812\n29813\n29814\n29815\n29816\n29817\n29818\n29819\n29820\n29821\n29822\n29823\n29824\n29825\n29826\n29827\n29828\n29829\n29830\n29831\n29832\n29833\n29834\n29835\n29836\n29837\n29838\n29839\n29840\n29841\n29842\n29843\n29844\n29845\n29846\n29847\n29848\n29849\n29850\n29851\n29852\n29853\n29854\n29855\n29856\n29857\n29858\n29859\n29860\n29861\n29862\n29863\n29864\n29865\n29866\n29867\n29868\n29869\n29870\n29871\n29872\n29873\n29874\n29875\n29876\n29877\n29878\n29879\n29880\n29881\n29882\n29883\n29884\n29885\n29886\n29887\n29888\n29889\n29890\n29891\n29892\n29893\n29894\n29895\n29896\n29897\n29898\n29899\n29900\n29901\n29902\n29903\n29904\n29905\n29906\n29907\n29908\n29909\n29910\n29911\n29912\n29913\n29914\n29915\n29916\n29917\n29918\n29919\n29920\n29921\n29922\n29923\n29924\n29925\n29926\n29927\n29928\n29929\n29930\n29931\n29932\n29933\n29934\n29935\n29936\n29937\n29938\n29939\n29940\n29941\n29942\n29943\n29944\n29945\n29946\n29947\n29948\n29949\n29950\n29951\n29952\n29953\n29954\n29955\n29956\n29957\n29958\n29959\n29960\n29961\n29962\n29963\n29964\n29965\n29966\n29967\n29968\n29969\n29970\n29971\n29972\n29973\n29974\n29975\n29976\n29977\n29978\n29979\n29980\n29981\n29982\n29983\n29984\n29985\n29986\n29987\n29988\n29989\n29990\n29991\n29992\n29993\n29994\n29995\n29996\n29997\n29998\n29999'
\ No newline at end of file
diff --git a/.venv/lib/python3.12/site-packages/scipy/io/arff/tests/data/test11.arff b/.venv/lib/python3.12/site-packages/scipy/io/arff/tests/data/test11.arff
new file mode 100644
index 0000000000000000000000000000000000000000..fadfaee884e3e91cd59f691afd954a6a6d4042da
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/io/arff/tests/data/test11.arff
@@ -0,0 +1,11 @@
+@RELATION test11
+
+@ATTRIBUTE attr0	REAL
+@ATTRIBUTE attr1 	REAL
+@ATTRIBUTE attr2 	REAL
+@ATTRIBUTE attr3	REAL
+@ATTRIBUTE class 	{ class0, class1, class2, class3 }
+@DATA
+0.1, 0.2, 0.3, 0.4,class1
+-0.1, -0.2, -0.3, -0.4,class2
+1, 2, 3, 4,class3
diff --git a/.venv/lib/python3.12/site-packages/scipy/io/arff/tests/data/test2.arff b/.venv/lib/python3.12/site-packages/scipy/io/arff/tests/data/test2.arff
new file mode 100644
index 0000000000000000000000000000000000000000..30f0dbf91b078ef670868d5e7321f956a6a7a506
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/io/arff/tests/data/test2.arff
@@ -0,0 +1,15 @@
+@RELATION test2
+
+@ATTRIBUTE attr0	REAL
+@ATTRIBUTE attr1 	real
+@ATTRIBUTE attr2 	integer
+@ATTRIBUTE attr3	Integer
+@ATTRIBUTE attr4 	Numeric
+@ATTRIBUTE attr5	numeric
+@ATTRIBUTE attr6 	string
+@ATTRIBUTE attr7 	STRING
+@ATTRIBUTE attr8 	{bla}
+@ATTRIBUTE attr9 	{bla, bla}
+
+@DATA
+0.1, 0.2, 0.3, 0.4,class1
diff --git a/.venv/lib/python3.12/site-packages/scipy/io/arff/tests/data/test3.arff b/.venv/lib/python3.12/site-packages/scipy/io/arff/tests/data/test3.arff
new file mode 100644
index 0000000000000000000000000000000000000000..23da3b30967fcc95d70883f70be9ef6e39d577fa
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/io/arff/tests/data/test3.arff
@@ -0,0 +1,6 @@
+@RELATION test3
+
+@ATTRIBUTE attr0	crap
+
+@DATA
+0.1, 0.2, 0.3, 0.4,class1
diff --git a/.venv/lib/python3.12/site-packages/scipy/io/arff/tests/data/test4.arff b/.venv/lib/python3.12/site-packages/scipy/io/arff/tests/data/test4.arff
new file mode 100644
index 0000000000000000000000000000000000000000..bf5f99ca89375fbd980185fd25711901f23ff844
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/io/arff/tests/data/test4.arff
@@ -0,0 +1,11 @@
+@RELATION test5
+
+@ATTRIBUTE attr0	REAL
+@ATTRIBUTE attr1 	REAL
+@ATTRIBUTE attr2 	REAL
+@ATTRIBUTE attr3	REAL
+@ATTRIBUTE class 	{class0, class1, class2, class3}
+@DATA
+0.1, 0.2, 0.3, 0.4,class1
+-0.1, -0.2, -0.3, -0.4,class2
+1, 2, 3, 4,class3
diff --git a/.venv/lib/python3.12/site-packages/scipy/io/arff/tests/data/test5.arff b/.venv/lib/python3.12/site-packages/scipy/io/arff/tests/data/test5.arff
new file mode 100644
index 0000000000000000000000000000000000000000..0075daf05e7792e80dcd565e791ce40e4dd49e85
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/io/arff/tests/data/test5.arff
@@ -0,0 +1,26 @@
+@RELATION test4
+
+@ATTRIBUTE attr0	REAL
+@ATTRIBUTE attr1 	REAL
+@ATTRIBUTE attr2 	REAL
+@ATTRIBUTE attr3	REAL
+@ATTRIBUTE class 	{class0, class1, class2, class3}
+
+@DATA
+
+% lsdflkjhaksjdhf
+
+% lsdflkjhaksjdhf
+
+0.1, 0.2, 0.3, 0.4,class1
+% laksjdhf
+
+% lsdflkjhaksjdhf
+-0.1, -0.2, -0.3, -0.4,class2
+
+% lsdflkjhaksjdhf
+% lsdflkjhaksjdhf
+
+% lsdflkjhaksjdhf
+
+1, 2, 3, 4,class3
diff --git a/.venv/lib/python3.12/site-packages/scipy/io/arff/tests/data/test6.arff b/.venv/lib/python3.12/site-packages/scipy/io/arff/tests/data/test6.arff
new file mode 100644
index 0000000000000000000000000000000000000000..b63280b03aef8e0553a83fbf96692d280a3f86b7
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/io/arff/tests/data/test6.arff
@@ -0,0 +1,12 @@
+@RELATION test6
+
+@ATTRIBUTE attr0	REAL
+@ATTRIBUTE attr1 	REAL
+@ATTRIBUTE attr2 	REAL
+@ATTRIBUTE attr3	REAL
+@ATTRIBUTE class 	{C}
+
+@DATA
+0.1, 0.2, 0.3, 0.4,C
+-0.1, -0.2, -0.3, -0.4,C
+1, 2, 3, 4,C
diff --git a/.venv/lib/python3.12/site-packages/scipy/io/arff/tests/data/test7.arff b/.venv/lib/python3.12/site-packages/scipy/io/arff/tests/data/test7.arff
new file mode 100644
index 0000000000000000000000000000000000000000..38ef6c9a7a10afb10caa5913687ea3636ab1d38e
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/io/arff/tests/data/test7.arff
@@ -0,0 +1,15 @@
+@RELATION test7
+
+@ATTRIBUTE attr_year	DATE yyyy
+@ATTRIBUTE attr_month	DATE yyyy-MM
+@ATTRIBUTE attr_date	DATE yyyy-MM-dd
+@ATTRIBUTE attr_datetime_local	DATE "yyyy-MM-dd HH:mm"
+@ATTRIBUTE attr_datetime_missing	DATE "yyyy-MM-dd HH:mm"
+
+@DATA
+1999,1999-01,1999-01-31,"1999-01-31 00:01",?
+2004,2004-12,2004-12-01,"2004-12-01 23:59","2004-12-01 23:59"
+1817,1817-04,1817-04-28,"1817-04-28 13:00",?
+2100,2100-09,2100-09-10,"2100-09-10 12:00",?
+2013,2013-11,2013-11-30,"2013-11-30 04:55","2013-11-30 04:55"
+1631,1631-10,1631-10-15,"1631-10-15 20:04","1631-10-15 20:04"
\ No newline at end of file
diff --git a/.venv/lib/python3.12/site-packages/scipy/io/arff/tests/data/test8.arff b/.venv/lib/python3.12/site-packages/scipy/io/arff/tests/data/test8.arff
new file mode 100644
index 0000000000000000000000000000000000000000..776deb4c9e7550eafdb26d16826f5651da37ef12
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/io/arff/tests/data/test8.arff
@@ -0,0 +1,12 @@
+@RELATION test8
+
+@ATTRIBUTE attr_datetime_utc	DATE "yyyy-MM-dd HH:mm Z"
+@ATTRIBUTE attr_datetime_full	DATE "yy-MM-dd HH:mm:ss z"
+
+@DATA
+"1999-01-31 00:01 UTC","99-01-31 00:01:08 +0430"
+"2004-12-01 23:59 UTC","04-12-01 23:59:59 -0800"
+"1817-04-28 13:00 UTC","17-04-28 13:00:33 +1000"
+"2100-09-10 12:00 UTC","21-09-10 12:00:21 -0300"
+"2013-11-30 04:55 UTC","13-11-30 04:55:48 -1100"
+"1631-10-15 20:04 UTC","31-10-15 20:04:10 +0000"
\ No newline at end of file
diff --git a/.venv/lib/python3.12/site-packages/scipy/io/arff/tests/data/test9.arff b/.venv/lib/python3.12/site-packages/scipy/io/arff/tests/data/test9.arff
new file mode 100644
index 0000000000000000000000000000000000000000..b3f97e32a3fd4909a3f9cbf8d5d2e8d250f8dbad
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/io/arff/tests/data/test9.arff
@@ -0,0 +1,14 @@
+@RELATION test9
+
+@ATTRIBUTE attr_date_number	    RELATIONAL
+	@ATTRIBUTE attr_date	DATE "yyyy-MM-dd"
+	@ATTRIBUTE attr_number	INTEGER
+@END attr_date_number
+
+@DATA
+"1999-01-31	1\n1935-11-27	10"
+"2004-12-01	2\n1942-08-13	20"
+"1817-04-28	3"
+"2100-09-10	4\n1957-04-17	40\n1721-01-14	400"
+"2013-11-30	5"
+"1631-10-15	6"
\ No newline at end of file
diff --git a/.venv/lib/python3.12/site-packages/scipy/io/arff/tests/test_arffread.py b/.venv/lib/python3.12/site-packages/scipy/io/arff/tests/test_arffread.py
new file mode 100644
index 0000000000000000000000000000000000000000..b8882e73bbae7b6a423638d87255bdfae77797a9
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/io/arff/tests/test_arffread.py
@@ -0,0 +1,421 @@
+import datetime
+import os
+import sys
+from os.path import join as pjoin
+
+from io import StringIO
+
+import numpy as np
+
+from numpy.testing import (assert_array_almost_equal,
+                           assert_array_equal, assert_equal, assert_)
+from pytest import raises as assert_raises
+
+from scipy.io.arff import loadarff
+from scipy.io.arff._arffread import read_header, ParseArffError
+
+
+data_path = pjoin(os.path.dirname(__file__), 'data')
+
+test1 = pjoin(data_path, 'test1.arff')
+test2 = pjoin(data_path, 'test2.arff')
+test3 = pjoin(data_path, 'test3.arff')
+
+test4 = pjoin(data_path, 'test4.arff')
+test5 = pjoin(data_path, 'test5.arff')
+test6 = pjoin(data_path, 'test6.arff')
+test7 = pjoin(data_path, 'test7.arff')
+test8 = pjoin(data_path, 'test8.arff')
+test9 = pjoin(data_path, 'test9.arff')
+test10 = pjoin(data_path, 'test10.arff')
+test11 = pjoin(data_path, 'test11.arff')
+test_quoted_nominal = pjoin(data_path, 'quoted_nominal.arff')
+test_quoted_nominal_spaces = pjoin(data_path, 'quoted_nominal_spaces.arff')
+
+expect4_data = [(0.1, 0.2, 0.3, 0.4, 'class1'),
+                (-0.1, -0.2, -0.3, -0.4, 'class2'),
+                (1, 2, 3, 4, 'class3')]
+expected_types = ['numeric', 'numeric', 'numeric', 'numeric', 'nominal']
+
+missing = pjoin(data_path, 'missing.arff')
+expect_missing_raw = np.array([[1, 5], [2, 4], [np.nan, np.nan]])
+expect_missing = np.empty(3, [('yop', float), ('yap', float)])
+expect_missing['yop'] = expect_missing_raw[:, 0]
+expect_missing['yap'] = expect_missing_raw[:, 1]
+
+
+class TestData:
+    def test1(self):
+        # Parsing trivial file with nothing.
+        self._test(test4)
+
+    def test2(self):
+        # Parsing trivial file with some comments in the data section.
+        self._test(test5)
+
+    def test3(self):
+        # Parsing trivial file with nominal attribute of 1 character.
+        self._test(test6)
+
+    def test4(self):
+        # Parsing trivial file with trailing spaces in attribute declaration.
+        self._test(test11)
+
+    def _test(self, test_file):
+        data, meta = loadarff(test_file)
+        for i in range(len(data)):
+            for j in range(4):
+                assert_array_almost_equal(expect4_data[i][j], data[i][j])
+        assert_equal(meta.types(), expected_types)
+
+    def test_filelike(self):
+        # Test reading from file-like object (StringIO)
+        with open(test1) as f1:
+            data1, meta1 = loadarff(f1)
+        with open(test1) as f2:
+            data2, meta2 = loadarff(StringIO(f2.read()))
+        assert_(data1 == data2)
+        assert_(repr(meta1) == repr(meta2))
+
+    def test_path(self):
+        # Test reading from `pathlib.Path` object
+        from pathlib import Path
+
+        with open(test1) as f1:
+            data1, meta1 = loadarff(f1)
+
+        data2, meta2 = loadarff(Path(test1))
+
+        assert_(data1 == data2)
+        assert_(repr(meta1) == repr(meta2))
+
+
+class TestMissingData:
+    def test_missing(self):
+        data, meta = loadarff(missing)
+        for i in ['yop', 'yap']:
+            assert_array_almost_equal(data[i], expect_missing[i])
+
+
+class TestNoData:
+    def test_nodata(self):
+        # The file nodata.arff has no data in the @DATA section.
+        # Reading it should result in an array with length 0.
+        nodata_filename = os.path.join(data_path, 'nodata.arff')
+        data, meta = loadarff(nodata_filename)
+        if sys.byteorder == 'big':
+            end = '>'
+        else:
+            end = '<'
+        expected_dtype = np.dtype([('sepallength', f'{end}f8'),
+                                   ('sepalwidth', f'{end}f8'),
+                                   ('petallength', f'{end}f8'),
+                                   ('petalwidth', f'{end}f8'),
+                                   ('class', 'S15')])
+        assert_equal(data.dtype, expected_dtype)
+        assert_equal(data.size, 0)
+
+
+class TestHeader:
+    def test_type_parsing(self):
+        # Test parsing type of attribute from their value.
+        with open(test2) as ofile:
+            rel, attrs = read_header(ofile)
+
+        expected = ['numeric', 'numeric', 'numeric', 'numeric', 'numeric',
+                    'numeric', 'string', 'string', 'nominal', 'nominal']
+
+        for i in range(len(attrs)):
+            assert_(attrs[i].type_name == expected[i])
+
+    def test_badtype_parsing(self):
+        # Test parsing wrong type of attribute from their value.
+        def badtype_read():
+            with open(test3) as ofile:
+                _, _ = read_header(ofile)
+
+        assert_raises(ParseArffError, badtype_read)
+
+    def test_fullheader1(self):
+        # Parsing trivial header with nothing.
+        with open(test1) as ofile:
+            rel, attrs = read_header(ofile)
+
+        # Test relation
+        assert_(rel == 'test1')
+
+        # Test numerical attributes
+        assert_(len(attrs) == 5)
+        for i in range(4):
+            assert_(attrs[i].name == f'attr{i}')
+            assert_(attrs[i].type_name == 'numeric')
+
+        # Test nominal attribute
+        assert_(attrs[4].name == 'class')
+        assert_(attrs[4].values == ('class0', 'class1', 'class2', 'class3'))
+
+    def test_dateheader(self):
+        with open(test7) as ofile:
+            rel, attrs = read_header(ofile)
+
+        assert_(rel == 'test7')
+
+        assert_(len(attrs) == 5)
+
+        assert_(attrs[0].name == 'attr_year')
+        assert_(attrs[0].date_format == '%Y')
+
+        assert_(attrs[1].name == 'attr_month')
+        assert_(attrs[1].date_format == '%Y-%m')
+
+        assert_(attrs[2].name == 'attr_date')
+        assert_(attrs[2].date_format == '%Y-%m-%d')
+
+        assert_(attrs[3].name == 'attr_datetime_local')
+        assert_(attrs[3].date_format == '%Y-%m-%d %H:%M')
+
+        assert_(attrs[4].name == 'attr_datetime_missing')
+        assert_(attrs[4].date_format == '%Y-%m-%d %H:%M')
+
+    def test_dateheader_unsupported(self):
+        def read_dateheader_unsupported():
+            with open(test8) as ofile:
+                _, _ = read_header(ofile)
+
+        assert_raises(ValueError, read_dateheader_unsupported)
+
+
+class TestDateAttribute:
+    def setup_method(self):
+        self.data, self.meta = loadarff(test7)
+
+    def test_year_attribute(self):
+        expected = np.array([
+            '1999',
+            '2004',
+            '1817',
+            '2100',
+            '2013',
+            '1631'
+        ], dtype='datetime64[Y]')
+
+        assert_array_equal(self.data["attr_year"], expected)
+
+    def test_month_attribute(self):
+        expected = np.array([
+            '1999-01',
+            '2004-12',
+            '1817-04',
+            '2100-09',
+            '2013-11',
+            '1631-10'
+        ], dtype='datetime64[M]')
+
+        assert_array_equal(self.data["attr_month"], expected)
+
+    def test_date_attribute(self):
+        expected = np.array([
+            '1999-01-31',
+            '2004-12-01',
+            '1817-04-28',
+            '2100-09-10',
+            '2013-11-30',
+            '1631-10-15'
+        ], dtype='datetime64[D]')
+
+        assert_array_equal(self.data["attr_date"], expected)
+
+    def test_datetime_local_attribute(self):
+        expected = np.array([
+            datetime.datetime(year=1999, month=1, day=31, hour=0, minute=1),
+            datetime.datetime(year=2004, month=12, day=1, hour=23, minute=59),
+            datetime.datetime(year=1817, month=4, day=28, hour=13, minute=0),
+            datetime.datetime(year=2100, month=9, day=10, hour=12, minute=0),
+            datetime.datetime(year=2013, month=11, day=30, hour=4, minute=55),
+            datetime.datetime(year=1631, month=10, day=15, hour=20, minute=4)
+        ], dtype='datetime64[m]')
+
+        assert_array_equal(self.data["attr_datetime_local"], expected)
+
+    def test_datetime_missing(self):
+        expected = np.array([
+            'nat',
+            '2004-12-01T23:59',
+            'nat',
+            'nat',
+            '2013-11-30T04:55',
+            '1631-10-15T20:04'
+        ], dtype='datetime64[m]')
+
+        assert_array_equal(self.data["attr_datetime_missing"], expected)
+
+    def test_datetime_timezone(self):
+        assert_raises(ParseArffError, loadarff, test8)
+
+
+class TestRelationalAttribute:
+    def setup_method(self):
+        self.data, self.meta = loadarff(test9)
+
+    def test_attributes(self):
+        assert_equal(len(self.meta._attributes), 1)
+
+        relational = list(self.meta._attributes.values())[0]
+
+        assert_equal(relational.name, 'attr_date_number')
+        assert_equal(relational.type_name, 'relational')
+        assert_equal(len(relational.attributes), 2)
+        assert_equal(relational.attributes[0].name,
+                     'attr_date')
+        assert_equal(relational.attributes[0].type_name,
+                     'date')
+        assert_equal(relational.attributes[1].name,
+                     'attr_number')
+        assert_equal(relational.attributes[1].type_name,
+                     'numeric')
+
+    def test_data(self):
+        dtype_instance = [('attr_date', 'datetime64[D]'),
+                          ('attr_number', np.float64)]
+
+        expected = [
+            np.array([('1999-01-31', 1), ('1935-11-27', 10)],
+                     dtype=dtype_instance),
+            np.array([('2004-12-01', 2), ('1942-08-13', 20)],
+                     dtype=dtype_instance),
+            np.array([('1817-04-28', 3)],
+                     dtype=dtype_instance),
+            np.array([('2100-09-10', 4), ('1957-04-17', 40),
+                      ('1721-01-14', 400)],
+                     dtype=dtype_instance),
+            np.array([('2013-11-30', 5)],
+                     dtype=dtype_instance),
+            np.array([('1631-10-15', 6)],
+                     dtype=dtype_instance)
+        ]
+
+        for i in range(len(self.data["attr_date_number"])):
+            assert_array_equal(self.data["attr_date_number"][i],
+                               expected[i])
+
+
+class TestRelationalAttributeLong:
+    def setup_method(self):
+        self.data, self.meta = loadarff(test10)
+
+    def test_attributes(self):
+        assert_equal(len(self.meta._attributes), 1)
+
+        relational = list(self.meta._attributes.values())[0]
+
+        assert_equal(relational.name, 'attr_relational')
+        assert_equal(relational.type_name, 'relational')
+        assert_equal(len(relational.attributes), 1)
+        assert_equal(relational.attributes[0].name,
+                     'attr_number')
+        assert_equal(relational.attributes[0].type_name, 'numeric')
+
+    def test_data(self):
+        dtype_instance = [('attr_number', np.float64)]
+
+        expected = np.array([(n,) for n in range(30000)],
+                            dtype=dtype_instance)
+
+        assert_array_equal(self.data["attr_relational"][0],
+                           expected)
+
+
+class TestQuotedNominal:
+    """
+    Regression test for issue #10232:
+
+    Exception in loadarff with quoted nominal attributes.
+    """
+
+    def setup_method(self):
+        self.data, self.meta = loadarff(test_quoted_nominal)
+
+    def test_attributes(self):
+        assert_equal(len(self.meta._attributes), 2)
+
+        age, smoker = self.meta._attributes.values()
+
+        assert_equal(age.name, 'age')
+        assert_equal(age.type_name, 'numeric')
+        assert_equal(smoker.name, 'smoker')
+        assert_equal(smoker.type_name, 'nominal')
+        assert_equal(smoker.values, ['yes', 'no'])
+
+    def test_data(self):
+
+        age_dtype_instance = np.float64
+        smoker_dtype_instance = '' (big endian)
+
+'''
+import sys
+
+__all__ = [
+    'aliases', 'native_code', 'swapped_code',
+    'sys_is_le', 'to_numpy_code'
+]
+
+sys_is_le = sys.byteorder == 'little'
+native_code = sys_is_le and '<' or '>'
+swapped_code = sys_is_le and '>' or '<'
+
+aliases = {'little': ('little', '<', 'l', 'le'),
+           'big': ('big', '>', 'b', 'be'),
+           'native': ('native', '='),
+           'swapped': ('swapped', 'S')}
+
+
+def to_numpy_code(code):
+    """
+    Convert various order codings to NumPy format.
+
+    Parameters
+    ----------
+    code : str
+        The code to convert. It is converted to lower case before parsing.
+        Legal values are:
+        'little', 'big', 'l', 'b', 'le', 'be', '<', '>', 'native', '=',
+        'swapped', 's'.
+
+    Returns
+    -------
+    out_code : {'<', '>'}
+        Here '<' is the numpy dtype code for little endian,
+        and '>' is the code for big endian.
+
+    Examples
+    --------
+    >>> import sys
+    >>> from scipy.io.matlab._byteordercodes import to_numpy_code
+    >>> sys_is_le = (sys.byteorder == 'little')
+    >>> sys_is_le
+    True
+    >>> to_numpy_code('big')
+    '>'
+    >>> to_numpy_code('little')
+    '<'
+    >>> nc = to_numpy_code('native')
+    >>> nc == '<' if sys_is_le else nc == '>'
+    True
+    >>> sc = to_numpy_code('swapped')
+    >>> sc == '>' if sys_is_le else sc == '<'
+    True
+
+    """
+    code = code.lower()
+    if code is None:
+        return native_code
+    if code in aliases['little']:
+        return '<'
+    elif code in aliases['big']:
+        return '>'
+    elif code in aliases['native']:
+        return native_code
+    elif code in aliases['swapped']:
+        return swapped_code
+    else:
+        raise ValueError(
+            f'We cannot handle byte order {code}')
diff --git a/.venv/lib/python3.12/site-packages/scipy/io/matlab/_mio.py b/.venv/lib/python3.12/site-packages/scipy/io/matlab/_mio.py
new file mode 100644
index 0000000000000000000000000000000000000000..984eb6f7062098869e69fb10452c5ae96d20d4ef
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/io/matlab/_mio.py
@@ -0,0 +1,397 @@
+"""
+Module for reading and writing matlab (TM) .mat files
+"""
+# Authors: Travis Oliphant, Matthew Brett
+
+import os
+import warnings
+
+from contextlib import contextmanager
+
+from ._miobase import _get_matfile_version, docfiller
+from ._mio4 import MatFile4Reader, MatFile4Writer
+from ._mio5 import MatFile5Reader, MatFile5Writer
+from scipy._lib.deprecation import _NoValue
+
+__all__ = ['loadmat', 'savemat', 'whosmat']
+
+
+@contextmanager
+def _open_file_context(file_like, appendmat, mode='rb'):
+    f, opened = _open_file(file_like, appendmat, mode)
+    try:
+        yield f
+    finally:
+        if opened:
+            f.close()
+
+
+def _open_file(file_like, appendmat, mode='rb'):
+    """
+    Open `file_like` and return as file-like object. First, check if object is
+    already file-like; if so, return it as-is. Otherwise, try to pass it
+    to open(). If that fails, and `file_like` is a string, and `appendmat` is true,
+    append '.mat' and try again.
+    """
+    reqs = {'read'} if set(mode) & set('r+') else set()
+    if set(mode) & set('wax+'):
+        reqs.add('write')
+    if reqs.issubset(dir(file_like)):
+        return file_like, False
+
+    try:
+        return open(file_like, mode), True
+    except OSError as e:
+        # Probably "not found"
+        if isinstance(file_like, str):
+            if appendmat and not file_like.endswith('.mat'):
+                file_like += '.mat'
+            return open(file_like, mode), True
+        else:
+            raise OSError(
+                'Reader needs file name or open file-like object'
+            ) from e
+
+
+def mat_reader_factory(file_name, appendmat=True, **kwargs):
+    """
+    Create reader for matlab .mat format files.
+
+    Returns
+    -------
+    matreader : MatFileReader object
+       Initialized instance of MatFileReader class matching the mat file
+       type detected in `filename`.
+    file_opened : bool
+       Whether the file was opened by this routine.
+
+    """
+    byte_stream, file_opened = _open_file(file_name, appendmat)
+    mjv, mnv = _get_matfile_version(byte_stream)
+    if mjv == 0:
+        return MatFile4Reader(byte_stream, **kwargs), file_opened
+    elif mjv == 1:
+        return MatFile5Reader(byte_stream, **kwargs), file_opened
+    elif mjv == 2:
+        raise NotImplementedError('Please use HDF reader for matlab v7.3 '
+                                  'files, e.g. h5py')
+    else:
+        raise TypeError(f'Did not recognize version {mjv}')
+
+
+def loadmat(file_name, mdict=None, appendmat=True, *, spmatrix=_NoValue, **kwargs):
+    """
+    Load MATLAB file.
+
+    Parameters
+    ----------
+    file_name : str
+        Name of the mat file (do not need .mat extension if
+        appendmat==True). Can also pass open file-like object.
+    mdict : dict, optional
+        Dictionary in which to insert matfile variables.
+    appendmat : bool, optional
+        True to append the .mat extension to the end of the given
+        filename, if not already present. Default is True.
+    spmatrix : bool, optional (default: True)
+        If ``True``, return sparse matrix. Otherwise return sparse array.
+        Format is `COO` for MatFile 4 and `CSC` for MatFile 5.
+        Only relevant for sparse variables.
+
+        .. deprecated:: 1.18.0
+            The default value for `spmatrix` is changing to False in v1.20.
+            That means the default return value will be a sparse array.
+            Unless you use * instead of @, ** for matrix power, or you depend
+            on 2D shapes from e.g. ``A.sum(axis=0)``, it may not matter to you.
+            See :ref:`Migration from spmatrix to sparray `.
+
+    **kwargs
+        The following aditional keyword arguments can be passed:
+
+        byte_order : str or None, optional
+            None by default, implying byte order guessed from mat
+            file. Otherwise can be one of ('native', '=', 'little', '<',
+            'BIG', '>').
+        mat_dtype : bool, optional
+            If True, return arrays in same dtype as would be loaded into
+            MATLAB (instead of the dtype with which they are saved).
+        squeeze_me : bool, optional
+            Whether to squeeze unit matrix dimensions or not.
+        chars_as_strings : bool, optional
+            Whether to convert char arrays to string arrays.
+        matlab_compatible : bool, optional
+            Returns matrices as would be loaded by MATLAB (implies
+            squeeze_me=False, chars_as_strings=False, mat_dtype=True,
+            struct_as_record=True).
+        struct_as_record : bool, optional
+            Whether to load MATLAB structs as NumPy record arrays, or as
+            old-style NumPy arrays with dtype=object. Setting this flag to
+            False replicates the behavior of scipy version 0.7.x (returning
+            NumPy object arrays). The default setting is True, because it
+            allows easier round-trip load and save of MATLAB files.
+        verify_compressed_data_integrity : bool, optional
+            Whether the length of compressed sequences in the MATLAB file
+            should be checked, to ensure that they are not longer than we expect.
+            It is advisable to enable this (the default) because overlong
+            compressed sequences in MATLAB files generally indicate that the
+            files have experienced some sort of corruption.
+        variable_names : None or sequence
+            If None (the default) - read all variables in file. Otherwise,
+            `variable_names` should be a sequence of strings, giving names of the
+            MATLAB variables to read from the file. The reader will skip any
+            variable with a name not in this sequence, possibly saving some read
+            processing.
+        simplify_cells : False, optional
+            If True, return a simplified dict structure (which is useful if the mat
+            file contains cell arrays). Note that this only affects the structure
+            of the result and not its contents (which is identical for both output
+            structures). If True, this automatically sets `struct_as_record` to
+            False and `squeeze_me` to True, which is required to simplify cells.
+        uint16_codec : str, optional
+            The codec to use for decoding characters, which are stored as uint16
+            values. The default uses the system encoding, but this can be manually
+            set to other values such as 'ascii', 'latin1', and 'utf-8'. This
+            parameter is relevant only for files stored as v6 and above, and not
+            for files stored as v4.
+
+    Returns
+    -------
+    mat_dict : dict
+       dictionary with variable names as keys, and loaded matrices as values.
+
+    Notes
+    -----
+    v4 (Level 1.0), v6 and v7 to 7.2 matfiles are supported.
+
+    You will need an HDF5 Python library to read MATLAB 7.3 format mat
+    files. Because SciPy does not supply one, we do not implement the
+    HDF5 / 7.3 interface here.
+
+    Examples
+    --------
+    >>> from os.path import dirname, join as pjoin
+    >>> import scipy.io as sio
+
+    Get the filename for an example .mat file from the tests/data directory.
+
+    >>> data_dir = pjoin(dirname(sio.__file__), 'matlab', 'tests', 'data')
+    >>> mat_fname = pjoin(data_dir, 'testdouble_7.4_GLNX86.mat')
+
+    Load the .mat file contents.
+
+    >>> mat_contents = sio.loadmat(mat_fname, spmatrix=False)
+
+    The result is a dictionary, one key/value pair for each variable:
+
+    >>> sorted(mat_contents.keys())
+    ['__globals__', '__header__', '__version__', 'testdouble']
+    >>> mat_contents['testdouble']
+    array([[0.        , 0.78539816, 1.57079633, 2.35619449, 3.14159265,
+            3.92699082, 4.71238898, 5.49778714, 6.28318531]])
+
+    By default SciPy reads MATLAB structs as structured NumPy arrays where the
+    dtype fields are of type `object` and the names correspond to the MATLAB
+    struct field names. This can be disabled by setting the optional argument
+    `struct_as_record=False`.
+
+    Get the filename for an example .mat file that contains a MATLAB struct
+    called `teststruct` and load the contents.
+
+    >>> matstruct_fname = pjoin(data_dir, 'teststruct_7.4_GLNX86.mat')
+    >>> matstruct_contents = sio.loadmat(matstruct_fname)
+    >>> teststruct = matstruct_contents['teststruct']
+    >>> teststruct.dtype
+    dtype([('stringfield', 'O'), ('doublefield', 'O'), ('complexfield', 'O')])
+
+    The size of the structured array is the size of the MATLAB struct, not the
+    number of elements in any particular field. The shape defaults to 2-D
+    unless the optional argument `squeeze_me=True`, in which case all length 1
+    dimensions are removed.
+
+    >>> teststruct.size
+    1
+    >>> teststruct.shape
+    (1, 1)
+
+    Get the 'stringfield' of the first element in the MATLAB struct.
+
+    >>> teststruct[0, 0]['stringfield']
+    array(['Rats live on no evil star.'],
+      dtype='>> teststruct['doublefield'][0, 0]
+    array([[ 1.41421356,  2.71828183,  3.14159265]])
+
+    Load the MATLAB struct, squeezing out length 1 dimensions, and get the item
+    from the 'complexfield'.
+
+    >>> matstruct_squeezed = sio.loadmat(matstruct_fname, squeeze_me=True)
+    >>> matstruct_squeezed['teststruct'].shape
+    ()
+    >>> matstruct_squeezed['teststruct']['complexfield'].shape
+    ()
+    >>> matstruct_squeezed['teststruct']['complexfield'].item()
+    array([ 1.41421356+1.41421356j,  2.71828183+2.71828183j,
+        3.14159265+3.14159265j])
+    """
+    variable_names = kwargs.pop('variable_names', None)
+    with _open_file_context(file_name, appendmat) as f:
+        MR, _ = mat_reader_factory(f, **kwargs)
+        matfile_dict = MR.get_variables(variable_names)
+
+    warn_msg = """The default value for `spmatrix` is changing to `False` in v1.20.
+        That means the default return type will be a sparse array.
+        Unless you use * instead of @, ** for matrix power, or you depend
+        on 2D shapes from e.g. `A.sum(axis=0)` it may not matter to you.
+        See the spmatrix to sparray migration guide for details.
+        https://docs.scipy.org/doc/scipy/reference/sparse.migration_to_sparray.html
+        """
+
+    from scipy.sparse import issparse, coo_matrix, csc_matrix, coo_array, csc_array
+    for name, var in list(matfile_dict.items()):
+        if issparse(var):
+            if spmatrix is _NoValue:
+                prefixes = (os.path.dirname(__file__),)
+                warnings.warn(warn_msg, DeprecationWarning, skip_file_prefixes=prefixes)
+                spmatrix = True
+            if spmatrix:
+                fmt_matrix = coo_matrix if var.format == "coo" else csc_matrix
+            else:
+                fmt_matrix = coo_array if var.format == "coo" else csc_array
+            matfile_dict[name] = fmt_matrix(var)
+
+    if mdict is not None:
+        mdict.update(matfile_dict)
+    else:
+        mdict = matfile_dict
+
+    return mdict
+
+
+def savemat(file_name, mdict,
+            appendmat=True,
+            format='5',
+            long_field_names=False,
+            do_compression=False,
+            oned_as='row'):
+    """
+    Save a dictionary of names and arrays into a MATLAB-style .mat file.
+
+    This saves the array objects in the given dictionary to a MATLAB-
+    style .mat file.
+
+    Parameters
+    ----------
+    file_name : str or file-like object
+        Name of the .mat file (.mat extension not needed if ``appendmat ==
+        True``).
+        Can also pass open file_like object.
+    mdict : dict
+        Dictionary from which to save matfile variables. Note that if this dict
+        has a key starting with ``_`` or a sub-dict has a key starting with ``_``
+        or a digit, these key's items will not be saved in the mat file and
+        `MatWriteWarning` will be issued.
+    appendmat : bool, optional
+        True (the default) to append the .mat extension to the end of the
+        given filename, if not already present.
+    format : {'5', '4'}, string, optional
+        '5' (the default) for MATLAB 5 and up (to 7.2),
+        '4' for MATLAB 4 .mat files.
+    long_field_names : bool, optional
+        False (the default) - maximum field name length in a structure is
+        31 characters which is the documented maximum length.
+        True - maximum field name length in a structure is 63 characters
+        which works for MATLAB 7.6+.
+    do_compression : bool, optional
+        Whether or not to compress matrices on write. Default is False.
+    oned_as : {'row', 'column'}, optional
+        If 'column', write 1-D NumPy arrays as column vectors.
+        If 'row', write 1-D NumPy arrays as row vectors.
+
+    Examples
+    --------
+    >>> from scipy.io import savemat
+    >>> import numpy as np
+    >>> a = np.arange(20)
+    >>> mdic = {"a": a, "label": "experiment"}
+    >>> mdic
+    {'a': array([ 0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12, 13, 14, 15, 16,
+        17, 18, 19]),
+    'label': 'experiment'}
+    >>> savemat("matlab_matrix.mat", mdic)
+    """
+    with _open_file_context(file_name, appendmat, 'wb') as file_stream:
+        if format == '4':
+            if long_field_names:
+                message = "Long field names are not available for version 4 files"
+                raise ValueError(message)
+            MW = MatFile4Writer(file_stream, oned_as)
+        elif format == '5':
+            MW = MatFile5Writer(file_stream,
+                                do_compression=do_compression,
+                                unicode_strings=True,
+                                long_field_names=long_field_names,
+                                oned_as=oned_as)
+        else:
+            raise ValueError("Format should be '4' or '5'")
+        MW.put_variables(mdict)
+
+
+@docfiller
+def whosmat(file_name, appendmat=True, **kwargs):
+    """
+    List variables inside a MATLAB file.
+
+    Parameters
+    ----------
+    %(file_arg)s
+    %(append_arg)s
+    %(load_args)s
+    %(struct_arg)s
+
+    Returns
+    -------
+    variables : list of tuples
+        A list of tuples, where each tuple holds the matrix name (a string),
+        its shape (tuple of ints), and its data class (a string).
+        Possible data classes are: int8, uint8, int16, uint16, int32, uint32,
+        int64, uint64, single, double, cell, struct, object, char, sparse,
+        function, opaque, logical, unknown.
+
+    Notes
+    -----
+    v4 (Level 1.0), v6 and v7 to 7.2 matfiles are supported.
+
+    You will need an HDF5 python library to read matlab 7.3 format mat
+    files (e.g. h5py). Because SciPy does not supply one, we do not implement the
+    HDF5 / 7.3 interface here.
+
+    .. versionadded:: 0.12.0
+
+    Examples
+    --------
+    >>> from io import BytesIO
+    >>> import numpy as np
+    >>> from scipy.io import savemat, whosmat
+
+    Create some arrays, and use `savemat` to write them to a ``BytesIO``
+    instance.
+
+    >>> a = np.array([[10, 20, 30], [11, 21, 31]], dtype=np.int32)
+    >>> b = np.geomspace(1, 10, 5)
+    >>> f = BytesIO()
+    >>> savemat(f, {'a': a, 'b': b})
+
+    Use `whosmat` to inspect ``f``.  Each tuple in the output list gives
+    the name, shape and data type of the array in ``f``.
+
+    >>> whosmat(f)
+    [('a', (2, 3), 'int32'), ('b', (1, 5), 'double')]
+
+    """  # numpydoc ignore=PR01,PR02
+    with _open_file_context(file_name, appendmat) as f:
+        ML, file_opened = mat_reader_factory(f, **kwargs)
+        variables = ML.list_variables()
+    return variables
diff --git a/.venv/lib/python3.12/site-packages/scipy/io/matlab/_mio4.py b/.venv/lib/python3.12/site-packages/scipy/io/matlab/_mio4.py
new file mode 100644
index 0000000000000000000000000000000000000000..b108386d110e6062d088498259e849603583eb94
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/io/matlab/_mio4.py
@@ -0,0 +1,632 @@
+''' Classes for read / write of matlab (TM) 4 files
+'''
+import sys
+import warnings
+import math
+from operator import mul
+
+import numpy as np
+
+import scipy.sparse
+
+from ._miobase import (MatFileReader, docfiller, matdims, read_dtype,
+                      convert_dtypes, arr_to_chars, arr_dtype_number)
+
+from ._mio_utils import squeeze_element, chars_to_strings
+from functools import reduce
+
+
+__all__ = [
+    'MatFile4Reader', 'MatFile4Writer', 'SYS_LITTLE_ENDIAN',
+    'VarHeader4', 'VarReader4', 'VarWriter4', 'arr_to_2d', 'mclass_info',
+    'mdtypes_template', 'miDOUBLE', 'miINT16', 'miINT32', 'miSINGLE',
+    'miUINT16', 'miUINT8', 'mxCHAR_CLASS', 'mxFULL_CLASS', 'mxSPARSE_CLASS',
+    'np_to_mtypes', 'order_codes'
+]
+
+
+SYS_LITTLE_ENDIAN = sys.byteorder == 'little'
+
+miDOUBLE = 0
+miSINGLE = 1
+miINT32 = 2
+miINT16 = 3
+miUINT16 = 4
+miUINT8 = 5
+
+mdtypes_template = {
+    miDOUBLE: 'f8',
+    miSINGLE: 'f4',
+    miINT32: 'i4',
+    miINT16: 'i2',
+    miUINT16: 'u2',
+    miUINT8: 'u1',
+    'header': [('mopt', 'i4'),
+               ('mrows', 'i4'),
+               ('ncols', 'i4'),
+               ('imagf', 'i4'),
+               ('namlen', 'i4')],
+    'U1': 'U1',
+    }
+
+np_to_mtypes = {
+    'f8': miDOUBLE,
+    'c32': miDOUBLE,
+    'c24': miDOUBLE,
+    'c16': miDOUBLE,
+    'f4': miSINGLE,
+    'c8': miSINGLE,
+    'i4': miINT32,
+    'i2': miINT16,
+    'u2': miUINT16,
+    'u1': miUINT8,
+    'S1': miUINT8,
+    }
+
+# matrix classes
+mxFULL_CLASS = 0
+mxCHAR_CLASS = 1
+mxSPARSE_CLASS = 2
+
+order_codes = {
+    0: '<',
+    1: '>',
+    2: 'VAX D-float',  # !
+    3: 'VAX G-float',
+    4: 'Cray',  # !!
+    }
+
+mclass_info = {
+    mxFULL_CLASS: 'double',
+    mxCHAR_CLASS: 'char',
+    mxSPARSE_CLASS: 'sparse',
+    }
+
+
+_MAX_INTP = np.iinfo(np.intp).max
+
+
+class VarHeader4:
+    # Mat4 variables never logical or global
+    is_logical = False
+    is_global = False
+
+    def __init__(self,
+                 name,
+                 dtype,
+                 mclass,
+                 dims,
+                 is_complex):
+        self.name = name
+        self.dtype = dtype
+        self.mclass = mclass
+        self.dims = dims
+        self.is_complex = is_complex
+
+
+class VarReader4:
+    ''' Class to read matlab 4 variables '''
+
+    def __init__(self, file_reader):
+        self.file_reader = file_reader
+        self.mat_stream = file_reader.mat_stream
+        self.dtypes = file_reader.dtypes
+        self.chars_as_strings = file_reader.chars_as_strings
+        self.squeeze_me = file_reader.squeeze_me
+
+    def read_header(self):
+        ''' Read and return header for variable '''
+        data = read_dtype(self.mat_stream, self.dtypes['header'])
+        name = self.mat_stream.read(int(data['namlen'])).strip(b'\x00')
+        if data['mopt'] < 0 or data['mopt'] > 5000:
+            raise ValueError('Mat 4 mopt wrong format, byteswapping problem?')
+        M, rest = divmod(data['mopt'], 1000)  # order code
+        if M not in (0, 1):
+            warnings.warn(f"We do not support byte ordering '{order_codes[M]}';"
+                          " returned data may be corrupt",
+                          UserWarning, stacklevel=3)
+        O, rest = divmod(rest, 100)  # unused, should be 0
+        if O != 0:
+            raise ValueError('O in MOPT integer should be 0, wrong format?')
+        P, rest = divmod(rest, 10)  # data type code e.g miDOUBLE (see above)
+        T = rest  # matrix type code e.g., mxFULL_CLASS (see above)
+        dims = (data['mrows'], data['ncols'])
+        is_complex = data['imagf'] == 1
+        dtype = self.dtypes[P]
+        return VarHeader4(
+            name,
+            dtype,
+            T,
+            dims,
+            is_complex)
+
+    def array_from_header(self, hdr, process=True):
+        mclass = hdr.mclass
+        if mclass == mxFULL_CLASS:
+            arr = self.read_full_array(hdr)
+        elif mclass == mxCHAR_CLASS:
+            arr = self.read_char_array(hdr)
+            if process and self.chars_as_strings:
+                arr = chars_to_strings(arr)
+        elif mclass == mxSPARSE_CLASS:
+            # no current processing (below) makes sense for sparse
+            return self.read_sparse_array(hdr)
+        else:
+            raise TypeError(f'No reader for class code {mclass}')
+        if process and self.squeeze_me:
+            return squeeze_element(arr)
+        return arr
+
+    def read_sub_array(self, hdr, copy=True):
+        ''' Mat4 read using header `hdr` dtype and dims
+
+        Parameters
+        ----------
+        hdr : object
+           object with attributes ``dtype``, ``dims``. dtype is assumed to be
+           the correct endianness
+        copy : bool, optional
+           copies array before return if True (default True)
+           (buffer is usually read only)
+
+        Returns
+        -------
+        arr : ndarray
+            of dtype given by `hdr` ``dtype`` and shape given by `hdr` ``dims``
+        '''
+        dt = hdr.dtype
+        # Fast product for large (>2GB) arrays.
+        num_bytes = reduce(mul, hdr.dims, np.int64(dt.itemsize))
+        if num_bytes > _MAX_INTP:
+            raise ValueError(
+                f"Variable '{hdr.name.decode('latin1')}' has byte length "
+                f"longer than largest possible NumPy array on this platform.")
+        buffer = self.mat_stream.read(num_bytes)
+        if len(buffer) != num_bytes:
+            raise ValueError(
+                f"Not enough bytes to read matrix "
+                f"'{hdr.name.decode('latin1')}'; is this a badly-formed file? "
+                f"Consider listing matrices with `whosmat` and loading named "
+                f"matrices with `variable_names` kwarg to `loadmat`")
+        arr = np.ndarray(shape=hdr.dims,
+                         dtype=dt,
+                         buffer=buffer,
+                         order='F')
+        if copy:
+            arr = arr.copy()
+        return arr
+
+    def read_full_array(self, hdr):
+        ''' Full (rather than sparse) matrix getter
+
+        Read matrix (array) can be real or complex
+
+        Parameters
+        ----------
+        hdr : ``VarHeader4`` instance
+
+        Returns
+        -------
+        arr : ndarray
+            complex array if ``hdr.is_complex`` is True, otherwise a real
+            numeric array
+        '''
+        if hdr.is_complex:
+            # avoid array copy to save memory
+            res = self.read_sub_array(hdr, copy=False)
+            res_j = self.read_sub_array(hdr, copy=False)
+            return res + (res_j * 1j)
+        return self.read_sub_array(hdr)
+
+    def read_char_array(self, hdr):
+        ''' latin-1 text matrix (char matrix) reader
+
+        Parameters
+        ----------
+        hdr : ``VarHeader4`` instance
+
+        Returns
+        -------
+        arr : ndarray
+            with dtype 'U1', shape given by `hdr` ``dims``
+        '''
+        arr = self.read_sub_array(hdr).astype(np.uint8)
+        S = arr.tobytes().decode('latin-1')
+        return np.ndarray(shape=hdr.dims,
+                          dtype=np.dtype('U1'),
+                          buffer=np.array(S)).copy()
+
+    def read_sparse_array(self, hdr):
+        ''' Read and return sparse matrix type
+
+        Parameters
+        ----------
+        hdr : ``VarHeader4`` instance
+
+        Returns
+        -------
+        arr : coo_array
+            with dtype ``float`` and shape read from the sparse array data
+
+        Notes
+        -----
+        MATLAB 4 real sparse arrays are saved in a N+1 by 3 array format, where
+        N is the number of non-zero values. Column 1 values [0:N] are the
+        (1-based) row indices of the each non-zero value, column 2 [0:N] are the
+        column indices, column 3 [0:N] are the (real) values. The last values
+        [-1,0:2] of the rows, column indices are shape[0] and shape[1]
+        respectively of the output matrix. The last value for the values column
+        is a padding 0. mrows and ncols values from the header give the shape of
+        the stored matrix, here [N+1, 3]. Complex data are saved as a 4 column
+        matrix, where the fourth column contains the imaginary component; the
+        last value is again 0. Complex sparse data do *not* have the header
+        ``imagf`` field set to True; the fact that the data are complex is only
+        detectable because there are 4 storage columns.
+        '''
+        res = self.read_sub_array(hdr)
+        tmp = res[:-1,:]
+        # All numbers are float64 in Matlab, but SciPy sparse expects int shape
+        dims = (int(res[-1,0]), int(res[-1,1]))
+        I = np.ascontiguousarray(tmp[:,0],dtype='intc')  # fixes byte order also
+        J = np.ascontiguousarray(tmp[:,1],dtype='intc')
+        I -= 1  # for 1-based indexing
+        J -= 1
+        if res.shape[1] == 3:
+            V = np.ascontiguousarray(tmp[:,2],dtype='float')
+        else:
+            V = np.ascontiguousarray(tmp[:,2],dtype='complex')
+            V.imag = tmp[:,3]
+        return scipy.sparse.coo_array((V,(I,J)), dims)
+
+    def shape_from_header(self, hdr):
+        '''Read the shape of the array described by the header.
+        The file position after this call is unspecified.
+        '''
+        mclass = hdr.mclass
+        if mclass == mxFULL_CLASS:
+            shape = tuple(map(int, hdr.dims))
+        elif mclass == mxCHAR_CLASS:
+            shape = tuple(map(int, hdr.dims))
+            if self.chars_as_strings:
+                shape = shape[:-1]
+        elif mclass == mxSPARSE_CLASS:
+            dt = hdr.dtype
+            dims = hdr.dims
+
+            if not (len(dims) == 2 and dims[0] >= 1 and dims[1] >= 1):
+                return ()
+
+            # Read only the row and column counts
+            self.mat_stream.seek(dt.itemsize * (dims[0] - 1), 1)
+            rows = np.ndarray(shape=(), dtype=dt,
+                              buffer=self.mat_stream.read(dt.itemsize))
+            self.mat_stream.seek(dt.itemsize * (dims[0] - 1), 1)
+            cols = np.ndarray(shape=(), dtype=dt,
+                              buffer=self.mat_stream.read(dt.itemsize))
+
+            shape = (int(rows), int(cols))
+        else:
+            raise TypeError(f'No reader for class code {mclass}')
+
+        if self.squeeze_me:
+            shape = tuple([x for x in shape if x != 1])
+        return shape
+
+
+class MatFile4Reader(MatFileReader):
+    ''' Reader for Mat4 files '''
+    @docfiller
+    def __init__(self, mat_stream, *args, **kwargs):
+        ''' Initialize matlab 4 file reader
+
+    %(matstream_arg)s
+    %(load_args)s
+        '''
+        super().__init__(mat_stream, *args, **kwargs)
+        self._matrix_reader = None
+
+    def guess_byte_order(self):
+        self.mat_stream.seek(0)
+        mopt = read_dtype(self.mat_stream, np.dtype('i4'))
+        self.mat_stream.seek(0)
+        if mopt == 0:
+            return '<'
+        if mopt < 0 or mopt > 5000:
+            # Number must have been byteswapped
+            return SYS_LITTLE_ENDIAN and '>' or '<'
+        # Not byteswapped
+        return SYS_LITTLE_ENDIAN and '<' or '>'
+
+    def initialize_read(self):
+        ''' Run when beginning read of variables
+
+        Sets up readers from parameters in `self`
+        '''
+        self.dtypes = convert_dtypes(mdtypes_template, self.byte_order)
+        self._matrix_reader = VarReader4(self)
+
+    def read_var_header(self):
+        ''' Read and return header, next position
+
+        Parameters
+        ----------
+        None
+
+        Returns
+        -------
+        header : object
+           object that can be passed to self.read_var_array, and that
+           has attributes ``name`` and ``is_global``
+        next_position : int
+           position in stream of next variable
+        '''
+        hdr = self._matrix_reader.read_header()
+        # Fast product for large (>2GB) arrays.
+        remaining_bytes = reduce(mul, hdr.dims, np.int64(hdr.dtype.itemsize))
+        if hdr.is_complex and not hdr.mclass == mxSPARSE_CLASS:
+            remaining_bytes *= 2
+        next_position = self.mat_stream.tell() + remaining_bytes
+        return hdr, next_position
+
+    def read_var_array(self, header, process=True):
+        ''' Read array, given `header`
+
+        Parameters
+        ----------
+        header : header object
+           object with fields defining variable header
+        process : {True, False}, optional
+           If True, apply recursive post-processing during loading of array.
+
+        Returns
+        -------
+        arr : array
+           array with post-processing applied or not according to
+           `process`.
+        '''
+        return self._matrix_reader.array_from_header(header, process)
+
+    def get_variables(self, variable_names=None):
+        ''' get variables from stream as dictionary
+
+        Parameters
+        ----------
+        variable_names : None or str or sequence of str, optional
+            variable name, or sequence of variable names to get from Mat file /
+            file stream. If None, then get all variables in file.
+        '''
+        if isinstance(variable_names, str):
+            variable_names = [variable_names]
+        elif variable_names is not None:
+            variable_names = list(variable_names)
+        self.mat_stream.seek(0)
+        # set up variable reader
+        self.initialize_read()
+        mdict = {}
+        while not self.end_of_stream():
+            hdr, next_position = self.read_var_header()
+            name = 'None' if hdr.name is None else hdr.name.decode('latin1')
+            if variable_names is not None and name not in variable_names:
+                self.mat_stream.seek(next_position)
+                continue
+            mdict[name] = self.read_var_array(hdr)
+            self.mat_stream.seek(next_position)
+            if variable_names is not None:
+                variable_names.remove(name)
+                if len(variable_names) == 0:
+                    break
+        return mdict
+
+    def list_variables(self):
+        ''' list variables from stream '''
+        self.mat_stream.seek(0)
+        # set up variable reader
+        self.initialize_read()
+        vars = []
+        while not self.end_of_stream():
+            hdr, next_position = self.read_var_header()
+            name = 'None' if hdr.name is None else hdr.name.decode('latin1')
+            shape = self._matrix_reader.shape_from_header(hdr)
+            info = mclass_info.get(hdr.mclass, 'unknown')
+            vars.append((name, shape, info))
+
+            self.mat_stream.seek(next_position)
+        return vars
+
+
+def arr_to_2d(arr, oned_as='row'):
+    ''' Make ``arr`` exactly two dimensional
+
+    If `arr` has more than 2 dimensions, raise a ValueError
+
+    Parameters
+    ----------
+    arr : array
+    oned_as : {'row', 'column'}, optional
+       Whether to reshape 1-D vectors as row vectors or column vectors.
+       See documentation for ``matdims`` for more detail
+
+    Returns
+    -------
+    arr2d : array
+       2-D version of the array
+    '''
+    dims = matdims(arr, oned_as)
+    if len(dims) > 2:
+        raise ValueError('Matlab 4 files cannot save arrays with more than '
+                         '2 dimensions')
+    return arr.reshape(dims)
+
+
+class VarWriter4:
+    def __init__(self, file_writer):
+        self.file_stream = file_writer.file_stream
+        self.oned_as = file_writer.oned_as
+
+    def write_bytes(self, arr):
+        self.file_stream.write(arr.tobytes(order='F'))
+
+    def write_string(self, s):
+        self.file_stream.write(s)
+
+    def write_header(self, name, shape, P=miDOUBLE, T=mxFULL_CLASS, imagf=0):
+        ''' Write header for given data options
+
+        Parameters
+        ----------
+        name : str
+            name of variable
+        shape : sequence
+            Shape of array as it will be read in matlab
+        P : int, optional
+            code for mat4 data type, one of ``miDOUBLE, miSINGLE, miINT32,
+            miINT16, miUINT16, miUINT8``
+        T : int, optional
+            code for mat4 matrix class, one of ``mxFULL_CLASS, mxCHAR_CLASS,
+            mxSPARSE_CLASS``
+        imagf : int, optional
+            flag indicating complex
+        '''
+        header = np.empty((), mdtypes_template['header'])
+        M = not SYS_LITTLE_ENDIAN
+        O = 0
+        header['mopt'] = (M * 1000 +
+                          O * 100 +
+                          P * 10 +
+                          T)
+        header['mrows'] = shape[0]
+        header['ncols'] = shape[1]
+        header['imagf'] = imagf
+        header['namlen'] = len(name) + 1
+        self.write_bytes(header)
+        data = name + '\0'
+        self.write_string(data.encode('latin1'))
+
+    def write(self, arr, name):
+        ''' Write matrix `arr`, with name `name`
+
+        Parameters
+        ----------
+        arr : array_like
+           array to write
+        name : str
+           name in matlab workspace
+        '''
+        # we need to catch sparse first, because np.asarray returns an
+        # an object array for scipy.sparse
+        if scipy.sparse.issparse(arr):
+            self.write_sparse(arr, name)
+            return
+        arr = np.asarray(arr)
+        dt = arr.dtype
+        if not dt.isnative:
+            arr = arr.astype(dt.newbyteorder('='))
+        dtt = dt.type
+        if dtt is np.object_:
+            raise TypeError('Cannot save object arrays in Mat4')
+        elif dtt is np.void:
+            raise TypeError('Cannot save void type arrays')
+        elif dtt in (np.str_, np.bytes_):
+            self.write_char(arr, name)
+            return
+        self.write_numeric(arr, name)
+
+    def write_numeric(self, arr, name):
+        arr = arr_to_2d(arr, self.oned_as)
+        imagf = arr.dtype.kind == 'c'
+        try:
+            P = np_to_mtypes[arr.dtype.str[1:]]
+        except KeyError:
+            if imagf:
+                arr = arr.astype('c128')
+            else:
+                arr = arr.astype('f8')
+            P = miDOUBLE
+        self.write_header(name,
+                          arr.shape,
+                          P=P,
+                          T=mxFULL_CLASS,
+                          imagf=imagf)
+        if imagf:
+            self.write_bytes(arr.real)
+            self.write_bytes(arr.imag)
+        else:
+            self.write_bytes(arr)
+
+    def write_char(self, arr, name):
+        if arr.dtype.type == np.str_ and arr.dtype.itemsize != np.dtype('U1').itemsize:
+            arr = arr_to_chars(arr)
+        arr = arr_to_2d(arr, self.oned_as)
+        dims = arr.shape
+        self.write_header(
+            name,
+            dims,
+            P=miUINT8,
+            T=mxCHAR_CLASS)
+        if arr.dtype.kind == 'U':
+            # Recode unicode to latin1
+            n_chars = math.prod(dims)
+            st_arr = np.ndarray(shape=(),
+                                dtype=arr_dtype_number(arr, n_chars),
+                                buffer=arr)
+            st = st_arr.item().encode('latin-1')
+            arr = np.ndarray(shape=dims, dtype='S1', buffer=st)
+        self.write_bytes(arr)
+
+    def write_sparse(self, arr, name):
+        ''' Sparse matrices are 2-D
+
+        See docstring for VarReader4.read_sparse_array
+        '''
+        A = arr.tocoo()  # convert to sparse COO format (ijv)
+        imagf = A.dtype.kind == 'c'
+        ijv = np.zeros((A.nnz + 1, 3+imagf), dtype='f8')
+        ijv[:-1,0] = A.row
+        ijv[:-1,1] = A.col
+        ijv[:-1,0:2] += 1  # 1 based indexing
+        if imagf:
+            ijv[:-1,2] = A.data.real
+            ijv[:-1,3] = A.data.imag
+        else:
+            ijv[:-1,2] = A.data
+        ijv[-1,0:2] = A.shape
+        self.write_header(
+            name,
+            ijv.shape,
+            P=miDOUBLE,
+            T=mxSPARSE_CLASS)
+        self.write_bytes(ijv)
+
+
+class MatFile4Writer:
+    ''' Class for writing matlab 4 format files '''
+    def __init__(self, file_stream, oned_as=None):
+        self.file_stream = file_stream
+        if oned_as is None:
+            oned_as = 'row'
+        self.oned_as = oned_as
+        self._matrix_writer = None
+
+    def put_variables(self, mdict, write_header=None):
+        ''' Write variables in `mdict` to stream
+
+        Parameters
+        ----------
+        mdict : mapping
+           mapping with method ``items`` return name, contents pairs
+           where ``name`` which will appeak in the matlab workspace in
+           file load, and ``contents`` is something writeable to a
+           matlab file, such as a NumPy array.
+        write_header : {None, True, False}
+           If True, then write the matlab file header before writing the
+           variables. If None (the default) then write the file header
+           if we are at position 0 in the stream. By setting False
+           here, and setting the stream position to the end of the file,
+           you can append variables to a matlab file
+        '''
+        # there is no header for a matlab 4 mat file, so we ignore the
+        # ``write_header`` input argument. It's there for compatibility
+        # with the matlab 5 version of this method
+        self._matrix_writer = VarWriter4(self)
+        for name, var in mdict.items():
+            self._matrix_writer.write(var, name)
diff --git a/.venv/lib/python3.12/site-packages/scipy/io/matlab/_mio5.py b/.venv/lib/python3.12/site-packages/scipy/io/matlab/_mio5.py
new file mode 100644
index 0000000000000000000000000000000000000000..59236c39822c0dedf20267a48defb0160ec1e9e9
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/io/matlab/_mio5.py
@@ -0,0 +1,918 @@
+''' Classes for read / write of matlab (TM) 5 files
+
+The matfile specification last found here:
+
+https://www.mathworks.com/access/helpdesk/help/pdf_doc/matlab/matfile_format.pdf
+
+(as of December 5 2008)
+
+=================================
+ Note on functions and mat files
+=================================
+
+The document above does not give any hints as to the storage of matlab
+function handles, or anonymous function handles. I had, therefore, to
+guess the format of matlab arrays of ``mxFUNCTION_CLASS`` and
+``mxOPAQUE_CLASS`` by looking at example mat files.
+
+``mxFUNCTION_CLASS`` stores all types of matlab functions. It seems to
+contain a struct matrix with a set pattern of fields. For anonymous
+functions, a sub-fields of one of these fields seems to contain the
+well-named ``mxOPAQUE_CLASS``. This seems to contain:
+
+* array flags as for any matlab matrix
+* 3 int8 strings
+* a matrix
+
+It seems that whenever the mat file contains a ``mxOPAQUE_CLASS``
+instance, there is also an un-named matrix (name == '') at the end of
+the mat file. I'll call this the ``__function_workspace__`` matrix.
+
+When I saved two anonymous functions in a mat file, or appended another
+anonymous function to the mat file, there was still only one
+``__function_workspace__`` un-named matrix at the end, but larger than
+that for a mat file with a single anonymous function, suggesting that
+the workspaces for the two functions had been merged.
+
+The ``__function_workspace__`` matrix appears to be of double class
+(``mxCLASS_DOUBLE``), but stored as uint8, the memory for which is in
+the format of a mini .mat file, without the first 124 bytes of the file
+header (the description and the subsystem_offset), but with the version
+U2 bytes, and the S2 endian test bytes. There follow 4 zero bytes,
+presumably for 8 byte padding, and then a series of ``miMATRIX``
+entries, as in a standard mat file. The ``miMATRIX`` entries appear to
+be series of un-named (name == '') matrices, and may also contain arrays
+of this same mini-mat format.
+
+I guess that:
+
+* saving an anonymous function back to a mat file will need the
+  associated ``__function_workspace__`` matrix saved as well for the
+  anonymous function to work correctly.
+* appending to a mat file that has a ``__function_workspace__`` would
+  involve first pulling off this workspace, appending, checking whether
+  there were any more anonymous functions appended, and then somehow
+  merging the relevant workspaces, and saving at the end of the mat
+  file.
+
+The mat files I was playing with are in ``tests/data``:
+
+* sqr.mat
+* parabola.mat
+* some_functions.mat
+
+See ``tests/test_mio.py:test_mio_funcs.py`` for the debugging
+script I was working with.
+
+Small fragments of current code adapted from matfile.py by Heiko
+Henkelmann; parts of the code for simplify_cells=True adapted from
+http://blog.nephics.com/2019/08/28/better-loadmat-for-scipy/.
+'''
+
+import math
+import os
+import time
+import sys
+import zlib
+
+from io import BytesIO
+
+import warnings
+
+import numpy as np
+
+import scipy.sparse
+
+from ._byteordercodes import native_code, swapped_code
+
+from ._miobase import (MatFileReader, docfiller, matdims, read_dtype,
+                      arr_to_chars, arr_dtype_number, MatWriteError,
+                      MatReadError, MatReadWarning, MatWriteWarning)
+
+# Reader object for matlab 5 format variables
+from ._mio5_utils import VarReader5
+
+# Constants and helper objects
+from ._mio5_params import (MatlabObject, MatlabFunction, MDTYPES, NP_TO_MTYPES,
+                          NP_TO_MXTYPES, miCOMPRESSED, miMATRIX, miINT8,
+                          miUTF8, miUINT32, mxCELL_CLASS, mxSTRUCT_CLASS,
+                          mxOBJECT_CLASS, mxCHAR_CLASS, mxSPARSE_CLASS,
+                          mxDOUBLE_CLASS, mclass_info, mat_struct,
+                          mxOPAQUE_CLASS, MatlabOpaque)
+
+from ._streams import ZlibInputStream
+
+
+def _has_struct(elem):
+    """Determine if elem is an array and if first array item is a struct."""
+    return (isinstance(elem, np.ndarray) and (elem.size > 0) and (elem.ndim > 0) and
+            isinstance(elem[0], mat_struct))
+
+
+def _inspect_cell_array(ndarray):
+    """Construct lists from cell arrays (loaded as numpy ndarrays), recursing
+    into items if they contain mat_struct objects."""
+    elem_list = []
+    for sub_elem in ndarray:
+        if isinstance(sub_elem, mat_struct):
+            elem_list.append(_matstruct_to_dict(sub_elem))
+        elif _has_struct(sub_elem):
+            elem_list.append(_inspect_cell_array(sub_elem))
+        else:
+            elem_list.append(sub_elem)
+    return elem_list
+
+
+def _matstruct_to_dict(matobj):
+    """Construct nested dicts from mat_struct objects."""
+    d = {}
+    for f in matobj._fieldnames:
+        elem = matobj.__dict__[f]
+        if isinstance(elem, mat_struct):
+            d[f] = _matstruct_to_dict(elem)
+        elif _has_struct(elem):
+            d[f] = _inspect_cell_array(elem)
+        else:
+            d[f] = elem
+    return d
+
+
+def _simplify_cells(d):
+    """Convert mat objects in dict to nested dicts."""
+    for key in d:
+        if isinstance(d[key], mat_struct):
+            d[key] = _matstruct_to_dict(d[key])
+        elif _has_struct(d[key]):
+            d[key] = _inspect_cell_array(d[key])
+    return d
+
+
+class MatFile5Reader(MatFileReader):
+    ''' Reader for Mat 5 mat files
+    Adds the following attribute to base class
+
+    uint16_codec - char codec to use for uint16 char arrays
+        (defaults to system default codec)
+
+    Uses variable reader that has the following standard interface (see
+    abstract class in ``miobase``::
+
+       __init__(self, file_reader)
+       read_header(self)
+       array_from_header(self)
+
+    and added interface::
+
+       set_stream(self, stream)
+       read_full_tag(self)
+
+    '''
+    @docfiller
+    def __init__(self,
+                 mat_stream,
+                 byte_order=None,
+                 mat_dtype=False,
+                 squeeze_me=False,
+                 chars_as_strings=True,
+                 matlab_compatible=False,
+                 struct_as_record=True,
+                 verify_compressed_data_integrity=True,
+                 uint16_codec=None,
+                 simplify_cells=False):
+        '''Initializer for matlab 5 file format reader
+
+    %(matstream_arg)s
+    %(load_args)s
+    %(struct_arg)s
+    uint16_codec : {None, string}
+        Set codec to use for uint16 char arrays (e.g., 'utf-8').
+        Use system default codec if None
+        '''
+        super().__init__(
+            mat_stream,
+            byte_order,
+            mat_dtype,
+            squeeze_me,
+            chars_as_strings,
+            matlab_compatible,
+            struct_as_record,
+            verify_compressed_data_integrity,
+            simplify_cells)
+        # Set uint16 codec
+        if not uint16_codec:
+            uint16_codec = sys.getdefaultencoding()
+        self.uint16_codec = uint16_codec
+        # placeholders for readers - see initialize_read method
+        self._file_reader = None
+        self._matrix_reader = None
+
+    def guess_byte_order(self):
+        ''' Guess byte order.
+        Sets stream pointer to 0'''
+        self.mat_stream.seek(126)
+        mi = self.mat_stream.read(2)
+        self.mat_stream.seek(0)
+        return mi == b'IM' and '<' or '>'
+
+    def read_file_header(self):
+        ''' Read in mat 5 file header '''
+        hdict = {}
+        hdr_dtype = MDTYPES[self.byte_order]['dtypes']['file_header']
+        hdr = read_dtype(self.mat_stream, hdr_dtype)
+        hdict['__header__'] = hdr['description'].item().strip(b' \t\n\000')
+        v_major = hdr['version'] >> 8
+        v_minor = hdr['version'] & 0xFF
+        hdict['__version__'] = f'{v_major}.{v_minor}'
+        return hdict
+
+    def initialize_read(self):
+        ''' Run when beginning read of variables
+
+        Sets up readers from parameters in `self`
+        '''
+        # reader for top level stream. We need this extra top-level
+        # reader because we use the matrix_reader object to contain
+        # compressed matrices (so they have their own stream)
+        self._file_reader = VarReader5(self)
+        # reader for matrix streams
+        self._matrix_reader = VarReader5(self)
+
+    def read_var_header(self):
+        ''' Read header, return header, next position
+
+        Header has to define at least .name and .is_global
+
+        Parameters
+        ----------
+        None
+
+        Returns
+        -------
+        header : object
+           object that can be passed to self.read_var_array, and that
+           has attributes .name and .is_global
+        next_position : int
+           position in stream of next variable
+        '''
+        mdtype, byte_count = self._file_reader.read_full_tag()
+        if not byte_count > 0:
+            raise ValueError("Did not read any bytes")
+        next_pos = self.mat_stream.tell() + byte_count
+        if mdtype == miCOMPRESSED:
+            # Make new stream from compressed data
+            stream = ZlibInputStream(self.mat_stream, byte_count)
+            self._matrix_reader.set_stream(stream)
+            check_stream_limit = self.verify_compressed_data_integrity
+            mdtype, byte_count = self._matrix_reader.read_full_tag()
+        else:
+            check_stream_limit = False
+            self._matrix_reader.set_stream(self.mat_stream)
+        if not mdtype == miMATRIX:
+            raise TypeError(f'Expecting miMATRIX type here, got {mdtype}')
+        header = self._matrix_reader.read_header(check_stream_limit)
+        return header, next_pos
+
+    def read_var_array(self, header, process=True):
+        ''' Read array, given `header`
+
+        Parameters
+        ----------
+        header : header object
+           object with fields defining variable header
+        process : {True, False} bool, optional
+           If True, apply recursive post-processing during loading of
+           array.
+
+        Returns
+        -------
+        arr : array
+           array with post-processing applied or not according to
+           `process`.
+        '''
+        return self._matrix_reader.array_from_header(header, process)
+
+    def get_variables(self, variable_names=None):
+        ''' get variables from stream as dictionary
+
+        variable_names   - optional list of variable names to get
+
+        If variable_names is None, then get all variables in file
+        '''
+        if isinstance(variable_names, str):
+            variable_names = [variable_names]
+        elif variable_names is not None:
+            variable_names = list(variable_names)
+
+        self.mat_stream.seek(0)
+        # Here we pass all the parameters in self to the reading objects
+        self.initialize_read()
+        mdict = self.read_file_header()
+        mdict['__globals__'] = []
+        while not self.end_of_stream():
+            hdr, next_position = self.read_var_header()
+            name = 'None' if hdr.name is None else hdr.name.decode('latin1')
+            if name in mdict:
+                msg = (
+                    f'Duplicate variable name "{name}" in stream'
+                    " - replacing previous with new\nConsider"
+                    "scipy.io.matlab.varmats_from_mat to split "
+                    "file into single variable files"
+                )
+                warnings.warn(msg, MatReadWarning, stacklevel=2)
+            if name == '':
+                # can only be a matlab 7 function workspace
+                name = '__function_workspace__'
+                # We want to keep this raw because mat_dtype processing
+                # will break the format (uint8 as mxDOUBLE_CLASS)
+                process = False
+            else:
+                process = True
+            if variable_names is not None and name not in variable_names:
+                self.mat_stream.seek(next_position)
+                continue
+            try:
+                res = self.read_var_array(hdr, process)
+            except MatReadError as err:
+                warnings.warn(
+                    f'Unreadable variable "{name}", because "{err}"',
+                    Warning, stacklevel=2)
+                res = f"Read error: {err}"
+            self.mat_stream.seek(next_position)
+            mdict[name] = res
+            if hdr.is_global:
+                mdict['__globals__'].append(name)
+            if variable_names is not None:
+                variable_names.remove(name)
+                if len(variable_names) == 0:
+                    break
+        if self.simplify_cells:
+            return _simplify_cells(mdict)
+        else:
+            return mdict
+
+    def list_variables(self):
+        ''' list variables from stream '''
+        self.mat_stream.seek(0)
+        # Here we pass all the parameters in self to the reading objects
+        self.initialize_read()
+        self.read_file_header()
+        vars = []
+        while not self.end_of_stream():
+            hdr, next_position = self.read_var_header()
+            name = 'None' if hdr.name is None else hdr.name.decode('latin1')
+            if name == '':
+                # can only be a matlab 7 function workspace
+                name = '__function_workspace__'
+
+            shape = self._matrix_reader.shape_from_header(hdr)
+            if hdr.is_logical:
+                info = 'logical'
+            else:
+                info = mclass_info.get(hdr.mclass, 'unknown')
+            vars.append((name, shape, info))
+
+            self.mat_stream.seek(next_position)
+        return vars
+
+
+def varmats_from_mat(file_obj):
+    """Pull variables out of mat 5 file as a sequence of mat file objects.
+
+    This can be useful with a difficult mat file, containing unreadable
+    variables. This routine pulls the variables out in raw form and puts them,
+    unread, back into a file stream for saving or reading. Another use is the
+    pathological case where there is more than one variable of the same name in
+    the file; this routine returns the duplicates, whereas the standard reader
+    will overwrite duplicates in the returned dictionary.
+
+    The file pointer in `file_obj` will be undefined. File pointers for the
+    returned file-like objects are set at 0.
+
+    Parameters
+    ----------
+    file_obj : file-like
+        file object containing mat file
+
+    Returns
+    -------
+    named_mats : list
+        list contains tuples of (name, BytesIO) where BytesIO is a file-like
+        object containing mat file contents as for a single variable. The
+        BytesIO contains a string with the original header and a single var. If
+        ``var_file_obj`` is an individual BytesIO instance, then save as a mat
+        file with something like ``open('test.mat',
+        'wb').write(var_file_obj.read())``
+
+    Examples
+    --------
+    >>> import scipy.io
+    >>> import numpy as np
+    >>> from io import BytesIO
+    >>> from scipy.io.matlab._mio5 import varmats_from_mat
+    >>> mat_fileobj = BytesIO()
+    >>> scipy.io.savemat(mat_fileobj, {'b': np.arange(10), 'a': 'a string'})
+    >>> varmats = varmats_from_mat(mat_fileobj)
+    >>> sorted([name for name, str_obj in varmats])
+    ['a', 'b']
+    """
+    rdr = MatFile5Reader(file_obj)
+    file_obj.seek(0)
+    # Raw read of top-level file header
+    hdr_len = MDTYPES[native_code]['dtypes']['file_header'].itemsize
+    raw_hdr = file_obj.read(hdr_len)
+    # Initialize variable reading
+    file_obj.seek(0)
+    rdr.initialize_read()
+    rdr.read_file_header()
+    next_position = file_obj.tell()
+    named_mats = []
+    while not rdr.end_of_stream():
+        start_position = next_position
+        hdr, next_position = rdr.read_var_header()
+        name = 'None' if hdr.name is None else hdr.name.decode('latin1')
+        # Read raw variable string
+        file_obj.seek(start_position)
+        byte_count = next_position - start_position
+        var_str = file_obj.read(byte_count)
+        # write to stringio object
+        out_obj = BytesIO()
+        out_obj.write(raw_hdr)
+        out_obj.write(var_str)
+        out_obj.seek(0)
+        named_mats.append((name, out_obj))
+    return named_mats
+
+
+class EmptyStructMarker:
+    """ Class to indicate presence of empty matlab struct on output """
+
+
+def to_writeable(source):
+    ''' Convert input object ``source`` to something we can write
+
+    Parameters
+    ----------
+    source : object
+
+    Returns
+    -------
+    arr : None or ndarray or EmptyStructMarker
+        If `source` cannot be converted to something we can write to a matfile,
+        return None.  If `source` is equivalent to an empty dictionary, return
+        ``EmptyStructMarker``.  Otherwise return `source` converted to an
+        ndarray with contents for writing to matfile.
+    '''
+    if isinstance(source, np.ndarray):
+        return source
+    if source is None:
+        return None
+    if hasattr(source, "__array__"):
+        return np.asarray(source)
+    # Objects that implement mappings
+    is_mapping = (hasattr(source, 'keys') and hasattr(source, 'values') and
+                  hasattr(source, 'items'))
+    # Objects that don't implement mappings, but do have dicts
+    if isinstance(source, np.generic):
+        # NumPy scalars are never mappings
+        pass
+    elif not is_mapping and hasattr(source, '__dict__'):
+        source = {key: value for key, value in source.__dict__.items()
+                      if not key.startswith('_')}
+        is_mapping = True
+    if is_mapping:
+        dtype = []
+        values = []
+        for field, value in source.items():
+            if isinstance(field, str):
+                if field[0] not in '_0123456789':
+                    dtype.append((str(field), object))
+                    values.append(value)
+                else:
+                    msg = (f"Starting field name with a underscore "
+                           f"or a digit ({field}) is ignored")
+                    warnings.warn(msg, MatWriteWarning, stacklevel=2)
+        if dtype:
+            return np.array([tuple(values)], dtype)
+        else:
+            return EmptyStructMarker
+    # Next try and convert to an array
+    try:
+        narr = np.asanyarray(source)
+    except ValueError:
+        narr = np.asanyarray(source, dtype=object)
+    if narr.dtype.type in (object, np.object_) and \
+       narr.shape == () and narr == source:
+        # No interesting conversion possible
+        return None
+    return narr
+
+
+# Native byte ordered dtypes for convenience for writers
+NDT_FILE_HDR = MDTYPES[native_code]['dtypes']['file_header']
+NDT_TAG_FULL = MDTYPES[native_code]['dtypes']['tag_full']
+NDT_TAG_SMALL = MDTYPES[native_code]['dtypes']['tag_smalldata']
+NDT_ARRAY_FLAGS = MDTYPES[native_code]['dtypes']['array_flags']
+
+
+class VarWriter5:
+    ''' Generic matlab matrix writing class '''
+    mat_tag = np.zeros((), NDT_TAG_FULL)
+    mat_tag['mdtype'] = miMATRIX
+
+    def __init__(self, file_writer):
+        self.file_stream = file_writer.file_stream
+        self.unicode_strings = file_writer.unicode_strings
+        self.long_field_names = file_writer.long_field_names
+        self.oned_as = file_writer.oned_as
+        # These are used for top level writes, and unset after
+        self._var_name = None
+        self._var_is_global = False
+
+    def write_bytes(self, arr):
+        self.file_stream.write(arr.tobytes(order='F'))
+
+    def write_string(self, s):
+        self.file_stream.write(s)
+
+    def write_element(self, arr, mdtype=None):
+        ''' write tag and data '''
+        if mdtype is None:
+            mdtype = NP_TO_MTYPES[arr.dtype.str[1:]]
+        # Array needs to be in native byte order
+        if arr.dtype.byteorder == swapped_code:
+            arr = arr.byteswap().view(arr.dtype.newbyteorder())
+        byte_count = arr.size*arr.itemsize
+        if byte_count <= 4:
+            self.write_smalldata_element(arr, mdtype, byte_count)
+        else:
+            self.write_regular_element(arr, mdtype, byte_count)
+
+    def write_smalldata_element(self, arr, mdtype, byte_count):
+        # write tag with embedded data
+        tag = np.zeros((), NDT_TAG_SMALL)
+        tag['byte_count_mdtype'] = (byte_count << 16) + mdtype
+        # if arr.tobytes is < 4, the element will be zero-padded as needed.
+        tag['data'] = arr.tobytes(order='F')
+        self.write_bytes(tag)
+
+    def write_regular_element(self, arr, mdtype, byte_count):
+        # write tag, data
+        tag = np.zeros((), NDT_TAG_FULL)
+        tag['mdtype'] = mdtype
+        tag['byte_count'] = byte_count
+        self.write_bytes(tag)
+        self.write_bytes(arr)
+        # pad to next 64-bit boundary
+        bc_mod_8 = byte_count % 8
+        if bc_mod_8:
+            self.file_stream.write(b'\x00' * (8-bc_mod_8))
+
+    def write_header(self,
+                     shape,
+                     mclass,
+                     is_complex=False,
+                     is_logical=False,
+                     nzmax=0):
+        ''' Write header for given data options
+        shape : sequence
+           array shape
+        mclass      - mat5 matrix class
+        is_complex  - True if matrix is complex
+        is_logical  - True if matrix is logical
+        nzmax        - max non zero elements for sparse arrays
+
+        We get the name and the global flag from the object, and reset
+        them to defaults after we've used them
+        '''
+        # get name and is_global from one-shot object store
+        name = self._var_name
+        is_global = self._var_is_global
+        # initialize the top-level matrix tag, store position
+        self._mat_tag_pos = self.file_stream.tell()
+        self.write_bytes(self.mat_tag)
+        # write array flags (complex, global, logical, class, nzmax)
+        af = np.zeros((), NDT_ARRAY_FLAGS)
+        af['data_type'] = miUINT32
+        af['byte_count'] = 8
+        flags = is_complex << 3 | is_global << 2 | is_logical << 1
+        af['flags_class'] = mclass | flags << 8
+        af['nzmax'] = nzmax
+        self.write_bytes(af)
+        # shape
+        if shape is not None:
+            self.write_element(np.array(shape, dtype='i4'))
+        # write name
+        name = np.asarray(name)
+        if name == '' or name == b'':  # empty string zero-terminated
+            self.write_smalldata_element(name, miINT8, 0)
+        else:
+            self.write_element(name, miINT8)
+        # reset the one-shot store to defaults
+        self._var_name = ''
+        self._var_is_global = False
+
+    def update_matrix_tag(self, start_pos):
+        curr_pos = self.file_stream.tell()
+        self.file_stream.seek(start_pos)
+        byte_count = curr_pos - start_pos - 8
+        if byte_count >= 2**32:
+            raise MatWriteError("Matrix too large to save with Matlab "
+                                "5 format")
+        self.mat_tag['byte_count'] = byte_count
+        self.write_bytes(self.mat_tag)
+        self.file_stream.seek(curr_pos)
+
+    def write_top(self, arr, name, is_global):
+        """ Write variable at top level of mat file
+
+        Parameters
+        ----------
+        arr : array_like
+            array-like object to create writer for
+        name : str, optional
+            name as it will appear in matlab workspace
+            default is empty string
+        is_global : {False, True}, optional
+            whether variable will be global on load into matlab
+        """
+        # these are set before the top-level header write, and unset at
+        # the end of the same write, because they do not apply for lower levels
+        self._var_is_global = is_global
+        self._var_name = name
+        # write the header and data
+        self.write(arr)
+
+    def write(self, arr):
+        ''' Write `arr` to stream at top and sub levels
+
+        Parameters
+        ----------
+        arr : array_like
+            array-like object to create writer for
+        '''
+        # store position, so we can update the matrix tag
+        mat_tag_pos = self.file_stream.tell()
+        # First check if these are sparse
+        if scipy.sparse.issparse(arr):
+            self.write_sparse(arr)
+            self.update_matrix_tag(mat_tag_pos)
+            return
+        # Try to convert things that aren't arrays
+        narr = to_writeable(arr)
+        if narr is None:
+            raise TypeError(f'Could not convert {arr} (type {type(arr)}) to array')
+        if isinstance(narr, MatlabOpaque):
+            self.write_opaque(narr)
+        elif isinstance(narr, MatlabObject):
+            self.write_object(narr)
+        elif isinstance(narr, MatlabFunction):
+            raise MatWriteError('Cannot write matlab functions')
+        elif narr is EmptyStructMarker:  # empty struct array
+            self.write_empty_struct()
+        elif narr.dtype.fields:  # struct array
+            self.write_struct(narr)
+        elif narr.dtype.hasobject:  # cell array
+            self.write_cells(narr)
+        elif narr.dtype.kind in ('U', 'S'):
+            if self.unicode_strings:
+                codec = 'UTF8'
+            else:
+                codec = 'ascii'
+            self.write_char(narr, codec)
+        else:
+            self.write_numeric(narr)
+        self.update_matrix_tag(mat_tag_pos)
+
+    def write_numeric(self, arr):
+        imagf = arr.dtype.kind == 'c'
+        logif = arr.dtype.kind == 'b'
+        try:
+            mclass = NP_TO_MXTYPES[arr.dtype.str[1:]]
+        except KeyError:
+            # No matching matlab type, probably complex256 / float128 / float96
+            # Cast data to complex128 / float64.
+            if imagf:
+                arr = arr.astype('c128')
+            elif logif:
+                arr = arr.astype('i1')  # Should only contain 0/1
+            else:
+                arr = arr.astype('f8')
+            mclass = mxDOUBLE_CLASS
+        self.write_header(matdims(arr, self.oned_as),
+                          mclass,
+                          is_complex=imagf,
+                          is_logical=logif)
+        if imagf:
+            self.write_element(arr.real)
+            self.write_element(arr.imag)
+        else:
+            self.write_element(arr)
+
+    def write_char(self, arr, codec='ascii'):
+        ''' Write string array `arr` with given `codec`
+        '''
+        if arr.size == 0 or np.all(arr == ''):
+            # This an empty string array or a string array containing
+            # only empty strings. Matlab cannot distinguish between a
+            # string array that is empty, and a string array containing
+            # only empty strings, because it stores strings as arrays of
+            # char. There is no way of having an array of char that is
+            # not empty, but contains an empty string. We have to
+            # special-case the array-with-empty-strings because even
+            # empty strings have zero padding, which would otherwise
+            # appear in matlab as a string with a space.
+            shape = (0,) * np.max([arr.ndim, 2])
+            self.write_header(shape, mxCHAR_CLASS)
+            self.write_smalldata_element(arr, miUTF8, 0)
+            return
+        # non-empty string.
+        #
+        # Convert to char array
+        arr = arr_to_chars(arr)
+        # We have to write the shape directly, because we are going
+        # recode the characters, and the resulting stream of chars
+        # may have a different length
+        shape = arr.shape
+        self.write_header(shape, mxCHAR_CLASS)
+        if arr.dtype.kind == 'U' and arr.size:
+            # Make one long string from all the characters. We need to
+            # transpose here, because we're flattening the array, before
+            # we write the bytes. The bytes have to be written in
+            # Fortran order.
+            n_chars = math.prod(shape)
+            st_arr = np.ndarray(shape=(),
+                                dtype=arr_dtype_number(arr, n_chars),
+                                buffer=arr.T.copy())  # Fortran order
+            # Recode with codec to give byte string
+            st = st_arr.item().encode(codec)
+            # Reconstruct as 1-D byte array
+            arr = np.ndarray(shape=(len(st),),
+                             dtype='S1',
+                             buffer=st)
+        self.write_element(arr, mdtype=miUTF8)
+
+    def write_sparse(self, arr):
+        ''' Sparse matrices are 2D
+        '''
+        A = arr.tocsc()  # convert to sparse CSC format
+        A.sort_indices()     # MATLAB expects sorted row indices
+        is_complex = (A.dtype.kind == 'c')
+        is_logical = (A.dtype.kind == 'b')
+        nz = A.nnz
+        self.write_header(matdims(arr, self.oned_as),
+                          mxSPARSE_CLASS,
+                          is_complex=is_complex,
+                          is_logical=is_logical,
+                          # matlab won't load file with 0 nzmax
+                          nzmax=1 if nz == 0 else nz)
+        self.write_element(A.indices.astype('i4'))
+        self.write_element(A.indptr.astype('i4'))
+        self.write_element(A.data.real)
+        if is_complex:
+            self.write_element(A.data.imag)
+
+    def write_cells(self, arr):
+        self.write_header(matdims(arr, self.oned_as),
+                          mxCELL_CLASS)
+        # loop over data, column major
+        A = np.atleast_2d(arr).flatten('F')
+        for el in A:
+            self.write(el)
+
+    def write_empty_struct(self):
+        self.write_header((1, 1), mxSTRUCT_CLASS)
+        # max field name length set to 1 in an example matlab struct
+        self.write_element(np.array(1, dtype=np.int32))
+        # Field names element is empty
+        self.write_element(np.array([], dtype=np.int8))
+
+    def write_struct(self, arr):
+        self.write_header(matdims(arr, self.oned_as),
+                          mxSTRUCT_CLASS)
+        self._write_items(arr)
+
+    def _write_items(self, arr):
+        # write fieldnames
+        fieldnames = [f[0] for f in arr.dtype.descr]
+        length = max([len(fieldname) for fieldname in fieldnames])+1
+        max_length = (self.long_field_names and 64) or 32
+        if length > max_length:
+            raise ValueError(
+                f"Field names are restricted to {max_length - 1} characters"
+            )
+        self.write_element(np.array([length], dtype='i4'))
+        self.write_element(np.array(fieldnames, dtype=f'S{length}'), mdtype=miINT8)
+        A = np.atleast_2d(arr).flatten('F')
+        for el in A:
+            for f in fieldnames:
+                self.write(el[f])
+
+    def write_object(self, arr):
+        '''Same as writing structs, except different mx class, and extra
+        classname element after header
+        '''
+        self.write_header(matdims(arr, self.oned_as),
+                          mxOBJECT_CLASS)
+        self.write_element(np.array(arr.classname, dtype='S'),
+                           mdtype=miINT8)
+        self._write_items(arr)
+
+    def write_opaque(self, arr):
+        '''Array Flags, Var Name, Type System, Class Name, Metadata'''
+        self.write_header(None, mxOPAQUE_CLASS)
+        # Write Type System
+        self.write_element(np.array(arr['_TypeSystem'].item(), dtype='S'),
+                           mdtype=miINT8)
+        # Write Classname
+        self.write_element(np.array(arr['_Class'].item(), dtype='S'),
+                           mdtype=miINT8)
+        self.write(arr['_ObjectMetadata'].item())
+
+
+class MatFile5Writer:
+    ''' Class for writing mat5 files '''
+
+    @docfiller
+    def __init__(self, file_stream,
+                 do_compression=False,
+                 unicode_strings=False,
+                 global_vars=None,
+                 long_field_names=False,
+                 oned_as='row'):
+        ''' Initialize writer for matlab 5 format files
+
+        Parameters
+        ----------
+        %(do_compression)s
+        %(unicode_strings)s
+        global_vars : None or sequence of strings, optional
+            Names of variables to be marked as global for matlab
+        %(long_fields)s
+        %(oned_as)s
+        '''
+        self.file_stream = file_stream
+        self.do_compression = do_compression
+        self.unicode_strings = unicode_strings
+        if global_vars:
+            self.global_vars = global_vars
+        else:
+            self.global_vars = []
+        self.long_field_names = long_field_names
+        self.oned_as = oned_as
+        self._matrix_writer = None
+
+    def write_file_header(self):
+        # write header
+        hdr = np.zeros((), NDT_FILE_HDR)
+        hdr['description'] = (f'MATLAB 5.0 MAT-file Platform: {os.name}, '
+                              f'Created on: {time.asctime()}')
+        hdr['version'] = 0x0100
+        hdr['endian_test'] = np.ndarray(shape=(),
+                                      dtype='S2',
+                                      buffer=np.uint16(0x4d49))
+        self.file_stream.write(hdr.tobytes())
+
+    def put_variables(self, mdict, write_header=None):
+        ''' Write variables in `mdict` to stream
+
+        Parameters
+        ----------
+        mdict : mapping
+           mapping with method ``items`` returns name, contents pairs where
+           ``name`` which will appear in the matlab workspace in file load, and
+           ``contents`` is something writeable to a matlab file, such as a NumPy
+           array.
+        write_header : {None, True, False}, optional
+           If True, then write the matlab file header before writing the
+           variables. If None (the default) then write the file header
+           if we are at position 0 in the stream. By setting False
+           here, and setting the stream position to the end of the file,
+           you can append variables to a matlab file
+        '''
+        # write header if requested, or None and start of file
+        if write_header is None:
+            write_header = self.file_stream.tell() == 0
+        if write_header:
+            self.write_file_header()
+        self._matrix_writer = VarWriter5(self)
+        for name, var in mdict.items():
+            if name == '__function_workspace__':
+                name = ''
+            elif name[0] == '_':
+                msg = (f"Starting field name with a "
+                       f"underscore ({name}) is ignored")
+                warnings.warn(msg, MatWriteWarning, stacklevel=2)
+                continue
+            is_global = name in self.global_vars
+            if self.do_compression:
+                stream = BytesIO()
+                self._matrix_writer.file_stream = stream
+                self._matrix_writer.write_top(var, name.encode('latin1'), is_global)
+                out_str = zlib.compress(stream.getvalue())
+                tag = np.empty((), NDT_TAG_FULL)
+                tag['mdtype'] = miCOMPRESSED
+                tag['byte_count'] = len(out_str)
+                self.file_stream.write(tag.tobytes())
+                self.file_stream.write(out_str)
+            else:  # not compressing
+                self._matrix_writer.write_top(var, name.encode('latin1'), is_global)
diff --git a/.venv/lib/python3.12/site-packages/scipy/io/matlab/_mio5_params.py b/.venv/lib/python3.12/site-packages/scipy/io/matlab/_mio5_params.py
new file mode 100644
index 0000000000000000000000000000000000000000..f82ffb79bd8666cd1a79f4328e81bca77f19ee9c
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/io/matlab/_mio5_params.py
@@ -0,0 +1,298 @@
+''' Constants and classes for matlab 5 read and write
+
+See also mio5_utils.pyx where these same constants arise as c enums.
+
+If you make changes in this file, don't forget to change mio5_utils.pyx
+'''
+import numpy as np
+
+from ._miobase import convert_dtypes
+
+
+__all__ = [
+    'MDTYPES', 'MatlabFunction', 'MatlabObject', 'MatlabOpaque',
+    'NP_TO_MTYPES', 'NP_TO_MXTYPES', 'OPAQUE_DTYPE', 'codecs_template',
+    'mat_struct', 'mclass_dtypes_template', 'mclass_info', 'mdtypes_template',
+    'miCOMPRESSED', 'miDOUBLE', 'miINT16', 'miINT32', 'miINT64', 'miINT8',
+    'miMATRIX', 'miSINGLE', 'miUINT16', 'miUINT32', 'miUINT64', 'miUINT8',
+    'miUTF16', 'miUTF32', 'miUTF8', 'mxCELL_CLASS', 'mxCHAR_CLASS',
+    'mxDOUBLE_CLASS', 'mxFUNCTION_CLASS', 'mxINT16_CLASS', 'mxINT32_CLASS',
+    'mxINT64_CLASS', 'mxINT8_CLASS', 'mxOBJECT_CLASS',
+    'mxOBJECT_CLASS_FROM_MATRIX_H', 'mxOPAQUE_CLASS', 'mxSINGLE_CLASS',
+    'mxSPARSE_CLASS', 'mxSTRUCT_CLASS', 'mxUINT16_CLASS', 'mxUINT32_CLASS',
+    'mxUINT64_CLASS', 'mxUINT8_CLASS'
+]
+miINT8 = 1
+miUINT8 = 2
+miINT16 = 3
+miUINT16 = 4
+miINT32 = 5
+miUINT32 = 6
+miSINGLE = 7
+miDOUBLE = 9
+miINT64 = 12
+miUINT64 = 13
+miMATRIX = 14
+miCOMPRESSED = 15
+miUTF8 = 16
+miUTF16 = 17
+miUTF32 = 18
+
+mxCELL_CLASS = 1
+mxSTRUCT_CLASS = 2
+# The March 2008 edition of "Matlab 7 MAT-File Format" says that
+# mxOBJECT_CLASS = 3, whereas matrix.h says that mxLOGICAL = 3.
+# Matlab 2008a appears to save logicals as type 9, so we assume that
+# the document is correct. See type 18, below.
+mxOBJECT_CLASS = 3
+mxCHAR_CLASS = 4
+mxSPARSE_CLASS = 5
+mxDOUBLE_CLASS = 6
+mxSINGLE_CLASS = 7
+mxINT8_CLASS = 8
+mxUINT8_CLASS = 9
+mxINT16_CLASS = 10
+mxUINT16_CLASS = 11
+mxINT32_CLASS = 12
+mxUINT32_CLASS = 13
+# The following are not in the March 2008 edition of "Matlab 7
+# MAT-File Format," but were guessed from matrix.h.
+mxINT64_CLASS = 14
+mxUINT64_CLASS = 15
+mxFUNCTION_CLASS = 16
+# Not doing anything with these at the moment.
+mxOPAQUE_CLASS = 17  # This appears to be a function workspace
+# Thread 'saving/loading symbol table of annymous functions',
+# octave-maintainers, April-May 2007
+# https://lists.gnu.org/archive/html/octave-maintainers/2007-04/msg00031.html
+# https://lists.gnu.org/archive/html/octave-maintainers/2007-05/msg00032.html
+# (Was/Deprecated: https://www-old.cae.wisc.edu/pipermail/octave-maintainers/2007-May/002824.html)
+mxOBJECT_CLASS_FROM_MATRIX_H = 18
+
+mdtypes_template = {
+    miINT8: 'i1',
+    miUINT8: 'u1',
+    miINT16: 'i2',
+    miUINT16: 'u2',
+    miINT32: 'i4',
+    miUINT32: 'u4',
+    miSINGLE: 'f4',
+    miDOUBLE: 'f8',
+    miINT64: 'i8',
+    miUINT64: 'u8',
+    miUTF8: 'u1',
+    miUTF16: 'u2',
+    miUTF32: 'u4',
+    'file_header': [('description', 'S116'),
+                    ('subsystem_offset', 'i8'),
+                    ('version', 'u2'),
+                    ('endian_test', 'S2')],
+    'tag_full': [('mdtype', 'u4'), ('byte_count', 'u4')],
+    'tag_smalldata':[('byte_count_mdtype', 'u4'), ('data', 'S4')],
+    'array_flags': [('data_type', 'u4'),
+                    ('byte_count', 'u4'),
+                    ('flags_class','u4'),
+                    ('nzmax', 'u4')],
+    'U1': 'U1',
+    }
+
+mclass_dtypes_template = {
+    mxINT8_CLASS: 'i1',
+    mxUINT8_CLASS: 'u1',
+    mxINT16_CLASS: 'i2',
+    mxUINT16_CLASS: 'u2',
+    mxINT32_CLASS: 'i4',
+    mxUINT32_CLASS: 'u4',
+    mxINT64_CLASS: 'i8',
+    mxUINT64_CLASS: 'u8',
+    mxSINGLE_CLASS: 'f4',
+    mxDOUBLE_CLASS: 'f8',
+    }
+
+mclass_info = {
+    mxINT8_CLASS: 'int8',
+    mxUINT8_CLASS: 'uint8',
+    mxINT16_CLASS: 'int16',
+    mxUINT16_CLASS: 'uint16',
+    mxINT32_CLASS: 'int32',
+    mxUINT32_CLASS: 'uint32',
+    mxINT64_CLASS: 'int64',
+    mxUINT64_CLASS: 'uint64',
+    mxSINGLE_CLASS: 'single',
+    mxDOUBLE_CLASS: 'double',
+    mxCELL_CLASS: 'cell',
+    mxSTRUCT_CLASS: 'struct',
+    mxOBJECT_CLASS: 'object',
+    mxCHAR_CLASS: 'char',
+    mxSPARSE_CLASS: 'sparse',
+    mxFUNCTION_CLASS: 'function',
+    mxOPAQUE_CLASS: 'opaque',
+    }
+
+NP_TO_MTYPES = {
+    'f8': miDOUBLE,
+    'c32': miDOUBLE,
+    'c24': miDOUBLE,
+    'c16': miDOUBLE,
+    'f4': miSINGLE,
+    'c8': miSINGLE,
+    'i8': miINT64,
+    'i4': miINT32,
+    'i2': miINT16,
+    'i1': miINT8,
+    'u8': miUINT64,
+    'u4': miUINT32,
+    'u2': miUINT16,
+    'u1': miUINT8,
+    'S1': miUINT8,
+    'U1': miUTF16,
+    'b1': miUINT8,  # not standard but seems MATLAB uses this (gh-4022)
+    }
+
+
+NP_TO_MXTYPES = {
+    'f8': mxDOUBLE_CLASS,
+    'c32': mxDOUBLE_CLASS,
+    'c24': mxDOUBLE_CLASS,
+    'c16': mxDOUBLE_CLASS,
+    'f4': mxSINGLE_CLASS,
+    'c8': mxSINGLE_CLASS,
+    'i8': mxINT64_CLASS,
+    'i4': mxINT32_CLASS,
+    'i2': mxINT16_CLASS,
+    'i1': mxINT8_CLASS,
+    'u8': mxUINT64_CLASS,
+    'u4': mxUINT32_CLASS,
+    'u2': mxUINT16_CLASS,
+    'u1': mxUINT8_CLASS,
+    'S1': mxUINT8_CLASS,
+    'b1': mxUINT8_CLASS,  # not standard but seems MATLAB uses this
+    }
+
+''' Before release v7.1 (release 14) matlab (TM) used the system
+default character encoding scheme padded out to 16-bits. Release 14
+and later use Unicode. When saving character data, R14 checks if it
+can be encoded in 7-bit ascii, and saves in that format if so.'''
+
+codecs_template = {
+    miUTF8: {'codec': 'utf_8', 'width': 1},
+    miUTF16: {'codec': 'utf_16', 'width': 2},
+    miUTF32: {'codec': 'utf_32','width': 4},
+    }
+
+
+def _convert_codecs(template, byte_order):
+    ''' Convert codec template mapping to byte order
+
+    Set codecs not on this system to None
+
+    Parameters
+    ----------
+    template : mapping
+       key, value are respectively codec name, and root name for codec
+       (without byte order suffix)
+    byte_order : {'<', '>'}
+       code for little or big endian
+
+    Returns
+    -------
+    codecs : dict
+       key, value are name, codec (as in .encode(codec))
+    '''
+    codecs = {}
+    postfix = byte_order == '<' and '_le' or '_be'
+    for k, v in template.items():
+        codec = v['codec']
+        try:
+            " ".encode(codec)
+        except LookupError:
+            codecs[k] = None
+            continue
+        if v['width'] > 1:
+            codec += postfix
+        codecs[k] = codec
+    return codecs.copy()
+
+
+MDTYPES: dict[str, dict[str, dict[str, str]]] = {}
+for _bytecode in '<>':
+    _def = {'dtypes': convert_dtypes(mdtypes_template, _bytecode),
+            'classes': convert_dtypes(mclass_dtypes_template, _bytecode),
+            'codecs': _convert_codecs(codecs_template, _bytecode)}
+    MDTYPES[_bytecode] = _def
+
+
+class mat_struct:
+    """Placeholder for holding read data from structs.
+
+    We use instances of this class when the user passes False as a value to the
+    ``struct_as_record`` parameter of the :func:`scipy.io.loadmat` function.
+    """
+    pass
+
+
+class MatlabObject(np.ndarray):
+    """Subclass of ndarray to signal this is a matlab object.
+
+    This is a simple subclass of :class:`numpy.ndarray` meant to be used
+    by :func:`scipy.io.loadmat` and should not be instantiated directly.
+
+    Parameters
+    ----------
+    input_array : array-like
+        The data to be stored in the array.
+    classname : str, optional
+        The MATLAB class name of the object.
+    """
+
+    def __new__(cls, input_array, classname=None):
+        # Input array is an already formed ndarray instance
+        # We first cast to be our class type
+        obj = np.asarray(input_array).view(cls)
+        # add the new attribute to the created instance
+        obj.classname = classname
+        # Finally, we must return the newly created object:
+        return obj
+
+    def __array_finalize__(self,obj):
+        # reset the attribute from passed original object
+        self.classname = getattr(obj, 'classname', None)
+        # We do not need to return anything
+
+
+class MatlabFunction(np.ndarray):
+    """Subclass for a MATLAB function.
+
+    This is a simple subclass of :class:`numpy.ndarray` meant to be used
+    by :func:`scipy.io.loadmat` and should not be directly instantiated.
+
+    Parameters
+    ----------
+    input_array : array-like
+        The data to be stored in the array.
+    """
+
+    def __new__(cls, input_array):
+        obj = np.asarray(input_array).view(cls)
+        return obj
+
+
+class MatlabOpaque(np.ndarray):
+    """Subclass for a MATLAB opaque matrix.
+
+    This is a simple subclass of :class:`numpy.ndarray` meant to be used
+    by :func:`scipy.io.loadmat` and should not be directly instantiated.
+
+    Parameters
+    ----------
+    input_array : array-like
+        The data to be stored in the array.
+    """
+
+    def __new__(cls, input_array):
+        obj = np.asarray(input_array).view(cls)
+        return obj
+
+
+OPAQUE_DTYPE = np.dtype(
+    [('_TypeSystem', 'O'), ('_Class', 'O'), ('_ObjectMetadata', 'O')])
diff --git a/.venv/lib/python3.12/site-packages/scipy/io/matlab/_mio5_utils.cpython-312-x86_64-linux-gnu.so b/.venv/lib/python3.12/site-packages/scipy/io/matlab/_mio5_utils.cpython-312-x86_64-linux-gnu.so
new file mode 100644
index 0000000000000000000000000000000000000000..16236f7520c3ed935ae8b5bfeeabac275914675d
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/io/matlab/_mio5_utils.cpython-312-x86_64-linux-gnu.so
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:6cbebdd55a404b8e705a8c8a310086ca871cd064355b7b903ebcc94e4de15fd1
+size 224152
diff --git a/.venv/lib/python3.12/site-packages/scipy/io/matlab/_mio_utils.cpython-312-x86_64-linux-gnu.so b/.venv/lib/python3.12/site-packages/scipy/io/matlab/_mio_utils.cpython-312-x86_64-linux-gnu.so
new file mode 100644
index 0000000000000000000000000000000000000000..a41d5f1a90ad63b3660b00c1a615f50b58516e80
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/scipy/io/matlab/_mio_utils.cpython-312-x86_64-linux-gnu.so differ
diff --git a/.venv/lib/python3.12/site-packages/scipy/io/matlab/_miobase.py b/.venv/lib/python3.12/site-packages/scipy/io/matlab/_miobase.py
new file mode 100644
index 0000000000000000000000000000000000000000..fb8d9a8374e1634c3f127fd2605adf543923eacd
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/io/matlab/_miobase.py
@@ -0,0 +1,435 @@
+# Authors: Travis Oliphant, Matthew Brett
+
+"""
+Base classes for MATLAB file stream reading.
+
+MATLAB is a registered trademark of the Mathworks inc.
+"""
+
+from typing import Final
+
+import numpy as np
+from scipy._lib import doccer
+
+from . import _byteordercodes as boc
+
+__all__ = [
+    'MatReadError', 'MatReadWarning', 'MatWriteError', 'MatWriteWarning',
+]
+
+class MatReadError(Exception):
+    """Exception indicating a read issue."""
+
+
+class MatWriteError(Exception):
+    """Exception indicating a write issue."""
+
+
+class MatReadWarning(UserWarning):
+    """Warning class for read issues."""
+
+class MatWriteWarning(UserWarning):
+    """Warning class for write issues."""
+
+
+doc_dict = \
+    {'file_arg':
+         '''file_name : str
+   Name of the mat file (do not need .mat extension if
+   appendmat==True) Can also pass open file-like object.''',
+     'append_arg':
+         '''appendmat : bool, optional
+   True to append the .mat extension to the end of the given
+   filename, if not already present. Default is True.''',
+     'load_args':
+         '''byte_order : str or None, optional
+   None by default, implying byte order guessed from mat
+   file. Otherwise can be one of ('native', '=', 'little', '<',
+   'BIG', '>').
+mat_dtype : bool, optional
+   If True, return arrays in same dtype as would be loaded into
+   MATLAB (instead of the dtype with which they are saved).
+squeeze_me : bool, optional
+   Whether to squeeze unit matrix dimensions or not.
+chars_as_strings : bool, optional
+   Whether to convert char arrays to string arrays.
+matlab_compatible : bool, optional
+   Returns matrices as would be loaded by MATLAB (implies
+   squeeze_me=False, chars_as_strings=False, mat_dtype=True,
+   struct_as_record=True).''',
+     'struct_arg':
+         '''struct_as_record : bool, optional
+   Whether to load MATLAB structs as NumPy record arrays, or as
+   old-style NumPy arrays with dtype=object. Setting this flag to
+   False replicates the behavior of SciPy version 0.7.x (returning
+   numpy object arrays). The default setting is True, because it
+   allows easier round-trip load and save of MATLAB files.''',
+     'matstream_arg':
+         '''mat_stream : file-like
+   Object with file API, open for reading.''',
+     'long_fields':
+         '''long_field_names : bool, optional
+   * False - maximum field name length in a structure is 31 characters
+     which is the documented maximum length. This is the default.
+   * True - maximum field name length in a structure is 63 characters
+     which works for MATLAB 7.6''',
+     'do_compression':
+         '''do_compression : bool, optional
+   Whether to compress matrices on write. Default is False.''',
+     'oned_as':
+         '''oned_as : {'row', 'column'}, optional
+   If 'column', write 1-D NumPy arrays as column vectors.
+   If 'row', write 1D NumPy arrays as row vectors.''',
+     'unicode_strings':
+         '''unicode_strings : bool, optional
+   If True, write strings as Unicode, else MATLAB usual encoding.'''}
+
+docfiller: Final = doccer.filldoc(doc_dict)
+
+'''
+
+ Note on architecture
+======================
+
+There are three sets of parameters relevant for reading files. The
+first are *file read parameters* - containing options that are common
+for reading the whole file, and therefore every variable within that
+file. At the moment these are:
+
+* mat_stream
+* dtypes (derived from byte code)
+* byte_order
+* chars_as_strings
+* squeeze_me
+* struct_as_record (MATLAB 5 files)
+* class_dtypes (derived from order code, MATLAB 5 files)
+* codecs (MATLAB 5 files)
+* uint16_codec (MATLAB 5 files)
+
+Another set of parameters are those that apply only to the current
+variable being read - the *header*:
+
+* header related variables (different for v4 and v5 mat files)
+* is_complex
+* mclass
+* var_stream
+
+With the header, we need ``next_position`` to tell us where the next
+variable in the stream is.
+
+Then, for each element in a matrix, there can be *element read
+parameters*. An element is, for example, one element in a MATLAB cell
+array. At the moment, these are:
+
+* mat_dtype
+
+The file-reading object contains the *file read parameters*. The
+*header* is passed around as a data object, or may be read and discarded
+in a single function. The *element read parameters* - the mat_dtype in
+this instance, is passed into a general post-processing function - see
+``mio_utils`` for details.
+'''
+
+
+def convert_dtypes(dtype_template, order_code):
+    ''' Convert dtypes in mapping to given order
+
+    Parameters
+    ----------
+    dtype_template : mapping
+       mapping with values returning numpy dtype from ``np.dtype(val)``
+    order_code : str
+       an order code suitable for using in ``dtype.newbyteorder()``
+
+    Returns
+    -------
+    dtypes : mapping
+       mapping where values have been replaced by
+       ``np.dtype(val).newbyteorder(order_code)``
+
+    '''
+    dtypes = dtype_template.copy()
+    for k in dtypes:
+        dtypes[k] = np.dtype(dtypes[k]).newbyteorder(order_code)
+    return dtypes
+
+
+def read_dtype(mat_stream, a_dtype):
+    """
+    Generic get of byte stream data of known type
+
+    Parameters
+    ----------
+    mat_stream : file_like object
+        MATLAB (tm) mat file stream
+    a_dtype : dtype
+        dtype of array to read. `a_dtype` is assumed to be correct
+        endianness.
+
+    Returns
+    -------
+    arr : ndarray
+        Array of dtype `a_dtype` read from stream.
+
+    """
+    num_bytes = a_dtype.itemsize
+    arr = np.ndarray(shape=(),
+                     dtype=a_dtype,
+                     buffer=mat_stream.read(num_bytes),
+                     order='F')
+    return arr
+
+
+def matfile_version(file_name, *, appendmat=True):
+    """
+    Return major, minor tuple depending on apparent mat file type.
+
+    Where:
+
+     #. 0,x -> version 4 format mat files
+     #. 1,x -> version 5 format mat files
+     #. 2,x -> version 7.3 format mat files (HDF format)
+
+    Parameters
+    ----------
+    file_name : str
+       Name of the mat file (do not need .mat extension if
+       appendmat==True). Can also pass open file-like object.
+    appendmat : bool, optional
+       True to append the .mat extension to the end of the given
+       filename, if not already present. Default is True.
+
+    Returns
+    -------
+    major_version : {0, 1, 2}
+        major MATLAB File format version
+    minor_version : int
+        minor MATLAB file format version
+
+    Raises
+    ------
+    MatReadError
+        If the file is empty.
+    ValueError
+        The matfile version is unknown.
+
+    Notes
+    -----
+    Has the side effect of setting the file read pointer to 0
+    """
+    from ._mio import _open_file_context
+    with _open_file_context(file_name, appendmat=appendmat) as fileobj:
+        return _get_matfile_version(fileobj)
+
+
+get_matfile_version = matfile_version
+
+
+_HDR_N_BYTES = 20
+
+
+def _get_matfile_version(fileobj):
+    # Mat4 files have a zero somewhere in first 4 bytes
+    fileobj.seek(0)
+    hdr_bytes = fileobj.read(_HDR_N_BYTES)
+    if len(hdr_bytes) < _HDR_N_BYTES:
+        raise MatReadError("Mat file appears to be truncated")
+    if hdr_bytes.count(0) == _HDR_N_BYTES:
+        raise MatReadError("Mat file appears to be corrupt "
+                           f"(first {_HDR_N_BYTES} bytes == 0)")
+    mopt_ints = np.ndarray(shape=(4,), dtype=np.uint8, buffer=hdr_bytes[:4])
+    if 0 in mopt_ints:
+        fileobj.seek(0)
+        return (0,0)
+    # For 5 format or 7.3 format we need to read an integer in the
+    # header. Bytes 124 through 128 contain a version integer and an
+    # endian test string
+    fileobj.seek(124)
+    tst_str = fileobj.read(4)
+    fileobj.seek(0)
+    maj_ind = int(tst_str[2] == b'I'[0])
+    maj_val = int(tst_str[maj_ind])
+    min_val = int(tst_str[1 - maj_ind])
+    ret = (maj_val, min_val)
+    if maj_val in (1, 2):
+        return ret
+    raise ValueError('Unknown mat file type, version {}, {}'.format(*ret))
+
+
+def matdims(arr, oned_as='column'):
+    """
+    Determine equivalent MATLAB dimensions for given array
+
+    Parameters
+    ----------
+    arr : ndarray
+        Input array
+    oned_as : {'column', 'row'}, optional
+        Whether 1-D arrays are returned as MATLAB row or column matrices.
+        Default is 'column'.
+
+    Returns
+    -------
+    dims : tuple
+        Shape tuple, in the form MATLAB expects it.
+
+    Notes
+    -----
+    We had to decide what shape a 1 dimensional array would be by
+    default. ``np.atleast_2d`` thinks it is a row vector. The
+    default for a vector in MATLAB (e.g., ``>> 1:12``) is a row vector.
+
+    Versions of scipy up to and including 0.11 resulted (accidentally)
+    in 1-D arrays being read as column vectors. For the moment, we
+    maintain the same tradition here.
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy.io.matlab._miobase import matdims
+    >>> matdims(np.array(1)) # NumPy scalar
+    (1, 1)
+    >>> matdims(np.array([1])) # 1-D array, 1 element
+    (1, 1)
+    >>> matdims(np.array([1,2])) # 1-D array, 2 elements
+    (2, 1)
+    >>> matdims(np.array([[2],[3]])) # 2-D array, column vector
+    (2, 1)
+    >>> matdims(np.array([[2,3]])) # 2-D array, row vector
+    (1, 2)
+    >>> matdims(np.array([[[2,3]]])) # 3-D array, rowish vector
+    (1, 1, 2)
+    >>> matdims(np.array([])) # empty 1-D array
+    (0, 0)
+    >>> matdims(np.array([[]])) # empty 2-D array
+    (0, 0)
+    >>> matdims(np.array([[[]]])) # empty 3-D array
+    (0, 0, 0)
+
+    Optional argument flips 1-D shape behavior.
+
+    >>> matdims(np.array([1,2]), 'row') # 1-D array, 2 elements
+    (1, 2)
+
+    The argument has to make sense though
+
+    >>> matdims(np.array([1,2]), 'bizarre')
+    Traceback (most recent call last):
+       ...
+    ValueError: 1-D option "bizarre" is strange
+
+    """
+    shape = arr.shape
+    if shape == ():  # scalar
+        return (1, 1)
+    if len(shape) == 1:  # 1D
+        if shape[0] == 0:
+            return (0, 0)
+        elif oned_as == 'column':
+            return shape + (1,)
+        elif oned_as == 'row':
+            return (1,) + shape
+        else:
+            raise ValueError(f'1-D option "{oned_as}" is strange')
+    return shape
+
+
+class MatVarReader:
+    ''' Abstract class defining required interface for var readers'''
+    def __init__(self, file_reader):
+        pass
+
+    def read_header(self):
+        ''' Returns header '''
+        pass
+
+    def array_from_header(self, header):
+        ''' Reads array given header '''
+        pass
+
+
+class MatFileReader:
+    """ Base object for reading mat files
+
+    To make this class functional, you will need to override the
+    following methods:
+
+    matrix_getter_factory   - gives object to fetch next matrix from stream
+    guess_byte_order        - guesses file byte order from file
+    """
+
+    @docfiller
+    def __init__(self, mat_stream,
+                 byte_order=None,
+                 mat_dtype=False,
+                 squeeze_me=False,
+                 chars_as_strings=True,
+                 matlab_compatible=False,
+                 struct_as_record=True,
+                 verify_compressed_data_integrity=True,
+                 simplify_cells=False):
+        '''
+        Initializer for mat file reader
+
+        mat_stream : file-like
+            object with file API, open for reading
+    %(load_args)s
+        '''
+        # Initialize stream
+        self.mat_stream = mat_stream
+        self.dtypes = {}
+        if not byte_order:
+            byte_order = self.guess_byte_order()
+        else:
+            byte_order = boc.to_numpy_code(byte_order)
+        self.byte_order = byte_order
+        self.struct_as_record = struct_as_record
+        if matlab_compatible:
+            self.set_matlab_compatible()
+        else:
+            self.squeeze_me = squeeze_me
+            self.chars_as_strings = chars_as_strings
+            self.mat_dtype = mat_dtype
+        self.verify_compressed_data_integrity = verify_compressed_data_integrity
+        self.simplify_cells = simplify_cells
+        if simplify_cells:
+            self.squeeze_me = True
+            self.struct_as_record = False
+
+    def set_matlab_compatible(self):
+        ''' Sets options to return arrays as MATLAB loads them '''
+        self.mat_dtype = True
+        self.squeeze_me = False
+        self.chars_as_strings = False
+
+    def guess_byte_order(self):
+        ''' As we do not know what file type we have, assume native '''
+        return boc.native_code
+
+    def end_of_stream(self):
+        b = self.mat_stream.read(1)
+        curpos = self.mat_stream.tell()
+        self.mat_stream.seek(curpos-1)
+        return len(b) == 0
+
+
+def arr_dtype_number(arr, num):
+    ''' Return dtype for given number of items per element'''
+    return np.dtype(arr.dtype.str[:2] + str(num))
+
+
+def arr_to_chars(arr):
+    ''' Convert string array to char array '''
+    dims = list(arr.shape)
+    if not dims:
+        dims = [1]
+    dims.append(int(arr.dtype.str[2:]))
+    arr = np.ndarray(shape=dims,
+                     dtype=arr_dtype_number(arr, 1),
+                     buffer=arr)
+    empties = [arr == np.array('', dtype=arr.dtype)]
+    if not np.any(empties):
+        return arr
+    arr = arr.copy()
+    arr[tuple(empties)] = ' '
+    return arr
diff --git a/.venv/lib/python3.12/site-packages/scipy/io/matlab/_streams.cpython-312-x86_64-linux-gnu.so b/.venv/lib/python3.12/site-packages/scipy/io/matlab/_streams.cpython-312-x86_64-linux-gnu.so
new file mode 100644
index 0000000000000000000000000000000000000000..a15fb33f5b02578a2559db3070b19bc210bf299a
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/io/matlab/_streams.cpython-312-x86_64-linux-gnu.so
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:c4e87d30fb965f3b029b55e0e623fc9faaf635f51cbc2befe3d307ca2af07fbb
+size 138936
diff --git a/.venv/lib/python3.12/site-packages/scipy/io/matlab/byteordercodes.py b/.venv/lib/python3.12/site-packages/scipy/io/matlab/byteordercodes.py
new file mode 100644
index 0000000000000000000000000000000000000000..0a1c5b0f5e77fdd461d6085037bfdf2850f40fa0
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/io/matlab/byteordercodes.py
@@ -0,0 +1,17 @@
+# This file is not meant for public use and will be removed in SciPy v2.0.0.
+# Use the `scipy.io.matlab` namespace for importing the functions
+# included below.
+
+from scipy._lib.deprecation import _sub_module_deprecation
+
+__all__: list[str] = []
+
+
+def __dir__():
+    return __all__
+
+
+def __getattr__(name):
+    return _sub_module_deprecation(sub_package="io.matlab", module="byteordercodes",
+                                   private_modules=["_byteordercodes"], all=__all__,
+                                   attribute=name)
diff --git a/.venv/lib/python3.12/site-packages/scipy/io/matlab/mio.py b/.venv/lib/python3.12/site-packages/scipy/io/matlab/mio.py
new file mode 100644
index 0000000000000000000000000000000000000000..65bb31e52dc719b485b12ba1294fc3d09806c9d0
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/io/matlab/mio.py
@@ -0,0 +1,16 @@
+# This file is not meant for public use and will be removed in SciPy v2.0.0.
+# Use the `scipy.io.matlab` namespace for importing the functions
+# included below.
+
+from scipy._lib.deprecation import _sub_module_deprecation
+
+__all__ = ["loadmat", "savemat", "whosmat"]  # noqa: F822
+
+def __dir__():
+    return __all__
+
+
+def __getattr__(name):
+    return _sub_module_deprecation(sub_package="io.matlab", module="mio",
+                                   private_modules=["_mio"], all=__all__,
+                                   attribute=name)
diff --git a/.venv/lib/python3.12/site-packages/scipy/io/matlab/mio4.py b/.venv/lib/python3.12/site-packages/scipy/io/matlab/mio4.py
new file mode 100644
index 0000000000000000000000000000000000000000..d13b99a0bcedc9746f7681843989791e0918df2e
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/io/matlab/mio4.py
@@ -0,0 +1,17 @@
+# This file is not meant for public use and will be removed in SciPy v2.0.0.
+# Use the `scipy.io.matlab` namespace for importing the functions
+# included below.
+
+from scipy._lib.deprecation import _sub_module_deprecation
+
+__all__: list[str] = []
+
+
+def __dir__():
+    return __all__
+
+
+def __getattr__(name):
+    return _sub_module_deprecation(sub_package="io.matlab", module="mio4",
+                                   private_modules=["_mio4"], all=__all__,
+                                   attribute=name)
diff --git a/.venv/lib/python3.12/site-packages/scipy/io/matlab/mio5.py b/.venv/lib/python3.12/site-packages/scipy/io/matlab/mio5.py
new file mode 100644
index 0000000000000000000000000000000000000000..b84ca19799b32999032833b4e1be1b21f6bc70da
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/io/matlab/mio5.py
@@ -0,0 +1,19 @@
+# This file is not meant for public use and will be removed in SciPy v2.0.0.
+# Use the `scipy.io.matlab` namespace for importing the functions
+# included below.
+
+from scipy._lib.deprecation import _sub_module_deprecation
+
+__all__ = [  # noqa: F822
+    'MatWriteError', 'MatReadError', 'MatReadWarning', 'MatlabObject',
+    'MatlabFunction', 'mat_struct', 'varmats_from_mat',
+]
+
+def __dir__():
+    return __all__
+
+
+def __getattr__(name):
+    return _sub_module_deprecation(sub_package="io.matlab", module="mio5",
+                                   private_modules=["_mio5"], all=__all__,
+                                   attribute=name)
diff --git a/.venv/lib/python3.12/site-packages/scipy/io/matlab/mio5_params.py b/.venv/lib/python3.12/site-packages/scipy/io/matlab/mio5_params.py
new file mode 100644
index 0000000000000000000000000000000000000000..2dcc9a4f353794546f0d8c07f9afe369baa992f5
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/io/matlab/mio5_params.py
@@ -0,0 +1,18 @@
+# This file is not meant for public use and will be removed in SciPy v2.0.0.
+# Use the `scipy.io.matlab` namespace for importing the functions
+# included below.
+
+from scipy._lib.deprecation import _sub_module_deprecation
+
+__all__ = [  # noqa: F822
+    'MatlabFunction', 'MatlabObject', 'MatlabOpaque', 'mat_struct',
+]
+
+def __dir__():
+    return __all__
+
+
+def __getattr__(name):
+    return _sub_module_deprecation(sub_package="io.matlab", module="mio5_params",
+                                   private_modules=["_mio5_params"], all=__all__,
+                                   attribute=name)
diff --git a/.venv/lib/python3.12/site-packages/scipy/io/matlab/mio5_utils.py b/.venv/lib/python3.12/site-packages/scipy/io/matlab/mio5_utils.py
new file mode 100644
index 0000000000000000000000000000000000000000..37ad9e2dc2f50b85bf5aba517c4ac7d661b5039a
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/io/matlab/mio5_utils.py
@@ -0,0 +1,17 @@
+# This file is not meant for public use and will be removed in SciPy v2.0.0.
+# Use the `scipy.io.matlab` namespace for importing the functions
+# included below.
+
+from scipy._lib.deprecation import _sub_module_deprecation
+
+__all__: list[str] = []
+
+
+def __dir__():
+    return __all__
+
+
+def __getattr__(name):
+    return _sub_module_deprecation(sub_package="io.matlab", module="mio5_utils",
+                                   private_modules=["_mio5_utils"], all=__all__,
+                                   attribute=name)
diff --git a/.venv/lib/python3.12/site-packages/scipy/io/matlab/mio_utils.py b/.venv/lib/python3.12/site-packages/scipy/io/matlab/mio_utils.py
new file mode 100644
index 0000000000000000000000000000000000000000..6920511d2635b44acd33ce6f5e00247daf6578d9
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/io/matlab/mio_utils.py
@@ -0,0 +1,17 @@
+# This file is not meant for public use and will be removed in SciPy v2.0.0.
+# Use the `scipy.io.matlab` namespace for importing the functions
+# included below.
+
+from scipy._lib.deprecation import _sub_module_deprecation
+
+__all__: list[str] = []
+
+
+def __dir__():
+    return __all__
+
+
+def __getattr__(name):
+    return _sub_module_deprecation(sub_package="io.matlab", module="mio_utils",
+                                   private_modules=["_mio_utils"], all=__all__,
+                                   attribute=name)
diff --git a/.venv/lib/python3.12/site-packages/scipy/io/matlab/miobase.py b/.venv/lib/python3.12/site-packages/scipy/io/matlab/miobase.py
new file mode 100644
index 0000000000000000000000000000000000000000..13e16848394471f9a1744a7b27fa4e6c86a9248b
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/io/matlab/miobase.py
@@ -0,0 +1,16 @@
+# This file is not meant for public use and will be removed in SciPy v2.0.0.
+# Use the `scipy.io.matlab` namespace for importing the functions
+# included below.
+
+from scipy._lib.deprecation import _sub_module_deprecation
+
+__all__ = ["MatReadError", "MatReadWarning", "MatWriteError"]  # noqa: F822
+
+def __dir__():
+    return __all__
+
+
+def __getattr__(name):
+    return _sub_module_deprecation(sub_package="io.matlab", module="miobase",
+                                   private_modules=["_miobase"], all=__all__,
+                                   attribute=name)
diff --git a/.venv/lib/python3.12/site-packages/scipy/io/matlab/streams.py b/.venv/lib/python3.12/site-packages/scipy/io/matlab/streams.py
new file mode 100644
index 0000000000000000000000000000000000000000..8125271b06cc6f44cee19b2f6079d26b8f32e268
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/io/matlab/streams.py
@@ -0,0 +1,16 @@
+# This file is not meant for public use and will be removed in SciPy v2.0.0.
+# Use the `scipy.io.matlab` namespace for importing the functions
+# included below.
+
+from scipy._lib.deprecation import _sub_module_deprecation
+
+__all__: list[str] = []
+
+def __dir__():
+    return __all__
+
+
+def __getattr__(name):
+    return _sub_module_deprecation(sub_package="io.matlab", module="streams",
+                                   private_modules=["_streams"], all=__all__,
+                                   attribute=name)
diff --git a/.venv/lib/python3.12/site-packages/scipy/io/matlab/tests/__init__.py b/.venv/lib/python3.12/site-packages/scipy/io/matlab/tests/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/.venv/lib/python3.12/site-packages/scipy/io/matlab/tests/data/bad_miuint32.mat b/.venv/lib/python3.12/site-packages/scipy/io/matlab/tests/data/bad_miuint32.mat
new file mode 100644
index 0000000000000000000000000000000000000000..c9ab357ec85972cf0014752a1e0ccb08ff284af9
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/scipy/io/matlab/tests/data/bad_miuint32.mat differ
diff --git a/.venv/lib/python3.12/site-packages/scipy/io/matlab/tests/data/bad_miutf8_array_name.mat b/.venv/lib/python3.12/site-packages/scipy/io/matlab/tests/data/bad_miutf8_array_name.mat
new file mode 100644
index 0000000000000000000000000000000000000000..a17203fbb2a7628db644b953ac7723b866a2a0a4
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/scipy/io/matlab/tests/data/bad_miutf8_array_name.mat differ
diff --git a/.venv/lib/python3.12/site-packages/scipy/io/matlab/tests/data/big_endian.mat b/.venv/lib/python3.12/site-packages/scipy/io/matlab/tests/data/big_endian.mat
new file mode 100644
index 0000000000000000000000000000000000000000..2a0c982c298fba9df96fd5a927a9c08ee12b09df
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/scipy/io/matlab/tests/data/big_endian.mat differ
diff --git a/.venv/lib/python3.12/site-packages/scipy/io/matlab/tests/data/broken_utf8.mat b/.venv/lib/python3.12/site-packages/scipy/io/matlab/tests/data/broken_utf8.mat
new file mode 100644
index 0000000000000000000000000000000000000000..4f6323870368cd97a6294e108ffea9067cf5e69b
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/scipy/io/matlab/tests/data/broken_utf8.mat differ
diff --git a/.venv/lib/python3.12/site-packages/scipy/io/matlab/tests/data/corrupted_zlib_checksum.mat b/.venv/lib/python3.12/site-packages/scipy/io/matlab/tests/data/corrupted_zlib_checksum.mat
new file mode 100644
index 0000000000000000000000000000000000000000..c88cbb6f54b70d4e795de7cf43f7b46ff6d4d5ef
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/scipy/io/matlab/tests/data/corrupted_zlib_checksum.mat differ
diff --git a/.venv/lib/python3.12/site-packages/scipy/io/matlab/tests/data/corrupted_zlib_data.mat b/.venv/lib/python3.12/site-packages/scipy/io/matlab/tests/data/corrupted_zlib_data.mat
new file mode 100644
index 0000000000000000000000000000000000000000..45a2ef4e39755ea1f41aab045f18a035af58ea07
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/scipy/io/matlab/tests/data/corrupted_zlib_data.mat differ
diff --git a/.venv/lib/python3.12/site-packages/scipy/io/matlab/tests/data/debigged_m4.mat b/.venv/lib/python3.12/site-packages/scipy/io/matlab/tests/data/debigged_m4.mat
new file mode 100644
index 0000000000000000000000000000000000000000..28aad199045d0b3bf31060300aff9231ee6d9a71
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/scipy/io/matlab/tests/data/debigged_m4.mat differ
diff --git a/.venv/lib/python3.12/site-packages/scipy/io/matlab/tests/data/japanese_utf8.txt b/.venv/lib/python3.12/site-packages/scipy/io/matlab/tests/data/japanese_utf8.txt
new file mode 100644
index 0000000000000000000000000000000000000000..1459b6b6ea635b17b5eb04c941e197f98cf04bf1
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/io/matlab/tests/data/japanese_utf8.txt
@@ -0,0 +1,5 @@
+Japanese: 
+すべての人間は、生まれながらにして自由であり、
+かつ、尊厳と権利と について平等である。
+人間は、理性と良心とを授けられており、
+互いに同胞の精神をもって行動しなければならない。
\ No newline at end of file
diff --git a/.venv/lib/python3.12/site-packages/scipy/io/matlab/tests/data/little_endian.mat b/.venv/lib/python3.12/site-packages/scipy/io/matlab/tests/data/little_endian.mat
new file mode 100644
index 0000000000000000000000000000000000000000..df6db666dcf2b98d66e04933bd4011f649dcbe30
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/scipy/io/matlab/tests/data/little_endian.mat differ
diff --git a/.venv/lib/python3.12/site-packages/scipy/io/matlab/tests/data/logical_sparse.mat b/.venv/lib/python3.12/site-packages/scipy/io/matlab/tests/data/logical_sparse.mat
new file mode 100644
index 0000000000000000000000000000000000000000..a60ad5b605a9dc6b0d85eb0a0e3e655c4955dd34
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/scipy/io/matlab/tests/data/logical_sparse.mat differ
diff --git a/.venv/lib/python3.12/site-packages/scipy/io/matlab/tests/data/malformed1.mat b/.venv/lib/python3.12/site-packages/scipy/io/matlab/tests/data/malformed1.mat
new file mode 100644
index 0000000000000000000000000000000000000000..54462e27d663770bc33ef73ed70baae65767719d
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/scipy/io/matlab/tests/data/malformed1.mat differ
diff --git a/.venv/lib/python3.12/site-packages/scipy/io/matlab/tests/data/miuint32_for_miint32.mat b/.venv/lib/python3.12/site-packages/scipy/io/matlab/tests/data/miuint32_for_miint32.mat
new file mode 100644
index 0000000000000000000000000000000000000000..fd2c4994578edbf31431902ecfcb601b11f60b0b
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/scipy/io/matlab/tests/data/miuint32_for_miint32.mat differ
diff --git a/.venv/lib/python3.12/site-packages/scipy/io/matlab/tests/data/miutf8_array_name.mat b/.venv/lib/python3.12/site-packages/scipy/io/matlab/tests/data/miutf8_array_name.mat
new file mode 100644
index 0000000000000000000000000000000000000000..ccfdaa8adb7879ba852eab9ce55b602e11dad06d
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/scipy/io/matlab/tests/data/miutf8_array_name.mat differ
diff --git a/.venv/lib/python3.12/site-packages/scipy/io/matlab/tests/data/nasty_duplicate_fieldnames.mat b/.venv/lib/python3.12/site-packages/scipy/io/matlab/tests/data/nasty_duplicate_fieldnames.mat
new file mode 100644
index 0000000000000000000000000000000000000000..35dcb715bca4cb7f4b0dca287648ef8ee797cd73
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/scipy/io/matlab/tests/data/nasty_duplicate_fieldnames.mat differ
diff --git a/.venv/lib/python3.12/site-packages/scipy/io/matlab/tests/data/one_by_zero_char.mat b/.venv/lib/python3.12/site-packages/scipy/io/matlab/tests/data/one_by_zero_char.mat
new file mode 100644
index 0000000000000000000000000000000000000000..07e7dca456843004dcfd9023a800ea91d309814d
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/scipy/io/matlab/tests/data/one_by_zero_char.mat differ
diff --git a/.venv/lib/python3.12/site-packages/scipy/io/matlab/tests/data/parabola.mat b/.venv/lib/python3.12/site-packages/scipy/io/matlab/tests/data/parabola.mat
new file mode 100644
index 0000000000000000000000000000000000000000..66350532a7737c475a3ae6ef1b1d8406543d890e
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/scipy/io/matlab/tests/data/parabola.mat differ
diff --git a/.venv/lib/python3.12/site-packages/scipy/io/matlab/tests/data/single_empty_string.mat b/.venv/lib/python3.12/site-packages/scipy/io/matlab/tests/data/single_empty_string.mat
new file mode 100644
index 0000000000000000000000000000000000000000..293f387719e8bdcacb075e0de5737894e5dafed3
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/scipy/io/matlab/tests/data/single_empty_string.mat differ
diff --git a/.venv/lib/python3.12/site-packages/scipy/io/matlab/tests/data/some_functions.mat b/.venv/lib/python3.12/site-packages/scipy/io/matlab/tests/data/some_functions.mat
new file mode 100644
index 0000000000000000000000000000000000000000..cc818593b48dd8d29a40a827210b54373e5acf50
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/scipy/io/matlab/tests/data/some_functions.mat differ
diff --git a/.venv/lib/python3.12/site-packages/scipy/io/matlab/tests/data/sqr.mat b/.venv/lib/python3.12/site-packages/scipy/io/matlab/tests/data/sqr.mat
new file mode 100644
index 0000000000000000000000000000000000000000..2436d87cc5dfb6d558b841c2367bfe2363bd1b3c
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/scipy/io/matlab/tests/data/sqr.mat differ
diff --git a/.venv/lib/python3.12/site-packages/scipy/io/matlab/tests/data/test3dmatrix_6.1_SOL2.mat b/.venv/lib/python3.12/site-packages/scipy/io/matlab/tests/data/test3dmatrix_6.1_SOL2.mat
new file mode 100644
index 0000000000000000000000000000000000000000..453712610bf46501d8dd3667ff72d8033f49d81c
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/scipy/io/matlab/tests/data/test3dmatrix_6.1_SOL2.mat differ
diff --git a/.venv/lib/python3.12/site-packages/scipy/io/matlab/tests/data/test3dmatrix_6.5.1_GLNX86.mat b/.venv/lib/python3.12/site-packages/scipy/io/matlab/tests/data/test3dmatrix_6.5.1_GLNX86.mat
new file mode 100644
index 0000000000000000000000000000000000000000..e04d27d30378655ed14634330c7a8ddcd0b98c10
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/scipy/io/matlab/tests/data/test3dmatrix_6.5.1_GLNX86.mat differ
diff --git a/.venv/lib/python3.12/site-packages/scipy/io/matlab/tests/data/test3dmatrix_7.1_GLNX86.mat b/.venv/lib/python3.12/site-packages/scipy/io/matlab/tests/data/test3dmatrix_7.1_GLNX86.mat
new file mode 100644
index 0000000000000000000000000000000000000000..4c0303039826af6f6caa928e505cec10ebb3fa81
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/scipy/io/matlab/tests/data/test3dmatrix_7.1_GLNX86.mat differ
diff --git a/.venv/lib/python3.12/site-packages/scipy/io/matlab/tests/data/test3dmatrix_7.4_GLNX86.mat b/.venv/lib/python3.12/site-packages/scipy/io/matlab/tests/data/test3dmatrix_7.4_GLNX86.mat
new file mode 100644
index 0000000000000000000000000000000000000000..232a051c774105176c28c9718c2cd46f1a1ee1af
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/scipy/io/matlab/tests/data/test3dmatrix_7.4_GLNX86.mat differ
diff --git a/.venv/lib/python3.12/site-packages/scipy/io/matlab/tests/data/test_empty_struct.mat b/.venv/lib/python3.12/site-packages/scipy/io/matlab/tests/data/test_empty_struct.mat
new file mode 100644
index 0000000000000000000000000000000000000000..30c8c8ad5378be4508bd785da8b7cef38adbd13e
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/scipy/io/matlab/tests/data/test_empty_struct.mat differ
diff --git a/.venv/lib/python3.12/site-packages/scipy/io/matlab/tests/data/test_mat4_le_floats.mat b/.venv/lib/python3.12/site-packages/scipy/io/matlab/tests/data/test_mat4_le_floats.mat
new file mode 100644
index 0000000000000000000000000000000000000000..6643c42ddcc9579930980b7eb30e11f339638404
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/scipy/io/matlab/tests/data/test_mat4_le_floats.mat differ
diff --git a/.venv/lib/python3.12/site-packages/scipy/io/matlab/tests/data/test_skip_variable.mat b/.venv/lib/python3.12/site-packages/scipy/io/matlab/tests/data/test_skip_variable.mat
new file mode 100644
index 0000000000000000000000000000000000000000..efbe3fec64ee54c9f8b3998e5035ccfa251e74ff
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/scipy/io/matlab/tests/data/test_skip_variable.mat differ
diff --git a/.venv/lib/python3.12/site-packages/scipy/io/matlab/tests/data/testbool_8_WIN64.mat b/.venv/lib/python3.12/site-packages/scipy/io/matlab/tests/data/testbool_8_WIN64.mat
new file mode 100644
index 0000000000000000000000000000000000000000..faa30b10bc61ea4889bd9e776c0a1a079e2c2a90
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/scipy/io/matlab/tests/data/testbool_8_WIN64.mat differ
diff --git a/.venv/lib/python3.12/site-packages/scipy/io/matlab/tests/data/testcell_6.1_SOL2.mat b/.venv/lib/python3.12/site-packages/scipy/io/matlab/tests/data/testcell_6.1_SOL2.mat
new file mode 100644
index 0000000000000000000000000000000000000000..512f7d889420a016094a903585f27acaa50bc658
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/scipy/io/matlab/tests/data/testcell_6.1_SOL2.mat differ
diff --git a/.venv/lib/python3.12/site-packages/scipy/io/matlab/tests/data/testcell_6.5.1_GLNX86.mat b/.venv/lib/python3.12/site-packages/scipy/io/matlab/tests/data/testcell_6.5.1_GLNX86.mat
new file mode 100644
index 0000000000000000000000000000000000000000..a7633104c1e4f32fe30fd43f389d7559527c8211
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/scipy/io/matlab/tests/data/testcell_6.5.1_GLNX86.mat differ
diff --git a/.venv/lib/python3.12/site-packages/scipy/io/matlab/tests/data/testcell_7.1_GLNX86.mat b/.venv/lib/python3.12/site-packages/scipy/io/matlab/tests/data/testcell_7.1_GLNX86.mat
new file mode 100644
index 0000000000000000000000000000000000000000..2ac1da15873c5edac27758b6f91563d2b8aaace0
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/scipy/io/matlab/tests/data/testcell_7.1_GLNX86.mat differ
diff --git a/.venv/lib/python3.12/site-packages/scipy/io/matlab/tests/data/testcell_7.4_GLNX86.mat b/.venv/lib/python3.12/site-packages/scipy/io/matlab/tests/data/testcell_7.4_GLNX86.mat
new file mode 100644
index 0000000000000000000000000000000000000000..fc893f331c985cf17b7ce9b7b8c179eaf2103659
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/scipy/io/matlab/tests/data/testcell_7.4_GLNX86.mat differ
diff --git a/.venv/lib/python3.12/site-packages/scipy/io/matlab/tests/data/testcellnest_6.1_SOL2.mat b/.venv/lib/python3.12/site-packages/scipy/io/matlab/tests/data/testcellnest_6.1_SOL2.mat
new file mode 100644
index 0000000000000000000000000000000000000000..4198a4f2aeb8effcccf94a9c0114539f98124179
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/scipy/io/matlab/tests/data/testcellnest_6.1_SOL2.mat differ
diff --git a/.venv/lib/python3.12/site-packages/scipy/io/matlab/tests/data/testcellnest_6.5.1_GLNX86.mat b/.venv/lib/python3.12/site-packages/scipy/io/matlab/tests/data/testcellnest_6.5.1_GLNX86.mat
new file mode 100644
index 0000000000000000000000000000000000000000..2c7826eeacdb456e5290cafba343703c7596d191
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/scipy/io/matlab/tests/data/testcellnest_6.5.1_GLNX86.mat differ
diff --git a/.venv/lib/python3.12/site-packages/scipy/io/matlab/tests/data/testcellnest_7.1_GLNX86.mat b/.venv/lib/python3.12/site-packages/scipy/io/matlab/tests/data/testcellnest_7.1_GLNX86.mat
new file mode 100644
index 0000000000000000000000000000000000000000..b3b086cc31dce2de1e300a1d018b0bf5661b69f3
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/scipy/io/matlab/tests/data/testcellnest_7.1_GLNX86.mat differ
diff --git a/.venv/lib/python3.12/site-packages/scipy/io/matlab/tests/data/testcellnest_7.4_GLNX86.mat b/.venv/lib/python3.12/site-packages/scipy/io/matlab/tests/data/testcellnest_7.4_GLNX86.mat
new file mode 100644
index 0000000000000000000000000000000000000000..316f8894c5ecc88468cfa0908c277f730e3163e8
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/scipy/io/matlab/tests/data/testcellnest_7.4_GLNX86.mat differ
diff --git a/.venv/lib/python3.12/site-packages/scipy/io/matlab/tests/data/testcomplex_4.2c_SOL2.mat b/.venv/lib/python3.12/site-packages/scipy/io/matlab/tests/data/testcomplex_4.2c_SOL2.mat
new file mode 100644
index 0000000000000000000000000000000000000000..36621b25c08f18e4545100c6eaec015123c3bf9f
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/scipy/io/matlab/tests/data/testcomplex_4.2c_SOL2.mat differ
diff --git a/.venv/lib/python3.12/site-packages/scipy/io/matlab/tests/data/testcomplex_6.1_SOL2.mat b/.venv/lib/python3.12/site-packages/scipy/io/matlab/tests/data/testcomplex_6.1_SOL2.mat
new file mode 100644
index 0000000000000000000000000000000000000000..32fcd2a93c91eff478a3ab3076e5c78e31f09bf1
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/scipy/io/matlab/tests/data/testcomplex_6.1_SOL2.mat differ
diff --git a/.venv/lib/python3.12/site-packages/scipy/io/matlab/tests/data/testcomplex_6.5.1_GLNX86.mat b/.venv/lib/python3.12/site-packages/scipy/io/matlab/tests/data/testcomplex_6.5.1_GLNX86.mat
new file mode 100644
index 0000000000000000000000000000000000000000..f3ecd203376c17b09d97a24aceab824dae0f91c1
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/scipy/io/matlab/tests/data/testcomplex_6.5.1_GLNX86.mat differ
diff --git a/.venv/lib/python3.12/site-packages/scipy/io/matlab/tests/data/testcomplex_7.1_GLNX86.mat b/.venv/lib/python3.12/site-packages/scipy/io/matlab/tests/data/testcomplex_7.1_GLNX86.mat
new file mode 100644
index 0000000000000000000000000000000000000000..c0c083855f38e62e3a29460b745f198c9c79313d
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/scipy/io/matlab/tests/data/testcomplex_7.1_GLNX86.mat differ
diff --git a/.venv/lib/python3.12/site-packages/scipy/io/matlab/tests/data/testcomplex_7.4_GLNX86.mat b/.venv/lib/python3.12/site-packages/scipy/io/matlab/tests/data/testcomplex_7.4_GLNX86.mat
new file mode 100644
index 0000000000000000000000000000000000000000..6a187edb1828256362617d3fe24d26cf58e7ca3b
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/scipy/io/matlab/tests/data/testcomplex_7.4_GLNX86.mat differ
diff --git a/.venv/lib/python3.12/site-packages/scipy/io/matlab/tests/data/testdouble_4.2c_SOL2.mat b/.venv/lib/python3.12/site-packages/scipy/io/matlab/tests/data/testdouble_4.2c_SOL2.mat
new file mode 100644
index 0000000000000000000000000000000000000000..5dbfcf17dd0e01dc0325dd009340291158906e8d
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/scipy/io/matlab/tests/data/testdouble_4.2c_SOL2.mat differ
diff --git a/.venv/lib/python3.12/site-packages/scipy/io/matlab/tests/data/testdouble_6.1_SOL2.mat b/.venv/lib/python3.12/site-packages/scipy/io/matlab/tests/data/testdouble_6.1_SOL2.mat
new file mode 100644
index 0000000000000000000000000000000000000000..8e36c0c8ce62d7559b60fde454a96e8eefcbcb92
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/scipy/io/matlab/tests/data/testdouble_6.1_SOL2.mat differ
diff --git a/.venv/lib/python3.12/site-packages/scipy/io/matlab/tests/data/testdouble_6.5.1_GLNX86.mat b/.venv/lib/python3.12/site-packages/scipy/io/matlab/tests/data/testdouble_6.5.1_GLNX86.mat
new file mode 100644
index 0000000000000000000000000000000000000000..a003b6d866f77a25d3b8b236bc95e343221e3019
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/scipy/io/matlab/tests/data/testdouble_6.5.1_GLNX86.mat differ
diff --git a/.venv/lib/python3.12/site-packages/scipy/io/matlab/tests/data/testdouble_7.1_GLNX86.mat b/.venv/lib/python3.12/site-packages/scipy/io/matlab/tests/data/testdouble_7.1_GLNX86.mat
new file mode 100644
index 0000000000000000000000000000000000000000..3106712e1099345b48dc4e4125d5e739c24b5341
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/scipy/io/matlab/tests/data/testdouble_7.1_GLNX86.mat differ
diff --git a/.venv/lib/python3.12/site-packages/scipy/io/matlab/tests/data/testdouble_7.4_GLNX86.mat b/.venv/lib/python3.12/site-packages/scipy/io/matlab/tests/data/testdouble_7.4_GLNX86.mat
new file mode 100644
index 0000000000000000000000000000000000000000..9097bb08712d5bfccf172b0366573f503136228d
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/scipy/io/matlab/tests/data/testdouble_7.4_GLNX86.mat differ
diff --git a/.venv/lib/python3.12/site-packages/scipy/io/matlab/tests/data/testemptycell_5.3_SOL2.mat b/.venv/lib/python3.12/site-packages/scipy/io/matlab/tests/data/testemptycell_5.3_SOL2.mat
new file mode 100644
index 0000000000000000000000000000000000000000..e7dec3b81abdae8769e0ae0329948548f4038adf
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/scipy/io/matlab/tests/data/testemptycell_5.3_SOL2.mat differ
diff --git a/.venv/lib/python3.12/site-packages/scipy/io/matlab/tests/data/testemptycell_6.5.1_GLNX86.mat b/.venv/lib/python3.12/site-packages/scipy/io/matlab/tests/data/testemptycell_6.5.1_GLNX86.mat
new file mode 100644
index 0000000000000000000000000000000000000000..a1c93483597f364443158132b31b86693891b02a
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/scipy/io/matlab/tests/data/testemptycell_6.5.1_GLNX86.mat differ
diff --git a/.venv/lib/python3.12/site-packages/scipy/io/matlab/tests/data/testemptycell_7.1_GLNX86.mat b/.venv/lib/python3.12/site-packages/scipy/io/matlab/tests/data/testemptycell_7.1_GLNX86.mat
new file mode 100644
index 0000000000000000000000000000000000000000..f29d4f9327aa906729234a38caa05ebfc50cfc30
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/scipy/io/matlab/tests/data/testemptycell_7.1_GLNX86.mat differ
diff --git a/.venv/lib/python3.12/site-packages/scipy/io/matlab/tests/data/testemptycell_7.4_GLNX86.mat b/.venv/lib/python3.12/site-packages/scipy/io/matlab/tests/data/testemptycell_7.4_GLNX86.mat
new file mode 100644
index 0000000000000000000000000000000000000000..8b244044cf3028df9a019a259d8fc533b80f7fb7
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/scipy/io/matlab/tests/data/testemptycell_7.4_GLNX86.mat differ
diff --git a/.venv/lib/python3.12/site-packages/scipy/io/matlab/tests/data/testfunc_7.4_GLNX86.mat b/.venv/lib/python3.12/site-packages/scipy/io/matlab/tests/data/testfunc_7.4_GLNX86.mat
new file mode 100644
index 0000000000000000000000000000000000000000..adb6c28ee95d1cf8bf3bfeb72295d1a7848020f8
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/scipy/io/matlab/tests/data/testfunc_7.4_GLNX86.mat differ
diff --git a/.venv/lib/python3.12/site-packages/scipy/io/matlab/tests/data/testhdf5_7.4_GLNX86.mat b/.venv/lib/python3.12/site-packages/scipy/io/matlab/tests/data/testhdf5_7.4_GLNX86.mat
new file mode 100644
index 0000000000000000000000000000000000000000..6066c1e30f69b76afdb8d251ecefd8cd9e1acde5
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/scipy/io/matlab/tests/data/testhdf5_7.4_GLNX86.mat differ
diff --git a/.venv/lib/python3.12/site-packages/scipy/io/matlab/tests/data/testmatlabstring_7_WIN64.mat b/.venv/lib/python3.12/site-packages/scipy/io/matlab/tests/data/testmatlabstring_7_WIN64.mat
new file mode 100644
index 0000000000000000000000000000000000000000..26344543b08ed9b57fb9fd8f411e64325e9bcab8
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/scipy/io/matlab/tests/data/testmatlabstring_7_WIN64.mat differ
diff --git a/.venv/lib/python3.12/site-packages/scipy/io/matlab/tests/data/testmatrix_4.2c_SOL2.mat b/.venv/lib/python3.12/site-packages/scipy/io/matlab/tests/data/testmatrix_4.2c_SOL2.mat
new file mode 100644
index 0000000000000000000000000000000000000000..3698c8853b46d4a42194002523b57fddfb225908
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/scipy/io/matlab/tests/data/testmatrix_4.2c_SOL2.mat differ
diff --git a/.venv/lib/python3.12/site-packages/scipy/io/matlab/tests/data/testmatrix_6.1_SOL2.mat b/.venv/lib/python3.12/site-packages/scipy/io/matlab/tests/data/testmatrix_6.1_SOL2.mat
new file mode 100644
index 0000000000000000000000000000000000000000..164be1109d977cf7681b1ea00a5df80d5e8f8e71
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/scipy/io/matlab/tests/data/testmatrix_6.1_SOL2.mat differ
diff --git a/.venv/lib/python3.12/site-packages/scipy/io/matlab/tests/data/testmatrix_6.5.1_GLNX86.mat b/.venv/lib/python3.12/site-packages/scipy/io/matlab/tests/data/testmatrix_6.5.1_GLNX86.mat
new file mode 100644
index 0000000000000000000000000000000000000000..a8735e9a23558ce86a528ceafa8f3475b053e43b
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/scipy/io/matlab/tests/data/testmatrix_6.5.1_GLNX86.mat differ
diff --git a/.venv/lib/python3.12/site-packages/scipy/io/matlab/tests/data/testmatrix_7.1_GLNX86.mat b/.venv/lib/python3.12/site-packages/scipy/io/matlab/tests/data/testmatrix_7.1_GLNX86.mat
new file mode 100644
index 0000000000000000000000000000000000000000..b6fb05bb7564c863d5bb6c145fe8b06928d3805a
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/scipy/io/matlab/tests/data/testmatrix_7.1_GLNX86.mat differ
diff --git a/.venv/lib/python3.12/site-packages/scipy/io/matlab/tests/data/testmatrix_7.4_GLNX86.mat b/.venv/lib/python3.12/site-packages/scipy/io/matlab/tests/data/testmatrix_7.4_GLNX86.mat
new file mode 100644
index 0000000000000000000000000000000000000000..eb537ab1042b0f989d49711b1a36cc508946fe55
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/scipy/io/matlab/tests/data/testmatrix_7.4_GLNX86.mat differ
diff --git a/.venv/lib/python3.12/site-packages/scipy/io/matlab/tests/data/testminus_4.2c_SOL2.mat b/.venv/lib/python3.12/site-packages/scipy/io/matlab/tests/data/testminus_4.2c_SOL2.mat
new file mode 100644
index 0000000000000000000000000000000000000000..cc207ed9f32095f39b7690e2dc1e2dc0d55ee8e0
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/scipy/io/matlab/tests/data/testminus_4.2c_SOL2.mat differ
diff --git a/.venv/lib/python3.12/site-packages/scipy/io/matlab/tests/data/testminus_6.1_SOL2.mat b/.venv/lib/python3.12/site-packages/scipy/io/matlab/tests/data/testminus_6.1_SOL2.mat
new file mode 100644
index 0000000000000000000000000000000000000000..c2f0ba2ae4c8a1750cace6eae0267e9736272fc0
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/scipy/io/matlab/tests/data/testminus_6.1_SOL2.mat differ
diff --git a/.venv/lib/python3.12/site-packages/scipy/io/matlab/tests/data/testminus_6.5.1_GLNX86.mat b/.venv/lib/python3.12/site-packages/scipy/io/matlab/tests/data/testminus_6.5.1_GLNX86.mat
new file mode 100644
index 0000000000000000000000000000000000000000..b4dbd152d6e9f3d289b3c4a9792729d2735a4c5c
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/scipy/io/matlab/tests/data/testminus_6.5.1_GLNX86.mat differ
diff --git a/.venv/lib/python3.12/site-packages/scipy/io/matlab/tests/data/testminus_7.1_GLNX86.mat b/.venv/lib/python3.12/site-packages/scipy/io/matlab/tests/data/testminus_7.1_GLNX86.mat
new file mode 100644
index 0000000000000000000000000000000000000000..fadcd2366b1867239782f073291ff327c2af3001
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/scipy/io/matlab/tests/data/testminus_7.1_GLNX86.mat differ
diff --git a/.venv/lib/python3.12/site-packages/scipy/io/matlab/tests/data/testminus_7.4_GLNX86.mat b/.venv/lib/python3.12/site-packages/scipy/io/matlab/tests/data/testminus_7.4_GLNX86.mat
new file mode 100644
index 0000000000000000000000000000000000000000..9ce65f91116f68332d1c16e21319e965541d0d73
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/scipy/io/matlab/tests/data/testminus_7.4_GLNX86.mat differ
diff --git a/.venv/lib/python3.12/site-packages/scipy/io/matlab/tests/data/testmulti_4.2c_SOL2.mat b/.venv/lib/python3.12/site-packages/scipy/io/matlab/tests/data/testmulti_4.2c_SOL2.mat
new file mode 100644
index 0000000000000000000000000000000000000000..9c6ba793cf41bf36447ab7a1890447fe5e939614
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/scipy/io/matlab/tests/data/testmulti_4.2c_SOL2.mat differ
diff --git a/.venv/lib/python3.12/site-packages/scipy/io/matlab/tests/data/testmulti_7.1_GLNX86.mat b/.venv/lib/python3.12/site-packages/scipy/io/matlab/tests/data/testmulti_7.1_GLNX86.mat
new file mode 100644
index 0000000000000000000000000000000000000000..0c4729c56b6ab1e8945249a4d3144c79d8538e9e
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/scipy/io/matlab/tests/data/testmulti_7.1_GLNX86.mat differ
diff --git a/.venv/lib/python3.12/site-packages/scipy/io/matlab/tests/data/testmulti_7.4_GLNX86.mat b/.venv/lib/python3.12/site-packages/scipy/io/matlab/tests/data/testmulti_7.4_GLNX86.mat
new file mode 100644
index 0000000000000000000000000000000000000000..6d3e068977edfe6407f29404f0a7d1737f7d3eba
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/scipy/io/matlab/tests/data/testmulti_7.4_GLNX86.mat differ
diff --git a/.venv/lib/python3.12/site-packages/scipy/io/matlab/tests/data/testobject_6.1_SOL2.mat b/.venv/lib/python3.12/site-packages/scipy/io/matlab/tests/data/testobject_6.1_SOL2.mat
new file mode 100644
index 0000000000000000000000000000000000000000..fc13642263a64874f6c2ac602be9cdcb9b788996
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/scipy/io/matlab/tests/data/testobject_6.1_SOL2.mat differ
diff --git a/.venv/lib/python3.12/site-packages/scipy/io/matlab/tests/data/testobject_6.5.1_GLNX86.mat b/.venv/lib/python3.12/site-packages/scipy/io/matlab/tests/data/testobject_6.5.1_GLNX86.mat
new file mode 100644
index 0000000000000000000000000000000000000000..f68323b0c8eb7fc999dead349ea3bd3a6da66bd4
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/scipy/io/matlab/tests/data/testobject_6.5.1_GLNX86.mat differ
diff --git a/.venv/lib/python3.12/site-packages/scipy/io/matlab/tests/data/testobject_7.1_GLNX86.mat b/.venv/lib/python3.12/site-packages/scipy/io/matlab/tests/data/testobject_7.1_GLNX86.mat
new file mode 100644
index 0000000000000000000000000000000000000000..83dcad34249afa543bf66dae9b836276246aab4a
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/scipy/io/matlab/tests/data/testobject_7.1_GLNX86.mat differ
diff --git a/.venv/lib/python3.12/site-packages/scipy/io/matlab/tests/data/testobject_7.4_GLNX86.mat b/.venv/lib/python3.12/site-packages/scipy/io/matlab/tests/data/testobject_7.4_GLNX86.mat
new file mode 100644
index 0000000000000000000000000000000000000000..59d243c4de4fbb3fa653753e40651a6d0a4f4967
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/scipy/io/matlab/tests/data/testobject_7.4_GLNX86.mat differ
diff --git a/.venv/lib/python3.12/site-packages/scipy/io/matlab/tests/data/testonechar_4.2c_SOL2.mat b/.venv/lib/python3.12/site-packages/scipy/io/matlab/tests/data/testonechar_4.2c_SOL2.mat
new file mode 100644
index 0000000000000000000000000000000000000000..cdb4191c7d2eb0ac66d4f6add250e1f6a604d892
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/scipy/io/matlab/tests/data/testonechar_4.2c_SOL2.mat differ
diff --git a/.venv/lib/python3.12/site-packages/scipy/io/matlab/tests/data/testonechar_6.1_SOL2.mat b/.venv/lib/python3.12/site-packages/scipy/io/matlab/tests/data/testonechar_6.1_SOL2.mat
new file mode 100644
index 0000000000000000000000000000000000000000..3b5a428501a53ae7308c7b6edc42f4881820664d
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/scipy/io/matlab/tests/data/testonechar_6.1_SOL2.mat differ
diff --git a/.venv/lib/python3.12/site-packages/scipy/io/matlab/tests/data/testonechar_6.5.1_GLNX86.mat b/.venv/lib/python3.12/site-packages/scipy/io/matlab/tests/data/testonechar_6.5.1_GLNX86.mat
new file mode 100644
index 0000000000000000000000000000000000000000..8cef2dd7ea6df8aac26ed067a9427935b81c7ac7
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/scipy/io/matlab/tests/data/testonechar_6.5.1_GLNX86.mat differ
diff --git a/.venv/lib/python3.12/site-packages/scipy/io/matlab/tests/data/testonechar_7.1_GLNX86.mat b/.venv/lib/python3.12/site-packages/scipy/io/matlab/tests/data/testonechar_7.1_GLNX86.mat
new file mode 100644
index 0000000000000000000000000000000000000000..5ba4810ac67756c17b0ef3163a496e913c0b5e57
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/scipy/io/matlab/tests/data/testonechar_7.1_GLNX86.mat differ
diff --git a/.venv/lib/python3.12/site-packages/scipy/io/matlab/tests/data/testonechar_7.4_GLNX86.mat b/.venv/lib/python3.12/site-packages/scipy/io/matlab/tests/data/testonechar_7.4_GLNX86.mat
new file mode 100644
index 0000000000000000000000000000000000000000..8964765f7bd207bfab63b4d16569cb1c3763bda7
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/scipy/io/matlab/tests/data/testonechar_7.4_GLNX86.mat differ
diff --git a/.venv/lib/python3.12/site-packages/scipy/io/matlab/tests/data/testscalarcell_7.4_GLNX86.mat b/.venv/lib/python3.12/site-packages/scipy/io/matlab/tests/data/testscalarcell_7.4_GLNX86.mat
new file mode 100644
index 0000000000000000000000000000000000000000..1dcd72e51a51abdcf48bd37f68b9927421c17cb0
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/scipy/io/matlab/tests/data/testscalarcell_7.4_GLNX86.mat differ
diff --git a/.venv/lib/python3.12/site-packages/scipy/io/matlab/tests/data/testsimplecell.mat b/.venv/lib/python3.12/site-packages/scipy/io/matlab/tests/data/testsimplecell.mat
new file mode 100644
index 0000000000000000000000000000000000000000..2a98f48917f8f275e541eeac5ef1fe741c40bb0b
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/scipy/io/matlab/tests/data/testsimplecell.mat differ
diff --git a/.venv/lib/python3.12/site-packages/scipy/io/matlab/tests/data/testsparse_4.2c_SOL2.mat b/.venv/lib/python3.12/site-packages/scipy/io/matlab/tests/data/testsparse_4.2c_SOL2.mat
new file mode 100644
index 0000000000000000000000000000000000000000..55cbd3c1b3d65630beae47832ffbcc7a6fd43354
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/scipy/io/matlab/tests/data/testsparse_4.2c_SOL2.mat differ
diff --git a/.venv/lib/python3.12/site-packages/scipy/io/matlab/tests/data/testsparse_6.1_SOL2.mat b/.venv/lib/python3.12/site-packages/scipy/io/matlab/tests/data/testsparse_6.1_SOL2.mat
new file mode 100644
index 0000000000000000000000000000000000000000..194ca4d7d4d4d22be5669041a25c3ca24ae6edcb
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/scipy/io/matlab/tests/data/testsparse_6.1_SOL2.mat differ
diff --git a/.venv/lib/python3.12/site-packages/scipy/io/matlab/tests/data/testsparse_6.5.1_GLNX86.mat b/.venv/lib/python3.12/site-packages/scipy/io/matlab/tests/data/testsparse_6.5.1_GLNX86.mat
new file mode 100644
index 0000000000000000000000000000000000000000..3e1e9a1ec916040e94c231f428725add10a2709c
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/scipy/io/matlab/tests/data/testsparse_6.5.1_GLNX86.mat differ
diff --git a/.venv/lib/python3.12/site-packages/scipy/io/matlab/tests/data/testsparse_7.1_GLNX86.mat b/.venv/lib/python3.12/site-packages/scipy/io/matlab/tests/data/testsparse_7.1_GLNX86.mat
new file mode 100644
index 0000000000000000000000000000000000000000..55b510762ee9b0ac04776e38f6b4bb46b0d10021
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/scipy/io/matlab/tests/data/testsparse_7.1_GLNX86.mat differ
diff --git a/.venv/lib/python3.12/site-packages/scipy/io/matlab/tests/data/testsparse_7.4_GLNX86.mat b/.venv/lib/python3.12/site-packages/scipy/io/matlab/tests/data/testsparse_7.4_GLNX86.mat
new file mode 100644
index 0000000000000000000000000000000000000000..bdb6ce66ce79b808f044124156db4b803dab155e
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/scipy/io/matlab/tests/data/testsparse_7.4_GLNX86.mat differ
diff --git a/.venv/lib/python3.12/site-packages/scipy/io/matlab/tests/data/testsparsecomplex_4.2c_SOL2.mat b/.venv/lib/python3.12/site-packages/scipy/io/matlab/tests/data/testsparsecomplex_4.2c_SOL2.mat
new file mode 100644
index 0000000000000000000000000000000000000000..81c536d0b067b92cae1b7a2ee71824e2c5e730d9
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/scipy/io/matlab/tests/data/testsparsecomplex_4.2c_SOL2.mat differ
diff --git a/.venv/lib/python3.12/site-packages/scipy/io/matlab/tests/data/testsparsecomplex_6.1_SOL2.mat b/.venv/lib/python3.12/site-packages/scipy/io/matlab/tests/data/testsparsecomplex_6.1_SOL2.mat
new file mode 100644
index 0000000000000000000000000000000000000000..520e1cedb3823b859666b1fa8872e073904fd4c6
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/scipy/io/matlab/tests/data/testsparsecomplex_6.1_SOL2.mat differ
diff --git a/.venv/lib/python3.12/site-packages/scipy/io/matlab/tests/data/testsparsecomplex_6.5.1_GLNX86.mat b/.venv/lib/python3.12/site-packages/scipy/io/matlab/tests/data/testsparsecomplex_6.5.1_GLNX86.mat
new file mode 100644
index 0000000000000000000000000000000000000000..969b7143dfff3bb817dbf70c54af8303c3b5822e
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/scipy/io/matlab/tests/data/testsparsecomplex_6.5.1_GLNX86.mat differ
diff --git a/.venv/lib/python3.12/site-packages/scipy/io/matlab/tests/data/testsparsecomplex_7.1_GLNX86.mat b/.venv/lib/python3.12/site-packages/scipy/io/matlab/tests/data/testsparsecomplex_7.1_GLNX86.mat
new file mode 100644
index 0000000000000000000000000000000000000000..9117dce3092e3e6a39b67da9a7ad1dcfc3ded385
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/scipy/io/matlab/tests/data/testsparsecomplex_7.1_GLNX86.mat differ
diff --git a/.venv/lib/python3.12/site-packages/scipy/io/matlab/tests/data/testsparsecomplex_7.4_GLNX86.mat b/.venv/lib/python3.12/site-packages/scipy/io/matlab/tests/data/testsparsecomplex_7.4_GLNX86.mat
new file mode 100644
index 0000000000000000000000000000000000000000..a8a615a320f9c8db068a9120c1ceb2e49bb0ea6d
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/scipy/io/matlab/tests/data/testsparsecomplex_7.4_GLNX86.mat differ
diff --git a/.venv/lib/python3.12/site-packages/scipy/io/matlab/tests/data/testsparsefloat_7.4_GLNX86.mat b/.venv/lib/python3.12/site-packages/scipy/io/matlab/tests/data/testsparsefloat_7.4_GLNX86.mat
new file mode 100644
index 0000000000000000000000000000000000000000..15424266a3bd4aa1e7525a8fdc4945b51d2b5ad6
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/scipy/io/matlab/tests/data/testsparsefloat_7.4_GLNX86.mat differ
diff --git a/.venv/lib/python3.12/site-packages/scipy/io/matlab/tests/data/teststring_4.2c_SOL2.mat b/.venv/lib/python3.12/site-packages/scipy/io/matlab/tests/data/teststring_4.2c_SOL2.mat
new file mode 100644
index 0000000000000000000000000000000000000000..137561e1f636d7b08959e43e969a6984eb7a3b37
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/scipy/io/matlab/tests/data/teststring_4.2c_SOL2.mat differ
diff --git a/.venv/lib/python3.12/site-packages/scipy/io/matlab/tests/data/teststring_6.1_SOL2.mat b/.venv/lib/python3.12/site-packages/scipy/io/matlab/tests/data/teststring_6.1_SOL2.mat
new file mode 100644
index 0000000000000000000000000000000000000000..2ad75f2e17d8b3fda285490d52b426d1f27d0d95
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/scipy/io/matlab/tests/data/teststring_6.1_SOL2.mat differ
diff --git a/.venv/lib/python3.12/site-packages/scipy/io/matlab/tests/data/teststring_6.5.1_GLNX86.mat b/.venv/lib/python3.12/site-packages/scipy/io/matlab/tests/data/teststring_6.5.1_GLNX86.mat
new file mode 100644
index 0000000000000000000000000000000000000000..6fd12d884d19df65f1534c13944e988e636166f1
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/scipy/io/matlab/tests/data/teststring_6.5.1_GLNX86.mat differ
diff --git a/.venv/lib/python3.12/site-packages/scipy/io/matlab/tests/data/teststring_7.1_GLNX86.mat b/.venv/lib/python3.12/site-packages/scipy/io/matlab/tests/data/teststring_7.1_GLNX86.mat
new file mode 100644
index 0000000000000000000000000000000000000000..ab93994f7befe7d1505c84c238d6409bcb3d438a
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/scipy/io/matlab/tests/data/teststring_7.1_GLNX86.mat differ
diff --git a/.venv/lib/python3.12/site-packages/scipy/io/matlab/tests/data/teststring_7.4_GLNX86.mat b/.venv/lib/python3.12/site-packages/scipy/io/matlab/tests/data/teststring_7.4_GLNX86.mat
new file mode 100644
index 0000000000000000000000000000000000000000..63059b84476749119f44ebefda795f85f6ab27d7
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/scipy/io/matlab/tests/data/teststring_7.4_GLNX86.mat differ
diff --git a/.venv/lib/python3.12/site-packages/scipy/io/matlab/tests/data/teststringarray_4.2c_SOL2.mat b/.venv/lib/python3.12/site-packages/scipy/io/matlab/tests/data/teststringarray_4.2c_SOL2.mat
new file mode 100644
index 0000000000000000000000000000000000000000..fa687ee988ce530bca87f46235667baa30ac038b
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/scipy/io/matlab/tests/data/teststringarray_4.2c_SOL2.mat differ
diff --git a/.venv/lib/python3.12/site-packages/scipy/io/matlab/tests/data/teststringarray_6.1_SOL2.mat b/.venv/lib/python3.12/site-packages/scipy/io/matlab/tests/data/teststringarray_6.1_SOL2.mat
new file mode 100644
index 0000000000000000000000000000000000000000..11afb412056ad803f0d8ac1d9dcb188d42285fdf
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/scipy/io/matlab/tests/data/teststringarray_6.1_SOL2.mat differ
diff --git a/.venv/lib/python3.12/site-packages/scipy/io/matlab/tests/data/teststringarray_6.5.1_GLNX86.mat b/.venv/lib/python3.12/site-packages/scipy/io/matlab/tests/data/teststringarray_6.5.1_GLNX86.mat
new file mode 100644
index 0000000000000000000000000000000000000000..75e07a0b55e008b070f41dabba7480a4e463b67a
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/scipy/io/matlab/tests/data/teststringarray_6.5.1_GLNX86.mat differ
diff --git a/.venv/lib/python3.12/site-packages/scipy/io/matlab/tests/data/teststringarray_7.1_GLNX86.mat b/.venv/lib/python3.12/site-packages/scipy/io/matlab/tests/data/teststringarray_7.1_GLNX86.mat
new file mode 100644
index 0000000000000000000000000000000000000000..7d76f63643737834053f80539188c9dad75ed0cb
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/scipy/io/matlab/tests/data/teststringarray_7.1_GLNX86.mat differ
diff --git a/.venv/lib/python3.12/site-packages/scipy/io/matlab/tests/data/teststringarray_7.4_GLNX86.mat b/.venv/lib/python3.12/site-packages/scipy/io/matlab/tests/data/teststringarray_7.4_GLNX86.mat
new file mode 100644
index 0000000000000000000000000000000000000000..954e39beb8156b460ca904ff66261d8f2fc338cb
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/scipy/io/matlab/tests/data/teststringarray_7.4_GLNX86.mat differ
diff --git a/.venv/lib/python3.12/site-packages/scipy/io/matlab/tests/data/teststruct_6.1_SOL2.mat b/.venv/lib/python3.12/site-packages/scipy/io/matlab/tests/data/teststruct_6.1_SOL2.mat
new file mode 100644
index 0000000000000000000000000000000000000000..5086bb7acdc3773186e903000aace436c90dc565
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/scipy/io/matlab/tests/data/teststruct_6.1_SOL2.mat differ
diff --git a/.venv/lib/python3.12/site-packages/scipy/io/matlab/tests/data/teststruct_6.5.1_GLNX86.mat b/.venv/lib/python3.12/site-packages/scipy/io/matlab/tests/data/teststruct_6.5.1_GLNX86.mat
new file mode 100644
index 0000000000000000000000000000000000000000..6feb6e42375ebebf6dd9440ee09312204cbf1a33
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/scipy/io/matlab/tests/data/teststruct_6.5.1_GLNX86.mat differ
diff --git a/.venv/lib/python3.12/site-packages/scipy/io/matlab/tests/data/teststruct_7.1_GLNX86.mat b/.venv/lib/python3.12/site-packages/scipy/io/matlab/tests/data/teststruct_7.1_GLNX86.mat
new file mode 100644
index 0000000000000000000000000000000000000000..b2ff2226223181ec5c42d36afe4f56728f25972d
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/scipy/io/matlab/tests/data/teststruct_7.1_GLNX86.mat differ
diff --git a/.venv/lib/python3.12/site-packages/scipy/io/matlab/tests/data/teststruct_7.4_GLNX86.mat b/.venv/lib/python3.12/site-packages/scipy/io/matlab/tests/data/teststruct_7.4_GLNX86.mat
new file mode 100644
index 0000000000000000000000000000000000000000..028841f9d3aae42d6cf782db14634cbe375f0a05
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/scipy/io/matlab/tests/data/teststruct_7.4_GLNX86.mat differ
diff --git a/.venv/lib/python3.12/site-packages/scipy/io/matlab/tests/data/teststructarr_6.1_SOL2.mat b/.venv/lib/python3.12/site-packages/scipy/io/matlab/tests/data/teststructarr_6.1_SOL2.mat
new file mode 100644
index 0000000000000000000000000000000000000000..da57365926afe1e8d7dd424a6fcd5b52bc3233ac
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/scipy/io/matlab/tests/data/teststructarr_6.1_SOL2.mat differ
diff --git a/.venv/lib/python3.12/site-packages/scipy/io/matlab/tests/data/teststructarr_6.5.1_GLNX86.mat b/.venv/lib/python3.12/site-packages/scipy/io/matlab/tests/data/teststructarr_6.5.1_GLNX86.mat
new file mode 100644
index 0000000000000000000000000000000000000000..d1c97a7a2e1edf9683959ec36e899ef8e355073c
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/scipy/io/matlab/tests/data/teststructarr_6.5.1_GLNX86.mat differ
diff --git a/.venv/lib/python3.12/site-packages/scipy/io/matlab/tests/data/teststructarr_7.1_GLNX86.mat b/.venv/lib/python3.12/site-packages/scipy/io/matlab/tests/data/teststructarr_7.1_GLNX86.mat
new file mode 100644
index 0000000000000000000000000000000000000000..c7ca09594106a765e815a55e942019d17c181270
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/scipy/io/matlab/tests/data/teststructarr_7.1_GLNX86.mat differ
diff --git a/.venv/lib/python3.12/site-packages/scipy/io/matlab/tests/data/teststructarr_7.4_GLNX86.mat b/.venv/lib/python3.12/site-packages/scipy/io/matlab/tests/data/teststructarr_7.4_GLNX86.mat
new file mode 100644
index 0000000000000000000000000000000000000000..8716f7e3db67d1fd479f913d12286715029ed1a4
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/scipy/io/matlab/tests/data/teststructarr_7.4_GLNX86.mat differ
diff --git a/.venv/lib/python3.12/site-packages/scipy/io/matlab/tests/data/teststructnest_6.1_SOL2.mat b/.venv/lib/python3.12/site-packages/scipy/io/matlab/tests/data/teststructnest_6.1_SOL2.mat
new file mode 100644
index 0000000000000000000000000000000000000000..2c34c4d8c1477bc4859880a8d2f800073825dcd1
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/scipy/io/matlab/tests/data/teststructnest_6.1_SOL2.mat differ
diff --git a/.venv/lib/python3.12/site-packages/scipy/io/matlab/tests/data/teststructnest_6.5.1_GLNX86.mat b/.venv/lib/python3.12/site-packages/scipy/io/matlab/tests/data/teststructnest_6.5.1_GLNX86.mat
new file mode 100644
index 0000000000000000000000000000000000000000..c6dccc00289f61787b235f4299aa5a14ab4f6d07
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/scipy/io/matlab/tests/data/teststructnest_6.5.1_GLNX86.mat differ
diff --git a/.venv/lib/python3.12/site-packages/scipy/io/matlab/tests/data/teststructnest_7.1_GLNX86.mat b/.venv/lib/python3.12/site-packages/scipy/io/matlab/tests/data/teststructnest_7.1_GLNX86.mat
new file mode 100644
index 0000000000000000000000000000000000000000..0f6f5444b0c1e4bcd80dc0f63b28523d655b05d0
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/scipy/io/matlab/tests/data/teststructnest_7.1_GLNX86.mat differ
diff --git a/.venv/lib/python3.12/site-packages/scipy/io/matlab/tests/data/teststructnest_7.4_GLNX86.mat b/.venv/lib/python3.12/site-packages/scipy/io/matlab/tests/data/teststructnest_7.4_GLNX86.mat
new file mode 100644
index 0000000000000000000000000000000000000000..faf9221b776eee67cd5d2971da5ba77732ef8016
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/scipy/io/matlab/tests/data/teststructnest_7.4_GLNX86.mat differ
diff --git a/.venv/lib/python3.12/site-packages/scipy/io/matlab/tests/data/testunicode_7.1_GLNX86.mat b/.venv/lib/python3.12/site-packages/scipy/io/matlab/tests/data/testunicode_7.1_GLNX86.mat
new file mode 100644
index 0000000000000000000000000000000000000000..1b7b3d7f002080839f672e4eb858bbfbddda27ec
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/scipy/io/matlab/tests/data/testunicode_7.1_GLNX86.mat differ
diff --git a/.venv/lib/python3.12/site-packages/scipy/io/matlab/tests/data/testunicode_7.4_GLNX86.mat b/.venv/lib/python3.12/site-packages/scipy/io/matlab/tests/data/testunicode_7.4_GLNX86.mat
new file mode 100644
index 0000000000000000000000000000000000000000..d22fb57c81fc3ec9ee7e9b447a05e8a89ff1fcfe
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/scipy/io/matlab/tests/data/testunicode_7.4_GLNX86.mat differ
diff --git a/.venv/lib/python3.12/site-packages/scipy/io/matlab/tests/data/testvec_4_GLNX86.mat b/.venv/lib/python3.12/site-packages/scipy/io/matlab/tests/data/testvec_4_GLNX86.mat
new file mode 100644
index 0000000000000000000000000000000000000000..76c51d01388a1770b348bc603ebfdd51bc011f0c
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/scipy/io/matlab/tests/data/testvec_4_GLNX86.mat differ
diff --git a/.venv/lib/python3.12/site-packages/scipy/io/matlab/tests/test_byteordercodes.py b/.venv/lib/python3.12/site-packages/scipy/io/matlab/tests/test_byteordercodes.py
new file mode 100644
index 0000000000000000000000000000000000000000..535434d188ff575029cc7a0de807b0daa7348f73
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/io/matlab/tests/test_byteordercodes.py
@@ -0,0 +1,29 @@
+''' Tests for byteorder module '''
+
+import sys
+
+from numpy.testing import assert_
+from pytest import raises as assert_raises
+
+import scipy.io.matlab._byteordercodes as sibc
+
+
+def test_native():
+    native_is_le = sys.byteorder == 'little'
+    assert_(sibc.sys_is_le == native_is_le)
+
+
+def test_to_numpy():
+    if sys.byteorder == 'little':
+        assert_(sibc.to_numpy_code('native') == '<')
+        assert_(sibc.to_numpy_code('swapped') == '>')
+    else:
+        assert_(sibc.to_numpy_code('native') == '>')
+        assert_(sibc.to_numpy_code('swapped') == '<')
+    assert_(sibc.to_numpy_code('native') == sibc.to_numpy_code('='))
+    assert_(sibc.to_numpy_code('big') == '>')
+    for code in ('little', '<', 'l', 'L', 'le'):
+        assert_(sibc.to_numpy_code(code) == '<')
+    for code in ('big', '>', 'b', 'B', 'be'):
+        assert_(sibc.to_numpy_code(code) == '>')
+    assert_raises(ValueError, sibc.to_numpy_code, 'silly string')
diff --git a/.venv/lib/python3.12/site-packages/scipy/io/matlab/tests/test_mio.py b/.venv/lib/python3.12/site-packages/scipy/io/matlab/tests/test_mio.py
new file mode 100644
index 0000000000000000000000000000000000000000..006284a49a1ae437bae9b116a33930e9a231551b
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/io/matlab/tests/test_mio.py
@@ -0,0 +1,1475 @@
+import os
+from collections import OrderedDict
+from os.path import join as pjoin, dirname
+from glob import glob
+from io import BytesIO
+import re
+from tempfile import mkdtemp
+
+import warnings
+import shutil
+import gzip
+
+from numpy.testing import (assert_array_equal, assert_array_almost_equal,
+                           assert_equal, assert_, assert_allclose)
+import pytest
+from pytest import raises as assert_raises, warns as assert_warns
+
+import numpy as np
+from numpy import array
+from scipy.sparse import issparse, eye_array, coo_array, csc_array, sparray
+
+import scipy.io
+from scipy.io.matlab import MatlabOpaque, MatlabFunction, MatlabObject
+import scipy.io.matlab._byteordercodes as boc
+from scipy.io.matlab._miobase import (matdims, MatWriteError, MatReadError,
+                                      matfile_version, MatWriteWarning)
+from scipy.io.matlab._mio import mat_reader_factory, loadmat, savemat, whosmat
+from scipy.io.matlab._mio5 import (
+    MatFile5Writer, MatFile5Reader, varmats_from_mat, to_writeable,
+    EmptyStructMarker)
+import scipy.io.matlab._mio5_params as mio5p
+
+
+test_data_path = pjoin(dirname(__file__), 'data')
+pytestmark = pytest.mark.thread_unsafe
+
+
+def mlarr(*args, **kwargs):
+    """Convenience function to return matlab-compatible 2-D array."""
+    arr = np.array(*args, **kwargs)
+    arr = arr.reshape(matdims(arr))
+    return arr
+
+
+# Define cases to test
+theta = np.pi/4*np.arange(9,dtype=float).reshape(1,9)
+case_table4 = [
+    {'name': 'double',
+     'classes': {'testdouble': 'double'},
+     'expected': {'testdouble': theta}
+     }]
+case_table4.append(
+    {'name': 'string',
+     'classes': {'teststring': 'char'},
+     'expected': {'teststring':
+                  array(['"Do nine men interpret?" "Nine men," I nod.'])}
+     })
+case_table4.append(
+    {'name': 'complex',
+     'classes': {'testcomplex': 'double'},
+     'expected': {'testcomplex': np.cos(theta) + 1j*np.sin(theta)}
+     })
+A = np.zeros((3,5))
+A[0] = list(range(1,6))
+A[:,0] = list(range(1,4))
+case_table4.append(
+    {'name': 'matrix',
+     'classes': {'testmatrix': 'double'},
+     'expected': {'testmatrix': A},
+     })
+case_table4.append(
+    {'name': 'sparse',
+     'classes': {'testsparse': 'sparse'},
+     'expected': {'testsparse': coo_array(A)},
+     })
+B = A.astype(complex)
+B[0,0] += 1j
+case_table4.append(
+    {'name': 'sparsecomplex',
+     'classes': {'testsparsecomplex': 'sparse'},
+     'expected': {'testsparsecomplex': coo_array(B)},
+     })
+case_table4.append(
+    {'name': 'multi',
+     'classes': {'theta': 'double', 'a': 'double'},
+     'expected': {'theta': theta, 'a': A},
+     })
+case_table4.append(
+    {'name': 'minus',
+     'classes': {'testminus': 'double'},
+     'expected': {'testminus': mlarr(-1)},
+     })
+case_table4.append(
+    {'name': 'onechar',
+     'classes': {'testonechar': 'char'},
+     'expected': {'testonechar': array(['r'])},
+     })
+# Cell arrays stored as object arrays
+CA = mlarr((  # tuple for object array creation
+        [],
+        mlarr([1]),
+        mlarr([[1,2]]),
+        mlarr([[1,2,3]])), dtype=object).reshape(1,-1)
+CA[0,0] = array(
+    ['This cell contains this string and 3 arrays of increasing length'])
+case_table5 = [
+    {'name': 'cell',
+     'classes': {'testcell': 'cell'},
+     'expected': {'testcell': CA}}]
+CAE = mlarr((  # tuple for object array creation
+    mlarr(1),
+    mlarr(2),
+    mlarr([]),
+    mlarr([]),
+    mlarr(3)), dtype=object).reshape(1,-1)
+objarr = np.empty((1,1),dtype=object)
+objarr[0,0] = mlarr(1)
+case_table5.append(
+    {'name': 'scalarcell',
+     'classes': {'testscalarcell': 'cell'},
+     'expected': {'testscalarcell': objarr}
+     })
+case_table5.append(
+    {'name': 'emptycell',
+     'classes': {'testemptycell': 'cell'},
+     'expected': {'testemptycell': CAE}})
+case_table5.append(
+    {'name': 'stringarray',
+     'classes': {'teststringarray': 'char'},
+     'expected': {'teststringarray': array(
+    ['one  ', 'two  ', 'three'])},
+     })
+case_table5.append(
+    {'name': '3dmatrix',
+     'classes': {'test3dmatrix': 'double'},
+     'expected': {
+    'test3dmatrix': np.transpose(np.reshape(list(range(1,25)), (4,3,2)))}
+     })
+st_sub_arr = array([np.sqrt(2),np.exp(1),np.pi]).reshape(1,3)
+dtype = [(n, object) for n in ['stringfield', 'doublefield', 'complexfield']]
+st1 = np.zeros((1,1), dtype)
+st1['stringfield'][0,0] = array(['Rats live on no evil star.'])
+st1['doublefield'][0,0] = st_sub_arr
+st1['complexfield'][0,0] = st_sub_arr * (1 + 1j)
+case_table5.append(
+    {'name': 'struct',
+     'classes': {'teststruct': 'struct'},
+     'expected': {'teststruct': st1}
+     })
+CN = np.zeros((1,2), dtype=object)
+CN[0,0] = mlarr(1)
+CN[0,1] = np.zeros((1,3), dtype=object)
+CN[0,1][0,0] = mlarr(2, dtype=np.uint8)
+CN[0,1][0,1] = mlarr([[3]], dtype=np.uint8)
+CN[0,1][0,2] = np.zeros((1,2), dtype=object)
+CN[0,1][0,2][0,0] = mlarr(4, dtype=np.uint8)
+CN[0,1][0,2][0,1] = mlarr(5, dtype=np.uint8)
+case_table5.append(
+    {'name': 'cellnest',
+     'classes': {'testcellnest': 'cell'},
+     'expected': {'testcellnest': CN},
+     })
+st2 = np.empty((1,1), dtype=[(n, object) for n in ['one', 'two']])
+st2[0,0]['one'] = mlarr(1)
+st2[0,0]['two'] = np.empty((1,1), dtype=[('three', object)])
+st2[0,0]['two'][0,0]['three'] = array(['number 3'])
+case_table5.append(
+    {'name': 'structnest',
+     'classes': {'teststructnest': 'struct'},
+     'expected': {'teststructnest': st2}
+     })
+a = np.empty((1,2), dtype=[(n, object) for n in ['one', 'two']])
+a[0,0]['one'] = mlarr(1)
+a[0,0]['two'] = mlarr(2)
+a[0,1]['one'] = array(['number 1'])
+a[0,1]['two'] = array(['number 2'])
+case_table5.append(
+    {'name': 'structarr',
+     'classes': {'teststructarr': 'struct'},
+     'expected': {'teststructarr': a}
+     })
+ODT = np.dtype([(n, object) for n in
+                 ['expr', 'inputExpr', 'args',
+                  'isEmpty', 'numArgs', 'version']])
+MO = MatlabObject(np.zeros((1,1), dtype=ODT), 'inline')
+m0 = MO[0,0]
+m0['expr'] = array(['x'])
+m0['inputExpr'] = array([' x = INLINE_INPUTS_{1};'])
+m0['args'] = array(['x'])
+m0['isEmpty'] = mlarr(0)
+m0['numArgs'] = mlarr(1)
+m0['version'] = mlarr(1)
+case_table5.append(
+    {'name': 'object',
+     'classes': {'testobject': 'object'},
+     'expected': {'testobject': MO}
+     })
+fp_u_str = open(pjoin(test_data_path, 'japanese_utf8.txt'), 'rb')
+u_str = fp_u_str.read().decode('utf-8')
+fp_u_str.close()
+case_table5.append(
+    {'name': 'unicode',
+     'classes': {'testunicode': 'char'},
+    'expected': {'testunicode': array([u_str])}
+     })
+case_table5.append(
+    {'name': 'sparse',
+     'classes': {'testsparse': 'sparse'},
+     'expected': {'testsparse': coo_array(A)},
+     })
+case_table5.append(
+    {'name': 'sparsecomplex',
+     'classes': {'testsparsecomplex': 'sparse'},
+     'expected': {'testsparsecomplex': coo_array(B)},
+     })
+case_table5.append(
+    {'name': 'bool',
+     'classes': {'testbools': 'logical'},
+     'expected': {'testbools':
+                  array([[True], [False]])},
+     })
+
+case_table5_rt = case_table5[:]
+# Inline functions can't be concatenated in matlab, so RT only
+case_table5_rt.append(
+    {'name': 'objectarray',
+     'classes': {'testobjectarray': 'object'},
+     'expected': {'testobjectarray': np.repeat(MO, 2).reshape(1,2)}})
+
+
+def types_compatible(var1, var2):
+    """Check if types are same or compatible.
+
+    0-D numpy scalars are compatible with bare python scalars.
+    """
+    type1 = type(var1)
+    type2 = type(var2)
+    if type1 is type2:
+        return True
+    if type1 is np.ndarray and var1.shape == ():
+        return type(var1.item()) is type2
+    if type2 is np.ndarray and var2.shape == ():
+        return type(var2.item()) is type1
+    return False
+
+
+def _check_level(label, expected, actual):
+    """ Check one level of a potentially nested array """
+    if issparse(expected):  # allow different types of sparse matrices
+        assert_(issparse(actual))
+        assert_array_almost_equal(actual.toarray(),
+                                  expected.toarray(),
+                                  err_msg=label,
+                                  decimal=5)
+        return
+    # Check types are as expected
+    assert_(types_compatible(expected, actual),
+            f"Expected type {type(expected)}, got {type(actual)} at {label}")
+    # A field in a record array may not be an ndarray
+    # A scalar from a record array will be type np.void
+    if not isinstance(expected, np.void | np.ndarray | MatlabObject):
+        assert_equal(expected, actual)
+        return
+    # This is an ndarray-like thing
+    assert_(expected.shape == actual.shape,
+            msg=f'Expected shape {expected.shape}, got {actual.shape} at {label}')
+    ex_dtype = expected.dtype
+    if ex_dtype.hasobject:  # array of objects
+        if isinstance(expected, MatlabObject):
+            assert_equal(expected.classname, actual.classname)
+        for i, ev in enumerate(expected):
+            level_label = f"{label}, [{i}], "
+            _check_level(level_label, ev, actual[i])
+        return
+    if ex_dtype.fields:  # probably recarray
+        for fn in ex_dtype.fields:
+            level_label = f"{label}, field {fn}, "
+            _check_level(level_label,
+                         expected[fn], actual[fn])
+        return
+    if ex_dtype.type in (str,  # string or bool
+                         np.str_,
+                         np.bool_):
+        assert_equal(actual, expected, err_msg=label)
+        return
+    # Something numeric
+    assert_array_almost_equal(actual, expected, err_msg=label, decimal=5)
+
+
+def _load_check_case(name, files, case):
+    for file_name in files:
+        matdict = loadmat(file_name, struct_as_record=True, spmatrix=False)
+        label = f"test {name}; file {file_name}"
+        for k, expected in case.items():
+            k_label = f"{label}, variable {k}"
+            assert_(k in matdict, f"Missing key at {k_label}")
+            _check_level(k_label, expected, matdict[k])
+
+
+def _whos_check_case(name, files, case, classes):
+    for file_name in files:
+        label = f"test {name}; file {file_name}"
+
+        whos = whosmat(file_name)
+
+        expected_whos = [
+            (k, expected.shape, classes[k]) for k, expected in case.items()]
+
+        whos.sort()
+        expected_whos.sort()
+        assert_equal(whos, expected_whos,
+                     f"{label}: {whos!r} != {expected_whos!r}"
+                     )
+
+
+# Round trip tests
+def _rt_check_case(name, expected, format):
+    mat_stream = BytesIO()
+    savemat(mat_stream, expected, format=format)
+    mat_stream.seek(0)
+    _load_check_case(name, [mat_stream], expected)
+
+
+# generator for tests
+def _cases(version, filt='test%(name)s_*.mat'):
+    if version == '4':
+        cases = case_table4
+    elif version == '5':
+        cases = case_table5
+    else:
+        assert version == '5_rt'
+        cases = case_table5_rt
+    for case in cases:
+        name = case['name']
+        expected = case['expected']
+        if filt is None:
+            files = None
+        else:
+            use_filt = pjoin(test_data_path, filt % dict(name=name))
+            files = glob(use_filt)
+            assert len(files) > 0, \
+                f"No files for test {name} using filter {filt}"
+        classes = case['classes']
+        yield name, files, expected, classes
+
+
+@pytest.mark.parametrize('version', ('4', '5'))
+def test_load(version):
+    for case in _cases(version):
+        _load_check_case(*case[:3])
+
+
+@pytest.mark.parametrize('version', ('4', '5'))
+def test_whos(version):
+    for case in _cases(version):
+        _whos_check_case(*case)
+
+
+# generator for round trip tests
+@pytest.mark.parametrize('version, fmts', [
+    ('4', ['4', '5']),
+    ('5_rt', ['5']),
+])
+def test_round_trip(version, fmts):
+    for case in _cases(version, filt=None):
+        for fmt in fmts:
+            _rt_check_case(case[0], case[2], fmt)
+
+
+def test_gzip_simple():
+    xdense = np.zeros((20,20))
+    xdense[2,3] = 2.3
+    xdense[4,5] = 4.5
+    x = csc_array(xdense)
+
+    name = 'gzip_test'
+    expected = {'x':x}
+    format = '4'
+
+    tmpdir = mkdtemp()
+    try:
+        fname = pjoin(tmpdir,name)
+        mat_stream = gzip.open(fname, mode='wb')
+        savemat(mat_stream, expected, format=format)
+        mat_stream.close()
+
+        mat_stream = gzip.open(fname, mode='rb')
+        actual = loadmat(mat_stream, struct_as_record=True, spmatrix=False)
+        mat_stream.close()
+    finally:
+        shutil.rmtree(tmpdir)
+
+    assert_array_almost_equal(actual['x'].toarray(),
+                              expected['x'].toarray(),
+                              err_msg=repr(actual))
+
+
+def test_multiple_open():
+    # Ticket #1039, on Windows: check that files are not left open
+    tmpdir = mkdtemp()
+    try:
+        x = dict(x=np.zeros((2, 2)))
+
+        fname = pjoin(tmpdir, "a.mat")
+
+        # Check that file is not left open
+        savemat(fname, x)
+        os.unlink(fname)
+        savemat(fname, x)
+        loadmat(fname)
+        os.unlink(fname)
+
+        # Check that stream is left open
+        f = open(fname, 'wb')
+        savemat(f, x)
+        f.seek(0)
+        f.close()
+
+        f = open(fname, 'rb')
+        loadmat(f)
+        f.seek(0)
+        f.close()
+    finally:
+        shutil.rmtree(tmpdir)
+
+
+def test_mat73():
+    # Check any hdf5 files raise an error
+    filenames = glob(
+        pjoin(test_data_path, 'testhdf5*.mat'))
+    assert_(len(filenames) > 0)
+    for filename in filenames:
+        fp = open(filename, 'rb')
+        assert_raises(NotImplementedError,
+                      loadmat,
+                      fp,
+                      struct_as_record=True)
+        fp.close()
+
+
+def test_warnings():
+    # This test is an echo of the previous behavior, which was to raise a
+    # warning if the user triggered a search for mat files on the Python system
+    # path. We can remove the test in the next version after upcoming (0.13).
+    fname = pjoin(test_data_path, 'testdouble_7.1_GLNX86.mat')
+    with warnings.catch_warnings():
+        warnings.simplefilter('error')
+        # This should not generate a warning
+        loadmat(fname, struct_as_record=True)
+        # This neither
+        loadmat(fname, struct_as_record=False)
+
+
+def test_regression_653():
+    # Saving a dictionary with only invalid keys used to raise an error. Now we
+    # save this as an empty struct in matlab space.
+    sio = BytesIO()
+    savemat(sio, {'d':{1:2}}, format='5')
+    back = loadmat(sio)['d']
+    # Check we got an empty struct equivalent
+    assert_equal(back.shape, (1,1))
+    assert_equal(back.dtype, np.dtype(object))
+    assert_(back[0,0] is None)
+
+
+def test_structname_len():
+    # Test limit for length of field names in structs
+    lim = 31
+    fldname = 'a' * lim
+    st1 = np.zeros((1,1), dtype=[(fldname, object)])
+    savemat(BytesIO(), {'longstruct': st1}, format='5')
+    fldname = 'a' * (lim+1)
+    st1 = np.zeros((1,1), dtype=[(fldname, object)])
+    assert_raises(ValueError, savemat, BytesIO(),
+                  {'longstruct': st1}, format='5')
+
+
+def test_4_and_long_field_names_incompatible():
+    # Long field names option not supported in 4
+    my_struct = np.zeros((1,1),dtype=[('my_fieldname',object)])
+    assert_raises(ValueError, savemat, BytesIO(),
+                  {'my_struct':my_struct}, format='4', long_field_names=True)
+
+
+def test_long_field_names():
+    # Test limit for length of field names in structs
+    lim = 63
+    fldname = 'a' * lim
+    st1 = np.zeros((1,1), dtype=[(fldname, object)])
+    savemat(BytesIO(), {'longstruct': st1}, format='5',long_field_names=True)
+    fldname = 'a' * (lim+1)
+    st1 = np.zeros((1,1), dtype=[(fldname, object)])
+    assert_raises(ValueError, savemat, BytesIO(),
+                  {'longstruct': st1}, format='5',long_field_names=True)
+
+
+def test_long_field_names_in_struct():
+    # Regression test - long_field_names was erased if you passed a struct
+    # within a struct
+    lim = 63
+    fldname = 'a' * lim
+    cell = np.ndarray((1,2),dtype=object)
+    st1 = np.zeros((1,1), dtype=[(fldname, object)])
+    cell[0,0] = st1
+    cell[0,1] = st1
+    savemat(BytesIO(), {'longstruct': cell}, format='5',long_field_names=True)
+    #
+    # Check to make sure it fails with long field names off
+    #
+    assert_raises(ValueError, savemat, BytesIO(),
+                  {'longstruct': cell}, format='5', long_field_names=False)
+
+
+def test_cell_with_one_thing_in_it():
+    # Regression test - make a cell array that's 1 x 2 and put two
+    # strings in it. It works. Make a cell array that's 1 x 1 and put
+    # a string in it. It should work but, in the old days, it didn't.
+    cells = np.ndarray((1,2),dtype=object)
+    cells[0,0] = 'Hello'
+    cells[0,1] = 'World'
+    savemat(BytesIO(), {'x': cells}, format='5')
+
+    cells = np.ndarray((1,1),dtype=object)
+    cells[0,0] = 'Hello, world'
+    savemat(BytesIO(), {'x': cells}, format='5')
+
+
+def test_writer_properties():
+    # Tests getting, setting of properties of matrix writer
+    mfw = MatFile5Writer(BytesIO())
+    assert_equal(mfw.global_vars, [])
+    mfw.global_vars = ['avar']
+    assert_equal(mfw.global_vars, ['avar'])
+    assert_equal(mfw.unicode_strings, False)
+    mfw.unicode_strings = True
+    assert_equal(mfw.unicode_strings, True)
+    assert_equal(mfw.long_field_names, False)
+    mfw.long_field_names = True
+    assert_equal(mfw.long_field_names, True)
+
+
+def test_use_small_element():
+    # Test whether we're using small data element or not
+    sio = BytesIO()
+    wtr = MatFile5Writer(sio)
+    # First check size for no sde for name
+    arr = np.zeros(10)
+    wtr.put_variables({'aaaaa': arr})
+    w_sz = len(sio.getvalue())
+    # Check small name results in largish difference in size
+    sio.truncate(0)
+    sio.seek(0)
+    wtr.put_variables({'aaaa': arr})
+    assert_(w_sz - len(sio.getvalue()) > 4)
+    # Whereas increasing name size makes less difference
+    sio.truncate(0)
+    sio.seek(0)
+    wtr.put_variables({'aaaaaa': arr})
+    assert_(len(sio.getvalue()) - w_sz < 4)
+
+
+def test_save_dict():
+    # Test that both dict and OrderedDict can be saved (as recarray),
+    # loaded as matstruct, and preserve order
+    ab_exp = np.array([[(1, 2)]], dtype=[('a', object), ('b', object)])
+    for dict_type in (dict, OrderedDict):
+        # Initialize with tuples to keep order
+        d = dict_type([('a', 1), ('b', 2)])
+        stream = BytesIO()
+        savemat(stream, {'dict': d})
+        stream.seek(0)
+        vals = loadmat(stream)['dict']
+        assert_equal(vals.dtype.names, ('a', 'b'))
+        assert_array_equal(vals, ab_exp)
+
+
+def test_1d_shape():
+    # New 5 behavior is 1D -> row vector
+    arr = np.arange(5)
+    for format in ('4', '5'):
+        # Column is the default
+        stream = BytesIO()
+        savemat(stream, {'oned': arr}, format=format)
+        vals = loadmat(stream)
+        assert_equal(vals['oned'].shape, (1, 5))
+        # can be explicitly 'column' for oned_as
+        stream = BytesIO()
+        savemat(stream, {'oned':arr},
+                format=format,
+                oned_as='column')
+        vals = loadmat(stream)
+        assert_equal(vals['oned'].shape, (5,1))
+        # but different from 'row'
+        stream = BytesIO()
+        savemat(stream, {'oned':arr},
+                format=format,
+                oned_as='row')
+        vals = loadmat(stream)
+        assert_equal(vals['oned'].shape, (1,5))
+
+
+def test_compression():
+    arr = np.zeros(100).reshape((5,20))
+    arr[2,10] = 1
+    stream = BytesIO()
+    savemat(stream, {'arr':arr})
+    raw_len = len(stream.getvalue())
+    vals = loadmat(stream)
+    assert_array_equal(vals['arr'], arr)
+    stream = BytesIO()
+    savemat(stream, {'arr':arr}, do_compression=True)
+    compressed_len = len(stream.getvalue())
+    vals = loadmat(stream)
+    assert_array_equal(vals['arr'], arr)
+    assert_(raw_len > compressed_len)
+    # Concatenate, test later
+    arr2 = arr.copy()
+    arr2[0,0] = 1
+    stream = BytesIO()
+    savemat(stream, {'arr':arr, 'arr2':arr2}, do_compression=False)
+    vals = loadmat(stream)
+    assert_array_equal(vals['arr2'], arr2)
+    stream = BytesIO()
+    savemat(stream, {'arr':arr, 'arr2':arr2}, do_compression=True)
+    vals = loadmat(stream)
+    assert_array_equal(vals['arr2'], arr2)
+
+
+def test_single_object():
+    stream = BytesIO()
+    savemat(stream, {'A':np.array(1, dtype=object)})
+
+
+def test_skip_variable():
+    # Test skipping over the first of two variables in a MAT file
+    # using mat_reader_factory and put_variables to read them in.
+    #
+    # This is a regression test of a problem that's caused by
+    # using the compressed file reader seek instead of the raw file
+    # I/O seek when skipping over a compressed chunk.
+    #
+    # The problem arises when the chunk is large: this file has
+    # a 256x256 array of random (uncompressible) doubles.
+    #
+    filename = pjoin(test_data_path,'test_skip_variable.mat')
+    #
+    # Prove that it loads with loadmat
+    #
+    d = loadmat(filename, struct_as_record=True)
+    assert_('first' in d)
+    assert_('second' in d)
+    #
+    # Make the factory
+    #
+    factory, file_opened = mat_reader_factory(filename, struct_as_record=True)
+    #
+    # This is where the factory breaks with an error in MatMatrixGetter.to_next
+    #
+    d = factory.get_variables('second')
+    assert_('second' in d)
+    factory.mat_stream.close()
+
+
+def test_empty_struct():
+    # ticket 885
+    filename = pjoin(test_data_path,'test_empty_struct.mat')
+    # before ticket fix, this would crash with ValueError, empty data
+    # type
+    d = loadmat(filename, struct_as_record=True)
+    a = d['a']
+    assert_equal(a.shape, (1,1))
+    assert_equal(a.dtype, np.dtype(object))
+    assert_(a[0,0] is None)
+    stream = BytesIO()
+    arr = np.array((), dtype='U')
+    # before ticket fix, this used to give data type not understood
+    savemat(stream, {'arr':arr})
+    d = loadmat(stream)
+    a2 = d['arr']
+    assert_array_equal(a2, arr)
+
+
+def test_save_empty_dict():
+    # saving empty dict also gives empty struct
+    stream = BytesIO()
+    savemat(stream, {'arr': {}})
+    d = loadmat(stream)
+    a = d['arr']
+    assert_equal(a.shape, (1,1))
+    assert_equal(a.dtype, np.dtype(object))
+    assert_(a[0,0] is None)
+
+
+def assert_any_equal(output, alternatives):
+    """ Assert `output` is equal to at least one element in `alternatives`
+    """
+    one_equal = False
+    for expected in alternatives:
+        if np.all(output == expected):
+            one_equal = True
+            break
+    assert_(one_equal)
+
+
+def test_to_writeable():
+    # Test to_writeable function
+    res = to_writeable(np.array([1]))  # pass through ndarrays
+    assert_equal(res.shape, (1,))
+    assert_array_equal(res, 1)
+    # Dict fields can be written in any order
+    expected1 = np.array([(1, 2)], dtype=[('a', '|O8'), ('b', '|O8')])
+    expected2 = np.array([(2, 1)], dtype=[('b', '|O8'), ('a', '|O8')])
+    alternatives = (expected1, expected2)
+    assert_any_equal(to_writeable({'a':1,'b':2}), alternatives)
+    # Fields with underscores discarded with a warning message.
+    with pytest.warns(MatWriteWarning, match='Starting field name with'):
+        assert_any_equal(to_writeable({'a':1, 'b':2, '_c':3}), alternatives)
+    # Not-string fields discarded
+    assert_any_equal(to_writeable({'a':1,'b':2, 100:3}), alternatives)
+    # String fields that are valid Python identifiers discarded
+    with pytest.warns(MatWriteWarning, match='Starting field name with'):
+        assert_any_equal(to_writeable({'a':1, 'b':2, '99':3}), alternatives)
+    # Object with field names is equivalent
+
+    class klass:
+        pass
+
+    c = klass
+    c.a = 1
+    c.b = 2
+    assert_any_equal(to_writeable(c), alternatives)
+    # empty list and tuple go to empty array
+    res = to_writeable([])
+    assert_equal(res.shape, (0,))
+    assert_equal(res.dtype.type, np.float64)
+    res = to_writeable(())
+    assert_equal(res.shape, (0,))
+    assert_equal(res.dtype.type, np.float64)
+    # None -> None
+    assert_(to_writeable(None) is None)
+    # String to strings
+    assert_equal(to_writeable('a string').dtype.type, np.str_)
+    # Scalars to numpy to NumPy scalars
+    res = to_writeable(1)
+    assert_equal(res.shape, ())
+    assert_equal(res.dtype.type, np.array(1).dtype.type)
+    assert_array_equal(res, 1)
+    # Empty dict returns EmptyStructMarker
+    assert_(to_writeable({}) is EmptyStructMarker)
+    # Object does not have (even empty) __dict__
+    assert_(to_writeable(object()) is None)
+    # Custom object does have empty __dict__, returns EmptyStructMarker
+
+    class C:
+        pass
+
+    assert_(to_writeable(c()) is EmptyStructMarker)
+    # dict keys with legal characters are convertible
+    res = to_writeable({'a': 1})['a']
+    assert_equal(res.shape, (1,))
+    assert_equal(res.dtype.type, np.object_)
+    # Only fields with illegal characters, falls back to EmptyStruct
+    with pytest.warns(MatWriteWarning, match='Starting field name with'):
+        assert_(to_writeable({'1':1}) is EmptyStructMarker)
+
+    with pytest.warns(MatWriteWarning, match='Starting field name with'):
+        assert_(to_writeable({'_a':1}) is EmptyStructMarker)
+    # Unless there are valid fields, in which case structured array
+    with pytest.warns(MatWriteWarning, match='Starting field name with'):
+        assert_equal(to_writeable({'1':1, 'f': 2}),
+                 np.array([(2,)], dtype=[('f', '|O8')]))
+
+
+def test_recarray():
+    # check roundtrip of structured array
+    dt = [('f1', 'f8'),
+          ('f2', 'S10')]
+    arr = np.zeros((2,), dtype=dt)
+    arr[0]['f1'] = 0.5
+    arr[0]['f2'] = 'python'
+    arr[1]['f1'] = 99
+    arr[1]['f2'] = 'not perl'
+    stream = BytesIO()
+    savemat(stream, {'arr': arr})
+    d = loadmat(stream, struct_as_record=False)
+    a20 = d['arr'][0,0]
+    assert_equal(a20.f1, 0.5)
+    assert_equal(a20.f2, 'python')
+    d = loadmat(stream, struct_as_record=True)
+    a20 = d['arr'][0,0]
+    assert_equal(a20['f1'], 0.5)
+    assert_equal(a20['f2'], 'python')
+    # structs always come back as object types
+    assert_equal(a20.dtype, np.dtype([('f1', 'O'),
+                                      ('f2', 'O')]))
+    a21 = d['arr'].flat[1]
+    assert_equal(a21['f1'], 99)
+    assert_equal(a21['f2'], 'not perl')
+
+
+def test_save_object():
+    class C:
+        pass
+    c = C()
+    c.field1 = 1
+    c.field2 = 'a string'
+    stream = BytesIO()
+    savemat(stream, {'c': c})
+    d = loadmat(stream, struct_as_record=False)
+    c2 = d['c'][0,0]
+    assert_equal(c2.field1, 1)
+    assert_equal(c2.field2, 'a string')
+    d = loadmat(stream, struct_as_record=True)
+    c2 = d['c'][0,0]
+    assert_equal(c2['field1'], 1)
+    assert_equal(c2['field2'], 'a string')
+
+
+def test_read_opts():
+    # tests if read is seeing option sets, at initialization and after
+    # initialization
+    arr = np.arange(6).reshape(1,6)
+    stream = BytesIO()
+    savemat(stream, {'a': arr})
+    rdr = MatFile5Reader(stream)
+    back_dict = rdr.get_variables()
+    rarr = back_dict['a']
+    assert_array_equal(rarr, arr)
+    rdr = MatFile5Reader(stream, squeeze_me=True)
+    assert_array_equal(rdr.get_variables()['a'], arr.reshape((6,)))
+    rdr.squeeze_me = False
+    assert_array_equal(rarr, arr)
+    rdr = MatFile5Reader(stream, byte_order=boc.native_code)
+    assert_array_equal(rdr.get_variables()['a'], arr)
+    # inverted byte code leads to error on read because of swapped
+    # header etc.
+    rdr = MatFile5Reader(stream, byte_order=boc.swapped_code)
+    assert_raises(Exception, rdr.get_variables)
+    rdr.byte_order = boc.native_code
+    assert_array_equal(rdr.get_variables()['a'], arr)
+    arr = np.array(['a string'])
+    stream.truncate(0)
+    stream.seek(0)
+    savemat(stream, {'a': arr})
+    rdr = MatFile5Reader(stream)
+    assert_array_equal(rdr.get_variables()['a'], arr)
+    rdr = MatFile5Reader(stream, chars_as_strings=False)
+    carr = np.atleast_2d(np.array(list(arr.item()), dtype='U1'))
+    assert_array_equal(rdr.get_variables()['a'], carr)
+    rdr.chars_as_strings = True
+    assert_array_equal(rdr.get_variables()['a'], arr)
+
+
+def test_empty_string():
+    # make sure reading empty string does not raise error
+    estring_fname = pjoin(test_data_path, 'single_empty_string.mat')
+    fp = open(estring_fname, 'rb')
+    rdr = MatFile5Reader(fp)
+    d = rdr.get_variables()
+    fp.close()
+    assert_array_equal(d['a'], np.array([], dtype='U1'))
+    # Empty string round trip. Matlab cannot distinguish
+    # between a string array that is empty, and a string array
+    # containing a single empty string, because it stores strings as
+    # arrays of char. There is no way of having an array of char that
+    # is not empty, but contains an empty string.
+    stream = BytesIO()
+    savemat(stream, {'a': np.array([''])})
+    rdr = MatFile5Reader(stream)
+    d = rdr.get_variables()
+    assert_array_equal(d['a'], np.array([], dtype='U1'))
+    stream.truncate(0)
+    stream.seek(0)
+    savemat(stream, {'a': np.array([], dtype='U1')})
+    rdr = MatFile5Reader(stream)
+    d = rdr.get_variables()
+    assert_array_equal(d['a'], np.array([], dtype='U1'))
+    stream.close()
+
+
+def test_corrupted_data():
+    import zlib
+    for exc, fname in [(ValueError, 'corrupted_zlib_data.mat'),
+                       (zlib.error, 'corrupted_zlib_checksum.mat')]:
+        with open(pjoin(test_data_path, fname), 'rb') as fp:
+            rdr = MatFile5Reader(fp)
+            assert_raises(exc, rdr.get_variables)
+
+
+def test_corrupted_data_check_can_be_disabled():
+    with open(pjoin(test_data_path, 'corrupted_zlib_data.mat'), 'rb') as fp:
+        rdr = MatFile5Reader(fp, verify_compressed_data_integrity=False)
+        rdr.get_variables()
+
+
+def test_read_both_endian():
+    # make sure big- and little- endian data is read correctly
+    for fname in ('big_endian.mat', 'little_endian.mat'):
+        fp = open(pjoin(test_data_path, fname), 'rb')
+        rdr = MatFile5Reader(fp)
+        d = rdr.get_variables()
+        fp.close()
+        assert_array_equal(d['strings'],
+                           np.array([['hello'],
+                                     ['world']], dtype=object))
+        assert_array_equal(d['floats'],
+                           np.array([[2., 3.],
+                                     [3., 4.]], dtype=np.float32))
+
+
+def test_write_opposite_endian():
+    # We don't support writing opposite endian .mat files, but we need to behave
+    # correctly if the user supplies an other-endian NumPy array to write out.
+    float_arr = np.array([[2., 3.],
+                          [3., 4.]])
+    int_arr = np.arange(6).reshape((2, 3))
+    uni_arr = np.array(['hello', 'world'], dtype='U')
+    stream = BytesIO()
+    savemat(stream, {
+        'floats': float_arr.byteswap().view(float_arr.dtype.newbyteorder()),
+        'ints': int_arr.byteswap().view(int_arr.dtype.newbyteorder()),
+        'uni_arr': uni_arr.byteswap().view(uni_arr.dtype.newbyteorder()),
+    })
+    rdr = MatFile5Reader(stream)
+    d = rdr.get_variables()
+    assert_array_equal(d['floats'], float_arr)
+    assert_array_equal(d['ints'], int_arr)
+    assert_array_equal(d['uni_arr'], uni_arr)
+    stream.close()
+
+
+def test_logical_array():
+    # The roundtrip test doesn't verify that we load the data up with the
+    # correct (bool) dtype
+    with open(pjoin(test_data_path, 'testbool_8_WIN64.mat'), 'rb') as fobj:
+        rdr = MatFile5Reader(fobj, mat_dtype=True)
+        d = rdr.get_variables()
+    x = np.array([[True], [False]], dtype=np.bool_)
+    assert_array_equal(d['testbools'], x)
+    assert_equal(d['testbools'].dtype, x.dtype)
+
+
+def test_logical_out_type():
+    # Confirm that bool type written as uint8, uint8 class
+    # See gh-4022
+    stream = BytesIO()
+    barr = np.array([False, True, False])
+    savemat(stream, {'barray': barr})
+    stream.seek(0)
+    reader = MatFile5Reader(stream)
+    reader.initialize_read()
+    reader.read_file_header()
+    hdr, _ = reader.read_var_header()
+    assert_equal(hdr.mclass, mio5p.mxUINT8_CLASS)
+    assert_equal(hdr.is_logical, True)
+    var = reader.read_var_array(hdr, False)
+    assert_equal(var.dtype.type, np.uint8)
+
+
+def test_roundtrip_zero_dimensions():
+    stream = BytesIO()
+    savemat(stream, {'d':np.empty((10, 0))})
+    d = loadmat(stream)
+    assert d['d'].shape == (10, 0)
+
+
+def test_mat4_3d():
+    # test behavior when writing 3-D arrays to matlab 4 files
+    stream = BytesIO()
+    arr = np.arange(24).reshape((2,3,4))
+    assert_raises(ValueError, savemat, stream, {'a': arr}, True, '4')
+
+
+def test_func_read():
+    func_eg = pjoin(test_data_path, 'testfunc_7.4_GLNX86.mat')
+    fp = open(func_eg, 'rb')
+    rdr = MatFile5Reader(fp)
+    d = rdr.get_variables()
+    fp.close()
+    assert isinstance(d['testfunc'], MatlabFunction)
+    stream = BytesIO()
+    wtr = MatFile5Writer(stream)
+    # This test mat file has `__header__` field.
+    with pytest.warns(MatWriteWarning, match='Starting field name with'):
+        assert_raises(MatWriteError, wtr.put_variables, d)
+
+
+def test_mat_dtype():
+    double_eg = pjoin(test_data_path, 'testmatrix_6.1_SOL2.mat')
+    fp = open(double_eg, 'rb')
+    rdr = MatFile5Reader(fp, mat_dtype=False)
+    d = rdr.get_variables()
+    fp.close()
+    assert_equal(d['testmatrix'].dtype.kind, 'u')
+
+    fp = open(double_eg, 'rb')
+    rdr = MatFile5Reader(fp, mat_dtype=True)
+    d = rdr.get_variables()
+    fp.close()
+    assert_equal(d['testmatrix'].dtype.kind, 'f')
+
+
+def test_sparse_in_struct():
+    # reproduces bug found by DC where Cython code was insisting on
+    # ndarray return type, but getting sparse matrix
+    st = {'sparsefield': eye_array(4)}
+    stream = BytesIO()
+    savemat(stream, {'a':st})
+    d = loadmat(stream, struct_as_record=True)
+    assert_array_equal(d['a'][0, 0]['sparsefield'].toarray(), np.eye(4))
+
+
+def test_mat_struct_squeeze():
+    stream = BytesIO()
+    in_d = {'st':{'one':1, 'two':2}}
+    savemat(stream, in_d)
+    # no error without squeeze
+    loadmat(stream, struct_as_record=False)
+    # previous error was with squeeze, with mat_struct
+    loadmat(stream, struct_as_record=False, squeeze_me=True)
+
+
+def test_scalar_squeeze():
+    stream = BytesIO()
+    in_d = {'scalar': [[0.1]], 'string': 'my name', 'st':{'one':1, 'two':2}}
+    savemat(stream, in_d)
+    out_d = loadmat(stream, squeeze_me=True)
+    assert_(isinstance(out_d['scalar'], float))
+    assert_(isinstance(out_d['string'], str))
+    assert_(isinstance(out_d['st'], np.ndarray))
+
+
+def test_str_round():
+    # from report by Angus McMorland on mailing list 3 May 2010
+    stream = BytesIO()
+    in_arr = np.array(['Hello', 'Foob'])
+    out_arr = np.array(['Hello', 'Foob '])
+    savemat(stream, dict(a=in_arr))
+    res = loadmat(stream)
+    # resulted in ['HloolFoa', 'elWrdobr']
+    assert_array_equal(res['a'], out_arr)
+    stream.truncate(0)
+    stream.seek(0)
+    # Make Fortran ordered version of string
+    in_str = in_arr.tobytes(order='F')
+    in_from_str = np.ndarray(shape=a.shape,
+                             dtype=in_arr.dtype,
+                             order='F',
+                             buffer=in_str)
+    savemat(stream, dict(a=in_from_str))
+    assert_array_equal(res['a'], out_arr)
+    # unicode save did lead to buffer too small error
+    stream.truncate(0)
+    stream.seek(0)
+    in_arr_u = in_arr.astype('U')
+    out_arr_u = out_arr.astype('U')
+    savemat(stream, {'a': in_arr_u})
+    res = loadmat(stream)
+    assert_array_equal(res['a'], out_arr_u)
+
+
+def test_fieldnames():
+    # Check that field names are as expected
+    stream = BytesIO()
+    savemat(stream, {'a': {'a':1, 'b':2}})
+    res = loadmat(stream)
+    field_names = res['a'].dtype.names
+    assert_equal(set(field_names), {'a', 'b'})
+
+
+def test_loadmat_varnames():
+    # Test that we can get just one variable from a mat file using loadmat
+    mat5_sys_names = ['__globals__',
+                      '__header__',
+                      '__version__']
+    for eg_file, sys_v_names in (
+        (pjoin(test_data_path, 'testmulti_4.2c_SOL2.mat'), []), (pjoin(
+            test_data_path, 'testmulti_7.4_GLNX86.mat'), mat5_sys_names)):
+        vars = loadmat(eg_file)
+        assert_equal(set(vars.keys()), set(['a', 'theta'] + sys_v_names))
+        vars = loadmat(eg_file, variable_names='a')
+        assert_equal(set(vars.keys()), set(['a'] + sys_v_names))
+        vars = loadmat(eg_file, variable_names=['a'])
+        assert_equal(set(vars.keys()), set(['a'] + sys_v_names))
+        vars = loadmat(eg_file, variable_names=['theta'])
+        assert_equal(set(vars.keys()), set(['theta'] + sys_v_names))
+        vars = loadmat(eg_file, variable_names=('theta',))
+        assert_equal(set(vars.keys()), set(['theta'] + sys_v_names))
+        vars = loadmat(eg_file, variable_names=[])
+        assert_equal(set(vars.keys()), set(sys_v_names))
+        vnames = ['theta']
+        vars = loadmat(eg_file, variable_names=vnames)
+        assert_equal(vnames, ['theta'])
+
+
+def test_round_types():
+    # Check that saving, loading preserves dtype in most cases
+    arr = np.arange(10)
+    stream = BytesIO()
+    for dts in ('f8','f4','i8','i4','i2','i1',
+                'u8','u4','u2','u1','c16','c8'):
+        stream.truncate(0)
+        stream.seek(0)  # needed for BytesIO in Python 3
+        savemat(stream, {'arr': arr.astype(dts)})
+        vars = loadmat(stream)
+        assert_equal(np.dtype(dts), vars['arr'].dtype)
+
+
+def test_varmats_from_mat():
+    # Make a mat file with several variables, write it, read it back
+    names_vars = (('arr', mlarr(np.arange(10))),
+                  ('mystr', mlarr('a string')),
+                  ('mynum', mlarr(10)))
+
+    # Dict like thing to give variables in defined order
+    class C:
+        def items(self):
+            return names_vars
+    stream = BytesIO()
+    savemat(stream, C())
+    varmats = varmats_from_mat(stream)
+    assert_equal(len(varmats), 3)
+    for i in range(3):
+        name, var_stream = varmats[i]
+        exp_name, exp_res = names_vars[i]
+        assert_equal(name, exp_name)
+        res = loadmat(var_stream)
+        assert_array_equal(res[name], exp_res)
+
+
+def test_one_by_zero():
+    # Test 1x0 chars get read correctly
+    func_eg = pjoin(test_data_path, 'one_by_zero_char.mat')
+    fp = open(func_eg, 'rb')
+    rdr = MatFile5Reader(fp)
+    d = rdr.get_variables()
+    fp.close()
+    assert_equal(d['var'].shape, (0,))
+
+
+def test_load_mat4_le():
+    # We were getting byte order wrong when reading little-endian floa64 dense
+    # matrices on big-endian platforms
+    mat4_fname = pjoin(test_data_path, 'test_mat4_le_floats.mat')
+    vars = loadmat(mat4_fname)
+    assert_array_equal(vars['a'], [[0.1, 1.2]])
+
+
+def test_unicode_mat4():
+    # Mat4 should save unicode as latin1
+    bio = BytesIO()
+    var = {'second_cat': 'Schrödinger'}
+    savemat(bio, var, format='4')
+    var_back = loadmat(bio)
+    assert_equal(var_back['second_cat'], var['second_cat'])
+
+
+def test_logical_sparse():
+    # Test we can read logical sparse stored in mat file as bytes.
+    # See https://github.com/scipy/scipy/issues/3539.
+    # In some files saved by MATLAB, the sparse data elements (Real Part
+    # Subelement in MATLAB speak) are stored with apparent type double
+    # (miDOUBLE) but are in fact single bytes.
+    filename = pjoin(test_data_path,'logical_sparse.mat')
+    # Before fix, this would crash with:
+    # ValueError: indices and data should have the same size
+    d = loadmat(filename, struct_as_record=True, spmatrix=False)
+    log_sp = d['sp_log_5_4']
+    assert_(issparse(log_sp) and log_sp.format == "csc")
+    assert_equal(log_sp.dtype.type, np.bool_)
+    assert_array_equal(log_sp.toarray(),
+                       [[True, True, True, False],
+                        [False, False, True, False],
+                        [False, False, True, False],
+                        [False, False, False, False],
+                        [False, False, False, False]])
+
+
+def test_empty_sparse():
+    # Can we read empty sparse matrices?
+    sio = BytesIO()
+    import scipy.sparse
+    empty_sparse = scipy.sparse.csr_array([[0,0],[0,0]])
+    savemat(sio, dict(x=empty_sparse))
+    sio.seek(0)
+
+    res = loadmat(sio, spmatrix=False)
+    assert isinstance(res['x'], sparray)
+    res = loadmat(sio, spmatrix=True)
+    assert scipy.sparse.issparse(res['x']) and not isinstance(res['x'], sparray)
+    with pytest.deprecated_call(match="The default value for `spmatrix"):
+        res = loadmat(sio)  # chk default
+        assert scipy.sparse.issparse(res['x']) and not isinstance(res['x'], sparray)
+
+    assert_array_equal(res['x'].shape, empty_sparse.shape)
+    assert_array_equal(res['x'].toarray(), 0)
+    # Do empty sparse matrices get written with max nnz 1?
+    # See https://github.com/scipy/scipy/issues/4208
+    sio.seek(0)
+    reader = MatFile5Reader(sio)
+    reader.initialize_read()
+    reader.read_file_header()
+    hdr, _ = reader.read_var_header()
+    assert_equal(hdr.nzmax, 1)
+
+
+def test_empty_mat_error():
+    # Test we get a specific warning for an empty mat file
+    sio = BytesIO()
+    assert_raises(MatReadError, loadmat, sio)
+
+
+def test_miuint32_compromise():
+    # Reader should accept miUINT32 for miINT32, but check signs
+    # mat file with miUINT32 for miINT32, but OK values
+    filename = pjoin(test_data_path, 'miuint32_for_miint32.mat')
+    res = loadmat(filename)
+    assert_equal(res['an_array'], np.arange(10)[None, :])
+    # mat file with miUINT32 for miINT32, with negative value
+    filename = pjoin(test_data_path, 'bad_miuint32.mat')
+    with assert_raises(ValueError):
+        loadmat(filename)
+
+
+def test_miutf8_for_miint8_compromise():
+    # Check reader accepts ascii as miUTF8 for array names
+    filename = pjoin(test_data_path, 'miutf8_array_name.mat')
+    res = loadmat(filename)
+    assert_equal(res['array_name'], [[1]])
+    # mat file with non-ascii utf8 name raises error
+    filename = pjoin(test_data_path, 'bad_miutf8_array_name.mat')
+    with assert_raises(ValueError):
+        loadmat(filename)
+
+
+def test_bad_utf8():
+    # Check that reader reads bad UTF with 'replace' option
+    filename = pjoin(test_data_path,'broken_utf8.mat')
+    res = loadmat(filename)
+    assert_equal(res['bad_string'],
+                 b'\x80 am broken'.decode('utf8', 'replace'))
+
+
+def test_save_unicode_field(tmpdir):
+    filename = os.path.join(str(tmpdir), 'test.mat')
+    test_dict = {'a':{'b':1,'c':'test_str'}}
+    savemat(filename, test_dict)
+
+
+def test_save_custom_array_type(tmpdir):
+    class CustomArray:
+        def __array__(self, dtype=None, copy=None):
+            return np.arange(6.0).reshape(2, 3)
+    a = CustomArray()
+    filename = os.path.join(str(tmpdir), 'test.mat')
+    savemat(filename, {'a': a})
+    out = loadmat(filename)
+    assert_array_equal(out['a'], np.array(a))
+
+
+def test_filenotfound():
+    # Check the correct error is thrown
+    assert_raises(OSError, loadmat, "NotExistentFile00.mat")
+    assert_raises(OSError, loadmat, "NotExistentFile00")
+
+
+def test_simplify_cells():
+    # Test output when simplify_cells=True
+    filename = pjoin(test_data_path, 'testsimplecell.mat')
+    res1 = loadmat(filename, simplify_cells=True)
+    res2 = loadmat(filename, simplify_cells=False)
+    assert_(isinstance(res1["s"], dict))
+    assert_(isinstance(res2["s"], np.ndarray))
+    assert_array_equal(res1["s"]["mycell"], np.array(["a", "b", "c"]))
+
+
+@pytest.mark.parametrize('version, filt, regex', [
+    (0, '_4*_*', None),
+    (1, '_5*_*', None),
+    (1, '_6*_*', None),
+    (1, '_7*_*', '^((?!hdf5).)*$'),  # not containing hdf5
+    (2, '_7*_*', '.*hdf5.*'),
+    (1, '8*_*', None),
+])
+def test_matfile_version(version, filt, regex):
+    use_filt = pjoin(test_data_path, f'test*{filt}.mat')
+    files = glob(use_filt)
+    if regex is not None:
+        files = [file for file in files if re.match(regex, file) is not None]
+    assert len(files) > 0, \
+        f"No files for version {version} using filter {filt}"
+    for file in files:
+        got_version = matfile_version(file)
+        assert got_version[0] == version
+
+
+def test_opaque():
+    """Test that we can read a MatlabOpaque object."""
+    data = loadmat(pjoin(test_data_path, 'parabola.mat'))
+    assert isinstance(data['parabola'], MatlabFunction)
+    assert isinstance(data['parabola'].item()[3].item()[3], MatlabOpaque)
+
+
+def test_opaque_simplify():
+    """Test that we can read a MatlabOpaque object when simplify_cells=True."""
+    data = loadmat(pjoin(test_data_path, 'parabola.mat'), simplify_cells=True)
+    assert isinstance(data['parabola'], MatlabFunction)
+
+
+def test_matlab_string_opaque():
+    """Test that we can read multiple MatlabOpaque objects from same file"""
+    data = loadmat(pjoin(test_data_path, 'testmatlabstring_7_WIN64.mat'))
+    assert "matstring1" in data
+    assert isinstance(data['matstring1'], MatlabOpaque)
+    assert data['matstring1'][0]['_Class'] == "string"
+    assert data['matstring1'][0]['_TypeSystem'] == "MCOS"
+    assert data['matstring1'][0]['_ObjectMetadata'].dtype == np.uint32
+
+    assert "matstring2" in data
+    assert isinstance(data['matstring2'], MatlabOpaque)
+    assert data['matstring2'][0]['_Class'] == "string"
+    assert data['matstring2'][0]['_TypeSystem'] == "MCOS"
+    assert data['matstring2'][0]['_ObjectMetadata'].dtype == np.uint32
+
+    # Ensure different object IDs
+    assert data['matstring1'][0]['_ObjectMetadata'][4, 0] == 1
+    assert data['matstring2'][0]['_ObjectMetadata'][4, 0] == 2
+
+
+def test_write_matlab_opaque():
+    """Test that we can write a MatlabOpaque object"""
+    stream = BytesIO()
+    arr = np.empty((1, 1), dtype=mio5p.OPAQUE_DTYPE)
+    arr[0, 0]['_Class'] = "string"
+    arr[0, 0]['_TypeSystem'] = "MCOS"
+    arr[0, 0]['_ObjectMetadata'] = np.array([[0xDD000000, 2, 1, 1, 1, 1]],
+                                            dtype=np.uint32)
+    arr = MatlabOpaque(arr)
+    savemat(stream, {'matstring1': arr})
+
+    stream.seek(0)
+    data = loadmat(stream)
+    assert "matstring1" in data
+    assert isinstance(data['matstring1'], MatlabOpaque)
+    assert data['matstring1'][0]['_Class'] == "string"
+    assert data['matstring1'][0]['_TypeSystem'] == "MCOS"
+    assert data['matstring1'][0]['_ObjectMetadata'].dtype == np.uint32
+
+
+def test_write_function_workspace():
+    """Test that we can write function workspace to a MAT-file"""
+
+    workspace = "This is not the actual workspace contents. Just a test"
+    stream = BytesIO()
+    savemat(stream, {'__function_workspace__': workspace})
+    stream.seek(0)
+    data = loadmat(stream)
+    assert "__function_workspace__" in data
+
+
+def test_write_multiple_matlab_opaque():
+    """Round-trip two MatlabOpaque objects with distinct IDs in one mdict."""
+    def make_opaque(obj_id):
+        arr = np.empty((1, 1), dtype=mio5p.OPAQUE_DTYPE)
+        arr[0, 0]['_Class'] = "string"
+        arr[0, 0]['_TypeSystem'] = "MCOS"
+        arr[0, 0]['_ObjectMetadata'] = np.array(
+            [[0xDD000000], [2], [1], [1], [obj_id], [1]], dtype=np.uint32)
+        return MatlabOpaque(arr)
+
+    stream = BytesIO()
+    savemat(stream, {'matstring1': make_opaque(1),
+                     'matstring2': make_opaque(2)})
+    stream.seek(0)
+    data = loadmat(stream)
+    for name, expected_id in [('matstring1', 1), ('matstring2', 2)]:
+        assert name in data
+        assert isinstance(data[name], MatlabOpaque)
+        assert data[name][0]['_Class'] == "string"
+        assert data[name][0]['_TypeSystem'] == "MCOS"
+        assert data[name][0]['_ObjectMetadata'].dtype == np.uint32
+        assert data[name][0]['_ObjectMetadata'][4, 0] == expected_id
+
+
+def test_deprecation():
+    """Test that access to previous attributes still works."""
+    # This should be accessible immediately from scipy.io import
+    with assert_warns(DeprecationWarning):
+        scipy.io.matlab.mio5_params.MatlabOpaque
+
+    # These should be importable but warn as well
+    with assert_warns(DeprecationWarning):
+        from scipy.io.matlab.miobase import MatReadError  # noqa: F401
+
+
+def test_gh_17992(tmp_path):
+    rng = np.random.default_rng(12345)
+    outfile = tmp_path / "lists.mat"
+    array_one = rng.random((5,3))
+    array_two = rng.random((6,3))
+    list_of_arrays = [array_one, array_two]
+    savemat(outfile,
+            {'data': list_of_arrays},
+            long_field_names=True,
+            do_compression=True)
+    # round trip check
+    new_dict = {}
+    loadmat(outfile,
+            new_dict)
+    assert_allclose(new_dict["data"][0][0], array_one)
+    assert_allclose(new_dict["data"][0][1], array_two)
+
+
+def test_gh_19659(tmp_path):
+    d = {
+        "char_array": np.array([list("char"), list("char")], dtype="U1"),
+        "string_array": np.array(["string", "string"]),
+        }
+    outfile = tmp_path / "tmp.mat"
+    # should not error:
+    savemat(outfile, d, format="4")
+
+
+def test_large_m4():
+    # Test we can read a Matlab 4 file with array > 2GB.
+    # (In fact, test we get the correct error from reading a truncated
+    # version).
+    # See https://github.com/scipy/scipy/issues/21256
+    # Data file is first 1024 bytes of:
+    # >>> a = np.zeros((134217728, 3))
+    # >>> siom.savemat('big_m4.mat', {'a': a}, format='4')
+    truncated_mat = pjoin(test_data_path, 'debigged_m4.mat')
+    match = ("Not enough bytes to read matrix 'a';"
+             if np.intp == np.int64 else
+             "Variable 'a' has byte length longer than largest possible")
+    with pytest.raises(ValueError, match=match):
+        loadmat(truncated_mat)
+
+
+def test_gh_19223():
+    from scipy.io.matlab import varmats_from_mat  # noqa: F401
+
+
+def test_invalid_field_name_warning():
+    names_vars = (
+        ('_1', mlarr(np.arange(10))),
+        ('mystr', mlarr('a string')))
+    check_mat_write_warning(names_vars)
+
+    names_vars = (('mymap', {"a": 1, "_b": 2}),)
+    check_mat_write_warning(names_vars)
+
+    names_vars = (('mymap', {"a": 1, "1a": 2}),)
+    check_mat_write_warning(names_vars)
+
+
+def check_mat_write_warning(names_vars):
+    class C:
+        def items(self):
+            return names_vars
+
+    stream = BytesIO()
+    with pytest.warns(MatWriteWarning, match='Starting field name with'):
+        savemat(stream, C())
+
+
+def test_corrupt_files():
+    # Test we can detect truncated or corrupt (all zero) files.
+    for n in (2, 4, 10, 19):
+        with pytest.raises(MatReadError,
+                           match="Mat file appears to be truncated"):
+            loadmat(BytesIO(b'\x00' * n))
+    with pytest.raises(MatReadError,
+                       match="Mat file appears to be corrupt"):
+        loadmat(BytesIO(b'\x00' * 20))
diff --git a/.venv/lib/python3.12/site-packages/scipy/io/matlab/tests/test_mio5_utils.py b/.venv/lib/python3.12/site-packages/scipy/io/matlab/tests/test_mio5_utils.py
new file mode 100644
index 0000000000000000000000000000000000000000..b3f27114c4a4ed10c1a2526058f4d0dbbd0e5638
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/io/matlab/tests/test_mio5_utils.py
@@ -0,0 +1,179 @@
+""" Testing mio5_utils Cython module
+
+"""
+import sys
+
+from io import BytesIO
+
+import numpy as np
+
+from numpy.testing import assert_array_equal, assert_equal, assert_
+from pytest import raises as assert_raises
+
+import scipy.io.matlab._byteordercodes as boc
+import scipy.io.matlab._streams as streams
+import scipy.io.matlab._mio5_params as mio5p
+import scipy.io.matlab._mio5_utils as m5u
+
+
+def test_byteswap():
+    for val in (
+        1,
+        0x100,
+        0x10000):
+        a = np.array(val, dtype=np.uint32)
+        b = a.byteswap()
+        c = m5u.byteswap_u4(a)
+        assert_equal(b.item(), c)
+        d = m5u.byteswap_u4(c)
+        assert_equal(a.item(), d)
+
+
+def _make_tag(base_dt, val, mdtype, sde=False):
+    ''' Makes a simple matlab tag, full or sde '''
+    base_dt = np.dtype(base_dt)
+    bo = boc.to_numpy_code(base_dt.byteorder)
+    byte_count = base_dt.itemsize
+    if not sde:
+        udt = bo + 'u4'
+        padding = 8 - (byte_count % 8)
+        all_dt = [('mdtype', udt),
+                  ('byte_count', udt),
+                  ('val', base_dt)]
+        if padding:
+            all_dt.append(('padding', 'u1', padding))
+    else:  # is sde
+        udt = bo + 'u2'
+        padding = 4-byte_count
+        if bo == '<':  # little endian
+            all_dt = [('mdtype', udt),
+                      ('byte_count', udt),
+                      ('val', base_dt)]
+        else:  # big endian
+            all_dt = [('byte_count', udt),
+                      ('mdtype', udt),
+                      ('val', base_dt)]
+        if padding:
+            all_dt.append(('padding', 'u1', padding))
+    tag = np.zeros((1,), dtype=all_dt)
+    tag['mdtype'] = mdtype
+    tag['byte_count'] = byte_count
+    tag['val'] = val
+    return tag
+
+
+def _write_stream(stream, *strings):
+    stream.truncate(0)
+    stream.seek(0)
+    for s in strings:
+        stream.write(s)
+    stream.seek(0)
+
+
+def _make_readerlike(stream, byte_order=boc.native_code):
+    class R:
+        pass
+    r = R()
+    r.mat_stream = stream
+    r.byte_order = byte_order
+    r.struct_as_record = True
+    r.uint16_codec = sys.getdefaultencoding()
+    r.chars_as_strings = False
+    r.mat_dtype = False
+    r.squeeze_me = False
+    return r
+
+
+def test_read_tag():
+    # mainly to test errors
+    # make reader-like thing
+    str_io = BytesIO()
+    r = _make_readerlike(str_io)
+    c_reader = m5u.VarReader5(r)
+    # This works for StringIO but _not_ BytesIO
+    assert_raises(OSError, c_reader.read_tag)
+    # bad SDE
+    tag = _make_tag('i4', 1, mio5p.miINT32, sde=True)
+    tag['byte_count'] = 5
+    _write_stream(str_io, tag.tobytes())
+    assert_raises(ValueError, c_reader.read_tag)
+
+
+def test_read_stream():
+    tag = _make_tag('i4', 1, mio5p.miINT32, sde=True)
+    tag_str = tag.tobytes()
+    str_io = BytesIO(tag_str)
+    st = streams.make_stream(str_io)
+    s = streams._read_into(st, tag.itemsize)
+    assert_equal(s, tag.tobytes())
+
+
+def test_read_numeric():
+    # make reader-like thing
+    str_io = BytesIO()
+    r = _make_readerlike(str_io)
+    # check simplest of tags
+    for base_dt, val, mdtype in (('u2', 30, mio5p.miUINT16),
+                                 ('i4', 1, mio5p.miINT32),
+                                 ('i2', -1, mio5p.miINT16)):
+        for byte_code in ('<', '>'):
+            r.byte_order = byte_code
+            c_reader = m5u.VarReader5(r)
+            assert_equal(c_reader.little_endian, byte_code == '<')
+            assert_equal(c_reader.is_swapped, byte_code != boc.native_code)
+            for sde_f in (False, True):
+                dt = np.dtype(base_dt).newbyteorder(byte_code)
+                a = _make_tag(dt, val, mdtype, sde_f)
+                a_str = a.tobytes()
+                _write_stream(str_io, a_str)
+                el = c_reader.read_numeric()
+                assert_equal(el, val)
+                # two sequential reads
+                _write_stream(str_io, a_str, a_str)
+                el = c_reader.read_numeric()
+                assert_equal(el, val)
+                el = c_reader.read_numeric()
+                assert_equal(el, val)
+
+
+def test_read_numeric_writeable():
+    # make reader-like thing
+    str_io = BytesIO()
+    r = _make_readerlike(str_io, '<')
+    c_reader = m5u.VarReader5(r)
+    dt = np.dtype(''
+    rdr.mat_stream.read(4)  # presumably byte padding
+    mdict = read_minimat_vars(rdr)
+    fp.close()
+    return mdict
+
+
+def test_jottings():
+    # example
+    fname = os.path.join(test_data_path, 'parabola.mat')
+    read_workspace_vars(fname)
diff --git a/.venv/lib/python3.12/site-packages/scipy/io/matlab/tests/test_mio_utils.py b/.venv/lib/python3.12/site-packages/scipy/io/matlab/tests/test_mio_utils.py
new file mode 100644
index 0000000000000000000000000000000000000000..1d19a9797faa2221307a7330b69fffa26410f624
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/io/matlab/tests/test_mio_utils.py
@@ -0,0 +1,45 @@
+""" Testing
+
+"""
+
+import numpy as np
+
+from numpy.testing import assert_array_equal, assert_
+
+from scipy.io.matlab._mio_utils import squeeze_element, chars_to_strings
+
+
+def test_squeeze_element():
+    a = np.zeros((1,3))
+    assert_array_equal(np.squeeze(a), squeeze_element(a))
+    # 0-D output from squeeze gives scalar
+    sq_int = squeeze_element(np.zeros((1,1), dtype=float))
+    assert_(isinstance(sq_int, float))
+    # Unless it's a structured array
+    sq_sa = squeeze_element(np.zeros((1,1),dtype=[('f1', 'f')]))
+    assert_(isinstance(sq_sa, np.ndarray))
+    # Squeezing empty arrays maintain their dtypes.
+    sq_empty = squeeze_element(np.empty(0, np.uint8))
+    assert sq_empty.dtype == np.uint8
+
+
+def test_chars_strings():
+    # chars as strings
+    strings = ['learn ', 'python', 'fast  ', 'here  ']
+    str_arr = np.array(strings, dtype='U6')  # shape (4,)
+    chars = [list(s) for s in strings]
+    char_arr = np.array(chars, dtype='U1')  # shape (4,6)
+    assert_array_equal(chars_to_strings(char_arr), str_arr)
+    ca2d = char_arr.reshape((2,2,6))
+    sa2d = str_arr.reshape((2,2))
+    assert_array_equal(chars_to_strings(ca2d), sa2d)
+    ca3d = char_arr.reshape((1,2,2,6))
+    sa3d = str_arr.reshape((1,2,2))
+    assert_array_equal(chars_to_strings(ca3d), sa3d)
+    # Fortran ordered arrays
+    char_arrf = np.array(chars, dtype='U1', order='F')  # shape (4,6)
+    assert_array_equal(chars_to_strings(char_arrf), str_arr)
+    # empty array
+    arr = np.array([['']], dtype='U1')
+    out_arr = np.array([''], dtype='U1')
+    assert_array_equal(chars_to_strings(arr), out_arr)
diff --git a/.venv/lib/python3.12/site-packages/scipy/io/matlab/tests/test_miobase.py b/.venv/lib/python3.12/site-packages/scipy/io/matlab/tests/test_miobase.py
new file mode 100644
index 0000000000000000000000000000000000000000..d8c8eb2a56aaa1d1de77bfb90c859ed0af0b7bc4
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/io/matlab/tests/test_miobase.py
@@ -0,0 +1,32 @@
+""" Testing miobase module
+"""
+
+import numpy as np
+
+from numpy.testing import assert_equal
+from pytest import raises as assert_raises
+
+from scipy.io.matlab._miobase import matdims
+
+
+def test_matdims():
+    # Test matdims dimension finder
+    assert_equal(matdims(np.array(1)), (1, 1))  # NumPy scalar
+    assert_equal(matdims(np.array([1])), (1, 1))  # 1-D array, 1 element
+    assert_equal(matdims(np.array([1,2])), (2, 1))  # 1-D array, 2 elements
+    assert_equal(matdims(np.array([[2],[3]])), (2, 1))  # 2-D array, column vector
+    assert_equal(matdims(np.array([[2,3]])), (1, 2))  # 2-D array, row vector
+    # 3d array, rowish vector
+    assert_equal(matdims(np.array([[[2,3]]])), (1, 1, 2))
+    assert_equal(matdims(np.array([])), (0, 0))  # empty 1-D array
+    assert_equal(matdims(np.array([[]])), (1, 0))  # empty 2-D array
+    assert_equal(matdims(np.array([[[]]])), (1, 1, 0))  # empty 3-D array
+    assert_equal(matdims(np.empty((1, 0, 1))), (1, 0, 1))  # empty 3-D array
+    # Optional argument flips 1-D shape behavior.
+    assert_equal(matdims(np.array([1,2]), 'row'), (1, 2))  # 1-D array, 2 elements
+    # The argument has to make sense though
+    assert_raises(ValueError, matdims, np.array([1,2]), 'bizarre')
+    # Check empty sparse matrices get their own shape
+    from scipy.sparse import csr_array, csc_array
+    assert_equal(matdims(csr_array(np.zeros((3, 3)))), (3, 3))
+    assert_equal(matdims(csc_array(np.zeros((2, 2)))), (2, 2))
diff --git a/.venv/lib/python3.12/site-packages/scipy/io/matlab/tests/test_pathological.py b/.venv/lib/python3.12/site-packages/scipy/io/matlab/tests/test_pathological.py
new file mode 100644
index 0000000000000000000000000000000000000000..c5c86decb7e90f69f293e90eba74fb47dd4f1277
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/io/matlab/tests/test_pathological.py
@@ -0,0 +1,33 @@
+""" Test reading of files not conforming to matlab specification
+
+We try and read any file that matlab reads, these files included
+"""
+from os.path import dirname, join as pjoin
+
+from numpy.testing import assert_
+from pytest import raises as assert_raises
+
+from scipy.io.matlab._mio import loadmat
+
+TEST_DATA_PATH = pjoin(dirname(__file__), 'data')
+
+
+def test_multiple_fieldnames():
+    # Example provided by Dharhas Pothina
+    # Extracted using mio5.varmats_from_mat
+    multi_fname = pjoin(TEST_DATA_PATH, 'nasty_duplicate_fieldnames.mat')
+    vars = loadmat(multi_fname)
+    funny_names = vars['Summary'].dtype.names
+    assert_({'_1_Station_Q', '_2_Station_Q',
+                     '_3_Station_Q'}.issubset(funny_names))
+
+
+def test_malformed1():
+    # Example from gh-6072
+    # Contains malformed header data, which previously resulted into a
+    # buffer overflow.
+    #
+    # Should raise an exception, not segfault
+    fname = pjoin(TEST_DATA_PATH, 'malformed1.mat')
+    with open(fname, 'rb') as f:
+        assert_raises(ValueError, loadmat, f)
diff --git a/.venv/lib/python3.12/site-packages/scipy/io/matlab/tests/test_streams.py b/.venv/lib/python3.12/site-packages/scipy/io/matlab/tests/test_streams.py
new file mode 100644
index 0000000000000000000000000000000000000000..5449a7d7070e6e4f1655e1071a9098259e4f47cd
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/io/matlab/tests/test_streams.py
@@ -0,0 +1,241 @@
+""" Testing
+
+"""
+
+import platform
+import os
+import random
+import sys
+import zlib
+
+from io import BytesIO
+
+
+from tempfile import mkstemp
+from contextlib import contextmanager
+
+import numpy as np
+
+from numpy.testing import assert_, assert_equal
+from pytest import raises as assert_raises
+import pytest
+
+from scipy.io.matlab._streams import (make_stream,
+    GenericStream, ZlibInputStream,
+    _read_into, _read_string, BLOCK_SIZE)
+
+
+@contextmanager
+def setup_test_file():
+    val = b'a\x00string'
+    fd, fname = mkstemp()
+
+    with os.fdopen(fd, 'wb') as fs:
+        fs.write(val)
+    with open(fname, 'rb') as fs:
+        gs = BytesIO(val)
+        cs = BytesIO(val)
+        yield fs, gs, cs
+    os.unlink(fname)
+
+
+def test_make_stream():
+    with setup_test_file() as (fs, gs, cs):
+        # test stream initialization
+        assert_(isinstance(make_stream(gs), GenericStream))
+
+
+def test_tell_seek():
+    with setup_test_file() as (fs, gs, cs):
+        for s in (fs, gs, cs):
+            st = make_stream(s)
+            res = st.seek(0)
+            assert_equal(res, 0)
+            assert_equal(st.tell(), 0)
+            res = st.seek(5)
+            assert_equal(res, 0)
+            assert_equal(st.tell(), 5)
+            res = st.seek(2, 1)
+            assert_equal(res, 0)
+            assert_equal(st.tell(), 7)
+            res = st.seek(-2, 2)
+            assert_equal(res, 0)
+            assert_equal(st.tell(), 6)
+
+
+def test_read():
+    with setup_test_file() as (fs, gs, cs):
+        for s in (fs, gs, cs):
+            st = make_stream(s)
+            st.seek(0)
+            res = st.read(-1)
+            assert_equal(res, b'a\x00string')
+            st.seek(0)
+            res = st.read(4)
+            assert_equal(res, b'a\x00st')
+            # read into
+            st.seek(0)
+            res = _read_into(st, 4)
+            assert_equal(res, b'a\x00st')
+            res = _read_into(st, 4)
+            assert_equal(res, b'ring')
+            assert_raises(OSError, _read_into, st, 2)
+            # read alloc
+            st.seek(0)
+            res = _read_string(st, 4)
+            assert_equal(res, b'a\x00st')
+            res = _read_string(st, 4)
+            assert_equal(res, b'ring')
+            assert_raises(OSError, _read_string, st, 2)
+
+
+class TestZlibInputStream:
+    def _get_data(self, size):
+        data = random.randbytes(size)
+        compressed_data = zlib.compress(data)
+        stream = BytesIO(compressed_data)
+        return stream, len(compressed_data), data
+
+    def test_read(self):
+        SIZES = [0, 1, 10, BLOCK_SIZE//2, BLOCK_SIZE-1,
+                 BLOCK_SIZE, BLOCK_SIZE+1, 2*BLOCK_SIZE-1]
+
+        READ_SIZES = [BLOCK_SIZE//2, BLOCK_SIZE-1,
+                      BLOCK_SIZE, BLOCK_SIZE+1]
+
+        def check(size, read_size):
+            compressed_stream, compressed_data_len, data = self._get_data(size)
+            stream = ZlibInputStream(compressed_stream, compressed_data_len)
+            data2 = b''
+            so_far = 0
+            while True:
+                block = stream.read(min(read_size,
+                                        size - so_far))
+                if not block:
+                    break
+                so_far += len(block)
+                data2 += block
+            assert_equal(data, data2)
+
+        for size in SIZES:
+            for read_size in READ_SIZES:
+                check(size, read_size)
+
+    def test_read_max_length(self):
+        data = random.randbytes(1234)
+        compressed_data = zlib.compress(data)
+        compressed_stream = BytesIO(compressed_data + b"abbacaca")
+        stream = ZlibInputStream(compressed_stream, len(compressed_data))
+
+        stream.read(len(data))
+        assert_equal(compressed_stream.tell(), len(compressed_data))
+
+        assert_raises(OSError, stream.read, 1)
+
+    def test_read_bad_checksum(self):
+        data = random.randbytes(10)
+        compressed_data = zlib.compress(data)
+
+        # break checksum
+        compressed_data = (compressed_data[:-1]
+                           + bytes([(compressed_data[-1] + 1) & 255]))
+
+        compressed_stream = BytesIO(compressed_data)
+        stream = ZlibInputStream(compressed_stream, len(compressed_data))
+
+        assert_raises(zlib.error, stream.read, len(data))
+
+    def test_seek(self):
+        compressed_stream, compressed_data_len, data = self._get_data(1024)
+
+        stream = ZlibInputStream(compressed_stream, compressed_data_len)
+
+        stream.seek(123)
+        p = 123
+        assert_equal(stream.tell(), p)
+        d1 = stream.read(11)
+        assert_equal(d1, data[p:p+11])
+
+        stream.seek(321, 1)
+        p = 123+11+321
+        assert_equal(stream.tell(), p)
+        d2 = stream.read(21)
+        assert_equal(d2, data[p:p+21])
+
+        stream.seek(641, 0)
+        p = 641
+        assert_equal(stream.tell(), p)
+        d3 = stream.read(11)
+        assert_equal(d3, data[p:p+11])
+
+        assert_raises(OSError, stream.seek, 10, 2)
+        assert_raises(OSError, stream.seek, -1, 1)
+        assert_raises(ValueError, stream.seek, 1, 123)
+
+        stream.seek(10000, 1)
+        assert_raises(OSError, stream.read, 12)
+
+    def test_seek_bad_checksum(self):
+        data = random.randbytes(10)
+        compressed_data = zlib.compress(data)
+
+        # break checksum
+        compressed_data = (compressed_data[:-1]
+                           + bytes([(compressed_data[-1] + 1) & 255]))
+
+        compressed_stream = BytesIO(compressed_data)
+        stream = ZlibInputStream(compressed_stream, len(compressed_data))
+
+        assert_raises(zlib.error, stream.seek, len(data))
+
+    def test_all_data_read(self):
+        compressed_stream, compressed_data_len, data = self._get_data(1024)
+        stream = ZlibInputStream(compressed_stream, compressed_data_len)
+        assert_(not stream.all_data_read())
+        stream.seek(512)
+        assert_(not stream.all_data_read())
+        stream.seek(1024)
+        assert_(stream.all_data_read())
+
+    @pytest.mark.skipif(
+            (platform.system() == 'Windows' and sys.version_info >= (3, 14)),
+            reason='gh-23185')
+    def test_all_data_read_overlap(self):
+        COMPRESSION_LEVEL = 6
+
+        data = np.arange(33707000, dtype=np.uint8)
+        compressed_data = zlib.compress(data, COMPRESSION_LEVEL)
+        compressed_data_len = len(compressed_data)
+
+        # check that part of the checksum overlaps
+        assert_(compressed_data_len == BLOCK_SIZE + 2)
+
+        compressed_stream = BytesIO(compressed_data)
+        stream = ZlibInputStream(compressed_stream, compressed_data_len)
+        assert_(not stream.all_data_read())
+        stream.seek(len(data))
+        assert_(stream.all_data_read())
+
+    @pytest.mark.skipif(
+            (platform.system() == 'Windows' and sys.version_info >= (3, 14)),
+            reason='gh-23185')
+    def test_all_data_read_bad_checksum(self):
+        COMPRESSION_LEVEL = 6
+
+        data = np.arange(33707000, dtype=np.uint8)
+        compressed_data = zlib.compress(data, COMPRESSION_LEVEL)
+        compressed_data_len = len(compressed_data)
+
+        # check that part of the checksum overlaps
+        assert_(compressed_data_len == BLOCK_SIZE + 2)
+
+        # break checksum
+        compressed_data = (compressed_data[:-1]
+                           + bytes([(compressed_data[-1] + 1) & 255]))
+
+        compressed_stream = BytesIO(compressed_data)
+        stream = ZlibInputStream(compressed_stream, compressed_data_len)
+        assert_(not stream.all_data_read())
+        stream.seek(len(data))
+
+        assert_raises(zlib.error, stream.all_data_read)
diff --git a/.venv/lib/python3.12/site-packages/scipy/io/mmio.py b/.venv/lib/python3.12/site-packages/scipy/io/mmio.py
new file mode 100644
index 0000000000000000000000000000000000000000..67cf0684cbf9468468027957a5b7f3da2c43c845
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/io/mmio.py
@@ -0,0 +1,17 @@
+# This file is not meant for public use and will be removed in SciPy v2.0.0.
+# Use the `scipy.io` namespace for importing the functions
+# included below.
+
+from scipy._lib.deprecation import _sub_module_deprecation
+
+__all__ = ["mminfo", "mmread", "mmwrite"]  # noqa: F822
+
+
+def __dir__():
+    return __all__
+
+
+def __getattr__(name):
+    return _sub_module_deprecation(sub_package="io", module="mmio",
+                                   private_modules=["_mmio"], all=__all__,
+                                   attribute=name)
diff --git a/.venv/lib/python3.12/site-packages/scipy/io/netcdf.py b/.venv/lib/python3.12/site-packages/scipy/io/netcdf.py
new file mode 100644
index 0000000000000000000000000000000000000000..c1f119dd2bad72d772c3d1db6ceec9fd3d91316d
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/io/netcdf.py
@@ -0,0 +1,17 @@
+# This file is not meant for public use and will be removed in SciPy v2.0.0.
+# Use the `scipy.io` namespace for importing the functions
+# included below.
+
+from scipy._lib.deprecation import _sub_module_deprecation
+
+__all__ = ["netcdf_file", "netcdf_variable"]  # noqa: F822
+
+
+def __dir__():
+    return __all__
+
+
+def __getattr__(name):
+    return _sub_module_deprecation(sub_package="io", module="netcdf",
+                                   private_modules=["_netcdf"], all=__all__,
+                                   attribute=name)
diff --git a/.venv/lib/python3.12/site-packages/scipy/io/tests/__init__.py b/.venv/lib/python3.12/site-packages/scipy/io/tests/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/.venv/lib/python3.12/site-packages/scipy/io/tests/data/Transparent Busy.ani b/.venv/lib/python3.12/site-packages/scipy/io/tests/data/Transparent Busy.ani
new file mode 100644
index 0000000000000000000000000000000000000000..3be500032786398c3efdbd9f873f705b6c1636bd
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/scipy/io/tests/data/Transparent Busy.ani differ
diff --git a/.venv/lib/python3.12/site-packages/scipy/io/tests/data/array_float32_1d.sav b/.venv/lib/python3.12/site-packages/scipy/io/tests/data/array_float32_1d.sav
new file mode 100644
index 0000000000000000000000000000000000000000..619a1259670a361ac76ffa86c481a813dbaec07a
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/scipy/io/tests/data/array_float32_1d.sav differ
diff --git a/.venv/lib/python3.12/site-packages/scipy/io/tests/data/array_float32_2d.sav b/.venv/lib/python3.12/site-packages/scipy/io/tests/data/array_float32_2d.sav
new file mode 100644
index 0000000000000000000000000000000000000000..804d8b1a8a90636c880e974b6f85bd385033306b
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/scipy/io/tests/data/array_float32_2d.sav differ
diff --git a/.venv/lib/python3.12/site-packages/scipy/io/tests/data/array_float32_3d.sav b/.venv/lib/python3.12/site-packages/scipy/io/tests/data/array_float32_3d.sav
new file mode 100644
index 0000000000000000000000000000000000000000..3fa56c450eaa916d9c91b492ba17e7e843df2d53
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/scipy/io/tests/data/array_float32_3d.sav differ
diff --git a/.venv/lib/python3.12/site-packages/scipy/io/tests/data/array_float32_4d.sav b/.venv/lib/python3.12/site-packages/scipy/io/tests/data/array_float32_4d.sav
new file mode 100644
index 0000000000000000000000000000000000000000..4bb951e274a399f091ff70b639d6e3b55ee1e122
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/scipy/io/tests/data/array_float32_4d.sav differ
diff --git a/.venv/lib/python3.12/site-packages/scipy/io/tests/data/array_float32_5d.sav b/.venv/lib/python3.12/site-packages/scipy/io/tests/data/array_float32_5d.sav
new file mode 100644
index 0000000000000000000000000000000000000000..2854dbc8b1e53f298ac3b135eac1f06e73940152
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/scipy/io/tests/data/array_float32_5d.sav differ
diff --git a/.venv/lib/python3.12/site-packages/scipy/io/tests/data/array_float32_6d.sav b/.venv/lib/python3.12/site-packages/scipy/io/tests/data/array_float32_6d.sav
new file mode 100644
index 0000000000000000000000000000000000000000..91588d348d5f89af354209840062202d5b28c1df
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/scipy/io/tests/data/array_float32_6d.sav differ
diff --git a/.venv/lib/python3.12/site-packages/scipy/io/tests/data/array_float32_7d.sav b/.venv/lib/python3.12/site-packages/scipy/io/tests/data/array_float32_7d.sav
new file mode 100644
index 0000000000000000000000000000000000000000..3e978fad540a8979435d4561de151573696affd8
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/scipy/io/tests/data/array_float32_7d.sav differ
diff --git a/.venv/lib/python3.12/site-packages/scipy/io/tests/data/array_float32_8d.sav b/.venv/lib/python3.12/site-packages/scipy/io/tests/data/array_float32_8d.sav
new file mode 100644
index 0000000000000000000000000000000000000000..f699fe2427dfe876283de0fcade2c2325a262061
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/scipy/io/tests/data/array_float32_8d.sav differ
diff --git a/.venv/lib/python3.12/site-packages/scipy/io/tests/data/array_float32_pointer_1d.sav b/.venv/lib/python3.12/site-packages/scipy/io/tests/data/array_float32_pointer_1d.sav
new file mode 100644
index 0000000000000000000000000000000000000000..8e3a402c60a515149811e2ca21628e97180c4956
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/scipy/io/tests/data/array_float32_pointer_1d.sav differ
diff --git a/.venv/lib/python3.12/site-packages/scipy/io/tests/data/array_float32_pointer_2d.sav b/.venv/lib/python3.12/site-packages/scipy/io/tests/data/array_float32_pointer_2d.sav
new file mode 100644
index 0000000000000000000000000000000000000000..dd3504f0ecfaed178ace02e1a8a84650111c3936
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/scipy/io/tests/data/array_float32_pointer_2d.sav differ
diff --git a/.venv/lib/python3.12/site-packages/scipy/io/tests/data/array_float32_pointer_3d.sav b/.venv/lib/python3.12/site-packages/scipy/io/tests/data/array_float32_pointer_3d.sav
new file mode 100644
index 0000000000000000000000000000000000000000..285da7f78ffbbf2155fd2e4e648f19a1d3a42ac3
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/scipy/io/tests/data/array_float32_pointer_3d.sav differ
diff --git a/.venv/lib/python3.12/site-packages/scipy/io/tests/data/array_float32_pointer_4d.sav b/.venv/lib/python3.12/site-packages/scipy/io/tests/data/array_float32_pointer_4d.sav
new file mode 100644
index 0000000000000000000000000000000000000000..d99fa48f0a43ec06c3101560f9cade829c8b1940
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/scipy/io/tests/data/array_float32_pointer_4d.sav differ
diff --git a/.venv/lib/python3.12/site-packages/scipy/io/tests/data/array_float32_pointer_5d.sav b/.venv/lib/python3.12/site-packages/scipy/io/tests/data/array_float32_pointer_5d.sav
new file mode 100644
index 0000000000000000000000000000000000000000..de5e984e49f507ae550b1ae2fd54b799e742a195
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/scipy/io/tests/data/array_float32_pointer_5d.sav differ
diff --git a/.venv/lib/python3.12/site-packages/scipy/io/tests/data/array_float32_pointer_6d.sav b/.venv/lib/python3.12/site-packages/scipy/io/tests/data/array_float32_pointer_6d.sav
new file mode 100644
index 0000000000000000000000000000000000000000..bb76671a65be41fd2a426146c6c366f1e7fb07c3
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/scipy/io/tests/data/array_float32_pointer_6d.sav differ
diff --git a/.venv/lib/python3.12/site-packages/scipy/io/tests/data/array_float32_pointer_7d.sav b/.venv/lib/python3.12/site-packages/scipy/io/tests/data/array_float32_pointer_7d.sav
new file mode 100644
index 0000000000000000000000000000000000000000..995d23c6ed05b095442b6247b09191126f797f23
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/scipy/io/tests/data/array_float32_pointer_7d.sav differ
diff --git a/.venv/lib/python3.12/site-packages/scipy/io/tests/data/array_float32_pointer_8d.sav b/.venv/lib/python3.12/site-packages/scipy/io/tests/data/array_float32_pointer_8d.sav
new file mode 100644
index 0000000000000000000000000000000000000000..4249ec62119e264d55a81d3faf9c87dcaed1c7c8
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/scipy/io/tests/data/array_float32_pointer_8d.sav differ
diff --git a/.venv/lib/python3.12/site-packages/scipy/io/tests/data/example_1.nc b/.venv/lib/python3.12/site-packages/scipy/io/tests/data/example_1.nc
new file mode 100644
index 0000000000000000000000000000000000000000..5775622d0ef85828b436dffcd21366f7538fc55c
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/scipy/io/tests/data/example_1.nc differ
diff --git a/.venv/lib/python3.12/site-packages/scipy/io/tests/data/example_2.nc b/.venv/lib/python3.12/site-packages/scipy/io/tests/data/example_2.nc
new file mode 100644
index 0000000000000000000000000000000000000000..07db1cd986a4c3b9929c01c1f22bcc3f562b1c16
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/scipy/io/tests/data/example_2.nc differ
diff --git a/.venv/lib/python3.12/site-packages/scipy/io/tests/data/example_3_maskedvals.nc b/.venv/lib/python3.12/site-packages/scipy/io/tests/data/example_3_maskedvals.nc
new file mode 100644
index 0000000000000000000000000000000000000000..57f8bf9da3bca295c15508963c77a870222af0bc
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/scipy/io/tests/data/example_3_maskedvals.nc differ
diff --git a/.venv/lib/python3.12/site-packages/scipy/io/tests/data/fortran-3x3d-2i.dat b/.venv/lib/python3.12/site-packages/scipy/io/tests/data/fortran-3x3d-2i.dat
new file mode 100644
index 0000000000000000000000000000000000000000..87731eb9d4b1f2ac827a212436fe6de175431e11
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/scipy/io/tests/data/fortran-3x3d-2i.dat differ
diff --git a/.venv/lib/python3.12/site-packages/scipy/io/tests/data/fortran-mixed.dat b/.venv/lib/python3.12/site-packages/scipy/io/tests/data/fortran-mixed.dat
new file mode 100644
index 0000000000000000000000000000000000000000..a165a7a30424b20af9a3a0636c5e655239ea6fa5
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/scipy/io/tests/data/fortran-mixed.dat differ
diff --git a/.venv/lib/python3.12/site-packages/scipy/io/tests/data/fortran-sf8-11x1x10.dat b/.venv/lib/python3.12/site-packages/scipy/io/tests/data/fortran-sf8-11x1x10.dat
new file mode 100644
index 0000000000000000000000000000000000000000..c3bb9dcbe50ef784ce3282b28e53f4c40beb48ce
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/scipy/io/tests/data/fortran-sf8-11x1x10.dat differ
diff --git a/.venv/lib/python3.12/site-packages/scipy/io/tests/data/fortran-sf8-15x10x22.dat b/.venv/lib/python3.12/site-packages/scipy/io/tests/data/fortran-sf8-15x10x22.dat
new file mode 100644
index 0000000000000000000000000000000000000000..351801fd47a2e3e48d9b63034fbae28f8318c9f9
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/scipy/io/tests/data/fortran-sf8-15x10x22.dat differ
diff --git a/.venv/lib/python3.12/site-packages/scipy/io/tests/data/fortran-sf8-1x1x1.dat b/.venv/lib/python3.12/site-packages/scipy/io/tests/data/fortran-sf8-1x1x1.dat
new file mode 100644
index 0000000000000000000000000000000000000000..64bf92f74a457d2f4bc42798493db15cc3ab1008
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/scipy/io/tests/data/fortran-sf8-1x1x1.dat differ
diff --git a/.venv/lib/python3.12/site-packages/scipy/io/tests/data/fortran-sf8-1x1x5.dat b/.venv/lib/python3.12/site-packages/scipy/io/tests/data/fortran-sf8-1x1x5.dat
new file mode 100644
index 0000000000000000000000000000000000000000..3d3f27f88eef4e02451d18204cdcfd51f96f6d15
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/scipy/io/tests/data/fortran-sf8-1x1x5.dat differ
diff --git a/.venv/lib/python3.12/site-packages/scipy/io/tests/data/fortran-sf8-1x1x7.dat b/.venv/lib/python3.12/site-packages/scipy/io/tests/data/fortran-sf8-1x1x7.dat
new file mode 100644
index 0000000000000000000000000000000000000000..0bd683096f18eadceb7168f811c75bf072baecfe
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/scipy/io/tests/data/fortran-sf8-1x1x7.dat differ
diff --git a/.venv/lib/python3.12/site-packages/scipy/io/tests/data/fortran-sf8-1x3x5.dat b/.venv/lib/python3.12/site-packages/scipy/io/tests/data/fortran-sf8-1x3x5.dat
new file mode 100644
index 0000000000000000000000000000000000000000..25269ff9ea4f6dd3f8a9ca0c8ad27d399e4248f5
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/scipy/io/tests/data/fortran-sf8-1x3x5.dat differ
diff --git a/.venv/lib/python3.12/site-packages/scipy/io/tests/data/fortran-si4-11x1x10.dat b/.venv/lib/python3.12/site-packages/scipy/io/tests/data/fortran-si4-11x1x10.dat
new file mode 100644
index 0000000000000000000000000000000000000000..9850de37cf86af622b759625c15e6b1a9477ce47
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/scipy/io/tests/data/fortran-si4-11x1x10.dat differ
diff --git a/.venv/lib/python3.12/site-packages/scipy/io/tests/data/fortran-si4-15x10x22.dat b/.venv/lib/python3.12/site-packages/scipy/io/tests/data/fortran-si4-15x10x22.dat
new file mode 100644
index 0000000000000000000000000000000000000000..98c09c2dff6e1ef605e25ed1d00afe94597abddc
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/scipy/io/tests/data/fortran-si4-15x10x22.dat differ
diff --git a/.venv/lib/python3.12/site-packages/scipy/io/tests/data/fortran-si4-1x1x1.dat b/.venv/lib/python3.12/site-packages/scipy/io/tests/data/fortran-si4-1x1x1.dat
new file mode 100644
index 0000000000000000000000000000000000000000..959098d2a9cdd6140758843e059d4ca529b14279
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/scipy/io/tests/data/fortran-si4-1x1x1.dat differ
diff --git a/.venv/lib/python3.12/site-packages/scipy/io/tests/data/fortran-si4-1x1x5.dat b/.venv/lib/python3.12/site-packages/scipy/io/tests/data/fortran-si4-1x1x5.dat
new file mode 100644
index 0000000000000000000000000000000000000000..49c0ec1d18d9f08111fe2d2a269ed407da71b158
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/scipy/io/tests/data/fortran-si4-1x1x5.dat differ
diff --git a/.venv/lib/python3.12/site-packages/scipy/io/tests/data/fortran-si4-1x1x7.dat b/.venv/lib/python3.12/site-packages/scipy/io/tests/data/fortran-si4-1x1x7.dat
new file mode 100644
index 0000000000000000000000000000000000000000..bb936b8789920ce18281fa754a5c048b31e59ba8
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/scipy/io/tests/data/fortran-si4-1x1x7.dat differ
diff --git a/.venv/lib/python3.12/site-packages/scipy/io/tests/data/fortran-si4-1x3x5.dat b/.venv/lib/python3.12/site-packages/scipy/io/tests/data/fortran-si4-1x3x5.dat
new file mode 100644
index 0000000000000000000000000000000000000000..cb3e9e4876249f42924a43232b74f05b91123815
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/scipy/io/tests/data/fortran-si4-1x3x5.dat differ
diff --git a/.venv/lib/python3.12/site-packages/scipy/io/tests/data/identification.sav b/.venv/lib/python3.12/site-packages/scipy/io/tests/data/identification.sav
new file mode 100644
index 0000000000000000000000000000000000000000..38faa91728b8484cd376acc1e4c9c1f99a118f6a
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/scipy/io/tests/data/identification.sav differ
diff --git a/.venv/lib/python3.12/site-packages/scipy/io/tests/data/invalid_pointer.sav b/.venv/lib/python3.12/site-packages/scipy/io/tests/data/invalid_pointer.sav
new file mode 100644
index 0000000000000000000000000000000000000000..d53893c6c734e6c7771e08042c16874623dc6f0e
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/scipy/io/tests/data/invalid_pointer.sav differ
diff --git a/.venv/lib/python3.12/site-packages/scipy/io/tests/data/null_pointer.sav b/.venv/lib/python3.12/site-packages/scipy/io/tests/data/null_pointer.sav
new file mode 100644
index 0000000000000000000000000000000000000000..8cee5ebecc3bef248ed37c438e0731160b31a310
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/scipy/io/tests/data/null_pointer.sav differ
diff --git a/.venv/lib/python3.12/site-packages/scipy/io/tests/data/scalar_byte.sav b/.venv/lib/python3.12/site-packages/scipy/io/tests/data/scalar_byte.sav
new file mode 100644
index 0000000000000000000000000000000000000000..e4027b3cf302b8610b87d9ef8b0aac39d5a40ef9
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/scipy/io/tests/data/scalar_byte.sav differ
diff --git a/.venv/lib/python3.12/site-packages/scipy/io/tests/data/scalar_byte_descr.sav b/.venv/lib/python3.12/site-packages/scipy/io/tests/data/scalar_byte_descr.sav
new file mode 100644
index 0000000000000000000000000000000000000000..182e29bc57dc05154388553a71876820025bca8d
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/scipy/io/tests/data/scalar_byte_descr.sav differ
diff --git a/.venv/lib/python3.12/site-packages/scipy/io/tests/data/scalar_complex32.sav b/.venv/lib/python3.12/site-packages/scipy/io/tests/data/scalar_complex32.sav
new file mode 100644
index 0000000000000000000000000000000000000000..593e8c6208ab0bf3aa869de89e213b8aa9f8c071
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/scipy/io/tests/data/scalar_complex32.sav differ
diff --git a/.venv/lib/python3.12/site-packages/scipy/io/tests/data/scalar_complex64.sav b/.venv/lib/python3.12/site-packages/scipy/io/tests/data/scalar_complex64.sav
new file mode 100644
index 0000000000000000000000000000000000000000..edb19d388afbaff44e5f0883978e6a74e9755613
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/scipy/io/tests/data/scalar_complex64.sav differ
diff --git a/.venv/lib/python3.12/site-packages/scipy/io/tests/data/scalar_float32.sav b/.venv/lib/python3.12/site-packages/scipy/io/tests/data/scalar_float32.sav
new file mode 100644
index 0000000000000000000000000000000000000000..be9e3877ea845da76d9466c14d70c4cce882368c
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/scipy/io/tests/data/scalar_float32.sav differ
diff --git a/.venv/lib/python3.12/site-packages/scipy/io/tests/data/scalar_float64.sav b/.venv/lib/python3.12/site-packages/scipy/io/tests/data/scalar_float64.sav
new file mode 100644
index 0000000000000000000000000000000000000000..9680b2878c6008a27c8fc9ae6966903ff936cc4a
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/scipy/io/tests/data/scalar_float64.sav differ
diff --git a/.venv/lib/python3.12/site-packages/scipy/io/tests/data/scalar_heap_pointer.sav b/.venv/lib/python3.12/site-packages/scipy/io/tests/data/scalar_heap_pointer.sav
new file mode 100644
index 0000000000000000000000000000000000000000..d02b1756ac043a4ba6119acb28ef34c40359a4dd
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/scipy/io/tests/data/scalar_heap_pointer.sav differ
diff --git a/.venv/lib/python3.12/site-packages/scipy/io/tests/data/scalar_int16.sav b/.venv/lib/python3.12/site-packages/scipy/io/tests/data/scalar_int16.sav
new file mode 100644
index 0000000000000000000000000000000000000000..603525694cc307d47412717c4c2f85ddc960897b
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/scipy/io/tests/data/scalar_int16.sav differ
diff --git a/.venv/lib/python3.12/site-packages/scipy/io/tests/data/scalar_int32.sav b/.venv/lib/python3.12/site-packages/scipy/io/tests/data/scalar_int32.sav
new file mode 100644
index 0000000000000000000000000000000000000000..40210b889402c0f27562296ab39ce1a714f0d0ef
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/scipy/io/tests/data/scalar_int32.sav differ
diff --git a/.venv/lib/python3.12/site-packages/scipy/io/tests/data/scalar_int64.sav b/.venv/lib/python3.12/site-packages/scipy/io/tests/data/scalar_int64.sav
new file mode 100644
index 0000000000000000000000000000000000000000..c91cd0a561e011a2f18c86119e45392fbc0be825
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/scipy/io/tests/data/scalar_int64.sav differ
diff --git a/.venv/lib/python3.12/site-packages/scipy/io/tests/data/scalar_string.sav b/.venv/lib/python3.12/site-packages/scipy/io/tests/data/scalar_string.sav
new file mode 100644
index 0000000000000000000000000000000000000000..ee6e69fe8461edfa580f682761118c8afe2add3a
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/scipy/io/tests/data/scalar_string.sav differ
diff --git a/.venv/lib/python3.12/site-packages/scipy/io/tests/data/scalar_uint16.sav b/.venv/lib/python3.12/site-packages/scipy/io/tests/data/scalar_uint16.sav
new file mode 100644
index 0000000000000000000000000000000000000000..759c2e64fa034c6ddbdbe6181efae1e699a0c314
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/scipy/io/tests/data/scalar_uint16.sav differ
diff --git a/.venv/lib/python3.12/site-packages/scipy/io/tests/data/scalar_uint32.sav b/.venv/lib/python3.12/site-packages/scipy/io/tests/data/scalar_uint32.sav
new file mode 100644
index 0000000000000000000000000000000000000000..74dec7b8933418d30d17c83d617443a73ceef0c6
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/scipy/io/tests/data/scalar_uint32.sav differ
diff --git a/.venv/lib/python3.12/site-packages/scipy/io/tests/data/scalar_uint64.sav b/.venv/lib/python3.12/site-packages/scipy/io/tests/data/scalar_uint64.sav
new file mode 100644
index 0000000000000000000000000000000000000000..fc9da5796eab6ce9fb59488b836ba2f567de7b25
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/scipy/io/tests/data/scalar_uint64.sav differ
diff --git a/.venv/lib/python3.12/site-packages/scipy/io/tests/data/struct_arrays.sav b/.venv/lib/python3.12/site-packages/scipy/io/tests/data/struct_arrays.sav
new file mode 100644
index 0000000000000000000000000000000000000000..40c9cd330e0c731968d71dbbfeae9bd8c4a745a2
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/scipy/io/tests/data/struct_arrays.sav differ
diff --git a/.venv/lib/python3.12/site-packages/scipy/io/tests/data/struct_arrays_byte_idl80.sav b/.venv/lib/python3.12/site-packages/scipy/io/tests/data/struct_arrays_byte_idl80.sav
new file mode 100644
index 0000000000000000000000000000000000000000..f1aa416f8e661893be282a490005536953d4b7af
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/scipy/io/tests/data/struct_arrays_byte_idl80.sav differ
diff --git a/.venv/lib/python3.12/site-packages/scipy/io/tests/data/struct_arrays_replicated.sav b/.venv/lib/python3.12/site-packages/scipy/io/tests/data/struct_arrays_replicated.sav
new file mode 100644
index 0000000000000000000000000000000000000000..6f01fbfd109e76c94b6e6e9bfd9eb388f39d99ee
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/scipy/io/tests/data/struct_arrays_replicated.sav differ
diff --git a/.venv/lib/python3.12/site-packages/scipy/io/tests/data/struct_arrays_replicated_3d.sav b/.venv/lib/python3.12/site-packages/scipy/io/tests/data/struct_arrays_replicated_3d.sav
new file mode 100644
index 0000000000000000000000000000000000000000..bac9b207488eb9712ec27fb3567155f0dd773f34
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/scipy/io/tests/data/struct_arrays_replicated_3d.sav differ
diff --git a/.venv/lib/python3.12/site-packages/scipy/io/tests/data/struct_inherit.sav b/.venv/lib/python3.12/site-packages/scipy/io/tests/data/struct_inherit.sav
new file mode 100644
index 0000000000000000000000000000000000000000..8babd56306f09fa612f731ce593ae13c75f84f4c
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/scipy/io/tests/data/struct_inherit.sav differ
diff --git a/.venv/lib/python3.12/site-packages/scipy/io/tests/data/struct_pointer_arrays.sav b/.venv/lib/python3.12/site-packages/scipy/io/tests/data/struct_pointer_arrays.sav
new file mode 100644
index 0000000000000000000000000000000000000000..a3c678162911426702a9a6e932761385a01f247e
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/scipy/io/tests/data/struct_pointer_arrays.sav differ
diff --git a/.venv/lib/python3.12/site-packages/scipy/io/tests/data/struct_pointer_arrays_replicated.sav b/.venv/lib/python3.12/site-packages/scipy/io/tests/data/struct_pointer_arrays_replicated.sav
new file mode 100644
index 0000000000000000000000000000000000000000..38b812261125e6aabef8618955b234f6c7b04955
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/scipy/io/tests/data/struct_pointer_arrays_replicated.sav differ
diff --git a/.venv/lib/python3.12/site-packages/scipy/io/tests/data/struct_pointer_arrays_replicated_3d.sav b/.venv/lib/python3.12/site-packages/scipy/io/tests/data/struct_pointer_arrays_replicated_3d.sav
new file mode 100644
index 0000000000000000000000000000000000000000..db1c256c85a707f0a0d78c28241b78d1eddcab1e
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/scipy/io/tests/data/struct_pointer_arrays_replicated_3d.sav differ
diff --git a/.venv/lib/python3.12/site-packages/scipy/io/tests/data/struct_pointers.sav b/.venv/lib/python3.12/site-packages/scipy/io/tests/data/struct_pointers.sav
new file mode 100644
index 0000000000000000000000000000000000000000..acbb058a307090f6c9e2d8402c7badf6bb48144c
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/scipy/io/tests/data/struct_pointers.sav differ
diff --git a/.venv/lib/python3.12/site-packages/scipy/io/tests/data/struct_pointers_replicated.sav b/.venv/lib/python3.12/site-packages/scipy/io/tests/data/struct_pointers_replicated.sav
new file mode 100644
index 0000000000000000000000000000000000000000..d16f4655cc20318db2b0d629cd5ed6d7be01b518
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/scipy/io/tests/data/struct_pointers_replicated.sav differ
diff --git a/.venv/lib/python3.12/site-packages/scipy/io/tests/data/struct_pointers_replicated_3d.sav b/.venv/lib/python3.12/site-packages/scipy/io/tests/data/struct_pointers_replicated_3d.sav
new file mode 100644
index 0000000000000000000000000000000000000000..732dd2cbfa9c7fd029bb59b4cfcb630cc1077f54
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/scipy/io/tests/data/struct_pointers_replicated_3d.sav differ
diff --git a/.venv/lib/python3.12/site-packages/scipy/io/tests/data/struct_scalars.sav b/.venv/lib/python3.12/site-packages/scipy/io/tests/data/struct_scalars.sav
new file mode 100644
index 0000000000000000000000000000000000000000..69d7eaf4ecf8747c21d07e14edcf65b4e394974c
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/scipy/io/tests/data/struct_scalars.sav differ
diff --git a/.venv/lib/python3.12/site-packages/scipy/io/tests/data/struct_scalars_replicated.sav b/.venv/lib/python3.12/site-packages/scipy/io/tests/data/struct_scalars_replicated.sav
new file mode 100644
index 0000000000000000000000000000000000000000..2222391ae5b93ba34c1fdb982c02eb97d9658b58
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/scipy/io/tests/data/struct_scalars_replicated.sav differ
diff --git a/.venv/lib/python3.12/site-packages/scipy/io/tests/data/struct_scalars_replicated_3d.sav b/.venv/lib/python3.12/site-packages/scipy/io/tests/data/struct_scalars_replicated_3d.sav
new file mode 100644
index 0000000000000000000000000000000000000000..a35f1acfb4cb93ecb637310bbfa7fc1a2151d483
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/scipy/io/tests/data/struct_scalars_replicated_3d.sav differ
diff --git a/.venv/lib/python3.12/site-packages/scipy/io/tests/data/test-1234Hz-le-1ch-10S-20bit-extra.wav b/.venv/lib/python3.12/site-packages/scipy/io/tests/data/test-1234Hz-le-1ch-10S-20bit-extra.wav
new file mode 100644
index 0000000000000000000000000000000000000000..4dc4ebed4e134fccfbf88c0ab93ac33705e93cb5
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/io/tests/data/test-1234Hz-le-1ch-10S-20bit-extra.wav
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:87c097b16e7f4a1291d7deedfddf935139600ea399fbbc0afc47151ae711f9a6
+size 74
diff --git a/.venv/lib/python3.12/site-packages/scipy/io/tests/data/test-44100Hz-2ch-32bit-float-be.wav b/.venv/lib/python3.12/site-packages/scipy/io/tests/data/test-44100Hz-2ch-32bit-float-be.wav
new file mode 100644
index 0000000000000000000000000000000000000000..20b9264eeb61d4575b9c0484cc0b7cd59f2efe0a
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/io/tests/data/test-44100Hz-2ch-32bit-float-be.wav
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:823bfffe783dc47fec9b7e21cb109b0a03b800ffbe3d901f0ce02b1f9a269233
+size 3586
diff --git a/.venv/lib/python3.12/site-packages/scipy/io/tests/data/test-44100Hz-2ch-32bit-float-le.wav b/.venv/lib/python3.12/site-packages/scipy/io/tests/data/test-44100Hz-2ch-32bit-float-le.wav
new file mode 100644
index 0000000000000000000000000000000000000000..aa79a3ae4097ba68e9a0071f273abd466d0dcc48
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/io/tests/data/test-44100Hz-2ch-32bit-float-le.wav
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:1f42cbcafda573682ecd81a7c780d65d4eaf079ec9ad15fe1bd0dde2a1a1d213
+size 3586
diff --git a/.venv/lib/python3.12/site-packages/scipy/io/tests/data/test-44100Hz-be-1ch-4bytes.wav b/.venv/lib/python3.12/site-packages/scipy/io/tests/data/test-44100Hz-be-1ch-4bytes.wav
new file mode 100644
index 0000000000000000000000000000000000000000..6fa1d82cc466464f0378654a0a1dfb6772e1384c
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/io/tests/data/test-44100Hz-be-1ch-4bytes.wav
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:28acfd497bff477817fc055e103dafca16278f806f0f5bb20e22a9093dee959d
+size 17720
diff --git a/.venv/lib/python3.12/site-packages/scipy/io/tests/data/test-44100Hz-le-1ch-4bytes-early-eof-no-data.wav b/.venv/lib/python3.12/site-packages/scipy/io/tests/data/test-44100Hz-le-1ch-4bytes-early-eof-no-data.wav
new file mode 100644
index 0000000000000000000000000000000000000000..8c227b753036941bf9b2488c1064a89c7608c66c
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/io/tests/data/test-44100Hz-le-1ch-4bytes-early-eof-no-data.wav
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:617d60f2a7423801b5eaf5fd1baab84ac7c28f6655935f7d8f30d0f12d335982
+size 72
diff --git a/.venv/lib/python3.12/site-packages/scipy/io/tests/data/test-44100Hz-le-1ch-4bytes-early-eof.wav b/.venv/lib/python3.12/site-packages/scipy/io/tests/data/test-44100Hz-le-1ch-4bytes-early-eof.wav
new file mode 100644
index 0000000000000000000000000000000000000000..87af8be1ae45f2d89b0557045f5ce1ac37463fe5
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/io/tests/data/test-44100Hz-le-1ch-4bytes-early-eof.wav
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:6c5aec46ac344179ac683b630fa4c53fc859e631183326829adfa46bf0ba18d9
+size 1024
diff --git a/.venv/lib/python3.12/site-packages/scipy/io/tests/data/test-44100Hz-le-1ch-4bytes-incomplete-chunk.wav b/.venv/lib/python3.12/site-packages/scipy/io/tests/data/test-44100Hz-le-1ch-4bytes-incomplete-chunk.wav
new file mode 100644
index 0000000000000000000000000000000000000000..f8d332e94208f448b8377fed7a539181e13bb65c
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/io/tests/data/test-44100Hz-le-1ch-4bytes-incomplete-chunk.wav
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:ccc9e1bd9beb3f893239629529f6c19decafd37c6fce0a976211cdc6c0310c9e
+size 13
diff --git a/.venv/lib/python3.12/site-packages/scipy/io/tests/data/test-44100Hz-le-1ch-4bytes-rf64.wav b/.venv/lib/python3.12/site-packages/scipy/io/tests/data/test-44100Hz-le-1ch-4bytes-rf64.wav
new file mode 100644
index 0000000000000000000000000000000000000000..37811d0253cbc106a571ac1a1ab118162ad9e240
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/io/tests/data/test-44100Hz-le-1ch-4bytes-rf64.wav
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:1922690ae7b396f1db84fdc2af88cd5a6cf8cc6e3a5d9ea3722d9f5ad88c3749
+size 17756
diff --git a/.venv/lib/python3.12/site-packages/scipy/io/tests/data/test-44100Hz-le-1ch-4bytes.wav b/.venv/lib/python3.12/site-packages/scipy/io/tests/data/test-44100Hz-le-1ch-4bytes.wav
new file mode 100644
index 0000000000000000000000000000000000000000..6971300129120ca8a3a2a92a733eddb0984abdad
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/io/tests/data/test-44100Hz-le-1ch-4bytes.wav
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:f6a4c2be981dcf7ada79c54dd558a08073e742305fe3bc665e877d8820ec1229
+size 17720
diff --git a/.venv/lib/python3.12/site-packages/scipy/io/tests/data/test-48000Hz-2ch-64bit-float-le-wavex.wav b/.venv/lib/python3.12/site-packages/scipy/io/tests/data/test-48000Hz-2ch-64bit-float-le-wavex.wav
new file mode 100644
index 0000000000000000000000000000000000000000..e8ae491462f17664f15c6daa7023f522078b6e82
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/io/tests/data/test-48000Hz-2ch-64bit-float-le-wavex.wav
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:12a6019c4813c532af69302d740e47225e3b0821488def77cb885ac11e8fcaed
+size 7792
diff --git a/.venv/lib/python3.12/site-packages/scipy/io/tests/data/test-8000Hz-be-3ch-5S-24bit.wav b/.venv/lib/python3.12/site-packages/scipy/io/tests/data/test-8000Hz-be-3ch-5S-24bit.wav
new file mode 100644
index 0000000000000000000000000000000000000000..71934ac873c7e4278420597e763a596f4dfbbc72
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/io/tests/data/test-8000Hz-be-3ch-5S-24bit.wav
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:84661c8714058ebb6f642068d142e2fb1759f24aea5dc29d4e5dcd4947ea7bc9
+size 90
diff --git a/.venv/lib/python3.12/site-packages/scipy/io/tests/data/test-8000Hz-le-1ch-1byte-ulaw.wav b/.venv/lib/python3.12/site-packages/scipy/io/tests/data/test-8000Hz-le-1ch-1byte-ulaw.wav
new file mode 100644
index 0000000000000000000000000000000000000000..b3c27ca654cd8fb73621c6ac226eb340fe808ed1
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/io/tests/data/test-8000Hz-le-1ch-1byte-ulaw.wav
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:0685020dcb771a263f24957f1e88211779b301e6d3d7c8f4d9cf8c3a7d7d2b15
+size 70
diff --git a/.venv/lib/python3.12/site-packages/scipy/io/tests/data/test-8000Hz-le-2ch-1byteu.wav b/.venv/lib/python3.12/site-packages/scipy/io/tests/data/test-8000Hz-le-2ch-1byteu.wav
new file mode 100644
index 0000000000000000000000000000000000000000..f733f90d4dea6f6429d88219928d52037365e9e0
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/io/tests/data/test-8000Hz-le-2ch-1byteu.wav
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:47a109b21bd0a79615478181f6ee0a867e4733554c7c9523d3cda2f2d901209f
+size 1644
diff --git a/.venv/lib/python3.12/site-packages/scipy/io/tests/data/test-8000Hz-le-3ch-5S-24bit-inconsistent.wav b/.venv/lib/python3.12/site-packages/scipy/io/tests/data/test-8000Hz-le-3ch-5S-24bit-inconsistent.wav
new file mode 100644
index 0000000000000000000000000000000000000000..fdd1849f98e5883c46e6c2889e7a32f484b1e847
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/io/tests/data/test-8000Hz-le-3ch-5S-24bit-inconsistent.wav
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:b76320ae2de1e892d00de92bc0884304e686e3a394cc7ca7533d2929bbcea4d5
+size 90
diff --git a/.venv/lib/python3.12/site-packages/scipy/io/tests/data/test-8000Hz-le-3ch-5S-24bit-rf64.wav b/.venv/lib/python3.12/site-packages/scipy/io/tests/data/test-8000Hz-le-3ch-5S-24bit-rf64.wav
new file mode 100644
index 0000000000000000000000000000000000000000..085b5afd663fec6e9c6d3fbf8c099c96a566cbde
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/io/tests/data/test-8000Hz-le-3ch-5S-24bit-rf64.wav
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:8921b2aa8b97e7735a101df7b732976b5d4d44863dec61b8d3fa6a585fe4e4b4
+size 126
diff --git a/.venv/lib/python3.12/site-packages/scipy/io/tests/data/test-8000Hz-le-3ch-5S-24bit.wav b/.venv/lib/python3.12/site-packages/scipy/io/tests/data/test-8000Hz-le-3ch-5S-24bit.wav
new file mode 100644
index 0000000000000000000000000000000000000000..23be5c7b67cc6c3209b9d66d2897e1daf2fb54e7
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/io/tests/data/test-8000Hz-le-3ch-5S-24bit.wav
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:c82bf4ba1faec7fb2426cc5e3a3ce88346019376503bf930e4724732ab55c88d
+size 90
diff --git a/.venv/lib/python3.12/site-packages/scipy/io/tests/data/test-8000Hz-le-3ch-5S-36bit.wav b/.venv/lib/python3.12/site-packages/scipy/io/tests/data/test-8000Hz-le-3ch-5S-36bit.wav
new file mode 100644
index 0000000000000000000000000000000000000000..3152c566f155a76b36c33f7de56b0942c26548ed
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/io/tests/data/test-8000Hz-le-3ch-5S-36bit.wav
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:a22315b1057dfaa181cff670b1f024800f416573635db1f8cf1086bef753d116
+size 120
diff --git a/.venv/lib/python3.12/site-packages/scipy/io/tests/data/test-8000Hz-le-3ch-5S-45bit.wav b/.venv/lib/python3.12/site-packages/scipy/io/tests/data/test-8000Hz-le-3ch-5S-45bit.wav
new file mode 100644
index 0000000000000000000000000000000000000000..2e9dc76040faaea314a81b66b024a01b63d1ff73
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/io/tests/data/test-8000Hz-le-3ch-5S-45bit.wav
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:7bded7a0facf1890c887c9ceea68a2fff562639c95966b783a73d0a03375763b
+size 134
diff --git a/.venv/lib/python3.12/site-packages/scipy/io/tests/data/test-8000Hz-le-3ch-5S-53bit.wav b/.venv/lib/python3.12/site-packages/scipy/io/tests/data/test-8000Hz-le-3ch-5S-53bit.wav
new file mode 100644
index 0000000000000000000000000000000000000000..99ec1413418a387563eba670c547de03b91ec783
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/io/tests/data/test-8000Hz-le-3ch-5S-53bit.wav
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:c1ba272a5cefcd0fdb418c81b23f86c278a164e867d2ec5f2a12ff9c434218d7
+size 150
diff --git a/.venv/lib/python3.12/site-packages/scipy/io/tests/data/test-8000Hz-le-3ch-5S-64bit.wav b/.venv/lib/python3.12/site-packages/scipy/io/tests/data/test-8000Hz-le-3ch-5S-64bit.wav
new file mode 100644
index 0000000000000000000000000000000000000000..09ea515215b4f92f881bf97900ac2b56ee0c89ca
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/io/tests/data/test-8000Hz-le-3ch-5S-64bit.wav
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:52ee503d071bb671659f139de33146c698930b8c20769e893a8609d95319214d
+size 164
diff --git a/.venv/lib/python3.12/site-packages/scipy/io/tests/data/test-8000Hz-le-4ch-9S-12bit.wav b/.venv/lib/python3.12/site-packages/scipy/io/tests/data/test-8000Hz-le-4ch-9S-12bit.wav
new file mode 100644
index 0000000000000000000000000000000000000000..d6f534ab9619a6cb3a121e36e61d5f8c00ecea29
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/io/tests/data/test-8000Hz-le-4ch-9S-12bit.wav
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:d45ebb87cb6bdb1cf40b92b6d53f72f60b29706034aa748ecec976be302b00cb
+size 116
diff --git a/.venv/lib/python3.12/site-packages/scipy/io/tests/data/test-8000Hz-le-5ch-9S-5bit.wav b/.venv/lib/python3.12/site-packages/scipy/io/tests/data/test-8000Hz-le-5ch-9S-5bit.wav
new file mode 100644
index 0000000000000000000000000000000000000000..d2fa9b3a9e9ba86eefbd1cee5378ba56a083cf3c
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/io/tests/data/test-8000Hz-le-5ch-9S-5bit.wav
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:4c9bc653b1a9817742addae3ccc943b6989e0cc9c32be95630caa55a34f6dc16
+size 89
diff --git a/.venv/lib/python3.12/site-packages/scipy/io/tests/data/various_compressed.sav b/.venv/lib/python3.12/site-packages/scipy/io/tests/data/various_compressed.sav
new file mode 100644
index 0000000000000000000000000000000000000000..dcdb0b0d433939d6a240c86e5060214cd8875732
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/scipy/io/tests/data/various_compressed.sav differ
diff --git a/.venv/lib/python3.12/site-packages/scipy/io/tests/test_fortran.py b/.venv/lib/python3.12/site-packages/scipy/io/tests/test_fortran.py
new file mode 100644
index 0000000000000000000000000000000000000000..d370b3098d0465f8d133da58c6aebbfec85d294b
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/io/tests/test_fortran.py
@@ -0,0 +1,344 @@
+''' Tests for fortran sequential files '''
+
+import tempfile
+import shutil
+import os
+from os import path
+from glob import iglob
+import threading
+import re
+
+from numpy.testing import assert_equal, assert_allclose
+import numpy as np
+import pytest
+
+from scipy.io import (FortranFile,
+                      FortranEOFError,
+                      FortranFormattingError)
+
+
+DATA_PATH = path.join(path.dirname(__file__), 'data')
+
+
+@pytest.fixture
+def io_lock():
+    return threading.Lock()
+
+
+def test_fortranfiles_read(io_lock):
+    for filename in iglob(path.join(DATA_PATH, "fortran-*-*x*x*.dat")):
+        m = re.search(r'fortran-([^-]+)-(\d+)x(\d+)x(\d+).dat', filename, re.I)
+        if not m:
+            raise RuntimeError(f"Couldn't match {filename} filename to regex")
+
+        dims = (int(m.group(2)), int(m.group(3)), int(m.group(4)))
+
+        dtype = m.group(1).replace('s', '<')
+
+        with io_lock:
+            f = FortranFile(filename, 'r', ' 0] = 1
+        info = (2, 2, 3, 'coordinate', 'pattern', 'general')
+        mmwrite(self.fn, a, field='pattern')
+        assert_equal(mminfo(self.fn), info)
+
+        b = mmread(self.fn, spmatrix=False)
+        assert_array_almost_equal(p, b.toarray())
+        assert isinstance(b, scipy.sparse.sparray)
+
+        b = mmread(self.fn, spmatrix=True)
+        assert_array_almost_equal(p, b.toarray())
+        assert isinstance(b, scipy.sparse.spmatrix)
+
+        with pytest.deprecated_call(match="The default value"):
+            b = mmread(self.fn)  # chk default
+            assert not isinstance(b, scipy.sparse.sparray)
+
+    def test_gh13634_non_skew_symmetric_int(self):
+        a = scipy.sparse.csr_array([[1, 2], [-2, 99]], dtype=np.int32)
+        self.check_exact(a, (2, 2, 4, 'coordinate', 'integer', 'general'))
+
+    def test_gh13634_non_skew_symmetric_float(self):
+        a = scipy.sparse.csr_array([[1, 2], [-2, 99.]], dtype=np.float32)
+        self.check(a, (2, 2, 4, 'coordinate', 'real', 'general'))
+
+
+_32bit_integer_dense_example = '''\
+%%MatrixMarket matrix array integer general
+2  2
+2147483647
+2147483646
+2147483647
+2147483646
+'''
+
+_32bit_integer_sparse_example = '''\
+%%MatrixMarket matrix coordinate integer symmetric
+2  2  2
+1  1  2147483647
+2  2  2147483646
+'''
+
+_64bit_integer_dense_example = '''\
+%%MatrixMarket matrix array integer general
+2  2
+          2147483648
+-9223372036854775806
+         -2147483648
+ 9223372036854775807
+'''
+
+_64bit_integer_sparse_general_example = '''\
+%%MatrixMarket matrix coordinate integer general
+2  2  3
+1  1           2147483648
+1  2  9223372036854775807
+2  2  9223372036854775807
+'''
+
+_64bit_integer_sparse_symmetric_example = '''\
+%%MatrixMarket matrix coordinate integer symmetric
+2  2  3
+1  1            2147483648
+1  2  -9223372036854775807
+2  2   9223372036854775807
+'''
+
+_64bit_integer_sparse_skew_example = '''\
+%%MatrixMarket matrix coordinate integer skew-symmetric
+2  2  3
+1  1            2147483648
+1  2  -9223372036854775807
+2  2   9223372036854775807
+'''
+
+_over64bit_integer_dense_example = '''\
+%%MatrixMarket matrix array integer general
+2  2
+         2147483648
+9223372036854775807
+         2147483648
+9223372036854775808
+'''
+
+_over64bit_integer_sparse_example = '''\
+%%MatrixMarket matrix coordinate integer symmetric
+2  2  2
+1  1            2147483648
+2  2  19223372036854775808
+'''
+
+
+class TestMMIOReadLargeIntegers:
+    def setup_method(self):
+        self.tmpdir = mkdtemp(suffix=str(threading.get_native_id()))
+        self.fn = os.path.join(self.tmpdir, 'testfile.mtx')
+
+    def teardown_method(self):
+        shutil.rmtree(self.tmpdir)
+
+    def check_read(self, example, a, info, dense, over32, over64):
+        with open(self.fn, 'w') as f:
+            f.write(example)
+        assert_equal(mminfo(self.fn), info)
+        if ((over32 and (np.intp(0).itemsize < 8) and mmwrite == scipy.io._mmio.mmwrite)
+            or over64):
+            assert_raises(OverflowError, mmread, self.fn)
+        else:
+            b = mmread(self.fn, spmatrix=False)
+            if not dense:
+                b = b.toarray()
+            assert_equal(a, b)
+
+    def test_read_32bit_integer_dense(self):
+        a = array([[2**31-1, 2**31-1],
+                   [2**31-2, 2**31-2]], dtype=np.int64)
+        self.check_read(_32bit_integer_dense_example,
+                        a,
+                        (2, 2, 4, 'array', 'integer', 'general'),
+                        dense=True,
+                        over32=False,
+                        over64=False)
+
+    def test_read_32bit_integer_sparse(self):
+        a = array([[2**31-1, 0],
+                   [0, 2**31-2]], dtype=np.int64)
+        self.check_read(_32bit_integer_sparse_example,
+                        a,
+                        (2, 2, 2, 'coordinate', 'integer', 'symmetric'),
+                        dense=False,
+                        over32=False,
+                        over64=False)
+
+    def test_read_64bit_integer_dense(self):
+        a = array([[2**31, -2**31],
+                   [-2**63+2, 2**63-1]], dtype=np.int64)
+        self.check_read(_64bit_integer_dense_example,
+                        a,
+                        (2, 2, 4, 'array', 'integer', 'general'),
+                        dense=True,
+                        over32=True,
+                        over64=False)
+
+    def test_read_64bit_integer_sparse_general(self):
+        a = array([[2**31, 2**63-1],
+                   [0, 2**63-1]], dtype=np.int64)
+        self.check_read(_64bit_integer_sparse_general_example,
+                        a,
+                        (2, 2, 3, 'coordinate', 'integer', 'general'),
+                        dense=False,
+                        over32=True,
+                        over64=False)
+
+    def test_read_64bit_integer_sparse_symmetric(self):
+        a = array([[2**31, -2**63+1],
+                   [-2**63+1, 2**63-1]], dtype=np.int64)
+        self.check_read(_64bit_integer_sparse_symmetric_example,
+                        a,
+                        (2, 2, 3, 'coordinate', 'integer', 'symmetric'),
+                        dense=False,
+                        over32=True,
+                        over64=False)
+
+    def test_read_64bit_integer_sparse_skew(self):
+        a = array([[2**31, -2**63+1],
+                   [2**63-1, 2**63-1]], dtype=np.int64)
+        self.check_read(_64bit_integer_sparse_skew_example,
+                        a,
+                        (2, 2, 3, 'coordinate', 'integer', 'skew-symmetric'),
+                        dense=False,
+                        over32=True,
+                        over64=False)
+
+    def test_read_over64bit_integer_dense(self):
+        self.check_read(_over64bit_integer_dense_example,
+                        None,
+                        (2, 2, 4, 'array', 'integer', 'general'),
+                        dense=True,
+                        over32=True,
+                        over64=True)
+
+    def test_read_over64bit_integer_sparse(self):
+        self.check_read(_over64bit_integer_sparse_example,
+                        None,
+                        (2, 2, 2, 'coordinate', 'integer', 'symmetric'),
+                        dense=False,
+                        over32=True,
+                        over64=True)
+
+
+_general_example = '''\
+%%MatrixMarket matrix coordinate real general
+%=================================================================================
+%
+% This ASCII file represents a sparse MxN matrix with L
+% nonzeros in the following Matrix Market format:
+%
+% +----------------------------------------------+
+% |%%MatrixMarket matrix coordinate real general | <--- header line
+% |%                                             | <--+
+% |% comments                                    |    |-- 0 or more comment lines
+% |%                                             | <--+
+% |    M  N  L                                   | <--- rows, columns, entries
+% |    I1  J1  A(I1, J1)                         | <--+
+% |    I2  J2  A(I2, J2)                         |    |
+% |    I3  J3  A(I3, J3)                         |    |-- L lines
+% |        . . .                                 |    |
+% |    IL JL  A(IL, JL)                          | <--+
+% +----------------------------------------------+
+%
+% Indices are 1-based, i.e. A(1,1) is the first element.
+%
+%=================================================================================
+  5  5  8
+    1     1   1.000e+00
+    2     2   1.050e+01
+    3     3   1.500e-02
+    1     4   6.000e+00
+    4     2   2.505e+02
+    4     4  -2.800e+02
+    4     5   3.332e+01
+    5     5   1.200e+01
+'''
+
+_hermitian_example = '''\
+%%MatrixMarket matrix coordinate complex hermitian
+  5  5  7
+    1     1     1.0      0
+    2     2    10.5      0
+    4     2   250.5     22.22
+    3     3     1.5e-2   0
+    4     4    -2.8e2    0
+    5     5    12.       0
+    5     4     0       33.32
+'''
+
+_skew_example = '''\
+%%MatrixMarket matrix coordinate real skew-symmetric
+  5  5  7
+    1     1     1.0
+    2     2    10.5
+    4     2   250.5
+    3     3     1.5e-2
+    4     4    -2.8e2
+    5     5    12.
+    5     4     0
+'''
+
+_symmetric_example = '''\
+%%MatrixMarket matrix coordinate real symmetric
+  5  5  7
+    1     1     1.0
+    2     2    10.5
+    4     2   250.5
+    3     3     1.5e-2
+    4     4    -2.8e2
+    5     5    12.
+    5     4     8
+'''
+
+_symmetric_pattern_example = '''\
+%%MatrixMarket matrix coordinate pattern symmetric
+  5  5  7
+    1     1
+    2     2
+    4     2
+    3     3
+    4     4
+    5     5
+    5     4
+'''
+
+# example (without comment lines) from Figure 1 in
+# https://math.nist.gov/MatrixMarket/reports/MMformat.ps
+_empty_lines_example = '''\
+%%MatrixMarket  MATRIX    Coordinate    Real General
+
+   5  5         8
+
+1 1  1.0
+2 2       10.5
+3 3             1.5e-2
+4 4                     -2.8E2
+5 5                              12.
+     1      4      6
+     4      2      250.5
+     4      5      33.32
+
+'''
+
+
+class TestMMIOCoordinate:
+    def setup_method(self):
+        self.tmpdir = mkdtemp(suffix=str(threading.get_native_id()))
+        self.fn = os.path.join(self.tmpdir, 'testfile.mtx')
+
+    def teardown_method(self):
+        shutil.rmtree(self.tmpdir)
+
+    def check_read(self, example, a, info):
+        f = open(self.fn, 'w')
+        f.write(example)
+        f.close()
+        assert_equal(mminfo(self.fn), info)
+        b = mmread(self.fn, spmatrix=False).toarray()
+        assert_array_almost_equal(a, b)
+
+    def test_read_general(self):
+        a = [[1, 0, 0, 6, 0],
+             [0, 10.5, 0, 0, 0],
+             [0, 0, .015, 0, 0],
+             [0, 250.5, 0, -280, 33.32],
+             [0, 0, 0, 0, 12]]
+        self.check_read(_general_example, a,
+                        (5, 5, 8, 'coordinate', 'real', 'general'))
+
+    def test_read_hermitian(self):
+        a = [[1, 0, 0, 0, 0],
+             [0, 10.5, 0, 250.5 - 22.22j, 0],
+             [0, 0, .015, 0, 0],
+             [0, 250.5 + 22.22j, 0, -280, -33.32j],
+             [0, 0, 0, 33.32j, 12]]
+        self.check_read(_hermitian_example, a,
+                        (5, 5, 7, 'coordinate', 'complex', 'hermitian'))
+
+    def test_read_skew(self):
+        a = [[1, 0, 0, 0, 0],
+             [0, 10.5, 0, -250.5, 0],
+             [0, 0, .015, 0, 0],
+             [0, 250.5, 0, -280, 0],
+             [0, 0, 0, 0, 12]]
+        self.check_read(_skew_example, a,
+                        (5, 5, 7, 'coordinate', 'real', 'skew-symmetric'))
+
+    def test_read_symmetric(self):
+        a = [[1, 0, 0, 0, 0],
+             [0, 10.5, 0, 250.5, 0],
+             [0, 0, .015, 0, 0],
+             [0, 250.5, 0, -280, 8],
+             [0, 0, 0, 8, 12]]
+        self.check_read(_symmetric_example, a,
+                        (5, 5, 7, 'coordinate', 'real', 'symmetric'))
+
+    def test_read_symmetric_pattern(self):
+        a = [[1, 0, 0, 0, 0],
+             [0, 1, 0, 1, 0],
+             [0, 0, 1, 0, 0],
+             [0, 1, 0, 1, 1],
+             [0, 0, 0, 1, 1]]
+        self.check_read(_symmetric_pattern_example, a,
+                        (5, 5, 7, 'coordinate', 'pattern', 'symmetric'))
+
+    def test_read_empty_lines(self):
+        a = [[1, 0, 0, 6, 0],
+             [0, 10.5, 0, 0, 0],
+             [0, 0, .015, 0, 0],
+             [0, 250.5, 0, -280, 33.32],
+             [0, 0, 0, 0, 12]]
+        self.check_read(_empty_lines_example, a,
+                        (5, 5, 8, 'coordinate', 'real', 'general'))
+
+    def test_empty_write_read(self):
+        # https://github.com/scipy/scipy/issues/1410 (Trac #883)
+
+        b = scipy.sparse.coo_array((10, 10))
+        mmwrite(self.fn, b)
+
+        assert_equal(mminfo(self.fn),
+                     (10, 10, 0, 'coordinate', 'real', 'symmetric'))
+        a = b.toarray()
+        b = mmread(self.fn, spmatrix=False).toarray()
+        assert_array_almost_equal(a, b)
+
+    def test_bzip2_py3(self):
+        # test if fix for #2152 works
+        try:
+            # bz2 module isn't always built when building Python.
+            import bz2
+        except ImportError:
+            return
+        I = array([0, 0, 1, 2, 3, 3, 3, 4])
+        J = array([0, 3, 1, 2, 1, 3, 4, 4])
+        V = array([1.0, 6.0, 10.5, 0.015, 250.5, -280.0, 33.32, 12.0])
+
+        b = scipy.sparse.coo_array((V, (I, J)), shape=(5, 5))
+
+        mmwrite(self.fn, b)
+
+        fn_bzip2 = f"{self.fn}.bz2"
+        with open(self.fn, 'rb') as f_in:
+            f_out = bz2.BZ2File(fn_bzip2, 'wb')
+            f_out.write(f_in.read())
+            f_out.close()
+
+        a = mmread(fn_bzip2, spmatrix=False).toarray()
+        assert_array_almost_equal(a, b.toarray())
+
+    def test_gzip_py3(self):
+        # test if fix for #2152 works
+        try:
+            # gzip module can be missing from Python installation
+            import gzip
+        except ImportError:
+            return
+        I = array([0, 0, 1, 2, 3, 3, 3, 4])
+        J = array([0, 3, 1, 2, 1, 3, 4, 4])
+        V = array([1.0, 6.0, 10.5, 0.015, 250.5, -280.0, 33.32, 12.0])
+
+        b = scipy.sparse.coo_array((V, (I, J)), shape=(5, 5))
+
+        mmwrite(self.fn, b)
+
+        fn_gzip = f"{self.fn}.gz"
+        with open(self.fn, 'rb') as f_in:
+            f_out = gzip.open(fn_gzip, 'wb')
+            f_out.write(f_in.read())
+            f_out.close()
+
+        a = mmread(fn_gzip, spmatrix=False).toarray()
+        assert_array_almost_equal(a, b.toarray())
+
+    def test_real_write_read(self):
+        I = array([0, 0, 1, 2, 3, 3, 3, 4])
+        J = array([0, 3, 1, 2, 1, 3, 4, 4])
+        V = array([1.0, 6.0, 10.5, 0.015, 250.5, -280.0, 33.32, 12.0])
+
+        b = scipy.sparse.coo_array((V, (I, J)), shape=(5, 5))
+
+        mmwrite(self.fn, b)
+
+        assert_equal(mminfo(self.fn),
+                     (5, 5, 8, 'coordinate', 'real', 'general'))
+        a = b.toarray()
+        b = mmread(self.fn, spmatrix=False).toarray()
+        assert_array_almost_equal(a, b)
+
+    def test_complex_write_read(self):
+        I = array([0, 0, 1, 2, 3, 3, 3, 4])
+        J = array([0, 3, 1, 2, 1, 3, 4, 4])
+        V = array([1.0 + 3j, 6.0 + 2j, 10.50 + 0.9j, 0.015 + -4.4j,
+                   250.5 + 0j, -280.0 + 5j, 33.32 + 6.4j, 12.00 + 0.8j])
+
+        b = scipy.sparse.coo_array((V, (I, J)), shape=(5, 5))
+
+        mmwrite(self.fn, b)
+
+        assert_equal(mminfo(self.fn),
+                     (5, 5, 8, 'coordinate', 'complex', 'general'))
+        a = b.toarray()
+        b = mmread(self.fn, spmatrix=False).toarray()
+        assert_array_almost_equal(a, b)
+
+    def test_sparse_formats(self, tmp_path):
+        # Note: `tmp_path` is a pytest fixture, it handles cleanup
+        tmpdir = tmp_path / 'sparse_formats'
+        tmpdir.mkdir()
+
+        mats = []
+        I = array([0, 0, 1, 2, 3, 3, 3, 4])
+        J = array([0, 3, 1, 2, 1, 3, 4, 4])
+
+        V = array([1.0, 6.0, 10.5, 0.015, 250.5, -280.0, 33.32, 12.0])
+        mats.append(scipy.sparse.coo_array((V, (I, J)), shape=(5, 5)))
+
+        V = array([1.0 + 3j, 6.0 + 2j, 10.50 + 0.9j, 0.015 + -4.4j,
+                   250.5 + 0j, -280.0 + 5j, 33.32 + 6.4j, 12.00 + 0.8j])
+        mats.append(scipy.sparse.coo_array((V, (I, J)), shape=(5, 5)))
+
+        for mat in mats:
+            expected = mat.toarray()
+            for fmt in ['csr', 'csc', 'coo']:
+                fname = tmpdir / (fmt + '.mtx')
+                mmwrite(fname, mat.asformat(fmt))
+                result = mmread(fname, spmatrix=False).toarray()
+                assert_array_almost_equal(result, expected)
+
+    def test_precision(self):
+        test_values = [pi] + [10**(i) for i in range(0, -10, -1)]
+        test_precisions = range(1, 10)
+        for value in test_values:
+            for precision in test_precisions:
+                # construct sparse matrix with test value at last main diagonal
+                n = 10**precision + 1
+                A = scipy.sparse.dok_array((n, n))
+                A[n-1, n-1] = value
+                # write matrix with test precision and read again
+                mmwrite(self.fn, A, precision=precision)
+                A = scipy.io.mmread(self.fn, spmatrix=False)
+                # check for right entries in matrix
+                assert_array_equal(A.row, [n-1])
+                assert_array_equal(A.col, [n-1])
+                assert_allclose(A.data, [float(f'{value:.{precision}g}')])
+
+    def test_bad_number_of_coordinate_header_fields(self):
+        s = """\
+            %%MatrixMarket matrix coordinate real general
+              5  5  8 999
+                1     1   1.000e+00
+                2     2   1.050e+01
+                3     3   1.500e-02
+                1     4   6.000e+00
+                4     2   2.505e+02
+                4     4  -2.800e+02
+                4     5   3.332e+01
+                5     5   1.200e+01
+            """
+        text = textwrap.dedent(s).encode('ascii')
+        with pytest.raises(ValueError, match='not of length 3'):
+            scipy.io.mmread(io.BytesIO(text))
+
+
+def test_gh11389():
+    mmread(io.StringIO("%%MatrixMarket matrix coordinate complex symmetric\n"
+                       " 1 1 1\n"
+                       "1 1 -2.1846000000000e+02  0.0000000000000e+00"),
+           spmatrix=False)
+
+
+def test_gh18123(tmp_path):
+    lines = [" %%MatrixMarket matrix coordinate real general\n",
+             "5 5 3\n",
+             "2 3 1.0\n",
+             "3 4 2.0\n",
+             "3 5 3.0\n"]
+    test_file = tmp_path / "test.mtx"
+    with open(test_file, "w") as f:
+        f.writelines(lines)
+    mmread(test_file, spmatrix=False)
+
+def test_mtx_append(tmp_path):
+    a = mmread(io.StringIO("%%MatrixMarket matrix coordinate complex symmetric\n"
+                           " 1 1 1\n"
+                           "1 1 -2.1846000000000e+02  0.0000000000000e+00"),
+               spmatrix=False)
+    test_writefile = tmp_path / "test_mtx"
+    test_readfile  = tmp_path / "test_mtx.mtx"
+    mmwrite(test_writefile, a)
+    mmread(test_readfile, spmatrix=False)
+
+
+def check_threadpoolctl():
+    try:
+        import threadpoolctl
+        if not hasattr(threadpoolctl, "register"):
+            pytest.skip("threadpoolctl too old")
+            return
+    except ImportError:
+        pytest.skip("no threadpoolctl")
+        return
+
+
+def test_threadpoolctl():
+    check_threadpoolctl()
+
+    import threadpoolctl
+
+    # Ensure the extension module _fmm_core is loaded.
+    from scipy.io._fast_matrix_market import _fmm_core  # noqa: F401
+
+    with threadpoolctl.threadpool_limits(limits=4):
+        assert_equal(fmm.PARALLELISM, 4)
+
+    with threadpoolctl.threadpool_limits(limits=2, user_api='scipy'):
+        assert_equal(fmm.PARALLELISM, 2)
+
+
+def test_scipy_threadpoolctl_version():
+    check_threadpoolctl()
+
+    import threadpoolctl
+
+    # Ensure the extension module _fmm_core is loaded.
+    from scipy.io._fast_matrix_market import _fmm_core
+    with threadpoolctl.threadpool_limits(limits=4, user_api='scipy'):
+        ctls = threadpoolctl.threadpool_info()
+        for ctl in ctls:
+            if ctl['user_api'] == 'scipy' and ctl['internal_api'] == 'scipy_mmio':
+                assert ctl['version'] == _fmm_core.__version__
+
+
+def test_gh21999_file_not_exist():
+    tmpdir = mkdtemp(suffix=str(threading.get_native_id()))
+    wrong_fn = os.path.join(tmpdir, 'not_exist_test_file.mtx')
+    assert_raises(FileNotFoundError, mmread, wrong_fn)
diff --git a/.venv/lib/python3.12/site-packages/scipy/io/tests/test_netcdf.py b/.venv/lib/python3.12/site-packages/scipy/io/tests/test_netcdf.py
new file mode 100644
index 0000000000000000000000000000000000000000..6dd12f6b057d2e6abe6885ee892d4dfabd27e56a
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/io/tests/test_netcdf.py
@@ -0,0 +1,562 @@
+''' Tests for netcdf '''
+import os
+from os.path import join as pjoin, dirname
+import shutil
+import tempfile
+import warnings
+from io import BytesIO
+from glob import glob
+from contextlib import chdir, contextmanager
+
+import numpy as np
+from numpy.testing import assert_, assert_allclose, assert_equal
+
+import pytest
+from pytest import raises as assert_raises
+
+from scipy.io import netcdf_file
+
+TEST_DATA_PATH = pjoin(dirname(__file__), 'data')
+
+N_EG_ELS = 11  # number of elements for example variable
+VARTYPE_EG = 'b'  # var type for example variable
+
+
+pytestmark = pytest.mark.thread_unsafe
+
+
+@contextmanager
+def in_tempdir():
+    ''' Create, return, and change directory to a temporary directory
+
+    Examples
+    --------
+    >>> import os
+    >>> my_cwd = os.getcwd()
+    >>> with in_tempdir() as tmpdir:
+    ...     _ = open('test.txt', 'wt').write('some text')
+    ...     assert os.path.isfile('test.txt')
+    ...     assert os.path.isfile(os.path.join(tmpdir, 'test.txt'))
+    >>> os.path.exists(tmpdir)
+    False
+    >>> os.getcwd() == my_cwd
+    True
+    '''
+    with tempfile.TemporaryDirectory() as td:
+        with chdir(td):
+            yield td
+
+
+@contextmanager
+def make_simple(*args, **kwargs):
+    f = netcdf_file(*args, **kwargs)
+    f.history = 'Created for a test'
+    f.createDimension('time', N_EG_ELS)
+    time = f.createVariable('time', VARTYPE_EG, ('time',))
+    time[:] = np.arange(N_EG_ELS)
+    time.units = 'days since 2008-01-01'
+    f.flush()
+    yield f
+    f.close()
+
+
+def check_simple(ncfileobj):
+    '''Example fileobj tests '''
+    assert_equal(ncfileobj.history, b'Created for a test')
+    time = ncfileobj.variables['time']
+    assert_equal(time.units, b'days since 2008-01-01')
+    assert_equal(time.shape, (N_EG_ELS,))
+    assert_equal(time[-1], N_EG_ELS-1)
+
+def assert_mask_matches(arr, expected_mask):
+    '''
+    Asserts that the mask of arr is effectively the same as expected_mask.
+
+    In contrast to numpy.ma.testutils.assert_mask_equal, this function allows
+    testing the 'mask' of a standard numpy array (the mask in this case is treated
+    as all False).
+
+    Parameters
+    ----------
+    arr : ndarray or MaskedArray
+        Array to test.
+    expected_mask : array_like of booleans
+        A list giving the expected mask.
+    '''
+
+    mask = np.ma.getmaskarray(arr)
+    assert_equal(mask, expected_mask)
+
+
+def test_read_write_files():
+    # test round trip for example file
+    cwd = os.getcwd()
+    try:
+        tmpdir = tempfile.mkdtemp()
+        os.chdir(tmpdir)
+        with make_simple('simple.nc', 'w') as f:
+            pass
+        # read the file we just created in 'a' mode
+        with netcdf_file('simple.nc', 'a') as f:
+            check_simple(f)
+            # add something
+            f._attributes['appendRan'] = 1
+
+        # To read the NetCDF file we just created::
+        with netcdf_file('simple.nc') as f:
+            # Using mmap is the default
+            assert f.use_mmap
+            check_simple(f)
+            assert_equal(f._attributes['appendRan'], 1)
+
+        # Read it in append (and check mmap is off)
+        with netcdf_file('simple.nc', 'a') as f:
+            assert_(not f.use_mmap)
+            check_simple(f)
+            assert_equal(f._attributes['appendRan'], 1)
+
+        # Now without mmap
+        with netcdf_file('simple.nc', mmap=False) as f:
+            # Using mmap is the default
+            assert_(not f.use_mmap)
+            check_simple(f)
+
+        # To read the NetCDF file we just created, as file object, no
+        # mmap.  When n * n_bytes(var_type) is not divisible by 4, this
+        # raised an error in pupynere 1.0.12 and scipy rev 5893, because
+        # calculated vsize was rounding up in units of 4 - see
+        # https://www.unidata.ucar.edu/software/netcdf/guide_toc.html
+        with open('simple.nc', 'rb') as fobj:
+            with netcdf_file(fobj) as f:
+                # by default, don't use mmap for file-like
+                assert_(not f.use_mmap)
+                check_simple(f)
+
+        # Read file from fileobj, with mmap
+        with warnings.catch_warnings():
+            with open('simple.nc', 'rb') as fobj:
+                with netcdf_file(fobj, mmap=True) as f:
+                    assert_(f.use_mmap)
+                    check_simple(f)
+
+        # Again read it in append mode (adding another att)
+        with open('simple.nc', 'r+b') as fobj:
+            with netcdf_file(fobj, 'a') as f:
+                assert_(not f.use_mmap)
+                check_simple(f)
+                f.createDimension('app_dim', 1)
+                var = f.createVariable('app_var', 'i', ('app_dim',))
+                var[:] = 42
+
+        # And... check that app_var made it in...
+        with netcdf_file('simple.nc') as f:
+            check_simple(f)
+            assert_equal(f.variables['app_var'][:], 42)
+
+    finally:
+        os.chdir(cwd)
+        shutil.rmtree(tmpdir)
+
+
+def test_read_write_sio():
+    eg_sio1 = BytesIO()
+    with make_simple(eg_sio1, 'w'):
+        str_val = eg_sio1.getvalue()
+
+    eg_sio2 = BytesIO(str_val)
+    with netcdf_file(eg_sio2) as f2:
+        check_simple(f2)
+
+    # Test that error is raised if attempting mmap for sio
+    eg_sio3 = BytesIO(str_val)
+    assert_raises(ValueError, netcdf_file, eg_sio3, 'r', True)
+    # Test 64-bit offset write / read
+    eg_sio_64 = BytesIO()
+    with make_simple(eg_sio_64, 'w', version=2) as f_64:
+        str_val = eg_sio_64.getvalue()
+
+    eg_sio_64 = BytesIO(str_val)
+    with netcdf_file(eg_sio_64) as f_64:
+        check_simple(f_64)
+        assert_equal(f_64.version_byte, 2)
+    # also when version 2 explicitly specified
+    eg_sio_64 = BytesIO(str_val)
+    with netcdf_file(eg_sio_64, version=2) as f_64:
+        check_simple(f_64)
+        assert_equal(f_64.version_byte, 2)
+
+
+def test_bytes():
+    raw_file = BytesIO()
+    f = netcdf_file(raw_file, mode='w')
+    # Dataset only has a single variable, dimension and attribute to avoid
+    # any ambiguity related to order.
+    f.a = 'b'
+    f.createDimension('dim', 1)
+    var = f.createVariable('var', np.int16, ('dim',))
+    var[0] = -9999
+    var.c = 'd'
+    f.sync()
+
+    actual = raw_file.getvalue()
+
+    expected = (b'CDF\x01'
+                b'\x00\x00\x00\x00'
+                b'\x00\x00\x00\x0a'
+                b'\x00\x00\x00\x01'
+                b'\x00\x00\x00\x03'
+                b'dim\x00'
+                b'\x00\x00\x00\x01'
+                b'\x00\x00\x00\x0c'
+                b'\x00\x00\x00\x01'
+                b'\x00\x00\x00\x01'
+                b'a\x00\x00\x00'
+                b'\x00\x00\x00\x02'
+                b'\x00\x00\x00\x01'
+                b'b\x00\x00\x00'
+                b'\x00\x00\x00\x0b'
+                b'\x00\x00\x00\x01'
+                b'\x00\x00\x00\x03'
+                b'var\x00'
+                b'\x00\x00\x00\x01'
+                b'\x00\x00\x00\x00'
+                b'\x00\x00\x00\x0c'
+                b'\x00\x00\x00\x01'
+                b'\x00\x00\x00\x01'
+                b'c\x00\x00\x00'
+                b'\x00\x00\x00\x02'
+                b'\x00\x00\x00\x01'
+                b'd\x00\x00\x00'
+                b'\x00\x00\x00\x03'
+                b'\x00\x00\x00\x04'
+                b'\x00\x00\x00\x78'
+                b'\xd8\xf1\x80\x01')
+
+    assert_equal(actual, expected)
+
+
+def test_encoded_fill_value():
+    with netcdf_file(BytesIO(), mode='w') as f:
+        f.createDimension('x', 1)
+        var = f.createVariable('var', 'S1', ('x',))
+        assert_equal(var._get_encoded_fill_value(), b'\x00')
+        var._FillValue = b'\x01'
+        assert_equal(var._get_encoded_fill_value(), b'\x01')
+        var._FillValue = b'\x00\x00'  # invalid, wrong size
+        assert_equal(var._get_encoded_fill_value(), b'\x00')
+
+
+def test_read_example_data():
+    # read any example data files
+    for fname in glob(pjoin(TEST_DATA_PATH, '*.nc')):
+        with netcdf_file(fname, 'r'):
+            pass
+        with netcdf_file(fname, 'r', mmap=False):
+            pass
+
+
+def test_itemset_no_segfault_on_readonly():
+    # Regression test for ticket #1202.
+    # Open the test file in read-only mode.
+
+    filename = pjoin(TEST_DATA_PATH, 'example_1.nc')
+    with warnings.catch_warnings():
+        message = ("Cannot close a netcdf_file opened with mmap=True, when "
+                   "netcdf_variables or arrays referring to its data still exist")
+        warnings.filterwarnings("ignore", message, RuntimeWarning)
+        with netcdf_file(filename, 'r', mmap=True) as f:
+            time_var = f.variables['time']
+
+    # time_var.assignValue(42) should raise a RuntimeError--not seg. fault!
+    assert_raises(RuntimeError, time_var.assignValue, 42)
+
+
+def test_appending_issue_gh_8625():
+    stream = BytesIO()
+
+    with make_simple(stream, mode='w') as f:
+        f.createDimension('x', 2)
+        f.createVariable('x', float, ('x',))
+        f.variables['x'][...] = 1
+        f.flush()
+        contents = stream.getvalue()
+
+    stream = BytesIO(contents)
+    with netcdf_file(stream, mode='a') as f:
+        f.variables['x'][...] = 2
+
+
+def test_write_invalid_dtype():
+    dtypes = ['int64', 'uint64']
+    if np.dtype('int').itemsize == 8:   # 64-bit machines
+        dtypes.append('int')
+    if np.dtype('uint').itemsize == 8:   # 64-bit machines
+        dtypes.append('uint')
+
+    with netcdf_file(BytesIO(), 'w') as f:
+        f.createDimension('time', N_EG_ELS)
+        for dt in dtypes:
+            assert_raises(ValueError, f.createVariable, 'time', dt, ('time',))
+
+
+def test_flush_rewind():
+    stream = BytesIO()
+    with make_simple(stream, mode='w') as f:
+        f.createDimension('x',4)  # x is used in createVariable
+        v = f.createVariable('v', 'i2', ['x'])
+        v[:] = 1
+        f.flush()
+        len_single = len(stream.getvalue())
+        f.flush()
+        len_double = len(stream.getvalue())
+
+    assert_(len_single == len_double)
+
+
+def test_dtype_specifiers():
+    # Numpy 1.7.0-dev had a bug where 'i2' wouldn't work.
+    # Specifying np.int16 or similar only works from the same commit as this
+    # comment was made.
+    with make_simple(BytesIO(), mode='w') as f:
+        f.createDimension('x',4)
+        f.createVariable('v1', 'i2', ['x'])
+        f.createVariable('v2', np.int16, ['x'])
+        f.createVariable('v3', np.dtype(np.int16), ['x'])
+
+
+def test_ticket_1720():
+    io = BytesIO()
+
+    items = [0,0.1,0.2,0.3,0.4,0.5,0.6,0.7,0.8,0.9]
+
+    with netcdf_file(io, 'w') as f:
+        f.history = 'Created for a test'
+        f.createDimension('float_var', 10)
+        float_var = f.createVariable('float_var', 'f', ('float_var',))
+        float_var[:] = items
+        float_var.units = 'metres'
+        f.flush()
+        contents = io.getvalue()
+
+    io = BytesIO(contents)
+    with netcdf_file(io, 'r') as f:
+        assert_equal(f.history, b'Created for a test')
+        float_var = f.variables['float_var']
+        assert_equal(float_var.units, b'metres')
+        assert_equal(float_var.shape, (10,))
+        assert_allclose(float_var[:], items)
+
+
+def test_mmaps_segfault():
+    filename = pjoin(TEST_DATA_PATH, 'example_1.nc')
+
+    with warnings.catch_warnings():
+        warnings.simplefilter("error")
+        with netcdf_file(filename, mmap=True) as f:
+            x = f.variables['lat'][:]
+            # should not raise warnings
+            del x
+
+    def doit():
+        with netcdf_file(filename, mmap=True) as f:
+            return f.variables['lat'][:]
+
+    # should not crash
+    with warnings.catch_warnings():
+        message = ("Cannot close a netcdf_file opened with mmap=True, when "
+                   "netcdf_variables or arrays referring to its data still exist")
+        warnings.filterwarnings("ignore", message, RuntimeWarning)
+        x = doit()
+    x.sum()
+
+
+def test_zero_dimensional_var():
+    io = BytesIO()
+    with make_simple(io, 'w') as f:
+        v = f.createVariable('zerodim', 'i2', [])
+        # This is checking that .isrec returns a boolean - don't simplify it
+        # to 'assert not ...'
+        assert v.isrec is False, v.isrec
+        f.flush()
+
+
+def test_byte_gatts():
+    # Check that global "string" atts work like they did before py3k
+    # unicode and general bytes confusion
+    with in_tempdir():
+        filename = 'g_byte_atts.nc'
+        f = netcdf_file(filename, 'w')
+        f._attributes['holy'] = b'grail'
+        f._attributes['witch'] = 'floats'
+        f.close()
+        f = netcdf_file(filename, 'r')
+        assert_equal(f._attributes['holy'], b'grail')
+        assert_equal(f._attributes['witch'], b'floats')
+        f.close()
+
+
+def test_open_append():
+    # open 'w' put one attr
+    with in_tempdir():
+        filename = 'append_dat.nc'
+        f = netcdf_file(filename, 'w')
+        f._attributes['Kilroy'] = 'was here'
+        f.close()
+
+        # open again in 'a', read the att and a new one
+        f = netcdf_file(filename, 'a')
+        assert_equal(f._attributes['Kilroy'], b'was here')
+        f._attributes['naughty'] = b'Zoot'
+        f.close()
+
+        # open yet again in 'r' and check both atts
+        f = netcdf_file(filename, 'r')
+        assert_equal(f._attributes['Kilroy'], b'was here')
+        assert_equal(f._attributes['naughty'], b'Zoot')
+        f.close()
+
+
+def test_append_recordDimension():
+    dataSize = 100
+
+    with in_tempdir():
+        # Create file with record time dimension
+        with netcdf_file('withRecordDimension.nc', 'w') as f:
+            f.createDimension('time', None)
+            f.createVariable('time', 'd', ('time',))
+            f.createDimension('x', dataSize)
+            x = f.createVariable('x', 'd', ('x',))
+            x[:] = np.array(range(dataSize))
+            f.createDimension('y', dataSize)
+            y = f.createVariable('y', 'd', ('y',))
+            y[:] = np.array(range(dataSize))
+            f.createVariable('testData', 'i', ('time', 'x', 'y'))
+            f.flush()
+            f.close()
+
+        for i in range(2):
+            # Open the file in append mode and add data
+            with netcdf_file('withRecordDimension.nc', 'a') as f:
+                f.variables['time'].data = np.append(f.variables["time"].data, i)
+                f.variables['testData'][i, :, :] = np.full((dataSize, dataSize), i)
+                f.flush()
+
+            # Read the file and check that append worked
+            with netcdf_file('withRecordDimension.nc') as f:
+                assert_equal(f.variables['time'][-1], i)
+                assert_equal(f.variables['testData'][-1, :, :].copy(),
+                             np.full((dataSize, dataSize), i))
+                assert_equal(f.variables['time'].data.shape[0], i+1)
+                assert_equal(f.variables['testData'].data.shape[0], i+1)
+
+        # Read the file and check that 'data' was not saved as user defined
+        # attribute of testData variable during append operation
+        with netcdf_file('withRecordDimension.nc') as f:
+            with assert_raises(KeyError) as ar:
+                f.variables['testData']._attributes['data']
+            ex = ar.value
+            assert_equal(ex.args[0], 'data')
+
+def test_maskandscale():
+    t = np.linspace(20, 30, 15)
+    t[3] = 100
+    tm = np.ma.masked_greater(t, 99)
+    fname = pjoin(TEST_DATA_PATH, 'example_2.nc')
+    with netcdf_file(fname, maskandscale=True) as f:
+        Temp = f.variables['Temperature']
+        assert_equal(Temp.missing_value, 9999)
+        assert_equal(Temp.add_offset, 20)
+        assert_equal(Temp.scale_factor, np.float32(0.01))
+        found = Temp[:].compressed()
+        del Temp  # Remove ref to mmap, so file can be closed.
+        expected = np.round(tm.compressed(), 2)
+        assert_allclose(found, expected)
+
+    with in_tempdir():
+        newfname = 'ms.nc'
+        f = netcdf_file(newfname, 'w', maskandscale=True)
+        f.createDimension('Temperature', len(tm))
+        temp = f.createVariable('Temperature', 'i', ('Temperature',))
+        temp.missing_value = 9999
+        temp.scale_factor = 0.01
+        temp.add_offset = 20
+        temp[:] = tm
+        f.close()
+
+        with netcdf_file(newfname, maskandscale=True) as f:
+            Temp = f.variables['Temperature']
+            assert_equal(Temp.missing_value, 9999)
+            assert_equal(Temp.add_offset, 20)
+            assert_equal(Temp.scale_factor, np.float32(0.01))
+            expected = np.round(tm.compressed(), 2)
+            found = Temp[:].compressed()
+            del Temp
+            assert_allclose(found, expected)
+
+
+# ------------------------------------------------------------------------
+# Test reading with masked values (_FillValue / missing_value)
+# ------------------------------------------------------------------------
+
+def test_read_withValuesNearFillValue():
+    # Regression test for ticket #5626
+    fname = pjoin(TEST_DATA_PATH, 'example_3_maskedvals.nc')
+    with netcdf_file(fname, maskandscale=True) as f:
+        vardata = f.variables['var1_fillval0'][:]
+        assert_mask_matches(vardata, [False, True, False])
+
+def test_read_withNoFillValue():
+    # For a variable with no fill value, reading data with maskandscale=True
+    # should return unmasked data
+    fname = pjoin(TEST_DATA_PATH, 'example_3_maskedvals.nc')
+    with netcdf_file(fname, maskandscale=True) as f:
+        vardata = f.variables['var2_noFillval'][:]
+        assert_mask_matches(vardata, [False, False, False])
+        assert_equal(vardata, [1,2,3])
+
+def test_read_withFillValueAndMissingValue():
+    # For a variable with both _FillValue and missing_value, the _FillValue
+    # should be used
+    IRRELEVANT_VALUE = 9999
+    fname = pjoin(TEST_DATA_PATH, 'example_3_maskedvals.nc')
+    with netcdf_file(fname, maskandscale=True) as f:
+        vardata = f.variables['var3_fillvalAndMissingValue'][:]
+        assert_mask_matches(vardata, [True, False, False])
+        assert_equal(vardata, [IRRELEVANT_VALUE, 2, 3])
+
+def test_read_withMissingValue():
+    # For a variable with missing_value but not _FillValue, the missing_value
+    # should be used
+    fname = pjoin(TEST_DATA_PATH, 'example_3_maskedvals.nc')
+    with netcdf_file(fname, maskandscale=True) as f:
+        vardata = f.variables['var4_missingValue'][:]
+        assert_mask_matches(vardata, [False, True, False])
+
+def test_read_withFillValNaN():
+    fname = pjoin(TEST_DATA_PATH, 'example_3_maskedvals.nc')
+    with netcdf_file(fname, maskandscale=True) as f:
+        vardata = f.variables['var5_fillvalNaN'][:]
+        assert_mask_matches(vardata, [False, True, False])
+
+def test_read_withChar():
+    fname = pjoin(TEST_DATA_PATH, 'example_3_maskedvals.nc')
+    with netcdf_file(fname, maskandscale=True) as f:
+        vardata = f.variables['var6_char'][:]
+        assert_mask_matches(vardata, [False, True, False])
+
+def test_read_with2dVar():
+    fname = pjoin(TEST_DATA_PATH, 'example_3_maskedvals.nc')
+    with netcdf_file(fname, maskandscale=True) as f:
+        vardata = f.variables['var7_2d'][:]
+        assert_mask_matches(vardata, [[True, False], [False, False], [False, True]])
+
+def test_read_withMaskAndScaleFalse():
+    # If a variable has a _FillValue (or missing_value) attribute, but is read
+    # with maskandscale set to False, the result should be unmasked
+    fname = pjoin(TEST_DATA_PATH, 'example_3_maskedvals.nc')
+    # Open file with mmap=False to avoid problems with closing a mmap'ed file
+    # when arrays referring to its data still exist:
+    with netcdf_file(fname, maskandscale=False, mmap=False) as f:
+        vardata = f.variables['var3_fillvalAndMissingValue'][:]
+        assert_mask_matches(vardata, [False, False, False])
+        assert_equal(vardata, [1, 2, 3])
diff --git a/.venv/lib/python3.12/site-packages/scipy/io/tests/test_paths.py b/.venv/lib/python3.12/site-packages/scipy/io/tests/test_paths.py
new file mode 100644
index 0000000000000000000000000000000000000000..665628c96a5bd82f469d2f60a033172138771179
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/io/tests/test_paths.py
@@ -0,0 +1,93 @@
+"""
+Ensure that we can use pathlib.Path objects in all relevant IO functions.
+"""
+from pathlib import Path
+from tempfile import TemporaryDirectory
+
+import numpy as np
+
+import scipy.io
+import scipy.io.wavfile
+import scipy.sparse
+
+
+class TestPaths:
+    data = np.arange(5).astype(np.int64)
+
+    def test_savemat(self):
+        with TemporaryDirectory() as temp_dir:
+            path = Path(temp_dir) / 'data.mat'
+            scipy.io.savemat(path, {'data': self.data})
+            assert path.is_file()
+
+    def test_loadmat(self):
+        # Save data with string path, load with pathlib.Path
+        with TemporaryDirectory() as temp_dir:
+            path = Path(temp_dir) / 'data.mat'
+            scipy.io.savemat(str(path), {'data': self.data})
+
+            mat_contents = scipy.io.loadmat(path)
+            assert (mat_contents['data'] == self.data).all()
+
+    def test_whosmat(self):
+        # Save data with string path, load with pathlib.Path
+        with TemporaryDirectory() as temp_dir:
+            path = Path(temp_dir) / 'data.mat'
+            scipy.io.savemat(str(path), {'data': self.data})
+
+            contents = scipy.io.whosmat(path)
+            assert contents[0] == ('data', (1, 5), 'int64')
+
+    def test_readsav(self):
+        path = Path(__file__).parent / 'data/scalar_string.sav'
+        scipy.io.readsav(path)
+
+    def test_hb_read(self):
+        # Save data with string path, load with pathlib.Path
+        with TemporaryDirectory() as temp_dir:
+            data = scipy.sparse.eye_array(3, format='csr')
+            path = Path(temp_dir) / 'data.hb'
+            scipy.io.hb_write(str(path), data)
+
+            data_new = scipy.io.hb_read(path, spmatrix=False)
+            assert (data_new != data).nnz == 0
+
+    def test_hb_write(self):
+        with TemporaryDirectory() as temp_dir:
+            data = scipy.sparse.eye_array(3, format='csr')
+            path = Path(temp_dir) / 'data.hb'
+            scipy.io.hb_write(path, data)
+            assert path.is_file()
+
+    def test_mmio_read(self):
+        # Save data with string path, load with pathlib.Path
+        with TemporaryDirectory() as temp_dir:
+            data = scipy.sparse.eye_array(3, format='csr')
+            path = Path(temp_dir) / 'data.mtx'
+            scipy.io.mmwrite(str(path), data)
+
+            data_new = scipy.io.mmread(path, spmatrix=False)
+            assert (data_new != data).nnz == 0
+
+    def test_mmio_write(self):
+        with TemporaryDirectory() as temp_dir:
+            data = scipy.sparse.eye_array(3, format='csr')
+            path = Path(temp_dir) / 'data.mtx'
+            scipy.io.mmwrite(path, data)
+
+    def test_netcdf_file(self):
+        path = Path(__file__).parent / 'data/example_1.nc'
+        scipy.io.netcdf_file(path)
+
+    def test_wavfile_read(self):
+        path = Path(__file__).parent / 'data/test-8000Hz-le-2ch-1byteu.wav'
+        scipy.io.wavfile.read(path)
+
+    def test_wavfile_write(self):
+        # Read from str path, write to Path
+        input_path = Path(__file__).parent / 'data/test-8000Hz-le-2ch-1byteu.wav'
+        rate, data = scipy.io.wavfile.read(str(input_path))
+
+        with TemporaryDirectory() as temp_dir:
+            output_path = Path(temp_dir) / input_path.name
+            scipy.io.wavfile.write(output_path, rate, data)
diff --git a/.venv/lib/python3.12/site-packages/scipy/io/tests/test_wavfile.py b/.venv/lib/python3.12/site-packages/scipy/io/tests/test_wavfile.py
new file mode 100644
index 0000000000000000000000000000000000000000..1a3e9ce880c7e5ad796d02d43ea8de76d28c461f
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/io/tests/test_wavfile.py
@@ -0,0 +1,514 @@
+import os
+import sys
+from io import (BytesIO, UnsupportedOperation)
+import threading
+import warnings
+
+import numpy as np
+from numpy.testing import assert_equal, assert_, assert_array_equal
+
+import pytest
+from pytest import raises, warns
+
+from scipy.io import wavfile
+
+
+def datafile(fn):
+    return os.path.join(os.path.dirname(__file__), 'data', fn)
+
+
+def test_read_1():
+    # 32-bit PCM (which uses extensible format)
+    for mmap in [False, True]:
+        filename = 'test-44100Hz-le-1ch-4bytes.wav'
+        rate, data = wavfile.read(datafile(filename), mmap=mmap)
+
+        assert_equal(rate, 44100)
+        assert_(np.issubdtype(data.dtype, np.int32))
+        assert_equal(data.shape, (4410,))
+
+        del data
+
+
+def test_read_2():
+    # 8-bit unsigned PCM
+    for mmap in [False, True]:
+        filename = 'test-8000Hz-le-2ch-1byteu.wav'
+        rate, data = wavfile.read(datafile(filename), mmap=mmap)
+
+        assert_equal(rate, 8000)
+        assert_(np.issubdtype(data.dtype, np.uint8))
+        assert_equal(data.shape, (800, 2))
+
+        del data
+
+
+def test_read_3():
+    # Little-endian float
+    for mmap in [False, True]:
+        filename = 'test-44100Hz-2ch-32bit-float-le.wav'
+        rate, data = wavfile.read(datafile(filename), mmap=mmap)
+
+        assert_equal(rate, 44100)
+        assert_(np.issubdtype(data.dtype, np.float32))
+        assert_equal(data.shape, (441, 2))
+
+        del data
+
+
+def test_read_4():
+    # Contains unsupported 'PEAK' chunk
+    for mmap in [False, True]:
+        with warnings.catch_warnings():
+            warnings.filterwarnings(
+                "ignore",
+                "Chunk .non-data. not understood, skipping it",
+                wavfile.WavFileWarning
+            )
+            filename = 'test-48000Hz-2ch-64bit-float-le-wavex.wav'
+            rate, data = wavfile.read(datafile(filename), mmap=mmap)
+
+        assert_equal(rate, 48000)
+        assert_(np.issubdtype(data.dtype, np.float64))
+        assert_equal(data.shape, (480, 2))
+
+        del data
+
+
+def test_read_5():
+    # Big-endian float
+    for mmap in [False, True]:
+        filename = 'test-44100Hz-2ch-32bit-float-be.wav'
+        rate, data = wavfile.read(datafile(filename), mmap=mmap)
+
+        assert_equal(rate, 44100)
+        assert_(np.issubdtype(data.dtype, np.float32))
+        assert_(data.dtype.byteorder == '>' or (sys.byteorder == 'big' and
+                                                data.dtype.byteorder == '='))
+        assert_equal(data.shape, (441, 2))
+
+        del data
+
+
+def test_5_bit_odd_size_no_pad():
+    # 5-bit, 1 B container, 5 channels, 9 samples, 45 B data chunk
+    # Generated by LTspice, which incorrectly omits pad byte, but should be
+    # readable anyway
+    for mmap in [False, True]:
+        filename = 'test-8000Hz-le-5ch-9S-5bit.wav'
+        rate, data = wavfile.read(datafile(filename), mmap=mmap)
+
+        assert_equal(rate, 8000)
+        assert_(np.issubdtype(data.dtype, np.uint8))
+        assert_equal(data.shape, (9, 5))
+
+        # 8-5 = 3 LSBits should be 0
+        assert_equal(data & 0b00000111, 0)
+
+        # Unsigned
+        assert_equal(data.max(), 0b11111000)  # Highest possible
+        assert_equal(data[0, 0], 128)  # Midpoint is 128 for <= 8-bit
+        assert_equal(data.min(), 0)  # Lowest possible
+
+        del data
+
+
+def test_12_bit_even_size():
+    # 12-bit, 2 B container, 4 channels, 9 samples, 72 B data chunk
+    # Generated by LTspice from 1 Vpk sine waves
+    for mmap in [False, True]:
+        filename = 'test-8000Hz-le-4ch-9S-12bit.wav'
+        rate, data = wavfile.read(datafile(filename), mmap=mmap)
+
+        assert_equal(rate, 8000)
+        assert_(np.issubdtype(data.dtype, np.int16))
+        assert_equal(data.shape, (9, 4))
+
+        # 16-12 = 4 LSBits should be 0
+        assert_equal(data & 0b00000000_00001111, 0)
+
+        # Signed
+        assert_equal(data.max(), 0b01111111_11110000)  # Highest possible
+        assert_equal(data[0, 0], 0)  # Midpoint is 0 for >= 9-bit
+        assert_equal(data.min(), -0b10000000_00000000)  # Lowest possible
+
+        del data
+
+
+def test_24_bit_odd_size_with_pad():
+    # 24-bit, 3 B container, 3 channels, 5 samples, 45 B data chunk
+    # Should not raise any warnings about the data chunk pad byte
+    filename = 'test-8000Hz-le-3ch-5S-24bit.wav'
+    rate, data = wavfile.read(datafile(filename), mmap=False)
+
+    assert_equal(rate, 8000)
+    assert_(np.issubdtype(data.dtype, np.int32))
+    assert_equal(data.shape, (5, 3))
+
+    # All LSBytes should be 0
+    assert_equal(data & 0xff, 0)
+
+    # Hand-made max/min samples under different conventions:
+    #                      2**(N-1)     2**(N-1)-1     LSB
+    assert_equal(data, [[-0x8000_0000, -0x7fff_ff00, -0x200],
+                        [-0x4000_0000, -0x3fff_ff00, -0x100],
+                        [+0x0000_0000, +0x0000_0000, +0x000],
+                        [+0x4000_0000, +0x3fff_ff00, +0x100],
+                        [+0x7fff_ff00, +0x7fff_ff00, +0x200]])
+    #                     ^ clipped
+
+
+def test_20_bit_extra_data():
+    # 20-bit, 3 B container, 1 channel, 10 samples, 30 B data chunk
+    # with extra data filling container beyond the bit depth
+    filename = 'test-1234Hz-le-1ch-10S-20bit-extra.wav'
+    rate, data = wavfile.read(datafile(filename), mmap=False)
+
+    assert_equal(rate, 1234)
+    assert_(np.issubdtype(data.dtype, np.int32))
+    assert_equal(data.shape, (10,))
+
+    # All LSBytes should still be 0, because 3 B container in 4 B dtype
+    assert_equal(data & 0xff, 0)
+
+    # But it should load the data beyond 20 bits
+    assert_((data & 0xf00).any())
+
+    # Full-scale positive/negative samples, then being halved each time
+    assert_equal(data, [+0x7ffff000,       # +full-scale 20-bit
+                        -0x7ffff000,       # -full-scale 20-bit
+                        +0x7ffff000 >> 1,  # +1/2
+                        -0x7ffff000 >> 1,  # -1/2
+                        +0x7ffff000 >> 2,  # +1/4
+                        -0x7ffff000 >> 2,  # -1/4
+                        +0x7ffff000 >> 3,  # +1/8
+                        -0x7ffff000 >> 3,  # -1/8
+                        +0x7ffff000 >> 4,  # +1/16
+                        -0x7ffff000 >> 4,  # -1/16
+                        ])
+
+
+def test_36_bit_odd_size():
+    # 36-bit, 5 B container, 3 channels, 5 samples, 75 B data chunk + pad
+    filename = 'test-8000Hz-le-3ch-5S-36bit.wav'
+    rate, data = wavfile.read(datafile(filename), mmap=False)
+
+    assert_equal(rate, 8000)
+    assert_(np.issubdtype(data.dtype, np.int64))
+    assert_equal(data.shape, (5, 3))
+
+    # 28 LSBits should be 0
+    assert_equal(data & 0xfffffff, 0)
+
+    # Hand-made max/min samples under different conventions:
+    #            Fixed-point 2**(N-1)    Full-scale 2**(N-1)-1       LSB
+    correct = [[-0x8000_0000_0000_0000, -0x7fff_ffff_f000_0000, -0x2000_0000],
+               [-0x4000_0000_0000_0000, -0x3fff_ffff_f000_0000, -0x1000_0000],
+               [+0x0000_0000_0000_0000, +0x0000_0000_0000_0000, +0x0000_0000],
+               [+0x4000_0000_0000_0000, +0x3fff_ffff_f000_0000, +0x1000_0000],
+               [+0x7fff_ffff_f000_0000, +0x7fff_ffff_f000_0000, +0x2000_0000]]
+    #              ^ clipped
+
+    assert_equal(data, correct)
+
+
+def test_45_bit_even_size():
+    # 45-bit, 6 B container, 3 channels, 5 samples, 90 B data chunk
+    filename = 'test-8000Hz-le-3ch-5S-45bit.wav'
+    rate, data = wavfile.read(datafile(filename), mmap=False)
+
+    assert_equal(rate, 8000)
+    assert_(np.issubdtype(data.dtype, np.int64))
+    assert_equal(data.shape, (5, 3))
+
+    # 19 LSBits should be 0
+    assert_equal(data & 0x7ffff, 0)
+
+    # Hand-made max/min samples under different conventions:
+    #            Fixed-point 2**(N-1)    Full-scale 2**(N-1)-1      LSB
+    correct = [[-0x8000_0000_0000_0000, -0x7fff_ffff_fff8_0000, -0x10_0000],
+               [-0x4000_0000_0000_0000, -0x3fff_ffff_fff8_0000, -0x08_0000],
+               [+0x0000_0000_0000_0000, +0x0000_0000_0000_0000, +0x00_0000],
+               [+0x4000_0000_0000_0000, +0x3fff_ffff_fff8_0000, +0x08_0000],
+               [+0x7fff_ffff_fff8_0000, +0x7fff_ffff_fff8_0000, +0x10_0000]]
+    #              ^ clipped
+
+    assert_equal(data, correct)
+
+
+def test_53_bit_odd_size():
+    # 53-bit, 7 B container, 3 channels, 5 samples, 105 B data chunk + pad
+    filename = 'test-8000Hz-le-3ch-5S-53bit.wav'
+    rate, data = wavfile.read(datafile(filename), mmap=False)
+
+    assert_equal(rate, 8000)
+    assert_(np.issubdtype(data.dtype, np.int64))
+    assert_equal(data.shape, (5, 3))
+
+    # 11 LSBits should be 0
+    assert_equal(data & 0x7ff, 0)
+
+    # Hand-made max/min samples under different conventions:
+    #            Fixed-point 2**(N-1)    Full-scale 2**(N-1)-1    LSB
+    correct = [[-0x8000_0000_0000_0000, -0x7fff_ffff_ffff_f800, -0x1000],
+               [-0x4000_0000_0000_0000, -0x3fff_ffff_ffff_f800, -0x0800],
+               [+0x0000_0000_0000_0000, +0x0000_0000_0000_0000, +0x0000],
+               [+0x4000_0000_0000_0000, +0x3fff_ffff_ffff_f800, +0x0800],
+               [+0x7fff_ffff_ffff_f800, +0x7fff_ffff_ffff_f800, +0x1000]]
+    #              ^ clipped
+
+    assert_equal(data, correct)
+
+
+def test_64_bit_even_size():
+    # 64-bit, 8 B container, 3 channels, 5 samples, 120 B data chunk
+    for mmap in [False, True]:
+        filename = 'test-8000Hz-le-3ch-5S-64bit.wav'
+        rate, data = wavfile.read(datafile(filename), mmap=mmap)
+
+        assert_equal(rate, 8000)
+        assert_(np.issubdtype(data.dtype, np.int64))
+        assert_equal(data.shape, (5, 3))
+
+        # Hand-made max/min samples under different conventions:
+        #            Fixed-point 2**(N-1)    Full-scale 2**(N-1)-1   LSB
+        correct = [[-0x8000_0000_0000_0000, -0x7fff_ffff_ffff_ffff, -0x2],
+                   [-0x4000_0000_0000_0000, -0x3fff_ffff_ffff_ffff, -0x1],
+                   [+0x0000_0000_0000_0000, +0x0000_0000_0000_0000, +0x0],
+                   [+0x4000_0000_0000_0000, +0x3fff_ffff_ffff_ffff, +0x1],
+                   [+0x7fff_ffff_ffff_ffff, +0x7fff_ffff_ffff_ffff, +0x2]]
+        #              ^ clipped
+
+        assert_equal(data, correct)
+
+        del data
+
+
+def test_unsupported_mmap():
+    # Test containers that cannot be mapped to numpy types
+    for filename in {'test-8000Hz-le-3ch-5S-24bit.wav',
+                     'test-8000Hz-le-3ch-5S-36bit.wav',
+                     'test-8000Hz-le-3ch-5S-45bit.wav',
+                     'test-8000Hz-le-3ch-5S-53bit.wav',
+                     'test-1234Hz-le-1ch-10S-20bit-extra.wav'}:
+        with raises(ValueError, match="mmap.*not compatible"):
+            rate, data = wavfile.read(datafile(filename), mmap=True)
+
+
+def test_rifx():
+    # Compare equivalent RIFX and RIFF files
+    for rifx, riff in {('test-44100Hz-be-1ch-4bytes.wav',
+                        'test-44100Hz-le-1ch-4bytes.wav'),
+                       ('test-8000Hz-be-3ch-5S-24bit.wav',
+                        'test-8000Hz-le-3ch-5S-24bit.wav')}:
+        rate1, data1 = wavfile.read(datafile(rifx), mmap=False)
+        rate2, data2 = wavfile.read(datafile(riff), mmap=False)
+        assert_equal(rate1, rate2)
+        assert_equal(data1, data2)
+
+
+def test_rf64():
+    # Compare equivalent RF64 and RIFF files
+    for rf64, riff in {('test-44100Hz-le-1ch-4bytes-rf64.wav',
+                        'test-44100Hz-le-1ch-4bytes.wav'),
+                       ('test-8000Hz-le-3ch-5S-24bit-rf64.wav',
+                        'test-8000Hz-le-3ch-5S-24bit.wav')}:
+        rate1, data1 = wavfile.read(datafile(rf64), mmap=False)
+        rate2, data2 = wavfile.read(datafile(riff), mmap=False)
+        assert_array_equal(rate1, rate2)
+        assert_array_equal(data1, data2)
+
+
+@pytest.mark.xslow
+def test_write_roundtrip_rf64(tmpdir):
+    dtype = np.dtype(" 0
+                assert rate == 44100
+                # also test writing (gh-12176)
+                data[0] = 0
+
+
+def test_read_early_eof():
+    # File ends after 'fact' chunk at boundary, no data read
+    for mmap in [False, True]:
+        filename = 'test-44100Hz-le-1ch-4bytes-early-eof-no-data.wav'
+        with open(datafile(filename), 'rb') as fp:
+            with raises(ValueError, match="Unexpected end of file."):
+                wavfile.read(fp, mmap=mmap)
+
+
+def test_read_incomplete_chunk():
+    # File ends inside 'fmt ' chunk ID, no data read
+    for mmap in [False, True]:
+        filename = 'test-44100Hz-le-1ch-4bytes-incomplete-chunk.wav'
+        with open(datafile(filename), 'rb') as fp:
+            with raises(ValueError, match="Incomplete chunk ID.*b'f'"):
+                wavfile.read(fp, mmap=mmap)
+
+
+def test_read_inconsistent_header():
+    # File header's size fields contradict each other
+    for mmap in [False, True]:
+        filename = 'test-8000Hz-le-3ch-5S-24bit-inconsistent.wav'
+        with open(datafile(filename), 'rb') as fp:
+            with raises(ValueError, match="header is invalid"):
+                wavfile.read(fp, mmap=mmap)
+
+
+# signed 8-bit integer PCM is not allowed
+# unsigned > 8-bit integer PCM is not allowed
+# 8- or 16-bit float PCM is not expected
+# g and q are platform-dependent, so not included
+@pytest.mark.parametrize("dt_str", ["i2", ">i4", ">i8", ">f4", ">f8", '|u1'])
+@pytest.mark.parametrize("channels", [1, 2, 5])
+@pytest.mark.parametrize("rate", [8000, 32000])
+@pytest.mark.parametrize("mmap", [False, True])
+@pytest.mark.parametrize("realfile", [False, True])
+def test_write_roundtrip(realfile, mmap, rate, channels, dt_str, tmpdir):
+    dtype = np.dtype(dt_str)
+    if realfile:
+        tmpfile = str(tmpdir.join(str(threading.get_native_id()), 'temp.wav'))
+        os.makedirs(os.path.dirname(tmpfile), exist_ok=True)
+    else:
+        tmpfile = BytesIO()
+    data = np.random.rand(100, channels)
+    if channels == 1:
+        data = data[:, 0]
+    if dtype.kind == 'f':
+        # The range of the float type should be in [-1, 1]
+        data = data.astype(dtype)
+    else:
+        data = (data*128).astype(dtype)
+
+    wavfile.write(tmpfile, rate, data)
+
+    rate2, data2 = wavfile.read(tmpfile, mmap=mmap)
+
+    assert_equal(rate, rate2)
+    assert_(data2.dtype.byteorder in ('<', '=', '|'), msg=data2.dtype)
+    assert_array_equal(data, data2)
+    # also test writing (gh-12176)
+    if realfile:
+        data2[0] = 0
+    else:
+        with pytest.raises(ValueError, match='read-only'):
+            data2[0] = 0
+
+
+@pytest.mark.parametrize("dtype", [np.float16])
+def test_wavfile_dtype_unsupported(tmpdir, dtype):
+    tmpfile = str(tmpdir.join('temp.wav'))
+    rng = np.random.default_rng(1234)
+    data = rng.random((100, 5)).astype(dtype)
+    rate = 8000
+    with pytest.raises(ValueError, match="Unsupported"):
+        wavfile.write(tmpfile, rate, data)
+
+def test_seek_emulating_reader_invalid_seek():
+    # Dummy data for the reader
+    reader = wavfile.SeekEmulatingReader(BytesIO(b'\x00\x00'))
+    
+    # Test SEEK_END with an invalid whence value
+    with pytest.raises(UnsupportedOperation):
+        reader.seek(0, 5)  # Invalid whence value
+    
+    # Test with negative seek value
+    with pytest.raises(UnsupportedOperation):
+        reader.seek(-1, 0)  # Negative position with SEEK_SET
+    
+    # Test SEEK_END with valid parameters (should not raise)
+    pos = reader.seek(0, os.SEEK_END)  # Valid usage
+    assert pos == 2, f"Failed to seek to end, got position {pos}"
diff --git a/.venv/lib/python3.12/site-packages/scipy/io/wavfile.py b/.venv/lib/python3.12/site-packages/scipy/io/wavfile.py
new file mode 100644
index 0000000000000000000000000000000000000000..e9f7affcd2fa6ac108581a25853cb52347bea478
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/io/wavfile.py
@@ -0,0 +1,944 @@
+"""
+Module to read / write wav files using NumPy arrays
+
+Functions
+---------
+`read`: Return the sample rate (in samples/sec) and data from a WAV file.
+
+`write`: Write a NumPy array as a WAV file.
+
+"""
+import io
+import os
+import sys
+import numpy as np
+import struct
+import warnings
+from enum import IntEnum
+
+
+__all__ = [
+    'WavFileWarning',
+    'read',
+    'write'
+]
+
+
+class WavFileWarning(UserWarning):
+    """
+    Warning for WAV files with format issues that can still be read.
+    
+    Raised when a WAV file has problems like missing metadata or 
+    non-standard formatting, but can still be processed successfully.
+    """
+    pass
+
+
+class SeekEmulatingReader:
+    """
+    Tracks stream position, provides tell(), and emulates only those
+    seeks that can be supported by reading forward. Other seeks raise
+    io.UnsupportedOperation. Note that this class implements only the
+    minimum necessary to keep wavfile.read() happy.
+    """
+    def __init__(self, reader):
+        self.reader = reader
+        self.pos = 0
+
+    def read(self, size=-1, /):
+        data = self.reader.read(size)
+        self.pos += len(data)
+        return data
+    
+    def seek(self, offset, whence=os.SEEK_SET, /):
+        match whence:
+            case os.SEEK_SET if offset >= self.pos:
+                self.read(offset - self.pos) # convert to relative
+            case os.SEEK_CUR if offset >= 0:
+                self.read(offset) # advance by offset
+            case os.SEEK_END if offset == 0:
+                self.read() # advance to end of stream
+            case _:
+                raise io.UnsupportedOperation("SeekEmulatingReader was asked to emulate"
+                                              " a seek operation it does not support.")
+        return self.pos
+    
+    def tell(self):
+        return self.pos
+    
+    def close(self):
+        self.reader.close()
+    
+    # np.fromfile expects to be able to call flush(), and _read_data_chunk
+    # expects to catch io.UnsupportedOperation if np.fromfile fails.
+    def flush(self):
+        raise io.UnsupportedOperation("SeekEmulatingReader can't flush.")
+
+
+class WAVE_FORMAT(IntEnum):
+    """
+    WAVE form wFormatTag IDs
+
+    Complete list is in mmreg.h in Windows 10 SDK.  ALAC and OPUS are the
+    newest additions, in v10.0.14393 2016-07
+    """
+    UNKNOWN = 0x0000
+    PCM = 0x0001
+    ADPCM = 0x0002
+    IEEE_FLOAT = 0x0003
+    VSELP = 0x0004
+    IBM_CVSD = 0x0005
+    ALAW = 0x0006
+    MULAW = 0x0007
+    DTS = 0x0008
+    DRM = 0x0009
+    WMAVOICE9 = 0x000A
+    WMAVOICE10 = 0x000B
+    OKI_ADPCM = 0x0010
+    DVI_ADPCM = 0x0011
+    IMA_ADPCM = 0x0011  # Duplicate
+    MEDIASPACE_ADPCM = 0x0012
+    SIERRA_ADPCM = 0x0013
+    G723_ADPCM = 0x0014
+    DIGISTD = 0x0015
+    DIGIFIX = 0x0016
+    DIALOGIC_OKI_ADPCM = 0x0017
+    MEDIAVISION_ADPCM = 0x0018
+    CU_CODEC = 0x0019
+    HP_DYN_VOICE = 0x001A
+    YAMAHA_ADPCM = 0x0020
+    SONARC = 0x0021
+    DSPGROUP_TRUESPEECH = 0x0022
+    ECHOSC1 = 0x0023
+    AUDIOFILE_AF36 = 0x0024
+    APTX = 0x0025
+    AUDIOFILE_AF10 = 0x0026
+    PROSODY_1612 = 0x0027
+    LRC = 0x0028
+    DOLBY_AC2 = 0x0030
+    GSM610 = 0x0031
+    MSNAUDIO = 0x0032
+    ANTEX_ADPCME = 0x0033
+    CONTROL_RES_VQLPC = 0x0034
+    DIGIREAL = 0x0035
+    DIGIADPCM = 0x0036
+    CONTROL_RES_CR10 = 0x0037
+    NMS_VBXADPCM = 0x0038
+    CS_IMAADPCM = 0x0039
+    ECHOSC3 = 0x003A
+    ROCKWELL_ADPCM = 0x003B
+    ROCKWELL_DIGITALK = 0x003C
+    XEBEC = 0x003D
+    G721_ADPCM = 0x0040
+    G728_CELP = 0x0041
+    MSG723 = 0x0042
+    INTEL_G723_1 = 0x0043
+    INTEL_G729 = 0x0044
+    SHARP_G726 = 0x0045
+    MPEG = 0x0050
+    RT24 = 0x0052
+    PAC = 0x0053
+    MPEGLAYER3 = 0x0055
+    LUCENT_G723 = 0x0059
+    CIRRUS = 0x0060
+    ESPCM = 0x0061
+    VOXWARE = 0x0062
+    CANOPUS_ATRAC = 0x0063
+    G726_ADPCM = 0x0064
+    G722_ADPCM = 0x0065
+    DSAT = 0x0066
+    DSAT_DISPLAY = 0x0067
+    VOXWARE_BYTE_ALIGNED = 0x0069
+    VOXWARE_AC8 = 0x0070
+    VOXWARE_AC10 = 0x0071
+    VOXWARE_AC16 = 0x0072
+    VOXWARE_AC20 = 0x0073
+    VOXWARE_RT24 = 0x0074
+    VOXWARE_RT29 = 0x0075
+    VOXWARE_RT29HW = 0x0076
+    VOXWARE_VR12 = 0x0077
+    VOXWARE_VR18 = 0x0078
+    VOXWARE_TQ40 = 0x0079
+    VOXWARE_SC3 = 0x007A
+    VOXWARE_SC3_1 = 0x007B
+    SOFTSOUND = 0x0080
+    VOXWARE_TQ60 = 0x0081
+    MSRT24 = 0x0082
+    G729A = 0x0083
+    MVI_MVI2 = 0x0084
+    DF_G726 = 0x0085
+    DF_GSM610 = 0x0086
+    ISIAUDIO = 0x0088
+    ONLIVE = 0x0089
+    MULTITUDE_FT_SX20 = 0x008A
+    INFOCOM_ITS_G721_ADPCM = 0x008B
+    CONVEDIA_G729 = 0x008C
+    CONGRUENCY = 0x008D
+    SBC24 = 0x0091
+    DOLBY_AC3_SPDIF = 0x0092
+    MEDIASONIC_G723 = 0x0093
+    PROSODY_8KBPS = 0x0094
+    ZYXEL_ADPCM = 0x0097
+    PHILIPS_LPCBB = 0x0098
+    PACKED = 0x0099
+    MALDEN_PHONYTALK = 0x00A0
+    RACAL_RECORDER_GSM = 0x00A1
+    RACAL_RECORDER_G720_A = 0x00A2
+    RACAL_RECORDER_G723_1 = 0x00A3
+    RACAL_RECORDER_TETRA_ACELP = 0x00A4
+    NEC_AAC = 0x00B0
+    RAW_AAC1 = 0x00FF
+    RHETOREX_ADPCM = 0x0100
+    IRAT = 0x0101
+    VIVO_G723 = 0x0111
+    VIVO_SIREN = 0x0112
+    PHILIPS_CELP = 0x0120
+    PHILIPS_GRUNDIG = 0x0121
+    DIGITAL_G723 = 0x0123
+    SANYO_LD_ADPCM = 0x0125
+    SIPROLAB_ACEPLNET = 0x0130
+    SIPROLAB_ACELP4800 = 0x0131
+    SIPROLAB_ACELP8V3 = 0x0132
+    SIPROLAB_G729 = 0x0133
+    SIPROLAB_G729A = 0x0134
+    SIPROLAB_KELVIN = 0x0135
+    VOICEAGE_AMR = 0x0136
+    G726ADPCM = 0x0140
+    DICTAPHONE_CELP68 = 0x0141
+    DICTAPHONE_CELP54 = 0x0142
+    QUALCOMM_PUREVOICE = 0x0150
+    QUALCOMM_HALFRATE = 0x0151
+    TUBGSM = 0x0155
+    MSAUDIO1 = 0x0160
+    WMAUDIO2 = 0x0161
+    WMAUDIO3 = 0x0162
+    WMAUDIO_LOSSLESS = 0x0163
+    WMASPDIF = 0x0164
+    UNISYS_NAP_ADPCM = 0x0170
+    UNISYS_NAP_ULAW = 0x0171
+    UNISYS_NAP_ALAW = 0x0172
+    UNISYS_NAP_16K = 0x0173
+    SYCOM_ACM_SYC008 = 0x0174
+    SYCOM_ACM_SYC701_G726L = 0x0175
+    SYCOM_ACM_SYC701_CELP54 = 0x0176
+    SYCOM_ACM_SYC701_CELP68 = 0x0177
+    KNOWLEDGE_ADVENTURE_ADPCM = 0x0178
+    FRAUNHOFER_IIS_MPEG2_AAC = 0x0180
+    DTS_DS = 0x0190
+    CREATIVE_ADPCM = 0x0200
+    CREATIVE_FASTSPEECH8 = 0x0202
+    CREATIVE_FASTSPEECH10 = 0x0203
+    UHER_ADPCM = 0x0210
+    ULEAD_DV_AUDIO = 0x0215
+    ULEAD_DV_AUDIO_1 = 0x0216
+    QUARTERDECK = 0x0220
+    ILINK_VC = 0x0230
+    RAW_SPORT = 0x0240
+    ESST_AC3 = 0x0241
+    GENERIC_PASSTHRU = 0x0249
+    IPI_HSX = 0x0250
+    IPI_RPELP = 0x0251
+    CS2 = 0x0260
+    SONY_SCX = 0x0270
+    SONY_SCY = 0x0271
+    SONY_ATRAC3 = 0x0272
+    SONY_SPC = 0x0273
+    TELUM_AUDIO = 0x0280
+    TELUM_IA_AUDIO = 0x0281
+    NORCOM_VOICE_SYSTEMS_ADPCM = 0x0285
+    FM_TOWNS_SND = 0x0300
+    MICRONAS = 0x0350
+    MICRONAS_CELP833 = 0x0351
+    BTV_DIGITAL = 0x0400
+    INTEL_MUSIC_CODER = 0x0401
+    INDEO_AUDIO = 0x0402
+    QDESIGN_MUSIC = 0x0450
+    ON2_VP7_AUDIO = 0x0500
+    ON2_VP6_AUDIO = 0x0501
+    VME_VMPCM = 0x0680
+    TPC = 0x0681
+    LIGHTWAVE_LOSSLESS = 0x08AE
+    OLIGSM = 0x1000
+    OLIADPCM = 0x1001
+    OLICELP = 0x1002
+    OLISBC = 0x1003
+    OLIOPR = 0x1004
+    LH_CODEC = 0x1100
+    LH_CODEC_CELP = 0x1101
+    LH_CODEC_SBC8 = 0x1102
+    LH_CODEC_SBC12 = 0x1103
+    LH_CODEC_SBC16 = 0x1104
+    NORRIS = 0x1400
+    ISIAUDIO_2 = 0x1401
+    SOUNDSPACE_MUSICOMPRESS = 0x1500
+    MPEG_ADTS_AAC = 0x1600
+    MPEG_RAW_AAC = 0x1601
+    MPEG_LOAS = 0x1602
+    NOKIA_MPEG_ADTS_AAC = 0x1608
+    NOKIA_MPEG_RAW_AAC = 0x1609
+    VODAFONE_MPEG_ADTS_AAC = 0x160A
+    VODAFONE_MPEG_RAW_AAC = 0x160B
+    MPEG_HEAAC = 0x1610
+    VOXWARE_RT24_SPEECH = 0x181C
+    SONICFOUNDRY_LOSSLESS = 0x1971
+    INNINGS_TELECOM_ADPCM = 0x1979
+    LUCENT_SX8300P = 0x1C07
+    LUCENT_SX5363S = 0x1C0C
+    CUSEEME = 0x1F03
+    NTCSOFT_ALF2CM_ACM = 0x1FC4
+    DVM = 0x2000
+    DTS2 = 0x2001
+    MAKEAVIS = 0x3313
+    DIVIO_MPEG4_AAC = 0x4143
+    NOKIA_ADAPTIVE_MULTIRATE = 0x4201
+    DIVIO_G726 = 0x4243
+    LEAD_SPEECH = 0x434C
+    LEAD_VORBIS = 0x564C
+    WAVPACK_AUDIO = 0x5756
+    OGG_VORBIS_MODE_1 = 0x674F
+    OGG_VORBIS_MODE_2 = 0x6750
+    OGG_VORBIS_MODE_3 = 0x6751
+    OGG_VORBIS_MODE_1_PLUS = 0x676F
+    OGG_VORBIS_MODE_2_PLUS = 0x6770
+    OGG_VORBIS_MODE_3_PLUS = 0x6771
+    ALAC = 0x6C61
+    _3COM_NBX = 0x7000  # Can't have leading digit
+    OPUS = 0x704F
+    FAAD_AAC = 0x706D
+    AMR_NB = 0x7361
+    AMR_WB = 0x7362
+    AMR_WP = 0x7363
+    GSM_AMR_CBR = 0x7A21
+    GSM_AMR_VBR_SID = 0x7A22
+    COMVERSE_INFOSYS_G723_1 = 0xA100
+    COMVERSE_INFOSYS_AVQSBC = 0xA101
+    COMVERSE_INFOSYS_SBC = 0xA102
+    SYMBOL_G729_A = 0xA103
+    VOICEAGE_AMR_WB = 0xA104
+    INGENIENT_G726 = 0xA105
+    MPEG4_AAC = 0xA106
+    ENCORE_G726 = 0xA107
+    ZOLL_ASAO = 0xA108
+    SPEEX_VOICE = 0xA109
+    VIANIX_MASC = 0xA10A
+    WM9_SPECTRUM_ANALYZER = 0xA10B
+    WMF_SPECTRUM_ANAYZER = 0xA10C
+    GSM_610 = 0xA10D
+    GSM_620 = 0xA10E
+    GSM_660 = 0xA10F
+    GSM_690 = 0xA110
+    GSM_ADAPTIVE_MULTIRATE_WB = 0xA111
+    POLYCOM_G722 = 0xA112
+    POLYCOM_G728 = 0xA113
+    POLYCOM_G729_A = 0xA114
+    POLYCOM_SIREN = 0xA115
+    GLOBAL_IP_ILBC = 0xA116
+    RADIOTIME_TIME_SHIFT_RADIO = 0xA117
+    NICE_ACA = 0xA118
+    NICE_ADPCM = 0xA119
+    VOCORD_G721 = 0xA11A
+    VOCORD_G726 = 0xA11B
+    VOCORD_G722_1 = 0xA11C
+    VOCORD_G728 = 0xA11D
+    VOCORD_G729 = 0xA11E
+    VOCORD_G729_A = 0xA11F
+    VOCORD_G723_1 = 0xA120
+    VOCORD_LBC = 0xA121
+    NICE_G728 = 0xA122
+    FRACE_TELECOM_G729 = 0xA123
+    CODIAN = 0xA124
+    FLAC = 0xF1AC
+    EXTENSIBLE = 0xFFFE
+    DEVELOPMENT = 0xFFFF
+
+
+KNOWN_WAVE_FORMATS = {WAVE_FORMAT.PCM, WAVE_FORMAT.IEEE_FLOAT}
+
+
+def _raise_bad_format(format_tag):
+    try:
+        format_name = WAVE_FORMAT(format_tag).name
+    except ValueError:
+        format_name = f'{format_tag:#06x}'
+    raise ValueError(f"Unknown wave file format: {format_name}. Supported "
+                     "formats: " +
+                     ', '.join(x.name for x in KNOWN_WAVE_FORMATS))
+
+
+def _read_fmt_chunk(fid, is_big_endian):
+    """
+    Returns
+    -------
+    size : int
+        size of format subchunk in bytes (minus 8 for "fmt " and itself)
+    format_tag : int
+        PCM, float, or compressed format
+    channels : int
+        number of channels
+    fs : int
+        sampling frequency in samples per second
+    bytes_per_second : int
+        overall byte rate for the file
+    block_align : int
+        bytes per sample, including all channels
+    bit_depth : int
+        bits per sample
+
+    Notes
+    -----
+    Assumes file pointer is immediately after the 'fmt ' id
+    """
+    if is_big_endian:
+        fmt = '>'
+    else:
+        fmt = '<'
+
+    size = struct.unpack(fmt+'I', fid.read(4))[0]
+
+    if size < 16:
+        raise ValueError("Binary structure of wave file is not compliant")
+
+    res = struct.unpack(fmt+'HHIIHH', fid.read(16))
+    bytes_read = 16
+
+    format_tag, channels, fs, bytes_per_second, block_align, bit_depth = res
+
+    if format_tag == WAVE_FORMAT.EXTENSIBLE and size >= (16+2):
+        ext_chunk_size = struct.unpack(fmt+'H', fid.read(2))[0]
+        bytes_read += 2
+        if ext_chunk_size >= 22:
+            extensible_chunk_data = fid.read(22)
+            bytes_read += 22
+            raw_guid = extensible_chunk_data[2+4:2+4+16]
+            # GUID template {XXXXXXXX-0000-0010-8000-00AA00389B71} (RFC-2361)
+            # MS GUID byte order: first three groups are native byte order,
+            # rest is Big Endian
+            if is_big_endian:
+                tail = b'\x00\x00\x00\x10\x80\x00\x00\xAA\x00\x38\x9B\x71'
+            else:
+                tail = b'\x00\x00\x10\x00\x80\x00\x00\xAA\x00\x38\x9B\x71'
+            if raw_guid.endswith(tail):
+                format_tag = struct.unpack(fmt+'I', raw_guid[:4])[0]
+        else:
+            raise ValueError("Binary structure of wave file is not compliant")
+
+    if format_tag not in KNOWN_WAVE_FORMATS:
+        _raise_bad_format(format_tag)
+
+    # move file pointer to next chunk
+    if size > bytes_read:
+        fid.read(size - bytes_read)
+
+    # fmt should always be 16, 18 or 40, but handle it just in case
+    _handle_pad_byte(fid, size)
+
+    if format_tag == WAVE_FORMAT.PCM:
+        if bytes_per_second != fs * block_align:
+            raise ValueError("WAV header is invalid: nAvgBytesPerSec must"
+                             " equal product of nSamplesPerSec and"
+                             " nBlockAlign, but file has nSamplesPerSec ="
+                             f" {fs}, nBlockAlign = {block_align}, and"
+                             f" nAvgBytesPerSec = {bytes_per_second}")
+
+    return (size, format_tag, channels, fs, bytes_per_second, block_align,
+            bit_depth)
+
+
+def _read_data_chunk(fid, format_tag, channels, bit_depth, is_big_endian, is_rf64,
+                     block_align, mmap=False, rf64_chunk_size=None):
+    """
+    Notes
+    -----
+    Assumes file pointer is immediately after the 'data' id
+
+    It's possible to not use all available bits in a container, or to store
+    samples in a container bigger than necessary, so bytes_per_sample uses
+    the actual reported container size (nBlockAlign / nChannels).  Real-world
+    examples:
+
+    Adobe Audition's "24-bit packed int (type 1, 20-bit)"
+
+        nChannels = 2, nBlockAlign = 6, wBitsPerSample = 20
+
+    http://www-mmsp.ece.mcgill.ca/Documents/AudioFormats/WAVE/Samples/AFsp/M1F1-int12-AFsp.wav
+    is:
+
+        nChannels = 2, nBlockAlign = 4, wBitsPerSample = 12
+
+    http://www-mmsp.ece.mcgill.ca/Documents/AudioFormats/WAVE/Docs/multichaudP.pdf
+    gives an example of:
+
+        nChannels = 2, nBlockAlign = 8, wBitsPerSample = 20
+    """
+    if is_big_endian:
+        fmt = '>'
+    else:
+        fmt = '<'
+
+    # Size of the data subchunk in bytes
+    if not is_rf64:
+        size = struct.unpack(fmt+'I', fid.read(4))[0]
+    else:
+        # chunk size is stored in global file header for RF64
+        size = rf64_chunk_size
+        # skip data chunk size as it is 0xFFFFFFF
+        fid.read(4)
+
+    # Number of bytes per sample (sample container size)
+    bytes_per_sample = block_align // channels
+    n_samples = size // bytes_per_sample
+
+    if format_tag == WAVE_FORMAT.PCM:
+        if 1 <= bit_depth <= 8:
+            dtype = 'u1'  # WAV of 8-bit integer or less are unsigned
+        elif bytes_per_sample in {3, 5, 6, 7}:
+            # No compatible dtype.  Load as raw bytes for reshaping later.
+            dtype = 'V1'
+        elif bit_depth <= 64:
+            # Remaining bit depths can map directly to signed numpy dtypes
+            dtype = f'{fmt}i{bytes_per_sample}'
+        else:
+            raise ValueError("Unsupported bit depth: the WAV file "
+                             f"has {bit_depth}-bit integer data.")
+    elif format_tag == WAVE_FORMAT.IEEE_FLOAT:
+        if bit_depth in {32, 64}:
+            dtype = f'{fmt}f{bytes_per_sample}'
+        else:
+            raise ValueError("Unsupported bit depth: the WAV file "
+                             f"has {bit_depth}-bit floating-point data.")
+    else:
+        _raise_bad_format(format_tag)
+
+    start = fid.tell()
+    if not mmap:
+        try:
+            count = size if dtype == 'V1' else n_samples
+            data = np.fromfile(fid, dtype=dtype, count=count)
+        except io.UnsupportedOperation:  # not a C-like file
+            fid.seek(start, 0)  # just in case it seeked, though it shouldn't
+            data = np.frombuffer(fid.read(size), dtype=dtype)
+
+        if dtype == 'V1':
+            # Rearrange raw bytes into smallest compatible numpy dtype
+            dt = f'{fmt}i4' if bytes_per_sample == 3 else f'{fmt}i8'
+            a = np.zeros((len(data) // bytes_per_sample, np.dtype(dt).itemsize),
+                            dtype='V1')
+            if is_big_endian:
+                a[:, :bytes_per_sample] = data.reshape((-1, bytes_per_sample))
+            else:
+                a[:, -bytes_per_sample:] = data.reshape((-1, bytes_per_sample))
+            data = a.view(dt).reshape(a.shape[:-1])
+    else:
+        if bytes_per_sample in {1, 2, 4, 8}:
+            start = fid.tell()
+            data = np.memmap(fid, dtype=dtype, mode='c', offset=start,
+                                shape=(n_samples,))
+            fid.seek(start + size)
+        else:
+            raise ValueError("mmap=True not compatible with "
+                             f"{bytes_per_sample}-byte container size.")
+
+    _handle_pad_byte(fid, size)
+
+    if channels > 1:
+        data = data.reshape(-1, channels)
+    return data
+
+
+def _skip_unknown_chunk(fid, is_big_endian):
+    if is_big_endian:
+        fmt = '>I'
+    else:
+        fmt = '>> from os.path import dirname, join as pjoin
+    >>> from scipy.io import wavfile
+    >>> import scipy.io
+
+    Get the filename for an example .wav file from the tests/data directory.
+
+    >>> data_dir = pjoin(dirname(scipy.io.__file__), 'tests', 'data')
+    >>> wav_fname = pjoin(data_dir, 'test-44100Hz-2ch-32bit-float-be.wav')
+
+    Load the .wav file contents.
+
+    >>> samplerate, data = wavfile.read(wav_fname)
+    >>> print(f"number of channels = {data.shape[1]}")
+    number of channels = 2
+    >>> length = data.shape[0] / samplerate
+    >>> print(f"length = {length}s")
+    length = 0.01s
+
+    Plot the waveform.
+
+    >>> import matplotlib.pyplot as plt
+    >>> import numpy as np
+    >>> time = np.linspace(0., length, data.shape[0])
+    >>> plt.plot(time, data[:, 0], label="Left channel")
+    >>> plt.plot(time, data[:, 1], label="Right channel")
+    >>> plt.legend()
+    >>> plt.xlabel("Time [s]")
+    >>> plt.ylabel("Amplitude")
+    >>> plt.show()
+
+    """
+    if hasattr(filename, 'read'):
+        fid = filename
+        mmap = False
+    else:
+        fid = open(filename, 'rb')
+    
+    if not (was_seekable := fid.seekable()):
+        fid = SeekEmulatingReader(fid)
+
+    try:
+        file_size, is_big_endian, is_rf64, rf64_chunk_size = _read_riff_chunk(fid)
+        fmt_chunk_received = False
+        data_chunk_received = False
+        while fid.tell() < file_size:
+            # read the next chunk
+            chunk_id = fid.read(4)
+
+            if not chunk_id:
+                if data_chunk_received:
+                    # End of file but data successfully read
+                    warnings.warn(
+                        f"Reached EOF prematurely; finished at {fid.tell():d} bytes, "
+                        f"expected {file_size:d} bytes from header.",
+                        WavFileWarning, stacklevel=2)
+                    break
+                else:
+                    raise ValueError("Unexpected end of file.")
+            elif len(chunk_id) < 4:
+                msg = f"Incomplete chunk ID: {repr(chunk_id)}"
+                # If we have the data, ignore the broken chunk
+                if fmt_chunk_received and data_chunk_received:
+                    warnings.warn(msg + ", ignoring it.", WavFileWarning,
+                                  stacklevel=2)
+                else:
+                    raise ValueError(msg)
+
+            if chunk_id == b'fmt ':
+                fmt_chunk_received = True
+                fmt_chunk = _read_fmt_chunk(fid, is_big_endian)
+                format_tag, channels, fs = fmt_chunk[1:4]
+                bit_depth = fmt_chunk[6]
+                block_align = fmt_chunk[5]
+            elif chunk_id == b'fact':
+                _skip_unknown_chunk(fid, is_big_endian)
+            elif chunk_id == b'data':
+                data_chunk_received = True
+                if not fmt_chunk_received:
+                    raise ValueError("No fmt chunk before data")
+                data = _read_data_chunk(fid, format_tag, channels, bit_depth,
+                                        is_big_endian, is_rf64, block_align,
+                                        mmap, rf64_chunk_size)
+            elif chunk_id == b'LIST':
+                # Someday this could be handled properly but for now skip it
+                _skip_unknown_chunk(fid, is_big_endian)
+            elif chunk_id in {b'JUNK', b'Fake'}:
+                # Skip alignment chunks without warning
+                _skip_unknown_chunk(fid, is_big_endian)
+            else:
+                warnings.warn("Chunk (non-data) not understood, skipping it.",
+                              WavFileWarning, stacklevel=2)
+                _skip_unknown_chunk(fid, is_big_endian)
+    finally:
+        if not hasattr(filename, 'read'):
+            fid.close()
+        elif was_seekable:
+            # Rewind, if we are able, so that caller can do something
+            # else with the raw WAV stream.
+            fid.seek(0)
+
+    return fs, data
+
+
+def write(filename, rate, data):
+    """
+    Write a NumPy array as a WAV file.
+
+    Parameters
+    ----------
+    filename : str or open file handle
+        Output wav file.
+    rate : int
+        The sample rate (in samples/sec).
+    data : ndarray
+        A 1-D or 2-D NumPy array of either integer or float data-type.
+
+    Notes
+    -----
+    * Writes a simple uncompressed WAV file.
+    * To write multiple-channels, use a 2-D array of shape
+      (Nsamples, Nchannels).
+    * The bits-per-sample and PCM/float will be determined by the data-type.
+
+    Common data types: [1]_
+
+    =====================  ===========  ===========  =============
+         WAV format            Min          Max       NumPy dtype
+    =====================  ===========  ===========  =============
+    32-bit floating-point  -1.0         +1.0         float32
+    32-bit PCM             -2147483648  +2147483647  int32
+    16-bit PCM             -32768       +32767       int16
+    8-bit PCM              0            255          uint8
+    =====================  ===========  ===========  =============
+
+    Note that 8-bit PCM is unsigned.
+
+    References
+    ----------
+    .. [1] IBM Corporation and Microsoft Corporation, "Multimedia Programming
+       Interface and Data Specifications 1.0", section "Data Format of the
+       Samples", August 1991
+       http://www.tactilemedia.com/info/MCI_Control_Info.html
+
+    Examples
+    --------
+    Create a 100Hz sine wave, sampled at 44100Hz.
+    Write to 16-bit PCM, Mono.
+
+    >>> from scipy.io.wavfile import write
+    >>> import numpy as np
+    >>> samplerate = 44100; fs = 100
+    >>> t = np.linspace(0., 1., samplerate)
+    >>> amplitude = np.iinfo(np.int16).max
+    >>> data = amplitude * np.sin(2. * np.pi * fs * t)
+    >>> write("example.wav", samplerate, data.astype(np.int16))
+
+    """
+    if hasattr(filename, 'write'):
+        fid = filename
+    else:
+        fid = open(filename, 'wb')
+
+    fs = rate
+
+    try:
+        dkind = data.dtype.kind
+        allowed_dtypes = ['float32', 'float64',
+                          'uint8', 'int16', 'int32', 'int64']
+        if data.dtype.name not in allowed_dtypes:
+            raise ValueError(f"Unsupported data type '{data.dtype}'")
+
+        header_data = b''
+
+        header_data += b'RIFF'
+        header_data += b'\x00\x00\x00\x00'
+        header_data += b'WAVE'
+
+        # fmt chunk
+        header_data += b'fmt '
+        if dkind == 'f':
+            format_tag = WAVE_FORMAT.IEEE_FLOAT
+        else:
+            format_tag = WAVE_FORMAT.PCM
+        if data.ndim == 1:
+            channels = 1
+        else:
+            channels = data.shape[1]
+        bit_depth = data.dtype.itemsize * 8
+        bytes_per_second = fs*(bit_depth // 8)*channels
+        block_align = channels * (bit_depth // 8)
+
+        fmt_chunk_data = struct.pack(' 0xFFFFFFFF
+        if is_rf64:
+            header_data = b''
+            header_data += b'RF64'
+            header_data += b'\xFF\xFF\xFF\xFF'
+            header_data += b'WAVE'
+            header_data += b'ds64'
+            # size of ds64 chunk
+            header_data += struct.pack('' or (data.dtype.byteorder == '=' and
+                                           sys.byteorder == 'big'):
+            data = data.byteswap()
+        _array_tofile(fid, data)
+
+        # Determine file size and place it in correct
+        # position at start of the file or the data chunk.
+        size = fid.tell()
+        if not is_rf64:
+            fid.seek(4)
+            fid.write(struct.pack('`__
+   for more linear algebra functions. Note that identically named
+   functions from `scipy.linalg` may offer more or slightly differing
+   functionality.
+
+
+Basics
+======
+
+.. autosummary::
+   :toctree: generated/
+
+   inv - Find the inverse of a square matrix
+   solve - Solve a linear system of equations
+   solve_banded - Solve a banded linear system
+   solveh_banded - Solve a Hermitian or symmetric banded system
+   solve_circulant - Solve a circulant system
+   solve_triangular - Solve a triangular matrix
+   solve_toeplitz - Solve a toeplitz matrix
+   matmul_toeplitz - Multiply a Toeplitz matrix with an array.
+   det - Find the determinant of a square matrix
+   norm - Matrix and vector norm
+   lstsq - Solve a linear least-squares problem
+   pinv - Pseudo-inverse (Moore-Penrose) using lstsq
+   pinvh - Pseudo-inverse of hermitian matrix
+   khatri_rao - Khatri-Rao product of two arrays
+   orthogonal_procrustes - Solve an orthogonal Procrustes problem
+   matrix_balance - Balance matrix entries with a similarity transformation
+   subspace_angles - Compute the subspace angles between two matrices
+   bandwidth - Return the lower and upper bandwidth of an array
+   issymmetric - Check if a square 2D array is symmetric
+   ishermitian - Check if a square 2D array is Hermitian
+   LinAlgError
+   LinAlgWarning
+
+Eigenvalue Problems
+===================
+
+.. autosummary::
+   :toctree: generated/
+
+   eig - Find the eigenvalues and eigenvectors of a square matrix
+   eigvals - Find just the eigenvalues of a square matrix
+   eigh - Find the e-vals and e-vectors of a Hermitian or symmetric matrix
+   eigvalsh - Find just the eigenvalues of a Hermitian or symmetric matrix
+   eig_banded - Find the eigenvalues and eigenvectors of a banded matrix
+   eigvals_banded - Find just the eigenvalues of a banded matrix
+   eigh_tridiagonal - Find the eigenvalues and eigenvectors of a tridiagonal matrix
+   eigvalsh_tridiagonal - Find just the eigenvalues of a tridiagonal matrix
+
+Decompositions
+==============
+
+.. autosummary::
+   :toctree: generated/
+
+   lu - LU decomposition of a matrix
+   lu_factor - LU decomposition returning unordered matrix and pivots
+   lu_solve - Solve Ax=b using back substitution with output of lu_factor
+   svd - Singular value decomposition of a matrix
+   svdvals - Singular values of a matrix
+   diagsvd - Construct matrix of singular values from output of svd
+   orth - Construct orthonormal basis for the range of A using svd
+   null_space - Construct orthonormal basis for the null space of A using svd
+   ldl - LDL.T decomposition of a Hermitian or a symmetric matrix.
+   cholesky - Cholesky decomposition of a matrix
+   cholesky_banded - Cholesky decomp. of a sym. or Hermitian banded matrix
+   cho_factor - Cholesky decomposition for use in solving a linear system
+   cho_solve - Solve previously factored linear system
+   cho_solve_banded - Solve previously factored banded linear system
+   polar - Compute the polar decomposition.
+   qr - QR decomposition of a matrix
+   qr_multiply - QR decomposition and multiplication by Q
+   qr_update - Rank k QR update
+   qr_delete - QR downdate on row or column deletion
+   qr_insert - QR update on row or column insertion
+   rq - RQ decomposition of a matrix
+   qz - QZ decomposition of a pair of matrices
+   ordqz - QZ decomposition of a pair of matrices with reordering
+   schur - Schur decomposition of a matrix
+   rsf2csf - Real to complex Schur form
+   hessenberg - Hessenberg form of a matrix
+   cdf2rdf - Complex diagonal form to real diagonal block form
+   cossin - Cosine sine decomposition of a unitary or orthogonal matrix
+
+.. seealso::
+
+   `scipy.linalg.interpolative` -- Interpolative matrix decompositions
+
+
+Matrix Functions
+================
+
+.. autosummary::
+   :toctree: generated/
+
+   expm - Matrix exponential
+   logm - Matrix logarithm
+   cosm - Matrix cosine
+   sinm - Matrix sine
+   tanm - Matrix tangent
+   coshm - Matrix hyperbolic cosine
+   sinhm - Matrix hyperbolic sine
+   tanhm - Matrix hyperbolic tangent
+   signm - Matrix sign
+   sqrtm - Matrix square root
+   funm - Evaluating an arbitrary matrix function
+   expm_frechet - Frechet derivative of the matrix exponential
+   expm_cond - Relative condition number of expm in the Frobenius norm
+   fractional_matrix_power - Fractional matrix power
+
+
+Matrix Equation Solvers
+=======================
+
+.. autosummary::
+   :toctree: generated/
+
+   solve_sylvester - Solve the Sylvester matrix equation
+   solve_continuous_are - Solve the continuous-time algebraic Riccati equation
+   solve_discrete_are - Solve the discrete-time algebraic Riccati equation
+   solve_continuous_lyapunov - Solve the continuous-time Lyapunov equation
+   solve_discrete_lyapunov - Solve the discrete-time Lyapunov equation
+
+
+Sketches and Random Projections
+===============================
+
+.. autosummary::
+   :toctree: generated/
+
+   clarkson_woodruff_transform - Applies the Clarkson Woodruff Sketch (a.k.a CountMin Sketch)
+
+Special Matrices
+================
+
+.. autosummary::
+   :toctree: generated/
+
+   block_diag - Construct a block diagonal matrix from submatrices
+   circulant - Circulant matrix
+   companion - Companion matrix
+   convolution_matrix - Convolution matrix
+   dft - Discrete Fourier transform matrix
+   fiedler - Fiedler matrix
+   fiedler_companion - Fiedler companion matrix
+   hadamard - Hadamard matrix of order 2**n
+   hankel - Hankel matrix
+   helmert - Helmert matrix
+   hilbert - Hilbert matrix
+   invhilbert - Inverse Hilbert matrix
+   leslie - Leslie matrix
+   pascal - Pascal matrix
+   invpascal - Inverse Pascal matrix
+   toeplitz - Toeplitz matrix
+
+Low-level routines
+==================
+
+.. autosummary::
+   :toctree: generated/
+
+   get_blas_funcs
+   get_lapack_funcs
+   find_best_blas_type
+
+.. seealso::
+
+   `scipy.linalg.blas` -- Low-level BLAS functions
+
+   `scipy.linalg.lapack` -- Low-level LAPACK functions
+
+   `scipy.linalg.cython_blas` -- Low-level BLAS functions for Cython
+
+   `scipy.linalg.cython_lapack` -- Low-level LAPACK functions for Cython
+
+"""  # noqa: E501
+
+from ._misc import *
+from ._cythonized_array_utils import *
+from ._basic import *
+from ._decomp import *
+from ._decomp_lu import *
+from ._decomp_ldl import *
+from ._decomp_cholesky import *
+from ._decomp_qr import *
+from ._decomp_qz import *
+from ._decomp_svd import *
+from ._decomp_schur import *
+from ._decomp_polar import *
+from ._matfuncs import *
+from .blas import *
+from .lapack import *
+from ._special_matrices import *
+from ._solvers import *
+from ._procrustes import *
+from ._decomp_update import *
+from ._sketches import *
+from ._decomp_cossin import *
+
+# Deprecated namespaces, to be removed in v2.0.0
+from . import (
+    decomp, decomp_cholesky, decomp_lu, decomp_qr, decomp_svd, decomp_schur,
+    basic, misc, special_matrices, matfuncs,
+)
+
+__all__ = [s for s in dir() if not s.startswith('_')]
+
+
+from scipy._lib._testutils import PytestTester
+test = PytestTester(__name__)
+del PytestTester
diff --git a/.venv/lib/python3.12/site-packages/scipy/linalg/__pycache__/__init__.cpython-312.pyc b/.venv/lib/python3.12/site-packages/scipy/linalg/__pycache__/__init__.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..3a1651aef36e3ed33b30de50904c46e27997e7b4
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/scipy/linalg/__pycache__/__init__.cpython-312.pyc differ
diff --git a/.venv/lib/python3.12/site-packages/scipy/linalg/__pycache__/_basic.cpython-312.pyc b/.venv/lib/python3.12/site-packages/scipy/linalg/__pycache__/_basic.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..0e3064c175c5cc755111f5909822b2494d611f6a
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/scipy/linalg/__pycache__/_basic.cpython-312.pyc differ
diff --git a/.venv/lib/python3.12/site-packages/scipy/linalg/__pycache__/_decomp.cpython-312.pyc b/.venv/lib/python3.12/site-packages/scipy/linalg/__pycache__/_decomp.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..8a63b862437bf9fc83f16999eea3ad87bb02b390
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/scipy/linalg/__pycache__/_decomp.cpython-312.pyc differ
diff --git a/.venv/lib/python3.12/site-packages/scipy/linalg/__pycache__/_decomp_cholesky.cpython-312.pyc b/.venv/lib/python3.12/site-packages/scipy/linalg/__pycache__/_decomp_cholesky.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..ca44e5a9a32d2fa92ff15a09ce365be5b351bbae
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/scipy/linalg/__pycache__/_decomp_cholesky.cpython-312.pyc differ
diff --git a/.venv/lib/python3.12/site-packages/scipy/linalg/__pycache__/_decomp_cossin.cpython-312.pyc b/.venv/lib/python3.12/site-packages/scipy/linalg/__pycache__/_decomp_cossin.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..09ee7c8f193f503d1d8161648b02c25b75010cf8
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/scipy/linalg/__pycache__/_decomp_cossin.cpython-312.pyc differ
diff --git a/.venv/lib/python3.12/site-packages/scipy/linalg/__pycache__/_decomp_ldl.cpython-312.pyc b/.venv/lib/python3.12/site-packages/scipy/linalg/__pycache__/_decomp_ldl.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..80904669d4fc7749085fa997067df10b7c0a647b
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/scipy/linalg/__pycache__/_decomp_ldl.cpython-312.pyc differ
diff --git a/.venv/lib/python3.12/site-packages/scipy/linalg/__pycache__/_decomp_lu.cpython-312.pyc b/.venv/lib/python3.12/site-packages/scipy/linalg/__pycache__/_decomp_lu.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..a0f138ec445e1f1284b0fdcec2b152ec3d23a12a
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/scipy/linalg/__pycache__/_decomp_lu.cpython-312.pyc differ
diff --git a/.venv/lib/python3.12/site-packages/scipy/linalg/__pycache__/_decomp_polar.cpython-312.pyc b/.venv/lib/python3.12/site-packages/scipy/linalg/__pycache__/_decomp_polar.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..d9517a851a7739d6c19215eced55f0c9fe4ae533
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/scipy/linalg/__pycache__/_decomp_polar.cpython-312.pyc differ
diff --git a/.venv/lib/python3.12/site-packages/scipy/linalg/__pycache__/_decomp_qr.cpython-312.pyc b/.venv/lib/python3.12/site-packages/scipy/linalg/__pycache__/_decomp_qr.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..41dc9cf142e1a4a5c95f4081e50e6670bcdfc0be
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/scipy/linalg/__pycache__/_decomp_qr.cpython-312.pyc differ
diff --git a/.venv/lib/python3.12/site-packages/scipy/linalg/__pycache__/_decomp_qz.cpython-312.pyc b/.venv/lib/python3.12/site-packages/scipy/linalg/__pycache__/_decomp_qz.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..66aedc75dce24d69452a055624a825bfe71cea23
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/scipy/linalg/__pycache__/_decomp_qz.cpython-312.pyc differ
diff --git a/.venv/lib/python3.12/site-packages/scipy/linalg/__pycache__/_decomp_schur.cpython-312.pyc b/.venv/lib/python3.12/site-packages/scipy/linalg/__pycache__/_decomp_schur.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..3b1927bab96f44d0d55297a12880d527a04740dc
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/scipy/linalg/__pycache__/_decomp_schur.cpython-312.pyc differ
diff --git a/.venv/lib/python3.12/site-packages/scipy/linalg/__pycache__/_decomp_svd.cpython-312.pyc b/.venv/lib/python3.12/site-packages/scipy/linalg/__pycache__/_decomp_svd.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..538d22e3337e3ae7b22eb703ceeacb036d2b1e48
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/scipy/linalg/__pycache__/_decomp_svd.cpython-312.pyc differ
diff --git a/.venv/lib/python3.12/site-packages/scipy/linalg/__pycache__/_expm_frechet.cpython-312.pyc b/.venv/lib/python3.12/site-packages/scipy/linalg/__pycache__/_expm_frechet.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..9bc9fa4c1bb377f5e1cb64444b90343ec976cd25
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/scipy/linalg/__pycache__/_expm_frechet.cpython-312.pyc differ
diff --git a/.venv/lib/python3.12/site-packages/scipy/linalg/__pycache__/_matfuncs.cpython-312.pyc b/.venv/lib/python3.12/site-packages/scipy/linalg/__pycache__/_matfuncs.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..4695872bec29da1cdeebbcc378ec7f7320f18207
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/scipy/linalg/__pycache__/_matfuncs.cpython-312.pyc differ
diff --git a/.venv/lib/python3.12/site-packages/scipy/linalg/__pycache__/_misc.cpython-312.pyc b/.venv/lib/python3.12/site-packages/scipy/linalg/__pycache__/_misc.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..6430dea7115e62d7a025f1a4a2a7274ad756453d
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/scipy/linalg/__pycache__/_misc.cpython-312.pyc differ
diff --git a/.venv/lib/python3.12/site-packages/scipy/linalg/__pycache__/_procrustes.cpython-312.pyc b/.venv/lib/python3.12/site-packages/scipy/linalg/__pycache__/_procrustes.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..9c8fe254a07e5a1ab7d4911a93c0cc7956326413
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/scipy/linalg/__pycache__/_procrustes.cpython-312.pyc differ
diff --git a/.venv/lib/python3.12/site-packages/scipy/linalg/__pycache__/_sketches.cpython-312.pyc b/.venv/lib/python3.12/site-packages/scipy/linalg/__pycache__/_sketches.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..a9d53390e78e33be2fe06ec572ba2a744cbf250e
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/scipy/linalg/__pycache__/_sketches.cpython-312.pyc differ
diff --git a/.venv/lib/python3.12/site-packages/scipy/linalg/__pycache__/_solvers.cpython-312.pyc b/.venv/lib/python3.12/site-packages/scipy/linalg/__pycache__/_solvers.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..cd4c41bd1168994d7374b5e50944b15bdcaf2017
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/scipy/linalg/__pycache__/_solvers.cpython-312.pyc differ
diff --git a/.venv/lib/python3.12/site-packages/scipy/linalg/__pycache__/_special_matrices.cpython-312.pyc b/.venv/lib/python3.12/site-packages/scipy/linalg/__pycache__/_special_matrices.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..fbb26a08b1bf4c9db909dca68ce227c5c03c86a2
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/scipy/linalg/__pycache__/_special_matrices.cpython-312.pyc differ
diff --git a/.venv/lib/python3.12/site-packages/scipy/linalg/__pycache__/basic.cpython-312.pyc b/.venv/lib/python3.12/site-packages/scipy/linalg/__pycache__/basic.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..f2e1d5aeb47bacb439a1ea4751155fe84ad8d332
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/scipy/linalg/__pycache__/basic.cpython-312.pyc differ
diff --git a/.venv/lib/python3.12/site-packages/scipy/linalg/__pycache__/blas.cpython-312.pyc b/.venv/lib/python3.12/site-packages/scipy/linalg/__pycache__/blas.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..a98722953014082fa9105e4a53ca5c6398061e7a
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/scipy/linalg/__pycache__/blas.cpython-312.pyc differ
diff --git a/.venv/lib/python3.12/site-packages/scipy/linalg/__pycache__/decomp.cpython-312.pyc b/.venv/lib/python3.12/site-packages/scipy/linalg/__pycache__/decomp.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..815d322d49d4274556b46e153c6de7a712ec4b48
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/scipy/linalg/__pycache__/decomp.cpython-312.pyc differ
diff --git a/.venv/lib/python3.12/site-packages/scipy/linalg/__pycache__/decomp_cholesky.cpython-312.pyc b/.venv/lib/python3.12/site-packages/scipy/linalg/__pycache__/decomp_cholesky.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..4b315e73e0ebd650bc78bf6d66c649ae1849e7fa
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/scipy/linalg/__pycache__/decomp_cholesky.cpython-312.pyc differ
diff --git a/.venv/lib/python3.12/site-packages/scipy/linalg/__pycache__/decomp_lu.cpython-312.pyc b/.venv/lib/python3.12/site-packages/scipy/linalg/__pycache__/decomp_lu.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..42a64965a426bde5f7b84e6f7e3a2b88b552d2f7
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/scipy/linalg/__pycache__/decomp_lu.cpython-312.pyc differ
diff --git a/.venv/lib/python3.12/site-packages/scipy/linalg/__pycache__/decomp_qr.cpython-312.pyc b/.venv/lib/python3.12/site-packages/scipy/linalg/__pycache__/decomp_qr.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..4ee769d38d5582e24aa591105a340c8f3a5b224b
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/scipy/linalg/__pycache__/decomp_qr.cpython-312.pyc differ
diff --git a/.venv/lib/python3.12/site-packages/scipy/linalg/__pycache__/decomp_schur.cpython-312.pyc b/.venv/lib/python3.12/site-packages/scipy/linalg/__pycache__/decomp_schur.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..3a16b0d0bd5ca4577263fa4fe8d2a598deb4c45d
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/scipy/linalg/__pycache__/decomp_schur.cpython-312.pyc differ
diff --git a/.venv/lib/python3.12/site-packages/scipy/linalg/__pycache__/decomp_svd.cpython-312.pyc b/.venv/lib/python3.12/site-packages/scipy/linalg/__pycache__/decomp_svd.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..e539ca638595970aaeaabf99e521d409563339ff
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/scipy/linalg/__pycache__/decomp_svd.cpython-312.pyc differ
diff --git a/.venv/lib/python3.12/site-packages/scipy/linalg/__pycache__/lapack.cpython-312.pyc b/.venv/lib/python3.12/site-packages/scipy/linalg/__pycache__/lapack.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..72e361ead6678d06b668c6b2340bbc53d56fa8f4
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/scipy/linalg/__pycache__/lapack.cpython-312.pyc differ
diff --git a/.venv/lib/python3.12/site-packages/scipy/linalg/__pycache__/matfuncs.cpython-312.pyc b/.venv/lib/python3.12/site-packages/scipy/linalg/__pycache__/matfuncs.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..451cf8acfbd0606a3fff9510e68c7c68acc2f700
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/scipy/linalg/__pycache__/matfuncs.cpython-312.pyc differ
diff --git a/.venv/lib/python3.12/site-packages/scipy/linalg/__pycache__/misc.cpython-312.pyc b/.venv/lib/python3.12/site-packages/scipy/linalg/__pycache__/misc.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..3abbbf876eb37bac8fb8d1fc35a199dbf4993a4a
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/scipy/linalg/__pycache__/misc.cpython-312.pyc differ
diff --git a/.venv/lib/python3.12/site-packages/scipy/linalg/__pycache__/special_matrices.cpython-312.pyc b/.venv/lib/python3.12/site-packages/scipy/linalg/__pycache__/special_matrices.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..d1013e94daa5a5af44380ceadf239ad5cf70379b
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/scipy/linalg/__pycache__/special_matrices.cpython-312.pyc differ
diff --git a/.venv/lib/python3.12/site-packages/scipy/linalg/_basic.py b/.venv/lib/python3.12/site-packages/scipy/linalg/_basic.py
new file mode 100644
index 0000000000000000000000000000000000000000..1be7b237445f0c3f1bcbd8f7a9993e8fa6bf7d54
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/linalg/_basic.py
@@ -0,0 +1,2097 @@
+#
+# Author: Pearu Peterson, March 2002
+#
+# w/ additions by Travis Oliphant, March 2002
+#              and Jake Vanderplas, August 2012
+
+import warnings
+import numpy as np
+from scipy._lib._util import _apply_over_batch, _deprecate_dtypes
+from .lapack import (
+    get_lapack_funcs, _normalize_lapack_dtype, _normalize_lapack_dtype1,
+    _ensure_aligned_and_native, _ensure_dtype_cdsz,
+)
+from ._misc import LinAlgError, _datacopied, LinAlgWarning
+from ._decomp import _asarray_validated
+from . import _decomp, _decomp_svd
+from ._solve_toeplitz import levinson
+from ._batched_linalg import _det as _linalg_det
+from . import _batched_linalg
+
+__all__ = ['solve', 'solve_triangular', 'solveh_banded', 'solve_banded',
+           'solve_toeplitz', 'solve_circulant', 'inv', 'det', 'lstsq',
+           'pinv', 'pinvh', 'matrix_balance', 'matmul_toeplitz']
+
+
+# Linear equations
+def _format_emit_errors_warnings(err_lst):
+    """Format/emit errors/warnings from a lowlevel batched routine.
+
+    See inv, solve.
+    """
+    singular, lapack_err, ill_cond = [], [], []
+    for i, dct in enumerate(err_lst):
+        if dct["is_singular"]:
+            singular.append(i)
+        if dct["lapack_info"] < 0:
+            lapack_err.append(f"slice {i} emits lapack info={dct['lapack_info']}")
+        if dct["is_ill_conditioned"]:
+            ill_cond.append(f"slice {i} has rcond = {dct['rcond']}")
+
+    if singular:
+        raise LinAlgError(
+            f"A singular matrix detected: slice(s) {singular} are singular."
+        )
+
+    if lapack_err:
+        raise ValueError(f"Internal LAPACK errors: {','.join(lapack_err)}.")
+
+    if ill_cond:
+       warnings.warn(
+            f"An ill-conditioned matrix detected: {','.join(ill_cond)}.",
+            LinAlgWarning,
+            stacklevel=3
+        )
+
+
+def solve(a, b, lower=False, overwrite_a=False,
+          overwrite_b=False, check_finite=True, assume_a=None,
+          transposed=False):
+    """
+    Solve the equation ``a @ x = b`` for  ``x``,
+    where `a` is a square matrix.
+
+    If the data matrix is known to be a particular type then supplying the
+    corresponding string to ``assume_a`` key chooses the dedicated solver.
+    The available options are
+
+    =============================  ================================
+     diagonal                       'diagonal'
+     tridiagonal                    'tridiagonal'
+     banded                         'banded'
+     upper triangular               'upper triangular'
+     lower triangular               'lower triangular'
+     symmetric                      'symmetric' (or 'sym')
+     hermitian                      'hermitian' (or 'her')
+     symmetric positive definite    'positive definite' (or 'pos')
+     general                        'general' (or 'gen')
+    =============================  ================================
+
+    Array argument(s) of this function may have additional
+    "batch" dimensions prepended to the core shape. In this case, the array is treated
+    as a batch of lower-dimensional slices; see :ref:`linalg_batch` for details.
+
+    Parameters
+    ----------
+    a : array_like, shape (..., N, N)
+        Square left-hand side matrix or a batch of matrices.
+    b : (..., N, NRHS) array_like
+        Input data for the right hand side or a batch of right-hand sides.
+    lower : bool, default: False
+        Ignored unless ``assume_a`` is one of ``'sym'``, ``'her'``, or ``'pos'``.
+        If True, the calculation uses only the data in the lower triangle of `a`;
+        entries above the diagonal are ignored. If False (default), the
+        calculation uses only the data in the upper triangle of `a`; entries
+        below the diagonal are ignored.
+    overwrite_a : bool, optional
+        Allow overwriting data in `a` (may enhance performance). Default is False.
+        See :ref:`tutorial_linalg_overwrite` for details.
+    overwrite_b : bool, optional
+        Allow overwriting data in `b` (may enhance performance). Default is False.
+        See :ref:`tutorial_linalg_overwrite` for details.
+    check_finite : bool, default: True
+        Whether to check that the input matrices contain only finite numbers.
+        Disabling may give a performance gain, but may result in problems
+        (crashes, non-termination) if the inputs do contain infinities or NaNs.
+    assume_a : str, optional
+        Valid entries are described above.
+        If omitted or ``None``, checks are performed to identify structure so the
+        appropriate solver can be called.
+    transposed : bool, default: False
+        If True, solve ``a.T @ x == b``. Raises `NotImplementedError`
+        for complex `a`.
+
+    Returns
+    -------
+    x : ndarray, shape (N, NRHS) or (..., N)
+        The solution array.
+
+    Raises
+    ------
+    ValueError
+        If size mismatches detected or input a is not square.
+    LinAlgError
+        If the computation fails because of matrix singularity.
+    LinAlgWarning
+        If an ill-conditioned input a is detected.
+    NotImplementedError
+        If transposed is True and input a is a complex matrix.
+
+    Notes
+    -----
+    If the input b matrix is a 1-D array with N elements, when supplied
+    together with an NxN input a, it is assumed as a valid column vector
+    despite the apparent size mismatch. This is compatible with the
+    numpy.dot() behavior and the returned result is still 1-D array.
+
+    The general, symmetric, Hermitian and positive definite solutions are
+    obtained via calling ?GETRF/?GETRS, ?SYSV, ?HESV, and ?POTRF/?POTRS routines of
+    LAPACK respectively.
+
+    The datatype of the arrays define which solver is called regardless
+    of the values. In other words, even when the complex array entries have
+    precisely zero imaginary parts, the complex solver will be called based
+    on the data type of the array.
+
+    Examples
+    --------
+    Given `a` and `b`, solve for `x`:
+
+    >>> import numpy as np
+    >>> a = np.array([[3, 2, 0], [1, -1, 0], [0, 5, 1]])
+    >>> b = np.array([2, 4, -1])
+    >>> from scipy.linalg import solve
+    >>> x = solve(a, b)
+    >>> x
+    array([ 2., -2.,  9.])
+    >>> a @ x == b
+    array([ True,  True,  True], dtype=bool)
+
+    Batches of matrices are supported, with and without structure detection:
+    (See :ref:`linalg_batch` for further details of handling batched inputs.)
+
+    >>> a = np.arange(12).reshape(3, 2, 2)   # a batch of 3 2x2 matrices
+    >>> A = a.transpose(0, 2, 1) @ a    # A is a batch of 3 positive definite matrices
+    >>> b = np.ones(2)
+    >>> solve(A, b)      # this automatically detects that A is pos.def.
+    array([[ 1. , -0.5],
+           [ 3. , -2.5],
+           [ 5. , -4.5]])
+    >>> solve(A, b, assume_a='pos')   # bypass structucture detection
+    array([[ 1. , -0.5],
+           [ 3. , -2.5],
+           [ 5. , -4.5]])
+
+    Note that the structure detection runs per-slice: in the example above, each of the
+    two slices will be independently discovered as being positive definite. Setting an
+    explicit ``assume_a`` argument bypasses structure detection and uses the provided
+    value without checking:
+
+    >>> a = np.stack((np.eye(2), np.arange(1, 5).reshape(2, 2)))
+    >>> b = [1, 1]
+    >>> solve(a, b, assume_a="diagonal")
+    array([[1.  , 1.  ],
+           [1.  , 0.25]])   # the second row is incorrect
+    """
+    # keep the numbers in sync with C
+    structure = {
+        None: -1,
+        'general': 0, 'gen': 0,
+        'diagonal': 11,
+        'tridiagonal': 31,
+        'banded': 41,
+        'upper triangular': 21,
+        'lower triangular': 22,
+        'pos' : 101, 'positive definite': 101,
+        'sym' : 201, 'symmetric': 201,
+        'her' : 211, 'hermitian': 211,
+    }.get(assume_a, 'unknown')
+    if structure == 'unknown':
+        raise ValueError(f'{assume_a} is not a recognized matrix structure')
+
+    a1 = np.atleast_2d(_asarray_validated(a, check_finite=check_finite))
+    b1 = np.atleast_1d(_asarray_validated(b, check_finite=check_finite))
+    _deprecate_dtypes("linalg.solve", a1, b1)
+
+    a1, b1 = _ensure_dtype_cdsz(a1, b1)   # XXX; b upcasts a?
+    a1, overwrite_a = _normalize_lapack_dtype(a1, overwrite_a)
+    a1, overwrite_a = _ensure_aligned_and_native(a1, overwrite_a)
+    b1, overwrite_b = _ensure_aligned_and_native(b1, overwrite_b)
+
+    if a1.ndim < 2:
+        raise ValueError(f"Expected at least ndim=2, got {a1.ndim=}")
+    if a1.shape[-1] != a1.shape[-2]:
+        raise ValueError(f"Expected square matrix, got {a1.shape=}")
+
+    # backwards compatibility
+    if np.issubdtype(a1.dtype, np.complexfloating) and transposed:
+        raise NotImplementedError('scipy.linalg.solve can currently '
+                                  'not solve a^T x = b or a^H x = b '
+                                  'for complex matrices.')
+
+    # align the shape of b with a: 1. make b1 at least 2D
+    b_is_1D = b1.ndim == 1
+    if b_is_1D:
+        b1 = b1[:, None]
+
+    a_is_scalar = a1.size == 1
+
+    if b1.shape[-2] != a1.shape[-1] and not a_is_scalar:
+        raise ValueError(f"incompatible shapes: {a1.shape=} and {b1.shape=}")
+
+    # 2. broadcast the batch dimensions of b1 and a1
+    batch_shape = np.broadcast_shapes(a1.shape[:-2], b1.shape[:-2])
+    a1 = np.broadcast_to(a1, batch_shape + a1.shape[-2:])
+    b1 = np.broadcast_to(b1, batch_shape + b1.shape[-2:])
+
+    # catch empty inputs
+    if a1.size == 0 or b1.size == 0:
+        x = np.empty_like(b1)
+        if b_is_1D:
+            x = x[..., 0]
+        return x
+
+    if a_is_scalar:
+        if a1.item() == 0:
+            raise LinAlgError("A singular matrix detected.")
+
+        out = b1 / a1
+        return out[..., 0] if b_is_1D else out
+
+    # XXX a1.ndim > 2 ; b1.ndim > 2
+    # XXX can do something if a1 C ordered & transposed==True ?
+    overwrite_a = overwrite_a and (a1.ndim == 2) and (a1.flags["F_CONTIGUOUS"])
+    overwrite_b = overwrite_b and (b1.ndim <= 2) and (b1.flags["F_CONTIGUOUS"])
+
+    # heavy lifting
+    x, err_lst = _batched_linalg._solve(
+        a1, b1, structure, lower, transposed, overwrite_a, overwrite_b
+    )
+
+    if err_lst:
+        _format_emit_errors_warnings(err_lst)
+
+    if b_is_1D:
+        x = x[..., 0]
+    return x
+
+
+def _to_banded(n_below, n_above, a):
+    n = a.shape[0]
+    rows = n_above + n_below + 1
+    ab = np.zeros((rows, n), dtype=a.dtype)
+    ab[n_above] = np.diag(a)
+    for i in range(1, n_above + 1):
+        ab[n_above - i, i:] = np.diag(a, i)
+    for i in range(1, n_below + 1):
+        ab[n_above + i, :-i] = np.diag(a, -i)
+    return ab
+
+
+@_apply_over_batch(('a', 2), ('b', '1|2'))
+def solve_triangular(a, b, trans=0, lower=False, unit_diagonal=False,
+                     overwrite_b=False, check_finite=True):
+    """
+    Solve the equation ``a @ x = b`` for ``x``, where `a` is a triangular matrix.
+
+    Parameters
+    ----------
+    a : (M, M) array_like
+        A triangular matrix
+    b : (M,) or (M, N) array_like
+        Right-hand side matrix in ``a x = b``
+    trans : {0, 1, 2, 'N', 'T', 'C'}, optional
+        Type of system to solve:
+
+        ========  =========
+        trans     system
+        ========  =========
+        0 or 'N'  a x  = b
+        1 or 'T'  a^T x = b
+        2 or 'C'  a^H x = b
+        ========  =========
+    lower : bool, optional
+        Use only data contained in the lower triangle of `a`.
+        Default is to use upper triangle.
+    unit_diagonal : bool, optional
+        If True, diagonal elements of `a` are assumed to be 1 and
+        will not be referenced.
+    overwrite_b : bool, optional
+        Allow overwriting data in `b` (may enhance performance)
+        See :ref:`tutorial_linalg_overwrite` for details.
+    check_finite : bool, optional
+        Whether to check that the input matrices contain only finite numbers.
+        Disabling may give a performance gain, but may result in problems
+        (crashes, non-termination) if the inputs do contain infinities or NaNs.
+
+    Returns
+    -------
+    x : (M,) or (M, N) ndarray
+        Solution to the system ``a x = b``.  Shape of return matches `b`.
+
+    Raises
+    ------
+    LinAlgError
+        If `a` is singular
+
+    Notes
+    -----
+    .. versionadded:: 0.9.0
+
+    Examples
+    --------
+    Solve the lower triangular system a x = b, where::
+
+             [3  0  0  0]       [4]
+        a =  [2  1  0  0]   b = [2]
+             [1  0  1  0]       [4]
+             [1  1  1  1]       [2]
+
+    >>> import numpy as np
+    >>> from scipy.linalg import solve_triangular
+    >>> a = np.array([[3, 0, 0, 0], [2, 1, 0, 0], [1, 0, 1, 0], [1, 1, 1, 1]])
+    >>> b = np.array([4, 2, 4, 2])
+    >>> x = solve_triangular(a, b, lower=True)
+    >>> x
+    array([ 1.33333333, -0.66666667,  2.66666667, -1.33333333])
+    >>> a.dot(x)  # Check the result
+    array([ 4.,  2.,  4.,  2.])
+
+    """
+
+    a1 = _asarray_validated(a, check_finite=check_finite)
+    b1 = _asarray_validated(b, check_finite=check_finite)
+
+    if len(a1.shape) != 2 or a1.shape[0] != a1.shape[1]:
+        raise ValueError('expected square matrix')
+
+    if a1.shape[0] != b1.shape[0]:
+        raise ValueError(f'shapes of a {a1.shape} and b {b1.shape} are incompatible')
+
+    # accommodate empty arrays
+    if b1.size == 0:
+        dt_nonempty = solve_triangular(
+            np.eye(2, dtype=a1.dtype), np.ones(2, dtype=b1.dtype)
+        ).dtype
+        return np.empty_like(b1, dtype=dt_nonempty)
+
+    overwrite_b = overwrite_b or _datacopied(b1, b)
+
+    x, _ = _solve_triangular(a1, b1, trans, lower, unit_diagonal, overwrite_b)
+    return x
+
+
+# solve_triangular without the input validation
+def _solve_triangular(a1, b1, trans=0, lower=False, unit_diagonal=False,
+                      overwrite_b=False):
+
+    trans = {'N': 0, 'T': 1, 'C': 2}.get(trans, trans)
+    trtrs, = get_lapack_funcs(('trtrs',), (a1, b1))
+    if a1.flags.f_contiguous or trans == 2:
+        x, info = trtrs(a1, b1, overwrite_b=overwrite_b, lower=lower,
+                        trans=trans, unitdiag=unit_diagonal)
+    else:
+        # transposed system is solved since trtrs expects Fortran ordering
+        x, info = trtrs(a1.T, b1, overwrite_b=overwrite_b, lower=not lower,
+                        trans=not trans, unitdiag=unit_diagonal)
+
+    if info == 0:
+        return x, info
+    if info > 0:
+        raise LinAlgError(f"singular matrix: resolution failed at diagonal {info-1}")
+    raise ValueError(f'illegal value in {-info}-th argument of internal trtrs')
+
+
+def solve_banded(l_and_u, ab, b, overwrite_ab=False, overwrite_b=False,
+                 check_finite=True):
+    """
+    Solve the equation ``a @ x = b`` for ``x``, where ``a`` is the banded matrix
+    defined by `ab`.
+
+    The matrix a is stored in `ab` using the matrix diagonal ordered form::
+
+        ab[u + i - j, j] == a[i,j]
+
+    Example of `ab` (shape of a is (6,6), `u` =1, `l` =2)::
+
+        *    a01  a12  a23  a34  a45
+        a00  a11  a22  a33  a44  a55
+        a10  a21  a32  a43  a54   *
+        a20  a31  a42  a53   *    *
+
+    The documentation is written assuming array arguments are of specified
+    "core" shapes. However, array argument(s) of this function may have additional
+    "batch" dimensions prepended to the core shape. In this case, the array is treated
+    as a batch of lower-dimensional slices; see :ref:`linalg_batch` for details.
+
+    Parameters
+    ----------
+    l_and_u : tuple of int
+        Number of non-zero lower and upper diagonals given as ``(l, u)``.
+    ab : (`l` + `u` + 1, M) array_like
+        Banded matrix
+    b : (M,) or (M, K) array_like
+        Right-hand side
+    overwrite_ab : bool, optional
+        Discard data in `ab` (may enhance performance)
+        See :ref:`tutorial_linalg_overwrite` for details.
+    overwrite_b : bool, optional
+        Discard data in `b` (may enhance performance)
+        See :ref:`tutorial_linalg_overwrite` for details.
+    check_finite : bool, optional
+        Whether to check that the input matrices contain only finite numbers.
+        Disabling may give a performance gain, but may result in problems
+        (crashes, non-termination) if the inputs do contain infinities or NaNs.
+
+    Returns
+    -------
+    x : (M,) or (M, K) ndarray
+        The solution to the system a x = b. Returned shape depends on the
+        shape of `b`.
+
+    Examples
+    --------
+    Solve the banded system a x = b, where::
+
+            [5  2 -1  0  0]       [0]
+            [1  4  2 -1  0]       [1]
+        a = [0  1  3  2 -1]   b = [2]
+            [0  0  1  2  2]       [2]
+            [0  0  0  1  1]       [3]
+
+    There is one nonzero diagonal below the main diagonal (l = 1), and
+    two above (u = 2). The diagonal banded form of the matrix is::
+
+             [*  * -1 -1 -1]
+        ab = [*  2  2  2  2]
+             [5  4  3  2  1]
+             [1  1  1  1  *]
+
+    >>> import numpy as np
+    >>> from scipy.linalg import solve_banded
+    >>> ab = np.array([[0,  0, -1, -1, -1],
+    ...                [0,  2,  2,  2,  2],
+    ...                [5,  4,  3,  2,  1],
+    ...                [1,  1,  1,  1,  0]])
+    >>> b = np.array([0, 1, 2, 2, 3])
+    >>> x = solve_banded((1, 2), ab, b)
+    >>> x
+    array([-2.37288136,  3.93220339, -4.        ,  4.3559322 , -1.3559322 ])
+
+    """
+    (nlower, nupper) = l_and_u
+    return _solve_banded(nlower, nupper, ab, b, overwrite_ab=overwrite_ab,
+                         overwrite_b=overwrite_b, check_finite=check_finite)
+
+
+@_apply_over_batch(('nlower', 0), ('nupper', 0), ('ab', 2), ('b', '1|2'))
+def _solve_banded(nlower, nupper, ab, b, overwrite_ab, overwrite_b, check_finite):
+    a1 = _asarray_validated(ab, check_finite=check_finite, as_inexact=True)
+    b1 = _asarray_validated(b, check_finite=check_finite, as_inexact=True)
+
+    # Validate shapes.
+    if a1.shape[-1] != b1.shape[0]:
+        raise ValueError("shapes of ab and b are not compatible.")
+
+    if nlower + nupper + 1 != a1.shape[0]:
+        raise ValueError(
+            f"invalid values for the number of lower and upper diagonals: l+u+1 "
+            f"({nlower + nupper + 1}) does not equal ab.shape[0] ({ab.shape[0]})"
+        )
+
+    # accommodate empty arrays
+    if b1.size == 0:
+        dt = solve(np.eye(1, dtype=a1.dtype), np.ones(1, dtype=b1.dtype)).dtype
+        return np.empty_like(b1, dtype=dt)
+
+    overwrite_b = overwrite_b or _datacopied(b1, b)
+    if a1.shape[-1] == 1:
+        b2 = np.array(b1, copy=(not overwrite_b))
+        # a1.shape[-1] == 1 -> original matrix is 1x1. Typically, the user
+        # will pass u = l = 0 and `a1` will be 1x1. However, the rest of the
+        # function works with unnecessary rows in `a1` as long as
+        # `a1[u + i - j, j] == a[i,j]`. In the 1x1 case, we want i = j = 0,
+        # so the diagonal is in row `u` of `a1`. See gh-8906.
+        b2 /= a1[nupper, 0]
+        return b2
+    if nlower == nupper == 1:
+        overwrite_ab = overwrite_ab or _datacopied(a1, ab)
+        gtsv, = get_lapack_funcs(('gtsv',), (a1, b1))
+        du = a1[0, 1:]
+        d = a1[1, :]
+        dl = a1[2, :-1]
+        du2, d, du, x, info = gtsv(dl, d, du, b1, overwrite_ab, overwrite_ab,
+                                   overwrite_ab, overwrite_b)
+    else:
+        gbsv, = get_lapack_funcs(('gbsv',), (a1, b1))
+        a2 = np.zeros((2*nlower + nupper + 1, a1.shape[1]), dtype=gbsv.dtype)
+        a2[nlower:, :] = a1
+        lu, piv, x, info = gbsv(nlower, nupper, a2, b1, overwrite_ab=True,
+                                overwrite_b=overwrite_b)
+    if info == 0:
+        return x
+    if info > 0:
+        raise LinAlgError("singular matrix")
+    raise ValueError(f'illegal value in {-info}-th argument of internal gbsv/gtsv')
+
+
+@_apply_over_batch(('a', 2), ('b', '1|2'))
+def solveh_banded(ab, b, overwrite_ab=False, overwrite_b=False, lower=False,
+                  check_finite=True):
+    """
+    Solve the equation ``a @ x = b`` for ``x``,  where ``a`` is the
+    Hermitian positive-definite banded matrix defined by `ab`.
+
+    Uses Thomas' Algorithm, which is more efficient than standard LU
+    factorization, but should only be used for Hermitian positive-definite
+    matrices.
+
+    The matrix ``a`` is stored in `ab` either in lower diagonal or upper
+    diagonal ordered form::
+
+        ab[u + i - j, j] == a[i,j]        (if upper form; i <= j)
+        ab[    i - j, j] == a[i,j]        (if lower form; i >= j)
+
+    Example of `ab` (shape of ``a`` is (6, 6), number of upper diagonals,
+    ``u`` =2)::
+
+        upper form:
+        *   *   a02 a13 a24 a35
+        *   a01 a12 a23 a34 a45
+        a00 a11 a22 a33 a44 a55
+
+        lower form:
+        a00 a11 a22 a33 a44 a55
+        a10 a21 a32 a43 a54 *
+        a20 a31 a42 a53 *   *
+
+    Cells marked with * are not used.
+
+    Parameters
+    ----------
+    ab : (``u`` + 1, M) array_like
+        Banded matrix
+    b : (M,) or (M, K) array_like
+        Right-hand side
+    overwrite_ab : bool, optional
+        Discard data in `ab` (may enhance performance)
+        See :ref:`tutorial_linalg_overwrite` for details.
+    overwrite_b : bool, optional
+        Discard data in `b` (may enhance performance)
+        See :ref:`tutorial_linalg_overwrite` for details.
+    lower : bool, optional
+        Is the matrix in the lower form. (Default is upper form)
+    check_finite : bool, optional
+        Whether to check that the input matrices contain only finite numbers.
+        Disabling may give a performance gain, but may result in problems
+        (crashes, non-termination) if the inputs do contain infinities or NaNs.
+
+    Returns
+    -------
+    x : (M,) or (M, K) ndarray
+        The solution to the system ``a x = b``. Shape of return matches shape
+        of `b`.
+
+    Notes
+    -----
+    In the case of a non-positive definite matrix ``a``, the solver
+    `solve_banded` may be used.
+
+    Examples
+    --------
+    Solve the banded system ``A x = b``, where::
+
+            [ 4  2 -1  0  0  0]       [1]
+            [ 2  5  2 -1  0  0]       [2]
+        A = [-1  2  6  2 -1  0]   b = [2]
+            [ 0 -1  2  7  2 -1]       [3]
+            [ 0  0 -1  2  8  2]       [3]
+            [ 0  0  0 -1  2  9]       [3]
+
+    >>> import numpy as np
+    >>> from scipy.linalg import solveh_banded
+
+    ``ab`` contains the main diagonal and the nonzero diagonals below the
+    main diagonal. That is, we use the lower form:
+
+    >>> ab = np.array([[ 4,  5,  6,  7, 8, 9],
+    ...                [ 2,  2,  2,  2, 2, 0],
+    ...                [-1, -1, -1, -1, 0, 0]])
+    >>> b = np.array([1, 2, 2, 3, 3, 3])
+    >>> x = solveh_banded(ab, b, lower=True)
+    >>> x
+    array([ 0.03431373,  0.45938375,  0.05602241,  0.47759104,  0.17577031,
+            0.34733894])
+
+
+    Solve the Hermitian banded system ``H x = b``, where::
+
+            [ 8   2-1j   0     0  ]        [ 1  ]
+        H = [2+1j  5     1j    0  ]    b = [1+1j]
+            [ 0   -1j    9   -2-1j]        [1-2j]
+            [ 0    0   -2+1j   6  ]        [ 0  ]
+
+    In this example, we put the upper diagonals in the array ``hb``:
+
+    >>> hb = np.array([[0, 2-1j, 1j, -2-1j],
+    ...                [8,  5,    9,   6  ]])
+    >>> b = np.array([1, 1+1j, 1-2j, 0])
+    >>> x = solveh_banded(hb, b)
+    >>> x
+    array([ 0.07318536-0.02939412j,  0.11877624+0.17696461j,
+            0.10077984-0.23035393j, -0.00479904-0.09358128j])
+
+    """
+    a1 = _asarray_validated(ab, check_finite=check_finite)
+    b1 = _asarray_validated(b, check_finite=check_finite)
+
+    # Validate shapes.
+    if a1.shape[-1] != b1.shape[0]:
+        raise ValueError("shapes of ab and b are not compatible.")
+
+    # accommodate empty arrays
+    if b1.size == 0:
+        dt = solve(np.eye(1, dtype=a1.dtype), np.ones(1, dtype=b1.dtype)).dtype
+        return np.empty_like(b1, dtype=dt)
+
+    overwrite_b = overwrite_b or _datacopied(b1, b)
+    overwrite_ab = overwrite_ab or _datacopied(a1, ab)
+
+    if a1.shape[0] == 2:
+        ptsv, = get_lapack_funcs(('ptsv',), (a1, b1))
+        if lower:
+            d = a1[0, :].real
+            e = a1[1, :-1]
+        else:
+            d = a1[1, :].real
+            e = a1[0, 1:].conj()
+        d, du, x, info = ptsv(d, e, b1, overwrite_ab, overwrite_ab,
+                              overwrite_b)
+    else:
+        pbsv, = get_lapack_funcs(('pbsv',), (a1, b1))
+        c, x, info = pbsv(a1, b1, lower=lower, overwrite_ab=overwrite_ab,
+                          overwrite_b=overwrite_b)
+    if info > 0:
+        raise LinAlgError(f"{info}th leading minor not positive definite")
+    if info < 0:
+        raise ValueError(f'illegal value in {-info}th argument of internal pbsv')
+    return x
+
+
+def solve_toeplitz(c_or_cr, b, check_finite=True):
+    r"""Solve the equation ``T @ x = b`` for ``x``, where ``T`` is a Toeplitz
+    matrix defined by `c_or_cr`.
+
+    The Toeplitz matrix has constant diagonals, with ``c`` as its first column
+    and ``r`` as its first row. If ``r`` is not given, ``r == conjugate(c)`` is
+    assumed.
+
+    The documentation is written assuming array arguments are of specified
+    "core" shapes. However, array argument(s) of this function may have additional
+    "batch" dimensions prepended to the core shape. In this case, the array is treated
+    as a batch of lower-dimensional slices; see :ref:`linalg_batch` for details.
+
+    Parameters
+    ----------
+    c_or_cr : array_like or tuple of (array_like, array_like)
+        The vector ``c``, or a tuple of arrays (``c``, ``r``). If not
+        supplied, ``r = conjugate(c)`` is assumed; in this case, if c[0] is
+        real, the Toeplitz matrix is Hermitian. r[0] is ignored; the first row
+        of the Toeplitz matrix is ``[c[0], r[1:]]``.
+    b : (M,) or (M, K) array_like
+        Right-hand side in ``T x = b``.
+    check_finite : bool, optional
+        Whether to check that the input matrices contain only finite numbers.
+        Disabling may give a performance gain, but may result in problems
+        (result entirely NaNs) if the inputs do contain infinities or NaNs.
+
+    Returns
+    -------
+    x : (M,) or (M, K) ndarray
+        The solution to the system ``T @ x = b``. Shape of return matches shape
+        of `b`.
+
+    See Also
+    --------
+    toeplitz : Toeplitz matrix
+
+    Notes
+    -----
+    The solution is computed using Levinson-Durbin recursion, which is faster
+    than generic least-squares methods, but can be less numerically stable.
+
+    Examples
+    --------
+    Solve the Toeplitz system ``T @ x = b``, where::
+
+            [ 1 -1 -2 -3]       [1]
+        T = [ 3  1 -1 -2]   b = [2]
+            [ 6  3  1 -1]       [2]
+            [10  6  3  1]       [5]
+
+    To specify the Toeplitz matrix, only the first column and the first
+    row are needed.
+
+    >>> import numpy as np
+    >>> c = np.array([1, 3, 6, 10])    # First column of T
+    >>> r = np.array([1, -1, -2, -3])  # First row of T
+    >>> b = np.array([1, 2, 2, 5])
+
+    >>> from scipy.linalg import solve_toeplitz, toeplitz
+    >>> x = solve_toeplitz((c, r), b)
+    >>> x
+    array([ 1.66666667, -1.        , -2.66666667,  2.33333333])
+
+    Check the result by creating the full Toeplitz matrix and
+    multiplying it by ``x``.  We should get `b`.
+
+    >>> T = toeplitz(c, r)
+    >>> T.dot(x)
+    array([ 1.,  2.,  2.,  5.])
+
+    """
+    # If numerical stability of this algorithm is a problem, a future
+    # developer might consider implementing other O(N^2) Toeplitz solvers,
+    # such as GKO (https://www.jstor.org/stable/2153371) or Bareiss.
+    c, r = c_or_cr if isinstance(c_or_cr, tuple) else (c_or_cr, np.conjugate(c_or_cr))
+    return _solve_toeplitz(c, r, b, check_finite)
+
+
+@_apply_over_batch(('c', 1), ('r', 1), ('b', '1|2'))
+def _solve_toeplitz(c, r, b, check_finite):
+    r, c, b, dtype, b_shape = _validate_args_for_toeplitz_ops(
+        (c, r), b, check_finite, keep_b_shape=True)
+
+    # accommodate empty arrays
+    if b.size == 0:
+        return np.empty_like(b)
+
+    # Form a 1-D array of values to be used in the matrix, containing a
+    # reversed copy of r[1:], followed by c.
+    vals = np.concatenate((r[-1:0:-1], c))
+    if b is None:
+        raise ValueError('illegal value, `b` is a required argument')
+
+    if b.ndim == 1:
+        x, _ = levinson(vals, np.ascontiguousarray(b))
+    else:
+        x = np.column_stack([levinson(vals, np.ascontiguousarray(b[:, i]))[0]
+                             for i in range(b.shape[1])])
+        x = x.reshape(*b_shape)
+
+    return x
+
+
+def _get_axis_len(aname, a, axis):
+    ax = axis
+    if ax < 0:
+        ax += a.ndim
+    if 0 <= ax < a.ndim:
+        return a.shape[ax]
+    raise ValueError(f"'{aname}axis' entry is out of bounds")
+
+
+def solve_circulant(c, b, singular='raise', tol=None,
+                    caxis=-1, baxis=0, outaxis=0):
+    """Solve the equation ``C @ x = b`` for ``x``, where ``C`` is a
+    circulant matrix defined by `c`.
+
+    `C` is the circulant matrix associated with the vector `c`.
+
+    The system is solved by doing division in Fourier space. The
+    calculation is::
+
+        x = ifft(fft(b) / fft(c))
+
+    where `fft` and `ifft` are the fast Fourier transform and its inverse,
+    respectively. For a large vector `c`, this is *much* faster than
+    solving the system with the full circulant matrix.
+
+    Parameters
+    ----------
+    c : array_like
+        The coefficients of the circulant matrix.
+    b : array_like
+        Right-hand side matrix in ``a x = b``.
+    singular : str, optional
+        This argument controls how a near singular circulant matrix is
+        handled.  If `singular` is "raise" and the circulant matrix is
+        near singular, a `LinAlgError` is raised. If `singular` is
+        "lstsq", the least squares solution is returned. Default is "raise".
+    tol : float, optional
+        If any eigenvalue of the circulant matrix has an absolute value
+        that is less than or equal to `tol`, the matrix is considered to be
+        near singular. If not given, `tol` is set to::
+
+            tol = abs_eigs.max() * abs_eigs.size * np.finfo(np.float64).eps
+
+        where `abs_eigs` is the array of absolute values of the eigenvalues
+        of the circulant matrix.
+    caxis : int
+        When `c` has dimension greater than 1, it is viewed as a collection
+        of circulant vectors. In this case, `caxis` is the axis of `c` that
+        holds the vectors of circulant coefficients.
+    baxis : int
+        When `b` has dimension greater than 1, it is viewed as a collection
+        of vectors. In this case, `baxis` is the axis of `b` that holds the
+        right-hand side vectors.
+    outaxis : int
+        When `c` or `b` are multidimensional, the value returned by
+        `solve_circulant` is multidimensional. In this case, `outaxis` is
+        the axis of the result that holds the solution vectors.
+
+    Returns
+    -------
+    x : ndarray
+        Solution to the system ``C x = b``.
+
+    Raises
+    ------
+    LinAlgError
+        If the circulant matrix associated with `c` is near singular.
+
+    See Also
+    --------
+    circulant : circulant matrix
+
+    Notes
+    -----
+    For a 1-D vector `c` with length `m`, and an array `b` with shape ``(m, ...)``,
+    ``solve_circulant(c, b)`` returns the same result as ``solve(circulant(c), b)``
+    where `solve` and `circulant` are from `scipy.linalg`.
+
+    .. versionadded:: 0.16.0
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy.linalg import solve_circulant, solve, circulant, lstsq
+
+    >>> c = np.array([2, 2, 4])
+    >>> b = np.array([1, 2, 3])
+    >>> solve_circulant(c, b)
+    array([ 0.75, -0.25,  0.25])
+
+    Compare that result to solving the system with `scipy.linalg.solve`:
+
+    >>> solve(circulant(c), b)
+    array([ 0.75, -0.25,  0.25])
+
+    A singular example:
+
+    >>> c = np.array([1, 1, 0, 0])
+    >>> b = np.array([1, 2, 3, 4])
+
+    Calling ``solve_circulant(c, b)`` will raise a `LinAlgError`.  For the
+    least square solution, use the option ``singular='lstsq'``:
+
+    >>> solve_circulant(c, b, singular='lstsq')
+    array([ 0.25,  1.25,  2.25,  1.25])
+
+    Compare to `scipy.linalg.lstsq`:
+
+    >>> x, resid, rnk, s = lstsq(circulant(c), b)
+    >>> x
+    array([ 0.25,  1.25,  2.25,  1.25])
+
+    A broadcasting example:
+
+    Suppose we have the vectors of two circulant matrices stored in an array
+    with shape (2, 5), and three `b` vectors stored in an array with shape
+    (3, 5).  For example,
+
+    >>> c = np.array([[1.5, 2, 3, 0, 0], [1, 1, 4, 3, 2]])
+    >>> b = np.arange(15).reshape(-1, 5)
+
+    We want to solve all combinations of circulant matrices and `b` vectors,
+    with the result stored in an array with shape (2, 3, 5). When we
+    disregard the axes of `c` and `b` that hold the vectors of coefficients,
+    the shapes of the collections are (2,) and (3,), respectively, which are
+    not compatible for broadcasting. To have a broadcast result with shape
+    (2, 3), we add a trivial dimension to `c`: ``c[:, np.newaxis, :]`` has
+    shape (2, 1, 5). The last dimension holds the coefficients of the
+    circulant matrices, so when we call `solve_circulant`, we can use the
+    default ``caxis=-1``. The coefficients of the `b` vectors are in the last
+    dimension of the array `b`, so we use ``baxis=-1``. If we use the
+    default `outaxis`, the result will have shape (5, 2, 3), so we'll use
+    ``outaxis=-1`` to put the solution vectors in the last dimension.
+
+    >>> x = solve_circulant(c[:, np.newaxis, :], b, baxis=-1, outaxis=-1)
+    >>> x.shape
+    (2, 3, 5)
+    >>> np.set_printoptions(precision=3)  # For compact output of numbers.
+    >>> x
+    array([[[-0.118,  0.22 ,  1.277, -0.142,  0.302],
+            [ 0.651,  0.989,  2.046,  0.627,  1.072],
+            [ 1.42 ,  1.758,  2.816,  1.396,  1.841]],
+           [[ 0.401,  0.304,  0.694, -0.867,  0.377],
+            [ 0.856,  0.758,  1.149, -0.412,  0.831],
+            [ 1.31 ,  1.213,  1.603,  0.042,  1.286]]])
+
+    Check by solving one pair of `c` and `b` vectors (cf. ``x[1, 1, :]``):
+
+    >>> solve_circulant(c[1], b[1, :])
+    array([ 0.856,  0.758,  1.149, -0.412,  0.831])
+
+    """
+    c = np.atleast_1d(c)
+    nc = _get_axis_len("c", c, caxis)
+    b = np.atleast_1d(b)
+    nb = _get_axis_len("b", b, baxis)
+    if nc != nb:
+        raise ValueError(f'Shapes of c {c.shape} and b {b.shape} are incompatible')
+
+    _deprecate_dtypes('solve_circulant', c, b)
+
+    # accommodate empty arrays
+    if b.size == 0:
+        dt = solve_circulant(np.arange(3, dtype=c.dtype),
+                             np.ones(3, dtype=b.dtype)).dtype
+        return np.empty_like(b, dtype=dt)
+
+    fc = np.fft.fft(np.moveaxis(c, caxis, -1), axis=-1)
+    abs_fc = np.abs(fc)
+    if tol is None:
+        # This is the same tolerance as used in np.linalg.matrix_rank.
+        tol = abs_fc.max(axis=-1) * nc * np.finfo(np.float64).eps
+        if tol.shape != ():
+            tol = tol.reshape(tol.shape + (1,))
+        else:
+            tol = np.atleast_1d(tol)
+
+    near_zeros = abs_fc <= tol
+    is_near_singular = np.any(near_zeros)
+    if is_near_singular:
+        if singular == 'raise':
+            raise LinAlgError("near singular circulant matrix.")
+        else:
+            # Replace the small values with 1 to avoid errors in the
+            # division fb/fc below.
+            fc[near_zeros] = 1
+
+    fb = np.fft.fft(np.moveaxis(b, baxis, -1), axis=-1)
+
+    q = fb / fc
+
+    if is_near_singular:
+        # `near_zeros` is a boolean array, same shape as `c`, that is
+        # True where `fc` is (near) zero. `q` is the broadcasted result
+        # of fb / fc, so to set the values of `q` to 0 where `fc` is near
+        # zero, we use a mask that is the broadcast result of an array
+        # of True values shaped like `b` with `near_zeros`.
+        mask = np.ones_like(b, dtype=bool) & near_zeros
+        q[mask] = 0
+
+    x = np.fft.ifft(q, axis=-1)
+    if not (np.iscomplexobj(c) or np.iscomplexobj(b)):
+        x = x.real
+    if outaxis != -1:
+        x = np.moveaxis(x, -1, outaxis)
+    return x
+
+
+# matrix inversion
+def inv(a, overwrite_a=False, check_finite=True, *, assume_a=None, lower=False):
+    r"""
+    Compute the inverse of a matrix.
+
+    If the data matrix is known to be a particular type then supplying the
+    corresponding string to ``assume_a`` key chooses the dedicated solver.
+    The available options are
+
+    =============================  ================================
+     general                        'general' (or 'gen')
+     diagonal                       'diagonal'
+     upper triangular               'upper triangular'
+     lower triangular               'lower triangular'
+     symmetric positive definite    'pos'
+     symmetric                      'sym'
+     Hermitian                      'her'
+    =============================  ================================
+
+    For the 'pos' option, only the triangle of the input matrix specified in
+    the `lower` argument is used, and the other triangle is not referenced.
+    Likewise, an explicit `assume_a='diagonal'` means that off-diagonal elements
+    are not referenced.
+
+    The `a` array argument may have additional "batch" dimensions prepended to the core
+    shape. In this case, the array is treated as a batch of lower-dimensional slices;
+    see :ref:`linalg_batch` for details.
+
+    Parameters
+    ----------
+    a : array_like, shape (..., M, M)
+        Square matrix (or a batch of matrices) to be inverted.
+    overwrite_a : bool, optional
+        Discard data in `a` (may improve performance). Default is False.
+        See :ref:`tutorial_linalg_overwrite` for details.
+    check_finite : bool, optional
+        Whether to check that the input matrix contains only finite numbers.
+        Disabling may give a performance gain, but may result in problems
+        (crashes, non-termination) if the inputs do contain infinities or NaNs.
+    assume_a : str, optional
+        Valid entries are described above.
+        If omitted or ``None``, checks are performed to identify structure so the
+        appropriate solver can be called.
+    lower : bool, optional
+        Ignored unless `assume_a` is one of 'sym', 'her', or 'pos'. If True, the
+        calculation uses only the data in the lower triangle of `a`; entries above the
+        diagonal are ignored. If False (default), the calculation uses only the data in
+        the upper triangle of `a`; entries below the diagonal are ignored.
+
+    Returns
+    -------
+    ainv : ndarray
+        Inverse of the matrix `a`.
+
+    Raises
+    ------
+    LinAlgError
+        If `a` is singular.
+    ValueError
+        If `a` is not square, or not 2D.
+
+    Notes
+    -----
+
+    This routine checks the condition number of the `a` matrix and emits a
+    `LinAlgWarning` for ill-conditioned inputs.
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy import linalg
+    >>> a = np.array([[1., 2.], [3., 4.]])
+    >>> linalg.inv(a)
+    array([[-2. ,  1. ],
+           [ 1.5, -0.5]])
+    >>> a @ linalg.inv(a)
+    array([[ 1.,  0.],
+           [ 0.,  1.]])
+
+    The input array ``a`` may represent a single matrix or a collection (a.k.a.
+    a "batch") of square matrices. For example, if ``a.shape == (4, 3, 2, 2)``, it is
+    interpreted as a ``(4, 3)``-shaped batch of :math:`2\times 2` matrices.
+    See :ref:`linalg_batch` for further details.
+    To illustrate:
+
+    >>> a = np.stack((np.eye(2), [[1, 2], [3, 4]]))
+    >>> linalg.inv(a)
+    array([[[ 1. ,  0. ],
+            [ 0. ,  1. ]],
+           [[-2. ,  1. ],
+            [ 1.5, -0.5]]])
+
+    Note that the structure detection runs per-slice: in the example above, each of the
+    two slices will be independently discovered as being diagonal. Setting an explicit
+    ``assume_a`` argument will bypass structure detection and use the provided value
+    without checking:
+
+    >>> a = np.stack((np.eye(2), [[1, 2], [3, 4]]))
+    >>> linalg.inv(a, assume_a="diagonal")
+    array([[[1.  , 0.  ],
+            [0.  , 1.  ]],
+           [[1.  , 2.  ],   # off-diagonal elements are incorrect
+            [3.  , 0.25]]])
+    """
+    a1 = _asarray_validated(a, check_finite=check_finite)
+    _deprecate_dtypes("linalg.inv", a1)
+
+    if a1.ndim < 2:
+        raise ValueError(f"Expected at least ndim=2, got {a1.ndim=}")
+    if a1.shape[-1] != a1.shape[-2]:
+        raise ValueError(f"Expected square matrix, got {a1.shape=}")
+
+    # accommodate empty matrices
+    if a1.size == 0:
+        dt = inv(np.eye(2, dtype=a1.dtype)).dtype
+        return np.empty_like(a1, dtype=dt)
+
+    # Also check if dtype is LAPACK compatible
+    a1, overwrite_a = _normalize_lapack_dtype(a1, overwrite_a)
+    a1, overwrite_a = _ensure_aligned_and_native(a1, overwrite_a)
+
+    # XXX can relax a1.ndim == 2?
+    overwrite_a = overwrite_a and (a1.ndim == 2) and (a1.flags["F_CONTIGUOUS"])
+
+    # keep the numbers in sync with C at `linalg/src/_common_array_utils.hh`
+    structure = {
+        None: -1,
+        'general': 0, 'gen': 0,
+        'diagonal': 11,
+        'upper triangular': 21,
+        'lower triangular': 22,
+        'pos' : 101,
+        'sym' : 201,
+        'her' : 211,
+    }[assume_a]
+
+    # a1 is well behaved, invert it.
+    inv_a, err_lst = _batched_linalg._inv(a1, structure, overwrite_a, lower)
+
+    if err_lst:
+        _format_emit_errors_warnings(err_lst)
+
+    return inv_a
+
+
+# Determinant
+
+def det(a, overwrite_a=False, check_finite=True):
+    """
+    Compute the determinant of a matrix.
+
+    The determinant is a scalar that is a function of the associated square
+    matrix coefficients. The determinant value is zero for singular matrices.
+
+    Array argument(s) of this function may have additional
+    "batch" dimensions prepended to the core shape. In this case, the array is treated
+    as a batch of lower-dimensional slices; see :ref:`linalg_batch` for details.
+
+    Parameters
+    ----------
+    a : (..., M, M) array_like
+        Input array to compute determinants for.
+    overwrite_a : bool, optional
+        Allow overwriting data in a (may enhance performance).
+        See :ref:`tutorial_linalg_overwrite` for details.
+    check_finite : bool, optional
+        Whether to check that the input matrix contains only finite numbers.
+        Disabling may give a performance gain, but may result in problems
+        (crashes, non-termination) if the inputs do contain infinities or NaNs.
+
+    Returns
+    -------
+    det : (...) float or complex
+        Determinant of `a`. For stacked arrays, a scalar is returned for each
+        (m, m) slice in the last two dimensions of the input. For example, an
+        input of shape (p, q, m, m) will produce a result of shape (p, q). If
+        all dimensions are 1 a scalar is returned regardless of ndim.
+
+    Notes
+    -----
+    The determinant is computed by performing an LU factorization of the
+    input with LAPACK routine 'getrf', and then calculating the product of
+    diagonal entries of the U factor.
+
+    Even if the input array is single precision (float32 or complex64), the
+    result will be returned in double precision (float64 or complex128) to
+    prevent overflows.
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy import linalg
+    >>> a = np.array([[1,2,3], [4,5,6], [7,8,9]])  # A singular matrix
+    >>> linalg.det(a)
+    0.0
+    >>> b = np.array([[0,2,3], [4,5,6], [7,8,9]])
+    >>> linalg.det(b)
+    3.0
+    >>> # An array with the shape (3, 2, 2, 2)
+    >>> c = np.array([[[[1., 2.], [3., 4.]],
+    ...                [[5., 6.], [7., 8.]]],
+    ...               [[[9., 10.], [11., 12.]],
+    ...                [[13., 14.], [15., 16.]]],
+    ...               [[[17., 18.], [19., 20.]],
+    ...                [[21., 22.], [23., 24.]]]])
+    >>> linalg.det(c)  # The resulting shape is (3, 2)
+    array([[-2., -2.],
+           [-2., -2.],
+           [-2., -2.]])
+    >>> linalg.det(c[0, 0])  # Confirm the (0, 0) slice, [[1, 2], [3, 4]]
+    -2.0
+    """
+    # The goal is to end up with a writable contiguous array to pass to Cython
+
+    # First we check and make arrays.
+    a1 = np.asarray_chkfinite(a) if check_finite else np.asarray(a)
+    _deprecate_dtypes("linalg.det", a1)
+
+    if a1.ndim < 2:
+        raise ValueError('The input array must be at least two-dimensional.')
+    if a1.shape[-1] != a1.shape[-2]:
+        raise ValueError('Last 2 dimensions of the array must be square'
+                         f' but received shape {a1.shape}.')
+
+    # Also check if dtype is LAPACK compatible
+    a1, overwrite_a = _normalize_lapack_dtype1(a1, overwrite_a)
+
+    # Empty array has determinant 1 because math.
+    if min(*a1.shape) == 0:
+        dtyp = np.float64 if a1.dtype.char not in 'FD' else np.complex128
+        if a1.ndim == 2:
+            return dtyp(1.0)
+        else:
+            return np.ones(shape=a1.shape[:-2], dtype=dtyp)
+
+    # Scalar case
+    if a1.shape[-2:] == (1, 1):
+        a1 = a1[..., 0, 0]
+        if a1.ndim == 0:
+            a1 = a1[()]
+        # Convert float32 to float64, and complex64 to complex128.
+        if a1.dtype.char in 'dD':
+            return a1
+        return a1.astype('d') if a1.dtype.char == 'f' else a1.astype('D')
+
+    det = _linalg_det(a1, overwrite_a)
+
+    # Promote single precision to double to prevent overflows
+    # Cf. np.linalg.det(np.diag([1e+38, 1e+38]).astype(np.float32))
+    if det.dtype.char == 'f':
+        det = det.astype(np.float64)
+    elif det.dtype.char == 'F':
+        det = det.astype(np.complex128)
+
+    # Return scalar for 2D input
+    if det.ndim == 0:
+        return det[()]
+    return det
+
+
+# Linear Least Squares
+
+
+def lstsq(a, b, cond=None, overwrite_a=False, overwrite_b=False,
+          check_finite=True, lapack_driver=None):
+    """
+    Compute least-squares solution to the equation ``a @ x = b``.
+
+    Compute a vector x such that the 2-norm ``|b - A x|`` is minimized.
+
+    Parameters
+    ----------
+    a : (..., M, N) array_like
+        Left-hand side array
+    b : (M,) or (..., M, K) array_like
+        Right hand side array
+    cond : float, optional
+        Cutoff for 'small' singular values; used to determine effective
+        rank of a. Singular values smaller than
+        ``cond * largest_singular_value`` are considered zero.
+    overwrite_a : bool, optional
+        Whether to overwrite data in `a` (may improve performance). Default is False.
+        See :ref:`tutorial_linalg_overwrite` for details.
+    overwrite_b : bool, optional
+        Whether to overwrite data in `b` (may improve performance). Default is False.
+        See :ref:`tutorial_linalg_overwrite` for details.
+    check_finite : bool, optional
+        Whether to check that the input matrices contain only finite numbers.
+        Disabling may give a performance gain, but may result in problems
+        (crashes, non-termination) if the inputs do contain infinities or NaNs.
+    lapack_driver : str, optional
+        Which LAPACK driver is used to solve the least-squares problem.
+        Options are ``'gelsd'``, ``'gelsy'``, ``'gelss'``. Default
+        (``'gelsd'``) is a good choice.  However, ``'gelsy'`` can be slightly
+        faster on many problems.  ``'gelss'`` was used historically.  It is
+        generally slow but uses less memory.
+
+        .. versionadded:: 0.17.0
+
+    Returns
+    -------
+    x : (N,) or (..., N, K) ndarray
+        Least-squares solution.
+    residues : (K,) ndarray or float
+        If `lapack_driver` is ``'gelss'`` or ``'gelsd'`` this contains the square of
+        the 2-norm for each column in ``b - a x`` if ``M > N`` and ``rank == N``. If
+        the rank condition is violated, ``NaN`` is returned instead. If `lapack_driver`
+        if ``'gelsy'`` or ``M <= N`` a (0,)-shaped array is returned.
+    rank : int
+        Effective rank of `a`.
+    s : (min(M, N),) ndarray or None
+        Singular values of `a`. The condition number of ``a`` is
+        ``s[0] / s[-1]``.
+
+    Raises
+    ------
+    LinAlgError
+        If computation does not converge.
+
+    ValueError
+        When parameters are not compatible.
+
+    See Also
+    --------
+    scipy.optimize.nnls : linear least squares with non-negativity constraint
+
+    Notes
+    -----
+    When ``'gelsy'`` is used as a driver, `s` is always ``None``.
+
+    Array arguments of this function, `a` and `b`, may have additional "batch"
+    dimensions prepended to the core shape. In this case, the array is treated as a
+    batch of lower-dimensional slices; see :ref:`linalg_batch` for details.
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy.linalg import lstsq
+    >>> import matplotlib.pyplot as plt
+
+    Suppose we have the following data:
+
+    >>> x = np.array([1, 2.5, 3.5, 4, 5, 7, 8.5])
+    >>> y = np.array([0.3, 1.1, 1.5, 2.0, 3.2, 6.6, 8.6])
+
+    We want to fit a quadratic polynomial of the form ``y = a + b*x**2``
+    to this data.  We first form the "design matrix" M, with a constant
+    column of 1s and a column containing ``x**2``:
+
+    >>> M = x[:, np.newaxis]**[0, 2]
+    >>> M
+    array([[  1.  ,   1.  ],
+           [  1.  ,   6.25],
+           [  1.  ,  12.25],
+           [  1.  ,  16.  ],
+           [  1.  ,  25.  ],
+           [  1.  ,  49.  ],
+           [  1.  ,  72.25]])
+
+    We want to find the least-squares solution to ``M.dot(p) = y``,
+    where ``p`` is a vector with length 2 that holds the parameters
+    ``a`` and ``b``.
+
+    >>> p, res, rnk, s = lstsq(M, y)
+    >>> p
+    array([ 0.20925829,  0.12013861])
+
+    Plot the data and the fitted curve.
+
+    >>> plt.plot(x, y, 'o', label='data')
+    >>> xx = np.linspace(0, 9, 101)
+    >>> yy = p[0] + p[1]*xx**2
+    >>> plt.plot(xx, yy, label='least squares fit, $y = a + bx^2$')
+    >>> plt.xlabel('x')
+    >>> plt.ylabel('y')
+    >>> plt.legend(framealpha=1, shadow=True)
+    >>> plt.grid(alpha=0.25)
+    >>> plt.show()
+
+    As an illustration of the "batching" feature (see :ref:`linalg_batch` for details),
+    suppose that we want to compare least-squares fits of the given data with two
+    models: a quadratic model above, and one with an additional linear term,
+    ``y = a + b*x**2 + c*x``.
+    To this end, we construct the design matrix for ``y = a + b*x**2 + c*x``, and
+    extend ``M`` to have three columns:
+
+    >>> M1 = np.hstack((M, np.zeros((7, 1))))
+    >>> M2 = x[:, np.newaxis] ** [0, 2, 1]
+    >>> MM = np.stack((M1, M2))
+    >>> x, res, rnk, s = lstsq(MM, y)
+    >>> x
+    array([[0.20925829, 0.12013861, 0.        ],
+           [0.0578403 , 0.11262261, 0.07701453]])
+    >>> rnk
+    array([2, 3])
+
+    Note that the rows of the ``x`` solution are equivalent to using ``M1`` and ``M2``,
+    respectively.
+    In a similar vein, to simulate an effect of random noise on ``y``, you can turn
+    it into an array with multiple columns, where each column corresponds to a specific
+    realization of the noise.
+    """
+
+    driver = lapack_driver
+    if driver is None:
+        driver = lstsq.default_lapack_driver
+    if driver not in ('gelsd', 'gelsy', 'gelss'):
+        raise ValueError(f'LAPACK driver "{driver}" is not found')
+
+    if len(a.shape) < 2:
+        raise ValueError('Input array a should be at least 2D, got {a.shape = }')
+
+    a1 = np.atleast_2d(_asarray_validated(a, check_finite=check_finite))
+    b1 = np.atleast_1d(_asarray_validated(b, check_finite=check_finite))
+    _deprecate_dtypes("linalg.lstsq", a1, b1)
+
+    a1, b1 = _ensure_dtype_cdsz(a1, b1)   # NB: makes a1.dtype == b1.dtype, if needed
+    a1, overwrite_a = _normalize_lapack_dtype(a1, overwrite_a)
+
+    a1, overwrite_a = _ensure_aligned_and_native(a1, overwrite_a)
+    b1, overwrite_b = _ensure_aligned_and_native(b1, overwrite_b)
+
+    m, n = a1.shape[-2:]
+
+    # Zero-sized problem, confuses LAPACK; bail out straight away
+    if m == 0 or n == 0:
+        x = np.zeros((n,) + b1.shape[1:], dtype=np.common_type(a1, b1))
+        if n == 0:
+            residues = np.linalg.norm(b1, axis=0)**2
+        else:
+            residues = np.empty((0,))
+        return x, residues, 0, np.empty((0,))
+
+    # align the shape of b with a
+    # 1. make b1 at least 2D
+    b_is_1D = b1.ndim == 1
+    if b_is_1D:
+        b1 = b1[:, None]
+
+    if m != b1.shape[-2]:
+        raise ValueError('Shape mismatch: a and b should have the same number'
+                         f' of rows ({m} != {b1.shape[-2]}).')
+
+    # 2. broadcast the batch dimensions of b1 and a1
+    batch_shape = np.broadcast_shapes(a1.shape[:-2], b1.shape[:-2])
+    a1 = np.broadcast_to(a1, batch_shape + a1.shape[-2:])
+    b1 = np.broadcast_to(b1, batch_shape + b1.shape[-2:])
+
+    overwrite_a = overwrite_a and (a1.ndim == 2) and a1.flags["F_CONTIGUOUS"]
+    overwrite_b = (
+        overwrite_b and (b1.ndim == 2) and b1.flags["F_CONTIGUOUS"] and m >= n
+    ) # Only overwrite when overdetermined system, otherwise ldb will be > m
+
+    if cond is None:
+        cond = np.finfo(a1.dtype).eps
+    else:
+        cond = float(cond)
+
+    x, rank, S, err_lst = _batched_linalg._lstsq(
+        a1, b1, cond, driver, overwrite_a, overwrite_b
+    )
+
+    if err_lst:
+        _format_emit_errors_warnings(err_lst)
+
+    x1 = x[..., :n, :]
+    if m > n and lapack_driver != "gelsy":
+        residuals = np.sum(x[..., n:, :] * x[..., n:, :].conj(), axis=-2)
+
+        # LAPACK makes no promises about residuals for non full-column rank, set to NaN
+        residuals[rank < n, :] = np.nan
+    else:
+        residuals = np.zeros(batch_shape + (0,), dtype=x.dtype)
+
+    if b_is_1D:
+        x1 = x1[..., 0]
+        if residuals.size > 0 and lapack_driver != "gelsy":
+            residuals = residuals[..., 0]
+
+    if m <= n: # residuals are empty for under- and exactly determined problems
+        residuals = np.zeros(batch_shape + (0,), dtype=residuals.dtype)
+
+    return x1, residuals, rank, S
+
+
+lstsq.default_lapack_driver = 'gelsd'  # pyrefly:ignore[missing-attribute]
+
+
+def pinv(a, *, atol=None, rtol=None, return_rank=False, check_finite=True):
+    """
+    Compute the (Moore-Penrose) pseudo-inverse of a matrix.
+
+    Calculate a generalized inverse of a matrix using its
+    singular-value decomposition ``U @ S @ V`` in the economy mode and picking
+    up only the columns/rows that are associated with significant singular
+    values.
+
+    If ``s`` is the maximum singular value of ``a``, then the
+    significance cut-off value is determined by ``atol + rtol * s``. Any
+    singular value below this value is assumed insignificant.
+
+    The `a` array argument may have additional "batch" dimensions prepended to the core
+    shape. In this case, the array is treated as a batch of lower-dimensional slices;
+    see :ref:`linalg_batch` for details.
+
+    Parameters
+    ----------
+    a : (..., M, N) array_like
+        Matrix to be pseudo-inverted.
+    atol : float, optional
+        Absolute threshold term, default value is 0.
+
+        .. versionadded:: 1.7.0
+
+    rtol : float, optional
+        Relative threshold term, default value is ``max(M, N) * eps`` where
+        ``eps`` is the machine precision value of the datatype of ``a``.
+
+        .. versionadded:: 1.7.0
+
+    return_rank : bool, optional
+        If True, return the effective rank of the matrix.
+    check_finite : bool, optional
+        Whether to check that the input matrix contains only finite numbers.
+        Disabling may give a performance gain, but may result in problems
+        (crashes, non-termination) if the inputs do contain infinities or NaNs.
+
+    Returns
+    -------
+    B : (..., N, M) ndarray
+        The pseudo-inverse of matrix `a`.
+    rank : int
+        The effective rank of the matrix. Returned if `return_rank` is True.
+
+    Raises
+    ------
+    LinAlgError
+        If SVD computation does not converge.
+
+    See Also
+    --------
+    pinvh : Moore-Penrose pseudoinverse of a hermitian matrix.
+
+    Notes
+    -----
+    If ``A`` is invertible then the Moore-Penrose pseudoinverse is exactly
+    the inverse of ``A`` [1]_. If ``A`` is not invertible then the
+    Moore-Penrose pseudoinverse computes the ``x`` solution to ``Ax = b`` such
+    that ``||Ax - b||`` is minimized [1]_.
+
+    References
+    ----------
+    .. [1] Penrose, R. (1956). On best approximate solutions of linear matrix
+           equations. Mathematical Proceedings of the Cambridge Philosophical
+           Society, 52(1), 17-19. :doi:`10.1017/S0305004100030929`.
+
+    Examples
+    --------
+
+    Given an ``m x n`` matrix ``A`` and an ``n x m`` matrix ``B`` the four
+    Moore-Penrose conditions are:
+
+    1. ``ABA = A`` (``B`` is a generalized inverse of ``A``),
+    2. ``BAB = B`` (``A`` is a generalized inverse of ``B``),
+    3. ``(AB)* = AB`` (``AB`` is hermitian),
+    4. ``(BA)* = BA`` (``BA`` is hermitian) [1]_.
+
+    Here, ``A*`` denotes the conjugate transpose. The Moore-Penrose
+    pseudoinverse is a unique ``B`` that satisfies all four of these
+    conditions and exists for any ``A``. Note that, unlike the standard
+    matrix inverse, ``A`` does not have to be a square matrix or have
+    linearly independent columns/rows.
+
+    As an example, we can calculate the Moore-Penrose pseudoinverse of a
+    random non-square matrix and verify it satisfies the four conditions.
+
+    >>> import numpy as np
+    >>> from scipy import linalg
+    >>> rng = np.random.default_rng()
+    >>> A = rng.standard_normal((9, 6))
+    >>> B = linalg.pinv(A)
+    >>> np.allclose(A @ B @ A, A)  # Condition 1
+    True
+    >>> np.allclose(B @ A @ B, B)  # Condition 2
+    True
+    >>> np.allclose((A @ B).conj().T, A @ B)  # Condition 3
+    True
+    >>> np.allclose((B @ A).conj().T, B @ A)  # Condition 4
+    True
+
+    If the input array has more than two dimensions, it is interpreted as a batch of
+    two-dimensional slices:
+
+    >>> a = np.stack((np.zeros((3, 3)), np.eye(3)))
+    >>> p, ranks = linalg.pinv(a, return_rank=True)
+    >>> p.shape
+    (2, 3, 3)
+    >>> ranks
+    array([0, 3])
+    """
+    a = _asarray_validated(a, check_finite=check_finite)
+    u, s, vh = _decomp_svd.svd(a.conj(), full_matrices=False, check_finite=False)
+
+    atol = 0. if atol is None else atol
+    rtol = max(a.shape[-2:]) * np.finfo(u.dtype).eps if (rtol is None) else rtol
+    if (atol < 0.) or (rtol < 0.):
+        raise ValueError("atol and rtol values must be positive.")
+
+    maxS = np.max(s, axis=-1, initial=0., keepdims=True)
+    val = atol + maxS * rtol
+
+    large = s > val
+    rank = np.sum(large, axis=-1)
+
+    # zero out small singular values, 1/s large singular values
+    np.divide(1, s, where=large, out=s)
+    s[~large] = 0
+
+    B = vh.mT @ (s[..., None] * u.mT)
+
+    if return_rank:
+        return B, rank
+    else:
+        return B
+
+
+@_apply_over_batch(('a', 2))
+def pinvh(a, atol=None, rtol=None, lower=True, return_rank=False,
+          check_finite=True):
+    """
+    Compute the (Moore-Penrose) pseudo-inverse of a Hermitian matrix.
+
+    Calculate a generalized inverse of a complex Hermitian/real symmetric
+    matrix using its eigenvalue decomposition and including all eigenvalues
+    with 'large' absolute value.
+
+    Parameters
+    ----------
+    a : (N, N) array_like
+        Real symmetric or complex hermetian matrix to be pseudo-inverted
+
+    atol : float, optional
+        Absolute threshold term, default value is 0.
+
+        .. versionadded:: 1.7.0
+
+    rtol : float, optional
+        Relative threshold term, default value is ``N * eps`` where
+        ``eps`` is the machine precision value of the datatype of ``a``.
+
+        .. versionadded:: 1.7.0
+
+    lower : bool, optional
+        Whether the pertinent array data is taken from the lower or upper
+        triangle of `a`. (Default: lower)
+    return_rank : bool, optional
+        If True, return the effective rank of the matrix.
+    check_finite : bool, optional
+        Whether to check that the input matrix contains only finite numbers.
+        Disabling may give a performance gain, but may result in problems
+        (crashes, non-termination) if the inputs do contain infinities or NaNs.
+
+    Returns
+    -------
+    B : (N, N) ndarray
+        The pseudo-inverse of matrix `a`.
+    rank : int
+        The effective rank of the matrix.  Returned if `return_rank` is True.
+
+    Raises
+    ------
+    LinAlgError
+        If eigenvalue algorithm does not converge.
+
+    See Also
+    --------
+    pinv : Moore-Penrose pseudoinverse of a matrix.
+
+    Examples
+    --------
+
+    For a more detailed example see `pinv`.
+
+    >>> import numpy as np
+    >>> from scipy.linalg import pinvh
+    >>> rng = np.random.default_rng()
+    >>> a = rng.standard_normal((9, 6))
+    >>> a = np.dot(a, a.T)
+    >>> B = pinvh(a)
+    >>> np.allclose(a, a @ B @ a)
+    True
+    >>> np.allclose(B, B @ a @ B)
+    True
+
+    """
+    a = _asarray_validated(a, check_finite=check_finite)
+    s, u = _decomp.eigh(a, lower=lower, check_finite=False, driver='ev')
+    t = u.dtype.char.lower()
+    maxS = np.max(np.abs(s), initial=0.)
+
+    atol = 0. if atol is None else atol
+    rtol = max(a.shape) * np.finfo(t).eps if (rtol is None) else rtol
+
+    if (atol < 0.) or (rtol < 0.):
+        raise ValueError("atol and rtol values must be positive.")
+
+    val = atol + maxS * rtol
+    above_cutoff = (abs(s) > val)
+
+    psigma_diag = 1.0 / s[above_cutoff]
+    u = u[:, above_cutoff]
+
+    B = (u * psigma_diag) @ u.conj().T
+
+    if return_rank:
+        return B, len(psigma_diag)
+    else:
+        return B
+
+
+@_apply_over_batch(('A', 2))
+def matrix_balance(A, permute=True, scale=True, separate=False,
+                   overwrite_a=False):
+    """
+    Compute a diagonal similarity transformation for row/column balancing.
+
+    The balancing tries to equalize the row and column 1-norms by applying
+    a similarity transformation such that the magnitude variation of the
+    matrix entries is reflected to the scaling matrices.
+
+    Moreover, if enabled, the matrix is first permuted to isolate the upper
+    triangular parts of the matrix and, again if scaling is also enabled,
+    only the remaining subblocks are subjected to scaling.
+
+    Parameters
+    ----------
+    A : (n, n) array_like
+        Square data matrix for the balancing.
+    permute : bool, optional
+        The selector to define whether permutation of A is also performed
+        prior to scaling.
+    scale : bool, optional
+        The selector to turn on and off the scaling. If False, the matrix
+        will not be scaled.
+    separate : bool, optional
+        This switches from returning a full matrix of the transformation
+        to a tuple of two separate 1-D permutation and scaling arrays.
+    overwrite_a : bool, optional
+        This is passed to xGEBAL directly. Essentially, overwrites the result
+        to the data. It might increase the space efficiency. See LAPACK manual
+        for details. This is False by default.
+        See :ref:`tutorial_linalg_overwrite` for details.
+
+    Returns
+    -------
+    B : (n, n) ndarray
+        Balanced matrix
+    T : (n, n) ndarray
+        A possibly permuted diagonal matrix whose nonzero entries are
+        integer powers of 2 to avoid numerical truncation errors.
+    scale, perm : (n,) ndarray
+        If ``separate`` keyword is set to True then instead of the array
+        ``T`` above, the scaling and the permutation vectors are given
+        separately as a tuple without allocating the full array ``T``.
+
+    Notes
+    -----
+    The balanced matrix satisfies the following equality
+
+    .. math::
+        B = T^{-1} A T
+
+    The scaling coefficients are approximated to the nearest power of 2
+    to avoid round-off errors.
+
+    This algorithm is particularly useful for eigenvalue and matrix
+    decompositions and in many cases it is already called by various
+    LAPACK routines.
+
+    The algorithm is based on the well-known technique of [1]_ and has
+    been modified to account for special cases. See [2]_ for details
+    which have been implemented since LAPACK v3.5.0. Before this version
+    there are corner cases where balancing can actually worsen the
+    conditioning. See [3]_ for such examples.
+
+    The code is a wrapper around LAPACK's xGEBAL routine family for matrix
+    balancing.
+
+    .. versionadded:: 0.19.0
+
+    References
+    ----------
+    .. [1] B.N. Parlett and C. Reinsch, "Balancing a Matrix for
+       Calculation of Eigenvalues and Eigenvectors", Numerische Mathematik,
+       Vol.13(4), 1969, :doi:`10.1007/BF02165404`
+    .. [2] R. James, J. Langou, B.R. Lowery, "On matrix balancing and
+       eigenvector computation", 2014, :arxiv:`1401.5766`
+    .. [3] D.S. Watkins. A case where balancing is harmful.
+       Electron. Trans. Numer. Anal, Vol.23, 2006.
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy import linalg
+    >>> x = np.array([[1,2,0], [9,1,0.01], [1,2,10*np.pi]])
+
+    >>> y, permscale = linalg.matrix_balance(x)
+    >>> np.abs(x).sum(axis=0) / np.abs(x).sum(axis=1)
+    array([ 3.66666667,  0.4995005 ,  0.91312162])
+
+    >>> np.abs(y).sum(axis=0) / np.abs(y).sum(axis=1)
+    array([ 1.2       ,  1.27041742,  0.92658316])  # may vary
+
+    >>> permscale  # only powers of 2 (0.5 == 2^(-1))
+    array([[  0.5,   0. ,  0. ],  # may vary
+           [  0. ,   1. ,  0. ],
+           [  0. ,   0. ,  1. ]])
+
+    """
+
+    A = np.atleast_2d(_asarray_validated(A, check_finite=True))
+
+    if not np.equal(*A.shape):
+        raise ValueError('The data matrix for balancing should be square.')
+
+    # accommodate empty arrays
+    if A.size == 0:
+        b_n, t_n = matrix_balance(np.eye(2, dtype=A.dtype))
+        B = np.empty_like(A, dtype=b_n.dtype)
+        if separate:
+            scaling = np.ones_like(A, shape=len(A))
+            perm = np.arange(len(A))
+            return B, (scaling, perm)
+        return B, np.empty_like(A, dtype=t_n.dtype)
+
+    gebal = get_lapack_funcs(('gebal'), (A,))
+    B, lo, hi, ps, info = gebal(A, scale=scale, permute=permute,
+                                overwrite_a=overwrite_a)
+
+    if info < 0:
+        raise ValueError('xGEBAL exited with the internal error '
+                         f'"illegal value in argument number {-info}.". See '
+                         'LAPACK documentation for the xGEBAL error codes.')
+
+    # Separate the permutations from the scalings and then convert to int
+    scaling = np.ones_like(ps, dtype=float)
+    scaling[lo:hi+1] = ps[lo:hi+1]
+
+    # gebal uses 1-indexing
+    ps = ps.astype(int, copy=False) - 1
+    n = A.shape[0]
+    perm = np.arange(n)
+
+    # LAPACK permutes with the ordering n --> hi, then 0--> lo
+    if hi < n:
+        for ind, x in enumerate(ps[hi+1:][::-1], 1):
+            if n-ind == x:
+                continue
+            perm[[x, n-ind]] = perm[[n-ind, x]]
+
+    if lo > 0:
+        for ind, x in enumerate(ps[:lo]):
+            if ind == x:
+                continue
+            perm[[x, ind]] = perm[[ind, x]]
+
+    if separate:
+        return B, (scaling, perm)
+
+    # get the inverse permutation
+    iperm = np.empty_like(perm)
+    iperm[perm] = np.arange(n)
+
+    return B, np.diag(scaling)[iperm, :]
+
+
+def _validate_args_for_toeplitz_ops(c_or_cr, b, check_finite, keep_b_shape,
+                                    enforce_square=True):
+    """Validate arguments and format inputs for toeplitz functions
+
+    Parameters
+    ----------
+    c_or_cr : array_like or tuple of (array_like, array_like)
+        The vector ``c``, or a tuple of arrays (``c``, ``r``). Whatever the
+        actual shape of ``c``, it will be converted to a 1-D array. If not
+        supplied, ``r = conjugate(c)`` is assumed; in this case, if c[0] is
+        real, the Toeplitz matrix is Hermitian. r[0] is ignored; the first row
+        of the Toeplitz matrix is ``[c[0], r[1:]]``. Whatever the actual shape
+        of ``r``, it will be converted to a 1-D array.
+    b : (M,) or (M, K) array_like
+        Right-hand side in ``T x = b``.
+    check_finite : bool
+        Whether to check that the input matrices contain only finite numbers.
+        Disabling may give a performance gain, but may result in problems
+        (result entirely NaNs) if the inputs do contain infinities or NaNs.
+    keep_b_shape : bool
+        Whether to convert a (M,) dimensional b into a (M, 1) dimensional
+        matrix.
+    enforce_square : bool, optional
+        If True (default), this verifies that the Toeplitz matrix is square.
+
+    Returns
+    -------
+    r : array
+        1d array corresponding to the first row of the Toeplitz matrix.
+    c: array
+        1d array corresponding to the first column of the Toeplitz matrix.
+    b: array
+        (M,), (M, 1) or (M, K) dimensional array, post validation,
+        corresponding to ``b``.
+    dtype: numpy datatype
+        ``dtype`` stores the datatype of ``r``, ``c`` and ``b``. If any of
+        ``r``, ``c`` or ``b`` are complex, ``dtype`` is ``np.complex128``,
+        otherwise, it is ``np.float``.
+    b_shape: tuple
+        Shape of ``b`` after passing it through ``_asarray_validated``.
+
+    """
+
+    if isinstance(c_or_cr, tuple):
+        c, r = c_or_cr
+        c = _asarray_validated(c, check_finite=check_finite)
+        r = _asarray_validated(r, check_finite=check_finite)
+    else:
+        c = _asarray_validated(c_or_cr, check_finite=check_finite)
+        r = c.conjugate()
+
+    if b is None:
+        raise ValueError('`b` must be an array, not None.')
+
+    b = _asarray_validated(b, check_finite=check_finite)
+    b_shape = b.shape
+
+    is_not_square = r.shape[0] != c.shape[0]
+    if (enforce_square and is_not_square) or b.shape[0] != r.shape[0]:
+        raise ValueError('Incompatible dimensions.')
+
+    is_cmplx = np.iscomplexobj(r) or np.iscomplexobj(c) or np.iscomplexobj(b)
+    dtype = np.complex128 if is_cmplx else np.float64
+    r, c, b = (np.asarray(i, dtype=dtype) for i in (r, c, b))
+
+    if b.ndim == 1 and not keep_b_shape:
+        b = b.reshape(-1, 1)
+    elif b.ndim != 1:
+        b = b.reshape(b.shape[0], -1 if b.size > 0 else 0)
+
+    return r, c, b, dtype, b_shape
+
+
+def matmul_toeplitz(c_or_cr, x, check_finite=False, workers=None):
+    r"""Efficient Toeplitz Matrix-Matrix Multiplication using FFT.
+
+    This function returns the matrix multiplication between a Toeplitz
+    matrix and a dense matrix.
+
+    The Toeplitz matrix has constant diagonals, with c as its first column
+    and r as its first row. If r is not given, ``r == conjugate(c)`` is
+    assumed.
+
+    The documentation is written assuming array arguments are of specified
+    "core" shapes. However, array argument(s) of this function may have additional
+    "batch" dimensions prepended to the core shape. In this case, the array is treated
+    as a batch of lower-dimensional slices; see :ref:`linalg_batch` for details.
+
+    Parameters
+    ----------
+    c_or_cr : array_like or tuple of (array_like, array_like)
+        The vector ``c``, or a tuple of arrays (``c``, ``r``). If not
+        supplied, ``r = conjugate(c)`` is assumed; in this case, if c[0] is
+        real, the Toeplitz matrix is Hermitian. r[0] is ignored; the first row
+        of the Toeplitz matrix is ``[c[0], r[1:]]``.
+    x : (M,) or (M, K) array_like
+        Matrix with which to multiply.
+    check_finite : bool, optional
+        Whether to check that the input matrices contain only finite numbers.
+        Disabling may give a performance gain, but may result in problems
+        (result entirely NaNs) if the inputs do contain infinities or NaNs.
+    workers : int, optional
+        To pass to scipy.fft.fft and ifft. Maximum number of workers to use
+        for parallel computation. If negative, the value wraps around from
+        ``os.cpu_count()``. See scipy.fft.fft for more details.
+
+    Returns
+    -------
+    T @ x : (M,) or (M, K) ndarray
+        The result of the matrix multiplication ``T @ x``. Shape of return
+        matches shape of `x`.
+
+    See Also
+    --------
+    toeplitz : Toeplitz matrix
+    solve_toeplitz : Solve a Toeplitz system using Levinson Recursion
+
+    Notes
+    -----
+    The Toeplitz matrix is embedded in a circulant matrix and the FFT is used
+    to efficiently calculate the matrix-matrix product.
+
+    Because the computation is based on the FFT, integer inputs will
+    result in floating point outputs.  This is unlike NumPy's `matmul`,
+    which preserves the data type of the input.
+
+    This is partly based on the implementation that can be found in [1]_,
+    licensed under the MIT license. More information about the method can be
+    found in reference [2]_. References [3]_ and [4]_ have more reference
+    implementations in Python.
+
+    .. versionadded:: 1.6.0
+
+    References
+    ----------
+    .. [1] Jacob R Gardner, Geoff Pleiss, David Bindel, Kilian
+       Q Weinberger, Andrew Gordon Wilson, "GPyTorch: Blackbox Matrix-Matrix
+       Gaussian Process Inference with GPU Acceleration" with contributions
+       from Max Balandat and Ruihan Wu. Available online:
+       https://github.com/cornellius-gp/gpytorch
+
+    .. [2] J. Demmel, P. Koev, and X. Li, "A Brief Survey of Direct Linear
+       Solvers". In Z. Bai, J. Demmel, J. Dongarra, A. Ruhe, and H. van der
+       Vorst, editors. Templates for the Solution of Algebraic Eigenvalue
+       Problems: A Practical Guide. SIAM, Philadelphia, 2000. Available at:
+       http://www.netlib.org/utk/people/JackDongarra/etemplates/node384.html
+
+    .. [3] R. Scheibler, E. Bezzam, I. Dokmanic, Pyroomacoustics: A Python
+       package for audio room simulations and array processing algorithms,
+       Proc. IEEE ICASSP, Calgary, CA, 2018.
+       https://github.com/LCAV/pyroomacoustics/blob/pypi-release/
+       pyroomacoustics/adaptive/util.py
+
+    .. [4] Marano S, Edwards B, Ferrari G and Fah D (2017), "Fitting
+       Earthquake Spectra: Colored Noise and Incomplete Data", Bulletin of
+       the Seismological Society of America., January, 2017. Vol. 107(1),
+       pp. 276-291.
+
+    Examples
+    --------
+    Multiply the Toeplitz matrix T with matrix x::
+
+            [ 1 -1 -2 -3]       [1 10]
+        T = [ 3  1 -1 -2]   x = [2 11]
+            [ 6  3  1 -1]       [2 11]
+            [10  6  3  1]       [5 19]
+
+    To specify the Toeplitz matrix, only the first column and the first
+    row are needed.
+
+    >>> import numpy as np
+    >>> c = np.array([1, 3, 6, 10])    # First column of T
+    >>> r = np.array([1, -1, -2, -3])  # First row of T
+    >>> x = np.array([[1, 10], [2, 11], [2, 11], [5, 19]])
+
+    >>> from scipy.linalg import toeplitz, matmul_toeplitz
+    >>> matmul_toeplitz((c, r), x)
+    array([[-20., -80.],
+           [ -7.,  -8.],
+           [  9.,  85.],
+           [ 33., 218.]])
+
+    Check the result by creating the full Toeplitz matrix and
+    multiplying it by ``x``.
+
+    >>> toeplitz(c, r) @ x
+    array([[-20, -80],
+           [ -7,  -8],
+           [  9,  85],
+           [ 33, 218]])
+
+    The full matrix is never formed explicitly, so this routine
+    is suitable for very large Toeplitz matrices.
+
+    >>> n = 1000000
+    >>> matmul_toeplitz([1] + [0]*(n-1), np.ones(n))
+    array([1., 1., 1., ..., 1., 1., 1.], shape=(1000000,))
+
+    """
+
+    from ..fft import fft, ifft, rfft, irfft
+    c, r = c_or_cr if isinstance(c_or_cr, tuple) else (c_or_cr, np.conjugate(c_or_cr))
+
+    return _matmul_toepltiz(r, c, x, workers, check_finite, fft, ifft, rfft, irfft)
+
+
+@_apply_over_batch(('r', 1), ('c', 1), ('x', '1|2'))
+def _matmul_toepltiz(r, c, x, workers, check_finite, fft, ifft, rfft, irfft):
+    r, c, x, dtype, x_shape = _validate_args_for_toeplitz_ops((c, r), x, check_finite,
+                                                              keep_b_shape=False,
+                                                              enforce_square=False)
+    n, m = x.shape
+
+    T_nrows = len(c)
+    T_ncols = len(r)
+    p = T_nrows + T_ncols - 1  # equivalent to len(embedded_col)
+    return_shape = (T_nrows,) if len(x_shape) == 1 else (T_nrows, m)
+
+    # accommodate empty arrays
+    if x.size == 0:
+        return np.empty_like(x, shape=return_shape)
+
+    embedded_col = np.concatenate((c, r[-1:0:-1]))
+
+    if np.iscomplexobj(embedded_col) or np.iscomplexobj(x):
+        fft_mat = fft(embedded_col, axis=0, workers=workers).reshape(-1, 1)
+        fft_x = fft(x, n=p, axis=0, workers=workers)
+
+        mat_times_x = ifft(fft_mat*fft_x, axis=0,
+                           workers=workers)[:T_nrows, :]
+    else:
+        # Real inputs; using rfft is faster
+        fft_mat = rfft(embedded_col, axis=0, workers=workers).reshape(-1, 1)
+        fft_x = rfft(x, n=p, axis=0, workers=workers)
+
+        mat_times_x = irfft(fft_mat*fft_x, axis=0,
+                            workers=workers, n=p)[:T_nrows, :]
+
+    return mat_times_x.reshape(*return_shape)
diff --git a/.venv/lib/python3.12/site-packages/scipy/linalg/_batched_linalg.cpython-312-x86_64-linux-gnu.so b/.venv/lib/python3.12/site-packages/scipy/linalg/_batched_linalg.cpython-312-x86_64-linux-gnu.so
new file mode 100644
index 0000000000000000000000000000000000000000..0f3904c3f40e1c31f5b22d0d35a612fa16e21620
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/linalg/_batched_linalg.cpython-312-x86_64-linux-gnu.so
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:355935cea298bca9349fcf05d9747df11a3c34dbf4fba2564b83aec2fe689d33
+size 360465
diff --git a/.venv/lib/python3.12/site-packages/scipy/linalg/_cythonized_array_utils.cpython-312-x86_64-linux-gnu.so b/.venv/lib/python3.12/site-packages/scipy/linalg/_cythonized_array_utils.cpython-312-x86_64-linux-gnu.so
new file mode 100644
index 0000000000000000000000000000000000000000..8bede12c0c531cdfa23a6ad28edc3ef5a75704f6
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/linalg/_cythonized_array_utils.cpython-312-x86_64-linux-gnu.so
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:3a1a61b7b58a79810a96f009f631980e6ad707fbb7a69aad53a17e24c92ccd27
+size 226040
diff --git a/.venv/lib/python3.12/site-packages/scipy/linalg/_cythonized_array_utils.pxd b/.venv/lib/python3.12/site-packages/scipy/linalg/_cythonized_array_utils.pxd
new file mode 100644
index 0000000000000000000000000000000000000000..103491beabba04c6e30d53fd48cad3a6dbd9cf8a
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/linalg/_cythonized_array_utils.pxd
@@ -0,0 +1,39 @@
+cimport numpy as cnp
+
+ctypedef fused lapack_t:
+    float
+    double
+    (float complex)
+    (double complex)
+
+ctypedef fused lapack_cz_t:
+    (float complex)
+    (double complex)
+
+ctypedef fused lapack_sd_t:
+    float
+    double
+
+ctypedef fused np_numeric_t:
+    cnp.int8_t
+    cnp.int16_t
+    cnp.int32_t
+    cnp.int64_t
+    cnp.uint8_t
+    cnp.uint16_t
+    cnp.uint32_t
+    cnp.uint64_t
+    cnp.float32_t
+    cnp.float64_t
+    cnp.longdouble_t
+    cnp.complex64_t
+    cnp.complex128_t
+
+ctypedef fused np_complex_numeric_t:
+    cnp.complex64_t
+    cnp.complex128_t
+
+
+cdef void swap_c_and_f_layout(lapack_t *a, lapack_t *b, int r, int c) noexcept nogil
+cdef bint is_sym_her_real_c_internal(np_numeric_t[:, ::1]A) noexcept nogil
+cdef bint is_sym_her_complex_c_internal(np_complex_numeric_t[:, ::1]A) noexcept nogil
diff --git a/.venv/lib/python3.12/site-packages/scipy/linalg/_cythonized_array_utils.pyi b/.venv/lib/python3.12/site-packages/scipy/linalg/_cythonized_array_utils.pyi
new file mode 100644
index 0000000000000000000000000000000000000000..f5c65f0ed5aeb4ad29120093f1ce1d36eb6fd7bb
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/linalg/_cythonized_array_utils.pyi
@@ -0,0 +1,14 @@
+from numpy.typing import NDArray
+from typing import Any
+
+def issymmetric(
+    a: NDArray[Any],
+    atol: None | float = ...,
+    rtol: None | float = ...,
+) -> bool: ...
+
+def ishermitian(
+    a: NDArray[Any],
+    atol: None | float = ...,
+    rtol: None | float = ...,
+) -> bool: ...
diff --git a/.venv/lib/python3.12/site-packages/scipy/linalg/_decomp.py b/.venv/lib/python3.12/site-packages/scipy/linalg/_decomp.py
new file mode 100644
index 0000000000000000000000000000000000000000..43e085b69a37bad48b2610313772599ad8f6fe7e
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/linalg/_decomp.py
@@ -0,0 +1,1707 @@
+#
+# Author: Pearu Peterson, March 2002
+#
+# additions by Travis Oliphant, March 2002
+# additions by Eric Jones,      June 2002
+# additions by Johannes Loehnert, June 2006
+# additions by Bart Vandereycken, June 2006
+# additions by Andrew D Straw, May 2007
+# additions by Tiziano Zito, November 2008
+#
+# April 2010: Functions for LU, QR, SVD, Schur, and Cholesky decompositions
+# were moved to their own files. Still in this file are functions for
+# eigenstuff and for the Hessenberg form.
+
+__all__ = ['eig', 'eigvals', 'eigh', 'eigvalsh',
+           'eig_banded', 'eigvals_banded',
+           'eigh_tridiagonal', 'eigvalsh_tridiagonal', 'hessenberg', 'cdf2rdf']
+
+import numpy as np
+from numpy import (array, isfinite, inexact, nonzero, iscomplexobj,
+                   asarray, argsort, empty, iscomplex, zeros, einsum, eye, inf)
+# Local imports
+from scipy._lib._util import _asarray_validated, _apply_over_batch, _deprecate_dtypes
+from ._misc import LinAlgError, _datacopied
+from scipy.linalg._misc import norm   # noqa: F401  (backwards compat)
+from .lapack import (
+    _normalize_lapack_dtype, _ensure_aligned_and_native, _ensure_dtype_cdsz
+)
+from .lapack import get_lapack_funcs, _compute_lwork
+from . import _batched_linalg
+
+
+def _make_eigvals(alpha, beta, homogeneous_eigvals):
+    if homogeneous_eigvals:
+        if beta is None:
+            beta = np.ones_like(alpha)
+        return np.stack((alpha, beta), axis=-2)
+    else:
+        if beta is None:
+            return alpha
+        else:
+            w = np.empty_like(alpha)
+            alpha_zero = (alpha == 0)
+            beta_zero = (beta == 0)
+            beta_nonzero = ~beta_zero
+            w[beta_nonzero] = alpha[beta_nonzero] / beta[beta_nonzero]
+            # Use np.inf for complex values too since
+            # 1/np.inf = 0, i.e., it correctly behaves as projective
+            # infinity.
+            w[~alpha_zero & beta_zero] = np.inf
+            if np.all(alpha.imag == 0):
+                w[alpha_zero & beta_zero] = np.nan
+            else:
+                w[alpha_zero & beta_zero] = complex(np.nan, np.nan)
+            return w
+
+
+def _check_format_errors_warnings(routine_name, err_lst):
+    # XXX: find a test case to cover this
+    mesg = (
+        f"Internal {routine_name} return info = {[e['lapack_info'] for e in err_lst]} "
+        f"for slices {[e['num'] for e in err_lst]}."
+    )
+    raise LinAlgError(mesg)
+
+
+def eig(a, b=None, left=False, right=True, overwrite_a=False,
+        overwrite_b=False, check_finite=True, homogeneous_eigvals=False):
+    r"""
+    Solve an ordinary or generalized eigenvalue problem of a square matrix.
+
+    Find eigenvalues w and right or left eigenvectors of a general matrix::
+
+        a   @ vr[:, i] = w[i]        * b   @ vr[:, i]
+        a.H @ vl[:, i] = w[i].conj() * b.H @ vl[:, i]
+
+    where ``.H`` is the Hermitian conjugation.
+
+    Parameters
+    ----------
+    a : (..., M, M) array_like
+        A complex or real matrix whose eigenvalues and eigenvectors
+        will be computed.
+    b : (..., M, M) array_like, optional
+        Right-hand side matrix in a generalized eigenvalue problem.
+        Default is None, identity matrix is assumed.
+    left : bool, optional
+        Whether to calculate and return left eigenvectors.  Default is False.
+    right : bool, optional
+        Whether to calculate and return right eigenvectors.  Default is True.
+    overwrite_a : bool, optional
+        Whether to overwrite `a`; may improve performance.  Default is False.
+        See :ref:`tutorial_linalg_overwrite` for details.
+    overwrite_b : bool, optional
+        Whether to overwrite `b`; may improve performance.  Default is False.
+        See :ref:`tutorial_linalg_overwrite` for details.
+    check_finite : bool, optional
+        Whether to check that the input matrices contain only finite numbers.
+        Disabling may give a performance gain, but may result in problems
+        (crashes, non-termination) if the inputs do contain infinities or NaNs.
+    homogeneous_eigvals : bool, optional
+        If True, return the eigenvalues in homogeneous coordinates.
+        In this case ``w`` is a ``(2, M)`` array so that::
+
+            w[1, i] * a @ vr[:, i] = w[0, i] * b @ vr[:, i]
+
+        This option is sometimes useful for generalized eigenvalue problems,
+        ``b is not None``, where an eigenvalue, :math:`\lambda = \alpha / \beta`  ,
+        can over- or underflow; typically, :\math:`\alpha` and :math:`\beta` are of the
+        order of ``norm(a)`` and ``norm(b)``, respectively.
+
+        Default is False.
+
+    Returns
+    -------
+    w : (..., M,) or (..., 2, M) complex ndarray
+        The eigenvalues, each repeated according to its
+        multiplicity. The shape is ``(..., M)`` unless ``homogeneous_eigvals=True``.
+    vl : (..., M, M) double or complex ndarray
+        The left eigenvector corresponding to the eigenvalue
+        ``w[i]`` is the column ``vl[:, i]``. Only returned if ``left=True``.
+        The left eigenvector is not normalized.
+    vr : (..., M, M) double or complex ndarray
+        The normalized right eigenvector corresponding to the eigenvalue
+        ``w[i]`` is the column ``vr[:, i]``.  Only returned if ``right=True`` (default).
+
+    Raises
+    ------
+    LinAlgError
+        If eigenvalue computation does not converge.
+
+    See Also
+    --------
+    eigvals : eigenvalues of general arrays
+    eigh : Eigenvalues and right eigenvectors for symmetric/Hermitian arrays.
+    eig_banded : eigenvalues and right eigenvectors for symmetric/Hermitian
+        band matrices
+    eigh_tridiagonal : eigenvalues and right eigenvectors for
+        symmetric/Hermitian tridiagonal matrices
+
+    Notes
+    -----
+    Array arguments of this function, `a` and `b`, may have additional
+    "batch" dimensions prepended to the core shape. In this case, the array is treated
+    as a batch of lower-dimensional slices; see :ref:`linalg_batch` for details.
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy import linalg
+    >>> a = np.array([[0., -1.],
+    ...               [1.,  0.]])
+
+    Compute the eigenvalues (``eigvals`` is the same as ``eig(a, right=False)``)
+
+    >>> linalg.eigvals(a)
+    array([0.+1.j, 0.-1.j])
+
+    Solve a generalized eigenvalue problem:
+
+    >>> b = np.array([[0., 1.], [1., 1.]])
+    >>> linalg.eigvals(a, b)
+    array([ 1.+0.j, -1.+0.j])
+
+    Inputs with ``ndim > 2`` are interpreted as a batch of matrices
+
+    >>> a2 = np.stack((a, 2*a))
+    >>> linalg.eigvals(a2)
+    array([[0.+1.j, 0.-1.j],
+           [0.+2.j, 0.-2.j]])
+
+    ``homogeneous_eigvals=True`` argument effectively separates each eigenvalue into a
+    numerator-denominator pair:
+
+    >>> a = np.array([[3., 0., 0.],
+    ...               [0., 8., 0.],
+    ...               [0., 0., 7.]])
+    >>> b = 2*np.eye(3)
+    >>> linalg.eigvals(a, b, homogeneous_eigvals=True)
+    array([[3.+0.j, 8.+0.j, 7.+0.j],
+           [2.+0.j, 2.+0.j, 2.+0.j]])
+
+    **Eigenvectors**: by default, ``eig`` returns normalized right eigenvectors in
+    columns of the second return array
+
+    >>> a = np.array([[0., -1.],
+    ...               [1., 0.]])
+    >>> w, vr = linalg.eig(a)
+    >>> w      # eigenvalues
+    array([0. + 1.j, 0. - 1.j])
+    >>> vr     # normalized right eigenvectors
+    array([[0.70710678 + 0.j        , 0.70710678 - 0.j        ],
+           [0.         - 0.70710678j, 0.         + 0.70710678j]])
+
+    Verify that columns of ``vr`` are indeed eigenvectors:
+
+    >>> a @ vr[:, 0] - w[0] * vr[:, 0]
+    array([0.+0.j, 0.+0.j])
+    >>> a @ vr[:, 1] - w[1] * vr[:, 1]
+    array([0.+0.j, 0.+0.j])
+
+    To compute the normalized left eigenvectors, use ``left=True``:
+
+    >>> w, vl, vr = linalg.eig(a, left=True, right=True)
+    >>> vl * np.sqrt(2)   # ``vl`` is normalized left eigenvectors
+    array([[-1. + 0.j, -1. - 0.j],
+           [ 0. + 1.j,  0. - 1.j]])
+    >>> vr * np.sqrt(2)   # ``vr`` is normalized right eigenvectors
+    array([[1. + 0.j, 1. + 0.j],
+           [0. - 1.j, 0. + 1.j]])
+    """
+    # basic sanity checks of the input matrix
+    a1 = _asarray_validated(a, check_finite=check_finite)
+    _deprecate_dtypes("eig", a1)
+
+    if len(a1.shape) < 2 or a1.shape[-1] != a1.shape[-2]:
+        raise ValueError(
+            f"Expected a square matrix or a batch of square matrices. Got {a.shape = }"
+        )
+
+    # Also check if dtype is LAPACK compatible
+    a1, overwrite_a = _normalize_lapack_dtype(a1, overwrite_a)
+    a1, overwrite_a = _ensure_aligned_and_native(a1, overwrite_a)
+
+    overwrite_a = overwrite_a or (_datacopied(a1, a))
+    overwrite_a = overwrite_a and (a1.ndim == 2) and (a1.flags["F_CONTIGUOUS"])
+
+    # accommodate empty arrays
+    if a1.shape[-1] == 0 or a1.shape[-2] == 0:
+        batch_shape = a1.shape[:-2]
+        w_n, vr_n = eig(np.eye(2, dtype=a1.dtype))
+        w = np.empty(batch_shape + (0,), dtype=w_n.dtype)
+        w = _make_eigvals(w, None, homogeneous_eigvals)
+        vl = np.empty(batch_shape + (0, 0), dtype=vr_n.dtype)
+        vr = np.empty(batch_shape + (0, 0), dtype=vr_n.dtype)
+        if not (left or right):
+            return w
+        if left:
+            if right:
+                return w, vl, vr
+            return w, vl
+        return w, vr
+
+    if b is None:
+        # regular eigenvalue problem
+        w, beta, vl, vr, err_lst  = _batched_linalg._eig(
+            a1, left, right, overwrite_a, False
+        )
+
+        if err_lst:
+            _check_format_errors_warnings("geev", err_lst)
+
+    else:
+        # b is not None: generalized eigenvalue problem
+
+        b1 = _asarray_validated(b, check_finite=check_finite)
+        _deprecate_dtypes("eig", b1)
+
+        a1, b1 = _ensure_dtype_cdsz(a1, b1)  # NB: makes a1.dtype == b1.dtype, if needed
+        b1, overwrite_b = _ensure_aligned_and_native(b1, overwrite_b)
+
+        if len(b1.shape) < 2 or b1.shape[-1] != b1.shape[-2]:
+            raise ValueError('expected square matrix')
+
+        if a1.shape[-1] != b1.shape[-1]:
+            raise ValueError('a and b must have the same shape')
+
+        # broadcast batch dimensions of b1 and a1
+        batch_shape = np.broadcast_shapes(a1.shape[:-2], b1.shape[:-2])
+        a1 = np.broadcast_to(a1, batch_shape + a1.shape[-2:])
+        b1 = np.broadcast_to(b1, batch_shape + b1.shape[-2:])
+
+        # check if we can work in-place (a1 might have been broadcast by b1)
+        overwrite_a = overwrite_a and (a1.ndim == 2)
+
+        overwrite_b = overwrite_b or (_datacopied(b1, b))
+        overwrite_b = overwrite_b and (b1.ndim == 2) and (b1.flags["F_CONTIGUOUS"])
+
+        w, beta, vl, vr, err_lst = _batched_linalg._eig(
+            a1, left, right, overwrite_a, overwrite_b, b1
+        )
+
+        if err_lst:
+            _check_format_errors_warnings("ggev", err_lst)
+
+        # eigenvectors returned by ?GGEV are NOT normalized
+        if right:
+            vr /= np.linalg.vector_norm(vr, axis=-2, keepdims=True)
+        if left:
+            vl /= np.linalg.vector_norm(vl, axis=-2, keepdims=True)
+
+    w = _make_eigvals(w, beta, homogeneous_eigvals)
+
+    # backwards compat: make eigvecs real if all eigenvalues have zero imaginary parts
+    a_is_real = a1.dtype in (np.float32, np.float64)
+    if a_is_real and (w.imag == 0).all():
+        if left:
+            vl = vl.real
+        if right:
+            vr = vr.real
+
+    if not (left or right):
+        return w
+    if left:
+        if right:
+            return w, vl, vr
+        return w, vl
+    return w, vr
+
+
+@_apply_over_batch(('a', 2), ('b', 2))
+def eigh(a, b=None, *, lower=True, eigvals_only=False, overwrite_a=False,
+         overwrite_b=False, type=1, check_finite=True, subset_by_index=None,
+         subset_by_value=None, driver=None):
+    """
+    Solve a standard or generalized eigenvalue problem for a complex
+    Hermitian or real symmetric matrix.
+
+    Find eigenvalues array ``w`` and optionally eigenvectors array ``v`` of
+    array ``a``, where ``b`` is positive definite such that for every
+    eigenvalue λ (i-th entry of w) and its eigenvector ``vi`` (i-th column of
+    ``v``) satisfies::
+
+                      a @ vi = λ * b @ vi
+        vi.conj().T @ a @ vi = λ
+        vi.conj().T @ b @ vi = 1
+
+    In the standard problem, ``b`` is assumed to be the identity matrix.
+
+    Parameters
+    ----------
+    a : (M, M) array_like
+        A complex Hermitian or real symmetric matrix whose eigenvalues and
+        eigenvectors will be computed.
+    b : (M, M) array_like, optional
+        A complex Hermitian or real symmetric definite positive matrix in.
+        If omitted, identity matrix is assumed.
+    lower : bool, optional
+        Whether the pertinent array data is taken from the lower or upper
+        triangle of ``a`` and, if applicable, ``b``. (Default: lower)
+    eigvals_only : bool, optional
+        Whether to calculate only eigenvalues and no eigenvectors.
+        (Default: both are calculated)
+    overwrite_a : bool, optional
+        Whether to overwrite data in ``a`` (may improve performance). Default is False.
+        See :ref:`tutorial_linalg_overwrite` for details.
+    overwrite_b : bool, optional
+        Whether to overwrite data in ``b`` (may improve performance). Default is False.
+        See :ref:`tutorial_linalg_overwrite` for details.
+    type : int, optional
+        For the generalized problems, this keyword specifies the problem type
+        to be solved for ``w`` and ``v`` (only takes 1, 2, 3 as possible
+        inputs)::
+
+            1 =>     a @ v = w @ b @ v
+            2 => a @ b @ v = w @ v
+            3 => b @ a @ v = w @ v
+
+        This keyword is ignored for standard problems.
+    check_finite : bool, optional
+        Whether to check that the input matrices contain only finite numbers.
+        Disabling may give a performance gain, but may result in problems
+        (crashes, non-termination) if the inputs do contain infinities or NaNs.
+    subset_by_index : iterable, optional
+        If provided, this two-element iterable defines the start and the end
+        indices of the desired eigenvalues (ascending order and 0-indexed).
+        To return only the second smallest to fifth smallest eigenvalues,
+        ``[1, 4]`` is used. ``[n-3, n-1]`` returns the largest three. Only
+        available with "evr", "evx", and "gvx" drivers. The entries are
+        directly converted to integers via ``int()``.
+    subset_by_value : iterable, optional
+        If provided, this two-element iterable defines the half-open interval
+        ``(a, b]`` that, if any, only the eigenvalues between these values
+        are returned. Only available with "evr", "evx", and "gvx" drivers. Use
+        ``np.inf`` for the unconstrained ends.
+    driver : str, optional
+        Defines which LAPACK driver should be used. Valid options are "ev",
+        "evd", "evr", "evx" for standard problems and "gv", "gvd", "gvx" for
+        generalized (where b is not None) problems. See the Notes section.
+        The default for standard problems is "evr". For generalized problems,
+        "gvd" is used for full set, and "gvx" for subset requested cases.
+
+    Returns
+    -------
+    w : (N,) ndarray
+        The N (N<=M) selected eigenvalues, in ascending order, each
+        repeated according to its multiplicity.
+    v : (M, N) ndarray
+        The normalized eigenvector corresponding to the eigenvalue ``w[i]`` is
+        the column ``v[:,i]``. Only returned if ``eigvals_only=False``.
+
+    Raises
+    ------
+    LinAlgError
+        If eigenvalue computation does not converge, an error occurred, or
+        b matrix is not definite positive. Note that if input matrices are
+        not symmetric or Hermitian, no error will be reported but results will
+        be wrong.
+
+    See Also
+    --------
+    eigvalsh : eigenvalues of symmetric or Hermitian arrays
+    eig : eigenvalues and right eigenvectors for non-symmetric arrays
+    eigh_tridiagonal : eigenvalues and right eigenvectors for
+        symmetric/Hermitian tridiagonal matrices
+
+    Notes
+    -----
+    This function does not check the input array for being Hermitian/symmetric
+    in order to allow for representing arrays with only their upper/lower
+    triangular parts. Also, note that even though not taken into account,
+    finiteness check applies to the whole array and unaffected by "lower"
+    keyword.
+
+    This function uses LAPACK drivers for computations in all possible keyword
+    combinations, prefixed with ``sy`` if arrays are real and ``he`` if
+    complex, e.g., a float array with "evr" driver is solved via
+    "syevr", complex arrays with "gvx" driver problem is solved via "hegvx"
+    etc.
+
+    As a brief summary, the slowest and the most robust driver is the
+    classical ``ev`` which uses symmetric QR. ``evr`` is seen as
+    the optimal choice for the most general cases. However, there are certain
+    occasions that ``evd`` computes faster at the expense of more
+    memory usage. ``evx``, while still being faster than ``ev``,
+    often performs worse than the rest except when very few eigenvalues are
+    requested for large arrays though there is still no performance guarantee.
+
+    Note that the underlying LAPACK algorithms are different depending on whether
+    `eigvals_only` is True or False --- thus the eigenvalues may differ
+    depending on whether eigenvectors are requested or not. The difference is
+    generally of the order of machine epsilon times the largest eigenvalue,
+    so is likely only visible for zero or nearly zero eigenvalues.
+
+    For the generalized problem, normalization with respect to the given
+    type argument::
+
+            type 1 and 3 :      v.conj().T @ a @ v = w
+            type 2       : inv(v).conj().T @ a @ inv(v) = w
+
+            type 1 or 2  :      v.conj().T @ b @ v  = I
+            type 3       : v.conj().T @ inv(b) @ v  = I
+
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy.linalg import eigh
+    >>> A = np.array([[6, 3, 1, 5], [3, 0, 5, 1], [1, 5, 6, 2], [5, 1, 2, 2]])
+    >>> w, v = eigh(A)
+    >>> np.allclose(A @ v - v @ np.diag(w), np.zeros((4, 4)))
+    True
+
+    Request only the eigenvalues
+
+    >>> w = eigh(A, eigvals_only=True)
+
+    Request eigenvalues that are less than 10.
+
+    >>> A = np.array([[34, -4, -10, -7, 2],
+    ...               [-4, 7, 2, 12, 0],
+    ...               [-10, 2, 44, 2, -19],
+    ...               [-7, 12, 2, 79, -34],
+    ...               [2, 0, -19, -34, 29]])
+    >>> eigh(A, eigvals_only=True, subset_by_value=[-np.inf, 10])
+    array([6.69199443e-07, 9.11938152e+00])
+
+    Request the second smallest eigenvalue and its eigenvector
+
+    >>> w, v = eigh(A, subset_by_index=[1, 1])
+    >>> w
+    array([9.11938152])
+    >>> v.shape  # only a single column is returned
+    (5, 1)
+
+    """
+    # set lower
+    uplo = 'L' if lower else 'U'
+    # Set job for Fortran routines
+    _job = 'N' if eigvals_only else 'V'
+
+    drv_str = [None, "ev", "evd", "evr", "evx", "gv", "gvd", "gvx"]
+    if driver not in drv_str:
+        raise ValueError('"{}" is unknown. Possible values are "None", "{}".'
+                         ''.format(driver, '", "'.join(drv_str[1:])))
+
+    a1 = _asarray_validated(a, check_finite=check_finite)
+    if len(a1.shape) != 2 or a1.shape[0] != a1.shape[1]:
+        raise ValueError('expected square "a" matrix')
+
+    # accommodate square empty matrices
+    if a1.size == 0:
+        w_n, v_n = eigh(np.eye(2, dtype=a1.dtype))
+
+        w = np.empty_like(a1, shape=(0,), dtype=w_n.dtype)
+        v = np.empty_like(a1, shape=(0, 0), dtype=v_n.dtype)
+        if eigvals_only:
+            return w
+        else:
+            return w, v
+
+    overwrite_a = overwrite_a or (_datacopied(a1, a))
+    cplx = True if iscomplexobj(a1) else False
+    n = a1.shape[0]
+    drv_args = {'overwrite_a': overwrite_a}
+
+    if b is not None:
+        b1 = _asarray_validated(b, check_finite=check_finite)
+        overwrite_b = overwrite_b or _datacopied(b1, b)
+        if len(b1.shape) != 2 or b1.shape[0] != b1.shape[1]:
+            raise ValueError('expected square "b" matrix')
+
+        if b1.shape != a1.shape:
+            raise ValueError(f"wrong b dimensions {b1.shape}, should be {a1.shape}")
+
+        if type not in [1, 2, 3]:
+            raise ValueError('"type" keyword only accepts 1, 2, and 3.')
+
+        cplx = True if iscomplexobj(b1) else (cplx or False)
+        drv_args.update({'overwrite_b': overwrite_b, 'itype': type})
+
+    subset = (subset_by_index is not None) or (subset_by_value is not None)
+
+    # Both subsets can't be given
+    if subset_by_index and subset_by_value:
+        raise ValueError('Either index or value subset can be requested.')
+
+    # Check indices if given
+    if subset_by_index:
+        lo, hi = (int(x) for x in subset_by_index)
+        if not (0 <= lo <= hi < n):
+            raise ValueError('Requested eigenvalue indices are not valid. '
+                             f'Valid range is [0, {n-1}] and start <= end, but '
+                             f'start={lo}, end={hi} is given')
+        # fortran is 1-indexed
+        drv_args.update({'range': 'I', 'il': lo + 1, 'iu': hi + 1})
+
+    if subset_by_value:
+        lo, hi = subset_by_value
+        if not (-inf <= lo < hi <= inf):
+            raise ValueError('Requested eigenvalue bounds are not valid. '
+                             'Valid range is (-inf, inf) and low < high, but '
+                             f'low={lo}, high={hi} is given')
+
+        drv_args.update({'range': 'V', 'vl': lo, 'vu': hi})
+
+    # fix prefix for lapack routines
+    pfx = 'he' if cplx else 'sy'
+
+    # decide on the driver if not given
+    # first early exit on incompatible choice
+    if driver:
+        if b is None and (driver in ["gv", "gvd", "gvx"]):
+            raise ValueError(f'{driver} requires input b array to be supplied '
+                             'for generalized eigenvalue problems.')
+        if (b is not None) and (driver in ['ev', 'evd', 'evr', 'evx']):
+            raise ValueError(f'"{driver}" does not accept input b array '
+                             'for standard eigenvalue problems.')
+        if subset and (driver in ["ev", "evd", "gv", "gvd"]):
+            raise ValueError(f'"{driver}" cannot compute subsets of eigenvalues')
+
+    # Default driver is evr and gvd
+    else:
+        driver = "evr" if b is None else ("gvx" if subset else "gvd")
+
+    lwork_spec = {
+                  'syevd': ['lwork', 'liwork'],
+                  'syevr': ['lwork', 'liwork'],
+                  'heevd': ['lwork', 'liwork', 'lrwork'],
+                  'heevr': ['lwork', 'lrwork', 'liwork'],
+                  }
+
+    if b is None:  # Standard problem
+        drv, drvlw = get_lapack_funcs((pfx + driver, pfx+driver+'_lwork'),
+                                      [a1])
+        clw_args = {'n': n, 'lower': lower}
+        if driver == 'evd':
+            clw_args.update({'compute_v': 0 if _job == "N" else 1})
+
+        lw = _compute_lwork(drvlw, **clw_args)
+        # Multiple lwork vars
+        if isinstance(lw, tuple):
+            lwork_args = dict(zip(lwork_spec[pfx+driver], lw))
+        else:
+            lwork_args = {'lwork': lw}
+
+        drv_args.update({'lower': lower, 'compute_v': 0 if _job == "N" else 1})
+        w, v, *other_args, info = drv(a=a1, **drv_args, **lwork_args)
+
+    else:  # Generalized problem
+        # 'gvd' doesn't have lwork query
+        if driver == "gvd":
+            drv = get_lapack_funcs(pfx + "gvd", [a1, b1])
+            lwork_args = {}
+        else:
+            drv, drvlw = get_lapack_funcs((pfx + driver, pfx+driver+'_lwork'),
+                                          [a1, b1])
+            # generalized drivers use uplo instead of lower
+            lw = _compute_lwork(drvlw, n, uplo=uplo)
+            lwork_args = {'lwork': lw}
+
+        drv_args.update({'uplo': uplo, 'jobz': _job})
+
+        w, v, *other_args, info = drv(a=a1, b=b1, **drv_args, **lwork_args)
+
+    # m is always the first extra argument
+    w = w[:other_args[0]] if subset else w
+    v = v[:, :other_args[0]] if (subset and not eigvals_only) else v
+
+    # Check if we had a  successful exit
+    if info == 0:
+        if eigvals_only:
+            return w
+        else:
+            return w, v
+    else:
+        if info < -1:
+            raise LinAlgError(f'Illegal value in argument {-info} of internal '
+                              f'{drv.typecode + pfx + driver}')
+        elif info > n:
+            raise LinAlgError(f'The leading minor of order {info-n} of B is not '
+                              'positive definite. The factorization of B '
+                              'could not be completed and no eigenvalues '
+                              'or eigenvectors were computed.')
+        else:
+            drv_err = {'ev': 'The algorithm failed to converge; {} '
+                             'off-diagonal elements of an intermediate '
+                             'tridiagonal form did not converge to zero.',
+                       'evx': '{} eigenvectors failed to converge.',
+                       'evd': 'The algorithm failed to compute an eigenvalue '
+                              'while working on the submatrix lying in rows '
+                              'and columns {0}/{1} through mod({0},{1}).',
+                       'evr': 'Internal Error.'
+                       }
+            if driver in ['ev', 'gv']:
+                msg = drv_err['ev'].format(info)
+            elif driver in ['evx', 'gvx']:
+                msg = drv_err['evx'].format(info)
+            elif driver in ['evd', 'gvd']:
+                if eigvals_only:
+                    msg = drv_err['ev'].format(info)
+                else:
+                    msg = drv_err['evd'].format(info, n+1)
+            else:
+                msg = drv_err['evr']
+
+            raise LinAlgError(msg)
+
+
+_conv_dict = {0: 0, 1: 1, 2: 2,
+              'all': 0, 'value': 1, 'index': 2,
+              'a': 0, 'v': 1, 'i': 2}
+
+
+def _check_select(select, select_range, max_ev, max_len):
+    """Check that select is valid, convert to Fortran style."""
+    if isinstance(select, str):
+        select = select.lower()
+    try:
+        select = _conv_dict[select]
+    except KeyError as e:
+        raise ValueError('invalid argument for select') from e
+    vl, vu = 0., 1.
+    il = iu = 1
+    if select != 0:  # (non-all)
+        sr = asarray(select_range)
+        if sr.ndim != 1 or sr.size != 2 or sr[1] < sr[0]:
+            raise ValueError('select_range must be a 2-element array-like '
+                             'in nondecreasing order')
+        if select == 1:  # (value)
+            vl, vu = sr
+            if max_ev == 0:
+                max_ev = max_len
+        else:  # 2 (index)
+            if sr.dtype.char.lower() not in 'hilqp':
+                raise ValueError(
+                    f'when using select="i", select_range must '
+                    f'contain integers, got dtype {sr.dtype} ({sr.dtype.char})'
+                )
+            # translate Python (0 ... N-1) into Fortran (1 ... N) with + 1
+            il, iu = sr + 1
+            if min(il, iu) < 1 or max(il, iu) > max_len:
+                raise ValueError('select_range out of bounds')
+            max_ev = iu - il + 1
+    return select, vl, vu, il, iu, max_ev
+
+
+@_apply_over_batch(('a_band', 2))
+def eig_banded(a_band, lower=False, eigvals_only=False, overwrite_a_band=False,
+               select='a', select_range=None, max_ev=0, check_finite=True):
+    """
+    Solve real symmetric or complex Hermitian band matrix eigenvalue problem.
+
+    Find eigenvalues w and optionally right eigenvectors v of a::
+
+        a v[:,i] = w[i] v[:,i]
+        v.H v    = identity
+
+    The matrix a is stored in a_band either in lower diagonal or upper
+    diagonal ordered form::
+
+        a_band[u + i - j, j] == a[i,j]        (if upper form; i <= j)
+        a_band[    i - j, j] == a[i,j]        (if lower form; i >= j)
+
+    where u is the number of bands above the diagonal.
+
+    Example of a_band (shape of a is (6,6), u=2)::
+
+        upper form:
+        *   *   a02 a13 a24 a35
+        *   a01 a12 a23 a34 a45
+        a00 a11 a22 a33 a44 a55
+
+        lower form:
+        a00 a11 a22 a33 a44 a55
+        a10 a21 a32 a43 a54 *
+        a20 a31 a42 a53 *   *
+
+    Cells marked with * are not used.
+
+    Parameters
+    ----------
+    a_band : (u+1, M) array_like
+        The bands of the M by M matrix a.
+    lower : bool, optional
+        Is the matrix in the lower form. (Default is upper form)
+    eigvals_only : bool, optional
+        Compute only the eigenvalues and no eigenvectors.
+        (Default: calculate also eigenvectors)
+    overwrite_a_band : bool, optional
+        Discard data in a_band (may enhance performance)
+        See :ref:`tutorial_linalg_overwrite` for details.
+    select : {'a', 'v', 'i'}, optional
+        Which eigenvalues to calculate
+
+        ======  ========================================
+        select  calculated
+        ======  ========================================
+        'a'     All eigenvalues
+        'v'     Eigenvalues in the interval (min, max]
+        'i'     Eigenvalues with indices min <= i <= max
+        ======  ========================================
+    select_range : (min, max), optional
+        Range of selected eigenvalues
+    max_ev : int, optional
+        For select=='v', maximum number of eigenvalues expected.
+        For other values of select, has no meaning.
+
+        In doubt, leave this parameter untouched.
+
+    check_finite : bool, optional
+        Whether to check that the input matrix contains only finite numbers.
+        Disabling may give a performance gain, but may result in problems
+        (crashes, non-termination) if the inputs do contain infinities or NaNs.
+
+    Returns
+    -------
+    w : (M,) ndarray
+        The eigenvalues, in ascending order, each repeated according to its
+        multiplicity.
+    v : (M, M) float or complex ndarray
+        The normalized eigenvector corresponding to the eigenvalue w[i] is
+        the column v[:,i]. Only returned if ``eigvals_only=False``.
+
+    Raises
+    ------
+    LinAlgError
+        If eigenvalue computation does not converge.
+
+    See Also
+    --------
+    eigvals_banded : eigenvalues for symmetric/Hermitian band matrices
+    eig : eigenvalues and right eigenvectors of general arrays.
+    eigh : eigenvalues and right eigenvectors for symmetric/Hermitian arrays
+    eigh_tridiagonal : eigenvalues and right eigenvectors for
+        symmetric/Hermitian tridiagonal matrices
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy.linalg import eig_banded
+    >>> A = np.array([[1, 5, 2, 0], [5, 2, 5, 2], [2, 5, 3, 5], [0, 2, 5, 4]])
+    >>> Ab = np.array([[1, 2, 3, 4], [5, 5, 5, 0], [2, 2, 0, 0]])
+    >>> w, v = eig_banded(Ab, lower=True)
+    >>> np.allclose(A @ v - v @ np.diag(w), np.zeros((4, 4)))
+    True
+    >>> w = eig_banded(Ab, lower=True, eigvals_only=True)
+    >>> w
+    array([-4.26200532, -2.22987175,  3.95222349, 12.53965359])
+
+    Request only the eigenvalues between ``[-3, 4]``
+
+    >>> w, v = eig_banded(Ab, lower=True, select='v', select_range=[-3, 4])
+    >>> w
+    array([-2.22987175,  3.95222349])
+
+    """
+    if eigvals_only or overwrite_a_band:
+        a1 = _asarray_validated(a_band, check_finite=check_finite)
+        overwrite_a_band = overwrite_a_band or (_datacopied(a1, a_band))
+    else:
+        a1 = array(a_band)
+        if issubclass(a1.dtype.type, inexact) and not isfinite(a1).all():
+            raise ValueError("array must not contain infs or NaNs")
+        overwrite_a_band = 1
+
+    if len(a1.shape) != 2:
+        raise ValueError('expected a 2-D array')
+
+    # accommodate square empty matrices
+    if a1.size == 0:
+        w_n, v_n = eig_banded(np.array([[0, 0], [1, 1]], dtype=a1.dtype))
+
+        w = np.empty_like(a1, shape=(0,), dtype=w_n.dtype)
+        v = np.empty_like(a1, shape=(0, 0), dtype=v_n.dtype)
+        if eigvals_only:
+            return w
+        else:
+            return w, v
+
+    select, vl, vu, il, iu, max_ev = _check_select(
+        select, select_range, max_ev, a1.shape[1])
+
+    del select_range
+    if select == 0:
+        if a1.dtype.char in 'GFD':
+            # FIXME: implement this somewhen, for now go with builtin values
+            # FIXME: calc optimal lwork by calling ?hbevd(lwork=-1)
+            #        or by using calc_lwork.f ???
+            # lwork = calc_lwork.hbevd(bevd.typecode, a1.shape[0], lower)
+            internal_name = 'hbevd'
+        else:  # a1.dtype.char in 'fd':
+            # FIXME: implement this somewhen, for now go with builtin values
+            #         see above
+            # lwork = calc_lwork.sbevd(bevd.typecode, a1.shape[0], lower)
+            internal_name = 'sbevd'
+        bevd, = get_lapack_funcs((internal_name,), (a1,))
+        w, v, info = bevd(a1, compute_v=not eigvals_only,
+                          lower=lower, overwrite_ab=overwrite_a_band)
+    else:  # select in [1, 2]
+        if eigvals_only:
+            max_ev = 1
+        # calculate optimal abstol for dsbevx (see manpage)
+        if a1.dtype.char in 'fF':  # single precision
+            lamch, = get_lapack_funcs(('lamch',), (array(0, dtype='f'),))
+        else:
+            lamch, = get_lapack_funcs(('lamch',), (array(0, dtype='d'),))
+        abstol = 2 * lamch('s')
+        if a1.dtype.char in 'GFD':
+            internal_name = 'hbevx'
+        else:  # a1.dtype.char in 'gfd'
+            internal_name = 'sbevx'
+        bevx, = get_lapack_funcs((internal_name,), (a1,))
+        w, v, m, ifail, info = bevx(
+            a1, vl, vu, il, iu, compute_v=not eigvals_only, mmax=max_ev,
+            range=select, lower=lower, overwrite_ab=overwrite_a_band,
+            abstol=abstol)
+        # crop off w and v
+        w = w[:m]
+        if not eigvals_only:
+            v = v[:, :m]
+    _check_info(info, internal_name)
+
+    if eigvals_only:
+        return w
+    return w, v
+
+
+def eigvals(a, b=None, overwrite_a=False, overwrite_b=False, check_finite=True,
+            homogeneous_eigvals=False):
+    r"""
+    Compute eigenvalues from an ordinary or generalized eigenvalue problem.
+
+    Find eigenvalues, ``w``, of a general matrix::
+
+        a @ vr[:, i] = w[i] * b  @ vr[:, i]
+
+    Parameters
+    ----------
+    a : (..., M, M) array_like
+        A complex or real matrix (or a stack of matrices), whose eigenvalues will be
+        computed.
+    b : (..., M, M) array_like, optional
+        Right-hand side matrix (or a stack of matrices) in a generalized eigenvalue
+        problem. If omitted (default), identity matrix is assumed.
+    overwrite_a : bool, optional
+        Whether to overwrite data in a (may improve performance). Default is False.
+    overwrite_b : bool, optional
+        Whether to overwrite data in b (may improve performance). Default is False.
+        See :ref:`tutorial_linalg_overwrite` for details.
+    check_finite : bool, optional
+        Whether to check that the input matrices contain only finite numbers.
+        Disabling may give a performance gain, but may result in problems
+        (crashes, non-termination) if the inputs do contain infinities
+        or NaNs.
+    homogeneous_eigvals : bool, optional
+        If True, return the eigenvalues in homogeneous coordinates.
+        In this case ``w`` is a ``(2, M)`` array so that::
+
+            w[1, i] * a @ vr[:, i] = w[0, i] * b @ vr[:, i]
+
+        This option is sometimes useful for generalized eigenvalue problems,
+        ``b is not None``, where an eigenvalue, :math:`\lambda = \alpha / \beta`,
+        can over- or underflow; typically, :\math:`\alpha` and :math:`\beta` are of the
+        order of ``norm(a)`` and ``norm(b)``, respectively.
+
+        Default is False.
+
+    Returns
+    -------
+    w : (..., M,) or (..., 2, M) complex ndarray
+        The eigenvalues, each repeated according to its multiplicity
+        but not in any specific order. The shape is ``(..., M)`` unless
+        ``homogeneous_eigvals=True``.
+
+    Raises
+    ------
+    LinAlgError
+        If eigenvalue computation does not converge
+
+    See Also
+    --------
+    eig : eigenvalues and right eigenvectors of general arrays.
+    eigvalsh : eigenvalues of symmetric or Hermitian arrays
+    eigvals_banded : eigenvalues for symmetric/Hermitian band matrices
+    eigvalsh_tridiagonal : eigenvalues of symmetric/Hermitian tridiagonal
+        matrices
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy import linalg
+    >>> a = np.array([[0., -1.],
+    ...               [1.,  0.]])
+
+    Compute the eigenvalues (``eigvals`` is the same as ``eig(a, right=False)``)
+
+    >>> linalg.eigvals(a)
+    array([0.+1.j, 0.-1.j])
+
+    Solve a generalized eigenvalue problem:
+
+    >>> b = np.array([[0., 1.], [1., 1.]])
+    >>> linalg.eigvals(a, b)
+    array([ 1.+0.j, -1.+0.j])
+
+    Inputs with ``ndim > 2`` are interpreted as a batch of matrices
+
+    >>> a2 = np.stack((a, 2*a))
+    >>> linalg.eigvals(a2)
+    array([[0.+1.j, 0.-1.j],
+           [0.+2.j, 0.-2.j]])
+
+    ``homogeneous_eigvals=True`` argument effectively separates each eigenvalue into a
+    numerator-denominator pair:
+
+    >>> a = np.array([[3., 0., 0.],
+    ...               [0., 8., 0.],
+    ...               [0., 0., 7.]])
+    >>> b = 2*np.eye(3)
+    >>> linalg.eigvals(a, b, homogeneous_eigvals=True)
+    array([[3.+0.j, 8.+0.j, 7.+0.j],
+           [2.+0.j, 2.+0.j, 2.+0.j]])
+    """
+    return eig(a, b=b, left=0, right=0, overwrite_a=overwrite_a,
+                overwrite_b=overwrite_b, check_finite=check_finite,
+                homogeneous_eigvals=homogeneous_eigvals)
+
+
+@_apply_over_batch(('a', 2), ('b', 2))
+def eigvalsh(a, b=None, *, lower=True, overwrite_a=False,
+             overwrite_b=False, type=1, check_finite=True, subset_by_index=None,
+             subset_by_value=None, driver=None):
+    """
+    Solves a standard or generalized eigenvalue problem for a complex
+    Hermitian or real symmetric matrix.
+
+    Find eigenvalues array ``w`` of array ``a``, where ``b`` is positive
+    definite such that for every eigenvalue λ (i-th entry of w) and its
+    eigenvector vi (i-th column of v) satisfies::
+
+                      a @ vi = λ * b @ vi
+        vi.conj().T @ a @ vi = λ
+        vi.conj().T @ b @ vi = 1
+
+    In the standard problem, b is assumed to be the identity matrix.
+
+    Parameters
+    ----------
+    a : (M, M) array_like
+        A complex Hermitian or real symmetric matrix whose eigenvalues will
+        be computed.
+    b : (M, M) array_like, optional
+        A complex Hermitian or real symmetric definite positive matrix in.
+        If omitted, identity matrix is assumed.
+    lower : bool, optional
+        Whether the pertinent array data is taken from the lower or upper
+        triangle of ``a`` and, if applicable, ``b``. (Default: lower)
+    overwrite_a : bool, optional
+        Whether to overwrite data in ``a`` (may improve performance). Default is False.
+        See :ref:`tutorial_linalg_overwrite` for details.
+    overwrite_b : bool, optional
+        Whether to overwrite data in ``b`` (may improve performance). Default
+        is False.
+        See :ref:`tutorial_linalg_overwrite` for details.
+    type : int, optional
+        For the generalized problems, this keyword specifies the problem type
+        to be solved for ``w`` and ``v`` (only takes 1, 2, 3 as possible
+        inputs)::
+
+            1 =>     a @ v = w @ b @ v
+            2 => a @ b @ v = w @ v
+            3 => b @ a @ v = w @ v
+
+        This keyword is ignored for standard problems.
+    check_finite : bool, optional
+        Whether to check that the input matrices contain only finite numbers.
+        Disabling may give a performance gain, but may result in problems
+        (crashes, non-termination) if the inputs do contain infinities or NaNs.
+    subset_by_index : iterable, optional
+        If provided, this two-element iterable defines the start and the end
+        indices of the desired eigenvalues (ascending order and 0-indexed).
+        To return only the second smallest to fifth smallest eigenvalues,
+        ``[1, 4]`` is used. ``[n-3, n-1]`` returns the largest three. Only
+        available with "evr", "evx", and "gvx" drivers. The entries are
+        directly converted to integers via ``int()``.
+    subset_by_value : iterable, optional
+        If provided, this two-element iterable defines the half-open interval
+        ``(a, b]`` that, if any, only the eigenvalues between these values
+        are returned. Only available with "evr", "evx", and "gvx" drivers. Use
+        ``np.inf`` for the unconstrained ends.
+    driver : str, optional
+        Defines which LAPACK driver should be used. Valid options are "ev",
+        "evd", "evr", "evx" for standard problems and "gv", "gvd", "gvx" for
+        generalized (where b is not None) problems. See the Notes section of
+        `scipy.linalg.eigh`.
+
+    Returns
+    -------
+    w : (N,) ndarray
+        The N (N<=M) selected eigenvalues, in ascending order, each
+        repeated according to its multiplicity.
+
+    Raises
+    ------
+    LinAlgError
+        If eigenvalue computation does not converge, an error occurred, or
+        b matrix is not definite positive. Note that if input matrices are
+        not symmetric or Hermitian, no error will be reported but results will
+        be wrong.
+
+    See Also
+    --------
+    eigh : eigenvalues and right eigenvectors for symmetric/Hermitian arrays
+    eigvals : eigenvalues of general arrays
+    eigvals_banded : eigenvalues for symmetric/Hermitian band matrices
+    eigvalsh_tridiagonal : eigenvalues of symmetric/Hermitian tridiagonal
+        matrices
+
+    Notes
+    -----
+    This function does not check the input array for being Hermitian/symmetric
+    in order to allow for representing arrays with only their upper/lower
+    triangular parts.
+
+    This function serves as a one-liner shorthand for `scipy.linalg.eigh` with
+    the option ``eigvals_only=True`` to get the eigenvalues and not the
+    eigenvectors. Here it is kept as a legacy convenience. It might be
+    beneficial to use the main function to have full control and to be a bit
+    more pythonic.
+
+    Examples
+    --------
+    For more examples see `scipy.linalg.eigh`.
+
+    >>> import numpy as np
+    >>> from scipy.linalg import eigvalsh
+    >>> A = np.array([[6, 3, 1, 5], [3, 0, 5, 1], [1, 5, 6, 2], [5, 1, 2, 2]])
+    >>> w = eigvalsh(A)
+    >>> w
+    array([-3.74637491, -0.76263923,  6.08502336, 12.42399079])
+
+    """
+    return eigh(a, b=b, lower=lower, eigvals_only=True, overwrite_a=overwrite_a,
+                overwrite_b=overwrite_b, type=type, check_finite=check_finite,
+                subset_by_index=subset_by_index, subset_by_value=subset_by_value,
+                driver=driver)
+
+
+@_apply_over_batch(('a_band', 2))
+def eigvals_banded(a_band, lower=False, overwrite_a_band=False,
+                   select='a', select_range=None, check_finite=True):
+    """
+    Solve real symmetric or complex Hermitian band matrix eigenvalue problem.
+
+    Find eigenvalues w of a::
+
+        a v[:,i] = w[i] v[:,i]
+        v.H v    = identity
+
+    The matrix a is stored in a_band either in lower diagonal or upper
+    diagonal ordered form::
+
+        a_band[u + i - j, j] == a[i,j]        (if upper form; i <= j)
+        a_band[    i - j, j] == a[i,j]        (if lower form; i >= j)
+
+    where u is the number of bands above the diagonal.
+
+    Example of a_band (shape of a is (6,6), u=2)::
+
+        upper form:
+        *   *   a02 a13 a24 a35
+        *   a01 a12 a23 a34 a45
+        a00 a11 a22 a33 a44 a55
+
+        lower form:
+        a00 a11 a22 a33 a44 a55
+        a10 a21 a32 a43 a54 *
+        a20 a31 a42 a53 *   *
+
+    Cells marked with * are not used.
+
+    Parameters
+    ----------
+    a_band : (u+1, M) array_like
+        The bands of the M by M matrix a.
+    lower : bool, optional
+        Is the matrix in the lower form. (Default is upper form)
+    overwrite_a_band : bool, optional
+        Discard data in a_band (may enhance performance)
+        See :ref:`tutorial_linalg_overwrite` for details.
+    select : {'a', 'v', 'i'}, optional
+        Which eigenvalues to calculate
+
+        ======  ========================================
+        select  calculated
+        ======  ========================================
+        'a'     All eigenvalues
+        'v'     Eigenvalues in the interval (min, max]
+        'i'     Eigenvalues with indices min <= i <= max
+        ======  ========================================
+    select_range : (min, max), optional
+        Range of selected eigenvalues
+    check_finite : bool, optional
+        Whether to check that the input matrix contains only finite numbers.
+        Disabling may give a performance gain, but may result in problems
+        (crashes, non-termination) if the inputs do contain infinities or NaNs.
+
+    Returns
+    -------
+    w : (M,) ndarray
+        The eigenvalues, in ascending order, each repeated according to its
+        multiplicity.
+
+    Raises
+    ------
+    LinAlgError
+        If eigenvalue computation does not converge.
+
+    See Also
+    --------
+    eig_banded : eigenvalues and right eigenvectors for symmetric/Hermitian
+        band matrices
+    eigvalsh_tridiagonal : eigenvalues of symmetric/Hermitian tridiagonal
+        matrices
+    eigvals : eigenvalues of general arrays
+    eigh : eigenvalues and right eigenvectors for symmetric/Hermitian arrays
+    eig : eigenvalues and right eigenvectors for non-symmetric arrays
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy.linalg import eigvals_banded
+    >>> A = np.array([[1, 5, 2, 0], [5, 2, 5, 2], [2, 5, 3, 5], [0, 2, 5, 4]])
+    >>> Ab = np.array([[1, 2, 3, 4], [5, 5, 5, 0], [2, 2, 0, 0]])
+    >>> w = eigvals_banded(Ab, lower=True)
+    >>> w
+    array([-4.26200532, -2.22987175,  3.95222349, 12.53965359])
+    """
+    return eig_banded(a_band, lower=lower, eigvals_only=1,
+                      overwrite_a_band=overwrite_a_band, select=select,
+                      select_range=select_range, check_finite=check_finite)
+
+
+@_apply_over_batch(('d', 1), ('e', 1))
+def eigvalsh_tridiagonal(d, e, select='a', select_range=None,
+                         check_finite=True, tol=0., lapack_driver='auto'):
+    """
+    Solve eigenvalue problem for a real symmetric tridiagonal matrix.
+
+    Find eigenvalues `w` of ``a``::
+
+        a v[:,i] = w[i] v[:,i]
+        v.H v    = identity
+
+    For a real symmetric matrix ``a`` with diagonal elements `d` and
+    off-diagonal elements `e`.
+
+    Parameters
+    ----------
+    d : ndarray, shape (ndim,)
+        The diagonal elements of the array.
+    e : ndarray, shape (ndim-1,)
+        The off-diagonal elements of the array.
+    select : {'a', 'v', 'i'}, optional
+        Which eigenvalues to calculate
+
+        ======  ========================================
+        select  calculated
+        ======  ========================================
+        'a'     All eigenvalues
+        'v'     Eigenvalues in the interval (min, max]
+        'i'     Eigenvalues with indices min <= i <= max
+        ======  ========================================
+    select_range : (min, max), optional
+        Range of selected eigenvalues
+    check_finite : bool, optional
+        Whether to check that the input matrix contains only finite numbers.
+        Disabling may give a performance gain, but may result in problems
+        (crashes, non-termination) if the inputs do contain infinities or NaNs.
+    tol : float
+        The absolute tolerance to which each eigenvalue is required
+        (only used when ``lapack_driver='stebz'``).
+        An eigenvalue (or cluster) is considered to have converged if it
+        lies in an interval of this width. If <= 0. (default),
+        the value ``eps*|a|`` is used where eps is the machine precision,
+        and ``|a|`` is the 1-norm of the matrix ``a``.
+    lapack_driver : str
+        LAPACK function to use, can be 'auto', 'stemr', 'stebz',  'sterf',
+        'stev', or 'stevd'. When 'auto' (default), it will use 'stevd' if
+        ``select='a'`` and 'stebz' otherwise. 'sterf' and 'stev' can only
+        be used when ``select='a'``.
+
+    Returns
+    -------
+    w : (M,) ndarray
+        The eigenvalues, in ascending order, each repeated according to its
+        multiplicity.
+
+    Raises
+    ------
+    LinAlgError
+        If eigenvalue computation does not converge.
+
+    See Also
+    --------
+    eigh_tridiagonal : eigenvalues and right eigenvectors for
+        symmetric/Hermitian tridiagonal matrices
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy.linalg import eigvalsh_tridiagonal, eigvalsh
+    >>> d = 3*np.ones(4)
+    >>> e = -1*np.ones(3)
+    >>> w = eigvalsh_tridiagonal(d, e)
+    >>> A = np.diag(d) + np.diag(e, k=1) + np.diag(e, k=-1)
+    >>> w2 = eigvalsh(A)  # Verify with other eigenvalue routines
+    >>> np.allclose(w - w2, np.zeros(4))
+    True
+    """
+    return eigh_tridiagonal(
+        d, e, eigvals_only=True, select=select, select_range=select_range,
+        check_finite=check_finite, tol=tol, lapack_driver=lapack_driver)
+
+
+@_apply_over_batch(('d', 1), ('e', 1))
+def eigh_tridiagonal(d, e, eigvals_only=False, select='a', select_range=None,
+                     check_finite=True, tol=0., lapack_driver='auto'):
+    """
+    Solve eigenvalue problem for a real symmetric tridiagonal matrix.
+
+    Find eigenvalues `w` and optionally right eigenvectors `v` of ``a``::
+
+        a v[:,i] = w[i] v[:,i]
+        v.H v    = identity
+
+    For a real symmetric matrix ``a`` with diagonal elements `d` and
+    off-diagonal elements `e`.
+
+    Parameters
+    ----------
+    d : ndarray, shape (ndim,)
+        The diagonal elements of the array.
+    e : ndarray, shape (ndim-1,)
+        The off-diagonal elements of the array.
+    eigvals_only : bool, optional
+        Compute only the eigenvalues and no eigenvectors.
+        (Default: calculate also eigenvectors)
+    select : {'a', 'v', 'i'}, optional
+        Which eigenvalues to calculate
+
+        ======  ========================================
+        select  calculated
+        ======  ========================================
+        'a'     All eigenvalues
+        'v'     Eigenvalues in the interval (min, max]
+        'i'     Eigenvalues with indices min <= i <= max
+        ======  ========================================
+    select_range : (min, max), optional
+        Range of selected eigenvalues
+    check_finite : bool, optional
+        Whether to check that the input matrix contains only finite numbers.
+        Disabling may give a performance gain, but may result in problems
+        (crashes, non-termination) if the inputs do contain infinities or NaNs.
+    tol : float
+        The absolute tolerance to which each eigenvalue is required
+        (only used when 'stebz' is the `lapack_driver`).
+        An eigenvalue (or cluster) is considered to have converged if it
+        lies in an interval of this width. If <= 0. (default),
+        the value ``eps*|a|`` is used where eps is the machine precision,
+        and ``|a|`` is the 1-norm of the matrix ``a``.
+    lapack_driver : str
+        LAPACK function to use, can be 'auto', 'stemr', 'stebz', 'sterf',
+        'stev', or 'stevd'. When 'auto' (default), it will use 'stevd' if ``select='a'``
+        and 'stebz' otherwise. When 'stebz' is used to find the eigenvalues and
+        ``eigvals_only=False``, then a second LAPACK call (to ``?STEIN``) is
+        used to find the corresponding eigenvectors. 'sterf' can only be
+        used when ``eigvals_only=True`` and ``select='a'``. 'stev' can only
+        be used when ``select='a'``.
+
+    Returns
+    -------
+    w : (M,) ndarray
+        The eigenvalues, in ascending order, each repeated according to its
+        multiplicity.
+    v : (M, M) ndarray
+        The normalized eigenvector corresponding to the eigenvalue ``w[i]`` is
+        the column ``v[:,i]``. Only returned if ``eigvals_only=False``.
+
+    Raises
+    ------
+    LinAlgError
+        If eigenvalue computation does not converge.
+
+    See Also
+    --------
+    eigvalsh_tridiagonal : eigenvalues of symmetric/Hermitian tridiagonal
+        matrices
+    eig : eigenvalues and right eigenvectors for non-symmetric arrays
+    eigh : eigenvalues and right eigenvectors for symmetric/Hermitian arrays
+    eig_banded : eigenvalues and right eigenvectors for symmetric/Hermitian
+        band matrices
+
+    Notes
+    -----
+    This function makes use of LAPACK ``S/DSTEMR`` routines.
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy.linalg import eigh_tridiagonal
+    >>> d = 3*np.ones(4)
+    >>> e = -1*np.ones(3)
+    >>> w, v = eigh_tridiagonal(d, e)
+    >>> A = np.diag(d) + np.diag(e, k=1) + np.diag(e, k=-1)
+    >>> np.allclose(A @ v - v @ np.diag(w), np.zeros((4, 4)))
+    True
+    """
+    d = _asarray_validated(d, check_finite=check_finite)
+    e = _asarray_validated(e, check_finite=check_finite)
+    for check in (d, e):
+        if check.ndim != 1:
+            raise ValueError('expected a 1-D array')
+        if check.dtype.char in 'GFD':  # complex
+            raise TypeError('Only real arrays currently supported')
+    if d.size != e.size + 1:
+        raise ValueError(f'd ({d.size}) must have one more element than e ({e.size})')
+    select, vl, vu, il, iu, _ = _check_select(
+        select, select_range, 0, d.size)
+    if not isinstance(lapack_driver, str):
+        raise TypeError('lapack_driver must be str')
+    drivers = ('auto', 'stemr', 'sterf', 'stebz', 'stev', 'stevd')
+    if lapack_driver not in drivers:
+        raise ValueError(f'lapack_driver must be one of {drivers}, '
+                         f'got {lapack_driver}')
+    if lapack_driver == 'auto':
+        lapack_driver = 'stevd' if select == 0 else 'stebz'
+
+    # Quick exit for 1x1 case
+    if len(d) == 1:
+        if select == 1 and (not (vl < d[0] <= vu)):  # request by value
+            w = array([])
+            v = empty([1, 0], dtype=d.dtype)
+        else:  # all and request by index
+            w = array([d[0]], dtype=d.dtype)
+            v = array([[1.]], dtype=d.dtype)
+
+        if eigvals_only:
+            return w
+        else:
+            return w, v
+
+    func, = get_lapack_funcs((lapack_driver,), (d, e))
+    compute_v = not eigvals_only
+    if lapack_driver == 'sterf':
+        if select != 0:
+            raise ValueError('sterf can only be used when select == "a"')
+        if not eigvals_only:
+            raise ValueError('sterf can only be used when eigvals_only is '
+                             'True')
+        w, info = func(d, e)
+        m = len(w)
+    elif lapack_driver == 'stev':
+        if select != 0:
+            raise ValueError('stev can only be used when select == "a"')
+        w, v, info = func(d, e, compute_v=compute_v)
+        m = len(w)
+    elif lapack_driver == 'stevd':
+        if select != 0:
+            raise ValueError('stevd can only be used when select == "a"')
+        w, v, info = func(d, e, compute_v=compute_v)
+        m = len(w)
+    elif lapack_driver == 'stebz':
+        tol = float(tol)
+        internal_name = 'stebz'
+        stebz, = get_lapack_funcs((internal_name,), (d, e))
+        # If getting eigenvectors, needs to be block-ordered (B) instead of
+        # matrix-ordered (E), and we will reorder later
+        order = 'E' if eigvals_only else 'B'
+        m, w, iblock, isplit, info = stebz(d, e, select, vl, vu, il, iu, tol,
+                                           order)
+    else:   # 'stemr'
+        # ?STEMR annoyingly requires size N instead of N-1
+        e_ = empty(e.size+1, e.dtype)
+        e_[:-1] = e
+        stemr_lwork, = get_lapack_funcs(('stemr_lwork',), (d, e))
+        lwork, liwork, info = stemr_lwork(d, e_, select, vl, vu, il, iu,
+                                          compute_v=compute_v)
+        _check_info(info, 'stemr_lwork')
+        m, w, v, info = func(d, e_, select, vl, vu, il, iu,
+                             compute_v=compute_v, lwork=lwork, liwork=liwork)
+    _check_info(info, lapack_driver + ' (eigh_tridiagonal)')
+    w = w[:m]
+    if eigvals_only:
+        return w
+    else:
+        # Do we still need to compute the eigenvalues?
+        if lapack_driver == 'stebz':
+            func, = get_lapack_funcs(('stein',), (d, e))
+            v, info = func(d, e, w, iblock, isplit)
+            _check_info(info, 'stein (eigh_tridiagonal)',
+                        positive='%d eigenvectors failed to converge')
+            # Convert block-order to matrix-order
+            order = argsort(w)
+            w, v = w[order], v[:, order]
+        else:
+            v = v[:, :m]
+        return w, v
+
+
+def _check_info(info, driver, positive='did not converge (LAPACK info=%d)'):
+    """Check info return value."""
+    if info < 0:
+        raise ValueError(f'illegal value in argument {-info} of internal {driver}')
+    if info > 0 and positive:
+        raise LinAlgError(("%s " + positive) % (driver, info,))
+
+
+@_apply_over_batch(('a', 2))
+def hessenberg(a, calc_q=False, overwrite_a=False, check_finite=True):
+    """
+    Compute Hessenberg form of a matrix.
+
+    The Hessenberg decomposition is::
+
+        A = Q H Q^H
+
+    where `Q` is unitary/orthogonal and `H` has only zero elements below
+    the first sub-diagonal.
+
+    Parameters
+    ----------
+    a : (M, M) array_like
+        Matrix to bring into Hessenberg form.
+    calc_q : bool, optional
+        Whether to compute the transformation matrix.  Default is False.
+    overwrite_a : bool, optional
+        Whether to overwrite `a`; may improve performance. Default is False.
+        See :ref:`tutorial_linalg_overwrite` for details.
+    check_finite : bool, optional
+        Whether to check that the input matrix contains only finite numbers.
+        Disabling may give a performance gain, but may result in problems
+        (crashes, non-termination) if the inputs do contain infinities or NaNs.
+
+    Returns
+    -------
+    H : (M, M) ndarray
+        Hessenberg form of `a`.
+    Q : (M, M) ndarray
+        Unitary/orthogonal similarity transformation matrix ``A = Q H Q^H``.
+        Only returned if ``calc_q=True``.
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy.linalg import hessenberg
+    >>> A = np.array([[2, 5, 8, 7], [5, 2, 2, 8], [7, 5, 6, 6], [5, 4, 4, 8]])
+    >>> H, Q = hessenberg(A, calc_q=True)
+    >>> H
+    array([[  2.        , -11.65843866,   1.42005301,   0.25349066],
+           [ -9.94987437,  14.53535354,  -5.31022304,   2.43081618],
+           [  0.        ,  -1.83299243,   0.38969961,  -0.51527034],
+           [  0.        ,   0.        ,  -3.83189513,   1.07494686]])
+    >>> np.allclose(Q @ H @ Q.conj().T - A, np.zeros((4, 4)))
+    True
+    """
+    a1 = _asarray_validated(a, check_finite=check_finite)
+    if len(a1.shape) != 2 or (a1.shape[0] != a1.shape[1]):
+        raise ValueError('expected square matrix')
+    overwrite_a = overwrite_a or (_datacopied(a1, a))
+
+    if a1.size == 0:
+        h3 = hessenberg(np.eye(3, dtype=a1.dtype))
+        h = np.empty(a1.shape, dtype=h3.dtype)
+        if not calc_q:
+            return h
+        else:
+            h3, q3 = hessenberg(np.eye(3, dtype=a1.dtype), calc_q=True)
+            q = np.empty(a1.shape, dtype=q3.dtype)
+            h = np.empty(a1.shape, dtype=h3.dtype)
+            return h, q
+
+    # if 2x2 or smaller: already in Hessenberg
+    if a1.shape[0] <= 2:
+        if calc_q:
+            return a1, eye(a1.shape[0])
+        return a1
+
+    gehrd, gebal, gehrd_lwork = get_lapack_funcs(('gehrd', 'gebal',
+                                                  'gehrd_lwork'), (a1,))
+    ba, lo, hi, pivscale, info = gebal(a1, permute=0, overwrite_a=overwrite_a)
+    _check_info(info, 'gebal (hessenberg)', positive=False)
+    n = len(a1)
+
+    lwork = _compute_lwork(gehrd_lwork, ba.shape[0], lo=lo, hi=hi)
+
+    hq, tau, info = gehrd(ba, lo=lo, hi=hi, lwork=lwork, overwrite_a=1)
+    _check_info(info, 'gehrd (hessenberg)', positive=False)
+    h = np.triu(hq, -1)
+    if not calc_q:
+        return h
+
+    # use orghr/unghr to compute q
+    orghr, orghr_lwork = get_lapack_funcs(('orghr', 'orghr_lwork'), (a1,))
+    lwork = _compute_lwork(orghr_lwork, n, lo=lo, hi=hi)
+
+    q, info = orghr(a=hq, tau=tau, lo=lo, hi=hi, lwork=lwork, overwrite_a=1)
+    _check_info(info, 'orghr (hessenberg)', positive=False)
+    return h, q
+
+
+def cdf2rdf(w, v):
+    """
+    Complex diagonal form to real diagonal block form.
+
+    Converts complex eigenvalues ``w`` and eigenvectors ``v`` to real
+    eigenvalues in a block diagonal form ``wr`` and the associated real
+    eigenvectors ``vr``, such that::
+
+        vr @ wr = X @ vr
+
+    continues to hold, where ``X`` is the original array for which ``w`` and
+    ``v`` are the eigenvalues and eigenvectors.
+
+    .. versionadded:: 1.1.0
+
+    Array argument(s) of this function may have additional
+    "batch" dimensions prepended to the core shape. In this case, the array is treated
+    as a batch of lower-dimensional slices; see :ref:`linalg_batch` for details.
+
+    Parameters
+    ----------
+    w : (..., M) array_like
+        Complex or real eigenvalues, an array or stack of arrays
+
+        Conjugate pairs must not be interleaved, else the wrong result
+        will be produced. So ``[1+1j, 1, 1-1j]`` will give a correct result,
+        but ``[1+1j, 2+1j, 1-1j, 2-1j]`` will not.
+
+    v : (..., M, M) array_like
+        Complex or real eigenvectors, a square array or stack of square arrays.
+
+    Returns
+    -------
+    wr : (..., M, M) ndarray
+        Real diagonal block form of eigenvalues
+    vr : (..., M, M) ndarray
+        Real eigenvectors associated with ``wr``
+
+    See Also
+    --------
+    eig : Eigenvalues and right eigenvectors for non-symmetric arrays
+    rsf2csf : Convert real Schur form to complex Schur form
+
+    Notes
+    -----
+    ``w``, ``v`` must be the eigenstructure for some *real* matrix ``X``.
+    For example, obtained by ``w, v = scipy.linalg.eig(X)`` or
+    ``w, v = numpy.linalg.eig(X)`` in which case ``X`` can also represent
+    stacked arrays.
+
+    .. versionadded:: 1.1.0
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> X = np.array([[1, 2, 3], [0, 4, 5], [0, -5, 4]])
+    >>> X
+    array([[ 1,  2,  3],
+           [ 0,  4,  5],
+           [ 0, -5,  4]])
+
+    >>> from scipy import linalg
+    >>> w, v = linalg.eig(X)
+    >>> w
+    array([ 1.+0.j,  4.+5.j,  4.-5.j])
+    >>> v
+    array([[ 1.00000+0.j     , -0.01906-0.40016j, -0.01906+0.40016j],
+           [ 0.00000+0.j     ,  0.00000-0.64788j,  0.00000+0.64788j],
+           [ 0.00000+0.j     ,  0.64788+0.j     ,  0.64788-0.j     ]])
+
+    >>> wr, vr = linalg.cdf2rdf(w, v)
+    >>> wr
+    array([[ 1.,  0.,  0.],
+           [ 0.,  4.,  5.],
+           [ 0., -5.,  4.]])
+    >>> vr
+    array([[ 1.     ,  0.40016, -0.01906],
+           [ 0.     ,  0.64788,  0.     ],
+           [ 0.     ,  0.     ,  0.64788]])
+
+    >>> vr @ wr
+    array([[ 1.     ,  1.69593,  1.9246 ],
+           [ 0.     ,  2.59153,  3.23942],
+           [ 0.     , -3.23942,  2.59153]])
+    >>> X @ vr
+    array([[ 1.     ,  1.69593,  1.9246 ],
+           [ 0.     ,  2.59153,  3.23942],
+           [ 0.     , -3.23942,  2.59153]])
+    """
+    w, v = _asarray_validated(w), _asarray_validated(v)
+    _deprecate_dtypes("cdf2rdf", w, v)
+
+    # check dimensions
+    if w.ndim < 1:
+        raise ValueError('expected w to be at least 1D')
+    if v.ndim < 2:
+        raise ValueError('expected v to be at least 2D')
+    if v.ndim != w.ndim + 1:
+        raise ValueError('expected eigenvectors array to have exactly one '
+                         'dimension more than eigenvalues array')
+
+    # check shapes
+    n = w.shape[-1]
+    M = w.shape[:-1]
+    if v.shape[-2] != v.shape[-1]:
+        raise ValueError('expected v to be a square matrix or stacked square '
+                         'matrices: v.shape[-2] = v.shape[-1]')
+    if v.shape[-1] != n:
+        raise ValueError('expected the same number of eigenvalues as '
+                         'eigenvectors')
+
+    # get indices for each first pair of complex eigenvalues
+    complex_mask = iscomplex(w)
+    n_complex = complex_mask.sum(axis=-1)
+
+    # check if all complex eigenvalues have conjugate pairs
+    if not (n_complex % 2 == 0).all():
+        raise ValueError('expected complex-conjugate pairs of eigenvalues')
+
+    # find complex indices
+    idx = nonzero(complex_mask)
+    idx_stack = idx[:-1]
+    idx_elem = idx[-1]
+
+    # filter them to conjugate indices, assuming pairs are not interleaved
+    j = idx_elem[0::2]
+    k = idx_elem[1::2]
+    stack_ind = ()
+    for i in idx_stack:
+        # should never happen, assuming nonzero orders by the last axis
+        assert (i[0::2] == i[1::2]).all(), \
+                "Conjugate pair spanned different arrays!"
+        stack_ind += (i[0::2],)
+
+    # all eigenvalues to diagonal form
+    wr = zeros(M + (n, n), dtype=w.real.dtype)
+    di = range(n)
+    wr[..., di, di] = w.real
+
+    # complex eigenvalues to real block diagonal form
+    wr[stack_ind + (j, k)] = w[stack_ind + (j,)].imag
+    wr[stack_ind + (k, j)] = w[stack_ind + (k,)].imag
+
+    # compute real eigenvectors associated with real block diagonal eigenvalues
+    u = zeros(M + (n, n), dtype=np.cdouble)
+    u[..., di, di] = 1.0
+    u[stack_ind + (j, j)] = 0.5j
+    u[stack_ind + (j, k)] = 0.5
+    u[stack_ind + (k, j)] = -0.5j
+    u[stack_ind + (k, k)] = 0.5
+
+    # multiply matrices v and u (equivalent to v @ u)
+    vr = einsum('...ij,...jk->...ik', v, u).real
+
+    return wr, vr
diff --git a/.venv/lib/python3.12/site-packages/scipy/linalg/_decomp_cholesky.py b/.venv/lib/python3.12/site-packages/scipy/linalg/_decomp_cholesky.py
new file mode 100644
index 0000000000000000000000000000000000000000..b1ede679eba26a3eeda0c211613872bcaa2bed18
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/linalg/_decomp_cholesky.py
@@ -0,0 +1,465 @@
+"""Cholesky decomposition functions."""
+
+import numpy as np
+from numpy import asarray_chkfinite, asarray, empty_like
+
+# Local imports
+from scipy._lib._util import _asarray_validated, _apply_over_batch, _deprecate_dtypes
+from ._misc import LinAlgError, _datacopied
+from .lapack import (
+    get_lapack_funcs, _normalize_lapack_dtype, _ensure_aligned_and_native
+)
+from . import _batched_linalg
+
+__all__ = ['cholesky', 'cho_factor', 'cho_solve', 'cholesky_banded',
+           'cho_solve_banded']
+
+
+def _check_format_errors_warnings(routine_name, err_lst):
+    msg = (
+        f"Internal {routine_name} return info = {[e['lapack_info'] for e in err_lst]} "
+        f"for slices {[e['num'] for e in err_lst]}."
+    )
+    raise LinAlgError(msg)
+
+
+def _cholesky(a, lower=False, overwrite_a=False, clean=True,
+              check_finite=True):
+    """Common code for cholesky() and cho_factor()."""
+
+    # sanity checks
+    a1 = _asarray_validated(a, check_finite=check_finite)
+    a1 = np.atleast_2d(a1)
+    if a1.shape[-1] != a1.shape[-2]:
+        raise ValueError(f"Expected a square matrix or batch thereof, got {a1.shape=}")
+
+    _deprecate_dtypes("linalg.cholesky", a1)
+
+    a1, overwrite_a = _normalize_lapack_dtype(a1, overwrite_a)
+    a1, overwrite_a = _ensure_aligned_and_native(a1, overwrite_a)
+    overwrite_a = (overwrite_a and (a1.ndim == 2)
+                   and (a1.flags["F_CONTIGUOUS"] or a1.flags["C_CONTIGUOUS"]))
+
+    # accommodate empty arrays
+    if a1.shape[-1] == 0:
+        batch_shape = a1.shape[:-2]
+        c = np.zeros(batch_shape + (0, 0), dtype=a1.dtype)
+        return c
+
+    # Heavy lifting
+    c, err_lst = _batched_linalg._cholesky(a1, lower, overwrite_a, clean)
+
+    if err_lst:
+        _check_format_errors_warnings("potrf", err_lst)
+
+    return c
+
+
+def cholesky(a, lower=False, overwrite_a=False, check_finite=True):
+    """
+    Compute the Cholesky decomposition of a matrix.
+
+    Returns the Cholesky decomposition, :math:`A = L L^*` or
+    :math:`A = U^* U` of a Hermitian positive-definite matrix A.
+
+    Parameters
+    ----------
+    a : (..., M, M) array_like
+        Matrix to be decomposed
+    lower : bool, optional
+        Whether to compute the upper- or lower-triangular Cholesky
+        factorization. During decomposition, only the selected half of the
+        matrix is referenced. Default is upper-triangular.
+    overwrite_a : bool, optional
+        Whether to overwrite data in `a` (may improve performance). Default is False.
+        See :ref:`tutorial_linalg_overwrite` for details.
+    check_finite : bool, optional
+        Whether to check that the entire input matrix contains only finite numbers.
+        Disabling may give a performance gain, but may result in problems
+        (crashes, non-termination) if the inputs do contain infinities or NaNs.
+
+    Returns
+    -------
+    c : (..., M, M) ndarray
+        Upper- or lower-triangular Cholesky factor of `a`.
+
+    Raises
+    ------
+    LinAlgError : if decomposition fails.
+
+    See Also
+    --------
+    cho_factor : Compute the Cholesky decomposition without explicitly setting
+                    the other triangle to 0.
+
+    Notes
+    -----
+    During the finiteness check (if selected), the entire matrix `a` is
+    checked. During decomposition, `a` is assumed to be symmetric or Hermitian
+    (as applicable), and only the half selected by option `lower` is referenced.
+    Consequently, if `a` is asymmetric/non-Hermitian, `cholesky` may still
+    succeed if the symmetric/Hermitian matrix represented by the selected half
+    is positive definite, yet it may fail if an element in the other half is
+    non-finite.
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy.linalg import cholesky
+    >>> a = np.array([[1,-2j],[2j,5]])
+    >>> L = cholesky(a, lower=True)
+    >>> L
+    array([[ 1.+0.j,  0.+0.j],
+           [ 0.+2.j,  1.+0.j]])
+    >>> L @ L.T.conj()
+    array([[ 1.+0.j,  0.-2.j],
+           [ 0.+2.j,  5.+0.j]])
+
+    """
+    # `clean = True` represents setting other triangle to 0.
+    c = _cholesky(a, lower=lower, overwrite_a=overwrite_a, clean=True,
+                check_finite=check_finite)
+    return c
+
+
+def cho_factor(a, lower=False, overwrite_a=False, check_finite=True):
+    """
+    Compute the Cholesky decomposition of a matrix, to use in cho_solve.
+
+    Returns a matrix containing the Cholesky decomposition,
+    ``A = L L*`` or ``A = U* U`` of a Hermitian positive-definite matrix `a`.
+    The return value can be directly used as the first parameter to cho_solve.
+
+    .. warning::
+        If `overwrite_a` is disabled, this function matches `cholesky` and
+        zeros the other triangle. If it is enabled, the returned matrix may
+        contain random data in the entries not used by the Cholesky
+        decomposition, saving out on the explicit putting to 0 done by
+        `cholesky`.
+
+    Parameters
+    ----------
+    a : (..., M, M) array_like
+        Matrix to be decomposed
+    lower : bool, optional
+        Whether to compute the upper or lower triangular Cholesky factorization.
+        During decomposition, only the selected half of the matrix is referenced.
+        (Default: upper-triangular)
+    overwrite_a : bool, optional
+        Whether to overwrite data in ``a`` (may improve performance). Default is False.
+        See :ref:`tutorial_linalg_overwrite` for details.
+    check_finite : bool, optional
+        Whether to check that the entire input matrix contains only finite numbers.
+        Disabling may give a performance gain, but may result in problems
+        (crashes, non-termination) if the inputs do contain infinities or NaNs.
+
+    Returns
+    -------
+    c : (..., M, M) ndarray
+        Matrix whose upper or lower triangle contains the Cholesky factor
+        of `a`. Other parts of the matrix contain random data.
+    lower : ndarray, bool
+        Flag indicating whether the factor is in the lower or upper triangle
+
+    Raises
+    ------
+    LinAlgError
+        Raised if decomposition fails.
+
+    See Also
+    --------
+    cholesky : Compute the Cholesky decomposition and explicitly put the
+                other triangle to 0.
+    cho_solve : Solve a linear set equations using the Cholesky factorization
+                of a matrix.
+
+    Notes
+    -----
+    During the finiteness check (if selected), the entire matrix `a` is
+    checked. During decomposition, `a` is assumed to be symmetric or Hermitian
+    (as applicable), and only the half selected by option `lower` is referenced.
+    Consequently, if `a` is asymmetric/non-Hermitian, `cholesky` may still
+    succeed if the symmetric/Hermitian matrix represented by the selected half
+    is positive definite, yet it may fail if an element in the other half is
+    non-finite.
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy.linalg import cho_factor
+    >>> A = np.array([[9, 3, 1, 5], [3, 7, 5, 1], [1, 5, 9, 2], [5, 1, 2, 6]],
+    ...             dtype=float, order="F")
+    >>> A_ref = np.copy(A)
+    >>> c, low = cho_factor(A)
+    >>> c
+    array([[3.        , 1.        , 0.33333333, 1.66666667],
+           [0.        , 2.44948974, 1.90515869, -0.27216553],
+           [0.        , 0.        , 2.29330749, 0.8559528 ],
+           [0.        , 0.        , 0.        , 1.55418563]])
+    >>> np.allclose(c.T @ c - A, np.zeros((4, 4)))
+    True
+    >>> c, low = cho_factor(A, overwrite_a=True)
+    >>> c
+    array([[3.        , 1.        , 0.33333333, 1.66666667],
+           [3.        , 2.44948974, 1.90515869, -0.27216553],
+           [1.        , 5.        , 2.29330749, 0.8559528 ],
+           [5.        , 1.        , 2.        , 1.55418563]])
+    >>> np.allclose(np.triu(c).T @ np.triu(c) - A_ref, np.zeros((4, 4)))
+    True
+
+    """
+    # `clean=False` to represent that it is not necessary to set other triangle to 0.
+    c = _cholesky(a, lower=lower, overwrite_a=overwrite_a, clean=False,
+                    check_finite=check_finite)
+
+    # broadcast `lower` argument for backwards compat
+    batch_shape = a.shape[:-2]
+    ret_lower = np.tile(lower, reps=batch_shape)
+
+    return c, ret_lower
+
+
+def cho_solve(c_and_lower, b, overwrite_b=False, check_finite=True):
+    """Solve the linear equations A x = b, given the Cholesky factorization of A.
+
+    The documentation is written assuming array arguments are of specified
+    "core" shapes. However, array argument(s) of this function may have additional
+    "batch" dimensions prepended to the core shape. In this case, the array is treated
+    as a batch of lower-dimensional slices; see :ref:`linalg_batch` for details.
+
+    Parameters
+    ----------
+    c_and_lower : tuple, (array, bool)
+        Cholesky factorization of an array, as given by cho_factor.
+        The first element of the
+        tuple is the matrix containing the Cholesky factor, and the second element is a
+        boolean flag indicating whether the factor is in the lower or upper triangle.
+    b : array
+        Right-hand side
+    overwrite_b : bool, optional
+        Whether to overwrite data in b (may improve performance)
+        See :ref:`tutorial_linalg_overwrite` for details.
+    check_finite : bool, optional
+        Whether to check that the input matrices contain only finite numbers.
+        Disabling may give a performance gain, but may result in problems
+        (crashes, non-termination) if the inputs do contain infinities or NaNs.
+
+    Returns
+    -------
+    x : array
+        The solution to the system A x = b
+
+    See Also
+    --------
+    cho_factor : Cholesky factorization of a matrix
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy.linalg import cho_factor, cho_solve
+    >>> A = np.array([[9, 3, 1, 5], [3, 7, 5, 1], [1, 5, 9, 2], [5, 1, 2, 6]])
+    >>> c, low = cho_factor(A)
+    >>> x = cho_solve((c, low), [1, 1, 1, 1])
+    >>> np.allclose(A @ x - [1, 1, 1, 1], np.zeros(4))
+    True
+
+    """
+    c, lower = c_and_lower
+    return _cho_solve(c, b, lower, overwrite_b=overwrite_b, check_finite=check_finite)
+
+
+@_apply_over_batch(('c', 2), ('b', '1|2'))
+def _cho_solve(c, b, lower, overwrite_b, check_finite):
+    if check_finite:
+        b1 = asarray_chkfinite(b)
+        c = asarray_chkfinite(c)
+    else:
+        b1 = asarray(b)
+        c = asarray(c)
+
+    if c.ndim != 2 or c.shape[0] != c.shape[1]:
+        raise ValueError("The factored matrix c is not square.")
+    if c.shape[1] != b1.shape[0]:
+        raise ValueError(f"incompatible dimensions ({c.shape} and {b1.shape})")
+
+    # accommodate empty arrays
+    if b1.size == 0:
+        dt = cho_solve((np.eye(2, dtype=b1.dtype), True),
+                        np.ones(2, dtype=c.dtype)).dtype
+        return empty_like(b1, dtype=dt)
+
+    overwrite_b = overwrite_b or _datacopied(b1, b)
+
+    potrs, = get_lapack_funcs(('potrs',), (c, b1))
+    x, info = potrs(c, b1, lower=lower, overwrite_b=overwrite_b)
+    if info != 0:
+        raise ValueError(f'illegal value in {-info}th argument of internal potrs')
+    return x
+
+
+@_apply_over_batch(("ab", 2))
+def cholesky_banded(ab, overwrite_ab=False, lower=False, check_finite=True):
+    """
+    Cholesky decompose a banded Hermitian positive-definite matrix.
+
+    The matrix a is stored in ab either in lower-diagonal or upper-
+    diagonal ordered form::
+
+        ab[u + i - j, j] == a[i,j]        (if upper form; i <= j)
+        ab[    i - j, j] == a[i,j]        (if lower form; i >= j)
+
+    Example of ab (shape of a is (6,6), u=2)::
+
+        upper form:
+        *   *   a02 a13 a24 a35
+        *   a01 a12 a23 a34 a45
+        a00 a11 a22 a33 a44 a55
+
+        lower form:
+        a00 a11 a22 a33 a44 a55
+        a10 a21 a32 a43 a54 *
+        a20 a31 a42 a53 *   *
+
+    Parameters
+    ----------
+    ab : (u + 1, M) array_like
+        Banded matrix
+    overwrite_ab : bool, optional
+        Discard data in ab (may enhance performance)
+        See :ref:`tutorial_linalg_overwrite` for details.
+    lower : bool, optional
+        Is the matrix in the lower form. (Default is upper form)
+    check_finite : bool, optional
+        Whether to check that the input matrix contains only finite numbers.
+        Disabling may give a performance gain, but may result in problems
+        (crashes, non-termination) if the inputs do contain infinities or NaNs.
+
+    Returns
+    -------
+    c : (u + 1, M) ndarray
+        Cholesky factorization of a, in the same banded format as ab
+
+    See Also
+    --------
+    cho_solve_banded :
+        Solve a linear set equations, given the Cholesky factorization
+        of a banded Hermitian.
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy.linalg import cholesky_banded
+    >>> from numpy import allclose, zeros, diag
+    >>> Ab = np.array([[0, 0, 1j, 2, 3j], [0, -1, -2, 3, 4], [9, 8, 7, 6, 9]])
+    >>> A = np.diag(Ab[0,2:], k=2) + np.diag(Ab[1,1:], k=1)
+    >>> A = A + A.conj().T + np.diag(Ab[2, :])
+    >>> c = cholesky_banded(Ab)
+    >>> C = np.diag(c[0, 2:], k=2) + np.diag(c[1, 1:], k=1) + np.diag(c[2, :])
+    >>> np.allclose(C.conj().T @ C - A, np.zeros((5, 5)))
+    True
+
+    """
+    if check_finite:
+        ab = asarray_chkfinite(ab)
+    else:
+        ab = asarray(ab)
+
+    # accommodate square empty matrices
+    if ab.size == 0:
+        dt = cholesky_banded(np.array([[0, 0], [1, 1]], dtype=ab.dtype)).dtype
+        return empty_like(ab, dtype=dt)
+
+    pbtrf, = get_lapack_funcs(('pbtrf',), (ab,))
+    c, info = pbtrf(ab, lower=lower, overwrite_ab=overwrite_ab)
+    if info > 0:
+        raise LinAlgError(f"{info}-th leading minor not positive definite")
+    if info < 0:
+        raise ValueError(f'illegal value in {info}-th argument of internal pbtrf')
+    return c
+
+
+def cho_solve_banded(cb_and_lower, b, overwrite_b=False, check_finite=True):
+    """
+    Solve the linear equations ``A x = b``, given the Cholesky factorization of
+    the banded Hermitian ``A``.
+
+    The documentation is written assuming array arguments are of specified
+    "core" shapes. However, array argument(s) of this function may have additional
+    "batch" dimensions prepended to the core shape. In this case, the array is treated
+    as a batch of lower-dimensional slices; see :ref:`linalg_batch` for details.
+
+    Parameters
+    ----------
+    cb_and_lower : tuple, (ndarray, bool)
+        The first element of the tuple is the matrix containing the Cholesky factor,
+        as provided by `cholesky_banded`. The second element is a boolean flag
+        indicating whether the factor is in the lower triangle, as provided *to*
+        `cholesky_banded`.
+    b : array_like
+        Right-hand side
+    overwrite_b : bool, optional
+        If True, the function will overwrite the values in `b`.
+        See :ref:`tutorial_linalg_overwrite` for details.
+    check_finite : bool, optional
+        Whether to check that the input matrices contain only finite numbers.
+        Disabling may give a performance gain, but may result in problems
+        (crashes, non-termination) if the inputs do contain infinities or NaNs.
+
+    Returns
+    -------
+    x : array
+        The solution to the system A x = b
+
+    See Also
+    --------
+    cholesky_banded : Cholesky factorization of a banded matrix
+
+    Notes
+    -----
+
+    .. versionadded:: 0.8.0
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy.linalg import cholesky_banded, cho_solve_banded
+    >>> Ab = np.array([[0, 0, 1j, 2, 3j], [0, -1, -2, 3, 4], [9, 8, 7, 6, 9]])
+    >>> A = np.diag(Ab[0,2:], k=2) + np.diag(Ab[1,1:], k=1)
+    >>> A = A + A.conj().T + np.diag(Ab[2, :])
+    >>> c = cholesky_banded(Ab)
+    >>> x = cho_solve_banded((c, False), np.ones(5))
+    >>> np.allclose(A @ x - np.ones(5), np.zeros(5))
+    True
+
+    """
+    (cb, lower) = cb_and_lower
+    return _cho_solve_banded(cb, b, lower, overwrite_b=overwrite_b,
+                             check_finite=check_finite)
+
+
+@_apply_over_batch(('cb', 2), ('b', '1|2'))
+def _cho_solve_banded(cb, b, lower, overwrite_b, check_finite):
+    if check_finite:
+        cb = asarray_chkfinite(cb)
+        b = asarray_chkfinite(b)
+    else:
+        cb = asarray(cb)
+        b = asarray(b)
+
+    # Validate shapes.
+    if cb.shape[-1] != b.shape[0]:
+        raise ValueError("shapes of cb and b are not compatible.")
+
+    # accommodate empty arrays
+    if b.size == 0:
+        m = cholesky_banded(np.array([[0, 0], [1, 1]], dtype=cb.dtype))
+        dt = cho_solve_banded((m, True), np.ones(2, dtype=b.dtype)).dtype
+        return empty_like(b, dtype=dt)
+
+    pbtrs, = get_lapack_funcs(('pbtrs',), (cb, b))
+    x, info = pbtrs(cb, b, lower=lower, overwrite_b=overwrite_b)
+    if info > 0:
+        raise LinAlgError(f"{info}th leading minor not positive definite")
+    if info < 0:
+        raise ValueError(f'illegal value in {-info}th argument of internal pbtrs')
+    return x
diff --git a/.venv/lib/python3.12/site-packages/scipy/linalg/_decomp_cossin.py b/.venv/lib/python3.12/site-packages/scipy/linalg/_decomp_cossin.py
new file mode 100644
index 0000000000000000000000000000000000000000..ccf6f62443913cce4f396a1eed22958de126e4ae
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/linalg/_decomp_cossin.py
@@ -0,0 +1,234 @@
+from collections.abc import Iterable
+import numpy as np
+
+from scipy._lib._util import _asarray_validated, _apply_over_batch
+from scipy.linalg import block_diag, LinAlgError
+from .lapack import _compute_lwork, get_lapack_funcs
+
+__all__ = ['cossin']
+
+
+def cossin(X, p=None, q=None, separate=False,
+           swap_sign=False, compute_u=True, compute_vh=True):
+    """
+    Compute the cosine-sine (CS) decomposition of an orthogonal/unitary matrix.
+
+    X is an ``(m, m)`` orthogonal/unitary matrix, partitioned as the following
+    where upper left block has the shape of ``(p, q)``::
+
+                                   ┌                   ┐
+                                   │ I  0  0 │ 0  0  0 │
+        ┌           ┐   ┌         ┐│ 0  C  0 │ 0 -S  0 │┌         ┐*
+        │ X11 │ X12 │   │ U1 │    ││ 0  0  0 │ 0  0 -I ││ V1 │    │
+        │ ────┼──── │ = │────┼────││─────────┼─────────││────┼────│
+        │ X21 │ X22 │   │    │ U2 ││ 0  0  0 │ I  0  0 ││    │ V2 │
+        └           ┘   └         ┘│ 0  S  0 │ 0  C  0 │└         ┘
+                                   │ 0  0  I │ 0  0  0 │
+                                   └                   ┘
+
+    ``U1``, ``U2``, ``V1``, ``V2`` are square orthogonal/unitary matrices of
+    dimensions ``(p,p)``, ``(m-p,m-p)``, ``(q,q)``, and ``(m-q,m-q)``
+    respectively, and ``C`` and ``S`` are ``(r, r)`` nonnegative diagonal
+    matrices satisfying ``C^2 + S^2 = I`` where ``r = min(p, m-p, q, m-q)``.
+
+    Moreover, the rank of the identity matrices are ``min(p, q) - r``,
+    ``min(p, m - q) - r``, ``min(m - p, q) - r``, and ``min(m - p, m - q) - r``
+    respectively.
+
+    X can be supplied either by itself and block specifications p, q or its
+    subblocks in an iterable from which the shapes would be derived. See the
+    examples below.
+
+    The documentation is written assuming array arguments are of specified
+    "core" shapes. However, array argument(s) of this function may have additional
+    "batch" dimensions prepended to the core shape. In this case, the array is treated
+    as a batch of lower-dimensional slices; see :ref:`linalg_batch` for details.
+
+    Parameters
+    ----------
+    X : array_like, iterable
+        complex unitary or real orthogonal matrix to be decomposed, or iterable
+        of subblocks ``X11``, ``X12``, ``X21``, ``X22``, when ``p``, ``q`` are
+        omitted.
+    p : int, optional
+        Number of rows of the upper left block ``X11``, used only when X is
+        given as an array.
+    q : int, optional
+        Number of columns of the upper left block ``X11``, used only when X is
+        given as an array.
+    separate : bool, optional
+        if ``True``, the low level components are returned instead of the
+        matrix factors, i.e. ``(u1,u2)``, ``theta``, ``(v1h,v2h)`` instead of
+        ``u``, ``cs``, ``vh``.
+    swap_sign : bool, optional
+        if ``True``, the ``-S``, ``-I`` block will be the bottom left,
+        otherwise (by default) they will be in the upper right block.
+    compute_u : bool, optional
+        if ``False``, ``u`` won't be computed and an empty array is returned.
+    compute_vh : bool, optional
+        if ``False``, ``vh`` won't be computed and an empty array is returned.
+
+    Returns
+    -------
+    u : ndarray
+        When ``compute_u=True``, contains the block diagonal orthogonal/unitary
+        matrix consisting of the blocks ``U1`` (``p`` x ``p``) and ``U2``
+        (``m-p`` x ``m-p``) orthogonal/unitary matrices. If ``separate=True``,
+        this contains the tuple of ``(U1, U2)``.
+    cs : ndarray
+        The cosine-sine factor with the structure described above.
+         If ``separate=True``, this contains the ``theta`` array containing the
+         angles in radians.
+    vh : ndarray
+        When ``compute_vh=True`, contains the block diagonal orthogonal/unitary
+        matrix consisting of the blocks ``V1H`` (``q`` x ``q``) and ``V2H``
+        (``m-q`` x ``m-q``) orthogonal/unitary matrices. If ``separate=True``,
+        this contains the tuple of ``(V1H, V2H)``.
+
+    References
+    ----------
+    .. [1] Brian D. Sutton. Computing the complete CS decomposition. Numer.
+           Algorithms, 50(1):33-65, 2009.
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy.linalg import cossin
+    >>> from scipy.stats import unitary_group
+    >>> x = unitary_group.rvs(4)
+    >>> u, cs, vdh = cossin(x, p=2, q=2)
+    >>> np.allclose(x, u @ cs @ vdh)
+    True
+
+    Same can be entered via subblocks without the need of ``p`` and ``q``. Also
+    let's skip the computation of ``u``
+
+    >>> ue, cs, vdh = cossin((x[:2, :2], x[:2, 2:], x[2:, :2], x[2:, 2:]),
+    ...                      compute_u=False)
+    >>> print(ue)
+    []
+    >>> np.allclose(x, u @ cs @ vdh)
+    True
+
+    """
+
+    if p or q:
+        p = 1 if p is None else int(p)
+        q = 1 if q is None else int(q)
+        X = _asarray_validated(X, check_finite=True)
+        if not np.equal(*X.shape[-2:]):
+            raise ValueError("Cosine Sine decomposition only supports square"
+                             f" matrices, got {X.shape[-2:]}")
+        m = X.shape[-2]
+        if p >= m or p <= 0:
+            raise ValueError(f"invalid p={p}, 0= m or q <= 0:
+            raise ValueError(f"invalid q={q}, 0 0:
+        raise LinAlgError(f"{method_name} did not converge: {info}")
+
+    if separate:
+        return (u1, u2), theta, (v1h, v2h)
+
+    U = block_diag(u1, u2)
+    VDH = block_diag(v1h, v2h)
+
+    # Construct the middle factor CS
+    c = np.diag(np.cos(theta))
+    s = np.diag(np.sin(theta))
+    r = min(p, q, m - p, m - q)
+    n11 = min(p, q) - r
+    n12 = min(p, m - q) - r
+    n21 = min(m - p, q) - r
+    n22 = min(m - p, m - q) - r
+    Id = np.eye(np.max([n11, n12, n21, n22, r]), dtype=theta.dtype)
+    CS = np.zeros((m, m), dtype=theta.dtype)
+
+    CS[:n11, :n11] = Id[:n11, :n11]
+
+    xs = n11 + r
+    xe = n11 + r + n12
+    ys = n11 + n21 + n22 + 2 * r
+    ye = n11 + n21 + n22 + 2 * r + n12
+    CS[xs: xe, ys:ye] = Id[:n12, :n12] if swap_sign else -Id[:n12, :n12]
+
+    xs = p + n22 + r
+    xe = p + n22 + r + + n21
+    ys = n11 + r
+    ye = n11 + r + n21
+    CS[xs:xe, ys:ye] = -Id[:n21, :n21] if swap_sign else Id[:n21, :n21]
+
+    CS[p:p + n22, q:q + n22] = Id[:n22, :n22]
+    CS[n11:n11 + r, n11:n11 + r] = c
+    CS[p + n22:p + n22 + r, n11 + r + n21 + n22:2 * r + n11 + n21 + n22] = c
+
+    xs = n11
+    xe = n11 + r
+    ys = n11 + n21 + n22 + r
+    ye = n11 + n21 + n22 + 2 * r
+    CS[xs:xe, ys:ye] = s if swap_sign else -s
+
+    CS[p + n22:p + n22 + r, n11:n11 + r] = -s if swap_sign else s
+
+    return U, CS, VDH
diff --git a/.venv/lib/python3.12/site-packages/scipy/linalg/_decomp_interpolative.cpython-312-x86_64-linux-gnu.so b/.venv/lib/python3.12/site-packages/scipy/linalg/_decomp_interpolative.cpython-312-x86_64-linux-gnu.so
new file mode 100644
index 0000000000000000000000000000000000000000..f2959e15fb8b0ce992e2224a7c775f444eeb6909
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/linalg/_decomp_interpolative.cpython-312-x86_64-linux-gnu.so
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:3a737ff7f297189b5f751574de6d147db90de82a4e3c315b7241f9219d19be5f
+size 740424
diff --git a/.venv/lib/python3.12/site-packages/scipy/linalg/_decomp_ldl.py b/.venv/lib/python3.12/site-packages/scipy/linalg/_decomp_ldl.py
new file mode 100644
index 0000000000000000000000000000000000000000..e91021db22e3fc5af65d6abb68049669b9b62a40
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/linalg/_decomp_ldl.py
@@ -0,0 +1,357 @@
+from warnings import warn
+
+import numpy as np
+from numpy import (atleast_2d, arange, zeros_like, imag, diag,
+                   iscomplexobj, tril, triu, argsort, empty_like)
+from numpy.exceptions import ComplexWarning
+
+from scipy._lib._util import _apply_over_batch
+from ._decomp import _asarray_validated
+from .lapack import get_lapack_funcs, _compute_lwork
+
+__all__ = ['ldl']
+
+
+@_apply_over_batch(('A', 2))
+def ldl(A, lower=True, hermitian=True, overwrite_a=False, check_finite=True):
+    """ Computes the LDLt or Bunch-Kaufman factorization of a symmetric/
+    hermitian matrix.
+
+    This function returns a block diagonal matrix D consisting blocks of size
+    at most 2x2 and also a possibly permuted unit lower triangular matrix
+    ``L`` such that the factorization ``A = L D L^H`` or ``A = L D L^T``
+    holds. If `lower` is False then (again possibly permuted) upper
+    triangular matrices are returned as outer factors.
+
+    The permutation array can be used to triangularize the outer factors
+    simply by a row shuffle, i.e., ``lu[perm, :]`` is an upper/lower
+    triangular matrix. This is also equivalent to multiplication with a
+    permutation matrix ``P.dot(lu)``, where ``P`` is a column-permuted
+    identity matrix ``I[:, perm]``.
+
+    Depending on the value of the boolean `lower`, only upper or lower
+    triangular part of the input array is referenced. Hence, a triangular
+    matrix on entry would give the same result as if the full matrix is
+    supplied.
+
+    Parameters
+    ----------
+    A : array_like
+        Square input array
+    lower : bool, optional
+        This switches between the lower and upper triangular outer factors of
+        the factorization. Lower triangular (``lower=True``) is the default.
+    hermitian : bool, optional
+        For complex-valued arrays, this defines whether ``A = A.conj().T`` or
+        ``A = A.T`` is assumed. For real-valued arrays, this switch has no
+        effect.
+    overwrite_a : bool, optional
+        Allow overwriting data in `A` (may enhance performance). The default
+        is False.
+        See :ref:`tutorial_linalg_overwrite` for details.
+    check_finite : bool, optional
+        Whether to check that the input matrices contain only finite numbers.
+        Disabling may give a performance gain, but may result in problems
+        (crashes, non-termination) if the inputs do contain infinities or NaNs.
+
+    Returns
+    -------
+    lu : ndarray
+        The (possibly) permuted upper/lower triangular outer factor of the
+        factorization.
+    d : ndarray
+        The block diagonal multiplier of the factorization.
+    perm : ndarray
+        The row-permutation index array that brings lu into triangular form.
+
+    Raises
+    ------
+    ValueError
+        If input array is not square.
+    ComplexWarning
+        If a complex-valued array with nonzero imaginary parts on the
+        diagonal is given and hermitian is set to True.
+
+    See Also
+    --------
+    cholesky, lu
+
+    Notes
+    -----
+    This function uses ``?SYTRF`` routines for symmetric matrices and
+    ``?HETRF`` routines for Hermitian matrices from LAPACK. See [1]_ for
+    the algorithm details.
+
+    Depending on the `lower` keyword value, only lower or upper triangular
+    part of the input array is referenced. Moreover, this keyword also defines
+    the structure of the outer factors of the factorization.
+
+    .. versionadded:: 1.1.0
+
+    References
+    ----------
+    .. [1] J.R. Bunch, L. Kaufman, Some stable methods for calculating
+       inertia and solving symmetric linear systems, Math. Comput. Vol.31,
+       1977. :doi:`10.2307/2005787`
+
+    Examples
+    --------
+    Given an upper triangular array ``a`` that represents the full symmetric
+    array with its entries, obtain ``l``, 'd' and the permutation vector `perm`:
+
+    >>> import numpy as np
+    >>> from scipy.linalg import ldl
+    >>> a = np.array([[2, -1, 3], [0, 2, 0], [0, 0, 1]])
+    >>> lu, d, perm = ldl(a, lower=0) # Use the upper part
+    >>> lu
+    array([[ 0. ,  0. ,  1. ],
+           [ 0. ,  1. , -0.5],
+           [ 1. ,  1. ,  1.5]])
+    >>> d
+    array([[-5. ,  0. ,  0. ],
+           [ 0. ,  1.5,  0. ],
+           [ 0. ,  0. ,  2. ]])
+    >>> perm
+    array([2, 1, 0])
+    >>> lu[perm, :]
+    array([[ 1. ,  1. ,  1.5],
+           [ 0. ,  1. , -0.5],
+           [ 0. ,  0. ,  1. ]])
+    >>> lu.dot(d).dot(lu.T)
+    array([[ 2., -1.,  3.],
+           [-1.,  2.,  0.],
+           [ 3.,  0.,  1.]])
+
+    """
+    a = atleast_2d(_asarray_validated(A, check_finite=check_finite))
+    if a.shape[0] != a.shape[1]:
+        raise ValueError('The input array "a" should be square.')
+    # Return empty arrays for empty square input
+    if a.size == 0:
+        return empty_like(a), empty_like(a), np.array([], dtype=int)
+
+    n = a.shape[0]
+    r_or_c = complex if iscomplexobj(a) else float
+
+    # Get the LAPACK routine
+    if r_or_c is complex and hermitian:
+        s, sl = 'hetrf', 'hetrf_lwork'
+        if np.any(imag(diag(a))):
+            warn('scipy.linalg.ldl():\nThe imaginary parts of the diagonal'
+                 'are ignored. Use "hermitian=False" for factorization of'
+                 'complex symmetric arrays.', ComplexWarning, stacklevel=2)
+    else:
+        s, sl = 'sytrf', 'sytrf_lwork'
+
+    solver, solver_lwork = get_lapack_funcs((s, sl), (a,))
+    lwork = _compute_lwork(solver_lwork, n, lower=lower)
+    ldu, piv, info = solver(a, lwork=lwork, lower=lower,
+                            overwrite_a=overwrite_a)
+    if info < 0:
+        raise ValueError(f'{s.upper()} exited with the internal error "illegal value '
+                         f'in argument number {-info}". See LAPACK documentation '
+                         'for the error codes.')
+
+    swap_arr, pivot_arr = _ldl_sanitize_ipiv(piv, lower=lower)
+    d, lu = _ldl_get_d_and_l(ldu, pivot_arr, lower=lower, hermitian=hermitian)
+    lu, perm = _ldl_construct_tri_factor(lu, swap_arr, pivot_arr, lower=lower)
+
+    return lu, d, perm
+
+
+def _ldl_sanitize_ipiv(a, lower=True):
+    """
+    This helper function takes the rather strangely encoded permutation array
+    returned by the LAPACK routines ?(HE/SY)TRF and converts it into
+    regularized permutation and diagonal pivot size format.
+
+    Since FORTRAN uses 1-indexing and LAPACK uses different start points for
+    upper and lower formats there are certain offsets in the indices used
+    below.
+
+    Let's assume a result where the matrix is 6x6 and there are two 2x2
+    and two 1x1 blocks reported by the routine. To ease the coding efforts,
+    we still populate a 6-sized array and fill zeros as the following ::
+
+        pivots = [2, 0, 2, 0, 1, 1]
+
+    This denotes a diagonal matrix of the form ::
+
+        [x x        ]
+        [x x        ]
+        [    x x    ]
+        [    x x    ]
+        [        x  ]
+        [          x]
+
+    In other words, we write 2 when the 2x2 block is first encountered and
+    automatically write 0 to the next entry and skip the next spin of the
+    loop. Thus, a separate counter or array appends to keep track of block
+    sizes are avoided. If needed, zeros can be filtered out later without
+    losing the block structure.
+
+    Parameters
+    ----------
+    a : ndarray
+        The permutation array ipiv returned by LAPACK
+    lower : bool, optional
+        The switch to select whether upper or lower triangle is chosen in
+        the LAPACK call.
+
+    Returns
+    -------
+    swap_ : ndarray
+        The array that defines the row/column swap operations. For example,
+        if row two is swapped with row four, the result is [0, 3, 2, 3].
+    pivots : ndarray
+        The array that defines the block diagonal structure as given above.
+
+    """
+    n = a.size
+    swap_ = arange(n)
+    pivots = zeros_like(swap_, dtype=int)
+    skip_2x2 = False
+
+    # Some upper/lower dependent offset values
+    # range (s)tart, r(e)nd, r(i)ncrement
+    x, y, rs, re, ri = (1, 0, 0, n, 1) if lower else (-1, -1, n-1, -1, -1)
+
+    for ind in range(rs, re, ri):
+        # If previous spin belonged already to a 2x2 block
+        if skip_2x2:
+            skip_2x2 = False
+            continue
+
+        cur_val = a[ind]
+        # do we have a 1x1 block or not?
+        if cur_val > 0:
+            if cur_val != ind+1:
+                # Index value != array value --> permutation required
+                swap_[ind] = swap_[cur_val-1]
+            pivots[ind] = 1
+        # Not.
+        elif cur_val < 0 and cur_val == a[ind+x]:
+            # first neg entry of 2x2 block identifier
+            if -cur_val != ind+2:
+                # Index value != array value --> permutation required
+                swap_[ind+x] = swap_[-cur_val-1]
+            pivots[ind+y] = 2
+            skip_2x2 = True
+        else:  # Doesn't make sense, give up
+            raise ValueError('While parsing the permutation array '
+                             'in "scipy.linalg.ldl", invalid entries '
+                             'found. The array syntax is invalid.')
+    return swap_, pivots
+
+
+def _ldl_get_d_and_l(ldu, pivs, lower=True, hermitian=True):
+    """
+    Helper function to extract the diagonal and triangular matrices for
+    LDL.T factorization.
+
+    Parameters
+    ----------
+    ldu : ndarray
+        The compact output returned by the LAPACK routing
+    pivs : ndarray
+        The sanitized array of {0, 1, 2} denoting the sizes of the pivots. For
+        every 2 there is a succeeding 0.
+    lower : bool, optional
+        If set to False, upper triangular part is considered.
+    hermitian : bool, optional
+        If set to False a symmetric complex array is assumed.
+
+    Returns
+    -------
+    d : ndarray
+        The block diagonal matrix.
+    lu : ndarray
+        The upper/lower triangular matrix
+    """
+    is_c = iscomplexobj(ldu)
+    d = diag(diag(ldu))
+    n = d.shape[0]
+    blk_i = 0  # block index
+
+    # row/column offsets for selecting sub-, super-diagonal
+    x, y = (1, 0) if lower else (0, 1)
+
+    lu = tril(ldu, -1) if lower else triu(ldu, 1)
+    diag_inds = arange(n)
+    lu[diag_inds, diag_inds] = 1
+
+    for blk in pivs[pivs != 0]:
+        # increment the block index and check for 2s
+        # if 2 then copy the off diagonals depending on uplo
+        inc = blk_i + blk
+
+        if blk == 2:
+            d[blk_i+x, blk_i+y] = ldu[blk_i+x, blk_i+y]
+            # If Hermitian matrix is factorized, the cross-offdiagonal element
+            # should be conjugated.
+            if is_c and hermitian:
+                d[blk_i+y, blk_i+x] = ldu[blk_i+x, blk_i+y].conj()
+            else:
+                d[blk_i+y, blk_i+x] = ldu[blk_i+x, blk_i+y]
+
+            lu[blk_i+x, blk_i+y] = 0.
+        blk_i = inc
+
+    return d, lu
+
+
+def _ldl_construct_tri_factor(lu, swap_vec, pivs, lower=True):
+    """
+    Helper function to construct explicit outer factors of LDL factorization.
+
+    If lower is True the permuted factors are multiplied as L(1)*L(2)*...*L(k).
+    Otherwise, the permuted factors are multiplied as L(k)*...*L(2)*L(1). See
+    LAPACK documentation for more details.
+
+    Parameters
+    ----------
+    lu : ndarray
+        The triangular array that is extracted from LAPACK routine call with
+        ones on the diagonals.
+    swap_vec : ndarray
+        The array that defines the row swapping indices. If the kth entry is m
+        then rows k,m are swapped. Notice that the mth entry is not necessarily
+        k to avoid undoing the swapping.
+    pivs : ndarray
+        The array that defines the block diagonal structure returned by
+        _ldl_sanitize_ipiv().
+    lower : bool, optional
+        The boolean to switch between lower and upper triangular structure.
+
+    Returns
+    -------
+    lu : ndarray
+        The square outer factor which satisfies the L * D * L.T = A
+    perm : ndarray
+        The permutation vector that brings the lu to the triangular form
+
+    Notes
+    -----
+    Note that the original argument "lu" is overwritten.
+
+    """
+    n = lu.shape[0]
+    perm = arange(n)
+    # Setup the reading order of the permutation matrix for upper/lower
+    rs, re, ri = (n-1, -1, -1) if lower else (0, n, 1)
+
+    for ind in range(rs, re, ri):
+        s_ind = swap_vec[ind]
+        if s_ind != ind:
+            # Column start and end positions
+            col_s = ind if lower else 0
+            col_e = n if lower else ind+1
+
+            # If we stumble upon a 2x2 block include both cols in the perm.
+            if pivs[ind] == (0 if lower else 2):
+                col_s += -1 if lower else 0
+                col_e += 0 if lower else 1
+            lu[[s_ind, ind], col_s:col_e] = lu[[ind, s_ind], col_s:col_e]
+            perm[[s_ind, ind]] = perm[[ind, s_ind]]
+
+    return lu, argsort(perm)
diff --git a/.venv/lib/python3.12/site-packages/scipy/linalg/_decomp_lu.py b/.venv/lib/python3.12/site-packages/scipy/linalg/_decomp_lu.py
new file mode 100644
index 0000000000000000000000000000000000000000..ba58918ee6cbb0835efe8299365774cb7f5753bf
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/linalg/_decomp_lu.py
@@ -0,0 +1,366 @@
+"""LU decomposition functions."""
+
+from warnings import warn
+
+from numpy import asarray, asarray_chkfinite
+import numpy as np
+
+from scipy._lib._util import _apply_over_batch, _deprecate_dtypes
+
+# Local imports
+from ._misc import _datacopied, LinAlgWarning
+from .lapack import get_lapack_funcs, _normalize_lapack_dtype, HAS_ILP64
+from ._batched_linalg import _lu as _linalg_lu
+
+
+__all__ = ['lu', 'lu_solve', 'lu_factor']
+
+
+@_apply_over_batch(('a', 2))
+def lu_factor(a, overwrite_a=False, check_finite=True):
+    """
+    Compute pivoted LU decomposition of a matrix.
+
+    The decomposition is::
+
+        A = P L U
+
+    where P is a permutation matrix, L lower triangular with unit
+    diagonal elements, and U upper triangular.
+
+    Parameters
+    ----------
+    a : (M, N) array_like
+        Matrix to decompose
+    overwrite_a : bool, optional
+        Whether to overwrite data in ``a`` (may improve performance). Default is False.
+        See :ref:`tutorial_linalg_overwrite` for details.
+    check_finite : bool, optional
+        Whether to check that the input matrix contains only finite numbers.
+        Disabling may give a performance gain, but may result in problems
+        (crashes, non-termination) if the inputs do contain infinities or NaNs.
+
+    Returns
+    -------
+    lu : (M, N) ndarray
+        Matrix containing U in its upper triangle, and L in its lower triangle.
+        The unit diagonal elements of L are not stored.
+    piv : (K,) ndarray
+        Pivot indices representing the permutation matrix P:
+        row i of matrix was interchanged with row piv[i].
+        Of shape ``(K,)``, with ``K = min(M, N)``.
+
+    See Also
+    --------
+    lu : gives lu factorization in more user-friendly format
+    lu_solve : solve an equation system using the LU factorization of a matrix
+
+    Notes
+    -----
+    This is a wrapper to the ``*GETRF`` routines from LAPACK. Unlike
+    :func:`lu`, it outputs the L and U factors into a single array
+    and returns pivot indices instead of a permutation matrix.
+
+    While the underlying ``*GETRF`` routines return 1-based pivot indices, the
+    ``piv`` array returned by ``lu_factor`` contains 0-based indices.
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy.linalg import lu_factor
+    >>> A = np.array([[2, 5, 8, 7], [5, 2, 2, 8], [7, 5, 6, 6], [5, 4, 4, 8]])
+    >>> lu, piv = lu_factor(A)
+    >>> piv
+    array([2, 2, 3, 3], dtype=int32)
+
+    Convert LAPACK's ``piv`` array to NumPy index and test the permutation
+
+    >>> def pivot_to_permutation(piv):
+    ...     perm = np.arange(len(piv))
+    ...     for i in range(len(piv)):
+    ...         perm[i], perm[piv[i]] = perm[piv[i]], perm[i]
+    ...     return perm
+    ...
+    >>> p_inv = pivot_to_permutation(piv)
+    >>> p_inv
+    array([2, 0, 3, 1])
+    >>> L, U = np.tril(lu, k=-1) + np.eye(4), np.triu(lu)
+    >>> np.allclose(A[p_inv] - L @ U, np.zeros((4, 4)))
+    True
+
+    The P matrix in P L U is defined by the inverse permutation and
+    can be recovered using argsort:
+
+    >>> p = np.argsort(p_inv)
+    >>> p
+    array([1, 3, 0, 2])
+    >>> np.allclose(A - L[p] @ U, np.zeros((4, 4)))
+    True
+
+    or alternatively:
+
+    >>> P = np.eye(4)[p]
+    >>> np.allclose(A - P @ L @ U, np.zeros((4, 4)))
+    True
+    """
+    if check_finite:
+        a1 = asarray_chkfinite(a)
+    else:
+        a1 = asarray(a)
+
+    # accommodate empty arrays
+    if a1.size == 0:
+        lu = np.empty_like(a1)
+        piv = np.arange(0, dtype=np.int64 if HAS_ILP64 else np.int32)
+        return lu, piv
+
+    overwrite_a = overwrite_a or (_datacopied(a1, a))
+
+    getrf, = get_lapack_funcs(('getrf',), (a1,))
+    lu, piv, info = getrf(a1, overwrite_a=overwrite_a)
+    if info < 0:
+        raise ValueError(
+            f'illegal value in {-info}th argument of internal getrf (lu_factor)'
+        )
+    if info > 0:
+        warn(
+            f"Diagonal number {info} is exactly zero. Singular matrix.",
+            LinAlgWarning,
+            stacklevel=2
+        )
+    return lu, piv
+
+
+def lu_solve(lu_and_piv, b, trans=0, overwrite_b=False, check_finite=True):
+    """Solve an equation system, ``a @ x = b``, given the LU factorization of a.
+
+    The documentation is written assuming array arguments are of specified
+    "core" shapes. However, array argument(s) of this function may have additional
+    "batch" dimensions prepended to the core shape. In this case, the array is treated
+    as a batch of lower-dimensional slices; see :ref:`linalg_batch` for details.
+
+    Parameters
+    ----------
+    lu_and_piv : tuple
+        Factorization of the coefficient matrix a in the form ``(lu, piv)``, as given
+        by lu_factor. In particular piv are 0-indexed pivot indices.
+    b : array
+        Right-hand side
+    trans : {0, 1, 2}, optional
+        Type of system to solve:
+
+        =====  =========
+        trans  system
+        =====  =========
+        0      a x   = b
+        1      a^T x = b
+        2      a^H x = b
+        =====  =========
+    overwrite_b : bool, optional
+        Whether to overwrite data in b (may increase performance)
+        See :ref:`tutorial_linalg_overwrite` for details.
+    check_finite : bool, optional
+        Whether to check that the input matrices contain only finite numbers.
+        Disabling may give a performance gain, but may result in problems
+        (crashes, non-termination) if the inputs do contain infinities or NaNs.
+
+    Returns
+    -------
+    x : array
+        Solution to the system
+
+    See Also
+    --------
+    lu_factor : LU factorize a matrix
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy.linalg import lu_factor, lu_solve
+    >>> A = np.array([[2, 5, 8, 7], [5, 2, 2, 8], [7, 5, 6, 6], [5, 4, 4, 8]])
+    >>> b = np.array([1, 1, 1, 1])
+    >>> lu, piv = lu_factor(A)
+    >>> x = lu_solve((lu, piv), b)
+    >>> np.allclose(A @ x - b, np.zeros((4,)))
+    True
+
+    """
+    (lu, piv) = lu_and_piv
+    return _lu_solve(lu, piv, b, trans=trans, overwrite_b=overwrite_b,
+                     check_finite=check_finite)
+
+
+@_apply_over_batch(('lu', 2), ('piv', 1), ('b', '1|2'))
+def _lu_solve(lu, piv, b, trans, overwrite_b, check_finite):
+    if check_finite:
+        b1 = asarray_chkfinite(b)
+    else:
+        b1 = asarray(b)
+
+    _deprecate_dtypes("lu_solve", lu, b)
+
+    overwrite_b = overwrite_b or _datacopied(b1, b)
+
+    if lu.shape[0] != b1.shape[0]:
+        raise ValueError(f"Shapes of lu {lu.shape} and b {b1.shape} are incompatible")
+
+    # accommodate empty arrays
+    if b1.size == 0:
+        m = lu_solve((np.eye(2, dtype=lu.dtype), [0, 1]), np.ones(2, dtype=b.dtype))
+        return np.empty_like(b1, dtype=m.dtype)
+
+    getrs, = get_lapack_funcs(('getrs',), (lu, b1))
+    x, info = getrs(lu, piv, b1, trans=trans, overwrite_b=overwrite_b)
+    if info == 0:
+        return x
+    raise ValueError(f'illegal value in {-info}th argument of internal gesv|posv')
+
+
+def lu(a, permute_l=False, overwrite_a=False, check_finite=True,
+       p_indices=False):
+    """
+    Compute LU decomposition of a matrix with partial pivoting.
+
+    The decomposition satisfies::
+
+        A = P @ L @ U
+
+    where ``P`` is a permutation matrix, ``L`` lower triangular with unit
+    diagonal elements, and ``U`` upper triangular. If `permute_l` is set to
+    ``True`` then ``L`` is returned already permuted and hence satisfying
+    ``A = L @ U``.
+
+    Array argument(s) of this function may have additional
+    "batch" dimensions prepended to the core shape. In this case, the array is treated
+    as a batch of lower-dimensional slices; see :ref:`linalg_batch` for details.
+
+    Parameters
+    ----------
+    a : (..., M, N) array_like
+        Array to decompose
+    permute_l : bool, optional
+        Perform the multiplication P*L (Default: do not permute)
+    overwrite_a : bool, optional
+        Whether to overwrite data in a (may improve performance). Default is False.
+        See :ref:`tutorial_linalg_overwrite` for details.
+    check_finite : bool, optional
+        Whether to check that the input matrix contains only finite numbers.
+        Disabling may give a performance gain, but may result in problems
+        (crashes, non-termination) if the inputs do contain infinities or NaNs.
+    p_indices : bool, optional
+        If ``True`` the permutation information is returned as row indices.
+        The default is ``False`` for backwards-compatibility reasons.
+
+    Returns
+    -------
+    (p, l, u) | (pl, u):
+        The tuple `(p, l, u)` is returned if `permute_l` is ``False`` (default) else
+        the tuple `(pl, u)` is returned, where:
+
+        p : (..., M, M) ndarray
+            Permutation arrays or vectors depending on `p_indices`.
+        l : (..., M, K) ndarray
+            Lower triangular or trapezoidal array with unit diagonal, where the last
+            dimension is ``K = min(M, N)``.
+        pl : (..., M, K) ndarray
+            Permuted L matrix with last dimension being ``K = min(M, N)``.
+        u : (..., K, N) ndarray
+            Upper triangular or trapezoidal array.
+
+    Notes
+    -----
+    Permutation matrices are costly since they are nothing but row reorder of
+    ``L`` and hence indices are strongly recommended to be used instead if the
+    permutation is required. The relation in the 2D case then becomes simply
+    ``A = L[P, :] @ U``. In higher dimensions, it is better to use `permute_l`
+    to avoid complicated indexing tricks.
+
+    In 2D case, if one has the indices however, for some reason, the
+    permutation matrix is still needed then it can be constructed by
+    ``np.eye(M)[P, :]``.
+
+    Examples
+    --------
+
+    >>> import numpy as np
+    >>> from scipy.linalg import lu
+    >>> A = np.array([[2, 5, 8, 7], [5, 2, 2, 8], [7, 5, 6, 6], [5, 4, 4, 8]])
+    >>> p, l, u = lu(A)
+    >>> np.allclose(A, p @ l @ u)
+    True
+    >>> p  # Permutation matrix
+    array([[0., 1., 0., 0.],  # Row index 1
+           [0., 0., 0., 1.],  # Row index 3
+           [1., 0., 0., 0.],  # Row index 0
+           [0., 0., 1., 0.]]) # Row index 2
+    >>> p, _, _ = lu(A, p_indices=True)
+    >>> p
+    array([1, 3, 0, 2], dtype=int32)  # as given by row indices above
+    >>> np.allclose(A, l[p, :] @ u)
+    True
+
+    We can also use nd-arrays, for example, a demonstration with 4D array:
+
+    >>> rng = np.random.default_rng()
+    >>> A = rng.uniform(low=-4, high=4, size=[3, 2, 4, 8])
+    >>> p, l, u = lu(A)
+    >>> p.shape, l.shape, u.shape
+    ((3, 2, 4, 4), (3, 2, 4, 4), (3, 2, 4, 8))
+    >>> np.allclose(A, p @ l @ u)
+    True
+    >>> PL, U = lu(A, permute_l=True)
+    >>> np.allclose(A, PL @ U)
+    True
+
+    """
+    a1 = np.asarray_chkfinite(a) if check_finite else np.asarray(a)
+    _deprecate_dtypes("lu", a1)
+    if a1.ndim < 2:
+        raise ValueError('The input array must be at least two-dimensional.')
+
+    # Also check if dtype is LAPACK compatible
+    a1, overwrite_a = _normalize_lapack_dtype(a1, overwrite_a)
+
+    *nd, m, n = a1.shape
+    k = min(m, n)
+    real_dchar = 'f' if a1.dtype.char in 'fF' else 'd'
+
+    # Empty input
+    if min(*a1.shape) == 0:
+        if permute_l:
+            PL = np.empty(shape=[*nd, m, k], dtype=a1.dtype)
+            U = np.empty(shape=[*nd, k, n], dtype=a1.dtype)
+            return PL, U
+        else:
+            P = (np.empty([*nd, 0], dtype=np.int32) if p_indices else
+                 np.empty([*nd, 0, 0], dtype=real_dchar))
+            L = np.empty(shape=[*nd, m, k], dtype=a1.dtype)
+            U = np.empty(shape=[*nd, k, n], dtype=a1.dtype)
+            return P, L, U
+
+    # Scalar case
+    if a1.shape[-2:] == (1, 1):
+        if permute_l:
+            return np.ones_like(a1), (a1 if overwrite_a else a1.copy())
+        else:
+            P = (np.zeros(shape=[*nd, m], dtype=int) if p_indices
+                 else np.ones_like(a1))
+            return P, np.ones_like(a1), (a1 if overwrite_a else a1.copy())
+
+    P, L, U = _linalg_lu(a1, permute_l, overwrite_a)
+
+    # Convert permutation vecs to permutation arrays
+    # permute_l=False needed to enter here to avoid wasted efforts
+    if (not p_indices) and (not permute_l):
+        if nd:
+            Pa = np.zeros([*nd, m, m], dtype=real_dchar)
+            # An unreadable index hack - One-hot encoding for perm matrices
+            nd_ix = np.ix_(*([np.arange(x) for x in nd]+[np.arange(m)]))
+            Pa[(*nd_ix, P)] = 1
+            P = Pa
+        else:  # 2D case
+            Pa = np.zeros([m, m], dtype=real_dchar)
+            Pa[np.arange(m), P] = 1
+            P = Pa
+
+    return (L, U) if permute_l else (P, L, U)
diff --git a/.venv/lib/python3.12/site-packages/scipy/linalg/_decomp_polar.py b/.venv/lib/python3.12/site-packages/scipy/linalg/_decomp_polar.py
new file mode 100644
index 0000000000000000000000000000000000000000..c25eb9892bc9c5a4c6a044aed64329f09da6104d
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/linalg/_decomp_polar.py
@@ -0,0 +1,113 @@
+import numpy as np
+from scipy._lib._util import _apply_over_batch
+from scipy.linalg import svd
+
+
+__all__ = ['polar']
+
+
+@_apply_over_batch(('a', 2))
+def polar(a, side="right"):
+    """
+    Compute the polar decomposition.
+
+    Returns the factors of the polar decomposition [1]_ `u` and `p` such
+    that ``a = up`` (if `side` is "right") or ``a = pu`` (if `side` is
+    "left"), where `p` is positive semidefinite. Depending on the shape
+    of `a`, either the rows or columns of `u` are orthonormal. When `a`
+    is a square array, `u` is a square unitary array. When `a` is not
+    square, the "canonical polar decomposition" [2]_ is computed.
+
+    Parameters
+    ----------
+    a : (m, n) array_like
+        The array to be factored.
+    side : {'left', 'right'}, optional
+        Determines whether a right or left polar decomposition is computed.
+        If `side` is "right", then ``a = up``.  If `side` is "left",  then
+        ``a = pu``.  The default is "right".
+
+    Returns
+    -------
+    u : (m, n) ndarray
+        If `a` is square, then `u` is unitary. If m > n, then the columns
+        of `u` are orthonormal, and if m < n, then the rows of `u` are
+        orthonormal.
+    p : ndarray
+        `p` is Hermitian positive semidefinite. If `a` is nonsingular, `p`
+        is positive definite. The shape of `p` is (n, n) or (m, m), depending
+        on whether `side` is "right" or "left", respectively.
+
+    References
+    ----------
+    .. [1] R. A. Horn and C. R. Johnson, "Matrix Analysis", Cambridge
+           University Press, 1985.
+    .. [2] N. J. Higham, "Functions of Matrices: Theory and Computation",
+           SIAM, 2008.
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy.linalg import polar
+    >>> a = np.array([[1, -1], [2, 4]])
+    >>> u, p = polar(a)
+    >>> u
+    array([[ 0.85749293, -0.51449576],
+           [ 0.51449576,  0.85749293]])
+    >>> p
+    array([[ 1.88648444,  1.2004901 ],
+           [ 1.2004901 ,  3.94446746]])
+
+    A non-square example, with m < n:
+
+    >>> b = np.array([[0.5, 1, 2], [1.5, 3, 4]])
+    >>> u, p = polar(b)
+    >>> u
+    array([[-0.21196618, -0.42393237,  0.88054056],
+           [ 0.39378971,  0.78757942,  0.4739708 ]])
+    >>> p
+    array([[ 0.48470147,  0.96940295,  1.15122648],
+           [ 0.96940295,  1.9388059 ,  2.30245295],
+           [ 1.15122648,  2.30245295,  3.65696431]])
+    >>> u.dot(p)   # Verify the decomposition.
+    array([[ 0.5,  1. ,  2. ],
+           [ 1.5,  3. ,  4. ]])
+    >>> u.dot(u.T)   # The rows of u are orthonormal.
+    array([[  1.00000000e+00,  -2.07353665e-17],
+           [ -2.07353665e-17,   1.00000000e+00]])
+
+    Another non-square example, with m > n:
+
+    >>> c = b.T
+    >>> u, p = polar(c)
+    >>> u
+    array([[-0.21196618,  0.39378971],
+           [-0.42393237,  0.78757942],
+           [ 0.88054056,  0.4739708 ]])
+    >>> p
+    array([[ 1.23116567,  1.93241587],
+           [ 1.93241587,  4.84930602]])
+    >>> u.dot(p)   # Verify the decomposition.
+    array([[ 0.5,  1.5],
+           [ 1. ,  3. ],
+           [ 2. ,  4. ]])
+    >>> u.T.dot(u)  # The columns of u are orthonormal.
+    array([[  1.00000000e+00,  -1.26363763e-16],
+           [ -1.26363763e-16,   1.00000000e+00]])
+
+    """
+    if side not in ['right', 'left']:
+        raise ValueError("`side` must be either 'right' or 'left'")
+    a = np.asarray(a)
+    if a.ndim != 2:
+        raise ValueError("`a` must be a 2-D array.")
+
+    w, s, vh = svd(a, full_matrices=False)
+    u = w.dot(vh)
+    if side == 'right':
+        # a = up
+        p = (vh.T.conj() * s).dot(vh)
+    else:
+        # a = pu
+        p = (w * s).dot(w.T.conj())
+    return u, p
diff --git a/.venv/lib/python3.12/site-packages/scipy/linalg/_decomp_qr.py b/.venv/lib/python3.12/site-packages/scipy/linalg/_decomp_qr.py
new file mode 100644
index 0000000000000000000000000000000000000000..1efae7c2a7584d5d04c41459328d6dfb7f306ec7
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/linalg/_decomp_qr.py
@@ -0,0 +1,521 @@
+"""QR decomposition functions."""
+import numpy as np
+
+from scipy._lib._util import _apply_over_batch, _deprecate_dtypes
+from scipy._lib.deprecation import _NoValue
+
+import warnings
+
+# Local imports
+from .lapack import _normalize_lapack_dtype, get_lapack_funcs, HAS_ILP64
+from ._misc import _datacopied
+from ._basic import _format_emit_errors_warnings
+from . import _batched_linalg
+
+__all__ = ['qr', 'qr_multiply', 'rq']
+
+
+def safecall(f, name, *args, **kwargs):
+    """Call a LAPACK routine, determining lwork automatically and handling
+    error return values"""
+    lwork = kwargs.get("lwork", None)
+    if lwork in (None, -1):
+        kwargs['lwork'] = -1
+        ret = f(*args, **kwargs)
+        kwargs['lwork'] = ret[-2][0].real.astype(np.int_)
+    ret = f(*args, **kwargs)
+    if ret[-1] < 0:
+        raise ValueError(f"illegal value in {-ret[-1]}th argument of internal {name}")
+    return ret[:-2]
+
+
+def qr(a, overwrite_a=False, lwork=_NoValue, mode="full", pivoting=False,
+    check_finite=True):
+    """
+    Compute QR decomposition of a matrix.
+
+    Calculate the decomposition ``A = Q R`` where Q is unitary/orthogonal
+    and R upper triangular.
+
+    Parameters
+    ----------
+    a : (..., M, N) array_like
+        Matrix to be decomposed
+    overwrite_a : bool, optional
+        Whether to overwrite data in `a` (may improve performance). Default is False.
+        See :ref:`tutorial_linalg_overwrite` for details.
+    lwork : int, optional
+        Work array size, lwork >= a.shape[1]. If None or -1, an optimal size
+        is computed.
+
+        .. deprecated:: 1.18.0
+            This keyword is deprecated as well as no longer in use and will be
+            removed in 1.20.0.
+
+    mode : {'full', 'r', 'economic', 'raw'}, optional
+        Determines what information is to be returned: either both Q and R
+        ('full', default), only R ('r') or both Q and R but computed in
+        economy-size ('economic', see Notes). The final option 'raw'
+        (added in SciPy 0.11) makes the function return two matrices
+        (Q, TAU) in the internal format used by LAPACK.
+    pivoting : bool, optional
+        Whether or not factorization should include pivoting for rank-revealing
+        qr decomposition. If pivoting, compute the decomposition
+        ``A[..., :, P] = Q @ R`` as above, but where P is chosen such that the
+        diagonal of R is non-increasing. Equivalently, albeit less efficiently,
+        an explicit P matrix may be formed explicitly by permuting the rows or columns
+        (depending on the side of the equation on which it is to be used) of
+        an identity matrix. See Examples.
+    check_finite : bool, optional
+        Whether to check that the input matrix contains only finite numbers.
+        Disabling may give a performance gain, but may result in problems
+        (crashes, non-termination) if the inputs do contain infinities or NaNs.
+
+    Returns
+    -------
+    Q : float or complex ndarray
+        Of shape (..., M, M), or (..., M, K) for ``mode='economic'``. Not returned
+        if ``mode='r'``. Replaced by tuple ``(Q, TAU)`` if ``mode='raw'``.
+    R : float or complex ndarray
+        Of shape (..., M, N), or (..., K, N) for ``mode in ['economic', 'raw']``.
+        ``K = min(M, N)``.
+    P : int ndarray
+        Of shape (..., N,) for ``pivoting=True``. Not returned if
+        ``pivoting=False``.
+
+    Raises
+    ------
+    LinAlgError
+        Raised if decomposition fails
+
+    Notes
+    -----
+    This is an interface to the LAPACK routines dgeqrf, zgeqrf,
+    dorgqr, zungqr, dgeqp3, and zgeqp3.
+
+    If ``mode=economic``, the shapes of Q and R are (..., M, K) and (..., K, N) instead
+    of (..., M,M) and (..., M,N), with ``K=min(M,N)``.
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy import linalg
+    >>> rng = np.random.default_rng()
+    >>> a = rng.standard_normal((9, 6))
+
+    >>> q, r = linalg.qr(a)
+    >>> np.allclose(a, np.dot(q, r))
+    True
+    >>> q.shape, r.shape
+    ((9, 9), (9, 6))
+
+    >>> r2 = linalg.qr(a, mode='r')
+    >>> np.allclose(r, r2)
+    True
+
+    >>> q3, r3 = linalg.qr(a, mode='economic')
+    >>> q3.shape, r3.shape
+    ((9, 6), (6, 6))
+
+    >>> q4, r4, p4 = linalg.qr(a, pivoting=True)
+    >>> d = np.abs(np.diag(r4))
+    >>> np.all(d[1:] <= d[:-1])
+    True
+    >>> np.allclose(a[:, p4], np.dot(q4, r4))
+    True
+    >>> P = np.eye(p4.size)[p4]
+    >>> np.allclose(a, np.dot(q4, r4) @ P)
+    True
+    >>> np.allclose(a @ P.T, np.dot(q4, r4))
+    True
+    >>> q4.shape, r4.shape, p4.shape
+    ((9, 9), (9, 6), (6,))
+
+    >>> q5, r5, p5 = linalg.qr(a, mode='economic', pivoting=True)
+    >>> q5.shape, r5.shape, p5.shape
+    ((9, 6), (6, 6), (6,))
+    >>> P = np.eye(6)[:, p5]
+    >>> np.allclose(a @ P, np.dot(q5, r5))
+    True
+    """
+    # structure mappings, keep in sync with the C side
+    modes = {
+        "full": 1,
+        "qr": 1, # equivalent to `full`
+        "r": 11,
+        "raw": 21,
+        "economic": 31
+    }
+
+    # 'qr' was the old default, equivalent to 'full'. Neither 'full' nor
+    # 'qr' are used below.
+    # 'raw' is used internally by qr_multiply
+    if mode not in modes.keys():
+        raise ValueError(f"Mode argument should be one of {list(modes.keys())}")
+
+    modeFlag = modes[mode] # convert the string to an int for the C enum
+
+    if check_finite:
+        a1 = np.asarray_chkfinite(a)
+    else:
+        a1 = np.asarray(a)
+
+    _deprecate_dtypes("linalg.qr", a1)
+
+    if a1.ndim < 2:
+        raise ValueError("Expected at least a 2-D array")
+
+    M, N = a1.shape[-2], a1.shape[-1]
+
+    # Throw error for backwards compat, else raise DeprecationWarning
+    if lwork is not _NoValue:
+        if lwork is not None and lwork != -1 and lwork <= M:
+            raise ValueError(f"lwork should be None, -1 or > M, got {lwork}")
+
+        else:
+            warnings.warn(
+                "scipy.linalg: the `lwork` keyword is deprecated and no longer in use"
+                " as of SciPy 1.18.0 and will be removed in SciPy 1.20.0",
+                DeprecationWarning,
+                stacklevel=2
+            )
+
+    # First normalize dtypes to ensure consistent return types
+    a1, overwrite_a = _normalize_lapack_dtype(a1, overwrite_a)
+
+    # accommodate empty arrays
+    if a1.size == 0:
+        K = min(M, N)
+        batch_shape = a1.shape[:-2]
+
+        if mode not in ['economic', 'raw']:
+            Q = np.empty_like(a1, shape=batch_shape + (M, M))
+            Q[..., :, :] = np.identity(M)
+            R = np.empty_like(a1)
+        else:
+            Q = np.empty_like(a1, shape=batch_shape + (M, K))
+            R = np.empty_like(a1, shape=batch_shape + (K, N))
+
+        if pivoting:
+            Rj = R, np.arange(N, dtype=np.int64 if HAS_ILP64 else np.int32)
+        else:
+            Rj = R,
+
+        if mode == 'r':
+            return Rj
+        elif mode == 'raw':
+            qr = np.empty_like(a1, shape=batch_shape + (M, N))
+            tau = np.zeros_like(a1, shape=batch_shape + (K,))
+            return ((qr, tau),) + Rj
+
+        return (Q,) + Rj
+
+    if not (a1.flags['ALIGNED'] and a1.dtype.byteorder == '='):
+        overwrite_a = True
+        a1 = a1.copy()
+
+    overwrite_a = overwrite_a or (_datacopied(a1, a))
+    overwrite_a = overwrite_a and (a1.ndim == 2) and a1.flags["F_CONTIGUOUS"]
+
+    # heavy lifting
+    Q, R, tau, jpvt, err_lst = _batched_linalg._qr(a1, overwrite_a, modeFlag, pivoting)
+
+    if err_lst:
+        _format_emit_errors_warnings(err_lst)
+
+    # construct return objects
+    if pivoting:
+        Rj = R, jpvt
+    else:
+        Rj = (R,)
+
+    if modeFlag == modes["raw"]:
+        Q = (Q, tau)
+    elif modeFlag == modes["economic"] and M < N:
+        Q = Q[..., :, :M]
+
+    if modeFlag == modes["r"]:
+        return Rj
+    else:
+        return (Q,) + Rj
+
+
+@_apply_over_batch(('a', 2), ('c', '1|2'))
+def qr_multiply(a, c, mode='right', pivoting=False, conjugate=False,
+                overwrite_a=False, overwrite_c=False):
+    """
+    Calculate the QR decomposition and multiply Q with a matrix.
+
+    Calculate the decomposition ``A = Q R`` where Q is unitary/orthogonal
+    and R upper triangular. Multiply Q with a vector or a matrix c.
+
+    Parameters
+    ----------
+    a : (M, N), array_like
+        Input array
+    c : array_like
+        Input array to be multiplied by ``q``.
+    mode : {'left', 'right'}, optional
+        ``Q @ c`` is returned if mode is 'left', ``c @ Q`` is returned if
+        mode is 'right'.
+        The shape of c must be appropriate for the matrix multiplications,
+        if mode is 'left', ``min(a.shape) == c.shape[0]``,
+        if mode is 'right', ``a.shape[0] == c.shape[1]``.
+    pivoting : bool, optional
+        Whether or not factorization should include pivoting for rank-revealing
+        qr decomposition, see the documentation of qr.
+    conjugate : bool, optional
+        Whether Q should be complex-conjugated. This might be faster
+        than explicit conjugation.
+    overwrite_a : bool, optional
+        Whether to overwrite data in `a` (may improve performance). Default is False.
+        See :ref:`tutorial_linalg_overwrite` for details.
+    overwrite_c : bool, optional
+        Whether data in c is overwritten (may improve performance).
+        If this is used, c must be big enough to keep the result,
+        i.e. ``c.shape[0]`` = ``a.shape[0]`` if mode is 'left'.
+        See :ref:`tutorial_linalg_overwrite` for details.
+
+    Returns
+    -------
+    CQ : ndarray
+        The product of ``Q`` and ``c``.
+    R : (K, N), ndarray
+        R array of the resulting QR factorization where ``K = min(M, N)``.
+    P : (N,) ndarray
+        Integer pivot array. Only returned when ``pivoting=True``.
+
+    Raises
+    ------
+    LinAlgError
+        Raised if QR decomposition fails.
+
+    Notes
+    -----
+    This is an interface to the LAPACK routines ``?GEQRF``, ``?ORMQR``,
+    ``?UNMQR``, and ``?GEQP3``.
+
+    .. versionadded:: 0.11.0
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy.linalg import qr_multiply, qr
+    >>> A = np.array([[1, 3, 3], [2, 3, 2], [2, 3, 3], [1, 3, 2]])
+    >>> qc, r1, piv1 = qr_multiply(A, 2*np.eye(4), pivoting=1)
+    >>> qc
+    array([[-1.,  1., -1.],
+           [-1., -1.,  1.],
+           [-1., -1., -1.],
+           [-1.,  1.,  1.]])
+    >>> r1
+    array([[-6., -3., -5.            ],
+           [ 0., -1., -1.11022302e-16],
+           [ 0.,  0., -1.            ]])
+    >>> piv1
+    array([1, 0, 2], dtype=int32)
+    >>> q2, r2, piv2 = qr(A, mode='economic', pivoting=1)
+    >>> np.allclose(2*q2 - qc, np.zeros((4, 3)))
+    True
+
+    """
+    if mode not in ['left', 'right']:
+        raise ValueError("Mode argument can only be 'left' or 'right' but "
+                         f"not '{mode}'")
+    c = np.asarray_chkfinite(c)
+    if c.ndim < 2:
+        onedim = True
+        c = np.atleast_2d(c)
+        if mode == "left":
+            c = c.T
+    else:
+        onedim = False
+
+    a = np.atleast_2d(np.asarray(a))  # chkfinite done in qr
+    M, N = a.shape
+
+    if mode == 'left':
+        if c.shape[0] != min(M, N + overwrite_c*(M-N)):
+            raise ValueError('Array shapes are not compatible for Q @ c'
+                             f' operation: {a.shape} vs {c.shape}')
+    else:
+        if M != c.shape[1]:
+            raise ValueError('Array shapes are not compatible for c @ Q'
+                             f' operation: {c.shape} vs {a.shape}')
+
+    raw = qr(a, overwrite_a, mode="raw", pivoting=pivoting)
+    Q, tau = raw[0]
+
+    # accommodate empty arrays
+    if c.size == 0:
+        return (np.empty_like(c),) + raw[1:]
+
+    gor_un_mqr, = get_lapack_funcs(('ormqr',), (Q,))
+    if gor_un_mqr.typecode in ('s', 'd'):
+        trans = "T"
+    else:
+        trans = "C"
+
+    Q = Q[:, :min(M, N)]
+    if M > N and mode == "left" and not overwrite_c:
+        if conjugate:
+            cc = np.zeros((c.shape[1], M), dtype=c.dtype, order="F")
+            cc[:, :N] = c.T
+        else:
+            cc = np.zeros((M, c.shape[1]), dtype=c.dtype, order="F")
+            cc[:N, :] = c
+            trans = "N"
+        if conjugate:
+            lr = "R"
+        else:
+            lr = "L"
+        overwrite_c = True
+    elif c.flags["C_CONTIGUOUS"] and trans == "T" or conjugate:
+        cc = c.T
+        if mode == "left":
+            lr = "R"
+        else:
+            lr = "L"
+    else:
+        trans = "N"
+        cc = c
+        if mode == "left":
+            lr = "L"
+        else:
+            lr = "R"
+    cQ, = safecall(gor_un_mqr, "gormqr/gunmqr", lr, trans, Q, tau, cc,
+                   overwrite_c=overwrite_c)
+    if trans != "N":
+        cQ = cQ.T
+    if mode == "right":
+        cQ = cQ[:, :min(M, N)]
+    if onedim:
+        cQ = cQ.ravel()
+
+    return (cQ,) + raw[1:]
+
+
+@_apply_over_batch(('a', 2))
+def rq(a, overwrite_a=False, lwork=None, mode='full', check_finite=True):
+    """
+    Compute RQ decomposition of a matrix.
+
+    Calculate the decomposition ``A = R Q`` where Q is unitary/orthogonal
+    and R upper triangular.
+
+    Parameters
+    ----------
+    a : (M, N) array_like
+        Matrix to be decomposed
+    overwrite_a : bool, optional
+        Whether to overwrite data in `a` (may improve performance). Default is False.
+        See :ref:`tutorial_linalg_overwrite` for details.
+    lwork : int, optional
+        Work array size, lwork >= a.shape[1]. If None or -1, an optimal size
+        is computed.
+    mode : {'full', 'r', 'economic'}, optional
+        Determines what information is to be returned: either both Q and R
+        ('full', default), only R ('r') or both Q and R but computed in
+        economy-size ('economic', see Notes).
+    check_finite : bool, optional
+        Whether to check that the input matrix contains only finite numbers.
+        Disabling may give a performance gain, but may result in problems
+        (crashes, non-termination) if the inputs do contain infinities or NaNs.
+
+    Returns
+    -------
+    R : float or complex ndarray
+        Of shape (M, N) or (M, K) for ``mode='economic'``. ``K = min(M, N)``.
+    Q : float or complex ndarray
+        Of shape (N, N) or (K, N) for ``mode='economic'``. Not returned
+        if ``mode='r'``.
+
+    Raises
+    ------
+    LinAlgError
+        If decomposition fails.
+
+    Notes
+    -----
+    This is an interface to the LAPACK routines sgerqf, dgerqf, cgerqf, zgerqf,
+    sorgrq, dorgrq, cungrq and zungrq.
+
+    If ``mode=economic``, the shapes of Q and R are (K, N) and (M, K) instead
+    of (N,N) and (M,N), with ``K=min(M,N)``.
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy import linalg
+    >>> rng = np.random.default_rng()
+    >>> a = rng.standard_normal((6, 9))
+    >>> r, q = linalg.rq(a)
+    >>> np.allclose(a, r @ q)
+    True
+    >>> r.shape, q.shape
+    ((6, 9), (9, 9))
+    >>> r2 = linalg.rq(a, mode='r')
+    >>> np.allclose(r, r2)
+    True
+    >>> r3, q3 = linalg.rq(a, mode='economic')
+    >>> r3.shape, q3.shape
+    ((6, 6), (6, 9))
+
+    """
+    if mode not in ['full', 'r', 'economic']:
+        raise ValueError(
+                 "Mode argument should be one of ['full', 'r', 'economic']")
+
+    if check_finite:
+        a1 = np.asarray_chkfinite(a)
+    else:
+        a1 = np.asarray(a)
+    if len(a1.shape) != 2:
+        raise ValueError('expected matrix')
+
+    M, N = a1.shape
+
+    # accommodate empty arrays
+    if a1.size == 0:
+        K = min(M, N)
+
+        if not mode == 'economic':
+            R = np.empty_like(a1)
+            Q = np.empty_like(a1, shape=(N, N))
+            Q[...] = np.identity(N)
+        else:
+            R = np.empty_like(a1, shape=(M, K))
+            Q = np.empty_like(a1, shape=(K, N))
+
+        if mode == 'r':
+            return R
+        return R, Q
+
+    overwrite_a = overwrite_a or (_datacopied(a1, a))
+
+    gerqf, = get_lapack_funcs(('gerqf',), (a1,))
+    rq, tau = safecall(gerqf, 'gerqf', a1, lwork=lwork,
+                       overwrite_a=overwrite_a)
+    if not mode == 'economic' or N < M:
+        R = np.triu(rq, N-M)
+    else:
+        R = np.triu(rq[-M:, -M:])
+
+    if mode == 'r':
+        return R
+
+    gor_un_grq, = get_lapack_funcs(('orgrq',), (rq,))
+
+    if N < M:
+        Q, = safecall(gor_un_grq, "gorgrq/gungrq", rq[-N:], tau, lwork=lwork,
+                      overwrite_a=1)
+    elif mode == 'economic':
+        Q, = safecall(gor_un_grq, "gorgrq/gungrq", rq, tau, lwork=lwork,
+                      overwrite_a=1)
+    else:
+        rq1 = np.empty((N, N), dtype=rq.dtype)
+        rq1[-M:] = rq
+        Q, = safecall(gor_un_grq, "gorgrq/gungrq", rq1, tau, lwork=lwork,
+                      overwrite_a=1)
+
+    return R, Q
diff --git a/.venv/lib/python3.12/site-packages/scipy/linalg/_decomp_qz.py b/.venv/lib/python3.12/site-packages/scipy/linalg/_decomp_qz.py
new file mode 100644
index 0000000000000000000000000000000000000000..265d86453cf0fb7dac62abae3a9b92e20c7b1ee0
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/linalg/_decomp_qz.py
@@ -0,0 +1,456 @@
+import warnings
+
+import numpy as np
+from numpy import asarray_chkfinite
+from scipy._lib._util import _apply_over_batch
+from ._misc import LinAlgError, _datacopied, LinAlgWarning
+from .lapack import get_lapack_funcs
+
+
+__all__ = ['qz', 'ordqz']
+
+_double_precision = ['i', 'l', 'd']
+
+
+def _select_function(sort):
+    if callable(sort):
+        # assume the user knows what they're doing
+        sfunction = sort
+    elif sort == 'lhp':
+        sfunction = _lhp
+    elif sort == 'rhp':
+        sfunction = _rhp
+    elif sort == 'iuc':
+        sfunction = _iuc
+    elif sort == 'ouc':
+        sfunction = _ouc
+    else:
+        raise ValueError("sort parameter must be None, a callable, or "
+                         "one of ('lhp','rhp','iuc','ouc')")
+
+    return sfunction
+
+
+def _lhp(x, y):
+    out = np.empty_like(x, dtype=bool)
+    nonzero = (y != 0)
+    # handles (x, y) = (0, 0) too
+    out[~nonzero] = False
+    out[nonzero] = (np.real(x[nonzero]/y[nonzero]) < 0.0)
+    return out
+
+
+def _rhp(x, y):
+    out = np.empty_like(x, dtype=bool)
+    nonzero = (y != 0)
+    # handles (x, y) = (0, 0) too
+    out[~nonzero] = False
+    out[nonzero] = (np.real(x[nonzero]/y[nonzero]) > 0.0)
+    return out
+
+
+def _iuc(x, y):
+    out = np.empty_like(x, dtype=bool)
+    nonzero = (y != 0)
+    # handles (x, y) = (0, 0) too
+    out[~nonzero] = False
+    out[nonzero] = (abs(x[nonzero]/y[nonzero]) < 1.0)
+    return out
+
+
+def _ouc(x, y):
+    out = np.empty_like(x, dtype=bool)
+    xzero = (x == 0)
+    yzero = (y == 0)
+    out[xzero & yzero] = False
+    out[~xzero & yzero] = True
+    out[~yzero] = (abs(x[~yzero]/y[~yzero]) > 1.0)
+    return out
+
+
+def _qz(A, B, output='real', lwork=None, sort=None, overwrite_a=False,
+        overwrite_b=False, check_finite=True):
+    if sort is not None:
+        # Disabled due to segfaults on win32, see ticket 1717.
+        raise ValueError("The 'sort' input of qz() has to be None and will be "
+                         "removed in a future release. Use ordqz instead.")
+
+    if output not in ['real', 'complex', 'r', 'c']:
+        raise ValueError("argument must be 'real', or 'complex'")
+
+    if check_finite:
+        a1 = asarray_chkfinite(A)
+        b1 = asarray_chkfinite(B)
+    else:
+        a1 = np.asarray(A)
+        b1 = np.asarray(B)
+
+    a_m, a_n = a1.shape
+    b_m, b_n = b1.shape
+    if not (a_m == a_n == b_m == b_n):
+        raise ValueError("Array dimensions must be square and agree")
+
+    typa = a1.dtype.char
+    if output in ['complex', 'c'] and typa not in ['F', 'D']:
+        if typa in _double_precision:
+            a1 = a1.astype('D')
+            typa = 'D'
+        else:
+            a1 = a1.astype('F')
+            typa = 'F'
+    typb = b1.dtype.char
+    if output in ['complex', 'c'] and typb not in ['F', 'D']:
+        if typb in _double_precision:
+            b1 = b1.astype('D')
+            typb = 'D'
+        else:
+            b1 = b1.astype('F')
+            typb = 'F'
+
+    overwrite_a = overwrite_a or (_datacopied(a1, A))
+    overwrite_b = overwrite_b or (_datacopied(b1, B))
+
+    gges, = get_lapack_funcs(('gges',), (a1, b1))
+
+    if lwork is None or lwork == -1:
+        # get optimal work array size
+        result = gges(lambda x: None, a1, b1, lwork=-1)
+        lwork = result[-2][0].real.astype(int)
+
+    def sfunction(x):
+        return None
+    result = gges(sfunction, a1, b1, lwork=lwork, overwrite_a=overwrite_a,
+                  overwrite_b=overwrite_b, sort_t=0)
+
+    info = result[-1]
+    if info < 0:
+        raise ValueError(f"Illegal value in argument {-info} of gges")
+    elif info > 0 and info <= a_n:
+        warnings.warn("The QZ iteration failed. (a,b) are not in Schur "
+                      "form, but ALPHAR(j), ALPHAI(j), and BETA(j) should be "
+                      f"correct for J={info-1},...,N", LinAlgWarning,
+                      stacklevel=3)
+    elif info == a_n+1:
+        raise LinAlgError("Something other than QZ iteration failed")
+    elif info == a_n+2:
+        raise LinAlgError("After reordering, roundoff changed values of some "
+                          "complex eigenvalues so that leading eigenvalues "
+                          "in the Generalized Schur form no longer satisfy "
+                          "sort=True. This could also be due to scaling.")
+    elif info == a_n+3:
+        raise LinAlgError("Reordering failed in tgsen")
+
+    return result, gges.typecode
+
+
+@_apply_over_batch(('A', 2), ('B', 2))
+def qz(A, B, output='real', lwork=None, sort=None, overwrite_a=False,
+       overwrite_b=False, check_finite=True):
+    """
+    QZ decomposition for generalized eigenvalues of a pair of matrices.
+
+    The QZ, or generalized Schur, decomposition for a pair of n-by-n
+    matrices (A,B) is::
+
+        (A,B) = (Q @ AA @ Z*, Q @ BB @ Z*)
+
+    where AA, BB is in generalized Schur form if BB is upper-triangular
+    with non-negative diagonal and AA is upper-triangular, or for real QZ
+    decomposition (``output='real'``) block upper triangular with 1x1
+    and 2x2 blocks. In this case, the 1x1 blocks correspond to real
+    generalized eigenvalues and 2x2 blocks are 'standardized' by making
+    the corresponding elements of BB have the form::
+
+        [ a 0 ]
+        [ 0 b ]
+
+    and the pair of corresponding 2x2 blocks in AA and BB will have a complex
+    conjugate pair of generalized eigenvalues. If (``output='complex'``) or
+    A and B are complex matrices, Z' denotes the conjugate-transpose of Z.
+    Q and Z are unitary matrices.
+
+    Parameters
+    ----------
+    A : (N, N) array_like
+        2-D array to decompose
+    B : (N, N) array_like
+        2-D array to decompose
+    output : {'real', 'complex'}, optional
+        Construct the real or complex QZ decomposition for real matrices.
+        Default is 'real'.
+    lwork : int, optional
+        Work array size. If None or -1, it is automatically computed.
+    sort : {None, callable, 'lhp', 'rhp', 'iuc', 'ouc'}, optional
+        NOTE: THIS INPUT IS DISABLED FOR NOW. Use ordqz instead.
+
+        Specifies whether the upper eigenvalues should be sorted. A callable
+        may be passed that, given an eigenvalue, returns a boolean denoting
+        whether the eigenvalue should be sorted to the top-left (True). For
+        real matrix pairs, the sort function takes three real arguments
+        (alphar, alphai, beta). The eigenvalue
+        ``x = (alphar + alphai*1j)/beta``. For complex matrix pairs or
+        output='complex', the sort function takes two complex arguments
+        (alpha, beta). The eigenvalue ``x = (alpha/beta)``.  Alternatively,
+        string parameters may be used:
+
+        - 'lhp'   Left-hand plane (x.real < 0.0)
+        - 'rhp'   Right-hand plane (x.real > 0.0)
+        - 'iuc'   Inside the unit circle (x*x.conjugate() < 1.0)
+        - 'ouc'   Outside the unit circle (x*x.conjugate() > 1.0)
+
+        Defaults to None (no sorting).
+    overwrite_a : bool, optional
+        Whether to overwrite data in a (may improve performance)
+        See :ref:`tutorial_linalg_overwrite` for details.
+    overwrite_b : bool, optional
+        Whether to overwrite data in b (may improve performance)
+        See :ref:`tutorial_linalg_overwrite` for details.
+    check_finite : bool, optional
+        If true checks the elements of `A` and `B` are finite numbers. If
+        false does no checking and passes matrix through to
+        underlying algorithm.
+
+    Returns
+    -------
+    AA : (N, N) ndarray
+        Generalized Schur form of A.
+    BB : (N, N) ndarray
+        Generalized Schur form of B.
+    Q : (N, N) ndarray
+        The left Schur vectors.
+    Z : (N, N) ndarray
+        The right Schur vectors.
+
+    See Also
+    --------
+    ordqz
+
+    Notes
+    -----
+    Q is transposed versus the equivalent function in Matlab.
+
+    .. versionadded:: 0.11.0
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy.linalg import qz
+
+    >>> A = np.array([[1, 2, -1], [5, 5, 5], [2, 4, -8]])
+    >>> B = np.array([[1, 1, -3], [3, 1, -1], [5, 6, -2]])
+
+    Compute the decomposition.  The QZ decomposition is not unique, so
+    depending on the underlying library that is used, there may be
+    differences in the signs of coefficients in the following output.
+
+    >>> AA, BB, Q, Z = qz(A, B)
+    >>> AA
+    array([[-1.36949157, -4.05459025,  7.44389431],
+           [ 0.        ,  7.65653432,  5.13476017],
+           [ 0.        , -0.65978437,  2.4186015 ]])  # may vary
+    >>> BB
+    array([[ 1.71890633, -1.64723705, -0.72696385],
+           [ 0.        ,  8.6965692 , -0.        ],
+           [ 0.        ,  0.        ,  2.27446233]])  # may vary
+    >>> Q
+    array([[-0.37048362,  0.1903278 ,  0.90912992],
+           [-0.90073232,  0.16534124, -0.40167593],
+           [ 0.22676676,  0.96769706, -0.11017818]])  # may vary
+    >>> Z
+    array([[-0.67660785,  0.63528924, -0.37230283],
+           [ 0.70243299,  0.70853819, -0.06753907],
+           [ 0.22088393, -0.30721526, -0.92565062]])  # may vary
+
+    Verify the QZ decomposition.  With real output, we only need the
+    transpose of ``Z`` in the following expressions.
+
+    >>> Q @ AA @ Z.T  # Should be A
+    array([[ 1.,  2., -1.],
+           [ 5.,  5.,  5.],
+           [ 2.,  4., -8.]])
+    >>> Q @ BB @ Z.T  # Should be B
+    array([[ 1.,  1., -3.],
+           [ 3.,  1., -1.],
+           [ 5.,  6., -2.]])
+
+    Repeat the decomposition, but with ``output='complex'``.
+
+    >>> AA, BB, Q, Z = qz(A, B, output='complex')
+
+    For conciseness in the output, we use ``np.set_printoptions()`` to set
+    the output precision of NumPy arrays to 3 and display tiny values as 0.
+
+    >>> np.set_printoptions(precision=3, suppress=True)
+    >>> AA
+    array([[-1.369+0.j   ,  2.248+4.237j,  4.861-5.022j],
+           [ 0.   +0.j   ,  7.037+2.922j,  0.794+4.932j],
+           [ 0.   +0.j   ,  0.   +0.j   ,  2.655-1.103j]])  # may vary
+    >>> BB
+    array([[ 1.719+0.j   , -1.115+1.j   , -0.763-0.646j],
+           [ 0.   +0.j   ,  7.24 +0.j   , -3.144+3.322j],
+           [ 0.   +0.j   ,  0.   +0.j   ,  2.732+0.j   ]])  # may vary
+    >>> Q
+    array([[ 0.326+0.175j, -0.273-0.029j, -0.886-0.052j],
+           [ 0.794+0.426j, -0.093+0.134j,  0.402-0.02j ],
+           [-0.2  -0.107j, -0.816+0.482j,  0.151-0.167j]])  # may vary
+    >>> Z
+    array([[ 0.596+0.32j , -0.31 +0.414j,  0.393-0.347j],
+           [-0.619-0.332j, -0.479+0.314j,  0.154-0.393j],
+           [-0.195-0.104j,  0.576+0.27j ,  0.715+0.187j]])  # may vary
+
+    With complex arrays, we must use ``Z.conj().T`` in the following
+    expressions to verify the decomposition.
+
+    >>> Q @ AA @ Z.conj().T  # Should be A
+    array([[ 1.-0.j,  2.-0.j, -1.-0.j],
+           [ 5.+0.j,  5.+0.j,  5.-0.j],
+           [ 2.+0.j,  4.+0.j, -8.+0.j]])
+    >>> Q @ BB @ Z.conj().T  # Should be B
+    array([[ 1.+0.j,  1.+0.j, -3.+0.j],
+           [ 3.-0.j,  1.-0.j, -1.+0.j],
+           [ 5.+0.j,  6.+0.j, -2.+0.j]])
+
+    """
+    # output for real
+    # AA, BB, sdim, alphar, alphai, beta, vsl, vsr, work, info
+    # output for complex
+    # AA, BB, sdim, alpha, beta, vsl, vsr, work, info
+    result, _ = _qz(A, B, output=output, lwork=lwork, sort=sort,
+                    overwrite_a=overwrite_a, overwrite_b=overwrite_b,
+                    check_finite=check_finite)
+    return result[0], result[1], result[-4], result[-3]
+
+
+@_apply_over_batch(('A', 2), ('B', 2))
+def ordqz(A, B, sort='lhp', output='real', overwrite_a=False,
+          overwrite_b=False, check_finite=True):
+    """QZ decomposition for a pair of matrices with reordering.
+
+    Parameters
+    ----------
+    A : (N, N) array_like
+        2-D array to decompose
+    B : (N, N) array_like
+        2-D array to decompose
+    sort : {callable, 'lhp', 'rhp', 'iuc', 'ouc'}, optional
+        Specifies whether the upper eigenvalues should be sorted. A
+        callable may be passed that, given an ordered pair ``(alpha,
+        beta)`` representing the eigenvalue ``x = (alpha/beta)``,
+        returns a boolean denoting whether the eigenvalue should be
+        sorted to the top-left (True). For the real matrix pairs
+        ``beta`` is real while ``alpha`` can be complex, and for
+        complex matrix pairs both ``alpha`` and ``beta`` can be
+        complex. The callable must be able to accept a NumPy
+        array. Alternatively, string parameters may be used:
+
+        - 'lhp'   Left-hand plane (x.real < 0.0)
+        - 'rhp'   Right-hand plane (x.real > 0.0)
+        - 'iuc'   Inside the unit circle (x*x.conjugate() < 1.0)
+        - 'ouc'   Outside the unit circle (x*x.conjugate() > 1.0)
+
+        With the predefined sorting functions, an infinite eigenvalue
+        (i.e., ``alpha != 0`` and ``beta = 0``) is considered to lie in
+        neither the left-hand nor the right-hand plane, but it is
+        considered to lie outside the unit circle. For the eigenvalue
+        ``(alpha, beta) = (0, 0)``, the predefined sorting functions
+        all return `False`.
+    output : str {'real','complex'}, optional
+        Construct the real or complex QZ decomposition for real matrices.
+        Default is 'real'.
+    overwrite_a : bool, optional
+        If True, the contents of A are overwritten.
+        See :ref:`tutorial_linalg_overwrite` for details.
+    overwrite_b : bool, optional
+        If True, the contents of B are overwritten.
+        See :ref:`tutorial_linalg_overwrite` for details.
+    check_finite : bool, optional
+        If true checks the elements of `A` and `B` are finite numbers. If
+        false does no checking and passes matrix through to
+        underlying algorithm.
+
+    Returns
+    -------
+    AA : (N, N) ndarray
+        Generalized Schur form of A.
+    BB : (N, N) ndarray
+        Generalized Schur form of B.
+    alpha : (N,) ndarray
+        alpha = alphar + alphai * 1j. See notes.
+    beta : (N,) ndarray
+        See notes.
+    Q : (N, N) ndarray
+        The left Schur vectors.
+    Z : (N, N) ndarray
+        The right Schur vectors.
+
+    See Also
+    --------
+    qz
+
+    Notes
+    -----
+    On exit, ``(ALPHAR(j) + ALPHAI(j)*i)/BETA(j), j=1,...,N``, will be the
+    generalized eigenvalues.  ``ALPHAR(j) + ALPHAI(j)*i`` and
+    ``BETA(j),j=1,...,N`` are the diagonals of the complex Schur form (S,T)
+    that would result if the 2-by-2 diagonal blocks of the real generalized
+    Schur form of (A,B) were further reduced to triangular form using complex
+    unitary transformations. If ALPHAI(j) is zero, then the jth eigenvalue is
+    real; if positive, then the ``j``\\ th and ``(j+1)``\\ st eigenvalues are a
+    complex conjugate pair, with ``ALPHAI(j+1)`` negative.
+
+    .. versionadded:: 0.17.0
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy.linalg import ordqz
+    >>> A = np.array([[2, 5, 8, 7], [5, 2, 2, 8], [7, 5, 6, 6], [5, 4, 4, 8]])
+    >>> B = np.array([[0, 6, 0, 0], [5, 0, 2, 1], [5, 2, 6, 6], [4, 7, 7, 7]])
+    >>> AA, BB, alpha, beta, Q, Z = ordqz(A, B, sort='lhp')
+
+    Since we have sorted for left half plane eigenvalues, negatives come first
+
+    >>> (alpha/beta).real < 0
+    array([ True,  True, False, False], dtype=bool)
+
+    """
+    (AA, BB, _, *ab, Q, Z, _, _), typ = _qz(A, B, output=output, sort=None,
+                                            overwrite_a=overwrite_a,
+                                            overwrite_b=overwrite_b,
+                                            check_finite=check_finite)
+
+    if typ == 's':
+        alpha, beta = ab[0] + ab[1]*np.complex64(1j), ab[2]
+    elif typ == 'd':
+        alpha, beta = ab[0] + ab[1]*1.j, ab[2]
+    else:
+        alpha, beta = ab
+
+    sfunction = _select_function(sort)
+    select = sfunction(alpha, beta)
+
+    tgsen = get_lapack_funcs('tgsen', (AA, BB))
+    # the real case needs 4n + 16 lwork
+    lwork = 4*AA.shape[0] + 16 if typ in 'sd' else 1
+    AAA, BBB, *ab, QQ, ZZ, _, _, _, _, info = tgsen(select, AA, BB, Q, Z,
+                                                    ijob=0,
+                                                    lwork=lwork, liwork=1)
+
+    # Once more for tgsen output
+    if typ == 's':
+        alpha, beta = ab[0] + ab[1]*np.complex64(1j), ab[2]
+    elif typ == 'd':
+        alpha, beta = ab[0] + ab[1]*1.j, ab[2]
+    else:
+        alpha, beta = ab
+
+    if info < 0:
+        raise ValueError(f"Illegal value in argument {-info} of tgsen")
+    elif info == 1:
+        raise ValueError("Reordering of (A, B) failed because the transformed"
+                         " matrix pair (A, B) would be too far from "
+                         "generalized Schur form; the problem is very "
+                         "ill-conditioned. (A, B) may have been partially "
+                         "reordered.")
+
+    return AAA, BBB, alpha, beta, QQ, ZZ
diff --git a/.venv/lib/python3.12/site-packages/scipy/linalg/_decomp_schur.py b/.venv/lib/python3.12/site-packages/scipy/linalg/_decomp_schur.py
new file mode 100644
index 0000000000000000000000000000000000000000..e696ebe0a68decfbc4afbdfeecbf792a8b71dc6e
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/linalg/_decomp_schur.py
@@ -0,0 +1,337 @@
+"""Schur decomposition functions."""
+import numpy as np
+from numpy import asarray_chkfinite, single, asarray, array
+from numpy.linalg import norm
+
+from scipy._lib._util import _apply_over_batch
+# Local imports.
+from ._misc import LinAlgError, _datacopied
+from .lapack import get_lapack_funcs
+from ._decomp import eigvals
+
+__all__ = ['schur', 'rsf2csf']
+
+_double_precision = ['i', 'l', 'd']
+
+
+@_apply_over_batch(('a', 2))
+def schur(a, output='real', lwork=None, overwrite_a=False, sort=None,
+          check_finite=True):
+    """
+    Compute Schur decomposition of a matrix.
+
+    The Schur decomposition is::
+
+        A = Z T Z^H
+
+    where Z is unitary and T is either upper-triangular, or for real
+    Schur decomposition (output='real'), quasi-upper triangular. In
+    the quasi-triangular form, 2x2 blocks describing complex-valued
+    eigenvalue pairs may extrude from the diagonal.
+
+    Parameters
+    ----------
+    a : (M, M) array_like
+        Matrix to decompose
+    output : {'real', 'complex'}, optional
+        When the dtype of `a` is real, this specifies whether to compute
+        the real or complex Schur decomposition.
+        When the dtype of `a` is complex, this argument is ignored, and the
+        complex Schur decomposition is computed.
+    lwork : int, optional
+        Work array size. If None or -1, it is automatically computed.
+    overwrite_a : bool, optional
+        Whether to overwrite data in a (may improve performance).
+        See :ref:`tutorial_linalg_overwrite` for details.
+    sort : {None, callable, 'lhp', 'rhp', 'iuc', 'ouc'}, optional
+        Specifies whether the upper eigenvalues should be sorted. A callable
+        may be passed that, given an eigenvalue, returns a boolean denoting
+        whether the eigenvalue should be sorted to the top-left (True).
+
+        - If ``output='complex'`` OR the dtype of `a` is complex, the callable
+          should have one argument: the eigenvalue expressed as a complex number.
+        - If ``output='real'`` AND the dtype of `a` is real, the callable should have
+          two arguments: the real and imaginary parts of the eigenvalue, respectively.
+
+        Alternatively, string parameters may be used::
+
+            'lhp'   Left-hand plane (real(eigenvalue) < 0.0)
+            'rhp'   Right-hand plane (real(eigenvalue) >= 0.0)
+            'iuc'   Inside the unit circle (abs(eigenvalue) <= 1.0)
+            'ouc'   Outside the unit circle (abs(eigenvalue) > 1.0)
+
+        Defaults to None (no sorting).
+    check_finite : bool, optional
+        Whether to check that the input matrix contains only finite numbers.
+        Disabling may give a performance gain, but may result in problems
+        (crashes, non-termination) if the inputs do contain infinities or NaNs.
+
+    Returns
+    -------
+    T : (M, M) ndarray
+        Schur form of A. It is real-valued for the real Schur decomposition.
+    Z : (M, M) ndarray
+        A unitary Schur transformation matrix for A.
+        It is real-valued for the real Schur decomposition.
+    sdim : int
+        If and only if sorting was requested, a third return value will
+        contain the number of eigenvalues satisfying the sort condition.
+        Note that complex conjugate pairs for which the condition is true
+        for either eigenvalue count as 2.
+
+    Raises
+    ------
+    LinAlgError
+        Error raised under three conditions:
+
+        1. The algorithm failed due to a failure of the QR algorithm to
+           compute all eigenvalues.
+        2. If eigenvalue sorting was requested, the eigenvalues could not be
+           reordered due to a failure to separate eigenvalues, usually because
+           of poor conditioning.
+        3. If eigenvalue sorting was requested, roundoff errors caused the
+           leading eigenvalues to no longer satisfy the sorting condition.
+
+    See Also
+    --------
+    rsf2csf : Convert real Schur form to complex Schur form
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy.linalg import schur, eigvals
+    >>> A = np.array([[0, 2, 2], [0, 1, 2], [1, 0, 1]])
+    >>> T, Z = schur(A)
+    >>> T
+    array([[ 2.65896708,  1.42440458, -1.92933439],
+           [ 0.        , -0.32948354, -0.49063704],
+           [ 0.        ,  1.31178921, -0.32948354]])
+    >>> Z
+    array([[0.72711591, -0.60156188, 0.33079564],
+           [0.52839428, 0.79801892, 0.28976765],
+           [0.43829436, 0.03590414, -0.89811411]])
+
+    >>> T2, Z2 = schur(A, output='complex')
+    >>> T2
+    array([[ 2.65896708, -1.22839825+1.32378589j,  0.42590089+1.51937378j], # may vary
+           [ 0.        , -0.32948354+0.80225456j, -0.59877807+0.56192146j],
+           [ 0.        ,  0.                    , -0.32948354-0.80225456j]])
+    >>> eigvals(T2)
+    array([2.65896708, -0.32948354+0.80225456j, -0.32948354-0.80225456j])   # may vary
+
+    A custom eigenvalue-sorting condition that sorts by positive imaginary part
+    is satisfied by only one eigenvalue.
+
+    >>> _, _, sdim = schur(A, output='complex', sort=lambda x: x.imag > 1e-15)
+    >>> sdim
+    1
+
+    When ``output='real'`` and the array `a` is real, the `sort` callable must accept
+    the real and imaginary parts as separate arguments. Note that now the complex
+    eigenvalues ``-0.32948354+0.80225456j`` and ``-0.32948354-0.80225456j`` will be
+    treated as a complex conjugate pair, and according to the `sdim` documentation,
+    complex conjugate pairs for which the condition is True for *either* eigenvalue
+    increase `sdim` by *two*.
+
+    >>> _, _, sdim = schur(A, output='real', sort=lambda x, y: y > 1e-15)
+    >>> sdim
+    2
+
+    """
+    if output not in ['real', 'complex', 'r', 'c']:
+        raise ValueError("argument must be 'real', or 'complex'")
+    if check_finite:
+        a1 = asarray_chkfinite(a)
+    else:
+        a1 = asarray(a)
+    if np.issubdtype(a1.dtype, np.integer):
+        a1 = asarray(a, dtype=np.dtype("long"))
+    if len(a1.shape) != 2 or (a1.shape[0] != a1.shape[1]):
+        raise ValueError('expected square matrix')
+
+    typ = a1.dtype.char
+    if output in ['complex', 'c'] and typ not in ['F', 'D']:
+        if typ in _double_precision:
+            a1 = a1.astype('D')
+        else:
+            a1 = a1.astype('F')
+
+    # accommodate empty matrix
+    if a1.size == 0:
+        t0, z0 = schur(np.eye(2, dtype=a1.dtype))
+        if sort is None:
+            return (np.empty_like(a1, dtype=t0.dtype),
+                    np.empty_like(a1, dtype=z0.dtype))
+        else:
+            return (np.empty_like(a1, dtype=t0.dtype),
+                    np.empty_like(a1, dtype=z0.dtype), 0)
+
+    overwrite_a = overwrite_a or (_datacopied(a1, a))
+    gees, = get_lapack_funcs(('gees',), (a1,))
+    if lwork is None or lwork == -1:
+        # get optimal work array
+        result = gees(lambda x: None, a1, lwork=-1)
+        lwork = result[-2][0].real.astype(np.int_)
+
+    if sort is None:
+        sort_t = 0
+        def sfunction(x, y=None):
+            return None
+    else:
+        sort_t = 1
+        if callable(sort):
+            sfunction = sort
+        elif sort == 'lhp':
+            def sfunction(x, y=None):
+                return x.real < 0.0
+        elif sort == 'rhp':
+            def sfunction(x, y=None):
+                return x.real >= 0.0
+        elif sort == 'iuc':
+            def sfunction(x, y=None):
+                z = x if y is None else x + y*1j
+                return abs(z) <= 1.0
+        elif sort == 'ouc':
+            def sfunction(x, y=None):
+                z = x if y is None else x + y*1j
+                return abs(z) > 1.0
+        else:
+            raise ValueError("'sort' parameter must either be 'None', or a "
+                             "callable, or one of ('lhp','rhp','iuc','ouc')")
+
+    result = gees(sfunction, a1, lwork=lwork, overwrite_a=overwrite_a,
+                  sort_t=sort_t)
+
+    info = result[-1]
+    if info < 0:
+        raise ValueError(f'illegal value in {-info}-th argument of internal gees')
+    elif info == a1.shape[0] + 1:
+        raise LinAlgError('Eigenvalues could not be separated for reordering.')
+    elif info == a1.shape[0] + 2:
+        raise LinAlgError('Leading eigenvalues do not satisfy sort condition.')
+    elif info > 0:
+        raise LinAlgError("Schur form not found. Possibly ill-conditioned.")
+
+    if sort is None:
+        return result[0], result[-3]
+    else:
+        return result[0], result[-3], result[1]
+
+
+eps = np.finfo(float).eps
+feps = np.finfo(single).eps
+
+_array_kind = {'b': 0, 'h': 0, 'B': 0, 'i': 0, 'l': 0,
+               'f': 0, 'd': 0, 'F': 1, 'D': 1}
+_array_precision = {'i': 1, 'l': 1, 'f': 0, 'd': 1, 'F': 0, 'D': 1}
+_array_type = [['f', 'd'], ['F', 'D']]
+
+
+def _commonType(*arrays):
+    kind = 0
+    precision = 0
+    for a in arrays:
+        t = a.dtype.char
+        kind = max(kind, _array_kind[t])
+        precision = max(precision, _array_precision[t])
+    return _array_type[kind][precision]
+
+
+def _castCopy(type, *arrays):
+    cast_arrays = ()
+    for a in arrays:
+        if a.dtype.char == type:
+            cast_arrays = cast_arrays + (a.copy(),)
+        else:
+            cast_arrays = cast_arrays + (a.astype(type),)
+    if len(cast_arrays) == 1:
+        return cast_arrays[0]
+    else:
+        return cast_arrays
+
+
+@_apply_over_batch(('T', 2), ('Z', 2))
+def rsf2csf(T, Z, check_finite=True):
+    """
+    Convert real Schur form to complex Schur form.
+
+    Convert a quasi-diagonal real-valued Schur form to the upper-triangular
+    complex-valued Schur form.
+
+    Parameters
+    ----------
+    T : (M, M) array_like
+        Real Schur form of the original array
+    Z : (M, M) array_like
+        Schur transformation matrix
+    check_finite : bool, optional
+        Whether to check that the input arrays contain only finite numbers.
+        Disabling may give a performance gain, but may result in problems
+        (crashes, non-termination) if the inputs do contain infinities or NaNs.
+
+    Returns
+    -------
+    T : (M, M) ndarray
+        Complex Schur form of the original array
+    Z : (M, M) ndarray
+        Schur transformation matrix corresponding to the complex form
+
+    See Also
+    --------
+    schur : Schur decomposition of an array
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy.linalg import schur, rsf2csf
+    >>> A = np.array([[0, 2, 2], [0, 1, 2], [1, 0, 1]])
+    >>> T, Z = schur(A)
+    >>> T
+    array([[ 2.65896708,  1.42440458, -1.92933439],
+           [ 0.        , -0.32948354, -0.49063704],
+           [ 0.        ,  1.31178921, -0.32948354]])
+    >>> Z
+    array([[0.72711591, -0.60156188, 0.33079564],
+           [0.52839428, 0.79801892, 0.28976765],
+           [0.43829436, 0.03590414, -0.89811411]])
+    >>> T2 , Z2 = rsf2csf(T, Z)
+    >>> T2
+    array([[2.65896708+0.j, -1.64592781+0.743164187j, -1.21516887+1.00660462j],
+           [0.+0.j , -0.32948354+8.02254558e-01j, -0.82115218-2.77555756e-17j],
+           [0.+0.j , 0.+0.j, -0.32948354-0.802254558j]])
+    >>> Z2
+    array([[0.72711591+0.j,  0.28220393-0.31385693j,  0.51319638-0.17258824j],
+           [0.52839428+0.j,  0.24720268+0.41635578j, -0.68079517-0.15118243j],
+           [0.43829436+0.j, -0.76618703+0.01873251j, -0.03063006+0.46857912j]])
+
+    """
+    if check_finite:
+        Z, T = map(asarray_chkfinite, (Z, T))
+    else:
+        Z, T = map(asarray, (Z, T))
+
+    for ind, X in enumerate([Z, T]):
+        if X.ndim != 2 or X.shape[0] != X.shape[1]:
+            raise ValueError(f"Input '{'ZT'[ind]}' must be square.")
+
+    if T.shape[0] != Z.shape[0]:
+        message = f"Input array shapes must match: Z: {Z.shape} vs. T: {T.shape}"
+        raise ValueError(message)
+    N = T.shape[0]
+    t = _commonType(Z, T, array([3.0], 'F'))
+    Z, T = _castCopy(t, Z, T)
+
+    for m in range(N-1, 0, -1):
+        if abs(T[m, m-1]) > eps*(abs(T[m-1, m-1]) + abs(T[m, m])):
+            mu = eigvals(T[m-1:m+1, m-1:m+1]) - T[m, m]
+            r = norm([mu[0], T[m, m-1]])
+            c = mu[0] / r
+            s = T[m, m-1] / r
+            G = array([[c.conj(), s], [-s, c]], dtype=t)
+
+            T[m-1:m+1, m-1:] = G.dot(T[m-1:m+1, m-1:])
+            T[:m+1, m-1:m+1] = T[:m+1, m-1:m+1].dot(G.conj().T)
+            Z[:, m-1:m+1] = Z[:, m-1:m+1].dot(G.conj().T)
+
+        T[m, m-1] = 0.0
+    return T, Z
diff --git a/.venv/lib/python3.12/site-packages/scipy/linalg/_decomp_svd.py b/.venv/lib/python3.12/site-packages/scipy/linalg/_decomp_svd.py
new file mode 100644
index 0000000000000000000000000000000000000000..687a0f94726848dfe6fc695c1e858be3083c2b9c
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/linalg/_decomp_svd.py
@@ -0,0 +1,590 @@
+"""SVD decomposition functions."""
+import numpy as np
+
+from scipy._lib._util import _apply_over_batch, _deprecate_dtypes
+from . import _batched_linalg
+
+# Local imports.
+from ._misc import LinAlgError, _datacopied
+from .lapack import _normalize_lapack_dtype, _ensure_aligned_and_native, HAS_ILP64
+from scipy.linalg.lapack import get_lapack_funcs   # noqa: F401  (backwards compat)
+from ._decomp import _asarray_validated
+
+
+__all__ = ['svd', 'svdvals', 'diagsvd', 'orth', 'subspace_angles', 'null_space']
+
+
+def _format_emit_errors_warnings(err_lst, lapack_driver):
+    """Format/emit errors/warnings from a lowlevel batched routine.
+    """
+    # NB the low-level routine currently stops processing a batch at the first error
+    for entry in err_lst:
+        info = entry["lapack_info"]
+        num = entry["num"]
+        if info != 0:
+            if info > 0:
+                raise LinAlgError(f"SVD did not converge for slice = {num}.")
+            if info < 0:
+                if lapack_driver == "gesdd" and info == -4:
+                    msg = f"slice {num} has a NaN entry"
+                    raise ValueError(msg)
+                raise ValueError(
+                    f'illegal value in {-info}th argument of internal {lapack_driver}'
+                    f'  for slice {num}.'
+                )
+
+
+def svd(a, full_matrices=True, compute_uv=True, overwrite_a=False,
+        check_finite=True, lapack_driver='gesdd'):
+    """
+    Singular Value Decomposition.
+
+    Factorizes the matrix `a` into two unitary matrices ``U`` and ``Vh``, and
+    a 1-D array ``s`` of singular values (real, non-negative) such that
+    ``a == U @ S @ Vh``, where ``S`` is a suitably shaped matrix of zeros with
+    main diagonal ``s``.
+
+    Parameters
+    ----------
+    a : (..., M, N) array_like
+        Matrix to decompose.
+    full_matrices : bool, optional
+        If True (default), `U` and `Vh` are of shape ``(M, M)``, ``(N, N)``.
+        If False, the shapes are ``(M, K)`` and ``(K, N)``, where
+        ``K = min(M, N)``.
+    compute_uv : bool, optional
+        Whether to compute also ``U`` and ``Vh`` in addition to ``s``.
+        Default is True.
+    overwrite_a : bool, optional
+        Whether to overwrite data in `a` (may improve performance). Default is False.
+        See :ref:`tutorial_linalg_overwrite` for details.
+    check_finite : bool, optional
+        Whether to check that the input matrix contains only finite numbers.
+        Disabling may give a performance gain, but may result in problems
+        (crashes, non-termination) if the inputs do contain infinities or NaNs.
+    lapack_driver : {'gesdd', 'gesvd'}, optional
+        Whether to use the more efficient divide-and-conquer approach
+        (``'gesdd'``) or general rectangular approach (``'gesvd'``)
+        to compute the SVD. MATLAB and Octave use the ``'gesvd'`` approach.
+        Default is ``'gesdd'``.
+
+    Returns
+    -------
+    U : ndarray
+        Unitary matrix having left singular vectors as columns.
+        Of shape ``(M, M)`` or ``(M, K)``, depending on `full_matrices`.
+        Only present when ``compute_uv=True``.
+    s : ndarray
+        The singular values, sorted in non-increasing order.
+        Of shape (K,), with ``K = min(M, N)``.
+    Vh : ndarray
+        Unitary matrix having right singular vectors as rows.
+        Of shape ``(N, N)`` or ``(K, N)`` depending on `full_matrices`.
+        Only present when ``compute_uv=True``.
+
+    Raises
+    ------
+    LinAlgError
+        If SVD computation does not converge.
+
+    See Also
+    --------
+    svdvals : Compute singular values of a matrix.
+    diagsvd : Construct the Sigma matrix, given the vector s.
+
+    Notes
+    -----
+    The array argument of this function, `a`, may have additional
+    "batch" dimensions prepended to the core shape. In this case, the array is treated
+    as a batch of lower-dimensional slices; see :ref:`linalg_batch` for details.
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy import linalg
+    >>> rng = np.random.default_rng()
+    >>> m, n = 9, 6
+    >>> a = rng.standard_normal((m, n)) + 1.j*rng.standard_normal((m, n))
+    >>> U, s, Vh = linalg.svd(a)
+    >>> U.shape,  s.shape, Vh.shape
+    ((9, 9), (6,), (6, 6))
+
+    Reconstruct the original matrix from the decomposition:
+
+    >>> sigma = np.zeros((m, n))
+    >>> for i in range(min(m, n)):
+    ...     sigma[i, i] = s[i]
+    >>> a1 = U @ sigma @ Vh
+    >>> np.allclose(a, a1)
+    True
+
+    Alternatively, use ``full_matrices=False`` (notice that the shape of
+    ``U`` is then ``(m, n)`` instead of ``(m, m)``):
+
+    >>> U, s, Vh = linalg.svd(a, full_matrices=False)
+    >>> U.shape, s.shape, Vh.shape
+    ((9, 6), (6,), (6, 6))
+    >>> S = np.diag(s)
+    >>> np.allclose(a, U @ S @ Vh)
+    True
+
+    >>> s2 = linalg.svd(a, compute_uv=False)
+    >>> np.allclose(s, s2)
+    True
+
+    If the input matrix has more than two dimensions, it is interpreted as a batch of
+    two-dimensional matrices:
+
+    >>> aa = np.stack((a, 2*a))
+    >>> linalg.svdvals(aa)[0] == linalg.svdvals(a)
+    array([ True,  True,  True,  True,  True,  True])
+    >>> linalg.svdvals(aa)[1] == 2 * linalg.svdvals(a)
+    array([ True,  True,  True,  True,  True,  True])
+    """
+    if not isinstance(lapack_driver, str):
+        raise TypeError('lapack_driver must be a string')
+    if lapack_driver not in ('gesdd', 'gesvd'):
+        message = f'lapack_driver must be "gesdd" or "gesvd", not "{lapack_driver}"'
+        raise ValueError(message)
+
+    # basic sanity checks of the input matrix
+    a1 = _asarray_validated(a, check_finite=check_finite)
+    _deprecate_dtypes("svd", a1)
+
+    if a1.ndim < 2:
+        raise ValueError(f"Expected at least ndim=2, got {a1.ndim=}")
+
+    m, n = a1.shape[-2], a1.shape[-1]
+
+    # Also check if dtype is LAPACK compatible
+    a1, overwrite_a = _normalize_lapack_dtype(a1, overwrite_a)
+    a1, overwrite_a = _ensure_aligned_and_native(a1, overwrite_a)
+
+    overwrite_a = overwrite_a or (_datacopied(a1, a))
+    overwrite_a = overwrite_a and (a1.ndim == 2) and (a1.flags["F_CONTIGUOUS"])
+
+    # accommodate empty matrix
+    if a1.size == 0:
+        u0, s0, v0 = svd(np.eye(2, dtype=a1.dtype))
+
+        batch_shape = a1.shape[:-2]
+        s = np.empty_like(a1, shape=batch_shape + (0,), dtype=s0.dtype)
+        if full_matrices:
+            u = np.empty_like(a1, shape=batch_shape + (m, m), dtype=u0.dtype)
+            u[...] = np.identity(m)
+            v = np.empty_like(a1, shape=batch_shape + (n, n), dtype=v0.dtype)
+            v[...] = np.identity(n)
+        else:
+            u = np.empty_like(a1, shape=batch_shape + (m, 0), dtype=u0.dtype)
+            v = np.empty_like(a1, shape=batch_shape + (0, n), dtype=v0.dtype)
+        if compute_uv:
+            return u, s, v
+        else:
+            return s
+
+    if compute_uv:
+        max_mn, min_mn = (m, n) if m > n else (n, m)
+        if full_matrices:
+            if not HAS_ILP64 and max_mn*max_mn > np.iinfo(np.int32).max:
+                raise ValueError(f"Indexing a matrix size {max_mn} x {max_mn} "
+                                  "would incur integer overflow in LAPACK. "
+                                  "Instead, either use using numpy.linalg.svd or build"
+                                  "SciPy with ILP64 support.")
+        else:
+            sz = max(m * min_mn, n * min_mn)
+            if not HAS_ILP64 and max(m * min_mn, n * min_mn) > np.iinfo(np.int32).max:
+                raise ValueError(f"Indexing a matrix of {sz} elements would "
+                                  "incur an in integer overflow in LAPACK. "
+                                  "Instead, either use using numpy.linalg.svd or build"
+                                  "SciPy with ILP64 support.")
+
+    res = _batched_linalg._svd(
+        a1, lapack_driver, compute_uv, full_matrices, overwrite_a
+    )
+
+    err_lst = res[-1]
+    if err_lst:
+        _format_emit_errors_warnings(err_lst, lapack_driver)
+
+    if compute_uv:
+        return res[:-1]    # u, s, v
+    else:
+        return res[0]   # s
+
+
+def svdvals(a, overwrite_a=False, check_finite=True):
+    """
+    Compute singular values of a matrix.
+
+    Parameters
+    ----------
+    a : (M, N) array_like
+        Matrix to decompose.
+    overwrite_a : bool, optional
+        Whether to overwrite data in `a` (may improve performance). Default is False.
+        See :ref:`tutorial_linalg_overwrite` for details.
+    check_finite : bool, optional
+        Whether to check that the input matrix contains only finite numbers.
+        Disabling may give a performance gain, but may result in problems
+        (crashes, non-termination) if the inputs do contain infinities or NaNs.
+
+    Returns
+    -------
+    s : (min(M, N),) ndarray
+        The singular values, sorted in decreasing order.
+
+    Raises
+    ------
+    LinAlgError
+        If SVD computation does not converge.
+
+    See Also
+    --------
+    svd : Compute the full singular value decomposition of a matrix.
+    diagsvd : Construct the Sigma matrix, given the vector s.
+
+    Notes
+    -----
+    Array argument of this function, `a`, may have additional
+    "batch" dimensions prepended to the core shape. In this case, the array is treated
+    as a batch of lower-dimensional slices; see :ref:`linalg_batch` for details.
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy.linalg import svdvals
+    >>> m = np.array([[1.0, 0.0],
+    ...               [2.0, 3.0],
+    ...               [1.0, 1.0],
+    ...               [0.0, 2.0],
+    ...               [1.0, 0.0]])
+    >>> svdvals(m)
+    array([ 4.28091555,  1.63516424])
+
+    If the input matrix has more than two dimensions, it is interpreted as a batch of
+    two-dimensional matrices:
+
+    >>> mm = np.stack((m, 2*m))
+    >>> svdvals(mm)
+    array([[4.28091555, 1.63516424],
+           [8.56183109, 3.27032847]])
+
+    We can verify the maximum singular value of `m` by computing the maximum
+    length of `m @ u` over all the unit vectors `u` in the (x,y) plane.
+    We approximate "all" the unit vectors with a large sample. Because
+    of linearity, we only need the unit vectors with angles in ``[0, pi]``.
+
+    >>> t = np.linspace(0, np.pi, 2000)
+    >>> u = np.array([np.cos(t), np.sin(t)])
+    >>> np.linalg.norm(m @ u, axis=0).max()
+    4.2809152422538475
+
+    `p` is a projection matrix with rank 1. With exact arithmetic,
+    its singular values would be ``[1, 0, 0, 0]``.
+
+    >>> v = np.array([0.1, 0.3, 0.9, 0.3])
+    >>> p = np.outer(v, v)
+    >>> svdvals(p)
+    array([  1.00000000e+00,   2.02021698e-17,   1.56692500e-17,
+             8.15115104e-34])
+
+    The singular values of an orthogonal matrix are all 1. Here, we
+    create a random orthogonal matrix by using the ``rvs()`` method of
+    `scipy.stats.ortho_group`.
+
+    >>> from scipy.stats import ortho_group
+    >>> orth = ortho_group.rvs(4)
+    >>> svdvals(orth)
+    array([ 1.,  1.,  1.,  1.])
+    """
+    return svd(a, compute_uv=0, overwrite_a=overwrite_a,
+               check_finite=check_finite)
+
+
+@_apply_over_batch(('s', 1))
+def diagsvd(s, M, N):
+    """
+    Construct the sigma matrix in SVD from singular values and size M, N.
+
+    Parameters
+    ----------
+    s : (M,) or (N,) array_like
+        Singular values
+    M : int
+        Size of the matrix whose singular values are `s`.
+    N : int
+        Size of the matrix whose singular values are `s`.
+
+    Returns
+    -------
+    S : (M, N) ndarray
+        The S-matrix in the singular value decomposition
+
+    See Also
+    --------
+    svd : Singular value decomposition of a matrix
+    svdvals : Compute singular values of a matrix.
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy.linalg import diagsvd
+    >>> vals = np.array([1, 2, 3])  # The array representing the computed svd
+    >>> diagsvd(vals, 3, 4)
+    array([[1, 0, 0, 0],
+           [0, 2, 0, 0],
+           [0, 0, 3, 0]])
+    >>> diagsvd(vals, 4, 3)
+    array([[1, 0, 0],
+           [0, 2, 0],
+           [0, 0, 3],
+           [0, 0, 0]])
+
+    """
+    part = np.diag(s)
+    typ = part.dtype.char
+    MorN = len(s)
+    if MorN == M:
+        return np.hstack((part, np.zeros((M, N - M), dtype=typ)))
+    elif MorN == N:
+        return np.r_[part, np.zeros((M - N, N), dtype=typ)]
+    else:
+        raise ValueError("Length of s must be M or N.")
+
+
+# Orthonormal decomposition
+
+@_apply_over_batch(('A', 2))
+def orth(A, rcond=None):
+    """
+    Construct an orthonormal basis for the range of A using SVD.
+
+    Parameters
+    ----------
+    A : (M, N) array_like
+        Input array
+    rcond : float, optional
+        Relative condition number. Singular values ``s`` smaller than
+        ``rcond * max(s)`` are considered zero.
+        Default: floating point eps * max(M,N).
+
+    Returns
+    -------
+    Q : (M, K) ndarray
+        Orthonormal basis for the range of A.
+        K = effective rank of A, as determined by rcond
+
+    See Also
+    --------
+    svd : Singular value decomposition of a matrix
+    null_space : Matrix null space
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy.linalg import orth
+    >>> A = np.array([[2, 0, 0], [0, 5, 0]])  # rank 2 array
+    >>> orth(A)
+    array([[0., 1.],
+           [1., 0.]])
+    >>> orth(A.T)
+    array([[0., 1.],
+           [1., 0.],
+           [0., 0.]])
+
+    """
+    u, s, vh = svd(A, full_matrices=False)
+    M, N = u.shape[0], vh.shape[1]
+    if rcond is None:
+        rcond = np.finfo(s.dtype).eps * max(M, N)
+    tol = np.amax(s, initial=0.) * rcond
+    num = np.sum(s > tol, dtype=int)
+    Q = u[:, :num]
+    return Q
+
+
+@_apply_over_batch(('A', 2))
+def null_space(A, rcond=None, *, overwrite_a=False, check_finite=True,
+               lapack_driver='gesdd'):
+    """
+    Construct an orthonormal basis for the null space of A using SVD.
+
+    Parameters
+    ----------
+    A : (M, N) array_like
+        Input array
+    rcond : float, optional
+        Relative condition number. Singular values ``s`` smaller than
+        ``rcond * max(s)`` are considered zero.
+        Default: floating point eps * max(M,N).
+    overwrite_a : bool, optional
+        Whether to overwrite `a`; may improve performance. Default is False.
+        See :ref:`tutorial_linalg_overwrite` for details.
+    check_finite : bool, optional
+        Whether to check that the input matrix contains only finite numbers.
+        Disabling may give a performance gain, but may result in problems
+        (crashes, non-termination) if the inputs do contain infinities or NaNs.
+    lapack_driver : {'gesdd', 'gesvd'}, optional
+        Whether to use the more efficient divide-and-conquer approach
+        (``'gesdd'``) or general rectangular approach (``'gesvd'``)
+        to compute the SVD. MATLAB and Octave use the ``'gesvd'`` approach.
+        Default is ``'gesdd'``.
+
+    Returns
+    -------
+    Z : (N, K) ndarray
+        Orthonormal basis for the null space of A.
+        K = dimension of effective null space, as determined by rcond
+
+    See Also
+    --------
+    svd : Singular value decomposition of a matrix
+    orth : Matrix range
+
+    Examples
+    --------
+    1-D null space:
+
+    >>> import numpy as np
+    >>> from scipy.linalg import null_space
+    >>> A = np.array([[1, 1], [1, 1]])
+    >>> ns = null_space(A)
+    >>> ns * np.copysign(1, ns[0,0])  # Remove the sign ambiguity of the vector
+    array([[ 0.70710678],
+           [-0.70710678]])
+
+    2-D null space:
+
+    >>> from numpy.random import default_rng
+    >>> rng = default_rng()
+    >>> B = rng.random((3, 5))
+    >>> Z = null_space(B)
+    >>> Z.shape
+    (5, 2)
+    >>> np.allclose(B.dot(Z), 0)
+    True
+
+    The basis vectors are orthonormal (up to rounding error):
+
+    >>> Z.T.dot(Z)
+    array([[  1.00000000e+00,   6.92087741e-17],
+           [  6.92087741e-17,   1.00000000e+00]])
+
+    """
+    u, s, vh = svd(A, full_matrices=True, overwrite_a=overwrite_a,
+                   check_finite=check_finite, lapack_driver=lapack_driver)
+    M, N = u.shape[0], vh.shape[1]
+    if rcond is None:
+        rcond = np.finfo(s.dtype).eps * max(M, N)
+    tol = np.amax(s, initial=0.) * rcond
+    num = np.sum(s > tol, dtype=int)
+    Q = vh[num:,:].T.conj()
+    return Q
+
+
+@_apply_over_batch(('A', 2), ('B', 2))
+def subspace_angles(A, B):
+    r"""
+    Compute the subspace angles between two matrices.
+
+    Parameters
+    ----------
+    A : (M, N) array_like
+        The first input array.
+    B : (M, K) array_like
+        The second input array.
+
+    Returns
+    -------
+    angles : ndarray, shape (min(N, K),)
+        The subspace angles between the column spaces of `A` and `B` in
+        descending order.
+
+    See Also
+    --------
+    orth
+    svd
+
+    Notes
+    -----
+    This computes the subspace angles according to the formula
+    provided in [1]_. For equivalence with MATLAB and Octave behavior,
+    use ``angles[0]``.
+
+    .. versionadded:: 1.0
+
+    References
+    ----------
+    .. [1] Knyazev A, Argentati M (2002) Principal Angles between Subspaces
+           in an A-Based Scalar Product: Algorithms and Perturbation
+           Estimates. SIAM J. Sci. Comput. 23:2008-2040.
+
+    Examples
+    --------
+    A Hadamard matrix, which has orthogonal columns, so we expect that
+    the subspace angle to be :math:`\frac{\pi}{2}`:
+
+    >>> import numpy as np
+    >>> from scipy.linalg import hadamard, subspace_angles
+    >>> rng = np.random.default_rng()
+    >>> H = hadamard(4)
+    >>> print(H)
+    [[ 1  1  1  1]
+     [ 1 -1  1 -1]
+     [ 1  1 -1 -1]
+     [ 1 -1 -1  1]]
+    >>> np.rad2deg(subspace_angles(H[:, :2], H[:, 2:]))
+    array([ 90.,  90.])
+
+    And the subspace angle of a matrix to itself should be zero:
+
+    >>> subspace_angles(H[:, :2], H[:, :2]) <= 2 * np.finfo(float).eps
+    array([ True,  True], dtype=bool)
+
+    The angles between non-orthogonal subspaces are in between these extremes:
+
+    >>> x = rng.standard_normal((4, 3))
+    >>> np.rad2deg(subspace_angles(x[:, :2], x[:, [2]]))
+    array([ 55.832])  # random
+    """
+    # Steps here omit the U and V calculation steps from the paper
+
+    # 1. Compute orthonormal bases of column-spaces
+    A = _asarray_validated(A, check_finite=True)
+    if len(A.shape) != 2:
+        raise ValueError(f'expected 2D array, got shape {A.shape}')
+    QA = orth(A)
+    del A
+
+    B = _asarray_validated(B, check_finite=True)
+    if len(B.shape) != 2:
+        raise ValueError(f'expected 2D array, got shape {B.shape}')
+    if len(B) != len(QA):
+        raise ValueError('A and B must have the same number of rows, got '
+                         f'{QA.shape[0]} and {B.shape[0]}')
+    QB = orth(B)
+    del B
+
+    # 2. Compute SVD for cosine
+    QA_H_QB = np.dot(QA.T.conj(), QB)
+    sigma = svdvals(QA_H_QB)
+
+    # 3. Compute matrix B
+    if QA.shape[1] >= QB.shape[1]:
+        B = QB - np.dot(QA, QA_H_QB)
+    else:
+        B = QA - np.dot(QB, QA_H_QB.T.conj())
+    del QA, QB, QA_H_QB
+
+    # 4. Compute SVD for sine
+    mask = sigma ** 2 >= 0.5
+    if mask.any():
+        mu_arcsin = np.arcsin(np.clip(svdvals(B, overwrite_a=True), -1., 1.))
+    else:
+        mu_arcsin = 0.
+
+    # 5. Compute the principal angles
+    # with reverse ordering of sigma because smallest sigma belongs to largest
+    # angle theta
+    theta = np.where(mask, mu_arcsin, np.arccos(np.clip(sigma[::-1], -1., 1.)))
+    return theta
diff --git a/.venv/lib/python3.12/site-packages/scipy/linalg/_decomp_update.cpython-312-x86_64-linux-gnu.so b/.venv/lib/python3.12/site-packages/scipy/linalg/_decomp_update.cpython-312-x86_64-linux-gnu.so
new file mode 100644
index 0000000000000000000000000000000000000000..573187caf8c163eaf9fa31cb234863be5a4afdc0
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/linalg/_decomp_update.cpython-312-x86_64-linux-gnu.so
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:943013cc1dbb23aeb8b09e93171dde39ccdf77e0836cd7b2b13cafa92f182f72
+size 333520
diff --git a/.venv/lib/python3.12/site-packages/scipy/linalg/_expm_frechet.py b/.venv/lib/python3.12/site-packages/scipy/linalg/_expm_frechet.py
new file mode 100644
index 0000000000000000000000000000000000000000..9260907ea62539b8438b1e0e63c476beb0e4e1d5
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/linalg/_expm_frechet.py
@@ -0,0 +1,416 @@
+"""Frechet derivative of the matrix exponential."""
+import numpy as np
+import scipy.linalg
+from scipy._lib._util import _apply_over_batch
+
+
+__all__ = ['expm_frechet', 'expm_cond']
+
+
+@_apply_over_batch(('A', 2), ('E', 2))
+def expm_frechet(A, E, method=None, compute_expm=True, check_finite=True):
+    """
+    Frechet derivative of the matrix exponential of A in the direction E.
+
+    Parameters
+    ----------
+    A : (N, N) array_like
+        Matrix of which to take the matrix exponential.
+    E : (N, N) array_like
+        Matrix direction in which to take the Frechet derivative.
+    method : str, optional
+        Choice of algorithm. Should be one of
+
+        - `SPS` (default)
+        - `blockEnlarge`
+
+    compute_expm : bool, optional
+        Whether to compute also `expm_A` in addition to `expm_frechet_AE`.
+        Default is True.
+    check_finite : bool, optional
+        Whether to check that the input matrix contains only finite numbers.
+        Disabling may give a performance gain, but may result in problems
+        (crashes, non-termination) if the inputs do contain infinities or NaNs.
+
+    Returns
+    -------
+    expm_A : ndarray
+        Matrix exponential of A. Only present when ``compute_expm`` is True.
+    expm_frechet_AE : ndarray
+        Frechet derivative of the matrix exponential of A in the direction E.
+
+    See Also
+    --------
+    expm : Compute the exponential of a matrix.
+
+    Notes
+    -----
+    This section describes the available implementations that can be selected
+    by the `method` parameter. The default method is *SPS*.
+
+    Method *blockEnlarge* is a naive algorithm.
+
+    Method *SPS* is Scaling-Pade-Squaring [1]_.
+    It is a sophisticated implementation which should take
+    only about 3/8 as much time as the naive implementation.
+    The asymptotics are the same.
+
+    .. versionadded:: 0.13.0
+
+    References
+    ----------
+    .. [1] Awad H. Al-Mohy and Nicholas J. Higham (2009)
+           Computing the Frechet Derivative of the Matrix Exponential,
+           with an application to Condition Number Estimation.
+           SIAM Journal On Matrix Analysis and Applications.,
+           30 (4). pp. 1639-1657. ISSN 1095-7162
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy import linalg
+    >>> rng = np.random.default_rng()
+
+    >>> A = rng.standard_normal((3, 3))
+    >>> E = rng.standard_normal((3, 3))
+    >>> expm_A, expm_frechet_AE = linalg.expm_frechet(A, E)
+    >>> expm_A.shape, expm_frechet_AE.shape
+    ((3, 3), (3, 3))
+
+    Create a 6x6 matrix containing [[A, E], [0, A]]:
+
+    >>> M = np.zeros((6, 6))
+    >>> M[:3, :3] = A
+    >>> M[:3, 3:] = E
+    >>> M[3:, 3:] = A
+
+    >>> expm_M = linalg.expm(M)
+    >>> np.allclose(expm_A, expm_M[:3, :3])
+    True
+    >>> np.allclose(expm_frechet_AE, expm_M[:3, 3:])
+    True
+
+    """
+    if check_finite:
+        A = np.asarray_chkfinite(A)
+        E = np.asarray_chkfinite(E)
+    else:
+        A = np.asarray(A)
+        E = np.asarray(E)
+    if A.ndim != 2 or A.shape[0] != A.shape[1]:
+        raise ValueError('expected A to be a square matrix')
+    if E.ndim != 2 or E.shape[0] != E.shape[1]:
+        raise ValueError('expected E to be a square matrix')
+    if A.shape != E.shape:
+        raise ValueError('expected A and E to be the same shape')
+    if method is None:
+        method = 'SPS'
+    if method == 'SPS':
+        expm_A, expm_frechet_AE = expm_frechet_algo_64(A, E)
+    elif method == 'blockEnlarge':
+        expm_A, expm_frechet_AE = expm_frechet_block_enlarge(A, E)
+    else:
+        raise ValueError(f'Unknown implementation {method}')
+    if compute_expm:
+        return expm_A, expm_frechet_AE
+    else:
+        return expm_frechet_AE
+
+
+def expm_frechet_block_enlarge(A, E):
+    """
+    This is a helper function, mostly for testing and profiling.
+    Return expm(A), frechet(A, E)
+    """
+    n = A.shape[0]
+    M = np.vstack([
+        np.hstack([A, E]),
+        np.hstack([np.zeros_like(A), A])])
+    expm_M = scipy.linalg.expm(M)
+    return expm_M[:n, :n], expm_M[:n, n:]
+
+
+"""
+Maximal values ell_m of ||2**-s A|| such that the backward error bound
+does not exceed 2**-53.
+"""
+ell_table_61 = (
+        None,
+        # 1
+        2.11e-8,
+        3.56e-4,
+        1.08e-2,
+        6.49e-2,
+        2.00e-1,
+        4.37e-1,
+        7.83e-1,
+        1.23e0,
+        1.78e0,
+        2.42e0,
+        # 11
+        3.13e0,
+        3.90e0,
+        4.74e0,
+        5.63e0,
+        6.56e0,
+        7.52e0,
+        8.53e0,
+        9.56e0,
+        1.06e1,
+        1.17e1,
+        )
+
+
+# The b vectors and U and V are copypasted
+# from scipy.sparse.linalg.matfuncs.py.
+# M, Lu, Lv follow (6.11), (6.12), (6.13), (3.3)
+
+def _diff_pade3(A, E, ident):
+    b = (120., 60., 12., 1.)
+    A2 = A.dot(A)
+    M2 = np.dot(A, E) + np.dot(E, A)
+    U = A.dot(b[3]*A2 + b[1]*ident)
+    V = b[2]*A2 + b[0]*ident
+    Lu = A.dot(b[3]*M2) + E.dot(b[3]*A2 + b[1]*ident)
+    Lv = b[2]*M2
+    return U, V, Lu, Lv
+
+
+def _diff_pade5(A, E, ident):
+    b = (30240., 15120., 3360., 420., 30., 1.)
+    A2 = A.dot(A)
+    M2 = np.dot(A, E) + np.dot(E, A)
+    A4 = np.dot(A2, A2)
+    M4 = np.dot(A2, M2) + np.dot(M2, A2)
+    U = A.dot(b[5]*A4 + b[3]*A2 + b[1]*ident)
+    V = b[4]*A4 + b[2]*A2 + b[0]*ident
+    Lu = (A.dot(b[5]*M4 + b[3]*M2) +
+            E.dot(b[5]*A4 + b[3]*A2 + b[1]*ident))
+    Lv = b[4]*M4 + b[2]*M2
+    return U, V, Lu, Lv
+
+
+def _diff_pade7(A, E, ident):
+    b = (17297280., 8648640., 1995840., 277200., 25200., 1512., 56., 1.)
+    A2 = A.dot(A)
+    M2 = np.dot(A, E) + np.dot(E, A)
+    A4 = np.dot(A2, A2)
+    M4 = np.dot(A2, M2) + np.dot(M2, A2)
+    A6 = np.dot(A2, A4)
+    M6 = np.dot(A4, M2) + np.dot(M4, A2)
+    U = A.dot(b[7]*A6 + b[5]*A4 + b[3]*A2 + b[1]*ident)
+    V = b[6]*A6 + b[4]*A4 + b[2]*A2 + b[0]*ident
+    Lu = (A.dot(b[7]*M6 + b[5]*M4 + b[3]*M2) +
+            E.dot(b[7]*A6 + b[5]*A4 + b[3]*A2 + b[1]*ident))
+    Lv = b[6]*M6 + b[4]*M4 + b[2]*M2
+    return U, V, Lu, Lv
+
+
+def _diff_pade9(A, E, ident):
+    b = (17643225600., 8821612800., 2075673600., 302702400., 30270240.,
+            2162160., 110880., 3960., 90., 1.)
+    A2 = A.dot(A)
+    M2 = np.dot(A, E) + np.dot(E, A)
+    A4 = np.dot(A2, A2)
+    M4 = np.dot(A2, M2) + np.dot(M2, A2)
+    A6 = np.dot(A2, A4)
+    M6 = np.dot(A4, M2) + np.dot(M4, A2)
+    A8 = np.dot(A4, A4)
+    M8 = np.dot(A4, M4) + np.dot(M4, A4)
+    U = A.dot(b[9]*A8 + b[7]*A6 + b[5]*A4 + b[3]*A2 + b[1]*ident)
+    V = b[8]*A8 + b[6]*A6 + b[4]*A4 + b[2]*A2 + b[0]*ident
+    Lu = (A.dot(b[9]*M8 + b[7]*M6 + b[5]*M4 + b[3]*M2) +
+            E.dot(b[9]*A8 + b[7]*A6 + b[5]*A4 + b[3]*A2 + b[1]*ident))
+    Lv = b[8]*M8 + b[6]*M6 + b[4]*M4 + b[2]*M2
+    return U, V, Lu, Lv
+
+
+def expm_frechet_algo_64(A, E):
+    n = A.shape[0]
+    s = None
+    ident = np.identity(n)
+    A_norm_1 = scipy.linalg.norm(A, 1)
+    m_pade_pairs = (
+            (3, _diff_pade3),
+            (5, _diff_pade5),
+            (7, _diff_pade7),
+            (9, _diff_pade9))
+    for m, pade in m_pade_pairs:
+        if A_norm_1 <= ell_table_61[m]:
+            U, V, Lu, Lv = pade(A, E, ident)
+            s = 0
+            break
+    if s is None:
+        # scaling
+        s = max(0, int(np.ceil(np.log2(A_norm_1 / ell_table_61[13]))))
+        A = A * 2.0**-s
+        E = E * 2.0**-s
+        # pade order 13
+        A2 = np.dot(A, A)
+        M2 = np.dot(A, E) + np.dot(E, A)
+        A4 = np.dot(A2, A2)
+        M4 = np.dot(A2, M2) + np.dot(M2, A2)
+        A6 = np.dot(A2, A4)
+        M6 = np.dot(A4, M2) + np.dot(M4, A2)
+        b = (64764752532480000., 32382376266240000., 7771770303897600.,
+                1187353796428800., 129060195264000., 10559470521600.,
+                670442572800., 33522128640., 1323241920., 40840800., 960960.,
+                16380., 182., 1.)
+        W1 = b[13]*A6 + b[11]*A4 + b[9]*A2
+        W2 = b[7]*A6 + b[5]*A4 + b[3]*A2 + b[1]*ident
+        Z1 = b[12]*A6 + b[10]*A4 + b[8]*A2
+        Z2 = b[6]*A6 + b[4]*A4 + b[2]*A2 + b[0]*ident
+        W = np.dot(A6, W1) + W2
+        U = np.dot(A, W)
+        V = np.dot(A6, Z1) + Z2
+        Lw1 = b[13]*M6 + b[11]*M4 + b[9]*M2
+        Lw2 = b[7]*M6 + b[5]*M4 + b[3]*M2
+        Lz1 = b[12]*M6 + b[10]*M4 + b[8]*M2
+        Lz2 = b[6]*M6 + b[4]*M4 + b[2]*M2
+        Lw = np.dot(A6, Lw1) + np.dot(M6, W1) + Lw2
+        Lu = np.dot(A, Lw) + np.dot(E, W)
+        Lv = np.dot(A6, Lz1) + np.dot(M6, Z1) + Lz2
+    # factor once and solve twice
+    lu_piv = scipy.linalg.lu_factor(-U + V)
+    R = scipy.linalg.lu_solve(lu_piv, U + V)
+    L = scipy.linalg.lu_solve(lu_piv, Lu + Lv + np.dot((Lu - Lv), R))
+    # squaring
+    for k in range(s):
+        L = np.dot(R, L) + np.dot(L, R)
+        R = np.dot(R, R)
+    return R, L
+
+
+def vec(M):
+    """
+    Stack columns of M to construct a single vector.
+
+    This is somewhat standard notation in linear algebra.
+
+    Parameters
+    ----------
+    M : 2-D array_like
+        Input matrix
+
+    Returns
+    -------
+    v : 1-D ndarray
+        Output vector
+
+    """
+    return M.T.ravel()
+
+
+def expm_frechet_kronform(A, method=None, check_finite=True):
+    """
+    Construct the Kronecker form of the Frechet derivative of expm.
+
+    Parameters
+    ----------
+    A : array_like with shape (N, N)
+        Matrix to be expm'd.
+    method : str, optional
+        Extra keyword to be passed to expm_frechet.
+    check_finite : bool, optional
+        Whether to check that the input matrix contains only finite numbers.
+        Disabling may give a performance gain, but may result in problems
+        (crashes, non-termination) if the inputs do contain infinities or NaNs.
+
+    Returns
+    -------
+    K : 2-D ndarray with shape (N*N, N*N)
+        Kronecker form of the Frechet derivative of the matrix exponential.
+
+    Notes
+    -----
+    This function is used to help compute the condition number
+    of the matrix exponential.
+
+    See Also
+    --------
+    expm : Compute a matrix exponential.
+    expm_frechet : Compute the Frechet derivative of the matrix exponential.
+    expm_cond : Compute the relative condition number of the matrix exponential
+                in the Frobenius norm.
+
+    """
+    if check_finite:
+        A = np.asarray_chkfinite(A)
+    else:
+        A = np.asarray(A)
+    if len(A.shape) != 2 or A.shape[0] != A.shape[1]:
+        raise ValueError('expected a square matrix')
+
+    n = A.shape[0]
+    ident = np.identity(n)
+    cols = []
+    for i in range(n):
+        for j in range(n):
+            E = np.outer(ident[i], ident[j])
+            F = expm_frechet(A, E,
+                    method=method, compute_expm=False, check_finite=False)
+            cols.append(vec(F))
+    return np.vstack(cols).T
+
+
+@_apply_over_batch(('A', 2))
+def expm_cond(A, check_finite=True):
+    """
+    Relative condition number of the matrix exponential in the Frobenius norm.
+
+    Parameters
+    ----------
+    A : 2-D array_like
+        Square input matrix with shape (N, N).
+    check_finite : bool, optional
+        Whether to check that the input matrix contains only finite numbers.
+        Disabling may give a performance gain, but may result in problems
+        (crashes, non-termination) if the inputs do contain infinities or NaNs.
+
+    Returns
+    -------
+    kappa : float
+        The relative condition number of the matrix exponential
+        in the Frobenius norm
+
+    See Also
+    --------
+    expm : Compute the exponential of a matrix.
+    expm_frechet : Compute the Frechet derivative of the matrix exponential.
+
+    Notes
+    -----
+    A faster estimate for the condition number in the 1-norm
+    has been published but is not yet implemented in SciPy.
+
+    .. versionadded:: 0.14.0
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy.linalg import expm_cond
+    >>> A = np.array([[-0.3, 0.2, 0.6], [0.6, 0.3, -0.1], [-0.7, 1.2, 0.9]])
+    >>> k = expm_cond(A)
+    >>> k
+    1.7787805864469866
+
+    """
+    if check_finite:
+        A = np.asarray_chkfinite(A)
+    else:
+        A = np.asarray(A)
+    if len(A.shape) != 2 or A.shape[0] != A.shape[1]:
+        raise ValueError('expected a square matrix')
+
+    X = scipy.linalg.expm(A)
+    K = expm_frechet_kronform(A, check_finite=False)
+
+    # The following norm choices are deliberate.
+    # The norms of A and X are Frobenius norms,
+    # and the norm of K is the induced 2-norm.
+    A_norm = scipy.linalg.norm(A, 'fro')
+    X_norm = scipy.linalg.norm(X, 'fro')
+    K_norm = scipy.linalg.norm(K, 2)
+
+    kappa = (K_norm * A_norm) / X_norm
+    return kappa
diff --git a/.venv/lib/python3.12/site-packages/scipy/linalg/_fblas.cpython-312-x86_64-linux-gnu.so b/.venv/lib/python3.12/site-packages/scipy/linalg/_fblas.cpython-312-x86_64-linux-gnu.so
new file mode 100644
index 0000000000000000000000000000000000000000..e0e8747b4a5c23821edea8e59b5c3d45c5ce3577
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/linalg/_fblas.cpython-312-x86_64-linux-gnu.so
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:d435d06d1822fe2e7a8b31fa0a889cdd209252b931715f1ecf6fab988e314f0f
+size 1036825
diff --git a/.venv/lib/python3.12/site-packages/scipy/linalg/_flapack.cpython-312-x86_64-linux-gnu.so b/.venv/lib/python3.12/site-packages/scipy/linalg/_flapack.cpython-312-x86_64-linux-gnu.so
new file mode 100644
index 0000000000000000000000000000000000000000..c2d28a512072bac3a4b140e8dae05871a4a729b5
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/linalg/_flapack.cpython-312-x86_64-linux-gnu.so
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:00fc3e3414d7f42f023d5ba1f1b616d3d81da8da0f5cc6b17279af70be963b9c
+size 2572905
diff --git a/.venv/lib/python3.12/site-packages/scipy/linalg/_internal_matfuncs.cpython-312-x86_64-linux-gnu.so b/.venv/lib/python3.12/site-packages/scipy/linalg/_internal_matfuncs.cpython-312-x86_64-linux-gnu.so
new file mode 100644
index 0000000000000000000000000000000000000000..feb8f0bfc2a0bba06d8a348bb4fc195ffaeabcf9
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/linalg/_internal_matfuncs.cpython-312-x86_64-linux-gnu.so
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:e98f03e852b7acf316c6a6d2294360ed2fb98ee4b1e9c8eccffd123f9c1dc74f
+size 182105
diff --git a/.venv/lib/python3.12/site-packages/scipy/linalg/_linalg_pythran.cpython-312-x86_64-linux-gnu.so b/.venv/lib/python3.12/site-packages/scipy/linalg/_linalg_pythran.cpython-312-x86_64-linux-gnu.so
new file mode 100644
index 0000000000000000000000000000000000000000..e2cf8802776f7dec22ca7f56bef3fb63d65ac3c5
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/linalg/_linalg_pythran.cpython-312-x86_64-linux-gnu.so
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:2fe8e8d428897533d47f25fcc1028d9f5fcd16651b9d1e919ef52af812fc1a38
+size 121680
diff --git a/.venv/lib/python3.12/site-packages/scipy/linalg/_matfuncs.py b/.venv/lib/python3.12/site-packages/scipy/linalg/_matfuncs.py
new file mode 100644
index 0000000000000000000000000000000000000000..76cd64bb9db5ff7da0d8dc89a1cf8ef81f095bf2
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/linalg/_matfuncs.py
@@ -0,0 +1,909 @@
+#
+# Author: Travis Oliphant, March 2002
+#
+import warnings
+
+import numpy as np
+from numpy import (dot, diag, prod, logical_not, ravel, transpose,
+                   conjugate, absolute, amax, sign, isfinite, triu)
+
+from scipy._lib._util import _apply_over_batch, _deprecate_dtypes
+
+# Local imports
+from scipy.linalg import LinAlgError, LinAlgWarning
+from ._misc import norm
+from ._basic import solve, inv
+from ._decomp_svd import svd
+from ._decomp_schur import schur, rsf2csf
+from ._expm_frechet import expm_frechet, expm_cond
+from ._internal_matfuncs import recursive_schur_sqrtm, matrix_exponential
+from ._linalg_pythran import _funm_loops  # type: ignore[import-not-found]
+
+__all__ = ['expm', 'cosm', 'sinm', 'tanm', 'coshm', 'sinhm', 'tanhm', 'logm',
+           'funm', 'signm', 'sqrtm', 'fractional_matrix_power', 'expm_frechet',
+           'expm_cond', 'khatri_rao']
+
+eps = np.finfo('d').eps
+feps = np.finfo('f').eps
+
+_array_precision = {'i': 1, 'l': 1, 'f': 0, 'd': 1, 'F': 0, 'D': 1}
+
+
+###############################################################################
+# Utility functions.
+
+
+def _asarray_square(A):
+    """
+    Wraps asarray with the extra requirement that the input be a square matrix.
+
+    The motivation is that the matfuncs module has real functions that have
+    been lifted to square matrix functions.
+
+    Parameters
+    ----------
+    A : array_like
+        A square matrix.
+
+    Returns
+    -------
+    out : ndarray
+        An ndarray copy or view or other representation of A.
+
+    """
+    A = np.asarray(A)
+    if len(A.shape) != 2 or A.shape[0] != A.shape[1]:
+        raise ValueError('expected square array_like input')
+    return A
+
+
+def _maybe_real(A, B, tol=None):
+    """
+    Return either B or the real part of B, depending on properties of A and B.
+
+    The motivation is that B has been computed as a complicated function of A,
+    and B may be perturbed by negligible imaginary components.
+    If A is real and B is complex with small imaginary components,
+    then return a real copy of B.  The assumption in that case would be that
+    the imaginary components of B are numerical artifacts.
+
+    Parameters
+    ----------
+    A : ndarray
+        Input array whose type is to be checked as real vs. complex.
+    B : ndarray
+        Array to be returned, possibly without its imaginary part.
+    tol : float
+        Absolute tolerance.
+
+    Returns
+    -------
+    out : real or complex array
+        Either the input array B or only the real part of the input array B.
+
+    """
+    # Note that booleans and integers compare as real.
+    if np.isrealobj(A) and np.iscomplexobj(B):
+        if tol is None:
+            tol = {0: feps*1e3, 1: eps*1e6}[_array_precision[B.dtype.char]]
+        if np.allclose(B.imag, 0.0, atol=tol):
+            B = B.real
+    return B
+
+
+###############################################################################
+# Matrix functions.
+
+
+@_apply_over_batch(('A', 2))
+def fractional_matrix_power(A, t):
+    """
+    Compute the fractional power of a matrix.
+
+    Proceeds according to the discussion in section (6) of [1]_.
+
+    Parameters
+    ----------
+    A : (N, N) array_like
+        Matrix whose fractional power to evaluate.
+    t : float
+        Fractional power.
+
+    Returns
+    -------
+    X : (N, N) array_like
+        The fractional power of the matrix.
+
+    References
+    ----------
+    .. [1] Nicholas J. Higham and Lijing Lin (2011)
+           "A Schur-Pade Algorithm for Fractional Powers of a Matrix."
+           SIAM Journal on Matrix Analysis and Applications,
+           32 (3). pp. 1056-1078. ISSN 0895-4798.
+           :doi:`10.1137/10081232X`
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy.linalg import fractional_matrix_power
+    >>> a = np.array([[1.0, 3.0], [1.0, 4.0]])
+    >>> b = fractional_matrix_power(a, 0.5)
+    >>> b
+    array([[ 0.75592895,  1.13389342],
+           [ 0.37796447,  1.88982237]])
+    >>> np.dot(b, b)      # Verify square root
+    array([[ 1.,  3.],
+           [ 1.,  4.]])
+
+    """
+    # This fixes some issue with imports;
+    # this function calls onenormest which is in scipy.sparse.
+    A = _asarray_square(A)
+    import scipy.linalg._matfuncs_inv_ssq
+    return scipy.linalg._matfuncs_inv_ssq._fractional_matrix_power(A, t)
+
+
+@_apply_over_batch(('A', 2))
+def logm(A):
+    """
+    Compute matrix logarithm.
+
+    The matrix logarithm is the inverse of
+    expm: expm(logm(`A`)) == `A`
+
+    Parameters
+    ----------
+    A : (N, N) array_like
+        Matrix whose logarithm to evaluate
+
+    Returns
+    -------
+    logm : (N, N) ndarray
+        Matrix logarithm of `A`
+
+    References
+    ----------
+    .. [1] Awad H. Al-Mohy and Nicholas J. Higham (2012)
+           "Improved Inverse Scaling and Squaring Algorithms
+           for the Matrix Logarithm."
+           SIAM Journal on Scientific Computing, 34 (4). C152-C169.
+           ISSN 1095-7197
+
+    .. [2] Nicholas J. Higham (2008)
+           "Functions of Matrices: Theory and Computation"
+           ISBN 978-0-898716-46-7
+
+    .. [3] Nicholas J. Higham and Lijing lin (2011)
+           "A Schur-Pade Algorithm for Fractional Powers of a Matrix."
+           SIAM Journal on Matrix Analysis and Applications,
+           32 (3). pp. 1056-1078. ISSN 0895-4798
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy.linalg import logm, expm
+    >>> a = np.array([[1.0, 3.0], [1.0, 4.0]])
+    >>> b = logm(a)
+    >>> b
+    array([[-1.02571087,  2.05142174],
+           [ 0.68380725,  1.02571087]])
+    >>> expm(b)         # Verify expm(logm(a)) returns a
+    array([[ 1.,  3.],
+           [ 1.,  4.]])
+
+    """
+    A = np.asarray(A)  # squareness checked in `_logm`
+    # Avoid circular import ... this is OK, right?
+    import scipy.linalg._matfuncs_inv_ssq
+    F = scipy.linalg._matfuncs_inv_ssq._logm(A)
+    F = _maybe_real(A, F)
+    errtol = 1000*eps
+    # TODO use a better error approximation
+    with np.errstate(divide='ignore', invalid='ignore'):
+        errest = norm(expm(F)-A, 1) / np.asarray(norm(A, 1), dtype=A.dtype).real[()]
+    if not isfinite(errest) or errest >= errtol:
+        message = f"logm result may be inaccurate, approximate err = {errest}"
+        warnings.warn(message, RuntimeWarning, stacklevel=2)
+    return F
+
+
+def expm(A):
+    """Compute the matrix exponential of an array.
+
+    Array argument(s) of this function may have additional
+    "batch" dimensions prepended to the core shape. In this case, the array is treated
+    as a batch of lower-dimensional slices; see :ref:`linalg_batch` for details.
+
+    Parameters
+    ----------
+    A : ndarray
+        Input with last two dimensions are square ``(..., n, n)``.
+
+    Returns
+    -------
+    eA : ndarray
+        The resulting matrix exponential with the same shape of ``A``
+
+    Notes
+    -----
+    Implements the algorithm given in [1]_, which is essentially a Pade
+    approximation with a variable order that is decided based on the array
+    data.
+
+    For input with size ``n``, the memory usage is in the worst case in the
+    order of ``8*(n**2)``. If the input data is not of single and double
+    precision of real and complex dtypes, it is copied to a new array.
+
+    For cases ``n >= 400``, the exact 1-norm computation cost, breaks even with
+    1-norm estimation and from that point on the estimation scheme given in
+    [2]_ is used to decide on the approximation order.
+
+    References
+    ----------
+    .. [1] Awad H. Al-Mohy and Nicholas J. Higham, (2009), "A New Scaling
+           and Squaring Algorithm for the Matrix Exponential", SIAM J. Matrix
+           Anal. Appl. 31(3):970-989, :doi:`10.1137/09074721X`
+
+    .. [2] Nicholas J. Higham and Francoise Tisseur (2000), "A Block Algorithm
+           for Matrix 1-Norm Estimation, with an Application to 1-Norm
+           Pseudospectra." SIAM J. Matrix Anal. Appl. 21(4):1185-1201,
+           :doi:`10.1137/S0895479899356080`
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy.linalg import expm, sinm, cosm
+
+    Matrix version of the formula exp(0) = 1:
+
+    >>> expm(np.zeros((3, 2, 2)))
+    array([[[1., 0.],
+            [0., 1.]],
+    
+           [[1., 0.],
+            [0., 1.]],
+    
+           [[1., 0.],
+            [0., 1.]]])
+
+    Euler's identity (exp(i*theta) = cos(theta) + i*sin(theta))
+    applied to a matrix:
+
+    >>> a = np.array([[1.0, 2.0], [-1.0, 3.0]])
+    >>> expm(1j*a)
+    array([[ 0.42645930+1.89217551j, -2.13721484-0.97811252j],
+           [ 1.06860742+0.48905626j, -1.71075555+0.91406299j]])
+    >>> cosm(a) + 1j*sinm(a)
+    array([[ 0.42645930+1.89217551j, -2.13721484-0.97811252j],
+           [ 1.06860742+0.48905626j, -1.71075555+0.91406299j]])
+
+    """
+    a = np.asarray(A)
+    _deprecate_dtypes("expm", a)
+
+    if a.size == 1 and a.ndim < 2:
+        return np.array([[np.exp(a.item())]])
+
+    if a.ndim < 2:
+        raise LinAlgError('The input array must be at least two-dimensional')
+    if a.shape[-1] != a.shape[-2]:
+        raise LinAlgError('Last 2 dimensions of the array must be square')
+
+    # Empty array
+    if min(*a.shape) == 0:
+        dtype = expm(np.eye(2, dtype=a.dtype)).dtype
+        return np.empty_like(a, dtype=dtype)
+
+    # Scalar case
+    if a.shape[-2:] == (1, 1):
+        return np.exp(a)
+
+    if not np.issubdtype(a.dtype, np.inexact):
+        a = a.astype(np.float64)
+    elif a.dtype == np.float16:
+        a = a.astype(np.float32)
+
+    # An explicit formula for 2x2 case exists (formula (2.2) in [1]_). However, without
+    # Kahan's method, numerical instabilities can occur (See gh-19584). Hence removed
+    # here until we have a more stable implementation.
+
+    eA, info = matrix_exponential(a)
+    if info != 0:
+        if info <= -11:
+            # We raise it from failed mallocs; negative LAPACK codes > -7
+            raise MemoryError("scipy.linalg.expm could not allocate "
+                            "sufficient memory while trying to compute the "
+                            f"exponential (error code {info}).")
+        else:
+            # LAPACK wrong argument error or exact singularity.
+            # Neither should happen.
+            raise RuntimeError("scipy.linalg.expm: Internal LAPACK "
+                                "error during the exponential computation "
+                                f"(error code {info})")
+    return eA
+
+
+def sqrtm(A):
+    """
+    Compute, if exists, the matrix square root.
+
+    The matrix square root of ``A`` is a matrix ``X`` such that ``X @ X = A``.
+    Every square matrix is not guaranteed to have a matrix square root, for
+    example, the array ``[[0, 1], [0, 0]]`` does not have a square root.
+
+    Moreover, not every real matrix has a real square root. Hence, for
+    real-valued matrices the return type can be complex if, numerically, there
+    is an eigenvalue on the negative real axis.
+
+    Array argument(s) of this function may have additional
+    "batch" dimensions prepended to the core shape. In this case, the array is treated
+    as a batch of lower-dimensional slices; see :ref:`linalg_batch` for details.
+
+    Parameters
+    ----------
+    A : ndarray
+        Input with last two dimensions are square ``(..., n, n)``.
+
+    Returns
+    -------
+    sqrtm : ndarray
+        Computed matrix squareroot of `A` with same size ``(..., n, n)``.
+
+    Notes
+    -----
+    This function uses the Schur decomposition method to compute the matrix
+    square root following [1]_ and for real matrices [2]_. Moreover, note
+    that, there exist matrices that have square roots that are not polynomials
+    in ``A``. For a classical example from [2]_, the matrix satisfies::
+
+            [ a, a**2 + 1]**2     [-1,  0]
+            [-1,       -a]     =  [ 0, -1]
+
+    for any scalar ``a`` but it is not a polynomial in ``-I``. Thus, they will
+    not be found by this function.
+
+    References
+    ----------
+    .. [1] Edvin Deadman, Nicholas J. Higham, Rui Ralha (2013)
+           "Blocked Schur Algorithms for Computing the Matrix Square Root,
+           Lecture Notes in Computer Science, 7782. pp. 171-182.
+           :doi:`10.1016/0024-3795(87)90118-2`
+    .. [2] Nicholas J. Higham (1987) "Computing real square roots of a real
+           matrix", Linear Algebra and its Applications, 88/89:405-430.
+           :doi:`10.1016/0024-3795(87)90118-2`
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy.linalg import sqrtm
+    >>> a = np.array([[1.0, 3.0], [1.0, 4.0]])
+    >>> r = sqrtm(a)
+    >>> r
+    array([[ 0.75592895,  1.13389342],
+           [ 0.37796447,  1.88982237]])
+    >>> r.dot(r)
+    array([[ 1.,  3.],
+           [ 1.,  4.]])
+
+    """
+    a = np.asarray(A)
+    _deprecate_dtypes('sqrtm', a)
+    if a.size == 1 and a.ndim < 2:
+        return np.array([[np.exp(a.item())]])
+
+    if a.ndim < 2:
+        raise LinAlgError('The input array must be at least two-dimensional')
+    if a.shape[-1] != a.shape[-2]:
+        raise LinAlgError('Last 2 dimensions of the array must be square')
+
+    # Empty array
+    if min(*a.shape) == 0:
+        dtype = sqrtm(np.eye(2, dtype=a.dtype)).dtype
+        return np.empty_like(a, dtype=dtype)
+
+    # Scalar case
+    if a.shape[-2:] == (1, 1):
+        return np.emath.sqrt(a)
+
+    if not np.issubdtype(a.dtype, np.inexact):
+        a = a.astype(np.float64)
+    elif a.dtype == np.float16:
+        a = a.astype(np.float32)
+    elif a.dtype.char in 'G':
+        a = a.astype(np.complex128)
+    elif a.dtype.char in 'g':
+        a = a.astype(np.float64)
+
+    if a.dtype.char not in 'fdFD':
+        raise TypeError("scipy.linalg.sqrtm is not supported for the data type"
+                        f" {a.dtype}")
+
+    res, isIllconditioned, isSingular, info = recursive_schur_sqrtm(a)
+    if info < 0:
+        raise LinAlgError(f"Internal error in scipy.linalg.sqrtm: {info}")
+
+    if isSingular or isIllconditioned:
+        if isSingular:
+            msg = ("Matrix is singular. The result might be inaccurate or the"
+                   " array might not have a square root.")
+        else:
+            msg = ("Matrix is ill-conditioned. The result might be inaccurate"
+                   " or the array might not have a square root.")
+        warnings.warn(msg, LinAlgWarning, stacklevel=2)
+
+    return res
+
+
+@_apply_over_batch(('A', 2))
+def cosm(A):
+    """
+    Compute the matrix cosine.
+
+    This routine uses expm to compute the matrix exponentials.
+
+    Parameters
+    ----------
+    A : (N, N) array_like
+        Input array
+
+    Returns
+    -------
+    cosm : (N, N) ndarray
+        Matrix cosine of A
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy.linalg import expm, sinm, cosm
+
+    Euler's identity (exp(i*theta) = cos(theta) + i*sin(theta))
+    applied to a matrix:
+
+    >>> a = np.array([[1.0, 2.0], [-1.0, 3.0]])
+    >>> expm(1j*a)
+    array([[ 0.42645930+1.89217551j, -2.13721484-0.97811252j],
+           [ 1.06860742+0.48905626j, -1.71075555+0.91406299j]])
+    >>> cosm(a) + 1j*sinm(a)
+    array([[ 0.42645930+1.89217551j, -2.13721484-0.97811252j],
+           [ 1.06860742+0.48905626j, -1.71075555+0.91406299j]])
+
+    """
+    A = _asarray_square(A)
+    if np.iscomplexobj(A):
+        return 0.5*(expm(1j*A) + expm(-1j*A))
+    else:
+        return expm(1j*A).real
+
+
+@_apply_over_batch(('A', 2))
+def sinm(A):
+    """
+    Compute the matrix sine.
+
+    This routine uses expm to compute the matrix exponentials.
+
+    Parameters
+    ----------
+    A : (N, N) array_like
+        Input array.
+
+    Returns
+    -------
+    sinm : (N, N) ndarray
+        Matrix sine of `A`
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy.linalg import expm, sinm, cosm
+
+    Euler's identity (exp(i*theta) = cos(theta) + i*sin(theta))
+    applied to a matrix:
+
+    >>> a = np.array([[1.0, 2.0], [-1.0, 3.0]])
+    >>> expm(1j*a)
+    array([[ 0.42645930+1.89217551j, -2.13721484-0.97811252j],
+           [ 1.06860742+0.48905626j, -1.71075555+0.91406299j]])
+    >>> cosm(a) + 1j*sinm(a)
+    array([[ 0.42645930+1.89217551j, -2.13721484-0.97811252j],
+           [ 1.06860742+0.48905626j, -1.71075555+0.91406299j]])
+
+    """
+    A = _asarray_square(A)
+    if np.iscomplexobj(A):
+        return -0.5j*(expm(1j*A) - expm(-1j*A))
+    else:
+        return expm(1j*A).imag
+
+
+@_apply_over_batch(('A', 2))
+def tanm(A):
+    """
+    Compute the matrix tangent.
+
+    This routine uses expm to compute the matrix exponentials.
+
+    Parameters
+    ----------
+    A : (N, N) array_like
+        Input array.
+
+    Returns
+    -------
+    tanm : (N, N) ndarray
+        Matrix tangent of `A`
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy.linalg import tanm, sinm, cosm
+    >>> a = np.array([[1.0, 3.0], [1.0, 4.0]])
+    >>> t = tanm(a)
+    >>> t
+    array([[ -2.00876993,  -8.41880636],
+           [ -2.80626879, -10.42757629]])
+
+    Verify tanm(a) = sinm(a).dot(inv(cosm(a)))
+
+    >>> s = sinm(a)
+    >>> c = cosm(a)
+    >>> s.dot(np.linalg.inv(c))
+    array([[ -2.00876993,  -8.41880636],
+           [ -2.80626879, -10.42757629]])
+
+    """
+    A = _asarray_square(A)
+    return _maybe_real(A, solve(cosm(A), sinm(A)))
+
+
+@_apply_over_batch(('A', 2))
+def coshm(A):
+    """
+    Compute the hyperbolic matrix cosine.
+
+    This routine uses expm to compute the matrix exponentials.
+
+    Parameters
+    ----------
+    A : (N, N) array_like
+        Input array.
+
+    Returns
+    -------
+    coshm : (N, N) ndarray
+        Hyperbolic matrix cosine of `A`
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy.linalg import tanhm, sinhm, coshm
+    >>> a = np.array([[1.0, 3.0], [1.0, 4.0]])
+    >>> c = coshm(a)
+    >>> c
+    array([[ 11.24592233,  38.76236492],
+           [ 12.92078831,  50.00828725]])
+
+    Verify tanhm(a) = sinhm(a).dot(inv(coshm(a)))
+
+    >>> t = tanhm(a)
+    >>> s = sinhm(a)
+    >>> t - s.dot(np.linalg.inv(c))
+    array([[  2.72004641e-15,   4.55191440e-15],
+           [  0.00000000e+00,  -5.55111512e-16]])
+
+    """
+    A = _asarray_square(A)
+    return _maybe_real(A, 0.5 * (expm(A) + expm(-A)))
+
+
+@_apply_over_batch(('A', 2))
+def sinhm(A):
+    """
+    Compute the hyperbolic matrix sine.
+
+    This routine uses expm to compute the matrix exponentials.
+
+    Parameters
+    ----------
+    A : (N, N) array_like
+        Input array.
+
+    Returns
+    -------
+    sinhm : (N, N) ndarray
+        Hyperbolic matrix sine of `A`
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy.linalg import tanhm, sinhm, coshm
+    >>> a = np.array([[1.0, 3.0], [1.0, 4.0]])
+    >>> s = sinhm(a)
+    >>> s
+    array([[ 10.57300653,  39.28826594],
+           [ 13.09608865,  49.86127247]])
+
+    Verify tanhm(a) = sinhm(a).dot(inv(coshm(a)))
+
+    >>> t = tanhm(a)
+    >>> c = coshm(a)
+    >>> t - s.dot(np.linalg.inv(c))
+    array([[  2.72004641e-15,   4.55191440e-15],
+           [  0.00000000e+00,  -5.55111512e-16]])
+
+    """
+    A = _asarray_square(A)
+    return _maybe_real(A, 0.5 * (expm(A) - expm(-A)))
+
+
+@_apply_over_batch(('A', 2))
+def tanhm(A):
+    """
+    Compute the hyperbolic matrix tangent.
+
+    This routine uses expm to compute the matrix exponentials.
+
+    Parameters
+    ----------
+    A : (N, N) array_like
+        Input array
+
+    Returns
+    -------
+    tanhm : (N, N) ndarray
+        Hyperbolic matrix tangent of `A`
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy.linalg import tanhm, sinhm, coshm
+    >>> a = np.array([[1.0, 3.0], [1.0, 4.0]])
+    >>> t = tanhm(a)
+    >>> t
+    array([[ 0.3428582 ,  0.51987926],
+           [ 0.17329309,  0.86273746]])
+
+    Verify tanhm(a) = sinhm(a).dot(inv(coshm(a)))
+
+    >>> s = sinhm(a)
+    >>> c = coshm(a)
+    >>> t - s.dot(np.linalg.inv(c))
+    array([[  2.72004641e-15,   4.55191440e-15],
+           [  0.00000000e+00,  -5.55111512e-16]])
+
+    """
+    A = _asarray_square(A)
+    return _maybe_real(A, solve(coshm(A), sinhm(A)))
+
+
+@_apply_over_batch(('A', 2))
+def funm(A, func, disp=True):
+    """
+    Evaluate a matrix function specified by a callable.
+
+    Returns the value of matrix-valued function ``f`` at `A`. The
+    function ``f`` is an extension of the scalar-valued function `func`
+    to matrices.
+
+    Parameters
+    ----------
+    A : (N, N) array_like
+        Matrix at which to evaluate the function
+    func : callable
+        Callable object that evaluates a scalar function f.
+        Must be vectorized (eg. using vectorize).
+    disp : bool, optional
+        Print warning if error in the result is estimated large
+        instead of returning estimated error. (Default: True)
+
+    Returns
+    -------
+    funm : (N, N) ndarray
+        Value of the matrix function specified by func evaluated at `A`
+    errest : float
+        (if disp == False)
+
+        1-norm of the estimated error, ||err||_1 / ||A||_1
+
+    Notes
+    -----
+    This function implements the general algorithm based on Schur decomposition
+    (Algorithm 9.1.1. in [1]_).
+
+    If the input matrix is known to be diagonalizable, then relying on the
+    eigendecomposition is likely to be faster. For example, if your matrix is
+    Hermitian, you can do
+
+    >>> from scipy.linalg import eigh
+    >>> def funm_herm(a, func, check_finite=False):
+    ...     w, v = eigh(a, check_finite=check_finite)
+    ...     ## if you further know that your matrix is positive semidefinite,
+    ...     ## you can optionally guard against precision errors by doing
+    ...     # w = np.maximum(w, 0)
+    ...     w = func(w)
+    ...     return (v * w).dot(v.conj().T)
+
+    References
+    ----------
+    .. [1] Gene H. Golub, Charles F. van Loan, Matrix Computations 4th ed.
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy.linalg import funm
+    >>> a = np.array([[1.0, 3.0], [1.0, 4.0]])
+    >>> funm(a, lambda x: x*x)
+    array([[  4.,  15.],
+           [  5.,  19.]])
+    >>> a.dot(a)
+    array([[  4.,  15.],
+           [  5.,  19.]])
+
+    """
+    A = _asarray_square(A)
+    # Perform Shur decomposition (lapack ?gees)
+    T, Z = schur(A)
+    T, Z = rsf2csf(T, Z)
+    n, n = T.shape
+    F = diag(func(diag(T)))  # apply function to diagonal elements
+    F = F.astype(T.dtype.char)  # e.g., when F is real but T is complex
+
+    minden = abs(T[0, 0])
+
+    # implement Algorithm 11.1.1 from Golub and Van Loan
+    #                 "matrix Computations."
+    F, minden = _funm_loops(F, T, n, minden)
+
+    F = dot(dot(Z, F), transpose(conjugate(Z)))
+    F = _maybe_real(A, F)
+
+    tol = {0: feps, 1: eps}[_array_precision[F.dtype.char]]
+    if minden == 0.0:
+        minden = tol
+    err = min(1, max(tol, (tol/minden)*norm(triu(T, 1), 1)))
+    if prod(ravel(logical_not(isfinite(F))), axis=0):
+        err = np.inf
+    if disp:
+        if err > 1000*tol:
+            print("funm result may be inaccurate, approximate err =", err)
+        return F
+    else:
+        return F, err
+
+
+@_apply_over_batch(('A', 2))
+def signm(A):
+    """
+    Matrix sign function.
+
+    Extension of the scalar sign(x) to matrices.
+
+    Parameters
+    ----------
+    A : (N, N) array_like
+        Matrix at which to evaluate the sign function
+
+    Returns
+    -------
+    signm : (N, N) ndarray
+        Value of the sign function at `A`
+
+    Examples
+    --------
+    >>> from scipy.linalg import signm, eigvals
+    >>> a = [[1,2,3], [1,2,1], [1,1,1]]
+    >>> eigvals(a)
+    array([ 4.12488542+0.j, -0.76155718+0.j,  0.63667176+0.j])
+    >>> eigvals(signm(a))
+    array([-1.+0.j,  1.+0.j,  1.+0.j])
+
+    """
+    A = _asarray_square(A)
+
+    def rounded_sign(x):
+        rx = np.real(x)
+        if rx.dtype.char == 'f':
+            c = 1e3*feps*amax(x)
+        else:
+            c = 1e3*eps*amax(x)
+        return sign((absolute(rx) > c) * rx)
+    result, errest = funm(A, rounded_sign, disp=0)
+    errtol = {0: 1e3*feps, 1: 1e3*eps}[_array_precision[result.dtype.char]]
+    if errest < errtol:
+        return result
+
+    # Handle signm of defective matrices:
+
+    # See "E.D.Denman and J.Leyva-Ramos, Appl.Math.Comp.,
+    # 8:237-250,1981" for how to improve the following (currently a
+    # rather naive) iteration process:
+
+    # a = result # sometimes iteration converges faster but where??
+
+    # Shifting to avoid zero eigenvalues. How to ensure that shifting does
+    # not change the spectrum too much?
+    vals = svd(A, compute_uv=False)
+    max_sv = np.amax(vals)
+    # min_nonzero_sv = vals[(vals>max_sv*errtol).tolist().count(1)-1]
+    # c = 0.5/min_nonzero_sv
+    c = 0.5/max_sv
+    S0 = A + c*np.identity(A.shape[0], dtype=A.dtype)
+    prev_errest = errest
+    for i in range(100):
+        iS0 = inv(S0)
+        S0 = 0.5*(S0 + iS0)
+        Pp = 0.5*(dot(S0, S0)+S0)
+        errest = norm(dot(Pp, Pp)-Pp, 1)
+        if errest < errtol or prev_errest == errest:
+            break
+        prev_errest = errest
+    if not isfinite(errest) or errest >= errtol:
+        print("signm result may be inaccurate, approximate err =", errest)
+    return S0
+
+
+@_apply_over_batch(('a', 2), ('b', 2))
+def khatri_rao(a, b):
+    r"""
+    Khatri-Rao product of two matrices.
+
+    A column-wise Kronecker product of two matrices
+
+    Parameters
+    ----------
+    a : (n, k) array_like
+        Input array
+    b : (m, k) array_like
+        Input array
+
+    Returns
+    -------
+    c:  (n*m, k) ndarray
+        Khatri-rao product of `a` and `b`.
+
+    Notes
+    -----
+    The mathematical definition of the Khatri-Rao product is:
+
+    .. math::
+
+        (A_{ij}  \bigotimes B_{ij})_{ij}
+
+    which is the Kronecker product of every column of A and B, e.g.::
+
+        c = np.vstack([np.kron(a[:, k], b[:, k]) for k in range(b.shape[1])]).T
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy import linalg
+    >>> a = np.array([[1, 2, 3], [4, 5, 6]])
+    >>> b = np.array([[3, 4, 5], [6, 7, 8], [2, 3, 9]])
+    >>> linalg.khatri_rao(a, b)
+    array([[ 3,  8, 15],
+           [ 6, 14, 24],
+           [ 2,  6, 27],
+           [12, 20, 30],
+           [24, 35, 48],
+           [ 8, 15, 54]])
+
+    """
+    a = np.asarray(a)
+    b = np.asarray(b)
+
+    if not (a.ndim == 2 and b.ndim == 2):
+        raise ValueError("The both arrays should be 2-dimensional.")
+
+    if not a.shape[1] == b.shape[1]:
+        raise ValueError("The number of columns for both arrays "
+                         "should be equal.")
+
+    # accommodate empty arrays
+    if a.size == 0 or b.size == 0:
+        m = a.shape[0] * b.shape[0]
+        n = a.shape[1]
+        return np.empty_like(a, shape=(m, n))
+
+    # c = np.vstack([np.kron(a[:, k], b[:, k]) for k in range(b.shape[1])]).T
+    c = a[..., :, np.newaxis, :] * b[..., np.newaxis, :, :]
+    return c.reshape((-1,) + c.shape[2:])
diff --git a/.venv/lib/python3.12/site-packages/scipy/linalg/_matfuncs_inv_ssq.py b/.venv/lib/python3.12/site-packages/scipy/linalg/_matfuncs_inv_ssq.py
new file mode 100644
index 0000000000000000000000000000000000000000..1fda059e10dc6abf0ba4f915d1709a38d25855e5
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/linalg/_matfuncs_inv_ssq.py
@@ -0,0 +1,885 @@
+"""
+Matrix functions that use Pade approximation with inverse scaling and squaring.
+
+"""
+import warnings
+
+import numpy as np
+
+from scipy.linalg._matfuncs_sqrtm import SqrtmError, _sqrtm_triu
+from scipy.linalg._decomp_schur import schur, rsf2csf
+from scipy.linalg._matfuncs import funm
+from scipy.linalg import svdvals, solve_triangular
+from scipy.sparse.linalg._interface import LinearOperator
+from scipy.sparse.linalg import onenormest
+import scipy.special
+
+
+class LogmRankWarning(UserWarning):
+    pass
+
+
+class LogmExactlySingularWarning(LogmRankWarning):
+    pass
+
+
+class LogmNearlySingularWarning(LogmRankWarning):
+    pass
+
+
+class LogmError(np.linalg.LinAlgError):
+    pass
+
+
+class FractionalMatrixPowerError(np.linalg.LinAlgError):
+    pass
+
+
+#TODO renovate or move this class when scipy operators are more mature
+class _MatrixM1PowerOperator(LinearOperator):
+    """
+    A representation of the linear operator (A - I)^p.
+    """
+
+    def __init__(self, A, p):
+        if A.ndim != 2 or A.shape[0] != A.shape[1]:
+            raise ValueError('expected A to be like a square matrix')
+        if p < 0 or p != int(p):
+            raise ValueError('expected p to be a non-negative integer')
+        self._A = A
+        self._p = p
+        super().__init__(dtype=A.dtype, shape=A.shape)
+
+    def _matvec(self, x):
+        for i in range(self._p):
+            x = self._A.dot(x) - x
+        return x
+
+    def _rmatvec(self, x):
+        for i in range(self._p):
+            x = x.dot(self._A) - x
+        return x
+
+    def _matmat(self, X):
+        for i in range(self._p):
+            X = self._A.dot(X) - X
+        return X
+
+    def _adjoint(self):
+        return _MatrixM1PowerOperator(self._A.T, self._p)
+
+
+#TODO renovate or move this function when SciPy operators are more mature
+def _onenormest_m1_power(A, p,
+        t=2, itmax=5, compute_v=False, compute_w=False):
+    """
+    Efficiently estimate the 1-norm of (A - I)^p.
+
+    Parameters
+    ----------
+    A : ndarray
+        Matrix whose 1-norm of a power is to be computed.
+    p : int
+        Non-negative integer power.
+    t : int, optional
+        A positive parameter controlling the tradeoff between
+        accuracy versus time and memory usage.
+        Larger values take longer and use more memory
+        but give more accurate output.
+    itmax : int, optional
+        Use at most this many iterations.
+    compute_v : bool, optional
+        Request a norm-maximizing linear operator input vector if True.
+    compute_w : bool, optional
+        Request a norm-maximizing linear operator output vector if True.
+
+    Returns
+    -------
+    est : float
+        An underestimate of the 1-norm of the sparse matrix.
+    v : ndarray, optional
+        The vector such that ||Av||_1 == est*||v||_1.
+        It can be thought of as an input to the linear operator
+        that gives an output with particularly large norm.
+    w : ndarray, optional
+        The vector Av which has relatively large 1-norm.
+        It can be thought of as an output of the linear operator
+        that is relatively large in norm compared to the input.
+
+    """
+    return onenormest(_MatrixM1PowerOperator(A, p),
+            t=t, itmax=itmax, compute_v=compute_v, compute_w=compute_w)
+
+
+def _unwindk(z):
+    """
+    Compute the scalar unwinding number.
+
+    Uses Eq. (5.3) in [1]_, and should be equal to (z - log(exp(z)) / (2 pi i).
+    Note that this definition differs in sign from the original definition
+    in equations (5, 6) in [2]_.  The sign convention is justified in [3]_.
+
+    Parameters
+    ----------
+    z : complex
+        A complex number.
+
+    Returns
+    -------
+    unwinding_number : int
+        The scalar unwinding number of z.
+
+    References
+    ----------
+    .. [1] Nicholas J. Higham and Lijing lin (2011)
+           "A Schur-Pade Algorithm for Fractional Powers of a Matrix."
+           SIAM Journal on Matrix Analysis and Applications,
+           32 (3). pp. 1056-1078. ISSN 0895-4798
+
+    .. [2] Robert M. Corless and David J. Jeffrey,
+           "The unwinding number." Newsletter ACM SIGSAM Bulletin
+           Volume 30, Issue 2, June 1996, Pages 28-35.
+
+    .. [3] Russell Bradford and Robert M. Corless and James H. Davenport and
+           David J. Jeffrey and Stephen M. Watt,
+           "Reasoning about the elementary functions of complex analysis"
+           Annals of Mathematics and Artificial Intelligence,
+           36: 303-318, 2002.
+
+    """
+    return int(np.ceil((z.imag - np.pi) / (2*np.pi)))
+
+
+def _briggs_helper_function(a, k):
+    """
+    Computes r = a^(1 / (2^k)) - 1.
+
+    This is algorithm (2) of [1]_.
+    The purpose is to avoid a danger of subtractive cancellation.
+    For more computational efficiency it should probably be cythonized.
+
+    Parameters
+    ----------
+    a : complex
+        A complex number.
+    k : int
+        A nonnegative integer.
+
+    Returns
+    -------
+    r : complex
+        The value r = a^(1 / (2^k)) - 1 computed with less cancellation.
+
+    Notes
+    -----
+    The algorithm as formulated in the reference does not handle k=0 or k=1
+    correctly, so these are special-cased in this implementation.
+    This function is intended to not allow `a` to belong to the closed
+    negative real axis, but this constraint is relaxed.
+
+    References
+    ----------
+    .. [1] Awad H. Al-Mohy (2012)
+           "A more accurate Briggs method for the logarithm",
+           Numerical Algorithms, 59 : 393--402.
+
+    """
+    if k < 0 or int(k) != k:
+        raise ValueError('expected a nonnegative integer k')
+    if k == 0:
+        return a - 1
+    elif k == 1:
+        return np.sqrt(a) - 1
+    else:
+        k_hat = k
+        if np.angle(a) >= np.pi / 2:
+            a = np.sqrt(a)
+            k_hat = k - 1
+        z0 = a - 1
+        a = np.sqrt(a)
+        r = 1 + a
+        for j in range(1, k_hat):
+            a = np.sqrt(a)
+            r = r * (1 + a)
+        r = z0 / r
+        return r
+
+
+def _fractional_power_superdiag_entry(l1, l2, t12, p):
+    """
+    Compute a superdiagonal entry of a fractional matrix power.
+
+    This is Eq. (5.6) in [1]_.
+
+    Parameters
+    ----------
+    l1 : complex
+        A diagonal entry of the matrix.
+    l2 : complex
+        A diagonal entry of the matrix.
+    t12 : complex
+        A superdiagonal entry of the matrix.
+    p : float
+        A fractional power.
+
+    Returns
+    -------
+    f12 : complex
+        A superdiagonal entry of the fractional matrix power.
+
+    Notes
+    -----
+    Care has been taken to return a real number if possible when
+    all of the inputs are real numbers.
+
+    References
+    ----------
+    .. [1] Nicholas J. Higham and Lijing lin (2011)
+           "A Schur-Pade Algorithm for Fractional Powers of a Matrix."
+           SIAM Journal on Matrix Analysis and Applications,
+           32 (3). pp. 1056-1078. ISSN 0895-4798
+
+    """
+    if l1 == l2:
+        f12 = t12 * p * l1**(p-1)
+    elif abs(l2 - l1) > abs(l1 + l2) / 2:
+        f12 = t12 * ((l2**p) - (l1**p)) / (l2 - l1)
+    else:
+        # This is Eq. (5.5) in [1].
+        z = (l2 - l1) / (l2 + l1)
+        log_l1 = np.log(l1)
+        log_l2 = np.log(l2)
+        arctanh_z = np.arctanh(z)
+        tmp_a = t12 * np.exp((p/2)*(log_l2 + log_l1))
+        tmp_u = _unwindk(log_l2 - log_l1)
+        if tmp_u:
+            tmp_b = p * (arctanh_z + np.pi * 1j * tmp_u)
+        else:
+            tmp_b = p * arctanh_z
+        tmp_c = 2 * np.sinh(tmp_b) / (l2 - l1)
+        f12 = tmp_a * tmp_c
+    return f12
+
+
+def _logm_superdiag_entry(l1, l2, t12):
+    """
+    Compute a superdiagonal entry of a matrix logarithm.
+
+    This is like Eq. (11.28) in [1]_, except the determination of whether
+    l1 and l2 are sufficiently far apart has been modified.
+
+    Parameters
+    ----------
+    l1 : complex
+        A diagonal entry of the matrix.
+    l2 : complex
+        A diagonal entry of the matrix.
+    t12 : complex
+        A superdiagonal entry of the matrix.
+
+    Returns
+    -------
+    f12 : complex
+        A superdiagonal entry of the matrix logarithm.
+
+    Notes
+    -----
+    Care has been taken to return a real number if possible when
+    all of the inputs are real numbers.
+
+    References
+    ----------
+    .. [1] Nicholas J. Higham (2008)
+           "Functions of Matrices: Theory and Computation"
+           ISBN 978-0-898716-46-7
+
+    """
+    if l1 == l2:
+        f12 = t12 / l1
+    elif abs(l2 - l1) > abs(l1 + l2) / 2:
+        f12 = t12 * (np.log(l2) - np.log(l1)) / (l2 - l1)
+    else:
+        z = (l2 - l1) / (l2 + l1)
+        u = _unwindk(np.log(l2) - np.log(l1))
+        if u:
+            f12 = t12 * 2 * (np.arctanh(z) + np.pi*1j*u) / (l2 - l1)
+        else:
+            f12 = t12 * 2 * np.arctanh(z) / (l2 - l1)
+    return f12
+
+
+def _inverse_squaring_helper(T0, theta):
+    """
+    A helper function for inverse scaling and squaring for Pade approximation.
+
+    Parameters
+    ----------
+    T0 : (N, N) array_like upper triangular
+        Matrix involved in inverse scaling and squaring.
+    theta : indexable
+        The values theta[1] .. theta[7] must be available.
+        They represent bounds related to Pade approximation, and they depend
+        on the matrix function which is being computed.
+        For example, different values of theta are required for
+        matrix logarithm than for fractional matrix power.
+
+    Returns
+    -------
+    R : (N, N) array_like upper triangular
+        Composition of zero or more matrix square roots of T0, minus I.
+    s : non-negative integer
+        Number of square roots taken.
+    m : positive integer
+        The degree of the Pade approximation.
+
+    Notes
+    -----
+    This subroutine appears as a chunk of lines within
+    a couple of published algorithms; for example it appears
+    as lines 4--35 in algorithm (3.1) of [1]_, and
+    as lines 3--34 in algorithm (4.1) of [2]_.
+    The instances of 'goto line 38' in algorithm (3.1) of [1]_
+    probably mean 'goto line 36' and have been interpreted accordingly.
+
+    References
+    ----------
+    .. [1] Nicholas J. Higham and Lijing Lin (2013)
+           "An Improved Schur-Pade Algorithm for Fractional Powers
+           of a Matrix and their Frechet Derivatives."
+
+    .. [2] Awad H. Al-Mohy and Nicholas J. Higham (2012)
+           "Improved Inverse Scaling and Squaring Algorithms
+           for the Matrix Logarithm."
+           SIAM Journal on Scientific Computing, 34 (4). C152-C169.
+           ISSN 1095-7197
+
+    """
+    if len(T0.shape) != 2 or T0.shape[0] != T0.shape[1]:
+        raise ValueError('expected an upper triangular square matrix')
+    n, n = T0.shape
+    T = T0
+
+    # Find s0, the smallest s such that the spectral radius
+    # of a certain diagonal matrix is at most theta[7].
+    # Note that because theta[7] < 1,
+    # this search will not terminate if any diagonal entry of T is zero.
+    s0 = 0
+    tmp_diag = np.diag(T)
+    if np.count_nonzero(tmp_diag) != n:
+        raise Exception('Diagonal entries of T must be nonzero')
+    while np.max(np.absolute(tmp_diag - 1), initial=0.) > theta[7]:
+        tmp_diag = np.sqrt(tmp_diag)
+        s0 += 1
+
+    # Take matrix square roots of T.
+    for i in range(s0):
+        T = _sqrtm_triu(T)
+
+    # Flow control in this section is a little odd.
+    # This is because I am translating algorithm descriptions
+    # which have GOTOs in the publication.
+    s = s0
+    k = 0
+    d2 = _onenormest_m1_power(T, 2) ** (1/2)
+    d3 = _onenormest_m1_power(T, 3) ** (1/3)
+    a2 = max(d2, d3)
+    m = None
+    for i in (1, 2):
+        if a2 <= theta[i]:
+            m = i
+            break
+    while m is None:
+        if s > s0:
+            d3 = _onenormest_m1_power(T, 3) ** (1/3)
+        d4 = _onenormest_m1_power(T, 4) ** (1/4)
+        a3 = max(d3, d4)
+        if a3 <= theta[7]:
+            j1 = min(i for i in (3, 4, 5, 6, 7) if a3 <= theta[i])
+            if j1 <= 6:
+                m = j1
+                break
+            elif a3 / 2 <= theta[5] and k < 2:
+                k += 1
+                T = _sqrtm_triu(T)
+                s += 1
+                continue
+        d5 = _onenormest_m1_power(T, 5) ** (1/5)
+        a4 = max(d4, d5)
+        eta = min(a3, a4)
+        for i in (6, 7):
+            if eta <= theta[i]:
+                m = i
+                break
+        if m is not None:
+            break
+        T = _sqrtm_triu(T)
+        s += 1
+
+    # The subtraction of the identity is redundant here,
+    # because the diagonal will be replaced for improved numerical accuracy,
+    # but this formulation should help clarify the meaning of R.
+    R = T - np.identity(n)
+
+    # Replace the diagonal and first superdiagonal of T0^(1/(2^s)) - I
+    # using formulas that have less subtractive cancellation.
+    # Skip this step if the principal branch
+    # does not exist at T0; this happens when a diagonal entry of T0
+    # is negative with imaginary part 0.
+    has_principal_branch = all(x.real > 0 or x.imag != 0 for x in np.diag(T0))
+    if has_principal_branch:
+        for j in range(n):
+            a = T0[j, j]
+            r = _briggs_helper_function(a, s)
+            R[j, j] = r
+        p = np.exp2(-s)
+        for j in range(n-1):
+            l1 = T0[j, j]
+            l2 = T0[j+1, j+1]
+            t12 = T0[j, j+1]
+            f12 = _fractional_power_superdiag_entry(l1, l2, t12, p)
+            R[j, j+1] = f12
+
+    # Return the T-I matrix, the number of square roots, and the Pade degree.
+    if not np.array_equal(R, np.triu(R)):
+        raise Exception('R is not upper triangular')
+    return R, s, m
+
+
+def _fractional_power_pade_constant(i, t):
+    # A helper function for matrix fractional power.
+    if i < 1:
+        raise ValueError('expected a positive integer i')
+    if not (-1 < t < 1):
+        raise ValueError('expected -1 < t < 1')
+    if i == 1:
+        return -t
+    elif i % 2 == 0:
+        j = i // 2
+        return (-j + t) / (2 * (2*j - 1))
+    elif i % 2 == 1:
+        j = (i - 1) // 2
+        return (-j - t) / (2 * (2*j + 1))
+    else:
+        raise Exception(f'unnexpected value of i, i = {i}')
+
+
+def _fractional_power_pade(R, t, m):
+    """
+    Evaluate the Pade approximation of a fractional matrix power.
+
+    Evaluate the degree-m Pade approximation of R
+    to the fractional matrix power t using the continued fraction
+    in bottom-up fashion using algorithm (4.1) in [1]_.
+
+    Parameters
+    ----------
+    R : (N, N) array_like
+        Upper triangular matrix whose fractional power to evaluate.
+    t : float
+        Fractional power between -1 and 1 exclusive.
+    m : positive integer
+        Degree of Pade approximation.
+
+    Returns
+    -------
+    U : (N, N) array_like
+        The degree-m Pade approximation of R to the fractional power t.
+        This matrix will be upper triangular.
+
+    References
+    ----------
+    .. [1] Nicholas J. Higham and Lijing lin (2011)
+           "A Schur-Pade Algorithm for Fractional Powers of a Matrix."
+           SIAM Journal on Matrix Analysis and Applications,
+           32 (3). pp. 1056-1078. ISSN 0895-4798
+
+    """
+    if m < 1 or int(m) != m:
+        raise ValueError('expected a positive integer m')
+    if not (-1 < t < 1):
+        raise ValueError('expected -1 < t < 1')
+    R = np.asarray(R)
+    if len(R.shape) != 2 or R.shape[0] != R.shape[1]:
+        raise ValueError('expected an upper triangular square matrix')
+    n, n = R.shape
+    ident = np.identity(n)
+    Y = R * _fractional_power_pade_constant(2*m, t)
+    for j in range(2*m - 1, 0, -1):
+        rhs = R * _fractional_power_pade_constant(j, t)
+        Y = solve_triangular(ident + Y, rhs)
+    U = ident + Y
+    if not np.array_equal(U, np.triu(U)):
+        raise Exception('U is not upper triangular')
+    return U
+
+
+def _remainder_matrix_power_triu(T, t):
+    """
+    Compute a fractional power of an upper triangular matrix.
+
+    The fractional power is restricted to fractions -1 < t < 1.
+    This uses algorithm (3.1) of [1]_.
+    The Pade approximation itself uses algorithm (4.1) of [2]_.
+
+    Parameters
+    ----------
+    T : (N, N) array_like
+        Upper triangular matrix whose fractional power to evaluate.
+    t : float
+        Fractional power between -1 and 1 exclusive.
+
+    Returns
+    -------
+    X : (N, N) array_like
+        The fractional power of the matrix.
+
+    References
+    ----------
+    .. [1] Nicholas J. Higham and Lijing Lin (2013)
+           "An Improved Schur-Pade Algorithm for Fractional Powers
+           of a Matrix and their Frechet Derivatives."
+
+    .. [2] Nicholas J. Higham and Lijing lin (2011)
+           "A Schur-Pade Algorithm for Fractional Powers of a Matrix."
+           SIAM Journal on Matrix Analysis and Applications,
+           32 (3). pp. 1056-1078. ISSN 0895-4798
+
+    """
+    m_to_theta = {
+            1: 1.51e-5,
+            2: 2.24e-3,
+            3: 1.88e-2,
+            4: 6.04e-2,
+            5: 1.24e-1,
+            6: 2.00e-1,
+            7: 2.79e-1,
+            }
+    n, n = T.shape
+    T0 = T
+    T0_diag = np.diag(T0)
+    if np.array_equal(T0, np.diag(T0_diag)):
+        U = np.diag(T0_diag ** t)
+    else:
+        R, s, m = _inverse_squaring_helper(T0, m_to_theta)
+
+        # Evaluate the Pade approximation.
+        # Note that this function expects the negative of the matrix
+        # returned by the inverse squaring helper.
+        U = _fractional_power_pade(-R, t, m)
+
+        # Undo the inverse scaling and squaring.
+        # Be less clever about this
+        # if the principal branch does not exist at T0;
+        # this happens when a diagonal entry of T0
+        # is negative with imaginary part 0.
+        eivals = np.diag(T0)
+        has_principal_branch = all(x.real > 0 or x.imag != 0 for x in eivals)
+        for i in range(s, -1, -1):
+            if i < s:
+                U = U.dot(U)
+            else:
+                if has_principal_branch:
+                    p = t * np.exp2(-i)
+                    U[np.diag_indices(n)] = T0_diag ** p
+                    for j in range(n-1):
+                        l1 = T0[j, j]
+                        l2 = T0[j+1, j+1]
+                        t12 = T0[j, j+1]
+                        f12 = _fractional_power_superdiag_entry(l1, l2, t12, p)
+                        U[j, j+1] = f12
+    if not np.array_equal(U, np.triu(U)):
+        raise Exception('U is not upper triangular')
+    return U
+
+
+def _remainder_matrix_power(A, t):
+    """
+    Compute the fractional power of a matrix, for fractions -1 < t < 1.
+
+    This uses algorithm (3.1) of [1]_.
+    The Pade approximation itself uses algorithm (4.1) of [2]_.
+
+    Parameters
+    ----------
+    A : (N, N) array_like
+        Matrix whose fractional power to evaluate.
+    t : float
+        Fractional power between -1 and 1 exclusive.
+
+    Returns
+    -------
+    X : (N, N) array_like
+        The fractional power of the matrix.
+
+    References
+    ----------
+    .. [1] Nicholas J. Higham and Lijing Lin (2013)
+           "An Improved Schur-Pade Algorithm for Fractional Powers
+           of a Matrix and their Frechet Derivatives."
+
+    .. [2] Nicholas J. Higham and Lijing lin (2011)
+           "A Schur-Pade Algorithm for Fractional Powers of a Matrix."
+           SIAM Journal on Matrix Analysis and Applications,
+           32 (3). pp. 1056-1078. ISSN 0895-4798
+
+    """
+    # This code block is copied from numpy.matrix_power().
+    A = np.asarray(A)
+    if len(A.shape) != 2 or A.shape[0] != A.shape[1]:
+        raise ValueError('input must be a square array')
+
+    # Get the number of rows and columns.
+    n, n = A.shape
+
+    # Triangularize the matrix if necessary,
+    # attempting to preserve dtype if possible.
+    if np.array_equal(A, np.triu(A)):
+        Z = None
+        T = A
+    else:
+        if np.isrealobj(A):
+            T, Z = schur(A)
+            if not np.array_equal(T, np.triu(T)):
+                T, Z = rsf2csf(T, Z)
+        else:
+            T, Z = schur(A, output='complex')
+
+    # Zeros on the diagonal of the triangular matrix are forbidden,
+    # because the inverse scaling and squaring cannot deal with it.
+    T_diag = np.diag(T)
+    if np.count_nonzero(T_diag) != n:
+        raise FractionalMatrixPowerError(
+                'cannot use inverse scaling and squaring to find '
+                'the fractional matrix power of a singular matrix')
+
+    # If the triangular matrix is real and has a negative
+    # entry on the diagonal, then force the matrix to be complex.
+    if np.isrealobj(T) and np.min(T_diag) < 0:
+        T = T.astype(complex)
+
+    # Get the fractional power of the triangular matrix,
+    # and de-triangularize it if necessary.
+    U = _remainder_matrix_power_triu(T, t)
+    if Z is not None:
+        ZH = np.conjugate(Z).T
+        return Z.dot(U).dot(ZH)
+    else:
+        return U
+
+
+def _fractional_matrix_power(A, p):
+    """
+    Compute the fractional power of a matrix.
+
+    See the fractional_matrix_power docstring in matfuncs.py for more info.
+
+    """
+    A = np.asarray(A)
+    if len(A.shape) != 2 or A.shape[0] != A.shape[1]:
+        raise ValueError('expected a square matrix')
+    if p == int(p):
+        return np.linalg.matrix_power(A, int(p))
+    # Compute singular values.
+    s = svdvals(A)
+    # Inverse scaling and squaring cannot deal with a singular matrix,
+    # because the process of repeatedly taking square roots
+    # would not converge to the identity matrix.
+    if s[-1]:
+        # Compute the condition number relative to matrix inversion,
+        # and use this to decide between floor(p) and ceil(p).
+        k2 = s[0] / s[-1]
+        p1 = p - np.floor(p)
+        p2 = p - np.ceil(p)
+        if p1 * k2 ** (1 - p1) <= -p2 * k2:
+            a = int(np.floor(p))
+            b = p1
+        else:
+            a = int(np.ceil(p))
+            b = p2
+        try:
+            R = _remainder_matrix_power(A, b)
+            Q = np.linalg.matrix_power(A, a)
+            return Q.dot(R)
+        except np.linalg.LinAlgError:
+            pass
+    # If p is negative then we are going to give up.
+    # If p is non-negative then we can fall back to generic funm.
+    if p < 0:
+        X = np.empty_like(A)
+        X.fill(np.nan)
+        return X
+    else:
+        p1 = p - np.floor(p)
+        a = int(np.floor(p))
+        b = p1
+        R, info = funm(A, lambda x: pow(x, b), disp=False)
+        Q = np.linalg.matrix_power(A, a)
+        return Q.dot(R)
+
+
+def _logm_triu(T):
+    """
+    Compute matrix logarithm of an upper triangular matrix.
+
+    The matrix logarithm is the inverse of
+    expm: expm(logm(`T`)) == `T`
+
+    Parameters
+    ----------
+    T : (N, N) array_like
+        Upper triangular matrix whose logarithm to evaluate
+
+    Returns
+    -------
+    logm : (N, N) ndarray
+        Matrix logarithm of `T`
+
+    References
+    ----------
+    .. [1] Awad H. Al-Mohy and Nicholas J. Higham (2012)
+           "Improved Inverse Scaling and Squaring Algorithms
+           for the Matrix Logarithm."
+           SIAM Journal on Scientific Computing, 34 (4). C152-C169.
+           ISSN 1095-7197
+
+    .. [2] Nicholas J. Higham (2008)
+           "Functions of Matrices: Theory and Computation"
+           ISBN 978-0-898716-46-7
+
+    .. [3] Nicholas J. Higham and Lijing lin (2011)
+           "A Schur-Pade Algorithm for Fractional Powers of a Matrix."
+           SIAM Journal on Matrix Analysis and Applications,
+           32 (3). pp. 1056-1078. ISSN 0895-4798
+
+    """
+    T = np.asarray(T)
+    if len(T.shape) != 2 or T.shape[0] != T.shape[1]:
+        raise ValueError('expected an upper triangular square matrix')
+    n, n = T.shape
+
+    # Construct T0 with the appropriate type,
+    # depending on the dtype and the spectrum of T.
+    T_diag = np.diag(T)
+    keep_it_real = np.isrealobj(T) and np.min(T_diag, initial=0.) >= 0
+    if keep_it_real:
+        T0 = T
+    else:
+        T0 = T.astype(complex)
+
+    # Define bounds given in Table (2.1).
+    theta = (None,
+            1.59e-5, 2.31e-3, 1.94e-2, 6.21e-2,
+            1.28e-1, 2.06e-1, 2.88e-1, 3.67e-1,
+            4.39e-1, 5.03e-1, 5.60e-1, 6.09e-1,
+            6.52e-1, 6.89e-1, 7.21e-1, 7.49e-1)
+
+    R, s, m = _inverse_squaring_helper(T0, theta)
+
+    # Evaluate U = 2**s r_m(T - I) using the partial fraction expansion (1.1).
+    # This requires the nodes and weights
+    # corresponding to degree-m Gauss-Legendre quadrature.
+    # These quadrature arrays need to be transformed from the [-1, 1] interval
+    # to the [0, 1] interval.
+    nodes, weights = scipy.special.p_roots(m)
+    nodes = nodes.real
+    if nodes.shape != (m,) or weights.shape != (m,):
+        raise Exception('internal error')
+    nodes = 0.5 + 0.5 * nodes
+    weights = 0.5 * weights
+    ident = np.identity(n)
+    U = np.zeros_like(R)
+    for alpha, beta in zip(weights, nodes):
+        U += solve_triangular(ident + beta*R, alpha*R)
+    U *= np.exp2(s)
+
+    # Skip this step if the principal branch
+    # does not exist at T0; this happens when a diagonal entry of T0
+    # is negative with imaginary part 0.
+    has_principal_branch = all(x.real > 0 or x.imag != 0 for x in np.diag(T0))
+    if has_principal_branch:
+
+        # Recompute diagonal entries of U.
+        U[np.diag_indices(n)] = np.log(np.diag(T0))
+
+        # Recompute superdiagonal entries of U.
+        # This indexing of this code should be renovated
+        # when newer np.diagonal() becomes available.
+        for i in range(n-1):
+            l1 = T0[i, i]
+            l2 = T0[i+1, i+1]
+            t12 = T0[i, i+1]
+            U[i, i+1] = _logm_superdiag_entry(l1, l2, t12)
+
+    # Return the logm of the upper triangular matrix.
+    if not np.array_equal(U, np.triu(U)):
+        raise Exception('U is not upper triangular')
+    return U
+
+
+def _logm_force_nonsingular_triangular_matrix(T, inplace=False):
+    # The input matrix should be upper triangular.
+    # The eps is ad hoc and is not meant to be machine precision.
+    tri_eps = 1e-20
+    abs_diag = np.absolute(np.diag(T))
+    if np.any(abs_diag == 0):
+        exact_singularity_msg = 'The logm input matrix is exactly singular.'
+        warnings.warn(exact_singularity_msg, LogmExactlySingularWarning, stacklevel=3)
+        if not inplace:
+            T = T.copy()
+        n = T.shape[0]
+        for i in range(n):
+            if not T[i, i]:
+                T[i, i] = tri_eps
+    elif np.any(abs_diag < tri_eps):
+        near_singularity_msg = 'The logm input matrix may be nearly singular.'
+        warnings.warn(near_singularity_msg, LogmNearlySingularWarning, stacklevel=3)
+    return T
+
+
+def _logm(A):
+    """
+    Compute the matrix logarithm.
+
+    See the logm docstring in matfuncs.py for more info.
+
+    Notes
+    -----
+    In this function we look at triangular matrices that are similar
+    to the input matrix. If any diagonal entry of such a triangular matrix
+    is exactly zero then the original matrix is singular.
+    The matrix logarithm does not exist for such matrices,
+    but in such cases we will pretend that the diagonal entries that are zero
+    are actually slightly positive by an ad-hoc amount, in the interest
+    of returning something more useful than NaN. This will cause a warning.
+
+    """
+    A = np.asarray(A)
+    if len(A.shape) != 2 or A.shape[0] != A.shape[1]:
+        raise ValueError('expected a square matrix')
+
+    # If the input matrix dtype is integer then copy to a float dtype matrix.
+    if issubclass(A.dtype.type, np.integer):
+        A = np.asarray(A, dtype=float)
+
+    keep_it_real = np.isrealobj(A)
+    try:
+        if np.array_equal(A, np.triu(A)):
+            A = _logm_force_nonsingular_triangular_matrix(A)
+            if np.min(np.diag(A), initial=0.) < 0:
+                A = A.astype(complex)
+            return _logm_triu(A)
+        else:
+            if keep_it_real:
+                T, Z = schur(A)
+                if not np.array_equal(T, np.triu(T)):
+                    T, Z = rsf2csf(T, Z)
+            else:
+                T, Z = schur(A, output='complex')
+            T = _logm_force_nonsingular_triangular_matrix(T, inplace=True)
+            U = _logm_triu(T)
+            ZH = np.conjugate(Z).T
+            return Z.dot(U).dot(ZH)
+    except (SqrtmError, LogmError):
+        X = np.empty_like(A)
+        X.fill(np.nan)
+        return X
diff --git a/.venv/lib/python3.12/site-packages/scipy/linalg/_matfuncs_sqrtm.py b/.venv/lib/python3.12/site-packages/scipy/linalg/_matfuncs_sqrtm.py
new file mode 100644
index 0000000000000000000000000000000000000000..529618e88f14fa7243738a115a6224d664b51c44
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/linalg/_matfuncs_sqrtm.py
@@ -0,0 +1,106 @@
+"""
+Matrix square root for general matrices and for upper triangular matrices.
+
+This module exists to avoid cyclic imports.
+
+"""
+__all__ = []
+
+import numpy as np
+
+# Local imports
+from .lapack import get_lapack_funcs
+
+class SqrtmError(np.linalg.LinAlgError):
+    pass
+
+from ._matfuncs_sqrtm_triu import within_block_loop  # noqa: E402
+
+
+def _sqrtm_triu(T, blocksize=64):
+    """
+    Matrix square root of an upper triangular matrix.
+
+    This is a helper function for `sqrtm` and `logm`.
+
+    Parameters
+    ----------
+    T : (N, N) array_like upper triangular
+        Matrix whose square root to evaluate
+    blocksize : int, optional
+        If the blocksize is not degenerate with respect to the
+        size of the input array, then use a blocked algorithm. (Default: 64)
+
+    Returns
+    -------
+    sqrtm : (N, N) ndarray
+        Value of the sqrt function at `T`
+
+    References
+    ----------
+    .. [1] Edvin Deadman, Nicholas J. Higham, Rui Ralha (2013)
+           "Blocked Schur Algorithms for Computing the Matrix Square Root,
+           Lecture Notes in Computer Science, 7782. pp. 171-182.
+
+    """
+    T_diag = np.diag(T)
+    keep_it_real = np.isrealobj(T) and np.min(T_diag, initial=0.) >= 0
+
+    # Cast to complex as necessary + ensure double precision
+    if not keep_it_real:
+        T = np.asarray(T, dtype=np.complex128, order="C")
+        T_diag = np.asarray(T_diag, dtype=np.complex128)
+    else:
+        T = np.asarray(T, dtype=np.float64, order="C")
+        T_diag = np.asarray(T_diag, dtype=np.float64)
+
+    R = np.diag(np.sqrt(T_diag))
+
+    trsyl = get_lapack_funcs('trsyl', (R,), ilp64="preferred")
+
+    # Compute the number of blocks to use; use at least one block.
+    n, n = T.shape
+    nblocks = max(n // blocksize, 1)
+
+    # Compute the smaller of the two sizes of blocks that
+    # we will actually use, and compute the number of large blocks.
+    bsmall, nlarge = divmod(n, nblocks)
+    blarge = bsmall + 1
+    nsmall = nblocks - nlarge
+    if nsmall * bsmall + nlarge * blarge != n:
+        raise Exception('internal inconsistency')
+
+    # Define the index range covered by each block.
+    start_stop_pairs = []
+    start = 0
+    for count, size in ((nsmall, bsmall), (nlarge, blarge)):
+        for i in range(count):
+            start_stop_pairs.append((start, start + size))
+            start += size
+
+    # Within-block interactions (Cythonized)
+    try:
+        within_block_loop(R, T, start_stop_pairs, nblocks)
+    except RuntimeError as e:
+        raise SqrtmError(*e.args) from e
+
+    # Between-block interactions (Cython would give no significant speedup)
+    for j in range(nblocks):
+        jstart, jstop = start_stop_pairs[j]
+        for i in range(j-1, -1, -1):
+            istart, istop = start_stop_pairs[i]
+            S = T[istart:istop, jstart:jstop]
+            if j - i > 1:
+                S = S - R[istart:istop, istop:jstart].dot(R[istop:jstart,
+                                                            jstart:jstop])
+
+            # Invoke LAPACK.
+            # For more details, see the solve_sylvester implementation
+            # and the fortran dtrsyl and ztrsyl docs.
+            Rii = R[istart:istop, istart:istop]
+            Rjj = R[jstart:jstop, jstart:jstop]
+            x, scale, info = trsyl(Rii, Rjj, S)
+            R[istart:istop, jstart:jstop] = x * scale
+
+    # Return the matrix square root.
+    return R
diff --git a/.venv/lib/python3.12/site-packages/scipy/linalg/_matfuncs_sqrtm_triu.cpython-312-x86_64-linux-gnu.so b/.venv/lib/python3.12/site-packages/scipy/linalg/_matfuncs_sqrtm_triu.cpython-312-x86_64-linux-gnu.so
new file mode 100644
index 0000000000000000000000000000000000000000..5ab4619a06b1c0d8e94502b1f72d2867f6a12230
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/linalg/_matfuncs_sqrtm_triu.cpython-312-x86_64-linux-gnu.so
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:ba3d3c38ad64f1a63a6b936cac7f2a1485712fb82742f12d2334bb4675569c39
+size 110600
diff --git a/.venv/lib/python3.12/site-packages/scipy/linalg/_misc.py b/.venv/lib/python3.12/site-packages/scipy/linalg/_misc.py
new file mode 100644
index 0000000000000000000000000000000000000000..cfd23f1ef1ea7066fab329e5f3139e1a5dcead30
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/linalg/_misc.py
@@ -0,0 +1,275 @@
+import numpy as np
+from numpy.linalg import LinAlgError
+from .blas import get_blas_funcs
+from .lapack import get_lapack_funcs
+from ._batched_linalg import _bandwidth
+from scipy._lib._util import _deprecate_dtypes
+
+__all__ = ['LinAlgError', 'LinAlgWarning', 'norm', 'bandwidth']
+
+
+class LinAlgWarning(RuntimeWarning):
+    """
+    The warning emitted when a linear algebra related operation is close
+    to fail conditions of the algorithm or loss of accuracy is expected.
+    """
+    pass
+
+
+def norm(a, ord=None, axis=None, keepdims=False, check_finite=True):
+    """
+    Matrix or vector norm.
+
+    This function is able to return one of eight different matrix norms,
+    or one of an infinite number of vector norms (described below), depending
+    on the value of the ``ord`` parameter. For tensors with rank different from
+    1 or 2, only `ord=None` is supported.
+
+    Parameters
+    ----------
+    a : array_like
+        Input array. If `axis` is None, `a` must be 1-D or 2-D, unless `ord`
+        is None. If both `axis` and `ord` are None, the 2-norm of
+        ``a.ravel`` will be returned.
+    ord : {int, inf, -inf, 'fro', 'nuc', None}, optional
+        Order of the norm (see table under ``Notes``). inf means NumPy's
+        `inf` object.
+    axis : {int, 2-tuple of ints, None}, optional
+        If `axis` is an integer, it specifies the axis of `a` along which to
+        compute the vector norms. If `axis` is a 2-tuple, it specifies the
+        axes that hold 2-D matrices, and the matrix norms of these matrices
+        are computed. If `axis` is None then either a vector norm (when `a`
+        is 1-D) or a matrix norm (when `a` is 2-D) is returned.
+    keepdims : bool, optional
+        If this is set to True, the axes which are normed over are left in the
+        result as dimensions with size one. With this option the result will
+        broadcast correctly against the original `a`.
+    check_finite : bool, optional
+        Whether to check that the input matrix contains only finite numbers.
+        Disabling may give a performance gain, but may result in problems
+        (crashes, non-termination) if the inputs do contain infinities or NaNs.
+
+    Returns
+    -------
+    n : float or ndarray
+        Norm of the matrix or vector(s).
+
+    Notes
+    -----
+    For values of ``ord <= 0``, the result is, strictly speaking, not a
+    mathematical 'norm', but it may still be useful for various numerical
+    purposes.
+
+    The following norms can be calculated:
+
+    =====  ============================  ==========================
+    ord    norm for matrices             norm for vectors
+    =====  ============================  ==========================
+    None   Frobenius norm                2-norm
+    'fro'  Frobenius norm                --
+    'nuc'  nuclear norm                  --
+    inf    max(sum(abs(a), axis=1))      max(abs(a))
+    -inf   min(sum(abs(a), axis=1))      min(abs(a))
+    0      --                            sum(a != 0)
+    1      max(sum(abs(a), axis=0))      as below
+    -1     min(sum(abs(a), axis=0))      as below
+    2      2-norm (largest sing. value)  as below
+    -2     smallest singular value       as below
+    other  --                            sum(abs(a)**ord)**(1./ord)
+    =====  ============================  ==========================
+
+    The Frobenius norm is given by [1]_:
+
+        :math:`||A||_F = [\\sum_{i,j} abs(a_{i,j})^2]^{1/2}`
+
+    The nuclear norm is the sum of the singular values.
+
+    Both the Frobenius and nuclear norm orders are only defined for
+    matrices.
+
+    References
+    ----------
+    .. [1] G. H. Golub and C. F. Van Loan, *Matrix Computations*,
+           Baltimore, MD, Johns Hopkins University Press, 1985, pg. 15
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy.linalg import norm
+    >>> a = np.arange(9) - 4.0
+    >>> a
+    array([-4., -3., -2., -1.,  0.,  1.,  2.,  3.,  4.])
+    >>> b = a.reshape((3, 3))
+    >>> b
+    array([[-4., -3., -2.],
+           [-1.,  0.,  1.],
+           [ 2.,  3.,  4.]])
+
+    >>> norm(a)
+    7.745966692414834
+    >>> norm(b)
+    7.745966692414834
+    >>> norm(b, 'fro')
+    7.745966692414834
+    >>> norm(a, np.inf)
+    4.0
+    >>> norm(b, np.inf)
+    9.0
+    >>> norm(a, -np.inf)
+    0.0
+    >>> norm(b, -np.inf)
+    2.0
+
+    >>> norm(a, 1)
+    20.0
+    >>> norm(b, 1)
+    7.0
+    >>> norm(a, -1)
+    -4.6566128774142013e-010
+    >>> norm(b, -1)
+    6.0
+    >>> norm(a, 2)
+    7.745966692414834
+    >>> norm(b, 2)
+    7.3484692283495345
+
+    >>> norm(a, -2)
+    0.0
+    >>> norm(b, -2)
+    1.8570331885190563e-016
+    >>> norm(a, 3)
+    5.8480354764257312
+    >>> norm(a, -3)
+    0.0
+
+    """
+    # Differs from numpy only in non-finite handling and the use of blas.
+    if check_finite:
+        a = np.asarray_chkfinite(a)
+    else:
+        a = np.asarray(a)
+    _deprecate_dtypes('norm', a)
+
+    if a.size and a.dtype.char in 'fdFD' and axis is None and not keepdims:
+
+        if ord in (None, 2) and (a.ndim == 1):
+            # use blas for fast and stable euclidean norm
+            nrm2 = get_blas_funcs('nrm2', dtype=a.dtype, ilp64='preferred')
+            return nrm2(a)
+
+        if a.ndim == 2:
+            # Use lapack for a couple fast matrix norms.
+            # For some reason the *lange frobenius norm is slow.
+            lange_args = None
+            # Make sure this works if the user uses the axis keywords
+            # to apply the norm to the transpose.
+            if ord == 1:
+                if np.isfortran(a):
+                    lange_args = '1', a
+                elif np.isfortran(a.T):
+                    lange_args = 'i', a.T
+            elif ord == np.inf:
+                if np.isfortran(a):
+                    lange_args = 'i', a
+                elif np.isfortran(a.T):
+                    lange_args = '1', a.T
+            if lange_args:
+                lange = get_lapack_funcs('lange', dtype=a.dtype, ilp64='preferred')
+                return lange(*lange_args)
+
+    # fall back to numpy in every other case
+    return np.linalg.norm(a, ord=ord, axis=axis, keepdims=keepdims)
+
+
+def _datacopied(arr, original):
+    """
+    Strict check for `arr` not sharing any data with `original`,
+    under the assumption that arr = asarray(original)
+
+    """
+    if arr is original:
+        return False
+    if not isinstance(original, np.ndarray) and hasattr(original, '__array__'):
+        return False
+    return arr.base is None
+
+
+def bandwidth(a):
+    """Return the lower and upper bandwidth of a numeric array.
+
+    Parameters
+    ----------
+    a : (..., N, M) array_like
+        Input array of at least 2 dimensions.
+
+    Returns
+    -------
+    lower : int | ndarray
+        Lower bandwidth. A scalar ``np.int64`` is assigned per
+        2D slice of the input array of last two dimensions. A value of 0
+        means the slice is upper triangular; ``N - 1`` means the lower part
+        is full. If the input array is 2D then an :class:`int` is returned.
+    upper : int | ndarray
+        Upper bandwidth. Same shape rules as `lower`. A value of 0
+        means the slice is lower triangular; ``M - 1`` means the upper
+        part is full. If the input array is 2D then a scalar :class:`int` is returned.
+
+    Raises
+    ------
+    TypeError
+        If the dtype of the array is not supported, in particular, for NumPy
+        float16, float128 and complex256 and other NumPy non-numeric types.
+
+    Notes
+    -----
+    This helper function simply runs over the array looking for the nonzero
+    entries whether there exists a banded structure in the array or not. Hence,
+    the performance depends on the density of nonzero entries and also
+    memory-layout. Fortran- or C- contiguous arrays are handled best and
+    otherwise suffers from extra random memory access cost.
+
+    The strategy is to look for only untested band elements in the upper
+    and lower triangular parts separately; depending on the memory layout
+    we scan row-wise or column-wise. Moreover, say we are scanning rows
+    and in the 6th row, 4th entry is nonzero then, on the succeeding rows
+    the horizontal search is done only up to that band entries since we know
+    that band is occupied. Therefore, a completely dense matrix scan cost is
+    in the order of n.
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy.linalg import bandwidth
+    >>> A = np.array([[3., 0., 0., 0., 0.],
+    ...               [0., 4., 0., 0., 0.],
+    ...               [0., 0., 5., 1., 0.],
+    ...               [8., 0., 0., 6., 2.],
+    ...               [0., 9., 0., 0., 7.]])
+    >>> bandwidth(A)
+    (3, 1)
+
+    """
+    a = np.asarray(a)
+    if a.ndim < 2:
+        raise ValueError('Input array must be at least 2D.')
+
+    if np.isdtype(a.dtype, (np.float16, np.longdouble, np.clongdouble)):
+        raise TypeError(f'Input array with {a.dtype} dtype is not supported.')
+
+    # Now that the problematic numeric types are tested, test for numeric or bool.
+    elif not np.isdtype(a.dtype, ("numeric", "bool")):
+        raise TypeError(f'Input array must have a numeric dtype, got {a.dtype}.')
+
+    # Empty array bandwidth is defined to be zero.
+    if a.size == 0:
+        if a.ndim == 2:
+            return (np.int64(0), np.int64(0))
+
+        batch_shape = a.shape[:-2]
+        return (
+            np.zeros(batch_shape, dtype=np.int64),
+            np.zeros(batch_shape, dtype=np.int64)
+        )
+
+    return _bandwidth(a)
+
diff --git a/.venv/lib/python3.12/site-packages/scipy/linalg/_procrustes.py b/.venv/lib/python3.12/site-packages/scipy/linalg/_procrustes.py
new file mode 100644
index 0000000000000000000000000000000000000000..e3584b85a0be556b1d43db88ba51447e9d62f1fc
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/linalg/_procrustes.py
@@ -0,0 +1,119 @@
+"""
+Solve the orthogonal Procrustes problem.
+
+"""
+
+from scipy._lib._util import _apply_over_batch
+from ._decomp_svd import svd
+from scipy._lib._array_api import array_namespace, xp_capabilities, _asarray, is_numpy
+
+
+__all__ = ['orthogonal_procrustes']
+
+
+@xp_capabilities(
+    jax_jit=False,
+    skip_backends=[("dask.array", "full_matrices=True is not supported by dask")],
+)
+@_apply_over_batch(('A', 2), ('B', 2))
+def orthogonal_procrustes(A, B, check_finite=True):
+    """
+    Compute the matrix solution of the orthogonal (or unitary) Procrustes problem.
+
+    Given matrices `A` and `B` of the same shape, find an orthogonal (or unitary in
+    the case of complex input) matrix `R` that most closely maps `A` to `B` using the
+    algorithm given in [1]_.
+
+    Parameters
+    ----------
+    A : (M, N) array_like
+        Matrix to be mapped.
+    B : (M, N) array_like
+        Target matrix.
+    check_finite : bool, optional
+        Whether to check that the input matrices contain only finite numbers.
+        Disabling may give a performance gain, but may result in problems
+        (crashes, non-termination) if the inputs do contain infinities or NaNs.
+
+    Returns
+    -------
+    R : (N, N) ndarray
+        The matrix solution of the orthogonal Procrustes problem.
+        Minimizes the Frobenius norm of ``(A @ R) - B``, subject to
+        ``R.conj().T @ R = I``.
+    scale : float
+        Sum of the singular values of ``A.conj().T @ B``.
+
+    Raises
+    ------
+    ValueError
+        If the input array shapes don't match or if check_finite is True and
+        the arrays contain Inf or NaN.
+
+    Notes
+    -----
+    Note that unlike higher level Procrustes analyses of spatial data, this
+    function only uses orthogonal transformations like rotations and
+    reflections, and it does not use scaling or translation.
+
+    References
+    ----------
+    .. [1] Peter H. Schonemann, "A generalized solution of the orthogonal
+           Procrustes problem", Psychometrica -- Vol. 31, No. 1, March, 1966.
+           :doi:`10.1007/BF02289451`
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy.linalg import orthogonal_procrustes
+    >>> A = np.array([[ 2,  0,  1], [-2,  0,  0]])
+
+    Flip the order of columns and check for the anti-diagonal mapping
+
+    >>> R, sca = orthogonal_procrustes(A, np.fliplr(A))
+    >>> R
+    array([[-5.34384992e-17,  0.00000000e+00,  1.00000000e+00],
+           [ 0.00000000e+00,  1.00000000e+00,  0.00000000e+00],
+           [ 1.00000000e+00,  0.00000000e+00, -7.85941422e-17]])
+    >>> sca
+    9.0
+
+    As an example of the unitary Procrustes problem, generate a
+    random complex matrix ``A``, a random unitary matrix ``Q``,
+    and their product ``B``.
+
+    >>> shape = (4, 4)
+    >>> rng = np.random.default_rng(589234981235)
+    >>> A = rng.random(shape) + rng.random(shape)*1j
+    >>> Q = rng.random(shape) + rng.random(shape)*1j
+    >>> Q, _ = np.linalg.qr(Q)
+    >>> B = A @ Q
+
+    `orthogonal_procrustes` recovers the unitary matrix ``Q``
+    from ``A`` and ``B``.
+
+    >>> R, _ = orthogonal_procrustes(A, B)
+    >>> np.allclose(R, Q)
+    True
+
+    """
+    xp = array_namespace(A, B)
+
+    A = _asarray(A, xp=xp, check_finite=check_finite, subok=True)
+    B = _asarray(B, xp=xp, check_finite=check_finite, subok=True)
+
+    if A.ndim != 2:
+        raise ValueError(f'expected ndim to be 2, but observed {A.ndim}')
+    if A.shape != B.shape:
+        raise ValueError(f'the shapes of A and B differ ({A.shape} vs {B.shape})')
+
+    # Be clever with transposes, with the intention to save memory.
+    # The conjugate has no effect for real inputs, but gives the correct solution
+    # for complex inputs.
+    if is_numpy(xp):
+        u, w, vt = svd((B.T @ xp.conj(A)).T)
+    else:
+        u, w, vt = xp.linalg.svd((B.T @ xp.conj(A)).T)
+    R = u @ vt
+    scale = xp.sum(w)
+    return R, scale
diff --git a/.venv/lib/python3.12/site-packages/scipy/linalg/_sketches.py b/.venv/lib/python3.12/site-packages/scipy/linalg/_sketches.py
new file mode 100644
index 0000000000000000000000000000000000000000..1270216182b88f98037b652247102b1ad905f705
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/linalg/_sketches.py
@@ -0,0 +1,200 @@
+""" Sketching-based Matrix Computations """
+
+# Author: Jordi Montes 
+# August 28, 2017
+
+import numpy as np
+
+from scipy._lib._util import (check_random_state, rng_integers,
+                              _transition_to_rng, _apply_over_batch)
+
+__all__ = ['clarkson_woodruff_transform']
+
+
+def cwt_matrix(n_rows, n_columns, rng=None):
+    r"""
+    Generate a matrix S which represents a Clarkson-Woodruff transform.
+
+    Given the desired size of matrix, the method returns a matrix S of size
+    (n_rows, n_columns) where each column has all the entries set to 0
+    except for one position which has been randomly set to +1 or -1 with
+    equal probability.
+
+    Parameters
+    ----------
+    n_rows : int
+        Number of rows of S
+    n_columns : int
+        Number of columns of S
+    rng : `numpy.random.Generator`, optional
+        Pseudorandom number generator state. When `rng` is None, a new
+        `numpy.random.Generator` is created using entropy from the
+        operating system. Types other than `numpy.random.Generator` are
+        passed to `numpy.random.default_rng` to instantiate a ``Generator``.
+
+    Returns
+    -------
+    S : (n_rows, n_columns) csc_array
+        The returned matrix has ``n_columns`` nonzero entries.
+
+    Notes
+    -----
+    Given a matrix A, with probability at least 9/10,
+    .. math:: \|SA\| = (1 \pm \epsilon)\|A\|
+    Where the error epsilon is related to the size of S.
+    """
+    # lazy import to prevent to prevent sparse dependency for whole module (gh-23420)
+    from scipy.sparse import csc_array
+    rng = check_random_state(rng)
+    rows = rng_integers(rng, 0, n_rows, n_columns)
+    cols = np.arange(n_columns+1)
+    signs = rng.choice([1, -1], n_columns)
+    S = csc_array((signs, rows, cols), shape=(n_rows, n_columns))
+    return S
+
+
+@_transition_to_rng("seed", position_num=2)
+def clarkson_woodruff_transform(input_matrix, sketch_size, rng=None):
+    r"""
+    Applies a Clarkson-Woodruff Transform/sketch to the input matrix.
+
+    Given an input_matrix ``A`` of size ``(n, d)``, compute a matrix ``A'`` of
+    size (sketch_size, d) so that
+
+    .. math:: \|Ax\| \approx \|A'x\|
+
+    with high probability via the Clarkson-Woodruff Transform, otherwise
+    known as the CountSketch matrix.
+
+    The documentation is written assuming array arguments are of specified
+    "core" shapes. However, array argument(s) of this function may have additional
+    "batch" dimensions prepended to the core shape. In this case, the array is treated
+    as a batch of lower-dimensional slices; see :ref:`linalg_batch` for details.
+
+    Parameters
+    ----------
+    input_matrix : array_like, shape (..., n, d)
+        Input matrix.
+    sketch_size : int
+        Number of rows for the sketch.
+    rng : `numpy.random.Generator`, optional
+        Pseudorandom number generator state. When `rng` is None, a new
+        `numpy.random.Generator` is created using entropy from the
+        operating system. Types other than `numpy.random.Generator` are
+        passed to `numpy.random.default_rng` to instantiate a ``Generator``.
+
+    Returns
+    -------
+    A' : array_like
+        Sketch of the input matrix ``A``, of size ``(sketch_size, d)``.
+
+    Notes
+    -----
+    To make the statement
+
+    .. math:: \|Ax\| \approx \|A'x\|
+
+    precise, observe the following result which is adapted from the
+    proof of Theorem 14 of [2]_ via Markov's Inequality. If we have
+    a sketch size ``sketch_size=k`` which is at least
+
+    .. math:: k \geq \frac{2}{\epsilon^2\delta}
+
+    Then for any fixed vector ``x``,
+
+    .. math:: \|Ax\| = (1\pm\epsilon)\|A'x\|
+
+    with probability at least one minus delta.
+
+    This implementation takes advantage of sparsity: computing
+    a sketch takes time proportional to ``A.nnz``. Data ``A`` which
+    is in ``scipy.sparse.csc_array`` format gives the quickest
+    computation time for sparse input.
+
+    >>> import numpy as np
+    >>> from scipy import linalg
+    >>> from scipy import sparse
+    >>> rng = np.random.default_rng()
+    >>> *shape, density, sketch_n_rows = 15000, 100, 0.01, 200
+    >>> A = sparse.random_array(shape, density=density, format='csc')
+    >>> B = sparse.random_array(shape, density=density, format='csr')
+    >>> C = sparse.random_array(shape, density=density, format='coo')
+    >>> D = rng.standard_normal(shape)
+    >>> SA = linalg.clarkson_woodruff_transform(A, sketch_n_rows) # fastest
+    >>> SB = linalg.clarkson_woodruff_transform(B, sketch_n_rows) # fast
+    >>> SC = linalg.clarkson_woodruff_transform(C, sketch_n_rows) # slower
+    >>> SD = linalg.clarkson_woodruff_transform(D, sketch_n_rows) # slowest
+
+    That said, this method does perform well on dense inputs, just slower
+    on a relative scale.
+
+    References
+    ----------
+    .. [1] Kenneth L. Clarkson and David P. Woodruff. Low rank approximation
+           and regression in input sparsity time. In STOC, 2013.
+    .. [2] David P. Woodruff. Sketching as a tool for numerical linear algebra.
+           In Foundations and Trends in Theoretical Computer Science, 2014.
+
+    Examples
+    --------
+    Create a big dense matrix ``A`` for the example:
+
+    >>> import numpy as np
+    >>> from scipy import linalg
+    >>> n_rows, n_columns  = 15000, 100
+    >>> rng = np.random.default_rng()
+    >>> A = rng.standard_normal((n_rows, n_columns))
+
+    Apply the transform to create a new matrix with 200 rows:
+
+    >>> sketch_n_rows = 200
+    >>> sketch = linalg.clarkson_woodruff_transform(A, sketch_n_rows, seed=rng)
+    >>> sketch.shape
+    (200, 100)
+
+    Now with high probability, the true norm is close to the sketched norm
+    in absolute value.
+
+    >>> linalg.norm(A)
+    1224.2812927123198
+    >>> linalg.norm(sketch)
+    1226.518328407333
+
+    Similarly, applying our sketch preserves the solution to a linear
+    regression of :math:`\min \|Ax - b\|`.
+
+    >>> b = rng.standard_normal(n_rows)
+    >>> x = linalg.lstsq(A, b)[0]
+    >>> Ab = np.hstack((A, b.reshape(-1, 1)))
+    >>> SAb = linalg.clarkson_woodruff_transform(Ab, sketch_n_rows, seed=rng)
+    >>> SA, Sb = SAb[:, :-1], SAb[:, -1]
+    >>> x_sketched = linalg.lstsq(SA, Sb)[0]
+
+    As with the matrix norm example, ``linalg.norm(A @ x - b)`` is close
+    to ``linalg.norm(A @ x_sketched - b)`` with high probability.
+
+    >>> linalg.norm(A @ x - b)
+    122.83242365433877
+    >>> linalg.norm(A @ x_sketched - b)
+    166.58473879945151
+
+    """
+    # lazy import to prevent to prevent sparse dependency for whole module (gh-23420)
+    from scipy.sparse import issparse
+    if issparse(input_matrix) and input_matrix.ndim > 2:
+        message = "Batch support for sparse arrays is not available."
+        raise NotImplementedError(message)
+
+    S = cwt_matrix(sketch_size, input_matrix.shape[-2], rng=rng)
+    if input_matrix.ndim <= 2:
+        # transposes are cheap and ensure output class matches input_matrix
+        return (input_matrix.T @ S.T).T
+
+    # Despite argument order (required by decorator), this is  S @ input_matrix
+    # Can avoid _batch_dot when gh-22153 is resolved.
+    return _batch_dot(input_matrix, S)
+
+
+@_apply_over_batch(('input_matrix', 2))
+def _batch_dot(input_matrix, S):
+    return S @ input_matrix
diff --git a/.venv/lib/python3.12/site-packages/scipy/linalg/_solve_toeplitz.cpython-312-x86_64-linux-gnu.so b/.venv/lib/python3.12/site-packages/scipy/linalg/_solve_toeplitz.cpython-312-x86_64-linux-gnu.so
new file mode 100644
index 0000000000000000000000000000000000000000..9ac1b9484de65d8af1bcae09bb10c6ac95b8de85
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/linalg/_solve_toeplitz.cpython-312-x86_64-linux-gnu.so
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:0fd9f45797544caea1341c035e7c7526731ad5f30b5208cfa39214feda3bd541
+size 127536
diff --git a/.venv/lib/python3.12/site-packages/scipy/linalg/_solvers.py b/.venv/lib/python3.12/site-packages/scipy/linalg/_solvers.py
new file mode 100644
index 0000000000000000000000000000000000000000..297d19e1a9cc4323f17a53bdd3b9e293eb310416
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/linalg/_solvers.py
@@ -0,0 +1,880 @@
+"""Matrix equation solver routines"""
+# Author: Jeffrey Armstrong 
+# February 24, 2012
+
+# Modified: Chad Fulton 
+# June 19, 2014
+
+# Modified: Ilhan Polat 
+# September 13, 2016
+
+import warnings
+import numpy as np
+from numpy.linalg import inv, LinAlgError, norm, cond, svd
+
+from scipy._lib._util import _apply_over_batch
+from ._basic import solve, solve_triangular, matrix_balance
+from .lapack import get_lapack_funcs
+from ._decomp_schur import schur
+from ._decomp_lu import lu
+from ._decomp_qr import qr
+from ._decomp_qz import ordqz
+from ._decomp import _asarray_validated
+from ._special_matrices import block_diag
+
+__all__ = ['solve_sylvester',
+           'solve_continuous_lyapunov', 'solve_discrete_lyapunov',
+           'solve_lyapunov',
+           'solve_continuous_are', 'solve_discrete_are']
+
+
+@_apply_over_batch(('a', 2), ('b', 2), ('q', 2))
+def solve_sylvester(a, b, q):
+    """
+    Computes a solution (X) to the Sylvester equation :math:`AX + XB = Q`.
+
+    Parameters
+    ----------
+    a : (M, M) array_like
+        Leading matrix of the Sylvester equation
+    b : (N, N) array_like
+        Trailing matrix of the Sylvester equation
+    q : (M, N) array_like
+        Right-hand side
+
+    Returns
+    -------
+    x : (M, N) ndarray
+        The solution to the Sylvester equation.
+
+    Raises
+    ------
+    LinAlgError
+        If solution was not found
+
+    Notes
+    -----
+    Computes a solution to the Sylvester matrix equation via the Bartels-
+    Stewart algorithm. The A and B matrices first undergo Schur
+    decompositions. The resulting matrices are used to construct an
+    alternative Sylvester equation (``RY + YS^T = F``) where the R and S
+    matrices are in quasi-triangular form (or, when R, S or F are complex,
+    triangular form). The simplified equation is then solved using
+    ``*TRSYL`` from LAPACK directly.
+
+    .. versionadded:: 0.11.0
+
+    Examples
+    --------
+    Given `a`, `b`, and `q` solve for `x`:
+
+    >>> import numpy as np
+    >>> from scipy import linalg
+    >>> a = np.array([[-3, -2, 0], [-1, -1, 3], [3, -5, -1]])
+    >>> b = np.array([[1]])
+    >>> q = np.array([[1],[2],[3]])
+    >>> x = linalg.solve_sylvester(a, b, q)
+    >>> x
+    array([[ 0.0625],
+           [-0.5625],
+           [ 0.6875]])
+    >>> np.allclose(a.dot(x) + x.dot(b), q)
+    True
+
+    """
+    # Accommodate empty a
+    if a.size == 0 or b.size == 0:
+        tdict = {'s': np.float32, 'd': np.float64,
+                 'c': np.complex64, 'z': np.complex128}
+        func, = get_lapack_funcs(('trsyl',), arrays=(a, b, q))
+        return np.empty(q.shape, dtype=tdict[func.typecode])
+
+    # Compute the Schur decomposition form of a
+    r, u = schur(a, output='real')
+
+    # Compute the Schur decomposition of b
+    s, v = schur(b.conj().transpose(), output='real')
+
+    # Construct f = u'*q*v
+    f = np.dot(np.dot(u.conj().transpose(), q), v)
+
+    # Call the Sylvester equation solver
+    trsyl, = get_lapack_funcs(('trsyl',), (r, s, f))
+    if trsyl is None:
+        raise RuntimeError('LAPACK implementation does not contain a proper '
+                           'Sylvester equation solver (TRSYL)')
+    y, scale, info = trsyl(r, s, f, tranb='C')
+
+    y = scale*y
+
+    if info < 0:
+        raise LinAlgError(f"Illegal value encountered in the {-info} term")
+
+    return np.dot(np.dot(u, y), v.conj().transpose())
+
+
+@_apply_over_batch(('a', 2), ('q', 2))
+def solve_continuous_lyapunov(a, q):
+    """
+    Solves the continuous Lyapunov equation :math:`AX + XA^H = Q`.
+
+    Uses the Bartels-Stewart algorithm to find :math:`X`.
+
+    Parameters
+    ----------
+    a : array_like
+        A square matrix
+
+    q : array_like
+        Right-hand side square matrix
+
+    Returns
+    -------
+    x : ndarray
+        Solution to the continuous Lyapunov equation
+
+    See Also
+    --------
+    solve_discrete_lyapunov : computes the solution to the discrete-time
+        Lyapunov equation
+    solve_sylvester : computes the solution to the Sylvester equation
+
+    Notes
+    -----
+    The continuous Lyapunov equation is a special form of the Sylvester
+    equation, hence this solver relies on LAPACK routine ?TRSYL.
+
+    .. versionadded:: 0.11.0
+
+    Examples
+    --------
+    Given `a` and `q` solve for `x`:
+
+    >>> import numpy as np
+    >>> from scipy import linalg
+    >>> a = np.array([[-3, -2, 0], [-1, -1, 0], [0, -5, -1]])
+    >>> b = np.array([2, 4, -1])
+    >>> q = np.eye(3)
+    >>> x = linalg.solve_continuous_lyapunov(a, q)
+    >>> x
+    array([[ -0.75  ,   0.875 ,  -3.75  ],
+           [  0.875 ,  -1.375 ,   5.3125],
+           [ -3.75  ,   5.3125, -27.0625]])
+    >>> np.allclose(a.dot(x) + x.dot(a.T), q)
+    True
+    """
+
+    a = np.atleast_2d(_asarray_validated(a, check_finite=True))
+    q = np.atleast_2d(_asarray_validated(q, check_finite=True))
+
+    r_or_c = float
+
+    for ind, _ in enumerate((a, q)):
+        if np.iscomplexobj(_):
+            r_or_c = complex
+
+        if not np.equal(*_.shape):
+            raise ValueError(f"Matrix {'aq'[ind]} should be square.")
+
+    # Shape consistency check
+    if a.shape != q.shape:
+        raise ValueError("Matrix a and q should have the same shape.")
+
+    # Accommodate empty array
+    if a.size == 0:
+        tdict = {'s': np.float32, 'd': np.float64,
+                 'c': np.complex64, 'z': np.complex128}
+        func, = get_lapack_funcs(('trsyl',), arrays=(a, q))
+        return np.empty(a.shape, dtype=tdict[func.typecode])
+
+    # Compute the Schur decomposition form of a
+    r, u = schur(a, output='real')
+
+    # Construct f = u'*q*u
+    f = u.conj().T.dot(q.dot(u))
+
+    # Call the Sylvester equation solver
+    trsyl = get_lapack_funcs('trsyl', (r, f))
+
+    dtype_string = 'T' if r_or_c is float else 'C'
+    y, scale, info = trsyl(r, r, f, tranb=dtype_string)
+
+    if info < 0:
+        raise ValueError('?TRSYL exited with the internal error '
+                         f'"illegal value in argument number {-info}.". See '
+                         'LAPACK documentation for the ?TRSYL error codes.')
+    elif info == 1:
+        warnings.warn('Input "a" has an eigenvalue pair whose sum is '
+                      'very close to or exactly zero. The solution is '
+                      'obtained via perturbing the coefficients.',
+                      RuntimeWarning, stacklevel=2)
+    y *= scale
+
+    return u.dot(y).dot(u.conj().T)
+
+
+# For backwards compatibility, keep the old name
+solve_lyapunov = solve_continuous_lyapunov
+
+
+def _solve_discrete_lyapunov_direct(a, q):
+    """
+    Solves the discrete Lyapunov equation directly.
+
+    This function is called by the `solve_discrete_lyapunov` function with
+    `method=direct`. It is not supposed to be called directly.
+    """
+
+    lhs = np.kron(a, a.conj())
+    lhs = np.eye(lhs.shape[0]) - lhs
+    x = solve(lhs, q.flatten())
+
+    return np.reshape(x, q.shape)
+
+
+def _solve_discrete_lyapunov_bilinear(a, q):
+    """
+    Solves the discrete Lyapunov equation using a bilinear transformation.
+
+    This function is called by the `solve_discrete_lyapunov` function with
+    `method=bilinear`. It is not supposed to be called directly.
+    """
+    eye = np.eye(a.shape[0])
+    aH = a.conj().transpose()
+    aHI_inv = inv(aH + eye)
+    b = np.dot(aH - eye, aHI_inv)
+    c = 2*np.dot(np.dot(inv(a + eye), q), aHI_inv)
+    return solve_lyapunov(b.conj().transpose(), -c)
+
+
+@_apply_over_batch(('a', 2), ('q', 2))
+def solve_discrete_lyapunov(a, q, method=None):
+    """
+    Solves the discrete Lyapunov equation :math:`AXA^H - X + Q = 0`.
+
+    Parameters
+    ----------
+    a, q : (M, M) array_like
+        Square matrices corresponding to A and Q in the equation
+        above respectively. Must have the same shape.
+
+    method : {'direct', 'bilinear'}, optional
+        Type of solver.
+
+        If not given, chosen to be ``direct`` if ``M`` is less than 10 and
+        ``bilinear`` otherwise.
+
+    Returns
+    -------
+    x : ndarray
+        Solution to the discrete Lyapunov equation
+
+    See Also
+    --------
+    solve_continuous_lyapunov : computes the solution to the continuous-time
+        Lyapunov equation
+
+    Notes
+    -----
+    This section describes the available solvers that can be selected by the
+    'method' parameter. The default method is *direct* if ``M`` is less than 10
+    and ``bilinear`` otherwise.
+
+    Method *direct* uses a direct analytical solution to the discrete Lyapunov
+    equation. The algorithm is given in, for example, [1]_. However, it requires
+    the linear solution of a system with dimension :math:`M^2` so that
+    performance degrades rapidly for even moderately sized matrices.
+
+    Method *bilinear* uses a bilinear transformation to convert the discrete
+    Lyapunov equation to a continuous Lyapunov equation :math:`(BX+XB'=-C)`
+    where :math:`B=(A-I)(A+I)^{-1}` and
+    :math:`C=2(A' + I)^{-1} Q (A + I)^{-1}`. The continuous equation can be
+    efficiently solved since it is a special case of a Sylvester equation.
+    The transformation algorithm is from Popov (1964) as described in [2]_.
+
+    .. versionadded:: 0.11.0
+
+    References
+    ----------
+    .. [1] "Lyapunov equation", Wikipedia,
+       https://en.wikipedia.org/wiki/Lyapunov_equation#Discrete_time
+    .. [2] Gajic, Z., and M.T.J. Qureshi. 2008.
+       Lyapunov Matrix Equation in System Stability and Control.
+       Dover Books on Engineering Series. Dover Publications.
+
+    Examples
+    --------
+    Given `a` and `q` solve for `x`:
+
+    >>> import numpy as np
+    >>> from scipy import linalg
+    >>> a = np.array([[0.2, 0.5],[0.7, -0.9]])
+    >>> q = np.eye(2)
+    >>> x = linalg.solve_discrete_lyapunov(a, q)
+    >>> x
+    array([[ 0.70872893,  1.43518822],
+           [ 1.43518822, -2.4266315 ]])
+    >>> np.allclose(a.dot(x).dot(a.T)-x, -q)
+    True
+
+    """
+    a = np.asarray(a)
+    q = np.asarray(q)
+    if method is None:
+        # Select automatically based on size of matrices
+        if a.shape[0] >= 10:
+            method = 'bilinear'
+        else:
+            method = 'direct'
+
+    meth = method.lower()
+
+    if meth == 'direct':
+        x = _solve_discrete_lyapunov_direct(a, q)
+    elif meth == 'bilinear':
+        x = _solve_discrete_lyapunov_bilinear(a, q)
+    else:
+        raise ValueError(f'Unknown solver {method}')
+
+    return x
+
+
+def solve_continuous_are(a, b, q, r, e=None, s=None, balanced=True):
+    r"""
+    Solves the continuous-time algebraic Riccati equation (CARE).
+
+    The CARE is defined as
+
+    .. math::
+
+          X A + A^H X - X B R^{-1} B^H X + Q = 0
+
+    The limitations for a solution to exist are :
+
+    * All eigenvalues of :math:`A` on the right half plane, should be
+      controllable.
+
+    * The associated hamiltonian pencil (See Notes), should have
+      eigenvalues sufficiently away from the imaginary axis.
+
+    Moreover, if ``e`` or ``s`` is not precisely ``None``, then the
+    generalized version of CARE
+
+    .. math::
+
+          E^HXA + A^HXE - (E^HXB + S) R^{-1} (B^HXE + S^H) + Q = 0
+
+    is solved. When omitted, ``e`` is assumed to be the identity and ``s``
+    is assumed to be the zero matrix with sizes compatible with ``a`` and
+    ``b``, respectively.
+
+    The documentation is written assuming array arguments are of specified
+    "core" shapes. However, array argument(s) of this function may have additional
+    "batch" dimensions prepended to the core shape. In this case, the array is treated
+    as a batch of lower-dimensional slices; see :ref:`linalg_batch` for details.
+
+    Parameters
+    ----------
+    a : (M, M) array_like
+        Square matrix
+    b : (M, N) array_like
+        Input
+    q : (M, M) array_like
+        Input
+    r : (N, N) array_like
+        Nonsingular square matrix
+    e : (M, M) array_like, optional
+        Nonsingular square matrix
+    s : (M, N) array_like, optional
+        Input
+    balanced : bool, optional
+        The boolean that indicates whether a balancing step is performed
+        on the data. The default is set to True.
+
+    Returns
+    -------
+    x : (M, M) ndarray
+        Solution to the continuous-time algebraic Riccati equation.
+
+    Raises
+    ------
+    LinAlgError
+        For cases where the stable subspace of the pencil could not be
+        isolated. See Notes section and the references for details.
+
+    See Also
+    --------
+    solve_discrete_are : Solves the discrete-time algebraic Riccati equation
+
+    Notes
+    -----
+    The equation is solved by forming the extended hamiltonian matrix pencil,
+    as described in [1]_, :math:`H - \lambda J` given by the block matrices ::
+
+        [ A    0    B ]             [ E   0    0 ]
+        [-Q  -A^H  -S ] - \lambda * [ 0  E^H   0 ]
+        [ S^H B^H   R ]             [ 0   0    0 ]
+
+    and using a QZ decomposition method.
+
+    In this algorithm, the fail conditions are linked to the symmetry
+    of the product :math:`U_2 U_1^{-1}` and condition number of
+    :math:`U_1`. Here, :math:`U` is the 2m-by-m matrix that holds the
+    eigenvectors spanning the stable subspace with 2-m rows and partitioned
+    into two m-row matrices. See [1]_ and [2]_ for more details.
+
+    In order to improve the QZ decomposition accuracy, the pencil goes
+    through a balancing step where the sum of absolute values of
+    :math:`H` and :math:`J` entries (after removing the diagonal entries of
+    the sum) is balanced following the recipe given in [3]_.
+
+    .. versionadded:: 0.11.0
+
+    References
+    ----------
+    .. [1]  P. van Dooren , "A Generalized Eigenvalue Approach For Solving
+       Riccati Equations.", SIAM Journal on Scientific and Statistical
+       Computing, Vol.2(2), :doi:`10.1137/0902010`
+
+    .. [2] A.J. Laub, "A Schur Method for Solving Algebraic Riccati
+       Equations.", Massachusetts Institute of Technology. Laboratory for
+       Information and Decision Systems. LIDS-R ; 859. Available online :
+       http://hdl.handle.net/1721.1/1301
+
+    .. [3] P. Benner, "Symplectic Balancing of Hamiltonian Matrices", 2001,
+       SIAM J. Sci. Comput., 2001, Vol.22(5), :doi:`10.1137/S1064827500367993`
+
+    Examples
+    --------
+    Given `a`, `b`, `q`, and `r` solve for `x`:
+
+    >>> import numpy as np
+    >>> from scipy import linalg
+    >>> a = np.array([[4, 3], [-4.5, -3.5]])
+    >>> b = np.array([[1], [-1]])
+    >>> q = np.array([[9, 6], [6, 4.]])
+    >>> r = 1
+    >>> x = linalg.solve_continuous_are(a, b, q, r)
+    >>> x
+    array([[ 21.72792206,  14.48528137],
+           [ 14.48528137,   9.65685425]])
+    >>> np.allclose(a.T.dot(x) + x.dot(a)-x.dot(b).dot(b.T).dot(x), -q)
+    True
+
+    """
+    # ensure that all arguments are present when using `_apply_over_batch` (gh-23336)
+    return _solve_continuous_are(a, b, q, r, e, s, balanced)
+
+
+@_apply_over_batch(('a', 2), ('b', 2), ('q', 2), ('r', 2), ('e', 2), ('s', 2))
+def _solve_continuous_are(a, b, q, r, e, s, balanced):
+    # Validate input arguments
+    a, b, q, r, e, s, m, n, r_or_c, gen_are = _are_validate_args(
+                                                     a, b, q, r, e, s, 'care')
+
+    H = np.empty((2*m+n, 2*m+n), dtype=r_or_c)
+    H[:m, :m] = a
+    H[:m, m:2*m] = 0.
+    H[:m, 2*m:] = b
+    H[m:2*m, :m] = -q
+    H[m:2*m, m:2*m] = -a.conj().T
+    H[m:2*m, 2*m:] = 0. if s is None else -s
+    H[2*m:, :m] = 0. if s is None else s.conj().T
+    H[2*m:, m:2*m] = b.conj().T
+    H[2*m:, 2*m:] = r
+
+    if gen_are and e is not None:
+        J = block_diag(e, e.conj().T, np.zeros_like(r, dtype=r_or_c))
+    else:
+        J = block_diag(np.eye(2*m), np.zeros_like(r, dtype=r_or_c))
+
+    if balanced:
+        # xGEBAL does not remove the diagonals before scaling. Also
+        # to avoid destroying the Symplectic structure, we follow Ref.3
+        M = np.abs(H) + np.abs(J)
+        np.fill_diagonal(M, 0.)
+        _, (sca, _) = matrix_balance(M, separate=1, permute=0)
+        # do we need to bother?
+        if not np.allclose(sca, np.ones_like(sca)):
+            # Now impose diag(D,inv(D)) from Benner where D is
+            # square root of s_i/s_(n+i) for i=0,....
+            sca = np.log2(sca)
+            # NOTE: Py3 uses "Bankers Rounding: round to the nearest even" !!
+            s = np.round((sca[m:2*m] - sca[:m])/2)
+            sca = 2 ** np.r_[s, -s, sca[2*m:]]
+            # Elementwise multiplication via broadcasting.
+            elwisescale = sca[:, None] * np.reciprocal(sca)
+            H *= elwisescale
+            J *= elwisescale
+
+    # Deflate the pencil to 2m x 2m ala Ref.1, eq.(55)
+    q, r = qr(H[:, -n:])
+    H = q[:, n:].conj().T.dot(H[:, :2*m])
+    J = q[:2*m, n:].conj().T.dot(J[:2*m, :2*m])
+
+    # Decide on which output type is needed for QZ
+    out_str = 'real' if r_or_c is float else 'complex'
+
+    _, _, _, _, _, u = ordqz(H, J, sort='lhp', overwrite_a=True,
+                             overwrite_b=True, check_finite=False,
+                             output=out_str)
+
+    # Get the relevant parts of the stable subspace basis
+    if e is not None:
+        u, _ = qr(np.vstack((e.dot(u[:m, :m]), u[m:, :m])))
+    u00 = u[:m, :m]
+    u10 = u[m:, :m]
+
+    # Solve via back-substituion after checking the condition of u00
+    up, ul, uu = lu(u00)
+    if 1/cond(uu) < np.spacing(1.):
+        raise LinAlgError('Failed to find a finite solution.')
+
+    # Exploit the triangular structure
+    x = solve_triangular(ul.conj().T,
+                         solve_triangular(uu.conj().T,
+                                          u10.conj().T,
+                                          lower=True),
+                         unit_diagonal=True,
+                         ).conj().T.dot(up.conj().T)
+    if balanced:
+        x *= sca[:m, None] * sca[:m]
+
+    # Check the deviation from symmetry for lack of success
+    # See proof of Thm.5 item 3 in [2]
+    u_sym = u00.conj().T.dot(u10)
+    n_u_sym = norm(u_sym, 1)
+    u_sym = u_sym - u_sym.conj().T
+    sym_threshold = np.max([np.spacing(1000.), 0.1*n_u_sym])
+
+    if norm(u_sym, 1) > sym_threshold:
+        raise LinAlgError('The associated Hamiltonian pencil has eigenvalues '
+                          'too close to the imaginary axis')
+
+    return (x + x.conj().T)/2
+
+
+def solve_discrete_are(a, b, q, r, e=None, s=None, balanced=True):
+    r"""
+    Solves the discrete-time algebraic Riccati equation (DARE).
+
+    The DARE is defined as
+
+    .. math::
+
+          A^HXA - X - (A^HXB) (R + B^HXB)^{-1} (B^HXA) + Q = 0
+
+    The limitations for a solution to exist are :
+
+    * All eigenvalues of :math:`A` outside the unit disc, should be
+      controllable.
+
+    * The associated symplectic pencil (See Notes), should have
+      eigenvalues sufficiently away from the unit circle.
+
+    Moreover, if ``e`` and ``s`` are not both precisely ``None``, then the
+    generalized version of DARE
+
+    .. math::
+
+          A^HXA - E^HXE - (A^HXB+S) (R+B^HXB)^{-1} (B^HXA+S^H) + Q = 0
+
+    is solved. When omitted, ``e`` is assumed to be the identity and ``s``
+    is assumed to be the zero matrix.
+
+    The documentation is written assuming array arguments are of specified
+    "core" shapes. However, array argument(s) of this function may have additional
+    "batch" dimensions prepended to the core shape. In this case, the array is treated
+    as a batch of lower-dimensional slices; see :ref:`linalg_batch` for details.
+
+    Parameters
+    ----------
+    a : (M, M) array_like
+        Square matrix
+    b : (M, N) array_like
+        Input
+    q : (M, M) array_like
+        Input
+    r : (N, N) array_like
+        Square matrix
+    e : (M, M) array_like, optional
+        Nonsingular square matrix
+    s : (M, N) array_like, optional
+        Input
+    balanced : bool
+        The boolean that indicates whether a balancing step is performed
+        on the data. The default is set to True.
+
+    Returns
+    -------
+    x : (M, M) ndarray
+        Solution to the discrete algebraic Riccati equation.
+
+    Raises
+    ------
+    LinAlgError
+        For cases where the stable subspace of the pencil could not be
+        isolated. See Notes section and the references for details.
+
+    See Also
+    --------
+    solve_continuous_are : Solves the continuous algebraic Riccati equation
+
+    Notes
+    -----
+    The equation is solved by forming the extended symplectic matrix pencil,
+    as described in [1]_, :math:`H - \lambda J` given by the block matrices ::
+
+           [  A   0   B ]             [ E   0   B ]
+           [ -Q  E^H -S ] - \lambda * [ 0  A^H  0 ]
+           [ S^H  0   R ]             [ 0 -B^H  0 ]
+
+    and using a QZ decomposition method.
+
+    In this algorithm, the fail conditions are linked to the symmetry
+    of the product :math:`U_2 U_1^{-1}` and condition number of
+    :math:`U_1`. Here, :math:`U` is the 2m-by-m matrix that holds the
+    eigenvectors spanning the stable subspace with 2-m rows and partitioned
+    into two m-row matrices. See [1]_ and [2]_ for more details.
+
+    In order to improve the QZ decomposition accuracy, the pencil goes
+    through a balancing step where the sum of absolute values of
+    :math:`H` and :math:`J` rows/cols (after removing the diagonal entries)
+    is balanced following the recipe given in [3]_. If the data has small
+    numerical noise, balancing may amplify their effects and some clean up
+    is required.
+
+    .. versionadded:: 0.11.0
+
+    References
+    ----------
+    .. [1]  P. van Dooren , "A Generalized Eigenvalue Approach For Solving
+       Riccati Equations.", SIAM Journal on Scientific and Statistical
+       Computing, Vol.2(2), :doi:`10.1137/0902010`
+
+    .. [2] A.J. Laub, "A Schur Method for Solving Algebraic Riccati
+       Equations.", Massachusetts Institute of Technology. Laboratory for
+       Information and Decision Systems. LIDS-R ; 859. Available online :
+       http://hdl.handle.net/1721.1/1301
+
+    .. [3] P. Benner, "Symplectic Balancing of Hamiltonian Matrices", 2001,
+       SIAM J. Sci. Comput., 2001, Vol.22(5), :doi:`10.1137/S1064827500367993`
+
+    Examples
+    --------
+    Given `a`, `b`, `q`, and `r` solve for `x`:
+
+    >>> import numpy as np
+    >>> from scipy import linalg as la
+    >>> a = np.array([[0, 1], [0, -1]])
+    >>> b = np.array([[1, 0], [2, 1]])
+    >>> q = np.array([[-4, -4], [-4, 7]])
+    >>> r = np.array([[9, 3], [3, 1]])
+    >>> x = la.solve_discrete_are(a, b, q, r)
+    >>> x
+    array([[-4., -4.],
+           [-4.,  7.]])
+    >>> R = la.solve(r + b.T.dot(x).dot(b), b.T.dot(x).dot(a))
+    >>> np.allclose(a.T.dot(x).dot(a) - x - a.T.dot(x).dot(b).dot(R), -q)
+    True
+
+    """
+    # ensure that all arguments are present when using `_apply_over_batch` (gh-23336)
+    return _solve_discrete_are(a, b, q, r, e, s, balanced)
+
+
+@_apply_over_batch(('a', 2), ('b', 2), ('q', 2), ('r', 2), ('e', 2), ('s', 2))
+def _solve_discrete_are(a, b, q, r, e, s, balanced):
+    # Validate input arguments
+    a, b, q, r, e, s, m, n, r_or_c, gen_are = _are_validate_args(
+                                                     a, b, q, r, e, s, 'dare')
+
+    # Form the matrix pencil
+    H = np.zeros((2*m+n, 2*m+n), dtype=r_or_c)
+    H[:m, :m] = a
+    H[:m, 2*m:] = b
+    H[m:2*m, :m] = -q
+    H[m:2*m, m:2*m] = np.eye(m) if e is None else e.conj().T
+    H[m:2*m, 2*m:] = 0. if s is None else -s
+    H[2*m:, :m] = 0. if s is None else s.conj().T
+    H[2*m:, 2*m:] = r
+
+    J = np.zeros_like(H, dtype=r_or_c)
+    J[:m, :m] = np.eye(m) if e is None else e
+    J[m:2*m, m:2*m] = a.conj().T
+    J[2*m:, m:2*m] = -b.conj().T
+
+    if balanced:
+        # xGEBAL does not remove the diagonals before scaling. Also
+        # to avoid destroying the Symplectic structure, we follow Ref.3
+        M = np.abs(H) + np.abs(J)
+        np.fill_diagonal(M, 0.)
+        _, (sca, _) = matrix_balance(M, separate=1, permute=0)
+        # do we need to bother?
+        if not np.allclose(sca, np.ones_like(sca)):
+            # Now impose diag(D,inv(D)) from Benner where D is
+            # square root of s_i/s_(n+i) for i=0,....
+            sca = np.log2(sca)
+            # NOTE: Py3 uses "Bankers Rounding: round to the nearest even" !!
+            s = np.round((sca[m:2*m] - sca[:m])/2)
+            sca = 2 ** np.r_[s, -s, sca[2*m:]]
+            # Elementwise multiplication via broadcasting.
+            elwisescale = sca[:, None] * np.reciprocal(sca)
+            H *= elwisescale
+            J *= elwisescale
+
+    # Deflate the pencil by the R column ala Ref.1
+    q_of_qr, _ = qr(H[:, -n:])
+    H = q_of_qr[:, n:].conj().T.dot(H[:, :2*m])
+    J = q_of_qr[:, n:].conj().T.dot(J[:, :2*m])
+
+    # Decide on which output type is needed for QZ
+    out_str = 'real' if r_or_c is float else 'complex'
+
+    _, _, _, _, _, u = ordqz(H, J, sort='iuc',
+                             overwrite_a=True,
+                             overwrite_b=True,
+                             check_finite=False,
+                             output=out_str)
+
+    # Get the relevant parts of the stable subspace basis
+    if e is not None:
+        u, _ = qr(np.vstack((e.dot(u[:m, :m]), u[m:, :m])))
+    u00 = u[:m, :m]
+    u10 = u[m:, :m]
+
+    # Solve via back-substituion after checking the condition of u00
+    up, ul, uu = lu(u00)
+
+    if 1/cond(uu) < np.spacing(1.):
+        raise LinAlgError('Failed to find a finite solution.')
+
+    # Exploit the triangular structure
+    x = solve_triangular(ul.conj().T,
+                         solve_triangular(uu.conj().T,
+                                          u10.conj().T,
+                                          lower=True),
+                         unit_diagonal=True,
+                         ).conj().T.dot(up.conj().T)
+    if balanced:
+        x *= sca[:m, None] * sca[:m]
+
+    # Check the deviation from symmetry for lack of success
+    # See proof of Thm.5 item 3 in [2]
+    u_sym = u00.conj().T.dot(u10)
+    n_u_sym = norm(u_sym, 1)
+    u_sym = u_sym - u_sym.conj().T
+    sym_threshold = np.max([np.spacing(1000.), 0.1*n_u_sym])
+
+    if norm(u_sym, 1) > sym_threshold:
+        raise LinAlgError('The associated symplectic pencil has eigenvalues '
+                          'too close to the unit circle')
+
+    return (x + x.conj().T)/2
+
+
+def _are_validate_args(a, b, q, r, e, s, eq_type='care'):
+    """
+    A helper function to validate the arguments supplied to the
+    Riccati equation solvers. Any discrepancy found in the input
+    matrices leads to a ``ValueError`` exception.
+
+    Essentially, it performs:
+
+        - a check whether the input is free of NaN and Infs
+        - a pass for the data through ``numpy.atleast_2d()``
+        - squareness check of the relevant arrays
+        - shape consistency check of the arrays
+        - singularity check of the relevant arrays
+        - symmetricity check of the relevant matrices
+        - a check whether the regular or the generalized version is asked.
+
+    This function is used by ``solve_continuous_are`` and
+    ``solve_discrete_are``.
+
+    Parameters
+    ----------
+    a, b, q, r, e, s : array_like
+        Input data
+    eq_type : str
+        Accepted arguments are 'care' and 'dare'.
+
+    Returns
+    -------
+    a, b, q, r, e, s : ndarray
+        Regularized input data
+    m, n : int
+        shape of the problem
+    r_or_c : type
+        Data type of the problem, returns float or complex
+    gen_or_not : bool
+        Type of the equation, True for generalized and False for regular ARE.
+
+    """
+
+    if eq_type.lower() not in ("dare", "care"):
+        raise ValueError("Equation type unknown. "
+                         "Only 'care' and 'dare' is understood")
+
+    a = np.atleast_2d(_asarray_validated(a, check_finite=True))
+    b = np.atleast_2d(_asarray_validated(b, check_finite=True))
+    q = np.atleast_2d(_asarray_validated(q, check_finite=True))
+    r = np.atleast_2d(_asarray_validated(r, check_finite=True))
+
+    # Get the correct data types otherwise NumPy complains
+    # about pushing complex numbers into real arrays.
+    r_or_c = complex if np.iscomplexobj(b) else float
+
+    for ind, mat in enumerate((a, q, r)):
+        if np.iscomplexobj(mat):
+            r_or_c = complex
+
+        if not np.equal(*mat.shape):
+            raise ValueError(f"Matrix {'aqr'[ind]} should be square.")
+
+    # Shape consistency checks
+    m, n = b.shape
+    if m != a.shape[0]:
+        raise ValueError("Matrix a and b should have the same number of rows.")
+    if m != q.shape[0]:
+        raise ValueError("Matrix a and q should have the same shape.")
+    if n != r.shape[0]:
+        raise ValueError("Matrix b and r should have the same number of cols.")
+
+    # Check if the data matrices q, r are (sufficiently) hermitian
+    for ind, mat in enumerate((q, r)):
+        if norm(mat - mat.conj().T, 1) > np.spacing(norm(mat, 1))*100:
+            raise ValueError(f"Matrix {'qr'[ind]} should be symmetric/hermitian.")
+
+    # Continuous time ARE should have a nonsingular r matrix.
+    if eq_type == 'care':
+        min_sv = svd(r, compute_uv=False)[-1]
+        if min_sv == 0. or min_sv < np.spacing(1.)*norm(r, 1):
+            raise ValueError('Matrix r is numerically singular.')
+
+    # Check if the generalized case is required with omitted arguments
+    # perform late shape checking etc.
+    generalized_case = e is not None or s is not None
+
+    if generalized_case:
+        if e is not None:
+            e = np.atleast_2d(_asarray_validated(e, check_finite=True))
+            if not np.equal(*e.shape):
+                raise ValueError("Matrix e should be square.")
+            if m != e.shape[0]:
+                raise ValueError("Matrix a and e should have the same shape.")
+            # numpy.linalg.cond doesn't check for exact zeros and
+            # emits a runtime warning. Hence the following manual check.
+            min_sv = svd(e, compute_uv=False)[-1]
+            if min_sv == 0. or min_sv < np.spacing(1.) * norm(e, 1):
+                raise ValueError('Matrix e is numerically singular.')
+            if np.iscomplexobj(e):
+                r_or_c = complex
+        if s is not None:
+            s = np.atleast_2d(_asarray_validated(s, check_finite=True))
+            if s.shape != b.shape:
+                raise ValueError("Matrix b and s should have the same shape.")
+            if np.iscomplexobj(s):
+                r_or_c = complex
+
+    return a, b, q, r, e, s, m, n, r_or_c, generalized_case
diff --git a/.venv/lib/python3.12/site-packages/scipy/linalg/_special_matrices.py b/.venv/lib/python3.12/site-packages/scipy/linalg/_special_matrices.py
new file mode 100644
index 0000000000000000000000000000000000000000..8b0031d573d67a9c59f1903e8d0b78aa700dd151
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/linalg/_special_matrices.py
@@ -0,0 +1,1313 @@
+import math
+import warnings
+
+import numpy as np
+from numpy.lib.stride_tricks import as_strided
+from scipy._lib._util import _apply_over_batch
+from scipy._lib._array_api import array_namespace, xp_capabilities, xp_size
+import scipy._external.array_api_extra as xpx
+
+
+__all__ = ['toeplitz', 'circulant', 'hankel',
+           'hadamard', 'leslie', 'block_diag', 'companion',
+           'helmert', 'hilbert', 'invhilbert', 'pascal', 'invpascal', 'dft',
+           'fiedler', 'fiedler_companion', 'convolution_matrix']
+
+
+# -----------------------------------------------------------------------------
+#  matrix construction functions
+# -----------------------------------------------------------------------------
+
+
+def toeplitz(c, r=None):
+    r"""
+    Construct a Toeplitz matrix.
+
+    The Toeplitz matrix has constant diagonals, with c as its first column
+    and r as its first row. If r is not given, ``r == conjugate(c)`` is
+    assumed.
+
+    The documentation is written assuming array arguments are of specified
+    "core" shapes. However, array argument(s) of this function may have additional
+    "batch" dimensions prepended to the core shape. In this case, the array is treated
+    as a batch of lower-dimensional slices; see :ref:`linalg_batch` for details.
+
+    Parameters
+    ----------
+    c : array_like
+        First column of the matrix.
+    r : array_like, optional
+        First row of the matrix. If None, ``r = conjugate(c)`` is assumed;
+        in this case, if c[0] is real, the result is a Hermitian matrix.
+        r[0] is ignored; the first row of the returned matrix is
+        ``[c[0], r[1:]]``.
+
+    Returns
+    -------
+    A : (len(c), len(r)) ndarray
+        The Toeplitz matrix. Dtype is the same as ``(c[0] + r[0]).dtype``.
+
+    See Also
+    --------
+    circulant : circulant matrix
+    hankel : Hankel matrix
+    solve_toeplitz : Solve a Toeplitz system.
+
+    Notes
+    -----
+    The behavior when `c` or `r` is a scalar, or when `c` is complex and
+    `r` is None, was changed in version 0.8.0. The behavior in previous
+    versions was undocumented and is no longer supported.
+
+    Examples
+    --------
+    >>> from scipy.linalg import toeplitz
+    >>> toeplitz([1,2,3], [1,4,5,6])
+    array([[1, 4, 5, 6],
+           [2, 1, 4, 5],
+           [3, 2, 1, 4]])
+    >>> toeplitz([1.0, 2+3j, 4-1j])
+    array([[ 1.+0.j,  2.-3.j,  4.+1.j],
+           [ 2.+3.j,  1.+0.j,  2.-3.j],
+           [ 4.-1.j,  2.+3.j,  1.+0.j]])
+
+    """
+    c = np.atleast_1d(c)
+    if r is None:
+        r = c.conjugate()
+    else:
+        r = np.atleast_1d(r)
+    return _toeplitz(c, r)
+
+
+@_apply_over_batch(("c", 1), ("r", 1))
+def _toeplitz(c, r):
+    # Form a 1-D array containing a reversed c followed by r[1:] that could be
+    # strided to give us toeplitz matrix.
+    vals = np.concatenate((c[::-1], r[1:]))
+    out_shp = len(c), len(r)
+    n = vals.strides[0]
+    return as_strided(vals[len(c)-1:], shape=out_shp, strides=(-n, n)).copy()
+
+
+def circulant(c):
+    """
+    Construct a circulant matrix.
+
+    Array argument(s) of this function may have additional
+    "batch" dimensions prepended to the core shape. In this case, the array is treated
+    as a batch of lower-dimensional slices; see :ref:`linalg_batch` for details.
+
+    Parameters
+    ----------
+    c : (..., N,)  array_like
+        The first column(s) of the matrix. Multidimensional arrays are treated as a
+        batch: each slice along the last axis is the first column of an output matrix.
+
+    Returns
+    -------
+    A : (..., N, N) ndarray
+        A circulant matrix whose first column is given by `c`.  For batch input, each
+        slice of shape ``(N, N)`` along the last two dimensions of the output
+        corresponds with a slice of shape ``(N,)`` along the last dimension of the
+        input.
+
+
+    See Also
+    --------
+    toeplitz : Toeplitz matrix
+    hankel : Hankel matrix
+    solve_circulant : Solve a circulant system.
+
+    Notes
+    -----
+    .. versionadded:: 0.8.0
+
+    Examples
+    --------
+    >>> from scipy.linalg import circulant
+    >>> circulant([1, 2, 3])
+    array([[1, 3, 2],
+           [2, 1, 3],
+           [3, 2, 1]])
+
+    >>> circulant([[1, 2, 3], [4, 5, 6]])
+    array([[[1, 3, 2],
+            [2, 1, 3],
+            [3, 2, 1]],
+           [[4, 6, 5],
+            [5, 4, 6],
+            [6, 5, 4]]])
+    """
+    c = np.atleast_1d(c)
+    batch_shape, N = c.shape[:-1], c.shape[-1]
+    # Need to use `prod(batch_shape)` instead of `-1` in case array has zero size
+    c = c.reshape(math.prod(batch_shape), N) if batch_shape else c
+    # Form an extended array that could be strided to give circulant version
+    c_ext = np.concatenate((c[..., ::-1], c[..., :0:-1]), axis=-1).ravel()
+    L = c.shape[-1]
+    n = c_ext.strides[-1]
+    if c.ndim == 1:
+        A = as_strided(c_ext[L-1:], shape=(L, L), strides=(-n, n))
+    else:
+        m = c.shape[0]
+        A = as_strided(c_ext[L-1:], shape=(m, L, L), strides=(n*(2*L-1), -n, n))
+    return A.reshape(batch_shape + (N, N)).copy()
+
+
+def hankel(c, r=None):
+    r"""
+    Construct a Hankel matrix.
+
+    The Hankel matrix has constant anti-diagonals, with `c` as its
+    first column and `r` as its last row. If the first element of `r`
+    differs from the last element of `c`, the first element of `r` is
+    replaced by the last element of `c` to ensure that anti-diagonals
+    remain constant. If `r` is not given, then `r = zeros_like(c)` is
+    assumed.
+
+    Parameters
+    ----------
+    c : array_like
+        First column of the matrix.
+    r : array_like, optional
+        Last row of the matrix. If None, ``r = zeros_like(c)`` is assumed.
+        r[0] is ignored; the last row of the returned matrix is
+        ``[c[-1], r[1:]]``.
+
+        .. warning::
+
+            Beginning in SciPy 1.19, multidimensional input will be treated as a batch,
+            not ``ravel``\ ed. To preserve the existing behavior, ``ravel`` arguments
+            before passing them to `toeplitz`.
+
+    Returns
+    -------
+    A : (len(c), len(r)) ndarray
+        The Hankel matrix. Dtype is the same as ``(c[0] + r[0]).dtype``.
+
+    See Also
+    --------
+    toeplitz : Toeplitz matrix
+    circulant : circulant matrix
+
+    Examples
+    --------
+    >>> from scipy.linalg import hankel
+    >>> hankel([1, 17, 99])
+    array([[ 1, 17, 99],
+           [17, 99,  0],
+           [99,  0,  0]])
+    >>> hankel([1,2,3,4], [4,7,7,8,9])
+    array([[1, 2, 3, 4, 7],
+           [2, 3, 4, 7, 7],
+           [3, 4, 7, 7, 8],
+           [4, 7, 7, 8, 9]])
+
+    """
+    c = np.asarray(c)
+    if r is None:
+        r = np.zeros_like(c)
+    else:
+        r = np.asarray(r)
+
+    if c.ndim > 1 or r.ndim > 1:
+        msg = ("Beginning in SciPy 1.19, multidimensional input will be treated as a "
+               "batch, not `ravel`ed. To preserve the existing behavior and silence "
+               "this warning, `ravel` arguments before passing them to `hankel`.")
+        warnings.warn(msg, FutureWarning, stacklevel=2)
+        c, r = c.ravel(), r.ravel()
+
+    # Form a 1-D array of values to be used in the matrix, containing `c`
+    # followed by r[1:].
+    vals = np.concatenate((c, r[1:]))
+    # Stride on concatenated array to get hankel matrix
+    out_shp = len(c), len(r)
+    n = vals.strides[0]
+    return as_strided(vals, shape=out_shp, strides=(n, n)).copy()
+
+
+def hadamard(n, dtype=int):
+    """
+    Construct a Hadamard matrix.
+
+    Constructs an n-by-n Hadamard matrix, using Sylvester's
+    construction. `n` must be a power of 2.
+
+    Parameters
+    ----------
+    n : int
+        The order of the matrix. `n` must be a power of 2.
+    dtype : dtype, optional
+        The data type of the array to be constructed.
+
+    Returns
+    -------
+    H : (n, n) ndarray
+        The Hadamard matrix.
+
+    Notes
+    -----
+    .. versionadded:: 0.8.0
+
+    Examples
+    --------
+    >>> from scipy.linalg import hadamard
+    >>> hadamard(2, dtype=complex)
+    array([[ 1.+0.j,  1.+0.j],
+           [ 1.+0.j, -1.-0.j]])
+    >>> hadamard(4)
+    array([[ 1,  1,  1,  1],
+           [ 1, -1,  1, -1],
+           [ 1,  1, -1, -1],
+           [ 1, -1, -1,  1]])
+
+    """
+
+    # This function is a slightly modified version of the
+    # function contributed by Ivo in ticket #675.
+
+    if n < 1:
+        lg2 = 0
+    else:
+        lg2 = int(math.log(n, 2))
+    if 2 ** lg2 != n:
+        raise ValueError("n must be a positive integer, and n must be "
+                         "a power of 2")
+
+    H = np.array([[1]], dtype=dtype)
+
+    # Sylvester's construction
+    for i in range(0, lg2):
+        H = np.vstack((np.hstack((H, H)), np.hstack((H, -H))))
+
+    return H
+
+
+@_apply_over_batch(("f", 1), ("s", 1))
+def leslie(f, s):
+    """
+    Create a Leslie matrix.
+
+    Given the length n array of fecundity coefficients `f` and the length
+    n-1 array of survival coefficients `s`, return the associated Leslie
+    matrix.
+
+    The documentation is written assuming array arguments are of specified
+    "core" shapes. However, array argument(s) of this function may have additional
+    "batch" dimensions prepended to the core shape. In this case, the array is treated
+    as a batch of lower-dimensional slices; see :ref:`linalg_batch` for details.
+
+    Parameters
+    ----------
+    f : (N,) array_like
+        The "fecundity" coefficients.
+    s : (N-1,) array_like
+        The "survival" coefficients. The length of `s` must be one less
+        than the length of `f`, and it must be at least 1.
+
+    Returns
+    -------
+    L : (N, N) ndarray
+        The array is zero except for the first row,
+        which is `f`, and the first sub-diagonal, which is `s`.
+        The data-type of the array will be the data-type of
+        ``f[0]+s[0]``.
+
+    Notes
+    -----
+    The Leslie matrix is used to model discrete-time, age-structured
+    population growth [1]_ [2]_. In a population with `n` age classes, two sets
+    of parameters define a Leslie matrix: the `n` "fecundity coefficients",
+    which give the number of offspring per-capita produced by each age
+    class, and the `n` - 1 "survival coefficients", which give the
+    per-capita survival rate of each age class.
+
+    References
+    ----------
+    .. [1] P. H. Leslie, On the use of matrices in certain population
+           mathematics, Biometrika, Vol. 33, No. 3, 183--212 (Nov. 1945)
+    .. [2] P. H. Leslie, Some further notes on the use of matrices in
+           population mathematics, Biometrika, Vol. 35, No. 3/4, 213--245
+           (Dec. 1948)
+
+    Examples
+    --------
+    >>> from scipy.linalg import leslie
+    >>> leslie([0.1, 2.0, 1.0, 0.1], [0.2, 0.8, 0.7])
+    array([[ 0.1,  2. ,  1. ,  0.1],
+           [ 0.2,  0. ,  0. ,  0. ],
+           [ 0. ,  0.8,  0. ,  0. ],
+           [ 0. ,  0. ,  0.7,  0. ]])
+
+    """
+    f = np.atleast_1d(f)
+    s = np.atleast_1d(s)
+
+    if f.shape[-1] != s.shape[-1] + 1:
+        raise ValueError("Incorrect lengths for f and s. The length of s along "
+                         "the last axis must be one less than the length of f.")
+    if s.shape[-1] == 0:
+        raise ValueError("The length of s must be at least 1.")
+
+    n = f.shape[-1]
+    tmp = f[0] + s[0]
+    a = np.zeros((n, n), dtype=tmp.dtype)
+    a[0] = f
+    a[list(range(1, n)), list(range(0, n - 1))] = s
+    return a
+
+
+@xp_capabilities(jax_jit=False, allow_dask_compute=2)
+def block_diag(*arrs):
+    """
+    Create a block diagonal array from provided arrays.
+
+    For example, given 2-D inputs `A`, `B` and `C`, the output will have these
+    arrays arranged on the diagonal::
+
+        [[A, 0, 0],
+         [0, B, 0],
+         [0, 0, C]]
+
+    The documentation is written assuming array arguments are of specified
+    "core" shapes. However, array argument(s) of this function may have additional
+    "batch" dimensions prepended to the core shape. In this case, the array is treated
+    as a batch of lower-dimensional slices; see :ref:`linalg_batch` for details.
+
+    Parameters
+    ----------
+    *arrs : array_like
+        Input arrays ``A, B, C, ...``. A 1-D array or array_like sequence of length
+        ``n`` is treated as a 2-D array with shape ``(1, n)``.
+
+    Returns
+    -------
+    D : ndarray
+        Array with `A`, `B`, `C`, ... on the diagonal of the last two
+        dimensions. `D` has the same dtype as the result type of the
+        inputs.
+
+    Notes
+    -----
+    If all the input arrays are square, the output is known as a
+    block diagonal matrix.
+
+    Empty sequences (i.e., array-likes of zero size) will not be ignored.
+    Noteworthy, both ``[]`` and ``[[]]`` are treated as matrices with shape
+    ``(1,0)``.
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy.linalg import block_diag
+    >>> A = [[1, 0],
+    ...      [0, 1]]
+    >>> B = [[3, 4, 5],
+    ...      [6, 7, 8]]
+    >>> C = [[7]]
+    >>> P = np.zeros((2, 0), dtype='int32')
+    >>> block_diag(A, B, C)
+    array([[1, 0, 0, 0, 0, 0],
+           [0, 1, 0, 0, 0, 0],
+           [0, 0, 3, 4, 5, 0],
+           [0, 0, 6, 7, 8, 0],
+           [0, 0, 0, 0, 0, 7]])
+    >>> block_diag(A, P, B, C)
+    array([[1, 0, 0, 0, 0, 0],
+           [0, 1, 0, 0, 0, 0],
+           [0, 0, 0, 0, 0, 0],
+           [0, 0, 0, 0, 0, 0],
+           [0, 0, 3, 4, 5, 0],
+           [0, 0, 6, 7, 8, 0],
+           [0, 0, 0, 0, 0, 7]])
+    >>> block_diag(1.0, [2, 3], [[4, 5], [6, 7]])
+    array([[ 1.,  0.,  0.,  0.,  0.],
+           [ 0.,  2.,  3.,  0.,  0.],
+           [ 0.,  0.,  0.,  4.,  5.],
+           [ 0.,  0.,  0.,  6.,  7.]])
+
+    """
+    xp = array_namespace(*arrs)
+
+    if arrs == ():
+        arrs = ([],)
+    arrs = [xpx.atleast_nd(xp.asarray(a), ndim=2) for a in arrs]
+
+    batch_shapes = [a.shape[:-2] for a in arrs]
+    batch_shape = np.broadcast_shapes(*batch_shapes)
+    arrs = [xp.broadcast_to(a, batch_shape + a.shape[-2:]) for a in arrs]
+    out_dtype = xp.result_type(*arrs)
+    block_shapes = [a.shape[-2:] for a in arrs]
+    out = xp.zeros(batch_shape +
+                   tuple(map(int, xp.sum(xp.asarray(block_shapes), axis=0))),
+                   dtype=out_dtype)
+
+    r, c = 0, 0
+    for i, (rr, cc) in enumerate(block_shapes):
+        out = xpx.at(out)[..., r:r+rr, c:c+cc].set(arrs[i])
+        r += rr
+        c += cc
+    return out
+
+
+def companion(a):
+    """
+    Create a companion matrix.
+
+    Create the companion matrix [1]_ associated with the polynomial whose
+    coefficients are given in `a`.
+
+    Array argument(s) of this function may have additional
+    "batch" dimensions prepended to the core shape. In this case, the array is treated
+    as a batch of lower-dimensional slices; see :ref:`linalg_batch` for details.
+
+    Parameters
+    ----------
+    a : (..., N) array_like
+        1-D array of polynomial coefficients. The length of `a` must be
+        at least two, and ``a[0]`` must not be zero.
+        M-dimensional arrays are treated as a batch: each slice along the last
+        axis is a 1-D array of polynomial coefficients.
+
+    Returns
+    -------
+    c : (..., N-1, N-1) ndarray
+        For 1-D input, the first row of `c` is ``-a[1:]/a[0]``, and the first
+        sub-diagonal is all ones.  The data-type of the array is the same
+        as the data-type of ``1.0*a[0]``.
+        For batch input, each slice of shape ``(N-1, N-1)`` along the last two
+        dimensions of the output corresponds with a slice of shape ``(N,)``
+        along the last dimension of the input.
+
+    Raises
+    ------
+    ValueError
+        If any of the following are true: a) ``a.shape[-1] < 2``; b) ``a[..., 0] == 0``.
+
+    Notes
+    -----
+    .. versionadded:: 0.8.0
+
+    References
+    ----------
+    .. [1] R. A. Horn & C. R. Johnson, *Matrix Analysis*.  Cambridge, UK:
+        Cambridge University Press, 1999, pp. 146-7.
+
+    Examples
+    --------
+    >>> from scipy.linalg import companion
+    >>> companion([1, -10, 31, -30])
+    array([[ 10., -31.,  30.],
+           [  1.,   0.,   0.],
+           [  0.,   1.,   0.]])
+
+    """
+    a = np.atleast_1d(a)
+    n = a.shape[-1]
+
+    if n < 2:
+        raise ValueError("The length of `a` along the last axis must be at least 2.")
+
+    if np.any(a[..., 0] == 0):
+        raise ValueError("The first coefficient(s) of `a` (i.e. elements "
+                         "of `a[..., 0]`) must not be zero.")
+
+    first_row = -a[..., 1:] / (1.0 * a[..., 0:1])
+    c = np.zeros(a.shape[:-1] + (n - 1, n - 1), dtype=first_row.dtype)
+    c[..., 0, :] = first_row
+    c[..., np.arange(1, n - 1), np.arange(0, n - 2)] = 1
+    return c
+
+
+def helmert(n, full=False):
+    """
+    Create a Helmert matrix of order `n`.
+
+    This has applications in statistics, compositional or simplicial analysis,
+    and in Aitchison geometry.
+
+    Parameters
+    ----------
+    n : int
+        The size of the array to create.
+    full : bool, optional
+        If True the (n, n) ndarray will be returned.
+        Otherwise the submatrix that does not include the first
+        row will be returned.
+        Default: False.
+
+    Returns
+    -------
+    M : ndarray
+        The Helmert matrix.
+        The shape is (n, n) or (n-1, n) depending on the `full` argument.
+
+    Examples
+    --------
+    >>> from scipy.linalg import helmert
+    >>> helmert(5, full=True)
+    array([[ 0.4472136 ,  0.4472136 ,  0.4472136 ,  0.4472136 ,  0.4472136 ],
+           [ 0.70710678, -0.70710678,  0.        ,  0.        ,  0.        ],
+           [ 0.40824829,  0.40824829, -0.81649658,  0.        ,  0.        ],
+           [ 0.28867513,  0.28867513,  0.28867513, -0.8660254 ,  0.        ],
+           [ 0.2236068 ,  0.2236068 ,  0.2236068 ,  0.2236068 , -0.89442719]])
+
+    """
+    H = np.tril(np.ones((n, n)), -1) - np.diag(np.arange(n))
+    d = np.arange(n) * np.arange(1, n+1)
+    H[0] = 1
+    d[0] = n
+    H_full = H / np.sqrt(d)[:, np.newaxis]
+    if full:
+        return H_full
+    else:
+        return H_full[1:]
+
+
+def hilbert(n):
+    """
+    Create a Hilbert matrix of order `n`.
+
+    Returns the `n` by `n` array with entries `h[i,j] = 1 / (i + j + 1)`.
+
+    Parameters
+    ----------
+    n : int
+        The size of the array to create.
+
+    Returns
+    -------
+    h : (n, n) ndarray
+        The Hilbert matrix.
+
+    See Also
+    --------
+    invhilbert : Compute the inverse of a Hilbert matrix.
+
+    Notes
+    -----
+    .. versionadded:: 0.10.0
+
+    Examples
+    --------
+    >>> from scipy.linalg import hilbert
+    >>> hilbert(3)
+    array([[ 1.        ,  0.5       ,  0.33333333],
+           [ 0.5       ,  0.33333333,  0.25      ],
+           [ 0.33333333,  0.25      ,  0.2       ]])
+
+    """
+    values = 1.0 / (1.0 + np.arange(2 * n - 1))
+    h = hankel(values[:n], r=values[n - 1:])
+    return h
+
+
+def invhilbert(n, exact=False):
+    """
+    Compute the inverse of the Hilbert matrix of order `n`.
+
+    The entries in the inverse of a Hilbert matrix are integers. When `n`
+    is greater than 14, some entries in the inverse exceed the upper limit
+    of 64 bit integers. The `exact` argument provides two options for
+    dealing with these large integers.
+
+    Parameters
+    ----------
+    n : int
+        The order of the Hilbert matrix.
+    exact : bool, optional
+        If False, the data type of the array that is returned is np.float64,
+        and the array is an approximation of the inverse.
+        If True, the array is the exact integer inverse array. To represent
+        the exact inverse when n > 14, the returned array is an object array
+        of long integers. For n <= 14, the exact inverse is returned as an
+        array with data type np.int64.
+
+    Returns
+    -------
+    invh : (n, n) ndarray
+        The data type of the array is np.float64 if `exact` is False.
+        If `exact` is True, the data type is either np.int64 (for n <= 14)
+        or object (for n > 14). In the latter case, the objects in the
+        array will be long integers.
+
+    See Also
+    --------
+    hilbert : Create a Hilbert matrix.
+
+    Notes
+    -----
+    .. versionadded:: 0.10.0
+
+    Examples
+    --------
+    >>> from scipy.linalg import invhilbert
+    >>> invhilbert(4)
+    array([[   16.,  -120.,   240.,  -140.],
+           [ -120.,  1200., -2700.,  1680.],
+           [  240., -2700.,  6480., -4200.],
+           [ -140.,  1680., -4200.,  2800.]])
+    >>> invhilbert(4, exact=True)
+    array([[   16,  -120,   240,  -140],
+           [ -120,  1200, -2700,  1680],
+           [  240, -2700,  6480, -4200],
+           [ -140,  1680, -4200,  2800]], dtype=int64)
+    >>> invhilbert(16)[7,7]
+    4.2475099528537506e+19
+    >>> invhilbert(16, exact=True)[7,7]
+    42475099528537378560
+
+    """
+    from scipy.special import comb
+    if exact:
+        if n > 14:
+            dtype = object
+        else:
+            dtype = np.int64
+    else:
+        dtype = np.float64
+    invh = np.empty((n, n), dtype=dtype)
+    for i in range(n):
+        for j in range(0, i + 1):
+            s = i + j
+            invh[i, j] = ((-1) ** s * (s + 1) *
+                          comb(n + i, n - j - 1, exact=exact) *
+                          comb(n + j, n - i - 1, exact=exact) *
+                          comb(s, i, exact=exact) ** 2)
+            if i != j:
+                invh[j, i] = invh[i, j]
+    return invh
+
+
+def pascal(n, kind='symmetric', exact=True):
+    """
+    Returns the n x n Pascal matrix.
+
+    The Pascal matrix is a matrix containing the binomial coefficients as
+    its elements.
+
+    Parameters
+    ----------
+    n : int
+        The size of the matrix to create; that is, the result is an n x n
+        matrix.
+    kind : str, optional
+        Must be one of 'symmetric', 'lower', or 'upper'.
+        Default is 'symmetric'.
+    exact : bool, optional
+        If `exact` is True, the result is either an array of type
+        numpy.uint64 (if n < 35) or an object array of Python long integers.
+        If `exact` is False, the coefficients in the matrix are computed using
+        `scipy.special.comb` with ``exact=False``. The result will be a floating
+        point array, and the values in the array will not be the exact
+        coefficients, but this version is much faster than ``exact=True``.
+
+    Returns
+    -------
+    p : (n, n) ndarray
+        The Pascal matrix.
+
+    See Also
+    --------
+    invpascal
+
+    Notes
+    -----
+    See https://en.wikipedia.org/wiki/Pascal_matrix for more information
+    about Pascal matrices.
+
+    .. versionadded:: 0.11.0
+
+    Examples
+    --------
+    >>> from scipy.linalg import pascal
+    >>> pascal(4)
+    array([[ 1,  1,  1,  1],
+           [ 1,  2,  3,  4],
+           [ 1,  3,  6, 10],
+           [ 1,  4, 10, 20]], dtype=uint64)
+    >>> pascal(4, kind='lower')
+    array([[1, 0, 0, 0],
+           [1, 1, 0, 0],
+           [1, 2, 1, 0],
+           [1, 3, 3, 1]], dtype=uint64)
+    >>> pascal(50)[-1, -1]
+    25477612258980856902730428600
+    >>> from scipy.special import comb
+    >>> comb(98, 49, exact=True)
+    25477612258980856902730428600
+
+    """
+
+    from scipy.special import comb
+    if kind not in ['symmetric', 'lower', 'upper']:
+        raise ValueError("kind must be 'symmetric', 'lower', or 'upper'")
+
+    if exact:
+        if n >= 35:
+            L_n = np.empty((n, n), dtype=object)
+            L_n.fill(0)
+        else:
+            L_n = np.zeros((n, n), dtype=np.uint64)
+        for i in range(n):
+            for j in range(i + 1):
+                L_n[i, j] = comb(i, j, exact=True)
+    else:
+        L_n = comb(*np.ogrid[:n, :n])
+
+    if kind == 'lower':
+        p = L_n
+    elif kind == 'upper':
+        p = L_n.T
+    else:
+        p = np.dot(L_n, L_n.T)
+
+    return p
+
+
+def invpascal(n, kind='symmetric', exact=True):
+    """
+    Returns the inverse of the n x n Pascal matrix.
+
+    The Pascal matrix is a matrix containing the binomial coefficients as
+    its elements.
+
+    Parameters
+    ----------
+    n : int
+        The size of the matrix to create; that is, the result is an n x n
+        matrix.
+    kind : str, optional
+        Must be one of 'symmetric', 'lower', or 'upper'.
+        Default is 'symmetric'.
+    exact : bool, optional
+        If `exact` is True, the result is either an array of type
+        ``numpy.int64`` (if `n` <= 35) or an object array of Python integers.
+        If `exact` is False, the coefficients in the matrix are computed using
+        `scipy.special.comb` with `exact=False`. The result will be a floating
+        point array, and for large `n`, the values in the array will not be the
+        exact coefficients.
+
+    Returns
+    -------
+    invp : (n, n) ndarray
+        The inverse of the Pascal matrix.
+
+    See Also
+    --------
+    pascal
+
+    Notes
+    -----
+
+    .. versionadded:: 0.16.0
+
+    References
+    ----------
+    .. [1] "Pascal matrix", https://en.wikipedia.org/wiki/Pascal_matrix
+    .. [2] Cohen, A. M., "The inverse of a Pascal matrix", Mathematical
+           Gazette, 59(408), pp. 111-112, 1975.
+
+    Examples
+    --------
+    >>> from scipy.linalg import invpascal, pascal
+    >>> invp = invpascal(5)
+    >>> invp
+    array([[  5, -10,  10,  -5,   1],
+           [-10,  30, -35,  19,  -4],
+           [ 10, -35,  46, -27,   6],
+           [ -5,  19, -27,  17,  -4],
+           [  1,  -4,   6,  -4,   1]])
+
+    >>> p = pascal(5)
+    >>> p.dot(invp)
+    array([[ 1.,  0.,  0.,  0.,  0.],
+           [ 0.,  1.,  0.,  0.,  0.],
+           [ 0.,  0.,  1.,  0.,  0.],
+           [ 0.,  0.,  0.,  1.,  0.],
+           [ 0.,  0.,  0.,  0.,  1.]])
+
+    An example of the use of `kind` and `exact`:
+
+    >>> invpascal(5, kind='lower', exact=False)
+    array([[ 1., -0.,  0., -0.,  0.],
+           [-1.,  1., -0.,  0., -0.],
+           [ 1., -2.,  1., -0.,  0.],
+           [-1.,  3., -3.,  1., -0.],
+           [ 1., -4.,  6., -4.,  1.]])
+
+    """
+    from scipy.special import comb
+
+    if kind not in ['symmetric', 'lower', 'upper']:
+        raise ValueError("'kind' must be 'symmetric', 'lower' or 'upper'.")
+
+    if kind == 'symmetric':
+        if exact:
+            if n > 34:
+                dt = object
+            else:
+                dt = np.int64
+        else:
+            dt = np.float64
+        invp = np.empty((n, n), dtype=dt)
+        for i in range(n):
+            for j in range(0, i + 1):
+                v = 0
+                for k in range(n - i):
+                    v += comb(i + k, k, exact=exact) * comb(i + k, i + k - j,
+                                                            exact=exact)
+                invp[i, j] = (-1)**(i - j) * v
+                if i != j:
+                    invp[j, i] = invp[i, j]
+    else:
+        # For the 'lower' and 'upper' cases, we computer the inverse by
+        # changing the sign of every other diagonal of the pascal matrix.
+        invp = pascal(n, kind=kind, exact=exact)
+        if invp.dtype == np.uint64:
+            # This cast from np.uint64 to int64 OK, because if `kind` is not
+            # "symmetric", the values in invp are all much less than 2**63.
+            invp = invp.view(np.int64)
+
+        # The toeplitz matrix has alternating bands of 1 and -1.
+        invp *= toeplitz((-1)**np.arange(n)).astype(invp.dtype)
+
+    return invp
+
+
+def dft(n, scale=None):
+    """
+    Discrete Fourier transform matrix.
+
+    Create the matrix that computes the discrete Fourier transform of a
+    sequence [1]_. The nth primitive root of unity used to generate the
+    matrix is exp(-2*pi*i/n), where i = sqrt(-1).
+
+    Parameters
+    ----------
+    n : int
+        Size the matrix to create.
+    scale : str, optional
+        Must be None, 'sqrtn', or 'n'.
+        If `scale` is 'sqrtn', the matrix is divided by `sqrt(n)`.
+        If `scale` is 'n', the matrix is divided by `n`.
+        If `scale` is None (the default), the matrix is not normalized, and the
+        return value is simply the Vandermonde matrix of the roots of unity.
+
+    Returns
+    -------
+    m : (n, n) ndarray
+        The DFT matrix.
+
+    Notes
+    -----
+    When `scale` is None, multiplying a vector by the matrix returned by
+    `dft` is mathematically equivalent to (but much less efficient than)
+    the calculation performed by `scipy.fft.fft`.
+
+    .. versionadded:: 0.14.0
+
+    References
+    ----------
+    .. [1] "DFT matrix", https://en.wikipedia.org/wiki/DFT_matrix
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy.linalg import dft
+    >>> np.set_printoptions(precision=2, suppress=True)  # for compact output
+    >>> m = dft(5)
+    >>> m
+    array([[ 1.  +0.j  ,  1.  +0.j  ,  1.  +0.j  ,  1.  +0.j  ,  1.  +0.j  ],
+           [ 1.  +0.j  ,  0.31-0.95j, -0.81-0.59j, -0.81+0.59j,  0.31+0.95j],
+           [ 1.  +0.j  , -0.81-0.59j,  0.31+0.95j,  0.31-0.95j, -0.81+0.59j],
+           [ 1.  +0.j  , -0.81+0.59j,  0.31-0.95j,  0.31+0.95j, -0.81-0.59j],
+           [ 1.  +0.j  ,  0.31+0.95j, -0.81+0.59j, -0.81-0.59j,  0.31-0.95j]])
+    >>> x = np.array([1, 2, 3, 0, 3])
+    >>> m @ x  # Compute the DFT of x
+    array([ 9.  +0.j  ,  0.12-0.81j, -2.12+3.44j, -2.12-3.44j,  0.12+0.81j])
+
+    Verify that ``m @ x`` is the same as ``fft(x)``.
+
+    >>> from scipy.fft import fft
+    >>> fft(x)     # Same result as m @ x
+    array([ 9.  +0.j  ,  0.12-0.81j, -2.12+3.44j, -2.12-3.44j,  0.12+0.81j])
+    """
+    if scale not in [None, 'sqrtn', 'n']:
+        raise ValueError("scale must be None, 'sqrtn', or 'n'; "
+                         f"{scale!r} is not valid.")
+
+    omegas = np.exp(-2j * np.pi * np.arange(n) / n).reshape(-1, 1)
+    m = omegas ** np.arange(n)
+    if scale == 'sqrtn':
+        m /= math.sqrt(n)
+    elif scale == 'n':
+        m /= n
+    return m
+
+
+@xp_capabilities()
+def fiedler(a):
+    """Returns a symmetric Fiedler matrix.
+
+    Given an sequence of numbers `a`, Fiedler matrices have the structure
+    ``F[i, j] = np.abs(a[i] - a[j])``, and hence zero diagonals and nonnegative
+    entries. A Fiedler matrix has a dominant positive eigenvalue and other
+    eigenvalues are negative. Although not valid generally, for certain inputs,
+    the inverse and the determinant can be derived explicitly as given in [1]_.
+
+    Array argument(s) of this function may have additional
+    "batch" dimensions prepended to the core shape. In this case, the array is treated
+    as a batch of lower-dimensional slices; see :ref:`linalg_batch` for details.
+
+    Parameters
+    ----------
+    a : (..., n,) array_like
+        Coefficient array. N-dimensional arrays are treated as a batch:
+        each slice along the last axis is a 1-D coefficient array.
+
+    Returns
+    -------
+    F : (..., n, n) ndarray
+        Fiedler matrix. For batch input, each slice of shape ``(n, n)``
+        along the last two dimensions of the output corresponds with a
+        slice of shape ``(n,)`` along the last dimension of the input.
+
+    See Also
+    --------
+    circulant, toeplitz
+
+    Notes
+    -----
+
+    .. versionadded:: 1.3.0
+
+    References
+    ----------
+    .. [1] J. Todd, "Basic Numerical Mathematics: Vol.2 : Numerical Algebra",
+        1977, Birkhauser, :doi:`10.1007/978-3-0348-7286-7`
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy.linalg import det, inv, fiedler
+    >>> a = [1, 4, 12, 45, 77]
+    >>> n = len(a)
+    >>> A = fiedler(a)
+    >>> A
+    array([[ 0,  3, 11, 44, 76],
+           [ 3,  0,  8, 41, 73],
+           [11,  8,  0, 33, 65],
+           [44, 41, 33,  0, 32],
+           [76, 73, 65, 32,  0]])
+
+    The explicit formulas for determinant and inverse seem to hold only for
+    monotonically increasing/decreasing arrays. Note the tridiagonal structure
+    and the corners.
+
+    >>> Ai = inv(A)
+    >>> Ai[np.abs(Ai) < 1e-12] = 0.  # cleanup the numerical noise for display
+    >>> Ai
+    array([[-0.16008772,  0.16666667,  0.        ,  0.        ,  0.00657895],
+           [ 0.16666667, -0.22916667,  0.0625    ,  0.        ,  0.        ],
+           [ 0.        ,  0.0625    , -0.07765152,  0.01515152,  0.        ],
+           [ 0.        ,  0.        ,  0.01515152, -0.03077652,  0.015625  ],
+           [ 0.00657895,  0.        ,  0.        ,  0.015625  , -0.00904605]])
+    >>> det(A)
+    15409151.999999998
+    >>> (-1)**(n-1) * 2**(n-2) * np.diff(a).prod() * (a[-1] - a[0])
+    15409152
+
+    """
+    xp = array_namespace(a)
+    a = xpx.atleast_nd(xp.asarray(a), ndim=1)
+
+    if xp_size(a) == 0:
+        return xp.empty((0, 0), dtype=xp.float64)
+    elif xp_size(a) == 1:
+        return xp.asarray([[0.]])
+    else:
+        return xp.abs(a[..., :, xp.newaxis] - a[..., xp.newaxis, :])
+
+
+def fiedler_companion(a):
+    """Returns a Fiedler companion matrix.
+
+    Given a polynomial coefficient array ``a``, this function forms a
+    pentadiagonal matrix with a special structure whose eigenvalues coincides
+    with the roots of ``a``.
+
+    Array argument(s) of this function may have additional
+    "batch" dimensions prepended to the core shape. In this case, the array is treated
+    as a batch of lower-dimensional slices; see :ref:`linalg_batch` for details.
+
+    Parameters
+    ----------
+    a : (..., N) array_like
+        1-D array of polynomial coefficients in descending order with a nonzero
+        leading coefficient. For ``N < 2``, an empty array is returned.
+        N-dimensional arrays are treated as a batch: each slice along the last
+        axis is a 1-D array of polynomial coefficients.
+
+    Returns
+    -------
+    c : (..., N-1, N-1) ndarray
+        Resulting companion matrix. For batch input, each slice of shape
+        ``(N-1, N-1)`` along the last two dimensions of the output corresponds
+        with a slice of shape ``(N,)`` along the last dimension of the input.
+
+    See Also
+    --------
+    companion
+
+    Notes
+    -----
+    Similar to `companion`, each leading coefficient along the last axis of the
+    input should be nonzero.
+    If the leading coefficient is not 1, other coefficients are rescaled before
+    the array generation. To avoid numerical issues, it is best to provide a
+    monic polynomial.
+
+    .. versionadded:: 1.3.0
+
+    References
+    ----------
+    .. [1] M. Fiedler, " A note on companion matrices", Linear Algebra and its
+        Applications, 2003, :doi:`10.1016/S0024-3795(03)00548-2`
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy.linalg import fiedler_companion, eigvals
+    >>> p = np.poly(np.arange(1, 9, 2))  # [1., -16., 86., -176., 105.]
+    >>> fc = fiedler_companion(p)
+    >>> fc
+    array([[  16.,  -86.,    1.,    0.],
+           [   1.,    0.,    0.,    0.],
+           [   0.,  176.,    0., -105.],
+           [   0.,    1.,    0.,    0.]])
+    >>> eigvals(fc)
+    array([7.+0.j, 5.+0.j, 3.+0.j, 1.+0.j])
+
+    """
+    a = np.atleast_1d(a)
+
+    if a.ndim > 1:
+        return np.apply_along_axis(fiedler_companion, -1, a)
+
+    if a.size <= 2:
+        if a.size == 2:
+            return np.array([[-(a/a[0])[-1]]])
+        if a.size == 1:
+            return np.empty((0, 0), dtype=a.dtype)
+        return np.array([], dtype=a.dtype)
+
+    if a[0] == 0.:
+        raise ValueError('Leading coefficient is zero.')
+
+    a = a/a[0]
+    n = a.size - 1
+    c = np.zeros((n, n), dtype=a.dtype)
+    # subdiagonals
+    c[range(3, n, 2), range(1, n-2, 2)] = 1.
+    c[range(2, n, 2), range(1, n-1, 2)] = -a[3::2]
+    # superdiagonals
+    c[range(0, n-2, 2), range(2, n, 2)] = 1.
+    c[range(0, n-1, 2), range(1, n, 2)] = -a[2::2]
+    c[[0, 1], 0] = [-a[1], 1]
+
+    return c
+
+
+def convolution_matrix(a, n, mode='full'):
+    """
+    Construct a convolution matrix.
+
+    Constructs the Toeplitz matrix representing one-dimensional
+    convolution [1]_.  See the notes below for details.
+
+    Array argument(s) of this function may have additional
+    "batch" dimensions prepended to the core shape. In this case, the array is treated
+    as a batch of lower-dimensional slices; see :ref:`linalg_batch` for details.
+
+    Parameters
+    ----------
+    a : (..., m) array_like
+        The 1-D array to convolve. N-dimensional arrays are treated as a
+        batch: each slice along the last axis is a 1-D array to convolve.
+    n : int
+        The number of columns in the resulting matrix.  It gives the length
+        of the input to be convolved with `a`.  This is analogous to the
+        length of `v` in ``numpy.convolve(a, v)``.
+    mode : str
+        This is analogous to `mode` in ``numpy.convolve(v, a, mode)``.
+        It must be one of ('full', 'valid', 'same').
+        See below for how `mode` determines the shape of the result.
+
+    Returns
+    -------
+    A : (..., k, n) ndarray
+        The convolution matrix whose row count `k` depends on `mode`::
+
+            =======  =========================
+             mode    k
+            =======  =========================
+            'full'   m + n -1
+            'same'   max(m, n)
+            'valid'  max(m, n) - min(m, n) + 1
+            =======  =========================
+
+        For batch input, each slice of shape ``(k, n)`` along the last two
+        dimensions of the output corresponds with a slice of shape ``(m,)``
+        along the last dimension of the input.
+
+    See Also
+    --------
+    toeplitz : Toeplitz matrix
+
+    Notes
+    -----
+    The code::
+
+        A = convolution_matrix(a, n, mode)
+
+    creates a Toeplitz matrix `A` such that ``A @ v`` is equivalent to
+    using ``convolve(a, v, mode)``.  The returned array always has `n`
+    columns.  The number of rows depends on the specified `mode`, as
+    explained above.
+
+    In the default 'full' mode, the entries of `A` are given by::
+
+        A[i, j] == (a[i-j] if (0 <= (i-j) < m) else 0)
+
+    where ``m = len(a)``.  Suppose, for example, the input array is
+    ``[x, y, z]``.  The convolution matrix has the form::
+
+        [x, 0, 0, ..., 0, 0]
+        [y, x, 0, ..., 0, 0]
+        [z, y, x, ..., 0, 0]
+        ...
+        [0, 0, 0, ..., x, 0]
+        [0, 0, 0, ..., y, x]
+        [0, 0, 0, ..., z, y]
+        [0, 0, 0, ..., 0, z]
+
+    In 'valid' mode, the entries of `A` are given by::
+
+        A[i, j] == (a[i-j+m-1] if (0 <= (i-j+m-1) < m) else 0)
+
+    This corresponds to a matrix whose rows are the subset of those from
+    the 'full' case where all the coefficients in `a` are contained in the
+    row.  For input ``[x, y, z]``, this array looks like::
+
+        [z, y, x, 0, 0, ..., 0, 0, 0]
+        [0, z, y, x, 0, ..., 0, 0, 0]
+        [0, 0, z, y, x, ..., 0, 0, 0]
+        ...
+        [0, 0, 0, 0, 0, ..., x, 0, 0]
+        [0, 0, 0, 0, 0, ..., y, x, 0]
+        [0, 0, 0, 0, 0, ..., z, y, x]
+
+    In the 'same' mode, the entries of `A` are given by::
+
+        d = (m - 1) // 2
+        A[i, j] == (a[i-j+d] if (0 <= (i-j+d) < m) else 0)
+
+    The typical application of the 'same' mode is when one has a signal of
+    length `n` (with `n` greater than ``len(a)``), and the desired output
+    is a filtered signal that is still of length `n`.
+
+    For input ``[x, y, z]``, this array looks like::
+
+        [y, x, 0, 0, ..., 0, 0, 0]
+        [z, y, x, 0, ..., 0, 0, 0]
+        [0, z, y, x, ..., 0, 0, 0]
+        [0, 0, z, y, ..., 0, 0, 0]
+        ...
+        [0, 0, 0, 0, ..., y, x, 0]
+        [0, 0, 0, 0, ..., z, y, x]
+        [0, 0, 0, 0, ..., 0, z, y]
+
+    .. versionadded:: 1.5.0
+
+    References
+    ----------
+    .. [1] "Convolution", https://en.wikipedia.org/wiki/Convolution
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy.linalg import convolution_matrix
+    >>> A = convolution_matrix([-1, 4, -2], 5, mode='same')
+    >>> A
+    array([[ 4, -1,  0,  0,  0],
+           [-2,  4, -1,  0,  0],
+           [ 0, -2,  4, -1,  0],
+           [ 0,  0, -2,  4, -1],
+           [ 0,  0,  0, -2,  4]])
+
+    Compare multiplication by `A` with the use of `numpy.convolve`.
+
+    >>> x = np.array([1, 2, 0, -3, 0.5])
+    >>> A @ x
+    array([  2. ,   6. ,  -1. , -12.5,   8. ])
+
+    Verify that ``A @ x`` produced the same result as applying the
+    convolution function.
+
+    >>> np.convolve([-1, 4, -2], x, mode='same')
+    array([  2. ,   6. ,  -1. , -12.5,   8. ])
+
+    For comparison to the case ``mode='same'`` shown above, here are the
+    matrices produced by ``mode='full'`` and ``mode='valid'`` for the
+    same coefficients and size.
+
+    >>> convolution_matrix([-1, 4, -2], 5, mode='full')
+    array([[-1,  0,  0,  0,  0],
+           [ 4, -1,  0,  0,  0],
+           [-2,  4, -1,  0,  0],
+           [ 0, -2,  4, -1,  0],
+           [ 0,  0, -2,  4, -1],
+           [ 0,  0,  0, -2,  4],
+           [ 0,  0,  0,  0, -2]])
+
+    >>> convolution_matrix([-1, 4, -2], 5, mode='valid')
+    array([[-2,  4, -1,  0,  0],
+           [ 0, -2,  4, -1,  0],
+           [ 0,  0, -2,  4, -1]])
+    """
+    if n <= 0:
+        raise ValueError('n must be a positive integer.')
+
+    a = np.asarray(a)
+
+    if a.size == 0:
+        raise ValueError('len(a) must be at least 1.')
+
+    if mode not in ('full', 'valid', 'same'):
+        raise ValueError(
+            "'mode' argument must be one of ('full', 'valid', 'same')")
+
+    if a.ndim > 1:
+        return np.apply_along_axis(lambda a: convolution_matrix(a, n, mode), -1, a)
+
+    # create zero padded versions of the array
+    az = np.pad(a, (0, n-1), 'constant')
+    raz = np.pad(a[::-1], (0, n-1), 'constant')
+
+    if mode == 'same':
+        trim = min(n, len(a)) - 1
+        tb = trim//2
+        te = trim - tb
+        col0 = az[tb:len(az)-te]
+        row0 = raz[-n-tb:len(raz)-tb]
+    elif mode == 'valid':
+        tb = min(n, len(a)) - 1
+        te = tb
+        col0 = az[tb:len(az)-te]
+        row0 = raz[-n-tb:len(raz)-tb]
+    else:  # 'full'
+        col0 = az
+        row0 = raz[-n:]
+    return toeplitz(col0, row0)
diff --git a/.venv/lib/python3.12/site-packages/scipy/linalg/_testutils.py b/.venv/lib/python3.12/site-packages/scipy/linalg/_testutils.py
new file mode 100644
index 0000000000000000000000000000000000000000..b8c83d707256462657c26fc852aefba7ea515789
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/linalg/_testutils.py
@@ -0,0 +1,73 @@
+import numpy as np
+
+
+class _FakeMatrix:
+    def __init__(self, data):
+        self._data = data
+        self.__array_interface__ = data.__array_interface__
+
+    @property
+    def shape(self):
+        return self._data.shape
+
+
+class _FakeMatrix2:
+    def __init__(self, data):
+        self._data = data
+
+    def __array__(self, dtype=None, copy=None):
+        if copy:
+            return self._data.copy()
+        return self._data
+
+    @property
+    def shape(self):
+        return self._data.shape
+
+
+def _get_array(shape, dtype):
+    """
+    Get a test array of given shape and data type.
+    Returned NxN matrices are posdef, and 2xN are banded-posdef.
+
+    """
+    if len(shape) == 2 and shape[0] == 2:
+        # yield a banded positive definite one
+        x = np.zeros(shape, dtype=dtype)
+        x[0, 1:] = -1
+        x[1] = 2
+        return x
+    elif len(shape) == 2 and shape[0] == shape[1]:
+        # always yield a positive definite matrix
+        x = np.zeros(shape, dtype=dtype)
+        j = np.arange(shape[0])
+        x[j, j] = 2
+        x[j[:-1], j[:-1]+1] = -1
+        x[j[:-1]+1, j[:-1]] = -1
+        return x
+    else:
+        np.random.seed(1234)
+        return np.random.randn(*shape).astype(dtype)
+
+
+def _id(x):
+    return x
+
+
+def assert_no_overwrite(call, shapes, dtypes=None):
+    """
+    Test that a call does not overwrite its input arguments
+    """
+
+    if dtypes is None:
+        dtypes = [np.float32, np.float64, np.complex64, np.complex128]
+
+    for dtype in dtypes:
+        for order in ["C", "F"]:
+            for faker in [_id, _FakeMatrix, _FakeMatrix2]:
+                orig_inputs = [_get_array(s, dtype) for s in shapes]
+                inputs = [faker(x.copy(order)) for x in orig_inputs]
+                call(*inputs)
+                msg = f"call modified inputs [{dtype!r}, {faker!r}]"
+                for a, b in zip(inputs, orig_inputs):
+                    np.testing.assert_equal(a, b, err_msg=msg)
diff --git a/.venv/lib/python3.12/site-packages/scipy/linalg/basic.py b/.venv/lib/python3.12/site-packages/scipy/linalg/basic.py
new file mode 100644
index 0000000000000000000000000000000000000000..04ef3645a2ed6a22106ed8ca1acf9e9ac93df5cf
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/linalg/basic.py
@@ -0,0 +1,23 @@
+# This file is not meant for public use and will be removed in SciPy v2.0.0.
+# Use the `scipy.linalg` namespace for importing the functions
+# included below.
+
+from scipy._lib.deprecation import _sub_module_deprecation
+
+
+__all__ = [  # noqa: F822
+    'solve', 'solve_triangular', 'solveh_banded', 'solve_banded',
+    'solve_toeplitz', 'solve_circulant', 'inv', 'det', 'lstsq',
+    'pinv', 'pinvh', 'matrix_balance', 'matmul_toeplitz',
+    'get_lapack_funcs', 'LinAlgError', 'LinAlgWarning',
+]
+
+
+def __dir__():
+    return __all__
+
+
+def __getattr__(name):
+    return _sub_module_deprecation(sub_package="linalg", module="basic",
+                                   private_modules=["_basic"], all=__all__,
+                                   attribute=name)
diff --git a/.venv/lib/python3.12/site-packages/scipy/linalg/blas.py b/.venv/lib/python3.12/site-packages/scipy/linalg/blas.py
new file mode 100644
index 0000000000000000000000000000000000000000..b969553db43f3a20233bdf0274bb47845b7783bc
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/linalg/blas.py
@@ -0,0 +1,531 @@
+"""
+Low-level BLAS functions (:mod:`scipy.linalg.blas`)
+===================================================
+
+This module contains low-level functions from the BLAS library.
+
+.. versionadded:: 0.12.0
+
+.. note::
+
+   The common ``overwrite_<>`` option in many routines, allows the
+   input arrays to be overwritten to avoid extra memory allocation.
+   However this requires the array to satisfy two conditions
+   which are memory order and the data type to match exactly the
+   order and the type expected by the routine.
+
+   As an example, if you pass a double precision float array to any
+   ``S....`` routine which expects single precision arguments, f2py
+   will create an intermediate array to match the argument types and
+   overwriting will be performed on that intermediate array.
+
+   Similarly, if a C-contiguous array is passed, f2py will pass a
+   FORTRAN-contiguous array internally. Please make sure that these
+   details are satisfied. More information can be found in the f2py
+   documentation.
+
+.. warning::
+
+   These functions do little to no error checking.
+   It is possible to cause crashes by mis-using them,
+   so prefer using the higher-level routines in `scipy.linalg`.
+
+.. note::
+
+    Prefer using ``get_blas_funcs`` to importing the bare functions directly.
+    If you do, for example, ``from scipy.linalg.blas import dgemm``, the ``dgemm``
+    function may be either LP64 or ILP64, depending on how SciPy is built.
+
+    The following is more robust:
+
+    >>> from scipy.linalg.blas import get_blas_funcs
+    >>> dgemm = get_blas_funcs('gemm', dtype='float64', ilp64='preferred')
+    >>> dgemm.int_dtype
+    dtype('int32')    # may vary
+
+
+Finding functions
+-----------------
+
+.. autosummary::
+   :toctree: generated/
+
+   get_blas_funcs
+   find_best_blas_type
+
+BLAS Level 1 functions
+----------------------
+
+.. autosummary::
+   :toctree: generated/
+
+   sasum
+   saxpy
+   scasum
+   scnrm2
+   scopy
+   sdot
+   snrm2
+   srot
+   srotg
+   srotm
+   srotmg
+   sscal
+   sswap
+   dasum
+   daxpy
+   dcopy
+   ddot
+   dnrm2
+   drot
+   drotg
+   drotm
+   drotmg
+   dscal
+   dswap
+   dzasum
+   dznrm2
+   icamax
+   idamax
+   isamax
+   izamax
+   caxpy
+   ccopy
+   cdotc
+   cdotu
+   crotg
+   cscal
+   csrot
+   csscal
+   cswap
+   zaxpy
+   zcopy
+   zdotc
+   zdotu
+   zdrot
+   zdscal
+   zrotg
+   zscal
+   zswap
+
+BLAS Level 2 functions
+----------------------
+
+.. autosummary::
+   :toctree: generated/
+
+   sgbmv
+   sgemv
+   sger
+   ssbmv
+   sspmv
+   sspr
+   sspr2
+   ssymv
+   ssyr
+   ssyr2
+   stbmv
+   stbsv
+   stpmv
+   stpsv
+   strmv
+   strsv
+   dgbmv
+   dgemv
+   dger
+   dsbmv
+   dspmv
+   dspr
+   dspr2
+   dsymv
+   dsyr
+   dsyr2
+   dtbmv
+   dtbsv
+   dtpmv
+   dtpsv
+   dtrmv
+   dtrsv
+   cgbmv
+   cgemv
+   cgerc
+   cgeru
+   chbmv
+   chemv
+   cher
+   cher2
+   chpmv
+   chpr
+   chpr2
+   cspmv
+   cspr
+   csyr
+   ctbmv
+   ctbsv
+   ctpmv
+   ctpsv
+   ctrmv
+   ctrsv
+   zgbmv
+   zgemv
+   zgerc
+   zgeru
+   zhbmv
+   zhemv
+   zher
+   zher2
+   zhpmv
+   zhpr
+   zhpr2
+   zspmv
+   zspr
+   zsyr
+   ztbmv
+   ztbsv
+   ztpmv
+   ztpsv
+   ztrmv
+   ztrsv
+
+BLAS Level 3 functions
+----------------------
+
+.. autosummary::
+   :toctree: generated/
+
+   sgemm
+   ssymm
+   ssyr2k
+   ssyrk
+   strmm
+   strsm
+   dgemm
+   dsymm
+   dsyr2k
+   dsyrk
+   dtrmm
+   dtrsm
+   cgemm
+   chemm
+   cher2k
+   cherk
+   csymm
+   csyr2k
+   csyrk
+   ctrmm
+   ctrsm
+   zgemm
+   zhemm
+   zher2k
+   zherk
+   zsymm
+   zsyr2k
+   zsyrk
+   ztrmm
+   ztrsm
+
+"""
+#
+# Author: Pearu Peterson, March 2002
+#         refactoring by Fabian Pedregosa, March 2010
+#
+
+__all__ = ['get_blas_funcs', 'find_best_blas_type']
+
+import numpy as np
+import functools
+from scipy.__config__ import CONFIG
+
+# If `_fblas` was built, it means the Cython BLAS ABI is LP64, and we're then also
+# keeping `linalg.blas` as LP64.
+HAS_LP64 = not bool(CONFIG['Build Dependencies']['blas']['cython blas ilp64'])
+HAS_ILP64 = CONFIG['Build Dependencies']['blas']['has ilp64']
+del CONFIG
+
+_fblas = None
+if HAS_LP64:
+    from scipy.linalg import _fblas
+
+_fblas_64 = None
+if HAS_ILP64:
+    from scipy.linalg import _fblas_64
+
+if not (HAS_LP64 or HAS_ILP64):
+    raise RuntimeError("SciPy needs either LP64 or ILP64 BLAS.")
+
+if HAS_LP64:
+    from scipy.linalg._fblas import *  # noqa: E402, F403
+else:
+    from scipy.linalg._fblas_64 import *  # noqa: E402, F403
+
+# all numeric dtypes '?bBhHiIlLqQefdgFDGO' that are safe to be converted to
+
+# single precision float   : '?bBhH!!!!!!ef!!!!!!'
+# double precision float   : '?bBhHiIlLqQefdg!!!!'
+# single precision complex : '?bBhH!!!!!!ef!!F!!!'
+# double precision complex : '?bBhHiIlLqQefdgFDG!'
+
+_type_score = {x: 1 for x in '?bBhHef'}
+_type_score.update({x: 2 for x in 'iIlLqQd'})
+
+# Handle float128(g) and complex256(G) separately in case non-Windows systems.
+# On Windows, the values will be rewritten to the same key with the same value.
+_type_score.update({'F': 3, 'D': 4, 'g': 2, 'G': 4})
+
+# Final mapping to the actual prefixes and dtypes
+_type_conv = {1: ('s', np.dtype('float32')),
+              2: ('d', np.dtype('float64')),
+              3: ('c', np.dtype('complex64')),
+              4: ('z', np.dtype('complex128'))}
+
+# some convenience alias for complex functions
+_blas_alias = {'cnrm2': 'scnrm2', 'znrm2': 'dznrm2',
+               'cdot': 'cdotc', 'zdot': 'zdotc',
+               'cger': 'cgerc', 'zger': 'zgerc',
+               'sdotc': 'sdot', 'sdotu': 'sdot',
+               'ddotc': 'ddot', 'ddotu': 'ddot'}
+
+
+def find_best_blas_type(arrays=(), dtype=None):
+    """Find best-matching BLAS/LAPACK type.
+
+    Arrays are used to determine the optimal prefix of BLAS routines.
+
+    Parameters
+    ----------
+    arrays : sequence of ndarrays, optional
+        Arrays can be given to determine optimal prefix of BLAS
+        routines. If not given, double-precision routines will be
+        used, otherwise the most generic type in arrays will be used.
+    dtype : str or dtype, optional
+        Data-type specifier. Not used if `arrays` is non-empty.
+
+    Returns
+    -------
+    prefix : str
+        BLAS/LAPACK prefix character.
+    dtype : dtype
+        Inferred Numpy data type.
+    prefer_fortran : bool
+        Whether to prefer Fortran order routines over C order.
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> import scipy.linalg.blas as bla
+    >>> rng = np.random.default_rng()
+    >>> a = rng.random((10,15))
+    >>> b = np.asfortranarray(a)  # Change the memory layout order
+    >>> bla.find_best_blas_type((a,))
+    ('d', dtype('float64'), False)
+    >>> bla.find_best_blas_type((a*1j,))
+    ('z', dtype('complex128'), False)
+    >>> bla.find_best_blas_type((b,))
+    ('d', dtype('float64'), True)
+
+    """
+    dtype = np.dtype(dtype)
+    max_score = _type_score.get(dtype.char, 5)
+    prefer_fortran = False
+
+    if arrays:
+        # In most cases, single element is passed through, quicker route
+        if len(arrays) == 1:
+            max_score = _type_score.get(arrays[0].dtype.char, 5)
+            prefer_fortran = arrays[0].flags['FORTRAN']
+        else:
+            # use the most generic type in arrays
+            scores = [_type_score.get(x.dtype.char, 5) for x in arrays]
+            max_score = max(scores)
+            ind_max_score = scores.index(max_score)
+            # safe upcasting for mix of float64 and complex64 --> prefix 'z'
+            if max_score == 3 and (2 in scores):
+                max_score = 4
+
+            if arrays[ind_max_score].flags['FORTRAN']:
+                # prefer Fortran for leading array with column major order
+                prefer_fortran = True
+
+    # Get the LAPACK prefix and the corresponding dtype if not fall back
+    # to 'd' and double precision float.
+    prefix, dtype = _type_conv.get(max_score, ('d', np.dtype('float64')))
+
+    return prefix, dtype, prefer_fortran
+
+
+def _get_funcs(
+    names, arrays, dtype, lib_name, fmodule, fmodule_name, alias, ilp64="preferred"
+):
+    """
+    Return available BLAS/LAPACK functions.
+
+    Used also in lapack.py. See get_blas_funcs for docstring.
+    """
+
+    funcs = []
+    unpack = False
+    dtype = np.dtype(dtype)
+
+    if isinstance(names, str):
+        names = (names,)
+        unpack = True
+
+    prefix, dtype, _ = find_best_blas_type(arrays, dtype)
+
+    for name in names:
+        func_name = prefix + name
+        func_name = alias.get(func_name, func_name)
+        func = getattr(fmodule, func_name, None)
+        if func is None:
+            raise ValueError(
+                f'{lib_name} function {func_name} could not be found')
+        func.module_name, func.typecode, func.dtype = fmodule_name, prefix, dtype
+        if not ilp64:
+            func.int_dtype = np.dtype(np.intc)
+        else:
+            func.int_dtype = np.dtype(np.int64)
+        func.prefix = prefix  # Backward compatibility
+        funcs.append(func)
+
+    if unpack:
+        return funcs[0]
+    else:
+        return funcs
+
+
+def _memoize_get_funcs(func):
+    """
+    Memoized fast path for _get_funcs instances
+    """
+    memo = {}
+    func.memo = memo
+
+    @functools.wraps(func)
+    def getter(names, arrays=(), dtype=None, ilp64="preferred"):
+        key = (names, dtype, ilp64)
+        for array in arrays:
+            # cf. find_blas_funcs
+            key += (array.dtype.char, array.flags.fortran)
+
+        try:
+            value = memo.get(key)
+        except TypeError:
+            # unhashable key etc.
+            key = None
+            value = None
+
+        if value is not None:
+            return value
+
+        value = func(names, arrays, dtype, ilp64)
+
+        if key is not None:
+            memo[key] = value
+
+        return value
+
+    return getter
+
+
+@_memoize_get_funcs
+def get_blas_funcs(names, arrays=(), dtype=None, ilp64="preferred"):
+    """Return available BLAS function objects from names.
+
+    Arrays are used to determine the optimal prefix of BLAS routines.
+
+    Parameters
+    ----------
+    names : str or sequence of str
+        Name(s) of BLAS functions without type prefix.
+
+    arrays : sequence of ndarrays, optional
+        Arrays can be given to determine optimal prefix of BLAS
+        routines. If not given, double-precision routines will be
+        used, otherwise the most generic type in arrays will be used.
+
+    dtype : str or dtype, optional
+        Data-type specifier. Not used if `arrays` is non-empty.
+
+    ilp64 : {True, False, 'preferred'}, optional
+        Whether to return ILP64 routine variant.
+        Choosing ``'preferred'`` returns ILP64 routine if available,
+        and otherwise the 32-bit (LP64) routine. Default: ``'preferred'``.
+
+    Returns
+    -------
+    funcs : list
+        List containing the found function(s).
+
+    Raises
+    ------
+    RuntimeError
+        If the requested LP64/ILP64 variant is not available.
+
+    See Also
+    --------
+    scipy.linalg.lapack.get_lapack_funcs
+        a similar routine for selecting LAPACK functions.
+
+    Notes
+    -----
+    In BLAS, the naming convention is that all functions start with a
+    type prefix, which depends on the type of the principal
+    matrix. These can be one of ``{'s', 'd', 'c', 'z'}`` for the NumPy
+    types ``{float32, float64, complex64, complex128}`` respectively.
+    The code and the dtype are stored in attributes `typecode` and `dtype`
+    of the returned functions.
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> import scipy.linalg as LA
+    >>> rng = np.random.default_rng()
+    >>> a = rng.random((3, 2))
+    >>> x_gemv = LA.get_blas_funcs('gemv', (a,))
+
+    Note that ``x_gemv`` string representation shows the exact BLAS function with the
+    prefix (here, ``d-`` because ``a`` is double precision real):
+
+    >>> x_gemv
+    
+
+    The BLAS variant information is also available from the ``typecode`` attribute:
+
+    >>> x_gemv.typecode
+    'd'
+
+    For double precision complex arrays, we select the ``z-`` variant, ``zgemv``
+
+    >>> x_gemv = LA.get_blas_funcs('gemv', (a*1j,))
+    >>> x_gemv.typecode
+    'z'
+
+    If you want to select a specific BLAS variant instead of relying on array types, use
+    the ``dtype=`` argument:
+
+    >>> LA.get_blas_funcs('gemv', dtype=np.float32)
+    
+
+    The ``int_dtype`` attribute stores whether the routine is ILP64 (integer arguments
+    and outputs are 64-bit) or LP64 (integer arguments and outputs are 32-bit):
+
+    >>> x_gemv.int_dtype
+    dtype('int32')   # may vary
+    """
+    if isinstance(ilp64, str):
+        if ilp64 == 'preferred':
+            ilp64 = HAS_ILP64
+        else:
+            raise ValueError(f"Invalid value for {ilp64 = }.")
+
+    if not ilp64:
+        return _get_funcs(
+            names, arrays, dtype, "BLAS", _fblas, "fblas", _blas_alias, ilp64=False
+        )
+    else:
+        if not HAS_ILP64:
+            raise RuntimeError("BLAS ILP64 routine requested, but Scipy "
+                               "compiled only with 32-bit BLAS")
+        return _get_funcs(
+            names, arrays, dtype, "BLAS", _fblas_64, "fblas_64", _blas_alias, ilp64=True
+        )
diff --git a/.venv/lib/python3.12/site-packages/scipy/linalg/cython_blas.cpython-312-x86_64-linux-gnu.so b/.venv/lib/python3.12/site-packages/scipy/linalg/cython_blas.cpython-312-x86_64-linux-gnu.so
new file mode 100644
index 0000000000000000000000000000000000000000..d84ae6100905a8310160d2159cd293acb0cbcbe3
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/linalg/cython_blas.cpython-312-x86_64-linux-gnu.so
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:ac79405ae0d508617382a9515cd5c16aeefc331f54757f16a905fde4ddeb89c9
+size 176817
diff --git a/.venv/lib/python3.12/site-packages/scipy/linalg/cython_blas.pxd b/.venv/lib/python3.12/site-packages/scipy/linalg/cython_blas.pxd
new file mode 100644
index 0000000000000000000000000000000000000000..439bd25fcfb34f0d032fc024d074b6c2feb65978
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/linalg/cython_blas.pxd
@@ -0,0 +1,172 @@
+"""
+This file was generated by _generate_pyx.py.
+Do not edit this file directly.
+"""
+
+# Within scipy, these wrappers can be used via relative or absolute cimport.
+# Examples:
+# from ..linalg cimport cython_blas
+# from scipy.linalg cimport cython_blas
+# cimport scipy.linalg.cython_blas as cython_blas
+# cimport ..linalg.cython_blas as cython_blas
+
+# Within SciPy, if BLAS functions are needed in C/C++/Fortran,
+# these wrappers should not be used.
+# The original libraries should be linked directly.
+
+ctypedef float s
+ctypedef double d
+ctypedef float complex c
+ctypedef double complex z
+
+ctypedef int blas_int
+ctypedef bint blas_bint
+
+cdef void caxpy(int *n, c *ca, c *cx, int *incx, c *cy, int *incy) noexcept nogil
+cdef void ccopy(int *n, c *cx, int *incx, c *cy, int *incy) noexcept nogil
+cdef c cdotc(int *n, c *cx, int *incx, c *cy, int *incy) noexcept nogil
+cdef c cdotu(int *n, c *cx, int *incx, c *cy, int *incy) noexcept nogil
+cdef void cgbmv(char *trans, int *m, int *n, int *kl, int *ku, c *alpha, c *a, int *lda, c *x, int *incx, c *beta, c *y, int *incy) noexcept nogil
+cdef void cgemm(char *transa, char *transb, int *m, int *n, int *k, c *alpha, c *a, int *lda, c *b, int *ldb, c *beta, c *c, int *ldc) noexcept nogil
+cdef void cgemv(char *trans, int *m, int *n, c *alpha, c *a, int *lda, c *x, int *incx, c *beta, c *y, int *incy) noexcept nogil
+cdef void cgerc(int *m, int *n, c *alpha, c *x, int *incx, c *y, int *incy, c *a, int *lda) noexcept nogil
+cdef void cgeru(int *m, int *n, c *alpha, c *x, int *incx, c *y, int *incy, c *a, int *lda) noexcept nogil
+cdef void chbmv(char *uplo, int *n, int *k, c *alpha, c *a, int *lda, c *x, int *incx, c *beta, c *y, int *incy) noexcept nogil
+cdef void chemm(char *side, char *uplo, int *m, int *n, c *alpha, c *a, int *lda, c *b, int *ldb, c *beta, c *c, int *ldc) noexcept nogil
+cdef void chemv(char *uplo, int *n, c *alpha, c *a, int *lda, c *x, int *incx, c *beta, c *y, int *incy) noexcept nogil
+cdef void cher(char *uplo, int *n, s *alpha, c *x, int *incx, c *a, int *lda) noexcept nogil
+cdef void cher2(char *uplo, int *n, c *alpha, c *x, int *incx, c *y, int *incy, c *a, int *lda) noexcept nogil
+cdef void cher2k(char *uplo, char *trans, int *n, int *k, c *alpha, c *a, int *lda, c *b, int *ldb, s *beta, c *c, int *ldc) noexcept nogil
+cdef void cherk(char *uplo, char *trans, int *n, int *k, s *alpha, c *a, int *lda, s *beta, c *c, int *ldc) noexcept nogil
+cdef void chpmv(char *uplo, int *n, c *alpha, c *ap, c *x, int *incx, c *beta, c *y, int *incy) noexcept nogil
+cdef void chpr(char *uplo, int *n, s *alpha, c *x, int *incx, c *ap) noexcept nogil
+cdef void chpr2(char *uplo, int *n, c *alpha, c *x, int *incx, c *y, int *incy, c *ap) noexcept nogil
+cdef void crotg(c *ca, c *cb, s *c, c *s) noexcept nogil
+cdef void cscal(int *n, c *ca, c *cx, int *incx) noexcept nogil
+cdef void csrot(int *n, c *cx, int *incx, c *cy, int *incy, s *c, s *s) noexcept nogil
+cdef void csscal(int *n, s *sa, c *cx, int *incx) noexcept nogil
+cdef void cswap(int *n, c *cx, int *incx, c *cy, int *incy) noexcept nogil
+cdef void csymm(char *side, char *uplo, int *m, int *n, c *alpha, c *a, int *lda, c *b, int *ldb, c *beta, c *c, int *ldc) noexcept nogil
+cdef void csyr2k(char *uplo, char *trans, int *n, int *k, c *alpha, c *a, int *lda, c *b, int *ldb, c *beta, c *c, int *ldc) noexcept nogil
+cdef void csyrk(char *uplo, char *trans, int *n, int *k, c *alpha, c *a, int *lda, c *beta, c *c, int *ldc) noexcept nogil
+cdef void ctbmv(char *uplo, char *trans, char *diag, int *n, int *k, c *a, int *lda, c *x, int *incx) noexcept nogil
+cdef void ctbsv(char *uplo, char *trans, char *diag, int *n, int *k, c *a, int *lda, c *x, int *incx) noexcept nogil
+cdef void ctpmv(char *uplo, char *trans, char *diag, int *n, c *ap, c *x, int *incx) noexcept nogil
+cdef void ctpsv(char *uplo, char *trans, char *diag, int *n, c *ap, c *x, int *incx) noexcept nogil
+cdef void ctrmm(char *side, char *uplo, char *transa, char *diag, int *m, int *n, c *alpha, c *a, int *lda, c *b, int *ldb) noexcept nogil
+cdef void ctrmv(char *uplo, char *trans, char *diag, int *n, c *a, int *lda, c *x, int *incx) noexcept nogil
+cdef void ctrsm(char *side, char *uplo, char *transa, char *diag, int *m, int *n, c *alpha, c *a, int *lda, c *b, int *ldb) noexcept nogil
+cdef void ctrsv(char *uplo, char *trans, char *diag, int *n, c *a, int *lda, c *x, int *incx) noexcept nogil
+cdef d dasum(int *n, d *dx, int *incx) noexcept nogil
+cdef void daxpy(int *n, d *da, d *dx, int *incx, d *dy, int *incy) noexcept nogil
+cdef d dcabs1(z *z) noexcept nogil
+cdef void dcopy(int *n, d *dx, int *incx, d *dy, int *incy) noexcept nogil
+cdef d ddot(int *n, d *dx, int *incx, d *dy, int *incy) noexcept nogil
+cdef void dgbmv(char *trans, int *m, int *n, int *kl, int *ku, d *alpha, d *a, int *lda, d *x, int *incx, d *beta, d *y, int *incy) noexcept nogil
+cdef void dgemm(char *transa, char *transb, int *m, int *n, int *k, d *alpha, d *a, int *lda, d *b, int *ldb, d *beta, d *c, int *ldc) noexcept nogil
+cdef void dgemv(char *trans, int *m, int *n, d *alpha, d *a, int *lda, d *x, int *incx, d *beta, d *y, int *incy) noexcept nogil
+cdef void dger(int *m, int *n, d *alpha, d *x, int *incx, d *y, int *incy, d *a, int *lda) noexcept nogil
+cdef d dnrm2(int *n, d *x, int *incx) noexcept nogil
+cdef void drot(int *n, d *dx, int *incx, d *dy, int *incy, d *c, d *s) noexcept nogil
+cdef void drotg(d *da, d *db, d *c, d *s) noexcept nogil
+cdef void drotm(int *n, d *dx, int *incx, d *dy, int *incy, d *dparam) noexcept nogil
+cdef void drotmg(d *dd1, d *dd2, d *dx1, d *dy1, d *dparam) noexcept nogil
+cdef void dsbmv(char *uplo, int *n, int *k, d *alpha, d *a, int *lda, d *x, int *incx, d *beta, d *y, int *incy) noexcept nogil
+cdef void dscal(int *n, d *da, d *dx, int *incx) noexcept nogil
+cdef d dsdot(int *n, s *sx, int *incx, s *sy, int *incy) noexcept nogil
+cdef void dspmv(char *uplo, int *n, d *alpha, d *ap, d *x, int *incx, d *beta, d *y, int *incy) noexcept nogil
+cdef void dspr(char *uplo, int *n, d *alpha, d *x, int *incx, d *ap) noexcept nogil
+cdef void dspr2(char *uplo, int *n, d *alpha, d *x, int *incx, d *y, int *incy, d *ap) noexcept nogil
+cdef void dswap(int *n, d *dx, int *incx, d *dy, int *incy) noexcept nogil
+cdef void dsymm(char *side, char *uplo, int *m, int *n, d *alpha, d *a, int *lda, d *b, int *ldb, d *beta, d *c, int *ldc) noexcept nogil
+cdef void dsymv(char *uplo, int *n, d *alpha, d *a, int *lda, d *x, int *incx, d *beta, d *y, int *incy) noexcept nogil
+cdef void dsyr(char *uplo, int *n, d *alpha, d *x, int *incx, d *a, int *lda) noexcept nogil
+cdef void dsyr2(char *uplo, int *n, d *alpha, d *x, int *incx, d *y, int *incy, d *a, int *lda) noexcept nogil
+cdef void dsyr2k(char *uplo, char *trans, int *n, int *k, d *alpha, d *a, int *lda, d *b, int *ldb, d *beta, d *c, int *ldc) noexcept nogil
+cdef void dsyrk(char *uplo, char *trans, int *n, int *k, d *alpha, d *a, int *lda, d *beta, d *c, int *ldc) noexcept nogil
+cdef void dtbmv(char *uplo, char *trans, char *diag, int *n, int *k, d *a, int *lda, d *x, int *incx) noexcept nogil
+cdef void dtbsv(char *uplo, char *trans, char *diag, int *n, int *k, d *a, int *lda, d *x, int *incx) noexcept nogil
+cdef void dtpmv(char *uplo, char *trans, char *diag, int *n, d *ap, d *x, int *incx) noexcept nogil
+cdef void dtpsv(char *uplo, char *trans, char *diag, int *n, d *ap, d *x, int *incx) noexcept nogil
+cdef void dtrmm(char *side, char *uplo, char *transa, char *diag, int *m, int *n, d *alpha, d *a, int *lda, d *b, int *ldb) noexcept nogil
+cdef void dtrmv(char *uplo, char *trans, char *diag, int *n, d *a, int *lda, d *x, int *incx) noexcept nogil
+cdef void dtrsm(char *side, char *uplo, char *transa, char *diag, int *m, int *n, d *alpha, d *a, int *lda, d *b, int *ldb) noexcept nogil
+cdef void dtrsv(char *uplo, char *trans, char *diag, int *n, d *a, int *lda, d *x, int *incx) noexcept nogil
+cdef d dzasum(int *n, z *zx, int *incx) noexcept nogil
+cdef d dznrm2(int *n, z *x, int *incx) noexcept nogil
+cdef int icamax(int *n, c *cx, int *incx) noexcept nogil
+cdef int idamax(int *n, d *dx, int *incx) noexcept nogil
+cdef int isamax(int *n, s *sx, int *incx) noexcept nogil
+cdef int izamax(int *n, z *zx, int *incx) noexcept nogil
+cdef bint lsame(char *ca, char *cb) noexcept nogil
+cdef s sasum(int *n, s *sx, int *incx) noexcept nogil
+cdef void saxpy(int *n, s *sa, s *sx, int *incx, s *sy, int *incy) noexcept nogil
+cdef s scasum(int *n, c *cx, int *incx) noexcept nogil
+cdef s scnrm2(int *n, c *x, int *incx) noexcept nogil
+cdef void scopy(int *n, s *sx, int *incx, s *sy, int *incy) noexcept nogil
+cdef s sdot(int *n, s *sx, int *incx, s *sy, int *incy) noexcept nogil
+cdef s sdsdot(int *n, s *sb, s *sx, int *incx, s *sy, int *incy) noexcept nogil
+cdef void sgbmv(char *trans, int *m, int *n, int *kl, int *ku, s *alpha, s *a, int *lda, s *x, int *incx, s *beta, s *y, int *incy) noexcept nogil
+cdef void sgemm(char *transa, char *transb, int *m, int *n, int *k, s *alpha, s *a, int *lda, s *b, int *ldb, s *beta, s *c, int *ldc) noexcept nogil
+cdef void sgemv(char *trans, int *m, int *n, s *alpha, s *a, int *lda, s *x, int *incx, s *beta, s *y, int *incy) noexcept nogil
+cdef void sger(int *m, int *n, s *alpha, s *x, int *incx, s *y, int *incy, s *a, int *lda) noexcept nogil
+cdef s snrm2(int *n, s *x, int *incx) noexcept nogil
+cdef void srot(int *n, s *sx, int *incx, s *sy, int *incy, s *c, s *s) noexcept nogil
+cdef void srotg(s *sa, s *sb, s *c, s *s) noexcept nogil
+cdef void srotm(int *n, s *sx, int *incx, s *sy, int *incy, s *sparam) noexcept nogil
+cdef void srotmg(s *sd1, s *sd2, s *sx1, s *sy1, s *sparam) noexcept nogil
+cdef void ssbmv(char *uplo, int *n, int *k, s *alpha, s *a, int *lda, s *x, int *incx, s *beta, s *y, int *incy) noexcept nogil
+cdef void sscal(int *n, s *sa, s *sx, int *incx) noexcept nogil
+cdef void sspmv(char *uplo, int *n, s *alpha, s *ap, s *x, int *incx, s *beta, s *y, int *incy) noexcept nogil
+cdef void sspr(char *uplo, int *n, s *alpha, s *x, int *incx, s *ap) noexcept nogil
+cdef void sspr2(char *uplo, int *n, s *alpha, s *x, int *incx, s *y, int *incy, s *ap) noexcept nogil
+cdef void sswap(int *n, s *sx, int *incx, s *sy, int *incy) noexcept nogil
+cdef void ssymm(char *side, char *uplo, int *m, int *n, s *alpha, s *a, int *lda, s *b, int *ldb, s *beta, s *c, int *ldc) noexcept nogil
+cdef void ssymv(char *uplo, int *n, s *alpha, s *a, int *lda, s *x, int *incx, s *beta, s *y, int *incy) noexcept nogil
+cdef void ssyr(char *uplo, int *n, s *alpha, s *x, int *incx, s *a, int *lda) noexcept nogil
+cdef void ssyr2(char *uplo, int *n, s *alpha, s *x, int *incx, s *y, int *incy, s *a, int *lda) noexcept nogil
+cdef void ssyr2k(char *uplo, char *trans, int *n, int *k, s *alpha, s *a, int *lda, s *b, int *ldb, s *beta, s *c, int *ldc) noexcept nogil
+cdef void ssyrk(char *uplo, char *trans, int *n, int *k, s *alpha, s *a, int *lda, s *beta, s *c, int *ldc) noexcept nogil
+cdef void stbmv(char *uplo, char *trans, char *diag, int *n, int *k, s *a, int *lda, s *x, int *incx) noexcept nogil
+cdef void stbsv(char *uplo, char *trans, char *diag, int *n, int *k, s *a, int *lda, s *x, int *incx) noexcept nogil
+cdef void stpmv(char *uplo, char *trans, char *diag, int *n, s *ap, s *x, int *incx) noexcept nogil
+cdef void stpsv(char *uplo, char *trans, char *diag, int *n, s *ap, s *x, int *incx) noexcept nogil
+cdef void strmm(char *side, char *uplo, char *transa, char *diag, int *m, int *n, s *alpha, s *a, int *lda, s *b, int *ldb) noexcept nogil
+cdef void strmv(char *uplo, char *trans, char *diag, int *n, s *a, int *lda, s *x, int *incx) noexcept nogil
+cdef void strsm(char *side, char *uplo, char *transa, char *diag, int *m, int *n, s *alpha, s *a, int *lda, s *b, int *ldb) noexcept nogil
+cdef void strsv(char *uplo, char *trans, char *diag, int *n, s *a, int *lda, s *x, int *incx) noexcept nogil
+cdef void zaxpy(int *n, z *za, z *zx, int *incx, z *zy, int *incy) noexcept nogil
+cdef void zcopy(int *n, z *zx, int *incx, z *zy, int *incy) noexcept nogil
+cdef z zdotc(int *n, z *zx, int *incx, z *zy, int *incy) noexcept nogil
+cdef z zdotu(int *n, z *zx, int *incx, z *zy, int *incy) noexcept nogil
+cdef void zdrot(int *n, z *cx, int *incx, z *cy, int *incy, d *c, d *s) noexcept nogil
+cdef void zdscal(int *n, d *da, z *zx, int *incx) noexcept nogil
+cdef void zgbmv(char *trans, int *m, int *n, int *kl, int *ku, z *alpha, z *a, int *lda, z *x, int *incx, z *beta, z *y, int *incy) noexcept nogil
+cdef void zgemm(char *transa, char *transb, int *m, int *n, int *k, z *alpha, z *a, int *lda, z *b, int *ldb, z *beta, z *c, int *ldc) noexcept nogil
+cdef void zgemv(char *trans, int *m, int *n, z *alpha, z *a, int *lda, z *x, int *incx, z *beta, z *y, int *incy) noexcept nogil
+cdef void zgerc(int *m, int *n, z *alpha, z *x, int *incx, z *y, int *incy, z *a, int *lda) noexcept nogil
+cdef void zgeru(int *m, int *n, z *alpha, z *x, int *incx, z *y, int *incy, z *a, int *lda) noexcept nogil
+cdef void zhbmv(char *uplo, int *n, int *k, z *alpha, z *a, int *lda, z *x, int *incx, z *beta, z *y, int *incy) noexcept nogil
+cdef void zhemm(char *side, char *uplo, int *m, int *n, z *alpha, z *a, int *lda, z *b, int *ldb, z *beta, z *c, int *ldc) noexcept nogil
+cdef void zhemv(char *uplo, int *n, z *alpha, z *a, int *lda, z *x, int *incx, z *beta, z *y, int *incy) noexcept nogil
+cdef void zher(char *uplo, int *n, d *alpha, z *x, int *incx, z *a, int *lda) noexcept nogil
+cdef void zher2(char *uplo, int *n, z *alpha, z *x, int *incx, z *y, int *incy, z *a, int *lda) noexcept nogil
+cdef void zher2k(char *uplo, char *trans, int *n, int *k, z *alpha, z *a, int *lda, z *b, int *ldb, d *beta, z *c, int *ldc) noexcept nogil
+cdef void zherk(char *uplo, char *trans, int *n, int *k, d *alpha, z *a, int *lda, d *beta, z *c, int *ldc) noexcept nogil
+cdef void zhpmv(char *uplo, int *n, z *alpha, z *ap, z *x, int *incx, z *beta, z *y, int *incy) noexcept nogil
+cdef void zhpr(char *uplo, int *n, d *alpha, z *x, int *incx, z *ap) noexcept nogil
+cdef void zhpr2(char *uplo, int *n, z *alpha, z *x, int *incx, z *y, int *incy, z *ap) noexcept nogil
+cdef void zrotg(z *ca, z *cb, d *c, z *s) noexcept nogil
+cdef void zscal(int *n, z *za, z *zx, int *incx) noexcept nogil
+cdef void zswap(int *n, z *zx, int *incx, z *zy, int *incy) noexcept nogil
+cdef void zsymm(char *side, char *uplo, int *m, int *n, z *alpha, z *a, int *lda, z *b, int *ldb, z *beta, z *c, int *ldc) noexcept nogil
+cdef void zsyr2k(char *uplo, char *trans, int *n, int *k, z *alpha, z *a, int *lda, z *b, int *ldb, z *beta, z *c, int *ldc) noexcept nogil
+cdef void zsyrk(char *uplo, char *trans, int *n, int *k, z *alpha, z *a, int *lda, z *beta, z *c, int *ldc) noexcept nogil
+cdef void ztbmv(char *uplo, char *trans, char *diag, int *n, int *k, z *a, int *lda, z *x, int *incx) noexcept nogil
+cdef void ztbsv(char *uplo, char *trans, char *diag, int *n, int *k, z *a, int *lda, z *x, int *incx) noexcept nogil
+cdef void ztpmv(char *uplo, char *trans, char *diag, int *n, z *ap, z *x, int *incx) noexcept nogil
+cdef void ztpsv(char *uplo, char *trans, char *diag, int *n, z *ap, z *x, int *incx) noexcept nogil
+cdef void ztrmm(char *side, char *uplo, char *transa, char *diag, int *m, int *n, z *alpha, z *a, int *lda, z *b, int *ldb) noexcept nogil
+cdef void ztrmv(char *uplo, char *trans, char *diag, int *n, z *a, int *lda, z *x, int *incx) noexcept nogil
+cdef void ztrsm(char *side, char *uplo, char *transa, char *diag, int *m, int *n, z *alpha, z *a, int *lda, z *b, int *ldb) noexcept nogil
+cdef void ztrsv(char *uplo, char *trans, char *diag, int *n, z *a, int *lda, z *x, int *incx) noexcept nogil
diff --git a/.venv/lib/python3.12/site-packages/scipy/linalg/cython_lapack.cpython-312-x86_64-linux-gnu.so b/.venv/lib/python3.12/site-packages/scipy/linalg/cython_lapack.cpython-312-x86_64-linux-gnu.so
new file mode 100644
index 0000000000000000000000000000000000000000..3179cce6c1284f900c97eb14434453021d473900
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/linalg/cython_lapack.cpython-312-x86_64-linux-gnu.so
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:d710277f4b904741c7d63fcac377f17578356f1f926637ef7ffd2db244d08a53
+size 588937
diff --git a/.venv/lib/python3.12/site-packages/scipy/linalg/cython_lapack.pxd b/.venv/lib/python3.12/site-packages/scipy/linalg/cython_lapack.pxd
new file mode 100644
index 0000000000000000000000000000000000000000..d9971114d0002bc6b1c078b5f354a6728b43a603
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/linalg/cython_lapack.pxd
@@ -0,0 +1,1531 @@
+"""
+This file was generated by _generate_pyx.py.
+Do not edit this file directly.
+"""
+
+# Within SciPy, these wrappers can be used via relative or absolute cimport.
+# Examples:
+# from ..linalg cimport cython_lapack
+# from scipy.linalg cimport cython_lapack
+# cimport scipy.linalg.cython_lapack as cython_lapack
+# cimport ..linalg.cython_lapack as cython_lapack
+
+# Within SciPy, if LAPACK functions are needed in C/C++/Fortran,
+# these wrappers should not be used.
+# The original libraries should be linked directly.
+
+ctypedef float s
+ctypedef double d
+ctypedef float complex c
+ctypedef double complex z
+
+ctypedef int blas_int
+ctypedef bint blas_bint
+
+# Function pointer type declarations for
+# gees and gges families of functions.
+ctypedef int cselect1(c*)
+ctypedef int cselect2(c*, c*)
+ctypedef int dselect2(d*, d*)
+ctypedef int dselect3(d*, d*, d*)
+ctypedef int sselect2(s*, s*)
+ctypedef int sselect3(s*, s*, s*)
+ctypedef int zselect1(z*)
+ctypedef int zselect2(z*, z*)
+
+cdef void cbbcsd(char *jobu1, char *jobu2, char *jobv1t, char *jobv2t, char *trans, int *m, int *p, int *q, s *theta, s *phi, c *u1, int *ldu1, c *u2, int *ldu2, c *v1t, int *ldv1t, c *v2t, int *ldv2t, s *b11d, s *b11e, s *b12d, s *b12e, s *b21d, s *b21e, s *b22d, s *b22e, s *rwork, int *lrwork, int *info) noexcept nogil
+cdef void cbdsqr(char *uplo, int *n, int *ncvt, int *nru, int *ncc, s *d, s *e, c *vt, int *ldvt, c *u, int *ldu, c *c, int *ldc, s *rwork, int *info) noexcept nogil
+cdef void cgbbrd(char *vect, int *m, int *n, int *ncc, int *kl, int *ku, c *ab, int *ldab, s *d, s *e, c *q, int *ldq, c *pt, int *ldpt, c *c, int *ldc, c *work, s *rwork, int *info) noexcept nogil
+cdef void cgbcon(char *norm, int *n, int *kl, int *ku, c *ab, int *ldab, int *ipiv, s *anorm, s *rcond, c *work, s *rwork, int *info) noexcept nogil
+cdef void cgbequ(int *m, int *n, int *kl, int *ku, c *ab, int *ldab, s *r, s *c, s *rowcnd, s *colcnd, s *amax, int *info) noexcept nogil
+cdef void cgbequb(int *m, int *n, int *kl, int *ku, c *ab, int *ldab, s *r, s *c, s *rowcnd, s *colcnd, s *amax, int *info) noexcept nogil
+cdef void cgbrfs(char *trans, int *n, int *kl, int *ku, int *nrhs, c *ab, int *ldab, c *afb, int *ldafb, int *ipiv, c *b, int *ldb, c *x, int *ldx, s *ferr, s *berr, c *work, s *rwork, int *info) noexcept nogil
+cdef void cgbsv(int *n, int *kl, int *ku, int *nrhs, c *ab, int *ldab, int *ipiv, c *b, int *ldb, int *info) noexcept nogil
+cdef void cgbsvx(char *fact, char *trans, int *n, int *kl, int *ku, int *nrhs, c *ab, int *ldab, c *afb, int *ldafb, int *ipiv, char *equed, s *r, s *c, c *b, int *ldb, c *x, int *ldx, s *rcond, s *ferr, s *berr, c *work, s *rwork, int *info) noexcept nogil
+cdef void cgbtf2(int *m, int *n, int *kl, int *ku, c *ab, int *ldab, int *ipiv, int *info) noexcept nogil
+cdef void cgbtrf(int *m, int *n, int *kl, int *ku, c *ab, int *ldab, int *ipiv, int *info) noexcept nogil
+cdef void cgbtrs(char *trans, int *n, int *kl, int *ku, int *nrhs, c *ab, int *ldab, int *ipiv, c *b, int *ldb, int *info) noexcept nogil
+cdef void cgebak(char *job, char *side, int *n, int *ilo, int *ihi, s *scale, int *m, c *v, int *ldv, int *info) noexcept nogil
+cdef void cgebal(char *job, int *n, c *a, int *lda, int *ilo, int *ihi, s *scale, int *info) noexcept nogil
+cdef void cgebd2(int *m, int *n, c *a, int *lda, s *d, s *e, c *tauq, c *taup, c *work, int *info) noexcept nogil
+cdef void cgebrd(int *m, int *n, c *a, int *lda, s *d, s *e, c *tauq, c *taup, c *work, int *lwork, int *info) noexcept nogil
+cdef void cgecon(char *norm, int *n, c *a, int *lda, s *anorm, s *rcond, c *work, s *rwork, int *info) noexcept nogil
+cdef void cgeequ(int *m, int *n, c *a, int *lda, s *r, s *c, s *rowcnd, s *colcnd, s *amax, int *info) noexcept nogil
+cdef void cgeequb(int *m, int *n, c *a, int *lda, s *r, s *c, s *rowcnd, s *colcnd, s *amax, int *info) noexcept nogil
+cdef void cgees(char *jobvs, char *sort, cselect1 *select, int *n, c *a, int *lda, int *sdim, c *w, c *vs, int *ldvs, c *work, int *lwork, s *rwork, bint *bwork, int *info) noexcept nogil
+cdef void cgeesx(char *jobvs, char *sort, cselect1 *select, char *sense, int *n, c *a, int *lda, int *sdim, c *w, c *vs, int *ldvs, s *rconde, s *rcondv, c *work, int *lwork, s *rwork, bint *bwork, int *info) noexcept nogil
+cdef void cgeev(char *jobvl, char *jobvr, int *n, c *a, int *lda, c *w, c *vl, int *ldvl, c *vr, int *ldvr, c *work, int *lwork, s *rwork, int *info) noexcept nogil
+cdef void cgeevx(char *balanc, char *jobvl, char *jobvr, char *sense, int *n, c *a, int *lda, c *w, c *vl, int *ldvl, c *vr, int *ldvr, int *ilo, int *ihi, s *scale, s *abnrm, s *rconde, s *rcondv, c *work, int *lwork, s *rwork, int *info) noexcept nogil
+cdef void cgehd2(int *n, int *ilo, int *ihi, c *a, int *lda, c *tau, c *work, int *info) noexcept nogil
+cdef void cgehrd(int *n, int *ilo, int *ihi, c *a, int *lda, c *tau, c *work, int *lwork, int *info) noexcept nogil
+cdef void cgelq2(int *m, int *n, c *a, int *lda, c *tau, c *work, int *info) noexcept nogil
+cdef void cgelqf(int *m, int *n, c *a, int *lda, c *tau, c *work, int *lwork, int *info) noexcept nogil
+cdef void cgels(char *trans, int *m, int *n, int *nrhs, c *a, int *lda, c *b, int *ldb, c *work, int *lwork, int *info) noexcept nogil
+cdef void cgelsd(int *m, int *n, int *nrhs, c *a, int *lda, c *b, int *ldb, s *s, s *rcond, int *rank, c *work, int *lwork, s *rwork, int *iwork, int *info) noexcept nogil
+cdef void cgelss(int *m, int *n, int *nrhs, c *a, int *lda, c *b, int *ldb, s *s, s *rcond, int *rank, c *work, int *lwork, s *rwork, int *info) noexcept nogil
+cdef void cgelsy(int *m, int *n, int *nrhs, c *a, int *lda, c *b, int *ldb, int *jpvt, s *rcond, int *rank, c *work, int *lwork, s *rwork, int *info) noexcept nogil
+cdef void cgemqrt(char *side, char *trans, int *m, int *n, int *k, int *nb, c *v, int *ldv, c *t, int *ldt, c *c, int *ldc, c *work, int *info) noexcept nogil
+cdef void cgeql2(int *m, int *n, c *a, int *lda, c *tau, c *work, int *info) noexcept nogil
+cdef void cgeqlf(int *m, int *n, c *a, int *lda, c *tau, c *work, int *lwork, int *info) noexcept nogil
+cdef void cgeqp3(int *m, int *n, c *a, int *lda, int *jpvt, c *tau, c *work, int *lwork, s *rwork, int *info) noexcept nogil
+cdef void cgeqr2(int *m, int *n, c *a, int *lda, c *tau, c *work, int *info) noexcept nogil
+cdef void cgeqr2p(int *m, int *n, c *a, int *lda, c *tau, c *work, int *info) noexcept nogil
+cdef void cgeqrf(int *m, int *n, c *a, int *lda, c *tau, c *work, int *lwork, int *info) noexcept nogil
+cdef void cgeqrfp(int *m, int *n, c *a, int *lda, c *tau, c *work, int *lwork, int *info) noexcept nogil
+cdef void cgeqrt(int *m, int *n, int *nb, c *a, int *lda, c *t, int *ldt, c *work, int *info) noexcept nogil
+cdef void cgeqrt2(int *m, int *n, c *a, int *lda, c *t, int *ldt, int *info) noexcept nogil
+cdef void cgeqrt3(int *m, int *n, c *a, int *lda, c *t, int *ldt, int *info) noexcept nogil
+cdef void cgerfs(char *trans, int *n, int *nrhs, c *a, int *lda, c *af, int *ldaf, int *ipiv, c *b, int *ldb, c *x, int *ldx, s *ferr, s *berr, c *work, s *rwork, int *info) noexcept nogil
+cdef void cgerq2(int *m, int *n, c *a, int *lda, c *tau, c *work, int *info) noexcept nogil
+cdef void cgerqf(int *m, int *n, c *a, int *lda, c *tau, c *work, int *lwork, int *info) noexcept nogil
+cdef void cgesc2(int *n, c *a, int *lda, c *rhs, int *ipiv, int *jpiv, s *scale) noexcept nogil
+cdef void cgesdd(char *jobz, int *m, int *n, c *a, int *lda, s *s, c *u, int *ldu, c *vt, int *ldvt, c *work, int *lwork, s *rwork, int *iwork, int *info) noexcept nogil
+cdef void cgesv(int *n, int *nrhs, c *a, int *lda, int *ipiv, c *b, int *ldb, int *info) noexcept nogil
+cdef void cgesvd(char *jobu, char *jobvt, int *m, int *n, c *a, int *lda, s *s, c *u, int *ldu, c *vt, int *ldvt, c *work, int *lwork, s *rwork, int *info) noexcept nogil
+cdef void cgesvx(char *fact, char *trans, int *n, int *nrhs, c *a, int *lda, c *af, int *ldaf, int *ipiv, char *equed, s *r, s *c, c *b, int *ldb, c *x, int *ldx, s *rcond, s *ferr, s *berr, c *work, s *rwork, int *info) noexcept nogil
+cdef void cgetc2(int *n, c *a, int *lda, int *ipiv, int *jpiv, int *info) noexcept nogil
+cdef void cgetf2(int *m, int *n, c *a, int *lda, int *ipiv, int *info) noexcept nogil
+cdef void cgetrf(int *m, int *n, c *a, int *lda, int *ipiv, int *info) noexcept nogil
+cdef void cgetri(int *n, c *a, int *lda, int *ipiv, c *work, int *lwork, int *info) noexcept nogil
+cdef void cgetrs(char *trans, int *n, int *nrhs, c *a, int *lda, int *ipiv, c *b, int *ldb, int *info) noexcept nogil
+cdef void cggbak(char *job, char *side, int *n, int *ilo, int *ihi, s *lscale, s *rscale, int *m, c *v, int *ldv, int *info) noexcept nogil
+cdef void cggbal(char *job, int *n, c *a, int *lda, c *b, int *ldb, int *ilo, int *ihi, s *lscale, s *rscale, s *work, int *info) noexcept nogil
+cdef void cgges(char *jobvsl, char *jobvsr, char *sort, cselect2 *selctg, int *n, c *a, int *lda, c *b, int *ldb, int *sdim, c *alpha, c *beta, c *vsl, int *ldvsl, c *vsr, int *ldvsr, c *work, int *lwork, s *rwork, bint *bwork, int *info) noexcept nogil
+cdef void cggesx(char *jobvsl, char *jobvsr, char *sort, cselect2 *selctg, char *sense, int *n, c *a, int *lda, c *b, int *ldb, int *sdim, c *alpha, c *beta, c *vsl, int *ldvsl, c *vsr, int *ldvsr, s *rconde, s *rcondv, c *work, int *lwork, s *rwork, int *iwork, int *liwork, bint *bwork, int *info) noexcept nogil
+cdef void cggev(char *jobvl, char *jobvr, int *n, c *a, int *lda, c *b, int *ldb, c *alpha, c *beta, c *vl, int *ldvl, c *vr, int *ldvr, c *work, int *lwork, s *rwork, int *info) noexcept nogil
+cdef void cggevx(char *balanc, char *jobvl, char *jobvr, char *sense, int *n, c *a, int *lda, c *b, int *ldb, c *alpha, c *beta, c *vl, int *ldvl, c *vr, int *ldvr, int *ilo, int *ihi, s *lscale, s *rscale, s *abnrm, s *bbnrm, s *rconde, s *rcondv, c *work, int *lwork, s *rwork, int *iwork, bint *bwork, int *info) noexcept nogil
+cdef void cggglm(int *n, int *m, int *p, c *a, int *lda, c *b, int *ldb, c *d, c *x, c *y, c *work, int *lwork, int *info) noexcept nogil
+cdef void cgghrd(char *compq, char *compz, int *n, int *ilo, int *ihi, c *a, int *lda, c *b, int *ldb, c *q, int *ldq, c *z, int *ldz, int *info) noexcept nogil
+cdef void cgglse(int *m, int *n, int *p, c *a, int *lda, c *b, int *ldb, c *c, c *d, c *x, c *work, int *lwork, int *info) noexcept nogil
+cdef void cggqrf(int *n, int *m, int *p, c *a, int *lda, c *taua, c *b, int *ldb, c *taub, c *work, int *lwork, int *info) noexcept nogil
+cdef void cggrqf(int *m, int *p, int *n, c *a, int *lda, c *taua, c *b, int *ldb, c *taub, c *work, int *lwork, int *info) noexcept nogil
+cdef void cgtcon(char *norm, int *n, c *dl, c *d, c *du, c *du2, int *ipiv, s *anorm, s *rcond, c *work, int *info) noexcept nogil
+cdef void cgtrfs(char *trans, int *n, int *nrhs, c *dl, c *d, c *du, c *dlf, c *df, c *duf, c *du2, int *ipiv, c *b, int *ldb, c *x, int *ldx, s *ferr, s *berr, c *work, s *rwork, int *info) noexcept nogil
+cdef void cgtsv(int *n, int *nrhs, c *dl, c *d, c *du, c *b, int *ldb, int *info) noexcept nogil
+cdef void cgtsvx(char *fact, char *trans, int *n, int *nrhs, c *dl, c *d, c *du, c *dlf, c *df, c *duf, c *du2, int *ipiv, c *b, int *ldb, c *x, int *ldx, s *rcond, s *ferr, s *berr, c *work, s *rwork, int *info) noexcept nogil
+cdef void cgttrf(int *n, c *dl, c *d, c *du, c *du2, int *ipiv, int *info) noexcept nogil
+cdef void cgttrs(char *trans, int *n, int *nrhs, c *dl, c *d, c *du, c *du2, int *ipiv, c *b, int *ldb, int *info) noexcept nogil
+cdef void cgtts2(int *itrans, int *n, int *nrhs, c *dl, c *d, c *du, c *du2, int *ipiv, c *b, int *ldb) noexcept nogil
+cdef void chbev(char *jobz, char *uplo, int *n, int *kd, c *ab, int *ldab, s *w, c *z, int *ldz, c *work, s *rwork, int *info) noexcept nogil
+cdef void chbevd(char *jobz, char *uplo, int *n, int *kd, c *ab, int *ldab, s *w, c *z, int *ldz, c *work, int *lwork, s *rwork, int *lrwork, int *iwork, int *liwork, int *info) noexcept nogil
+cdef void chbevx(char *jobz, char *range, char *uplo, int *n, int *kd, c *ab, int *ldab, c *q, int *ldq, s *vl, s *vu, int *il, int *iu, s *abstol, int *m, s *w, c *z, int *ldz, c *work, s *rwork, int *iwork, int *ifail, int *info) noexcept nogil
+cdef void chbgst(char *vect, char *uplo, int *n, int *ka, int *kb, c *ab, int *ldab, c *bb, int *ldbb, c *x, int *ldx, c *work, s *rwork, int *info) noexcept nogil
+cdef void chbgv(char *jobz, char *uplo, int *n, int *ka, int *kb, c *ab, int *ldab, c *bb, int *ldbb, s *w, c *z, int *ldz, c *work, s *rwork, int *info) noexcept nogil
+cdef void chbgvd(char *jobz, char *uplo, int *n, int *ka, int *kb, c *ab, int *ldab, c *bb, int *ldbb, s *w, c *z, int *ldz, c *work, int *lwork, s *rwork, int *lrwork, int *iwork, int *liwork, int *info) noexcept nogil
+cdef void chbgvx(char *jobz, char *range, char *uplo, int *n, int *ka, int *kb, c *ab, int *ldab, c *bb, int *ldbb, c *q, int *ldq, s *vl, s *vu, int *il, int *iu, s *abstol, int *m, s *w, c *z, int *ldz, c *work, s *rwork, int *iwork, int *ifail, int *info) noexcept nogil
+cdef void chbtrd(char *vect, char *uplo, int *n, int *kd, c *ab, int *ldab, s *d, s *e, c *q, int *ldq, c *work, int *info) noexcept nogil
+cdef void checon(char *uplo, int *n, c *a, int *lda, int *ipiv, s *anorm, s *rcond, c *work, int *info) noexcept nogil
+cdef void cheequb(char *uplo, int *n, c *a, int *lda, s *s, s *scond, s *amax, c *work, int *info) noexcept nogil
+cdef void cheev(char *jobz, char *uplo, int *n, c *a, int *lda, s *w, c *work, int *lwork, s *rwork, int *info) noexcept nogil
+cdef void cheevd(char *jobz, char *uplo, int *n, c *a, int *lda, s *w, c *work, int *lwork, s *rwork, int *lrwork, int *iwork, int *liwork, int *info) noexcept nogil
+cdef void cheevr(char *jobz, char *range, char *uplo, int *n, c *a, int *lda, s *vl, s *vu, int *il, int *iu, s *abstol, int *m, s *w, c *z, int *ldz, int *isuppz, c *work, int *lwork, s *rwork, int *lrwork, int *iwork, int *liwork, int *info) noexcept nogil
+cdef void cheevx(char *jobz, char *range, char *uplo, int *n, c *a, int *lda, s *vl, s *vu, int *il, int *iu, s *abstol, int *m, s *w, c *z, int *ldz, c *work, int *lwork, s *rwork, int *iwork, int *ifail, int *info) noexcept nogil
+cdef void chegs2(int *itype, char *uplo, int *n, c *a, int *lda, c *b, int *ldb, int *info) noexcept nogil
+cdef void chegst(int *itype, char *uplo, int *n, c *a, int *lda, c *b, int *ldb, int *info) noexcept nogil
+cdef void chegv(int *itype, char *jobz, char *uplo, int *n, c *a, int *lda, c *b, int *ldb, s *w, c *work, int *lwork, s *rwork, int *info) noexcept nogil
+cdef void chegvd(int *itype, char *jobz, char *uplo, int *n, c *a, int *lda, c *b, int *ldb, s *w, c *work, int *lwork, s *rwork, int *lrwork, int *iwork, int *liwork, int *info) noexcept nogil
+cdef void chegvx(int *itype, char *jobz, char *range, char *uplo, int *n, c *a, int *lda, c *b, int *ldb, s *vl, s *vu, int *il, int *iu, s *abstol, int *m, s *w, c *z, int *ldz, c *work, int *lwork, s *rwork, int *iwork, int *ifail, int *info) noexcept nogil
+cdef void cherfs(char *uplo, int *n, int *nrhs, c *a, int *lda, c *af, int *ldaf, int *ipiv, c *b, int *ldb, c *x, int *ldx, s *ferr, s *berr, c *work, s *rwork, int *info) noexcept nogil
+cdef void chesv(char *uplo, int *n, int *nrhs, c *a, int *lda, int *ipiv, c *b, int *ldb, c *work, int *lwork, int *info) noexcept nogil
+cdef void chesvx(char *fact, char *uplo, int *n, int *nrhs, c *a, int *lda, c *af, int *ldaf, int *ipiv, c *b, int *ldb, c *x, int *ldx, s *rcond, s *ferr, s *berr, c *work, int *lwork, s *rwork, int *info) noexcept nogil
+cdef void cheswapr(char *uplo, int *n, c *a, int *lda, int *i1, int *i2) noexcept nogil
+cdef void chetd2(char *uplo, int *n, c *a, int *lda, s *d, s *e, c *tau, int *info) noexcept nogil
+cdef void chetf2(char *uplo, int *n, c *a, int *lda, int *ipiv, int *info) noexcept nogil
+cdef void chetrd(char *uplo, int *n, c *a, int *lda, s *d, s *e, c *tau, c *work, int *lwork, int *info) noexcept nogil
+cdef void chetrf(char *uplo, int *n, c *a, int *lda, int *ipiv, c *work, int *lwork, int *info) noexcept nogil
+cdef void chetri(char *uplo, int *n, c *a, int *lda, int *ipiv, c *work, int *info) noexcept nogil
+cdef void chetri2(char *uplo, int *n, c *a, int *lda, int *ipiv, c *work, int *lwork, int *info) noexcept nogil
+cdef void chetri2x(char *uplo, int *n, c *a, int *lda, int *ipiv, c *work, int *nb, int *info) noexcept nogil
+cdef void chetrs(char *uplo, int *n, int *nrhs, c *a, int *lda, int *ipiv, c *b, int *ldb, int *info) noexcept nogil
+cdef void chetrs2(char *uplo, int *n, int *nrhs, c *a, int *lda, int *ipiv, c *b, int *ldb, c *work, int *info) noexcept nogil
+cdef void chfrk(char *transr, char *uplo, char *trans, int *n, int *k, s *alpha, c *a, int *lda, s *beta, c *c) noexcept nogil
+cdef void chgeqz(char *job, char *compq, char *compz, int *n, int *ilo, int *ihi, c *h, int *ldh, c *t, int *ldt, c *alpha, c *beta, c *q, int *ldq, c *z, int *ldz, c *work, int *lwork, s *rwork, int *info) noexcept nogil
+cdef char chla_transtype(int *trans) noexcept nogil
+cdef void chpcon(char *uplo, int *n, c *ap, int *ipiv, s *anorm, s *rcond, c *work, int *info) noexcept nogil
+cdef void chpev(char *jobz, char *uplo, int *n, c *ap, s *w, c *z, int *ldz, c *work, s *rwork, int *info) noexcept nogil
+cdef void chpevd(char *jobz, char *uplo, int *n, c *ap, s *w, c *z, int *ldz, c *work, int *lwork, s *rwork, int *lrwork, int *iwork, int *liwork, int *info) noexcept nogil
+cdef void chpevx(char *jobz, char *range, char *uplo, int *n, c *ap, s *vl, s *vu, int *il, int *iu, s *abstol, int *m, s *w, c *z, int *ldz, c *work, s *rwork, int *iwork, int *ifail, int *info) noexcept nogil
+cdef void chpgst(int *itype, char *uplo, int *n, c *ap, c *bp, int *info) noexcept nogil
+cdef void chpgv(int *itype, char *jobz, char *uplo, int *n, c *ap, c *bp, s *w, c *z, int *ldz, c *work, s *rwork, int *info) noexcept nogil
+cdef void chpgvd(int *itype, char *jobz, char *uplo, int *n, c *ap, c *bp, s *w, c *z, int *ldz, c *work, int *lwork, s *rwork, int *lrwork, int *iwork, int *liwork, int *info) noexcept nogil
+cdef void chpgvx(int *itype, char *jobz, char *range, char *uplo, int *n, c *ap, c *bp, s *vl, s *vu, int *il, int *iu, s *abstol, int *m, s *w, c *z, int *ldz, c *work, s *rwork, int *iwork, int *ifail, int *info) noexcept nogil
+cdef void chprfs(char *uplo, int *n, int *nrhs, c *ap, c *afp, int *ipiv, c *b, int *ldb, c *x, int *ldx, s *ferr, s *berr, c *work, s *rwork, int *info) noexcept nogil
+cdef void chpsv(char *uplo, int *n, int *nrhs, c *ap, int *ipiv, c *b, int *ldb, int *info) noexcept nogil
+cdef void chpsvx(char *fact, char *uplo, int *n, int *nrhs, c *ap, c *afp, int *ipiv, c *b, int *ldb, c *x, int *ldx, s *rcond, s *ferr, s *berr, c *work, s *rwork, int *info) noexcept nogil
+cdef void chptrd(char *uplo, int *n, c *ap, s *d, s *e, c *tau, int *info) noexcept nogil
+cdef void chptrf(char *uplo, int *n, c *ap, int *ipiv, int *info) noexcept nogil
+cdef void chptri(char *uplo, int *n, c *ap, int *ipiv, c *work, int *info) noexcept nogil
+cdef void chptrs(char *uplo, int *n, int *nrhs, c *ap, int *ipiv, c *b, int *ldb, int *info) noexcept nogil
+cdef void chsein(char *side, char *eigsrc, char *initv, bint *select, int *n, c *h, int *ldh, c *w, c *vl, int *ldvl, c *vr, int *ldvr, int *mm, int *m, c *work, s *rwork, int *ifaill, int *ifailr, int *info) noexcept nogil
+cdef void chseqr(char *job, char *compz, int *n, int *ilo, int *ihi, c *h, int *ldh, c *w, c *z, int *ldz, c *work, int *lwork, int *info) noexcept nogil
+cdef void clabrd(int *m, int *n, int *nb, c *a, int *lda, s *d, s *e, c *tauq, c *taup, c *x, int *ldx, c *y, int *ldy) noexcept nogil
+cdef void clacgv(int *n, c *x, int *incx) noexcept nogil
+cdef void clacn2(int *n, c *v, c *x, s *est, int *kase, int *isave) noexcept nogil
+cdef void clacon(int *n, c *v, c *x, s *est, int *kase) noexcept nogil
+cdef void clacp2(char *uplo, int *m, int *n, s *a, int *lda, c *b, int *ldb) noexcept nogil
+cdef void clacpy(char *uplo, int *m, int *n, c *a, int *lda, c *b, int *ldb) noexcept nogil
+cdef void clacrm(int *m, int *n, c *a, int *lda, s *b, int *ldb, c *c, int *ldc, s *rwork) noexcept nogil
+cdef void clacrt(int *n, c *cx, int *incx, c *cy, int *incy, c *c, c *s) noexcept nogil
+cdef c cladiv(c *x, c *y) noexcept nogil
+cdef void claed0(int *qsiz, int *n, s *d, s *e, c *q, int *ldq, c *qstore, int *ldqs, s *rwork, int *iwork, int *info) noexcept nogil
+cdef void claed7(int *n, int *cutpnt, int *qsiz, int *tlvls, int *curlvl, int *curpbm, s *d, c *q, int *ldq, s *rho, int *indxq, s *qstore, int *qptr, int *prmptr, int *perm, int *givptr, int *givcol, s *givnum, c *work, s *rwork, int *iwork, int *info) noexcept nogil
+cdef void claed8(int *k, int *n, int *qsiz, c *q, int *ldq, s *d, s *rho, int *cutpnt, s *z, s *dlamda, c *q2, int *ldq2, s *w, int *indxp, int *indx, int *indxq, int *perm, int *givptr, int *givcol, s *givnum, int *info) noexcept nogil
+cdef void claein(bint *rightv, bint *noinit, int *n, c *h, int *ldh, c *w, c *v, c *b, int *ldb, s *rwork, s *eps3, s *smlnum, int *info) noexcept nogil
+cdef void claesy(c *a, c *b, c *c, c *rt1, c *rt2, c *evscal, c *cs1, c *sn1) noexcept nogil
+cdef void claev2(c *a, c *b, c *c, s *rt1, s *rt2, s *cs1, c *sn1) noexcept nogil
+cdef void clag2z(int *m, int *n, c *sa, int *ldsa, z *a, int *lda, int *info) noexcept nogil
+cdef void clags2(bint *upper, s *a1, c *a2, s *a3, s *b1, c *b2, s *b3, s *csu, c *snu, s *csv, c *snv, s *csq, c *snq) noexcept nogil
+cdef void clagtm(char *trans, int *n, int *nrhs, s *alpha, c *dl, c *d, c *du, c *x, int *ldx, s *beta, c *b, int *ldb) noexcept nogil
+cdef void clahef(char *uplo, int *n, int *nb, int *kb, c *a, int *lda, int *ipiv, c *w, int *ldw, int *info) noexcept nogil
+cdef void clahqr(bint *wantt, bint *wantz, int *n, int *ilo, int *ihi, c *h, int *ldh, c *w, int *iloz, int *ihiz, c *z, int *ldz, int *info) noexcept nogil
+cdef void clahr2(int *n, int *k, int *nb, c *a, int *lda, c *tau, c *t, int *ldt, c *y, int *ldy) noexcept nogil
+cdef void claic1(int *job, int *j, c *x, s *sest, c *w, c *gamma, s *sestpr, c *s, c *c) noexcept nogil
+cdef void clals0(int *icompq, int *nl, int *nr, int *sqre, int *nrhs, c *b, int *ldb, c *bx, int *ldbx, int *perm, int *givptr, int *givcol, int *ldgcol, s *givnum, int *ldgnum, s *poles, s *difl, s *difr, s *z, int *k, s *c, s *s, s *rwork, int *info) noexcept nogil
+cdef void clalsa(int *icompq, int *smlsiz, int *n, int *nrhs, c *b, int *ldb, c *bx, int *ldbx, s *u, int *ldu, s *vt, int *k, s *difl, s *difr, s *z, s *poles, int *givptr, int *givcol, int *ldgcol, int *perm, s *givnum, s *c, s *s, s *rwork, int *iwork, int *info) noexcept nogil
+cdef void clalsd(char *uplo, int *smlsiz, int *n, int *nrhs, s *d, s *e, c *b, int *ldb, s *rcond, int *rank, c *work, s *rwork, int *iwork, int *info) noexcept nogil
+cdef s clangb(char *norm, int *n, int *kl, int *ku, c *ab, int *ldab, s *work) noexcept nogil
+cdef s clange(char *norm, int *m, int *n, c *a, int *lda, s *work) noexcept nogil
+cdef s clangt(char *norm, int *n, c *dl, c *d, c *du) noexcept nogil
+cdef s clanhb(char *norm, char *uplo, int *n, int *k, c *ab, int *ldab, s *work) noexcept nogil
+cdef s clanhe(char *norm, char *uplo, int *n, c *a, int *lda, s *work) noexcept nogil
+cdef s clanhf(char *norm, char *transr, char *uplo, int *n, c *a, s *work) noexcept nogil
+cdef s clanhp(char *norm, char *uplo, int *n, c *ap, s *work) noexcept nogil
+cdef s clanhs(char *norm, int *n, c *a, int *lda, s *work) noexcept nogil
+cdef s clanht(char *norm, int *n, s *d, c *e) noexcept nogil
+cdef s clansb(char *norm, char *uplo, int *n, int *k, c *ab, int *ldab, s *work) noexcept nogil
+cdef s clansp(char *norm, char *uplo, int *n, c *ap, s *work) noexcept nogil
+cdef s clansy(char *norm, char *uplo, int *n, c *a, int *lda, s *work) noexcept nogil
+cdef s clantb(char *norm, char *uplo, char *diag, int *n, int *k, c *ab, int *ldab, s *work) noexcept nogil
+cdef s clantp(char *norm, char *uplo, char *diag, int *n, c *ap, s *work) noexcept nogil
+cdef s clantr(char *norm, char *uplo, char *diag, int *m, int *n, c *a, int *lda, s *work) noexcept nogil
+cdef void clapll(int *n, c *x, int *incx, c *y, int *incy, s *ssmin) noexcept nogil
+cdef void clapmr(bint *forwrd, int *m, int *n, c *x, int *ldx, int *k) noexcept nogil
+cdef void clapmt(bint *forwrd, int *m, int *n, c *x, int *ldx, int *k) noexcept nogil
+cdef void claqgb(int *m, int *n, int *kl, int *ku, c *ab, int *ldab, s *r, s *c, s *rowcnd, s *colcnd, s *amax, char *equed) noexcept nogil
+cdef void claqge(int *m, int *n, c *a, int *lda, s *r, s *c, s *rowcnd, s *colcnd, s *amax, char *equed) noexcept nogil
+cdef void claqhb(char *uplo, int *n, int *kd, c *ab, int *ldab, s *s, s *scond, s *amax, char *equed) noexcept nogil
+cdef void claqhe(char *uplo, int *n, c *a, int *lda, s *s, s *scond, s *amax, char *equed) noexcept nogil
+cdef void claqhp(char *uplo, int *n, c *ap, s *s, s *scond, s *amax, char *equed) noexcept nogil
+cdef void claqp2(int *m, int *n, int *offset, c *a, int *lda, int *jpvt, c *tau, s *vn1, s *vn2, c *work) noexcept nogil
+cdef void claqps(int *m, int *n, int *offset, int *nb, int *kb, c *a, int *lda, int *jpvt, c *tau, s *vn1, s *vn2, c *auxv, c *f, int *ldf) noexcept nogil
+cdef void claqr0(bint *wantt, bint *wantz, int *n, int *ilo, int *ihi, c *h, int *ldh, c *w, int *iloz, int *ihiz, c *z, int *ldz, c *work, int *lwork, int *info) noexcept nogil
+cdef void claqr1(int *n, c *h, int *ldh, c *s1, c *s2, c *v) noexcept nogil
+cdef void claqr2(bint *wantt, bint *wantz, int *n, int *ktop, int *kbot, int *nw, c *h, int *ldh, int *iloz, int *ihiz, c *z, int *ldz, int *ns, int *nd, c *sh, c *v, int *ldv, int *nh, c *t, int *ldt, int *nv, c *wv, int *ldwv, c *work, int *lwork) noexcept nogil
+cdef void claqr3(bint *wantt, bint *wantz, int *n, int *ktop, int *kbot, int *nw, c *h, int *ldh, int *iloz, int *ihiz, c *z, int *ldz, int *ns, int *nd, c *sh, c *v, int *ldv, int *nh, c *t, int *ldt, int *nv, c *wv, int *ldwv, c *work, int *lwork) noexcept nogil
+cdef void claqr4(bint *wantt, bint *wantz, int *n, int *ilo, int *ihi, c *h, int *ldh, c *w, int *iloz, int *ihiz, c *z, int *ldz, c *work, int *lwork, int *info) noexcept nogil
+cdef void claqr5(bint *wantt, bint *wantz, int *kacc22, int *n, int *ktop, int *kbot, int *nshfts, c *s, c *h, int *ldh, int *iloz, int *ihiz, c *z, int *ldz, c *v, int *ldv, c *u, int *ldu, int *nv, c *wv, int *ldwv, int *nh, c *wh, int *ldwh) noexcept nogil
+cdef void claqsb(char *uplo, int *n, int *kd, c *ab, int *ldab, s *s, s *scond, s *amax, char *equed) noexcept nogil
+cdef void claqsp(char *uplo, int *n, c *ap, s *s, s *scond, s *amax, char *equed) noexcept nogil
+cdef void claqsy(char *uplo, int *n, c *a, int *lda, s *s, s *scond, s *amax, char *equed) noexcept nogil
+cdef void clar1v(int *n, int *b1, int *bn, s *lambda_, s *d, s *l, s *ld, s *lld, s *pivmin, s *gaptol, c *z, bint *wantnc, int *negcnt, s *ztz, s *mingma, int *r, int *isuppz, s *nrminv, s *resid, s *rqcorr, s *work) noexcept nogil
+cdef void clar2v(int *n, c *x, c *y, c *z, int *incx, s *c, c *s, int *incc) noexcept nogil
+cdef void clarcm(int *m, int *n, s *a, int *lda, c *b, int *ldb, c *c, int *ldc, s *rwork) noexcept nogil
+cdef void clarf(char *side, int *m, int *n, c *v, int *incv, c *tau, c *c, int *ldc, c *work) noexcept nogil
+cdef void clarfb(char *side, char *trans, char *direct, char *storev, int *m, int *n, int *k, c *v, int *ldv, c *t, int *ldt, c *c, int *ldc, c *work, int *ldwork) noexcept nogil
+cdef void clarfg(int *n, c *alpha, c *x, int *incx, c *tau) noexcept nogil
+cdef void clarfgp(int *n, c *alpha, c *x, int *incx, c *tau) noexcept nogil
+cdef void clarft(char *direct, char *storev, int *n, int *k, c *v, int *ldv, c *tau, c *t, int *ldt) noexcept nogil
+cdef void clarfx(char *side, int *m, int *n, c *v, c *tau, c *c, int *ldc, c *work) noexcept nogil
+cdef void clargv(int *n, c *x, int *incx, c *y, int *incy, s *c, int *incc) noexcept nogil
+cdef void clarnv(int *idist, int *iseed, int *n, c *x) noexcept nogil
+cdef void clarrv(int *n, s *vl, s *vu, s *d, s *l, s *pivmin, int *isplit, int *m, int *dol, int *dou, s *minrgp, s *rtol1, s *rtol2, s *w, s *werr, s *wgap, int *iblock, int *indexw, s *gers, c *z, int *ldz, int *isuppz, s *work, int *iwork, int *info) noexcept nogil
+cdef void clartg(c *f, c *g, s *cs, c *sn, c *r) noexcept nogil
+cdef void clartv(int *n, c *x, int *incx, c *y, int *incy, s *c, c *s, int *incc) noexcept nogil
+cdef void clarz(char *side, int *m, int *n, int *l, c *v, int *incv, c *tau, c *c, int *ldc, c *work) noexcept nogil
+cdef void clarzb(char *side, char *trans, char *direct, char *storev, int *m, int *n, int *k, int *l, c *v, int *ldv, c *t, int *ldt, c *c, int *ldc, c *work, int *ldwork) noexcept nogil
+cdef void clarzt(char *direct, char *storev, int *n, int *k, c *v, int *ldv, c *tau, c *t, int *ldt) noexcept nogil
+cdef void clascl(char *type_bn, int *kl, int *ku, s *cfrom, s *cto, int *m, int *n, c *a, int *lda, int *info) noexcept nogil
+cdef void claset(char *uplo, int *m, int *n, c *alpha, c *beta, c *a, int *lda) noexcept nogil
+cdef void clasr(char *side, char *pivot, char *direct, int *m, int *n, s *c, s *s, c *a, int *lda) noexcept nogil
+cdef void classq(int *n, c *x, int *incx, s *scale, s *sumsq) noexcept nogil
+cdef void claswp(int *n, c *a, int *lda, int *k1, int *k2, int *ipiv, int *incx) noexcept nogil
+cdef void clasyf(char *uplo, int *n, int *nb, int *kb, c *a, int *lda, int *ipiv, c *w, int *ldw, int *info) noexcept nogil
+cdef void clatbs(char *uplo, char *trans, char *diag, char *normin, int *n, int *kd, c *ab, int *ldab, c *x, s *scale, s *cnorm, int *info) noexcept nogil
+cdef void clatdf(int *ijob, int *n, c *z, int *ldz, c *rhs, s *rdsum, s *rdscal, int *ipiv, int *jpiv) noexcept nogil
+cdef void clatps(char *uplo, char *trans, char *diag, char *normin, int *n, c *ap, c *x, s *scale, s *cnorm, int *info) noexcept nogil
+cdef void clatrd(char *uplo, int *n, int *nb, c *a, int *lda, s *e, c *tau, c *w, int *ldw) noexcept nogil
+cdef void clatrs(char *uplo, char *trans, char *diag, char *normin, int *n, c *a, int *lda, c *x, s *scale, s *cnorm, int *info) noexcept nogil
+cdef void clatrz(int *m, int *n, int *l, c *a, int *lda, c *tau, c *work) noexcept nogil
+cdef void clauu2(char *uplo, int *n, c *a, int *lda, int *info) noexcept nogil
+cdef void clauum(char *uplo, int *n, c *a, int *lda, int *info) noexcept nogil
+cdef void cpbcon(char *uplo, int *n, int *kd, c *ab, int *ldab, s *anorm, s *rcond, c *work, s *rwork, int *info) noexcept nogil
+cdef void cpbequ(char *uplo, int *n, int *kd, c *ab, int *ldab, s *s, s *scond, s *amax, int *info) noexcept nogil
+cdef void cpbrfs(char *uplo, int *n, int *kd, int *nrhs, c *ab, int *ldab, c *afb, int *ldafb, c *b, int *ldb, c *x, int *ldx, s *ferr, s *berr, c *work, s *rwork, int *info) noexcept nogil
+cdef void cpbstf(char *uplo, int *n, int *kd, c *ab, int *ldab, int *info) noexcept nogil
+cdef void cpbsv(char *uplo, int *n, int *kd, int *nrhs, c *ab, int *ldab, c *b, int *ldb, int *info) noexcept nogil
+cdef void cpbsvx(char *fact, char *uplo, int *n, int *kd, int *nrhs, c *ab, int *ldab, c *afb, int *ldafb, char *equed, s *s, c *b, int *ldb, c *x, int *ldx, s *rcond, s *ferr, s *berr, c *work, s *rwork, int *info) noexcept nogil
+cdef void cpbtf2(char *uplo, int *n, int *kd, c *ab, int *ldab, int *info) noexcept nogil
+cdef void cpbtrf(char *uplo, int *n, int *kd, c *ab, int *ldab, int *info) noexcept nogil
+cdef void cpbtrs(char *uplo, int *n, int *kd, int *nrhs, c *ab, int *ldab, c *b, int *ldb, int *info) noexcept nogil
+cdef void cpftrf(char *transr, char *uplo, int *n, c *a, int *info) noexcept nogil
+cdef void cpftri(char *transr, char *uplo, int *n, c *a, int *info) noexcept nogil
+cdef void cpftrs(char *transr, char *uplo, int *n, int *nrhs, c *a, c *b, int *ldb, int *info) noexcept nogil
+cdef void cpocon(char *uplo, int *n, c *a, int *lda, s *anorm, s *rcond, c *work, s *rwork, int *info) noexcept nogil
+cdef void cpoequ(int *n, c *a, int *lda, s *s, s *scond, s *amax, int *info) noexcept nogil
+cdef void cpoequb(int *n, c *a, int *lda, s *s, s *scond, s *amax, int *info) noexcept nogil
+cdef void cporfs(char *uplo, int *n, int *nrhs, c *a, int *lda, c *af, int *ldaf, c *b, int *ldb, c *x, int *ldx, s *ferr, s *berr, c *work, s *rwork, int *info) noexcept nogil
+cdef void cposv(char *uplo, int *n, int *nrhs, c *a, int *lda, c *b, int *ldb, int *info) noexcept nogil
+cdef void cposvx(char *fact, char *uplo, int *n, int *nrhs, c *a, int *lda, c *af, int *ldaf, char *equed, s *s, c *b, int *ldb, c *x, int *ldx, s *rcond, s *ferr, s *berr, c *work, s *rwork, int *info) noexcept nogil
+cdef void cpotf2(char *uplo, int *n, c *a, int *lda, int *info) noexcept nogil
+cdef void cpotrf(char *uplo, int *n, c *a, int *lda, int *info) noexcept nogil
+cdef void cpotri(char *uplo, int *n, c *a, int *lda, int *info) noexcept nogil
+cdef void cpotrs(char *uplo, int *n, int *nrhs, c *a, int *lda, c *b, int *ldb, int *info) noexcept nogil
+cdef void cppcon(char *uplo, int *n, c *ap, s *anorm, s *rcond, c *work, s *rwork, int *info) noexcept nogil
+cdef void cppequ(char *uplo, int *n, c *ap, s *s, s *scond, s *amax, int *info) noexcept nogil
+cdef void cpprfs(char *uplo, int *n, int *nrhs, c *ap, c *afp, c *b, int *ldb, c *x, int *ldx, s *ferr, s *berr, c *work, s *rwork, int *info) noexcept nogil
+cdef void cppsv(char *uplo, int *n, int *nrhs, c *ap, c *b, int *ldb, int *info) noexcept nogil
+cdef void cppsvx(char *fact, char *uplo, int *n, int *nrhs, c *ap, c *afp, char *equed, s *s, c *b, int *ldb, c *x, int *ldx, s *rcond, s *ferr, s *berr, c *work, s *rwork, int *info) noexcept nogil
+cdef void cpptrf(char *uplo, int *n, c *ap, int *info) noexcept nogil
+cdef void cpptri(char *uplo, int *n, c *ap, int *info) noexcept nogil
+cdef void cpptrs(char *uplo, int *n, int *nrhs, c *ap, c *b, int *ldb, int *info) noexcept nogil
+cdef void cpstf2(char *uplo, int *n, c *a, int *lda, int *piv, int *rank, s *tol, s *work, int *info) noexcept nogil
+cdef void cpstrf(char *uplo, int *n, c *a, int *lda, int *piv, int *rank, s *tol, s *work, int *info) noexcept nogil
+cdef void cptcon(int *n, s *d, c *e, s *anorm, s *rcond, s *rwork, int *info) noexcept nogil
+cdef void cpteqr(char *compz, int *n, s *d, s *e, c *z, int *ldz, s *work, int *info) noexcept nogil
+cdef void cptrfs(char *uplo, int *n, int *nrhs, s *d, c *e, s *df, c *ef, c *b, int *ldb, c *x, int *ldx, s *ferr, s *berr, c *work, s *rwork, int *info) noexcept nogil
+cdef void cptsv(int *n, int *nrhs, s *d, c *e, c *b, int *ldb, int *info) noexcept nogil
+cdef void cptsvx(char *fact, int *n, int *nrhs, s *d, c *e, s *df, c *ef, c *b, int *ldb, c *x, int *ldx, s *rcond, s *ferr, s *berr, c *work, s *rwork, int *info) noexcept nogil
+cdef void cpttrf(int *n, s *d, c *e, int *info) noexcept nogil
+cdef void cpttrs(char *uplo, int *n, int *nrhs, s *d, c *e, c *b, int *ldb, int *info) noexcept nogil
+cdef void cptts2(int *iuplo, int *n, int *nrhs, s *d, c *e, c *b, int *ldb) noexcept nogil
+cdef void crot(int *n, c *cx, int *incx, c *cy, int *incy, s *c, c *s) noexcept nogil
+cdef void cspcon(char *uplo, int *n, c *ap, int *ipiv, s *anorm, s *rcond, c *work, int *info) noexcept nogil
+cdef void cspmv(char *uplo, int *n, c *alpha, c *ap, c *x, int *incx, c *beta, c *y, int *incy) noexcept nogil
+cdef void cspr(char *uplo, int *n, c *alpha, c *x, int *incx, c *ap) noexcept nogil
+cdef void csprfs(char *uplo, int *n, int *nrhs, c *ap, c *afp, int *ipiv, c *b, int *ldb, c *x, int *ldx, s *ferr, s *berr, c *work, s *rwork, int *info) noexcept nogil
+cdef void cspsv(char *uplo, int *n, int *nrhs, c *ap, int *ipiv, c *b, int *ldb, int *info) noexcept nogil
+cdef void cspsvx(char *fact, char *uplo, int *n, int *nrhs, c *ap, c *afp, int *ipiv, c *b, int *ldb, c *x, int *ldx, s *rcond, s *ferr, s *berr, c *work, s *rwork, int *info) noexcept nogil
+cdef void csptrf(char *uplo, int *n, c *ap, int *ipiv, int *info) noexcept nogil
+cdef void csptri(char *uplo, int *n, c *ap, int *ipiv, c *work, int *info) noexcept nogil
+cdef void csptrs(char *uplo, int *n, int *nrhs, c *ap, int *ipiv, c *b, int *ldb, int *info) noexcept nogil
+cdef void csrscl(int *n, s *sa, c *sx, int *incx) noexcept nogil
+cdef void cstedc(char *compz, int *n, s *d, s *e, c *z, int *ldz, c *work, int *lwork, s *rwork, int *lrwork, int *iwork, int *liwork, int *info) noexcept nogil
+cdef void cstegr(char *jobz, char *range, int *n, s *d, s *e, s *vl, s *vu, int *il, int *iu, s *abstol, int *m, s *w, c *z, int *ldz, int *isuppz, s *work, int *lwork, int *iwork, int *liwork, int *info) noexcept nogil
+cdef void cstein(int *n, s *d, s *e, int *m, s *w, int *iblock, int *isplit, c *z, int *ldz, s *work, int *iwork, int *ifail, int *info) noexcept nogil
+cdef void cstemr(char *jobz, char *range, int *n, s *d, s *e, s *vl, s *vu, int *il, int *iu, int *m, s *w, c *z, int *ldz, int *nzc, int *isuppz, bint *tryrac, s *work, int *lwork, int *iwork, int *liwork, int *info) noexcept nogil
+cdef void csteqr(char *compz, int *n, s *d, s *e, c *z, int *ldz, s *work, int *info) noexcept nogil
+cdef void csycon(char *uplo, int *n, c *a, int *lda, int *ipiv, s *anorm, s *rcond, c *work, int *info) noexcept nogil
+cdef void csyconv(char *uplo, char *way, int *n, c *a, int *lda, int *ipiv, c *work, int *info) noexcept nogil
+cdef void csyequb(char *uplo, int *n, c *a, int *lda, s *s, s *scond, s *amax, c *work, int *info) noexcept nogil
+cdef void csymv(char *uplo, int *n, c *alpha, c *a, int *lda, c *x, int *incx, c *beta, c *y, int *incy) noexcept nogil
+cdef void csyr(char *uplo, int *n, c *alpha, c *x, int *incx, c *a, int *lda) noexcept nogil
+cdef void csyrfs(char *uplo, int *n, int *nrhs, c *a, int *lda, c *af, int *ldaf, int *ipiv, c *b, int *ldb, c *x, int *ldx, s *ferr, s *berr, c *work, s *rwork, int *info) noexcept nogil
+cdef void csysv(char *uplo, int *n, int *nrhs, c *a, int *lda, int *ipiv, c *b, int *ldb, c *work, int *lwork, int *info) noexcept nogil
+cdef void csysvx(char *fact, char *uplo, int *n, int *nrhs, c *a, int *lda, c *af, int *ldaf, int *ipiv, c *b, int *ldb, c *x, int *ldx, s *rcond, s *ferr, s *berr, c *work, int *lwork, s *rwork, int *info) noexcept nogil
+cdef void csyswapr(char *uplo, int *n, c *a, int *lda, int *i1, int *i2) noexcept nogil
+cdef void csytf2(char *uplo, int *n, c *a, int *lda, int *ipiv, int *info) noexcept nogil
+cdef void csytrf(char *uplo, int *n, c *a, int *lda, int *ipiv, c *work, int *lwork, int *info) noexcept nogil
+cdef void csytri(char *uplo, int *n, c *a, int *lda, int *ipiv, c *work, int *info) noexcept nogil
+cdef void csytri2(char *uplo, int *n, c *a, int *lda, int *ipiv, c *work, int *lwork, int *info) noexcept nogil
+cdef void csytri2x(char *uplo, int *n, c *a, int *lda, int *ipiv, c *work, int *nb, int *info) noexcept nogil
+cdef void csytrs(char *uplo, int *n, int *nrhs, c *a, int *lda, int *ipiv, c *b, int *ldb, int *info) noexcept nogil
+cdef void csytrs2(char *uplo, int *n, int *nrhs, c *a, int *lda, int *ipiv, c *b, int *ldb, c *work, int *info) noexcept nogil
+cdef void ctbcon(char *norm, char *uplo, char *diag, int *n, int *kd, c *ab, int *ldab, s *rcond, c *work, s *rwork, int *info) noexcept nogil
+cdef void ctbrfs(char *uplo, char *trans, char *diag, int *n, int *kd, int *nrhs, c *ab, int *ldab, c *b, int *ldb, c *x, int *ldx, s *ferr, s *berr, c *work, s *rwork, int *info) noexcept nogil
+cdef void ctbtrs(char *uplo, char *trans, char *diag, int *n, int *kd, int *nrhs, c *ab, int *ldab, c *b, int *ldb, int *info) noexcept nogil
+cdef void ctfsm(char *transr, char *side, char *uplo, char *trans, char *diag, int *m, int *n, c *alpha, c *a, c *b, int *ldb) noexcept nogil
+cdef void ctftri(char *transr, char *uplo, char *diag, int *n, c *a, int *info) noexcept nogil
+cdef void ctfttp(char *transr, char *uplo, int *n, c *arf, c *ap, int *info) noexcept nogil
+cdef void ctfttr(char *transr, char *uplo, int *n, c *arf, c *a, int *lda, int *info) noexcept nogil
+cdef void ctgevc(char *side, char *howmny, bint *select, int *n, c *s, int *lds, c *p, int *ldp, c *vl, int *ldvl, c *vr, int *ldvr, int *mm, int *m, c *work, s *rwork, int *info) noexcept nogil
+cdef void ctgex2(bint *wantq, bint *wantz, int *n, c *a, int *lda, c *b, int *ldb, c *q, int *ldq, c *z, int *ldz, int *j1, int *info) noexcept nogil
+cdef void ctgexc(bint *wantq, bint *wantz, int *n, c *a, int *lda, c *b, int *ldb, c *q, int *ldq, c *z, int *ldz, int *ifst, int *ilst, int *info) noexcept nogil
+cdef void ctgsen(int *ijob, bint *wantq, bint *wantz, bint *select, int *n, c *a, int *lda, c *b, int *ldb, c *alpha, c *beta, c *q, int *ldq, c *z, int *ldz, int *m, s *pl, s *pr, s *dif, c *work, int *lwork, int *iwork, int *liwork, int *info) noexcept nogil
+cdef void ctgsja(char *jobu, char *jobv, char *jobq, int *m, int *p, int *n, int *k, int *l, c *a, int *lda, c *b, int *ldb, s *tola, s *tolb, s *alpha, s *beta, c *u, int *ldu, c *v, int *ldv, c *q, int *ldq, c *work, int *ncycle, int *info) noexcept nogil
+cdef void ctgsna(char *job, char *howmny, bint *select, int *n, c *a, int *lda, c *b, int *ldb, c *vl, int *ldvl, c *vr, int *ldvr, s *s, s *dif, int *mm, int *m, c *work, int *lwork, int *iwork, int *info) noexcept nogil
+cdef void ctgsy2(char *trans, int *ijob, int *m, int *n, c *a, int *lda, c *b, int *ldb, c *c, int *ldc, c *d, int *ldd, c *e, int *lde, c *f, int *ldf, s *scale, s *rdsum, s *rdscal, int *info) noexcept nogil
+cdef void ctgsyl(char *trans, int *ijob, int *m, int *n, c *a, int *lda, c *b, int *ldb, c *c, int *ldc, c *d, int *ldd, c *e, int *lde, c *f, int *ldf, s *scale, s *dif, c *work, int *lwork, int *iwork, int *info) noexcept nogil
+cdef void ctpcon(char *norm, char *uplo, char *diag, int *n, c *ap, s *rcond, c *work, s *rwork, int *info) noexcept nogil
+cdef void ctpmqrt(char *side, char *trans, int *m, int *n, int *k, int *l, int *nb, c *v, int *ldv, c *t, int *ldt, c *a, int *lda, c *b, int *ldb, c *work, int *info) noexcept nogil
+cdef void ctpqrt(int *m, int *n, int *l, int *nb, c *a, int *lda, c *b, int *ldb, c *t, int *ldt, c *work, int *info) noexcept nogil
+cdef void ctpqrt2(int *m, int *n, int *l, c *a, int *lda, c *b, int *ldb, c *t, int *ldt, int *info) noexcept nogil
+cdef void ctprfb(char *side, char *trans, char *direct, char *storev, int *m, int *n, int *k, int *l, c *v, int *ldv, c *t, int *ldt, c *a, int *lda, c *b, int *ldb, c *work, int *ldwork) noexcept nogil
+cdef void ctprfs(char *uplo, char *trans, char *diag, int *n, int *nrhs, c *ap, c *b, int *ldb, c *x, int *ldx, s *ferr, s *berr, c *work, s *rwork, int *info) noexcept nogil
+cdef void ctptri(char *uplo, char *diag, int *n, c *ap, int *info) noexcept nogil
+cdef void ctptrs(char *uplo, char *trans, char *diag, int *n, int *nrhs, c *ap, c *b, int *ldb, int *info) noexcept nogil
+cdef void ctpttf(char *transr, char *uplo, int *n, c *ap, c *arf, int *info) noexcept nogil
+cdef void ctpttr(char *uplo, int *n, c *ap, c *a, int *lda, int *info) noexcept nogil
+cdef void ctrcon(char *norm, char *uplo, char *diag, int *n, c *a, int *lda, s *rcond, c *work, s *rwork, int *info) noexcept nogil
+cdef void ctrevc(char *side, char *howmny, bint *select, int *n, c *t, int *ldt, c *vl, int *ldvl, c *vr, int *ldvr, int *mm, int *m, c *work, s *rwork, int *info) noexcept nogil
+cdef void ctrexc(char *compq, int *n, c *t, int *ldt, c *q, int *ldq, int *ifst, int *ilst, int *info) noexcept nogil
+cdef void ctrrfs(char *uplo, char *trans, char *diag, int *n, int *nrhs, c *a, int *lda, c *b, int *ldb, c *x, int *ldx, s *ferr, s *berr, c *work, s *rwork, int *info) noexcept nogil
+cdef void ctrsen(char *job, char *compq, bint *select, int *n, c *t, int *ldt, c *q, int *ldq, c *w, int *m, s *s, s *sep, c *work, int *lwork, int *info) noexcept nogil
+cdef void ctrsna(char *job, char *howmny, bint *select, int *n, c *t, int *ldt, c *vl, int *ldvl, c *vr, int *ldvr, s *s, s *sep, int *mm, int *m, c *work, int *ldwork, s *rwork, int *info) noexcept nogil
+cdef void ctrsyl(char *trana, char *tranb, int *isgn, int *m, int *n, c *a, int *lda, c *b, int *ldb, c *c, int *ldc, s *scale, int *info) noexcept nogil
+cdef void ctrti2(char *uplo, char *diag, int *n, c *a, int *lda, int *info) noexcept nogil
+cdef void ctrtri(char *uplo, char *diag, int *n, c *a, int *lda, int *info) noexcept nogil
+cdef void ctrtrs(char *uplo, char *trans, char *diag, int *n, int *nrhs, c *a, int *lda, c *b, int *ldb, int *info) noexcept nogil
+cdef void ctrttf(char *transr, char *uplo, int *n, c *a, int *lda, c *arf, int *info) noexcept nogil
+cdef void ctrttp(char *uplo, int *n, c *a, int *lda, c *ap, int *info) noexcept nogil
+cdef void ctzrzf(int *m, int *n, c *a, int *lda, c *tau, c *work, int *lwork, int *info) noexcept nogil
+cdef void cunbdb(char *trans, char *signs, int *m, int *p, int *q, c *x11, int *ldx11, c *x12, int *ldx12, c *x21, int *ldx21, c *x22, int *ldx22, s *theta, s *phi, c *taup1, c *taup2, c *tauq1, c *tauq2, c *work, int *lwork, int *info) noexcept nogil
+cdef void cuncsd(char *jobu1, char *jobu2, char *jobv1t, char *jobv2t, char *trans, char *signs, int *m, int *p, int *q, c *x11, int *ldx11, c *x12, int *ldx12, c *x21, int *ldx21, c *x22, int *ldx22, s *theta, c *u1, int *ldu1, c *u2, int *ldu2, c *v1t, int *ldv1t, c *v2t, int *ldv2t, c *work, int *lwork, s *rwork, int *lrwork, int *iwork, int *info) noexcept nogil
+cdef void cung2l(int *m, int *n, int *k, c *a, int *lda, c *tau, c *work, int *info) noexcept nogil
+cdef void cung2r(int *m, int *n, int *k, c *a, int *lda, c *tau, c *work, int *info) noexcept nogil
+cdef void cungbr(char *vect, int *m, int *n, int *k, c *a, int *lda, c *tau, c *work, int *lwork, int *info) noexcept nogil
+cdef void cunghr(int *n, int *ilo, int *ihi, c *a, int *lda, c *tau, c *work, int *lwork, int *info) noexcept nogil
+cdef void cungl2(int *m, int *n, int *k, c *a, int *lda, c *tau, c *work, int *info) noexcept nogil
+cdef void cunglq(int *m, int *n, int *k, c *a, int *lda, c *tau, c *work, int *lwork, int *info) noexcept nogil
+cdef void cungql(int *m, int *n, int *k, c *a, int *lda, c *tau, c *work, int *lwork, int *info) noexcept nogil
+cdef void cungqr(int *m, int *n, int *k, c *a, int *lda, c *tau, c *work, int *lwork, int *info) noexcept nogil
+cdef void cungr2(int *m, int *n, int *k, c *a, int *lda, c *tau, c *work, int *info) noexcept nogil
+cdef void cungrq(int *m, int *n, int *k, c *a, int *lda, c *tau, c *work, int *lwork, int *info) noexcept nogil
+cdef void cungtr(char *uplo, int *n, c *a, int *lda, c *tau, c *work, int *lwork, int *info) noexcept nogil
+cdef void cunm2l(char *side, char *trans, int *m, int *n, int *k, c *a, int *lda, c *tau, c *c, int *ldc, c *work, int *info) noexcept nogil
+cdef void cunm2r(char *side, char *trans, int *m, int *n, int *k, c *a, int *lda, c *tau, c *c, int *ldc, c *work, int *info) noexcept nogil
+cdef void cunmbr(char *vect, char *side, char *trans, int *m, int *n, int *k, c *a, int *lda, c *tau, c *c, int *ldc, c *work, int *lwork, int *info) noexcept nogil
+cdef void cunmhr(char *side, char *trans, int *m, int *n, int *ilo, int *ihi, c *a, int *lda, c *tau, c *c, int *ldc, c *work, int *lwork, int *info) noexcept nogil
+cdef void cunml2(char *side, char *trans, int *m, int *n, int *k, c *a, int *lda, c *tau, c *c, int *ldc, c *work, int *info) noexcept nogil
+cdef void cunmlq(char *side, char *trans, int *m, int *n, int *k, c *a, int *lda, c *tau, c *c, int *ldc, c *work, int *lwork, int *info) noexcept nogil
+cdef void cunmql(char *side, char *trans, int *m, int *n, int *k, c *a, int *lda, c *tau, c *c, int *ldc, c *work, int *lwork, int *info) noexcept nogil
+cdef void cunmqr(char *side, char *trans, int *m, int *n, int *k, c *a, int *lda, c *tau, c *c, int *ldc, c *work, int *lwork, int *info) noexcept nogil
+cdef void cunmr2(char *side, char *trans, int *m, int *n, int *k, c *a, int *lda, c *tau, c *c, int *ldc, c *work, int *info) noexcept nogil
+cdef void cunmr3(char *side, char *trans, int *m, int *n, int *k, int *l, c *a, int *lda, c *tau, c *c, int *ldc, c *work, int *info) noexcept nogil
+cdef void cunmrq(char *side, char *trans, int *m, int *n, int *k, c *a, int *lda, c *tau, c *c, int *ldc, c *work, int *lwork, int *info) noexcept nogil
+cdef void cunmrz(char *side, char *trans, int *m, int *n, int *k, int *l, c *a, int *lda, c *tau, c *c, int *ldc, c *work, int *lwork, int *info) noexcept nogil
+cdef void cunmtr(char *side, char *uplo, char *trans, int *m, int *n, c *a, int *lda, c *tau, c *c, int *ldc, c *work, int *lwork, int *info) noexcept nogil
+cdef void cupgtr(char *uplo, int *n, c *ap, c *tau, c *q, int *ldq, c *work, int *info) noexcept nogil
+cdef void cupmtr(char *side, char *uplo, char *trans, int *m, int *n, c *ap, c *tau, c *c, int *ldc, c *work, int *info) noexcept nogil
+cdef void dbbcsd(char *jobu1, char *jobu2, char *jobv1t, char *jobv2t, char *trans, int *m, int *p, int *q, d *theta, d *phi, d *u1, int *ldu1, d *u2, int *ldu2, d *v1t, int *ldv1t, d *v2t, int *ldv2t, d *b11d, d *b11e, d *b12d, d *b12e, d *b21d, d *b21e, d *b22d, d *b22e, d *work, int *lwork, int *info) noexcept nogil
+cdef void dbdsdc(char *uplo, char *compq, int *n, d *d, d *e, d *u, int *ldu, d *vt, int *ldvt, d *q, int *iq, d *work, int *iwork, int *info) noexcept nogil
+cdef void dbdsqr(char *uplo, int *n, int *ncvt, int *nru, int *ncc, d *d, d *e, d *vt, int *ldvt, d *u, int *ldu, d *c, int *ldc, d *work, int *info) noexcept nogil
+cdef void ddisna(char *job, int *m, int *n, d *d, d *sep, int *info) noexcept nogil
+cdef void dgbbrd(char *vect, int *m, int *n, int *ncc, int *kl, int *ku, d *ab, int *ldab, d *d, d *e, d *q, int *ldq, d *pt, int *ldpt, d *c, int *ldc, d *work, int *info) noexcept nogil
+cdef void dgbcon(char *norm, int *n, int *kl, int *ku, d *ab, int *ldab, int *ipiv, d *anorm, d *rcond, d *work, int *iwork, int *info) noexcept nogil
+cdef void dgbequ(int *m, int *n, int *kl, int *ku, d *ab, int *ldab, d *r, d *c, d *rowcnd, d *colcnd, d *amax, int *info) noexcept nogil
+cdef void dgbequb(int *m, int *n, int *kl, int *ku, d *ab, int *ldab, d *r, d *c, d *rowcnd, d *colcnd, d *amax, int *info) noexcept nogil
+cdef void dgbrfs(char *trans, int *n, int *kl, int *ku, int *nrhs, d *ab, int *ldab, d *afb, int *ldafb, int *ipiv, d *b, int *ldb, d *x, int *ldx, d *ferr, d *berr, d *work, int *iwork, int *info) noexcept nogil
+cdef void dgbsv(int *n, int *kl, int *ku, int *nrhs, d *ab, int *ldab, int *ipiv, d *b, int *ldb, int *info) noexcept nogil
+cdef void dgbsvx(char *fact, char *trans, int *n, int *kl, int *ku, int *nrhs, d *ab, int *ldab, d *afb, int *ldafb, int *ipiv, char *equed, d *r, d *c, d *b, int *ldb, d *x, int *ldx, d *rcond, d *ferr, d *berr, d *work, int *iwork, int *info) noexcept nogil
+cdef void dgbtf2(int *m, int *n, int *kl, int *ku, d *ab, int *ldab, int *ipiv, int *info) noexcept nogil
+cdef void dgbtrf(int *m, int *n, int *kl, int *ku, d *ab, int *ldab, int *ipiv, int *info) noexcept nogil
+cdef void dgbtrs(char *trans, int *n, int *kl, int *ku, int *nrhs, d *ab, int *ldab, int *ipiv, d *b, int *ldb, int *info) noexcept nogil
+cdef void dgebak(char *job, char *side, int *n, int *ilo, int *ihi, d *scale, int *m, d *v, int *ldv, int *info) noexcept nogil
+cdef void dgebal(char *job, int *n, d *a, int *lda, int *ilo, int *ihi, d *scale, int *info) noexcept nogil
+cdef void dgebd2(int *m, int *n, d *a, int *lda, d *d, d *e, d *tauq, d *taup, d *work, int *info) noexcept nogil
+cdef void dgebrd(int *m, int *n, d *a, int *lda, d *d, d *e, d *tauq, d *taup, d *work, int *lwork, int *info) noexcept nogil
+cdef void dgecon(char *norm, int *n, d *a, int *lda, d *anorm, d *rcond, d *work, int *iwork, int *info) noexcept nogil
+cdef void dgeequ(int *m, int *n, d *a, int *lda, d *r, d *c, d *rowcnd, d *colcnd, d *amax, int *info) noexcept nogil
+cdef void dgeequb(int *m, int *n, d *a, int *lda, d *r, d *c, d *rowcnd, d *colcnd, d *amax, int *info) noexcept nogil
+cdef void dgees(char *jobvs, char *sort, dselect2 *select, int *n, d *a, int *lda, int *sdim, d *wr, d *wi, d *vs, int *ldvs, d *work, int *lwork, bint *bwork, int *info) noexcept nogil
+cdef void dgeesx(char *jobvs, char *sort, dselect2 *select, char *sense, int *n, d *a, int *lda, int *sdim, d *wr, d *wi, d *vs, int *ldvs, d *rconde, d *rcondv, d *work, int *lwork, int *iwork, int *liwork, bint *bwork, int *info) noexcept nogil
+cdef void dgeev(char *jobvl, char *jobvr, int *n, d *a, int *lda, d *wr, d *wi, d *vl, int *ldvl, d *vr, int *ldvr, d *work, int *lwork, int *info) noexcept nogil
+cdef void dgeevx(char *balanc, char *jobvl, char *jobvr, char *sense, int *n, d *a, int *lda, d *wr, d *wi, d *vl, int *ldvl, d *vr, int *ldvr, int *ilo, int *ihi, d *scale, d *abnrm, d *rconde, d *rcondv, d *work, int *lwork, int *iwork, int *info) noexcept nogil
+cdef void dgehd2(int *n, int *ilo, int *ihi, d *a, int *lda, d *tau, d *work, int *info) noexcept nogil
+cdef void dgehrd(int *n, int *ilo, int *ihi, d *a, int *lda, d *tau, d *work, int *lwork, int *info) noexcept nogil
+cdef void dgejsv(char *joba, char *jobu, char *jobv, char *jobr, char *jobt, char *jobp, int *m, int *n, d *a, int *lda, d *sva, d *u, int *ldu, d *v, int *ldv, d *work, int *lwork, int *iwork, int *info) noexcept nogil
+cdef void dgelq2(int *m, int *n, d *a, int *lda, d *tau, d *work, int *info) noexcept nogil
+cdef void dgelqf(int *m, int *n, d *a, int *lda, d *tau, d *work, int *lwork, int *info) noexcept nogil
+cdef void dgels(char *trans, int *m, int *n, int *nrhs, d *a, int *lda, d *b, int *ldb, d *work, int *lwork, int *info) noexcept nogil
+cdef void dgelsd(int *m, int *n, int *nrhs, d *a, int *lda, d *b, int *ldb, d *s, d *rcond, int *rank, d *work, int *lwork, int *iwork, int *info) noexcept nogil
+cdef void dgelss(int *m, int *n, int *nrhs, d *a, int *lda, d *b, int *ldb, d *s, d *rcond, int *rank, d *work, int *lwork, int *info) noexcept nogil
+cdef void dgelsy(int *m, int *n, int *nrhs, d *a, int *lda, d *b, int *ldb, int *jpvt, d *rcond, int *rank, d *work, int *lwork, int *info) noexcept nogil
+cdef void dgemqrt(char *side, char *trans, int *m, int *n, int *k, int *nb, d *v, int *ldv, d *t, int *ldt, d *c, int *ldc, d *work, int *info) noexcept nogil
+cdef void dgeql2(int *m, int *n, d *a, int *lda, d *tau, d *work, int *info) noexcept nogil
+cdef void dgeqlf(int *m, int *n, d *a, int *lda, d *tau, d *work, int *lwork, int *info) noexcept nogil
+cdef void dgeqp3(int *m, int *n, d *a, int *lda, int *jpvt, d *tau, d *work, int *lwork, int *info) noexcept nogil
+cdef void dgeqr2(int *m, int *n, d *a, int *lda, d *tau, d *work, int *info) noexcept nogil
+cdef void dgeqr2p(int *m, int *n, d *a, int *lda, d *tau, d *work, int *info) noexcept nogil
+cdef void dgeqrf(int *m, int *n, d *a, int *lda, d *tau, d *work, int *lwork, int *info) noexcept nogil
+cdef void dgeqrfp(int *m, int *n, d *a, int *lda, d *tau, d *work, int *lwork, int *info) noexcept nogil
+cdef void dgeqrt(int *m, int *n, int *nb, d *a, int *lda, d *t, int *ldt, d *work, int *info) noexcept nogil
+cdef void dgeqrt2(int *m, int *n, d *a, int *lda, d *t, int *ldt, int *info) noexcept nogil
+cdef void dgeqrt3(int *m, int *n, d *a, int *lda, d *t, int *ldt, int *info) noexcept nogil
+cdef void dgerfs(char *trans, int *n, int *nrhs, d *a, int *lda, d *af, int *ldaf, int *ipiv, d *b, int *ldb, d *x, int *ldx, d *ferr, d *berr, d *work, int *iwork, int *info) noexcept nogil
+cdef void dgerq2(int *m, int *n, d *a, int *lda, d *tau, d *work, int *info) noexcept nogil
+cdef void dgerqf(int *m, int *n, d *a, int *lda, d *tau, d *work, int *lwork, int *info) noexcept nogil
+cdef void dgesc2(int *n, d *a, int *lda, d *rhs, int *ipiv, int *jpiv, d *scale) noexcept nogil
+cdef void dgesdd(char *jobz, int *m, int *n, d *a, int *lda, d *s, d *u, int *ldu, d *vt, int *ldvt, d *work, int *lwork, int *iwork, int *info) noexcept nogil
+cdef void dgesv(int *n, int *nrhs, d *a, int *lda, int *ipiv, d *b, int *ldb, int *info) noexcept nogil
+cdef void dgesvd(char *jobu, char *jobvt, int *m, int *n, d *a, int *lda, d *s, d *u, int *ldu, d *vt, int *ldvt, d *work, int *lwork, int *info) noexcept nogil
+cdef void dgesvj(char *joba, char *jobu, char *jobv, int *m, int *n, d *a, int *lda, d *sva, int *mv, d *v, int *ldv, d *work, int *lwork, int *info) noexcept nogil
+cdef void dgesvx(char *fact, char *trans, int *n, int *nrhs, d *a, int *lda, d *af, int *ldaf, int *ipiv, char *equed, d *r, d *c, d *b, int *ldb, d *x, int *ldx, d *rcond, d *ferr, d *berr, d *work, int *iwork, int *info) noexcept nogil
+cdef void dgetc2(int *n, d *a, int *lda, int *ipiv, int *jpiv, int *info) noexcept nogil
+cdef void dgetf2(int *m, int *n, d *a, int *lda, int *ipiv, int *info) noexcept nogil
+cdef void dgetrf(int *m, int *n, d *a, int *lda, int *ipiv, int *info) noexcept nogil
+cdef void dgetri(int *n, d *a, int *lda, int *ipiv, d *work, int *lwork, int *info) noexcept nogil
+cdef void dgetrs(char *trans, int *n, int *nrhs, d *a, int *lda, int *ipiv, d *b, int *ldb, int *info) noexcept nogil
+cdef void dggbak(char *job, char *side, int *n, int *ilo, int *ihi, d *lscale, d *rscale, int *m, d *v, int *ldv, int *info) noexcept nogil
+cdef void dggbal(char *job, int *n, d *a, int *lda, d *b, int *ldb, int *ilo, int *ihi, d *lscale, d *rscale, d *work, int *info) noexcept nogil
+cdef void dgges(char *jobvsl, char *jobvsr, char *sort, dselect3 *selctg, int *n, d *a, int *lda, d *b, int *ldb, int *sdim, d *alphar, d *alphai, d *beta, d *vsl, int *ldvsl, d *vsr, int *ldvsr, d *work, int *lwork, bint *bwork, int *info) noexcept nogil
+cdef void dggesx(char *jobvsl, char *jobvsr, char *sort, dselect3 *selctg, char *sense, int *n, d *a, int *lda, d *b, int *ldb, int *sdim, d *alphar, d *alphai, d *beta, d *vsl, int *ldvsl, d *vsr, int *ldvsr, d *rconde, d *rcondv, d *work, int *lwork, int *iwork, int *liwork, bint *bwork, int *info) noexcept nogil
+cdef void dggev(char *jobvl, char *jobvr, int *n, d *a, int *lda, d *b, int *ldb, d *alphar, d *alphai, d *beta, d *vl, int *ldvl, d *vr, int *ldvr, d *work, int *lwork, int *info) noexcept nogil
+cdef void dggevx(char *balanc, char *jobvl, char *jobvr, char *sense, int *n, d *a, int *lda, d *b, int *ldb, d *alphar, d *alphai, d *beta, d *vl, int *ldvl, d *vr, int *ldvr, int *ilo, int *ihi, d *lscale, d *rscale, d *abnrm, d *bbnrm, d *rconde, d *rcondv, d *work, int *lwork, int *iwork, bint *bwork, int *info) noexcept nogil
+cdef void dggglm(int *n, int *m, int *p, d *a, int *lda, d *b, int *ldb, d *d, d *x, d *y, d *work, int *lwork, int *info) noexcept nogil
+cdef void dgghrd(char *compq, char *compz, int *n, int *ilo, int *ihi, d *a, int *lda, d *b, int *ldb, d *q, int *ldq, d *z, int *ldz, int *info) noexcept nogil
+cdef void dgglse(int *m, int *n, int *p, d *a, int *lda, d *b, int *ldb, d *c, d *d, d *x, d *work, int *lwork, int *info) noexcept nogil
+cdef void dggqrf(int *n, int *m, int *p, d *a, int *lda, d *taua, d *b, int *ldb, d *taub, d *work, int *lwork, int *info) noexcept nogil
+cdef void dggrqf(int *m, int *p, int *n, d *a, int *lda, d *taua, d *b, int *ldb, d *taub, d *work, int *lwork, int *info) noexcept nogil
+cdef void dgsvj0(char *jobv, int *m, int *n, d *a, int *lda, d *d, d *sva, int *mv, d *v, int *ldv, d *eps, d *sfmin, d *tol, int *nsweep, d *work, int *lwork, int *info) noexcept nogil
+cdef void dgsvj1(char *jobv, int *m, int *n, int *n1, d *a, int *lda, d *d, d *sva, int *mv, d *v, int *ldv, d *eps, d *sfmin, d *tol, int *nsweep, d *work, int *lwork, int *info) noexcept nogil
+cdef void dgtcon(char *norm, int *n, d *dl, d *d, d *du, d *du2, int *ipiv, d *anorm, d *rcond, d *work, int *iwork, int *info) noexcept nogil
+cdef void dgtrfs(char *trans, int *n, int *nrhs, d *dl, d *d, d *du, d *dlf, d *df, d *duf, d *du2, int *ipiv, d *b, int *ldb, d *x, int *ldx, d *ferr, d *berr, d *work, int *iwork, int *info) noexcept nogil
+cdef void dgtsv(int *n, int *nrhs, d *dl, d *d, d *du, d *b, int *ldb, int *info) noexcept nogil
+cdef void dgtsvx(char *fact, char *trans, int *n, int *nrhs, d *dl, d *d, d *du, d *dlf, d *df, d *duf, d *du2, int *ipiv, d *b, int *ldb, d *x, int *ldx, d *rcond, d *ferr, d *berr, d *work, int *iwork, int *info) noexcept nogil
+cdef void dgttrf(int *n, d *dl, d *d, d *du, d *du2, int *ipiv, int *info) noexcept nogil
+cdef void dgttrs(char *trans, int *n, int *nrhs, d *dl, d *d, d *du, d *du2, int *ipiv, d *b, int *ldb, int *info) noexcept nogil
+cdef void dgtts2(int *itrans, int *n, int *nrhs, d *dl, d *d, d *du, d *du2, int *ipiv, d *b, int *ldb) noexcept nogil
+cdef void dhgeqz(char *job, char *compq, char *compz, int *n, int *ilo, int *ihi, d *h, int *ldh, d *t, int *ldt, d *alphar, d *alphai, d *beta, d *q, int *ldq, d *z, int *ldz, d *work, int *lwork, int *info) noexcept nogil
+cdef void dhsein(char *side, char *eigsrc, char *initv, bint *select, int *n, d *h, int *ldh, d *wr, d *wi, d *vl, int *ldvl, d *vr, int *ldvr, int *mm, int *m, d *work, int *ifaill, int *ifailr, int *info) noexcept nogil
+cdef void dhseqr(char *job, char *compz, int *n, int *ilo, int *ihi, d *h, int *ldh, d *wr, d *wi, d *z, int *ldz, d *work, int *lwork, int *info) noexcept nogil
+cdef bint disnan(d *din) noexcept nogil
+cdef void dlabad(d *small, d *large) noexcept nogil
+cdef void dlabrd(int *m, int *n, int *nb, d *a, int *lda, d *d, d *e, d *tauq, d *taup, d *x, int *ldx, d *y, int *ldy) noexcept nogil
+cdef void dlacn2(int *n, d *v, d *x, int *isgn, d *est, int *kase, int *isave) noexcept nogil
+cdef void dlacon(int *n, d *v, d *x, int *isgn, d *est, int *kase) noexcept nogil
+cdef void dlacpy(char *uplo, int *m, int *n, d *a, int *lda, d *b, int *ldb) noexcept nogil
+cdef void dladiv(d *a, d *b, d *c, d *d, d *p, d *q) noexcept nogil
+cdef void dlae2(d *a, d *b, d *c, d *rt1, d *rt2) noexcept nogil
+cdef void dlaebz(int *ijob, int *nitmax, int *n, int *mmax, int *minp, int *nbmin, d *abstol, d *reltol, d *pivmin, d *d, d *e, d *e2, int *nval, d *ab, d *c, int *mout, int *nab, d *work, int *iwork, int *info) noexcept nogil
+cdef void dlaed0(int *icompq, int *qsiz, int *n, d *d, d *e, d *q, int *ldq, d *qstore, int *ldqs, d *work, int *iwork, int *info) noexcept nogil
+cdef void dlaed1(int *n, d *d, d *q, int *ldq, int *indxq, d *rho, int *cutpnt, d *work, int *iwork, int *info) noexcept nogil
+cdef void dlaed2(int *k, int *n, int *n1, d *d, d *q, int *ldq, int *indxq, d *rho, d *z, d *dlamda, d *w, d *q2, int *indx, int *indxc, int *indxp, int *coltyp, int *info) noexcept nogil
+cdef void dlaed3(int *k, int *n, int *n1, d *d, d *q, int *ldq, d *rho, d *dlamda, d *q2, int *indx, int *ctot, d *w, d *s, int *info) noexcept nogil
+cdef void dlaed4(int *n, int *i, d *d, d *z, d *delta, d *rho, d *dlam, int *info) noexcept nogil
+cdef void dlaed5(int *i, d *d, d *z, d *delta, d *rho, d *dlam) noexcept nogil
+cdef void dlaed6(int *kniter, bint *orgati, d *rho, d *d, d *z, d *finit, d *tau, int *info) noexcept nogil
+cdef void dlaed7(int *icompq, int *n, int *qsiz, int *tlvls, int *curlvl, int *curpbm, d *d, d *q, int *ldq, int *indxq, d *rho, int *cutpnt, d *qstore, int *qptr, int *prmptr, int *perm, int *givptr, int *givcol, d *givnum, d *work, int *iwork, int *info) noexcept nogil
+cdef void dlaed8(int *icompq, int *k, int *n, int *qsiz, d *d, d *q, int *ldq, int *indxq, d *rho, int *cutpnt, d *z, d *dlamda, d *q2, int *ldq2, d *w, int *perm, int *givptr, int *givcol, d *givnum, int *indxp, int *indx, int *info) noexcept nogil
+cdef void dlaed9(int *k, int *kstart, int *kstop, int *n, d *d, d *q, int *ldq, d *rho, d *dlamda, d *w, d *s, int *lds, int *info) noexcept nogil
+cdef void dlaeda(int *n, int *tlvls, int *curlvl, int *curpbm, int *prmptr, int *perm, int *givptr, int *givcol, d *givnum, d *q, int *qptr, d *z, d *ztemp, int *info) noexcept nogil
+cdef void dlaein(bint *rightv, bint *noinit, int *n, d *h, int *ldh, d *wr, d *wi, d *vr, d *vi, d *b, int *ldb, d *work, d *eps3, d *smlnum, d *bignum, int *info) noexcept nogil
+cdef void dlaev2(d *a, d *b, d *c, d *rt1, d *rt2, d *cs1, d *sn1) noexcept nogil
+cdef void dlaexc(bint *wantq, int *n, d *t, int *ldt, d *q, int *ldq, int *j1, int *n1, int *n2, d *work, int *info) noexcept nogil
+cdef void dlag2(d *a, int *lda, d *b, int *ldb, d *safmin, d *scale1, d *scale2, d *wr1, d *wr2, d *wi) noexcept nogil
+cdef void dlag2s(int *m, int *n, d *a, int *lda, s *sa, int *ldsa, int *info) noexcept nogil
+cdef void dlags2(bint *upper, d *a1, d *a2, d *a3, d *b1, d *b2, d *b3, d *csu, d *snu, d *csv, d *snv, d *csq, d *snq) noexcept nogil
+cdef void dlagtf(int *n, d *a, d *lambda_, d *b, d *c, d *tol, d *d, int *in_, int *info) noexcept nogil
+cdef void dlagtm(char *trans, int *n, int *nrhs, d *alpha, d *dl, d *d, d *du, d *x, int *ldx, d *beta, d *b, int *ldb) noexcept nogil
+cdef void dlagts(int *job, int *n, d *a, d *b, d *c, d *d, int *in_, d *y, d *tol, int *info) noexcept nogil
+cdef void dlagv2(d *a, int *lda, d *b, int *ldb, d *alphar, d *alphai, d *beta, d *csl, d *snl, d *csr, d *snr) noexcept nogil
+cdef void dlahqr(bint *wantt, bint *wantz, int *n, int *ilo, int *ihi, d *h, int *ldh, d *wr, d *wi, int *iloz, int *ihiz, d *z, int *ldz, int *info) noexcept nogil
+cdef void dlahr2(int *n, int *k, int *nb, d *a, int *lda, d *tau, d *t, int *ldt, d *y, int *ldy) noexcept nogil
+cdef void dlaic1(int *job, int *j, d *x, d *sest, d *w, d *gamma, d *sestpr, d *s, d *c) noexcept nogil
+cdef void dlaln2(bint *ltrans, int *na, int *nw, d *smin, d *ca, d *a, int *lda, d *d1, d *d2, d *b, int *ldb, d *wr, d *wi, d *x, int *ldx, d *scale, d *xnorm, int *info) noexcept nogil
+cdef void dlals0(int *icompq, int *nl, int *nr, int *sqre, int *nrhs, d *b, int *ldb, d *bx, int *ldbx, int *perm, int *givptr, int *givcol, int *ldgcol, d *givnum, int *ldgnum, d *poles, d *difl, d *difr, d *z, int *k, d *c, d *s, d *work, int *info) noexcept nogil
+cdef void dlalsa(int *icompq, int *smlsiz, int *n, int *nrhs, d *b, int *ldb, d *bx, int *ldbx, d *u, int *ldu, d *vt, int *k, d *difl, d *difr, d *z, d *poles, int *givptr, int *givcol, int *ldgcol, int *perm, d *givnum, d *c, d *s, d *work, int *iwork, int *info) noexcept nogil
+cdef void dlalsd(char *uplo, int *smlsiz, int *n, int *nrhs, d *d, d *e, d *b, int *ldb, d *rcond, int *rank, d *work, int *iwork, int *info) noexcept nogil
+cdef d dlamch(char *cmach) noexcept nogil
+cdef void dlamrg(int *n1, int *n2, d *a, int *dtrd1, int *dtrd2, int *index_bn) noexcept nogil
+cdef int dlaneg(int *n, d *d, d *lld, d *sigma, d *pivmin, int *r) noexcept nogil
+cdef d dlangb(char *norm, int *n, int *kl, int *ku, d *ab, int *ldab, d *work) noexcept nogil
+cdef d dlange(char *norm, int *m, int *n, d *a, int *lda, d *work) noexcept nogil
+cdef d dlangt(char *norm, int *n, d *dl, d *d_, d *du) noexcept nogil
+cdef d dlanhs(char *norm, int *n, d *a, int *lda, d *work) noexcept nogil
+cdef d dlansb(char *norm, char *uplo, int *n, int *k, d *ab, int *ldab, d *work) noexcept nogil
+cdef d dlansf(char *norm, char *transr, char *uplo, int *n, d *a, d *work) noexcept nogil
+cdef d dlansp(char *norm, char *uplo, int *n, d *ap, d *work) noexcept nogil
+cdef d dlanst(char *norm, int *n, d *d_, d *e) noexcept nogil
+cdef d dlansy(char *norm, char *uplo, int *n, d *a, int *lda, d *work) noexcept nogil
+cdef d dlantb(char *norm, char *uplo, char *diag, int *n, int *k, d *ab, int *ldab, d *work) noexcept nogil
+cdef d dlantp(char *norm, char *uplo, char *diag, int *n, d *ap, d *work) noexcept nogil
+cdef d dlantr(char *norm, char *uplo, char *diag, int *m, int *n, d *a, int *lda, d *work) noexcept nogil
+cdef void dlanv2(d *a, d *b, d *c, d *d, d *rt1r, d *rt1i, d *rt2r, d *rt2i, d *cs, d *sn) noexcept nogil
+cdef void dlapll(int *n, d *x, int *incx, d *y, int *incy, d *ssmin) noexcept nogil
+cdef void dlapmr(bint *forwrd, int *m, int *n, d *x, int *ldx, int *k) noexcept nogil
+cdef void dlapmt(bint *forwrd, int *m, int *n, d *x, int *ldx, int *k) noexcept nogil
+cdef d dlapy2(d *x, d *y) noexcept nogil
+cdef d dlapy3(d *x, d *y, d *z) noexcept nogil
+cdef void dlaqgb(int *m, int *n, int *kl, int *ku, d *ab, int *ldab, d *r, d *c, d *rowcnd, d *colcnd, d *amax, char *equed) noexcept nogil
+cdef void dlaqge(int *m, int *n, d *a, int *lda, d *r, d *c, d *rowcnd, d *colcnd, d *amax, char *equed) noexcept nogil
+cdef void dlaqp2(int *m, int *n, int *offset, d *a, int *lda, int *jpvt, d *tau, d *vn1, d *vn2, d *work) noexcept nogil
+cdef void dlaqps(int *m, int *n, int *offset, int *nb, int *kb, d *a, int *lda, int *jpvt, d *tau, d *vn1, d *vn2, d *auxv, d *f, int *ldf) noexcept nogil
+cdef void dlaqr0(bint *wantt, bint *wantz, int *n, int *ilo, int *ihi, d *h, int *ldh, d *wr, d *wi, int *iloz, int *ihiz, d *z, int *ldz, d *work, int *lwork, int *info) noexcept nogil
+cdef void dlaqr1(int *n, d *h, int *ldh, d *sr1, d *si1, d *sr2, d *si2, d *v) noexcept nogil
+cdef void dlaqr2(bint *wantt, bint *wantz, int *n, int *ktop, int *kbot, int *nw, d *h, int *ldh, int *iloz, int *ihiz, d *z, int *ldz, int *ns, int *nd, d *sr, d *si, d *v, int *ldv, int *nh, d *t, int *ldt, int *nv, d *wv, int *ldwv, d *work, int *lwork) noexcept nogil
+cdef void dlaqr3(bint *wantt, bint *wantz, int *n, int *ktop, int *kbot, int *nw, d *h, int *ldh, int *iloz, int *ihiz, d *z, int *ldz, int *ns, int *nd, d *sr, d *si, d *v, int *ldv, int *nh, d *t, int *ldt, int *nv, d *wv, int *ldwv, d *work, int *lwork) noexcept nogil
+cdef void dlaqr4(bint *wantt, bint *wantz, int *n, int *ilo, int *ihi, d *h, int *ldh, d *wr, d *wi, int *iloz, int *ihiz, d *z, int *ldz, d *work, int *lwork, int *info) noexcept nogil
+cdef void dlaqr5(bint *wantt, bint *wantz, int *kacc22, int *n, int *ktop, int *kbot, int *nshfts, d *sr, d *si, d *h, int *ldh, int *iloz, int *ihiz, d *z, int *ldz, d *v, int *ldv, d *u, int *ldu, int *nv, d *wv, int *ldwv, int *nh, d *wh, int *ldwh) noexcept nogil
+cdef void dlaqsb(char *uplo, int *n, int *kd, d *ab, int *ldab, d *s, d *scond, d *amax, char *equed) noexcept nogil
+cdef void dlaqsp(char *uplo, int *n, d *ap, d *s, d *scond, d *amax, char *equed) noexcept nogil
+cdef void dlaqsy(char *uplo, int *n, d *a, int *lda, d *s, d *scond, d *amax, char *equed) noexcept nogil
+cdef void dlaqtr(bint *ltran, bint *lreal, int *n, d *t, int *ldt, d *b, d *w, d *scale, d *x, d *work, int *info) noexcept nogil
+cdef void dlar1v(int *n, int *b1, int *bn, d *lambda_, d *d, d *l, d *ld, d *lld, d *pivmin, d *gaptol, d *z, bint *wantnc, int *negcnt, d *ztz, d *mingma, int *r, int *isuppz, d *nrminv, d *resid, d *rqcorr, d *work) noexcept nogil
+cdef void dlar2v(int *n, d *x, d *y, d *z, int *incx, d *c, d *s, int *incc) noexcept nogil
+cdef void dlarf(char *side, int *m, int *n, d *v, int *incv, d *tau, d *c, int *ldc, d *work) noexcept nogil
+cdef void dlarfb(char *side, char *trans, char *direct, char *storev, int *m, int *n, int *k, d *v, int *ldv, d *t, int *ldt, d *c, int *ldc, d *work, int *ldwork) noexcept nogil
+cdef void dlarfg(int *n, d *alpha, d *x, int *incx, d *tau) noexcept nogil
+cdef void dlarfgp(int *n, d *alpha, d *x, int *incx, d *tau) noexcept nogil
+cdef void dlarft(char *direct, char *storev, int *n, int *k, d *v, int *ldv, d *tau, d *t, int *ldt) noexcept nogil
+cdef void dlarfx(char *side, int *m, int *n, d *v, d *tau, d *c, int *ldc, d *work) noexcept nogil
+cdef void dlargv(int *n, d *x, int *incx, d *y, int *incy, d *c, int *incc) noexcept nogil
+cdef void dlarnv(int *idist, int *iseed, int *n, d *x) noexcept nogil
+cdef void dlarra(int *n, d *d, d *e, d *e2, d *spltol, d *tnrm, int *nsplit, int *isplit, int *info) noexcept nogil
+cdef void dlarrb(int *n, d *d, d *lld, int *ifirst, int *ilast, d *rtol1, d *rtol2, int *offset, d *w, d *wgap, d *werr, d *work, int *iwork, d *pivmin, d *spdiam, int *twist, int *info) noexcept nogil
+cdef void dlarrc(char *jobt, int *n, d *vl, d *vu, d *d, d *e, d *pivmin, int *eigcnt, int *lcnt, int *rcnt, int *info) noexcept nogil
+cdef void dlarrd(char *range, char *order, int *n, d *vl, d *vu, int *il, int *iu, d *gers, d *reltol, d *d, d *e, d *e2, d *pivmin, int *nsplit, int *isplit, int *m, d *w, d *werr, d *wl, d *wu, int *iblock, int *indexw, d *work, int *iwork, int *info) noexcept nogil
+cdef void dlarre(char *range, int *n, d *vl, d *vu, int *il, int *iu, d *d, d *e, d *e2, d *rtol1, d *rtol2, d *spltol, int *nsplit, int *isplit, int *m, d *w, d *werr, d *wgap, int *iblock, int *indexw, d *gers, d *pivmin, d *work, int *iwork, int *info) noexcept nogil
+cdef void dlarrf(int *n, d *d, d *l, d *ld, int *clstrt, int *clend, d *w, d *wgap, d *werr, d *spdiam, d *clgapl, d *clgapr, d *pivmin, d *sigma, d *dplus, d *lplus, d *work, int *info) noexcept nogil
+cdef void dlarrj(int *n, d *d, d *e2, int *ifirst, int *ilast, d *rtol, int *offset, d *w, d *werr, d *work, int *iwork, d *pivmin, d *spdiam, int *info) noexcept nogil
+cdef void dlarrk(int *n, int *iw, d *gl, d *gu, d *d, d *e2, d *pivmin, d *reltol, d *w, d *werr, int *info) noexcept nogil
+cdef void dlarrr(int *n, d *d, d *e, int *info) noexcept nogil
+cdef void dlarrv(int *n, d *vl, d *vu, d *d, d *l, d *pivmin, int *isplit, int *m, int *dol, int *dou, d *minrgp, d *rtol1, d *rtol2, d *w, d *werr, d *wgap, int *iblock, int *indexw, d *gers, d *z, int *ldz, int *isuppz, d *work, int *iwork, int *info) noexcept nogil
+cdef void dlartg(d *f, d *g, d *cs, d *sn, d *r) noexcept nogil
+cdef void dlartgp(d *f, d *g, d *cs, d *sn, d *r) noexcept nogil
+cdef void dlartgs(d *x, d *y, d *sigma, d *cs, d *sn) noexcept nogil
+cdef void dlartv(int *n, d *x, int *incx, d *y, int *incy, d *c, d *s, int *incc) noexcept nogil
+cdef void dlaruv(int *iseed, int *n, d *x) noexcept nogil
+cdef void dlarz(char *side, int *m, int *n, int *l, d *v, int *incv, d *tau, d *c, int *ldc, d *work) noexcept nogil
+cdef void dlarzb(char *side, char *trans, char *direct, char *storev, int *m, int *n, int *k, int *l, d *v, int *ldv, d *t, int *ldt, d *c, int *ldc, d *work, int *ldwork) noexcept nogil
+cdef void dlarzt(char *direct, char *storev, int *n, int *k, d *v, int *ldv, d *tau, d *t, int *ldt) noexcept nogil
+cdef void dlas2(d *f, d *g, d *h, d *ssmin, d *ssmax) noexcept nogil
+cdef void dlascl(char *type_bn, int *kl, int *ku, d *cfrom, d *cto, int *m, int *n, d *a, int *lda, int *info) noexcept nogil
+cdef void dlasd0(int *n, int *sqre, d *d, d *e, d *u, int *ldu, d *vt, int *ldvt, int *smlsiz, int *iwork, d *work, int *info) noexcept nogil
+cdef void dlasd1(int *nl, int *nr, int *sqre, d *d, d *alpha, d *beta, d *u, int *ldu, d *vt, int *ldvt, int *idxq, int *iwork, d *work, int *info) noexcept nogil
+cdef void dlasd2(int *nl, int *nr, int *sqre, int *k, d *d, d *z, d *alpha, d *beta, d *u, int *ldu, d *vt, int *ldvt, d *dsigma, d *u2, int *ldu2, d *vt2, int *ldvt2, int *idxp, int *idx, int *idxc, int *idxq, int *coltyp, int *info) noexcept nogil
+cdef void dlasd3(int *nl, int *nr, int *sqre, int *k, d *d, d *q, int *ldq, d *dsigma, d *u, int *ldu, d *u2, int *ldu2, d *vt, int *ldvt, d *vt2, int *ldvt2, int *idxc, int *ctot, d *z, int *info) noexcept nogil
+cdef void dlasd4(int *n, int *i, d *d, d *z, d *delta, d *rho, d *sigma, d *work, int *info) noexcept nogil
+cdef void dlasd5(int *i, d *d, d *z, d *delta, d *rho, d *dsigma, d *work) noexcept nogil
+cdef void dlasd6(int *icompq, int *nl, int *nr, int *sqre, d *d, d *vf, d *vl, d *alpha, d *beta, int *idxq, int *perm, int *givptr, int *givcol, int *ldgcol, d *givnum, int *ldgnum, d *poles, d *difl, d *difr, d *z, int *k, d *c, d *s, d *work, int *iwork, int *info) noexcept nogil
+cdef void dlasd7(int *icompq, int *nl, int *nr, int *sqre, int *k, d *d, d *z, d *zw, d *vf, d *vfw, d *vl, d *vlw, d *alpha, d *beta, d *dsigma, int *idx, int *idxp, int *idxq, int *perm, int *givptr, int *givcol, int *ldgcol, d *givnum, int *ldgnum, d *c, d *s, int *info) noexcept nogil
+cdef void dlasd8(int *icompq, int *k, d *d, d *z, d *vf, d *vl, d *difl, d *difr, int *lddifr, d *dsigma, d *work, int *info) noexcept nogil
+cdef void dlasda(int *icompq, int *smlsiz, int *n, int *sqre, d *d, d *e, d *u, int *ldu, d *vt, int *k, d *difl, d *difr, d *z, d *poles, int *givptr, int *givcol, int *ldgcol, int *perm, d *givnum, d *c, d *s, d *work, int *iwork, int *info) noexcept nogil
+cdef void dlasdq(char *uplo, int *sqre, int *n, int *ncvt, int *nru, int *ncc, d *d, d *e, d *vt, int *ldvt, d *u, int *ldu, d *c, int *ldc, d *work, int *info) noexcept nogil
+cdef void dlasdt(int *n, int *lvl, int *nd, int *inode, int *ndiml, int *ndimr, int *msub) noexcept nogil
+cdef void dlaset(char *uplo, int *m, int *n, d *alpha, d *beta, d *a, int *lda) noexcept nogil
+cdef void dlasq1(int *n, d *d, d *e, d *work, int *info) noexcept nogil
+cdef void dlasq2(int *n, d *z, int *info) noexcept nogil
+cdef void dlasq3(int *i0, int *n0, d *z, int *pp, d *dmin, d *sigma, d *desig, d *qmax, int *nfail, int *iter, int *ndiv, bint *ieee, int *ttype, d *dmin1, d *dmin2, d *dn, d *dn1, d *dn2, d *g, d *tau) noexcept nogil
+cdef void dlasq4(int *i0, int *n0, d *z, int *pp, int *n0in, d *dmin, d *dmin1, d *dmin2, d *dn, d *dn1, d *dn2, d *tau, int *ttype, d *g) noexcept nogil
+cdef void dlasq6(int *i0, int *n0, d *z, int *pp, d *dmin, d *dmin1, d *dmin2, d *dn, d *dnm1, d *dnm2) noexcept nogil
+cdef void dlasr(char *side, char *pivot, char *direct, int *m, int *n, d *c, d *s, d *a, int *lda) noexcept nogil
+cdef void dlasrt(char *id, int *n, d *d, int *info) noexcept nogil
+cdef void dlassq(int *n, d *x, int *incx, d *scale, d *sumsq) noexcept nogil
+cdef void dlasv2(d *f, d *g, d *h, d *ssmin, d *ssmax, d *snr, d *csr, d *snl, d *csl) noexcept nogil
+cdef void dlaswp(int *n, d *a, int *lda, int *k1, int *k2, int *ipiv, int *incx) noexcept nogil
+cdef void dlasy2(bint *ltranl, bint *ltranr, int *isgn, int *n1, int *n2, d *tl, int *ldtl, d *tr, int *ldtr, d *b, int *ldb, d *scale, d *x, int *ldx, d *xnorm, int *info) noexcept nogil
+cdef void dlasyf(char *uplo, int *n, int *nb, int *kb, d *a, int *lda, int *ipiv, d *w, int *ldw, int *info) noexcept nogil
+cdef void dlat2s(char *uplo, int *n, d *a, int *lda, s *sa, int *ldsa, int *info) noexcept nogil
+cdef void dlatbs(char *uplo, char *trans, char *diag, char *normin, int *n, int *kd, d *ab, int *ldab, d *x, d *scale, d *cnorm, int *info) noexcept nogil
+cdef void dlatdf(int *ijob, int *n, d *z, int *ldz, d *rhs, d *rdsum, d *rdscal, int *ipiv, int *jpiv) noexcept nogil
+cdef void dlatps(char *uplo, char *trans, char *diag, char *normin, int *n, d *ap, d *x, d *scale, d *cnorm, int *info) noexcept nogil
+cdef void dlatrd(char *uplo, int *n, int *nb, d *a, int *lda, d *e, d *tau, d *w, int *ldw) noexcept nogil
+cdef void dlatrs(char *uplo, char *trans, char *diag, char *normin, int *n, d *a, int *lda, d *x, d *scale, d *cnorm, int *info) noexcept nogil
+cdef void dlatrz(int *m, int *n, int *l, d *a, int *lda, d *tau, d *work) noexcept nogil
+cdef void dlauu2(char *uplo, int *n, d *a, int *lda, int *info) noexcept nogil
+cdef void dlauum(char *uplo, int *n, d *a, int *lda, int *info) noexcept nogil
+cdef void dopgtr(char *uplo, int *n, d *ap, d *tau, d *q, int *ldq, d *work, int *info) noexcept nogil
+cdef void dopmtr(char *side, char *uplo, char *trans, int *m, int *n, d *ap, d *tau, d *c, int *ldc, d *work, int *info) noexcept nogil
+cdef void dorbdb(char *trans, char *signs, int *m, int *p, int *q, d *x11, int *ldx11, d *x12, int *ldx12, d *x21, int *ldx21, d *x22, int *ldx22, d *theta, d *phi, d *taup1, d *taup2, d *tauq1, d *tauq2, d *work, int *lwork, int *info) noexcept nogil
+cdef void dorcsd(char *jobu1, char *jobu2, char *jobv1t, char *jobv2t, char *trans, char *signs, int *m, int *p, int *q, d *x11, int *ldx11, d *x12, int *ldx12, d *x21, int *ldx21, d *x22, int *ldx22, d *theta, d *u1, int *ldu1, d *u2, int *ldu2, d *v1t, int *ldv1t, d *v2t, int *ldv2t, d *work, int *lwork, int *iwork, int *info) noexcept nogil
+cdef void dorg2l(int *m, int *n, int *k, d *a, int *lda, d *tau, d *work, int *info) noexcept nogil
+cdef void dorg2r(int *m, int *n, int *k, d *a, int *lda, d *tau, d *work, int *info) noexcept nogil
+cdef void dorgbr(char *vect, int *m, int *n, int *k, d *a, int *lda, d *tau, d *work, int *lwork, int *info) noexcept nogil
+cdef void dorghr(int *n, int *ilo, int *ihi, d *a, int *lda, d *tau, d *work, int *lwork, int *info) noexcept nogil
+cdef void dorgl2(int *m, int *n, int *k, d *a, int *lda, d *tau, d *work, int *info) noexcept nogil
+cdef void dorglq(int *m, int *n, int *k, d *a, int *lda, d *tau, d *work, int *lwork, int *info) noexcept nogil
+cdef void dorgql(int *m, int *n, int *k, d *a, int *lda, d *tau, d *work, int *lwork, int *info) noexcept nogil
+cdef void dorgqr(int *m, int *n, int *k, d *a, int *lda, d *tau, d *work, int *lwork, int *info) noexcept nogil
+cdef void dorgr2(int *m, int *n, int *k, d *a, int *lda, d *tau, d *work, int *info) noexcept nogil
+cdef void dorgrq(int *m, int *n, int *k, d *a, int *lda, d *tau, d *work, int *lwork, int *info) noexcept nogil
+cdef void dorgtr(char *uplo, int *n, d *a, int *lda, d *tau, d *work, int *lwork, int *info) noexcept nogil
+cdef void dorm2l(char *side, char *trans, int *m, int *n, int *k, d *a, int *lda, d *tau, d *c, int *ldc, d *work, int *info) noexcept nogil
+cdef void dorm2r(char *side, char *trans, int *m, int *n, int *k, d *a, int *lda, d *tau, d *c, int *ldc, d *work, int *info) noexcept nogil
+cdef void dormbr(char *vect, char *side, char *trans, int *m, int *n, int *k, d *a, int *lda, d *tau, d *c, int *ldc, d *work, int *lwork, int *info) noexcept nogil
+cdef void dormhr(char *side, char *trans, int *m, int *n, int *ilo, int *ihi, d *a, int *lda, d *tau, d *c, int *ldc, d *work, int *lwork, int *info) noexcept nogil
+cdef void dorml2(char *side, char *trans, int *m, int *n, int *k, d *a, int *lda, d *tau, d *c, int *ldc, d *work, int *info) noexcept nogil
+cdef void dormlq(char *side, char *trans, int *m, int *n, int *k, d *a, int *lda, d *tau, d *c, int *ldc, d *work, int *lwork, int *info) noexcept nogil
+cdef void dormql(char *side, char *trans, int *m, int *n, int *k, d *a, int *lda, d *tau, d *c, int *ldc, d *work, int *lwork, int *info) noexcept nogil
+cdef void dormqr(char *side, char *trans, int *m, int *n, int *k, d *a, int *lda, d *tau, d *c, int *ldc, d *work, int *lwork, int *info) noexcept nogil
+cdef void dormr2(char *side, char *trans, int *m, int *n, int *k, d *a, int *lda, d *tau, d *c, int *ldc, d *work, int *info) noexcept nogil
+cdef void dormr3(char *side, char *trans, int *m, int *n, int *k, int *l, d *a, int *lda, d *tau, d *c, int *ldc, d *work, int *info) noexcept nogil
+cdef void dormrq(char *side, char *trans, int *m, int *n, int *k, d *a, int *lda, d *tau, d *c, int *ldc, d *work, int *lwork, int *info) noexcept nogil
+cdef void dormrz(char *side, char *trans, int *m, int *n, int *k, int *l, d *a, int *lda, d *tau, d *c, int *ldc, d *work, int *lwork, int *info) noexcept nogil
+cdef void dormtr(char *side, char *uplo, char *trans, int *m, int *n, d *a, int *lda, d *tau, d *c, int *ldc, d *work, int *lwork, int *info) noexcept nogil
+cdef void dpbcon(char *uplo, int *n, int *kd, d *ab, int *ldab, d *anorm, d *rcond, d *work, int *iwork, int *info) noexcept nogil
+cdef void dpbequ(char *uplo, int *n, int *kd, d *ab, int *ldab, d *s, d *scond, d *amax, int *info) noexcept nogil
+cdef void dpbrfs(char *uplo, int *n, int *kd, int *nrhs, d *ab, int *ldab, d *afb, int *ldafb, d *b, int *ldb, d *x, int *ldx, d *ferr, d *berr, d *work, int *iwork, int *info) noexcept nogil
+cdef void dpbstf(char *uplo, int *n, int *kd, d *ab, int *ldab, int *info) noexcept nogil
+cdef void dpbsv(char *uplo, int *n, int *kd, int *nrhs, d *ab, int *ldab, d *b, int *ldb, int *info) noexcept nogil
+cdef void dpbsvx(char *fact, char *uplo, int *n, int *kd, int *nrhs, d *ab, int *ldab, d *afb, int *ldafb, char *equed, d *s, d *b, int *ldb, d *x, int *ldx, d *rcond, d *ferr, d *berr, d *work, int *iwork, int *info) noexcept nogil
+cdef void dpbtf2(char *uplo, int *n, int *kd, d *ab, int *ldab, int *info) noexcept nogil
+cdef void dpbtrf(char *uplo, int *n, int *kd, d *ab, int *ldab, int *info) noexcept nogil
+cdef void dpbtrs(char *uplo, int *n, int *kd, int *nrhs, d *ab, int *ldab, d *b, int *ldb, int *info) noexcept nogil
+cdef void dpftrf(char *transr, char *uplo, int *n, d *a, int *info) noexcept nogil
+cdef void dpftri(char *transr, char *uplo, int *n, d *a, int *info) noexcept nogil
+cdef void dpftrs(char *transr, char *uplo, int *n, int *nrhs, d *a, d *b, int *ldb, int *info) noexcept nogil
+cdef void dpocon(char *uplo, int *n, d *a, int *lda, d *anorm, d *rcond, d *work, int *iwork, int *info) noexcept nogil
+cdef void dpoequ(int *n, d *a, int *lda, d *s, d *scond, d *amax, int *info) noexcept nogil
+cdef void dpoequb(int *n, d *a, int *lda, d *s, d *scond, d *amax, int *info) noexcept nogil
+cdef void dporfs(char *uplo, int *n, int *nrhs, d *a, int *lda, d *af, int *ldaf, d *b, int *ldb, d *x, int *ldx, d *ferr, d *berr, d *work, int *iwork, int *info) noexcept nogil
+cdef void dposv(char *uplo, int *n, int *nrhs, d *a, int *lda, d *b, int *ldb, int *info) noexcept nogil
+cdef void dposvx(char *fact, char *uplo, int *n, int *nrhs, d *a, int *lda, d *af, int *ldaf, char *equed, d *s, d *b, int *ldb, d *x, int *ldx, d *rcond, d *ferr, d *berr, d *work, int *iwork, int *info) noexcept nogil
+cdef void dpotf2(char *uplo, int *n, d *a, int *lda, int *info) noexcept nogil
+cdef void dpotrf(char *uplo, int *n, d *a, int *lda, int *info) noexcept nogil
+cdef void dpotri(char *uplo, int *n, d *a, int *lda, int *info) noexcept nogil
+cdef void dpotrs(char *uplo, int *n, int *nrhs, d *a, int *lda, d *b, int *ldb, int *info) noexcept nogil
+cdef void dppcon(char *uplo, int *n, d *ap, d *anorm, d *rcond, d *work, int *iwork, int *info) noexcept nogil
+cdef void dppequ(char *uplo, int *n, d *ap, d *s, d *scond, d *amax, int *info) noexcept nogil
+cdef void dpprfs(char *uplo, int *n, int *nrhs, d *ap, d *afp, d *b, int *ldb, d *x, int *ldx, d *ferr, d *berr, d *work, int *iwork, int *info) noexcept nogil
+cdef void dppsv(char *uplo, int *n, int *nrhs, d *ap, d *b, int *ldb, int *info) noexcept nogil
+cdef void dppsvx(char *fact, char *uplo, int *n, int *nrhs, d *ap, d *afp, char *equed, d *s, d *b, int *ldb, d *x, int *ldx, d *rcond, d *ferr, d *berr, d *work, int *iwork, int *info) noexcept nogil
+cdef void dpptrf(char *uplo, int *n, d *ap, int *info) noexcept nogil
+cdef void dpptri(char *uplo, int *n, d *ap, int *info) noexcept nogil
+cdef void dpptrs(char *uplo, int *n, int *nrhs, d *ap, d *b, int *ldb, int *info) noexcept nogil
+cdef void dpstf2(char *uplo, int *n, d *a, int *lda, int *piv, int *rank, d *tol, d *work, int *info) noexcept nogil
+cdef void dpstrf(char *uplo, int *n, d *a, int *lda, int *piv, int *rank, d *tol, d *work, int *info) noexcept nogil
+cdef void dptcon(int *n, d *d, d *e, d *anorm, d *rcond, d *work, int *info) noexcept nogil
+cdef void dpteqr(char *compz, int *n, d *d, d *e, d *z, int *ldz, d *work, int *info) noexcept nogil
+cdef void dptrfs(int *n, int *nrhs, d *d, d *e, d *df, d *ef, d *b, int *ldb, d *x, int *ldx, d *ferr, d *berr, d *work, int *info) noexcept nogil
+cdef void dptsv(int *n, int *nrhs, d *d, d *e, d *b, int *ldb, int *info) noexcept nogil
+cdef void dptsvx(char *fact, int *n, int *nrhs, d *d, d *e, d *df, d *ef, d *b, int *ldb, d *x, int *ldx, d *rcond, d *ferr, d *berr, d *work, int *info) noexcept nogil
+cdef void dpttrf(int *n, d *d, d *e, int *info) noexcept nogil
+cdef void dpttrs(int *n, int *nrhs, d *d, d *e, d *b, int *ldb, int *info) noexcept nogil
+cdef void dptts2(int *n, int *nrhs, d *d, d *e, d *b, int *ldb) noexcept nogil
+cdef void drscl(int *n, d *sa, d *sx, int *incx) noexcept nogil
+cdef void dsbev(char *jobz, char *uplo, int *n, int *kd, d *ab, int *ldab, d *w, d *z, int *ldz, d *work, int *info) noexcept nogil
+cdef void dsbevd(char *jobz, char *uplo, int *n, int *kd, d *ab, int *ldab, d *w, d *z, int *ldz, d *work, int *lwork, int *iwork, int *liwork, int *info) noexcept nogil
+cdef void dsbevx(char *jobz, char *range, char *uplo, int *n, int *kd, d *ab, int *ldab, d *q, int *ldq, d *vl, d *vu, int *il, int *iu, d *abstol, int *m, d *w, d *z, int *ldz, d *work, int *iwork, int *ifail, int *info) noexcept nogil
+cdef void dsbgst(char *vect, char *uplo, int *n, int *ka, int *kb, d *ab, int *ldab, d *bb, int *ldbb, d *x, int *ldx, d *work, int *info) noexcept nogil
+cdef void dsbgv(char *jobz, char *uplo, int *n, int *ka, int *kb, d *ab, int *ldab, d *bb, int *ldbb, d *w, d *z, int *ldz, d *work, int *info) noexcept nogil
+cdef void dsbgvd(char *jobz, char *uplo, int *n, int *ka, int *kb, d *ab, int *ldab, d *bb, int *ldbb, d *w, d *z, int *ldz, d *work, int *lwork, int *iwork, int *liwork, int *info) noexcept nogil
+cdef void dsbgvx(char *jobz, char *range, char *uplo, int *n, int *ka, int *kb, d *ab, int *ldab, d *bb, int *ldbb, d *q, int *ldq, d *vl, d *vu, int *il, int *iu, d *abstol, int *m, d *w, d *z, int *ldz, d *work, int *iwork, int *ifail, int *info) noexcept nogil
+cdef void dsbtrd(char *vect, char *uplo, int *n, int *kd, d *ab, int *ldab, d *d, d *e, d *q, int *ldq, d *work, int *info) noexcept nogil
+cdef void dsfrk(char *transr, char *uplo, char *trans, int *n, int *k, d *alpha, d *a, int *lda, d *beta, d *c) noexcept nogil
+cdef void dsgesv(int *n, int *nrhs, d *a, int *lda, int *ipiv, d *b, int *ldb, d *x, int *ldx, d *work, s *swork, int *iter, int *info) noexcept nogil
+cdef void dspcon(char *uplo, int *n, d *ap, int *ipiv, d *anorm, d *rcond, d *work, int *iwork, int *info) noexcept nogil
+cdef void dspev(char *jobz, char *uplo, int *n, d *ap, d *w, d *z, int *ldz, d *work, int *info) noexcept nogil
+cdef void dspevd(char *jobz, char *uplo, int *n, d *ap, d *w, d *z, int *ldz, d *work, int *lwork, int *iwork, int *liwork, int *info) noexcept nogil
+cdef void dspevx(char *jobz, char *range, char *uplo, int *n, d *ap, d *vl, d *vu, int *il, int *iu, d *abstol, int *m, d *w, d *z, int *ldz, d *work, int *iwork, int *ifail, int *info) noexcept nogil
+cdef void dspgst(int *itype, char *uplo, int *n, d *ap, d *bp, int *info) noexcept nogil
+cdef void dspgv(int *itype, char *jobz, char *uplo, int *n, d *ap, d *bp, d *w, d *z, int *ldz, d *work, int *info) noexcept nogil
+cdef void dspgvd(int *itype, char *jobz, char *uplo, int *n, d *ap, d *bp, d *w, d *z, int *ldz, d *work, int *lwork, int *iwork, int *liwork, int *info) noexcept nogil
+cdef void dspgvx(int *itype, char *jobz, char *range, char *uplo, int *n, d *ap, d *bp, d *vl, d *vu, int *il, int *iu, d *abstol, int *m, d *w, d *z, int *ldz, d *work, int *iwork, int *ifail, int *info) noexcept nogil
+cdef void dsposv(char *uplo, int *n, int *nrhs, d *a, int *lda, d *b, int *ldb, d *x, int *ldx, d *work, s *swork, int *iter, int *info) noexcept nogil
+cdef void dsprfs(char *uplo, int *n, int *nrhs, d *ap, d *afp, int *ipiv, d *b, int *ldb, d *x, int *ldx, d *ferr, d *berr, d *work, int *iwork, int *info) noexcept nogil
+cdef void dspsv(char *uplo, int *n, int *nrhs, d *ap, int *ipiv, d *b, int *ldb, int *info) noexcept nogil
+cdef void dspsvx(char *fact, char *uplo, int *n, int *nrhs, d *ap, d *afp, int *ipiv, d *b, int *ldb, d *x, int *ldx, d *rcond, d *ferr, d *berr, d *work, int *iwork, int *info) noexcept nogil
+cdef void dsptrd(char *uplo, int *n, d *ap, d *d, d *e, d *tau, int *info) noexcept nogil
+cdef void dsptrf(char *uplo, int *n, d *ap, int *ipiv, int *info) noexcept nogil
+cdef void dsptri(char *uplo, int *n, d *ap, int *ipiv, d *work, int *info) noexcept nogil
+cdef void dsptrs(char *uplo, int *n, int *nrhs, d *ap, int *ipiv, d *b, int *ldb, int *info) noexcept nogil
+cdef void dstebz(char *range, char *order, int *n, d *vl, d *vu, int *il, int *iu, d *abstol, d *d, d *e, int *m, int *nsplit, d *w, int *iblock, int *isplit, d *work, int *iwork, int *info) noexcept nogil
+cdef void dstedc(char *compz, int *n, d *d, d *e, d *z, int *ldz, d *work, int *lwork, int *iwork, int *liwork, int *info) noexcept nogil
+cdef void dstegr(char *jobz, char *range, int *n, d *d, d *e, d *vl, d *vu, int *il, int *iu, d *abstol, int *m, d *w, d *z, int *ldz, int *isuppz, d *work, int *lwork, int *iwork, int *liwork, int *info) noexcept nogil
+cdef void dstein(int *n, d *d, d *e, int *m, d *w, int *iblock, int *isplit, d *z, int *ldz, d *work, int *iwork, int *ifail, int *info) noexcept nogil
+cdef void dstemr(char *jobz, char *range, int *n, d *d, d *e, d *vl, d *vu, int *il, int *iu, int *m, d *w, d *z, int *ldz, int *nzc, int *isuppz, bint *tryrac, d *work, int *lwork, int *iwork, int *liwork, int *info) noexcept nogil
+cdef void dsteqr(char *compz, int *n, d *d, d *e, d *z, int *ldz, d *work, int *info) noexcept nogil
+cdef void dsterf(int *n, d *d, d *e, int *info) noexcept nogil
+cdef void dstev(char *jobz, int *n, d *d, d *e, d *z, int *ldz, d *work, int *info) noexcept nogil
+cdef void dstevd(char *jobz, int *n, d *d, d *e, d *z, int *ldz, d *work, int *lwork, int *iwork, int *liwork, int *info) noexcept nogil
+cdef void dstevr(char *jobz, char *range, int *n, d *d, d *e, d *vl, d *vu, int *il, int *iu, d *abstol, int *m, d *w, d *z, int *ldz, int *isuppz, d *work, int *lwork, int *iwork, int *liwork, int *info) noexcept nogil
+cdef void dstevx(char *jobz, char *range, int *n, d *d, d *e, d *vl, d *vu, int *il, int *iu, d *abstol, int *m, d *w, d *z, int *ldz, d *work, int *iwork, int *ifail, int *info) noexcept nogil
+cdef void dsycon(char *uplo, int *n, d *a, int *lda, int *ipiv, d *anorm, d *rcond, d *work, int *iwork, int *info) noexcept nogil
+cdef void dsyconv(char *uplo, char *way, int *n, d *a, int *lda, int *ipiv, d *work, int *info) noexcept nogil
+cdef void dsyequb(char *uplo, int *n, d *a, int *lda, d *s, d *scond, d *amax, d *work, int *info) noexcept nogil
+cdef void dsyev(char *jobz, char *uplo, int *n, d *a, int *lda, d *w, d *work, int *lwork, int *info) noexcept nogil
+cdef void dsyevd(char *jobz, char *uplo, int *n, d *a, int *lda, d *w, d *work, int *lwork, int *iwork, int *liwork, int *info) noexcept nogil
+cdef void dsyevr(char *jobz, char *range, char *uplo, int *n, d *a, int *lda, d *vl, d *vu, int *il, int *iu, d *abstol, int *m, d *w, d *z, int *ldz, int *isuppz, d *work, int *lwork, int *iwork, int *liwork, int *info) noexcept nogil
+cdef void dsyevx(char *jobz, char *range, char *uplo, int *n, d *a, int *lda, d *vl, d *vu, int *il, int *iu, d *abstol, int *m, d *w, d *z, int *ldz, d *work, int *lwork, int *iwork, int *ifail, int *info) noexcept nogil
+cdef void dsygs2(int *itype, char *uplo, int *n, d *a, int *lda, d *b, int *ldb, int *info) noexcept nogil
+cdef void dsygst(int *itype, char *uplo, int *n, d *a, int *lda, d *b, int *ldb, int *info) noexcept nogil
+cdef void dsygv(int *itype, char *jobz, char *uplo, int *n, d *a, int *lda, d *b, int *ldb, d *w, d *work, int *lwork, int *info) noexcept nogil
+cdef void dsygvd(int *itype, char *jobz, char *uplo, int *n, d *a, int *lda, d *b, int *ldb, d *w, d *work, int *lwork, int *iwork, int *liwork, int *info) noexcept nogil
+cdef void dsygvx(int *itype, char *jobz, char *range, char *uplo, int *n, d *a, int *lda, d *b, int *ldb, d *vl, d *vu, int *il, int *iu, d *abstol, int *m, d *w, d *z, int *ldz, d *work, int *lwork, int *iwork, int *ifail, int *info) noexcept nogil
+cdef void dsyrfs(char *uplo, int *n, int *nrhs, d *a, int *lda, d *af, int *ldaf, int *ipiv, d *b, int *ldb, d *x, int *ldx, d *ferr, d *berr, d *work, int *iwork, int *info) noexcept nogil
+cdef void dsysv(char *uplo, int *n, int *nrhs, d *a, int *lda, int *ipiv, d *b, int *ldb, d *work, int *lwork, int *info) noexcept nogil
+cdef void dsysvx(char *fact, char *uplo, int *n, int *nrhs, d *a, int *lda, d *af, int *ldaf, int *ipiv, d *b, int *ldb, d *x, int *ldx, d *rcond, d *ferr, d *berr, d *work, int *lwork, int *iwork, int *info) noexcept nogil
+cdef void dsyswapr(char *uplo, int *n, d *a, int *lda, int *i1, int *i2) noexcept nogil
+cdef void dsytd2(char *uplo, int *n, d *a, int *lda, d *d, d *e, d *tau, int *info) noexcept nogil
+cdef void dsytf2(char *uplo, int *n, d *a, int *lda, int *ipiv, int *info) noexcept nogil
+cdef void dsytrd(char *uplo, int *n, d *a, int *lda, d *d, d *e, d *tau, d *work, int *lwork, int *info) noexcept nogil
+cdef void dsytrf(char *uplo, int *n, d *a, int *lda, int *ipiv, d *work, int *lwork, int *info) noexcept nogil
+cdef void dsytri(char *uplo, int *n, d *a, int *lda, int *ipiv, d *work, int *info) noexcept nogil
+cdef void dsytri2(char *uplo, int *n, d *a, int *lda, int *ipiv, d *work, int *lwork, int *info) noexcept nogil
+cdef void dsytri2x(char *uplo, int *n, d *a, int *lda, int *ipiv, d *work, int *nb, int *info) noexcept nogil
+cdef void dsytrs(char *uplo, int *n, int *nrhs, d *a, int *lda, int *ipiv, d *b, int *ldb, int *info) noexcept nogil
+cdef void dsytrs2(char *uplo, int *n, int *nrhs, d *a, int *lda, int *ipiv, d *b, int *ldb, d *work, int *info) noexcept nogil
+cdef void dtbcon(char *norm, char *uplo, char *diag, int *n, int *kd, d *ab, int *ldab, d *rcond, d *work, int *iwork, int *info) noexcept nogil
+cdef void dtbrfs(char *uplo, char *trans, char *diag, int *n, int *kd, int *nrhs, d *ab, int *ldab, d *b, int *ldb, d *x, int *ldx, d *ferr, d *berr, d *work, int *iwork, int *info) noexcept nogil
+cdef void dtbtrs(char *uplo, char *trans, char *diag, int *n, int *kd, int *nrhs, d *ab, int *ldab, d *b, int *ldb, int *info) noexcept nogil
+cdef void dtfsm(char *transr, char *side, char *uplo, char *trans, char *diag, int *m, int *n, d *alpha, d *a, d *b, int *ldb) noexcept nogil
+cdef void dtftri(char *transr, char *uplo, char *diag, int *n, d *a, int *info) noexcept nogil
+cdef void dtfttp(char *transr, char *uplo, int *n, d *arf, d *ap, int *info) noexcept nogil
+cdef void dtfttr(char *transr, char *uplo, int *n, d *arf, d *a, int *lda, int *info) noexcept nogil
+cdef void dtgevc(char *side, char *howmny, bint *select, int *n, d *s, int *lds, d *p, int *ldp, d *vl, int *ldvl, d *vr, int *ldvr, int *mm, int *m, d *work, int *info) noexcept nogil
+cdef void dtgex2(bint *wantq, bint *wantz, int *n, d *a, int *lda, d *b, int *ldb, d *q, int *ldq, d *z, int *ldz, int *j1, int *n1, int *n2, d *work, int *lwork, int *info) noexcept nogil
+cdef void dtgexc(bint *wantq, bint *wantz, int *n, d *a, int *lda, d *b, int *ldb, d *q, int *ldq, d *z, int *ldz, int *ifst, int *ilst, d *work, int *lwork, int *info) noexcept nogil
+cdef void dtgsen(int *ijob, bint *wantq, bint *wantz, bint *select, int *n, d *a, int *lda, d *b, int *ldb, d *alphar, d *alphai, d *beta, d *q, int *ldq, d *z, int *ldz, int *m, d *pl, d *pr, d *dif, d *work, int *lwork, int *iwork, int *liwork, int *info) noexcept nogil
+cdef void dtgsja(char *jobu, char *jobv, char *jobq, int *m, int *p, int *n, int *k, int *l, d *a, int *lda, d *b, int *ldb, d *tola, d *tolb, d *alpha, d *beta, d *u, int *ldu, d *v, int *ldv, d *q, int *ldq, d *work, int *ncycle, int *info) noexcept nogil
+cdef void dtgsna(char *job, char *howmny, bint *select, int *n, d *a, int *lda, d *b, int *ldb, d *vl, int *ldvl, d *vr, int *ldvr, d *s, d *dif, int *mm, int *m, d *work, int *lwork, int *iwork, int *info) noexcept nogil
+cdef void dtgsy2(char *trans, int *ijob, int *m, int *n, d *a, int *lda, d *b, int *ldb, d *c, int *ldc, d *d, int *ldd, d *e, int *lde, d *f, int *ldf, d *scale, d *rdsum, d *rdscal, int *iwork, int *pq, int *info) noexcept nogil
+cdef void dtgsyl(char *trans, int *ijob, int *m, int *n, d *a, int *lda, d *b, int *ldb, d *c, int *ldc, d *d, int *ldd, d *e, int *lde, d *f, int *ldf, d *scale, d *dif, d *work, int *lwork, int *iwork, int *info) noexcept nogil
+cdef void dtpcon(char *norm, char *uplo, char *diag, int *n, d *ap, d *rcond, d *work, int *iwork, int *info) noexcept nogil
+cdef void dtpmqrt(char *side, char *trans, int *m, int *n, int *k, int *l, int *nb, d *v, int *ldv, d *t, int *ldt, d *a, int *lda, d *b, int *ldb, d *work, int *info) noexcept nogil
+cdef void dtpqrt(int *m, int *n, int *l, int *nb, d *a, int *lda, d *b, int *ldb, d *t, int *ldt, d *work, int *info) noexcept nogil
+cdef void dtpqrt2(int *m, int *n, int *l, d *a, int *lda, d *b, int *ldb, d *t, int *ldt, int *info) noexcept nogil
+cdef void dtprfb(char *side, char *trans, char *direct, char *storev, int *m, int *n, int *k, int *l, d *v, int *ldv, d *t, int *ldt, d *a, int *lda, d *b, int *ldb, d *work, int *ldwork) noexcept nogil
+cdef void dtprfs(char *uplo, char *trans, char *diag, int *n, int *nrhs, d *ap, d *b, int *ldb, d *x, int *ldx, d *ferr, d *berr, d *work, int *iwork, int *info) noexcept nogil
+cdef void dtptri(char *uplo, char *diag, int *n, d *ap, int *info) noexcept nogil
+cdef void dtptrs(char *uplo, char *trans, char *diag, int *n, int *nrhs, d *ap, d *b, int *ldb, int *info) noexcept nogil
+cdef void dtpttf(char *transr, char *uplo, int *n, d *ap, d *arf, int *info) noexcept nogil
+cdef void dtpttr(char *uplo, int *n, d *ap, d *a, int *lda, int *info) noexcept nogil
+cdef void dtrcon(char *norm, char *uplo, char *diag, int *n, d *a, int *lda, d *rcond, d *work, int *iwork, int *info) noexcept nogil
+cdef void dtrevc(char *side, char *howmny, bint *select, int *n, d *t, int *ldt, d *vl, int *ldvl, d *vr, int *ldvr, int *mm, int *m, d *work, int *info) noexcept nogil
+cdef void dtrexc(char *compq, int *n, d *t, int *ldt, d *q, int *ldq, int *ifst, int *ilst, d *work, int *info) noexcept nogil
+cdef void dtrrfs(char *uplo, char *trans, char *diag, int *n, int *nrhs, d *a, int *lda, d *b, int *ldb, d *x, int *ldx, d *ferr, d *berr, d *work, int *iwork, int *info) noexcept nogil
+cdef void dtrsen(char *job, char *compq, bint *select, int *n, d *t, int *ldt, d *q, int *ldq, d *wr, d *wi, int *m, d *s, d *sep, d *work, int *lwork, int *iwork, int *liwork, int *info) noexcept nogil
+cdef void dtrsna(char *job, char *howmny, bint *select, int *n, d *t, int *ldt, d *vl, int *ldvl, d *vr, int *ldvr, d *s, d *sep, int *mm, int *m, d *work, int *ldwork, int *iwork, int *info) noexcept nogil
+cdef void dtrsyl(char *trana, char *tranb, int *isgn, int *m, int *n, d *a, int *lda, d *b, int *ldb, d *c, int *ldc, d *scale, int *info) noexcept nogil
+cdef void dtrti2(char *uplo, char *diag, int *n, d *a, int *lda, int *info) noexcept nogil
+cdef void dtrtri(char *uplo, char *diag, int *n, d *a, int *lda, int *info) noexcept nogil
+cdef void dtrtrs(char *uplo, char *trans, char *diag, int *n, int *nrhs, d *a, int *lda, d *b, int *ldb, int *info) noexcept nogil
+cdef void dtrttf(char *transr, char *uplo, int *n, d *a, int *lda, d *arf, int *info) noexcept nogil
+cdef void dtrttp(char *uplo, int *n, d *a, int *lda, d *ap, int *info) noexcept nogil
+cdef void dtzrzf(int *m, int *n, d *a, int *lda, d *tau, d *work, int *lwork, int *info) noexcept nogil
+cdef d dzsum1(int *n, z *cx, int *incx) noexcept nogil
+cdef int icmax1(int *n, c *cx, int *incx) noexcept nogil
+cdef int ieeeck(int *ispec, s *zero, s *one) noexcept nogil
+cdef int ilaclc(int *m, int *n, c *a, int *lda) noexcept nogil
+cdef int ilaclr(int *m, int *n, c *a, int *lda) noexcept nogil
+cdef int iladiag(char *diag) noexcept nogil
+cdef int iladlc(int *m, int *n, d *a, int *lda) noexcept nogil
+cdef int iladlr(int *m, int *n, d *a, int *lda) noexcept nogil
+cdef int ilaprec(char *prec) noexcept nogil
+cdef int ilaslc(int *m, int *n, s *a, int *lda) noexcept nogil
+cdef int ilaslr(int *m, int *n, s *a, int *lda) noexcept nogil
+cdef int ilatrans(char *trans) noexcept nogil
+cdef int ilauplo(char *uplo) noexcept nogil
+cdef void ilaver(int *vers_major, int *vers_minor, int *vers_patch) noexcept nogil
+cdef int ilazlc(int *m, int *n, z *a, int *lda) noexcept nogil
+cdef int ilazlr(int *m, int *n, z *a, int *lda) noexcept nogil
+cdef int izmax1(int *n, z *cx, int *incx) noexcept nogil
+cdef void sbbcsd(char *jobu1, char *jobu2, char *jobv1t, char *jobv2t, char *trans, int *m, int *p, int *q, s *theta, s *phi, s *u1, int *ldu1, s *u2, int *ldu2, s *v1t, int *ldv1t, s *v2t, int *ldv2t, s *b11d, s *b11e, s *b12d, s *b12e, s *b21d, s *b21e, s *b22d, s *b22e, s *work, int *lwork, int *info) noexcept nogil
+cdef void sbdsdc(char *uplo, char *compq, int *n, s *d, s *e, s *u, int *ldu, s *vt, int *ldvt, s *q, int *iq, s *work, int *iwork, int *info) noexcept nogil
+cdef void sbdsqr(char *uplo, int *n, int *ncvt, int *nru, int *ncc, s *d, s *e, s *vt, int *ldvt, s *u, int *ldu, s *c, int *ldc, s *work, int *info) noexcept nogil
+cdef s scsum1(int *n, c *cx, int *incx) noexcept nogil
+cdef void sdisna(char *job, int *m, int *n, s *d, s *sep, int *info) noexcept nogil
+cdef void sgbbrd(char *vect, int *m, int *n, int *ncc, int *kl, int *ku, s *ab, int *ldab, s *d, s *e, s *q, int *ldq, s *pt, int *ldpt, s *c, int *ldc, s *work, int *info) noexcept nogil
+cdef void sgbcon(char *norm, int *n, int *kl, int *ku, s *ab, int *ldab, int *ipiv, s *anorm, s *rcond, s *work, int *iwork, int *info) noexcept nogil
+cdef void sgbequ(int *m, int *n, int *kl, int *ku, s *ab, int *ldab, s *r, s *c, s *rowcnd, s *colcnd, s *amax, int *info) noexcept nogil
+cdef void sgbequb(int *m, int *n, int *kl, int *ku, s *ab, int *ldab, s *r, s *c, s *rowcnd, s *colcnd, s *amax, int *info) noexcept nogil
+cdef void sgbrfs(char *trans, int *n, int *kl, int *ku, int *nrhs, s *ab, int *ldab, s *afb, int *ldafb, int *ipiv, s *b, int *ldb, s *x, int *ldx, s *ferr, s *berr, s *work, int *iwork, int *info) noexcept nogil
+cdef void sgbsv(int *n, int *kl, int *ku, int *nrhs, s *ab, int *ldab, int *ipiv, s *b, int *ldb, int *info) noexcept nogil
+cdef void sgbsvx(char *fact, char *trans, int *n, int *kl, int *ku, int *nrhs, s *ab, int *ldab, s *afb, int *ldafb, int *ipiv, char *equed, s *r, s *c, s *b, int *ldb, s *x, int *ldx, s *rcond, s *ferr, s *berr, s *work, int *iwork, int *info) noexcept nogil
+cdef void sgbtf2(int *m, int *n, int *kl, int *ku, s *ab, int *ldab, int *ipiv, int *info) noexcept nogil
+cdef void sgbtrf(int *m, int *n, int *kl, int *ku, s *ab, int *ldab, int *ipiv, int *info) noexcept nogil
+cdef void sgbtrs(char *trans, int *n, int *kl, int *ku, int *nrhs, s *ab, int *ldab, int *ipiv, s *b, int *ldb, int *info) noexcept nogil
+cdef void sgebak(char *job, char *side, int *n, int *ilo, int *ihi, s *scale, int *m, s *v, int *ldv, int *info) noexcept nogil
+cdef void sgebal(char *job, int *n, s *a, int *lda, int *ilo, int *ihi, s *scale, int *info) noexcept nogil
+cdef void sgebd2(int *m, int *n, s *a, int *lda, s *d, s *e, s *tauq, s *taup, s *work, int *info) noexcept nogil
+cdef void sgebrd(int *m, int *n, s *a, int *lda, s *d, s *e, s *tauq, s *taup, s *work, int *lwork, int *info) noexcept nogil
+cdef void sgecon(char *norm, int *n, s *a, int *lda, s *anorm, s *rcond, s *work, int *iwork, int *info) noexcept nogil
+cdef void sgeequ(int *m, int *n, s *a, int *lda, s *r, s *c, s *rowcnd, s *colcnd, s *amax, int *info) noexcept nogil
+cdef void sgeequb(int *m, int *n, s *a, int *lda, s *r, s *c, s *rowcnd, s *colcnd, s *amax, int *info) noexcept nogil
+cdef void sgees(char *jobvs, char *sort, sselect2 *select, int *n, s *a, int *lda, int *sdim, s *wr, s *wi, s *vs, int *ldvs, s *work, int *lwork, bint *bwork, int *info) noexcept nogil
+cdef void sgeesx(char *jobvs, char *sort, sselect2 *select, char *sense, int *n, s *a, int *lda, int *sdim, s *wr, s *wi, s *vs, int *ldvs, s *rconde, s *rcondv, s *work, int *lwork, int *iwork, int *liwork, bint *bwork, int *info) noexcept nogil
+cdef void sgeev(char *jobvl, char *jobvr, int *n, s *a, int *lda, s *wr, s *wi, s *vl, int *ldvl, s *vr, int *ldvr, s *work, int *lwork, int *info) noexcept nogil
+cdef void sgeevx(char *balanc, char *jobvl, char *jobvr, char *sense, int *n, s *a, int *lda, s *wr, s *wi, s *vl, int *ldvl, s *vr, int *ldvr, int *ilo, int *ihi, s *scale, s *abnrm, s *rconde, s *rcondv, s *work, int *lwork, int *iwork, int *info) noexcept nogil
+cdef void sgehd2(int *n, int *ilo, int *ihi, s *a, int *lda, s *tau, s *work, int *info) noexcept nogil
+cdef void sgehrd(int *n, int *ilo, int *ihi, s *a, int *lda, s *tau, s *work, int *lwork, int *info) noexcept nogil
+cdef void sgejsv(char *joba, char *jobu, char *jobv, char *jobr, char *jobt, char *jobp, int *m, int *n, s *a, int *lda, s *sva, s *u, int *ldu, s *v, int *ldv, s *work, int *lwork, int *iwork, int *info) noexcept nogil
+cdef void sgelq2(int *m, int *n, s *a, int *lda, s *tau, s *work, int *info) noexcept nogil
+cdef void sgelqf(int *m, int *n, s *a, int *lda, s *tau, s *work, int *lwork, int *info) noexcept nogil
+cdef void sgels(char *trans, int *m, int *n, int *nrhs, s *a, int *lda, s *b, int *ldb, s *work, int *lwork, int *info) noexcept nogil
+cdef void sgelsd(int *m, int *n, int *nrhs, s *a, int *lda, s *b, int *ldb, s *s, s *rcond, int *rank, s *work, int *lwork, int *iwork, int *info) noexcept nogil
+cdef void sgelss(int *m, int *n, int *nrhs, s *a, int *lda, s *b, int *ldb, s *s, s *rcond, int *rank, s *work, int *lwork, int *info) noexcept nogil
+cdef void sgelsy(int *m, int *n, int *nrhs, s *a, int *lda, s *b, int *ldb, int *jpvt, s *rcond, int *rank, s *work, int *lwork, int *info) noexcept nogil
+cdef void sgemqrt(char *side, char *trans, int *m, int *n, int *k, int *nb, s *v, int *ldv, s *t, int *ldt, s *c, int *ldc, s *work, int *info) noexcept nogil
+cdef void sgeql2(int *m, int *n, s *a, int *lda, s *tau, s *work, int *info) noexcept nogil
+cdef void sgeqlf(int *m, int *n, s *a, int *lda, s *tau, s *work, int *lwork, int *info) noexcept nogil
+cdef void sgeqp3(int *m, int *n, s *a, int *lda, int *jpvt, s *tau, s *work, int *lwork, int *info) noexcept nogil
+cdef void sgeqr2(int *m, int *n, s *a, int *lda, s *tau, s *work, int *info) noexcept nogil
+cdef void sgeqr2p(int *m, int *n, s *a, int *lda, s *tau, s *work, int *info) noexcept nogil
+cdef void sgeqrf(int *m, int *n, s *a, int *lda, s *tau, s *work, int *lwork, int *info) noexcept nogil
+cdef void sgeqrfp(int *m, int *n, s *a, int *lda, s *tau, s *work, int *lwork, int *info) noexcept nogil
+cdef void sgeqrt(int *m, int *n, int *nb, s *a, int *lda, s *t, int *ldt, s *work, int *info) noexcept nogil
+cdef void sgeqrt2(int *m, int *n, s *a, int *lda, s *t, int *ldt, int *info) noexcept nogil
+cdef void sgeqrt3(int *m, int *n, s *a, int *lda, s *t, int *ldt, int *info) noexcept nogil
+cdef void sgerfs(char *trans, int *n, int *nrhs, s *a, int *lda, s *af, int *ldaf, int *ipiv, s *b, int *ldb, s *x, int *ldx, s *ferr, s *berr, s *work, int *iwork, int *info) noexcept nogil
+cdef void sgerq2(int *m, int *n, s *a, int *lda, s *tau, s *work, int *info) noexcept nogil
+cdef void sgerqf(int *m, int *n, s *a, int *lda, s *tau, s *work, int *lwork, int *info) noexcept nogil
+cdef void sgesc2(int *n, s *a, int *lda, s *rhs, int *ipiv, int *jpiv, s *scale) noexcept nogil
+cdef void sgesdd(char *jobz, int *m, int *n, s *a, int *lda, s *s, s *u, int *ldu, s *vt, int *ldvt, s *work, int *lwork, int *iwork, int *info) noexcept nogil
+cdef void sgesv(int *n, int *nrhs, s *a, int *lda, int *ipiv, s *b, int *ldb, int *info) noexcept nogil
+cdef void sgesvd(char *jobu, char *jobvt, int *m, int *n, s *a, int *lda, s *s, s *u, int *ldu, s *vt, int *ldvt, s *work, int *lwork, int *info) noexcept nogil
+cdef void sgesvj(char *joba, char *jobu, char *jobv, int *m, int *n, s *a, int *lda, s *sva, int *mv, s *v, int *ldv, s *work, int *lwork, int *info) noexcept nogil
+cdef void sgesvx(char *fact, char *trans, int *n, int *nrhs, s *a, int *lda, s *af, int *ldaf, int *ipiv, char *equed, s *r, s *c, s *b, int *ldb, s *x, int *ldx, s *rcond, s *ferr, s *berr, s *work, int *iwork, int *info) noexcept nogil
+cdef void sgetc2(int *n, s *a, int *lda, int *ipiv, int *jpiv, int *info) noexcept nogil
+cdef void sgetf2(int *m, int *n, s *a, int *lda, int *ipiv, int *info) noexcept nogil
+cdef void sgetrf(int *m, int *n, s *a, int *lda, int *ipiv, int *info) noexcept nogil
+cdef void sgetri(int *n, s *a, int *lda, int *ipiv, s *work, int *lwork, int *info) noexcept nogil
+cdef void sgetrs(char *trans, int *n, int *nrhs, s *a, int *lda, int *ipiv, s *b, int *ldb, int *info) noexcept nogil
+cdef void sggbak(char *job, char *side, int *n, int *ilo, int *ihi, s *lscale, s *rscale, int *m, s *v, int *ldv, int *info) noexcept nogil
+cdef void sggbal(char *job, int *n, s *a, int *lda, s *b, int *ldb, int *ilo, int *ihi, s *lscale, s *rscale, s *work, int *info) noexcept nogil
+cdef void sgges(char *jobvsl, char *jobvsr, char *sort, sselect3 *selctg, int *n, s *a, int *lda, s *b, int *ldb, int *sdim, s *alphar, s *alphai, s *beta, s *vsl, int *ldvsl, s *vsr, int *ldvsr, s *work, int *lwork, bint *bwork, int *info) noexcept nogil
+cdef void sggesx(char *jobvsl, char *jobvsr, char *sort, sselect3 *selctg, char *sense, int *n, s *a, int *lda, s *b, int *ldb, int *sdim, s *alphar, s *alphai, s *beta, s *vsl, int *ldvsl, s *vsr, int *ldvsr, s *rconde, s *rcondv, s *work, int *lwork, int *iwork, int *liwork, bint *bwork, int *info) noexcept nogil
+cdef void sggev(char *jobvl, char *jobvr, int *n, s *a, int *lda, s *b, int *ldb, s *alphar, s *alphai, s *beta, s *vl, int *ldvl, s *vr, int *ldvr, s *work, int *lwork, int *info) noexcept nogil
+cdef void sggevx(char *balanc, char *jobvl, char *jobvr, char *sense, int *n, s *a, int *lda, s *b, int *ldb, s *alphar, s *alphai, s *beta, s *vl, int *ldvl, s *vr, int *ldvr, int *ilo, int *ihi, s *lscale, s *rscale, s *abnrm, s *bbnrm, s *rconde, s *rcondv, s *work, int *lwork, int *iwork, bint *bwork, int *info) noexcept nogil
+cdef void sggglm(int *n, int *m, int *p, s *a, int *lda, s *b, int *ldb, s *d, s *x, s *y, s *work, int *lwork, int *info) noexcept nogil
+cdef void sgghrd(char *compq, char *compz, int *n, int *ilo, int *ihi, s *a, int *lda, s *b, int *ldb, s *q, int *ldq, s *z, int *ldz, int *info) noexcept nogil
+cdef void sgglse(int *m, int *n, int *p, s *a, int *lda, s *b, int *ldb, s *c, s *d, s *x, s *work, int *lwork, int *info) noexcept nogil
+cdef void sggqrf(int *n, int *m, int *p, s *a, int *lda, s *taua, s *b, int *ldb, s *taub, s *work, int *lwork, int *info) noexcept nogil
+cdef void sggrqf(int *m, int *p, int *n, s *a, int *lda, s *taua, s *b, int *ldb, s *taub, s *work, int *lwork, int *info) noexcept nogil
+cdef void sgsvj0(char *jobv, int *m, int *n, s *a, int *lda, s *d, s *sva, int *mv, s *v, int *ldv, s *eps, s *sfmin, s *tol, int *nsweep, s *work, int *lwork, int *info) noexcept nogil
+cdef void sgsvj1(char *jobv, int *m, int *n, int *n1, s *a, int *lda, s *d, s *sva, int *mv, s *v, int *ldv, s *eps, s *sfmin, s *tol, int *nsweep, s *work, int *lwork, int *info) noexcept nogil
+cdef void sgtcon(char *norm, int *n, s *dl, s *d, s *du, s *du2, int *ipiv, s *anorm, s *rcond, s *work, int *iwork, int *info) noexcept nogil
+cdef void sgtrfs(char *trans, int *n, int *nrhs, s *dl, s *d, s *du, s *dlf, s *df, s *duf, s *du2, int *ipiv, s *b, int *ldb, s *x, int *ldx, s *ferr, s *berr, s *work, int *iwork, int *info) noexcept nogil
+cdef void sgtsv(int *n, int *nrhs, s *dl, s *d, s *du, s *b, int *ldb, int *info) noexcept nogil
+cdef void sgtsvx(char *fact, char *trans, int *n, int *nrhs, s *dl, s *d, s *du, s *dlf, s *df, s *duf, s *du2, int *ipiv, s *b, int *ldb, s *x, int *ldx, s *rcond, s *ferr, s *berr, s *work, int *iwork, int *info) noexcept nogil
+cdef void sgttrf(int *n, s *dl, s *d, s *du, s *du2, int *ipiv, int *info) noexcept nogil
+cdef void sgttrs(char *trans, int *n, int *nrhs, s *dl, s *d, s *du, s *du2, int *ipiv, s *b, int *ldb, int *info) noexcept nogil
+cdef void sgtts2(int *itrans, int *n, int *nrhs, s *dl, s *d, s *du, s *du2, int *ipiv, s *b, int *ldb) noexcept nogil
+cdef void shgeqz(char *job, char *compq, char *compz, int *n, int *ilo, int *ihi, s *h, int *ldh, s *t, int *ldt, s *alphar, s *alphai, s *beta, s *q, int *ldq, s *z, int *ldz, s *work, int *lwork, int *info) noexcept nogil
+cdef void shsein(char *side, char *eigsrc, char *initv, bint *select, int *n, s *h, int *ldh, s *wr, s *wi, s *vl, int *ldvl, s *vr, int *ldvr, int *mm, int *m, s *work, int *ifaill, int *ifailr, int *info) noexcept nogil
+cdef void shseqr(char *job, char *compz, int *n, int *ilo, int *ihi, s *h, int *ldh, s *wr, s *wi, s *z, int *ldz, s *work, int *lwork, int *info) noexcept nogil
+cdef void slabad(s *small, s *large) noexcept nogil
+cdef void slabrd(int *m, int *n, int *nb, s *a, int *lda, s *d, s *e, s *tauq, s *taup, s *x, int *ldx, s *y, int *ldy) noexcept nogil
+cdef void slacn2(int *n, s *v, s *x, int *isgn, s *est, int *kase, int *isave) noexcept nogil
+cdef void slacon(int *n, s *v, s *x, int *isgn, s *est, int *kase) noexcept nogil
+cdef void slacpy(char *uplo, int *m, int *n, s *a, int *lda, s *b, int *ldb) noexcept nogil
+cdef void sladiv(s *a, s *b, s *c, s *d, s *p, s *q) noexcept nogil
+cdef void slae2(s *a, s *b, s *c, s *rt1, s *rt2) noexcept nogil
+cdef void slaebz(int *ijob, int *nitmax, int *n, int *mmax, int *minp, int *nbmin, s *abstol, s *reltol, s *pivmin, s *d, s *e, s *e2, int *nval, s *ab, s *c, int *mout, int *nab, s *work, int *iwork, int *info) noexcept nogil
+cdef void slaed0(int *icompq, int *qsiz, int *n, s *d, s *e, s *q, int *ldq, s *qstore, int *ldqs, s *work, int *iwork, int *info) noexcept nogil
+cdef void slaed1(int *n, s *d, s *q, int *ldq, int *indxq, s *rho, int *cutpnt, s *work, int *iwork, int *info) noexcept nogil
+cdef void slaed2(int *k, int *n, int *n1, s *d, s *q, int *ldq, int *indxq, s *rho, s *z, s *dlamda, s *w, s *q2, int *indx, int *indxc, int *indxp, int *coltyp, int *info) noexcept nogil
+cdef void slaed3(int *k, int *n, int *n1, s *d, s *q, int *ldq, s *rho, s *dlamda, s *q2, int *indx, int *ctot, s *w, s *s, int *info) noexcept nogil
+cdef void slaed4(int *n, int *i, s *d, s *z, s *delta, s *rho, s *dlam, int *info) noexcept nogil
+cdef void slaed5(int *i, s *d, s *z, s *delta, s *rho, s *dlam) noexcept nogil
+cdef void slaed6(int *kniter, bint *orgati, s *rho, s *d, s *z, s *finit, s *tau, int *info) noexcept nogil
+cdef void slaed7(int *icompq, int *n, int *qsiz, int *tlvls, int *curlvl, int *curpbm, s *d, s *q, int *ldq, int *indxq, s *rho, int *cutpnt, s *qstore, int *qptr, int *prmptr, int *perm, int *givptr, int *givcol, s *givnum, s *work, int *iwork, int *info) noexcept nogil
+cdef void slaed8(int *icompq, int *k, int *n, int *qsiz, s *d, s *q, int *ldq, int *indxq, s *rho, int *cutpnt, s *z, s *dlamda, s *q2, int *ldq2, s *w, int *perm, int *givptr, int *givcol, s *givnum, int *indxp, int *indx, int *info) noexcept nogil
+cdef void slaed9(int *k, int *kstart, int *kstop, int *n, s *d, s *q, int *ldq, s *rho, s *dlamda, s *w, s *s, int *lds, int *info) noexcept nogil
+cdef void slaeda(int *n, int *tlvls, int *curlvl, int *curpbm, int *prmptr, int *perm, int *givptr, int *givcol, s *givnum, s *q, int *qptr, s *z, s *ztemp, int *info) noexcept nogil
+cdef void slaein(bint *rightv, bint *noinit, int *n, s *h, int *ldh, s *wr, s *wi, s *vr, s *vi, s *b, int *ldb, s *work, s *eps3, s *smlnum, s *bignum, int *info) noexcept nogil
+cdef void slaev2(s *a, s *b, s *c, s *rt1, s *rt2, s *cs1, s *sn1) noexcept nogil
+cdef void slaexc(bint *wantq, int *n, s *t, int *ldt, s *q, int *ldq, int *j1, int *n1, int *n2, s *work, int *info) noexcept nogil
+cdef void slag2(s *a, int *lda, s *b, int *ldb, s *safmin, s *scale1, s *scale2, s *wr1, s *wr2, s *wi) noexcept nogil
+cdef void slag2d(int *m, int *n, s *sa, int *ldsa, d *a, int *lda, int *info) noexcept nogil
+cdef void slags2(bint *upper, s *a1, s *a2, s *a3, s *b1, s *b2, s *b3, s *csu, s *snu, s *csv, s *snv, s *csq, s *snq) noexcept nogil
+cdef void slagtf(int *n, s *a, s *lambda_, s *b, s *c, s *tol, s *d, int *in_, int *info) noexcept nogil
+cdef void slagtm(char *trans, int *n, int *nrhs, s *alpha, s *dl, s *d, s *du, s *x, int *ldx, s *beta, s *b, int *ldb) noexcept nogil
+cdef void slagts(int *job, int *n, s *a, s *b, s *c, s *d, int *in_, s *y, s *tol, int *info) noexcept nogil
+cdef void slagv2(s *a, int *lda, s *b, int *ldb, s *alphar, s *alphai, s *beta, s *csl, s *snl, s *csr, s *snr) noexcept nogil
+cdef void slahqr(bint *wantt, bint *wantz, int *n, int *ilo, int *ihi, s *h, int *ldh, s *wr, s *wi, int *iloz, int *ihiz, s *z, int *ldz, int *info) noexcept nogil
+cdef void slahr2(int *n, int *k, int *nb, s *a, int *lda, s *tau, s *t, int *ldt, s *y, int *ldy) noexcept nogil
+cdef void slaic1(int *job, int *j, s *x, s *sest, s *w, s *gamma, s *sestpr, s *s, s *c) noexcept nogil
+cdef void slaln2(bint *ltrans, int *na, int *nw, s *smin, s *ca, s *a, int *lda, s *d1, s *d2, s *b, int *ldb, s *wr, s *wi, s *x, int *ldx, s *scale, s *xnorm, int *info) noexcept nogil
+cdef void slals0(int *icompq, int *nl, int *nr, int *sqre, int *nrhs, s *b, int *ldb, s *bx, int *ldbx, int *perm, int *givptr, int *givcol, int *ldgcol, s *givnum, int *ldgnum, s *poles, s *difl, s *difr, s *z, int *k, s *c, s *s, s *work, int *info) noexcept nogil
+cdef void slalsa(int *icompq, int *smlsiz, int *n, int *nrhs, s *b, int *ldb, s *bx, int *ldbx, s *u, int *ldu, s *vt, int *k, s *difl, s *difr, s *z, s *poles, int *givptr, int *givcol, int *ldgcol, int *perm, s *givnum, s *c, s *s, s *work, int *iwork, int *info) noexcept nogil
+cdef void slalsd(char *uplo, int *smlsiz, int *n, int *nrhs, s *d, s *e, s *b, int *ldb, s *rcond, int *rank, s *work, int *iwork, int *info) noexcept nogil
+cdef s slamch(char *cmach) noexcept nogil
+cdef void slamrg(int *n1, int *n2, s *a, int *strd1, int *strd2, int *index_bn) noexcept nogil
+cdef s slangb(char *norm, int *n, int *kl, int *ku, s *ab, int *ldab, s *work) noexcept nogil
+cdef s slange(char *norm, int *m, int *n, s *a, int *lda, s *work) noexcept nogil
+cdef s slangt(char *norm, int *n, s *dl, s *d, s *du) noexcept nogil
+cdef s slanhs(char *norm, int *n, s *a, int *lda, s *work) noexcept nogil
+cdef s slansb(char *norm, char *uplo, int *n, int *k, s *ab, int *ldab, s *work) noexcept nogil
+cdef s slansf(char *norm, char *transr, char *uplo, int *n, s *a, s *work) noexcept nogil
+cdef s slansp(char *norm, char *uplo, int *n, s *ap, s *work) noexcept nogil
+cdef s slanst(char *norm, int *n, s *d, s *e) noexcept nogil
+cdef s slansy(char *norm, char *uplo, int *n, s *a, int *lda, s *work) noexcept nogil
+cdef s slantb(char *norm, char *uplo, char *diag, int *n, int *k, s *ab, int *ldab, s *work) noexcept nogil
+cdef s slantp(char *norm, char *uplo, char *diag, int *n, s *ap, s *work) noexcept nogil
+cdef s slantr(char *norm, char *uplo, char *diag, int *m, int *n, s *a, int *lda, s *work) noexcept nogil
+cdef void slanv2(s *a, s *b, s *c, s *d, s *rt1r, s *rt1i, s *rt2r, s *rt2i, s *cs, s *sn) noexcept nogil
+cdef void slapll(int *n, s *x, int *incx, s *y, int *incy, s *ssmin) noexcept nogil
+cdef void slapmr(bint *forwrd, int *m, int *n, s *x, int *ldx, int *k) noexcept nogil
+cdef void slapmt(bint *forwrd, int *m, int *n, s *x, int *ldx, int *k) noexcept nogil
+cdef s slapy2(s *x, s *y) noexcept nogil
+cdef s slapy3(s *x, s *y, s *z) noexcept nogil
+cdef void slaqgb(int *m, int *n, int *kl, int *ku, s *ab, int *ldab, s *r, s *c, s *rowcnd, s *colcnd, s *amax, char *equed) noexcept nogil
+cdef void slaqge(int *m, int *n, s *a, int *lda, s *r, s *c, s *rowcnd, s *colcnd, s *amax, char *equed) noexcept nogil
+cdef void slaqp2(int *m, int *n, int *offset, s *a, int *lda, int *jpvt, s *tau, s *vn1, s *vn2, s *work) noexcept nogil
+cdef void slaqps(int *m, int *n, int *offset, int *nb, int *kb, s *a, int *lda, int *jpvt, s *tau, s *vn1, s *vn2, s *auxv, s *f, int *ldf) noexcept nogil
+cdef void slaqr0(bint *wantt, bint *wantz, int *n, int *ilo, int *ihi, s *h, int *ldh, s *wr, s *wi, int *iloz, int *ihiz, s *z, int *ldz, s *work, int *lwork, int *info) noexcept nogil
+cdef void slaqr1(int *n, s *h, int *ldh, s *sr1, s *si1, s *sr2, s *si2, s *v) noexcept nogil
+cdef void slaqr2(bint *wantt, bint *wantz, int *n, int *ktop, int *kbot, int *nw, s *h, int *ldh, int *iloz, int *ihiz, s *z, int *ldz, int *ns, int *nd, s *sr, s *si, s *v, int *ldv, int *nh, s *t, int *ldt, int *nv, s *wv, int *ldwv, s *work, int *lwork) noexcept nogil
+cdef void slaqr3(bint *wantt, bint *wantz, int *n, int *ktop, int *kbot, int *nw, s *h, int *ldh, int *iloz, int *ihiz, s *z, int *ldz, int *ns, int *nd, s *sr, s *si, s *v, int *ldv, int *nh, s *t, int *ldt, int *nv, s *wv, int *ldwv, s *work, int *lwork) noexcept nogil
+cdef void slaqr4(bint *wantt, bint *wantz, int *n, int *ilo, int *ihi, s *h, int *ldh, s *wr, s *wi, int *iloz, int *ihiz, s *z, int *ldz, s *work, int *lwork, int *info) noexcept nogil
+cdef void slaqr5(bint *wantt, bint *wantz, int *kacc22, int *n, int *ktop, int *kbot, int *nshfts, s *sr, s *si, s *h, int *ldh, int *iloz, int *ihiz, s *z, int *ldz, s *v, int *ldv, s *u, int *ldu, int *nv, s *wv, int *ldwv, int *nh, s *wh, int *ldwh) noexcept nogil
+cdef void slaqsb(char *uplo, int *n, int *kd, s *ab, int *ldab, s *s, s *scond, s *amax, char *equed) noexcept nogil
+cdef void slaqsp(char *uplo, int *n, s *ap, s *s, s *scond, s *amax, char *equed) noexcept nogil
+cdef void slaqsy(char *uplo, int *n, s *a, int *lda, s *s, s *scond, s *amax, char *equed) noexcept nogil
+cdef void slaqtr(bint *ltran, bint *lreal, int *n, s *t, int *ldt, s *b, s *w, s *scale, s *x, s *work, int *info) noexcept nogil
+cdef void slar1v(int *n, int *b1, int *bn, s *lambda_, s *d, s *l, s *ld, s *lld, s *pivmin, s *gaptol, s *z, bint *wantnc, int *negcnt, s *ztz, s *mingma, int *r, int *isuppz, s *nrminv, s *resid, s *rqcorr, s *work) noexcept nogil
+cdef void slar2v(int *n, s *x, s *y, s *z, int *incx, s *c, s *s, int *incc) noexcept nogil
+cdef void slarf(char *side, int *m, int *n, s *v, int *incv, s *tau, s *c, int *ldc, s *work) noexcept nogil
+cdef void slarfb(char *side, char *trans, char *direct, char *storev, int *m, int *n, int *k, s *v, int *ldv, s *t, int *ldt, s *c, int *ldc, s *work, int *ldwork) noexcept nogil
+cdef void slarfg(int *n, s *alpha, s *x, int *incx, s *tau) noexcept nogil
+cdef void slarfgp(int *n, s *alpha, s *x, int *incx, s *tau) noexcept nogil
+cdef void slarft(char *direct, char *storev, int *n, int *k, s *v, int *ldv, s *tau, s *t, int *ldt) noexcept nogil
+cdef void slarfx(char *side, int *m, int *n, s *v, s *tau, s *c, int *ldc, s *work) noexcept nogil
+cdef void slargv(int *n, s *x, int *incx, s *y, int *incy, s *c, int *incc) noexcept nogil
+cdef void slarnv(int *idist, int *iseed, int *n, s *x) noexcept nogil
+cdef void slarra(int *n, s *d, s *e, s *e2, s *spltol, s *tnrm, int *nsplit, int *isplit, int *info) noexcept nogil
+cdef void slarrb(int *n, s *d, s *lld, int *ifirst, int *ilast, s *rtol1, s *rtol2, int *offset, s *w, s *wgap, s *werr, s *work, int *iwork, s *pivmin, s *spdiam, int *twist, int *info) noexcept nogil
+cdef void slarrc(char *jobt, int *n, s *vl, s *vu, s *d, s *e, s *pivmin, int *eigcnt, int *lcnt, int *rcnt, int *info) noexcept nogil
+cdef void slarrd(char *range, char *order, int *n, s *vl, s *vu, int *il, int *iu, s *gers, s *reltol, s *d, s *e, s *e2, s *pivmin, int *nsplit, int *isplit, int *m, s *w, s *werr, s *wl, s *wu, int *iblock, int *indexw, s *work, int *iwork, int *info) noexcept nogil
+cdef void slarre(char *range, int *n, s *vl, s *vu, int *il, int *iu, s *d, s *e, s *e2, s *rtol1, s *rtol2, s *spltol, int *nsplit, int *isplit, int *m, s *w, s *werr, s *wgap, int *iblock, int *indexw, s *gers, s *pivmin, s *work, int *iwork, int *info) noexcept nogil
+cdef void slarrf(int *n, s *d, s *l, s *ld, int *clstrt, int *clend, s *w, s *wgap, s *werr, s *spdiam, s *clgapl, s *clgapr, s *pivmin, s *sigma, s *dplus, s *lplus, s *work, int *info) noexcept nogil
+cdef void slarrj(int *n, s *d, s *e2, int *ifirst, int *ilast, s *rtol, int *offset, s *w, s *werr, s *work, int *iwork, s *pivmin, s *spdiam, int *info) noexcept nogil
+cdef void slarrk(int *n, int *iw, s *gl, s *gu, s *d, s *e2, s *pivmin, s *reltol, s *w, s *werr, int *info) noexcept nogil
+cdef void slarrr(int *n, s *d, s *e, int *info) noexcept nogil
+cdef void slarrv(int *n, s *vl, s *vu, s *d, s *l, s *pivmin, int *isplit, int *m, int *dol, int *dou, s *minrgp, s *rtol1, s *rtol2, s *w, s *werr, s *wgap, int *iblock, int *indexw, s *gers, s *z, int *ldz, int *isuppz, s *work, int *iwork, int *info) noexcept nogil
+cdef void slartg(s *f, s *g, s *cs, s *sn, s *r) noexcept nogil
+cdef void slartgp(s *f, s *g, s *cs, s *sn, s *r) noexcept nogil
+cdef void slartgs(s *x, s *y, s *sigma, s *cs, s *sn) noexcept nogil
+cdef void slartv(int *n, s *x, int *incx, s *y, int *incy, s *c, s *s, int *incc) noexcept nogil
+cdef void slaruv(int *iseed, int *n, s *x) noexcept nogil
+cdef void slarz(char *side, int *m, int *n, int *l, s *v, int *incv, s *tau, s *c, int *ldc, s *work) noexcept nogil
+cdef void slarzb(char *side, char *trans, char *direct, char *storev, int *m, int *n, int *k, int *l, s *v, int *ldv, s *t, int *ldt, s *c, int *ldc, s *work, int *ldwork) noexcept nogil
+cdef void slarzt(char *direct, char *storev, int *n, int *k, s *v, int *ldv, s *tau, s *t, int *ldt) noexcept nogil
+cdef void slas2(s *f, s *g, s *h, s *ssmin, s *ssmax) noexcept nogil
+cdef void slascl(char *type_bn, int *kl, int *ku, s *cfrom, s *cto, int *m, int *n, s *a, int *lda, int *info) noexcept nogil
+cdef void slasd0(int *n, int *sqre, s *d, s *e, s *u, int *ldu, s *vt, int *ldvt, int *smlsiz, int *iwork, s *work, int *info) noexcept nogil
+cdef void slasd1(int *nl, int *nr, int *sqre, s *d, s *alpha, s *beta, s *u, int *ldu, s *vt, int *ldvt, int *idxq, int *iwork, s *work, int *info) noexcept nogil
+cdef void slasd2(int *nl, int *nr, int *sqre, int *k, s *d, s *z, s *alpha, s *beta, s *u, int *ldu, s *vt, int *ldvt, s *dsigma, s *u2, int *ldu2, s *vt2, int *ldvt2, int *idxp, int *idx, int *idxc, int *idxq, int *coltyp, int *info) noexcept nogil
+cdef void slasd3(int *nl, int *nr, int *sqre, int *k, s *d, s *q, int *ldq, s *dsigma, s *u, int *ldu, s *u2, int *ldu2, s *vt, int *ldvt, s *vt2, int *ldvt2, int *idxc, int *ctot, s *z, int *info) noexcept nogil
+cdef void slasd4(int *n, int *i, s *d, s *z, s *delta, s *rho, s *sigma, s *work, int *info) noexcept nogil
+cdef void slasd5(int *i, s *d, s *z, s *delta, s *rho, s *dsigma, s *work) noexcept nogil
+cdef void slasd6(int *icompq, int *nl, int *nr, int *sqre, s *d, s *vf, s *vl, s *alpha, s *beta, int *idxq, int *perm, int *givptr, int *givcol, int *ldgcol, s *givnum, int *ldgnum, s *poles, s *difl, s *difr, s *z, int *k, s *c, s *s, s *work, int *iwork, int *info) noexcept nogil
+cdef void slasd7(int *icompq, int *nl, int *nr, int *sqre, int *k, s *d, s *z, s *zw, s *vf, s *vfw, s *vl, s *vlw, s *alpha, s *beta, s *dsigma, int *idx, int *idxp, int *idxq, int *perm, int *givptr, int *givcol, int *ldgcol, s *givnum, int *ldgnum, s *c, s *s, int *info) noexcept nogil
+cdef void slasd8(int *icompq, int *k, s *d, s *z, s *vf, s *vl, s *difl, s *difr, int *lddifr, s *dsigma, s *work, int *info) noexcept nogil
+cdef void slasda(int *icompq, int *smlsiz, int *n, int *sqre, s *d, s *e, s *u, int *ldu, s *vt, int *k, s *difl, s *difr, s *z, s *poles, int *givptr, int *givcol, int *ldgcol, int *perm, s *givnum, s *c, s *s, s *work, int *iwork, int *info) noexcept nogil
+cdef void slasdq(char *uplo, int *sqre, int *n, int *ncvt, int *nru, int *ncc, s *d, s *e, s *vt, int *ldvt, s *u, int *ldu, s *c, int *ldc, s *work, int *info) noexcept nogil
+cdef void slasdt(int *n, int *lvl, int *nd, int *inode, int *ndiml, int *ndimr, int *msub) noexcept nogil
+cdef void slaset(char *uplo, int *m, int *n, s *alpha, s *beta, s *a, int *lda) noexcept nogil
+cdef void slasq1(int *n, s *d, s *e, s *work, int *info) noexcept nogil
+cdef void slasq2(int *n, s *z, int *info) noexcept nogil
+cdef void slasq3(int *i0, int *n0, s *z, int *pp, s *dmin, s *sigma, s *desig, s *qmax, int *nfail, int *iter, int *ndiv, bint *ieee, int *ttype, s *dmin1, s *dmin2, s *dn, s *dn1, s *dn2, s *g, s *tau) noexcept nogil
+cdef void slasq4(int *i0, int *n0, s *z, int *pp, int *n0in, s *dmin, s *dmin1, s *dmin2, s *dn, s *dn1, s *dn2, s *tau, int *ttype, s *g) noexcept nogil
+cdef void slasq6(int *i0, int *n0, s *z, int *pp, s *dmin, s *dmin1, s *dmin2, s *dn, s *dnm1, s *dnm2) noexcept nogil
+cdef void slasr(char *side, char *pivot, char *direct, int *m, int *n, s *c, s *s, s *a, int *lda) noexcept nogil
+cdef void slasrt(char *id, int *n, s *d, int *info) noexcept nogil
+cdef void slassq(int *n, s *x, int *incx, s *scale, s *sumsq) noexcept nogil
+cdef void slasv2(s *f, s *g, s *h, s *ssmin, s *ssmax, s *snr, s *csr, s *snl, s *csl) noexcept nogil
+cdef void slaswp(int *n, s *a, int *lda, int *k1, int *k2, int *ipiv, int *incx) noexcept nogil
+cdef void slasy2(bint *ltranl, bint *ltranr, int *isgn, int *n1, int *n2, s *tl, int *ldtl, s *tr, int *ldtr, s *b, int *ldb, s *scale, s *x, int *ldx, s *xnorm, int *info) noexcept nogil
+cdef void slasyf(char *uplo, int *n, int *nb, int *kb, s *a, int *lda, int *ipiv, s *w, int *ldw, int *info) noexcept nogil
+cdef void slatbs(char *uplo, char *trans, char *diag, char *normin, int *n, int *kd, s *ab, int *ldab, s *x, s *scale, s *cnorm, int *info) noexcept nogil
+cdef void slatdf(int *ijob, int *n, s *z, int *ldz, s *rhs, s *rdsum, s *rdscal, int *ipiv, int *jpiv) noexcept nogil
+cdef void slatps(char *uplo, char *trans, char *diag, char *normin, int *n, s *ap, s *x, s *scale, s *cnorm, int *info) noexcept nogil
+cdef void slatrd(char *uplo, int *n, int *nb, s *a, int *lda, s *e, s *tau, s *w, int *ldw) noexcept nogil
+cdef void slatrs(char *uplo, char *trans, char *diag, char *normin, int *n, s *a, int *lda, s *x, s *scale, s *cnorm, int *info) noexcept nogil
+cdef void slatrz(int *m, int *n, int *l, s *a, int *lda, s *tau, s *work) noexcept nogil
+cdef void slauu2(char *uplo, int *n, s *a, int *lda, int *info) noexcept nogil
+cdef void slauum(char *uplo, int *n, s *a, int *lda, int *info) noexcept nogil
+cdef void sopgtr(char *uplo, int *n, s *ap, s *tau, s *q, int *ldq, s *work, int *info) noexcept nogil
+cdef void sopmtr(char *side, char *uplo, char *trans, int *m, int *n, s *ap, s *tau, s *c, int *ldc, s *work, int *info) noexcept nogil
+cdef void sorbdb(char *trans, char *signs, int *m, int *p, int *q, s *x11, int *ldx11, s *x12, int *ldx12, s *x21, int *ldx21, s *x22, int *ldx22, s *theta, s *phi, s *taup1, s *taup2, s *tauq1, s *tauq2, s *work, int *lwork, int *info) noexcept nogil
+cdef void sorcsd(char *jobu1, char *jobu2, char *jobv1t, char *jobv2t, char *trans, char *signs, int *m, int *p, int *q, s *x11, int *ldx11, s *x12, int *ldx12, s *x21, int *ldx21, s *x22, int *ldx22, s *theta, s *u1, int *ldu1, s *u2, int *ldu2, s *v1t, int *ldv1t, s *v2t, int *ldv2t, s *work, int *lwork, int *iwork, int *info) noexcept nogil
+cdef void sorg2l(int *m, int *n, int *k, s *a, int *lda, s *tau, s *work, int *info) noexcept nogil
+cdef void sorg2r(int *m, int *n, int *k, s *a, int *lda, s *tau, s *work, int *info) noexcept nogil
+cdef void sorgbr(char *vect, int *m, int *n, int *k, s *a, int *lda, s *tau, s *work, int *lwork, int *info) noexcept nogil
+cdef void sorghr(int *n, int *ilo, int *ihi, s *a, int *lda, s *tau, s *work, int *lwork, int *info) noexcept nogil
+cdef void sorgl2(int *m, int *n, int *k, s *a, int *lda, s *tau, s *work, int *info) noexcept nogil
+cdef void sorglq(int *m, int *n, int *k, s *a, int *lda, s *tau, s *work, int *lwork, int *info) noexcept nogil
+cdef void sorgql(int *m, int *n, int *k, s *a, int *lda, s *tau, s *work, int *lwork, int *info) noexcept nogil
+cdef void sorgqr(int *m, int *n, int *k, s *a, int *lda, s *tau, s *work, int *lwork, int *info) noexcept nogil
+cdef void sorgr2(int *m, int *n, int *k, s *a, int *lda, s *tau, s *work, int *info) noexcept nogil
+cdef void sorgrq(int *m, int *n, int *k, s *a, int *lda, s *tau, s *work, int *lwork, int *info) noexcept nogil
+cdef void sorgtr(char *uplo, int *n, s *a, int *lda, s *tau, s *work, int *lwork, int *info) noexcept nogil
+cdef void sorm2l(char *side, char *trans, int *m, int *n, int *k, s *a, int *lda, s *tau, s *c, int *ldc, s *work, int *info) noexcept nogil
+cdef void sorm2r(char *side, char *trans, int *m, int *n, int *k, s *a, int *lda, s *tau, s *c, int *ldc, s *work, int *info) noexcept nogil
+cdef void sormbr(char *vect, char *side, char *trans, int *m, int *n, int *k, s *a, int *lda, s *tau, s *c, int *ldc, s *work, int *lwork, int *info) noexcept nogil
+cdef void sormhr(char *side, char *trans, int *m, int *n, int *ilo, int *ihi, s *a, int *lda, s *tau, s *c, int *ldc, s *work, int *lwork, int *info) noexcept nogil
+cdef void sorml2(char *side, char *trans, int *m, int *n, int *k, s *a, int *lda, s *tau, s *c, int *ldc, s *work, int *info) noexcept nogil
+cdef void sormlq(char *side, char *trans, int *m, int *n, int *k, s *a, int *lda, s *tau, s *c, int *ldc, s *work, int *lwork, int *info) noexcept nogil
+cdef void sormql(char *side, char *trans, int *m, int *n, int *k, s *a, int *lda, s *tau, s *c, int *ldc, s *work, int *lwork, int *info) noexcept nogil
+cdef void sormqr(char *side, char *trans, int *m, int *n, int *k, s *a, int *lda, s *tau, s *c, int *ldc, s *work, int *lwork, int *info) noexcept nogil
+cdef void sormr2(char *side, char *trans, int *m, int *n, int *k, s *a, int *lda, s *tau, s *c, int *ldc, s *work, int *info) noexcept nogil
+cdef void sormr3(char *side, char *trans, int *m, int *n, int *k, int *l, s *a, int *lda, s *tau, s *c, int *ldc, s *work, int *info) noexcept nogil
+cdef void sormrq(char *side, char *trans, int *m, int *n, int *k, s *a, int *lda, s *tau, s *c, int *ldc, s *work, int *lwork, int *info) noexcept nogil
+cdef void sormrz(char *side, char *trans, int *m, int *n, int *k, int *l, s *a, int *lda, s *tau, s *c, int *ldc, s *work, int *lwork, int *info) noexcept nogil
+cdef void sormtr(char *side, char *uplo, char *trans, int *m, int *n, s *a, int *lda, s *tau, s *c, int *ldc, s *work, int *lwork, int *info) noexcept nogil
+cdef void spbcon(char *uplo, int *n, int *kd, s *ab, int *ldab, s *anorm, s *rcond, s *work, int *iwork, int *info) noexcept nogil
+cdef void spbequ(char *uplo, int *n, int *kd, s *ab, int *ldab, s *s, s *scond, s *amax, int *info) noexcept nogil
+cdef void spbrfs(char *uplo, int *n, int *kd, int *nrhs, s *ab, int *ldab, s *afb, int *ldafb, s *b, int *ldb, s *x, int *ldx, s *ferr, s *berr, s *work, int *iwork, int *info) noexcept nogil
+cdef void spbstf(char *uplo, int *n, int *kd, s *ab, int *ldab, int *info) noexcept nogil
+cdef void spbsv(char *uplo, int *n, int *kd, int *nrhs, s *ab, int *ldab, s *b, int *ldb, int *info) noexcept nogil
+cdef void spbsvx(char *fact, char *uplo, int *n, int *kd, int *nrhs, s *ab, int *ldab, s *afb, int *ldafb, char *equed, s *s, s *b, int *ldb, s *x, int *ldx, s *rcond, s *ferr, s *berr, s *work, int *iwork, int *info) noexcept nogil
+cdef void spbtf2(char *uplo, int *n, int *kd, s *ab, int *ldab, int *info) noexcept nogil
+cdef void spbtrf(char *uplo, int *n, int *kd, s *ab, int *ldab, int *info) noexcept nogil
+cdef void spbtrs(char *uplo, int *n, int *kd, int *nrhs, s *ab, int *ldab, s *b, int *ldb, int *info) noexcept nogil
+cdef void spftrf(char *transr, char *uplo, int *n, s *a, int *info) noexcept nogil
+cdef void spftri(char *transr, char *uplo, int *n, s *a, int *info) noexcept nogil
+cdef void spftrs(char *transr, char *uplo, int *n, int *nrhs, s *a, s *b, int *ldb, int *info) noexcept nogil
+cdef void spocon(char *uplo, int *n, s *a, int *lda, s *anorm, s *rcond, s *work, int *iwork, int *info) noexcept nogil
+cdef void spoequ(int *n, s *a, int *lda, s *s, s *scond, s *amax, int *info) noexcept nogil
+cdef void spoequb(int *n, s *a, int *lda, s *s, s *scond, s *amax, int *info) noexcept nogil
+cdef void sporfs(char *uplo, int *n, int *nrhs, s *a, int *lda, s *af, int *ldaf, s *b, int *ldb, s *x, int *ldx, s *ferr, s *berr, s *work, int *iwork, int *info) noexcept nogil
+cdef void sposv(char *uplo, int *n, int *nrhs, s *a, int *lda, s *b, int *ldb, int *info) noexcept nogil
+cdef void sposvx(char *fact, char *uplo, int *n, int *nrhs, s *a, int *lda, s *af, int *ldaf, char *equed, s *s, s *b, int *ldb, s *x, int *ldx, s *rcond, s *ferr, s *berr, s *work, int *iwork, int *info) noexcept nogil
+cdef void spotf2(char *uplo, int *n, s *a, int *lda, int *info) noexcept nogil
+cdef void spotrf(char *uplo, int *n, s *a, int *lda, int *info) noexcept nogil
+cdef void spotri(char *uplo, int *n, s *a, int *lda, int *info) noexcept nogil
+cdef void spotrs(char *uplo, int *n, int *nrhs, s *a, int *lda, s *b, int *ldb, int *info) noexcept nogil
+cdef void sppcon(char *uplo, int *n, s *ap, s *anorm, s *rcond, s *work, int *iwork, int *info) noexcept nogil
+cdef void sppequ(char *uplo, int *n, s *ap, s *s, s *scond, s *amax, int *info) noexcept nogil
+cdef void spprfs(char *uplo, int *n, int *nrhs, s *ap, s *afp, s *b, int *ldb, s *x, int *ldx, s *ferr, s *berr, s *work, int *iwork, int *info) noexcept nogil
+cdef void sppsv(char *uplo, int *n, int *nrhs, s *ap, s *b, int *ldb, int *info) noexcept nogil
+cdef void sppsvx(char *fact, char *uplo, int *n, int *nrhs, s *ap, s *afp, char *equed, s *s, s *b, int *ldb, s *x, int *ldx, s *rcond, s *ferr, s *berr, s *work, int *iwork, int *info) noexcept nogil
+cdef void spptrf(char *uplo, int *n, s *ap, int *info) noexcept nogil
+cdef void spptri(char *uplo, int *n, s *ap, int *info) noexcept nogil
+cdef void spptrs(char *uplo, int *n, int *nrhs, s *ap, s *b, int *ldb, int *info) noexcept nogil
+cdef void spstf2(char *uplo, int *n, s *a, int *lda, int *piv, int *rank, s *tol, s *work, int *info) noexcept nogil
+cdef void spstrf(char *uplo, int *n, s *a, int *lda, int *piv, int *rank, s *tol, s *work, int *info) noexcept nogil
+cdef void sptcon(int *n, s *d, s *e, s *anorm, s *rcond, s *work, int *info) noexcept nogil
+cdef void spteqr(char *compz, int *n, s *d, s *e, s *z, int *ldz, s *work, int *info) noexcept nogil
+cdef void sptrfs(int *n, int *nrhs, s *d, s *e, s *df, s *ef, s *b, int *ldb, s *x, int *ldx, s *ferr, s *berr, s *work, int *info) noexcept nogil
+cdef void sptsv(int *n, int *nrhs, s *d, s *e, s *b, int *ldb, int *info) noexcept nogil
+cdef void sptsvx(char *fact, int *n, int *nrhs, s *d, s *e, s *df, s *ef, s *b, int *ldb, s *x, int *ldx, s *rcond, s *ferr, s *berr, s *work, int *info) noexcept nogil
+cdef void spttrf(int *n, s *d, s *e, int *info) noexcept nogil
+cdef void spttrs(int *n, int *nrhs, s *d, s *e, s *b, int *ldb, int *info) noexcept nogil
+cdef void sptts2(int *n, int *nrhs, s *d, s *e, s *b, int *ldb) noexcept nogil
+cdef void srscl(int *n, s *sa, s *sx, int *incx) noexcept nogil
+cdef void ssbev(char *jobz, char *uplo, int *n, int *kd, s *ab, int *ldab, s *w, s *z, int *ldz, s *work, int *info) noexcept nogil
+cdef void ssbevd(char *jobz, char *uplo, int *n, int *kd, s *ab, int *ldab, s *w, s *z, int *ldz, s *work, int *lwork, int *iwork, int *liwork, int *info) noexcept nogil
+cdef void ssbevx(char *jobz, char *range, char *uplo, int *n, int *kd, s *ab, int *ldab, s *q, int *ldq, s *vl, s *vu, int *il, int *iu, s *abstol, int *m, s *w, s *z, int *ldz, s *work, int *iwork, int *ifail, int *info) noexcept nogil
+cdef void ssbgst(char *vect, char *uplo, int *n, int *ka, int *kb, s *ab, int *ldab, s *bb, int *ldbb, s *x, int *ldx, s *work, int *info) noexcept nogil
+cdef void ssbgv(char *jobz, char *uplo, int *n, int *ka, int *kb, s *ab, int *ldab, s *bb, int *ldbb, s *w, s *z, int *ldz, s *work, int *info) noexcept nogil
+cdef void ssbgvd(char *jobz, char *uplo, int *n, int *ka, int *kb, s *ab, int *ldab, s *bb, int *ldbb, s *w, s *z, int *ldz, s *work, int *lwork, int *iwork, int *liwork, int *info) noexcept nogil
+cdef void ssbgvx(char *jobz, char *range, char *uplo, int *n, int *ka, int *kb, s *ab, int *ldab, s *bb, int *ldbb, s *q, int *ldq, s *vl, s *vu, int *il, int *iu, s *abstol, int *m, s *w, s *z, int *ldz, s *work, int *iwork, int *ifail, int *info) noexcept nogil
+cdef void ssbtrd(char *vect, char *uplo, int *n, int *kd, s *ab, int *ldab, s *d, s *e, s *q, int *ldq, s *work, int *info) noexcept nogil
+cdef void ssfrk(char *transr, char *uplo, char *trans, int *n, int *k, s *alpha, s *a, int *lda, s *beta, s *c) noexcept nogil
+cdef void sspcon(char *uplo, int *n, s *ap, int *ipiv, s *anorm, s *rcond, s *work, int *iwork, int *info) noexcept nogil
+cdef void sspev(char *jobz, char *uplo, int *n, s *ap, s *w, s *z, int *ldz, s *work, int *info) noexcept nogil
+cdef void sspevd(char *jobz, char *uplo, int *n, s *ap, s *w, s *z, int *ldz, s *work, int *lwork, int *iwork, int *liwork, int *info) noexcept nogil
+cdef void sspevx(char *jobz, char *range, char *uplo, int *n, s *ap, s *vl, s *vu, int *il, int *iu, s *abstol, int *m, s *w, s *z, int *ldz, s *work, int *iwork, int *ifail, int *info) noexcept nogil
+cdef void sspgst(int *itype, char *uplo, int *n, s *ap, s *bp, int *info) noexcept nogil
+cdef void sspgv(int *itype, char *jobz, char *uplo, int *n, s *ap, s *bp, s *w, s *z, int *ldz, s *work, int *info) noexcept nogil
+cdef void sspgvd(int *itype, char *jobz, char *uplo, int *n, s *ap, s *bp, s *w, s *z, int *ldz, s *work, int *lwork, int *iwork, int *liwork, int *info) noexcept nogil
+cdef void sspgvx(int *itype, char *jobz, char *range, char *uplo, int *n, s *ap, s *bp, s *vl, s *vu, int *il, int *iu, s *abstol, int *m, s *w, s *z, int *ldz, s *work, int *iwork, int *ifail, int *info) noexcept nogil
+cdef void ssprfs(char *uplo, int *n, int *nrhs, s *ap, s *afp, int *ipiv, s *b, int *ldb, s *x, int *ldx, s *ferr, s *berr, s *work, int *iwork, int *info) noexcept nogil
+cdef void sspsv(char *uplo, int *n, int *nrhs, s *ap, int *ipiv, s *b, int *ldb, int *info) noexcept nogil
+cdef void sspsvx(char *fact, char *uplo, int *n, int *nrhs, s *ap, s *afp, int *ipiv, s *b, int *ldb, s *x, int *ldx, s *rcond, s *ferr, s *berr, s *work, int *iwork, int *info) noexcept nogil
+cdef void ssptrd(char *uplo, int *n, s *ap, s *d, s *e, s *tau, int *info) noexcept nogil
+cdef void ssptrf(char *uplo, int *n, s *ap, int *ipiv, int *info) noexcept nogil
+cdef void ssptri(char *uplo, int *n, s *ap, int *ipiv, s *work, int *info) noexcept nogil
+cdef void ssptrs(char *uplo, int *n, int *nrhs, s *ap, int *ipiv, s *b, int *ldb, int *info) noexcept nogil
+cdef void sstebz(char *range, char *order, int *n, s *vl, s *vu, int *il, int *iu, s *abstol, s *d, s *e, int *m, int *nsplit, s *w, int *iblock, int *isplit, s *work, int *iwork, int *info) noexcept nogil
+cdef void sstedc(char *compz, int *n, s *d, s *e, s *z, int *ldz, s *work, int *lwork, int *iwork, int *liwork, int *info) noexcept nogil
+cdef void sstegr(char *jobz, char *range, int *n, s *d, s *e, s *vl, s *vu, int *il, int *iu, s *abstol, int *m, s *w, s *z, int *ldz, int *isuppz, s *work, int *lwork, int *iwork, int *liwork, int *info) noexcept nogil
+cdef void sstein(int *n, s *d, s *e, int *m, s *w, int *iblock, int *isplit, s *z, int *ldz, s *work, int *iwork, int *ifail, int *info) noexcept nogil
+cdef void sstemr(char *jobz, char *range, int *n, s *d, s *e, s *vl, s *vu, int *il, int *iu, int *m, s *w, s *z, int *ldz, int *nzc, int *isuppz, bint *tryrac, s *work, int *lwork, int *iwork, int *liwork, int *info) noexcept nogil
+cdef void ssteqr(char *compz, int *n, s *d, s *e, s *z, int *ldz, s *work, int *info) noexcept nogil
+cdef void ssterf(int *n, s *d, s *e, int *info) noexcept nogil
+cdef void sstev(char *jobz, int *n, s *d, s *e, s *z, int *ldz, s *work, int *info) noexcept nogil
+cdef void sstevd(char *jobz, int *n, s *d, s *e, s *z, int *ldz, s *work, int *lwork, int *iwork, int *liwork, int *info) noexcept nogil
+cdef void sstevr(char *jobz, char *range, int *n, s *d, s *e, s *vl, s *vu, int *il, int *iu, s *abstol, int *m, s *w, s *z, int *ldz, int *isuppz, s *work, int *lwork, int *iwork, int *liwork, int *info) noexcept nogil
+cdef void sstevx(char *jobz, char *range, int *n, s *d, s *e, s *vl, s *vu, int *il, int *iu, s *abstol, int *m, s *w, s *z, int *ldz, s *work, int *iwork, int *ifail, int *info) noexcept nogil
+cdef void ssycon(char *uplo, int *n, s *a, int *lda, int *ipiv, s *anorm, s *rcond, s *work, int *iwork, int *info) noexcept nogil
+cdef void ssyconv(char *uplo, char *way, int *n, s *a, int *lda, int *ipiv, s *work, int *info) noexcept nogil
+cdef void ssyequb(char *uplo, int *n, s *a, int *lda, s *s, s *scond, s *amax, s *work, int *info) noexcept nogil
+cdef void ssyev(char *jobz, char *uplo, int *n, s *a, int *lda, s *w, s *work, int *lwork, int *info) noexcept nogil
+cdef void ssyevd(char *jobz, char *uplo, int *n, s *a, int *lda, s *w, s *work, int *lwork, int *iwork, int *liwork, int *info) noexcept nogil
+cdef void ssyevr(char *jobz, char *range, char *uplo, int *n, s *a, int *lda, s *vl, s *vu, int *il, int *iu, s *abstol, int *m, s *w, s *z, int *ldz, int *isuppz, s *work, int *lwork, int *iwork, int *liwork, int *info) noexcept nogil
+cdef void ssyevx(char *jobz, char *range, char *uplo, int *n, s *a, int *lda, s *vl, s *vu, int *il, int *iu, s *abstol, int *m, s *w, s *z, int *ldz, s *work, int *lwork, int *iwork, int *ifail, int *info) noexcept nogil
+cdef void ssygs2(int *itype, char *uplo, int *n, s *a, int *lda, s *b, int *ldb, int *info) noexcept nogil
+cdef void ssygst(int *itype, char *uplo, int *n, s *a, int *lda, s *b, int *ldb, int *info) noexcept nogil
+cdef void ssygv(int *itype, char *jobz, char *uplo, int *n, s *a, int *lda, s *b, int *ldb, s *w, s *work, int *lwork, int *info) noexcept nogil
+cdef void ssygvd(int *itype, char *jobz, char *uplo, int *n, s *a, int *lda, s *b, int *ldb, s *w, s *work, int *lwork, int *iwork, int *liwork, int *info) noexcept nogil
+cdef void ssygvx(int *itype, char *jobz, char *range, char *uplo, int *n, s *a, int *lda, s *b, int *ldb, s *vl, s *vu, int *il, int *iu, s *abstol, int *m, s *w, s *z, int *ldz, s *work, int *lwork, int *iwork, int *ifail, int *info) noexcept nogil
+cdef void ssyrfs(char *uplo, int *n, int *nrhs, s *a, int *lda, s *af, int *ldaf, int *ipiv, s *b, int *ldb, s *x, int *ldx, s *ferr, s *berr, s *work, int *iwork, int *info) noexcept nogil
+cdef void ssysv(char *uplo, int *n, int *nrhs, s *a, int *lda, int *ipiv, s *b, int *ldb, s *work, int *lwork, int *info) noexcept nogil
+cdef void ssysvx(char *fact, char *uplo, int *n, int *nrhs, s *a, int *lda, s *af, int *ldaf, int *ipiv, s *b, int *ldb, s *x, int *ldx, s *rcond, s *ferr, s *berr, s *work, int *lwork, int *iwork, int *info) noexcept nogil
+cdef void ssyswapr(char *uplo, int *n, s *a, int *lda, int *i1, int *i2) noexcept nogil
+cdef void ssytd2(char *uplo, int *n, s *a, int *lda, s *d, s *e, s *tau, int *info) noexcept nogil
+cdef void ssytf2(char *uplo, int *n, s *a, int *lda, int *ipiv, int *info) noexcept nogil
+cdef void ssytrd(char *uplo, int *n, s *a, int *lda, s *d, s *e, s *tau, s *work, int *lwork, int *info) noexcept nogil
+cdef void ssytrf(char *uplo, int *n, s *a, int *lda, int *ipiv, s *work, int *lwork, int *info) noexcept nogil
+cdef void ssytri(char *uplo, int *n, s *a, int *lda, int *ipiv, s *work, int *info) noexcept nogil
+cdef void ssytri2(char *uplo, int *n, s *a, int *lda, int *ipiv, s *work, int *lwork, int *info) noexcept nogil
+cdef void ssytri2x(char *uplo, int *n, s *a, int *lda, int *ipiv, s *work, int *nb, int *info) noexcept nogil
+cdef void ssytrs(char *uplo, int *n, int *nrhs, s *a, int *lda, int *ipiv, s *b, int *ldb, int *info) noexcept nogil
+cdef void ssytrs2(char *uplo, int *n, int *nrhs, s *a, int *lda, int *ipiv, s *b, int *ldb, s *work, int *info) noexcept nogil
+cdef void stbcon(char *norm, char *uplo, char *diag, int *n, int *kd, s *ab, int *ldab, s *rcond, s *work, int *iwork, int *info) noexcept nogil
+cdef void stbrfs(char *uplo, char *trans, char *diag, int *n, int *kd, int *nrhs, s *ab, int *ldab, s *b, int *ldb, s *x, int *ldx, s *ferr, s *berr, s *work, int *iwork, int *info) noexcept nogil
+cdef void stbtrs(char *uplo, char *trans, char *diag, int *n, int *kd, int *nrhs, s *ab, int *ldab, s *b, int *ldb, int *info) noexcept nogil
+cdef void stfsm(char *transr, char *side, char *uplo, char *trans, char *diag, int *m, int *n, s *alpha, s *a, s *b, int *ldb) noexcept nogil
+cdef void stftri(char *transr, char *uplo, char *diag, int *n, s *a, int *info) noexcept nogil
+cdef void stfttp(char *transr, char *uplo, int *n, s *arf, s *ap, int *info) noexcept nogil
+cdef void stfttr(char *transr, char *uplo, int *n, s *arf, s *a, int *lda, int *info) noexcept nogil
+cdef void stgevc(char *side, char *howmny, bint *select, int *n, s *s, int *lds, s *p, int *ldp, s *vl, int *ldvl, s *vr, int *ldvr, int *mm, int *m, s *work, int *info) noexcept nogil
+cdef void stgex2(bint *wantq, bint *wantz, int *n, s *a, int *lda, s *b, int *ldb, s *q, int *ldq, s *z, int *ldz, int *j1, int *n1, int *n2, s *work, int *lwork, int *info) noexcept nogil
+cdef void stgexc(bint *wantq, bint *wantz, int *n, s *a, int *lda, s *b, int *ldb, s *q, int *ldq, s *z, int *ldz, int *ifst, int *ilst, s *work, int *lwork, int *info) noexcept nogil
+cdef void stgsen(int *ijob, bint *wantq, bint *wantz, bint *select, int *n, s *a, int *lda, s *b, int *ldb, s *alphar, s *alphai, s *beta, s *q, int *ldq, s *z, int *ldz, int *m, s *pl, s *pr, s *dif, s *work, int *lwork, int *iwork, int *liwork, int *info) noexcept nogil
+cdef void stgsja(char *jobu, char *jobv, char *jobq, int *m, int *p, int *n, int *k, int *l, s *a, int *lda, s *b, int *ldb, s *tola, s *tolb, s *alpha, s *beta, s *u, int *ldu, s *v, int *ldv, s *q, int *ldq, s *work, int *ncycle, int *info) noexcept nogil
+cdef void stgsna(char *job, char *howmny, bint *select, int *n, s *a, int *lda, s *b, int *ldb, s *vl, int *ldvl, s *vr, int *ldvr, s *s, s *dif, int *mm, int *m, s *work, int *lwork, int *iwork, int *info) noexcept nogil
+cdef void stgsy2(char *trans, int *ijob, int *m, int *n, s *a, int *lda, s *b, int *ldb, s *c, int *ldc, s *d, int *ldd, s *e, int *lde, s *f, int *ldf, s *scale, s *rdsum, s *rdscal, int *iwork, int *pq, int *info) noexcept nogil
+cdef void stgsyl(char *trans, int *ijob, int *m, int *n, s *a, int *lda, s *b, int *ldb, s *c, int *ldc, s *d, int *ldd, s *e, int *lde, s *f, int *ldf, s *scale, s *dif, s *work, int *lwork, int *iwork, int *info) noexcept nogil
+cdef void stpcon(char *norm, char *uplo, char *diag, int *n, s *ap, s *rcond, s *work, int *iwork, int *info) noexcept nogil
+cdef void stpmqrt(char *side, char *trans, int *m, int *n, int *k, int *l, int *nb, s *v, int *ldv, s *t, int *ldt, s *a, int *lda, s *b, int *ldb, s *work, int *info) noexcept nogil
+cdef void stpqrt(int *m, int *n, int *l, int *nb, s *a, int *lda, s *b, int *ldb, s *t, int *ldt, s *work, int *info) noexcept nogil
+cdef void stpqrt2(int *m, int *n, int *l, s *a, int *lda, s *b, int *ldb, s *t, int *ldt, int *info) noexcept nogil
+cdef void stprfb(char *side, char *trans, char *direct, char *storev, int *m, int *n, int *k, int *l, s *v, int *ldv, s *t, int *ldt, s *a, int *lda, s *b, int *ldb, s *work, int *ldwork) noexcept nogil
+cdef void stprfs(char *uplo, char *trans, char *diag, int *n, int *nrhs, s *ap, s *b, int *ldb, s *x, int *ldx, s *ferr, s *berr, s *work, int *iwork, int *info) noexcept nogil
+cdef void stptri(char *uplo, char *diag, int *n, s *ap, int *info) noexcept nogil
+cdef void stptrs(char *uplo, char *trans, char *diag, int *n, int *nrhs, s *ap, s *b, int *ldb, int *info) noexcept nogil
+cdef void stpttf(char *transr, char *uplo, int *n, s *ap, s *arf, int *info) noexcept nogil
+cdef void stpttr(char *uplo, int *n, s *ap, s *a, int *lda, int *info) noexcept nogil
+cdef void strcon(char *norm, char *uplo, char *diag, int *n, s *a, int *lda, s *rcond, s *work, int *iwork, int *info) noexcept nogil
+cdef void strevc(char *side, char *howmny, bint *select, int *n, s *t, int *ldt, s *vl, int *ldvl, s *vr, int *ldvr, int *mm, int *m, s *work, int *info) noexcept nogil
+cdef void strexc(char *compq, int *n, s *t, int *ldt, s *q, int *ldq, int *ifst, int *ilst, s *work, int *info) noexcept nogil
+cdef void strrfs(char *uplo, char *trans, char *diag, int *n, int *nrhs, s *a, int *lda, s *b, int *ldb, s *x, int *ldx, s *ferr, s *berr, s *work, int *iwork, int *info) noexcept nogil
+cdef void strsen(char *job, char *compq, bint *select, int *n, s *t, int *ldt, s *q, int *ldq, s *wr, s *wi, int *m, s *s, s *sep, s *work, int *lwork, int *iwork, int *liwork, int *info) noexcept nogil
+cdef void strsna(char *job, char *howmny, bint *select, int *n, s *t, int *ldt, s *vl, int *ldvl, s *vr, int *ldvr, s *s, s *sep, int *mm, int *m, s *work, int *ldwork, int *iwork, int *info) noexcept nogil
+cdef void strsyl(char *trana, char *tranb, int *isgn, int *m, int *n, s *a, int *lda, s *b, int *ldb, s *c, int *ldc, s *scale, int *info) noexcept nogil
+cdef void strti2(char *uplo, char *diag, int *n, s *a, int *lda, int *info) noexcept nogil
+cdef void strtri(char *uplo, char *diag, int *n, s *a, int *lda, int *info) noexcept nogil
+cdef void strtrs(char *uplo, char *trans, char *diag, int *n, int *nrhs, s *a, int *lda, s *b, int *ldb, int *info) noexcept nogil
+cdef void strttf(char *transr, char *uplo, int *n, s *a, int *lda, s *arf, int *info) noexcept nogil
+cdef void strttp(char *uplo, int *n, s *a, int *lda, s *ap, int *info) noexcept nogil
+cdef void stzrzf(int *m, int *n, s *a, int *lda, s *tau, s *work, int *lwork, int *info) noexcept nogil
+cdef void xerbla_array(char *srname_array, int *srname_len, int *info) noexcept nogil
+cdef void zbbcsd(char *jobu1, char *jobu2, char *jobv1t, char *jobv2t, char *trans, int *m, int *p, int *q, d *theta, d *phi, z *u1, int *ldu1, z *u2, int *ldu2, z *v1t, int *ldv1t, z *v2t, int *ldv2t, d *b11d, d *b11e, d *b12d, d *b12e, d *b21d, d *b21e, d *b22d, d *b22e, d *rwork, int *lrwork, int *info) noexcept nogil
+cdef void zbdsqr(char *uplo, int *n, int *ncvt, int *nru, int *ncc, d *d, d *e, z *vt, int *ldvt, z *u, int *ldu, z *c, int *ldc, d *rwork, int *info) noexcept nogil
+cdef void zcgesv(int *n, int *nrhs, z *a, int *lda, int *ipiv, z *b, int *ldb, z *x, int *ldx, z *work, c *swork, d *rwork, int *iter, int *info) noexcept nogil
+cdef void zcposv(char *uplo, int *n, int *nrhs, z *a, int *lda, z *b, int *ldb, z *x, int *ldx, z *work, c *swork, d *rwork, int *iter, int *info) noexcept nogil
+cdef void zdrscl(int *n, d *sa, z *sx, int *incx) noexcept nogil
+cdef void zgbbrd(char *vect, int *m, int *n, int *ncc, int *kl, int *ku, z *ab, int *ldab, d *d, d *e, z *q, int *ldq, z *pt, int *ldpt, z *c, int *ldc, z *work, d *rwork, int *info) noexcept nogil
+cdef void zgbcon(char *norm, int *n, int *kl, int *ku, z *ab, int *ldab, int *ipiv, d *anorm, d *rcond, z *work, d *rwork, int *info) noexcept nogil
+cdef void zgbequ(int *m, int *n, int *kl, int *ku, z *ab, int *ldab, d *r, d *c, d *rowcnd, d *colcnd, d *amax, int *info) noexcept nogil
+cdef void zgbequb(int *m, int *n, int *kl, int *ku, z *ab, int *ldab, d *r, d *c, d *rowcnd, d *colcnd, d *amax, int *info) noexcept nogil
+cdef void zgbrfs(char *trans, int *n, int *kl, int *ku, int *nrhs, z *ab, int *ldab, z *afb, int *ldafb, int *ipiv, z *b, int *ldb, z *x, int *ldx, d *ferr, d *berr, z *work, d *rwork, int *info) noexcept nogil
+cdef void zgbsv(int *n, int *kl, int *ku, int *nrhs, z *ab, int *ldab, int *ipiv, z *b, int *ldb, int *info) noexcept nogil
+cdef void zgbsvx(char *fact, char *trans, int *n, int *kl, int *ku, int *nrhs, z *ab, int *ldab, z *afb, int *ldafb, int *ipiv, char *equed, d *r, d *c, z *b, int *ldb, z *x, int *ldx, d *rcond, d *ferr, d *berr, z *work, d *rwork, int *info) noexcept nogil
+cdef void zgbtf2(int *m, int *n, int *kl, int *ku, z *ab, int *ldab, int *ipiv, int *info) noexcept nogil
+cdef void zgbtrf(int *m, int *n, int *kl, int *ku, z *ab, int *ldab, int *ipiv, int *info) noexcept nogil
+cdef void zgbtrs(char *trans, int *n, int *kl, int *ku, int *nrhs, z *ab, int *ldab, int *ipiv, z *b, int *ldb, int *info) noexcept nogil
+cdef void zgebak(char *job, char *side, int *n, int *ilo, int *ihi, d *scale, int *m, z *v, int *ldv, int *info) noexcept nogil
+cdef void zgebal(char *job, int *n, z *a, int *lda, int *ilo, int *ihi, d *scale, int *info) noexcept nogil
+cdef void zgebd2(int *m, int *n, z *a, int *lda, d *d, d *e, z *tauq, z *taup, z *work, int *info) noexcept nogil
+cdef void zgebrd(int *m, int *n, z *a, int *lda, d *d, d *e, z *tauq, z *taup, z *work, int *lwork, int *info) noexcept nogil
+cdef void zgecon(char *norm, int *n, z *a, int *lda, d *anorm, d *rcond, z *work, d *rwork, int *info) noexcept nogil
+cdef void zgeequ(int *m, int *n, z *a, int *lda, d *r, d *c, d *rowcnd, d *colcnd, d *amax, int *info) noexcept nogil
+cdef void zgeequb(int *m, int *n, z *a, int *lda, d *r, d *c, d *rowcnd, d *colcnd, d *amax, int *info) noexcept nogil
+cdef void zgees(char *jobvs, char *sort, zselect1 *select, int *n, z *a, int *lda, int *sdim, z *w, z *vs, int *ldvs, z *work, int *lwork, d *rwork, bint *bwork, int *info) noexcept nogil
+cdef void zgeesx(char *jobvs, char *sort, zselect1 *select, char *sense, int *n, z *a, int *lda, int *sdim, z *w, z *vs, int *ldvs, d *rconde, d *rcondv, z *work, int *lwork, d *rwork, bint *bwork, int *info) noexcept nogil
+cdef void zgeev(char *jobvl, char *jobvr, int *n, z *a, int *lda, z *w, z *vl, int *ldvl, z *vr, int *ldvr, z *work, int *lwork, d *rwork, int *info) noexcept nogil
+cdef void zgeevx(char *balanc, char *jobvl, char *jobvr, char *sense, int *n, z *a, int *lda, z *w, z *vl, int *ldvl, z *vr, int *ldvr, int *ilo, int *ihi, d *scale, d *abnrm, d *rconde, d *rcondv, z *work, int *lwork, d *rwork, int *info) noexcept nogil
+cdef void zgehd2(int *n, int *ilo, int *ihi, z *a, int *lda, z *tau, z *work, int *info) noexcept nogil
+cdef void zgehrd(int *n, int *ilo, int *ihi, z *a, int *lda, z *tau, z *work, int *lwork, int *info) noexcept nogil
+cdef void zgelq2(int *m, int *n, z *a, int *lda, z *tau, z *work, int *info) noexcept nogil
+cdef void zgelqf(int *m, int *n, z *a, int *lda, z *tau, z *work, int *lwork, int *info) noexcept nogil
+cdef void zgels(char *trans, int *m, int *n, int *nrhs, z *a, int *lda, z *b, int *ldb, z *work, int *lwork, int *info) noexcept nogil
+cdef void zgelsd(int *m, int *n, int *nrhs, z *a, int *lda, z *b, int *ldb, d *s, d *rcond, int *rank, z *work, int *lwork, d *rwork, int *iwork, int *info) noexcept nogil
+cdef void zgelss(int *m, int *n, int *nrhs, z *a, int *lda, z *b, int *ldb, d *s, d *rcond, int *rank, z *work, int *lwork, d *rwork, int *info) noexcept nogil
+cdef void zgelsy(int *m, int *n, int *nrhs, z *a, int *lda, z *b, int *ldb, int *jpvt, d *rcond, int *rank, z *work, int *lwork, d *rwork, int *info) noexcept nogil
+cdef void zgemqrt(char *side, char *trans, int *m, int *n, int *k, int *nb, z *v, int *ldv, z *t, int *ldt, z *c, int *ldc, z *work, int *info) noexcept nogil
+cdef void zgeql2(int *m, int *n, z *a, int *lda, z *tau, z *work, int *info) noexcept nogil
+cdef void zgeqlf(int *m, int *n, z *a, int *lda, z *tau, z *work, int *lwork, int *info) noexcept nogil
+cdef void zgeqp3(int *m, int *n, z *a, int *lda, int *jpvt, z *tau, z *work, int *lwork, d *rwork, int *info) noexcept nogil
+cdef void zgeqr2(int *m, int *n, z *a, int *lda, z *tau, z *work, int *info) noexcept nogil
+cdef void zgeqr2p(int *m, int *n, z *a, int *lda, z *tau, z *work, int *info) noexcept nogil
+cdef void zgeqrf(int *m, int *n, z *a, int *lda, z *tau, z *work, int *lwork, int *info) noexcept nogil
+cdef void zgeqrfp(int *m, int *n, z *a, int *lda, z *tau, z *work, int *lwork, int *info) noexcept nogil
+cdef void zgeqrt(int *m, int *n, int *nb, z *a, int *lda, z *t, int *ldt, z *work, int *info) noexcept nogil
+cdef void zgeqrt2(int *m, int *n, z *a, int *lda, z *t, int *ldt, int *info) noexcept nogil
+cdef void zgeqrt3(int *m, int *n, z *a, int *lda, z *t, int *ldt, int *info) noexcept nogil
+cdef void zgerfs(char *trans, int *n, int *nrhs, z *a, int *lda, z *af, int *ldaf, int *ipiv, z *b, int *ldb, z *x, int *ldx, d *ferr, d *berr, z *work, d *rwork, int *info) noexcept nogil
+cdef void zgerq2(int *m, int *n, z *a, int *lda, z *tau, z *work, int *info) noexcept nogil
+cdef void zgerqf(int *m, int *n, z *a, int *lda, z *tau, z *work, int *lwork, int *info) noexcept nogil
+cdef void zgesc2(int *n, z *a, int *lda, z *rhs, int *ipiv, int *jpiv, d *scale) noexcept nogil
+cdef void zgesdd(char *jobz, int *m, int *n, z *a, int *lda, d *s, z *u, int *ldu, z *vt, int *ldvt, z *work, int *lwork, d *rwork, int *iwork, int *info) noexcept nogil
+cdef void zgesv(int *n, int *nrhs, z *a, int *lda, int *ipiv, z *b, int *ldb, int *info) noexcept nogil
+cdef void zgesvd(char *jobu, char *jobvt, int *m, int *n, z *a, int *lda, d *s, z *u, int *ldu, z *vt, int *ldvt, z *work, int *lwork, d *rwork, int *info) noexcept nogil
+cdef void zgesvx(char *fact, char *trans, int *n, int *nrhs, z *a, int *lda, z *af, int *ldaf, int *ipiv, char *equed, d *r, d *c, z *b, int *ldb, z *x, int *ldx, d *rcond, d *ferr, d *berr, z *work, d *rwork, int *info) noexcept nogil
+cdef void zgetc2(int *n, z *a, int *lda, int *ipiv, int *jpiv, int *info) noexcept nogil
+cdef void zgetf2(int *m, int *n, z *a, int *lda, int *ipiv, int *info) noexcept nogil
+cdef void zgetrf(int *m, int *n, z *a, int *lda, int *ipiv, int *info) noexcept nogil
+cdef void zgetri(int *n, z *a, int *lda, int *ipiv, z *work, int *lwork, int *info) noexcept nogil
+cdef void zgetrs(char *trans, int *n, int *nrhs, z *a, int *lda, int *ipiv, z *b, int *ldb, int *info) noexcept nogil
+cdef void zggbak(char *job, char *side, int *n, int *ilo, int *ihi, d *lscale, d *rscale, int *m, z *v, int *ldv, int *info) noexcept nogil
+cdef void zggbal(char *job, int *n, z *a, int *lda, z *b, int *ldb, int *ilo, int *ihi, d *lscale, d *rscale, d *work, int *info) noexcept nogil
+cdef void zgges(char *jobvsl, char *jobvsr, char *sort, zselect2 *selctg, int *n, z *a, int *lda, z *b, int *ldb, int *sdim, z *alpha, z *beta, z *vsl, int *ldvsl, z *vsr, int *ldvsr, z *work, int *lwork, d *rwork, bint *bwork, int *info) noexcept nogil
+cdef void zggesx(char *jobvsl, char *jobvsr, char *sort, zselect2 *selctg, char *sense, int *n, z *a, int *lda, z *b, int *ldb, int *sdim, z *alpha, z *beta, z *vsl, int *ldvsl, z *vsr, int *ldvsr, d *rconde, d *rcondv, z *work, int *lwork, d *rwork, int *iwork, int *liwork, bint *bwork, int *info) noexcept nogil
+cdef void zggev(char *jobvl, char *jobvr, int *n, z *a, int *lda, z *b, int *ldb, z *alpha, z *beta, z *vl, int *ldvl, z *vr, int *ldvr, z *work, int *lwork, d *rwork, int *info) noexcept nogil
+cdef void zggevx(char *balanc, char *jobvl, char *jobvr, char *sense, int *n, z *a, int *lda, z *b, int *ldb, z *alpha, z *beta, z *vl, int *ldvl, z *vr, int *ldvr, int *ilo, int *ihi, d *lscale, d *rscale, d *abnrm, d *bbnrm, d *rconde, d *rcondv, z *work, int *lwork, d *rwork, int *iwork, bint *bwork, int *info) noexcept nogil
+cdef void zggglm(int *n, int *m, int *p, z *a, int *lda, z *b, int *ldb, z *d, z *x, z *y, z *work, int *lwork, int *info) noexcept nogil
+cdef void zgghrd(char *compq, char *compz, int *n, int *ilo, int *ihi, z *a, int *lda, z *b, int *ldb, z *q, int *ldq, z *z, int *ldz, int *info) noexcept nogil
+cdef void zgglse(int *m, int *n, int *p, z *a, int *lda, z *b, int *ldb, z *c, z *d, z *x, z *work, int *lwork, int *info) noexcept nogil
+cdef void zggqrf(int *n, int *m, int *p, z *a, int *lda, z *taua, z *b, int *ldb, z *taub, z *work, int *lwork, int *info) noexcept nogil
+cdef void zggrqf(int *m, int *p, int *n, z *a, int *lda, z *taua, z *b, int *ldb, z *taub, z *work, int *lwork, int *info) noexcept nogil
+cdef void zgtcon(char *norm, int *n, z *dl, z *d, z *du, z *du2, int *ipiv, d *anorm, d *rcond, z *work, int *info) noexcept nogil
+cdef void zgtrfs(char *trans, int *n, int *nrhs, z *dl, z *d, z *du, z *dlf, z *df, z *duf, z *du2, int *ipiv, z *b, int *ldb, z *x, int *ldx, d *ferr, d *berr, z *work, d *rwork, int *info) noexcept nogil
+cdef void zgtsv(int *n, int *nrhs, z *dl, z *d, z *du, z *b, int *ldb, int *info) noexcept nogil
+cdef void zgtsvx(char *fact, char *trans, int *n, int *nrhs, z *dl, z *d, z *du, z *dlf, z *df, z *duf, z *du2, int *ipiv, z *b, int *ldb, z *x, int *ldx, d *rcond, d *ferr, d *berr, z *work, d *rwork, int *info) noexcept nogil
+cdef void zgttrf(int *n, z *dl, z *d, z *du, z *du2, int *ipiv, int *info) noexcept nogil
+cdef void zgttrs(char *trans, int *n, int *nrhs, z *dl, z *d, z *du, z *du2, int *ipiv, z *b, int *ldb, int *info) noexcept nogil
+cdef void zgtts2(int *itrans, int *n, int *nrhs, z *dl, z *d, z *du, z *du2, int *ipiv, z *b, int *ldb) noexcept nogil
+cdef void zhbev(char *jobz, char *uplo, int *n, int *kd, z *ab, int *ldab, d *w, z *z, int *ldz, z *work, d *rwork, int *info) noexcept nogil
+cdef void zhbevd(char *jobz, char *uplo, int *n, int *kd, z *ab, int *ldab, d *w, z *z, int *ldz, z *work, int *lwork, d *rwork, int *lrwork, int *iwork, int *liwork, int *info) noexcept nogil
+cdef void zhbevx(char *jobz, char *range, char *uplo, int *n, int *kd, z *ab, int *ldab, z *q, int *ldq, d *vl, d *vu, int *il, int *iu, d *abstol, int *m, d *w, z *z, int *ldz, z *work, d *rwork, int *iwork, int *ifail, int *info) noexcept nogil
+cdef void zhbgst(char *vect, char *uplo, int *n, int *ka, int *kb, z *ab, int *ldab, z *bb, int *ldbb, z *x, int *ldx, z *work, d *rwork, int *info) noexcept nogil
+cdef void zhbgv(char *jobz, char *uplo, int *n, int *ka, int *kb, z *ab, int *ldab, z *bb, int *ldbb, d *w, z *z, int *ldz, z *work, d *rwork, int *info) noexcept nogil
+cdef void zhbgvd(char *jobz, char *uplo, int *n, int *ka, int *kb, z *ab, int *ldab, z *bb, int *ldbb, d *w, z *z, int *ldz, z *work, int *lwork, d *rwork, int *lrwork, int *iwork, int *liwork, int *info) noexcept nogil
+cdef void zhbgvx(char *jobz, char *range, char *uplo, int *n, int *ka, int *kb, z *ab, int *ldab, z *bb, int *ldbb, z *q, int *ldq, d *vl, d *vu, int *il, int *iu, d *abstol, int *m, d *w, z *z, int *ldz, z *work, d *rwork, int *iwork, int *ifail, int *info) noexcept nogil
+cdef void zhbtrd(char *vect, char *uplo, int *n, int *kd, z *ab, int *ldab, d *d, d *e, z *q, int *ldq, z *work, int *info) noexcept nogil
+cdef void zhecon(char *uplo, int *n, z *a, int *lda, int *ipiv, d *anorm, d *rcond, z *work, int *info) noexcept nogil
+cdef void zheequb(char *uplo, int *n, z *a, int *lda, d *s, d *scond, d *amax, z *work, int *info) noexcept nogil
+cdef void zheev(char *jobz, char *uplo, int *n, z *a, int *lda, d *w, z *work, int *lwork, d *rwork, int *info) noexcept nogil
+cdef void zheevd(char *jobz, char *uplo, int *n, z *a, int *lda, d *w, z *work, int *lwork, d *rwork, int *lrwork, int *iwork, int *liwork, int *info) noexcept nogil
+cdef void zheevr(char *jobz, char *range, char *uplo, int *n, z *a, int *lda, d *vl, d *vu, int *il, int *iu, d *abstol, int *m, d *w, z *z, int *ldz, int *isuppz, z *work, int *lwork, d *rwork, int *lrwork, int *iwork, int *liwork, int *info) noexcept nogil
+cdef void zheevx(char *jobz, char *range, char *uplo, int *n, z *a, int *lda, d *vl, d *vu, int *il, int *iu, d *abstol, int *m, d *w, z *z, int *ldz, z *work, int *lwork, d *rwork, int *iwork, int *ifail, int *info) noexcept nogil
+cdef void zhegs2(int *itype, char *uplo, int *n, z *a, int *lda, z *b, int *ldb, int *info) noexcept nogil
+cdef void zhegst(int *itype, char *uplo, int *n, z *a, int *lda, z *b, int *ldb, int *info) noexcept nogil
+cdef void zhegv(int *itype, char *jobz, char *uplo, int *n, z *a, int *lda, z *b, int *ldb, d *w, z *work, int *lwork, d *rwork, int *info) noexcept nogil
+cdef void zhegvd(int *itype, char *jobz, char *uplo, int *n, z *a, int *lda, z *b, int *ldb, d *w, z *work, int *lwork, d *rwork, int *lrwork, int *iwork, int *liwork, int *info) noexcept nogil
+cdef void zhegvx(int *itype, char *jobz, char *range, char *uplo, int *n, z *a, int *lda, z *b, int *ldb, d *vl, d *vu, int *il, int *iu, d *abstol, int *m, d *w, z *z, int *ldz, z *work, int *lwork, d *rwork, int *iwork, int *ifail, int *info) noexcept nogil
+cdef void zherfs(char *uplo, int *n, int *nrhs, z *a, int *lda, z *af, int *ldaf, int *ipiv, z *b, int *ldb, z *x, int *ldx, d *ferr, d *berr, z *work, d *rwork, int *info) noexcept nogil
+cdef void zhesv(char *uplo, int *n, int *nrhs, z *a, int *lda, int *ipiv, z *b, int *ldb, z *work, int *lwork, int *info) noexcept nogil
+cdef void zhesvx(char *fact, char *uplo, int *n, int *nrhs, z *a, int *lda, z *af, int *ldaf, int *ipiv, z *b, int *ldb, z *x, int *ldx, d *rcond, d *ferr, d *berr, z *work, int *lwork, d *rwork, int *info) noexcept nogil
+cdef void zheswapr(char *uplo, int *n, z *a, int *lda, int *i1, int *i2) noexcept nogil
+cdef void zhetd2(char *uplo, int *n, z *a, int *lda, d *d, d *e, z *tau, int *info) noexcept nogil
+cdef void zhetf2(char *uplo, int *n, z *a, int *lda, int *ipiv, int *info) noexcept nogil
+cdef void zhetrd(char *uplo, int *n, z *a, int *lda, d *d, d *e, z *tau, z *work, int *lwork, int *info) noexcept nogil
+cdef void zhetrf(char *uplo, int *n, z *a, int *lda, int *ipiv, z *work, int *lwork, int *info) noexcept nogil
+cdef void zhetri(char *uplo, int *n, z *a, int *lda, int *ipiv, z *work, int *info) noexcept nogil
+cdef void zhetri2(char *uplo, int *n, z *a, int *lda, int *ipiv, z *work, int *lwork, int *info) noexcept nogil
+cdef void zhetri2x(char *uplo, int *n, z *a, int *lda, int *ipiv, z *work, int *nb, int *info) noexcept nogil
+cdef void zhetrs(char *uplo, int *n, int *nrhs, z *a, int *lda, int *ipiv, z *b, int *ldb, int *info) noexcept nogil
+cdef void zhetrs2(char *uplo, int *n, int *nrhs, z *a, int *lda, int *ipiv, z *b, int *ldb, z *work, int *info) noexcept nogil
+cdef void zhfrk(char *transr, char *uplo, char *trans, int *n, int *k, d *alpha, z *a, int *lda, d *beta, z *c) noexcept nogil
+cdef void zhgeqz(char *job, char *compq, char *compz, int *n, int *ilo, int *ihi, z *h, int *ldh, z *t, int *ldt, z *alpha, z *beta, z *q, int *ldq, z *z, int *ldz, z *work, int *lwork, d *rwork, int *info) noexcept nogil
+cdef void zhpcon(char *uplo, int *n, z *ap, int *ipiv, d *anorm, d *rcond, z *work, int *info) noexcept nogil
+cdef void zhpev(char *jobz, char *uplo, int *n, z *ap, d *w, z *z, int *ldz, z *work, d *rwork, int *info) noexcept nogil
+cdef void zhpevd(char *jobz, char *uplo, int *n, z *ap, d *w, z *z, int *ldz, z *work, int *lwork, d *rwork, int *lrwork, int *iwork, int *liwork, int *info) noexcept nogil
+cdef void zhpevx(char *jobz, char *range, char *uplo, int *n, z *ap, d *vl, d *vu, int *il, int *iu, d *abstol, int *m, d *w, z *z, int *ldz, z *work, d *rwork, int *iwork, int *ifail, int *info) noexcept nogil
+cdef void zhpgst(int *itype, char *uplo, int *n, z *ap, z *bp, int *info) noexcept nogil
+cdef void zhpgv(int *itype, char *jobz, char *uplo, int *n, z *ap, z *bp, d *w, z *z, int *ldz, z *work, d *rwork, int *info) noexcept nogil
+cdef void zhpgvd(int *itype, char *jobz, char *uplo, int *n, z *ap, z *bp, d *w, z *z, int *ldz, z *work, int *lwork, d *rwork, int *lrwork, int *iwork, int *liwork, int *info) noexcept nogil
+cdef void zhpgvx(int *itype, char *jobz, char *range, char *uplo, int *n, z *ap, z *bp, d *vl, d *vu, int *il, int *iu, d *abstol, int *m, d *w, z *z, int *ldz, z *work, d *rwork, int *iwork, int *ifail, int *info) noexcept nogil
+cdef void zhprfs(char *uplo, int *n, int *nrhs, z *ap, z *afp, int *ipiv, z *b, int *ldb, z *x, int *ldx, d *ferr, d *berr, z *work, d *rwork, int *info) noexcept nogil
+cdef void zhpsv(char *uplo, int *n, int *nrhs, z *ap, int *ipiv, z *b, int *ldb, int *info) noexcept nogil
+cdef void zhpsvx(char *fact, char *uplo, int *n, int *nrhs, z *ap, z *afp, int *ipiv, z *b, int *ldb, z *x, int *ldx, d *rcond, d *ferr, d *berr, z *work, d *rwork, int *info) noexcept nogil
+cdef void zhptrd(char *uplo, int *n, z *ap, d *d, d *e, z *tau, int *info) noexcept nogil
+cdef void zhptrf(char *uplo, int *n, z *ap, int *ipiv, int *info) noexcept nogil
+cdef void zhptri(char *uplo, int *n, z *ap, int *ipiv, z *work, int *info) noexcept nogil
+cdef void zhptrs(char *uplo, int *n, int *nrhs, z *ap, int *ipiv, z *b, int *ldb, int *info) noexcept nogil
+cdef void zhsein(char *side, char *eigsrc, char *initv, bint *select, int *n, z *h, int *ldh, z *w, z *vl, int *ldvl, z *vr, int *ldvr, int *mm, int *m, z *work, d *rwork, int *ifaill, int *ifailr, int *info) noexcept nogil
+cdef void zhseqr(char *job, char *compz, int *n, int *ilo, int *ihi, z *h, int *ldh, z *w, z *z, int *ldz, z *work, int *lwork, int *info) noexcept nogil
+cdef void zlabrd(int *m, int *n, int *nb, z *a, int *lda, d *d, d *e, z *tauq, z *taup, z *x, int *ldx, z *y, int *ldy) noexcept nogil
+cdef void zlacgv(int *n, z *x, int *incx) noexcept nogil
+cdef void zlacn2(int *n, z *v, z *x, d *est, int *kase, int *isave) noexcept nogil
+cdef void zlacon(int *n, z *v, z *x, d *est, int *kase) noexcept nogil
+cdef void zlacp2(char *uplo, int *m, int *n, d *a, int *lda, z *b, int *ldb) noexcept nogil
+cdef void zlacpy(char *uplo, int *m, int *n, z *a, int *lda, z *b, int *ldb) noexcept nogil
+cdef void zlacrm(int *m, int *n, z *a, int *lda, d *b, int *ldb, z *c, int *ldc, d *rwork) noexcept nogil
+cdef void zlacrt(int *n, z *cx, int *incx, z *cy, int *incy, z *c, z *s) noexcept nogil
+cdef z zladiv(z *x, z *y) noexcept nogil
+cdef void zlaed0(int *qsiz, int *n, d *d, d *e, z *q, int *ldq, z *qstore, int *ldqs, d *rwork, int *iwork, int *info) noexcept nogil
+cdef void zlaed7(int *n, int *cutpnt, int *qsiz, int *tlvls, int *curlvl, int *curpbm, d *d, z *q, int *ldq, d *rho, int *indxq, d *qstore, int *qptr, int *prmptr, int *perm, int *givptr, int *givcol, d *givnum, z *work, d *rwork, int *iwork, int *info) noexcept nogil
+cdef void zlaed8(int *k, int *n, int *qsiz, z *q, int *ldq, d *d, d *rho, int *cutpnt, d *z, d *dlamda, z *q2, int *ldq2, d *w, int *indxp, int *indx, int *indxq, int *perm, int *givptr, int *givcol, d *givnum, int *info) noexcept nogil
+cdef void zlaein(bint *rightv, bint *noinit, int *n, z *h, int *ldh, z *w, z *v, z *b, int *ldb, d *rwork, d *eps3, d *smlnum, int *info) noexcept nogil
+cdef void zlaesy(z *a, z *b, z *c, z *rt1, z *rt2, z *evscal, z *cs1, z *sn1) noexcept nogil
+cdef void zlaev2(z *a, z *b, z *c, d *rt1, d *rt2, d *cs1, z *sn1) noexcept nogil
+cdef void zlag2c(int *m, int *n, z *a, int *lda, c *sa, int *ldsa, int *info) noexcept nogil
+cdef void zlags2(bint *upper, d *a1, z *a2, d *a3, d *b1, z *b2, d *b3, d *csu, z *snu, d *csv, z *snv, d *csq, z *snq) noexcept nogil
+cdef void zlagtm(char *trans, int *n, int *nrhs, d *alpha, z *dl, z *d, z *du, z *x, int *ldx, d *beta, z *b, int *ldb) noexcept nogil
+cdef void zlahef(char *uplo, int *n, int *nb, int *kb, z *a, int *lda, int *ipiv, z *w, int *ldw, int *info) noexcept nogil
+cdef void zlahqr(bint *wantt, bint *wantz, int *n, int *ilo, int *ihi, z *h, int *ldh, z *w, int *iloz, int *ihiz, z *z, int *ldz, int *info) noexcept nogil
+cdef void zlahr2(int *n, int *k, int *nb, z *a, int *lda, z *tau, z *t, int *ldt, z *y, int *ldy) noexcept nogil
+cdef void zlaic1(int *job, int *j, z *x, d *sest, z *w, z *gamma, d *sestpr, z *s, z *c) noexcept nogil
+cdef void zlals0(int *icompq, int *nl, int *nr, int *sqre, int *nrhs, z *b, int *ldb, z *bx, int *ldbx, int *perm, int *givptr, int *givcol, int *ldgcol, d *givnum, int *ldgnum, d *poles, d *difl, d *difr, d *z, int *k, d *c, d *s, d *rwork, int *info) noexcept nogil
+cdef void zlalsa(int *icompq, int *smlsiz, int *n, int *nrhs, z *b, int *ldb, z *bx, int *ldbx, d *u, int *ldu, d *vt, int *k, d *difl, d *difr, d *z, d *poles, int *givptr, int *givcol, int *ldgcol, int *perm, d *givnum, d *c, d *s, d *rwork, int *iwork, int *info) noexcept nogil
+cdef void zlalsd(char *uplo, int *smlsiz, int *n, int *nrhs, d *d, d *e, z *b, int *ldb, d *rcond, int *rank, z *work, d *rwork, int *iwork, int *info) noexcept nogil
+cdef d zlangb(char *norm, int *n, int *kl, int *ku, z *ab, int *ldab, d *work) noexcept nogil
+cdef d zlange(char *norm, int *m, int *n, z *a, int *lda, d *work) noexcept nogil
+cdef d zlangt(char *norm, int *n, z *dl, z *d_, z *du) noexcept nogil
+cdef d zlanhb(char *norm, char *uplo, int *n, int *k, z *ab, int *ldab, d *work) noexcept nogil
+cdef d zlanhe(char *norm, char *uplo, int *n, z *a, int *lda, d *work) noexcept nogil
+cdef d zlanhf(char *norm, char *transr, char *uplo, int *n, z *a, d *work) noexcept nogil
+cdef d zlanhp(char *norm, char *uplo, int *n, z *ap, d *work) noexcept nogil
+cdef d zlanhs(char *norm, int *n, z *a, int *lda, d *work) noexcept nogil
+cdef d zlanht(char *norm, int *n, d *d_, z *e) noexcept nogil
+cdef d zlansb(char *norm, char *uplo, int *n, int *k, z *ab, int *ldab, d *work) noexcept nogil
+cdef d zlansp(char *norm, char *uplo, int *n, z *ap, d *work) noexcept nogil
+cdef d zlansy(char *norm, char *uplo, int *n, z *a, int *lda, d *work) noexcept nogil
+cdef d zlantb(char *norm, char *uplo, char *diag, int *n, int *k, z *ab, int *ldab, d *work) noexcept nogil
+cdef d zlantp(char *norm, char *uplo, char *diag, int *n, z *ap, d *work) noexcept nogil
+cdef d zlantr(char *norm, char *uplo, char *diag, int *m, int *n, z *a, int *lda, d *work) noexcept nogil
+cdef void zlapll(int *n, z *x, int *incx, z *y, int *incy, d *ssmin) noexcept nogil
+cdef void zlapmr(bint *forwrd, int *m, int *n, z *x, int *ldx, int *k) noexcept nogil
+cdef void zlapmt(bint *forwrd, int *m, int *n, z *x, int *ldx, int *k) noexcept nogil
+cdef void zlaqgb(int *m, int *n, int *kl, int *ku, z *ab, int *ldab, d *r, d *c, d *rowcnd, d *colcnd, d *amax, char *equed) noexcept nogil
+cdef void zlaqge(int *m, int *n, z *a, int *lda, d *r, d *c, d *rowcnd, d *colcnd, d *amax, char *equed) noexcept nogil
+cdef void zlaqhb(char *uplo, int *n, int *kd, z *ab, int *ldab, d *s, d *scond, d *amax, char *equed) noexcept nogil
+cdef void zlaqhe(char *uplo, int *n, z *a, int *lda, d *s, d *scond, d *amax, char *equed) noexcept nogil
+cdef void zlaqhp(char *uplo, int *n, z *ap, d *s, d *scond, d *amax, char *equed) noexcept nogil
+cdef void zlaqp2(int *m, int *n, int *offset, z *a, int *lda, int *jpvt, z *tau, d *vn1, d *vn2, z *work) noexcept nogil
+cdef void zlaqps(int *m, int *n, int *offset, int *nb, int *kb, z *a, int *lda, int *jpvt, z *tau, d *vn1, d *vn2, z *auxv, z *f, int *ldf) noexcept nogil
+cdef void zlaqr0(bint *wantt, bint *wantz, int *n, int *ilo, int *ihi, z *h, int *ldh, z *w, int *iloz, int *ihiz, z *z, int *ldz, z *work, int *lwork, int *info) noexcept nogil
+cdef void zlaqr1(int *n, z *h, int *ldh, z *s1, z *s2, z *v) noexcept nogil
+cdef void zlaqr2(bint *wantt, bint *wantz, int *n, int *ktop, int *kbot, int *nw, z *h, int *ldh, int *iloz, int *ihiz, z *z, int *ldz, int *ns, int *nd, z *sh, z *v, int *ldv, int *nh, z *t, int *ldt, int *nv, z *wv, int *ldwv, z *work, int *lwork) noexcept nogil
+cdef void zlaqr3(bint *wantt, bint *wantz, int *n, int *ktop, int *kbot, int *nw, z *h, int *ldh, int *iloz, int *ihiz, z *z, int *ldz, int *ns, int *nd, z *sh, z *v, int *ldv, int *nh, z *t, int *ldt, int *nv, z *wv, int *ldwv, z *work, int *lwork) noexcept nogil
+cdef void zlaqr4(bint *wantt, bint *wantz, int *n, int *ilo, int *ihi, z *h, int *ldh, z *w, int *iloz, int *ihiz, z *z, int *ldz, z *work, int *lwork, int *info) noexcept nogil
+cdef void zlaqr5(bint *wantt, bint *wantz, int *kacc22, int *n, int *ktop, int *kbot, int *nshfts, z *s, z *h, int *ldh, int *iloz, int *ihiz, z *z, int *ldz, z *v, int *ldv, z *u, int *ldu, int *nv, z *wv, int *ldwv, int *nh, z *wh, int *ldwh) noexcept nogil
+cdef void zlaqsb(char *uplo, int *n, int *kd, z *ab, int *ldab, d *s, d *scond, d *amax, char *equed) noexcept nogil
+cdef void zlaqsp(char *uplo, int *n, z *ap, d *s, d *scond, d *amax, char *equed) noexcept nogil
+cdef void zlaqsy(char *uplo, int *n, z *a, int *lda, d *s, d *scond, d *amax, char *equed) noexcept nogil
+cdef void zlar1v(int *n, int *b1, int *bn, d *lambda_, d *d, d *l, d *ld, d *lld, d *pivmin, d *gaptol, z *z, bint *wantnc, int *negcnt, d *ztz, d *mingma, int *r, int *isuppz, d *nrminv, d *resid, d *rqcorr, d *work) noexcept nogil
+cdef void zlar2v(int *n, z *x, z *y, z *z, int *incx, d *c, z *s, int *incc) noexcept nogil
+cdef void zlarcm(int *m, int *n, d *a, int *lda, z *b, int *ldb, z *c, int *ldc, d *rwork) noexcept nogil
+cdef void zlarf(char *side, int *m, int *n, z *v, int *incv, z *tau, z *c, int *ldc, z *work) noexcept nogil
+cdef void zlarfb(char *side, char *trans, char *direct, char *storev, int *m, int *n, int *k, z *v, int *ldv, z *t, int *ldt, z *c, int *ldc, z *work, int *ldwork) noexcept nogil
+cdef void zlarfg(int *n, z *alpha, z *x, int *incx, z *tau) noexcept nogil
+cdef void zlarfgp(int *n, z *alpha, z *x, int *incx, z *tau) noexcept nogil
+cdef void zlarft(char *direct, char *storev, int *n, int *k, z *v, int *ldv, z *tau, z *t, int *ldt) noexcept nogil
+cdef void zlarfx(char *side, int *m, int *n, z *v, z *tau, z *c, int *ldc, z *work) noexcept nogil
+cdef void zlargv(int *n, z *x, int *incx, z *y, int *incy, d *c, int *incc) noexcept nogil
+cdef void zlarnv(int *idist, int *iseed, int *n, z *x) noexcept nogil
+cdef void zlarrv(int *n, d *vl, d *vu, d *d, d *l, d *pivmin, int *isplit, int *m, int *dol, int *dou, d *minrgp, d *rtol1, d *rtol2, d *w, d *werr, d *wgap, int *iblock, int *indexw, d *gers, z *z, int *ldz, int *isuppz, d *work, int *iwork, int *info) noexcept nogil
+cdef void zlartg(z *f, z *g, d *cs, z *sn, z *r) noexcept nogil
+cdef void zlartv(int *n, z *x, int *incx, z *y, int *incy, d *c, z *s, int *incc) noexcept nogil
+cdef void zlarz(char *side, int *m, int *n, int *l, z *v, int *incv, z *tau, z *c, int *ldc, z *work) noexcept nogil
+cdef void zlarzb(char *side, char *trans, char *direct, char *storev, int *m, int *n, int *k, int *l, z *v, int *ldv, z *t, int *ldt, z *c, int *ldc, z *work, int *ldwork) noexcept nogil
+cdef void zlarzt(char *direct, char *storev, int *n, int *k, z *v, int *ldv, z *tau, z *t, int *ldt) noexcept nogil
+cdef void zlascl(char *type_bn, int *kl, int *ku, d *cfrom, d *cto, int *m, int *n, z *a, int *lda, int *info) noexcept nogil
+cdef void zlaset(char *uplo, int *m, int *n, z *alpha, z *beta, z *a, int *lda) noexcept nogil
+cdef void zlasr(char *side, char *pivot, char *direct, int *m, int *n, d *c, d *s, z *a, int *lda) noexcept nogil
+cdef void zlassq(int *n, z *x, int *incx, d *scale, d *sumsq) noexcept nogil
+cdef void zlaswp(int *n, z *a, int *lda, int *k1, int *k2, int *ipiv, int *incx) noexcept nogil
+cdef void zlasyf(char *uplo, int *n, int *nb, int *kb, z *a, int *lda, int *ipiv, z *w, int *ldw, int *info) noexcept nogil
+cdef void zlat2c(char *uplo, int *n, z *a, int *lda, c *sa, int *ldsa, int *info) noexcept nogil
+cdef void zlatbs(char *uplo, char *trans, char *diag, char *normin, int *n, int *kd, z *ab, int *ldab, z *x, d *scale, d *cnorm, int *info) noexcept nogil
+cdef void zlatdf(int *ijob, int *n, z *z, int *ldz, z *rhs, d *rdsum, d *rdscal, int *ipiv, int *jpiv) noexcept nogil
+cdef void zlatps(char *uplo, char *trans, char *diag, char *normin, int *n, z *ap, z *x, d *scale, d *cnorm, int *info) noexcept nogil
+cdef void zlatrd(char *uplo, int *n, int *nb, z *a, int *lda, d *e, z *tau, z *w, int *ldw) noexcept nogil
+cdef void zlatrs(char *uplo, char *trans, char *diag, char *normin, int *n, z *a, int *lda, z *x, d *scale, d *cnorm, int *info) noexcept nogil
+cdef void zlatrz(int *m, int *n, int *l, z *a, int *lda, z *tau, z *work) noexcept nogil
+cdef void zlauu2(char *uplo, int *n, z *a, int *lda, int *info) noexcept nogil
+cdef void zlauum(char *uplo, int *n, z *a, int *lda, int *info) noexcept nogil
+cdef void zpbcon(char *uplo, int *n, int *kd, z *ab, int *ldab, d *anorm, d *rcond, z *work, d *rwork, int *info) noexcept nogil
+cdef void zpbequ(char *uplo, int *n, int *kd, z *ab, int *ldab, d *s, d *scond, d *amax, int *info) noexcept nogil
+cdef void zpbrfs(char *uplo, int *n, int *kd, int *nrhs, z *ab, int *ldab, z *afb, int *ldafb, z *b, int *ldb, z *x, int *ldx, d *ferr, d *berr, z *work, d *rwork, int *info) noexcept nogil
+cdef void zpbstf(char *uplo, int *n, int *kd, z *ab, int *ldab, int *info) noexcept nogil
+cdef void zpbsv(char *uplo, int *n, int *kd, int *nrhs, z *ab, int *ldab, z *b, int *ldb, int *info) noexcept nogil
+cdef void zpbsvx(char *fact, char *uplo, int *n, int *kd, int *nrhs, z *ab, int *ldab, z *afb, int *ldafb, char *equed, d *s, z *b, int *ldb, z *x, int *ldx, d *rcond, d *ferr, d *berr, z *work, d *rwork, int *info) noexcept nogil
+cdef void zpbtf2(char *uplo, int *n, int *kd, z *ab, int *ldab, int *info) noexcept nogil
+cdef void zpbtrf(char *uplo, int *n, int *kd, z *ab, int *ldab, int *info) noexcept nogil
+cdef void zpbtrs(char *uplo, int *n, int *kd, int *nrhs, z *ab, int *ldab, z *b, int *ldb, int *info) noexcept nogil
+cdef void zpftrf(char *transr, char *uplo, int *n, z *a, int *info) noexcept nogil
+cdef void zpftri(char *transr, char *uplo, int *n, z *a, int *info) noexcept nogil
+cdef void zpftrs(char *transr, char *uplo, int *n, int *nrhs, z *a, z *b, int *ldb, int *info) noexcept nogil
+cdef void zpocon(char *uplo, int *n, z *a, int *lda, d *anorm, d *rcond, z *work, d *rwork, int *info) noexcept nogil
+cdef void zpoequ(int *n, z *a, int *lda, d *s, d *scond, d *amax, int *info) noexcept nogil
+cdef void zpoequb(int *n, z *a, int *lda, d *s, d *scond, d *amax, int *info) noexcept nogil
+cdef void zporfs(char *uplo, int *n, int *nrhs, z *a, int *lda, z *af, int *ldaf, z *b, int *ldb, z *x, int *ldx, d *ferr, d *berr, z *work, d *rwork, int *info) noexcept nogil
+cdef void zposv(char *uplo, int *n, int *nrhs, z *a, int *lda, z *b, int *ldb, int *info) noexcept nogil
+cdef void zposvx(char *fact, char *uplo, int *n, int *nrhs, z *a, int *lda, z *af, int *ldaf, char *equed, d *s, z *b, int *ldb, z *x, int *ldx, d *rcond, d *ferr, d *berr, z *work, d *rwork, int *info) noexcept nogil
+cdef void zpotf2(char *uplo, int *n, z *a, int *lda, int *info) noexcept nogil
+cdef void zpotrf(char *uplo, int *n, z *a, int *lda, int *info) noexcept nogil
+cdef void zpotri(char *uplo, int *n, z *a, int *lda, int *info) noexcept nogil
+cdef void zpotrs(char *uplo, int *n, int *nrhs, z *a, int *lda, z *b, int *ldb, int *info) noexcept nogil
+cdef void zppcon(char *uplo, int *n, z *ap, d *anorm, d *rcond, z *work, d *rwork, int *info) noexcept nogil
+cdef void zppequ(char *uplo, int *n, z *ap, d *s, d *scond, d *amax, int *info) noexcept nogil
+cdef void zpprfs(char *uplo, int *n, int *nrhs, z *ap, z *afp, z *b, int *ldb, z *x, int *ldx, d *ferr, d *berr, z *work, d *rwork, int *info) noexcept nogil
+cdef void zppsv(char *uplo, int *n, int *nrhs, z *ap, z *b, int *ldb, int *info) noexcept nogil
+cdef void zppsvx(char *fact, char *uplo, int *n, int *nrhs, z *ap, z *afp, char *equed, d *s, z *b, int *ldb, z *x, int *ldx, d *rcond, d *ferr, d *berr, z *work, d *rwork, int *info) noexcept nogil
+cdef void zpptrf(char *uplo, int *n, z *ap, int *info) noexcept nogil
+cdef void zpptri(char *uplo, int *n, z *ap, int *info) noexcept nogil
+cdef void zpptrs(char *uplo, int *n, int *nrhs, z *ap, z *b, int *ldb, int *info) noexcept nogil
+cdef void zpstf2(char *uplo, int *n, z *a, int *lda, int *piv, int *rank, d *tol, d *work, int *info) noexcept nogil
+cdef void zpstrf(char *uplo, int *n, z *a, int *lda, int *piv, int *rank, d *tol, d *work, int *info) noexcept nogil
+cdef void zptcon(int *n, d *d, z *e, d *anorm, d *rcond, d *rwork, int *info) noexcept nogil
+cdef void zpteqr(char *compz, int *n, d *d, d *e, z *z, int *ldz, d *work, int *info) noexcept nogil
+cdef void zptrfs(char *uplo, int *n, int *nrhs, d *d, z *e, d *df, z *ef, z *b, int *ldb, z *x, int *ldx, d *ferr, d *berr, z *work, d *rwork, int *info) noexcept nogil
+cdef void zptsv(int *n, int *nrhs, d *d, z *e, z *b, int *ldb, int *info) noexcept nogil
+cdef void zptsvx(char *fact, int *n, int *nrhs, d *d, z *e, d *df, z *ef, z *b, int *ldb, z *x, int *ldx, d *rcond, d *ferr, d *berr, z *work, d *rwork, int *info) noexcept nogil
+cdef void zpttrf(int *n, d *d, z *e, int *info) noexcept nogil
+cdef void zpttrs(char *uplo, int *n, int *nrhs, d *d, z *e, z *b, int *ldb, int *info) noexcept nogil
+cdef void zptts2(int *iuplo, int *n, int *nrhs, d *d, z *e, z *b, int *ldb) noexcept nogil
+cdef void zrot(int *n, z *cx, int *incx, z *cy, int *incy, d *c, z *s) noexcept nogil
+cdef void zspcon(char *uplo, int *n, z *ap, int *ipiv, d *anorm, d *rcond, z *work, int *info) noexcept nogil
+cdef void zspmv(char *uplo, int *n, z *alpha, z *ap, z *x, int *incx, z *beta, z *y, int *incy) noexcept nogil
+cdef void zspr(char *uplo, int *n, z *alpha, z *x, int *incx, z *ap) noexcept nogil
+cdef void zsprfs(char *uplo, int *n, int *nrhs, z *ap, z *afp, int *ipiv, z *b, int *ldb, z *x, int *ldx, d *ferr, d *berr, z *work, d *rwork, int *info) noexcept nogil
+cdef void zspsv(char *uplo, int *n, int *nrhs, z *ap, int *ipiv, z *b, int *ldb, int *info) noexcept nogil
+cdef void zspsvx(char *fact, char *uplo, int *n, int *nrhs, z *ap, z *afp, int *ipiv, z *b, int *ldb, z *x, int *ldx, d *rcond, d *ferr, d *berr, z *work, d *rwork, int *info) noexcept nogil
+cdef void zsptrf(char *uplo, int *n, z *ap, int *ipiv, int *info) noexcept nogil
+cdef void zsptri(char *uplo, int *n, z *ap, int *ipiv, z *work, int *info) noexcept nogil
+cdef void zsptrs(char *uplo, int *n, int *nrhs, z *ap, int *ipiv, z *b, int *ldb, int *info) noexcept nogil
+cdef void zstedc(char *compz, int *n, d *d, d *e, z *z, int *ldz, z *work, int *lwork, d *rwork, int *lrwork, int *iwork, int *liwork, int *info) noexcept nogil
+cdef void zstegr(char *jobz, char *range, int *n, d *d, d *e, d *vl, d *vu, int *il, int *iu, d *abstol, int *m, d *w, z *z, int *ldz, int *isuppz, d *work, int *lwork, int *iwork, int *liwork, int *info) noexcept nogil
+cdef void zstein(int *n, d *d, d *e, int *m, d *w, int *iblock, int *isplit, z *z, int *ldz, d *work, int *iwork, int *ifail, int *info) noexcept nogil
+cdef void zstemr(char *jobz, char *range, int *n, d *d, d *e, d *vl, d *vu, int *il, int *iu, int *m, d *w, z *z, int *ldz, int *nzc, int *isuppz, bint *tryrac, d *work, int *lwork, int *iwork, int *liwork, int *info) noexcept nogil
+cdef void zsteqr(char *compz, int *n, d *d, d *e, z *z, int *ldz, d *work, int *info) noexcept nogil
+cdef void zsycon(char *uplo, int *n, z *a, int *lda, int *ipiv, d *anorm, d *rcond, z *work, int *info) noexcept nogil
+cdef void zsyconv(char *uplo, char *way, int *n, z *a, int *lda, int *ipiv, z *work, int *info) noexcept nogil
+cdef void zsyequb(char *uplo, int *n, z *a, int *lda, d *s, d *scond, d *amax, z *work, int *info) noexcept nogil
+cdef void zsymv(char *uplo, int *n, z *alpha, z *a, int *lda, z *x, int *incx, z *beta, z *y, int *incy) noexcept nogil
+cdef void zsyr(char *uplo, int *n, z *alpha, z *x, int *incx, z *a, int *lda) noexcept nogil
+cdef void zsyrfs(char *uplo, int *n, int *nrhs, z *a, int *lda, z *af, int *ldaf, int *ipiv, z *b, int *ldb, z *x, int *ldx, d *ferr, d *berr, z *work, d *rwork, int *info) noexcept nogil
+cdef void zsysv(char *uplo, int *n, int *nrhs, z *a, int *lda, int *ipiv, z *b, int *ldb, z *work, int *lwork, int *info) noexcept nogil
+cdef void zsysvx(char *fact, char *uplo, int *n, int *nrhs, z *a, int *lda, z *af, int *ldaf, int *ipiv, z *b, int *ldb, z *x, int *ldx, d *rcond, d *ferr, d *berr, z *work, int *lwork, d *rwork, int *info) noexcept nogil
+cdef void zsyswapr(char *uplo, int *n, z *a, int *lda, int *i1, int *i2) noexcept nogil
+cdef void zsytf2(char *uplo, int *n, z *a, int *lda, int *ipiv, int *info) noexcept nogil
+cdef void zsytrf(char *uplo, int *n, z *a, int *lda, int *ipiv, z *work, int *lwork, int *info) noexcept nogil
+cdef void zsytri(char *uplo, int *n, z *a, int *lda, int *ipiv, z *work, int *info) noexcept nogil
+cdef void zsytri2(char *uplo, int *n, z *a, int *lda, int *ipiv, z *work, int *lwork, int *info) noexcept nogil
+cdef void zsytri2x(char *uplo, int *n, z *a, int *lda, int *ipiv, z *work, int *nb, int *info) noexcept nogil
+cdef void zsytrs(char *uplo, int *n, int *nrhs, z *a, int *lda, int *ipiv, z *b, int *ldb, int *info) noexcept nogil
+cdef void zsytrs2(char *uplo, int *n, int *nrhs, z *a, int *lda, int *ipiv, z *b, int *ldb, z *work, int *info) noexcept nogil
+cdef void ztbcon(char *norm, char *uplo, char *diag, int *n, int *kd, z *ab, int *ldab, d *rcond, z *work, d *rwork, int *info) noexcept nogil
+cdef void ztbrfs(char *uplo, char *trans, char *diag, int *n, int *kd, int *nrhs, z *ab, int *ldab, z *b, int *ldb, z *x, int *ldx, d *ferr, d *berr, z *work, d *rwork, int *info) noexcept nogil
+cdef void ztbtrs(char *uplo, char *trans, char *diag, int *n, int *kd, int *nrhs, z *ab, int *ldab, z *b, int *ldb, int *info) noexcept nogil
+cdef void ztfsm(char *transr, char *side, char *uplo, char *trans, char *diag, int *m, int *n, z *alpha, z *a, z *b, int *ldb) noexcept nogil
+cdef void ztftri(char *transr, char *uplo, char *diag, int *n, z *a, int *info) noexcept nogil
+cdef void ztfttp(char *transr, char *uplo, int *n, z *arf, z *ap, int *info) noexcept nogil
+cdef void ztfttr(char *transr, char *uplo, int *n, z *arf, z *a, int *lda, int *info) noexcept nogil
+cdef void ztgevc(char *side, char *howmny, bint *select, int *n, z *s, int *lds, z *p, int *ldp, z *vl, int *ldvl, z *vr, int *ldvr, int *mm, int *m, z *work, d *rwork, int *info) noexcept nogil
+cdef void ztgex2(bint *wantq, bint *wantz, int *n, z *a, int *lda, z *b, int *ldb, z *q, int *ldq, z *z, int *ldz, int *j1, int *info) noexcept nogil
+cdef void ztgexc(bint *wantq, bint *wantz, int *n, z *a, int *lda, z *b, int *ldb, z *q, int *ldq, z *z, int *ldz, int *ifst, int *ilst, int *info) noexcept nogil
+cdef void ztgsen(int *ijob, bint *wantq, bint *wantz, bint *select, int *n, z *a, int *lda, z *b, int *ldb, z *alpha, z *beta, z *q, int *ldq, z *z, int *ldz, int *m, d *pl, d *pr, d *dif, z *work, int *lwork, int *iwork, int *liwork, int *info) noexcept nogil
+cdef void ztgsja(char *jobu, char *jobv, char *jobq, int *m, int *p, int *n, int *k, int *l, z *a, int *lda, z *b, int *ldb, d *tola, d *tolb, d *alpha, d *beta, z *u, int *ldu, z *v, int *ldv, z *q, int *ldq, z *work, int *ncycle, int *info) noexcept nogil
+cdef void ztgsna(char *job, char *howmny, bint *select, int *n, z *a, int *lda, z *b, int *ldb, z *vl, int *ldvl, z *vr, int *ldvr, d *s, d *dif, int *mm, int *m, z *work, int *lwork, int *iwork, int *info) noexcept nogil
+cdef void ztgsy2(char *trans, int *ijob, int *m, int *n, z *a, int *lda, z *b, int *ldb, z *c, int *ldc, z *d, int *ldd, z *e, int *lde, z *f, int *ldf, d *scale, d *rdsum, d *rdscal, int *info) noexcept nogil
+cdef void ztgsyl(char *trans, int *ijob, int *m, int *n, z *a, int *lda, z *b, int *ldb, z *c, int *ldc, z *d, int *ldd, z *e, int *lde, z *f, int *ldf, d *scale, d *dif, z *work, int *lwork, int *iwork, int *info) noexcept nogil
+cdef void ztpcon(char *norm, char *uplo, char *diag, int *n, z *ap, d *rcond, z *work, d *rwork, int *info) noexcept nogil
+cdef void ztpmqrt(char *side, char *trans, int *m, int *n, int *k, int *l, int *nb, z *v, int *ldv, z *t, int *ldt, z *a, int *lda, z *b, int *ldb, z *work, int *info) noexcept nogil
+cdef void ztpqrt(int *m, int *n, int *l, int *nb, z *a, int *lda, z *b, int *ldb, z *t, int *ldt, z *work, int *info) noexcept nogil
+cdef void ztpqrt2(int *m, int *n, int *l, z *a, int *lda, z *b, int *ldb, z *t, int *ldt, int *info) noexcept nogil
+cdef void ztprfb(char *side, char *trans, char *direct, char *storev, int *m, int *n, int *k, int *l, z *v, int *ldv, z *t, int *ldt, z *a, int *lda, z *b, int *ldb, z *work, int *ldwork) noexcept nogil
+cdef void ztprfs(char *uplo, char *trans, char *diag, int *n, int *nrhs, z *ap, z *b, int *ldb, z *x, int *ldx, d *ferr, d *berr, z *work, d *rwork, int *info) noexcept nogil
+cdef void ztptri(char *uplo, char *diag, int *n, z *ap, int *info) noexcept nogil
+cdef void ztptrs(char *uplo, char *trans, char *diag, int *n, int *nrhs, z *ap, z *b, int *ldb, int *info) noexcept nogil
+cdef void ztpttf(char *transr, char *uplo, int *n, z *ap, z *arf, int *info) noexcept nogil
+cdef void ztpttr(char *uplo, int *n, z *ap, z *a, int *lda, int *info) noexcept nogil
+cdef void ztrcon(char *norm, char *uplo, char *diag, int *n, z *a, int *lda, d *rcond, z *work, d *rwork, int *info) noexcept nogil
+cdef void ztrevc(char *side, char *howmny, bint *select, int *n, z *t, int *ldt, z *vl, int *ldvl, z *vr, int *ldvr, int *mm, int *m, z *work, d *rwork, int *info) noexcept nogil
+cdef void ztrexc(char *compq, int *n, z *t, int *ldt, z *q, int *ldq, int *ifst, int *ilst, int *info) noexcept nogil
+cdef void ztrrfs(char *uplo, char *trans, char *diag, int *n, int *nrhs, z *a, int *lda, z *b, int *ldb, z *x, int *ldx, d *ferr, d *berr, z *work, d *rwork, int *info) noexcept nogil
+cdef void ztrsen(char *job, char *compq, bint *select, int *n, z *t, int *ldt, z *q, int *ldq, z *w, int *m, d *s, d *sep, z *work, int *lwork, int *info) noexcept nogil
+cdef void ztrsna(char *job, char *howmny, bint *select, int *n, z *t, int *ldt, z *vl, int *ldvl, z *vr, int *ldvr, d *s, d *sep, int *mm, int *m, z *work, int *ldwork, d *rwork, int *info) noexcept nogil
+cdef void ztrsyl(char *trana, char *tranb, int *isgn, int *m, int *n, z *a, int *lda, z *b, int *ldb, z *c, int *ldc, d *scale, int *info) noexcept nogil
+cdef void ztrti2(char *uplo, char *diag, int *n, z *a, int *lda, int *info) noexcept nogil
+cdef void ztrtri(char *uplo, char *diag, int *n, z *a, int *lda, int *info) noexcept nogil
+cdef void ztrtrs(char *uplo, char *trans, char *diag, int *n, int *nrhs, z *a, int *lda, z *b, int *ldb, int *info) noexcept nogil
+cdef void ztrttf(char *transr, char *uplo, int *n, z *a, int *lda, z *arf, int *info) noexcept nogil
+cdef void ztrttp(char *uplo, int *n, z *a, int *lda, z *ap, int *info) noexcept nogil
+cdef void ztzrzf(int *m, int *n, z *a, int *lda, z *tau, z *work, int *lwork, int *info) noexcept nogil
+cdef void zunbdb(char *trans, char *signs, int *m, int *p, int *q, z *x11, int *ldx11, z *x12, int *ldx12, z *x21, int *ldx21, z *x22, int *ldx22, d *theta, d *phi, z *taup1, z *taup2, z *tauq1, z *tauq2, z *work, int *lwork, int *info) noexcept nogil
+cdef void zuncsd(char *jobu1, char *jobu2, char *jobv1t, char *jobv2t, char *trans, char *signs, int *m, int *p, int *q, z *x11, int *ldx11, z *x12, int *ldx12, z *x21, int *ldx21, z *x22, int *ldx22, d *theta, z *u1, int *ldu1, z *u2, int *ldu2, z *v1t, int *ldv1t, z *v2t, int *ldv2t, z *work, int *lwork, d *rwork, int *lrwork, int *iwork, int *info) noexcept nogil
+cdef void zung2l(int *m, int *n, int *k, z *a, int *lda, z *tau, z *work, int *info) noexcept nogil
+cdef void zung2r(int *m, int *n, int *k, z *a, int *lda, z *tau, z *work, int *info) noexcept nogil
+cdef void zungbr(char *vect, int *m, int *n, int *k, z *a, int *lda, z *tau, z *work, int *lwork, int *info) noexcept nogil
+cdef void zunghr(int *n, int *ilo, int *ihi, z *a, int *lda, z *tau, z *work, int *lwork, int *info) noexcept nogil
+cdef void zungl2(int *m, int *n, int *k, z *a, int *lda, z *tau, z *work, int *info) noexcept nogil
+cdef void zunglq(int *m, int *n, int *k, z *a, int *lda, z *tau, z *work, int *lwork, int *info) noexcept nogil
+cdef void zungql(int *m, int *n, int *k, z *a, int *lda, z *tau, z *work, int *lwork, int *info) noexcept nogil
+cdef void zungqr(int *m, int *n, int *k, z *a, int *lda, z *tau, z *work, int *lwork, int *info) noexcept nogil
+cdef void zungr2(int *m, int *n, int *k, z *a, int *lda, z *tau, z *work, int *info) noexcept nogil
+cdef void zungrq(int *m, int *n, int *k, z *a, int *lda, z *tau, z *work, int *lwork, int *info) noexcept nogil
+cdef void zungtr(char *uplo, int *n, z *a, int *lda, z *tau, z *work, int *lwork, int *info) noexcept nogil
+cdef void zunm2l(char *side, char *trans, int *m, int *n, int *k, z *a, int *lda, z *tau, z *c, int *ldc, z *work, int *info) noexcept nogil
+cdef void zunm2r(char *side, char *trans, int *m, int *n, int *k, z *a, int *lda, z *tau, z *c, int *ldc, z *work, int *info) noexcept nogil
+cdef void zunmbr(char *vect, char *side, char *trans, int *m, int *n, int *k, z *a, int *lda, z *tau, z *c, int *ldc, z *work, int *lwork, int *info) noexcept nogil
+cdef void zunmhr(char *side, char *trans, int *m, int *n, int *ilo, int *ihi, z *a, int *lda, z *tau, z *c, int *ldc, z *work, int *lwork, int *info) noexcept nogil
+cdef void zunml2(char *side, char *trans, int *m, int *n, int *k, z *a, int *lda, z *tau, z *c, int *ldc, z *work, int *info) noexcept nogil
+cdef void zunmlq(char *side, char *trans, int *m, int *n, int *k, z *a, int *lda, z *tau, z *c, int *ldc, z *work, int *lwork, int *info) noexcept nogil
+cdef void zunmql(char *side, char *trans, int *m, int *n, int *k, z *a, int *lda, z *tau, z *c, int *ldc, z *work, int *lwork, int *info) noexcept nogil
+cdef void zunmqr(char *side, char *trans, int *m, int *n, int *k, z *a, int *lda, z *tau, z *c, int *ldc, z *work, int *lwork, int *info) noexcept nogil
+cdef void zunmr2(char *side, char *trans, int *m, int *n, int *k, z *a, int *lda, z *tau, z *c, int *ldc, z *work, int *info) noexcept nogil
+cdef void zunmr3(char *side, char *trans, int *m, int *n, int *k, int *l, z *a, int *lda, z *tau, z *c, int *ldc, z *work, int *info) noexcept nogil
+cdef void zunmrq(char *side, char *trans, int *m, int *n, int *k, z *a, int *lda, z *tau, z *c, int *ldc, z *work, int *lwork, int *info) noexcept nogil
+cdef void zunmrz(char *side, char *trans, int *m, int *n, int *k, int *l, z *a, int *lda, z *tau, z *c, int *ldc, z *work, int *lwork, int *info) noexcept nogil
+cdef void zunmtr(char *side, char *uplo, char *trans, int *m, int *n, z *a, int *lda, z *tau, z *c, int *ldc, z *work, int *lwork, int *info) noexcept nogil
+cdef void zupgtr(char *uplo, int *n, z *ap, z *tau, z *q, int *ldq, z *work, int *info) noexcept nogil
+cdef void zupmtr(char *side, char *uplo, char *trans, int *m, int *n, z *ap, z *tau, z *c, int *ldc, z *work, int *info) noexcept nogil
diff --git a/.venv/lib/python3.12/site-packages/scipy/linalg/decomp.py b/.venv/lib/python3.12/site-packages/scipy/linalg/decomp.py
new file mode 100644
index 0000000000000000000000000000000000000000..0d82ab157ce3be763f63e453c9a6fee064557c85
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/linalg/decomp.py
@@ -0,0 +1,23 @@
+# This file is not meant for public use and will be removed in SciPy v2.0.0.
+# Use the `scipy.linalg` namespace for importing the functions
+# included below.
+
+from scipy._lib.deprecation import _sub_module_deprecation
+
+
+__all__ = [  # noqa: F822
+    'eig', 'eigvals', 'eigh', 'eigvalsh',
+    'eig_banded', 'eigvals_banded',
+    'eigh_tridiagonal', 'eigvalsh_tridiagonal', 'hessenberg', 'cdf2rdf',
+    'LinAlgError', 'norm', 'get_lapack_funcs'
+]
+
+
+def __dir__():
+    return __all__
+
+
+def __getattr__(name):
+    return _sub_module_deprecation(sub_package="linalg", module="decomp",
+                                   private_modules=["_decomp"], all=__all__,
+                                   attribute=name)
diff --git a/.venv/lib/python3.12/site-packages/scipy/linalg/decomp_cholesky.py b/.venv/lib/python3.12/site-packages/scipy/linalg/decomp_cholesky.py
new file mode 100644
index 0000000000000000000000000000000000000000..92545a5c6af5fe7a4de13f8746b96696d68b5bd2
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/linalg/decomp_cholesky.py
@@ -0,0 +1,21 @@
+# This file is not meant for public use and will be removed in SciPy v2.0.0.
+# Use the `scipy.linalg` namespace for importing the functions
+# included below.
+
+from scipy._lib.deprecation import _sub_module_deprecation
+
+
+__all__ = [  # noqa: F822
+    'cholesky', 'cho_factor', 'cho_solve', 'cholesky_banded',
+    'cho_solve_banded', 'LinAlgError', 'get_lapack_funcs'
+]
+
+
+def __dir__():
+    return __all__
+
+
+def __getattr__(name):
+    return _sub_module_deprecation(sub_package="linalg", module="decomp_cholesky",
+                                   private_modules=["_decomp_cholesky"], all=__all__,
+                                   attribute=name)
diff --git a/.venv/lib/python3.12/site-packages/scipy/linalg/decomp_lu.py b/.venv/lib/python3.12/site-packages/scipy/linalg/decomp_lu.py
new file mode 100644
index 0000000000000000000000000000000000000000..9d5d9a98a04a689fb735f81299e129dc7f307590
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/linalg/decomp_lu.py
@@ -0,0 +1,21 @@
+# This file is not meant for public use and will be removed in SciPy v2.0.0.
+# Use the `scipy.linalg` namespace for importing the functions
+# included below.
+
+from scipy._lib.deprecation import _sub_module_deprecation
+
+
+__all__ = [  # noqa: F822
+    'lu', 'lu_solve', 'lu_factor',
+    'LinAlgWarning', 'get_lapack_funcs',
+]
+
+
+def __dir__():
+    return __all__
+
+
+def __getattr__(name):
+    return _sub_module_deprecation(sub_package="linalg", module="decomp_lu",
+                                   private_modules=["_decomp_lu"], all=__all__,
+                                   attribute=name)
diff --git a/.venv/lib/python3.12/site-packages/scipy/linalg/decomp_qr.py b/.venv/lib/python3.12/site-packages/scipy/linalg/decomp_qr.py
new file mode 100644
index 0000000000000000000000000000000000000000..4ef58729412ce2c83310b7817a143d14b8f28c19
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/linalg/decomp_qr.py
@@ -0,0 +1,20 @@
+# This file is not meant for public use and will be removed in SciPy v2.0.0.
+# Use the `scipy.linalg` namespace for importing the functions
+# included below.
+
+from scipy._lib.deprecation import _sub_module_deprecation
+
+
+__all__ = [  # noqa: F822
+    'qr', 'qr_multiply', 'rq', 'get_lapack_funcs'
+]
+
+
+def __dir__():
+    return __all__
+
+
+def __getattr__(name):
+    return _sub_module_deprecation(sub_package="linalg", module="decomp_qr",
+                                   private_modules=["_decomp_qr"], all=__all__,
+                                   attribute=name)
diff --git a/.venv/lib/python3.12/site-packages/scipy/linalg/decomp_schur.py b/.venv/lib/python3.12/site-packages/scipy/linalg/decomp_schur.py
new file mode 100644
index 0000000000000000000000000000000000000000..c3c6cc494db9b35dce8e4007c8c30d823b03881f
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/linalg/decomp_schur.py
@@ -0,0 +1,21 @@
+# This file is not meant for public use and will be removed in SciPy v2.0.0.
+# Use the `scipy.linalg` namespace for importing the functions
+# included below.
+
+from scipy._lib.deprecation import _sub_module_deprecation
+
+
+__all__ = [  # noqa: F822
+    'schur', 'rsf2csf', 'norm', 'LinAlgError', 'get_lapack_funcs', 'eigvals',
+]
+
+
+def __dir__():
+    return __all__
+
+
+def __getattr__(name):
+    return _sub_module_deprecation(sub_package="linalg", module="decomp_schur",
+                                   private_modules=["_decomp_schur"], all=__all__,
+                                   attribute=name)
+
diff --git a/.venv/lib/python3.12/site-packages/scipy/linalg/decomp_svd.py b/.venv/lib/python3.12/site-packages/scipy/linalg/decomp_svd.py
new file mode 100644
index 0000000000000000000000000000000000000000..64d0ce8562f06a3837df050f0ea6b8b15a2b359e
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/linalg/decomp_svd.py
@@ -0,0 +1,21 @@
+# This file is not meant for public use and will be removed in SciPy v2.0.0.
+# Use the `scipy.linalg` namespace for importing the functions
+# included below.
+
+from scipy._lib.deprecation import _sub_module_deprecation
+
+
+__all__ = [  # noqa: F822
+    'svd', 'svdvals', 'diagsvd', 'orth', 'subspace_angles', 'null_space',
+    'LinAlgError', 'get_lapack_funcs'
+]
+
+
+def __dir__():
+    return __all__
+
+
+def __getattr__(name):
+    return _sub_module_deprecation(sub_package="linalg", module="decomp_svd",
+                                   private_modules=["_decomp_svd"], all=__all__,
+                                   attribute=name)
diff --git a/.venv/lib/python3.12/site-packages/scipy/linalg/interpolative.py b/.venv/lib/python3.12/site-packages/scipy/linalg/interpolative.py
new file mode 100644
index 0000000000000000000000000000000000000000..2550d4edfa443945a87d39a92b6a95da61cdac4b
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/linalg/interpolative.py
@@ -0,0 +1,941 @@
+#  ******************************************************************************
+#   Copyright (C) 2013 Kenneth L. Ho
+#
+#   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.
+#
+#   None of the names of the copyright holders may be used to endorse or
+#   promote products derived from this software without specific prior written
+#   permission.
+#
+#   THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+#   AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+#   IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+#   ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
+#   LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+#   CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+#   SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+#   INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+#   CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+#   ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+#   POSSIBILITY OF SUCH DAMAGE.
+#  ******************************************************************************
+
+r"""
+======================================================================
+Interpolative matrix decomposition (:mod:`scipy.linalg.interpolative`)
+======================================================================
+
+.. versionadded:: 0.13
+
+.. versionchanged:: 1.15.0
+    The underlying algorithms have been ported to Python from the original Fortran77
+    code. See references below for more details.
+
+.. currentmodule:: scipy.linalg.interpolative
+
+An interpolative decomposition (ID) of a matrix :math:`A \in
+\mathbb{C}^{m \times n}` of rank :math:`k \leq \min \{ m, n \}` is a
+factorization
+
+.. math::
+  A \Pi =
+  \begin{bmatrix}
+   A \Pi_{1} & A \Pi_{2}
+  \end{bmatrix} =
+  A \Pi_{1}
+  \begin{bmatrix}
+   I & T
+  \end{bmatrix},
+
+where :math:`\Pi = [\Pi_{1}, \Pi_{2}]` is a permutation matrix with
+:math:`\Pi_{1} \in \{ 0, 1 \}^{n \times k}`, i.e., :math:`A \Pi_{2} =
+A \Pi_{1} T`. This can equivalently be written as :math:`A = BP`,
+where :math:`B = A \Pi_{1}` and :math:`P = [I, T] \Pi^{\mathsf{T}}`
+are the *skeleton* and *interpolation matrices*, respectively.
+
+If :math:`A` does not have exact rank :math:`k`, then there exists an
+approximation in the form of an ID such that :math:`A = BP + E`, where
+:math:`\| E \| \sim \sigma_{k + 1}` is on the order of the :math:`(k +
+1)`-th largest singular value of :math:`A`. Note that :math:`\sigma_{k
++ 1}` is the best possible error for a rank-:math:`k` approximation
+and, in fact, is achieved by the singular value decomposition (SVD)
+:math:`A \approx U S V^{*}`, where :math:`U \in \mathbb{C}^{m \times
+k}` and :math:`V \in \mathbb{C}^{n \times k}` have orthonormal columns
+and :math:`S = \mathop{\mathrm{diag}} (\sigma_{i}) \in \mathbb{C}^{k
+\times k}` is diagonal with nonnegative entries. The principal
+advantages of using an ID over an SVD are that:
+
+- it is cheaper to construct;
+- it preserves the structure of :math:`A`; and
+- it is more efficient to compute with in light of the identity submatrix of :math:`P`.
+
+Routines
+========
+
+Main functionality:
+
+.. autosummary::
+   :toctree: generated/
+
+   interp_decomp
+   reconstruct_matrix_from_id
+   reconstruct_interp_matrix
+   reconstruct_skel_matrix
+   id_to_svd
+   svd
+   estimate_spectral_norm
+   estimate_spectral_norm_diff
+   estimate_rank
+
+
+References
+==========
+
+This module uses the algorithms found in ID software package [1]_ by Martinsson,
+Rokhlin, Shkolnisky, and Tygert, which is a Fortran library for computing IDs using
+various algorithms, including the rank-revealing QR approach of [2]_ and the more
+recent randomized methods described in [3]_, [4]_, and [5]_.
+
+We advise the user to consult also the documentation for the `ID package
+`_.
+
+.. [1] P.G. Martinsson, V. Rokhlin, Y. Shkolnisky, M. Tygert. "ID: a
+    software package for low-rank approximation of matrices via interpolative
+    decompositions, version 0.2." http://tygert.com/id_doc.4.pdf.
+
+.. [2] H. Cheng, Z. Gimbutas, P.G. Martinsson, V. Rokhlin. "On the
+    compression of low rank matrices." *SIAM J. Sci. Comput.* 26 (4): 1389--1404,
+    2005. :doi:`10.1137/030602678`.
+
+.. [3] E. Liberty, F. Woolfe, P.G. Martinsson, V. Rokhlin, M.
+    Tygert. "Randomized algorithms for the low-rank approximation of matrices."
+    *Proc. Natl. Acad. Sci. U.S.A.* 104 (51): 20167--20172, 2007.
+    :doi:`10.1073/pnas.0709640104`.
+
+.. [4] P.G. Martinsson, V. Rokhlin, M. Tygert. "A randomized
+    algorithm for the decomposition of matrices." *Appl. Comput. Harmon. Anal.* 30
+    (1): 47--68,  2011. :doi:`10.1016/j.acha.2010.02.003`.
+
+.. [5] F. Woolfe, E. Liberty, V. Rokhlin, M. Tygert. "A fast
+    randomized algorithm for the approximation of matrices." *Appl. Comput.
+    Harmon. Anal.* 25 (3): 335--366, 2008. :doi:`10.1016/j.acha.2007.12.002`.
+
+
+Tutorial
+========
+
+Initializing
+------------
+
+The first step is to import :mod:`scipy.linalg.interpolative` by issuing the
+command:
+
+>>> import scipy.linalg.interpolative as sli
+
+Now let's build a matrix. For this, we consider a Hilbert matrix, which is well
+know to have low rank:
+
+>>> from scipy.linalg import hilbert
+>>> n = 1000
+>>> A = hilbert(n)
+
+We can also do this explicitly via:
+
+>>> import numpy as np
+>>> n = 1000
+>>> A = np.empty((n, n), order='F')
+>>> for j in range(n):
+...     for i in range(n):
+...         A[i,j] = 1. / (i + j + 1)
+
+Note the use of the flag ``order='F'`` in :func:`numpy.empty`. This
+instantiates the matrix in Fortran-contiguous order and is important for
+avoiding data copying when passing to the backend.
+
+We then define multiplication routines for the matrix by regarding it as a
+:class:`scipy.sparse.linalg.LinearOperator`:
+
+>>> from scipy.sparse.linalg import aslinearoperator
+>>> L = aslinearoperator(A)
+
+This automatically sets up methods describing the action of the matrix and its
+adjoint on a vector.
+
+Computing an ID
+---------------
+
+We have several choices of algorithm to compute an ID. These fall largely
+according to two dichotomies:
+
+1. how the matrix is represented, i.e., via its entries or via its action on a
+   vector; and
+2. whether to approximate it to a fixed relative precision or to a fixed rank.
+
+We step through each choice in turn below.
+
+In all cases, the ID is represented by three parameters:
+
+1. a rank ``k``;
+2. an index array ``idx``; and
+3. interpolation coefficients ``proj``.
+
+The ID is specified by the relation
+``np.dot(A[:,idx[:k]], proj) == A[:,idx[k:]]``.
+
+From matrix entries
+...................
+
+We first consider a matrix given in terms of its entries.
+
+To compute an ID to a fixed precision, type:
+
+>>> eps = 1e-3
+>>> k, idx, proj = sli.interp_decomp(A, eps)
+
+where ``eps < 1`` is the desired precision.
+
+To compute an ID to a fixed rank, use:
+
+>>> idx, proj = sli.interp_decomp(A, k)
+
+where ``k >= 1`` is the desired rank.
+
+Both algorithms use random sampling and are usually faster than the
+corresponding older, deterministic algorithms, which can be accessed via the
+commands:
+
+>>> k, idx, proj = sli.interp_decomp(A, eps, rand=False)
+
+and:
+
+>>> idx, proj = sli.interp_decomp(A, k, rand=False)
+
+respectively.
+
+From matrix action
+..................
+
+Now consider a matrix given in terms of its action on a vector as a
+:class:`scipy.sparse.linalg.LinearOperator`.
+
+To compute an ID to a fixed precision, type:
+
+>>> k, idx, proj = sli.interp_decomp(L, eps)
+
+To compute an ID to a fixed rank, use:
+
+>>> idx, proj = sli.interp_decomp(L, k)
+
+These algorithms are randomized.
+
+Reconstructing an ID
+--------------------
+
+The ID routines above do not output the skeleton and interpolation matrices
+explicitly but instead return the relevant information in a more compact (and
+sometimes more useful) form. To build these matrices, write:
+
+>>> B = sli.reconstruct_skel_matrix(A, k, idx)
+
+for the skeleton matrix and:
+
+>>> P = sli.reconstruct_interp_matrix(idx, proj)
+
+for the interpolation matrix. The ID approximation can then be computed as:
+
+>>> C = np.dot(B, P)
+
+This can also be constructed directly using:
+
+>>> C = sli.reconstruct_matrix_from_id(B, idx, proj)
+
+without having to first compute ``P``.
+
+Alternatively, this can be done explicitly as well using:
+
+>>> B = A[:,idx[:k]]
+>>> P = np.hstack([np.eye(k), proj])[:,np.argsort(idx)]
+>>> C = np.dot(B, P)
+
+Computing an SVD
+----------------
+
+An ID can be converted to an SVD via the command:
+
+>>> U, S, V = sli.id_to_svd(B, idx, proj)
+
+The SVD approximation is then:
+
+>>> approx = U @ np.diag(S) @ V.conj().T
+
+The SVD can also be computed "fresh" by combining both the ID and conversion
+steps into one command. Following the various ID algorithms above, there are
+correspondingly various SVD algorithms that one can employ.
+
+From matrix entries
+...................
+
+We consider first SVD algorithms for a matrix given in terms of its entries.
+
+To compute an SVD to a fixed precision, type:
+
+>>> U, S, V = sli.svd(A, eps)
+
+To compute an SVD to a fixed rank, use:
+
+>>> U, S, V = sli.svd(A, k)
+
+Both algorithms use random sampling; for the deterministic versions, issue the
+keyword ``rand=False`` as above.
+
+From matrix action
+..................
+
+Now consider a matrix given in terms of its action on a vector.
+
+To compute an SVD to a fixed precision, type:
+
+>>> U, S, V = sli.svd(L, eps)
+
+To compute an SVD to a fixed rank, use:
+
+>>> U, S, V = sli.svd(L, k)
+
+Utility routines
+----------------
+
+Several utility routines are also available.
+
+To estimate the spectral norm of a matrix, use:
+
+>>> snorm = sli.estimate_spectral_norm(A)
+
+This algorithm is based on the randomized power method and thus requires only
+matrix-vector products. The number of iterations to take can be set using the
+keyword ``its`` (default: ``its=20``). The matrix is interpreted as a
+:class:`scipy.sparse.linalg.LinearOperator`, but it is also valid to supply it
+as a :class:`numpy.ndarray`, in which case it is trivially converted using
+:func:`scipy.sparse.linalg.aslinearoperator`.
+
+The same algorithm can also estimate the spectral norm of the difference of two
+matrices ``A1`` and ``A2`` as follows:
+
+>>> A1, A2 = A**2, A
+>>> diff = sli.estimate_spectral_norm_diff(A1, A2)
+
+This is often useful for checking the accuracy of a matrix approximation.
+
+Some routines in :mod:`scipy.linalg.interpolative` require estimating the rank
+of a matrix as well. This can be done with either:
+
+>>> k = sli.estimate_rank(A, eps)
+
+or:
+
+>>> k = sli.estimate_rank(L, eps)
+
+depending on the representation. The parameter ``eps`` controls the definition
+of the numerical rank.
+
+Finally, the random number generation required for all randomized routines can
+be controlled via providing NumPy pseudo-random generators with a fixed seed. See
+:class:`numpy.random.Generator` and :func:`numpy.random.default_rng` for more details.
+
+Remarks
+-------
+
+The above functions all automatically detect the appropriate interface and work
+with both real and complex data types, passing input arguments to the proper
+backend routine.
+
+"""
+
+import scipy.linalg._decomp_interpolative as _backend
+import numpy as np
+
+__all__ = [
+    'estimate_rank',
+    'estimate_spectral_norm',
+    'estimate_spectral_norm_diff',
+    'id_to_svd',
+    'interp_decomp',
+    'reconstruct_interp_matrix',
+    'reconstruct_matrix_from_id',
+    'reconstruct_skel_matrix',
+    'svd',
+]
+
+_DTYPE_ERROR = ValueError("invalid input dtype (input must be float64 or complex128)")
+_TYPE_ERROR = TypeError("invalid input type (must be array or LinearOperator)")
+
+
+def _C_contiguous_copy(A):
+    """
+    Same as np.ascontiguousarray, but ensure a copy
+    """
+    A = np.asarray(A)
+    if A.flags.c_contiguous:
+        A = A.copy()
+    else:
+        A = np.ascontiguousarray(A)
+    return A
+
+
+def _is_real(A):
+    try:
+        if A.dtype == np.complex128:
+            return False
+        elif A.dtype == np.float64:
+            return True
+        else:
+            raise _DTYPE_ERROR
+    except AttributeError as e:
+        raise _TYPE_ERROR from e
+
+
+def interp_decomp(A, eps_or_k, rand=True, rng=None):
+    """
+    Compute ID of a matrix.
+
+    An ID of a matrix `A` is a factorization defined by a rank `k`, a column
+    index array `idx`, and interpolation coefficients `proj` such that::
+
+        numpy.dot(A[:,idx[:k]], proj) = A[:,idx[k:]]
+
+    The original matrix can then be reconstructed as::
+
+        numpy.hstack([A[:,idx[:k]],
+                                    numpy.dot(A[:,idx[:k]], proj)]
+                                )[:,numpy.argsort(idx)]
+
+    or via the routine :func:`reconstruct_matrix_from_id`. This can
+    equivalently be written as::
+
+        numpy.dot(A[:,idx[:k]],
+                            numpy.hstack([numpy.eye(k), proj])
+                          )[:,np.argsort(idx)]
+
+    in terms of the skeleton and interpolation matrices::
+
+        B = A[:,idx[:k]]
+
+    and::
+
+        P = numpy.hstack([numpy.eye(k), proj])[:,np.argsort(idx)]
+
+    respectively. See also :func:`reconstruct_interp_matrix` and
+    :func:`reconstruct_skel_matrix`.
+
+    The ID can be computed to any relative precision or rank (depending on the
+    value of `eps_or_k`). If a precision is specified (`eps_or_k < 1`), then
+    this function has the output signature::
+
+        k, idx, proj = interp_decomp(A, eps_or_k)
+
+    Otherwise, if a rank is specified (`eps_or_k >= 1`), then the output
+    signature is::
+
+        idx, proj = interp_decomp(A, eps_or_k)
+
+    ..  This function automatically detects the form of the input parameters
+        and passes them to the appropriate backend. For details, see
+        :func:`_backend.iddp_id`, :func:`_backend.iddp_aid`,
+        :func:`_backend.iddp_rid`, :func:`_backend.iddr_id`,
+        :func:`_backend.iddr_aid`, :func:`_backend.iddr_rid`,
+        :func:`_backend.idzp_id`, :func:`_backend.idzp_aid`,
+        :func:`_backend.idzp_rid`, :func:`_backend.idzr_id`,
+        :func:`_backend.idzr_aid`, and :func:`_backend.idzr_rid`.
+
+    Parameters
+    ----------
+    A : :class:`numpy.ndarray` or :class:`scipy.sparse.linalg.LinearOperator` with `rmatvec`
+        Matrix to be factored
+    eps_or_k : float or int
+        Relative error (if ``eps_or_k < 1``) or rank (if ``eps_or_k >= 1``) of
+        approximation.
+    rand : bool, optional
+        Whether to use random sampling if `A` is of type :class:`numpy.ndarray`
+        (randomized algorithms are always used if `A` is of type
+        :class:`scipy.sparse.linalg.LinearOperator`).
+    rng : `numpy.random.Generator`, optional
+        Pseudorandom number generator state. When `rng` is None, a new
+        `numpy.random.Generator` is created using entropy from the
+        operating system. Types other than `numpy.random.Generator` are
+        passed to `numpy.random.default_rng` to instantiate a ``Generator``.
+        If `rand` is ``False``, the argument is ignored.
+
+    Returns
+    -------
+    k : int
+        Rank required to achieve specified relative precision if
+        ``eps_or_k < 1``.
+    idx : :class:`numpy.ndarray`
+        Column index array.
+    proj : :class:`numpy.ndarray`
+        Interpolation coefficients.
+    """  # numpy/numpydoc#87  # noqa: E501
+    from scipy.sparse.linalg import LinearOperator
+    rng = np.random.default_rng(rng)
+    real = _is_real(A)
+
+    if isinstance(A, np.ndarray):
+        A = _C_contiguous_copy(A)
+        if eps_or_k < 1:
+            eps = eps_or_k
+            if rand:
+                if real:
+                    k, idx, proj = _backend.iddp_aid(A, eps, rng=rng)
+                else:
+                    k, idx, proj = _backend.idzp_aid(A, eps, rng=rng)
+            else:
+                if real:
+                    k, idx, proj = _backend.iddp_id(A, eps)
+                else:
+                    k, idx, proj = _backend.idzp_id(A, eps)
+            return k, idx, proj
+        else:
+            k = int(eps_or_k)
+            if rand:
+                if real:
+                    idx, proj = _backend.iddr_aid(A, k, rng=rng)
+                else:
+                    idx, proj = _backend.idzr_aid(A, k, rng=rng)
+            else:
+                if real:
+                    idx, proj = _backend.iddr_id(A, k)
+                else:
+                    idx, proj = _backend.idzr_id(A, k)
+            return idx, proj
+    elif isinstance(A, LinearOperator):
+
+        if eps_or_k < 1:
+            eps = eps_or_k
+            if real:
+                k, idx, proj = _backend.iddp_rid(A, eps, rng=rng)
+            else:
+                k, idx, proj = _backend.idzp_rid(A, eps, rng=rng)
+            return k, idx, proj
+        else:
+            k = int(eps_or_k)
+            if real:
+                idx, proj = _backend.iddr_rid(A, k, rng=rng)
+            else:
+                idx, proj = _backend.idzr_rid(A, k, rng=rng)
+            return idx, proj
+    else:
+        raise _TYPE_ERROR
+
+
+def reconstruct_matrix_from_id(B, idx, proj):
+    """
+    Reconstruct matrix from its ID.
+
+    A matrix `A` with skeleton matrix `B` and ID indices and coefficients `idx`
+    and `proj`, respectively, can be reconstructed as::
+
+        numpy.hstack([B, numpy.dot(B, proj)])[:,numpy.argsort(idx)]
+
+    See also :func:`reconstruct_interp_matrix` and
+    :func:`reconstruct_skel_matrix`.
+
+    ..  This function automatically detects the matrix data type and calls the
+        appropriate backend. For details, see :func:`_backend.idd_reconid` and
+        :func:`_backend.idz_reconid`.
+
+    Parameters
+    ----------
+    B : :class:`numpy.ndarray`
+        Skeleton matrix.
+    idx : :class:`numpy.ndarray`
+        Column index array.
+    proj : :class:`numpy.ndarray`
+        Interpolation coefficients.
+
+    Returns
+    -------
+    :class:`numpy.ndarray`
+        Reconstructed matrix.
+    """
+    B = np.atleast_2d(_C_contiguous_copy(B))
+    if _is_real(B):
+        return _backend.idd_reconid(B, idx, proj)
+    else:
+        return _backend.idz_reconid(B, idx, proj)
+
+
+def reconstruct_interp_matrix(idx, proj):
+    """
+    Reconstruct interpolation matrix from ID.
+
+    The interpolation matrix can be reconstructed from the ID indices and
+    coefficients `idx` and `proj`, respectively, as::
+
+        P = numpy.hstack([numpy.eye(proj.shape[0]), proj])[:,numpy.argsort(idx)]
+
+    The original matrix can then be reconstructed from its skeleton matrix ``B``
+    via ``A = B @ P``
+
+    See also :func:`reconstruct_matrix_from_id` and
+    :func:`reconstruct_skel_matrix`.
+
+    ..  This function automatically detects the matrix data type and calls the
+        appropriate backend. For details, see :func:`_backend.idd_reconint` and
+        :func:`_backend.idz_reconint`.
+
+    Parameters
+    ----------
+    idx : :class:`numpy.ndarray`
+        1D column index array.
+    proj : :class:`numpy.ndarray`
+        Interpolation coefficients.
+
+    Returns
+    -------
+    :class:`numpy.ndarray`
+        Interpolation matrix.
+    """
+    n, krank = len(idx), proj.shape[0]
+    if _is_real(proj):
+        p = np.zeros([krank, n], dtype=np.float64)
+    else:
+        p = np.zeros([krank, n], dtype=np.complex128)
+
+    for ci in range(krank):
+        p[ci, idx[ci]] = 1.0
+    p[:, idx[krank:]] = proj[:, :]
+
+    return p
+
+
+def reconstruct_skel_matrix(A, k, idx):
+    """
+    Reconstruct skeleton matrix from ID.
+
+    The skeleton matrix can be reconstructed from the original matrix `A` and its
+    ID rank and indices `k` and `idx`, respectively, as::
+
+        B = A[:,idx[:k]]
+
+    The original matrix can then be reconstructed via::
+
+        numpy.hstack([B, numpy.dot(B, proj)])[:,numpy.argsort(idx)]
+
+    See also :func:`reconstruct_matrix_from_id` and
+    :func:`reconstruct_interp_matrix`.
+
+    ..  This function automatically detects the matrix data type and calls the
+        appropriate backend. For details, see :func:`_backend.idd_copycols` and
+        :func:`_backend.idz_copycols`.
+
+    Parameters
+    ----------
+    A : :class:`numpy.ndarray`
+        Original matrix.
+    k : int
+        Rank of ID.
+    idx : :class:`numpy.ndarray`
+        Column index array.
+
+    Returns
+    -------
+    :class:`numpy.ndarray`
+        Skeleton matrix.
+    """
+    return A[:, idx[:k]]
+
+
+def id_to_svd(B, idx, proj):
+    """
+    Convert ID to SVD.
+
+    The SVD reconstruction of a matrix with skeleton matrix `B` and ID indices and
+    coefficients `idx` and `proj`, respectively, is::
+
+        U, S, V = id_to_svd(B, idx, proj)
+        A = numpy.dot(U, numpy.dot(numpy.diag(S), V.conj().T))
+
+    See also :func:`svd`.
+
+    ..  This function automatically detects the matrix data type and calls the
+        appropriate backend. For details, see :func:`_backend.idd_id2svd` and
+        :func:`_backend.idz_id2svd`.
+
+    Parameters
+    ----------
+    B : :class:`numpy.ndarray`
+        Skeleton matrix.
+    idx : :class:`numpy.ndarray`
+        1D column index array.
+    proj : :class:`numpy.ndarray`
+        Interpolation coefficients.
+
+    Returns
+    -------
+    U : :class:`numpy.ndarray`
+        Left singular vectors.
+    S : :class:`numpy.ndarray`
+        Singular values.
+    V : :class:`numpy.ndarray`
+        Right singular vectors.
+    """
+    B = _C_contiguous_copy(B)
+    if _is_real(B):
+        U, S, V = _backend.idd_id2svd(B, idx, proj)
+    else:
+        U, S, V = _backend.idz_id2svd(B, idx, proj)
+
+    return U, S, V
+
+
+def estimate_spectral_norm(A, its=20, rng=None):
+    """
+    Estimate spectral norm of a matrix by the randomized power method.
+
+    ..  This function automatically detects the matrix data type and calls the
+        appropriate backend. For details, see :func:`_backend.idd_snorm` and
+        :func:`_backend.idz_snorm`.
+
+    Parameters
+    ----------
+    A : :class:`scipy.sparse.linalg.LinearOperator`
+        Matrix given as a :class:`scipy.sparse.linalg.LinearOperator` with the
+        `matvec` and `rmatvec` methods (to apply the matrix and its adjoint).
+    its : int, optional
+        Number of power method iterations.
+    rng : `numpy.random.Generator`, optional
+        Pseudorandom number generator state. When `rng` is None, a new
+        `numpy.random.Generator` is created using entropy from the
+        operating system. Types other than `numpy.random.Generator` are
+        passed to `numpy.random.default_rng` to instantiate a ``Generator``.
+        If `rand` is ``False``, the argument is ignored.
+
+    Returns
+    -------
+    float
+        Spectral norm estimate.
+    """
+    from scipy.sparse.linalg import aslinearoperator
+    rng = np.random.default_rng(rng)
+    A = aslinearoperator(A)
+
+    if _is_real(A):
+        return _backend.idd_snorm(A, its=its, rng=rng)
+    else:
+        return _backend.idz_snorm(A, its=its, rng=rng)
+
+
+def estimate_spectral_norm_diff(A, B, its=20, rng=None):
+    """
+    Estimate spectral norm of the difference of two matrices by the randomized
+    power method.
+
+    ..  This function automatically detects the matrix data type and calls the
+        appropriate backend. For details, see :func:`_backend.idd_diffsnorm` and
+        :func:`_backend.idz_diffsnorm`.
+
+    Parameters
+    ----------
+    A : :class:`scipy.sparse.linalg.LinearOperator`
+        First matrix given as a :class:`scipy.sparse.linalg.LinearOperator` with the
+        `matvec` and `rmatvec` methods (to apply the matrix and its adjoint).
+    B : :class:`scipy.sparse.linalg.LinearOperator`
+        Second matrix given as a :class:`scipy.sparse.linalg.LinearOperator` with
+        the `matvec` and `rmatvec` methods (to apply the matrix and its adjoint).
+    its : int, optional
+        Number of power method iterations.
+    rng : `numpy.random.Generator`, optional
+        Pseudorandom number generator state. When `rng` is None, a new
+        `numpy.random.Generator` is created using entropy from the
+        operating system. Types other than `numpy.random.Generator` are
+        passed to `numpy.random.default_rng` to instantiate a ``Generator``.
+        If `rand` is ``False``, the argument is ignored.
+
+    Returns
+    -------
+    float
+        Spectral norm estimate of matrix difference.
+    """
+    from scipy.sparse.linalg import aslinearoperator
+    rng = np.random.default_rng(rng)
+    A = aslinearoperator(A)
+    B = aslinearoperator(B)
+
+    if _is_real(A):
+        return _backend.idd_diffsnorm(A, B, its=its, rng=rng)
+    else:
+        return _backend.idz_diffsnorm(A, B, its=its, rng=rng)
+
+
+def svd(A, eps_or_k, rand=True, rng=None):
+    """
+    Compute SVD of a matrix via an ID.
+
+    An SVD of a matrix `A` is a factorization::
+
+        A = U @ np.diag(S) @ V.conj().T
+
+    where `U` and `V` have orthonormal columns and `S` is nonnegative.
+
+    The SVD can be computed to any relative precision or rank (depending on the
+    value of `eps_or_k`).
+
+    See also :func:`interp_decomp` and :func:`id_to_svd`.
+
+    ..  This function automatically detects the form of the input parameters and
+        passes them to the appropriate backend. For details, see
+        :func:`_backend.iddp_svd`, :func:`_backend.iddp_asvd`,
+        :func:`_backend.iddp_rsvd`, :func:`_backend.iddr_svd`,
+        :func:`_backend.iddr_asvd`, :func:`_backend.iddr_rsvd`,
+        :func:`_backend.idzp_svd`, :func:`_backend.idzp_asvd`,
+        :func:`_backend.idzp_rsvd`, :func:`_backend.idzr_svd`,
+        :func:`_backend.idzr_asvd`, and :func:`_backend.idzr_rsvd`.
+
+    Parameters
+    ----------
+    A : :class:`numpy.ndarray` or :class:`scipy.sparse.linalg.LinearOperator`
+        Matrix to be factored, given as either a :class:`numpy.ndarray` or a
+        :class:`scipy.sparse.linalg.LinearOperator` with the `matvec` and
+        `rmatvec` methods (to apply the matrix and its adjoint).
+    eps_or_k : float or int
+        Relative error (if ``eps_or_k < 1``) or rank (if ``eps_or_k >= 1``) of
+        approximation.
+    rand : bool, optional
+        Whether to use random sampling if `A` is of type :class:`numpy.ndarray`
+        (randomized algorithms are always used if `A` is of type
+        :class:`scipy.sparse.linalg.LinearOperator`).
+    rng : `numpy.random.Generator`, optional
+        Pseudorandom number generator state. When `rng` is None, a new
+        `numpy.random.Generator` is created using entropy from the
+        operating system. Types other than `numpy.random.Generator` are
+        passed to `numpy.random.default_rng` to instantiate a ``Generator``.
+        If `rand` is ``False``, the argument is ignored.
+
+    Returns
+    -------
+    U : :class:`numpy.ndarray`
+        2D array of left singular vectors.
+    S : :class:`numpy.ndarray`
+        1D array of singular values.
+    V : :class:`numpy.ndarray`
+        2D array right singular vectors.
+    """
+    from scipy.sparse.linalg import LinearOperator
+    rng = np.random.default_rng(rng)
+
+    real = _is_real(A)
+
+    if isinstance(A, np.ndarray):
+        A = _C_contiguous_copy(A)
+        if eps_or_k < 1:
+            eps = eps_or_k
+            if rand:
+                if real:
+                    U, S, V = _backend.iddp_asvd(A, eps, rng=rng)
+                else:
+                    U, S, V = _backend.idzp_asvd(A, eps, rng=rng)
+            else:
+                if real:
+                    U, S, V = _backend.iddp_svd(A, eps)
+                    V = V.T.conj()
+                else:
+                    U, S, V = _backend.idzp_svd(A, eps)
+                    V = V.T.conj()
+        else:
+            k = int(eps_or_k)
+            if k > min(A.shape):
+                raise ValueError(f"Approximation rank {k} exceeds min(A.shape) = "
+                                 f" {min(A.shape)} ")
+            if rand:
+                if real:
+                    U, S, V = _backend.iddr_asvd(A, k, rng=rng)
+                else:
+                    U, S, V = _backend.idzr_asvd(A, k, rng=rng)
+            else:
+                if real:
+                    U, S, V = _backend.iddr_svd(A, k)
+                    V = V.T.conj()
+                else:
+                    U, S, V = _backend.idzr_svd(A, k)
+                    V = V.T.conj()
+    elif isinstance(A, LinearOperator):
+        if eps_or_k < 1:
+            eps = eps_or_k
+            if real:
+                U, S, V = _backend.iddp_rsvd(A, eps, rng=rng)
+            else:
+                U, S, V = _backend.idzp_rsvd(A, eps, rng=rng)
+        else:
+            k = int(eps_or_k)
+            if real:
+                U, S, V = _backend.iddr_rsvd(A, k, rng=rng)
+            else:
+                U, S, V = _backend.idzr_rsvd(A, k, rng=rng)
+    else:
+        raise _TYPE_ERROR
+    return U, S, V
+
+
+def estimate_rank(A, eps, rng=None):
+    """
+    Estimate matrix rank to a specified relative precision using randomized
+    methods.
+
+    The matrix `A` can be given as either a :class:`numpy.ndarray` or a
+    :class:`scipy.sparse.linalg.LinearOperator`, with different algorithms used
+    for each case. If `A` is of type :class:`numpy.ndarray`, then the output
+    rank is typically about 8 higher than the actual numerical rank.
+
+    ..  This function automatically detects the form of the input parameters and
+        passes them to the appropriate backend. For details,
+        see :func:`_backend.idd_estrank`, :func:`_backend.idd_findrank`,
+        :func:`_backend.idz_estrank`, and :func:`_backend.idz_findrank`.
+
+    Parameters
+    ----------
+    A : :class:`numpy.ndarray` or :class:`scipy.sparse.linalg.LinearOperator`
+        Matrix whose rank is to be estimated, given as either a
+        :class:`numpy.ndarray` or a :class:`scipy.sparse.linalg.LinearOperator`
+        with the `rmatvec` method (to apply the matrix adjoint).
+    eps : float
+        Relative error for numerical rank definition.
+    rng : `numpy.random.Generator`, optional
+        Pseudorandom number generator state. When `rng` is None, a new
+        `numpy.random.Generator` is created using entropy from the
+        operating system. Types other than `numpy.random.Generator` are
+        passed to `numpy.random.default_rng` to instantiate a ``Generator``.
+        If `rand` is ``False``, the argument is ignored.
+
+    Returns
+    -------
+    int
+        Estimated matrix rank.
+    """
+    from scipy.sparse.linalg import LinearOperator
+
+    rng = np.random.default_rng(rng)
+    real = _is_real(A)
+
+    if isinstance(A, np.ndarray):
+        A = _C_contiguous_copy(A)
+        if real:
+            rank, _ = _backend.idd_estrank(A, eps, rng=rng)
+        else:
+            rank, _ = _backend.idz_estrank(A, eps, rng=rng)
+        if rank == 0:
+            # special return value for nearly full rank
+            rank = min(A.shape)
+        return rank
+    elif isinstance(A, LinearOperator):
+        if real:
+            return _backend.idd_findrank(A, eps, rng=rng)[0]
+        else:
+            return _backend.idz_findrank(A, eps, rng=rng)[0]
+    else:
+        raise _TYPE_ERROR
diff --git a/.venv/lib/python3.12/site-packages/scipy/linalg/lapack.py b/.venv/lib/python3.12/site-packages/scipy/linalg/lapack.py
new file mode 100644
index 0000000000000000000000000000000000000000..7c935dcf0142ed1f9714c5e81a3b6517b3d99196
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/linalg/lapack.py
@@ -0,0 +1,1182 @@
+"""
+Low-level LAPACK functions (:mod:`scipy.linalg.lapack`)
+=======================================================
+
+This module contains low-level functions from the LAPACK library.
+
+.. versionadded:: 0.12.0
+
+.. note::
+
+    The common ``overwrite_<>`` option in many routines, allows the
+    input arrays to be overwritten to avoid extra memory allocation.
+    However this requires the array to satisfy two conditions
+    which are memory order and the data type to match exactly the
+    order and the type expected by the routine.
+
+    As an example, if you pass a double precision float array to any
+    ``S....`` routine which expects single precision arguments, f2py
+    will create an intermediate array to match the argument types and
+    overwriting will be performed on that intermediate array.
+
+    Similarly, if a C-contiguous array is passed, f2py will pass a
+    FORTRAN-contiguous array internally. Please make sure that these
+    details are satisfied. More information can be found in the f2py
+    documentation.
+
+.. warning::
+
+   These functions do little to no error checking.
+   It is possible to cause crashes by mis-using them,
+   so prefer using the higher-level routines in `scipy.linalg`.
+
+.. note::
+
+    Prefer using ``get_lapack_funcs`` to importing the bare functions directly.
+    If you do, for example, ``from scipy.linalg.lapack import dsysv``, the ``dsysv``
+    function may be either LP64 or ILP64, depending on how SciPy is built.
+
+    The following is more robust:
+
+    >>> from scipy.linalg.lapack import get_lapack_funcs
+    >>> dsysv = get_lapack_funcs('sysv', dtype='float64', ilp64='preferred')
+    >>> dsysv.int_dtype
+    dtype('int32')    # may vary
+
+
+Finding functions
+-----------------
+
+.. autosummary::
+   :toctree: generated/
+
+   get_lapack_funcs
+
+All functions
+-------------
+
+.. autosummary::
+   :toctree: generated/
+
+   sgbcon
+   dgbcon
+   cgbcon
+   zgbcon
+
+   sgbsv
+   dgbsv
+   cgbsv
+   zgbsv
+
+   sgbtrf
+   dgbtrf
+   cgbtrf
+   zgbtrf
+
+   sgbtrs
+   dgbtrs
+   cgbtrs
+   zgbtrs
+
+   sgebal
+   dgebal
+   cgebal
+   zgebal
+
+   sgecon
+   dgecon
+   cgecon
+   zgecon
+
+   sgeequ
+   dgeequ
+   cgeequ
+   zgeequ
+
+   sgeequb
+   dgeequb
+   cgeequb
+   zgeequb
+
+   sgees
+   dgees
+   cgees
+   zgees
+
+   sgeev
+   dgeev
+   cgeev
+   zgeev
+
+   sgeev_lwork
+   dgeev_lwork
+   cgeev_lwork
+   zgeev_lwork
+
+   sgehrd
+   dgehrd
+   cgehrd
+   zgehrd
+
+   sgehrd_lwork
+   dgehrd_lwork
+   cgehrd_lwork
+   zgehrd_lwork
+
+   sgejsv
+   dgejsv
+
+   sgels
+   dgels
+   cgels
+   zgels
+
+   sgels_lwork
+   dgels_lwork
+   cgels_lwork
+   zgels_lwork
+
+   sgelsd
+   dgelsd
+   cgelsd
+   zgelsd
+
+   sgelsd_lwork
+   dgelsd_lwork
+   cgelsd_lwork
+   zgelsd_lwork
+
+   sgelss
+   dgelss
+   cgelss
+   zgelss
+
+   sgelss_lwork
+   dgelss_lwork
+   cgelss_lwork
+   zgelss_lwork
+
+   sgelsy
+   dgelsy
+   cgelsy
+   zgelsy
+
+   sgelsy_lwork
+   dgelsy_lwork
+   cgelsy_lwork
+   zgelsy_lwork
+
+   sgeqp3
+   dgeqp3
+   cgeqp3
+   zgeqp3
+
+   sgeqrf
+   dgeqrf
+   cgeqrf
+   zgeqrf
+
+   sgeqrf_lwork
+   dgeqrf_lwork
+   cgeqrf_lwork
+   zgeqrf_lwork
+
+   sgeqrfp
+   dgeqrfp
+   cgeqrfp
+   zgeqrfp
+
+   sgeqrfp_lwork
+   dgeqrfp_lwork
+   cgeqrfp_lwork
+   zgeqrfp_lwork
+
+   sgerqf
+   dgerqf
+   cgerqf
+   zgerqf
+
+   sgesdd
+   dgesdd
+   cgesdd
+   zgesdd
+
+   sgesdd_lwork
+   dgesdd_lwork
+   cgesdd_lwork
+   zgesdd_lwork
+
+   sgesv
+   dgesv
+   cgesv
+   zgesv
+
+   sgesvd
+   dgesvd
+   cgesvd
+   zgesvd
+
+   sgesvd_lwork
+   dgesvd_lwork
+   cgesvd_lwork
+   zgesvd_lwork
+
+   sgesvx
+   dgesvx
+   cgesvx
+   zgesvx
+
+   sgetrf
+   dgetrf
+   cgetrf
+   zgetrf
+
+   sgetc2
+   dgetc2
+   cgetc2
+   zgetc2
+
+   sgetri
+   dgetri
+   cgetri
+   zgetri
+
+   sgetri_lwork
+   dgetri_lwork
+   cgetri_lwork
+   zgetri_lwork
+
+   sgetrs
+   dgetrs
+   cgetrs
+   zgetrs
+
+   sgesc2
+   dgesc2
+   cgesc2
+   zgesc2
+
+   sgges
+   dgges
+   cgges
+   zgges
+
+   sggev
+   dggev
+   cggev
+   zggev
+
+   sgglse
+   dgglse
+   cgglse
+   zgglse
+
+   sgglse_lwork
+   dgglse_lwork
+   cgglse_lwork
+   zgglse_lwork
+
+   sgtsv
+   dgtsv
+   cgtsv
+   zgtsv
+
+   sgtsvx
+   dgtsvx
+   cgtsvx
+   zgtsvx
+
+   chbevd
+   zhbevd
+
+   chbevx
+   zhbevx
+
+   checon
+   zhecon
+
+   cheequb
+   zheequb
+
+   cheev
+   zheev
+
+   cheev_lwork
+   zheev_lwork
+
+   cheevd
+   zheevd
+
+   cheevd_lwork
+   zheevd_lwork
+
+   cheevr
+   zheevr
+
+   cheevr_lwork
+   zheevr_lwork
+
+   cheevx
+   zheevx
+
+   cheevx_lwork
+   zheevx_lwork
+
+   chegst
+   zhegst
+
+   chegv
+   zhegv
+
+   chegv_lwork
+   zhegv_lwork
+
+   chegvd
+   zhegvd
+
+   chegvx
+   zhegvx
+
+   chegvx_lwork
+   zhegvx_lwork
+
+   chesv
+   zhesv
+
+   chesv_lwork
+   zhesv_lwork
+
+   chesvx
+   zhesvx
+
+   chesvx_lwork
+   zhesvx_lwork
+
+   chetrd
+   zhetrd
+
+   chetrd_lwork
+   zhetrd_lwork
+
+   chetrf
+   zhetrf
+
+   chetrf_lwork
+   zhetrf_lwork
+
+   chetri
+   zhetri
+
+   chetrs
+   zhetrs
+
+   chfrk
+   zhfrk
+
+   slamch
+   dlamch
+
+   slangb
+   dlangb
+   clangb
+   zlangb
+
+   slange
+   dlange
+   clange
+   zlange
+
+   slantr
+   dlantr
+   clantr
+   zlantr
+
+   slarf
+   dlarf
+   clarf
+   zlarf
+
+   slarfg
+   dlarfg
+   clarfg
+   zlarfg
+
+   slartg
+   dlartg
+   clartg
+   zlartg
+
+   slasd4
+   dlasd4
+
+   slaswp
+   dlaswp
+   claswp
+   zlaswp
+
+   slauum
+   dlauum
+   clauum
+   zlauum
+
+   sorcsd
+   dorcsd
+   sorcsd_lwork
+   dorcsd_lwork
+
+   sorghr
+   dorghr
+   sorghr_lwork
+   dorghr_lwork
+
+   sorgqr
+   dorgqr
+
+   sorgrq
+   dorgrq
+
+   sormqr
+   dormqr
+
+   sormrz
+   dormrz
+
+   sormrz_lwork
+   dormrz_lwork
+
+   spbsv
+   dpbsv
+   cpbsv
+   zpbsv
+
+   spbtrf
+   dpbtrf
+   cpbtrf
+   zpbtrf
+
+   spbtrs
+   dpbtrs
+   cpbtrs
+   zpbtrs
+
+   spftrf
+   dpftrf
+   cpftrf
+   zpftrf
+
+   spftri
+   dpftri
+   cpftri
+   zpftri
+
+   spftrs
+   dpftrs
+   cpftrs
+   zpftrs
+
+   spocon
+   dpocon
+   cpocon
+   zpocon
+
+   spstrf
+   dpstrf
+   cpstrf
+   zpstrf
+
+   spstf2
+   dpstf2
+   cpstf2
+   zpstf2
+
+   sposv
+   dposv
+   cposv
+   zposv
+
+   sposvx
+   dposvx
+   cposvx
+   zposvx
+
+   spotrf
+   dpotrf
+   cpotrf
+   zpotrf
+
+   spotri
+   dpotri
+   cpotri
+   zpotri
+
+   spotrs
+   dpotrs
+   cpotrs
+   zpotrs
+
+   sppcon
+   dppcon
+   cppcon
+   zppcon
+
+   sppsv
+   dppsv
+   cppsv
+   zppsv
+
+   spptrf
+   dpptrf
+   cpptrf
+   zpptrf
+
+   spptri
+   dpptri
+   cpptri
+   zpptri
+
+   spptrs
+   dpptrs
+   cpptrs
+   zpptrs
+
+   sptsv
+   dptsv
+   cptsv
+   zptsv
+
+   sptsvx
+   dptsvx
+   cptsvx
+   zptsvx
+
+   spttrf
+   dpttrf
+   cpttrf
+   zpttrf
+
+   spttrs
+   dpttrs
+   cpttrs
+   zpttrs
+
+   spteqr
+   dpteqr
+   cpteqr
+   zpteqr
+
+   crot
+   zrot
+
+   ssbev
+   dsbev
+
+   ssbevd
+   dsbevd
+
+   ssbevx
+   dsbevx
+
+   ssfrk
+   dsfrk
+
+   sstebz
+   dstebz
+
+   sstein
+   dstein
+
+   sstemr
+   dstemr
+
+   sstemr_lwork
+   dstemr_lwork
+
+   ssterf
+   dsterf
+
+   sstev
+   dstev
+
+   sstevd
+   dstevd
+
+   ssycon
+   dsycon
+   csycon
+   zsycon
+
+   ssyconv
+   dsyconv
+   csyconv
+   zsyconv
+
+   ssyequb
+   dsyequb
+   csyequb
+   zsyequb
+
+   ssyev
+   dsyev
+
+   ssyev_lwork
+   dsyev_lwork
+
+   ssyevd
+   dsyevd
+
+   ssyevd_lwork
+   dsyevd_lwork
+
+   ssyevr
+   dsyevr
+
+   ssyevr_lwork
+   dsyevr_lwork
+
+   ssyevx
+   dsyevx
+
+   ssyevx_lwork
+   dsyevx_lwork
+
+   ssygst
+   dsygst
+
+   ssygv
+   dsygv
+
+   ssygv_lwork
+   dsygv_lwork
+
+   ssygvd
+   dsygvd
+
+   ssygvx
+   dsygvx
+
+   ssygvx_lwork
+   dsygvx_lwork
+
+   ssysv
+   dsysv
+   csysv
+   zsysv
+
+   ssysv_lwork
+   dsysv_lwork
+   csysv_lwork
+   zsysv_lwork
+
+   ssysvx
+   dsysvx
+   csysvx
+   zsysvx
+
+   ssysvx_lwork
+   dsysvx_lwork
+   csysvx_lwork
+   zsysvx_lwork
+
+   ssytf2
+   dsytf2
+   csytf2
+   zsytf2
+
+   ssytrd
+   dsytrd
+
+   ssytrd_lwork
+   dsytrd_lwork
+
+   ssytrf
+   dsytrf
+   csytrf
+   zsytrf
+
+   ssytrf_lwork
+   dsytrf_lwork
+   csytrf_lwork
+   zsytrf_lwork
+
+   ssytri
+   dsytri
+   csytri
+   zsytri
+
+   ssytrs
+   dsytrs
+   csytrs
+   zsytrs
+
+   stbtrs
+   dtbtrs
+   ctbtrs
+   ztbtrs
+
+   stfsm
+   dtfsm
+   ctfsm
+   ztfsm
+
+   stfttp
+   dtfttp
+   ctfttp
+   ztfttp
+
+   stfttr
+   dtfttr
+   ctfttr
+   ztfttr
+
+   stgexc
+   dtgexc
+   ctgexc
+   ztgexc
+
+   stgsen
+   dtgsen
+   ctgsen
+   ztgsen
+
+   stgsen_lwork
+   dtgsen_lwork
+   ctgsen_lwork
+   ztgsen_lwork
+
+   stgsyl
+   dtgsyl
+
+   stpttf
+   dtpttf
+   ctpttf
+   ztpttf
+
+   stpttr
+   dtpttr
+   ctpttr
+   ztpttr
+
+   strcon
+   dtrcon
+   ctrcon
+   ztrcon
+
+   strexc
+   dtrexc
+   ctrexc
+   ztrexc
+
+   strsen
+   dtrsen
+   ctrsen
+   ztrsen
+
+   strsen_lwork
+   dtrsen_lwork
+   ctrsen_lwork
+   ztrsen_lwork
+
+   strsyl
+   dtrsyl
+   ctrsyl
+   ztrsyl
+
+   strtri
+   dtrtri
+   ctrtri
+   ztrtri
+
+   strtrs
+   dtrtrs
+   ctrtrs
+   ztrtrs
+
+   strttf
+   dtrttf
+   ctrttf
+   ztrttf
+
+   strttp
+   dtrttp
+   ctrttp
+   ztrttp
+
+   stzrzf
+   dtzrzf
+   ctzrzf
+   ztzrzf
+
+   stzrzf_lwork
+   dtzrzf_lwork
+   ctzrzf_lwork
+   ztzrzf_lwork
+
+   cunghr
+   zunghr
+
+   cunghr_lwork
+   zunghr_lwork
+
+   cungqr
+   zungqr
+
+   cungrq
+   zungrq
+
+   cunmqr
+   zunmqr
+
+   sgeqrt
+   dgeqrt
+   cgeqrt
+   zgeqrt
+
+   sgemqrt
+   dgemqrt
+   cgemqrt
+   zgemqrt
+
+   sgttrf
+   dgttrf
+   cgttrf
+   zgttrf
+
+   sgttrs
+   dgttrs
+   cgttrs
+   zgttrs
+
+   sgtcon
+   dgtcon
+   cgtcon
+   zgtcon
+
+   stpqrt
+   dtpqrt
+   ctpqrt
+   ztpqrt
+
+   stpmqrt
+   dtpmqrt
+   ctpmqrt
+   ztpmqrt
+
+   cuncsd
+   zuncsd
+
+   cuncsd_lwork
+   zuncsd_lwork
+
+   cunmrz
+   zunmrz
+
+   cunmrz_lwork
+   zunmrz_lwork
+
+   ilaver
+
+"""
+#
+# Author: Pearu Peterson, March 2002
+#
+
+import numpy as np
+from .blas import (
+    _get_funcs, _memoize_get_funcs,
+    find_best_blas_type as find_best_lapack_type   # to appease the name test
+)
+
+from re import compile as regex_compile
+from scipy.__config__ import CONFIG
+
+# If `_fblas` was built, it means the Cython BLAS ABI is LP64, and we're then also
+# keeping `linalg.blas` as LP64.
+HAS_LP64 = not bool(CONFIG['Build Dependencies']['blas']['cython blas ilp64'])
+HAS_ILP64 = CONFIG['Build Dependencies']['lapack']['has ilp64']
+del CONFIG
+
+_flapack = None
+if HAS_LP64:
+    from scipy.linalg import _flapack
+
+_flapack_64 = None
+if HAS_ILP64:
+    from scipy.linalg import _flapack_64
+
+if not (HAS_LP64 or HAS_ILP64):
+    raise RuntimeError("SciPy needs either LP64 or ILP64 LAPACK.")
+
+if HAS_LP64:
+    from scipy.linalg._flapack import *  # noqa: E402, F403
+else:
+    from scipy.linalg._flapack_64 import *  # noqa: E402, F403
+
+
+__all__ = ['get_lapack_funcs']
+
+# some convenience alias for complex functions
+_lapack_alias = {
+    'corghr': 'cunghr', 'zorghr': 'zunghr',
+    'corghr_lwork': 'cunghr_lwork', 'zorghr_lwork': 'zunghr_lwork',
+    'corgqr': 'cungqr', 'zorgqr': 'zungqr',
+    'cormqr': 'cunmqr', 'zormqr': 'zunmqr',
+    'corgrq': 'cungrq', 'zorgrq': 'zungrq',
+}
+
+
+# Place guards against docstring rendering issues with special characters
+p1 = regex_compile(r'with bounds (?P.*?)( and (?P.*?) storage){0,1}\n')
+p2 = regex_compile(r'Default: (?P.*?)\n')
+
+
+def backtickrepl(m):
+    if m.group('s'):
+        return (f"with bounds ``{m.group('b')}`` with ``{m.group('s')}`` storage\n")
+    else:
+        return f"with bounds ``{m.group('b')}``\n"
+
+
+for routine in [ssyevr, dsyevr, cheevr, zheevr,  # pyrefly:ignore[unknown-name]
+                ssyevx, dsyevx, cheevx, zheevx,  # pyrefly:ignore[unknown-name]
+                ssygvd, dsygvd, chegvd, zhegvd]:  # pyrefly:ignore[unknown-name]
+    if routine.__doc__:
+        routine.__doc__ = p1.sub(backtickrepl, routine.__doc__)
+        routine.__doc__ = p2.sub('Default ``\\1``\n', routine.__doc__)
+    else:
+        continue
+
+del regex_compile, p1, p2, backtickrepl
+
+
+@_memoize_get_funcs
+def get_lapack_funcs(names, arrays=(), dtype=None, ilp64="preferred"):
+    """Return available LAPACK function objects from names.
+
+    Arrays are used to determine the optimal prefix of LAPACK routines.
+
+    Parameters
+    ----------
+    names : str or sequence of str
+        Name(s) of LAPACK functions without type prefix.
+
+    arrays : sequence of ndarrays, optional
+        Arrays can be given to determine optimal prefix of LAPACK
+        routines. If not given, double-precision routines will be
+        used, otherwise the most generic type in arrays will be used.
+
+    dtype : str or dtype, optional
+        Data-type specifier. Not used if `arrays` is non-empty.
+
+    ilp64 : {True, False, 'preferred'}, optional
+        Whether to return ILP64 routine variant.
+        Choosing 'preferred' returns ILP64 routine if available, and
+        otherwise the 32-bit routine. Default: ``'preferred'``.
+
+    Returns
+    -------
+    funcs : list
+        List containing the found function(s).
+
+    Raises
+    ------
+    RuntimeError
+        If the requested LP64/ILP64 variant is not available.
+
+    See Also
+    --------
+    scipy.linalg.blas.get_blas_funcs
+        A similar routine for selecting BLAS functions.
+
+    Notes
+    -----
+    In LAPACK, the naming convention is that all functions start with a
+    type prefix, which depends on the type of the principal
+    matrix. These can be one of ``{'s', 'd', 'c', 'z'}`` for the NumPy
+    types ``{float32, float64, complex64, complex128}`` respectively, and
+    are stored in attribute ``typecode`` of the returned functions.
+
+    Examples
+    --------
+    Suppose we would like to use '?lange' routine which computes the selected
+    norm of an array. We pass our array in order to get the correct 'lange'
+    flavor.
+
+    >>> import numpy as np
+    >>> import scipy.linalg as LA
+    >>> rng = np.random.default_rng()
+
+    >>> a = rng.random((3, 2))
+    >>> x_lange = LA.get_lapack_funcs('lange', (a,))
+    >>> x_lange.typecode
+    'd'
+    >>> x_lange = LA.get_lapack_funcs('lange', (a*1j,))
+    >>> x_lange.typecode
+    'z'
+
+    If you want to select a specific LAPACK variant instead of relying on array types,
+    use the ``dtype=`` argument:
+
+    >>> LA.get_lapack_funcs('lange', dtype=np.float32)
+    
+
+    The ``int_dtype`` attribute stores whether the routine is ILP64 (integer arguments
+    and outputs are 64-bit) or LP64 (integer arguments and outputs are 32-bit):
+
+    >>> x_lange.int_dtype
+    dtype('int32')   # may vary
+
+    **Work size computations**
+
+    Several LAPACK routines work best when its internal WORK array has
+    the optimal size (big enough for fast computation and small enough to
+    avoid waste of memory). This size is determined also by a dedicated query
+    to the function which is often wrapped as a standalone function and
+    commonly denoted as ``###_lwork``. Below is an example for ``?sysv``
+
+    >>> a = rng.random((1000, 1000))
+    >>> b = rng.random((1000, 1)) * 1j
+    >>> # We pick up zsysv and zsysv_lwork due to b array
+    ... xsysv, xlwork = LA.get_lapack_funcs(('sysv', 'sysv_lwork'), (a, b))
+    >>> opt_lwork, _ = xlwork(a.shape[0])  # returns a complex for 'z' prefix
+    >>> udut, ipiv, x, info = xsysv(a, b, lwork=int(opt_lwork.real))
+
+    """
+    if isinstance(ilp64, str):
+        if ilp64 == 'preferred':
+            ilp64 = HAS_ILP64
+        else:
+            raise ValueError(f"Invalid value for {ilp64 = }.")
+
+    if not ilp64:
+        return _get_funcs(names, arrays, dtype,
+                          "LAPACK", _flapack, "flapack", _lapack_alias,
+                          ilp64=False)
+    else:
+        if not HAS_ILP64:
+            raise RuntimeError("LAPACK ILP64 routine requested, but Scipy "
+                               "compiled only with 32-bit LAPACK")
+        return _get_funcs(names, arrays, dtype,
+                          "LAPACK", _flapack_64, "flapack_64", _lapack_alias,
+                          ilp64=True)
+
+
+_int32_max = np.iinfo(np.int32).max
+_int64_max = np.iinfo(np.int64).max
+
+
+def _compute_lwork(routine, *args, **kwargs):
+    """
+    Round floating-point lwork returned by lapack to integer.
+
+    Several LAPACK routines compute optimal values for LWORK, which
+    they return in a floating-point variable. However, for large
+    values of LWORK, single-precision floating point is not sufficient
+    to hold the exact value --- some LAPACK versions (<= 3.5.0 at
+    least) truncate the returned integer to single precision and in
+    some cases this can be smaller than the required value.
+
+    Examples
+    --------
+    >>> from scipy.linalg import lapack
+    >>> n = 5000
+    >>> s_r, s_lw = lapack.get_lapack_funcs(('sysvx', 'sysvx_lwork'))
+    >>> lwork = lapack._compute_lwork(s_lw, n)
+    >>> lwork
+    32000
+
+    """
+    dtype = getattr(routine, 'dtype', None)
+    int_dtype = getattr(routine, 'int_dtype', None)
+    ret = routine(*args, **kwargs)
+    if ret[-1] != 0:
+        raise ValueError(f"Internal work array size computation failed: {ret[-1]}")
+
+    if len(ret) == 2:
+        return _check_work_float(ret[0].real, dtype, int_dtype)
+    else:
+        return tuple(_check_work_float(x.real, dtype, int_dtype)
+                     for x in ret[:-1])
+
+
+def _check_work_float(value, dtype, int_dtype):
+    """
+    Convert LAPACK-returned work array size float to integer,
+    carefully for single-precision types.
+    """
+
+    if dtype == np.float32 or dtype == np.complex64:
+        # Single-precision routine -- take next fp value to work
+        # around possible truncation in LAPACK code
+        value = np.nextafter(value, np.inf, dtype=np.float32)
+
+    value = int(value)
+    if int_dtype.itemsize == 4:
+        if value < 0 or value > _int32_max:
+            raise ValueError("Too large work array required -- computation "
+                             "cannot be performed with standard 32-bit"
+                             " LAPACK.")
+    elif int_dtype.itemsize == 8:
+        if value < 0 or value > _int64_max:
+            raise ValueError("Too large work array required -- computation"
+                             " cannot be performed with standard 64-bit"
+                             " LAPACK.")
+    return value
+
+
+# The numpy facilities for type-casting checks are too slow for small sized
+# arrays and eat away the time budget for the checkups. Here we set a
+# precomputed dict container of the numpy.can_cast() table.
+
+# It can be used to determine quickly what a dtype can be cast to LAPACK
+# compatible types, i.e., 'float32, float64, complex64, complex128'.
+# Then it can be checked via "casting_dict[arr.dtype.char]"
+
+# TODO unify "normalization" functions below, see gh-24505
+
+_lapack_cast_dict = {x: ''.join([y for y in 'fdFD' if np.can_cast(x, y)])
+                    for x in np.typecodes['All']}
+
+def _normalize_lapack_dtype(a, overwrite_a):
+    """Make sure an input array has a LAPACK-compatible dtype, cast and copy otherwise.
+    """
+    _, dtyp, _ = find_best_lapack_type((a,))
+    needs_copy = dtyp.char != a.dtype.char  # .char to tell 'g' from 'd' on arm
+    if needs_copy:
+        a = a.astype(dtyp)   # makes a copy, free to scratch
+    return a, overwrite_a or needs_copy
+
+
+def _normalize_lapack_dtype1(a, overwrite_a):
+    if a.dtype.char not in 'fdFD':
+        dtype_char = _lapack_cast_dict[a.dtype.char]
+        if not dtype_char:  # No casting possible
+            raise TypeError(f'The dtype {a.dtype} cannot be cast '
+                            'to float(32, 64) or complex(64, 128).')
+
+        a = a.astype(dtype_char[0])  # makes a copy, free to scratch
+        overwrite_a = True
+    return a, overwrite_a
+
+
+def _ensure_dtype_cdsz(*arrays):
+    # Ensure that the dtype of arrays is one of the standard types
+    # compatible with LAPACK functions (single or double precision
+    # real or complex).
+    dtype = np.result_type(*arrays)
+    if not np.issubdtype(dtype, np.inexact):
+        return (array.astype(np.float64) for array in arrays)
+    complex = np.issubdtype(dtype, np.complexfloating)
+    if np.finfo(dtype).bits <= 32:
+        dtype = np.complex64 if complex else np.float32
+    elif np.finfo(dtype).bits >= 64:
+        dtype = np.complex128 if complex else np.float64
+    return (array.astype(dtype, copy=False) for array in arrays)
+
+
+def _ensure_aligned_and_native(a, overwrite_a):
+    """Make sure an input array is aligned and not byteswapped, copy otherwise.
+    """
+    if not (a.flags['ALIGNED'] and a.dtype.byteorder == '='):
+        overwrite_a = True
+        a = a.copy()
+    return a, overwrite_a
diff --git a/.venv/lib/python3.12/site-packages/scipy/linalg/matfuncs.py b/.venv/lib/python3.12/site-packages/scipy/linalg/matfuncs.py
new file mode 100644
index 0000000000000000000000000000000000000000..9ec8123b3ad8df096d5791c29bb28cce8271d4ad
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/linalg/matfuncs.py
@@ -0,0 +1,23 @@
+# This file is not meant for public use and will be removed in SciPy v2.0.0.
+# Use the `scipy.linalg` namespace for importing the functions
+# included below.
+
+from scipy._lib.deprecation import _sub_module_deprecation
+
+
+__all__ = [  # noqa: F822
+    'expm', 'cosm', 'sinm', 'tanm', 'coshm', 'sinhm',
+    'tanhm', 'logm', 'funm', 'signm', 'sqrtm',
+    'expm_frechet', 'expm_cond', 'fractional_matrix_power',
+    'khatri_rao', 'norm', 'solve', 'inv', 'svd', 'schur', 'rsf2csf'
+]
+
+
+def __dir__():
+    return __all__
+
+
+def __getattr__(name):
+    return _sub_module_deprecation(sub_package="linalg", module="matfuncs",
+                                   private_modules=["_matfuncs"], all=__all__,
+                                   attribute=name)
diff --git a/.venv/lib/python3.12/site-packages/scipy/linalg/misc.py b/.venv/lib/python3.12/site-packages/scipy/linalg/misc.py
new file mode 100644
index 0000000000000000000000000000000000000000..1fad087489c6a24c8e33df54b811b6c37a3a46d4
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/linalg/misc.py
@@ -0,0 +1,21 @@
+# This file is not meant for public use and will be removed in SciPy v2.0.0.
+# Use the `scipy.linalg` namespace for importing the functions
+# included below.
+
+from scipy._lib.deprecation import _sub_module_deprecation
+
+
+__all__ = [  # noqa: F822
+    'LinAlgError', 'LinAlgWarning', 'norm', 'get_blas_funcs',
+    'get_lapack_funcs'
+]
+
+
+def __dir__():
+    return __all__
+
+
+def __getattr__(name):
+    return _sub_module_deprecation(sub_package="linalg", module="misc",
+                                   private_modules=["_misc"], all=__all__,
+                                   attribute=name)
diff --git a/.venv/lib/python3.12/site-packages/scipy/linalg/special_matrices.py b/.venv/lib/python3.12/site-packages/scipy/linalg/special_matrices.py
new file mode 100644
index 0000000000000000000000000000000000000000..4810e8a4506730dadc7072ee0748870542c173bb
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/linalg/special_matrices.py
@@ -0,0 +1,22 @@
+# This file is not meant for public use and will be removed in SciPy v2.0.0.
+# Use the `scipy.linalg` namespace for importing the functions
+# included below.
+
+from scipy._lib.deprecation import _sub_module_deprecation
+
+__all__ = [  # noqa: F822
+    'toeplitz', 'circulant', 'hankel',
+    'hadamard', 'leslie', 'block_diag', 'companion',
+    'helmert', 'hilbert', 'invhilbert', 'pascal', 'invpascal', 'dft',
+    'fiedler', 'fiedler_companion', 'convolution_matrix'
+]
+
+
+def __dir__():
+    return __all__
+
+
+def __getattr__(name):
+    return _sub_module_deprecation(sub_package="linalg", module="special_matrices",
+                                   private_modules=["_special_matrices"], all=__all__,
+                                   attribute=name)
diff --git a/.venv/lib/python3.12/site-packages/scipy/linalg/tests/__init__.py b/.venv/lib/python3.12/site-packages/scipy/linalg/tests/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/.venv/lib/python3.12/site-packages/scipy/linalg/tests/_cython_examples/extending.pyx b/.venv/lib/python3.12/site-packages/scipy/linalg/tests/_cython_examples/extending.pyx
new file mode 100644
index 0000000000000000000000000000000000000000..61503ed4e00e0dba36a74fd92ea9bf1b7aa99383
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/linalg/tests/_cython_examples/extending.pyx
@@ -0,0 +1,27 @@
+#!/usr/bin/env python3
+#cython: language_level=3
+#cython: boundscheck=False
+#cython: wraparound=False
+
+cimport scipy.linalg
+from scipy.linalg.cython_blas cimport blas_int, cdotu
+from scipy.linalg.cython_lapack cimport dgtsv
+
+cpdef tridiag(double[:] a, double[:] b, double[:] c, double[:] x):
+    """ Solve the system A y = x for y where A is the tridiagonal matrix with
+    subdiagonal 'a', diagonal 'b', and superdiagonal 'c'. """
+    cdef blas_int n=b.shape[0], nrhs=1, info
+    # Solution is written over the values in x.
+    dgtsv(&n, &nrhs, &a[0], &b[0], &c[0], &x[0], &n, &info)
+
+cpdef float complex complex_dot(float complex[:] cx, float complex[:] cy):
+    """ Take dot product of two complex vectors """
+    cdef:
+        blas_int n = cx.shape[0]
+        blas_int incx = cx.strides[0] // sizeof(cx[0])
+        blas_int incy = cy.strides[0] // sizeof(cy[0])
+    return cdotu(&n, &cx[0], &incx, &cy[0], &incy)
+
+cpdef int get_blas_int_size():
+    """Return sizeof(blas_int) to verify correct type at compile+runtime."""
+    return sizeof(blas_int)
diff --git a/.venv/lib/python3.12/site-packages/scipy/linalg/tests/_cython_examples/meson.build b/.venv/lib/python3.12/site-packages/scipy/linalg/tests/_cython_examples/meson.build
new file mode 100644
index 0000000000000000000000000000000000000000..13a07eac45ec4b4e3f71a9c17cca674e8b3b9aa6
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/linalg/tests/_cython_examples/meson.build
@@ -0,0 +1,34 @@
+project('random-build-examples', 'c', 'cpp', 'cython')
+
+fs = import('fs')
+
+py3 = import('python').find_installation(pure: false)
+
+cy = meson.get_compiler('cython')
+
+if not cy.version().version_compare('>=3.2.0')
+  error('tests requires Cython >= 3.2.0')
+endif
+
+cython_args = []
+if cy.version().version_compare('>=3.1.0')
+  cython_args += ['-Xfreethreading_compatible=True']
+endif
+
+py3.extension_module(
+  'extending',
+  'extending.pyx',
+  install: false,
+  cython_args: cython_args,
+  c_args: ['-DCYTHON_CCOMPLEX=0'] # see gh-18975 for why we need this
+)
+
+extending_cpp = fs.copyfile('extending.pyx', 'extending_cpp.pyx')
+py3.extension_module(
+  'extending_cpp',
+  extending_cpp,
+  install: false,
+  override_options : ['cython_language=cpp'],
+  cython_args: cython_args,
+  cpp_args: ['-DCYTHON_CCOMPLEX=0'] # see gh-18975 for why we need this
+)
diff --git a/.venv/lib/python3.12/site-packages/scipy/linalg/tests/cython_abi_signatures.json b/.venv/lib/python3.12/site-packages/scipy/linalg/tests/cython_abi_signatures.json
new file mode 100644
index 0000000000000000000000000000000000000000..ba925c139089275e231200928a417296f295a1de
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/linalg/tests/cython_abi_signatures.json
@@ -0,0 +1,1650 @@
+{
+  "scipy.linalg.cython_blas": {
+    "caxpy": "void (int *, __pyx_t_float_complex *, __pyx_t_float_complex *, int *, __pyx_t_float_complex *, int *)",
+    "ccopy": "void (int *, __pyx_t_float_complex *, int *, __pyx_t_float_complex *, int *)",
+    "cdotc": "__pyx_t_float_complex (int *, __pyx_t_float_complex *, int *, __pyx_t_float_complex *, int *)",
+    "cdotu": "__pyx_t_float_complex (int *, __pyx_t_float_complex *, int *, __pyx_t_float_complex *, int *)",
+    "cgbmv": "void (char *, int *, int *, int *, int *, __pyx_t_float_complex *, __pyx_t_float_complex *, int *, __pyx_t_float_complex *, int *, __pyx_t_float_complex *, __pyx_t_float_complex *, int *)",
+    "cgemm": "void (char *, char *, int *, int *, int *, __pyx_t_float_complex *, __pyx_t_float_complex *, int *, __pyx_t_float_complex *, int *, __pyx_t_float_complex *, __pyx_t_float_complex *, int *)",
+    "cgemv": "void (char *, int *, int *, __pyx_t_float_complex *, __pyx_t_float_complex *, int *, __pyx_t_float_complex *, int *, __pyx_t_float_complex *, __pyx_t_float_complex *, int *)",
+    "cgerc": "void (int *, int *, __pyx_t_float_complex *, __pyx_t_float_complex *, int *, __pyx_t_float_complex *, int *, __pyx_t_float_complex *, int *)",
+    "cgeru": "void (int *, int *, __pyx_t_float_complex *, __pyx_t_float_complex *, int *, __pyx_t_float_complex *, int *, __pyx_t_float_complex *, int *)",
+    "chbmv": "void (char *, int *, int *, __pyx_t_float_complex *, __pyx_t_float_complex *, int *, __pyx_t_float_complex *, int *, __pyx_t_float_complex *, __pyx_t_float_complex *, int *)",
+    "chemm": "void (char *, char *, int *, int *, __pyx_t_float_complex *, __pyx_t_float_complex *, int *, __pyx_t_float_complex *, int *, __pyx_t_float_complex *, __pyx_t_float_complex *, int *)",
+    "chemv": "void (char *, int *, __pyx_t_float_complex *, __pyx_t_float_complex *, int *, __pyx_t_float_complex *, int *, __pyx_t_float_complex *, __pyx_t_float_complex *, int *)",
+    "cher": "void (char *, int *, __pyx_t_5scipy_6linalg_11cython_blas_s *, __pyx_t_float_complex *, int *, __pyx_t_float_complex *, int *)",
+    "cher2": "void (char *, int *, __pyx_t_float_complex *, __pyx_t_float_complex *, int *, __pyx_t_float_complex *, int *, __pyx_t_float_complex *, int *)",
+    "cher2k": "void (char *, char *, int *, int *, __pyx_t_float_complex *, __pyx_t_float_complex *, int *, __pyx_t_float_complex *, int *, __pyx_t_5scipy_6linalg_11cython_blas_s *, __pyx_t_float_complex *, int *)",
+    "cherk": "void (char *, char *, int *, int *, __pyx_t_5scipy_6linalg_11cython_blas_s *, __pyx_t_float_complex *, int *, __pyx_t_5scipy_6linalg_11cython_blas_s *, __pyx_t_float_complex *, int *)",
+    "chpmv": "void (char *, int *, __pyx_t_float_complex *, __pyx_t_float_complex *, __pyx_t_float_complex *, int *, __pyx_t_float_complex *, __pyx_t_float_complex *, int *)",
+    "chpr": "void (char *, int *, __pyx_t_5scipy_6linalg_11cython_blas_s *, __pyx_t_float_complex *, int *, __pyx_t_float_complex *)",
+    "chpr2": "void (char *, int *, __pyx_t_float_complex *, __pyx_t_float_complex *, int *, __pyx_t_float_complex *, int *, __pyx_t_float_complex *)",
+    "crotg": "void (__pyx_t_float_complex *, __pyx_t_float_complex *, __pyx_t_5scipy_6linalg_11cython_blas_s *, __pyx_t_float_complex *)",
+    "cscal": "void (int *, __pyx_t_float_complex *, __pyx_t_float_complex *, int *)",
+    "csrot": "void (int *, __pyx_t_float_complex *, int *, __pyx_t_float_complex *, int *, __pyx_t_5scipy_6linalg_11cython_blas_s *, __pyx_t_5scipy_6linalg_11cython_blas_s *)",
+    "csscal": "void (int *, __pyx_t_5scipy_6linalg_11cython_blas_s *, __pyx_t_float_complex *, int *)",
+    "cswap": "void (int *, __pyx_t_float_complex *, int *, __pyx_t_float_complex *, int *)",
+    "csymm": "void (char *, char *, int *, int *, __pyx_t_float_complex *, __pyx_t_float_complex *, int *, __pyx_t_float_complex *, int *, __pyx_t_float_complex *, __pyx_t_float_complex *, int *)",
+    "csyr2k": "void (char *, char *, int *, int *, __pyx_t_float_complex *, __pyx_t_float_complex *, int *, __pyx_t_float_complex *, int *, __pyx_t_float_complex *, __pyx_t_float_complex *, int *)",
+    "csyrk": "void (char *, char *, int *, int *, __pyx_t_float_complex *, __pyx_t_float_complex *, int *, __pyx_t_float_complex *, __pyx_t_float_complex *, int *)",
+    "ctbmv": "void (char *, char *, char *, int *, int *, __pyx_t_float_complex *, int *, __pyx_t_float_complex *, int *)",
+    "ctbsv": "void (char *, char *, char *, int *, int *, __pyx_t_float_complex *, int *, __pyx_t_float_complex *, int *)",
+    "ctpmv": "void (char *, char *, char *, int *, __pyx_t_float_complex *, __pyx_t_float_complex *, int *)",
+    "ctpsv": "void (char *, char *, char *, int *, __pyx_t_float_complex *, __pyx_t_float_complex *, int *)",
+    "ctrmm": "void (char *, char *, char *, char *, int *, int *, __pyx_t_float_complex *, __pyx_t_float_complex *, int *, __pyx_t_float_complex *, int *)",
+    "ctrmv": "void (char *, char *, char *, int *, __pyx_t_float_complex *, int *, __pyx_t_float_complex *, int *)",
+    "ctrsm": "void (char *, char *, char *, char *, int *, int *, __pyx_t_float_complex *, __pyx_t_float_complex *, int *, __pyx_t_float_complex *, int *)",
+    "ctrsv": "void (char *, char *, char *, int *, __pyx_t_float_complex *, int *, __pyx_t_float_complex *, int *)",
+    "dasum": "__pyx_t_5scipy_6linalg_11cython_blas_d (int *, __pyx_t_5scipy_6linalg_11cython_blas_d *, int *)",
+    "daxpy": "void (int *, __pyx_t_5scipy_6linalg_11cython_blas_d *, __pyx_t_5scipy_6linalg_11cython_blas_d *, int *, __pyx_t_5scipy_6linalg_11cython_blas_d *, int *)",
+    "dcabs1": "__pyx_t_5scipy_6linalg_11cython_blas_d (__pyx_t_double_complex *)",
+    "dcopy": "void (int *, __pyx_t_5scipy_6linalg_11cython_blas_d *, int *, __pyx_t_5scipy_6linalg_11cython_blas_d *, int *)",
+    "ddot": "__pyx_t_5scipy_6linalg_11cython_blas_d (int *, __pyx_t_5scipy_6linalg_11cython_blas_d *, int *, __pyx_t_5scipy_6linalg_11cython_blas_d *, int *)",
+    "dgbmv": "void (char *, int *, int *, int *, int *, __pyx_t_5scipy_6linalg_11cython_blas_d *, __pyx_t_5scipy_6linalg_11cython_blas_d *, int *, __pyx_t_5scipy_6linalg_11cython_blas_d *, int *, __pyx_t_5scipy_6linalg_11cython_blas_d *, __pyx_t_5scipy_6linalg_11cython_blas_d *, int *)",
+    "dgemm": "void (char *, char *, int *, int *, int *, __pyx_t_5scipy_6linalg_11cython_blas_d *, __pyx_t_5scipy_6linalg_11cython_blas_d *, int *, __pyx_t_5scipy_6linalg_11cython_blas_d *, int *, __pyx_t_5scipy_6linalg_11cython_blas_d *, __pyx_t_5scipy_6linalg_11cython_blas_d *, int *)",
+    "dgemv": "void (char *, int *, int *, __pyx_t_5scipy_6linalg_11cython_blas_d *, __pyx_t_5scipy_6linalg_11cython_blas_d *, int *, __pyx_t_5scipy_6linalg_11cython_blas_d *, int *, __pyx_t_5scipy_6linalg_11cython_blas_d *, __pyx_t_5scipy_6linalg_11cython_blas_d *, int *)",
+    "dger": "void (int *, int *, __pyx_t_5scipy_6linalg_11cython_blas_d *, __pyx_t_5scipy_6linalg_11cython_blas_d *, int *, __pyx_t_5scipy_6linalg_11cython_blas_d *, int *, __pyx_t_5scipy_6linalg_11cython_blas_d *, int *)",
+    "dnrm2": "__pyx_t_5scipy_6linalg_11cython_blas_d (int *, __pyx_t_5scipy_6linalg_11cython_blas_d *, int *)",
+    "drot": "void (int *, __pyx_t_5scipy_6linalg_11cython_blas_d *, int *, __pyx_t_5scipy_6linalg_11cython_blas_d *, int *, __pyx_t_5scipy_6linalg_11cython_blas_d *, __pyx_t_5scipy_6linalg_11cython_blas_d *)",
+    "drotg": "void (__pyx_t_5scipy_6linalg_11cython_blas_d *, __pyx_t_5scipy_6linalg_11cython_blas_d *, __pyx_t_5scipy_6linalg_11cython_blas_d *, __pyx_t_5scipy_6linalg_11cython_blas_d *)",
+    "drotm": "void (int *, __pyx_t_5scipy_6linalg_11cython_blas_d *, int *, __pyx_t_5scipy_6linalg_11cython_blas_d *, int *, __pyx_t_5scipy_6linalg_11cython_blas_d *)",
+    "drotmg": "void (__pyx_t_5scipy_6linalg_11cython_blas_d *, __pyx_t_5scipy_6linalg_11cython_blas_d *, __pyx_t_5scipy_6linalg_11cython_blas_d *, __pyx_t_5scipy_6linalg_11cython_blas_d *, __pyx_t_5scipy_6linalg_11cython_blas_d *)",
+    "dsbmv": "void (char *, int *, int *, __pyx_t_5scipy_6linalg_11cython_blas_d *, __pyx_t_5scipy_6linalg_11cython_blas_d *, int *, __pyx_t_5scipy_6linalg_11cython_blas_d *, int *, __pyx_t_5scipy_6linalg_11cython_blas_d *, __pyx_t_5scipy_6linalg_11cython_blas_d *, int *)",
+    "dscal": "void (int *, __pyx_t_5scipy_6linalg_11cython_blas_d *, __pyx_t_5scipy_6linalg_11cython_blas_d *, int *)",
+    "dsdot": "__pyx_t_5scipy_6linalg_11cython_blas_d (int *, __pyx_t_5scipy_6linalg_11cython_blas_s *, int *, __pyx_t_5scipy_6linalg_11cython_blas_s *, int *)",
+    "dspmv": "void (char *, int *, __pyx_t_5scipy_6linalg_11cython_blas_d *, __pyx_t_5scipy_6linalg_11cython_blas_d *, __pyx_t_5scipy_6linalg_11cython_blas_d *, int *, __pyx_t_5scipy_6linalg_11cython_blas_d *, __pyx_t_5scipy_6linalg_11cython_blas_d *, int *)",
+    "dspr": "void (char *, int *, __pyx_t_5scipy_6linalg_11cython_blas_d *, __pyx_t_5scipy_6linalg_11cython_blas_d *, int *, __pyx_t_5scipy_6linalg_11cython_blas_d *)",
+    "dspr2": "void (char *, int *, __pyx_t_5scipy_6linalg_11cython_blas_d *, __pyx_t_5scipy_6linalg_11cython_blas_d *, int *, __pyx_t_5scipy_6linalg_11cython_blas_d *, int *, __pyx_t_5scipy_6linalg_11cython_blas_d *)",
+    "dswap": "void (int *, __pyx_t_5scipy_6linalg_11cython_blas_d *, int *, __pyx_t_5scipy_6linalg_11cython_blas_d *, int *)",
+    "dsymm": "void (char *, char *, int *, int *, __pyx_t_5scipy_6linalg_11cython_blas_d *, __pyx_t_5scipy_6linalg_11cython_blas_d *, int *, __pyx_t_5scipy_6linalg_11cython_blas_d *, int *, __pyx_t_5scipy_6linalg_11cython_blas_d *, __pyx_t_5scipy_6linalg_11cython_blas_d *, int *)",
+    "dsymv": "void (char *, int *, __pyx_t_5scipy_6linalg_11cython_blas_d *, __pyx_t_5scipy_6linalg_11cython_blas_d *, int *, __pyx_t_5scipy_6linalg_11cython_blas_d *, int *, __pyx_t_5scipy_6linalg_11cython_blas_d *, __pyx_t_5scipy_6linalg_11cython_blas_d *, int *)",
+    "dsyr": "void (char *, int *, __pyx_t_5scipy_6linalg_11cython_blas_d *, __pyx_t_5scipy_6linalg_11cython_blas_d *, int *, __pyx_t_5scipy_6linalg_11cython_blas_d *, int *)",
+    "dsyr2": "void (char *, int *, __pyx_t_5scipy_6linalg_11cython_blas_d *, __pyx_t_5scipy_6linalg_11cython_blas_d *, int *, __pyx_t_5scipy_6linalg_11cython_blas_d *, int *, __pyx_t_5scipy_6linalg_11cython_blas_d *, int *)",
+    "dsyr2k": "void (char *, char *, int *, int *, __pyx_t_5scipy_6linalg_11cython_blas_d *, __pyx_t_5scipy_6linalg_11cython_blas_d *, int *, __pyx_t_5scipy_6linalg_11cython_blas_d *, int *, __pyx_t_5scipy_6linalg_11cython_blas_d *, __pyx_t_5scipy_6linalg_11cython_blas_d *, int *)",
+    "dsyrk": "void (char *, char *, int *, int *, __pyx_t_5scipy_6linalg_11cython_blas_d *, __pyx_t_5scipy_6linalg_11cython_blas_d *, int *, __pyx_t_5scipy_6linalg_11cython_blas_d *, __pyx_t_5scipy_6linalg_11cython_blas_d *, int *)",
+    "dtbmv": "void (char *, char *, char *, int *, int *, __pyx_t_5scipy_6linalg_11cython_blas_d *, int *, __pyx_t_5scipy_6linalg_11cython_blas_d *, int *)",
+    "dtbsv": "void (char *, char *, char *, int *, int *, __pyx_t_5scipy_6linalg_11cython_blas_d *, int *, __pyx_t_5scipy_6linalg_11cython_blas_d *, int *)",
+    "dtpmv": "void (char *, char *, char *, int *, __pyx_t_5scipy_6linalg_11cython_blas_d *, __pyx_t_5scipy_6linalg_11cython_blas_d *, int *)",
+    "dtpsv": "void (char *, char *, char *, int *, __pyx_t_5scipy_6linalg_11cython_blas_d *, __pyx_t_5scipy_6linalg_11cython_blas_d *, int *)",
+    "dtrmm": "void (char *, char *, char *, char *, int *, int *, __pyx_t_5scipy_6linalg_11cython_blas_d *, __pyx_t_5scipy_6linalg_11cython_blas_d *, int *, __pyx_t_5scipy_6linalg_11cython_blas_d *, int *)",
+    "dtrmv": "void (char *, char *, char *, int *, __pyx_t_5scipy_6linalg_11cython_blas_d *, int *, __pyx_t_5scipy_6linalg_11cython_blas_d *, int *)",
+    "dtrsm": "void (char *, char *, char *, char *, int *, int *, __pyx_t_5scipy_6linalg_11cython_blas_d *, __pyx_t_5scipy_6linalg_11cython_blas_d *, int *, __pyx_t_5scipy_6linalg_11cython_blas_d *, int *)",
+    "dtrsv": "void (char *, char *, char *, int *, __pyx_t_5scipy_6linalg_11cython_blas_d *, int *, __pyx_t_5scipy_6linalg_11cython_blas_d *, int *)",
+    "dzasum": "__pyx_t_5scipy_6linalg_11cython_blas_d (int *, __pyx_t_double_complex *, int *)",
+    "dznrm2": "__pyx_t_5scipy_6linalg_11cython_blas_d (int *, __pyx_t_double_complex *, int *)",
+    "icamax": "int (int *, __pyx_t_float_complex *, int *)",
+    "idamax": "int (int *, __pyx_t_5scipy_6linalg_11cython_blas_d *, int *)",
+    "isamax": "int (int *, __pyx_t_5scipy_6linalg_11cython_blas_s *, int *)",
+    "izamax": "int (int *, __pyx_t_double_complex *, int *)",
+    "lsame": "int (char *, char *)",
+    "sasum": "__pyx_t_5scipy_6linalg_11cython_blas_s (int *, __pyx_t_5scipy_6linalg_11cython_blas_s *, int *)",
+    "saxpy": "void (int *, __pyx_t_5scipy_6linalg_11cython_blas_s *, __pyx_t_5scipy_6linalg_11cython_blas_s *, int *, __pyx_t_5scipy_6linalg_11cython_blas_s *, int *)",
+    "scasum": "__pyx_t_5scipy_6linalg_11cython_blas_s (int *, __pyx_t_float_complex *, int *)",
+    "scnrm2": "__pyx_t_5scipy_6linalg_11cython_blas_s (int *, __pyx_t_float_complex *, int *)",
+    "scopy": "void (int *, __pyx_t_5scipy_6linalg_11cython_blas_s *, int *, __pyx_t_5scipy_6linalg_11cython_blas_s *, int *)",
+    "sdot": "__pyx_t_5scipy_6linalg_11cython_blas_s (int *, __pyx_t_5scipy_6linalg_11cython_blas_s *, int *, __pyx_t_5scipy_6linalg_11cython_blas_s *, int *)",
+    "sdsdot": "__pyx_t_5scipy_6linalg_11cython_blas_s (int *, __pyx_t_5scipy_6linalg_11cython_blas_s *, __pyx_t_5scipy_6linalg_11cython_blas_s *, int *, __pyx_t_5scipy_6linalg_11cython_blas_s *, int *)",
+    "sgbmv": "void (char *, int *, int *, int *, int *, __pyx_t_5scipy_6linalg_11cython_blas_s *, __pyx_t_5scipy_6linalg_11cython_blas_s *, int *, __pyx_t_5scipy_6linalg_11cython_blas_s *, int *, __pyx_t_5scipy_6linalg_11cython_blas_s *, __pyx_t_5scipy_6linalg_11cython_blas_s *, int *)",
+    "sgemm": "void (char *, char *, int *, int *, int *, __pyx_t_5scipy_6linalg_11cython_blas_s *, __pyx_t_5scipy_6linalg_11cython_blas_s *, int *, __pyx_t_5scipy_6linalg_11cython_blas_s *, int *, __pyx_t_5scipy_6linalg_11cython_blas_s *, __pyx_t_5scipy_6linalg_11cython_blas_s *, int *)",
+    "sgemv": "void (char *, int *, int *, __pyx_t_5scipy_6linalg_11cython_blas_s *, __pyx_t_5scipy_6linalg_11cython_blas_s *, int *, __pyx_t_5scipy_6linalg_11cython_blas_s *, int *, __pyx_t_5scipy_6linalg_11cython_blas_s *, __pyx_t_5scipy_6linalg_11cython_blas_s *, int *)",
+    "sger": "void (int *, int *, __pyx_t_5scipy_6linalg_11cython_blas_s *, __pyx_t_5scipy_6linalg_11cython_blas_s *, int *, __pyx_t_5scipy_6linalg_11cython_blas_s *, int *, __pyx_t_5scipy_6linalg_11cython_blas_s *, int *)",
+    "snrm2": "__pyx_t_5scipy_6linalg_11cython_blas_s (int *, __pyx_t_5scipy_6linalg_11cython_blas_s *, int *)",
+    "srot": "void (int *, __pyx_t_5scipy_6linalg_11cython_blas_s *, int *, __pyx_t_5scipy_6linalg_11cython_blas_s *, int *, __pyx_t_5scipy_6linalg_11cython_blas_s *, __pyx_t_5scipy_6linalg_11cython_blas_s *)",
+    "srotg": "void (__pyx_t_5scipy_6linalg_11cython_blas_s *, __pyx_t_5scipy_6linalg_11cython_blas_s *, __pyx_t_5scipy_6linalg_11cython_blas_s *, __pyx_t_5scipy_6linalg_11cython_blas_s *)",
+    "srotm": "void (int *, __pyx_t_5scipy_6linalg_11cython_blas_s *, int *, __pyx_t_5scipy_6linalg_11cython_blas_s *, int *, __pyx_t_5scipy_6linalg_11cython_blas_s *)",
+    "srotmg": "void (__pyx_t_5scipy_6linalg_11cython_blas_s *, __pyx_t_5scipy_6linalg_11cython_blas_s *, __pyx_t_5scipy_6linalg_11cython_blas_s *, __pyx_t_5scipy_6linalg_11cython_blas_s *, __pyx_t_5scipy_6linalg_11cython_blas_s *)",
+    "ssbmv": "void (char *, int *, int *, __pyx_t_5scipy_6linalg_11cython_blas_s *, __pyx_t_5scipy_6linalg_11cython_blas_s *, int *, __pyx_t_5scipy_6linalg_11cython_blas_s *, int *, __pyx_t_5scipy_6linalg_11cython_blas_s *, __pyx_t_5scipy_6linalg_11cython_blas_s *, int *)",
+    "sscal": "void (int *, __pyx_t_5scipy_6linalg_11cython_blas_s *, __pyx_t_5scipy_6linalg_11cython_blas_s *, int *)",
+    "sspmv": "void (char *, int *, __pyx_t_5scipy_6linalg_11cython_blas_s *, __pyx_t_5scipy_6linalg_11cython_blas_s *, __pyx_t_5scipy_6linalg_11cython_blas_s *, int *, __pyx_t_5scipy_6linalg_11cython_blas_s *, __pyx_t_5scipy_6linalg_11cython_blas_s *, int *)",
+    "sspr": "void (char *, int *, __pyx_t_5scipy_6linalg_11cython_blas_s *, __pyx_t_5scipy_6linalg_11cython_blas_s *, int *, __pyx_t_5scipy_6linalg_11cython_blas_s *)",
+    "sspr2": "void (char *, int *, __pyx_t_5scipy_6linalg_11cython_blas_s *, __pyx_t_5scipy_6linalg_11cython_blas_s *, int *, __pyx_t_5scipy_6linalg_11cython_blas_s *, int *, __pyx_t_5scipy_6linalg_11cython_blas_s *)",
+    "sswap": "void (int *, __pyx_t_5scipy_6linalg_11cython_blas_s *, int *, __pyx_t_5scipy_6linalg_11cython_blas_s *, int *)",
+    "ssymm": "void (char *, char *, int *, int *, __pyx_t_5scipy_6linalg_11cython_blas_s *, __pyx_t_5scipy_6linalg_11cython_blas_s *, int *, __pyx_t_5scipy_6linalg_11cython_blas_s *, int *, __pyx_t_5scipy_6linalg_11cython_blas_s *, __pyx_t_5scipy_6linalg_11cython_blas_s *, int *)",
+    "ssymv": "void (char *, int *, __pyx_t_5scipy_6linalg_11cython_blas_s *, __pyx_t_5scipy_6linalg_11cython_blas_s *, int *, __pyx_t_5scipy_6linalg_11cython_blas_s *, int *, __pyx_t_5scipy_6linalg_11cython_blas_s *, __pyx_t_5scipy_6linalg_11cython_blas_s *, int *)",
+    "ssyr": "void (char *, int *, __pyx_t_5scipy_6linalg_11cython_blas_s *, __pyx_t_5scipy_6linalg_11cython_blas_s *, int *, __pyx_t_5scipy_6linalg_11cython_blas_s *, int *)",
+    "ssyr2": "void (char *, int *, __pyx_t_5scipy_6linalg_11cython_blas_s *, __pyx_t_5scipy_6linalg_11cython_blas_s *, int *, __pyx_t_5scipy_6linalg_11cython_blas_s *, int *, __pyx_t_5scipy_6linalg_11cython_blas_s *, int *)",
+    "ssyr2k": "void (char *, char *, int *, int *, __pyx_t_5scipy_6linalg_11cython_blas_s *, __pyx_t_5scipy_6linalg_11cython_blas_s *, int *, __pyx_t_5scipy_6linalg_11cython_blas_s *, int *, __pyx_t_5scipy_6linalg_11cython_blas_s *, __pyx_t_5scipy_6linalg_11cython_blas_s *, int *)",
+    "ssyrk": "void (char *, char *, int *, int *, __pyx_t_5scipy_6linalg_11cython_blas_s *, __pyx_t_5scipy_6linalg_11cython_blas_s *, int *, __pyx_t_5scipy_6linalg_11cython_blas_s *, __pyx_t_5scipy_6linalg_11cython_blas_s *, int *)",
+    "stbmv": "void (char *, char *, char *, int *, int *, __pyx_t_5scipy_6linalg_11cython_blas_s *, int *, __pyx_t_5scipy_6linalg_11cython_blas_s *, int *)",
+    "stbsv": "void (char *, char *, char *, int *, int *, __pyx_t_5scipy_6linalg_11cython_blas_s *, int *, __pyx_t_5scipy_6linalg_11cython_blas_s *, int *)",
+    "stpmv": "void (char *, char *, char *, int *, __pyx_t_5scipy_6linalg_11cython_blas_s *, __pyx_t_5scipy_6linalg_11cython_blas_s *, int *)",
+    "stpsv": "void (char *, char *, char *, int *, __pyx_t_5scipy_6linalg_11cython_blas_s *, __pyx_t_5scipy_6linalg_11cython_blas_s *, int *)",
+    "strmm": "void (char *, char *, char *, char *, int *, int *, __pyx_t_5scipy_6linalg_11cython_blas_s *, __pyx_t_5scipy_6linalg_11cython_blas_s *, int *, __pyx_t_5scipy_6linalg_11cython_blas_s *, int *)",
+    "strmv": "void (char *, char *, char *, int *, __pyx_t_5scipy_6linalg_11cython_blas_s *, int *, __pyx_t_5scipy_6linalg_11cython_blas_s *, int *)",
+    "strsm": "void (char *, char *, char *, char *, int *, int *, __pyx_t_5scipy_6linalg_11cython_blas_s *, __pyx_t_5scipy_6linalg_11cython_blas_s *, int *, __pyx_t_5scipy_6linalg_11cython_blas_s *, int *)",
+    "strsv": "void (char *, char *, char *, int *, __pyx_t_5scipy_6linalg_11cython_blas_s *, int *, __pyx_t_5scipy_6linalg_11cython_blas_s *, int *)",
+    "zaxpy": "void (int *, __pyx_t_double_complex *, __pyx_t_double_complex *, int *, __pyx_t_double_complex *, int *)",
+    "zcopy": "void (int *, __pyx_t_double_complex *, int *, __pyx_t_double_complex *, int *)",
+    "zdotc": "__pyx_t_double_complex (int *, __pyx_t_double_complex *, int *, __pyx_t_double_complex *, int *)",
+    "zdotu": "__pyx_t_double_complex (int *, __pyx_t_double_complex *, int *, __pyx_t_double_complex *, int *)",
+    "zdrot": "void (int *, __pyx_t_double_complex *, int *, __pyx_t_double_complex *, int *, __pyx_t_5scipy_6linalg_11cython_blas_d *, __pyx_t_5scipy_6linalg_11cython_blas_d *)",
+    "zdscal": "void (int *, __pyx_t_5scipy_6linalg_11cython_blas_d *, __pyx_t_double_complex *, int *)",
+    "zgbmv": "void (char *, int *, int *, int *, int *, __pyx_t_double_complex *, __pyx_t_double_complex *, int *, __pyx_t_double_complex *, int *, __pyx_t_double_complex *, __pyx_t_double_complex *, int *)",
+    "zgemm": "void (char *, char *, int *, int *, int *, __pyx_t_double_complex *, __pyx_t_double_complex *, int *, __pyx_t_double_complex *, int *, __pyx_t_double_complex *, __pyx_t_double_complex *, int *)",
+    "zgemv": "void (char *, int *, int *, __pyx_t_double_complex *, __pyx_t_double_complex *, int *, __pyx_t_double_complex *, int *, __pyx_t_double_complex *, __pyx_t_double_complex *, int *)",
+    "zgerc": "void (int *, int *, __pyx_t_double_complex *, __pyx_t_double_complex *, int *, __pyx_t_double_complex *, int *, __pyx_t_double_complex *, int *)",
+    "zgeru": "void (int *, int *, __pyx_t_double_complex *, __pyx_t_double_complex *, int *, __pyx_t_double_complex *, int *, __pyx_t_double_complex *, int *)",
+    "zhbmv": "void (char *, int *, int *, __pyx_t_double_complex *, __pyx_t_double_complex *, int *, __pyx_t_double_complex *, int *, __pyx_t_double_complex *, __pyx_t_double_complex *, int *)",
+    "zhemm": "void (char *, char *, int *, int *, __pyx_t_double_complex *, __pyx_t_double_complex *, int *, __pyx_t_double_complex *, int *, __pyx_t_double_complex *, __pyx_t_double_complex *, int *)",
+    "zhemv": "void (char *, int *, __pyx_t_double_complex *, __pyx_t_double_complex *, int *, __pyx_t_double_complex *, int *, __pyx_t_double_complex *, __pyx_t_double_complex *, int *)",
+    "zher": "void (char *, int *, __pyx_t_5scipy_6linalg_11cython_blas_d *, __pyx_t_double_complex *, int *, __pyx_t_double_complex *, int *)",
+    "zher2": "void (char *, int *, __pyx_t_double_complex *, __pyx_t_double_complex *, int *, __pyx_t_double_complex *, int *, __pyx_t_double_complex *, int *)",
+    "zher2k": "void (char *, char *, int *, int *, __pyx_t_double_complex *, __pyx_t_double_complex *, int *, __pyx_t_double_complex *, int *, __pyx_t_5scipy_6linalg_11cython_blas_d *, __pyx_t_double_complex *, int *)",
+    "zherk": "void (char *, char *, int *, int *, __pyx_t_5scipy_6linalg_11cython_blas_d *, __pyx_t_double_complex *, int *, __pyx_t_5scipy_6linalg_11cython_blas_d *, __pyx_t_double_complex *, int *)",
+    "zhpmv": "void (char *, int *, __pyx_t_double_complex *, __pyx_t_double_complex *, __pyx_t_double_complex *, int *, __pyx_t_double_complex *, __pyx_t_double_complex *, int *)",
+    "zhpr": "void (char *, int *, __pyx_t_5scipy_6linalg_11cython_blas_d *, __pyx_t_double_complex *, int *, __pyx_t_double_complex *)",
+    "zhpr2": "void (char *, int *, __pyx_t_double_complex *, __pyx_t_double_complex *, int *, __pyx_t_double_complex *, int *, __pyx_t_double_complex *)",
+    "zrotg": "void (__pyx_t_double_complex *, __pyx_t_double_complex *, __pyx_t_5scipy_6linalg_11cython_blas_d *, __pyx_t_double_complex *)",
+    "zscal": "void (int *, __pyx_t_double_complex *, __pyx_t_double_complex *, int *)",
+    "zswap": "void (int *, __pyx_t_double_complex *, int *, __pyx_t_double_complex *, int *)",
+    "zsymm": "void (char *, char *, int *, int *, __pyx_t_double_complex *, __pyx_t_double_complex *, int *, __pyx_t_double_complex *, int *, __pyx_t_double_complex *, __pyx_t_double_complex *, int *)",
+    "zsyr2k": "void (char *, char *, int *, int *, __pyx_t_double_complex *, __pyx_t_double_complex *, int *, __pyx_t_double_complex *, int *, __pyx_t_double_complex *, __pyx_t_double_complex *, int *)",
+    "zsyrk": "void (char *, char *, int *, int *, __pyx_t_double_complex *, __pyx_t_double_complex *, int *, __pyx_t_double_complex *, __pyx_t_double_complex *, int *)",
+    "ztbmv": "void (char *, char *, char *, int *, int *, __pyx_t_double_complex *, int *, __pyx_t_double_complex *, int *)",
+    "ztbsv": "void (char *, char *, char *, int *, int *, __pyx_t_double_complex *, int *, __pyx_t_double_complex *, int *)",
+    "ztpmv": "void (char *, char *, char *, int *, __pyx_t_double_complex *, __pyx_t_double_complex *, int *)",
+    "ztpsv": "void (char *, char *, char *, int *, __pyx_t_double_complex *, __pyx_t_double_complex *, int *)",
+    "ztrmm": "void (char *, char *, char *, char *, int *, int *, __pyx_t_double_complex *, __pyx_t_double_complex *, int *, __pyx_t_double_complex *, int *)",
+    "ztrmv": "void (char *, char *, char *, int *, __pyx_t_double_complex *, int *, __pyx_t_double_complex *, int *)",
+    "ztrsm": "void (char *, char *, char *, char *, int *, int *, __pyx_t_double_complex *, __pyx_t_double_complex *, int *, __pyx_t_double_complex *, int *)",
+    "ztrsv": "void (char *, char *, char *, int *, __pyx_t_double_complex *, int *, __pyx_t_double_complex *, int *)"
+  },
+  "scipy.linalg.cython_lapack": {
+    "cbbcsd": "void (char *, char *, char *, char *, char *, int *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_float_complex *, int *, __pyx_t_float_complex *, int *, __pyx_t_float_complex *, int *, __pyx_t_float_complex *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, int *)",
+    "cbdsqr": "void (char *, int *, int *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_float_complex *, int *, __pyx_t_float_complex *, int *, __pyx_t_float_complex *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *)",
+    "cgbbrd": "void (char *, int *, int *, int *, int *, int *, __pyx_t_float_complex *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_float_complex *, int *, __pyx_t_float_complex *, int *, __pyx_t_float_complex *, int *, __pyx_t_float_complex *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *)",
+    "cgbcon": "void (char *, int *, int *, int *, __pyx_t_float_complex *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_float_complex *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *)",
+    "cgbequ": "void (int *, int *, int *, int *, __pyx_t_float_complex *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *)",
+    "cgbequb": "void (int *, int *, int *, int *, __pyx_t_float_complex *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *)",
+    "cgbrfs": "void (char *, int *, int *, int *, int *, __pyx_t_float_complex *, int *, __pyx_t_float_complex *, int *, int *, __pyx_t_float_complex *, int *, __pyx_t_float_complex *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_float_complex *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *)",
+    "cgbsv": "void (int *, int *, int *, int *, __pyx_t_float_complex *, int *, int *, __pyx_t_float_complex *, int *, int *)",
+    "cgbsvx": "void (char *, char *, int *, int *, int *, int *, __pyx_t_float_complex *, int *, __pyx_t_float_complex *, int *, int *, char *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_float_complex *, int *, __pyx_t_float_complex *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_float_complex *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *)",
+    "cgbtf2": "void (int *, int *, int *, int *, __pyx_t_float_complex *, int *, int *, int *)",
+    "cgbtrf": "void (int *, int *, int *, int *, __pyx_t_float_complex *, int *, int *, int *)",
+    "cgbtrs": "void (char *, int *, int *, int *, int *, __pyx_t_float_complex *, int *, int *, __pyx_t_float_complex *, int *, int *)",
+    "cgebak": "void (char *, char *, int *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_float_complex *, int *, int *)",
+    "cgebal": "void (char *, int *, __pyx_t_float_complex *, int *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *)",
+    "cgebd2": "void (int *, int *, __pyx_t_float_complex *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_float_complex *, __pyx_t_float_complex *, __pyx_t_float_complex *, int *)",
+    "cgebrd": "void (int *, int *, __pyx_t_float_complex *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_float_complex *, __pyx_t_float_complex *, __pyx_t_float_complex *, int *, int *)",
+    "cgecon": "void (char *, int *, __pyx_t_float_complex *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_float_complex *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *)",
+    "cgeequ": "void (int *, int *, __pyx_t_float_complex *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *)",
+    "cgeequb": "void (int *, int *, __pyx_t_float_complex *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *)",
+    "cgees": "void (char *, char *, __pyx_t_5scipy_6linalg_13cython_lapack_cselect1 *, int *, __pyx_t_float_complex *, int *, int *, __pyx_t_float_complex *, __pyx_t_float_complex *, int *, __pyx_t_float_complex *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, int *)",
+    "cgeesx": "void (char *, char *, __pyx_t_5scipy_6linalg_13cython_lapack_cselect1 *, char *, int *, __pyx_t_float_complex *, int *, int *, __pyx_t_float_complex *, __pyx_t_float_complex *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_float_complex *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, int *)",
+    "cgeev": "void (char *, char *, int *, __pyx_t_float_complex *, int *, __pyx_t_float_complex *, __pyx_t_float_complex *, int *, __pyx_t_float_complex *, int *, __pyx_t_float_complex *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *)",
+    "cgeevx": "void (char *, char *, char *, char *, int *, __pyx_t_float_complex *, int *, __pyx_t_float_complex *, __pyx_t_float_complex *, int *, __pyx_t_float_complex *, int *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_float_complex *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *)",
+    "cgehd2": "void (int *, int *, int *, __pyx_t_float_complex *, int *, __pyx_t_float_complex *, __pyx_t_float_complex *, int *)",
+    "cgehrd": "void (int *, int *, int *, __pyx_t_float_complex *, int *, __pyx_t_float_complex *, __pyx_t_float_complex *, int *, int *)",
+    "cgelq2": "void (int *, int *, __pyx_t_float_complex *, int *, __pyx_t_float_complex *, __pyx_t_float_complex *, int *)",
+    "cgelqf": "void (int *, int *, __pyx_t_float_complex *, int *, __pyx_t_float_complex *, __pyx_t_float_complex *, int *, int *)",
+    "cgels": "void (char *, int *, int *, int *, __pyx_t_float_complex *, int *, __pyx_t_float_complex *, int *, __pyx_t_float_complex *, int *, int *)",
+    "cgelsd": "void (int *, int *, int *, __pyx_t_float_complex *, int *, __pyx_t_float_complex *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_float_complex *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, int *)",
+    "cgelss": "void (int *, int *, int *, __pyx_t_float_complex *, int *, __pyx_t_float_complex *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_float_complex *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *)",
+    "cgelsy": "void (int *, int *, int *, __pyx_t_float_complex *, int *, __pyx_t_float_complex *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_float_complex *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *)",
+    "cgemqrt": "void (char *, char *, int *, int *, int *, int *, __pyx_t_float_complex *, int *, __pyx_t_float_complex *, int *, __pyx_t_float_complex *, int *, __pyx_t_float_complex *, int *)",
+    "cgeql2": "void (int *, int *, __pyx_t_float_complex *, int *, __pyx_t_float_complex *, __pyx_t_float_complex *, int *)",
+    "cgeqlf": "void (int *, int *, __pyx_t_float_complex *, int *, __pyx_t_float_complex *, __pyx_t_float_complex *, int *, int *)",
+    "cgeqp3": "void (int *, int *, __pyx_t_float_complex *, int *, int *, __pyx_t_float_complex *, __pyx_t_float_complex *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *)",
+    "cgeqr2": "void (int *, int *, __pyx_t_float_complex *, int *, __pyx_t_float_complex *, __pyx_t_float_complex *, int *)",
+    "cgeqr2p": "void (int *, int *, __pyx_t_float_complex *, int *, __pyx_t_float_complex *, __pyx_t_float_complex *, int *)",
+    "cgeqrf": "void (int *, int *, __pyx_t_float_complex *, int *, __pyx_t_float_complex *, __pyx_t_float_complex *, int *, int *)",
+    "cgeqrfp": "void (int *, int *, __pyx_t_float_complex *, int *, __pyx_t_float_complex *, __pyx_t_float_complex *, int *, int *)",
+    "cgeqrt": "void (int *, int *, int *, __pyx_t_float_complex *, int *, __pyx_t_float_complex *, int *, __pyx_t_float_complex *, int *)",
+    "cgeqrt2": "void (int *, int *, __pyx_t_float_complex *, int *, __pyx_t_float_complex *, int *, int *)",
+    "cgeqrt3": "void (int *, int *, __pyx_t_float_complex *, int *, __pyx_t_float_complex *, int *, int *)",
+    "cgerfs": "void (char *, int *, int *, __pyx_t_float_complex *, int *, __pyx_t_float_complex *, int *, int *, __pyx_t_float_complex *, int *, __pyx_t_float_complex *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_float_complex *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *)",
+    "cgerq2": "void (int *, int *, __pyx_t_float_complex *, int *, __pyx_t_float_complex *, __pyx_t_float_complex *, int *)",
+    "cgerqf": "void (int *, int *, __pyx_t_float_complex *, int *, __pyx_t_float_complex *, __pyx_t_float_complex *, int *, int *)",
+    "cgesc2": "void (int *, __pyx_t_float_complex *, int *, __pyx_t_float_complex *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *)",
+    "cgesdd": "void (char *, int *, int *, __pyx_t_float_complex *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_float_complex *, int *, __pyx_t_float_complex *, int *, __pyx_t_float_complex *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, int *)",
+    "cgesv": "void (int *, int *, __pyx_t_float_complex *, int *, int *, __pyx_t_float_complex *, int *, int *)",
+    "cgesvd": "void (char *, char *, int *, int *, __pyx_t_float_complex *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_float_complex *, int *, __pyx_t_float_complex *, int *, __pyx_t_float_complex *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *)",
+    "cgesvx": "void (char *, char *, int *, int *, __pyx_t_float_complex *, int *, __pyx_t_float_complex *, int *, int *, char *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_float_complex *, int *, __pyx_t_float_complex *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_float_complex *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *)",
+    "cgetc2": "void (int *, __pyx_t_float_complex *, int *, int *, int *, int *)",
+    "cgetf2": "void (int *, int *, __pyx_t_float_complex *, int *, int *, int *)",
+    "cgetrf": "void (int *, int *, __pyx_t_float_complex *, int *, int *, int *)",
+    "cgetri": "void (int *, __pyx_t_float_complex *, int *, int *, __pyx_t_float_complex *, int *, int *)",
+    "cgetrs": "void (char *, int *, int *, __pyx_t_float_complex *, int *, int *, __pyx_t_float_complex *, int *, int *)",
+    "cggbak": "void (char *, char *, int *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_float_complex *, int *, int *)",
+    "cggbal": "void (char *, int *, __pyx_t_float_complex *, int *, __pyx_t_float_complex *, int *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *)",
+    "cgges": "void (char *, char *, char *, __pyx_t_5scipy_6linalg_13cython_lapack_cselect2 *, int *, __pyx_t_float_complex *, int *, __pyx_t_float_complex *, int *, int *, __pyx_t_float_complex *, __pyx_t_float_complex *, __pyx_t_float_complex *, int *, __pyx_t_float_complex *, int *, __pyx_t_float_complex *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, int *)",
+    "cggesx": "void (char *, char *, char *, __pyx_t_5scipy_6linalg_13cython_lapack_cselect2 *, char *, int *, __pyx_t_float_complex *, int *, __pyx_t_float_complex *, int *, int *, __pyx_t_float_complex *, __pyx_t_float_complex *, __pyx_t_float_complex *, int *, __pyx_t_float_complex *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_float_complex *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, int *, int *, int *)",
+    "cggev": "void (char *, char *, int *, __pyx_t_float_complex *, int *, __pyx_t_float_complex *, int *, __pyx_t_float_complex *, __pyx_t_float_complex *, __pyx_t_float_complex *, int *, __pyx_t_float_complex *, int *, __pyx_t_float_complex *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *)",
+    "cggevx": "void (char *, char *, char *, char *, int *, __pyx_t_float_complex *, int *, __pyx_t_float_complex *, int *, __pyx_t_float_complex *, __pyx_t_float_complex *, __pyx_t_float_complex *, int *, __pyx_t_float_complex *, int *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_float_complex *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, int *, int *)",
+    "cggglm": "void (int *, int *, int *, __pyx_t_float_complex *, int *, __pyx_t_float_complex *, int *, __pyx_t_float_complex *, __pyx_t_float_complex *, __pyx_t_float_complex *, __pyx_t_float_complex *, int *, int *)",
+    "cgghrd": "void (char *, char *, int *, int *, int *, __pyx_t_float_complex *, int *, __pyx_t_float_complex *, int *, __pyx_t_float_complex *, int *, __pyx_t_float_complex *, int *, int *)",
+    "cgglse": "void (int *, int *, int *, __pyx_t_float_complex *, int *, __pyx_t_float_complex *, int *, __pyx_t_float_complex *, __pyx_t_float_complex *, __pyx_t_float_complex *, __pyx_t_float_complex *, int *, int *)",
+    "cggqrf": "void (int *, int *, int *, __pyx_t_float_complex *, int *, __pyx_t_float_complex *, __pyx_t_float_complex *, int *, __pyx_t_float_complex *, __pyx_t_float_complex *, int *, int *)",
+    "cggrqf": "void (int *, int *, int *, __pyx_t_float_complex *, int *, __pyx_t_float_complex *, __pyx_t_float_complex *, int *, __pyx_t_float_complex *, __pyx_t_float_complex *, int *, int *)",
+    "cgtcon": "void (char *, int *, __pyx_t_float_complex *, __pyx_t_float_complex *, __pyx_t_float_complex *, __pyx_t_float_complex *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_float_complex *, int *)",
+    "cgtrfs": "void (char *, int *, int *, __pyx_t_float_complex *, __pyx_t_float_complex *, __pyx_t_float_complex *, __pyx_t_float_complex *, __pyx_t_float_complex *, __pyx_t_float_complex *, __pyx_t_float_complex *, int *, __pyx_t_float_complex *, int *, __pyx_t_float_complex *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_float_complex *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *)",
+    "cgtsv": "void (int *, int *, __pyx_t_float_complex *, __pyx_t_float_complex *, __pyx_t_float_complex *, __pyx_t_float_complex *, int *, int *)",
+    "cgtsvx": "void (char *, char *, int *, int *, __pyx_t_float_complex *, __pyx_t_float_complex *, __pyx_t_float_complex *, __pyx_t_float_complex *, __pyx_t_float_complex *, __pyx_t_float_complex *, __pyx_t_float_complex *, int *, __pyx_t_float_complex *, int *, __pyx_t_float_complex *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_float_complex *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *)",
+    "cgttrf": "void (int *, __pyx_t_float_complex *, __pyx_t_float_complex *, __pyx_t_float_complex *, __pyx_t_float_complex *, int *, int *)",
+    "cgttrs": "void (char *, int *, int *, __pyx_t_float_complex *, __pyx_t_float_complex *, __pyx_t_float_complex *, __pyx_t_float_complex *, int *, __pyx_t_float_complex *, int *, int *)",
+    "cgtts2": "void (int *, int *, int *, __pyx_t_float_complex *, __pyx_t_float_complex *, __pyx_t_float_complex *, __pyx_t_float_complex *, int *, __pyx_t_float_complex *, int *)",
+    "chbev": "void (char *, char *, int *, int *, __pyx_t_float_complex *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_float_complex *, int *, __pyx_t_float_complex *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *)",
+    "chbevd": "void (char *, char *, int *, int *, __pyx_t_float_complex *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_float_complex *, int *, __pyx_t_float_complex *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, int *, int *, int *)",
+    "chbevx": "void (char *, char *, char *, int *, int *, __pyx_t_float_complex *, int *, __pyx_t_float_complex *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_float_complex *, int *, __pyx_t_float_complex *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, int *, int *)",
+    "chbgst": "void (char *, char *, int *, int *, int *, __pyx_t_float_complex *, int *, __pyx_t_float_complex *, int *, __pyx_t_float_complex *, int *, __pyx_t_float_complex *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *)",
+    "chbgv": "void (char *, char *, int *, int *, int *, __pyx_t_float_complex *, int *, __pyx_t_float_complex *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_float_complex *, int *, __pyx_t_float_complex *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *)",
+    "chbgvd": "void (char *, char *, int *, int *, int *, __pyx_t_float_complex *, int *, __pyx_t_float_complex *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_float_complex *, int *, __pyx_t_float_complex *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, int *, int *, int *)",
+    "chbgvx": "void (char *, char *, char *, int *, int *, int *, __pyx_t_float_complex *, int *, __pyx_t_float_complex *, int *, __pyx_t_float_complex *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_float_complex *, int *, __pyx_t_float_complex *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, int *, int *)",
+    "chbtrd": "void (char *, char *, int *, int *, __pyx_t_float_complex *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_float_complex *, int *, __pyx_t_float_complex *, int *)",
+    "checon": "void (char *, int *, __pyx_t_float_complex *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_float_complex *, int *)",
+    "cheequb": "void (char *, int *, __pyx_t_float_complex *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_float_complex *, int *)",
+    "cheev": "void (char *, char *, int *, __pyx_t_float_complex *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_float_complex *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *)",
+    "cheevd": "void (char *, char *, int *, __pyx_t_float_complex *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_float_complex *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, int *, int *, int *)",
+    "cheevr": "void (char *, char *, char *, int *, __pyx_t_float_complex *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_float_complex *, int *, int *, __pyx_t_float_complex *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, int *, int *, int *)",
+    "cheevx": "void (char *, char *, char *, int *, __pyx_t_float_complex *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_float_complex *, int *, __pyx_t_float_complex *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, int *, int *)",
+    "chegs2": "void (int *, char *, int *, __pyx_t_float_complex *, int *, __pyx_t_float_complex *, int *, int *)",
+    "chegst": "void (int *, char *, int *, __pyx_t_float_complex *, int *, __pyx_t_float_complex *, int *, int *)",
+    "chegv": "void (int *, char *, char *, int *, __pyx_t_float_complex *, int *, __pyx_t_float_complex *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_float_complex *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *)",
+    "chegvd": "void (int *, char *, char *, int *, __pyx_t_float_complex *, int *, __pyx_t_float_complex *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_float_complex *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, int *, int *, int *)",
+    "chegvx": "void (int *, char *, char *, char *, int *, __pyx_t_float_complex *, int *, __pyx_t_float_complex *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_float_complex *, int *, __pyx_t_float_complex *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, int *, int *)",
+    "cherfs": "void (char *, int *, int *, __pyx_t_float_complex *, int *, __pyx_t_float_complex *, int *, int *, __pyx_t_float_complex *, int *, __pyx_t_float_complex *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_float_complex *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *)",
+    "chesv": "void (char *, int *, int *, __pyx_t_float_complex *, int *, int *, __pyx_t_float_complex *, int *, __pyx_t_float_complex *, int *, int *)",
+    "chesvx": "void (char *, char *, int *, int *, __pyx_t_float_complex *, int *, __pyx_t_float_complex *, int *, int *, __pyx_t_float_complex *, int *, __pyx_t_float_complex *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_float_complex *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *)",
+    "cheswapr": "void (char *, int *, __pyx_t_float_complex *, int *, int *, int *)",
+    "chetd2": "void (char *, int *, __pyx_t_float_complex *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_float_complex *, int *)",
+    "chetf2": "void (char *, int *, __pyx_t_float_complex *, int *, int *, int *)",
+    "chetrd": "void (char *, int *, __pyx_t_float_complex *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_float_complex *, __pyx_t_float_complex *, int *, int *)",
+    "chetrf": "void (char *, int *, __pyx_t_float_complex *, int *, int *, __pyx_t_float_complex *, int *, int *)",
+    "chetri": "void (char *, int *, __pyx_t_float_complex *, int *, int *, __pyx_t_float_complex *, int *)",
+    "chetri2": "void (char *, int *, __pyx_t_float_complex *, int *, int *, __pyx_t_float_complex *, int *, int *)",
+    "chetri2x": "void (char *, int *, __pyx_t_float_complex *, int *, int *, __pyx_t_float_complex *, int *, int *)",
+    "chetrs": "void (char *, int *, int *, __pyx_t_float_complex *, int *, int *, __pyx_t_float_complex *, int *, int *)",
+    "chetrs2": "void (char *, int *, int *, __pyx_t_float_complex *, int *, int *, __pyx_t_float_complex *, int *, __pyx_t_float_complex *, int *)",
+    "chfrk": "void (char *, char *, char *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_float_complex *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_float_complex *)",
+    "chgeqz": "void (char *, char *, char *, int *, int *, int *, __pyx_t_float_complex *, int *, __pyx_t_float_complex *, int *, __pyx_t_float_complex *, __pyx_t_float_complex *, __pyx_t_float_complex *, int *, __pyx_t_float_complex *, int *, __pyx_t_float_complex *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *)",
+    "chla_transtype": "char (int *)",
+    "chpcon": "void (char *, int *, __pyx_t_float_complex *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_float_complex *, int *)",
+    "chpev": "void (char *, char *, int *, __pyx_t_float_complex *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_float_complex *, int *, __pyx_t_float_complex *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *)",
+    "chpevd": "void (char *, char *, int *, __pyx_t_float_complex *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_float_complex *, int *, __pyx_t_float_complex *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, int *, int *, int *)",
+    "chpevx": "void (char *, char *, char *, int *, __pyx_t_float_complex *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_float_complex *, int *, __pyx_t_float_complex *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, int *, int *)",
+    "chpgst": "void (int *, char *, int *, __pyx_t_float_complex *, __pyx_t_float_complex *, int *)",
+    "chpgv": "void (int *, char *, char *, int *, __pyx_t_float_complex *, __pyx_t_float_complex *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_float_complex *, int *, __pyx_t_float_complex *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *)",
+    "chpgvd": "void (int *, char *, char *, int *, __pyx_t_float_complex *, __pyx_t_float_complex *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_float_complex *, int *, __pyx_t_float_complex *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, int *, int *, int *)",
+    "chpgvx": "void (int *, char *, char *, char *, int *, __pyx_t_float_complex *, __pyx_t_float_complex *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_float_complex *, int *, __pyx_t_float_complex *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, int *, int *)",
+    "chprfs": "void (char *, int *, int *, __pyx_t_float_complex *, __pyx_t_float_complex *, int *, __pyx_t_float_complex *, int *, __pyx_t_float_complex *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_float_complex *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *)",
+    "chpsv": "void (char *, int *, int *, __pyx_t_float_complex *, int *, __pyx_t_float_complex *, int *, int *)",
+    "chpsvx": "void (char *, char *, int *, int *, __pyx_t_float_complex *, __pyx_t_float_complex *, int *, __pyx_t_float_complex *, int *, __pyx_t_float_complex *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_float_complex *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *)",
+    "chptrd": "void (char *, int *, __pyx_t_float_complex *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_float_complex *, int *)",
+    "chptrf": "void (char *, int *, __pyx_t_float_complex *, int *, int *)",
+    "chptri": "void (char *, int *, __pyx_t_float_complex *, int *, __pyx_t_float_complex *, int *)",
+    "chptrs": "void (char *, int *, int *, __pyx_t_float_complex *, int *, __pyx_t_float_complex *, int *, int *)",
+    "chsein": "void (char *, char *, char *, int *, int *, __pyx_t_float_complex *, int *, __pyx_t_float_complex *, __pyx_t_float_complex *, int *, __pyx_t_float_complex *, int *, int *, int *, __pyx_t_float_complex *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, int *, int *)",
+    "chseqr": "void (char *, char *, int *, int *, int *, __pyx_t_float_complex *, int *, __pyx_t_float_complex *, __pyx_t_float_complex *, int *, __pyx_t_float_complex *, int *, int *)",
+    "clabrd": "void (int *, int *, int *, __pyx_t_float_complex *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_float_complex *, __pyx_t_float_complex *, __pyx_t_float_complex *, int *, __pyx_t_float_complex *, int *)",
+    "clacgv": "void (int *, __pyx_t_float_complex *, int *)",
+    "clacn2": "void (int *, __pyx_t_float_complex *, __pyx_t_float_complex *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, int *)",
+    "clacon": "void (int *, __pyx_t_float_complex *, __pyx_t_float_complex *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *)",
+    "clacp2": "void (char *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_float_complex *, int *)",
+    "clacpy": "void (char *, int *, int *, __pyx_t_float_complex *, int *, __pyx_t_float_complex *, int *)",
+    "clacrm": "void (int *, int *, __pyx_t_float_complex *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_float_complex *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *)",
+    "clacrt": "void (int *, __pyx_t_float_complex *, int *, __pyx_t_float_complex *, int *, __pyx_t_float_complex *, __pyx_t_float_complex *)",
+    "cladiv": "__pyx_t_float_complex (__pyx_t_float_complex *, __pyx_t_float_complex *)",
+    "claed0": "void (int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_float_complex *, int *, __pyx_t_float_complex *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, int *)",
+    "claed7": "void (int *, int *, int *, int *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_float_complex *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, int *, int *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_float_complex *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, int *)",
+    "claed8": "void (int *, int *, int *, __pyx_t_float_complex *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_float_complex *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, int *, int *, int *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *)",
+    "claein": "void (int *, int *, int *, __pyx_t_float_complex *, int *, __pyx_t_float_complex *, __pyx_t_float_complex *, __pyx_t_float_complex *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *)",
+    "claesy": "void (__pyx_t_float_complex *, __pyx_t_float_complex *, __pyx_t_float_complex *, __pyx_t_float_complex *, __pyx_t_float_complex *, __pyx_t_float_complex *, __pyx_t_float_complex *, __pyx_t_float_complex *)",
+    "claev2": "void (__pyx_t_float_complex *, __pyx_t_float_complex *, __pyx_t_float_complex *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_float_complex *)",
+    "clag2z": "void (int *, int *, __pyx_t_float_complex *, int *, __pyx_t_double_complex *, int *, int *)",
+    "clags2": "void (int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_float_complex *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_float_complex *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_float_complex *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_float_complex *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_float_complex *)",
+    "clagtm": "void (char *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_float_complex *, __pyx_t_float_complex *, __pyx_t_float_complex *, __pyx_t_float_complex *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_float_complex *, int *)",
+    "clahef": "void (char *, int *, int *, int *, __pyx_t_float_complex *, int *, int *, __pyx_t_float_complex *, int *, int *)",
+    "clahqr": "void (int *, int *, int *, int *, int *, __pyx_t_float_complex *, int *, __pyx_t_float_complex *, int *, int *, __pyx_t_float_complex *, int *, int *)",
+    "clahr2": "void (int *, int *, int *, __pyx_t_float_complex *, int *, __pyx_t_float_complex *, __pyx_t_float_complex *, int *, __pyx_t_float_complex *, int *)",
+    "claic1": "void (int *, int *, __pyx_t_float_complex *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_float_complex *, __pyx_t_float_complex *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_float_complex *, __pyx_t_float_complex *)",
+    "clals0": "void (int *, int *, int *, int *, int *, __pyx_t_float_complex *, int *, __pyx_t_float_complex *, int *, int *, int *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *)",
+    "clalsa": "void (int *, int *, int *, int *, __pyx_t_float_complex *, int *, __pyx_t_float_complex *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, int *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, int *)",
+    "clalsd": "void (char *, int *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_float_complex *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_float_complex *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, int *)",
+    "clangb": "__pyx_t_5scipy_6linalg_13cython_lapack_s (char *, int *, int *, int *, __pyx_t_float_complex *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *)",
+    "clange": "__pyx_t_5scipy_6linalg_13cython_lapack_s (char *, int *, int *, __pyx_t_float_complex *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *)",
+    "clangt": "__pyx_t_5scipy_6linalg_13cython_lapack_s (char *, int *, __pyx_t_float_complex *, __pyx_t_float_complex *, __pyx_t_float_complex *)",
+    "clanhb": "__pyx_t_5scipy_6linalg_13cython_lapack_s (char *, char *, int *, int *, __pyx_t_float_complex *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *)",
+    "clanhe": "__pyx_t_5scipy_6linalg_13cython_lapack_s (char *, char *, int *, __pyx_t_float_complex *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *)",
+    "clanhf": "__pyx_t_5scipy_6linalg_13cython_lapack_s (char *, char *, char *, int *, __pyx_t_float_complex *, __pyx_t_5scipy_6linalg_13cython_lapack_s *)",
+    "clanhp": "__pyx_t_5scipy_6linalg_13cython_lapack_s (char *, char *, int *, __pyx_t_float_complex *, __pyx_t_5scipy_6linalg_13cython_lapack_s *)",
+    "clanhs": "__pyx_t_5scipy_6linalg_13cython_lapack_s (char *, int *, __pyx_t_float_complex *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *)",
+    "clanht": "__pyx_t_5scipy_6linalg_13cython_lapack_s (char *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_float_complex *)",
+    "clansb": "__pyx_t_5scipy_6linalg_13cython_lapack_s (char *, char *, int *, int *, __pyx_t_float_complex *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *)",
+    "clansp": "__pyx_t_5scipy_6linalg_13cython_lapack_s (char *, char *, int *, __pyx_t_float_complex *, __pyx_t_5scipy_6linalg_13cython_lapack_s *)",
+    "clansy": "__pyx_t_5scipy_6linalg_13cython_lapack_s (char *, char *, int *, __pyx_t_float_complex *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *)",
+    "clantb": "__pyx_t_5scipy_6linalg_13cython_lapack_s (char *, char *, char *, int *, int *, __pyx_t_float_complex *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *)",
+    "clantp": "__pyx_t_5scipy_6linalg_13cython_lapack_s (char *, char *, char *, int *, __pyx_t_float_complex *, __pyx_t_5scipy_6linalg_13cython_lapack_s *)",
+    "clantr": "__pyx_t_5scipy_6linalg_13cython_lapack_s (char *, char *, char *, int *, int *, __pyx_t_float_complex *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *)",
+    "clapll": "void (int *, __pyx_t_float_complex *, int *, __pyx_t_float_complex *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *)",
+    "clapmr": "void (int *, int *, int *, __pyx_t_float_complex *, int *, int *)",
+    "clapmt": "void (int *, int *, int *, __pyx_t_float_complex *, int *, int *)",
+    "claqgb": "void (int *, int *, int *, int *, __pyx_t_float_complex *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, char *)",
+    "claqge": "void (int *, int *, __pyx_t_float_complex *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, char *)",
+    "claqhb": "void (char *, int *, int *, __pyx_t_float_complex *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, char *)",
+    "claqhe": "void (char *, int *, __pyx_t_float_complex *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, char *)",
+    "claqhp": "void (char *, int *, __pyx_t_float_complex *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, char *)",
+    "claqp2": "void (int *, int *, int *, __pyx_t_float_complex *, int *, int *, __pyx_t_float_complex *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_float_complex *)",
+    "claqps": "void (int *, int *, int *, int *, int *, __pyx_t_float_complex *, int *, int *, __pyx_t_float_complex *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_float_complex *, __pyx_t_float_complex *, int *)",
+    "claqr0": "void (int *, int *, int *, int *, int *, __pyx_t_float_complex *, int *, __pyx_t_float_complex *, int *, int *, __pyx_t_float_complex *, int *, __pyx_t_float_complex *, int *, int *)",
+    "claqr1": "void (int *, __pyx_t_float_complex *, int *, __pyx_t_float_complex *, __pyx_t_float_complex *, __pyx_t_float_complex *)",
+    "claqr2": "void (int *, int *, int *, int *, int *, int *, __pyx_t_float_complex *, int *, int *, int *, __pyx_t_float_complex *, int *, int *, int *, __pyx_t_float_complex *, __pyx_t_float_complex *, int *, int *, __pyx_t_float_complex *, int *, int *, __pyx_t_float_complex *, int *, __pyx_t_float_complex *, int *)",
+    "claqr3": "void (int *, int *, int *, int *, int *, int *, __pyx_t_float_complex *, int *, int *, int *, __pyx_t_float_complex *, int *, int *, int *, __pyx_t_float_complex *, __pyx_t_float_complex *, int *, int *, __pyx_t_float_complex *, int *, int *, __pyx_t_float_complex *, int *, __pyx_t_float_complex *, int *)",
+    "claqr4": "void (int *, int *, int *, int *, int *, __pyx_t_float_complex *, int *, __pyx_t_float_complex *, int *, int *, __pyx_t_float_complex *, int *, __pyx_t_float_complex *, int *, int *)",
+    "claqr5": "void (int *, int *, int *, int *, int *, int *, int *, __pyx_t_float_complex *, __pyx_t_float_complex *, int *, int *, int *, __pyx_t_float_complex *, int *, __pyx_t_float_complex *, int *, __pyx_t_float_complex *, int *, int *, __pyx_t_float_complex *, int *, int *, __pyx_t_float_complex *, int *)",
+    "claqsb": "void (char *, int *, int *, __pyx_t_float_complex *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, char *)",
+    "claqsp": "void (char *, int *, __pyx_t_float_complex *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, char *)",
+    "claqsy": "void (char *, int *, __pyx_t_float_complex *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, char *)",
+    "clar1v": "void (int *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_float_complex *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *)",
+    "clar2v": "void (int *, __pyx_t_float_complex *, __pyx_t_float_complex *, __pyx_t_float_complex *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_float_complex *, int *)",
+    "clarcm": "void (int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_float_complex *, int *, __pyx_t_float_complex *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *)",
+    "clarf": "void (char *, int *, int *, __pyx_t_float_complex *, int *, __pyx_t_float_complex *, __pyx_t_float_complex *, int *, __pyx_t_float_complex *)",
+    "clarfb": "void (char *, char *, char *, char *, int *, int *, int *, __pyx_t_float_complex *, int *, __pyx_t_float_complex *, int *, __pyx_t_float_complex *, int *, __pyx_t_float_complex *, int *)",
+    "clarfg": "void (int *, __pyx_t_float_complex *, __pyx_t_float_complex *, int *, __pyx_t_float_complex *)",
+    "clarfgp": "void (int *, __pyx_t_float_complex *, __pyx_t_float_complex *, int *, __pyx_t_float_complex *)",
+    "clarft": "void (char *, char *, int *, int *, __pyx_t_float_complex *, int *, __pyx_t_float_complex *, __pyx_t_float_complex *, int *)",
+    "clarfx": "void (char *, int *, int *, __pyx_t_float_complex *, __pyx_t_float_complex *, __pyx_t_float_complex *, int *, __pyx_t_float_complex *)",
+    "clargv": "void (int *, __pyx_t_float_complex *, int *, __pyx_t_float_complex *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *)",
+    "clarnv": "void (int *, int *, int *, __pyx_t_float_complex *)",
+    "clarrv": "void (int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, int *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_float_complex *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, int *)",
+    "clartg": "void (__pyx_t_float_complex *, __pyx_t_float_complex *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_float_complex *, __pyx_t_float_complex *)",
+    "clartv": "void (int *, __pyx_t_float_complex *, int *, __pyx_t_float_complex *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_float_complex *, int *)",
+    "clarz": "void (char *, int *, int *, int *, __pyx_t_float_complex *, int *, __pyx_t_float_complex *, __pyx_t_float_complex *, int *, __pyx_t_float_complex *)",
+    "clarzb": "void (char *, char *, char *, char *, int *, int *, int *, int *, __pyx_t_float_complex *, int *, __pyx_t_float_complex *, int *, __pyx_t_float_complex *, int *, __pyx_t_float_complex *, int *)",
+    "clarzt": "void (char *, char *, int *, int *, __pyx_t_float_complex *, int *, __pyx_t_float_complex *, __pyx_t_float_complex *, int *)",
+    "clascl": "void (char *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, int *, __pyx_t_float_complex *, int *, int *)",
+    "claset": "void (char *, int *, int *, __pyx_t_float_complex *, __pyx_t_float_complex *, __pyx_t_float_complex *, int *)",
+    "clasr": "void (char *, char *, char *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_float_complex *, int *)",
+    "classq": "void (int *, __pyx_t_float_complex *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *)",
+    "claswp": "void (int *, __pyx_t_float_complex *, int *, int *, int *, int *, int *)",
+    "clasyf": "void (char *, int *, int *, int *, __pyx_t_float_complex *, int *, int *, __pyx_t_float_complex *, int *, int *)",
+    "clatbs": "void (char *, char *, char *, char *, int *, int *, __pyx_t_float_complex *, int *, __pyx_t_float_complex *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *)",
+    "clatdf": "void (int *, int *, __pyx_t_float_complex *, int *, __pyx_t_float_complex *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, int *)",
+    "clatps": "void (char *, char *, char *, char *, int *, __pyx_t_float_complex *, __pyx_t_float_complex *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *)",
+    "clatrd": "void (char *, int *, int *, __pyx_t_float_complex *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_float_complex *, __pyx_t_float_complex *, int *)",
+    "clatrs": "void (char *, char *, char *, char *, int *, __pyx_t_float_complex *, int *, __pyx_t_float_complex *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *)",
+    "clatrz": "void (int *, int *, int *, __pyx_t_float_complex *, int *, __pyx_t_float_complex *, __pyx_t_float_complex *)",
+    "clauu2": "void (char *, int *, __pyx_t_float_complex *, int *, int *)",
+    "clauum": "void (char *, int *, __pyx_t_float_complex *, int *, int *)",
+    "cpbcon": "void (char *, int *, int *, __pyx_t_float_complex *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_float_complex *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *)",
+    "cpbequ": "void (char *, int *, int *, __pyx_t_float_complex *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *)",
+    "cpbrfs": "void (char *, int *, int *, int *, __pyx_t_float_complex *, int *, __pyx_t_float_complex *, int *, __pyx_t_float_complex *, int *, __pyx_t_float_complex *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_float_complex *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *)",
+    "cpbstf": "void (char *, int *, int *, __pyx_t_float_complex *, int *, int *)",
+    "cpbsv": "void (char *, int *, int *, int *, __pyx_t_float_complex *, int *, __pyx_t_float_complex *, int *, int *)",
+    "cpbsvx": "void (char *, char *, int *, int *, int *, __pyx_t_float_complex *, int *, __pyx_t_float_complex *, int *, char *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_float_complex *, int *, __pyx_t_float_complex *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_float_complex *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *)",
+    "cpbtf2": "void (char *, int *, int *, __pyx_t_float_complex *, int *, int *)",
+    "cpbtrf": "void (char *, int *, int *, __pyx_t_float_complex *, int *, int *)",
+    "cpbtrs": "void (char *, int *, int *, int *, __pyx_t_float_complex *, int *, __pyx_t_float_complex *, int *, int *)",
+    "cpftrf": "void (char *, char *, int *, __pyx_t_float_complex *, int *)",
+    "cpftri": "void (char *, char *, int *, __pyx_t_float_complex *, int *)",
+    "cpftrs": "void (char *, char *, int *, int *, __pyx_t_float_complex *, __pyx_t_float_complex *, int *, int *)",
+    "cpocon": "void (char *, int *, __pyx_t_float_complex *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_float_complex *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *)",
+    "cpoequ": "void (int *, __pyx_t_float_complex *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *)",
+    "cpoequb": "void (int *, __pyx_t_float_complex *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *)",
+    "cporfs": "void (char *, int *, int *, __pyx_t_float_complex *, int *, __pyx_t_float_complex *, int *, __pyx_t_float_complex *, int *, __pyx_t_float_complex *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_float_complex *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *)",
+    "cposv": "void (char *, int *, int *, __pyx_t_float_complex *, int *, __pyx_t_float_complex *, int *, int *)",
+    "cposvx": "void (char *, char *, int *, int *, __pyx_t_float_complex *, int *, __pyx_t_float_complex *, int *, char *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_float_complex *, int *, __pyx_t_float_complex *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_float_complex *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *)",
+    "cpotf2": "void (char *, int *, __pyx_t_float_complex *, int *, int *)",
+    "cpotrf": "void (char *, int *, __pyx_t_float_complex *, int *, int *)",
+    "cpotri": "void (char *, int *, __pyx_t_float_complex *, int *, int *)",
+    "cpotrs": "void (char *, int *, int *, __pyx_t_float_complex *, int *, __pyx_t_float_complex *, int *, int *)",
+    "cppcon": "void (char *, int *, __pyx_t_float_complex *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_float_complex *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *)",
+    "cppequ": "void (char *, int *, __pyx_t_float_complex *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *)",
+    "cpprfs": "void (char *, int *, int *, __pyx_t_float_complex *, __pyx_t_float_complex *, __pyx_t_float_complex *, int *, __pyx_t_float_complex *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_float_complex *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *)",
+    "cppsv": "void (char *, int *, int *, __pyx_t_float_complex *, __pyx_t_float_complex *, int *, int *)",
+    "cppsvx": "void (char *, char *, int *, int *, __pyx_t_float_complex *, __pyx_t_float_complex *, char *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_float_complex *, int *, __pyx_t_float_complex *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_float_complex *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *)",
+    "cpptrf": "void (char *, int *, __pyx_t_float_complex *, int *)",
+    "cpptri": "void (char *, int *, __pyx_t_float_complex *, int *)",
+    "cpptrs": "void (char *, int *, int *, __pyx_t_float_complex *, __pyx_t_float_complex *, int *, int *)",
+    "cpstf2": "void (char *, int *, __pyx_t_float_complex *, int *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *)",
+    "cpstrf": "void (char *, int *, __pyx_t_float_complex *, int *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *)",
+    "cptcon": "void (int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_float_complex *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *)",
+    "cpteqr": "void (char *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_float_complex *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *)",
+    "cptrfs": "void (char *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_float_complex *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_float_complex *, __pyx_t_float_complex *, int *, __pyx_t_float_complex *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_float_complex *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *)",
+    "cptsv": "void (int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_float_complex *, __pyx_t_float_complex *, int *, int *)",
+    "cptsvx": "void (char *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_float_complex *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_float_complex *, __pyx_t_float_complex *, int *, __pyx_t_float_complex *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_float_complex *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *)",
+    "cpttrf": "void (int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_float_complex *, int *)",
+    "cpttrs": "void (char *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_float_complex *, __pyx_t_float_complex *, int *, int *)",
+    "cptts2": "void (int *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_float_complex *, __pyx_t_float_complex *, int *)",
+    "crot": "void (int *, __pyx_t_float_complex *, int *, __pyx_t_float_complex *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_float_complex *)",
+    "cspcon": "void (char *, int *, __pyx_t_float_complex *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_float_complex *, int *)",
+    "cspmv": "void (char *, int *, __pyx_t_float_complex *, __pyx_t_float_complex *, __pyx_t_float_complex *, int *, __pyx_t_float_complex *, __pyx_t_float_complex *, int *)",
+    "cspr": "void (char *, int *, __pyx_t_float_complex *, __pyx_t_float_complex *, int *, __pyx_t_float_complex *)",
+    "csprfs": "void (char *, int *, int *, __pyx_t_float_complex *, __pyx_t_float_complex *, int *, __pyx_t_float_complex *, int *, __pyx_t_float_complex *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_float_complex *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *)",
+    "cspsv": "void (char *, int *, int *, __pyx_t_float_complex *, int *, __pyx_t_float_complex *, int *, int *)",
+    "cspsvx": "void (char *, char *, int *, int *, __pyx_t_float_complex *, __pyx_t_float_complex *, int *, __pyx_t_float_complex *, int *, __pyx_t_float_complex *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_float_complex *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *)",
+    "csptrf": "void (char *, int *, __pyx_t_float_complex *, int *, int *)",
+    "csptri": "void (char *, int *, __pyx_t_float_complex *, int *, __pyx_t_float_complex *, int *)",
+    "csptrs": "void (char *, int *, int *, __pyx_t_float_complex *, int *, __pyx_t_float_complex *, int *, int *)",
+    "csrscl": "void (int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_float_complex *, int *)",
+    "cstedc": "void (char *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_float_complex *, int *, __pyx_t_float_complex *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, int *, int *, int *)",
+    "cstegr": "void (char *, char *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_float_complex *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, int *, int *, int *)",
+    "cstein": "void (int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, int *, __pyx_t_float_complex *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, int *, int *)",
+    "cstemr": "void (char *, char *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_float_complex *, int *, int *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, int *, int *, int *)",
+    "csteqr": "void (char *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_float_complex *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *)",
+    "csycon": "void (char *, int *, __pyx_t_float_complex *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_float_complex *, int *)",
+    "csyconv": "void (char *, char *, int *, __pyx_t_float_complex *, int *, int *, __pyx_t_float_complex *, int *)",
+    "csyequb": "void (char *, int *, __pyx_t_float_complex *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_float_complex *, int *)",
+    "csymv": "void (char *, int *, __pyx_t_float_complex *, __pyx_t_float_complex *, int *, __pyx_t_float_complex *, int *, __pyx_t_float_complex *, __pyx_t_float_complex *, int *)",
+    "csyr": "void (char *, int *, __pyx_t_float_complex *, __pyx_t_float_complex *, int *, __pyx_t_float_complex *, int *)",
+    "csyrfs": "void (char *, int *, int *, __pyx_t_float_complex *, int *, __pyx_t_float_complex *, int *, int *, __pyx_t_float_complex *, int *, __pyx_t_float_complex *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_float_complex *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *)",
+    "csysv": "void (char *, int *, int *, __pyx_t_float_complex *, int *, int *, __pyx_t_float_complex *, int *, __pyx_t_float_complex *, int *, int *)",
+    "csysvx": "void (char *, char *, int *, int *, __pyx_t_float_complex *, int *, __pyx_t_float_complex *, int *, int *, __pyx_t_float_complex *, int *, __pyx_t_float_complex *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_float_complex *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *)",
+    "csyswapr": "void (char *, int *, __pyx_t_float_complex *, int *, int *, int *)",
+    "csytf2": "void (char *, int *, __pyx_t_float_complex *, int *, int *, int *)",
+    "csytrf": "void (char *, int *, __pyx_t_float_complex *, int *, int *, __pyx_t_float_complex *, int *, int *)",
+    "csytri": "void (char *, int *, __pyx_t_float_complex *, int *, int *, __pyx_t_float_complex *, int *)",
+    "csytri2": "void (char *, int *, __pyx_t_float_complex *, int *, int *, __pyx_t_float_complex *, int *, int *)",
+    "csytri2x": "void (char *, int *, __pyx_t_float_complex *, int *, int *, __pyx_t_float_complex *, int *, int *)",
+    "csytrs": "void (char *, int *, int *, __pyx_t_float_complex *, int *, int *, __pyx_t_float_complex *, int *, int *)",
+    "csytrs2": "void (char *, int *, int *, __pyx_t_float_complex *, int *, int *, __pyx_t_float_complex *, int *, __pyx_t_float_complex *, int *)",
+    "ctbcon": "void (char *, char *, char *, int *, int *, __pyx_t_float_complex *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_float_complex *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *)",
+    "ctbrfs": "void (char *, char *, char *, int *, int *, int *, __pyx_t_float_complex *, int *, __pyx_t_float_complex *, int *, __pyx_t_float_complex *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_float_complex *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *)",
+    "ctbtrs": "void (char *, char *, char *, int *, int *, int *, __pyx_t_float_complex *, int *, __pyx_t_float_complex *, int *, int *)",
+    "ctfsm": "void (char *, char *, char *, char *, char *, int *, int *, __pyx_t_float_complex *, __pyx_t_float_complex *, __pyx_t_float_complex *, int *)",
+    "ctftri": "void (char *, char *, char *, int *, __pyx_t_float_complex *, int *)",
+    "ctfttp": "void (char *, char *, int *, __pyx_t_float_complex *, __pyx_t_float_complex *, int *)",
+    "ctfttr": "void (char *, char *, int *, __pyx_t_float_complex *, __pyx_t_float_complex *, int *, int *)",
+    "ctgevc": "void (char *, char *, int *, int *, __pyx_t_float_complex *, int *, __pyx_t_float_complex *, int *, __pyx_t_float_complex *, int *, __pyx_t_float_complex *, int *, int *, int *, __pyx_t_float_complex *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *)",
+    "ctgex2": "void (int *, int *, int *, __pyx_t_float_complex *, int *, __pyx_t_float_complex *, int *, __pyx_t_float_complex *, int *, __pyx_t_float_complex *, int *, int *, int *)",
+    "ctgexc": "void (int *, int *, int *, __pyx_t_float_complex *, int *, __pyx_t_float_complex *, int *, __pyx_t_float_complex *, int *, __pyx_t_float_complex *, int *, int *, int *, int *)",
+    "ctgsen": "void (int *, int *, int *, int *, int *, __pyx_t_float_complex *, int *, __pyx_t_float_complex *, int *, __pyx_t_float_complex *, __pyx_t_float_complex *, __pyx_t_float_complex *, int *, __pyx_t_float_complex *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_float_complex *, int *, int *, int *, int *)",
+    "ctgsja": "void (char *, char *, char *, int *, int *, int *, int *, int *, __pyx_t_float_complex *, int *, __pyx_t_float_complex *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_float_complex *, int *, __pyx_t_float_complex *, int *, __pyx_t_float_complex *, int *, __pyx_t_float_complex *, int *, int *)",
+    "ctgsna": "void (char *, char *, int *, int *, __pyx_t_float_complex *, int *, __pyx_t_float_complex *, int *, __pyx_t_float_complex *, int *, __pyx_t_float_complex *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, int *, __pyx_t_float_complex *, int *, int *, int *)",
+    "ctgsy2": "void (char *, int *, int *, int *, __pyx_t_float_complex *, int *, __pyx_t_float_complex *, int *, __pyx_t_float_complex *, int *, __pyx_t_float_complex *, int *, __pyx_t_float_complex *, int *, __pyx_t_float_complex *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *)",
+    "ctgsyl": "void (char *, int *, int *, int *, __pyx_t_float_complex *, int *, __pyx_t_float_complex *, int *, __pyx_t_float_complex *, int *, __pyx_t_float_complex *, int *, __pyx_t_float_complex *, int *, __pyx_t_float_complex *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_float_complex *, int *, int *, int *)",
+    "ctpcon": "void (char *, char *, char *, int *, __pyx_t_float_complex *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_float_complex *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *)",
+    "ctpmqrt": "void (char *, char *, int *, int *, int *, int *, int *, __pyx_t_float_complex *, int *, __pyx_t_float_complex *, int *, __pyx_t_float_complex *, int *, __pyx_t_float_complex *, int *, __pyx_t_float_complex *, int *)",
+    "ctpqrt": "void (int *, int *, int *, int *, __pyx_t_float_complex *, int *, __pyx_t_float_complex *, int *, __pyx_t_float_complex *, int *, __pyx_t_float_complex *, int *)",
+    "ctpqrt2": "void (int *, int *, int *, __pyx_t_float_complex *, int *, __pyx_t_float_complex *, int *, __pyx_t_float_complex *, int *, int *)",
+    "ctprfb": "void (char *, char *, char *, char *, int *, int *, int *, int *, __pyx_t_float_complex *, int *, __pyx_t_float_complex *, int *, __pyx_t_float_complex *, int *, __pyx_t_float_complex *, int *, __pyx_t_float_complex *, int *)",
+    "ctprfs": "void (char *, char *, char *, int *, int *, __pyx_t_float_complex *, __pyx_t_float_complex *, int *, __pyx_t_float_complex *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_float_complex *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *)",
+    "ctptri": "void (char *, char *, int *, __pyx_t_float_complex *, int *)",
+    "ctptrs": "void (char *, char *, char *, int *, int *, __pyx_t_float_complex *, __pyx_t_float_complex *, int *, int *)",
+    "ctpttf": "void (char *, char *, int *, __pyx_t_float_complex *, __pyx_t_float_complex *, int *)",
+    "ctpttr": "void (char *, int *, __pyx_t_float_complex *, __pyx_t_float_complex *, int *, int *)",
+    "ctrcon": "void (char *, char *, char *, int *, __pyx_t_float_complex *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_float_complex *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *)",
+    "ctrevc": "void (char *, char *, int *, int *, __pyx_t_float_complex *, int *, __pyx_t_float_complex *, int *, __pyx_t_float_complex *, int *, int *, int *, __pyx_t_float_complex *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *)",
+    "ctrexc": "void (char *, int *, __pyx_t_float_complex *, int *, __pyx_t_float_complex *, int *, int *, int *, int *)",
+    "ctrrfs": "void (char *, char *, char *, int *, int *, __pyx_t_float_complex *, int *, __pyx_t_float_complex *, int *, __pyx_t_float_complex *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_float_complex *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *)",
+    "ctrsen": "void (char *, char *, int *, int *, __pyx_t_float_complex *, int *, __pyx_t_float_complex *, int *, __pyx_t_float_complex *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_float_complex *, int *, int *)",
+    "ctrsna": "void (char *, char *, int *, int *, __pyx_t_float_complex *, int *, __pyx_t_float_complex *, int *, __pyx_t_float_complex *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, int *, __pyx_t_float_complex *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *)",
+    "ctrsyl": "void (char *, char *, int *, int *, int *, __pyx_t_float_complex *, int *, __pyx_t_float_complex *, int *, __pyx_t_float_complex *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *)",
+    "ctrti2": "void (char *, char *, int *, __pyx_t_float_complex *, int *, int *)",
+    "ctrtri": "void (char *, char *, int *, __pyx_t_float_complex *, int *, int *)",
+    "ctrtrs": "void (char *, char *, char *, int *, int *, __pyx_t_float_complex *, int *, __pyx_t_float_complex *, int *, int *)",
+    "ctrttf": "void (char *, char *, int *, __pyx_t_float_complex *, int *, __pyx_t_float_complex *, int *)",
+    "ctrttp": "void (char *, int *, __pyx_t_float_complex *, int *, __pyx_t_float_complex *, int *)",
+    "ctzrzf": "void (int *, int *, __pyx_t_float_complex *, int *, __pyx_t_float_complex *, __pyx_t_float_complex *, int *, int *)",
+    "cunbdb": "void (char *, char *, int *, int *, int *, __pyx_t_float_complex *, int *, __pyx_t_float_complex *, int *, __pyx_t_float_complex *, int *, __pyx_t_float_complex *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_float_complex *, __pyx_t_float_complex *, __pyx_t_float_complex *, __pyx_t_float_complex *, __pyx_t_float_complex *, int *, int *)",
+    "cuncsd": "void (char *, char *, char *, char *, char *, char *, int *, int *, int *, __pyx_t_float_complex *, int *, __pyx_t_float_complex *, int *, __pyx_t_float_complex *, int *, __pyx_t_float_complex *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_float_complex *, int *, __pyx_t_float_complex *, int *, __pyx_t_float_complex *, int *, __pyx_t_float_complex *, int *, __pyx_t_float_complex *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, int *, int *)",
+    "cung2l": "void (int *, int *, int *, __pyx_t_float_complex *, int *, __pyx_t_float_complex *, __pyx_t_float_complex *, int *)",
+    "cung2r": "void (int *, int *, int *, __pyx_t_float_complex *, int *, __pyx_t_float_complex *, __pyx_t_float_complex *, int *)",
+    "cungbr": "void (char *, int *, int *, int *, __pyx_t_float_complex *, int *, __pyx_t_float_complex *, __pyx_t_float_complex *, int *, int *)",
+    "cunghr": "void (int *, int *, int *, __pyx_t_float_complex *, int *, __pyx_t_float_complex *, __pyx_t_float_complex *, int *, int *)",
+    "cungl2": "void (int *, int *, int *, __pyx_t_float_complex *, int *, __pyx_t_float_complex *, __pyx_t_float_complex *, int *)",
+    "cunglq": "void (int *, int *, int *, __pyx_t_float_complex *, int *, __pyx_t_float_complex *, __pyx_t_float_complex *, int *, int *)",
+    "cungql": "void (int *, int *, int *, __pyx_t_float_complex *, int *, __pyx_t_float_complex *, __pyx_t_float_complex *, int *, int *)",
+    "cungqr": "void (int *, int *, int *, __pyx_t_float_complex *, int *, __pyx_t_float_complex *, __pyx_t_float_complex *, int *, int *)",
+    "cungr2": "void (int *, int *, int *, __pyx_t_float_complex *, int *, __pyx_t_float_complex *, __pyx_t_float_complex *, int *)",
+    "cungrq": "void (int *, int *, int *, __pyx_t_float_complex *, int *, __pyx_t_float_complex *, __pyx_t_float_complex *, int *, int *)",
+    "cungtr": "void (char *, int *, __pyx_t_float_complex *, int *, __pyx_t_float_complex *, __pyx_t_float_complex *, int *, int *)",
+    "cunm2l": "void (char *, char *, int *, int *, int *, __pyx_t_float_complex *, int *, __pyx_t_float_complex *, __pyx_t_float_complex *, int *, __pyx_t_float_complex *, int *)",
+    "cunm2r": "void (char *, char *, int *, int *, int *, __pyx_t_float_complex *, int *, __pyx_t_float_complex *, __pyx_t_float_complex *, int *, __pyx_t_float_complex *, int *)",
+    "cunmbr": "void (char *, char *, char *, int *, int *, int *, __pyx_t_float_complex *, int *, __pyx_t_float_complex *, __pyx_t_float_complex *, int *, __pyx_t_float_complex *, int *, int *)",
+    "cunmhr": "void (char *, char *, int *, int *, int *, int *, __pyx_t_float_complex *, int *, __pyx_t_float_complex *, __pyx_t_float_complex *, int *, __pyx_t_float_complex *, int *, int *)",
+    "cunml2": "void (char *, char *, int *, int *, int *, __pyx_t_float_complex *, int *, __pyx_t_float_complex *, __pyx_t_float_complex *, int *, __pyx_t_float_complex *, int *)",
+    "cunmlq": "void (char *, char *, int *, int *, int *, __pyx_t_float_complex *, int *, __pyx_t_float_complex *, __pyx_t_float_complex *, int *, __pyx_t_float_complex *, int *, int *)",
+    "cunmql": "void (char *, char *, int *, int *, int *, __pyx_t_float_complex *, int *, __pyx_t_float_complex *, __pyx_t_float_complex *, int *, __pyx_t_float_complex *, int *, int *)",
+    "cunmqr": "void (char *, char *, int *, int *, int *, __pyx_t_float_complex *, int *, __pyx_t_float_complex *, __pyx_t_float_complex *, int *, __pyx_t_float_complex *, int *, int *)",
+    "cunmr2": "void (char *, char *, int *, int *, int *, __pyx_t_float_complex *, int *, __pyx_t_float_complex *, __pyx_t_float_complex *, int *, __pyx_t_float_complex *, int *)",
+    "cunmr3": "void (char *, char *, int *, int *, int *, int *, __pyx_t_float_complex *, int *, __pyx_t_float_complex *, __pyx_t_float_complex *, int *, __pyx_t_float_complex *, int *)",
+    "cunmrq": "void (char *, char *, int *, int *, int *, __pyx_t_float_complex *, int *, __pyx_t_float_complex *, __pyx_t_float_complex *, int *, __pyx_t_float_complex *, int *, int *)",
+    "cunmrz": "void (char *, char *, int *, int *, int *, int *, __pyx_t_float_complex *, int *, __pyx_t_float_complex *, __pyx_t_float_complex *, int *, __pyx_t_float_complex *, int *, int *)",
+    "cunmtr": "void (char *, char *, char *, int *, int *, __pyx_t_float_complex *, int *, __pyx_t_float_complex *, __pyx_t_float_complex *, int *, __pyx_t_float_complex *, int *, int *)",
+    "cupgtr": "void (char *, int *, __pyx_t_float_complex *, __pyx_t_float_complex *, __pyx_t_float_complex *, int *, __pyx_t_float_complex *, int *)",
+    "cupmtr": "void (char *, char *, char *, int *, int *, __pyx_t_float_complex *, __pyx_t_float_complex *, __pyx_t_float_complex *, int *, __pyx_t_float_complex *, int *)",
+    "dbbcsd": "void (char *, char *, char *, char *, char *, int *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, int *)",
+    "dbdsdc": "void (char *, char *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, int *)",
+    "dbdsqr": "void (char *, int *, int *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *)",
+    "ddisna": "void (char *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *)",
+    "dgbbrd": "void (char *, int *, int *, int *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *)",
+    "dgbcon": "void (char *, int *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, int *)",
+    "dgbequ": "void (int *, int *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *)",
+    "dgbequb": "void (int *, int *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *)",
+    "dgbrfs": "void (char *, int *, int *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, int *)",
+    "dgbsv": "void (int *, int *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, int *)",
+    "dgbsvx": "void (char *, char *, int *, int *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, int *, char *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, int *)",
+    "dgbtf2": "void (int *, int *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, int *, int *)",
+    "dgbtrf": "void (int *, int *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, int *, int *)",
+    "dgbtrs": "void (char *, int *, int *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, int *)",
+    "dgebak": "void (char *, char *, int *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, int *)",
+    "dgebal": "void (char *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *)",
+    "dgebd2": "void (int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *)",
+    "dgebrd": "void (int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, int *)",
+    "dgecon": "void (char *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, int *)",
+    "dgeequ": "void (int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *)",
+    "dgeequb": "void (int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *)",
+    "dgees": "void (char *, char *, __pyx_t_5scipy_6linalg_13cython_lapack_dselect2 *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, int *, int *)",
+    "dgeesx": "void (char *, char *, __pyx_t_5scipy_6linalg_13cython_lapack_dselect2 *, char *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, int *, int *, int *, int *)",
+    "dgeev": "void (char *, char *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, int *)",
+    "dgeevx": "void (char *, char *, char *, char *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, int *, int *)",
+    "dgehd2": "void (int *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *)",
+    "dgehrd": "void (int *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, int *)",
+    "dgejsv": "void (char *, char *, char *, char *, char *, char *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, int *, int *)",
+    "dgelq2": "void (int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *)",
+    "dgelqf": "void (int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, int *)",
+    "dgels": "void (char *, int *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, int *)",
+    "dgelsd": "void (int *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, int *, int *)",
+    "dgelss": "void (int *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, int *)",
+    "dgelsy": "void (int *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, int *)",
+    "dgemqrt": "void (char *, char *, int *, int *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *)",
+    "dgeql2": "void (int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *)",
+    "dgeqlf": "void (int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, int *)",
+    "dgeqp3": "void (int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, int *)",
+    "dgeqr2": "void (int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *)",
+    "dgeqr2p": "void (int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *)",
+    "dgeqrf": "void (int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, int *)",
+    "dgeqrfp": "void (int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, int *)",
+    "dgeqrt": "void (int *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *)",
+    "dgeqrt2": "void (int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, int *)",
+    "dgeqrt3": "void (int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, int *)",
+    "dgerfs": "void (char *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, int *)",
+    "dgerq2": "void (int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *)",
+    "dgerqf": "void (int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, int *)",
+    "dgesc2": "void (int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *)",
+    "dgesdd": "void (char *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, int *, int *)",
+    "dgesv": "void (int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, int *)",
+    "dgesvd": "void (char *, char *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, int *)",
+    "dgesvj": "void (char *, char *, char *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, int *)",
+    "dgesvx": "void (char *, char *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, int *, char *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, int *)",
+    "dgetc2": "void (int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, int *, int *, int *)",
+    "dgetf2": "void (int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, int *, int *)",
+    "dgetrf": "void (int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, int *, int *)",
+    "dgetri": "void (int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, int *)",
+    "dgetrs": "void (char *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, int *)",
+    "dggbak": "void (char *, char *, int *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, int *)",
+    "dggbal": "void (char *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *)",
+    "dgges": "void (char *, char *, char *, __pyx_t_5scipy_6linalg_13cython_lapack_dselect3 *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, int *, int *)",
+    "dggesx": "void (char *, char *, char *, __pyx_t_5scipy_6linalg_13cython_lapack_dselect3 *, char *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, int *, int *, int *, int *)",
+    "dggev": "void (char *, char *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, int *)",
+    "dggevx": "void (char *, char *, char *, char *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, int *, int *, int *)",
+    "dggglm": "void (int *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, int *)",
+    "dgghrd": "void (char *, char *, int *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, int *)",
+    "dgglse": "void (int *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, int *)",
+    "dggqrf": "void (int *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, int *)",
+    "dggrqf": "void (int *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, int *)",
+    "dgsvj0": "void (char *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, int *)",
+    "dgsvj1": "void (char *, int *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, int *)",
+    "dgtcon": "void (char *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, int *)",
+    "dgtrfs": "void (char *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, int *)",
+    "dgtsv": "void (int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, int *)",
+    "dgtsvx": "void (char *, char *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, int *)",
+    "dgttrf": "void (int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, int *)",
+    "dgttrs": "void (char *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, int *)",
+    "dgtts2": "void (int *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *)",
+    "dhgeqz": "void (char *, char *, char *, int *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, int *)",
+    "dhsein": "void (char *, char *, char *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, int *, int *)",
+    "dhseqr": "void (char *, char *, int *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, int *)",
+    "disnan": "int (__pyx_t_5scipy_6linalg_13cython_lapack_d *)",
+    "dlabad": "void (__pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *)",
+    "dlabrd": "void (int *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *)",
+    "dlacn2": "void (int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, int *)",
+    "dlacon": "void (int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *)",
+    "dlacpy": "void (char *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *)",
+    "dladiv": "void (__pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *)",
+    "dlae2": "void (__pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *)",
+    "dlaebz": "void (int *, int *, int *, int *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, int *)",
+    "dlaed0": "void (int *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, int *)",
+    "dlaed1": "void (int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, int *)",
+    "dlaed2": "void (int *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, int *, int *, int *, int *)",
+    "dlaed3": "void (int *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *)",
+    "dlaed4": "void (int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *)",
+    "dlaed5": "void (int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *)",
+    "dlaed6": "void (int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *)",
+    "dlaed7": "void (int *, int *, int *, int *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, int *, int *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, int *)",
+    "dlaed8": "void (int *, int *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, int *, int *)",
+    "dlaed9": "void (int *, int *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, int *)",
+    "dlaeda": "void (int *, int *, int *, int *, int *, int *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *)",
+    "dlaein": "void (int *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *)",
+    "dlaev2": "void (__pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *)",
+    "dlaexc": "void (int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, int *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *)",
+    "dlag2": "void (__pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *)",
+    "dlag2s": "void (int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, int *)",
+    "dlags2": "void (int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *)",
+    "dlagtf": "void (int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, int *)",
+    "dlagtm": "void (char *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *)",
+    "dlagts": "void (int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *)",
+    "dlagv2": "void (__pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *)",
+    "dlahqr": "void (int *, int *, int *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, int *)",
+    "dlahr2": "void (int *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *)",
+    "dlaic1": "void (int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *)",
+    "dlaln2": "void (int *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *)",
+    "dlals0": "void (int *, int *, int *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, int *, int *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *)",
+    "dlalsa": "void (int *, int *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, int *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, int *)",
+    "dlalsd": "void (char *, int *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, int *)",
+    "dlamch": "__pyx_t_5scipy_6linalg_13cython_lapack_d (char *)",
+    "dlamrg": "void (int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, int *, int *)",
+    "dlaneg": "int (int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *)",
+    "dlangb": "__pyx_t_5scipy_6linalg_13cython_lapack_d (char *, int *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *)",
+    "dlange": "__pyx_t_5scipy_6linalg_13cython_lapack_d (char *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *)",
+    "dlangt": "__pyx_t_5scipy_6linalg_13cython_lapack_d (char *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *)",
+    "dlanhs": "__pyx_t_5scipy_6linalg_13cython_lapack_d (char *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *)",
+    "dlansb": "__pyx_t_5scipy_6linalg_13cython_lapack_d (char *, char *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *)",
+    "dlansf": "__pyx_t_5scipy_6linalg_13cython_lapack_d (char *, char *, char *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *)",
+    "dlansp": "__pyx_t_5scipy_6linalg_13cython_lapack_d (char *, char *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *)",
+    "dlanst": "__pyx_t_5scipy_6linalg_13cython_lapack_d (char *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *)",
+    "dlansy": "__pyx_t_5scipy_6linalg_13cython_lapack_d (char *, char *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *)",
+    "dlantb": "__pyx_t_5scipy_6linalg_13cython_lapack_d (char *, char *, char *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *)",
+    "dlantp": "__pyx_t_5scipy_6linalg_13cython_lapack_d (char *, char *, char *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *)",
+    "dlantr": "__pyx_t_5scipy_6linalg_13cython_lapack_d (char *, char *, char *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *)",
+    "dlanv2": "void (__pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *)",
+    "dlapll": "void (int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *)",
+    "dlapmr": "void (int *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, int *)",
+    "dlapmt": "void (int *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, int *)",
+    "dlapy2": "__pyx_t_5scipy_6linalg_13cython_lapack_d (__pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *)",
+    "dlapy3": "__pyx_t_5scipy_6linalg_13cython_lapack_d (__pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *)",
+    "dlaqgb": "void (int *, int *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, char *)",
+    "dlaqge": "void (int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, char *)",
+    "dlaqp2": "void (int *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *)",
+    "dlaqps": "void (int *, int *, int *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *)",
+    "dlaqr0": "void (int *, int *, int *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, int *)",
+    "dlaqr1": "void (int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *)",
+    "dlaqr2": "void (int *, int *, int *, int *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *)",
+    "dlaqr3": "void (int *, int *, int *, int *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *)",
+    "dlaqr4": "void (int *, int *, int *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, int *)",
+    "dlaqr5": "void (int *, int *, int *, int *, int *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *)",
+    "dlaqsb": "void (char *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, char *)",
+    "dlaqsp": "void (char *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, char *)",
+    "dlaqsy": "void (char *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, char *)",
+    "dlaqtr": "void (int *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *)",
+    "dlar1v": "void (int *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *)",
+    "dlar2v": "void (int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *)",
+    "dlarf": "void (char *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *)",
+    "dlarfb": "void (char *, char *, char *, char *, int *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *)",
+    "dlarfg": "void (int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *)",
+    "dlarfgp": "void (int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *)",
+    "dlarft": "void (char *, char *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *)",
+    "dlarfx": "void (char *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *)",
+    "dlargv": "void (int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *)",
+    "dlarnv": "void (int *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *)",
+    "dlarra": "void (int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, int *, int *)",
+    "dlarrb": "void (int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, int *)",
+    "dlarrc": "void (char *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, int *, int *, int *)",
+    "dlarrd": "void (char *, char *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, int *)",
+    "dlarre": "void (char *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, int *)",
+    "dlarrf": "void (int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *)",
+    "dlarrj": "void (int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *)",
+    "dlarrk": "void (int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *)",
+    "dlarrr": "void (int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *)",
+    "dlarrv": "void (int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, int *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, int *)",
+    "dlartg": "void (__pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *)",
+    "dlartgp": "void (__pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *)",
+    "dlartgs": "void (__pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *)",
+    "dlartv": "void (int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *)",
+    "dlaruv": "void (int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *)",
+    "dlarz": "void (char *, int *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *)",
+    "dlarzb": "void (char *, char *, char *, char *, int *, int *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *)",
+    "dlarzt": "void (char *, char *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *)",
+    "dlas2": "void (__pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *)",
+    "dlascl": "void (char *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, int *)",
+    "dlasd0": "void (int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *)",
+    "dlasd1": "void (int *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *)",
+    "dlasd2": "void (int *, int *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, int *, int *, int *, int *, int *, int *)",
+    "dlasd3": "void (int *, int *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *)",
+    "dlasd4": "void (int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *)",
+    "dlasd5": "void (int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *)",
+    "dlasd6": "void (int *, int *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, int *, int *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, int *)",
+    "dlasd7": "void (int *, int *, int *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, int *, int *, int *, int *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *)",
+    "dlasd8": "void (int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *)",
+    "dlasda": "void (int *, int *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, int *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, int *)",
+    "dlasdq": "void (char *, int *, int *, int *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *)",
+    "dlasdt": "void (int *, int *, int *, int *, int *, int *, int *)",
+    "dlaset": "void (char *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *)",
+    "dlasq1": "void (int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *)",
+    "dlasq2": "void (int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *)",
+    "dlasq3": "void (int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, int *, int *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *)",
+    "dlasq4": "void (int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *)",
+    "dlasq6": "void (int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *)",
+    "dlasr": "void (char *, char *, char *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *)",
+    "dlasrt": "void (char *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *)",
+    "dlassq": "void (int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *)",
+    "dlasv2": "void (__pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *)",
+    "dlaswp": "void (int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, int *, int *, int *, int *)",
+    "dlasy2": "void (int *, int *, int *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *)",
+    "dlasyf": "void (char *, int *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, int *)",
+    "dlat2s": "void (char *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, int *)",
+    "dlatbs": "void (char *, char *, char *, char *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *)",
+    "dlatdf": "void (int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, int *)",
+    "dlatps": "void (char *, char *, char *, char *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *)",
+    "dlatrd": "void (char *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *)",
+    "dlatrs": "void (char *, char *, char *, char *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *)",
+    "dlatrz": "void (int *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *)",
+    "dlauu2": "void (char *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, int *)",
+    "dlauum": "void (char *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, int *)",
+    "dopgtr": "void (char *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *)",
+    "dopmtr": "void (char *, char *, char *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *)",
+    "dorbdb": "void (char *, char *, int *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, int *)",
+    "dorcsd": "void (char *, char *, char *, char *, char *, char *, int *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, int *, int *)",
+    "dorg2l": "void (int *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *)",
+    "dorg2r": "void (int *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *)",
+    "dorgbr": "void (char *, int *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, int *)",
+    "dorghr": "void (int *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, int *)",
+    "dorgl2": "void (int *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *)",
+    "dorglq": "void (int *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, int *)",
+    "dorgql": "void (int *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, int *)",
+    "dorgqr": "void (int *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, int *)",
+    "dorgr2": "void (int *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *)",
+    "dorgrq": "void (int *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, int *)",
+    "dorgtr": "void (char *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, int *)",
+    "dorm2l": "void (char *, char *, int *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *)",
+    "dorm2r": "void (char *, char *, int *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *)",
+    "dormbr": "void (char *, char *, char *, int *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, int *)",
+    "dormhr": "void (char *, char *, int *, int *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, int *)",
+    "dorml2": "void (char *, char *, int *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *)",
+    "dormlq": "void (char *, char *, int *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, int *)",
+    "dormql": "void (char *, char *, int *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, int *)",
+    "dormqr": "void (char *, char *, int *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, int *)",
+    "dormr2": "void (char *, char *, int *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *)",
+    "dormr3": "void (char *, char *, int *, int *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *)",
+    "dormrq": "void (char *, char *, int *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, int *)",
+    "dormrz": "void (char *, char *, int *, int *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, int *)",
+    "dormtr": "void (char *, char *, char *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, int *)",
+    "dpbcon": "void (char *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, int *)",
+    "dpbequ": "void (char *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *)",
+    "dpbrfs": "void (char *, int *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, int *)",
+    "dpbstf": "void (char *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, int *)",
+    "dpbsv": "void (char *, int *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, int *)",
+    "dpbsvx": "void (char *, char *, int *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, char *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, int *)",
+    "dpbtf2": "void (char *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, int *)",
+    "dpbtrf": "void (char *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, int *)",
+    "dpbtrs": "void (char *, int *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, int *)",
+    "dpftrf": "void (char *, char *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *)",
+    "dpftri": "void (char *, char *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *)",
+    "dpftrs": "void (char *, char *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, int *)",
+    "dpocon": "void (char *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, int *)",
+    "dpoequ": "void (int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *)",
+    "dpoequb": "void (int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *)",
+    "dporfs": "void (char *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, int *)",
+    "dposv": "void (char *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, int *)",
+    "dposvx": "void (char *, char *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, char *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, int *)",
+    "dpotf2": "void (char *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, int *)",
+    "dpotrf": "void (char *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, int *)",
+    "dpotri": "void (char *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, int *)",
+    "dpotrs": "void (char *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, int *)",
+    "dppcon": "void (char *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, int *)",
+    "dppequ": "void (char *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *)",
+    "dpprfs": "void (char *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, int *)",
+    "dppsv": "void (char *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, int *)",
+    "dppsvx": "void (char *, char *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, char *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, int *)",
+    "dpptrf": "void (char *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *)",
+    "dpptri": "void (char *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *)",
+    "dpptrs": "void (char *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, int *)",
+    "dpstf2": "void (char *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *)",
+    "dpstrf": "void (char *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *)",
+    "dptcon": "void (int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *)",
+    "dpteqr": "void (char *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *)",
+    "dptrfs": "void (int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *)",
+    "dptsv": "void (int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, int *)",
+    "dptsvx": "void (char *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *)",
+    "dpttrf": "void (int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *)",
+    "dpttrs": "void (int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, int *)",
+    "dptts2": "void (int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *)",
+    "drscl": "void (int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *)",
+    "dsbev": "void (char *, char *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *)",
+    "dsbevd": "void (char *, char *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, int *, int *, int *)",
+    "dsbevx": "void (char *, char *, char *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, int *, int *)",
+    "dsbgst": "void (char *, char *, int *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *)",
+    "dsbgv": "void (char *, char *, int *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *)",
+    "dsbgvd": "void (char *, char *, int *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, int *, int *, int *)",
+    "dsbgvx": "void (char *, char *, char *, int *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, int *, int *)",
+    "dsbtrd": "void (char *, char *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *)",
+    "dsfrk": "void (char *, char *, char *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *)",
+    "dsgesv": "void (int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, int *)",
+    "dspcon": "void (char *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, int *)",
+    "dspev": "void (char *, char *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *)",
+    "dspevd": "void (char *, char *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, int *, int *, int *)",
+    "dspevx": "void (char *, char *, char *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, int *, int *)",
+    "dspgst": "void (int *, char *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *)",
+    "dspgv": "void (int *, char *, char *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *)",
+    "dspgvd": "void (int *, char *, char *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, int *, int *, int *)",
+    "dspgvx": "void (int *, char *, char *, char *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, int *, int *)",
+    "dsposv": "void (char *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, int *)",
+    "dsprfs": "void (char *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, int *)",
+    "dspsv": "void (char *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, int *)",
+    "dspsvx": "void (char *, char *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, int *)",
+    "dsptrd": "void (char *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *)",
+    "dsptrf": "void (char *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, int *)",
+    "dsptri": "void (char *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *)",
+    "dsptrs": "void (char *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, int *)",
+    "dstebz": "void (char *, char *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, int *)",
+    "dstedc": "void (char *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, int *, int *, int *)",
+    "dstegr": "void (char *, char *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, int *, int *, int *)",
+    "dstein": "void (int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, int *, int *)",
+    "dstemr": "void (char *, char *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, int *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, int *, int *, int *)",
+    "dsteqr": "void (char *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *)",
+    "dsterf": "void (int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *)",
+    "dstev": "void (char *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *)",
+    "dstevd": "void (char *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, int *, int *, int *)",
+    "dstevr": "void (char *, char *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, int *, int *, int *)",
+    "dstevx": "void (char *, char *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, int *, int *)",
+    "dsycon": "void (char *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, int *)",
+    "dsyconv": "void (char *, char *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *)",
+    "dsyequb": "void (char *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *)",
+    "dsyev": "void (char *, char *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, int *)",
+    "dsyevd": "void (char *, char *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, int *, int *, int *)",
+    "dsyevr": "void (char *, char *, char *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, int *, int *, int *)",
+    "dsyevx": "void (char *, char *, char *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, int *, int *, int *)",
+    "dsygs2": "void (int *, char *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, int *)",
+    "dsygst": "void (int *, char *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, int *)",
+    "dsygv": "void (int *, char *, char *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, int *)",
+    "dsygvd": "void (int *, char *, char *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, int *, int *, int *)",
+    "dsygvx": "void (int *, char *, char *, char *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, int *, int *, int *)",
+    "dsyrfs": "void (char *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, int *)",
+    "dsysv": "void (char *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, int *)",
+    "dsysvx": "void (char *, char *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, int *, int *)",
+    "dsyswapr": "void (char *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, int *, int *)",
+    "dsytd2": "void (char *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *)",
+    "dsytf2": "void (char *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, int *, int *)",
+    "dsytrd": "void (char *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, int *)",
+    "dsytrf": "void (char *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, int *)",
+    "dsytri": "void (char *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *)",
+    "dsytri2": "void (char *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, int *)",
+    "dsytri2x": "void (char *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, int *)",
+    "dsytrs": "void (char *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, int *)",
+    "dsytrs2": "void (char *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *)",
+    "dtbcon": "void (char *, char *, char *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, int *)",
+    "dtbrfs": "void (char *, char *, char *, int *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, int *)",
+    "dtbtrs": "void (char *, char *, char *, int *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, int *)",
+    "dtfsm": "void (char *, char *, char *, char *, char *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *)",
+    "dtftri": "void (char *, char *, char *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *)",
+    "dtfttp": "void (char *, char *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *)",
+    "dtfttr": "void (char *, char *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, int *)",
+    "dtgevc": "void (char *, char *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *)",
+    "dtgex2": "void (int *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, int *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, int *)",
+    "dtgexc": "void (int *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, int *)",
+    "dtgsen": "void (int *, int *, int *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, int *, int *, int *)",
+    "dtgsja": "void (char *, char *, char *, int *, int *, int *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, int *)",
+    "dtgsna": "void (char *, char *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, int *, int *)",
+    "dtgsy2": "void (char *, int *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, int *, int *)",
+    "dtgsyl": "void (char *, int *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, int *, int *)",
+    "dtpcon": "void (char *, char *, char *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, int *)",
+    "dtpmqrt": "void (char *, char *, int *, int *, int *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *)",
+    "dtpqrt": "void (int *, int *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *)",
+    "dtpqrt2": "void (int *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, int *)",
+    "dtprfb": "void (char *, char *, char *, char *, int *, int *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *)",
+    "dtprfs": "void (char *, char *, char *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, int *)",
+    "dtptri": "void (char *, char *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *)",
+    "dtptrs": "void (char *, char *, char *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, int *)",
+    "dtpttf": "void (char *, char *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *)",
+    "dtpttr": "void (char *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, int *)",
+    "dtrcon": "void (char *, char *, char *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, int *)",
+    "dtrevc": "void (char *, char *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *)",
+    "dtrexc": "void (char *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *)",
+    "dtrrfs": "void (char *, char *, char *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, int *)",
+    "dtrsen": "void (char *, char *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, int *, int *, int *)",
+    "dtrsna": "void (char *, char *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, int *, int *)",
+    "dtrsyl": "void (char *, char *, int *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *)",
+    "dtrti2": "void (char *, char *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, int *)",
+    "dtrtri": "void (char *, char *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, int *)",
+    "dtrtrs": "void (char *, char *, char *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, int *)",
+    "dtrttf": "void (char *, char *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *)",
+    "dtrttp": "void (char *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *)",
+    "dtzrzf": "void (int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, int *)",
+    "dzsum1": "__pyx_t_5scipy_6linalg_13cython_lapack_d (int *, __pyx_t_double_complex *, int *)",
+    "icmax1": "int (int *, __pyx_t_float_complex *, int *)",
+    "ieeeck": "int (int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *)",
+    "ilaclc": "int (int *, int *, __pyx_t_float_complex *, int *)",
+    "ilaclr": "int (int *, int *, __pyx_t_float_complex *, int *)",
+    "iladiag": "int (char *)",
+    "iladlc": "int (int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *)",
+    "iladlr": "int (int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *)",
+    "ilaprec": "int (char *)",
+    "ilaslc": "int (int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *)",
+    "ilaslr": "int (int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *)",
+    "ilatrans": "int (char *)",
+    "ilauplo": "int (char *)",
+    "ilaver": "void (int *, int *, int *)",
+    "ilazlc": "int (int *, int *, __pyx_t_double_complex *, int *)",
+    "ilazlr": "int (int *, int *, __pyx_t_double_complex *, int *)",
+    "izmax1": "int (int *, __pyx_t_double_complex *, int *)",
+    "sbbcsd": "void (char *, char *, char *, char *, char *, int *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, int *)",
+    "sbdsdc": "void (char *, char *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, int *)",
+    "sbdsqr": "void (char *, int *, int *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *)",
+    "scsum1": "__pyx_t_5scipy_6linalg_13cython_lapack_s (int *, __pyx_t_float_complex *, int *)",
+    "sdisna": "void (char *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *)",
+    "sgbbrd": "void (char *, int *, int *, int *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *)",
+    "sgbcon": "void (char *, int *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, int *)",
+    "sgbequ": "void (int *, int *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *)",
+    "sgbequb": "void (int *, int *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *)",
+    "sgbrfs": "void (char *, int *, int *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, int *)",
+    "sgbsv": "void (int *, int *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, int *)",
+    "sgbsvx": "void (char *, char *, int *, int *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, int *, char *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, int *)",
+    "sgbtf2": "void (int *, int *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, int *, int *)",
+    "sgbtrf": "void (int *, int *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, int *, int *)",
+    "sgbtrs": "void (char *, int *, int *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, int *)",
+    "sgebak": "void (char *, char *, int *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, int *)",
+    "sgebal": "void (char *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *)",
+    "sgebd2": "void (int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *)",
+    "sgebrd": "void (int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, int *)",
+    "sgecon": "void (char *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, int *)",
+    "sgeequ": "void (int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *)",
+    "sgeequb": "void (int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *)",
+    "sgees": "void (char *, char *, __pyx_t_5scipy_6linalg_13cython_lapack_sselect2 *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, int *, int *)",
+    "sgeesx": "void (char *, char *, __pyx_t_5scipy_6linalg_13cython_lapack_sselect2 *, char *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, int *, int *, int *, int *)",
+    "sgeev": "void (char *, char *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, int *)",
+    "sgeevx": "void (char *, char *, char *, char *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, int *, int *)",
+    "sgehd2": "void (int *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *)",
+    "sgehrd": "void (int *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, int *)",
+    "sgejsv": "void (char *, char *, char *, char *, char *, char *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, int *, int *)",
+    "sgelq2": "void (int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *)",
+    "sgelqf": "void (int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, int *)",
+    "sgels": "void (char *, int *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, int *)",
+    "sgelsd": "void (int *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, int *, int *)",
+    "sgelss": "void (int *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, int *)",
+    "sgelsy": "void (int *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, int *)",
+    "sgemqrt": "void (char *, char *, int *, int *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *)",
+    "sgeql2": "void (int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *)",
+    "sgeqlf": "void (int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, int *)",
+    "sgeqp3": "void (int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, int *)",
+    "sgeqr2": "void (int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *)",
+    "sgeqr2p": "void (int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *)",
+    "sgeqrf": "void (int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, int *)",
+    "sgeqrfp": "void (int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, int *)",
+    "sgeqrt": "void (int *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *)",
+    "sgeqrt2": "void (int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, int *)",
+    "sgeqrt3": "void (int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, int *)",
+    "sgerfs": "void (char *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, int *)",
+    "sgerq2": "void (int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *)",
+    "sgerqf": "void (int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, int *)",
+    "sgesc2": "void (int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *)",
+    "sgesdd": "void (char *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, int *, int *)",
+    "sgesv": "void (int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, int *)",
+    "sgesvd": "void (char *, char *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, int *)",
+    "sgesvj": "void (char *, char *, char *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, int *)",
+    "sgesvx": "void (char *, char *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, int *, char *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, int *)",
+    "sgetc2": "void (int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, int *, int *, int *)",
+    "sgetf2": "void (int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, int *, int *)",
+    "sgetrf": "void (int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, int *, int *)",
+    "sgetri": "void (int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, int *)",
+    "sgetrs": "void (char *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, int *)",
+    "sggbak": "void (char *, char *, int *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, int *)",
+    "sggbal": "void (char *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *)",
+    "sgges": "void (char *, char *, char *, __pyx_t_5scipy_6linalg_13cython_lapack_sselect3 *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, int *, int *)",
+    "sggesx": "void (char *, char *, char *, __pyx_t_5scipy_6linalg_13cython_lapack_sselect3 *, char *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, int *, int *, int *, int *)",
+    "sggev": "void (char *, char *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, int *)",
+    "sggevx": "void (char *, char *, char *, char *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, int *, int *, int *)",
+    "sggglm": "void (int *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, int *)",
+    "sgghrd": "void (char *, char *, int *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, int *)",
+    "sgglse": "void (int *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, int *)",
+    "sggqrf": "void (int *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, int *)",
+    "sggrqf": "void (int *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, int *)",
+    "sgsvj0": "void (char *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, int *)",
+    "sgsvj1": "void (char *, int *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, int *)",
+    "sgtcon": "void (char *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, int *)",
+    "sgtrfs": "void (char *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, int *)",
+    "sgtsv": "void (int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, int *)",
+    "sgtsvx": "void (char *, char *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, int *)",
+    "sgttrf": "void (int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, int *)",
+    "sgttrs": "void (char *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, int *)",
+    "sgtts2": "void (int *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *)",
+    "shgeqz": "void (char *, char *, char *, int *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, int *)",
+    "shsein": "void (char *, char *, char *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, int *, int *)",
+    "shseqr": "void (char *, char *, int *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, int *)",
+    "slabad": "void (__pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *)",
+    "slabrd": "void (int *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *)",
+    "slacn2": "void (int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, int *)",
+    "slacon": "void (int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *)",
+    "slacpy": "void (char *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *)",
+    "sladiv": "void (__pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *)",
+    "slae2": "void (__pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *)",
+    "slaebz": "void (int *, int *, int *, int *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, int *)",
+    "slaed0": "void (int *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, int *)",
+    "slaed1": "void (int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, int *)",
+    "slaed2": "void (int *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, int *, int *, int *, int *)",
+    "slaed3": "void (int *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *)",
+    "slaed4": "void (int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *)",
+    "slaed5": "void (int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *)",
+    "slaed6": "void (int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *)",
+    "slaed7": "void (int *, int *, int *, int *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, int *, int *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, int *)",
+    "slaed8": "void (int *, int *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, int *, int *)",
+    "slaed9": "void (int *, int *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, int *)",
+    "slaeda": "void (int *, int *, int *, int *, int *, int *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *)",
+    "slaein": "void (int *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *)",
+    "slaev2": "void (__pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *)",
+    "slaexc": "void (int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, int *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *)",
+    "slag2": "void (__pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *)",
+    "slag2d": "void (int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, int *)",
+    "slags2": "void (int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *)",
+    "slagtf": "void (int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, int *)",
+    "slagtm": "void (char *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *)",
+    "slagts": "void (int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *)",
+    "slagv2": "void (__pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *)",
+    "slahqr": "void (int *, int *, int *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, int *)",
+    "slahr2": "void (int *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *)",
+    "slaic1": "void (int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *)",
+    "slaln2": "void (int *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *)",
+    "slals0": "void (int *, int *, int *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, int *, int *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *)",
+    "slalsa": "void (int *, int *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, int *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, int *)",
+    "slalsd": "void (char *, int *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, int *)",
+    "slamch": "__pyx_t_5scipy_6linalg_13cython_lapack_s (char *)",
+    "slamrg": "void (int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, int *, int *)",
+    "slangb": "__pyx_t_5scipy_6linalg_13cython_lapack_s (char *, int *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *)",
+    "slange": "__pyx_t_5scipy_6linalg_13cython_lapack_s (char *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *)",
+    "slangt": "__pyx_t_5scipy_6linalg_13cython_lapack_s (char *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *)",
+    "slanhs": "__pyx_t_5scipy_6linalg_13cython_lapack_s (char *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *)",
+    "slansb": "__pyx_t_5scipy_6linalg_13cython_lapack_s (char *, char *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *)",
+    "slansf": "__pyx_t_5scipy_6linalg_13cython_lapack_s (char *, char *, char *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *)",
+    "slansp": "__pyx_t_5scipy_6linalg_13cython_lapack_s (char *, char *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *)",
+    "slanst": "__pyx_t_5scipy_6linalg_13cython_lapack_s (char *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *)",
+    "slansy": "__pyx_t_5scipy_6linalg_13cython_lapack_s (char *, char *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *)",
+    "slantb": "__pyx_t_5scipy_6linalg_13cython_lapack_s (char *, char *, char *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *)",
+    "slantp": "__pyx_t_5scipy_6linalg_13cython_lapack_s (char *, char *, char *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *)",
+    "slantr": "__pyx_t_5scipy_6linalg_13cython_lapack_s (char *, char *, char *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *)",
+    "slanv2": "void (__pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *)",
+    "slapll": "void (int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *)",
+    "slapmr": "void (int *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, int *)",
+    "slapmt": "void (int *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, int *)",
+    "slapy2": "__pyx_t_5scipy_6linalg_13cython_lapack_s (__pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *)",
+    "slapy3": "__pyx_t_5scipy_6linalg_13cython_lapack_s (__pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *)",
+    "slaqgb": "void (int *, int *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, char *)",
+    "slaqge": "void (int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, char *)",
+    "slaqp2": "void (int *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *)",
+    "slaqps": "void (int *, int *, int *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *)",
+    "slaqr0": "void (int *, int *, int *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, int *)",
+    "slaqr1": "void (int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *)",
+    "slaqr2": "void (int *, int *, int *, int *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *)",
+    "slaqr3": "void (int *, int *, int *, int *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *)",
+    "slaqr4": "void (int *, int *, int *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, int *)",
+    "slaqr5": "void (int *, int *, int *, int *, int *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *)",
+    "slaqsb": "void (char *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, char *)",
+    "slaqsp": "void (char *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, char *)",
+    "slaqsy": "void (char *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, char *)",
+    "slaqtr": "void (int *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *)",
+    "slar1v": "void (int *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *)",
+    "slar2v": "void (int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *)",
+    "slarf": "void (char *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *)",
+    "slarfb": "void (char *, char *, char *, char *, int *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *)",
+    "slarfg": "void (int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *)",
+    "slarfgp": "void (int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *)",
+    "slarft": "void (char *, char *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *)",
+    "slarfx": "void (char *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *)",
+    "slargv": "void (int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *)",
+    "slarnv": "void (int *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *)",
+    "slarra": "void (int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, int *, int *)",
+    "slarrb": "void (int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, int *)",
+    "slarrc": "void (char *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, int *, int *, int *)",
+    "slarrd": "void (char *, char *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, int *)",
+    "slarre": "void (char *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, int *)",
+    "slarrf": "void (int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *)",
+    "slarrj": "void (int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *)",
+    "slarrk": "void (int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *)",
+    "slarrr": "void (int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *)",
+    "slarrv": "void (int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, int *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, int *)",
+    "slartg": "void (__pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *)",
+    "slartgp": "void (__pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *)",
+    "slartgs": "void (__pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *)",
+    "slartv": "void (int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *)",
+    "slaruv": "void (int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *)",
+    "slarz": "void (char *, int *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *)",
+    "slarzb": "void (char *, char *, char *, char *, int *, int *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *)",
+    "slarzt": "void (char *, char *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *)",
+    "slas2": "void (__pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *)",
+    "slascl": "void (char *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, int *)",
+    "slasd0": "void (int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *)",
+    "slasd1": "void (int *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *)",
+    "slasd2": "void (int *, int *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, int *, int *, int *, int *, int *, int *)",
+    "slasd3": "void (int *, int *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *)",
+    "slasd4": "void (int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *)",
+    "slasd5": "void (int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *)",
+    "slasd6": "void (int *, int *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, int *, int *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, int *)",
+    "slasd7": "void (int *, int *, int *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, int *, int *, int *, int *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *)",
+    "slasd8": "void (int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *)",
+    "slasda": "void (int *, int *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, int *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, int *)",
+    "slasdq": "void (char *, int *, int *, int *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *)",
+    "slasdt": "void (int *, int *, int *, int *, int *, int *, int *)",
+    "slaset": "void (char *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *)",
+    "slasq1": "void (int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *)",
+    "slasq2": "void (int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *)",
+    "slasq3": "void (int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, int *, int *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *)",
+    "slasq4": "void (int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *)",
+    "slasq6": "void (int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *)",
+    "slasr": "void (char *, char *, char *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *)",
+    "slasrt": "void (char *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *)",
+    "slassq": "void (int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *)",
+    "slasv2": "void (__pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *)",
+    "slaswp": "void (int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, int *, int *, int *, int *)",
+    "slasy2": "void (int *, int *, int *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *)",
+    "slasyf": "void (char *, int *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, int *)",
+    "slatbs": "void (char *, char *, char *, char *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *)",
+    "slatdf": "void (int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, int *)",
+    "slatps": "void (char *, char *, char *, char *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *)",
+    "slatrd": "void (char *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *)",
+    "slatrs": "void (char *, char *, char *, char *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *)",
+    "slatrz": "void (int *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *)",
+    "slauu2": "void (char *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, int *)",
+    "slauum": "void (char *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, int *)",
+    "sopgtr": "void (char *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *)",
+    "sopmtr": "void (char *, char *, char *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *)",
+    "sorbdb": "void (char *, char *, int *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, int *)",
+    "sorcsd": "void (char *, char *, char *, char *, char *, char *, int *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, int *, int *)",
+    "sorg2l": "void (int *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *)",
+    "sorg2r": "void (int *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *)",
+    "sorgbr": "void (char *, int *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, int *)",
+    "sorghr": "void (int *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, int *)",
+    "sorgl2": "void (int *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *)",
+    "sorglq": "void (int *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, int *)",
+    "sorgql": "void (int *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, int *)",
+    "sorgqr": "void (int *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, int *)",
+    "sorgr2": "void (int *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *)",
+    "sorgrq": "void (int *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, int *)",
+    "sorgtr": "void (char *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, int *)",
+    "sorm2l": "void (char *, char *, int *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *)",
+    "sorm2r": "void (char *, char *, int *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *)",
+    "sormbr": "void (char *, char *, char *, int *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, int *)",
+    "sormhr": "void (char *, char *, int *, int *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, int *)",
+    "sorml2": "void (char *, char *, int *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *)",
+    "sormlq": "void (char *, char *, int *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, int *)",
+    "sormql": "void (char *, char *, int *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, int *)",
+    "sormqr": "void (char *, char *, int *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, int *)",
+    "sormr2": "void (char *, char *, int *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *)",
+    "sormr3": "void (char *, char *, int *, int *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *)",
+    "sormrq": "void (char *, char *, int *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, int *)",
+    "sormrz": "void (char *, char *, int *, int *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, int *)",
+    "sormtr": "void (char *, char *, char *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, int *)",
+    "spbcon": "void (char *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, int *)",
+    "spbequ": "void (char *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *)",
+    "spbrfs": "void (char *, int *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, int *)",
+    "spbstf": "void (char *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, int *)",
+    "spbsv": "void (char *, int *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, int *)",
+    "spbsvx": "void (char *, char *, int *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, char *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, int *)",
+    "spbtf2": "void (char *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, int *)",
+    "spbtrf": "void (char *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, int *)",
+    "spbtrs": "void (char *, int *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, int *)",
+    "spftrf": "void (char *, char *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *)",
+    "spftri": "void (char *, char *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *)",
+    "spftrs": "void (char *, char *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, int *)",
+    "spocon": "void (char *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, int *)",
+    "spoequ": "void (int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *)",
+    "spoequb": "void (int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *)",
+    "sporfs": "void (char *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, int *)",
+    "sposv": "void (char *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, int *)",
+    "sposvx": "void (char *, char *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, char *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, int *)",
+    "spotf2": "void (char *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, int *)",
+    "spotrf": "void (char *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, int *)",
+    "spotri": "void (char *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, int *)",
+    "spotrs": "void (char *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, int *)",
+    "sppcon": "void (char *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, int *)",
+    "sppequ": "void (char *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *)",
+    "spprfs": "void (char *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, int *)",
+    "sppsv": "void (char *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, int *)",
+    "sppsvx": "void (char *, char *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, char *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, int *)",
+    "spptrf": "void (char *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *)",
+    "spptri": "void (char *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *)",
+    "spptrs": "void (char *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, int *)",
+    "spstf2": "void (char *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *)",
+    "spstrf": "void (char *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *)",
+    "sptcon": "void (int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *)",
+    "spteqr": "void (char *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *)",
+    "sptrfs": "void (int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *)",
+    "sptsv": "void (int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, int *)",
+    "sptsvx": "void (char *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *)",
+    "spttrf": "void (int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *)",
+    "spttrs": "void (int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, int *)",
+    "sptts2": "void (int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *)",
+    "srscl": "void (int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *)",
+    "ssbev": "void (char *, char *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *)",
+    "ssbevd": "void (char *, char *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, int *, int *, int *)",
+    "ssbevx": "void (char *, char *, char *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, int *, int *)",
+    "ssbgst": "void (char *, char *, int *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *)",
+    "ssbgv": "void (char *, char *, int *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *)",
+    "ssbgvd": "void (char *, char *, int *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, int *, int *, int *)",
+    "ssbgvx": "void (char *, char *, char *, int *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, int *, int *)",
+    "ssbtrd": "void (char *, char *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *)",
+    "ssfrk": "void (char *, char *, char *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *)",
+    "sspcon": "void (char *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, int *)",
+    "sspev": "void (char *, char *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *)",
+    "sspevd": "void (char *, char *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, int *, int *, int *)",
+    "sspevx": "void (char *, char *, char *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, int *, int *)",
+    "sspgst": "void (int *, char *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *)",
+    "sspgv": "void (int *, char *, char *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *)",
+    "sspgvd": "void (int *, char *, char *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, int *, int *, int *)",
+    "sspgvx": "void (int *, char *, char *, char *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, int *, int *)",
+    "ssprfs": "void (char *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, int *)",
+    "sspsv": "void (char *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, int *)",
+    "sspsvx": "void (char *, char *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, int *)",
+    "ssptrd": "void (char *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *)",
+    "ssptrf": "void (char *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, int *)",
+    "ssptri": "void (char *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *)",
+    "ssptrs": "void (char *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, int *)",
+    "sstebz": "void (char *, char *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, int *)",
+    "sstedc": "void (char *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, int *, int *, int *)",
+    "sstegr": "void (char *, char *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, int *, int *, int *)",
+    "sstein": "void (int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, int *, int *)",
+    "sstemr": "void (char *, char *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, int *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, int *, int *, int *)",
+    "ssteqr": "void (char *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *)",
+    "ssterf": "void (int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *)",
+    "sstev": "void (char *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *)",
+    "sstevd": "void (char *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, int *, int *, int *)",
+    "sstevr": "void (char *, char *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, int *, int *, int *)",
+    "sstevx": "void (char *, char *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, int *, int *)",
+    "ssycon": "void (char *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, int *)",
+    "ssyconv": "void (char *, char *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *)",
+    "ssyequb": "void (char *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *)",
+    "ssyev": "void (char *, char *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, int *)",
+    "ssyevd": "void (char *, char *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, int *, int *, int *)",
+    "ssyevr": "void (char *, char *, char *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, int *, int *, int *)",
+    "ssyevx": "void (char *, char *, char *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, int *, int *, int *)",
+    "ssygs2": "void (int *, char *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, int *)",
+    "ssygst": "void (int *, char *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, int *)",
+    "ssygv": "void (int *, char *, char *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, int *)",
+    "ssygvd": "void (int *, char *, char *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, int *, int *, int *)",
+    "ssygvx": "void (int *, char *, char *, char *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, int *, int *, int *)",
+    "ssyrfs": "void (char *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, int *)",
+    "ssysv": "void (char *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, int *)",
+    "ssysvx": "void (char *, char *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, int *, int *)",
+    "ssyswapr": "void (char *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, int *, int *)",
+    "ssytd2": "void (char *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *)",
+    "ssytf2": "void (char *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, int *, int *)",
+    "ssytrd": "void (char *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, int *)",
+    "ssytrf": "void (char *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, int *)",
+    "ssytri": "void (char *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *)",
+    "ssytri2": "void (char *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, int *)",
+    "ssytri2x": "void (char *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, int *)",
+    "ssytrs": "void (char *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, int *)",
+    "ssytrs2": "void (char *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *)",
+    "stbcon": "void (char *, char *, char *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, int *)",
+    "stbrfs": "void (char *, char *, char *, int *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, int *)",
+    "stbtrs": "void (char *, char *, char *, int *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, int *)",
+    "stfsm": "void (char *, char *, char *, char *, char *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *)",
+    "stftri": "void (char *, char *, char *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *)",
+    "stfttp": "void (char *, char *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *)",
+    "stfttr": "void (char *, char *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, int *)",
+    "stgevc": "void (char *, char *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *)",
+    "stgex2": "void (int *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, int *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, int *)",
+    "stgexc": "void (int *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, int *)",
+    "stgsen": "void (int *, int *, int *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, int *, int *, int *)",
+    "stgsja": "void (char *, char *, char *, int *, int *, int *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, int *)",
+    "stgsna": "void (char *, char *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, int *, int *)",
+    "stgsy2": "void (char *, int *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, int *, int *)",
+    "stgsyl": "void (char *, int *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, int *, int *)",
+    "stpcon": "void (char *, char *, char *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, int *)",
+    "stpmqrt": "void (char *, char *, int *, int *, int *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *)",
+    "stpqrt": "void (int *, int *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *)",
+    "stpqrt2": "void (int *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, int *)",
+    "stprfb": "void (char *, char *, char *, char *, int *, int *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *)",
+    "stprfs": "void (char *, char *, char *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, int *)",
+    "stptri": "void (char *, char *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *)",
+    "stptrs": "void (char *, char *, char *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, int *)",
+    "stpttf": "void (char *, char *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *)",
+    "stpttr": "void (char *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, int *)",
+    "strcon": "void (char *, char *, char *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, int *)",
+    "strevc": "void (char *, char *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *)",
+    "strexc": "void (char *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *)",
+    "strrfs": "void (char *, char *, char *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, int *)",
+    "strsen": "void (char *, char *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, int *, int *, int *)",
+    "strsna": "void (char *, char *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, int *, int *)",
+    "strsyl": "void (char *, char *, int *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *)",
+    "strti2": "void (char *, char *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, int *)",
+    "strtri": "void (char *, char *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, int *)",
+    "strtrs": "void (char *, char *, char *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, int *)",
+    "strttf": "void (char *, char *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *)",
+    "strttp": "void (char *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *)",
+    "stzrzf": "void (int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, __pyx_t_5scipy_6linalg_13cython_lapack_s *, int *, int *)",
+    "xerbla_array": "void (char *, int *, int *)",
+    "zbbcsd": "void (char *, char *, char *, char *, char *, int *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_double_complex *, int *, __pyx_t_double_complex *, int *, __pyx_t_double_complex *, int *, __pyx_t_double_complex *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, int *)",
+    "zbdsqr": "void (char *, int *, int *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_double_complex *, int *, __pyx_t_double_complex *, int *, __pyx_t_double_complex *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *)",
+    "zcgesv": "void (int *, int *, __pyx_t_double_complex *, int *, int *, __pyx_t_double_complex *, int *, __pyx_t_double_complex *, int *, __pyx_t_double_complex *, __pyx_t_float_complex *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, int *)",
+    "zcposv": "void (char *, int *, int *, __pyx_t_double_complex *, int *, __pyx_t_double_complex *, int *, __pyx_t_double_complex *, int *, __pyx_t_double_complex *, __pyx_t_float_complex *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, int *)",
+    "zdrscl": "void (int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_double_complex *, int *)",
+    "zgbbrd": "void (char *, int *, int *, int *, int *, int *, __pyx_t_double_complex *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_double_complex *, int *, __pyx_t_double_complex *, int *, __pyx_t_double_complex *, int *, __pyx_t_double_complex *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *)",
+    "zgbcon": "void (char *, int *, int *, int *, __pyx_t_double_complex *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_double_complex *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *)",
+    "zgbequ": "void (int *, int *, int *, int *, __pyx_t_double_complex *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *)",
+    "zgbequb": "void (int *, int *, int *, int *, __pyx_t_double_complex *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *)",
+    "zgbrfs": "void (char *, int *, int *, int *, int *, __pyx_t_double_complex *, int *, __pyx_t_double_complex *, int *, int *, __pyx_t_double_complex *, int *, __pyx_t_double_complex *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_double_complex *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *)",
+    "zgbsv": "void (int *, int *, int *, int *, __pyx_t_double_complex *, int *, int *, __pyx_t_double_complex *, int *, int *)",
+    "zgbsvx": "void (char *, char *, int *, int *, int *, int *, __pyx_t_double_complex *, int *, __pyx_t_double_complex *, int *, int *, char *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_double_complex *, int *, __pyx_t_double_complex *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_double_complex *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *)",
+    "zgbtf2": "void (int *, int *, int *, int *, __pyx_t_double_complex *, int *, int *, int *)",
+    "zgbtrf": "void (int *, int *, int *, int *, __pyx_t_double_complex *, int *, int *, int *)",
+    "zgbtrs": "void (char *, int *, int *, int *, int *, __pyx_t_double_complex *, int *, int *, __pyx_t_double_complex *, int *, int *)",
+    "zgebak": "void (char *, char *, int *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_double_complex *, int *, int *)",
+    "zgebal": "void (char *, int *, __pyx_t_double_complex *, int *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *)",
+    "zgebd2": "void (int *, int *, __pyx_t_double_complex *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_double_complex *, __pyx_t_double_complex *, __pyx_t_double_complex *, int *)",
+    "zgebrd": "void (int *, int *, __pyx_t_double_complex *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_double_complex *, __pyx_t_double_complex *, __pyx_t_double_complex *, int *, int *)",
+    "zgecon": "void (char *, int *, __pyx_t_double_complex *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_double_complex *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *)",
+    "zgeequ": "void (int *, int *, __pyx_t_double_complex *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *)",
+    "zgeequb": "void (int *, int *, __pyx_t_double_complex *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *)",
+    "zgees": "void (char *, char *, __pyx_t_5scipy_6linalg_13cython_lapack_zselect1 *, int *, __pyx_t_double_complex *, int *, int *, __pyx_t_double_complex *, __pyx_t_double_complex *, int *, __pyx_t_double_complex *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, int *)",
+    "zgeesx": "void (char *, char *, __pyx_t_5scipy_6linalg_13cython_lapack_zselect1 *, char *, int *, __pyx_t_double_complex *, int *, int *, __pyx_t_double_complex *, __pyx_t_double_complex *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_double_complex *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, int *)",
+    "zgeev": "void (char *, char *, int *, __pyx_t_double_complex *, int *, __pyx_t_double_complex *, __pyx_t_double_complex *, int *, __pyx_t_double_complex *, int *, __pyx_t_double_complex *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *)",
+    "zgeevx": "void (char *, char *, char *, char *, int *, __pyx_t_double_complex *, int *, __pyx_t_double_complex *, __pyx_t_double_complex *, int *, __pyx_t_double_complex *, int *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_double_complex *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *)",
+    "zgehd2": "void (int *, int *, int *, __pyx_t_double_complex *, int *, __pyx_t_double_complex *, __pyx_t_double_complex *, int *)",
+    "zgehrd": "void (int *, int *, int *, __pyx_t_double_complex *, int *, __pyx_t_double_complex *, __pyx_t_double_complex *, int *, int *)",
+    "zgelq2": "void (int *, int *, __pyx_t_double_complex *, int *, __pyx_t_double_complex *, __pyx_t_double_complex *, int *)",
+    "zgelqf": "void (int *, int *, __pyx_t_double_complex *, int *, __pyx_t_double_complex *, __pyx_t_double_complex *, int *, int *)",
+    "zgels": "void (char *, int *, int *, int *, __pyx_t_double_complex *, int *, __pyx_t_double_complex *, int *, __pyx_t_double_complex *, int *, int *)",
+    "zgelsd": "void (int *, int *, int *, __pyx_t_double_complex *, int *, __pyx_t_double_complex *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_double_complex *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, int *)",
+    "zgelss": "void (int *, int *, int *, __pyx_t_double_complex *, int *, __pyx_t_double_complex *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_double_complex *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *)",
+    "zgelsy": "void (int *, int *, int *, __pyx_t_double_complex *, int *, __pyx_t_double_complex *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_double_complex *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *)",
+    "zgemqrt": "void (char *, char *, int *, int *, int *, int *, __pyx_t_double_complex *, int *, __pyx_t_double_complex *, int *, __pyx_t_double_complex *, int *, __pyx_t_double_complex *, int *)",
+    "zgeql2": "void (int *, int *, __pyx_t_double_complex *, int *, __pyx_t_double_complex *, __pyx_t_double_complex *, int *)",
+    "zgeqlf": "void (int *, int *, __pyx_t_double_complex *, int *, __pyx_t_double_complex *, __pyx_t_double_complex *, int *, int *)",
+    "zgeqp3": "void (int *, int *, __pyx_t_double_complex *, int *, int *, __pyx_t_double_complex *, __pyx_t_double_complex *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *)",
+    "zgeqr2": "void (int *, int *, __pyx_t_double_complex *, int *, __pyx_t_double_complex *, __pyx_t_double_complex *, int *)",
+    "zgeqr2p": "void (int *, int *, __pyx_t_double_complex *, int *, __pyx_t_double_complex *, __pyx_t_double_complex *, int *)",
+    "zgeqrf": "void (int *, int *, __pyx_t_double_complex *, int *, __pyx_t_double_complex *, __pyx_t_double_complex *, int *, int *)",
+    "zgeqrfp": "void (int *, int *, __pyx_t_double_complex *, int *, __pyx_t_double_complex *, __pyx_t_double_complex *, int *, int *)",
+    "zgeqrt": "void (int *, int *, int *, __pyx_t_double_complex *, int *, __pyx_t_double_complex *, int *, __pyx_t_double_complex *, int *)",
+    "zgeqrt2": "void (int *, int *, __pyx_t_double_complex *, int *, __pyx_t_double_complex *, int *, int *)",
+    "zgeqrt3": "void (int *, int *, __pyx_t_double_complex *, int *, __pyx_t_double_complex *, int *, int *)",
+    "zgerfs": "void (char *, int *, int *, __pyx_t_double_complex *, int *, __pyx_t_double_complex *, int *, int *, __pyx_t_double_complex *, int *, __pyx_t_double_complex *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_double_complex *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *)",
+    "zgerq2": "void (int *, int *, __pyx_t_double_complex *, int *, __pyx_t_double_complex *, __pyx_t_double_complex *, int *)",
+    "zgerqf": "void (int *, int *, __pyx_t_double_complex *, int *, __pyx_t_double_complex *, __pyx_t_double_complex *, int *, int *)",
+    "zgesc2": "void (int *, __pyx_t_double_complex *, int *, __pyx_t_double_complex *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *)",
+    "zgesdd": "void (char *, int *, int *, __pyx_t_double_complex *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_double_complex *, int *, __pyx_t_double_complex *, int *, __pyx_t_double_complex *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, int *)",
+    "zgesv": "void (int *, int *, __pyx_t_double_complex *, int *, int *, __pyx_t_double_complex *, int *, int *)",
+    "zgesvd": "void (char *, char *, int *, int *, __pyx_t_double_complex *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_double_complex *, int *, __pyx_t_double_complex *, int *, __pyx_t_double_complex *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *)",
+    "zgesvx": "void (char *, char *, int *, int *, __pyx_t_double_complex *, int *, __pyx_t_double_complex *, int *, int *, char *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_double_complex *, int *, __pyx_t_double_complex *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_double_complex *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *)",
+    "zgetc2": "void (int *, __pyx_t_double_complex *, int *, int *, int *, int *)",
+    "zgetf2": "void (int *, int *, __pyx_t_double_complex *, int *, int *, int *)",
+    "zgetrf": "void (int *, int *, __pyx_t_double_complex *, int *, int *, int *)",
+    "zgetri": "void (int *, __pyx_t_double_complex *, int *, int *, __pyx_t_double_complex *, int *, int *)",
+    "zgetrs": "void (char *, int *, int *, __pyx_t_double_complex *, int *, int *, __pyx_t_double_complex *, int *, int *)",
+    "zggbak": "void (char *, char *, int *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_double_complex *, int *, int *)",
+    "zggbal": "void (char *, int *, __pyx_t_double_complex *, int *, __pyx_t_double_complex *, int *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *)",
+    "zgges": "void (char *, char *, char *, __pyx_t_5scipy_6linalg_13cython_lapack_zselect2 *, int *, __pyx_t_double_complex *, int *, __pyx_t_double_complex *, int *, int *, __pyx_t_double_complex *, __pyx_t_double_complex *, __pyx_t_double_complex *, int *, __pyx_t_double_complex *, int *, __pyx_t_double_complex *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, int *)",
+    "zggesx": "void (char *, char *, char *, __pyx_t_5scipy_6linalg_13cython_lapack_zselect2 *, char *, int *, __pyx_t_double_complex *, int *, __pyx_t_double_complex *, int *, int *, __pyx_t_double_complex *, __pyx_t_double_complex *, __pyx_t_double_complex *, int *, __pyx_t_double_complex *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_double_complex *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, int *, int *, int *)",
+    "zggev": "void (char *, char *, int *, __pyx_t_double_complex *, int *, __pyx_t_double_complex *, int *, __pyx_t_double_complex *, __pyx_t_double_complex *, __pyx_t_double_complex *, int *, __pyx_t_double_complex *, int *, __pyx_t_double_complex *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *)",
+    "zggevx": "void (char *, char *, char *, char *, int *, __pyx_t_double_complex *, int *, __pyx_t_double_complex *, int *, __pyx_t_double_complex *, __pyx_t_double_complex *, __pyx_t_double_complex *, int *, __pyx_t_double_complex *, int *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_double_complex *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, int *, int *)",
+    "zggglm": "void (int *, int *, int *, __pyx_t_double_complex *, int *, __pyx_t_double_complex *, int *, __pyx_t_double_complex *, __pyx_t_double_complex *, __pyx_t_double_complex *, __pyx_t_double_complex *, int *, int *)",
+    "zgghrd": "void (char *, char *, int *, int *, int *, __pyx_t_double_complex *, int *, __pyx_t_double_complex *, int *, __pyx_t_double_complex *, int *, __pyx_t_double_complex *, int *, int *)",
+    "zgglse": "void (int *, int *, int *, __pyx_t_double_complex *, int *, __pyx_t_double_complex *, int *, __pyx_t_double_complex *, __pyx_t_double_complex *, __pyx_t_double_complex *, __pyx_t_double_complex *, int *, int *)",
+    "zggqrf": "void (int *, int *, int *, __pyx_t_double_complex *, int *, __pyx_t_double_complex *, __pyx_t_double_complex *, int *, __pyx_t_double_complex *, __pyx_t_double_complex *, int *, int *)",
+    "zggrqf": "void (int *, int *, int *, __pyx_t_double_complex *, int *, __pyx_t_double_complex *, __pyx_t_double_complex *, int *, __pyx_t_double_complex *, __pyx_t_double_complex *, int *, int *)",
+    "zgtcon": "void (char *, int *, __pyx_t_double_complex *, __pyx_t_double_complex *, __pyx_t_double_complex *, __pyx_t_double_complex *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_double_complex *, int *)",
+    "zgtrfs": "void (char *, int *, int *, __pyx_t_double_complex *, __pyx_t_double_complex *, __pyx_t_double_complex *, __pyx_t_double_complex *, __pyx_t_double_complex *, __pyx_t_double_complex *, __pyx_t_double_complex *, int *, __pyx_t_double_complex *, int *, __pyx_t_double_complex *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_double_complex *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *)",
+    "zgtsv": "void (int *, int *, __pyx_t_double_complex *, __pyx_t_double_complex *, __pyx_t_double_complex *, __pyx_t_double_complex *, int *, int *)",
+    "zgtsvx": "void (char *, char *, int *, int *, __pyx_t_double_complex *, __pyx_t_double_complex *, __pyx_t_double_complex *, __pyx_t_double_complex *, __pyx_t_double_complex *, __pyx_t_double_complex *, __pyx_t_double_complex *, int *, __pyx_t_double_complex *, int *, __pyx_t_double_complex *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_double_complex *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *)",
+    "zgttrf": "void (int *, __pyx_t_double_complex *, __pyx_t_double_complex *, __pyx_t_double_complex *, __pyx_t_double_complex *, int *, int *)",
+    "zgttrs": "void (char *, int *, int *, __pyx_t_double_complex *, __pyx_t_double_complex *, __pyx_t_double_complex *, __pyx_t_double_complex *, int *, __pyx_t_double_complex *, int *, int *)",
+    "zgtts2": "void (int *, int *, int *, __pyx_t_double_complex *, __pyx_t_double_complex *, __pyx_t_double_complex *, __pyx_t_double_complex *, int *, __pyx_t_double_complex *, int *)",
+    "zhbev": "void (char *, char *, int *, int *, __pyx_t_double_complex *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_double_complex *, int *, __pyx_t_double_complex *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *)",
+    "zhbevd": "void (char *, char *, int *, int *, __pyx_t_double_complex *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_double_complex *, int *, __pyx_t_double_complex *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, int *, int *, int *)",
+    "zhbevx": "void (char *, char *, char *, int *, int *, __pyx_t_double_complex *, int *, __pyx_t_double_complex *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_double_complex *, int *, __pyx_t_double_complex *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, int *, int *)",
+    "zhbgst": "void (char *, char *, int *, int *, int *, __pyx_t_double_complex *, int *, __pyx_t_double_complex *, int *, __pyx_t_double_complex *, int *, __pyx_t_double_complex *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *)",
+    "zhbgv": "void (char *, char *, int *, int *, int *, __pyx_t_double_complex *, int *, __pyx_t_double_complex *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_double_complex *, int *, __pyx_t_double_complex *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *)",
+    "zhbgvd": "void (char *, char *, int *, int *, int *, __pyx_t_double_complex *, int *, __pyx_t_double_complex *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_double_complex *, int *, __pyx_t_double_complex *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, int *, int *, int *)",
+    "zhbgvx": "void (char *, char *, char *, int *, int *, int *, __pyx_t_double_complex *, int *, __pyx_t_double_complex *, int *, __pyx_t_double_complex *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_double_complex *, int *, __pyx_t_double_complex *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, int *, int *)",
+    "zhbtrd": "void (char *, char *, int *, int *, __pyx_t_double_complex *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_double_complex *, int *, __pyx_t_double_complex *, int *)",
+    "zhecon": "void (char *, int *, __pyx_t_double_complex *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_double_complex *, int *)",
+    "zheequb": "void (char *, int *, __pyx_t_double_complex *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_double_complex *, int *)",
+    "zheev": "void (char *, char *, int *, __pyx_t_double_complex *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_double_complex *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *)",
+    "zheevd": "void (char *, char *, int *, __pyx_t_double_complex *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_double_complex *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, int *, int *, int *)",
+    "zheevr": "void (char *, char *, char *, int *, __pyx_t_double_complex *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_double_complex *, int *, int *, __pyx_t_double_complex *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, int *, int *, int *)",
+    "zheevx": "void (char *, char *, char *, int *, __pyx_t_double_complex *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_double_complex *, int *, __pyx_t_double_complex *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, int *, int *)",
+    "zhegs2": "void (int *, char *, int *, __pyx_t_double_complex *, int *, __pyx_t_double_complex *, int *, int *)",
+    "zhegst": "void (int *, char *, int *, __pyx_t_double_complex *, int *, __pyx_t_double_complex *, int *, int *)",
+    "zhegv": "void (int *, char *, char *, int *, __pyx_t_double_complex *, int *, __pyx_t_double_complex *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_double_complex *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *)",
+    "zhegvd": "void (int *, char *, char *, int *, __pyx_t_double_complex *, int *, __pyx_t_double_complex *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_double_complex *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, int *, int *, int *)",
+    "zhegvx": "void (int *, char *, char *, char *, int *, __pyx_t_double_complex *, int *, __pyx_t_double_complex *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_double_complex *, int *, __pyx_t_double_complex *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, int *, int *)",
+    "zherfs": "void (char *, int *, int *, __pyx_t_double_complex *, int *, __pyx_t_double_complex *, int *, int *, __pyx_t_double_complex *, int *, __pyx_t_double_complex *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_double_complex *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *)",
+    "zhesv": "void (char *, int *, int *, __pyx_t_double_complex *, int *, int *, __pyx_t_double_complex *, int *, __pyx_t_double_complex *, int *, int *)",
+    "zhesvx": "void (char *, char *, int *, int *, __pyx_t_double_complex *, int *, __pyx_t_double_complex *, int *, int *, __pyx_t_double_complex *, int *, __pyx_t_double_complex *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_double_complex *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *)",
+    "zheswapr": "void (char *, int *, __pyx_t_double_complex *, int *, int *, int *)",
+    "zhetd2": "void (char *, int *, __pyx_t_double_complex *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_double_complex *, int *)",
+    "zhetf2": "void (char *, int *, __pyx_t_double_complex *, int *, int *, int *)",
+    "zhetrd": "void (char *, int *, __pyx_t_double_complex *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_double_complex *, __pyx_t_double_complex *, int *, int *)",
+    "zhetrf": "void (char *, int *, __pyx_t_double_complex *, int *, int *, __pyx_t_double_complex *, int *, int *)",
+    "zhetri": "void (char *, int *, __pyx_t_double_complex *, int *, int *, __pyx_t_double_complex *, int *)",
+    "zhetri2": "void (char *, int *, __pyx_t_double_complex *, int *, int *, __pyx_t_double_complex *, int *, int *)",
+    "zhetri2x": "void (char *, int *, __pyx_t_double_complex *, int *, int *, __pyx_t_double_complex *, int *, int *)",
+    "zhetrs": "void (char *, int *, int *, __pyx_t_double_complex *, int *, int *, __pyx_t_double_complex *, int *, int *)",
+    "zhetrs2": "void (char *, int *, int *, __pyx_t_double_complex *, int *, int *, __pyx_t_double_complex *, int *, __pyx_t_double_complex *, int *)",
+    "zhfrk": "void (char *, char *, char *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_double_complex *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_double_complex *)",
+    "zhgeqz": "void (char *, char *, char *, int *, int *, int *, __pyx_t_double_complex *, int *, __pyx_t_double_complex *, int *, __pyx_t_double_complex *, __pyx_t_double_complex *, __pyx_t_double_complex *, int *, __pyx_t_double_complex *, int *, __pyx_t_double_complex *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *)",
+    "zhpcon": "void (char *, int *, __pyx_t_double_complex *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_double_complex *, int *)",
+    "zhpev": "void (char *, char *, int *, __pyx_t_double_complex *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_double_complex *, int *, __pyx_t_double_complex *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *)",
+    "zhpevd": "void (char *, char *, int *, __pyx_t_double_complex *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_double_complex *, int *, __pyx_t_double_complex *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, int *, int *, int *)",
+    "zhpevx": "void (char *, char *, char *, int *, __pyx_t_double_complex *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_double_complex *, int *, __pyx_t_double_complex *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, int *, int *)",
+    "zhpgst": "void (int *, char *, int *, __pyx_t_double_complex *, __pyx_t_double_complex *, int *)",
+    "zhpgv": "void (int *, char *, char *, int *, __pyx_t_double_complex *, __pyx_t_double_complex *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_double_complex *, int *, __pyx_t_double_complex *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *)",
+    "zhpgvd": "void (int *, char *, char *, int *, __pyx_t_double_complex *, __pyx_t_double_complex *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_double_complex *, int *, __pyx_t_double_complex *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, int *, int *, int *)",
+    "zhpgvx": "void (int *, char *, char *, char *, int *, __pyx_t_double_complex *, __pyx_t_double_complex *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_double_complex *, int *, __pyx_t_double_complex *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, int *, int *)",
+    "zhprfs": "void (char *, int *, int *, __pyx_t_double_complex *, __pyx_t_double_complex *, int *, __pyx_t_double_complex *, int *, __pyx_t_double_complex *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_double_complex *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *)",
+    "zhpsv": "void (char *, int *, int *, __pyx_t_double_complex *, int *, __pyx_t_double_complex *, int *, int *)",
+    "zhpsvx": "void (char *, char *, int *, int *, __pyx_t_double_complex *, __pyx_t_double_complex *, int *, __pyx_t_double_complex *, int *, __pyx_t_double_complex *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_double_complex *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *)",
+    "zhptrd": "void (char *, int *, __pyx_t_double_complex *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_double_complex *, int *)",
+    "zhptrf": "void (char *, int *, __pyx_t_double_complex *, int *, int *)",
+    "zhptri": "void (char *, int *, __pyx_t_double_complex *, int *, __pyx_t_double_complex *, int *)",
+    "zhptrs": "void (char *, int *, int *, __pyx_t_double_complex *, int *, __pyx_t_double_complex *, int *, int *)",
+    "zhsein": "void (char *, char *, char *, int *, int *, __pyx_t_double_complex *, int *, __pyx_t_double_complex *, __pyx_t_double_complex *, int *, __pyx_t_double_complex *, int *, int *, int *, __pyx_t_double_complex *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, int *, int *)",
+    "zhseqr": "void (char *, char *, int *, int *, int *, __pyx_t_double_complex *, int *, __pyx_t_double_complex *, __pyx_t_double_complex *, int *, __pyx_t_double_complex *, int *, int *)",
+    "zlabrd": "void (int *, int *, int *, __pyx_t_double_complex *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_double_complex *, __pyx_t_double_complex *, __pyx_t_double_complex *, int *, __pyx_t_double_complex *, int *)",
+    "zlacgv": "void (int *, __pyx_t_double_complex *, int *)",
+    "zlacn2": "void (int *, __pyx_t_double_complex *, __pyx_t_double_complex *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, int *)",
+    "zlacon": "void (int *, __pyx_t_double_complex *, __pyx_t_double_complex *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *)",
+    "zlacp2": "void (char *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_double_complex *, int *)",
+    "zlacpy": "void (char *, int *, int *, __pyx_t_double_complex *, int *, __pyx_t_double_complex *, int *)",
+    "zlacrm": "void (int *, int *, __pyx_t_double_complex *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_double_complex *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *)",
+    "zlacrt": "void (int *, __pyx_t_double_complex *, int *, __pyx_t_double_complex *, int *, __pyx_t_double_complex *, __pyx_t_double_complex *)",
+    "zladiv": "__pyx_t_double_complex (__pyx_t_double_complex *, __pyx_t_double_complex *)",
+    "zlaed0": "void (int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_double_complex *, int *, __pyx_t_double_complex *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, int *)",
+    "zlaed7": "void (int *, int *, int *, int *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_double_complex *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, int *, int *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_double_complex *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, int *)",
+    "zlaed8": "void (int *, int *, int *, __pyx_t_double_complex *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_double_complex *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, int *, int *, int *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *)",
+    "zlaein": "void (int *, int *, int *, __pyx_t_double_complex *, int *, __pyx_t_double_complex *, __pyx_t_double_complex *, __pyx_t_double_complex *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *)",
+    "zlaesy": "void (__pyx_t_double_complex *, __pyx_t_double_complex *, __pyx_t_double_complex *, __pyx_t_double_complex *, __pyx_t_double_complex *, __pyx_t_double_complex *, __pyx_t_double_complex *, __pyx_t_double_complex *)",
+    "zlaev2": "void (__pyx_t_double_complex *, __pyx_t_double_complex *, __pyx_t_double_complex *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_double_complex *)",
+    "zlag2c": "void (int *, int *, __pyx_t_double_complex *, int *, __pyx_t_float_complex *, int *, int *)",
+    "zlags2": "void (int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_double_complex *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_double_complex *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_double_complex *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_double_complex *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_double_complex *)",
+    "zlagtm": "void (char *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_double_complex *, __pyx_t_double_complex *, __pyx_t_double_complex *, __pyx_t_double_complex *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_double_complex *, int *)",
+    "zlahef": "void (char *, int *, int *, int *, __pyx_t_double_complex *, int *, int *, __pyx_t_double_complex *, int *, int *)",
+    "zlahqr": "void (int *, int *, int *, int *, int *, __pyx_t_double_complex *, int *, __pyx_t_double_complex *, int *, int *, __pyx_t_double_complex *, int *, int *)",
+    "zlahr2": "void (int *, int *, int *, __pyx_t_double_complex *, int *, __pyx_t_double_complex *, __pyx_t_double_complex *, int *, __pyx_t_double_complex *, int *)",
+    "zlaic1": "void (int *, int *, __pyx_t_double_complex *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_double_complex *, __pyx_t_double_complex *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_double_complex *, __pyx_t_double_complex *)",
+    "zlals0": "void (int *, int *, int *, int *, int *, __pyx_t_double_complex *, int *, __pyx_t_double_complex *, int *, int *, int *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *)",
+    "zlalsa": "void (int *, int *, int *, int *, __pyx_t_double_complex *, int *, __pyx_t_double_complex *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, int *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, int *)",
+    "zlalsd": "void (char *, int *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_double_complex *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_double_complex *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, int *)",
+    "zlangb": "__pyx_t_5scipy_6linalg_13cython_lapack_d (char *, int *, int *, int *, __pyx_t_double_complex *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *)",
+    "zlange": "__pyx_t_5scipy_6linalg_13cython_lapack_d (char *, int *, int *, __pyx_t_double_complex *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *)",
+    "zlangt": "__pyx_t_5scipy_6linalg_13cython_lapack_d (char *, int *, __pyx_t_double_complex *, __pyx_t_double_complex *, __pyx_t_double_complex *)",
+    "zlanhb": "__pyx_t_5scipy_6linalg_13cython_lapack_d (char *, char *, int *, int *, __pyx_t_double_complex *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *)",
+    "zlanhe": "__pyx_t_5scipy_6linalg_13cython_lapack_d (char *, char *, int *, __pyx_t_double_complex *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *)",
+    "zlanhf": "__pyx_t_5scipy_6linalg_13cython_lapack_d (char *, char *, char *, int *, __pyx_t_double_complex *, __pyx_t_5scipy_6linalg_13cython_lapack_d *)",
+    "zlanhp": "__pyx_t_5scipy_6linalg_13cython_lapack_d (char *, char *, int *, __pyx_t_double_complex *, __pyx_t_5scipy_6linalg_13cython_lapack_d *)",
+    "zlanhs": "__pyx_t_5scipy_6linalg_13cython_lapack_d (char *, int *, __pyx_t_double_complex *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *)",
+    "zlanht": "__pyx_t_5scipy_6linalg_13cython_lapack_d (char *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_double_complex *)",
+    "zlansb": "__pyx_t_5scipy_6linalg_13cython_lapack_d (char *, char *, int *, int *, __pyx_t_double_complex *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *)",
+    "zlansp": "__pyx_t_5scipy_6linalg_13cython_lapack_d (char *, char *, int *, __pyx_t_double_complex *, __pyx_t_5scipy_6linalg_13cython_lapack_d *)",
+    "zlansy": "__pyx_t_5scipy_6linalg_13cython_lapack_d (char *, char *, int *, __pyx_t_double_complex *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *)",
+    "zlantb": "__pyx_t_5scipy_6linalg_13cython_lapack_d (char *, char *, char *, int *, int *, __pyx_t_double_complex *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *)",
+    "zlantp": "__pyx_t_5scipy_6linalg_13cython_lapack_d (char *, char *, char *, int *, __pyx_t_double_complex *, __pyx_t_5scipy_6linalg_13cython_lapack_d *)",
+    "zlantr": "__pyx_t_5scipy_6linalg_13cython_lapack_d (char *, char *, char *, int *, int *, __pyx_t_double_complex *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *)",
+    "zlapll": "void (int *, __pyx_t_double_complex *, int *, __pyx_t_double_complex *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *)",
+    "zlapmr": "void (int *, int *, int *, __pyx_t_double_complex *, int *, int *)",
+    "zlapmt": "void (int *, int *, int *, __pyx_t_double_complex *, int *, int *)",
+    "zlaqgb": "void (int *, int *, int *, int *, __pyx_t_double_complex *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, char *)",
+    "zlaqge": "void (int *, int *, __pyx_t_double_complex *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, char *)",
+    "zlaqhb": "void (char *, int *, int *, __pyx_t_double_complex *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, char *)",
+    "zlaqhe": "void (char *, int *, __pyx_t_double_complex *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, char *)",
+    "zlaqhp": "void (char *, int *, __pyx_t_double_complex *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, char *)",
+    "zlaqp2": "void (int *, int *, int *, __pyx_t_double_complex *, int *, int *, __pyx_t_double_complex *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_double_complex *)",
+    "zlaqps": "void (int *, int *, int *, int *, int *, __pyx_t_double_complex *, int *, int *, __pyx_t_double_complex *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_double_complex *, __pyx_t_double_complex *, int *)",
+    "zlaqr0": "void (int *, int *, int *, int *, int *, __pyx_t_double_complex *, int *, __pyx_t_double_complex *, int *, int *, __pyx_t_double_complex *, int *, __pyx_t_double_complex *, int *, int *)",
+    "zlaqr1": "void (int *, __pyx_t_double_complex *, int *, __pyx_t_double_complex *, __pyx_t_double_complex *, __pyx_t_double_complex *)",
+    "zlaqr2": "void (int *, int *, int *, int *, int *, int *, __pyx_t_double_complex *, int *, int *, int *, __pyx_t_double_complex *, int *, int *, int *, __pyx_t_double_complex *, __pyx_t_double_complex *, int *, int *, __pyx_t_double_complex *, int *, int *, __pyx_t_double_complex *, int *, __pyx_t_double_complex *, int *)",
+    "zlaqr3": "void (int *, int *, int *, int *, int *, int *, __pyx_t_double_complex *, int *, int *, int *, __pyx_t_double_complex *, int *, int *, int *, __pyx_t_double_complex *, __pyx_t_double_complex *, int *, int *, __pyx_t_double_complex *, int *, int *, __pyx_t_double_complex *, int *, __pyx_t_double_complex *, int *)",
+    "zlaqr4": "void (int *, int *, int *, int *, int *, __pyx_t_double_complex *, int *, __pyx_t_double_complex *, int *, int *, __pyx_t_double_complex *, int *, __pyx_t_double_complex *, int *, int *)",
+    "zlaqr5": "void (int *, int *, int *, int *, int *, int *, int *, __pyx_t_double_complex *, __pyx_t_double_complex *, int *, int *, int *, __pyx_t_double_complex *, int *, __pyx_t_double_complex *, int *, __pyx_t_double_complex *, int *, int *, __pyx_t_double_complex *, int *, int *, __pyx_t_double_complex *, int *)",
+    "zlaqsb": "void (char *, int *, int *, __pyx_t_double_complex *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, char *)",
+    "zlaqsp": "void (char *, int *, __pyx_t_double_complex *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, char *)",
+    "zlaqsy": "void (char *, int *, __pyx_t_double_complex *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, char *)",
+    "zlar1v": "void (int *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_double_complex *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *)",
+    "zlar2v": "void (int *, __pyx_t_double_complex *, __pyx_t_double_complex *, __pyx_t_double_complex *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_double_complex *, int *)",
+    "zlarcm": "void (int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_double_complex *, int *, __pyx_t_double_complex *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *)",
+    "zlarf": "void (char *, int *, int *, __pyx_t_double_complex *, int *, __pyx_t_double_complex *, __pyx_t_double_complex *, int *, __pyx_t_double_complex *)",
+    "zlarfb": "void (char *, char *, char *, char *, int *, int *, int *, __pyx_t_double_complex *, int *, __pyx_t_double_complex *, int *, __pyx_t_double_complex *, int *, __pyx_t_double_complex *, int *)",
+    "zlarfg": "void (int *, __pyx_t_double_complex *, __pyx_t_double_complex *, int *, __pyx_t_double_complex *)",
+    "zlarfgp": "void (int *, __pyx_t_double_complex *, __pyx_t_double_complex *, int *, __pyx_t_double_complex *)",
+    "zlarft": "void (char *, char *, int *, int *, __pyx_t_double_complex *, int *, __pyx_t_double_complex *, __pyx_t_double_complex *, int *)",
+    "zlarfx": "void (char *, int *, int *, __pyx_t_double_complex *, __pyx_t_double_complex *, __pyx_t_double_complex *, int *, __pyx_t_double_complex *)",
+    "zlargv": "void (int *, __pyx_t_double_complex *, int *, __pyx_t_double_complex *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *)",
+    "zlarnv": "void (int *, int *, int *, __pyx_t_double_complex *)",
+    "zlarrv": "void (int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, int *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_double_complex *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, int *)",
+    "zlartg": "void (__pyx_t_double_complex *, __pyx_t_double_complex *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_double_complex *, __pyx_t_double_complex *)",
+    "zlartv": "void (int *, __pyx_t_double_complex *, int *, __pyx_t_double_complex *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_double_complex *, int *)",
+    "zlarz": "void (char *, int *, int *, int *, __pyx_t_double_complex *, int *, __pyx_t_double_complex *, __pyx_t_double_complex *, int *, __pyx_t_double_complex *)",
+    "zlarzb": "void (char *, char *, char *, char *, int *, int *, int *, int *, __pyx_t_double_complex *, int *, __pyx_t_double_complex *, int *, __pyx_t_double_complex *, int *, __pyx_t_double_complex *, int *)",
+    "zlarzt": "void (char *, char *, int *, int *, __pyx_t_double_complex *, int *, __pyx_t_double_complex *, __pyx_t_double_complex *, int *)",
+    "zlascl": "void (char *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, int *, __pyx_t_double_complex *, int *, int *)",
+    "zlaset": "void (char *, int *, int *, __pyx_t_double_complex *, __pyx_t_double_complex *, __pyx_t_double_complex *, int *)",
+    "zlasr": "void (char *, char *, char *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_double_complex *, int *)",
+    "zlassq": "void (int *, __pyx_t_double_complex *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *)",
+    "zlaswp": "void (int *, __pyx_t_double_complex *, int *, int *, int *, int *, int *)",
+    "zlasyf": "void (char *, int *, int *, int *, __pyx_t_double_complex *, int *, int *, __pyx_t_double_complex *, int *, int *)",
+    "zlat2c": "void (char *, int *, __pyx_t_double_complex *, int *, __pyx_t_float_complex *, int *, int *)",
+    "zlatbs": "void (char *, char *, char *, char *, int *, int *, __pyx_t_double_complex *, int *, __pyx_t_double_complex *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *)",
+    "zlatdf": "void (int *, int *, __pyx_t_double_complex *, int *, __pyx_t_double_complex *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, int *)",
+    "zlatps": "void (char *, char *, char *, char *, int *, __pyx_t_double_complex *, __pyx_t_double_complex *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *)",
+    "zlatrd": "void (char *, int *, int *, __pyx_t_double_complex *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_double_complex *, __pyx_t_double_complex *, int *)",
+    "zlatrs": "void (char *, char *, char *, char *, int *, __pyx_t_double_complex *, int *, __pyx_t_double_complex *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *)",
+    "zlatrz": "void (int *, int *, int *, __pyx_t_double_complex *, int *, __pyx_t_double_complex *, __pyx_t_double_complex *)",
+    "zlauu2": "void (char *, int *, __pyx_t_double_complex *, int *, int *)",
+    "zlauum": "void (char *, int *, __pyx_t_double_complex *, int *, int *)",
+    "zpbcon": "void (char *, int *, int *, __pyx_t_double_complex *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_double_complex *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *)",
+    "zpbequ": "void (char *, int *, int *, __pyx_t_double_complex *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *)",
+    "zpbrfs": "void (char *, int *, int *, int *, __pyx_t_double_complex *, int *, __pyx_t_double_complex *, int *, __pyx_t_double_complex *, int *, __pyx_t_double_complex *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_double_complex *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *)",
+    "zpbstf": "void (char *, int *, int *, __pyx_t_double_complex *, int *, int *)",
+    "zpbsv": "void (char *, int *, int *, int *, __pyx_t_double_complex *, int *, __pyx_t_double_complex *, int *, int *)",
+    "zpbsvx": "void (char *, char *, int *, int *, int *, __pyx_t_double_complex *, int *, __pyx_t_double_complex *, int *, char *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_double_complex *, int *, __pyx_t_double_complex *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_double_complex *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *)",
+    "zpbtf2": "void (char *, int *, int *, __pyx_t_double_complex *, int *, int *)",
+    "zpbtrf": "void (char *, int *, int *, __pyx_t_double_complex *, int *, int *)",
+    "zpbtrs": "void (char *, int *, int *, int *, __pyx_t_double_complex *, int *, __pyx_t_double_complex *, int *, int *)",
+    "zpftrf": "void (char *, char *, int *, __pyx_t_double_complex *, int *)",
+    "zpftri": "void (char *, char *, int *, __pyx_t_double_complex *, int *)",
+    "zpftrs": "void (char *, char *, int *, int *, __pyx_t_double_complex *, __pyx_t_double_complex *, int *, int *)",
+    "zpocon": "void (char *, int *, __pyx_t_double_complex *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_double_complex *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *)",
+    "zpoequ": "void (int *, __pyx_t_double_complex *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *)",
+    "zpoequb": "void (int *, __pyx_t_double_complex *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *)",
+    "zporfs": "void (char *, int *, int *, __pyx_t_double_complex *, int *, __pyx_t_double_complex *, int *, __pyx_t_double_complex *, int *, __pyx_t_double_complex *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_double_complex *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *)",
+    "zposv": "void (char *, int *, int *, __pyx_t_double_complex *, int *, __pyx_t_double_complex *, int *, int *)",
+    "zposvx": "void (char *, char *, int *, int *, __pyx_t_double_complex *, int *, __pyx_t_double_complex *, int *, char *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_double_complex *, int *, __pyx_t_double_complex *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_double_complex *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *)",
+    "zpotf2": "void (char *, int *, __pyx_t_double_complex *, int *, int *)",
+    "zpotrf": "void (char *, int *, __pyx_t_double_complex *, int *, int *)",
+    "zpotri": "void (char *, int *, __pyx_t_double_complex *, int *, int *)",
+    "zpotrs": "void (char *, int *, int *, __pyx_t_double_complex *, int *, __pyx_t_double_complex *, int *, int *)",
+    "zppcon": "void (char *, int *, __pyx_t_double_complex *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_double_complex *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *)",
+    "zppequ": "void (char *, int *, __pyx_t_double_complex *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *)",
+    "zpprfs": "void (char *, int *, int *, __pyx_t_double_complex *, __pyx_t_double_complex *, __pyx_t_double_complex *, int *, __pyx_t_double_complex *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_double_complex *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *)",
+    "zppsv": "void (char *, int *, int *, __pyx_t_double_complex *, __pyx_t_double_complex *, int *, int *)",
+    "zppsvx": "void (char *, char *, int *, int *, __pyx_t_double_complex *, __pyx_t_double_complex *, char *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_double_complex *, int *, __pyx_t_double_complex *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_double_complex *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *)",
+    "zpptrf": "void (char *, int *, __pyx_t_double_complex *, int *)",
+    "zpptri": "void (char *, int *, __pyx_t_double_complex *, int *)",
+    "zpptrs": "void (char *, int *, int *, __pyx_t_double_complex *, __pyx_t_double_complex *, int *, int *)",
+    "zpstf2": "void (char *, int *, __pyx_t_double_complex *, int *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *)",
+    "zpstrf": "void (char *, int *, __pyx_t_double_complex *, int *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *)",
+    "zptcon": "void (int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_double_complex *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *)",
+    "zpteqr": "void (char *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_double_complex *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *)",
+    "zptrfs": "void (char *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_double_complex *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_double_complex *, __pyx_t_double_complex *, int *, __pyx_t_double_complex *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_double_complex *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *)",
+    "zptsv": "void (int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_double_complex *, __pyx_t_double_complex *, int *, int *)",
+    "zptsvx": "void (char *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_double_complex *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_double_complex *, __pyx_t_double_complex *, int *, __pyx_t_double_complex *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_double_complex *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *)",
+    "zpttrf": "void (int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_double_complex *, int *)",
+    "zpttrs": "void (char *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_double_complex *, __pyx_t_double_complex *, int *, int *)",
+    "zptts2": "void (int *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_double_complex *, __pyx_t_double_complex *, int *)",
+    "zrot": "void (int *, __pyx_t_double_complex *, int *, __pyx_t_double_complex *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_double_complex *)",
+    "zspcon": "void (char *, int *, __pyx_t_double_complex *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_double_complex *, int *)",
+    "zspmv": "void (char *, int *, __pyx_t_double_complex *, __pyx_t_double_complex *, __pyx_t_double_complex *, int *, __pyx_t_double_complex *, __pyx_t_double_complex *, int *)",
+    "zspr": "void (char *, int *, __pyx_t_double_complex *, __pyx_t_double_complex *, int *, __pyx_t_double_complex *)",
+    "zsprfs": "void (char *, int *, int *, __pyx_t_double_complex *, __pyx_t_double_complex *, int *, __pyx_t_double_complex *, int *, __pyx_t_double_complex *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_double_complex *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *)",
+    "zspsv": "void (char *, int *, int *, __pyx_t_double_complex *, int *, __pyx_t_double_complex *, int *, int *)",
+    "zspsvx": "void (char *, char *, int *, int *, __pyx_t_double_complex *, __pyx_t_double_complex *, int *, __pyx_t_double_complex *, int *, __pyx_t_double_complex *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_double_complex *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *)",
+    "zsptrf": "void (char *, int *, __pyx_t_double_complex *, int *, int *)",
+    "zsptri": "void (char *, int *, __pyx_t_double_complex *, int *, __pyx_t_double_complex *, int *)",
+    "zsptrs": "void (char *, int *, int *, __pyx_t_double_complex *, int *, __pyx_t_double_complex *, int *, int *)",
+    "zstedc": "void (char *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_double_complex *, int *, __pyx_t_double_complex *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, int *, int *, int *)",
+    "zstegr": "void (char *, char *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_double_complex *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, int *, int *, int *)",
+    "zstein": "void (int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, int *, __pyx_t_double_complex *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, int *, int *)",
+    "zstemr": "void (char *, char *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_double_complex *, int *, int *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, int *, int *, int *)",
+    "zsteqr": "void (char *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_double_complex *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *)",
+    "zsycon": "void (char *, int *, __pyx_t_double_complex *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_double_complex *, int *)",
+    "zsyconv": "void (char *, char *, int *, __pyx_t_double_complex *, int *, int *, __pyx_t_double_complex *, int *)",
+    "zsyequb": "void (char *, int *, __pyx_t_double_complex *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_double_complex *, int *)",
+    "zsymv": "void (char *, int *, __pyx_t_double_complex *, __pyx_t_double_complex *, int *, __pyx_t_double_complex *, int *, __pyx_t_double_complex *, __pyx_t_double_complex *, int *)",
+    "zsyr": "void (char *, int *, __pyx_t_double_complex *, __pyx_t_double_complex *, int *, __pyx_t_double_complex *, int *)",
+    "zsyrfs": "void (char *, int *, int *, __pyx_t_double_complex *, int *, __pyx_t_double_complex *, int *, int *, __pyx_t_double_complex *, int *, __pyx_t_double_complex *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_double_complex *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *)",
+    "zsysv": "void (char *, int *, int *, __pyx_t_double_complex *, int *, int *, __pyx_t_double_complex *, int *, __pyx_t_double_complex *, int *, int *)",
+    "zsysvx": "void (char *, char *, int *, int *, __pyx_t_double_complex *, int *, __pyx_t_double_complex *, int *, int *, __pyx_t_double_complex *, int *, __pyx_t_double_complex *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_double_complex *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *)",
+    "zsyswapr": "void (char *, int *, __pyx_t_double_complex *, int *, int *, int *)",
+    "zsytf2": "void (char *, int *, __pyx_t_double_complex *, int *, int *, int *)",
+    "zsytrf": "void (char *, int *, __pyx_t_double_complex *, int *, int *, __pyx_t_double_complex *, int *, int *)",
+    "zsytri": "void (char *, int *, __pyx_t_double_complex *, int *, int *, __pyx_t_double_complex *, int *)",
+    "zsytri2": "void (char *, int *, __pyx_t_double_complex *, int *, int *, __pyx_t_double_complex *, int *, int *)",
+    "zsytri2x": "void (char *, int *, __pyx_t_double_complex *, int *, int *, __pyx_t_double_complex *, int *, int *)",
+    "zsytrs": "void (char *, int *, int *, __pyx_t_double_complex *, int *, int *, __pyx_t_double_complex *, int *, int *)",
+    "zsytrs2": "void (char *, int *, int *, __pyx_t_double_complex *, int *, int *, __pyx_t_double_complex *, int *, __pyx_t_double_complex *, int *)",
+    "ztbcon": "void (char *, char *, char *, int *, int *, __pyx_t_double_complex *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_double_complex *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *)",
+    "ztbrfs": "void (char *, char *, char *, int *, int *, int *, __pyx_t_double_complex *, int *, __pyx_t_double_complex *, int *, __pyx_t_double_complex *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_double_complex *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *)",
+    "ztbtrs": "void (char *, char *, char *, int *, int *, int *, __pyx_t_double_complex *, int *, __pyx_t_double_complex *, int *, int *)",
+    "ztfsm": "void (char *, char *, char *, char *, char *, int *, int *, __pyx_t_double_complex *, __pyx_t_double_complex *, __pyx_t_double_complex *, int *)",
+    "ztftri": "void (char *, char *, char *, int *, __pyx_t_double_complex *, int *)",
+    "ztfttp": "void (char *, char *, int *, __pyx_t_double_complex *, __pyx_t_double_complex *, int *)",
+    "ztfttr": "void (char *, char *, int *, __pyx_t_double_complex *, __pyx_t_double_complex *, int *, int *)",
+    "ztgevc": "void (char *, char *, int *, int *, __pyx_t_double_complex *, int *, __pyx_t_double_complex *, int *, __pyx_t_double_complex *, int *, __pyx_t_double_complex *, int *, int *, int *, __pyx_t_double_complex *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *)",
+    "ztgex2": "void (int *, int *, int *, __pyx_t_double_complex *, int *, __pyx_t_double_complex *, int *, __pyx_t_double_complex *, int *, __pyx_t_double_complex *, int *, int *, int *)",
+    "ztgexc": "void (int *, int *, int *, __pyx_t_double_complex *, int *, __pyx_t_double_complex *, int *, __pyx_t_double_complex *, int *, __pyx_t_double_complex *, int *, int *, int *, int *)",
+    "ztgsen": "void (int *, int *, int *, int *, int *, __pyx_t_double_complex *, int *, __pyx_t_double_complex *, int *, __pyx_t_double_complex *, __pyx_t_double_complex *, __pyx_t_double_complex *, int *, __pyx_t_double_complex *, int *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_double_complex *, int *, int *, int *, int *)",
+    "ztgsja": "void (char *, char *, char *, int *, int *, int *, int *, int *, __pyx_t_double_complex *, int *, __pyx_t_double_complex *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_double_complex *, int *, __pyx_t_double_complex *, int *, __pyx_t_double_complex *, int *, __pyx_t_double_complex *, int *, int *)",
+    "ztgsna": "void (char *, char *, int *, int *, __pyx_t_double_complex *, int *, __pyx_t_double_complex *, int *, __pyx_t_double_complex *, int *, __pyx_t_double_complex *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, int *, __pyx_t_double_complex *, int *, int *, int *)",
+    "ztgsy2": "void (char *, int *, int *, int *, __pyx_t_double_complex *, int *, __pyx_t_double_complex *, int *, __pyx_t_double_complex *, int *, __pyx_t_double_complex *, int *, __pyx_t_double_complex *, int *, __pyx_t_double_complex *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *)",
+    "ztgsyl": "void (char *, int *, int *, int *, __pyx_t_double_complex *, int *, __pyx_t_double_complex *, int *, __pyx_t_double_complex *, int *, __pyx_t_double_complex *, int *, __pyx_t_double_complex *, int *, __pyx_t_double_complex *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_double_complex *, int *, int *, int *)",
+    "ztpcon": "void (char *, char *, char *, int *, __pyx_t_double_complex *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_double_complex *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *)",
+    "ztpmqrt": "void (char *, char *, int *, int *, int *, int *, int *, __pyx_t_double_complex *, int *, __pyx_t_double_complex *, int *, __pyx_t_double_complex *, int *, __pyx_t_double_complex *, int *, __pyx_t_double_complex *, int *)",
+    "ztpqrt": "void (int *, int *, int *, int *, __pyx_t_double_complex *, int *, __pyx_t_double_complex *, int *, __pyx_t_double_complex *, int *, __pyx_t_double_complex *, int *)",
+    "ztpqrt2": "void (int *, int *, int *, __pyx_t_double_complex *, int *, __pyx_t_double_complex *, int *, __pyx_t_double_complex *, int *, int *)",
+    "ztprfb": "void (char *, char *, char *, char *, int *, int *, int *, int *, __pyx_t_double_complex *, int *, __pyx_t_double_complex *, int *, __pyx_t_double_complex *, int *, __pyx_t_double_complex *, int *, __pyx_t_double_complex *, int *)",
+    "ztprfs": "void (char *, char *, char *, int *, int *, __pyx_t_double_complex *, __pyx_t_double_complex *, int *, __pyx_t_double_complex *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_double_complex *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *)",
+    "ztptri": "void (char *, char *, int *, __pyx_t_double_complex *, int *)",
+    "ztptrs": "void (char *, char *, char *, int *, int *, __pyx_t_double_complex *, __pyx_t_double_complex *, int *, int *)",
+    "ztpttf": "void (char *, char *, int *, __pyx_t_double_complex *, __pyx_t_double_complex *, int *)",
+    "ztpttr": "void (char *, int *, __pyx_t_double_complex *, __pyx_t_double_complex *, int *, int *)",
+    "ztrcon": "void (char *, char *, char *, int *, __pyx_t_double_complex *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_double_complex *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *)",
+    "ztrevc": "void (char *, char *, int *, int *, __pyx_t_double_complex *, int *, __pyx_t_double_complex *, int *, __pyx_t_double_complex *, int *, int *, int *, __pyx_t_double_complex *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *)",
+    "ztrexc": "void (char *, int *, __pyx_t_double_complex *, int *, __pyx_t_double_complex *, int *, int *, int *, int *)",
+    "ztrrfs": "void (char *, char *, char *, int *, int *, __pyx_t_double_complex *, int *, __pyx_t_double_complex *, int *, __pyx_t_double_complex *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_double_complex *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *)",
+    "ztrsen": "void (char *, char *, int *, int *, __pyx_t_double_complex *, int *, __pyx_t_double_complex *, int *, __pyx_t_double_complex *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_double_complex *, int *, int *)",
+    "ztrsna": "void (char *, char *, int *, int *, __pyx_t_double_complex *, int *, __pyx_t_double_complex *, int *, __pyx_t_double_complex *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, int *, __pyx_t_double_complex *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *)",
+    "ztrsyl": "void (char *, char *, int *, int *, int *, __pyx_t_double_complex *, int *, __pyx_t_double_complex *, int *, __pyx_t_double_complex *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *)",
+    "ztrti2": "void (char *, char *, int *, __pyx_t_double_complex *, int *, int *)",
+    "ztrtri": "void (char *, char *, int *, __pyx_t_double_complex *, int *, int *)",
+    "ztrtrs": "void (char *, char *, char *, int *, int *, __pyx_t_double_complex *, int *, __pyx_t_double_complex *, int *, int *)",
+    "ztrttf": "void (char *, char *, int *, __pyx_t_double_complex *, int *, __pyx_t_double_complex *, int *)",
+    "ztrttp": "void (char *, int *, __pyx_t_double_complex *, int *, __pyx_t_double_complex *, int *)",
+    "ztzrzf": "void (int *, int *, __pyx_t_double_complex *, int *, __pyx_t_double_complex *, __pyx_t_double_complex *, int *, int *)",
+    "zunbdb": "void (char *, char *, int *, int *, int *, __pyx_t_double_complex *, int *, __pyx_t_double_complex *, int *, __pyx_t_double_complex *, int *, __pyx_t_double_complex *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_double_complex *, __pyx_t_double_complex *, __pyx_t_double_complex *, __pyx_t_double_complex *, __pyx_t_double_complex *, int *, int *)",
+    "zuncsd": "void (char *, char *, char *, char *, char *, char *, int *, int *, int *, __pyx_t_double_complex *, int *, __pyx_t_double_complex *, int *, __pyx_t_double_complex *, int *, __pyx_t_double_complex *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, __pyx_t_double_complex *, int *, __pyx_t_double_complex *, int *, __pyx_t_double_complex *, int *, __pyx_t_double_complex *, int *, __pyx_t_double_complex *, int *, __pyx_t_5scipy_6linalg_13cython_lapack_d *, int *, int *, int *)",
+    "zung2l": "void (int *, int *, int *, __pyx_t_double_complex *, int *, __pyx_t_double_complex *, __pyx_t_double_complex *, int *)",
+    "zung2r": "void (int *, int *, int *, __pyx_t_double_complex *, int *, __pyx_t_double_complex *, __pyx_t_double_complex *, int *)",
+    "zungbr": "void (char *, int *, int *, int *, __pyx_t_double_complex *, int *, __pyx_t_double_complex *, __pyx_t_double_complex *, int *, int *)",
+    "zunghr": "void (int *, int *, int *, __pyx_t_double_complex *, int *, __pyx_t_double_complex *, __pyx_t_double_complex *, int *, int *)",
+    "zungl2": "void (int *, int *, int *, __pyx_t_double_complex *, int *, __pyx_t_double_complex *, __pyx_t_double_complex *, int *)",
+    "zunglq": "void (int *, int *, int *, __pyx_t_double_complex *, int *, __pyx_t_double_complex *, __pyx_t_double_complex *, int *, int *)",
+    "zungql": "void (int *, int *, int *, __pyx_t_double_complex *, int *, __pyx_t_double_complex *, __pyx_t_double_complex *, int *, int *)",
+    "zungqr": "void (int *, int *, int *, __pyx_t_double_complex *, int *, __pyx_t_double_complex *, __pyx_t_double_complex *, int *, int *)",
+    "zungr2": "void (int *, int *, int *, __pyx_t_double_complex *, int *, __pyx_t_double_complex *, __pyx_t_double_complex *, int *)",
+    "zungrq": "void (int *, int *, int *, __pyx_t_double_complex *, int *, __pyx_t_double_complex *, __pyx_t_double_complex *, int *, int *)",
+    "zungtr": "void (char *, int *, __pyx_t_double_complex *, int *, __pyx_t_double_complex *, __pyx_t_double_complex *, int *, int *)",
+    "zunm2l": "void (char *, char *, int *, int *, int *, __pyx_t_double_complex *, int *, __pyx_t_double_complex *, __pyx_t_double_complex *, int *, __pyx_t_double_complex *, int *)",
+    "zunm2r": "void (char *, char *, int *, int *, int *, __pyx_t_double_complex *, int *, __pyx_t_double_complex *, __pyx_t_double_complex *, int *, __pyx_t_double_complex *, int *)",
+    "zunmbr": "void (char *, char *, char *, int *, int *, int *, __pyx_t_double_complex *, int *, __pyx_t_double_complex *, __pyx_t_double_complex *, int *, __pyx_t_double_complex *, int *, int *)",
+    "zunmhr": "void (char *, char *, int *, int *, int *, int *, __pyx_t_double_complex *, int *, __pyx_t_double_complex *, __pyx_t_double_complex *, int *, __pyx_t_double_complex *, int *, int *)",
+    "zunml2": "void (char *, char *, int *, int *, int *, __pyx_t_double_complex *, int *, __pyx_t_double_complex *, __pyx_t_double_complex *, int *, __pyx_t_double_complex *, int *)",
+    "zunmlq": "void (char *, char *, int *, int *, int *, __pyx_t_double_complex *, int *, __pyx_t_double_complex *, __pyx_t_double_complex *, int *, __pyx_t_double_complex *, int *, int *)",
+    "zunmql": "void (char *, char *, int *, int *, int *, __pyx_t_double_complex *, int *, __pyx_t_double_complex *, __pyx_t_double_complex *, int *, __pyx_t_double_complex *, int *, int *)",
+    "zunmqr": "void (char *, char *, int *, int *, int *, __pyx_t_double_complex *, int *, __pyx_t_double_complex *, __pyx_t_double_complex *, int *, __pyx_t_double_complex *, int *, int *)",
+    "zunmr2": "void (char *, char *, int *, int *, int *, __pyx_t_double_complex *, int *, __pyx_t_double_complex *, __pyx_t_double_complex *, int *, __pyx_t_double_complex *, int *)",
+    "zunmr3": "void (char *, char *, int *, int *, int *, int *, __pyx_t_double_complex *, int *, __pyx_t_double_complex *, __pyx_t_double_complex *, int *, __pyx_t_double_complex *, int *)",
+    "zunmrq": "void (char *, char *, int *, int *, int *, __pyx_t_double_complex *, int *, __pyx_t_double_complex *, __pyx_t_double_complex *, int *, __pyx_t_double_complex *, int *, int *)",
+    "zunmrz": "void (char *, char *, int *, int *, int *, int *, __pyx_t_double_complex *, int *, __pyx_t_double_complex *, __pyx_t_double_complex *, int *, __pyx_t_double_complex *, int *, int *)",
+    "zunmtr": "void (char *, char *, char *, int *, int *, __pyx_t_double_complex *, int *, __pyx_t_double_complex *, __pyx_t_double_complex *, int *, __pyx_t_double_complex *, int *, int *)",
+    "zupgtr": "void (char *, int *, __pyx_t_double_complex *, __pyx_t_double_complex *, __pyx_t_double_complex *, int *, __pyx_t_double_complex *, int *)",
+    "zupmtr": "void (char *, char *, char *, int *, int *, __pyx_t_double_complex *, __pyx_t_double_complex *, __pyx_t_double_complex *, int *, __pyx_t_double_complex *, int *)"
+  }
+}
diff --git a/.venv/lib/python3.12/site-packages/scipy/linalg/tests/data/carex_15_data.npz b/.venv/lib/python3.12/site-packages/scipy/linalg/tests/data/carex_15_data.npz
new file mode 100644
index 0000000000000000000000000000000000000000..660bbb41b7fad43ed945dc701693451ceb60166c
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/linalg/tests/data/carex_15_data.npz
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:13f3e1491a876bbf59d7ea10ad29c1f9b5996a2ab99216f31d5bfcd659012c1e
+size 34462
diff --git a/.venv/lib/python3.12/site-packages/scipy/linalg/tests/data/carex_18_data.npz b/.venv/lib/python3.12/site-packages/scipy/linalg/tests/data/carex_18_data.npz
new file mode 100644
index 0000000000000000000000000000000000000000..0b3d569a1a65e9b5ff153ae4121a6a5a69409f7c
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/linalg/tests/data/carex_18_data.npz
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:59f839467f2752b7df6fb6d4094396edd32a5929b764f7ffa1e6666431e6cac6
+size 161487
diff --git a/.venv/lib/python3.12/site-packages/scipy/linalg/tests/data/carex_19_data.npz b/.venv/lib/python3.12/site-packages/scipy/linalg/tests/data/carex_19_data.npz
new file mode 100644
index 0000000000000000000000000000000000000000..90168ad4e888fba29a772ee13798ec126016140e
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/linalg/tests/data/carex_19_data.npz
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:38e8fc7b041df0b23d7e5ca15ead1a065e6467611ef9a848cc7db93f80adfd87
+size 34050
diff --git a/.venv/lib/python3.12/site-packages/scipy/linalg/tests/data/carex_20_data.npz b/.venv/lib/python3.12/site-packages/scipy/linalg/tests/data/carex_20_data.npz
new file mode 100644
index 0000000000000000000000000000000000000000..87266deb46238307347362b63a4878f2565baf56
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/linalg/tests/data/carex_20_data.npz
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:14e222d34a7118c7284a1675c6feceee77b84df951a5c6ba2a5ee9ff3054fa1d
+size 31231